Finish the optical post's network cue and edge cases (#136)

- a radar's fresh track reaches a post as a cue only: it points the head
  but never enters the post's tracks, seen or own set
- a searching post's sector follows the turning head, not the fixed base
  heading; switching contacts drops the old contact's picture
- dead and blinded posts spend no probe budget and never observe
- the icon alias is part of the generator, so the placeholder item uses
  the radar texture without a duplicate PNG or a hand-written asset
- part diagnostics read "Опт" for a passive post's sensor
- tests: cue wiring, turning sector, contact switch, dead post, graphics
  preset; generator alias

Cherry-picked from 3697a1764aec7a7bdc6311918453dd51e26ecabf onto the
#132/#133/#134 base: the cue-wiring test's track literal now carries the
shared class/source/product/quality contract instead of a DroneKind.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
This commit is contained in:
2026-11-20 22:37:36 +03:00
parent e5ee15a2ca
commit 8550de16f8
15 changed files with 228 additions and 48 deletions
+2 -1
View File
@@ -271,7 +271,8 @@ API мода `render.set-lights` (до 512, плавно интерполиру
Обслуживающая техника (тоже пультами или `/airdef deploy <ключ>`): **РЛС дальнего обнаружения** (`radar`,
видит на 2,5 км с высокой мачты, хуже прячутся за рельефом), **склад боеприпасов** (`depot`), **ТЗМ** (`tzm`),
**станция РЭБ** (`ew`), **прожектор** (`light`). Новые комплексы: `irist`, `nasams`, `buk`, `tor`, `p1sun`.
**станция РЭБ** (`ew`), **прожектор** (`light`), **оптический пост** (`optical`: пассивно уточняет широкий класс
контакта по прямой видимости, не излучает и не ведёт огневой трек). Новые комплексы: `irist`, `nasams`, `buk`, `tor`, `p1sun`.
**Согласование огня.** Комплексы делят цели между собой: на обычную цель идёт одна ракета, на баллистическую две; чем ближе цель к своей точке попадания,
тем больше перехватчиков разрешено на неё сразу (за ~12 с до удара ещё один, за ~5 с — ещё один). Комплекс, у которого кончились ракеты
@@ -3,4 +3,4 @@
"type": "minecraft:model",
"model": "airdef:item/deploy_optical"
}
}
}
@@ -3,4 +3,4 @@
"textures": {
"layer0": "airdef:item/deploy_radar"
}
}
}
@@ -1,4 +1,4 @@
{
"template": "minecraft:stick",
"max_stack_size": 1
}
}
+5 -2
View File
@@ -114,6 +114,7 @@ b50fe5804cbbe10df992ebbc7e095a32ce8b73fc35159fa19889640681e408e9 assets/airdef/
0c9c5ee3fc87e2dc6d716bdb0bb5f30d3b265268bfd5083462b4861a8da65f0f assets/airdef/items/deploy_irist.json
09e46a6c4b59f66c24060ac627e6a287bf6797c7b1e32a9ec6c9d9662fdc3de3 assets/airdef/items/deploy_light.json
6983561b3558aee16662aa83d2d9af760fb6236cc7dbe79ba20802f8a2ff15b9 assets/airdef/items/deploy_nasams.json
e39c555ff197ed6c7c8fdfab924b7a609b5d111a905ca599a75a7b1270448fcc assets/airdef/items/deploy_optical.json
d8ac6a9258e2fc2e0791bbce18a3a07a72e471fbc72b6be7b5ca545c53f8d633 assets/airdef/items/deploy_p1sun.json
e2353c70f6e5053864ab2fdf51df886d72c03e5c34db84fef8f3fff9c84a7ae4 assets/airdef/items/deploy_pantsir.json
68dd9b1382b2dd6ad23d0f507a8cfcdcfa18ef5c4203e69c61f6ade9cfbf238e assets/airdef/items/deploy_patriot.json
@@ -136,8 +137,8 @@ b4d98a938486d49db28c6c7a608ca3b6ab0c9c3eac266ecf12c7dd931cc28f93 assets/airdef/
489799dcb5b441e9d4be8bfb3d73a6ebd5fdf2b5ee614b62f38b85bb2fbfad75 assets/airdef/items/launch_zircon.json
6b6da5887aa8d9bc987b2c181c243bc2afdd5846a869818f699b59204e559929 assets/airdef/items/mover.json
177f7535e4c52ed975d6f737c2b2acb7741b7a928955c8899aced85211443bbf assets/airdef/items/remover.json
cede33ba58f61891a8afe42e1f4311cb293ca93f4d7eb3a57636caff17317a4d assets/airdef/lang/en_us.json
cede33ba58f61891a8afe42e1f4311cb293ca93f4d7eb3a57636caff17317a4d assets/airdef/lang/ru_ru.json
14c7fae39807f31ed6a20ebf8d0805c845f4d94e46ef5c38d1f2ba5c2671f768 assets/airdef/lang/en_us.json
14c7fae39807f31ed6a20ebf8d0805c845f4d94e46ef5c38d1f2ba5c2671f768 assets/airdef/lang/ru_ru.json
b9b5b5bec33a77e944552c225ee2f526ab9820fa8fca4b3ccf311f2a325925ee assets/airdef/models/block/amraam_missile.json
c54e6b24ab69e9d9a2dbbbc63fe2ac60fa37735bf644500ddd5c3de0b91908cf assets/airdef/models/block/barge.json
a4198ff647de5866919f9b82a3d53e6486fc56cc9f175f7907951d063a6f4526 assets/airdef/models/block/beam.json
@@ -254,6 +255,7 @@ a5d0450da8d6757b9b45f86e6b36977894dd9e3e1278c3668b99a8acab36f399 assets/airdef/
e80ee81085241b9712e024bbef73ef744ef5493eebb88770f4912d8aae138fe6 assets/airdef/models/item/deploy_irist.json
637b9bfe426ee50045f8fcbfd4f25dfbc1d819ce36dedbd60abdac63c274f088 assets/airdef/models/item/deploy_light.json
3398844e90203f97ee73e35619684c775d1856c8ca3399b5ed682786170d9327 assets/airdef/models/item/deploy_nasams.json
332f9de8c88658a562748fc7a6de7ec37847273ac0cd0733e23c0dff4b44418c assets/airdef/models/item/deploy_optical.json
76019c05d070cf1141cdf95b744b3d6198ab99469dba1f88a6903de1de303bde assets/airdef/models/item/deploy_p1sun.json
8b1af688bc83be5a8065673bca7054deee86ca425f0bfd1fb4ffb491844e90bf assets/airdef/models/item/deploy_pantsir.json
d0091d809816350c648e532a90ae59a3c5c9b94f837b2a46b5695e7f985a00f9 assets/airdef/models/item/deploy_patriot.json
@@ -567,6 +569,7 @@ cc0877f40434365b45b03429222926aa0cf135e504017311be53263fd27c5f8f data/airdef/ho
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_irist.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_light.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_nasams.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_optical.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_p1sun.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_pantsir.json
2a3912a7c9d5bb8025b1ac16a1a1d6b5eff0360bb3184e810d319e498255bf97 data/airdef/horizon/item/deploy_patriot.json
+1 -1
View File
@@ -1499,7 +1499,7 @@ impl AirDef {
/// monitored one always; those shown keep a head start, so the grid doesn't flicker.
fn pick_grid(&mut self) {
let shown = &self.grid_ids;
// Units that shoot, and the radars; depots, trucks and lights have nothing to show.
// Units that shoot, the radars and the passive optics; depots, trucks and lights have nothing to show.
let mut scored: Vec<(f64, u32)> = self
.sim
.sams
+18 -11
View File
@@ -2681,7 +2681,14 @@ impl AirDef {
lines.push((if bare == 0 { "Все объекты в зоне поражения".into() } else { format!("Без прикрытия: объектов {bare} (красные)") }, if bare == 0 { GREEN } else { RED }));
lines.push(("Зелёное: зона огня, тёмное: дыра".into(), GREY));
match ui.pick {
Pick::Sam(k) => lines.push((format!("В руке: {}, дальность {}", k.name(), distance(k.range())), YELLOW)),
Pick::Sam(k) => {
let reach = if k == SamKind::Optical {
format!("оптика {}", distance(sim::OPTICAL_RANGE))
} else {
format!("дальность {}", distance(k.range()))
};
lines.push((format!("В руке: {}, {reach}", k.name()), YELLOW));
}
Pick::Object => lines.push(("В руке: объект (его будут защищать)".into(), YELLOW)),
Pick::None => lines.push(("Выберите тип внизу".into(), GREY)),
}
@@ -2713,16 +2720,16 @@ impl AirDef {
btns.push((if sam.radar_on { "Выключить РЛС" } else { "Включить РЛС" }.into(), Act::RadarEmission, sam.radar_on));
}
lines.push((crate::battery_view::sam_status(sam), WHITE));
if k == SamKind::Optical {
if let Some(r) = self.sim.optical_report(sam.id) {
lines.push((r.line(), WHITE));
if let Some(o) = r.observation {
lines.push((format!("Последнее наблюдение: {} · {} с назад", o.class.name(), o.age(now) / 20), WHITE));
}
lines.push(("Пассивный пост: не излучает и не ведёт огневой трек".into(), GREY));
if r.target.is_some() {
lines.push(("Выбранный контакт показан линией".into(), GREY));
}
if k == SamKind::Optical
&& let Some(r) = self.sim.optical_report(sam.id)
{
lines.push((r.line(), WHITE));
if let Some(o) = r.observation {
lines.push((format!("Последнее наблюдение: {} · {} с назад", o.class.name(), o.age(now) / 20), WHITE));
}
lines.push(("Пассивный пост: не излучает и не ведёт огневой трек".into(), GREY));
if r.target.is_some() {
lines.push(("Выбранный контакт показан линией".into(), GREY));
}
}
lines.push((format!("Исправен {:.0}% · {:.0} {:.0}", sam.health * 100.0, sam.pos.x, sam.pos.z), GREY));
+4
View File
@@ -54,6 +54,10 @@ impl Part {
Part::Comms => "Св",
}
}
/// The short label as this kind of unit reads it: a passive post has optics, not a radar.
pub fn short_on(self, kind: SamKind) -> &'static str {
if self == Part::Sensor && kind == SamKind::Optical { "Опт" } else { self.short() }
}
fn index(self) -> usize {
self as usize
}
+127 -20
View File
@@ -47,8 +47,6 @@ const LOCAL_CANDIDATES: usize = 8;
const TERRAIN_SAMPLES: usize = 6;
/// A relayed track older than this is not worth turning the head for.
const CUE_MAX_AGE: u64 = 120;
/// Where the antenna sits over the post's base, blocks.
const MAST: f64 = 2.5;
/// What the post is doing, in the words the map and monitor use.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
@@ -188,6 +186,8 @@ pub struct Optical {
/// The last clear sighting of the current contact: target, where it was, its velocity then, when.
/// Only a clear line writes it; a blocked line leaves the old one to be forecast, never refreshed.
seen: Option<(u32, DVec3, DVec3, u64)>,
/// The freshest relayed track: a direction to look, never a measurement and never a track.
cue: Option<Track>,
checks: u64,
}
@@ -216,6 +216,16 @@ impl Optical {
pub fn checks(&self) -> u64 {
self.checks
}
/// Takes a relayed track only as a cue: it is not stored in `Sam::tracks` and never becomes own.
pub(super) fn offer_cue(&mut self, track: Track) {
let cue = Track { own_tick: 0, ..track };
if self.cue.is_none_or(|old| cue.tick >= old.tick) {
self.cue = Some(cue);
}
}
pub(super) fn cue(&self) -> Option<&Track> {
self.cue.as_ref()
}
fn commanded(&self) -> Option<u32> {
self.commanded
}
@@ -242,6 +252,8 @@ impl Optical {
self.held = 0;
self.observations = 0;
self.seen = None;
// The old picture belongs to the old contact: it must not be read as this one's.
self.observation = None;
}
self.target = id;
self.block = None;
@@ -363,6 +375,9 @@ impl Sim {
sam.optical.target = None;
sam.optical.held = 0;
sam.optical.observations = 0;
sam.optical.seen = None;
// An explicit switch drops the old contact's picture; it was never this contact's.
sam.optical.observation = None;
sam.optical.state = OpticalState::Searching;
sam.optical.block = None;
}
@@ -387,23 +402,15 @@ impl Sim {
}
}
// The network's freshest cue: the post measures it itself, the relay only points the head.
let mut cue: Option<(u64, f64, u32)> = None;
for t in &sam.tracks {
if t.own_tick != 0 || t.age(now) > CUE_MAX_AGE || !alive(t.id) {
continue;
}
let dist = t.est(now).distance(sam.pos);
if dist > CUE_RANGE {
continue;
}
if cue.is_none_or(|(fresh, near, _)| t.tick > fresh || (t.tick == fresh && dist < near)) {
cue = Some((t.tick, dist, t.id));
}
}
if let Some((_, _, id)) = cue {
return Some(id);
if let Some(t) = optical.cue()
&& t.age(now) <= CUE_MAX_AGE
&& alive(t.id)
&& t.est(now).distance(sam.pos) <= CUE_RANGE
{
return Some(t.id);
}
// Nothing cued: search a narrow near sector, nearest first, comparing no more than a few.
// The sector is the head's (`dish`, which turns while it searches), not the base's heading.
let mut local: Vec<(f64, u32)> = self
.drones
.iter()
@@ -415,7 +422,7 @@ impl Sim {
return None;
}
let bearing = heading_of(rel);
(angle_diff(sam.heading, bearing).abs() <= SECTOR_HALF).then_some((dist, d.id))
(angle_diff(sam.dish, bearing).abs() <= SECTOR_HALF).then_some((dist, d.id))
})
.collect();
local.sort_by(|a, b| a.0.total_cmp(&b.0));
@@ -478,6 +485,10 @@ impl Sim {
break;
}
let i = posts[(start + k) % posts.len()];
// A dead, moving or blinded post spends none of the tick's probe budget.
if !self.sams[i].alive() || self.sams[i].moving() || self.sams[i].part(Part::Sensor) <= 0.0 {
continue;
}
let phase = (self.sams[i].id / PARTS) as u64 % PERIOD;
if now % PERIOD != phase {
continue;
@@ -493,7 +504,7 @@ impl Sim {
let Some(d) = self.drones.iter().find(|d| d.id == target && d.alive()) else {
continue;
};
let from = sam.pos + DVec3::Y * MAST;
let from = sam.pos + DVec3::Y * sam.kind.spec().mast;
let to = d.pos;
let rel = to - from;
let range = rel.length();
@@ -754,13 +765,29 @@ mod tests {
}
}
// The client's graphics preset is not part of the model: HD and plain give the same estimate.
#[test]
fn a_graphics_preset_does_not_change_the_class() {
fn estimate(shader: bool) -> (Class, f64) {
let mut sim = Sim::new(17);
sim.shader = shader;
let post = optical_at(&mut sim, 0.0, 0.0, 0.0);
flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -100.0), DVec3::new(0.5, 0.0, -0.6));
let mut ground = clear_ground();
run(&mut sim, &mut ground, 200);
let o = sim.optical_report(post).unwrap().observation.expect("no observation");
(o.class, o.uncertainty)
}
assert_eq!(estimate(false), estimate(true));
}
// A network cue only points the head; it is not a measurement and does not raise confidence.
#[test]
fn a_network_cue_is_not_a_measurement() {
let mut sim = Sim::new(8);
let post = optical_at(&mut sim, 0.0, 0.0, 0.0);
let id = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -500.0), DVec3::new(0.5, 0.0, -0.6));
sim.sams[0].tracks.push(Track {
sim.sams[0].optical.offer_cue(Track {
id,
class: ClassEst::Probable(Class::Drone),
pos: sim.drones[0].pos,
@@ -786,6 +813,72 @@ mod tests {
assert!(r.observation.is_none() && r.observations == 0, "a relayed track became a measurement");
}
// A searching post turns its head: a near contact outside the base heading comes into the sector.
#[test]
fn a_searching_head_turns_its_sector() {
let mut sim = Sim::new(13);
let post = optical_at(&mut sim, 0.0, 0.0, 0.0);
let id = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(20.0, 95.0, 0.0), DVec3::ZERO);
let mut ground = clear_ground();
run(&mut sim, &mut ground, 300);
assert_eq!(sim.optical_report(post).unwrap().target, Some(id));
}
// Switching the watched contact drops the previous picture: it is never read as the new one's.
#[test]
fn switching_the_contact_drops_the_previous_picture() {
let mut sim = Sim::new(14);
let post = optical_at(&mut sim, 0.0, 0.0, 0.0);
flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -100.0), DVec3::new(0.1, 0.0, -0.1));
let mut ground = clear_ground();
run(&mut sim, &mut ground, 200);
assert!(sim.optical_report(post).unwrap().observation.is_some());
let other = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -150.0), DVec3::new(0.1, 0.0, -0.1));
assert!(sim.assign_optical(post, Some(other)));
let r = sim.optical_report(post).unwrap();
assert!(r.observation.is_none(), "the old contact's picture survived the switch");
assert!(r.seen.is_none());
}
// The network really reaches the post: a radar's fresh track is offered as a cue and stays a cue.
#[test]
fn a_radar_offers_the_post_a_cue_without_becoming_a_track() {
let mut sim = Sim::new(15);
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Radar, DVec3::new(0.0, 70.0, 0.0), 0.0));
let post = optical_at(&mut sim, 0.0, 0.0, 0.0);
let drone = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -500.0), DVec3::new(0.5, 0.0, -0.6));
// The post probes on its phase; the cue and the radar's measurement are of that same tick.
sim.tick = 20 + (post / PARTS) as u64 % PERIOD;
let now = sim.tick;
sim.sams[0].tracks.push(Track {
id: drone,
class: ClassEst::Probable(Class::Drone),
pos: sim.drones[0].pos,
vel: sim.drones[0].vel,
tick: now,
own_tick: now,
source: id,
product: battery::Measure::Fire,
quality: 90,
own_product: battery::Measure::Fire,
own_quality: 90,
ttl: 1000,
hits: 3,
locked: false,
});
let mut ground = clear_ground();
sim.update_sight(&mut ground);
let sighting = sim.sams.iter().find(|s| s.id == post).unwrap();
assert!(sighting.optical.cue().is_some_and(|t| t.id == drone), "the network never cued the post");
assert!(sighting.tracks.is_empty(), "a cue entered the post's own tracks");
assert!(!sighting.seen.contains(&drone) && !sighting.own.contains(&drone), "a cue became a track");
let r = sim.optical_report(post).unwrap();
assert_eq!(r.target, Some(drone));
assert_eq!(r.block, Some(SightBlock::OutOfRange));
assert!(r.observation.is_none() && r.observations == 0, "a cue became a measurement");
}
// A manual priority selects exactly one contact and is kept while it lives.
#[test]
fn a_manual_priority_selects_one_contact() {
@@ -804,6 +897,20 @@ mod tests {
assert!(!sim.assign_optical(post, Some(u32::MAX)), "a dead contact cannot be assigned");
}
// A dead post neither probes nor invents an observation.
#[test]
fn a_dead_post_does_not_probe() {
let mut sim = Sim::new(16);
let post = optical_at(&mut sim, 0.0, 0.0, 0.0);
flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -100.0), DVec3::new(0.5, 0.0, -0.6));
sim.sams[0].health = 0.0;
let mut ground = clear_ground();
run(&mut sim, &mut ground, 200);
let sam = sim.sams.iter().find(|s| s.id == post).unwrap();
assert_eq!(sam.optical.checks(), 0);
assert!(sam.optical.observation().is_none());
}
// A failed optic is not a clear line: the state says so, and no observation is made.
#[test]
fn a_failed_sensor_stops_the_observation() {
+30
View File
@@ -589,7 +589,37 @@ impl Sim {
.map(|s| (s.id, s.pos, s.link_range(), s.tracks.iter().filter(|t| t.own_tick > 0 && t.own_tick == t.tick).copied().collect::<Vec<_>>()))
.filter(|s| !s.3.is_empty())
.collect();
// One freshest track per radar is all a cue needs: the posts never walk every contact.
let cues: Vec<(u32, DVec3, f64, Track)> = if self.sams.iter().any(|s| s.kind == SamKind::Optical) {
shared
.iter()
.filter_map(|(id, at, range, tracks)| tracks.iter().max_by_key(|t| t.tick).map(|t| (*id, *at, *range, *t)))
.collect()
} else {
Vec::new()
};
for sam in &mut self.sams {
if sam.kind == SamKind::Optical {
// An optical post receives a cue, not a track: the freshest network measurement within
// link range only points its head, and none of it enters `tracks`, `seen` or `own`.
sam.seen.clear();
sam.own.clear();
if sam.alive() && !sam.moving() && sam.link_range() > 0.0 {
let mine = sam.link_range();
let mut best: Option<Track> = None;
for (id, at, range, t) in &cues {
if *id != sam.id && at.distance(sam.pos) <= range.min(mine)
&& best.is_none_or(|b: Track| t.tick > b.tick)
{
best = Some(*t);
}
}
if let Some(t) = best {
sam.optical.offer_cue(t);
}
}
continue;
}
if sam.alive() && !sam.moving() && (sam.kind.armed() || (sam.kind == SamKind::Radar && sam.radar_role == battery::RadarRole::Engagement)) && sam.link_range() > 0.0 && !shared.is_empty() {
index.clear();
index.extend(sam.tracks.iter().enumerate().map(|(k, t)| (t.id, k)));
+11 -2
View File
@@ -7,17 +7,22 @@ fn part_value(part: Part, value: f64) -> String {
else { format!("{} {:.0}%", part.short(), value * 100.0) }
}
fn part_value_on(part: Part, value: f64, kind: SamKind) -> String {
if value <= 0.0 { format!("{} отказ", part.short_on(kind)) }
else { format!("{} {:.0}%", part.short_on(kind), value * 100.0) }
}
/// Every worn or failed part of a system, as the monitor and the status line read it.
pub fn parts(comps: &Comps, kind: SamKind) -> String {
Part::ALL.iter().filter(|p| p.on(kind) && comps.get(**p) < 1.0)
.map(|p| part_value(*p, comps.get(*p))).collect::<Vec<_>>().join(", ")
.map(|p| part_value_on(*p, comps.get(*p), kind)).collect::<Vec<_>>().join(", ")
}
/// The weakest worn or failed part alone, for a one-line status.
pub fn worst(comps: &Comps, kind: SamKind) -> String {
Part::ALL.iter().filter(|p| p.on(kind) && comps.get(**p) < 1.0)
.min_by(|a, b| comps.get(**a).total_cmp(&comps.get(**b)))
.map(|p| part_value(*p, comps.get(*p))).unwrap_or_default()
.map(|p| part_value_on(*p, comps.get(*p), kind)).unwrap_or_default()
}
pub fn reason(reason: &CheckReason) -> String {
@@ -53,6 +58,10 @@ mod tests {
comps.0[Part::Tracks as usize] = 0.0;
assert_eq!(parts(&comps, SamKind::Pantsir), "РЛС 40%, Ход отказ");
assert_eq!(worst(&comps, SamKind::Pantsir), "Ход отказ");
// A passive post's sensor is optics; only its sensor is fitted.
let mut optics = Comps([1.0; 6]);
optics.0[Part::Sensor as usize] = 0.4;
assert_eq!(parts(&optics, SamKind::Optical), "Опт 40%");
}
#[test]
+7 -3
View File
@@ -339,15 +339,19 @@ ICON_DRAW = {
"deploy_radar": _radar, "deploy_ew": _ew,
"deploy_depot": _depot, "deploy_tzm": _tzm,
"deploy_light": _searchlight,
# Temporary placeholder until the optical post has its own icon (#136).
"deploy_optical": _radar,
"mover": _mover, "remover": _remover, "flare_gun": _flare,
}
# Items that borrow another item's icon until their own art lands (#136: the optical post uses the
# radar icon). The alias is part of the generated model, so no duplicate texture is written.
ICON_ALIAS = {
"deploy_optical": "deploy_radar",
}
def render_icon(name, color, seed):
c = _Icon(color, seed)
ICON_DRAW[name](c)
ICON_DRAW[ICON_ALIAS.get(name, name)](c)
# Контур по краю силуэта: тёмные предметы — светлым, светлые — тёмным, чтобы читались на обоих фонах.
# Альфа-маска не меняется: контур перекрашивает только уже нарисованные пиксели.
lum = 0.3 * color[0] + 0.59 * color[1] + 0.11 * color[2]
+4 -2
View File
@@ -9,7 +9,7 @@ def write_json(path, obj):
def write_registry(out, namespace, models, items, camera_models):
def write_registry(out, namespace, models, items, camera_models, icon_aliases=None):
a = os.path.join(out, "assets", namespace)
d = os.path.join(out, "data", namespace, "horizon")
lang = {}
@@ -19,9 +19,11 @@ def write_registry(out, namespace, models, items, camera_models):
write_json(os.path.join(d, "block", name + ".json"),
{"template": "minecraft:stone", "item": False})
lang[f"block.{NS}.{name}"] = title
icon_aliases = icon_aliases or {}
for name, title, _ in items:
icon = icon_aliases.get(name, name)
write_json(os.path.join(a, "models", "item", name + ".json"),
{"parent": "minecraft:item/generated", "textures": {"layer0": f"{NS}:item/{name}"}})
{"parent": "minecraft:item/generated", "textures": {"layer0": f"{NS}:item/{icon}"}})
write_json(os.path.join(a, "items", name + ".json"),
{"model": {"type": "minecraft:model", "model": f"{NS}:item/{name}"}})
write_json(os.path.join(d, "item", name + ".json"), {"template": "minecraft:stick", "max_stack_size": 1})
+4 -3
View File
@@ -27,7 +27,7 @@ from airdef_assets import pipeline
from airdef_assets.bounds import write_rust_bounds
from airdef_assets.registry import write_json, write_registry
from airdef_assets.texture_catalog import RINGED, STRETCH_FN, TEXTURES
from airdef_assets.icons import ITEMS, render_icon
from airdef_assets.icons import ICON_ALIAS, ITEMS, render_icon
ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", "airdef-mod"))
NS = "airdef"
@@ -1090,8 +1090,9 @@ def generate(out):
write_json(os.path.join(a, "models", "block", name + ".json"), model(fn(), name.endswith("_burnt")))
GT.write_block_textures(a, TEXTURES, VARIANTS, STRETCH_FN)
for name, _, color in ITEMS:
GT.write_item_icon(a, name, render_icon(name, color, zlib.crc32(name.encode())))
write_registry(out, NS, [(name, title) for name, (_, title) in MODELS.items()], ITEMS, CAM_MODELS)
if name not in ICON_ALIAS:
GT.write_item_icon(a, name, render_icon(name, color, zlib.crc32(name.encode())))
write_registry(out, NS, [(name, title) for name, (_, title) in MODELS.items()], ITEMS, CAM_MODELS, ICON_ALIAS)
return len(MODELS), len(ITEMS), len(TEXTURES)
+12
View File
@@ -111,6 +111,18 @@ class ReproducibilityTests(unittest.TestCase):
second = gen_tex.camo("nato_green", 1234, 32)
self.assertEqual(first.tobytes(), second.tobytes())
def test_an_icon_alias_reuses_an_existing_texture_without_writing_a_duplicate(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp) / "mod"
root.mkdir()
gen_models.regenerate(root, root / "source-assets", root / "generated-manifest.txt")
model = json.loads((root / "assets/airdef/models/item/deploy_optical.json").read_text(encoding="utf-8"))
self.assertEqual(model["textures"]["layer0"], "airdef:item/deploy_radar")
self.assertTrue((root / "assets/airdef/textures/item/deploy_radar.png").is_file())
self.assertFalse((root / "assets/airdef/textures/item/deploy_optical.png").exists())
items = {item[0] for item in icons.ITEMS}
self.assertLessEqual(set(icons.ICON_ALIAS.values()), items)
def test_authored_override_is_merged_without_changing_source(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)