Compare commits
3 Commits
v0.3.0-rc2
...
cd3c4ed76d
| Author | SHA1 | Date | |
|---|---|---|---|
| cd3c4ed76d | |||
| 31d967b036 | |||
| 1a693763fd |
@@ -162,7 +162,8 @@ API мода `render.set-lights` (до 512, плавно интерполиру
|
||||
- **Удар.** Ударных ракет мало (3 в запасе, максимум 4, новая за 5 минут), дальность до 4500 блоков; стартуют оттуда, где вы стоите, летят 4 блока в тик (2 км за 25 с) в точку *оценки*. На подлёте ракету может сбить ПВО противника: у ПУ её нет (40%), лёгкая (35%, сбивает в 30%) или тяжёлая (25%, 65%), у баллистических батарей тяжёлая чаще; узнаёте только по итогу. Разброс ракеты 14 блоков; решает истинное расстояние до ПУ: до 35 блоков — **уничтожена** (запас сгорел и рвётся, отложенные запуски отменены, огонь и дымящийся остов, взрыв общим кодом), до 90 — **подавлена** на 30 с (пуски отложены, не отменены), дальше — **промах**, воронка рядом, ПУ цела: очередь за попадание в соседний грунт не списывается. Плохо известную ПУ (круг в сотни блоков) бить почти бесполезно.
|
||||
- **Вне карты.** ПУ без земли (нет загруженной карты) тоже находится: азимут и дальность по трекам, но не рисуется. Удар, который попал бы, прекращает её пуски («результат не виден»); промах теряется.
|
||||
- **Цена выбора.** Ракета запаса не вернётся, пока летит, налёт идёт: близкие площадки не остановить, далёкие (крылатые и баллистические за 2–4 км) успеваете, но для этого нужны РЛС с обзором в сторону налёта и риск промаха или ПВО противника. Отчёт налёта называет сорванные пуски: «Налёт сорван ударами по ПУ (№…): не взлетело N из заявленных M».
|
||||
- Запись: удар попадает в журнал повтора (строка и взрыв/огонь на карте), сами ПУ в повторе не рисуются. Запас ракет входит в сохранение и сценарий (`strikes <запас> <тиков до следующей>`). Все числа механики в одной таблице `TUNE` в `src/sim/strike.rs`.
|
||||
- Столкновение с рельефом или строением по пути взрывает ракету в точке контакта, не поражая ПУ; неизвестная геометрия задерживает полёт, а не считается воздухом. Если новая волна сворачивает старую ПУ, уже выпущенная ракета всё равно завершает полёт и даёт обычный исход.
|
||||
- Запись: полёт ударной ракеты, её двигатель и исход попадают в журнал повтора (трек, строка и взрыв/огонь на карте), самостоятельный удар удерживает запись до завершения; сами ПУ в повторе не рисуются. Запас ракет входит в сохранение и сценарий (`strikes <запас> <тиков до следующей>`), прогресс пополнения автосохраняется контрольными точками с точностью до 5 секунд. Все числа механики в одной таблице `TUNE` в `src/sim/strike.rs`.
|
||||
- `/airdef roles` — показать, по каким классам целей работает каждый комплекс; `/airdef roles <patriot|gepard|pantsir|s400|s500|all> <классы|default>` — задать (классы через запятую: `drone`, `jet`, `cruise`, `supersonic`, `ballistic` или `all`), например `/airdef roles s400 cruise,ballistic`;
|
||||
- `/airdef doctrine` — доктрины комплексов (#47; в меню N: «Доктрины…»): `/airdef doctrine <номер|all> reserve <K>` — держать K ракет для срочных целей (баллистика или до удара меньше 12 с); `salvo eco|normal|heavy` — сколько перехватчиков на цель (только базовые / как обычно / на один больше); `sector <центр°> <полуширина°>` или `sector off` — сектор ответственности (0° — север); `guard <объект№>[,<№>]` или `guard off` — стрелять только по тому, что идёт на охраняемые объекты (отметка: `/airdef target here`). По умолчанию ограничений нет; последний шанс сильнее доктрины; `/airdef why <номер>` называет, какая настройка остановила или разрешила пуск; сохраняется с миром и сценариями. Карта охраны и пробелов в ней — вместе с картой (#48).
|
||||
- `/airdef deploy <patriot|gepard|pantsir|s400|s500>` — поставить комплекс в 8 блоках перед собой;
|
||||
|
||||
+97
-30
@@ -101,7 +101,7 @@ struct AirDef {
|
||||
hd: bool,
|
||||
/// The world whose state is loaded (`game.world-id`), once one is.
|
||||
world: Option<Option<String>>,
|
||||
/// The systems' and objects' health as last saved, to save again when it changes.
|
||||
/// The durable systems, objects and strike stock as last saved, to save again when they change.
|
||||
health_mark: u64,
|
||||
/// The menu's page while it is open.
|
||||
menu: Option<Page>,
|
||||
@@ -827,9 +827,9 @@ impl AirDef {
|
||||
}
|
||||
|
||||
fn draw_hud(&mut self, player: DVec3, yaw: f32) {
|
||||
let air: Vec<&sim::Drone> = self.sim.drones.iter().filter(|d| d.alive()).collect();
|
||||
let pic = self.sim.air_picture();
|
||||
// The command post's grid and replays cover the screen: the other panels wait under them.
|
||||
if self.grid || self.replay.is_some() || (air.is_empty() && self.sim.sams.is_empty() && self.sim.missiles.is_empty()) {
|
||||
if self.grid || self.replay.is_some() || (pic.tracks.is_empty() && self.sim.sams.is_empty() && self.sim.missiles.is_empty()) {
|
||||
if self.hud_shown {
|
||||
hud::clear();
|
||||
render::clear_corner();
|
||||
@@ -838,7 +838,7 @@ impl AirDef {
|
||||
return;
|
||||
}
|
||||
self.hud_shown = true;
|
||||
hud::set_panel(Corner::TopRight, &panel::summary(&self.sim, &air, player));
|
||||
hud::set_panel(Corner::TopRight, &panel::summary(&self.sim, &pic, player));
|
||||
render::set_corner(render::Corner::BottomRight, radar::SIZE, radar::SIZE + 12.0, &radar::draw(&self.sim, player, yaw));
|
||||
}
|
||||
|
||||
@@ -917,7 +917,23 @@ impl AirDef {
|
||||
}
|
||||
|
||||
fn load(&mut self) {
|
||||
self.load_from(&self.state_key());
|
||||
let key = self.state_key();
|
||||
// A save from before worlds were told apart by seed (kept under the folder name alone) goes to the
|
||||
// world that opens first under that name and is then removed, so a later world of the same name
|
||||
// starts empty.
|
||||
if storage::get(&key).is_none()
|
||||
&& let Some(Some(id)) = &self.world
|
||||
&& let Some((base, _)) = id.split_once('#')
|
||||
{
|
||||
let old = state_key_of(Some(base));
|
||||
if storage::get(&old).is_some() {
|
||||
self.load_from(&old);
|
||||
let _ = storage::delete(&old);
|
||||
self.dirty = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
self.load_from(&key);
|
||||
}
|
||||
|
||||
fn load_from(&mut self, key: &str) {
|
||||
@@ -1022,6 +1038,51 @@ impl AirDef {
|
||||
}
|
||||
}
|
||||
|
||||
/// The storage key of a world's state: a hash of its identity (`world_identity`).
|
||||
fn state_key_of(world: Option<&str>) -> String {
|
||||
match world {
|
||||
Some(w) => {
|
||||
// FNV-1a: storage keys are short, lowercase and plain.
|
||||
let h = w.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ b as u64).wrapping_mul(0x100_0000_01b3));
|
||||
format!("state-{h:016x}")
|
||||
}
|
||||
None => "state".into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Which world is open: its folder (`game.world-id`) and, for a saved world, its seed, so a new world
|
||||
/// with the name of an old one has a layout of its own.
|
||||
fn world_identity() -> Option<String> {
|
||||
let id = game::world_id()?;
|
||||
Some(match game::world_seed() {
|
||||
Some(seed) => format!("{id}#{seed:x}"),
|
||||
None => id,
|
||||
})
|
||||
}
|
||||
|
||||
/// What an autosave must not miss (#7, #113): the systems' places, ammunition and damage, the objects' health, and
|
||||
/// the strike missiles' stock and refill. A change here marks the durable state dirty; the write itself is still
|
||||
/// paced by `next_save`, and a failed write is retried.
|
||||
fn durable_mark(sim: &Sim) -> u64 {
|
||||
let st = &sim.strikes;
|
||||
// The stock exactly; the refill at checkpoints, so that a tick-by-tick progress doesn't ask for a save (and a
|
||||
// full state dump) every tick. A restart is at most `progress_save` ticks (5 s) behind on the next missile.
|
||||
let strikes = u64::from(st.stock) | u64::from(st.progress / sim::strike::TUNE.progress_save.max(1)) << 8;
|
||||
sim.sams
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let at = s.dest.unwrap_or(s.pos);
|
||||
let place = (at.x * 10.0) as i64 as u64 ^ ((at.z * 10.0) as i64 as u64).rotate_left(21) ^ (if s.dest.is_some() { 0 } else { (s.heading * 100.0) as i64 as u64 }).rotate_left(42);
|
||||
let ammo = u64::from(s.missiles) | u64::from(s.bursts) << 16 | u64::from(s.cargo) << 32 | u64::from(s.empty) << 48 | u64::from(s.reloading > 0) << 49;
|
||||
let parts = s.comps.0.iter().fold(0u64, |a, v| a.wrapping_mul(131).wrapping_add((v * 100.0) as u64));
|
||||
((s.health * 1000.0) as u64).wrapping_mul(1_000_003) ^ place ^ ammo.rotate_left(7) ^ parts.rotate_left(13)
|
||||
})
|
||||
.chain(sim.target_health.iter().map(|h| (h * 10.0) as u64))
|
||||
.fold(sim.sams.len() as u64, |a, h| a.wrapping_mul(31).wrapping_add(h))
|
||||
.wrapping_mul(31)
|
||||
.wrapping_add(strikes)
|
||||
}
|
||||
|
||||
impl AirDef {
|
||||
/// The EW stations: on if none is, else off.
|
||||
fn toggle_ew(&mut self) {
|
||||
@@ -1038,14 +1099,7 @@ impl AirDef {
|
||||
|
||||
/// Where the open world's state is kept: a key of its own per world.
|
||||
fn state_key(&self) -> String {
|
||||
match self.world.as_ref().and_then(|w| w.as_ref()) {
|
||||
Some(w) => {
|
||||
// FNV-1a: storage keys are short, lowercase and plain.
|
||||
let h = w.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ b as u64).wrapping_mul(0x100_0000_01b3));
|
||||
format!("state-{h:016x}")
|
||||
}
|
||||
None => "state".into(),
|
||||
}
|
||||
state_key_of(self.world.as_ref().and_then(|w| w.as_deref()))
|
||||
}
|
||||
|
||||
/// Another world opened: the last one's state saved, a clean simulation with this one's loaded.
|
||||
@@ -1682,7 +1736,7 @@ impl Mod for AirDef {
|
||||
self.sim.engine_tick = tick;
|
||||
let Some(p) = player() else { return };
|
||||
// Each world keeps its own systems, objects and settings: loaded when it opens.
|
||||
let world = game::world_id();
|
||||
let world = world_identity();
|
||||
if self.world.as_ref() != Some(&world) {
|
||||
self.open_world(world);
|
||||
}
|
||||
@@ -1732,10 +1786,11 @@ impl Mod for AirDef {
|
||||
}
|
||||
}
|
||||
let now = self.sim.tick;
|
||||
self.ground.answer(render::ground(), now);
|
||||
// The blocks themselves (issues #42, #43): what changed, and the sections asked for last tick.
|
||||
// The blocks themselves (issues #42, #43): what changed, and the sections asked for last tick. First, so
|
||||
// that the answers below are judged by the world they come in.
|
||||
let changes = render::world_changes();
|
||||
self.ground.world.changed_rev(changes.epoch, changes.revision, changes.overflow, &changes.sections);
|
||||
self.ground.answer(render::ground(), now);
|
||||
let sections = render::sections()
|
||||
.into_iter()
|
||||
.map(|s| sim::world::SectionAnswer {
|
||||
@@ -1857,19 +1912,7 @@ impl Mod for AirDef {
|
||||
}
|
||||
// Damage is saved too: a destroyed system stays destroyed. So are where the units stand
|
||||
// (or drive to: not every step of the way), their ammunition and the depots' stock.
|
||||
let mark = self
|
||||
.sim
|
||||
.sams
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let at = s.dest.unwrap_or(s.pos);
|
||||
let place = (at.x * 10.0) as i64 as u64 ^ ((at.z * 10.0) as i64 as u64).rotate_left(21) ^ (if s.dest.is_some() { 0 } else { (s.heading * 100.0) as i64 as u64 }).rotate_left(42);
|
||||
let ammo = u64::from(s.missiles) | u64::from(s.bursts) << 16 | u64::from(s.cargo) << 32 | u64::from(s.empty) << 48 | u64::from(s.reloading > 0) << 49;
|
||||
let parts = s.comps.0.iter().fold(0u64, |a, v| a.wrapping_mul(131).wrapping_add((v * 100.0) as u64));
|
||||
((s.health * 1000.0) as u64).wrapping_mul(1_000_003) ^ place ^ ammo.rotate_left(7) ^ parts.rotate_left(13)
|
||||
})
|
||||
.chain(self.sim.target_health.iter().map(|h| (h * 10.0) as u64))
|
||||
.fold(self.sim.sams.len() as u64, |a, h| a.wrapping_mul(31).wrapping_add(h));
|
||||
let mark = durable_mark(&self.sim);
|
||||
if mark != self.health_mark {
|
||||
self.health_mark = mark;
|
||||
self.dirty = true;
|
||||
@@ -2176,7 +2219,10 @@ impl Mod for AirDef {
|
||||
// A strike missile at known site n, from where the player stands.
|
||||
let p = player().ok_or("Нет игрока")?;
|
||||
let id = n.parse::<u32>().map_err(|_| "/airdef strike <номер ПУ из /airdef sites>")?;
|
||||
Some(self.sim.order_strike(id, DVec3::new(p.x, p.y, p.z), &mut out)?)
|
||||
let said = self.sim.order_strike(id, DVec3::new(p.x, p.y, p.z), &mut out)?;
|
||||
// The stock went down: the durable state must not forget it (#113).
|
||||
self.dirty = true;
|
||||
Some(said)
|
||||
}
|
||||
["move", n] => {
|
||||
// Unit n (as the summary numbers them) drives to where the player stands.
|
||||
@@ -2323,4 +2369,25 @@ mod tests {
|
||||
assert!(switch_allowed(true).is_err());
|
||||
assert!(switch_allowed(false).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strike_stock_and_refill_change_the_durable_mark() {
|
||||
let mut sim = Sim::new(7);
|
||||
let full = durable_mark(&sim);
|
||||
sim.strikes.stock -= 1;
|
||||
assert_ne!(durable_mark(&sim), full, "spending a missile is not saved");
|
||||
|
||||
sim.strikes.progress = sim::strike::TUNE.resupply - 1;
|
||||
let before = durable_mark(&sim);
|
||||
let (mut ground, mut out) = (sim::Ground::default(), sim::Out::default());
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
assert_eq!(sim.strikes.stock, 3);
|
||||
assert_ne!(durable_mark(&sim), before, "refilling a missile is not saved");
|
||||
|
||||
let checkpoint = durable_mark(&sim);
|
||||
sim.strikes.progress = 1;
|
||||
assert_eq!(durable_mark(&sim), checkpoint, "progress inside one checkpoint saves every tick");
|
||||
sim.strikes.progress = sim::strike::TUNE.progress_save;
|
||||
assert_ne!(durable_mark(&sim), checkpoint, "a refill checkpoint is not saved");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1047,6 +1047,8 @@ impl AirDef {
|
||||
let mut out = sim::Out::default();
|
||||
match self.sim.order_strike(site, DVec3::new(p.x, p.y, p.z), &mut out) {
|
||||
Ok(m) => {
|
||||
// The stock went down: the durable state must not forget it (#113).
|
||||
self.dirty = true;
|
||||
say(&m);
|
||||
ui.note(tick, "Ударная ракета пошла");
|
||||
}
|
||||
@@ -1418,13 +1420,13 @@ impl AirDef {
|
||||
};
|
||||
self.map_sector(ui, &mut s, sam.pos, &d, sam.kind.range().max(200.0));
|
||||
}
|
||||
// Flights of the strike missiles.
|
||||
// Flights of the strike missiles: the line to the target, the marker where the missile really is (#106).
|
||||
for f in &self.sim.strikes.flights {
|
||||
let a = ui.to_screen(f.from.x, f.from.z);
|
||||
let b = ui.to_screen(f.aim.x, f.aim.y);
|
||||
s.push(line(a, b, 1.0, alpha(0xFFA040, 0.5)));
|
||||
let k = ((now.saturating_sub(f.start)) as f64 / (f.arrive.saturating_sub(f.start)).max(1) as f64).clamp(0.0, 1.0) as f32;
|
||||
s.push(diamond(a.0 + (b.0 - a.0) * k, a.1 + (b.1 - a.1) * k, 3.0, ORANGE));
|
||||
let c = ui.to_screen(f.pos.x, f.pos.z);
|
||||
s.push(diamond(c.0, c.1, 3.0, ORANGE));
|
||||
}
|
||||
// Objects.
|
||||
if ui.filters[F_OBJECTS] {
|
||||
|
||||
+24
-26
@@ -1,6 +1,6 @@
|
||||
//! The summary panel (top right): the alert, what is in the air, each
|
||||
//! air-defence system's state and the score.
|
||||
use crate::sim::{Drone, DroneKind, Sim};
|
||||
use crate::sim::{AirPicture, DroneKind, Sim};
|
||||
use glam::DVec3;
|
||||
use horizon_mod_sdk::hud::Line;
|
||||
|
||||
@@ -23,18 +23,21 @@ fn kmh(v: DVec3) -> f64 {
|
||||
v.length() * 20.0 * 3.6
|
||||
}
|
||||
|
||||
pub fn summary(sim: &Sim, air: &[&Drone], player: DVec3) -> Vec<Line> {
|
||||
/// The panel reads the air picture only (#93): what the network holds, with the age of a forecast. The sandbox's
|
||||
/// `truth` adds one marked line of the real figures; it changes nothing else.
|
||||
pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec<Line> {
|
||||
let mut lines = Vec::new();
|
||||
let line = |text: String, color: u32| Line { text, color };
|
||||
if air.is_empty() {
|
||||
let now = pic.now;
|
||||
if pic.tracks.is_empty() {
|
||||
lines.push(line("Небо чистое".into(), GREEN));
|
||||
} else {
|
||||
let blink = (sim.tick / 10) % 2 == 0;
|
||||
lines.push(line(format!("ВОЗДУШНАЯ ТРЕВОГА — целей: {}", air.len()), if blink { RED } else { PINK }));
|
||||
// By type.
|
||||
lines.push(line(format!("ВОЗДУШНАЯ ТРЕВОГА — целей: {}", pic.tracks.len()), if blink { RED } else { PINK }));
|
||||
// By type, as the radars classed them.
|
||||
let mut by_type = String::new();
|
||||
for kind in DroneKind::ALL {
|
||||
let n = air.iter().filter(|d| d.kind == kind).count();
|
||||
let n = pic.tracks.iter().filter(|t| t.kind == kind).count();
|
||||
if n > 0 {
|
||||
if !by_type.is_empty() {
|
||||
by_type += ", ";
|
||||
@@ -43,29 +46,24 @@ pub fn summary(sim: &Sim, air: &[&Drone], player: DVec3) -> Vec<Line> {
|
||||
}
|
||||
}
|
||||
lines.push(line(by_type, PINK));
|
||||
// The nearest threat to the player.
|
||||
if let Some(d) = air.iter().min_by(|a, b| a.pos.distance(player).total_cmp(&b.pos.distance(player))) {
|
||||
// The nearest track to the player: where it was last measured (a forecast says so, with its age).
|
||||
if let Some(t) = pic.nearest(player) {
|
||||
let e = t.est(now);
|
||||
let mark = if t.forecast(now) { format!(" ~{}с", t.age(now) / 20) } else { String::new() };
|
||||
lines.push(line(
|
||||
format!(
|
||||
"Ближ.: {} {} выс.{:.0} {:.0}км/ч",
|
||||
d.kind.spec().name,
|
||||
distance(d.pos.distance(player)),
|
||||
d.pos.y - player.y,
|
||||
kmh(d.vel)
|
||||
),
|
||||
format!("Ближ.: {} {} выс.{:.0} {:.0}км/ч{mark}", t.kind.spec().name, distance(e.distance(player)), e.y - player.y, kmh(t.vel)),
|
||||
PINK,
|
||||
));
|
||||
}
|
||||
}
|
||||
if sim.planning() {
|
||||
lines.push(line("Противник планирует налёт…".into(), YELLOW));
|
||||
}
|
||||
if !sim.queue.is_empty() {
|
||||
lines.push(line(format!("Ещё взлетает: {}", sim.queue.len()), PINK));
|
||||
}
|
||||
let hidden = air.iter().filter(|d| !sim.sams.is_empty() && !sim.tracked(d.id)).count();
|
||||
if hidden > 0 {
|
||||
lines.push(line(format!("Вне видимости РЛС: {hidden}"), GREY));
|
||||
if sim.truth {
|
||||
let real = sim.drones.iter().filter(|d| d.alive()).count();
|
||||
let unseen = sim.drones.iter().filter(|d| d.alive() && pic.get(d.id).is_none()).count();
|
||||
let mut text = format!("ИСТИНА: в воздухе {real}, вне картины {unseen}, взлетает {}", sim.queue.len());
|
||||
if sim.planning() {
|
||||
text += ", противник планирует налёт";
|
||||
}
|
||||
lines.push(line(text, YELLOW));
|
||||
}
|
||||
// The launch sites found, and the strike missiles (#101).
|
||||
if !sim.strikes.known.is_empty() || !sim.strikes.flights.is_empty() {
|
||||
@@ -103,8 +101,8 @@ pub fn summary(sim: &Sim, air: &[&Drone], player: DVec3) -> Vec<Line> {
|
||||
} else {
|
||||
sam.status()
|
||||
};
|
||||
if let Some(t) = sam.gun_target.or(sam.target).and_then(|t| sim.drones.iter().find(|d| d.id == t)) {
|
||||
text += &format!(" > {} {}", t.kind.spec().name, distance(t.pos.distance(sam.pos)));
|
||||
if let Some(t) = sam.gun_target.or(sam.target).and_then(|t| pic.get(t)) {
|
||||
text += &format!(" > {} {}", t.kind.spec().name, distance(t.est(now).distance(sam.pos)));
|
||||
}
|
||||
if sam.kills > 0 {
|
||||
text += &format!(" ({})", sam.kills);
|
||||
|
||||
+22
-27
@@ -139,43 +139,38 @@ pub fn draw(sim: &Sim, player: DVec3, yaw: f32) -> Vec<Shape> {
|
||||
}
|
||||
// Strike missiles in flight, on the same footing: a small bright dot where the scope reaches, else nothing.
|
||||
for f in &sim.strikes.flights {
|
||||
let t = (sim.tick.saturating_sub(f.start)) as f64 / (f.arrive - f.start).max(1) as f64;
|
||||
let p = f.from.lerp(DVec3::new(f.aim.x, f.from.y, f.aim.y), t.min(1.0));
|
||||
if let Some((x, y, _)) = scope(p) {
|
||||
if let Some((x, y, _)) = scope(f.pos) {
|
||||
s.push(square(x, y, 1.5, 0xFFFFFFA0));
|
||||
}
|
||||
}
|
||||
let mut far = 0;
|
||||
// The air picture is what the systems' radars hold, as they last measured it (a track older than a second
|
||||
// is a forecast, dimmer); with no system deployed, everything as it is.
|
||||
let any = !sim.sams.is_empty();
|
||||
let picture = sim.picture();
|
||||
let now = sim.tick;
|
||||
for d in sim.drones.iter().filter(|d| !any || !d.alive() || picture.contains_key(&d.id)) {
|
||||
let track = picture.get(&d.id).filter(|_| any && d.alive());
|
||||
let (pos, vel) = track.map_or((d.pos, d.vel), |t| (t.est(now), t.vel));
|
||||
// is a forecast, dimmer); with no system deployed, the sky as it is. Nothing else is read (#93).
|
||||
let pic = sim.air_picture();
|
||||
let now = pic.now;
|
||||
for t in &pic.tracks {
|
||||
let (pos, vel) = (t.est(now), t.vel);
|
||||
match scope(pos) {
|
||||
Some((x, y, bearing)) => {
|
||||
if d.alive() {
|
||||
// Fresh: bright and red; a forecast: orange, fading as it ages towards the track's drop.
|
||||
let (a, color) = match track {
|
||||
Some(t) if t.forecast(now) => ((1.0 - t.age(now) as f64 / t.ttl.max(1) as f64 * 0.7).max(0.3), 0xFFB040),
|
||||
Some(_) => (1.0, 0xFF4040),
|
||||
None => (fade(bearing), 0xFF4040),
|
||||
};
|
||||
s.push(square(x, y, 1.8, alpha(color, a)));
|
||||
// Its heading, a short tail.
|
||||
let v = vel.normalize_or_zero();
|
||||
s.push(quad(pt(x, y), pt(x + 0.6, y), pt(x - v.x as f32 * 6.0 + 0.6, y - v.z as f32 * 6.0), pt(x - v.x as f32 * 6.0, y - v.z as f32 * 6.0), alpha(color, a * 0.6)));
|
||||
// Fresh: bright and red; a forecast: orange, fading as it ages towards the track's drop.
|
||||
let (a, color) = if pic.unaided {
|
||||
(fade(bearing), 0xFF4040)
|
||||
} else if t.forecast(now) {
|
||||
((1.0 - t.age(now) as f64 / t.ttl.max(1) as f64 * 0.7).max(0.3), 0xFFB040)
|
||||
} else {
|
||||
s.push(square(x, y, 1.2, alpha(0x909090, fade(bearing))));
|
||||
}
|
||||
(1.0, 0xFF4040)
|
||||
};
|
||||
s.push(square(x, y, 1.8, alpha(color, a)));
|
||||
// Its heading, a short tail.
|
||||
let v = vel.normalize_or_zero();
|
||||
s.push(quad(pt(x, y), pt(x + 0.6, y), pt(x - v.x as f32 * 6.0 + 0.6, y - v.z as f32 * 6.0), pt(x - v.x as f32 * 6.0, y - v.z as f32 * 6.0), alpha(color, a * 0.6)));
|
||||
}
|
||||
None if d.alive() => far += 1,
|
||||
None => {}
|
||||
None => far += 1,
|
||||
}
|
||||
// The true place, when asked for: a white dot beside the track, to see how far the picture is off.
|
||||
if sim.truth && d.alive() && any {
|
||||
}
|
||||
// The true places, when the sandbox asks for them: a white dot beside the track, to see how far the picture is off.
|
||||
if sim.truth && !pic.unaided {
|
||||
for d in sim.drones.iter().filter(|d| d.alive()) {
|
||||
if let Some((x, y, _)) = scope(d.pos) {
|
||||
s.push(square(x, y, 0.8, 0xFFFFFFFF));
|
||||
}
|
||||
|
||||
@@ -145,6 +145,7 @@ fn strike_word(result: StrikeResult) -> &'static str {
|
||||
StrikeResult::Missed => "промах",
|
||||
StrikeResult::Intercepted => "ракета сбита ПВО противника",
|
||||
StrikeResult::Halted => "пуски прекращены (вне карты)",
|
||||
StrikeResult::Blocked => "разбилась о рельеф",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -501,6 +502,12 @@ impl Player {
|
||||
out.engine(key, event, at, vel, gain, pitch, false);
|
||||
}
|
||||
}
|
||||
What::Strike => {
|
||||
// A counter-strike's motor from its launch, as the live flight has it (#109).
|
||||
if let Some((event, pitch)) = DroneKind::Kalibr.engine_voice() {
|
||||
out.engine(key, event, at, vel, 0.8, pitch, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -930,6 +937,7 @@ impl Player {
|
||||
What::Drone(kind) if kind.spec().decoy => (0x70A0A0A0, 0xFFC0C0C0),
|
||||
What::Drone(_) => (0x90FF4040, 0xFFFF6060),
|
||||
What::Missile(..) => (0x90FFD040, 0xFFFFE070),
|
||||
What::Strike => (0x90FFA040, 0xFFFFC060),
|
||||
};
|
||||
let upto = ((self.t - tr.first as f64) / STEP as f64).floor();
|
||||
if upto < 0.0 {
|
||||
|
||||
@@ -162,7 +162,7 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
fn track(pos: DVec3, vel: DVec3) -> Track {
|
||||
Track { id: 1, pos, vel, tick: 0, own_tick: 0, ttl: 100, hits: 3, locked: false }
|
||||
Track { id: 1, kind: DroneKind::Shahed, pos, vel, tick: 0, own_tick: 0, ttl: 100, hits: 3, locked: false }
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -145,6 +145,12 @@ impl Sim {
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether the enemy has this unit in its intelligence: a radar emits, so it is known; the rest only once
|
||||
/// they gave themselves away (a launch, jamming) and are in `known`.
|
||||
pub(super) fn enemy_knows(s: &Sam, known: &[(u32, DVec3)]) -> bool {
|
||||
s.alive() && (s.kind == SamKind::Radar || known.iter().any(|k| k.0 == s.id))
|
||||
}
|
||||
|
||||
/// During a smart raid: its drones not yet launched go for what just gave itself away (a jamming station
|
||||
/// first, then systems that fired), and drones whose system target is gone pick another.
|
||||
pub(super) fn adapt(&mut self) {
|
||||
|
||||
@@ -36,7 +36,7 @@ mod regress;
|
||||
mod sensor_tests;
|
||||
pub use ew::EW_RADIUS;
|
||||
pub use damage::{Comps, Part, PartState};
|
||||
pub use sight::{Ident, LowSensor, Track, RIM_RAYS};
|
||||
pub use sight::{AirPicture, Ident, LowSensor, Track, RIM_RAYS};
|
||||
use damage::dice;
|
||||
use outcome::{Impact, Outcome};
|
||||
pub use units::{Family, SamKind};
|
||||
@@ -245,10 +245,19 @@ pub struct Ground {
|
||||
swept: u64,
|
||||
/// The tick of the last answer round: what the heights' ages are measured against.
|
||||
now: u64,
|
||||
/// The world's epoch when the last questions went out: an answer to them is of that world or dimension, or of none.
|
||||
asked_epoch: Option<u32>,
|
||||
/// The blocks themselves (issues #42, #43): what stops a flight.
|
||||
pub world: world::WorldCache,
|
||||
}
|
||||
|
||||
/// What `render.ground` answers where the chunk is not loaded (and never will be, unless asked for).
|
||||
pub const NO_LAND: i32 = -64;
|
||||
/// A height the game answered as a land height: none where it had no chunk. The one place that reads `NO_LAND`.
|
||||
pub(crate) fn land_height(y: i32) -> Option<f64> {
|
||||
(y > NO_LAND).then_some(f64::from(y))
|
||||
}
|
||||
|
||||
/// What `render.ground` answers (`i32::MIN`) for a column whose chunk it is loading for the mod.
|
||||
pub const PENDING: i32 = i32::MIN;
|
||||
/// Ticks before a column that was loading is asked about again.
|
||||
@@ -279,7 +288,7 @@ impl Ground {
|
||||
if (when == STALE || now.saturating_sub(when) > 200) && self.wanted.len() < 64 && self.asked.insert(key) {
|
||||
self.wanted.push(key);
|
||||
}
|
||||
(y > -64).then_some(f64::from(y))
|
||||
land_height(y)
|
||||
}
|
||||
None => {
|
||||
if self.wanted.len() < 256 && self.asked.insert(key) {
|
||||
@@ -289,8 +298,18 @@ impl Ground {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The game's answers to the questions of `take_wanted`. Each is a height (`land_height`), "no land" or
|
||||
/// "loading"; one to a question of another world or dimension than the one open now is dropped (it is
|
||||
/// asked again when needed), not taken as this one's.
|
||||
pub fn answer(&mut self, answers: Vec<(i32, i32, i32)>, now: u64) {
|
||||
self.now = now;
|
||||
let answers = match self.asked_epoch.take() {
|
||||
Some(e) if e != 0 && e != self.world.epoch() => {
|
||||
self.world.stats.late_dropped += answers.len() as u64;
|
||||
Vec::new()
|
||||
}
|
||||
_ => answers,
|
||||
};
|
||||
for (x, z, y) in answers {
|
||||
if y == PENDING {
|
||||
self.loading.insert((x, z), now);
|
||||
@@ -304,6 +323,12 @@ impl Ground {
|
||||
self.loading.retain(|_, t| now.saturating_sub(*t) < 400);
|
||||
}
|
||||
self.age_heights();
|
||||
// Blasts the game did not report in the blocks: the land there is looked at again.
|
||||
for at in self.world.overdue_blasts(now) {
|
||||
let how = if self.peek(at).is_some() { world::Settled::Unchanged } else { world::Settled::Unloaded };
|
||||
self.world.note_settled(how);
|
||||
self.forget(at, 8);
|
||||
}
|
||||
if self.known.len() > 300_000 && now.saturating_sub(self.swept) >= SWEEP_EVERY {
|
||||
self.swept = now;
|
||||
self.known.retain(|_, (_, when)| now.saturating_sub(*when) < 2000);
|
||||
@@ -312,6 +337,13 @@ impl Ground {
|
||||
/// Heights over blocks that changed (the block cache's notes of changes, chunk replacements and a new world)
|
||||
/// are marked old (`when` = STALE): still used, asked again within the budget. #64.
|
||||
fn age_heights(&mut self) {
|
||||
// Another world or dimension: nothing known, asked or loading belongs to this one.
|
||||
if std::mem::take(&mut self.world.epoch_reset) {
|
||||
self.known.clear();
|
||||
self.loading.clear();
|
||||
self.wanted.clear();
|
||||
self.asked.clear();
|
||||
}
|
||||
let all = std::mem::take(&mut self.world.changed_all);
|
||||
let cols = std::mem::take(&mut self.world.changed_cols);
|
||||
if !all && cols.is_empty() {
|
||||
@@ -359,14 +391,14 @@ impl Ground {
|
||||
// What was answered as "no chunk" there is asked again: the chunk is being loaded now.
|
||||
for x in c.0 * 16..c.0 * 16 + 16 {
|
||||
for z in c.1 * 16..c.1 * 16 + 16 {
|
||||
if self.known.get(&(x, z)).is_some_and(|v| v.0 <= -64) {
|
||||
if self.known.get(&(x, z)).is_some_and(|v| land_height(v.0).is_none()) {
|
||||
self.known.remove(&(x, z));
|
||||
}
|
||||
}
|
||||
}
|
||||
for x in (c.0 * 16..c.0 * 16 + 16).step_by(8) {
|
||||
for z in (c.1 * 16..c.1 * 16 + 16).step_by(8) {
|
||||
if self.known.get(&(x + 4, z + 4)).is_some_and(|v| v.0 <= -64) {
|
||||
if self.known.get(&(x + 4, z + 4)).is_some_and(|v| land_height(v.0).is_none()) {
|
||||
self.known.remove(&(x + 4, z + 4));
|
||||
}
|
||||
}
|
||||
@@ -383,6 +415,7 @@ impl Ground {
|
||||
}
|
||||
pub fn take_wanted(&mut self) -> Vec<(i32, i32)> {
|
||||
self.asked.clear();
|
||||
self.asked_epoch = Some(self.world.epoch());
|
||||
std::mem::take(&mut self.wanted)
|
||||
}
|
||||
/// The first solid block on the way from `a` to `b` (the real blocks, not the height of the land).
|
||||
@@ -926,6 +959,40 @@ pub struct Drone {
|
||||
err: DVec3,
|
||||
/// Ticks held at the edge of blocks the game has not told of (#61); reset by a clear step.
|
||||
hold: u16,
|
||||
/// Its progress towards the aim: a flight that stops getting nearer runs out of fuel (see `Pace`).
|
||||
pace: Pace,
|
||||
}
|
||||
|
||||
/// Ticks a cruise flight may go without getting nearer its aim or passing a route point before it is out of fuel:
|
||||
/// long enough for a detour round a radar, far short of `MAX_FLIGHT`. It stops a drone circling an aim it
|
||||
/// cannot turn onto, or one that holds for an answer that never comes, from loitering over the map for ever.
|
||||
pub const STALL_TICKS: u32 = 3600;
|
||||
/// How much nearer counts as getting nearer (blocks).
|
||||
const STALL_GAIN: f64 = 10.0;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Pace {
|
||||
/// The least distance to the aim so far, the age it was reached at, and the route points left then.
|
||||
best: f64,
|
||||
at: u32,
|
||||
route: usize,
|
||||
}
|
||||
|
||||
impl Default for Pace {
|
||||
fn default() -> Self {
|
||||
Pace { best: f64::INFINITY, at: 0, route: usize::MAX }
|
||||
}
|
||||
}
|
||||
|
||||
impl Pace {
|
||||
/// One tick: true when the flight has gone `STALL_TICKS` without progress.
|
||||
fn stalled(&mut self, age: u32, distance: f64, route: usize) -> bool {
|
||||
if distance + STALL_GAIN < self.best || route < self.route {
|
||||
*self = Pace { best: distance.min(self.best), at: age, route };
|
||||
return false;
|
||||
}
|
||||
age.saturating_sub(self.at) > STALL_TICKS
|
||||
}
|
||||
}
|
||||
|
||||
/// A drone's terrain following: refreshed every few ticks, used every one.
|
||||
@@ -1510,6 +1577,8 @@ pub struct Sim {
|
||||
pub hits: u32,
|
||||
/// Drones that struck the land or a building short of their aim.
|
||||
pub crashes: u32,
|
||||
/// Cruise flights that ran out of fuel for making no headway (`STALL_TICKS`).
|
||||
pub stalled: u32,
|
||||
/// Systems just deployed by hand and not yet checked for standing in the land: (id, until tick).
|
||||
settling: Vec<(u32, u64)>,
|
||||
/// What crashed, where, and its aim (balance measurements only).
|
||||
@@ -1604,6 +1673,7 @@ impl Sim {
|
||||
kills: 0,
|
||||
hits: 0,
|
||||
crashes: 0,
|
||||
stalled: 0,
|
||||
settling: Vec::new(),
|
||||
#[cfg(test)]
|
||||
crashed: Vec::new(),
|
||||
@@ -1949,6 +2019,15 @@ impl Sim {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Out of fuel: no nearer its aim for a long time (it circles, or waits for what never comes): it falls
|
||||
// where it is, a wreck like any other, and the raid is not held open by it.
|
||||
if d.pace.stalled(d.age, d.pos.distance(d.target), d.route.len()) {
|
||||
d.flight = Flight::Falling;
|
||||
d.age = 0;
|
||||
d.vel *= 0.35;
|
||||
self.stalled += 1;
|
||||
continue;
|
||||
}
|
||||
// An interceptor coming: drones drop to the treetops (radars lose them sooner).
|
||||
if d.engaged > 0 && matches!(spec.class, Class::Drone | Class::Jet) {
|
||||
d.low = true;
|
||||
@@ -2162,6 +2241,7 @@ impl Sim {
|
||||
nav: Nav::default(),
|
||||
err: DVec3::ZERO,
|
||||
hold: 0,
|
||||
pace: Pace::default(),
|
||||
});
|
||||
}
|
||||
for d in &self.drones {
|
||||
@@ -2255,6 +2335,7 @@ impl Sim {
|
||||
));
|
||||
}
|
||||
ground.forget(pos, 8);
|
||||
ground.world.expect_blast(pos, 8.0, self.tick);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -512,6 +512,7 @@ impl Sim {
|
||||
nav: Nav::default(),
|
||||
err,
|
||||
hold: 0,
|
||||
pace: Pace::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -560,8 +561,11 @@ impl Sim {
|
||||
}
|
||||
// Smart: each kind at what it is good against; what gave itself away first (a jamming
|
||||
// station, a radar, a system that fired).
|
||||
// The planner has only what the enemy knows (#93): the radars (they emit) and the units that gave
|
||||
// themselves away; the rest of the player's layout is not in its hands.
|
||||
let known = self.known_units();
|
||||
let known_ew: Vec<&Sam> = alive.iter().copied().filter(|s| s.kind == SamKind::Ew && known.iter().any(|k| k.0 == s.id)).collect();
|
||||
let alive: Vec<&Sam> = alive.iter().copied().filter(|s| Self::enemy_knows(s, &known)).collect();
|
||||
let known_ew: Vec<&Sam> = alive.iter().copied().filter(|s| s.kind == SamKind::Ew).collect();
|
||||
if matches!(kind, DroneKind::Lancet | DroneKind::Kh22) && !known_ew.is_empty() && roll < 0.6 {
|
||||
let s = known_ew[(r * known_ew.len() as f64) as usize % known_ew.len()];
|
||||
return (s.pos, Some(s.id));
|
||||
@@ -593,6 +597,7 @@ impl Sim {
|
||||
let mut cost = 0;
|
||||
let spec = kind.spec();
|
||||
let height = spec.clearance.max(6.0);
|
||||
let known_now = self.known_units();
|
||||
let n = grid.size;
|
||||
let mut prices = vec![1.0f32; (n * n) as usize];
|
||||
// Known jamming stations: drones that navigate by satellite keep away.
|
||||
@@ -610,7 +615,8 @@ impl Sim {
|
||||
}
|
||||
}
|
||||
}
|
||||
for s in self.sams.iter().filter(|s| s.alive() && s.roles & spec.class.bit() != 0) {
|
||||
// Only the systems the enemy knows of are priced in (#93): a hidden one is flown into.
|
||||
for s in self.sams.iter().filter(|s| s.alive() && s.roles & spec.class.bit() != 0 && Self::enemy_knows(s, &known_now)) {
|
||||
let sp = s.kind.spec();
|
||||
let (lo, hi) = sp.missile.as_ref().map_or((0.0, 0.0), |m| (m.min, m.max));
|
||||
let gun = sp.gun.as_ref().map_or(0.0, |g| g.range);
|
||||
@@ -750,7 +756,8 @@ const AIR_START_WAIT: u32 = 120;
|
||||
// A side that found nothing is not given up (no raid is cancelled for it): its site is off the map.
|
||||
// The pads, and the sites themselves; the old raid's sites go unless they still have jobs to fly.
|
||||
let queued: Vec<u32> = self.queue.iter().map(|q| q.1.id).collect();
|
||||
self.sites.retire(&queued);
|
||||
let refs = self.site_refs();
|
||||
self.sites.retire(&queued, &refs);
|
||||
for w in plan.wants.iter_mut() {
|
||||
w.jobs = 0;
|
||||
}
|
||||
|
||||
@@ -153,6 +153,8 @@ pub enum What {
|
||||
Drone(DroneKind),
|
||||
/// An interceptor and the system that fired it.
|
||||
Missile(MissileKind, u32),
|
||||
/// A counter-strike missile on its way to a launch site (#109).
|
||||
Strike,
|
||||
}
|
||||
|
||||
pub struct Track {
|
||||
@@ -195,6 +197,8 @@ pub enum StrikeResult {
|
||||
Intercepted,
|
||||
/// Off the map: its launches ended, nothing to see.
|
||||
Halted,
|
||||
/// It met the land or a building short of its aim (#106): it went off there.
|
||||
Blocked,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -357,7 +361,7 @@ pub fn strike_power(result: StrikeResult) -> u32 {
|
||||
match result {
|
||||
StrikeResult::Destroyed => 3,
|
||||
StrikeResult::Stunned => 2,
|
||||
StrikeResult::Missed => 1,
|
||||
StrikeResult::Missed | StrikeResult::Blocked => 1,
|
||||
StrikeResult::Intercepted | StrikeResult::Halted => 0,
|
||||
}
|
||||
}
|
||||
@@ -379,7 +383,7 @@ pub fn blast_spec(kind: EventKind) -> (f32, u32) {
|
||||
EventKind::Split { .. } => (2.0, 7 * 9),
|
||||
EventKind::Strike { result, .. } => match result {
|
||||
StrikeResult::Destroyed => (SIZE[4], LIFE[4] * 9),
|
||||
StrikeResult::Stunned | StrikeResult::Missed => (SIZE[3], LIFE[3] * 9),
|
||||
StrikeResult::Stunned | StrikeResult::Missed | StrikeResult::Blocked => (SIZE[3], LIFE[3] * 9),
|
||||
StrikeResult::Intercepted => (SIZE[0], LIFE[0] * 9),
|
||||
StrikeResult::Halted => (0.0, 0),
|
||||
},
|
||||
@@ -570,14 +574,15 @@ impl Sim {
|
||||
}
|
||||
}
|
||||
|
||||
/// Once a tick: starts a recording with the first drone, adds the tracks' points, ends it
|
||||
/// when the sky has been clear 5 s.
|
||||
/// Once a tick: starts a recording with the first drone or counter-strike in the air, adds the tracks' points,
|
||||
/// ends it when the sky has been clear 5 s.
|
||||
pub(super) fn record(&mut self) {
|
||||
// Wrecks still falling (far off they fall a long while) don't keep it going.
|
||||
let busy = self.drones.iter().any(|d| d.alive()) || !self.missiles.is_empty() || !self.queue.is_empty();
|
||||
// Wrecks still falling (far off they fall a long while) don't keep it going. A counter-strike is a recorded
|
||||
// object in its own right (#109): it holds the recording open until it lands, whatever the sky is doing.
|
||||
let busy = self.drones.iter().any(|d| d.alive()) || !self.missiles.is_empty() || !self.queue.is_empty() || !self.strikes.flights.is_empty();
|
||||
if self.rec.is_none() {
|
||||
// It starts with the first drone in the sky (not with a raid's drones still waiting).
|
||||
if !self.drones.iter().any(|d| d.alive()) {
|
||||
// It starts with the first drone or strike missile in the air (not with a raid's drones still waiting).
|
||||
if !self.drones.iter().any(|d| d.alive()) && self.strikes.flights.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.recordings += 1;
|
||||
@@ -599,6 +604,9 @@ impl Sim {
|
||||
for m in &self.missiles {
|
||||
r.point(m.id, What::Missile(m.kind, m.sam), m.pos);
|
||||
}
|
||||
for f in &self.strikes.flights {
|
||||
r.point(f.track(), What::Strike, f.pos);
|
||||
}
|
||||
}
|
||||
r.len += 1;
|
||||
r.quiet = if busy { 0 } else { r.quiet + 1 };
|
||||
@@ -665,6 +673,16 @@ impl Sim {
|
||||
out.model(id + 1, "airdef:flame", pos + rot * DVec3::new(0.0, 0.0, back), rot, spec.flame, true);
|
||||
}
|
||||
}
|
||||
What::Strike => {
|
||||
// The same model, flame and turn the live flight drew (#106, #109).
|
||||
let spec = DroneKind::Kalibr.spec();
|
||||
let rot = look(dir, 0.0);
|
||||
out.model(id, spec.model, pos, rot, spec.scale, false);
|
||||
if let Engine::Jet(up, back, size) = spec.engine {
|
||||
let flicker = 0.7 + 0.3 * (t * 1.7).sin().abs();
|
||||
out.model(id + 1, "airdef:geran3_flame", pos + rot * DVec3::new(0.0, up * spec.scale, back * spec.scale), rot, spec.scale * size * flicker, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The air-defence systems as they stood: where, which way, the launcher or turret where it
|
||||
|
||||
@@ -51,6 +51,10 @@ fn network_launcher_must_contribute_to_route_risk() {
|
||||
let id=sim.id();sim.sams.push(Sam::new(id,SamKind::P1sun,DVec3::new(0.,70.,0.),0.));
|
||||
let id=sim.id();sim.sams.push(Sam::new(id,SamKind::Radar,DVec3::new(0.,70.,0.),0.));
|
||||
let grid=Grid{min:DVec3::new(-160.,0.,-160.),cell:16.,size:20};
|
||||
// #93: the planner prices only what the enemy knows; the radar emits, the launcher is not known until it gives itself away.
|
||||
let (prices,_)=sim.price_grid(&grid,DroneKind::Shahed);
|
||||
assert!(prices.iter().all(|p|*p==1.),"an unknown launcher must not be priced");
|
||||
sim.intel.revealed.push((sim.sams[0].id,DVec3::new(0.,70.,0.),0));
|
||||
let (prices,_)=sim.price_grid(&grid,DroneKind::Shahed);
|
||||
assert!(prices.iter().any(|p|*p>1.),"armed launcher with a network radar is invisible to route risk");
|
||||
}
|
||||
@@ -1711,3 +1715,92 @@ fn over_unknown_land_a_flight_does_not_descend() {
|
||||
}
|
||||
assert!(sim.drones[0].pos.y > 245.0, "it came down over unknown land: {}", sim.drones[0].pos.y);
|
||||
}
|
||||
|
||||
/// #90: a cruise flight that stops getting nearer its aim (a turn circle wider than the distance, a hold that
|
||||
/// never ends) falls out of the sky after `STALL_TICKS`, so a raid is not held open by it.
|
||||
#[test]
|
||||
fn a_flight_that_makes_no_headway_runs_out_of_fuel() {
|
||||
let mut pace = Pace::default();
|
||||
// Nearer and nearer: never stalled.
|
||||
for age in 1..10_000u32 {
|
||||
assert!(!pace.stalled(age, 5000.0 - f64::from(age) * 0.5, 1), "a flight under way stalled at {age}");
|
||||
}
|
||||
// Circling at 40 blocks from the aim.
|
||||
let mut pace = Pace::default();
|
||||
let mut ended = None;
|
||||
for age in 1..10_000u32 {
|
||||
if pace.stalled(age, 40.0 + f64::from(age % 7), 1) {
|
||||
ended = Some(age);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let ended = ended.expect("a circling flight never ran out of fuel");
|
||||
assert!((STALL_TICKS..STALL_TICKS + 20).contains(&ended), "{ended}");
|
||||
// Passing a route point is progress, however far off the aim the way goes.
|
||||
let mut pace = Pace::default();
|
||||
for age in 1..10_000u32 {
|
||||
assert!(!pace.stalled(age, 3000.0, 10 - (age / 1000) as usize), "route points passed, still stalled at {age}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #90: the same in the simulation: a drone that gets no nearer its aim (here the aim keeps its distance, as one
|
||||
/// does that it cannot turn onto) ends, falling, within the stall time, and the raid is not held open by it.
|
||||
#[test]
|
||||
fn a_drone_that_never_arrives_ends_the_raid() {
|
||||
let mut sim = Sim::new(4);
|
||||
let mut d = sim.make_drone(DroneKind::Kh101, DVec3::new(0.0, 400.0, 0.0), DVec3::X, DVec3::new(3000.0, 400.0, 0.0));
|
||||
d.low = false;
|
||||
sim.drones.push(d);
|
||||
let (mut ground, mut out) = (Ground::default(), Out::default());
|
||||
let mut ended = None;
|
||||
for t in 0..STALL_TICKS + 400 {
|
||||
if let Some(d) = sim.drones.first_mut() {
|
||||
d.target = d.pos + DVec3::X * 3000.0;
|
||||
}
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
if !sim.drones.iter().any(|d| d.alive()) {
|
||||
ended = Some(t);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let ended = ended.expect("still airborne after the stall time");
|
||||
assert!(ended >= STALL_TICKS, "ended early: {ended}");
|
||||
assert_eq!(sim.stalled, 1);
|
||||
}
|
||||
|
||||
/// #90: an answer says which world it is of. Heights of another dimension are not this one's, and an answer to a
|
||||
/// question asked before the world changed is dropped, not read as the new world's.
|
||||
#[test]
|
||||
fn heights_of_another_world_are_void_and_late_answers_are_dropped() {
|
||||
let mut ground = Ground::default();
|
||||
ground.world.changed_rev(1, 0, false, &[]);
|
||||
ground.answer(vec![(4, 4, 70), (12, 4, NO_LAND)], 1);
|
||||
assert_eq!(ground.land_state(DVec3::new(4.5, 80.0, 4.5)), Some(Some(70.0)));
|
||||
assert_eq!(ground.land_state(DVec3::new(12.5, 80.0, 4.5)), Some(None), "no land is an answer too");
|
||||
// A question goes out in world 1; the dimension changes before the answer comes.
|
||||
let _ = ground.land(DVec3::new(100.5, 80.0, 100.5));
|
||||
assert_eq!(ground.take_wanted().len(), 1);
|
||||
ground.world.changed_rev(2, 0, false, &[]);
|
||||
ground.answer(vec![(100, 100, 55)], 2);
|
||||
assert_eq!(ground.world.stats.late_dropped, 1);
|
||||
assert_eq!(ground.land_state(DVec3::new(4.5, 80.0, 4.5)), None, "the old dimension's height is gone, asked again");
|
||||
assert_eq!(ground.land_state(DVec3::new(100.5, 80.0, 100.5)), None, "the late answer was not taken");
|
||||
}
|
||||
|
||||
/// #90: a blast asked of the game in the blocks is confirmed by the game's own report of blocks changed there; one
|
||||
/// that is not reported is told apart by whether the land was there.
|
||||
#[test]
|
||||
fn a_blast_in_the_blocks_waits_for_the_games_word() {
|
||||
let mut ground = Ground::default();
|
||||
ground.answer(vec![(4, 4, 70)], 1);
|
||||
let near = DVec3::new(4.5, 70.0, 4.5);
|
||||
let far = DVec3::new(900.5, 70.0, 900.5);
|
||||
ground.world.expect_blast(near, 8.0, 1);
|
||||
ground.world.expect_blast(near + DVec3::X * 200.0, 8.0, 1);
|
||||
ground.world.expect_blast(far, 8.0, 1);
|
||||
ground.world.changed_rev(1, 1, false, &[(0, 4, 0)]);
|
||||
assert_eq!(ground.world.stats.blasts_confirmed, 1);
|
||||
ground.answer(vec![], 1 + world::CONFIRM_TICKS);
|
||||
let s = ground.world.stats;
|
||||
assert_eq!((s.blasts_asked, s.blasts_confirmed, s.blasts_unchanged, s.blasts_unloaded), (3, 1, 0, 2));
|
||||
}
|
||||
|
||||
@@ -119,7 +119,7 @@ impl Ground {
|
||||
let hit = self.known.get(&k).or_else(|| {
|
||||
self.known.get(&(k.0.div_euclid(LAT) * LAT + LAT / 2, k.1.div_euclid(LAT) * LAT + LAT / 2))
|
||||
});
|
||||
hit.and_then(|&(y, _)| (y > -64).then_some(f64::from(y)))
|
||||
hit.and_then(|&(y, _)| land_height(y))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -235,6 +235,8 @@ impl Ident {
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Track {
|
||||
pub id: u32,
|
||||
/// What the radar made of it when it measured (the class the picture shows).
|
||||
pub kind: DroneKind,
|
||||
/// Where it was and how it went when last measured (blocks, blocks a tick).
|
||||
pub pos: DVec3,
|
||||
pub vel: DVec3,
|
||||
@@ -248,6 +250,24 @@ pub struct Track {
|
||||
pub locked: bool,
|
||||
}
|
||||
|
||||
/// What the player's side knows of the air: the network's tracks as last measured, never the drones themselves.
|
||||
pub struct AirPicture {
|
||||
pub now: u64,
|
||||
pub tracks: Vec<Track>,
|
||||
/// No system is deployed: the tracks are the sky as it is.
|
||||
pub unaided: bool,
|
||||
}
|
||||
|
||||
impl AirPicture {
|
||||
pub fn get(&self, id: u32) -> Option<&Track> {
|
||||
self.tracks.iter().find(|t| t.id == id)
|
||||
}
|
||||
/// The track nearest to a point, by its forecast place.
|
||||
pub fn nearest(&self, to: DVec3) -> Option<&Track> {
|
||||
self.tracks.iter().min_by(|a, b| a.est(self.now).distance(to).total_cmp(&b.est(self.now).distance(to)))
|
||||
}
|
||||
}
|
||||
|
||||
impl Track {
|
||||
pub fn age(&self, now: u64) -> u64 {
|
||||
now.saturating_sub(self.tick)
|
||||
@@ -396,6 +416,7 @@ impl Sim {
|
||||
let noise = DVec3::new(dice(seed, now, key, 1) - 0.5, (dice(seed, now, key, 2) - 0.5) * 0.5, dice(seed, now, key, 3) - 0.5) * 2.0 * sigma;
|
||||
fresh.push(Track {
|
||||
id: d.id,
|
||||
kind: d.kind,
|
||||
pos: d.pos + noise,
|
||||
vel: d.vel,
|
||||
tick: now,
|
||||
@@ -447,6 +468,25 @@ impl Sim {
|
||||
self.sams.iter().any(|s| s.seen.contains(&id))
|
||||
}
|
||||
|
||||
/// The air picture as the player's panel and radar read it (the only thing they read).
|
||||
pub fn air_picture(&self) -> AirPicture {
|
||||
let now = self.tick;
|
||||
// With no system deployed there is no radar to be blind: the sky as it is (the same fallback the screens
|
||||
// always had); a network's picture is only what it holds.
|
||||
let unaided = self.sams.is_empty();
|
||||
let mut tracks: Vec<Track> = if unaided {
|
||||
self.drones
|
||||
.iter()
|
||||
.filter(|d| d.alive())
|
||||
.map(|d| Track { id: d.id, kind: d.kind, pos: d.pos, vel: d.vel, tick: now, own_tick: now, ttl: 1, hits: 3, locked: false })
|
||||
.collect()
|
||||
} else {
|
||||
self.picture().into_values().collect()
|
||||
};
|
||||
tracks.sort_by_key(|t| t.id);
|
||||
AirPicture { now, tracks, unaided }
|
||||
}
|
||||
|
||||
/// The freshest track of each drone any system holds: the air picture.
|
||||
pub fn picture(&self) -> HashMap<u32, Track> {
|
||||
let mut best: HashMap<u32, Track> = HashMap::new();
|
||||
|
||||
+144
-3
@@ -164,6 +164,10 @@ pub struct Sites {
|
||||
pub list: Vec<LaunchSite>,
|
||||
next: u32,
|
||||
jobs: Vec<(u32, u32)>,
|
||||
/// Sites a new wave kept for something still in the air (#108): their kit stays until that is gone.
|
||||
holding: Vec<u32>,
|
||||
/// Drones that left a site and are still in the air: (drone, site), so their site is not taken away under them.
|
||||
flying: Vec<(u32, u32)>,
|
||||
}
|
||||
|
||||
/// What a site says about a drone due to leave.
|
||||
@@ -194,6 +198,8 @@ impl Sites {
|
||||
pub fn clear(&mut self) {
|
||||
self.list.clear();
|
||||
self.jobs.clear();
|
||||
self.holding.clear();
|
||||
self.flying.clear();
|
||||
}
|
||||
pub(super) fn add(&mut self, mut site: LaunchSite) -> u32 {
|
||||
self.next += 1;
|
||||
@@ -205,11 +211,34 @@ impl Sites {
|
||||
pub(super) fn job(&mut self, drone: u32, site: u32) {
|
||||
self.jobs.push((drone, site));
|
||||
}
|
||||
/// The old raid's sites go, but not those with jobs still to fly.
|
||||
pub(super) fn retire(&mut self, queued: &[u32]) {
|
||||
/// The old raid's sites go, but not those with jobs still to fly, nor those something in the air still came
|
||||
/// from or is flying to (#108: a missile on its way is not left shooting at a vanished base).
|
||||
pub(super) fn retire(&mut self, queued: &[u32], refs: &[u32]) {
|
||||
self.jobs.retain(|j| queued.contains(&j.0));
|
||||
let jobs = &self.jobs;
|
||||
self.list.retain(|s| jobs.iter().any(|j| j.1 == s.id));
|
||||
let mut list = std::mem::take(&mut self.list);
|
||||
list.retain(|s| jobs.iter().any(|j| j.1 == s.id) || refs.contains(&s.id));
|
||||
self.list = list;
|
||||
// What only the references hold: let go once they are gone, so no old bases pile up.
|
||||
self.holding = self.list.iter().filter(|s| !jobs.iter().any(|j| j.1 == s.id)).map(|s| s.id).collect();
|
||||
}
|
||||
/// Drops the sites `retire` held only for a flight, a drone or a scout link that is now gone.
|
||||
pub(super) fn prune(&mut self, refs: &[u32]) {
|
||||
if self.holding.is_empty() {
|
||||
return;
|
||||
}
|
||||
let live = |id: &u32| refs.contains(id) || self.jobs.iter().any(|j| j.1 == *id);
|
||||
let gone: Vec<u32> = self.holding.iter().copied().filter(|id| !live(id)).collect();
|
||||
if gone.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.holding.retain(|id| live(id));
|
||||
self.list.retain(|s| !gone.contains(&s.id));
|
||||
}
|
||||
/// Sites drones still in the air left: (drone, site) for those alive in the list, forgetting the others.
|
||||
pub(super) fn flying_sites(&mut self, alive: &[u32]) -> Vec<u32> {
|
||||
self.flying.retain(|(d, _)| alive.contains(d));
|
||||
self.flying.iter().map(|f| f.1).collect()
|
||||
}
|
||||
fn take(&mut self, drone: u32, now: u64) -> Slot {
|
||||
let Some(j) = self.jobs.iter().position(|j| j.0 == drone) else { return Slot::Free };
|
||||
@@ -229,6 +258,8 @@ impl Sites {
|
||||
s.next_free = now + s.class.cadence();
|
||||
let air = s.offmap;
|
||||
self.jobs.swap_remove(j);
|
||||
// A drone in the air still belongs to its site: a new wave must not take the pad from under it (#108).
|
||||
self.flying.push((drone, site));
|
||||
if air { Slot::Air } else { Slot::Go }
|
||||
}
|
||||
}
|
||||
@@ -1052,4 +1083,114 @@ mod tests {
|
||||
};
|
||||
assert_eq!(run(false), run(true));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- #108: what holds a site beyond its wave
|
||||
|
||||
/// A site with the radars' fix on it, and no launches left: a strike can be sent at it without any drone flying.
|
||||
fn fixed_site(sim: &mut Sim, pos: DVec3) -> u32 {
|
||||
let id = sim.sites.add(LaunchSite {
|
||||
id: 0,
|
||||
side: 0,
|
||||
sector: 0,
|
||||
bearing: 0.0,
|
||||
class: SiteClass::Ramp,
|
||||
pos,
|
||||
range: pos.z,
|
||||
water: false,
|
||||
stock: 0,
|
||||
planned: 0,
|
||||
alive: true,
|
||||
next_free: 0,
|
||||
offmap: false,
|
||||
});
|
||||
sim.strikes.known.push(super::super::strike::Known {
|
||||
site: id,
|
||||
class: SiteClass::Ramp,
|
||||
obs: Vec::new(),
|
||||
est: Some(super::super::strike::Estimate {
|
||||
pos: glam::DVec2::new(pos.x, pos.z),
|
||||
radius: 5.0,
|
||||
fix: true,
|
||||
bearing: 0.0,
|
||||
bearing_err: 0.01,
|
||||
origin: glam::DVec2::ZERO,
|
||||
}),
|
||||
launches: 1,
|
||||
last: 0,
|
||||
state: super::super::strike::SiteState::Active,
|
||||
cover: None,
|
||||
aimed: false,
|
||||
});
|
||||
id
|
||||
}
|
||||
#[test]
|
||||
fn a_wave_keeps_the_site_a_strike_is_still_flying_to() {
|
||||
let mut sim = Sim::new(11);
|
||||
sim.strikes.cover_override = Some(0);
|
||||
let id = fixed_site(&mut sim, DVec3::new(0.0, 64.0, 300.0));
|
||||
let mut ground = Ground::default();
|
||||
let mut out = Out::default();
|
||||
sim.order_strike(id, DVec3::new(0.0, 64.0, 0.0), &mut out).unwrap();
|
||||
// The next wave is planned while the missile is in the air: its housekeeping must not take the target away.
|
||||
let refs = sim.site_refs();
|
||||
assert!(refs.contains(&id), "the flight is no reference to its site");
|
||||
sim.sites.retire(&[], &refs);
|
||||
assert!(sim.sites.get(id).is_some(), "a new wave took the site a missile was flying to");
|
||||
// The missile lands: the site is hit, and nothing keeps it afterwards.
|
||||
for _ in 0..300 {
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
if sim.strikes.flights.is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(sim.strikes.flights.is_empty());
|
||||
assert_eq!(sim.strikes.fired, 1);
|
||||
assert_eq!(sim.strikes.destroyed + sim.strikes.stunned + sim.strikes.missed, 1, "{:?}", out.messages);
|
||||
assert!(sim.sites.get(id).is_none(), "the old base stays on the map for ever");
|
||||
assert!(sim.strikes.flights.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wave_keeps_the_site_a_drone_left_from_until_that_is_gone() {
|
||||
let mut sim = Sim::new(11);
|
||||
let id = sim.sites.add(LaunchSite {
|
||||
id: 0,
|
||||
side: 0,
|
||||
sector: 0,
|
||||
bearing: 0.0,
|
||||
class: SiteClass::Ramp,
|
||||
pos: DVec3::new(0.0, 64.0, 300.0),
|
||||
range: 300.0,
|
||||
water: false,
|
||||
stock: 1,
|
||||
planned: 1,
|
||||
alive: true,
|
||||
next_free: 0,
|
||||
offmap: false,
|
||||
});
|
||||
let site = sim.sites.get(id).unwrap().clone();
|
||||
let d = sim.make_drone(DroneKind::Shahed, site.muzzle(0), -DVec3::Z, DVec3::new(0.0, 70.0, 0.0));
|
||||
sim.sites.job(d.id, id);
|
||||
sim.queue.push((1, d));
|
||||
let (mut ground, mut out) = (Ground::default(), Out::default());
|
||||
// Let the drone leave the ramp.
|
||||
let mut left = false;
|
||||
for _ in 0..200 {
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
left |= sim.drones.iter().any(|d| d.alive());
|
||||
if left {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(left, "the drone never left");
|
||||
let refs = sim.site_refs();
|
||||
assert!(refs.contains(&id), "a drone in the air is no reference to the site it left");
|
||||
sim.sites.retire(&[], &refs);
|
||||
assert!(sim.sites.get(id).is_some(), "the site of a flying drone was taken away");
|
||||
// Once the drone is gone, the site is let go: no old bases pile up.
|
||||
sim.drones.clear();
|
||||
let refs = sim.site_refs();
|
||||
sim.sites.prune(&refs);
|
||||
assert!(sim.sites.get(id).is_none(), "an old base stays after its last drone");
|
||||
}
|
||||
}
|
||||
|
||||
+405
-35
@@ -50,6 +50,9 @@ pub struct Tune {
|
||||
pub stock: u32,
|
||||
pub stock_max: u32,
|
||||
pub resupply: u32,
|
||||
/// Ticks between the checkpoints at which the refilling progress is written to a save: a restart is at most
|
||||
/// this much of the wait to the next missile behind (#113).
|
||||
pub progress_save: u32,
|
||||
/// Blocks a tick, the farthest target (blocks), and the cruise height over the launch (blocks).
|
||||
pub speed: f64,
|
||||
pub range: f64,
|
||||
@@ -83,6 +86,7 @@ pub const TUNE: Tune = Tune {
|
||||
stock: 3,
|
||||
stock_max: 4,
|
||||
resupply: 6000,
|
||||
progress_save: 100,
|
||||
speed: 8.0,
|
||||
range: 4500.0,
|
||||
height: 40.0,
|
||||
@@ -261,16 +265,48 @@ struct Flown {
|
||||
at: u64,
|
||||
}
|
||||
|
||||
/// A strike missile in flight.
|
||||
/// The target of a strike as it was when the missile left: what the outcome is judged against, even if the site
|
||||
/// has been taken off the map since (#108).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Target {
|
||||
/// Where the site really stands (x, z).
|
||||
pub pos: DVec2,
|
||||
pub stock: u32,
|
||||
pub offmap: bool,
|
||||
pub alive: bool,
|
||||
/// What its cover was (0 none, 1 light, 2 heavy), fixed at the launch.
|
||||
pub cover: u8,
|
||||
}
|
||||
|
||||
/// A strike missile in flight: the shot it was fired as, where it is, and where it is going.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Flight {
|
||||
pub id: u32,
|
||||
pub site: u32,
|
||||
/// Where it was fired from, and where it is now (the swept step, not the plan).
|
||||
pub from: DVec3,
|
||||
/// The aim (x, z).
|
||||
pub pos: DVec3,
|
||||
/// The aim (x, z) the player was told of, and the place it really lands: the aim plus its own scatter,
|
||||
/// fixed at the launch so the flight and its outcome name the same point.
|
||||
pub aim: DVec2,
|
||||
pub land: DVec2,
|
||||
pub start: u64,
|
||||
pub arrive: u64,
|
||||
/// The site as it was at the launch.
|
||||
pub snap: Target,
|
||||
/// Ticks it was held at an unread stretch of the world (#61).
|
||||
hold: u16,
|
||||
}
|
||||
|
||||
impl Flight {
|
||||
/// The id of its track in a recording (a range of its own, apart from the drones').
|
||||
pub fn track(&self) -> u32 {
|
||||
0x7100_0000 | self.id
|
||||
}
|
||||
/// The key of its exact-shape questions, apart from those of the drones' and interceptors'.
|
||||
fn key(&self) -> u32 {
|
||||
0x9000_0000 | self.id
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -314,6 +350,10 @@ impl Strikes {
|
||||
pub fn seconds_to_next(&self) -> u32 {
|
||||
(TUNE.resupply - self.progress.min(TUNE.resupply)) / 20
|
||||
}
|
||||
/// Sites a living launched drone not yet picked up on a track still came from (#108).
|
||||
pub(super) fn scouted<'a>(&'a self, alive: &'a [u32]) -> impl Iterator<Item = u32> + 'a {
|
||||
self.flown.iter().filter(move |f| alive.contains(&f.drone)).map(|f| f.site)
|
||||
}
|
||||
}
|
||||
|
||||
/// A standard normal from the seed and three numbers (the combat's random sequence is left alone).
|
||||
@@ -534,21 +574,65 @@ impl Sim {
|
||||
}
|
||||
}
|
||||
|
||||
/// Strike missiles on their way: drawn, heard, and landed when their time is up.
|
||||
/// Strike missiles on their way: moved a swept step at a time, drawn and heard where they really are, and
|
||||
/// landed or broken on what the world says is in the way (#106).
|
||||
fn fly_strikes(&mut self, ground: &mut Ground, player: Option<DVec3>, out: &mut Out) {
|
||||
let now = self.tick;
|
||||
let spec = DroneKind::Kalibr.spec();
|
||||
let flights = std::mem::take(&mut self.strikes.flights);
|
||||
let mut rest = Vec::with_capacity(flights.len());
|
||||
for f in flights {
|
||||
if now >= f.arrive {
|
||||
self.land_strike(f, ground, player, out);
|
||||
for mut f in flights {
|
||||
// The terminal point: where it lands, at the land there as known now (a ridge that changed since the
|
||||
// launch is flown over or into as it stands). With no land told of, the height it left at.
|
||||
let below = ground.at(DVec3::new(f.land.x, 0.0, f.land.y), now);
|
||||
let end = DVec3::new(f.land.x, below.unwrap_or(f.from.y), f.land.y);
|
||||
let t = ((now - f.start) as f64 / (f.arrive - f.start).max(1) as f64).clamp(0.0, 1.0);
|
||||
let want = f.from.lerp(end, t) + DVec3::Y * (TUNE.height * (std::f64::consts::PI * t).sin().max(0.0).sqrt());
|
||||
let from = f.pos;
|
||||
if now >= f.arrive && from.distance(end) <= TUNE.speed * 1.5 + 2.0 {
|
||||
self.land_strike(f, from, ground, player, out);
|
||||
continue;
|
||||
}
|
||||
let t = (now - f.start) as f64 / (f.arrive - f.start).max(1) as f64;
|
||||
let end = DVec3::new(f.aim.x, f.from.y, f.aim.y);
|
||||
let pos = f.from.lerp(end, t) + DVec3::Y * (TUNE.height * (std::f64::consts::PI * t).sin().max(0.0).sqrt());
|
||||
let dir = (end - f.from).normalize_or(DVec3::NEG_Z) + DVec3::Y * 0.001;
|
||||
// A missile that never reaches its point (the world never tells of the way) ends somewhere: it does
|
||||
// not stay in the air for ever.
|
||||
if now >= f.arrive + 600 {
|
||||
self.crash_strike(f, from, ground, player, out);
|
||||
continue;
|
||||
}
|
||||
let vel = want - from;
|
||||
if vel.length() > 1e-6 {
|
||||
ground.ahead(from, vel, 20.0, now);
|
||||
}
|
||||
let sweep = ground.trace(f.key(), from, want, false, now);
|
||||
let mut pos = want;
|
||||
let contact = match sweep {
|
||||
world::Sweep::Hit { point, .. } => Some(point),
|
||||
world::Sweep::Wait { t } => {
|
||||
pos = from.lerp(want, (t - 1e-6).max(0.0));
|
||||
None
|
||||
}
|
||||
world::Sweep::Unknown { .. } => {
|
||||
// Unread is not air (#61): the flight holds at the edge of what is read, and only a chunk
|
||||
// the game doesn't have (not one still loading) is passed, high over the land.
|
||||
let low = ground.at(from, now).is_some_and(|g| from.y < g + 12.0);
|
||||
if let Some(t) = ground.unread(&sweep, &mut f.hold, low) {
|
||||
pos = from.lerp(want, t);
|
||||
}
|
||||
None
|
||||
}
|
||||
world::Sweep::Clear => None,
|
||||
};
|
||||
if let Some(point) = contact {
|
||||
self.crash_strike(f, point, ground, player, out);
|
||||
continue;
|
||||
}
|
||||
// The land's height says it met the ground where the blocks were not read: the same contact.
|
||||
let here = ground.at(pos, now);
|
||||
if ground.ground_hit(here, pos, 0.2, &sweep, now) {
|
||||
self.crash_strike(f, pos, ground, player, out);
|
||||
continue;
|
||||
}
|
||||
let dir = (pos - from).normalize_or(end - f.from).normalize_or(DVec3::NEG_Z);
|
||||
let rot = look(dir, 0.0);
|
||||
let id = 0x7500_0000 + f.id * PARTS;
|
||||
out.model(id, spec.model, pos, rot, spec.scale, false);
|
||||
@@ -557,12 +641,28 @@ impl Sim {
|
||||
out.model(id + 1, "airdef:geran3_flame", pos + rot * DVec3::new(0.0, up * spec.scale, back * spec.scale), rot, spec.scale * size * flicker, true);
|
||||
}
|
||||
if let Some((event, pitch)) = DroneKind::Kalibr.engine_voice() {
|
||||
out.engine(id, event, pos, dir.normalize() * TUNE.speed, 0.8, pitch, false);
|
||||
out.engine(id, event, pos, dir * TUNE.speed, 0.8, pitch, false);
|
||||
}
|
||||
f.pos = pos;
|
||||
rest.push(f);
|
||||
}
|
||||
rest.append(&mut self.strikes.flights);
|
||||
self.strikes.flights = rest;
|
||||
// A site held only for something still in the air goes when that is gone (#108): no old bases pile up.
|
||||
let refs = self.site_refs();
|
||||
self.sites.prune(&refs);
|
||||
}
|
||||
|
||||
/// The sites something still in the air came from or is flying to (#108): a site retired by a new wave is kept
|
||||
/// while these exist, and let go after.
|
||||
pub(super) fn site_refs(&mut self) -> Vec<u32> {
|
||||
let mut v: Vec<u32> = self.strikes.flights.iter().map(|f| f.site).collect();
|
||||
let alive: Vec<u32> = self.drones.iter().filter(|d| d.alive()).map(|d| d.id).collect();
|
||||
v.extend(self.strikes.scouted(&alive));
|
||||
v.extend(self.sites.flying_sites(&alive));
|
||||
v.sort_unstable();
|
||||
v.dedup();
|
||||
v
|
||||
}
|
||||
|
||||
/// Fires a strike missile at known site `id` from `from`. Returns the line for the player.
|
||||
@@ -584,14 +684,32 @@ impl Sim {
|
||||
if dist > TUNE.range {
|
||||
return Err(format!("ПУ №{id} дальше дальности удара ({})", crate::panel::distance(TUNE.range)));
|
||||
}
|
||||
// The target as it is now: the missile is judged against this whatever becomes of the site meanwhile (#108).
|
||||
let site = self.sites.get(id).ok_or_else(|| format!("ПУ №{id} уже нет на карте"))?;
|
||||
let snap = Target { pos: DVec2::new(site.pos.x, site.pos.z), stock: site.stock, offmap: site.offmap, alive: site.alive, cover: self.cover_of(site) };
|
||||
self.strikes.stock -= 1;
|
||||
self.strikes.fired += 1;
|
||||
self.strikes.next += 1;
|
||||
let ticks = (dist / TUNE.speed).ceil().max(20.0) as u64;
|
||||
let start = from + DVec3::Y * 1.5;
|
||||
self.strikes.flights.push(Flight { id: self.strikes.next, site: id, from: start, aim: est.pos, start: self.tick, arrive: self.tick + ticks });
|
||||
// Its own scatter at the aim, rolled once here: the flight and its outcome name one point.
|
||||
let (gx, gz) = (gauss(self.seed, self.strikes.next as u64, id as u64, 7), gauss(self.seed, self.strikes.next as u64, id as u64, 8));
|
||||
let land = est.pos + DVec2::new(gx, gz) * TUNE.cep;
|
||||
self.strikes.flights.push(Flight {
|
||||
id: self.strikes.next,
|
||||
site: id,
|
||||
from: start,
|
||||
pos: start,
|
||||
aim: est.pos,
|
||||
land,
|
||||
start: self.tick,
|
||||
arrive: self.tick + ticks,
|
||||
snap,
|
||||
hold: 0,
|
||||
});
|
||||
if let Some(k) = self.strikes.known.iter_mut().find(|k| k.site == id) {
|
||||
k.aimed = true;
|
||||
k.cover = Some(snap.cover);
|
||||
}
|
||||
out.sound(DroneKind::Kalibr.launch_sound(), start, 1.0, 1.0);
|
||||
out.particles("minecraft:large_smoke", start, 0.6, DVec3::ZERO, 0.05, 30);
|
||||
@@ -605,37 +723,34 @@ impl Sim {
|
||||
))
|
||||
}
|
||||
|
||||
/// A strike arrives.
|
||||
fn land_strike(&mut self, f: Flight, ground: &mut Ground, player: Option<DVec3>, out: &mut Out) {
|
||||
/// A strike arrives at `at` (the contact point: the ground under its landing point, or the face it met).
|
||||
fn land_strike(&mut self, f: Flight, at: DVec3, ground: &mut Ground, player: Option<DVec3>, out: &mut Out) {
|
||||
let now = self.tick;
|
||||
if let Some(k) = self.strikes.known.iter_mut().find(|k| k.site == f.site) {
|
||||
k.aimed = false;
|
||||
k.cover = Some(f.snap.cover);
|
||||
}
|
||||
let Some(site) = self.sites.get(f.site).cloned() else {
|
||||
out.messages.push(format!("Удар по ПУ №{}: площадка уже свёрнута, ракета ушла в пустоту", f.site));
|
||||
return;
|
||||
// The site as it stands now; if it has been taken off the map since the launch (a new wave's housekeeping,
|
||||
// a clear), the shot was still fired at that place: it has its outcome by its coordinates (#108).
|
||||
let (truth, offmap, alive, stock) = match self.sites.get(f.site) {
|
||||
Some(s) => (DVec2::new(s.pos.x, s.pos.z), s.offmap, s.alive, s.stock),
|
||||
None => (f.snap.pos, f.snap.offmap, f.snap.alive, f.snap.stock),
|
||||
};
|
||||
let cover = self.cover_of(&site);
|
||||
if let Some(k) = self.strikes.known.iter_mut().find(|k| k.site == f.site) {
|
||||
k.cover = Some(cover);
|
||||
}
|
||||
let spot = |x: f64, z: f64, ground: &mut Ground, fallback: f64| DVec3::new(x, ground.at(DVec3::new(x, 0.0, z), now).unwrap_or(fallback), z);
|
||||
let cover = f.snap.cover;
|
||||
// The enemy's cover.
|
||||
if dice(self.seed, f.id as u64, f.site as u64, 201) < TUNE.cover_p[cover as usize] {
|
||||
self.strikes.shot_down += 1;
|
||||
let at = spot(f.aim.x, f.aim.y, ground, site.pos.y) + DVec3::Y * 40.0;
|
||||
self.blast_at(at, 0, true, false, ground, player, out);
|
||||
self.log(at, record::EventKind::Strike { site: f.site, result: record::StrikeResult::Intercepted });
|
||||
let high = at + DVec3::Y * 40.0;
|
||||
self.blast_at(high, 0, true, false, ground, player, out);
|
||||
self.log(high, record::EventKind::Strike { site: f.site, result: record::StrikeResult::Intercepted });
|
||||
out.messages.push(format!("Удар по ПУ №{}: ракета сбита ПВО противника у площадки, цель цела", f.site));
|
||||
return;
|
||||
}
|
||||
// Where it lands: the aim and the missile's scatter; how far from the site decides.
|
||||
let (gx, gz) = (gauss(self.seed, f.id as u64, f.site as u64, 7), gauss(self.seed, f.id as u64, f.site as u64, 8));
|
||||
let land = DVec2::new(f.aim.x + gx * TUNE.cep, f.aim.y + gz * TUNE.cep);
|
||||
let miss = (land - DVec2::new(site.pos.x, site.pos.z)).length();
|
||||
let result = if site.offmap && miss <= TUNE.hit_r {
|
||||
// Where it lands was fixed at the launch; how far from the site decides.
|
||||
let miss = (f.land - truth).length();
|
||||
let result = if offmap && miss <= TUNE.hit_r {
|
||||
record::StrikeResult::Halted
|
||||
} else if !site.alive {
|
||||
} else if !alive {
|
||||
record::StrikeResult::Missed
|
||||
} else if miss <= TUNE.hit_r {
|
||||
record::StrikeResult::Destroyed
|
||||
@@ -645,25 +760,24 @@ impl Sim {
|
||||
record::StrikeResult::Missed
|
||||
};
|
||||
use record::StrikeResult as R;
|
||||
if site.offmap {
|
||||
if offmap {
|
||||
// Nothing stands there, nothing is seen: the launches stop or they do not.
|
||||
if result == R::Halted {
|
||||
let n = self.halt_site(f.site);
|
||||
self.strikes.destroyed += 1;
|
||||
self.strikes.cancelled.push((f.site, n));
|
||||
self.set_state(f.site, SiteState::Destroyed(now));
|
||||
self.log(site.pos, record::EventKind::Strike { site: f.site, result });
|
||||
self.log(at, record::EventKind::Strike { site: f.site, result });
|
||||
out.messages.push(format!("Удар по ПУ №{}: за пределами загруженной карты, результат не виден; пуски оттуда прекратились (отменено {n})", f.site));
|
||||
} else {
|
||||
self.strikes.missed += 1;
|
||||
self.log(at, record::EventKind::Strike { site: f.site, result: R::Missed });
|
||||
out.messages.push(format!("Удар по ПУ №{}: за пределами загруженной карты; пуски идут, ракета потеряна", f.site));
|
||||
}
|
||||
return;
|
||||
}
|
||||
let at = spot(land.x, land.y, ground, site.pos.y);
|
||||
match result {
|
||||
R::Destroyed => {
|
||||
let stock = site.stock;
|
||||
let n = self.destroy_site(f.site);
|
||||
self.strikes.destroyed += 1;
|
||||
self.strikes.cancelled.push((f.site, n));
|
||||
@@ -706,6 +820,22 @@ impl Sim {
|
||||
}
|
||||
}
|
||||
|
||||
/// A strike missile met the land or a building short of its aim: it goes off there, and the site is untouched
|
||||
/// because nothing was aimed at. One result for the statistics and the record, before any cover (#106).
|
||||
fn crash_strike(&mut self, f: Flight, at: DVec3, ground: &mut Ground, player: Option<DVec3>, out: &mut Out) {
|
||||
if let Some(k) = self.strikes.known.iter_mut().find(|k| k.site == f.site) {
|
||||
k.aimed = false;
|
||||
}
|
||||
self.strikes.missed += 1;
|
||||
self.blast_at(at, 4, false, false, ground, player, out);
|
||||
self.log(at, record::EventKind::Strike { site: f.site, result: record::StrikeResult::Blocked });
|
||||
out.messages.push(format!(
|
||||
"Удар по ПУ №{}: ракета разбилась о рельеф или строение в {:.0} м от цели, площадка цела",
|
||||
f.site,
|
||||
(at.x - f.snap.pos.x).hypot(at.z - f.snap.pos.y)
|
||||
));
|
||||
}
|
||||
|
||||
fn set_state(&mut self, site: u32, state: SiteState) {
|
||||
if let Some(k) = self.strikes.known.iter_mut().find(|k| k.site == site) {
|
||||
k.state = state;
|
||||
@@ -1126,4 +1256,244 @@ mod tests {
|
||||
assert!(sim.queue.is_empty() && sim.sites.pending(site.id) == 0);
|
||||
assert!(left_at_strike > 3);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- #106: the strike flies through the world
|
||||
|
||||
/// A wall across `at` (z), solid in the sections from the ground up, with `hole` (a band of block heights) left
|
||||
/// open by its exact shapes: the narrow phase is what decides.
|
||||
struct Wall {
|
||||
at: i32,
|
||||
hole: Option<(i32, i32)>,
|
||||
}
|
||||
impl Wall {
|
||||
fn in_wall(&self, y: i32, z: i32) -> bool {
|
||||
z == self.at && (64..200).contains(&y)
|
||||
}
|
||||
}
|
||||
impl world::WorldSource for Wall {
|
||||
fn solid(&self, _x: i32, y: i32, z: i32) -> Option<bool> {
|
||||
Some(y < 64 || self.in_wall(y, z))
|
||||
}
|
||||
fn boxes(&self, _x: i32, y: i32, z: i32) -> Vec<[f64; 6]> {
|
||||
let open = self.hole.is_some_and(|(lo, hi)| (lo..hi).contains(&y));
|
||||
if self.in_wall(y, z) && !open { vec![[0.0, 0.0, 0.0, 1.0, 1.0, 1.0]] } else { Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
/// The game's answers of the tick, as `step` would get them: the land heights and the sections.
|
||||
fn serve(ground: &mut Ground, src: &dyn world::WorldSource, now: u64) {
|
||||
let cols = ground.take_wanted().into_iter().map(|(x, z)| (x, z, 64)).collect();
|
||||
ground.answer(cols, now);
|
||||
let secs = ground.world.take_wanted(now);
|
||||
ground.world.serve(src, secs, now);
|
||||
}
|
||||
|
||||
/// Reads the sections along `a`..`b` ahead of the flight, as a real game has them loaded before the shot.
|
||||
fn warm(ground: &mut Ground, src: &dyn world::WorldSource, a: DVec3, b: DVec3) {
|
||||
for _ in 0..4 {
|
||||
ground.world.sweep(a, b, false, 0);
|
||||
let w = ground.world.take_wanted(0);
|
||||
ground.world.serve(src, w, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A site at `pos` with `stock` launches still ahead of it and the radars' fix on it: no drone has to fly first.
|
||||
fn fixed_site(sim: &mut Sim, pos: DVec3, stock: u32) -> u32 {
|
||||
let id = sim.sites.add(LaunchSite {
|
||||
id: 0,
|
||||
side: 0,
|
||||
sector: 0,
|
||||
bearing: 0.0,
|
||||
class: SiteClass::Ramp,
|
||||
pos,
|
||||
range: pos.z,
|
||||
water: false,
|
||||
stock,
|
||||
planned: stock,
|
||||
alive: true,
|
||||
next_free: 0,
|
||||
offmap: false,
|
||||
});
|
||||
sim.strikes.known.push(Known {
|
||||
site: id,
|
||||
class: SiteClass::Ramp,
|
||||
obs: Vec::new(),
|
||||
est: Some(Estimate { pos: DVec2::new(pos.x, pos.z), radius: 5.0, fix: true, bearing: 0.0, bearing_err: 0.01, origin: DVec2::ZERO }),
|
||||
launches: 1,
|
||||
last: 0,
|
||||
state: SiteState::Active,
|
||||
cover: None,
|
||||
aimed: false,
|
||||
});
|
||||
for i in 0..stock {
|
||||
let site = sim.sites.get(id).unwrap().clone();
|
||||
let d = sim.make_drone(DroneKind::Shahed, site.muzzle(i), -DVec3::Z, DVec3::new(0.0, 70.0, 0.0));
|
||||
sim.sites.job(d.id, id);
|
||||
// Well after the strike: the site keeps its stock and its launches.
|
||||
sim.queue.push((20_000 + u64::from(i), d));
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
fn strike_events(sim: &Sim) -> Vec<record::EventKind> {
|
||||
sim.rec.iter().chain(sim.replays.iter()).flat_map(|r| r.events.iter().map(|e| e.kind)).filter(|k| matches!(k, record::EventKind::Strike { .. })).collect()
|
||||
}
|
||||
|
||||
// #106: a wall between the shot and the site catches the missile: it goes off at the contact, the site is untouched
|
||||
// and keeps its launches, the stock is spent once and the result is counted once, before any cover roll.
|
||||
#[test]
|
||||
fn a_counter_strike_breaks_on_a_wall_between_it_and_its_site() {
|
||||
let mut sim = Sim::new(11);
|
||||
// Heavy cover would shoot a missile down half the time: a broken one is never intercepted.
|
||||
sim.strikes.cover_override = Some(2);
|
||||
let id = fixed_site(&mut sim, DVec3::new(0.0, 64.0, 300.0), 4);
|
||||
let (mut ground, mut out) = (Ground::default(), Out::default());
|
||||
let wall = Wall { at: 140, hole: None };
|
||||
warm(&mut ground, &wall, DVec3::new(0.0, 65.5, 0.0), DVec3::new(0.0, 105.0, 300.0));
|
||||
sim.order_strike(id, DVec3::new(0.0, 64.0, 0.0), &mut out).unwrap();
|
||||
out.messages.clear();
|
||||
let mut crossed = false;
|
||||
for _ in 0..300 {
|
||||
serve(&mut ground, &wall, sim.tick);
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
crossed |= sim.strikes.flights.iter().any(|f| f.pos.z > 144.0);
|
||||
if sim.strikes.flights.is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(!crossed, "the missile flew through the wall");
|
||||
assert!(sim.strikes.flights.is_empty(), "still flying");
|
||||
let site = sim.sites.get(id).expect("the site was taken away");
|
||||
assert!(site.alive && site.stock == 4, "the site was hit through the wall: {site:?}");
|
||||
assert_eq!(sim.sites.pending(id), 4, "its launches still stand");
|
||||
assert_eq!((sim.strikes.fired, sim.strikes.missed, sim.strikes.destroyed, sim.strikes.stunned, sim.strikes.shot_down), (1, 1, 0, 0, 0));
|
||||
// The blast is at the wall's face, not at the site 160 blocks on.
|
||||
let at = sim.blasts.first().expect("no blast").at;
|
||||
assert!((at.z - 140.0).abs() < 1.0 && at.x.abs() < 1.0, "burst at {at:?}, not at the wall");
|
||||
assert!(out.messages.iter().any(|m| m.contains("разбилась")), "{:?}", out.messages);
|
||||
// One result, recorded, with the flight it belongs to as a track of its own (#109).
|
||||
let events = strike_events(&sim);
|
||||
assert_eq!(events.len(), 1, "{events:?}");
|
||||
assert!(matches!(events[0], record::EventKind::Strike { result: record::StrikeResult::Blocked, .. }), "{:?}", events[0]);
|
||||
let rec = sim.rec.iter().chain(sim.replays.iter()).next().expect("the shot made no recording");
|
||||
let tr = rec.tracks.iter().find(|t| t.what == record::What::Strike).expect("no recorded flight");
|
||||
let end = tr.at(rec.origin, tr.last() as f64).expect("no last point");
|
||||
assert!(end.z < 145.0 && end.z > 100.0, "the recorded flight ends at {end:?}, not at the wall");
|
||||
assert!((end.z - at.z).abs() < 3.0, "the recorded flight and the blast disagree: {end:?} / {at:?}");
|
||||
}
|
||||
|
||||
// #106: the sections say "solid" over the whole wall, but its exact shape leaves an opening: the flight goes
|
||||
// through it by the narrow phase (and a slab in the way is flown over, not assumed clear).
|
||||
#[test]
|
||||
fn a_counter_strike_passes_an_opening_by_the_blocks_shape() {
|
||||
let mut sim = Sim::new(11);
|
||||
sim.strikes.cover_override = Some(0);
|
||||
// No launches: only the strike can make a recording here.
|
||||
let id = fixed_site(&mut sim, DVec3::new(0.0, 64.0, 300.0), 0);
|
||||
let (mut ground, mut out) = (Ground::default(), Out::default());
|
||||
// A slit between 100 and 110 blocks high, where the missile flies at about 104.
|
||||
let wall = Wall { at: 140, hole: Some((100, 110)) };
|
||||
warm(&mut ground, &wall, DVec3::new(0.0, 65.5, 0.0), DVec3::new(0.0, 105.0, 300.0));
|
||||
sim.order_strike(id, DVec3::new(0.0, 64.0, 0.0), &mut out).unwrap();
|
||||
let mut crossed = false;
|
||||
for _ in 0..400 {
|
||||
serve(&mut ground, &wall, sim.tick);
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
crossed |= sim.strikes.flights.iter().any(|f| f.pos.z > 144.0);
|
||||
if sim.strikes.flights.is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(crossed, "the missile was stopped by a wall with a slit: {:?}", out.messages);
|
||||
assert_eq!(sim.strikes.missed, 0, "it broke on the slit: {:?}", out.messages);
|
||||
// It went on to its point: the site is hit (or narrowly missed), and never "blocked".
|
||||
let events = strike_events(&sim);
|
||||
assert_eq!(events.len(), 1, "{events:?}");
|
||||
assert!(!matches!(events[0], record::EventKind::Strike { result: record::StrikeResult::Blocked, .. }), "{:?}", events[0]);
|
||||
assert_eq!(sim.strikes.fired, 1);
|
||||
}
|
||||
|
||||
// #106: an open way works as before: the missile reaches its point, the site dies, one result, one stock spent.
|
||||
#[test]
|
||||
fn a_counter_strike_on_an_open_way_still_reaches_its_site() {
|
||||
let mut sim = Sim::new(11);
|
||||
sim.strikes.cover_override = Some(0);
|
||||
let id = fixed_site(&mut sim, DVec3::new(0.0, 64.0, 300.0), 2);
|
||||
let (mut ground, mut out) = (Ground::default(), Out::default());
|
||||
let open = Wall { at: 10_000, hole: None };
|
||||
sim.order_strike(id, DVec3::new(0.0, 64.0, 0.0), &mut out).unwrap();
|
||||
for _ in 0..400 {
|
||||
serve(&mut ground, &open, sim.tick);
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
if sim.strikes.flights.is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(sim.strikes.flights.is_empty());
|
||||
assert_eq!((sim.strikes.fired, sim.strikes.missed), (1, 0), "{:?}", out.messages);
|
||||
assert_eq!(sim.strikes.destroyed, 1, "{:?}", out.messages);
|
||||
assert!(!sim.sites.get(id).unwrap().alive);
|
||||
}
|
||||
|
||||
// #108: a missile already in the air is not lost when its site is taken off the map: it keeps its outcome by
|
||||
// the coordinates it was fired at, and the stock and the result are accounted once.
|
||||
#[test]
|
||||
fn a_strike_whose_site_is_taken_off_the_map_still_has_its_result() {
|
||||
let mut sim = Sim::new(11);
|
||||
sim.strikes.cover_override = Some(0);
|
||||
let id = fixed_site(&mut sim, DVec3::new(0.0, 64.0, 300.0), 0);
|
||||
let (mut ground, mut out) = (Ground::default(), Out::default());
|
||||
sim.order_strike(id, DVec3::new(0.0, 64.0, 0.0), &mut out).unwrap();
|
||||
// The world unloads (or the sky is cleared): no site to find on arrival.
|
||||
sim.clear();
|
||||
assert!(sim.sites.get(id).is_none());
|
||||
out.messages.clear();
|
||||
for _ in 0..400 {
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
if sim.strikes.flights.is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(sim.strikes.flights.is_empty(), "the missile vanished with the site");
|
||||
assert!(!out.messages.iter().any(|m| m.contains("свёрнута") || m.contains("пустоту")), "{:?}", out.messages);
|
||||
assert_eq!(sim.strikes.fired, 1);
|
||||
assert_eq!(sim.strikes.destroyed + sim.strikes.stunned + sim.strikes.missed, 1, "{:?}", out.messages);
|
||||
assert_eq!(sim.strikes.shot_down, 0);
|
||||
assert_eq!(strike_events(&sim).len(), 1, "the result was not recorded");
|
||||
}
|
||||
|
||||
// #109: after the last enemy is gone, a strike still flying five seconds later keeps its recording open;
|
||||
// its track and outcome survive, and the recording closes only after the usual quiet tail.
|
||||
#[test]
|
||||
fn a_late_counter_strike_keeps_the_recording_until_it_lands() {
|
||||
let mut sim = Sim::new(11);
|
||||
sim.strikes.cover_override = Some(0);
|
||||
let id = fixed_site(&mut sim, DVec3::new(0.0, 64.0, 1000.0), 0);
|
||||
let (mut ground, mut out) = (Ground::default(), Out::default());
|
||||
let open = Wall { at: 10_000, hole: None };
|
||||
sim.order_strike(id, DVec3::new(0.0, 64.0, 0.0), &mut out).unwrap();
|
||||
let drone = sim.make_drone(DroneKind::Shahed, DVec3::new(0.0, 65.0, 0.0), -DVec3::Z, DVec3::new(0.0, 64.0, 1000.0));
|
||||
sim.drones.push(drone);
|
||||
serve(&mut ground, &open, sim.tick);
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
assert!(sim.rec.is_some());
|
||||
sim.drones.clear();
|
||||
for _ in 0..100 {
|
||||
serve(&mut ground, &open, sim.tick);
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
}
|
||||
assert!(!sim.strikes.flights.is_empty(), "the strike landed too early for this scenario");
|
||||
assert!(sim.rec.is_some(), "the recording closed five seconds after the last drone");
|
||||
for _ in 0..400 {
|
||||
serve(&mut ground, &open, sim.tick);
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
if sim.rec.is_none() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(sim.rec.is_none(), "the recording never closed after the strike and its quiet tail");
|
||||
let rec = sim.replays.last().expect("the late strike was not kept");
|
||||
assert!(rec.tracks.iter().any(|t| t.what == record::What::Strike));
|
||||
assert!(rec.events.iter().any(|e| matches!(e.kind, record::EventKind::Strike { .. })));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ impl Ground {
|
||||
if self.due(when) && self.wanted.len() < ASK_MAX / 2 && self.asked.insert(key) {
|
||||
self.wanted.push(key);
|
||||
}
|
||||
if y > -64 { Rise::At(f64::from(y)) } else { Rise::Void }
|
||||
land_height(y).map_or(Rise::Void, Rise::At)
|
||||
}
|
||||
None => {
|
||||
if self.wanted.len() < ASK_MAX && self.asked.insert(key) {
|
||||
@@ -76,7 +76,7 @@ impl Ground {
|
||||
if self.due(when) && self.wanted.len() < cap / 2 && self.asked.insert((x, z)) {
|
||||
self.wanted.push((x, z));
|
||||
}
|
||||
Some((y > -64).then_some(f64::from(y)))
|
||||
Some(land_height(y))
|
||||
}
|
||||
None => {
|
||||
// A chunk the game is loading is asked about again in a few ticks, not every one.
|
||||
|
||||
@@ -640,7 +640,7 @@ mod tests {
|
||||
.drones
|
||||
.iter()
|
||||
.filter(|d| d.alive())
|
||||
.map(|d| Track { id: d.id, pos: d.pos, vel: d.vel, tick: now, own_tick: now, ttl: 400, hits: 3, locked: false })
|
||||
.map(|d| Track { id: d.id, kind: d.kind, pos: d.pos, vel: d.vel, tick: now, own_tick: now, ttl: 400, hits: 3, locked: false })
|
||||
.collect();
|
||||
for r in sim.sams.iter_mut().filter(|s| s.kind == SamKind::Radar) {
|
||||
for t in &tracks {
|
||||
|
||||
@@ -94,6 +94,13 @@ pub struct WorldStats {
|
||||
/// Sections dropped or re-read for a chunk's unload or replacement, or for age (#62).
|
||||
pub aged: u64,
|
||||
pub columns_changed: u64,
|
||||
/// Blasts asked in the blocks, and what became of them (`Settled`).
|
||||
pub blasts_asked: u64,
|
||||
pub blasts_confirmed: u64,
|
||||
pub blasts_unchanged: u64,
|
||||
pub blasts_unloaded: u64,
|
||||
/// Answers dropped for being to a question of another world or dimension.
|
||||
pub late_dropped: u64,
|
||||
}
|
||||
|
||||
/// What the game's exact ray said of a flight's step, once it answered (#63).
|
||||
@@ -182,9 +189,37 @@ pub struct WorldCache {
|
||||
/// Columns (section x, z) where blocks changed since the land heights last looked (#64); `all`: too many to say.
|
||||
pub(super) changed_cols: HashSet<(i32, i32)>,
|
||||
pub(super) changed_all: bool,
|
||||
/// Another world or dimension opened since the land heights last looked: they are all void.
|
||||
pub(super) epoch_reset: bool,
|
||||
/// Blasts the mod asked the game to make in the blocks (`Out.commands`), waiting for the game's word that
|
||||
/// blocks changed there. The game's damage (the simulation's own) and the geometry the game confirms
|
||||
/// are two things: this is the second (#90). Singleplayer: the client's world is the authority.
|
||||
expected: Vec<Expected>,
|
||||
pub stats: WorldStats,
|
||||
}
|
||||
|
||||
/// A blast asked for: the sections it reaches (lowest, highest) and the tick it was asked.
|
||||
struct Expected {
|
||||
lo: Sec,
|
||||
hi: Sec,
|
||||
at: DVec3,
|
||||
since: u64,
|
||||
}
|
||||
|
||||
/// Ticks the game has to report a block changed after a blast was asked for (the fuse is 0; commands run 64 a tick).
|
||||
pub const CONFIRM_TICKS: u64 = 100;
|
||||
|
||||
/// What became of a blast asked for in the blocks.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Settled {
|
||||
/// The game reported blocks changed in the sections it reaches.
|
||||
Confirmed,
|
||||
/// The chunk was there and nothing changed: nothing to break, a rule or the server's rights said no.
|
||||
Unchanged,
|
||||
/// There was no chunk to change.
|
||||
Unloaded,
|
||||
}
|
||||
|
||||
fn sec_of(x: i32, y: i32, z: i32) -> Sec {
|
||||
(x >> 4, y >> 4, z >> 4)
|
||||
}
|
||||
@@ -207,7 +242,7 @@ impl WorldCache {
|
||||
pub fn text(&self) -> String {
|
||||
let s = &self.stats;
|
||||
format!(
|
||||
"мир: {} секций ({} КБ), запросов {}, неизвестно {}, лучей {} (ударов {}, неизв. {}), клеток {}",
|
||||
"мир: {} секций ({} КБ), запросов {}, неизвестно {}, лучей {} (ударов {}, неизв. {}), клеток {}; взрывы в блоках: {} (подтверждено {}, без перемен {}, нет чанка {}), чужих ответов {}",
|
||||
self.len(),
|
||||
self.bytes() / 1024,
|
||||
s.sections_asked,
|
||||
@@ -215,7 +250,12 @@ impl WorldCache {
|
||||
s.sweeps,
|
||||
s.hits,
|
||||
s.unknown_sweeps,
|
||||
s.cells
|
||||
s.cells,
|
||||
s.blasts_asked,
|
||||
s.blasts_confirmed,
|
||||
s.blasts_unchanged,
|
||||
s.blasts_unloaded,
|
||||
s.late_dropped
|
||||
)
|
||||
}
|
||||
|
||||
@@ -241,6 +281,8 @@ impl WorldCache {
|
||||
if epoch != self.epoch {
|
||||
self.rays = RayDesk { next: self.rays.next, ..RayDesk::default() };
|
||||
if self.epoch != 0 {
|
||||
self.epoch_reset = true;
|
||||
self.expected.clear();
|
||||
self.secs.clear();
|
||||
self.urgent.clear();
|
||||
self.ahead.clear();
|
||||
@@ -264,6 +306,11 @@ impl WorldCache {
|
||||
let set: HashSet<Sec> = sections.iter().copied().collect();
|
||||
self.drop_rays(|b| set.contains(&sec_of(b[0], b[1], b[2])));
|
||||
}
|
||||
if !self.expected.is_empty() {
|
||||
let before = self.expected.len();
|
||||
self.expected.retain(|e| !sections.iter().any(|s| (e.lo.0..=e.hi.0).contains(&s.0) && (e.lo.1..=e.hi.1).contains(&s.1) && (e.lo.2..=e.hi.2).contains(&s.2)));
|
||||
self.stats.blasts_confirmed += (before - self.expected.len()) as u64;
|
||||
}
|
||||
for s in sections {
|
||||
self.note_column(s.0, s.2);
|
||||
if let Some(e) = self.secs.get_mut(s) {
|
||||
@@ -274,6 +321,37 @@ impl WorldCache {
|
||||
self.stats.world_changes += sections.len() as u64;
|
||||
}
|
||||
|
||||
/// The game's epoch as last told: another world or dimension opening changes it.
|
||||
pub fn epoch(&self) -> u32 {
|
||||
self.epoch
|
||||
}
|
||||
|
||||
/// A blast of `radius` blocks was asked of the game at `at`: expect the game to report blocks changed there.
|
||||
pub fn expect_blast(&mut self, at: DVec3, radius: f64, now: u64) {
|
||||
let (lo, hi) = (at - DVec3::splat(radius), at + DVec3::splat(radius));
|
||||
let sec = |p: DVec3| sec_of(p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32);
|
||||
if self.expected.len() < 256 {
|
||||
self.expected.push(Expected { lo: sec(lo), hi: sec(hi), at, since: now });
|
||||
}
|
||||
self.stats.blasts_asked += 1;
|
||||
}
|
||||
|
||||
/// The blasts that the game did not report in `CONFIRM_TICKS`, taken: where each was.
|
||||
pub fn overdue_blasts(&mut self, now: u64) -> Vec<DVec3> {
|
||||
let (late, keep): (Vec<_>, Vec<_>) = std::mem::take(&mut self.expected).into_iter().partition(|e| now.saturating_sub(e.since) >= CONFIRM_TICKS);
|
||||
self.expected = keep;
|
||||
late.into_iter().map(|e| e.at).collect()
|
||||
}
|
||||
|
||||
/// What became of a blast that was not reported.
|
||||
pub fn note_settled(&mut self, how: Settled) {
|
||||
match how {
|
||||
Settled::Confirmed => self.stats.blasts_confirmed += 1,
|
||||
Settled::Unchanged => self.stats.blasts_unchanged += 1,
|
||||
Settled::Unloaded => self.stats.blasts_unloaded += 1,
|
||||
}
|
||||
}
|
||||
|
||||
fn note_column(&mut self, sx: i32, sz: i32) {
|
||||
if self.changed_cols.len() >= 4096 {
|
||||
self.changed_all = true;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! derives everything from a segment's age, so the columns and blasts are a pure function of the
|
||||
//! tick (nothing grows twice when a frame is shown again); trails are the only state, and they are
|
||||
//! cut back when the tick goes backwards.
|
||||
use crate::sim::{Class, Sim};
|
||||
use crate::sim::{Class, DroneKind, Sim};
|
||||
use glam::DVec3;
|
||||
use horizon_mod_sdk::render::SmokeSegment;
|
||||
use std::collections::HashMap;
|
||||
@@ -162,6 +162,8 @@ pub fn replay_smoke(rec: &crate::sim::record::Recording, t: f64) -> Vec<SmokeSeg
|
||||
Some(drone_look(spec.class, spec.trail_scale()))
|
||||
}
|
||||
What::Missile(kind, _) => missile_look(kind),
|
||||
// A counter-strike leaves the trail of the cruise missile it is (#109).
|
||||
What::Strike => Some(drone_look(Class::Cruise, DroneKind::Kalibr.spec().trail_scale())),
|
||||
};
|
||||
let Some(look) = look else { continue };
|
||||
let life = look.life as f64;
|
||||
|
||||
+8
-4
@@ -27,9 +27,12 @@ GPL-файлы три: `acoustics/spr_occlusion.rs`, (стадия 2) `acoustics
|
||||
- Дальность 512 блоков (SPR: ~64), счёт клеток, не времени: 40 тыс. клеток на тик встроенно (новый звук, 1 путь, чтобы взрыв
|
||||
не начинался «ярким»), 400 тыс. на задание рабочего потока (9 путей, одно задание за раз); при съёмке всё встроенно, 600 тыс.
|
||||
клеток на тик. Порядок: по громкости, затем по id; сумма голосов в `mix` теперь тоже по id (раньше порядок HashMap делал дорожку
|
||||
недетерминированной при нескольких голосах).
|
||||
недетерминированной при нескольких голосах). При выходе за дальность/порог слышимости или потере геометрии микшеру явно
|
||||
возвращают обычные `gain=1` и воздушный `cutoff` без старой стены; посылки и эхо отзываются, при возвращении считаются заново.
|
||||
- Кеш по ячейкам 2x2x2 источника и слушателя, 4096 записей; сброс по секциям `World.sound_changes` (как `mod_changes`),
|
||||
по эпохе мира и при переполнении; результат задания, начатого до изменения в его коробке, отбрасывается.
|
||||
по эпохе мира и при переполнении; результат задания, начатого до изменения в его коробке, отбрасывается. Вставка, замена
|
||||
и выгрузка чанка меняют residency-счётчик и инвалидируют затронутые секции и старые worker-задания. Трасса, встретившая
|
||||
Unknown, пересчитывается не позднее чем через 40 тиков, поэтому приехавшая геометрия применяется без движения слушателя.
|
||||
- Воздух: `0.994^расстояние` на верха (EFX по умолчанию, не проверено по OpenAL Soft) — иначе при `acoustics=on` пропадала бы
|
||||
дальность, которую раньше давали `_far`-сэмплы.
|
||||
- Мод: API 21, `render.acoustics()`; при включённой акустике мод играет ближние варианты до 480 блоков (`ACOUSTIC_FAR`), дальше
|
||||
@@ -64,8 +67,9 @@ GPL-файлы три: `acoustics/spr_occlusion.rs`, (стадия 2) `acoustics
|
||||
- Срез близких отражений: отвод ближе 30 мс к прямому звуку отбрасывается, до 50 мс плавно входит (иначе стена рядом с
|
||||
игроком даёт гребёнку, а не эхо). Из найденных плоскостей берутся до 6 сильнейших не ближе 40 мс друг к другу.
|
||||
- Кому: `deserves_echo` в `audio.rs`: не петля, не относительный, громкость >= 0.5, дальность (linear) >= 96, длина 0.1-12 с,
|
||||
прошло меньше 70% звука; не более `ECHO_VOICES = 8` одновременно (самые громкие). Сотня двигателей эха не получает
|
||||
(петли), сотня выстрелов: восемь самых громких.
|
||||
прошло меньше 70% звука; не более `ECHO_VOICES = 8` активных наборов (самые громкие). При смене приоритетов старый набор
|
||||
отзывается и затухает ~50 мс, поэтому во время ротации кратковременно звучат до 16, затем снова 8. Сотня двигателей эха
|
||||
не получает (петли), сотня выстрелов: восемь самых громких.
|
||||
- Планирование: счёт по клеткам, не по времени. Живьём трассировка идёт на том же рабочем потоке (в задании до 4 трасс и
|
||||
240 тыс. клеток), кеш по блочным ячейкам источника и слушателя (центры ячеек, 256 записей), сброс по секциям, которых
|
||||
касаются точки опоры отводов, и по эпохе; в съёмке трасса синхронная, 480 тыс. клеток на тик. Микшер получает отводы
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 3de7a6875140a107e28563cc44489b55f5794517 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Wed, 28 Oct 2026 12:37:45 +0300
|
||||
Subject: [PATCH 01/41] Mod API (AirDef fork): world models, client particles,
|
||||
Subject: [PATCH 01/42] Mod API (AirDef fork): world models, client particles,
|
||||
sounds, ground heights
|
||||
|
||||
render.set-models draws block models with an interpolated pose per id;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From a6d64e6415bf618539af464e521091e72b72d72f Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Wed, 28 Oct 2026 12:39:45 +0300
|
||||
Subject: [PATCH 02/41] cargo-horizon-mod: report particles and sounds
|
||||
Subject: [PATCH 02/42] cargo-horizon-mod: report particles and sounds
|
||||
|
||||
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From ee79b3562feebe51959a01f1585a9e85bd53ccb5 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Wed, 28 Oct 2026 13:33:10 +0300
|
||||
Subject: [PATCH 03/41] Mod API (AirDef fork): full-screen post pass for mods
|
||||
Subject: [PATCH 03/42] Mod API (AirDef fork): full-screen post pass for mods
|
||||
|
||||
render.set-post compiles a mod's WGSL after a prelude (camera matrices,
|
||||
time, 256 vec4 of params, the world's colour and depth) and runs it after
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 2b137dbbedd540daeebc7f5e387847aeb56a1355 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Wed, 28 Oct 2026 22:09:30 +0300
|
||||
Subject: [PATCH 04/41] Mod models: draw far models as scaled impostors past
|
||||
Subject: [PATCH 04/42] Mod models: draw far models as scaled impostors past
|
||||
the far plane, cull at 4096
|
||||
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From c8ebca6e0af68630e65211844b34d25c5b985c03 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Wed, 28 Oct 2026 22:31:00 +0300
|
||||
Subject: [PATCH 05/41] Mod cameras: render.set-views draws the world from
|
||||
Subject: [PATCH 05/42] Mod cameras: render.set-views draws the world from
|
||||
other points into pictures that HUD view shapes show (API level 9)
|
||||
|
||||
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 8d2261fc4f8072c32e454139cfea7a8c0cd9d664 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Wed, 28 Oct 2026 23:08:21 +0300
|
||||
Subject: [PATCH 06/41] Mods: more fuel per tick and per event (AirDef plans
|
||||
Subject: [PATCH 06/42] Mods: more fuel per tick and per event (AirDef plans
|
||||
raids)
|
||||
|
||||
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 6c548de34def8e4a624d734243418090798bd16a Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Wed, 28 Oct 2026 23:25:29 +0300
|
||||
Subject: [PATCH 07/41] Mod cameras up to 1920x1080 (full-screen replays)
|
||||
Subject: [PATCH 07/42] Mod cameras up to 1920x1080 (full-screen replays)
|
||||
|
||||
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||||
---
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 9b9e93269d67401cc620567a884d5ce97f68d76e Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Thu, 29 Oct 2026 11:15:11 +0300
|
||||
Subject: [PATCH 08/41] Mod cameras: distant terrain tiles, fog measured from
|
||||
Subject: [PATCH 08/42] Mod cameras: distant terrain tiles, fog measured from
|
||||
the camera, no impostors while one is shown
|
||||
|
||||
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 065d9fa02966238a5bd9ff460392a1a809db0b11 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Thu, 29 Oct 2026 11:25:45 +0300
|
||||
Subject: [PATCH 09/41] Mods: game.world-id, so mods keep state per world (API
|
||||
Subject: [PATCH 09/42] Mods: game.world-id, so mods keep state per world (API
|
||||
level 9)
|
||||
|
||||
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 1bf28135fd9a31f837323dc3a8d81ed73343d816 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Thu, 29 Oct 2026 12:01:08 +0300
|
||||
Subject: [PATCH 10/41] cargo-horizon-mod: trial runs behind feature full, so a
|
||||
Subject: [PATCH 10/42] cargo-horizon-mod: trial runs behind feature full, so a
|
||||
packing-only tool skips wasmtime
|
||||
|
||||
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 0a56f5616df4699588cbcc529d4720661baa810f Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Thu, 29 Oct 2026 13:18:43 +0300
|
||||
Subject: [PATCH 11/41] HD lighting: G-buffer pass, per-pixel mod point lights
|
||||
Subject: [PATCH 11/42] HD lighting: G-buffer pass, per-pixel mod point lights
|
||||
in HDR, bloom and tone curve; render.set-lights and render.set-lighting (API
|
||||
level 10)
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 9ebf0031fe9ba6b7f02afb26e4fd3a1ba4ddb0d0 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Thu, 29 Oct 2026 13:59:43 +0300
|
||||
Subject: [PATCH 12/41] HD lighting stage 2: sun and moon shadow cascades, the
|
||||
Subject: [PATCH 12/42] HD lighting stage 2: sun and moon shadow cascades, the
|
||||
world relit (sun by face angle and shadow, sky and block light through the
|
||||
lightmap), light shafts and halos, fog over it again, a light colour grade
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 7a5a38f68923aec62f10bfa0df50b436474ed612 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Thu, 29 Oct 2026 16:19:53 +0300
|
||||
Subject: [PATCH 13/41] HD: bind groups cached until a resize or a new source,
|
||||
Subject: [PATCH 13/42] HD: bind groups cached until a resize or a new source,
|
||||
shadow passes draw only the entities that cast shadows
|
||||
|
||||
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 8020811e57d4b5a9ea1cd72d30ce859dc5095d35 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Thu, 29 Oct 2026 16:25:44 +0300
|
||||
Subject: [PATCH 14/41] HD: lights culled per 16x16 tile (surface and halo
|
||||
Subject: [PATCH 14/42] HD: lights culled per 16x16 tile (surface and halo
|
||||
lists built on the CPU), a naga test for the lighting shaders
|
||||
|
||||
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 72d3fddfea329e578162656151350f0aa2efd323 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Thu, 29 Oct 2026 16:43:36 +0300
|
||||
Subject: [PATCH 15/41] HD: GPU time per pass in the F3 timing list,
|
||||
Subject: [PATCH 15/42] HD: GPU time per pass in the F3 timing list,
|
||||
half-resolution GTAO with a depth-aware blur
|
||||
|
||||
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 1fd83a821bf270879d8ece5aa583f200ed920d89 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Thu, 29 Oct 2026 17:02:02 +0300
|
||||
Subject: [PATCH 16/41] HD: shadows draw only sun-facing quads and skip buried
|
||||
Subject: [PATCH 16/42] HD: shadows draw only sun-facing quads and skip buried
|
||||
sections, the far cascade every second frame; TAA (Halton jitter,
|
||||
reprojection by depth, YCoCg variance clipping) before bloom
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 1502d359d599228fe0f44ce6b99a3fded2ac5ea0 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Thu, 29 Oct 2026 17:02:02 +0300
|
||||
Subject: [PATCH 17/41] Mods: model handles (render.model-id, model-generation,
|
||||
Subject: [PATCH 17/42] Mods: model handles (render.model-id, model-generation,
|
||||
set-models-by-id; API level 11) so mods send no model names each tick;
|
||||
clear-post and set-lighting documented
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 0f9d99b8ad3e4b72e621d84c2396cf1d3d2b7a33 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Thu, 29 Oct 2026 17:19:57 +0300
|
||||
Subject: [PATCH 18/41] HD: temporal upscaling (HORIZON_HD_SCALE: world,
|
||||
Subject: [PATCH 18/42] HD: temporal upscaling (HORIZON_HD_SCALE: world,
|
||||
G-buffer and lighting at a lower size, rebuilt to the window in the TAA
|
||||
pass); fix flickering shadows near the player (the near cascade lost its
|
||||
sections on frames the far one was held, the held far matrix ignored the
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 38250c4392e27d5700842ca6ee47291dd1831b72 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Thu, 29 Oct 2026 17:47:52 +0300
|
||||
Subject: [PATCH 19/41] HD water: its own pass (colour, normal, depth), the
|
||||
Subject: [PATCH 19/42] HD water: its own pass (colour, normal, depth), the
|
||||
floor under it lit, a composite with world-space waves, refraction with depth
|
||||
absorption in the biome colour, screen-space reflections, Fresnel and a
|
||||
shadowed sun glint (HORIZON_HD_WATER=0 to switch off)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From dbc6f8a6e9c2eeabe1de15f1794013c90be7faa5 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Thu, 29 Oct 2026 17:56:04 +0300
|
||||
Subject: [PATCH 20/41] HD water: no vanilla texture on the surface (the biome
|
||||
Subject: [PATCH 20/42] HD water: no vanilla texture on the surface (the biome
|
||||
colour only), a darker, deeper colour
|
||||
|
||||
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 13e74537dd6e63482e3613e0e416de1158944dfe Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Thu, 29 Oct 2026 18:38:19 +0300
|
||||
Subject: [PATCH 21/41] HD sky and light: a physical atmosphere (Rayleigh, Mie,
|
||||
Subject: [PATCH 21/42] HD sky and light: a physical atmosphere (Rayleigh, Mie,
|
||||
ozone; constants and transmittance after Photon, MIT) for the sky, haze, fog
|
||||
and water reflections; warmer sunlight from the atmosphere's transmittance, a
|
||||
gentle sky-coloured ambient, soft PCSS-lite shadows near the player, a haze
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 6277e051a89c2537570982f6ef275887193c05cf Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Thu, 29 Oct 2026 19:02:16 +0300
|
||||
Subject: [PATCH 22/41] HD water: a darker blue, a little clearer, ripples a
|
||||
Subject: [PATCH 22/42] HD water: a darker blue, a little clearer, ripples a
|
||||
little higher
|
||||
|
||||
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 982265d21bb9d74ec0040db03feb5a55762286ad Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Thu, 29 Oct 2026 21:41:48 +0300
|
||||
Subject: [PATCH 23/41] HD: Photon-style sunsets (Rec. 2020 atmosphere, sun
|
||||
Subject: [PATCH 23/42] HD: Photon-style sunsets (Rec. 2020 atmosphere, sun
|
||||
tint, blue hour; MIT), volumetric clouds with ground shadows instead of
|
||||
vanilla's in HD, volumetric fog with sun shafts and morning mist
|
||||
(HORIZON_HD_CLOUDS=0, HORIZON_HD_VOLFOG=0)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 24971b3c67d8c87673eb2e0d204cedf8a2f46d1c Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Thu, 29 Oct 2026 21:43:22 +0300
|
||||
Subject: [PATCH 24/41] Mods: world queries for simulations (render.query-rays,
|
||||
Subject: [PATCH 24/42] Mods: world queries for simulations (render.query-rays,
|
||||
query-sections, world-changes; API level 12): block-exact rays and section
|
||||
occupancy by collision, sight or sound, answered next tick within budgets,
|
||||
and a log of changed sections
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From fdec4960983bdff82f3793460f9a5234f0cd3f49 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Thu, 29 Oct 2026 22:56:15 +0300
|
||||
Subject: [PATCH 25/41] HD fixes: rain level from the world not from rain
|
||||
Subject: [PATCH 25/42] HD fixes: rain level from the world not from rain
|
||||
geometry (#41), TAA history on the jittered grid (#38), vanilla cloud tint
|
||||
without a depth heuristic (#35), air fog once over water (#37), translucent
|
||||
things in front of HD water (#36), cheaper sunrise fan (#39), halos in thick
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 21391afb26f49505d6cdaf454a6355cd4e747503 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Thu, 29 Oct 2026 23:19:53 +0300
|
||||
Subject: [PATCH 26/41] HD split into modules (gfx/hd/: one Rust file and one
|
||||
Subject: [PATCH 26/42] HD split into modules (gfx/hd/: one Rust file and one
|
||||
WGSL file per pass, a shared prelude), contracts for colour, depth, alpha,
|
||||
time and coordinates written down, tests that the frame layout and bindings
|
||||
match between Rust and WGSL (#45)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 8d4cadbf8534309ac847d34e229f6d764770475d Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Thu, 29 Oct 2026 23:22:19 +0300
|
||||
Subject: [PATCH 27/41] HD clouds: noise scales that divide the camera's
|
||||
Subject: [PATCH 27/42] HD clouds: noise scales that divide the camera's
|
||||
65536-block wrap, so the clouds and their shadows no longer jump at x or z =
|
||||
0
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 0fb59c782abf269fe555faa3241b31acf41e26d7 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Fri, 30 Oct 2026 03:17:11 +0300
|
||||
Subject: [PATCH 28/41] HD: volumetric smoke and missile trails with clear
|
||||
Subject: [PATCH 28/42] HD: volumetric smoke and missile trails with clear
|
||||
tunnels through fog and cloud (render.set-smoke, API level 14; #54); sun
|
||||
speculars by material, wet surfaces and puddles in rain, wind in foliage
|
||||
(HORIZON_HD_SPECULAR=0, HORIZON_HD_WIND=0, HORIZON_HD_SMOKE=0); HD shaders
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From e4bc29da45d0d38244c6eb2ba3ffb9ab853540c0 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Fri, 30 Oct 2026 03:26:09 +0300
|
||||
Subject: [PATCH 29/41] HD clouds composited by depth so terrain and vehicles
|
||||
Subject: [PATCH 29/42] HD clouds composited by depth so terrain and vehicles
|
||||
inside or behind the layer are hidden and those in front stay in front (#67);
|
||||
world-anchored noise everywhere (cloud detail by height above the layer, fog,
|
||||
smoke and puddle scales dividing the wrap) (#68); the replay's time is visual
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 20f699796afb12b600236a4e8859cd97430f86f0 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Fri, 30 Oct 2026 03:44:45 +0300
|
||||
Subject: [PATCH 30/41] HD smoke: young trails drawn at least as wide as a grid
|
||||
Subject: [PATCH 30/42] HD smoke: young trails drawn at least as wide as a grid
|
||||
cell (density scaled to keep the mass), gentler bulges, so a trail is a
|
||||
smooth ribbon and not a chain of puffs
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 35ffbaa26dd91855c8b93446646ba8c58448d3d0 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Fri, 30 Oct 2026 03:59:41 +0300
|
||||
Subject: [PATCH 31/41] Mods: render.set-main-view (API level 15) renders the
|
||||
Subject: [PATCH 31/42] Mods: render.set-main-view (API level 15) renders the
|
||||
screen's world from a mod camera with the full pipeline, so replays get HD
|
||||
and the post effects; small mod views get the post pass with their own camera
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 27e24527550942695164dd3a769a42a659e797ca Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Fri, 30 Oct 2026 09:28:05 +0300
|
||||
Subject: [PATCH 32/41] Spot lights for mods (render.set-spot-lights, API level
|
||||
Subject: [PATCH 32/42] Spot lights for mods (render.set-spot-lights, API level
|
||||
16): surfaces lit in the cone, a volumetric beam stopped by depth (#60); film
|
||||
capture (render.capture-*, set-film-quality, API level 17): fixed-step clock,
|
||||
frames piped to ffmpeg or PNGs, offline audio, no chat in the frames (#58);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 615f5c3fa7c19a9895f8972a88333c6f250ad78a Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Fri, 30 Oct 2026 14:30:39 +0300
|
||||
Subject: [PATCH 33/41] HD clouds and fog polish: cloud panorama, cirrus,
|
||||
Subject: [PATCH 33/42] HD clouds and fog polish: cloud panorama, cirrus,
|
||||
terrain-aware fog, far smoke cascade; replay world log and film clock;
|
||||
material overlays by sprite name
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 0254984fdcce53a4a0f2bff15f9be3b78c93842e Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Fri, 30 Oct 2026 15:01:09 +0300
|
||||
Subject: [PATCH 34/41] HD: coloured sun through glass and leaves, rain ripples
|
||||
Subject: [PATCH 34/42] HD: coloured sun through glass and leaves, rain ripples
|
||||
on water, film motion blur and depth of field
|
||||
|
||||
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 9645d3f1f47d8bb358d5630288bdd801bd874911 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Fri, 30 Oct 2026 15:19:32 +0300
|
||||
Subject: [PATCH 35/41] Film export: every frame in flight reaches the writer,
|
||||
Subject: [PATCH 35/42] Film export: every frame in flight reaches the writer,
|
||||
listener follows the main view, cloud wind on film frames, set-smoke reports
|
||||
real activity
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 22d6835507d5627b0fe4a749b082b025b35e0262 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Fri, 30 Oct 2026 15:43:11 +0300
|
||||
Subject: [PATCH 36/41] Mod command trees: command.set-tree and
|
||||
Subject: [PATCH 36/42] Mod command trees: command.set-tree and
|
||||
set-suggestions, typed parse, colouring and completion from one tree (API 19)
|
||||
|
||||
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 9be21a54fff055e78db245488c28a971a823fdba Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Fri, 30 Oct 2026 16:10:23 +0300
|
||||
Subject: [PATCH 37/41] Persistent mod sound sources: start, update, stop with
|
||||
Subject: [PATCH 37/42] Persistent mod sound sources: start, update, stop with
|
||||
generations, click-free voices, loop sections, voice budget and virtual loops
|
||||
(API 20)
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From e84cdc21a9fabc4518c18edbeacb2df24c85b983 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Fri, 30 Oct 2026 19:07:37 +0300
|
||||
Subject: [PATCH 38/41] HD clouds: rays from a far point, so the view bob's eye
|
||||
Subject: [PATCH 38/42] HD clouds: rays from a far point, so the view bob's eye
|
||||
offset does not bend them
|
||||
|
||||
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 19f07ff4295766c7bee4bd1fbfc509b6a82d12d4 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Fri, 30 Oct 2026 22:09:23 +0300
|
||||
Subject: [PATCH 39/41] Acoustics stage 1: direct-path occlusion ported from
|
||||
Subject: [PATCH 39/42] Acoustics stage 1: direct-path occlusion ported from
|
||||
Sound Physics Remastered 453654e (GPL-3.0, separate files), off by default;
|
||||
stereo output on surround devices; mixer sum in a fixed order (API 21)
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From 449edb87be5b5ddc61d0d2fbeef3a91316a97b62 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Fri, 30 Oct 2026 23:44:14 +0300
|
||||
Subject: [PATCH 40/41] Mod chunk tickets through the server thread (API 22),
|
||||
Subject: [PATCH 40/42] Mod chunk tickets through the server thread (API 22),
|
||||
softer searchlights and light halos, acoustics stage 2: echo taps
|
||||
|
||||
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
From ce3b535af682ff475e5256a05136f653a2e2608c Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Sat, 31 Oct 2026 00:59:02 +0300
|
||||
Subject: [PATCH 41/41] Mod canvas with terrain tiles and mouse input (API 24),
|
||||
Subject: [PATCH 41/42] Mod canvas with terrain tiles and mouse input (API 24),
|
||||
set-acoustics (API 23), acoustics stage 3: reverb
|
||||
|
||||
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
From a6dcb0b5f73640e0324c8bec3508e8e396e713bd Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Sat, 31 Oct 2026 03:20:06 +0300
|
||||
Subject: [PATCH 42/42] game.world-seed (API 25)
|
||||
|
||||
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
||||
---
|
||||
crates/horizon-client/src/game/mods.rs | 3 +++
|
||||
crates/horizon-mod-sdk/wit/horizon.wit | 4 ++++
|
||||
crates/horizon-mods/src/api_level.rs | 6 ++++--
|
||||
crates/horizon-mods/src/runtime.rs | 5 +++++
|
||||
docs/api/mods-reference.md | 1 +
|
||||
5 files changed, 17 insertions(+), 2 deletions(-)
|
||||
|
||||
diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs
|
||||
index 7f9714a18..e96744775 100644
|
||||
--- a/crates/horizon-client/src/game/mods.rs
|
||||
+++ b/crates/horizon-client/src/game/mods.rs
|
||||
@@ -599,6 +599,9 @@ impl Game<'_> {
|
||||
.is_some()
|
||||
.then(|| self.mods.world_id.clone())
|
||||
.flatten(),
|
||||
+ world_seed: (self.player.is_some()
|
||||
+ && self.mods.world_id.as_deref().is_some_and(|w| w.starts_with("world:")))
|
||||
+ .then_some(self.level.seed),
|
||||
}
|
||||
}
|
||||
/// The first block along the player's view within
|
||||
diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit
|
||||
index 805c2a515..774cc5851 100644
|
||||
--- a/crates/horizon-mod-sdk/wit/horizon.wit
|
||||
+++ b/crates/horizon-mod-sdk/wit/horizon.wit
|
||||
@@ -51,6 +51,10 @@ interface game {
|
||||
/// world, `server:<address>` on a server; none on the title screen.
|
||||
/// Mods keep their state apart by it.
|
||||
world-id: func() -> option<string>;
|
||||
+ /// The open saved world's seed (AirDef fork, API level 25): with the
|
||||
+ /// folder name it tells a new world from an old one that had the same
|
||||
+ /// name. None on the title screen and on a server.
|
||||
+ world-seed: func() -> option<s64>;
|
||||
/// A block along the player's view.
|
||||
record hit {
|
||||
/// The block hit.
|
||||
diff --git a/crates/horizon-mods/src/api_level.rs b/crates/horizon-mods/src/api_level.rs
|
||||
index 579af9e25..3af36e7c1 100644
|
||||
--- a/crates/horizon-mods/src/api_level.rs
|
||||
+++ b/crates/horizon-mods/src/api_level.rs
|
||||
@@ -7,13 +7,13 @@
|
||||
//! version's level so the launcher can tell before it installs.
|
||||
|
||||
/// The newest level this Horizon serves.
|
||||
-pub const LEVEL: u32 = 24;
|
||||
+pub const LEVEL: u32 = 25;
|
||||
|
||||
/// Every function the game offers mods, as `interface.function`, with its
|
||||
/// level. Level 0 is the contract of Horizon 0.2.67 to 0.2.69. A new
|
||||
/// function takes the next level and raises [`LEVEL`] (the `api_reference`
|
||||
/// test fails until it is listed here).
|
||||
-pub const FUNCTIONS: [(&str, u32); 90] = [
|
||||
+pub const FUNCTIONS: [(&str, u32); 91] = [
|
||||
("log.write", 0),
|
||||
("game.get-player", 0),
|
||||
("game.get-clock", 0),
|
||||
@@ -118,6 +118,8 @@ pub const FUNCTIONS: [(&str, u32); 90] = [
|
||||
("render.set-canvas", 24),
|
||||
("render.canvas-events", 24),
|
||||
("render.canvas-open", 24),
|
||||
+ // AirDef fork: the open world's seed, so a new world is not an old one of the same name.
|
||||
+ ("game.world-seed", 25),
|
||||
];
|
||||
|
||||
/// What the game's program carries so the launcher can read its level
|
||||
diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs
|
||||
index 81286975f..910986549 100644
|
||||
--- a/crates/horizon-mods/src/runtime.rs
|
||||
+++ b/crates/horizon-mods/src/runtime.rs
|
||||
@@ -189,6 +189,8 @@ pub struct Snapshot {
|
||||
pub creative: bool,
|
||||
/// The open world (`game.world-id`, AirDef fork).
|
||||
pub world: Option<String>,
|
||||
+ /// The open saved world's seed (`game.world-seed`, AirDef fork).
|
||||
+ pub world_seed: Option<i64>,
|
||||
}
|
||||
|
||||
/// Capability `recipes`'s tables: `items` in the registry's order, which
|
||||
@@ -1930,6 +1932,9 @@ impl game::Host for State {
|
||||
fn world_id(&mut self) -> Option<String> {
|
||||
self.snapshot.world.clone()
|
||||
}
|
||||
+ fn world_seed(&mut self) -> Option<i64> {
|
||||
+ self.snapshot.world_seed
|
||||
+ }
|
||||
fn raycast(&mut self, distance: f32) -> Option<Hit> {
|
||||
let (at, hit) = self.snapshot.view_hit.as_ref()?;
|
||||
// NaN compares false: no hit.
|
||||
diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md
|
||||
index cf6e61440..3ab23b490 100644
|
||||
--- a/docs/api/mods-reference.md
|
||||
+++ b/docs/api/mods-reference.md
|
||||
@@ -126,6 +126,7 @@ A block along the player's view.
|
||||
| `get-player` | `func() -> option<player>` | None on the title screen. |
|
||||
| `get-clock` | `func() -> option<clock>` | None on the title screen. |
|
||||
| `world-id` | `func() -> option<string>` | Which world is open (AirDef fork): `world:<folder>` for a saved world, `server:<address>` on a server; none on the title screen. Mods keep their state apart by it. |
|
||||
+| `world-seed` | `func() -> option<s64>` | The open saved world's seed (AirDef fork, API level 25): with the folder name it tells a new world from an old one that had the same name. None on the title screen and on a server. |
|
||||
| `raycast` | `func(distance: f32) -> option<hit>` | The first block along the player's view (fluids pass), up to `distance` blocks (at most 1024; past the loaded chunks, across the distant terrain when LOD Distance is on), as of this tick. None when nothing is hit, and on the title screen. |
|
||||
|
||||
## `chat`
|
||||
--
|
||||
2.54.0 (Apple Git-157)
|
||||
|
||||
@@ -0,0 +1,887 @@
|
||||
From 2fff36c3c6183a440d55371b2db0f3bd6eb586c5 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Sun, 1 Nov 2026 02:30:48 +0300
|
||||
Subject: [PATCH 1/2] Mods read live blocks while replay shows history (#105)
|
||||
|
||||
Co-Authored-By: Kimi <noreply@moonshot.ai>
|
||||
---
|
||||
crates/horizon-client/src/game.rs | 9 +
|
||||
crates/horizon-client/src/game/mod_world.rs | 80 +-----
|
||||
crates/horizon-client/src/game/mods.rs | 10 +-
|
||||
crates/horizon-client/src/lib.rs | 1 +
|
||||
crates/horizon-client/src/streaming.rs | 4 +-
|
||||
crates/horizon-client/src/world.rs | 97 ++++++-
|
||||
crates/horizon-client/src/world_log.rs | 135 ++++++++-
|
||||
crates/horizon-client/src/world_view.rs | 296 ++++++++++++++++++++
|
||||
8 files changed, 549 insertions(+), 83 deletions(-)
|
||||
create mode 100644 crates/horizon-client/src/world_view.rs
|
||||
|
||||
diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs
|
||||
index d7529b12d..a2099747b 100644
|
||||
--- a/crates/horizon-client/src/game.rs
|
||||
+++ b/crates/horizon-client/src/game.rs
|
||||
@@ -10798,6 +10798,15 @@ impl Game<'_> {
|
||||
HeightmapType::MotionBlocking.is_opaque(properties.heightmap_state(s))
|
||||
})
|
||||
}
|
||||
+ /// `rain_height` over the real blocks: what a mod's ground query reads, whatever a film's
|
||||
+ /// view of an earlier time shows (the weather's rain follows the picture).
|
||||
+ fn live_rain_height(&self, x: i32, z: i32) -> i32 {
|
||||
+ use horizon_world::{heightmap::HeightmapType, worldgen::terrain::TerrainBlockStates};
|
||||
+ let properties = &self.pack.assets.properties;
|
||||
+ self.world.live_motion_blocking(x, z, |s| {
|
||||
+ HeightmapType::MotionBlocking.is_opaque(properties.heightmap_state(s))
|
||||
+ })
|
||||
+ }
|
||||
fn tick_weather_effects(&mut self) {
|
||||
if self.flash > 0 {
|
||||
self.flash -= 1;
|
||||
diff --git a/crates/horizon-client/src/game/mod_world.rs b/crates/horizon-client/src/game/mod_world.rs
|
||||
index 7e3a97b0c..2cda0fae7 100644
|
||||
--- a/crates/horizon-client/src/game/mod_world.rs
|
||||
+++ b/crates/horizon-client/src/game/mod_world.rs
|
||||
@@ -4,11 +4,13 @@
|
||||
//! the game holds: a chunk it doesn't have is `unknown`, never air. The
|
||||
//! walk and the bit packing are `horizon_mods::world_query`; this is the
|
||||
//! game's side: which blocks count under each policy, and the chunks.
|
||||
+//! The chunks are read through `horizon_client::world_view`, which puts back
|
||||
+//! every block a film's view of an earlier time shows otherwise: what a mod
|
||||
+//! simulates is the real world, whatever the picture (and #105).
|
||||
use super::Game;
|
||||
-use horizon_client::chunk::{Chunk, MIN_Y, SECTIONS};
|
||||
-use horizon_client::world::World;
|
||||
+use horizon_client::world_view::{SectionView, WorldProbe};
|
||||
use horizon_core::geometry::Axis;
|
||||
-use horizon_mods::world_query::{self, BlockProbe, Cell, SectionBits, Trace};
|
||||
+use horizon_mods::world_query::{SectionBits, Trace};
|
||||
use horizon_mods::{
|
||||
SectionFill, WorldChanges, WorldPolicy, WorldRay, WorldRayAnswer, WorldSection, WorldVerdict,
|
||||
};
|
||||
@@ -43,41 +45,6 @@ fn mask(policy: WorldPolicy) -> u8 {
|
||||
}
|
||||
}
|
||||
|
||||
-/// The blocks of the resident chunks, for [`world_query::trace`].
|
||||
-struct Probe<'a> {
|
||||
- world: &'a World,
|
||||
- tables: &'a WorldTables,
|
||||
- mask: u8,
|
||||
- last: Option<((i32, i32), &'a Arc<Chunk>)>,
|
||||
- cells: usize,
|
||||
-}
|
||||
-impl BlockProbe for Probe<'_> {
|
||||
- fn cell(&mut self, x: i32, y: i32, z: i32) -> Cell<'_> {
|
||||
- self.cells += 1;
|
||||
- let key = (x >> 4, z >> 4);
|
||||
- let chunk = match self.last {
|
||||
- Some((k, c)) if k == key => c,
|
||||
- _ => {
|
||||
- let Some(c) = self.world.chunks.get(&key) else {
|
||||
- return Cell::Unknown;
|
||||
- };
|
||||
- self.last = Some((key, c));
|
||||
- c
|
||||
- }
|
||||
- };
|
||||
- let state = chunk.get(x & 15, y, z & 15) as usize;
|
||||
- if self
|
||||
- .tables
|
||||
- .flags
|
||||
- .get(state)
|
||||
- .is_none_or(|f| f & self.mask == 0)
|
||||
- {
|
||||
- return Cell::Empty;
|
||||
- }
|
||||
- Cell::Solid(self.tables.boxes[state].as_deref())
|
||||
- }
|
||||
-}
|
||||
-
|
||||
impl Game<'_> {
|
||||
/// The tables for this world, made when it is new.
|
||||
fn world_tables(&mut self) -> Arc<WorldTables> {
|
||||
@@ -158,7 +125,7 @@ impl Game<'_> {
|
||||
let (changed, overflow) = self.world.mod_changes.take();
|
||||
let changes = WorldChanges {
|
||||
epoch: self.world.epoch,
|
||||
- revision: self.world.revision,
|
||||
+ revision: self.world.live_revision,
|
||||
overflow,
|
||||
sections: changed,
|
||||
};
|
||||
@@ -192,14 +159,8 @@ impl Game<'_> {
|
||||
if budget == 0 {
|
||||
return (unknown(r.id, 0.0), 0);
|
||||
}
|
||||
- let mut probe = Probe {
|
||||
- world: &self.world,
|
||||
- tables,
|
||||
- mask: mask(r.policy),
|
||||
- last: None,
|
||||
- cells: 0,
|
||||
- };
|
||||
- let t = world_query::trace(
|
||||
+ let mut probe = WorldProbe::new(&self.world, &tables.flags, &tables.boxes, mask(r.policy));
|
||||
+ let t = horizon_mods::world_query::trace(
|
||||
&mut probe,
|
||||
[r.start.0, r.start.1, r.start.2],
|
||||
[r.end.0, r.end.1, r.end.2],
|
||||
@@ -238,25 +199,12 @@ impl Game<'_> {
|
||||
fill: SectionFill::Unknown,
|
||||
bits: Vec::new(),
|
||||
};
|
||||
- let Some(chunk) = self.world.chunks.get(&(x, z)) else {
|
||||
- return s;
|
||||
- };
|
||||
- let index = y - (MIN_Y >> 4);
|
||||
- if !(0..SECTIONS as i32).contains(&index) {
|
||||
- s.fill = SectionFill::Empty;
|
||||
- return s;
|
||||
- }
|
||||
- let section = &chunk.sections[index as usize];
|
||||
- let mut states = [0u32; 4096];
|
||||
- if let Some(v) = section.blocks.uniform() {
|
||||
- states.fill(v);
|
||||
- } else {
|
||||
- section.unpack(&mut states);
|
||||
- }
|
||||
- match world_query::section_bits(&states, &tables.flags, mask) {
|
||||
- SectionBits::Empty => s.fill = SectionFill::Empty,
|
||||
- SectionBits::Full => s.fill = SectionFill::Full,
|
||||
- SectionBits::Mixed(bits) => {
|
||||
+ match self.world.live_section(x, y, z, &tables.flags, mask) {
|
||||
+ SectionView::Unknown => {}
|
||||
+ SectionView::Empty => s.fill = SectionFill::Empty,
|
||||
+ SectionView::Bits(SectionBits::Empty) => s.fill = SectionFill::Empty,
|
||||
+ SectionView::Bits(SectionBits::Full) => s.fill = SectionFill::Full,
|
||||
+ SectionView::Bits(SectionBits::Mixed(bits)) => {
|
||||
s.fill = SectionFill::Mixed;
|
||||
s.bits = bits.to_vec();
|
||||
}
|
||||
diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs
|
||||
index e96744775..e95aaed2d 100644
|
||||
--- a/crates/horizon-client/src/game/mods.rs
|
||||
+++ b/crates/horizon-client/src/game/mods.rs
|
||||
@@ -789,8 +789,9 @@ impl Game<'_> {
|
||||
tickets.truncate(CHUNK_TICKETS);
|
||||
}
|
||||
}
|
||||
- /// `render.query-ground`'s answer: the heightmap, or `i32::MIN` for a column whose chunk a
|
||||
- /// mod asked to load and which is not there yet.
|
||||
+ /// `render.query-ground`'s answer: the heightmap of the real blocks, or `i32::MIN` for a
|
||||
+ /// column whose chunk a mod asked to load and which is not there yet. A film's view of an
|
||||
+ /// earlier time is the picture only: a simulation's ground is the one it flies over.
|
||||
fn mod_ground(&self, x: i32, z: i32) -> i32 {
|
||||
let key = (x >> 4, z >> 4);
|
||||
if !self.world.chunks.contains_key(&key)
|
||||
@@ -798,7 +799,7 @@ impl Game<'_> {
|
||||
{
|
||||
return i32::MIN;
|
||||
}
|
||||
- self.rain_height(x, z)
|
||||
+ self.live_rain_height(x, z)
|
||||
}
|
||||
/// The mods' persistent sound sources (API level 20): their changes go to the mixer, and the
|
||||
/// sources of a mod that no longer runs are released. The generation the mods read is the
|
||||
@@ -941,6 +942,9 @@ impl Game<'_> {
|
||||
match wanted {
|
||||
Some(id) => {
|
||||
if self.world.log.as_ref().is_none_or(|l| l.id != id) {
|
||||
+ // A log replaced while it still shows earlier blocks puts them back first:
|
||||
+ // only the log knows which block is real where the picture differs.
|
||||
+ self.world.view_log(None, usize::MAX, None);
|
||||
self.world.log = Some(WorldLog::new(id, self.ticks));
|
||||
}
|
||||
}
|
||||
diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs
|
||||
index 879133e81..d7fa5303b 100644
|
||||
--- a/crates/horizon-client/src/lib.rs
|
||||
+++ b/crates/horizon-client/src/lib.rs
|
||||
@@ -186,6 +186,7 @@ pub mod win_screen;
|
||||
pub mod world;
|
||||
pub mod world_log;
|
||||
pub mod world_spawn;
|
||||
+pub mod world_view;
|
||||
pub mod worldborder;
|
||||
pub mod zip;
|
||||
pub use horizon_client_core::Result;
|
||||
diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs
|
||||
index 6588ac32d..4432626f0 100644
|
||||
--- a/crates/horizon-client/src/streaming.rs
|
||||
+++ b/crates/horizon-client/src/streaming.rs
|
||||
@@ -626,7 +626,7 @@ impl Streaming {
|
||||
let key = (chunk.x, chunk.z);
|
||||
self.lighting.remove(&key);
|
||||
self.light_snapshots.remove(&key);
|
||||
- world.chunks.insert(key, Arc::new(chunk));
|
||||
+ world.insert_chunk(key, Arc::new(chunk));
|
||||
self.lit.insert(key);
|
||||
self.generated_total += 1;
|
||||
for dz in -1..=1 {
|
||||
@@ -770,7 +770,7 @@ impl Streaming {
|
||||
// A chunk saved with its light needs no light job; its unlit
|
||||
// neighbours still light themselves from it.
|
||||
let loaded = chunk.light_loaded;
|
||||
- world.chunks.insert(key, Arc::new(chunk));
|
||||
+ world.insert_chunk(key, Arc::new(chunk));
|
||||
if loaded {
|
||||
self.lit.insert(key);
|
||||
for sy in 0..SECTIONS as i32 {
|
||||
diff --git a/crates/horizon-client/src/world.rs b/crates/horizon-client/src/world.rs
|
||||
index d42e51ac8..5c2b0c267 100644
|
||||
--- a/crates/horizon-client/src/world.rs
|
||||
+++ b/crates/horizon-client/src/world.rs
|
||||
@@ -52,7 +52,12 @@ pub struct World {
|
||||
pub fast_lava: bool,
|
||||
pub chunks: crate::chunk_map::ChunkMap,
|
||||
pub random: LegacyRandom,
|
||||
+ /// The revision of the blocks shown: a real change, and a view of an earlier time that
|
||||
+ /// changes the picture (the renderer and the acoustics follow it). Mods cache on
|
||||
+ /// `live_revision`: a film's view is no change of the world they simulate.
|
||||
pub revision: u64,
|
||||
+ /// The revision of the real blocks, which a view of an earlier time leaves alone.
|
||||
+ pub live_revision: u64,
|
||||
pub health_rules: HealthRules,
|
||||
pub air: BlockStateId,
|
||||
/// Sections whose geometry changed and need remeshing.
|
||||
@@ -130,6 +135,23 @@ impl ModChanges {
|
||||
self.sections.insert((x >> 4, y >> 4, z >> 4));
|
||||
}
|
||||
}
|
||||
+ /// A column's residency changed (a chunk loaded, was replaced by a reload
|
||||
+ /// or is gone): every section of the column counts as changed, for caches
|
||||
+ /// keyed to sections. Bounded like `note` is.
|
||||
+ pub fn column(&mut self, x: i32, z: i32) {
|
||||
+ if self.sections.len() < Self::MAX {
|
||||
+ for sy in 0..SECTIONS as i32 {
|
||||
+ self.sections.insert((x, sy, z));
|
||||
+ }
|
||||
+ }
|
||||
+ if self.sections.len() >= Self::MAX {
|
||||
+ self.overflow = true;
|
||||
+ }
|
||||
+ }
|
||||
+ /// The change log overflowed or the resident columns were cleared: every cached section may be stale.
|
||||
+ pub fn overflow(&mut self) {
|
||||
+ self.overflow = true;
|
||||
+ }
|
||||
/// What changed since the last call, as the mod reads it.
|
||||
pub fn take(&mut self) -> (Vec<(i32, i32, i32)>, bool) {
|
||||
(
|
||||
@@ -209,6 +231,7 @@ impl World {
|
||||
chunks: Default::default(),
|
||||
random: LegacyRandom::new(seed),
|
||||
revision: 0,
|
||||
+ live_revision: 0,
|
||||
health_rules: HealthRules::default(),
|
||||
air,
|
||||
fast_lava: false,
|
||||
@@ -335,6 +358,7 @@ impl World {
|
||||
self.watched_writes.push(((x, y, z), previous, state.0));
|
||||
}
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
+ self.live_revision = self.live_revision.wrapping_add(1);
|
||||
if self.mod_changes.watching {
|
||||
self.mod_changes.note(x, y, z);
|
||||
}
|
||||
@@ -378,7 +402,9 @@ impl World {
|
||||
}
|
||||
/// A mod's view of the world at an earlier tick (`render.set-world-time-view`): moves it
|
||||
/// toward `target` by at most `budget` changes, leaving alone the blocks around `protect`
|
||||
- /// (a block position whose neighbourhood stays as it is: the player's). Only the client's copy of the blocks changes. True when it has got there.
|
||||
+ /// (a block position whose neighbourhood stays as it is: the player's). Only the picture
|
||||
+ /// changes: the renderer meshes these chunks, while a simulation reads the real blocks
|
||||
+ /// ([`Self::live_block`]). True when it has got there.
|
||||
pub fn view_log(
|
||||
&mut self,
|
||||
target: Option<u64>,
|
||||
@@ -400,7 +426,9 @@ impl World {
|
||||
done
|
||||
}
|
||||
}
|
||||
-/// The world as a log's view writes it: only what is drawn changes.
|
||||
+/// The world as a log's view writes it: the picture the renderer meshes changes, and nothing
|
||||
+/// else. The real state of every block written stays in the log (`WorldLog::real`), which is
|
||||
+/// what a simulation reads; the world's own change signals stay the real ones.
|
||||
struct ShownBlocks<'a>(&'a mut World);
|
||||
impl crate::world_log::Blocks for ShownBlocks<'_> {
|
||||
fn get(&self, pos: [i32; 3]) -> Option<u32> {
|
||||
@@ -419,10 +447,10 @@ impl crate::world_log::Blocks for ShownBlocks<'_> {
|
||||
};
|
||||
let previous = Arc::make_mut(chunk).set(x & 15, y, z & 15, state);
|
||||
if previous != state {
|
||||
+ // The picture changed, so the renderer and the acoustics look at it again; the
|
||||
+ // blocks did not, so `live_revision` and `mod_changes` — what mods cache and
|
||||
+ // simulate by — stay as they are.
|
||||
w.revision = w.revision.wrapping_add(1);
|
||||
- if w.mod_changes.watching {
|
||||
- w.mod_changes.note(x, y, z);
|
||||
- }
|
||||
if w.sound_changes.watching {
|
||||
w.sound_changes.note(x, y, z);
|
||||
}
|
||||
@@ -452,6 +480,65 @@ impl World {
|
||||
.get(&(x >> 4, z >> 4))
|
||||
.map_or(self.air, |chunk| chunk.block(x & 15, y, z & 15))
|
||||
}
|
||||
+ /// Inserts a whole current column. A replay keeps its picture, but the real states behind it
|
||||
+ /// are refreshed from this column and simulations hear the change.
|
||||
+ pub fn insert_chunk(&mut self, key: (i32, i32), mut chunk: Arc<crate::chunk::Chunk>) -> Option<Arc<crate::chunk::Chunk>> {
|
||||
+ if let Some(log) = &mut self.log {
|
||||
+ let current = self.chunks.get(&key).cloned();
|
||||
+ log.reload_column(key.0, key.1, current.as_deref(), Arc::make_mut(&mut chunk));
|
||||
+ }
|
||||
+ self.live_revision = self.live_revision.wrapping_add(1);
|
||||
+ if self.mod_changes.watching {
|
||||
+ self.mod_changes.column(key.0, key.1);
|
||||
+ }
|
||||
+ self.chunks.insert(key, chunk)
|
||||
+ }
|
||||
+ /// The real block at `(x, y, z)`: what a simulation reads, where a view of an earlier
|
||||
+ /// time shows something else for a film ([`Self::view_log`]). [`Self::block`] stays the
|
||||
+ /// picture, which is what the renderer meshes.
|
||||
+ pub fn live_block(&self, x: i32, y: i32, z: i32) -> BlockStateId {
|
||||
+ match self.log.as_ref().and_then(|log| log.real([x, y, z])) {
|
||||
+ Some(real) => BlockStateId(real),
|
||||
+ None => self.block(x, y, z),
|
||||
+ }
|
||||
+ }
|
||||
+ /// Whether a view of an earlier time shows a block of the column `(x >> 4, z >> 4)`
|
||||
+ /// otherwise: until it does, the column reads as the real one.
|
||||
+ pub fn view_shows_in_column(&self, cx: i32, cz: i32) -> bool {
|
||||
+ self.log
|
||||
+ .as_ref()
|
||||
+ .is_some_and(|log| log.shows_in_column(cx, cz))
|
||||
+ }
|
||||
+ /// The blocks of section `(cx, sy, cz)` (vanilla section coordinates, `sy = y >> 4`), in
|
||||
+ /// `chunk::index` order, with every block a view of an earlier time shows otherwise put
|
||||
+ /// back to its real state.
|
||||
+ pub fn live_section_states(&self, cx: i32, sy: i32, cz: i32, states: &mut [u32; 4096]) {
|
||||
+ let Some(log) = &self.log else {
|
||||
+ return;
|
||||
+ };
|
||||
+ if !log.shows_in_section(cx, sy, cz) {
|
||||
+ return;
|
||||
+ }
|
||||
+ for ([x, y, z], real) in log.real_in_section(cx, sy, cz) {
|
||||
+ states[crate::chunk::index(x, y, z)] = real;
|
||||
+ }
|
||||
+ }
|
||||
+ /// [`Self::motion_blocking`] over the real blocks: a mod's ground query, whatever a view
|
||||
+ /// of an earlier time shows.
|
||||
+ pub fn live_motion_blocking(
|
||||
+ &self,
|
||||
+ x: i32,
|
||||
+ z: i32,
|
||||
+ blocks: impl Fn(BlockStateId) -> bool,
|
||||
+ ) -> i32 {
|
||||
+ if !self.view_shows_in_column(x >> 4, z >> 4) {
|
||||
+ return self.motion_blocking(x, z, blocks);
|
||||
+ }
|
||||
+ (MIN_Y..MIN_Y + (SECTIONS as i32) * 16)
|
||||
+ .rev()
|
||||
+ .find(|&y| blocks(self.live_block(x, y, z)))
|
||||
+ .map_or(MIN_Y, |y| y + 1)
|
||||
+ }
|
||||
/// Whether a block of the box `lo..=hi` may match, from the palettes of
|
||||
/// the sections it reaches (a palette of the whole registry may hold
|
||||
/// anything): `false` means [`Self::block`] matches in none of its cells,
|
||||
diff --git a/crates/horizon-client/src/world_log.rs b/crates/horizon-client/src/world_log.rs
|
||||
index d0c0b1158..315388c00 100644
|
||||
--- a/crates/horizon-client/src/world_log.rs
|
||||
+++ b/crates/horizon-client/src/world_log.rs
|
||||
@@ -7,6 +7,11 @@
|
||||
//! while the cursor is behind the end is logged and kept as the block's real state, but not
|
||||
//! written (it lies after the view's time): it shows when the cursor passes it, or when the
|
||||
//! view ends and every displaced block is put back. Pure over [`Blocks`]; the world is one.
|
||||
+//!
|
||||
+//! A block written here is the picture (what the renderer meshes): the real state of every
|
||||
+//! displaced block stays in `shown`, and what stands for the simulation reads it
|
||||
+//! ([`WorldLog::real`], `World::live_block`). Moving the view changes the picture alone, so it
|
||||
+//! is no block change of the world a mod simulates.
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
|
||||
pub type Pos = [i32; 3];
|
||||
@@ -39,6 +44,10 @@ pub struct WorldLog {
|
||||
cursor: u64,
|
||||
/// Blocks shown other than they are: their real state.
|
||||
shown: HashMap<Pos, u32>,
|
||||
+ /// How many blocks of each section (`x >> 4, y >> 4, z >> 4`) and column (`x >> 4,
|
||||
+ /// z >> 4`) are in `shown`: absent means none, so a query passes those over whole.
|
||||
+ sections: HashMap<(i32, i32, i32), usize>,
|
||||
+ columns: HashMap<(i32, i32), usize>,
|
||||
cap: usize,
|
||||
/// The tick the log began, and the tick of the newest change it let go.
|
||||
start: u64,
|
||||
@@ -56,6 +65,8 @@ impl WorldLog {
|
||||
base: 0,
|
||||
cursor: 0,
|
||||
shown: HashMap::new(),
|
||||
+ sections: HashMap::new(),
|
||||
+ columns: HashMap::new(),
|
||||
cap: cap.max(1),
|
||||
start: tick,
|
||||
lost: None,
|
||||
@@ -82,6 +93,54 @@ impl WorldLog {
|
||||
pub fn displaced(&self) -> usize {
|
||||
self.shown.len()
|
||||
}
|
||||
+ /// The real state of a block the view shows otherwise, which is what a simulation reads:
|
||||
+ /// None where the block is shown as it is.
|
||||
+ pub fn real(&self, pos: Pos) -> Option<u32> {
|
||||
+ self.shown.get(&pos).copied()
|
||||
+ }
|
||||
+ /// Whether the view shows a block of section `(x >> 4, y >> 4, z >> 4)` otherwise.
|
||||
+ pub fn shows_in_section(&self, cx: i32, sy: i32, cz: i32) -> bool {
|
||||
+ self.sections.contains_key(&(cx, sy, cz))
|
||||
+ }
|
||||
+ /// Whether the view shows a block of column `(x >> 4, z >> 4)` otherwise.
|
||||
+ pub fn shows_in_column(&self, cx: i32, cz: i32) -> bool {
|
||||
+ self.columns.contains_key(&(cx, cz))
|
||||
+ }
|
||||
+ /// The blocks of a section the view shows otherwise, with their real states.
|
||||
+ pub fn real_in_section(
|
||||
+ &self,
|
||||
+ cx: i32,
|
||||
+ sy: i32,
|
||||
+ cz: i32,
|
||||
+ ) -> impl Iterator<Item = (Pos, u32)> + '_ {
|
||||
+ self.shown.iter().filter_map(move |(&pos, &real)| {
|
||||
+ (pos[0] >> 4 == cx && pos[1] >> 4 == sy && pos[2] >> 4 == cz).then_some((pos, real))
|
||||
+ })
|
||||
+ }
|
||||
+ /// A whole column arrived from the server or generation: its current blocks replace the real
|
||||
+ /// states saved behind the picture, while the picture itself stays at the replay's time.
|
||||
+ pub fn reload_column(
|
||||
+ &mut self,
|
||||
+ cx: i32,
|
||||
+ cz: i32,
|
||||
+ current: Option<&crate::chunk::Chunk>,
|
||||
+ next: &mut crate::chunk::Chunk,
|
||||
+ ) {
|
||||
+ let changes: Vec<(Pos, u32, u32)> = self
|
||||
+ .shown
|
||||
+ .iter()
|
||||
+ .filter(|(pos, _)| pos[0] >> 4 == cx && pos[2] >> 4 == cz)
|
||||
+ .map(|(&pos, &real)| {
|
||||
+ let fresh = next.get(pos[0] & 15, pos[1], pos[2] & 15);
|
||||
+ let picture = current.map_or(real, |chunk| chunk.get(pos[0] & 15, pos[1], pos[2] & 15));
|
||||
+ (pos, fresh, picture)
|
||||
+ })
|
||||
+ .collect();
|
||||
+ for (pos, fresh, picture) in changes {
|
||||
+ next.set(pos[0] & 15, pos[1], pos[2] & 15, picture);
|
||||
+ self.shown.insert(pos, fresh);
|
||||
+ }
|
||||
+ }
|
||||
/// The first sequence number whose change came after tick `t` (the world at `t` is the real
|
||||
/// one with those undone).
|
||||
fn seq_after(&self, t: u64) -> u64 {
|
||||
@@ -114,7 +173,7 @@ impl WorldLog {
|
||||
self.cursor = self.end();
|
||||
}
|
||||
if deferred {
|
||||
- self.shown.insert(pos, new);
|
||||
+ self.displace(pos, new);
|
||||
if at_end {
|
||||
// Displaced blocks wait for their restoration with the cursor at the end.
|
||||
self.cursor = self.end();
|
||||
@@ -162,7 +221,7 @@ impl WorldLog {
|
||||
.collect();
|
||||
for (pos, real) in rest {
|
||||
blocks.put(pos, real);
|
||||
- self.shown.remove(&pos);
|
||||
+ self.put_back(pos);
|
||||
}
|
||||
}
|
||||
self.cursor == goal && (goal != self.end() || self.shown.is_empty())
|
||||
@@ -186,13 +245,45 @@ impl WorldLog {
|
||||
None => return,
|
||||
},
|
||||
};
|
||||
- if !blocks.put(pos, state) {
|
||||
- self.shown.remove(&pos);
|
||||
- } else if state == real {
|
||||
- self.shown.remove(&pos);
|
||||
+ if !blocks.put(pos, state) || state == real {
|
||||
+ self.put_back(pos);
|
||||
} else {
|
||||
- self.shown.insert(pos, real);
|
||||
+ self.displace(pos, real);
|
||||
+ }
|
||||
+ }
|
||||
+ /// Keeps `real` as the real state of a block shown otherwise.
|
||||
+ fn displace(&mut self, pos: Pos, real: u32) {
|
||||
+ if self.shown.insert(pos, real).is_some() {
|
||||
+ return;
|
||||
+ }
|
||||
+ count(
|
||||
+ &mut self.sections,
|
||||
+ (pos[0] >> 4, pos[1] >> 4, pos[2] >> 4),
|
||||
+ 1,
|
||||
+ );
|
||||
+ count(&mut self.columns, (pos[0] >> 4, pos[2] >> 4), 1);
|
||||
+ }
|
||||
+ /// Forgets a displaced block: what is shown is its real state again.
|
||||
+ fn put_back(&mut self, pos: Pos) {
|
||||
+ if self.shown.remove(&pos).is_none() {
|
||||
+ return;
|
||||
}
|
||||
+ count(
|
||||
+ &mut self.sections,
|
||||
+ (pos[0] >> 4, pos[1] >> 4, pos[2] >> 4),
|
||||
+ -1,
|
||||
+ );
|
||||
+ count(&mut self.columns, (pos[0] >> 4, pos[2] >> 4), -1);
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+/// Keeps the number of displaced blocks under `key`, dropping it at zero.
|
||||
+fn count<K: std::hash::Hash + Eq>(counts: &mut HashMap<K, usize>, key: K, by: isize) {
|
||||
+ let n = counts.get(&key).copied().unwrap_or(0) as isize + by;
|
||||
+ if n > 0 {
|
||||
+ counts.insert(key, n as usize);
|
||||
+ } else {
|
||||
+ counts.remove(&key);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -369,4 +460,34 @@ mod tests {
|
||||
log.view(&mut w, None, 100, all);
|
||||
assert_eq!(w.shows([0, 0, 0]), 7);
|
||||
}
|
||||
+
|
||||
+ #[test]
|
||||
+ fn the_real_blocks_of_a_view_are_read_where_it_shows_others() {
|
||||
+ let (mut w, mut log) = raid();
|
||||
+ log.view(&mut w, Some(5), 100, all);
|
||||
+ // The sections and columns the view touches, and the real state of what it shows otherwise.
|
||||
+ assert_eq!(log.real([0, 0, 0]), Some(7));
|
||||
+ assert_eq!(log.real([9, 0, 0]), None);
|
||||
+ assert!(log.shows_in_column(0, 0));
|
||||
+ assert!(!log.shows_in_column(1, 0));
|
||||
+ assert!(log.shows_in_section(0, 0, 0));
|
||||
+ assert!(!log.shows_in_section(0, 1, 0));
|
||||
+ let displaced: Vec<_> = log.real_in_section(0, 0, 0).collect();
|
||||
+ assert_eq!(displaced.len(), 3);
|
||||
+ for (pos, real) in [([0, 0, 0], 7), ([1, 0, 0], 0), ([2, 0, 0], 0)] {
|
||||
+ assert!(displaced.contains(&(pos, real)));
|
||||
+ }
|
||||
+ // A change arriving behind the view is the block's real state, shown nowhere.
|
||||
+ w.set(&mut log, 40, [20, 20, 3], 5);
|
||||
+ assert_eq!(w.shows([20, 20, 3]), 0);
|
||||
+ assert_eq!(log.real([20, 20, 3]), Some(5));
|
||||
+ assert!(log.shows_in_column(1, 0) && log.shows_in_section(1, 1, 0));
|
||||
+ // The end puts every block back: nothing is left to read.
|
||||
+ assert!(log.view(&mut w, None, 100, all));
|
||||
+ for pos in [[0, 0, 0], [20, 20, 3]] {
|
||||
+ assert_eq!(log.real(pos), None);
|
||||
+ }
|
||||
+ assert!(!log.shows_in_column(0, 0) && !log.shows_in_column(1, 0));
|
||||
+ assert!(!log.shows_in_section(0, 0, 0) && !log.shows_in_section(1, 1, 0));
|
||||
+ }
|
||||
}
|
||||
diff --git a/crates/horizon-client/src/world_view.rs b/crates/horizon-client/src/world_view.rs
|
||||
new file mode 100644
|
||||
index 000000000..fdc3f6515
|
||||
--- /dev/null
|
||||
+++ b/crates/horizon-client/src/world_view.rs
|
||||
@@ -0,0 +1,296 @@
|
||||
+//! The world as a mod's simulation reads it (capability `render`, AirDef fork): the real
|
||||
+//! blocks. A film's view of an earlier time (`World::view_log`) is written into the chunks
|
||||
+//! the renderer meshes, so a query that stands for a simulation has to read past it: a raid
|
||||
+//! does not go back in time with the picture (#105).
|
||||
+use crate::chunk::{Chunk, MIN_Y, SECTIONS};
|
||||
+use crate::world::World;
|
||||
+use horizon_mods::world_query::{BlockProbe, Cell, SectionBits, section_bits};
|
||||
+use std::sync::Arc;
|
||||
+
|
||||
+/// The resident chunks, with every block a view of an earlier time shows otherwise put back
|
||||
+/// to its real state.
|
||||
+pub struct WorldProbe<'a> {
|
||||
+ world: &'a World,
|
||||
+ /// Per state: the policy bits that it stops.
|
||||
+ flags: &'a [u8],
|
||||
+ /// Per state: its collision boxes in block space; none for a full cube (or a state that
|
||||
+ /// stops nothing).
|
||||
+ boxes: &'a [Option<Box<[[f64; 6]]>>],
|
||||
+ mask: u8,
|
||||
+ /// The last column read, and whether the view shows any of its blocks otherwise.
|
||||
+ last: Option<((i32, i32), &'a Arc<Chunk>, bool)>,
|
||||
+ /// Cells read.
|
||||
+ pub cells: usize,
|
||||
+}
|
||||
+
|
||||
+impl<'a> WorldProbe<'a> {
|
||||
+ pub fn new(
|
||||
+ world: &'a World,
|
||||
+ flags: &'a [u8],
|
||||
+ boxes: &'a [Option<Box<[[f64; 6]]>>],
|
||||
+ mask: u8,
|
||||
+ ) -> Self {
|
||||
+ Self {
|
||||
+ world,
|
||||
+ flags,
|
||||
+ boxes,
|
||||
+ mask,
|
||||
+ last: None,
|
||||
+ cells: 0,
|
||||
+ }
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+impl BlockProbe for WorldProbe<'_> {
|
||||
+ fn cell(&mut self, x: i32, y: i32, z: i32) -> Cell<'_> {
|
||||
+ self.cells += 1;
|
||||
+ let key = (x >> 4, z >> 4);
|
||||
+ let (chunk, view) = match self.last {
|
||||
+ Some((k, chunk, view)) if k == key => (chunk, view),
|
||||
+ _ => {
|
||||
+ let Some(chunk) = self.world.chunks.get(&key) else {
|
||||
+ return Cell::Unknown;
|
||||
+ };
|
||||
+ let view = self.world.view_shows_in_column(key.0, key.1);
|
||||
+ self.last = Some((key, chunk, view));
|
||||
+ (chunk, view)
|
||||
+ }
|
||||
+ };
|
||||
+ // Only a column the view touches costs a lookup per block.
|
||||
+ let state = if view {
|
||||
+ self.world.live_block(x, y, z).0
|
||||
+ } else {
|
||||
+ chunk.get(x & 15, y, z & 15)
|
||||
+ } as usize;
|
||||
+ if self.flags.get(state).is_none_or(|f| f & self.mask == 0) {
|
||||
+ return Cell::Empty;
|
||||
+ }
|
||||
+ Cell::Solid(self.boxes[state].as_deref())
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+/// A section as a mod's query reads it: the real blocks, never a film's picture.
|
||||
+#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
+pub enum SectionView {
|
||||
+ /// No chunk holds the column.
|
||||
+ Unknown,
|
||||
+ /// The section lies outside the world's height: nothing there.
|
||||
+ Empty,
|
||||
+ /// Its real blocks under the state table.
|
||||
+ Bits(SectionBits),
|
||||
+}
|
||||
+
|
||||
+impl World {
|
||||
+ /// A section (`x >> 4, y >> 4, z >> 4`: vanilla section coordinates) under a state table
|
||||
+ /// and a policy mask, read from the real blocks.
|
||||
+ pub fn live_section(&self, cx: i32, sy: i32, cz: i32, flags: &[u8], mask: u8) -> SectionView {
|
||||
+ let Some(chunk) = self.chunks.get(&(cx, cz)) else {
|
||||
+ return SectionView::Unknown;
|
||||
+ };
|
||||
+ let index = sy - (MIN_Y >> 4);
|
||||
+ if !(0..SECTIONS as i32).contains(&index) {
|
||||
+ return SectionView::Empty;
|
||||
+ }
|
||||
+ let section = &chunk.sections[index as usize];
|
||||
+ let mut states = [0u32; 4096];
|
||||
+ if let Some(v) = section.blocks.uniform() {
|
||||
+ states.fill(v);
|
||||
+ } else {
|
||||
+ section.unpack(&mut states);
|
||||
+ }
|
||||
+ self.live_section_states(cx, sy, cz, &mut states);
|
||||
+ SectionView::Bits(section_bits(&states, flags, mask))
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+#[cfg(test)]
|
||||
+mod tests {
|
||||
+ use super::*;
|
||||
+ use crate::chunk::index;
|
||||
+ use crate::world_log::WorldLog;
|
||||
+ use horizon_mods::world_query::{Trace, trace};
|
||||
+ use horizon_world::registry::BlockStateId;
|
||||
+ use std::sync::Arc;
|
||||
+
|
||||
+ const AIR: u32 = 0;
|
||||
+ const STONE: u32 = 1;
|
||||
+ /// The policy bits of `COLLISION | SIGHT | SOUND`, as `game::mod_world` makes them.
|
||||
+ const ALL: u8 = 0b111;
|
||||
+ /// The section of the wall at y 100 (`y >> 4`).
|
||||
+ const SY: i32 = 6;
|
||||
+
|
||||
+ type Tables = (Vec<u8>, Vec<Option<Box<[[f64; 6]]>>>);
|
||||
+
|
||||
+ /// A floor at y 70 and a wall at x 10, z 0, in the one resident chunk.
|
||||
+ fn walled() -> World {
|
||||
+ let mut world = World::new(BlockStateId(AIR), 0);
|
||||
+ world.chunks.insert((0, 0), Arc::new(Chunk::empty(0, 0)));
|
||||
+ for z in 0..=2 {
|
||||
+ for x in 0..=14 {
|
||||
+ world.set(x, 70, z, BlockStateId(STONE)).unwrap();
|
||||
+ }
|
||||
+ }
|
||||
+ world.set(10, 100, 0, BlockStateId(STONE)).unwrap();
|
||||
+ world
|
||||
+ }
|
||||
+
|
||||
+ /// State flags and collision boxes: stone stops every policy, as a full cube.
|
||||
+ fn tables() -> Tables {
|
||||
+ let mut flags = vec![0u8; 8];
|
||||
+ flags[STONE as usize] = ALL;
|
||||
+ (flags, vec![None; 8])
|
||||
+ }
|
||||
+
|
||||
+ /// A collision flight from x 9.5 to 11.5 at y 100.5, along `z`, as a mod asks one.
|
||||
+ fn ray(world: &World, z: i32, tables: &Tables) -> Trace {
|
||||
+ let mut probe = WorldProbe::new(world, &tables.0, &tables.1, 0b001);
|
||||
+ let z = f64::from(z) + 0.5;
|
||||
+ trace(&mut probe, [9.5, 100.5, z], [11.5, 100.5, z])
|
||||
+ }
|
||||
+
|
||||
+ /// Whether the section's presented bits have the block `(10, y, 0)` set.
|
||||
+ fn presented_bit(world: &World, flags: &[u8], y: i32) -> bool {
|
||||
+ let chunk = world.chunks.get(&(0, 0)).unwrap();
|
||||
+ let mut states = [0u32; 4096];
|
||||
+ chunk.sections[((y - MIN_Y) >> 4) as usize].unpack(&mut states);
|
||||
+ let i = index(10, y, 0);
|
||||
+ match section_bits(&states, flags, 0b001) {
|
||||
+ SectionBits::Mixed(bits) => bits[i >> 3] & (1 << (i & 7)) != 0,
|
||||
+ _ => false,
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn a_films_view_of_earlier_blocks_is_no_change_of_the_simulated_world() {
|
||||
+ let tables = tables();
|
||||
+ let mut world = walled();
|
||||
+ // The wall stops the flight.
|
||||
+ let wall = ray(&world, 0, &tables);
|
||||
+ assert!(
|
||||
+ matches!(
|
||||
+ wall,
|
||||
+ Trace::Hit {
|
||||
+ block: [10, 100, 0],
|
||||
+ ..
|
||||
+ }
|
||||
+ ),
|
||||
+ "{wall:?}"
|
||||
+ );
|
||||
+ world.log = Some(WorldLog::new(1, 0));
|
||||
+ // The raid breaks it: a real change, logged.
|
||||
+ world.log_tick = 10;
|
||||
+ world.set(10, 100, 0, BlockStateId(AIR)).unwrap();
|
||||
+ let cleared = ray(&world, 0, &tables);
|
||||
+ assert_eq!(cleared, Trace::Clear);
|
||||
+ assert_eq!(
|
||||
+ world.live_section(0, SY, 0, &tables.0, 0b001),
|
||||
+ SectionView::Bits(SectionBits::Empty)
|
||||
+ );
|
||||
+ let live_revision = world.live_revision;
|
||||
+ // Watching for block changes, as a mod's world query does.
|
||||
+ world.mod_changes.watching = true;
|
||||
+ let _ = world.mod_changes.take();
|
||||
+ // The film goes back to before the blast: the picture has the wall, the world has not.
|
||||
+ assert!(world.view_log(Some(0), 100, None));
|
||||
+ assert_eq!(world.block(10, 100, 0), BlockStateId(STONE), "the picture");
|
||||
+ assert_eq!(world.live_block(10, 100, 0), BlockStateId(AIR), "the world");
|
||||
+ assert!(presented_bit(&world, &tables.0, 100));
|
||||
+ assert_eq!(
|
||||
+ world.live_section(0, SY, 0, &tables.0, 0b001),
|
||||
+ SectionView::Bits(SectionBits::Empty)
|
||||
+ );
|
||||
+ assert_eq!(
|
||||
+ ray(&world, 0, &tables),
|
||||
+ cleared,
|
||||
+ "the same flight through the passage the raid made"
|
||||
+ );
|
||||
+ // The picture changed; no block change reached the mod, and its revision stands.
|
||||
+ assert_eq!(world.mod_changes.take(), (Vec::new(), false));
|
||||
+ assert_eq!(world.live_revision, live_revision);
|
||||
+ // A real change during the film: the simulation meets it, the picture stays at tick 0.
|
||||
+ world.log_tick = 20;
|
||||
+ world.set(10, 100, 2, BlockStateId(STONE)).unwrap();
|
||||
+ assert_eq!(world.block(10, 100, 2), BlockStateId(AIR), "not shown");
|
||||
+ assert!(
|
||||
+ matches!(
|
||||
+ ray(&world, 2, &tables),
|
||||
+ Trace::Hit {
|
||||
+ block: [10, 100, 2],
|
||||
+ ..
|
||||
+ }
|
||||
+ ),
|
||||
+ "a change behind the view is the real block"
|
||||
+ );
|
||||
+ assert_ne!(world.mod_changes.take(), (Vec::new(), false));
|
||||
+ assert_eq!(world.live_revision, live_revision + 1);
|
||||
+ // Seeking about changes nothing else either.
|
||||
+ assert!(world.view_log(None, usize::MAX, None));
|
||||
+ assert_eq!(world.mod_changes.take(), (Vec::new(), false));
|
||||
+ assert_eq!(world.live_revision, live_revision + 1);
|
||||
+ // The film ends: the picture is the real world again, and so are both flights.
|
||||
+ world.log = None;
|
||||
+ assert_eq!(world.block(10, 100, 0), BlockStateId(AIR));
|
||||
+ assert_eq!(world.block(10, 100, 2), BlockStateId(STONE));
|
||||
+ assert_eq!(ray(&world, 0, &tables), cleared);
|
||||
+ assert!(matches!(
|
||||
+ ray(&world, 2, &tables),
|
||||
+ Trace::Hit {
|
||||
+ block: [10, 100, 2],
|
||||
+ ..
|
||||
+ }
|
||||
+ ));
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn a_ground_query_reads_the_real_blocks() {
|
||||
+ let mut world = walled();
|
||||
+ let opaque = |s: BlockStateId| s.0 != AIR;
|
||||
+ assert_eq!(world.motion_blocking(10, 0, opaque), 101);
|
||||
+ world.log = Some(WorldLog::new(1, 0));
|
||||
+ world.log_tick = 10;
|
||||
+ world.set(10, 100, 0, BlockStateId(AIR)).unwrap();
|
||||
+ assert_eq!(world.live_motion_blocking(10, 0, opaque), 71);
|
||||
+ world.view_log(Some(0), 100, None);
|
||||
+ assert_eq!(world.motion_blocking(10, 0, opaque), 101, "the picture");
|
||||
+ assert_eq!(world.live_motion_blocking(10, 0, opaque), 71, "the world");
|
||||
+ // A column of the same chunk with no displaced block reads the same height either way.
|
||||
+ assert_eq!(world.motion_blocking(5, 0, opaque), 71);
|
||||
+ assert_eq!(world.live_motion_blocking(5, 0, opaque), 71);
|
||||
+ world.view_log(None, usize::MAX, None);
|
||||
+ assert_eq!(world.motion_blocking(10, 0, opaque), 71);
|
||||
+ assert_eq!(world.live_motion_blocking(10, 0, opaque), 71);
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn a_server_chunk_replacement_refreshes_the_real_blocks_behind_the_picture() {
|
||||
+ let tables = tables();
|
||||
+ let mut world = walled();
|
||||
+ world.log = Some(WorldLog::new(1, 0));
|
||||
+ world.log_tick = 10;
|
||||
+ world.set(10, 100, 0, BlockStateId(AIR)).unwrap();
|
||||
+ world.view_log(Some(0), 100, None);
|
||||
+ assert_eq!(world.block(10, 100, 0), BlockStateId(STONE), "the old wall is shown");
|
||||
+ world.mod_changes.watching = true;
|
||||
+ let _ = world.mod_changes.take();
|
||||
+
|
||||
+ let mut replacement = Chunk::empty(0, 0);
|
||||
+ replacement.set(10, 100, 2, STONE);
|
||||
+ world.insert_chunk((0, 0), Arc::new(replacement));
|
||||
+ assert_eq!(world.live_block(10, 100, 0), BlockStateId(AIR));
|
||||
+ assert_eq!(world.live_block(10, 100, 2), BlockStateId(STONE));
|
||||
+ assert_eq!(world.block(10, 100, 0), BlockStateId(STONE), "the picture is unchanged");
|
||||
+ assert!(matches!(ray(&world, 2, &tables), Trace::Hit { block: [10, 100, 2], .. }));
|
||||
+ assert_eq!(world.mod_changes.take().0.len(), crate::chunk::SECTIONS);
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn a_ray_into_an_unloaded_column_is_unknown() {
|
||||
+ let tables = tables();
|
||||
+ let world = walled();
|
||||
+ let mut probe = WorldProbe::new(&world, &tables.0, &tables.1, 0b001);
|
||||
+ assert_eq!(
|
||||
+ trace(&mut probe, [20.5, 100.5, 0.5], [40.5, 100.5, 0.5]),
|
||||
+ Trace::Unknown { known_to: 0.0 }
|
||||
+ );
|
||||
+ }
|
||||
+}
|
||||
--
|
||||
2.54.0 (Apple Git-157)
|
||||
|
||||
+927
@@ -0,0 +1,927 @@
|
||||
From b1dd9f55c1af556b95797e34211319909910ab49 Mon Sep 17 00:00:00 2001
|
||||
From: chexit <chexit@duck.com>
|
||||
Date: Sun, 1 Nov 2026 02:30:58 +0300
|
||||
Subject: [PATCH 2/2] Acoustics follows chunk residency and voice lifecycle
|
||||
(#110 #111 #112)
|
||||
|
||||
Co-Authored-By: Kimi <noreply@moonshot.ai>
|
||||
---
|
||||
crates/horizon-client/src/acoustics.rs | 480 +++++++++++++++++++-
|
||||
crates/horizon-client/src/chunk_map.rs | 97 +++-
|
||||
crates/horizon-client/src/game/acoustics.rs | 18 +-
|
||||
3 files changed, 574 insertions(+), 21 deletions(-)
|
||||
|
||||
diff --git a/crates/horizon-client/src/acoustics.rs b/crates/horizon-client/src/acoustics.rs
|
||||
index 7dd895d83..a5281d1b6 100644
|
||||
--- a/crates/horizon-client/src/acoustics.rs
|
||||
+++ b/crates/horizon-client/src/acoustics.rs
|
||||
@@ -13,13 +13,25 @@
|
||||
//! at a time, and applied a tick or two later. While a film is being made, everything is traced
|
||||
//! at once and under the same kind of budget (cells, never time), so the sound of a film does not
|
||||
//! depend on the speed of the machine. Results are cached by the cells (2 blocks) of the source
|
||||
-//! and the listener, and dropped when a block changes in a section a path passed through.
|
||||
+//! and the listener, and dropped when a block changes in a section a path passed through, or when
|
||||
+//! the chunk underneath them arrives, is replaced by a reload or goes away. A trace that met a
|
||||
+//! block nobody knows is marked so and is traced again once it is a bit old, so a wall that
|
||||
+//! streams in is found without anything else happening; answers that come back possibly after a
|
||||
+//! chunk moved are checked against that change and dropped when it was theirs.
|
||||
+//!
|
||||
+//! What the mixer is told is also scoped: a sound that leaves the acoustic range (beyond
|
||||
+//! [`RANGE`], too quiet to hear, or a world that is gone for a moment) is explicitly given the
|
||||
+//! plain numbers again — the air's absorption at its distance, no wall, no echoes, no reverb sends
|
||||
+//! — so what was once traced for it is not remembered for it; when it comes back, the current
|
||||
+//! geometry applies.
|
||||
//!
|
||||
//! Stage 2 adds echo taps for loud one-shots (`echo`): rays from the source and the listener find
|
||||
//! the walls, and each wall that is really there gives a copy of the sound delayed by the longer
|
||||
//! path. They are traced on the same worker, cached by the 1-block cells of the source and the
|
||||
//! listener, and handed to the mixer by [`Acoustics::take_echoes`]; only [`ECHO_VOICES`] sounds
|
||||
-//! at a time get them.
|
||||
+//! get them at once (the loudest that deserve them) — a sound that drops out of that set has its
|
||||
+//! taps recalled, which the mixer fades out over about 50 ms, so the taps actually sounding may
|
||||
+//! briefly reach another round of [`ECHO_VOICES`] while a rotation plays out.
|
||||
//!
|
||||
//! Stage 3 adds the reverb (`room`): rays from the listener (and from each echo source, in its
|
||||
//! echo trace) measure how enclosed, how large and how reflective the space is, which gives the
|
||||
@@ -39,7 +51,7 @@ pub use room::Room;
|
||||
use spr_occlusion::run_occlusion;
|
||||
|
||||
use crate::chunk::{Chunk, HEIGHT, MIN_Y};
|
||||
-use crate::fast_hash::FxHashMap;
|
||||
+use crate::fast_hash::{FxHashMap, FxHashSet};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc::{Receiver, Sender};
|
||||
@@ -61,9 +73,17 @@ const JOB_CELLS: usize = 400_000;
|
||||
const JOB_SOURCES: usize = 32;
|
||||
/// Sources that get the nine paths; the rest get one.
|
||||
const FULL_PATHS: usize = 16;
|
||||
+/// Ticks a trace that met unknown cells is kept before it is traced again: the snapshot then may
|
||||
+/// miss chunks that are not there yet, and they arrive on their own. A section change always
|
||||
+/// drops the trace at once; this only bounds how long a partial answer is mixed with.
|
||||
+const UNKNOWN_TICKS: u64 = 40;
|
||||
/// Cached estimates.
|
||||
const CACHE: usize = 4096;
|
||||
-/// Sounds that have echo taps at the same time (the loudest of those that deserve them).
|
||||
+/// Sounds that have echo taps at the same time (the loudest of those that deserve them). This is
|
||||
+/// the budget of the engine's work, not of the mixer's taps alone: a sound that leaves the set has
|
||||
+/// its taps recalled, which the mixer fades out over about 50 ms (about five mixer buffers), so
|
||||
+/// right after a full rotation up to twice this many taps are sounding, and within that fade the
|
||||
+/// steady number is `ECHO_VOICES` again.
|
||||
pub const ECHO_VOICES: usize = 8;
|
||||
/// Echo traces one worker job holds.
|
||||
const ECHO_JOB: usize = 4;
|
||||
@@ -100,6 +120,9 @@ pub struct Snapshot {
|
||||
pub reflect: Arc<Vec<f32>>,
|
||||
pub epoch: u32,
|
||||
pub revision: u64,
|
||||
+ /// The residency of the columns it was made from (`ChunkMap::content_revision`): a reload,
|
||||
+ /// an unload or a new column means the ranks' contents may differ from these `Arc`s.
|
||||
+ pub chunk_rev: u64,
|
||||
pub tick: u64,
|
||||
pub center: [f64; 3],
|
||||
}
|
||||
@@ -177,6 +200,10 @@ pub struct Changes {
|
||||
pub epoch: u32,
|
||||
pub overflow: bool,
|
||||
pub sections: Vec<(i32, i32, i32)>,
|
||||
+ /// What the resident chunks held (`ChunkMap::content_revision`): when it moves, a worker job
|
||||
+ /// made from the snapshot before it applies to chunks that may be gone, and its answers are
|
||||
+ /// dropped. The `sections` of the same change still drop the individual cached estimates.
|
||||
+ pub residency: u64,
|
||||
}
|
||||
|
||||
type Cell = (i32, i32, i32);
|
||||
@@ -187,6 +214,11 @@ struct Entry {
|
||||
/// The box (in blocks) the paths lay in.
|
||||
min: [i32; 3],
|
||||
max: [i32; 3],
|
||||
+ /// The tick it was traced at, so a trace that met unknown cells (see
|
||||
+ /// [`UNKNOWN_TICKS`]) is not kept for ever.
|
||||
+ born: u64,
|
||||
+ /// The walk met blocks nobody knows (a chunk the snapshot is missing).
|
||||
+ unk: bool,
|
||||
used: u64,
|
||||
}
|
||||
impl Entry {
|
||||
@@ -206,12 +238,16 @@ struct EchoEntry {
|
||||
room: Room,
|
||||
min: [i32; 3],
|
||||
max: [i32; 3],
|
||||
+ born: u64,
|
||||
+ unk: bool,
|
||||
used: u64,
|
||||
}
|
||||
/// The space round the listener's block.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct RoomEntry {
|
||||
room: Room,
|
||||
+ born: u64,
|
||||
+ unk: bool,
|
||||
used: u64,
|
||||
}
|
||||
/// The box a room measure from `cell` looked in.
|
||||
@@ -270,7 +306,7 @@ struct Done {
|
||||
seq: u64,
|
||||
entries: Vec<(Key, Entry)>,
|
||||
echoes: Vec<(Key, EchoEntry, u64)>,
|
||||
- rooms: Vec<(Cell, Room)>,
|
||||
+ rooms: Vec<(Cell, Room, bool)>,
|
||||
cells: usize,
|
||||
unknown: usize,
|
||||
}
|
||||
@@ -294,7 +330,15 @@ fn trace_echo(geometry: &dyn Geometry, key: Key, budget: &mut usize, clock: u64)
|
||||
let m = room::measure(geometry, centre(key.0), &mut room_budget);
|
||||
let us = start.elapsed().as_micros() as u64;
|
||||
(
|
||||
- EchoEntry { taps: t.taps, room: m.room, min: t.min, max: t.max, used: clock },
|
||||
+ EchoEntry {
|
||||
+ taps: t.taps,
|
||||
+ room: m.room,
|
||||
+ min: t.min,
|
||||
+ max: t.max,
|
||||
+ born: clock,
|
||||
+ unk: t.unknown + m.unknown > 0,
|
||||
+ used: clock,
|
||||
+ },
|
||||
t.cells + m.cells,
|
||||
t.unknown + m.unknown,
|
||||
us,
|
||||
@@ -320,6 +364,8 @@ fn trace(geometry: &dyn Geometry, listener: [f64; 3], at: [f64; 3], paths: usize
|
||||
paths: paths as u8,
|
||||
min: [lo(0), lo(1), lo(2)],
|
||||
max: [hi(0), hi(1), hi(2)],
|
||||
+ born: 0,
|
||||
+ unk: unknown > 0,
|
||||
used: 0,
|
||||
},
|
||||
before - *budget,
|
||||
@@ -334,6 +380,12 @@ pub struct Acoustics {
|
||||
cache: HashMap<Key, Entry>,
|
||||
clock: u64,
|
||||
applied: HashMap<u32, Applied>,
|
||||
+ /// The sounds that were in the acoustic range at the last step (with the geometry present),
|
||||
+ /// so one that leaves it (beyond `RANGE`, inaudible, or the world gone) is told so plainly.
|
||||
+ scoped: FxHashSet<u32>,
|
||||
+ /// The residency (`Changes::residency`) the last step saw: worker jobs made before a change
|
||||
+ /// are dropped (`floor`) when it moves.
|
||||
+ residency: Option<u64>,
|
||||
log: std::collections::VecDeque<(u64, Cell)>,
|
||||
seq: u64,
|
||||
/// Jobs up to this number belong to a world that is gone.
|
||||
@@ -360,6 +412,8 @@ impl Acoustics {
|
||||
cache: HashMap::new(),
|
||||
clock: 0,
|
||||
applied: HashMap::new(),
|
||||
+ scoped: FxHashSet::default(),
|
||||
+ residency: None,
|
||||
log: Default::default(),
|
||||
seq: 0,
|
||||
floor: 0,
|
||||
@@ -381,6 +435,8 @@ impl Acoustics {
|
||||
pub fn reset(&mut self) {
|
||||
self.cache.clear();
|
||||
self.applied.clear();
|
||||
+ self.scoped.clear();
|
||||
+ self.residency = None;
|
||||
self.echo_cache.clear();
|
||||
self.echo_applied.clear();
|
||||
self.echo_pending.clear();
|
||||
@@ -427,7 +483,7 @@ impl Acoustics {
|
||||
let m = room::measure(&*job.geometry, centre(cell), &mut b);
|
||||
cells += m.cells;
|
||||
unknown += m.unknown;
|
||||
- rooms.push((cell, m.room));
|
||||
+ rooms.push((cell, m.room, m.unknown > 0));
|
||||
}
|
||||
if done_tx.send(Done { seq: job.seq, entries, echoes, rooms, cells, unknown }).is_err() {
|
||||
break;
|
||||
@@ -453,6 +509,7 @@ impl Acoustics {
|
||||
self.floor = self.seq;
|
||||
self.in_flight = None;
|
||||
self.applied.clear();
|
||||
+ self.scoped.clear();
|
||||
return;
|
||||
}
|
||||
for &s in &changes.sections {
|
||||
@@ -473,6 +530,7 @@ impl Acoustics {
|
||||
|
||||
fn insert(&mut self, key: Key, mut entry: Entry) {
|
||||
entry.used = self.clock;
|
||||
+ entry.born = self.clock;
|
||||
self.cache.insert(key, entry);
|
||||
if self.cache.len() > CACHE {
|
||||
let mut ages: Vec<u64> = self.cache.values().map(|e| e.used).collect();
|
||||
@@ -484,6 +542,9 @@ impl Acoustics {
|
||||
|
||||
fn insert_echo(&mut self, key: Key, mut entry: EchoEntry) {
|
||||
entry.used = self.clock;
|
||||
+ if entry.born == 0 {
|
||||
+ entry.born = self.clock;
|
||||
+ }
|
||||
self.echo_cache.insert(key, entry);
|
||||
if self.echo_cache.len() > ECHO_CACHE {
|
||||
let mut ages: Vec<u64> = self.echo_cache.values().map(|e| e.used).collect();
|
||||
@@ -510,6 +571,14 @@ impl Acoustics {
|
||||
) -> Vec<Applied> {
|
||||
self.clock += 1;
|
||||
self.invalidate(changes);
|
||||
+ // The resident chunks changed: a job traced from the snapshot before them applies to
|
||||
+ // chunks that may be gone, so its answers are dropped with the old residency's answers.
|
||||
+ if self.residency != Some(changes.residency) {
|
||||
+ self.residency = Some(changes.residency);
|
||||
+ self.seq += 1;
|
||||
+ self.floor = self.seq;
|
||||
+ self.in_flight = None;
|
||||
+ }
|
||||
// The worker's results; one that began before a change in its box is not kept.
|
||||
if let Some((_, rx)) = &self.worker {
|
||||
let done: Vec<Done> = rx.try_iter().collect();
|
||||
@@ -535,13 +604,16 @@ impl Acoustics {
|
||||
self.insert_echo(key, e);
|
||||
}
|
||||
}
|
||||
- for (cell, room) in d.rooms {
|
||||
+ for (cell, room, unknown) in d.rooms {
|
||||
let (lo, hi) = room_box(cell);
|
||||
self.stats.room_traces += 1;
|
||||
if self.log.iter().any(|(s, c)| *s >= d.seq && box_touches(lo, hi, *c)) {
|
||||
self.stats.dropped_late += 1;
|
||||
} else {
|
||||
- self.room_cache.insert(cell, RoomEntry { room, used: self.clock });
|
||||
+ self.room_cache.insert(
|
||||
+ cell,
|
||||
+ RoomEntry { room, born: self.clock, unk: unknown, used: self.clock },
|
||||
+ );
|
||||
}
|
||||
}
|
||||
for (key, e) in d.entries {
|
||||
@@ -562,8 +634,11 @@ impl Acoustics {
|
||||
self.applied.retain(|id, _| sources.iter().any(|s| s.id == *id));
|
||||
self.sends_applied.retain(|id, _| sources.iter().any(|s| s.id == *id));
|
||||
self.echo_applied.retain(|id, _| sources.iter().any(|s| s.id == *id));
|
||||
+ // A sound that left the acoustic range no longer holds what it was once told: the mixer
|
||||
+ // gets the plain numbers for it (and no taps, no sends), instead of its last wall.
|
||||
+ let mut told = self.settle_scope(sources, &live, listener, geometry.is_none());
|
||||
let Some(geometry) = geometry else {
|
||||
- return self.settle(&live, listener, None);
|
||||
+ return told;
|
||||
};
|
||||
// The loudest first; ties by id, so the order never depends on a hash.
|
||||
let mut order: Vec<usize> = (0..live.len()).collect();
|
||||
@@ -577,7 +652,9 @@ impl Acoustics {
|
||||
let want = if rank < FULL_PATHS { 9 } else { 1 };
|
||||
if let Some(e) = self.cache.get_mut(&key) {
|
||||
e.used = self.clock;
|
||||
- if e.paths as usize >= want || e.paths == 9 {
|
||||
+ // A trace that met unknown cells is not kept for ever: a chunk may have arrived.
|
||||
+ let partial = e.unk && self.clock >= e.born + UNKNOWN_TICKS;
|
||||
+ if !partial && (e.paths as usize >= want || e.paths == 9) {
|
||||
self.stats.hits += 1;
|
||||
continue;
|
||||
}
|
||||
@@ -621,7 +698,8 @@ impl Acoustics {
|
||||
}
|
||||
}
|
||||
self.stats.cached = self.cache.len();
|
||||
- self.settle(&live, listener, Some(lcell))
|
||||
+ told.extend(self.settle(&live, listener, Some(lcell)));
|
||||
+ told
|
||||
}
|
||||
|
||||
/// Gives the loudest echo sources their taps from the cache, traces the missing ones at once
|
||||
@@ -638,10 +716,22 @@ impl Acoustics {
|
||||
}
|
||||
if served >= ECHO_VOICES {
|
||||
self.stats.echo_capped += 1;
|
||||
+ // It was served before (its taps are in the mixer): they are recalled, so the
|
||||
+ // cap holds on the taps that sound, not only on these traced just now.
|
||||
+ self.recall_echo(s.id);
|
||||
continue;
|
||||
}
|
||||
served += 1;
|
||||
let key = (block_of(s.at), lcell);
|
||||
+ // A trace that met unknown cells is not kept for ever: a chunk may have arrived
|
||||
+ // under it, and it is traced again like a missing one would be.
|
||||
+ if self
|
||||
+ .echo_cache
|
||||
+ .get(&key)
|
||||
+ .is_some_and(|e| e.unk && self.clock >= e.born + UNKNOWN_TICKS)
|
||||
+ {
|
||||
+ self.echo_cache.remove(&key);
|
||||
+ }
|
||||
if let Some(e) = self.echo_cache.get_mut(&key) {
|
||||
e.used = self.clock;
|
||||
self.stats.echo_hits += 1;
|
||||
@@ -677,24 +767,38 @@ impl Acoustics {
|
||||
}
|
||||
|
||||
/// The space the listener is in: from the cache, measured at once (a film) or asked of the
|
||||
- /// worker (the cell is returned). The last known space stays until the new one is.
|
||||
+ /// worker (the cell is returned). The last known space stays until the new one is. A measure
|
||||
+ /// that met unknown cells is not kept for ever: a chunk may have arrived under it.
|
||||
fn settle_room(&mut self, geometry: &dyn Geometry, listener: [f64; 3]) -> Vec<Cell> {
|
||||
let cell = block_of(listener);
|
||||
if let Some(e) = self.room_cache.get_mut(&cell) {
|
||||
e.used = self.clock;
|
||||
- self.stats.room_hits += 1;
|
||||
- self.room_now = Some(e.room);
|
||||
- } else if self.sync {
|
||||
+ if !(e.unk && self.clock >= e.born + UNKNOWN_TICKS) {
|
||||
+ self.stats.room_hits += 1;
|
||||
+ self.room_now = Some(e.room);
|
||||
+ return self.room_cache_tidy();
|
||||
+ }
|
||||
+ self.room_cache.remove(&cell);
|
||||
+ }
|
||||
+ if self.sync {
|
||||
let mut budget = ROOM_CELLS;
|
||||
let m = room::measure(geometry, centre(cell), &mut budget);
|
||||
self.stats.room_traces += 1;
|
||||
self.stats.room_cells += m.cells as u64;
|
||||
self.stats.unknown_cells += m.unknown as u64;
|
||||
- self.room_cache.insert(cell, RoomEntry { room: m.room, used: self.clock });
|
||||
+ self.room_cache.insert(
|
||||
+ cell,
|
||||
+ RoomEntry { room: m.room, born: self.clock, unk: m.unknown > 0, used: self.clock },
|
||||
+ );
|
||||
self.room_now = Some(m.room);
|
||||
} else {
|
||||
return vec![cell];
|
||||
}
|
||||
+ self.room_cache_tidy()
|
||||
+ }
|
||||
+
|
||||
+ /// Keeps the room cache bounded and carries the listener's space into the stats.
|
||||
+ fn room_cache_tidy(&mut self) -> Vec<Cell> {
|
||||
if self.room_cache.len() > ROOM_CACHE {
|
||||
let mut ages: Vec<u64> = self.room_cache.values().map(|e| e.used).collect();
|
||||
ages.sort_unstable();
|
||||
@@ -741,6 +845,76 @@ impl Acoustics {
|
||||
std::mem::take(&mut self.sends_pending)
|
||||
}
|
||||
|
||||
+ /// A sound that left the acoustic range is not traced any more, but what the mixer was told
|
||||
+ /// keeps playing: the sounds that just left the range (beyond [`RANGE`], too quiet to hear, or
|
||||
+ /// with the world gone for a step) are given the plain numbers again — the air's absorption
|
||||
+ /// and no wall — and their echo taps are recalled and their reverb sends to nothing. Nothing
|
||||
+ /// is kept for a sound the mixer never had numbers for.
|
||||
+ fn settle_scope(&mut self, sources: &[Source], live: &[Source], listener: [f64; 3], no_geometry: bool) -> Vec<Applied> {
|
||||
+ let mut out = Vec::new();
|
||||
+ let mut was = std::mem::take(&mut self.scoped);
|
||||
+ if no_geometry {
|
||||
+ // The world is gone for a step: nothing can be traced for the live ones either, so
|
||||
+ // the plain numbers stand for them until the world is read again.
|
||||
+ for s in live {
|
||||
+ if was.remove(&s.id) {
|
||||
+ let cutoff = AIR.powf(dist(s.at, listener) as f32);
|
||||
+ out.extend(self.unhold(s.id, 1.0, cutoff));
|
||||
+ }
|
||||
+ }
|
||||
+ } else {
|
||||
+ for s in live {
|
||||
+ was.remove(&s.id);
|
||||
+ }
|
||||
+ }
|
||||
+ // What is left are the sounds that left the range while the geometry was there: beyond
|
||||
+ // RANGE, or quieter than the ear hears. The air still takes the highs by the distance,
|
||||
+ // so the numbers continue the open air's numbers without the old wall.
|
||||
+ for s in sources {
|
||||
+ if !was.remove(&s.id) {
|
||||
+ continue;
|
||||
+ }
|
||||
+ let cutoff = AIR.powf(dist(s.at, listener) as f32);
|
||||
+ out.extend(self.unhold(s.id, 1.0, cutoff));
|
||||
+ }
|
||||
+ if !no_geometry {
|
||||
+ self.scoped.extend(live.iter().map(|s| s.id));
|
||||
+ }
|
||||
+ out
|
||||
+ }
|
||||
+
|
||||
+ /// Puts one sound's acoustics back to the plain numbers. The mixer hears them only when they
|
||||
+ /// differ; the echo taps are recalled (they fade out there) and the reverb send goes to
|
||||
+ /// nothing (it fades in the mixer too). Returns the numbers, if the mixer has to hear them.
|
||||
+ fn unhold(&mut self, id: u32, gain: f32, cutoff: f32) -> Option<Applied> {
|
||||
+ let out = self
|
||||
+ .applied
|
||||
+ .get(&id)
|
||||
+ .is_some_and(|p| {
|
||||
+ (p.gain - gain).abs() >= 0.002 || (p.cutoff - cutoff).abs() >= 0.002 * p.cutoff.max(0.01)
|
||||
+ })
|
||||
+ .then_some(Applied { id, gain, cutoff });
|
||||
+ if let Some(now) = out {
|
||||
+ self.applied.insert(id, now);
|
||||
+ }
|
||||
+ self.recall_echo(id);
|
||||
+ if self.sends_applied.get(&id).is_some_and(|s| s.iter().any(|v| v > &0.0)) {
|
||||
+ self.sends_applied.insert(id, [0.0; 4]);
|
||||
+ self.sends_pending.push((id, [0.0; 4]));
|
||||
+ self.stats.sends += 1;
|
||||
+ }
|
||||
+ out
|
||||
+ }
|
||||
+
|
||||
+ /// The echo taps of one sound are recalled (the mixer fades them out, so a tap that comes
|
||||
+ /// back a moment later picks up where it left off). A sound that had none gains none.
|
||||
+ fn recall_echo(&mut self, id: u32) {
|
||||
+ if self.echo_applied.get(&id).is_some_and(|t| !t.is_empty()) {
|
||||
+ self.echo_applied.insert(id, Vec::new());
|
||||
+ self.echo_pending.push((id, Vec::new()));
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
/// The numbers for each live source from the cache; only the changed ones are returned.
|
||||
fn settle(&mut self, live: &[Source], listener: [f64; 3], lcell: Option<Cell>) -> Vec<Applied> {
|
||||
let lcell = lcell.unwrap_or_else(|| cell_of(listener));
|
||||
@@ -1033,4 +1207,276 @@ mod tests {
|
||||
}
|
||||
panic!("the worker did not answer");
|
||||
}
|
||||
+
|
||||
+ /// A wall appears at x = 40..41 once `arrived` is set; while it is not, its columns are
|
||||
+ /// unknown to the walk (a chunk that is not resident yet), and open ground otherwise.
|
||||
+ struct Arriving {
|
||||
+ arrived: std::sync::atomic::AtomicU32,
|
||||
+ wall: std::ops::Range<i32>,
|
||||
+ }
|
||||
+ impl Geometry for Arriving {
|
||||
+ fn walker(&self) -> Box<dyn FnMut(i32, i32, i32) -> Option<f32> + '_> {
|
||||
+ let arrived = self.arrived.load(std::sync::atomic::Ordering::Relaxed);
|
||||
+ let wall = self.wall.clone();
|
||||
+ Box::new(move |x, _, _| match (arrived, wall.contains(&x)) {
|
||||
+ (0, true) => None,
|
||||
+ (1, true) => Some(1.0),
|
||||
+ _ => Some(0.0),
|
||||
+ })
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ /// (AirDef fork #110.) A wall streams in underneath a trace made while its columns were
|
||||
+ /// unknown: nothing invalidates the cache, but the unknown trace does not outlive it.
|
||||
+ #[test]
|
||||
+ fn an_unknown_trace_is_not_kept_and_is_traced_again_when_the_chunks_answer() {
|
||||
+ let concrete = Arc::new(Arriving { arrived: 0.into(), wall: 40..42 });
|
||||
+ let g: Arc<dyn Geometry> = concrete.clone();
|
||||
+ let mut a = Acoustics::new(true);
|
||||
+ let l = [0.5, 70.5, 0.5];
|
||||
+ let before = a.step(Some(&g), l, &[src(1, 90.5)], &Changes::default());
|
||||
+ assert!(before[0].cutoff > 0.5, "nothing is known yet: {before:?}");
|
||||
+ assert!(a.stats.unknown_cells > 0);
|
||||
+ concrete.arrived.store(1, std::sync::atomic::Ordering::Relaxed);
|
||||
+ // The partial answer is mixed with only for a bounded while.
|
||||
+ for _ in 1..UNKNOWN_TICKS {
|
||||
+ let out = a.step(Some(&g), l, &[src(1, 90.5)], &Changes::default());
|
||||
+ assert!(out.is_empty(), "coasting on the partial answer: {out:?}");
|
||||
+ }
|
||||
+ // Then it is traced again against the geometry that now knows the wall: muted.
|
||||
+ let after = a.step(Some(&g), l, &[src(1, 90.5)], &Changes::default());
|
||||
+ assert_eq!(after.len(), 1);
|
||||
+ assert!(after[0].cutoff < 0.01, "{after:?}");
|
||||
+ assert!(a.stats.traces >= 2);
|
||||
+ // And being out of partial answers, the cache answers again.
|
||||
+ assert!(a.step(Some(&g), l, &[src(1, 90.5)], &Changes::default()).is_empty());
|
||||
+ }
|
||||
+
|
||||
+ /// (AirDef fork #110.) The column is reloaded (a chunk packet replaces a loaded one) and
|
||||
+ /// then it goes away: the estimates traced through its sections are dropped both ways.
|
||||
+ #[test]
|
||||
+ fn a_reload_of_the_same_column_with_other_content_changes_the_sound() {
|
||||
+ let mut a = Acoustics::new(true);
|
||||
+ let open: Arc<dyn Geometry> = Arc::new(Arriving { arrived: 0.into(), wall: 0..0 });
|
||||
+ let l = [0.5, 70.5, 0.5];
|
||||
+ let first = a.step(Some(&open), l, &[src(1, 90.5)], &Changes::default());
|
||||
+ assert!(first[0].cutoff > 0.5, "{first:?}");
|
||||
+ // Reloaded with a wall in it: its section counts as changed, and the estimate traced
|
||||
+ // through it is not kept.
|
||||
+ let walled: Arc<dyn Geometry> = Arc::new(Arriving { arrived: 1.into(), wall: 40..42 });
|
||||
+ let reload = a.step(
|
||||
+ Some(&walled),
|
||||
+ l,
|
||||
+ &[src(1, 90.5)],
|
||||
+ &Changes { residency: 3, sections: vec![(2, 4, 0)], ..Default::default() },
|
||||
+ );
|
||||
+ assert!(reload[0].cutoff < 0.01, "{reload:?}");
|
||||
+ // Unloaded again: bright once more.
|
||||
+ let gone = a.step(
|
||||
+ Some(&open),
|
||||
+ l,
|
||||
+ &[src(1, 90.5)],
|
||||
+ &Changes { residency: 4, sections: vec![(2, 4, 0)], ..Default::default() },
|
||||
+ );
|
||||
+ assert!(gone[0].cutoff > 0.5, "{gone:?}");
|
||||
+ }
|
||||
+
|
||||
+ /// (AirDef fork #111.) A sound (or a listener) that walks out of the acoustic range gives
|
||||
+ /// up its old wall and takes the plain numbers of its new distance until it comes back.
|
||||
+ #[test]
|
||||
+ fn a_sound_that_leaves_the_range_lets_the_wall_go_and_comes_back_traced_anew() {
|
||||
+ let mut a = Acoustics::new(true);
|
||||
+ let wall = Wall::new(100..103, 1.0);
|
||||
+ let l = [0.5, 70.5, 0.5];
|
||||
+ let first = a.step(Some(&wall), l, &[src(1, 200.5)], &Changes::default());
|
||||
+ assert!(first[0].cutoff < 0.001, "{first:?}");
|
||||
+ // The same sound moves past the range: the wall it was behind stops applying.
|
||||
+ let far = a.step(Some(&wall), l, &[src(1, 700.5)], &Changes::default());
|
||||
+ assert_eq!(far.len(), 1);
|
||||
+ assert_eq!(far[0].gain, 1.0);
|
||||
+ assert!((far[0].cutoff - AIR.powf(700.0)).abs() < 1e-6, "{far:?}");
|
||||
+ // Already there: the mixer hears nothing new.
|
||||
+ assert!(a.step(Some(&wall), l, &[src(1, 700.5)], &Changes::default()).is_empty());
|
||||
+ // It walks back into the range and the actual wall applies again.
|
||||
+ let back = a.step(Some(&wall), l, &[src(1, 200.5)], &Changes::default());
|
||||
+ assert!(back[0].cutoff < 0.001 && (back[0].gain - 0.41).abs() < 0.01, "{back:?}");
|
||||
+ // A listener walking past the range falls back the same way.
|
||||
+ let away = a.step(Some(&wall), [800.5, 70.5, 0.5], &[src(1, 200.5)], &Changes::default());
|
||||
+ assert!((away[0].cutoff - AIR.powf(600.0)).abs() < 1e-6, "{away:?}");
|
||||
+ let here = a.step(Some(&wall), l, &[src(1, 200.5)], &Changes::default());
|
||||
+ assert!(here[0].cutoff < 0.001, "{here:?}");
|
||||
+ // One sound, one set of numbers: nothing piles up.
|
||||
+ assert_eq!(a.applied.len(), 1);
|
||||
+ }
|
||||
+
|
||||
+ /// (AirDef fork #111.) A sound the distance gain makes inaudible stops holding the wall.
|
||||
+ #[test]
|
||||
+ fn a_temporarily_inaudible_sound_goes_plain_and_gets_the_wall_back_when_loud() {
|
||||
+ let mut a = Acoustics::new(true);
|
||||
+ let wall = Wall::new(40..42, 1.0);
|
||||
+ let l = [0.5, 70.5, 0.5];
|
||||
+ a.step(Some(&wall), l, &[src(1, 90.5)], &Changes::default());
|
||||
+ let quiet = [Source { loud: 0.0001, ..src(1, 90.5) }];
|
||||
+ let plain = a.step(Some(&wall), l, &quiet, &Changes::default());
|
||||
+ assert_eq!(plain.len(), 1, "{plain:?}");
|
||||
+ assert_eq!(plain[0].gain, 1.0);
|
||||
+ assert!((plain[0].cutoff - AIR.powf(90.0)).abs() < 1e-6);
|
||||
+ let loud_again = a.step(Some(&wall), l, &[src(1, 90.5)], &Changes::default());
|
||||
+ assert!(loud_again[0].cutoff < 0.01, "{loud_again:?}");
|
||||
+ }
|
||||
+
|
||||
+ /// (AirDef fork #111.) A world that is gone for a step (no geometry to read) does not keep
|
||||
+ /// any sound's numbers beyond its last trace, and the real numbers apply when it returns.
|
||||
+ #[test]
|
||||
+ fn a_world_that_is_gone_for_a_step_lets_every_sound_go_until_it_can_be_read() {
|
||||
+ let mut a = Acoustics::new(true);
|
||||
+ let wall = Wall::new(100..103, 1.0);
|
||||
+ let l = [0.5, 70.5, 0.5];
|
||||
+ let muted = a.step(Some(&wall), l, &[src(1, 200.5)], &Changes::default());
|
||||
+ assert!(muted[0].cutoff < 0.001, "{muted:?}");
|
||||
+ // No geometry: the plain numbers, and nothing gets traced.
|
||||
+ let plain = a.step(None, l, &[src(1, 200.5)], &Changes::default());
|
||||
+ assert_eq!(plain.len(), 1);
|
||||
+ assert_eq!(plain[0].gain, 1.0);
|
||||
+ assert!((plain[0].cutoff - AIR.powf(200.0)).abs() < 1e-6);
|
||||
+ assert!(a.step(None, l, &[src(1, 200.5)], &Changes::default()).is_empty(), "no repeats");
|
||||
+ assert_eq!(a.stats.traces, 1, "nothing was traced without the geometry");
|
||||
+ // The world is back: the actual numbers apply again.
|
||||
+ let back = a.step(Some(&wall), l, &[src(1, 200.5)], &Changes::default());
|
||||
+ assert!(back[0].cutoff < 0.001 && (back[0].gain - 0.41).abs() < 0.01, "{back:?}");
|
||||
+ assert_eq!(a.applied.len(), 1);
|
||||
+ }
|
||||
+
|
||||
+ /// (AirDef fork #111.) An echo sound out of the range recalls its taps (an empty set, which
|
||||
+ /// the mixer fades out) and takes the current geometry's taps when it comes back.
|
||||
+ #[test]
|
||||
+ fn an_echo_sound_leaving_the_range_recalls_its_taps_and_takes_them_back() {
|
||||
+ let mut a = Acoustics::new(true);
|
||||
+ let g = gorge(true);
|
||||
+ a.step(Some(&g), LISTENER, &[shot(1, 0.5)], &Changes::default());
|
||||
+ assert_eq!(a.take_echoes().len(), 1, "served once");
|
||||
+ a.take_sends();
|
||||
+ assert_eq!(a.echo_applied.len(), 1);
|
||||
+ assert_eq!(a.echo_applied[&1].len(), 2);
|
||||
+ a.step(Some(&g), LISTENER, &[shot(1, 700.5)], &Changes::default());
|
||||
+ assert_eq!(a.take_echoes(), [(1, Vec::new())], "recalled");
|
||||
+ a.take_sends();
|
||||
+ // Nothing more while it stays out.
|
||||
+ a.step(Some(&g), LISTENER, &[shot(1, 700.5)], &Changes::default());
|
||||
+ assert!(a.take_echoes().is_empty() && a.take_sends().is_empty());
|
||||
+ // Back in range: the current taps apply again.
|
||||
+ a.step(Some(&g), LISTENER, &[shot(1, 0.5)], &Changes::default());
|
||||
+ assert_eq!(a.echo_applied[&1].len(), 2);
|
||||
+ assert_eq!(a.echo_applied.len(), 1, "one sound, one record");
|
||||
+ }
|
||||
+
|
||||
+ /// (AirDef fork #111.) A sound out of the range stops its reverb send explicitly.
|
||||
+ #[test]
|
||||
+ fn a_sound_leaving_the_range_sends_nothing_to_the_reverb_until_it_returns() {
|
||||
+ let mut a = Acoustics::new(true);
|
||||
+ let inside = [12.5, 64.5, 12.5];
|
||||
+ let source = Source { id: 1, at: [12.5, 64.5, 18.5], loud: 0.5, echo: true };
|
||||
+ a.step(Some(&hall()), inside, &[source], &Changes::default());
|
||||
+ assert!(!a.take_sends().is_empty(), "the hall sends");
|
||||
+ // Far away: the send goes to nothing explicitly (the mixer fades it out).
|
||||
+ let far = Source { at: [700.5, 64.5, 12.5], ..source };
|
||||
+ a.step(Some(&hall()), inside, &[far], &Changes::default());
|
||||
+ assert_eq!(a.take_sends(), [(1, [0.0; 4])]);
|
||||
+ // Already nothing: no repeats.
|
||||
+ assert!(a.step(Some(&hall()), inside, &[far], &Changes::default()).is_empty());
|
||||
+ // Back in the hall: its sends apply again.
|
||||
+ a.step(Some(&hall()), inside, &[source], &Changes::default());
|
||||
+ let again = a.take_sends();
|
||||
+ assert_eq!(again.len(), 1);
|
||||
+ assert!(again[0].1.iter().any(|v| *v > 0.0), "{again:?}");
|
||||
+ }
|
||||
+
|
||||
+ /// (AirDef fork #112.) Rotating the loudest ECHO_VOICES around: the voices that leave the
|
||||
+ /// budget have their taps recalled, so the budget holds on the taps that sound.
|
||||
+ #[test]
|
||||
+ fn the_echo_budget_recalls_the_taps_of_the_voices_that_leave_it() {
|
||||
+ let mut a = Acoustics::new(true);
|
||||
+ let rocks: Vec<Source> = (0..16).map(|i| shot(i, f64::from(i) * 1.5 + 0.5)).collect();
|
||||
+ a.step(Some(&gorge(true)), LISTENER, &rocks, &Changes::default());
|
||||
+ a.take_echoes();
|
||||
+ // Equal loudnesses: the first eight ids take the budget, each with taps.
|
||||
+ assert_eq!(a.echo_applied.len(), 8);
|
||||
+ assert_eq!(a.echo_applied[&0].len(), 2);
|
||||
+ // Now the even ids are louder: they take the budget, the odd ones' taps are recalled.
|
||||
+ let swapped: Vec<Source> = (0..16)
|
||||
+ .map(|i| Source { loud: if i % 2 == 0 { 0.9 } else { 0.1 }, ..shot(i, f64::from(i) * 1.5 + 0.5) })
|
||||
+ .collect();
|
||||
+ a.step(Some(&gorge(true)), LISTENER, &swapped, &Changes::default());
|
||||
+ let told = a.take_echoes();
|
||||
+ assert_eq!(
|
||||
+ told.iter().filter(|(_, t)| t.is_empty()).map(|(id, _)| *id).collect::<Vec<_>>(),
|
||||
+ [1, 3, 5, 7],
|
||||
+ "the recalled voices",
|
||||
+ );
|
||||
+ assert_eq!(
|
||||
+ told.iter().filter(|(_, t)| !t.is_empty()).map(|(id, _)| *id).collect::<Vec<_>>(),
|
||||
+ [8, 10, 12, 14],
|
||||
+ "the new voices",
|
||||
+ );
|
||||
+ // Exactly the cap holds on the voices that carry taps, through the rotation.
|
||||
+ assert_eq!(a.echo_applied.iter().filter(|(_, t)| !t.is_empty()).count(), ECHO_VOICES);
|
||||
+ assert_eq!(a.echo_applied.iter().filter(|(_, t)| t.is_empty()).count(), 4);
|
||||
+ // And rotating back does not pile anything up.
|
||||
+ a.step(Some(&gorge(true)), LISTENER, &rocks, &Changes::default());
|
||||
+ a.take_echoes();
|
||||
+ assert_eq!(a.echo_applied.iter().filter(|(_, t)| !t.is_empty()).count(), ECHO_VOICES);
|
||||
+ assert_eq!(a.echo_applied.len(), 12);
|
||||
+ assert_eq!(a.stats.echo_capped, 24);
|
||||
+ }
|
||||
+
|
||||
+ /// A geometry whose walk is slow, so that a worker job can be watched without a race.
|
||||
+ struct Slow(std::ops::Range<i32>);
|
||||
+ impl Geometry for Slow {
|
||||
+ fn walker(&self) -> Box<dyn FnMut(i32, i32, i32) -> Option<f32> + '_> {
|
||||
+ Box::new(move |x, _, _| {
|
||||
+ std::hint::black_box(
|
||||
+ (0..3_000).fold(1u64, |s, i| s.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(i)),
|
||||
+ );
|
||||
+ Some(if self.0.contains(&x) { 1.0 } else { 0.0 })
|
||||
+ })
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ /// (AirDef fork #110.) A worker job that traced the snapshot before the resident chunks
|
||||
+ /// changed is dropped as a late answer; the job made after the change applies.
|
||||
+ #[test]
|
||||
+ fn an_answer_made_from_the_old_residency_is_dropped_and_the_new_one_applies() {
|
||||
+ let mut a = Acoustics::new(false);
|
||||
+ let slow: Arc<dyn Geometry> = Arc::new(Slow(40..42));
|
||||
+ let l = [0.5, 70.5, 0.5];
|
||||
+ let s = [src(1, 90.5)];
|
||||
+ a.step(Some(&slow), l, &s, &Changes::default());
|
||||
+ // The one-path estimate goes to the worker for its nine paths; before the answer lands,
|
||||
+ // the resident columns change: its answer is dropped with the old residency's answers.
|
||||
+ a.step(Some(&slow), l, &s, &Changes { residency: 1, ..Default::default() });
|
||||
+ let after = Changes { residency: 7, ..Default::default() };
|
||||
+ for _ in 0..200 {
|
||||
+ a.step(None, l, &s, &after);
|
||||
+ if a.stats.jobs >= 1 && a.stats.dropped_late > 0 {
|
||||
+ break;
|
||||
+ }
|
||||
+ std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
+ }
|
||||
+ assert!(a.stats.dropped_late >= 1, "the job was not dropped: {:?}", &a.stats);
|
||||
+ assert_eq!(a.cache.len(), 1, "only the game thread's own estimate is cached");
|
||||
+ assert_eq!(a.cache.values().next().unwrap().paths, 1, "the worker's refined answer never landed");
|
||||
+ // The next job, made after the change, is kept. Wait for its actual result rather than
|
||||
+ // for the number of unrelated echo/room jobs that happened to finish first.
|
||||
+ a.step(Some(&slow), l, &s, &after);
|
||||
+ for _ in 0..400 {
|
||||
+ a.step(None, l, &s, &after);
|
||||
+ if a.cache.values().next().is_some_and(|e| e.paths == 9) {
|
||||
+ break;
|
||||
+ }
|
||||
+ std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
+ }
|
||||
+ assert!(a.stats.jobs >= 2);
|
||||
+ assert_eq!(a.cache.len(), 1, "the new residency's answer is cached");
|
||||
+ assert_eq!(a.cache.values().next().unwrap().paths, 9, "it refined to nine paths");
|
||||
+ }
|
||||
}
|
||||
diff --git a/crates/horizon-client/src/chunk_map.rs b/crates/horizon-client/src/chunk_map.rs
|
||||
index fddded9e1..a53ffda5e 100644
|
||||
--- a/crates/horizon-client/src/chunk_map.rs
|
||||
+++ b/crates/horizon-client/src/chunk_map.rs
|
||||
@@ -1,7 +1,9 @@
|
||||
-//! Resident chunk membership, with a token for consumers that cache its keys.
|
||||
-use crate::{chunk::Chunk, fast_hash::FxHashMap};
|
||||
+//! Resident chunk membership, with a token for consumers that cache its keys and the columns
|
||||
+//! whose residency changed (AirDef fork #110: the acoustics must hear that too).
|
||||
+use crate::{chunk::Chunk, fast_hash::{FxHashMap, FxHashSet}};
|
||||
use std::{
|
||||
collections::hash_map::{Iter, ValuesMut},
|
||||
+ collections::VecDeque,
|
||||
ops::Deref,
|
||||
sync::{
|
||||
Arc,
|
||||
@@ -16,18 +18,31 @@ fn next_revision() -> u64 {
|
||||
NEXT_REVISION.fetch_add(1, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
+/// Columns kept in the changed log past this many of them: everything counts as changed, then.
|
||||
+const CHANGE_CAP: usize = 256;
|
||||
/// Read access behaves like a map. Structural writes are explicit so edits to
|
||||
/// blocks or light don't invalidate consumers of the loaded chunk key set.
|
||||
/// Tokens are process-wide: replacing the entire map also invalidates caches.
|
||||
pub struct ChunkMap {
|
||||
columns: Columns,
|
||||
revision: u64,
|
||||
+ /// Bumped by every change of what the columns hold: an insertion (new or
|
||||
+ /// replacing a loaded one) and a removal. Edits through `get_mut` are
|
||||
+ /// block writes, which the world reports by itself.
|
||||
+ content: u64,
|
||||
+ /// The columns whose residency changed since `take_changed` last read,
|
||||
+ /// in the order they changed, up to [`CHANGE_CAP`] of them.
|
||||
+ changed: VecDeque<Key>,
|
||||
+ changed_dropped: bool,
|
||||
}
|
||||
impl Default for ChunkMap {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
columns: Columns::default(),
|
||||
revision: next_revision(),
|
||||
+ content: next_revision(),
|
||||
+ changed: VecDeque::default(),
|
||||
+ changed_dropped: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,17 +50,41 @@ impl ChunkMap {
|
||||
pub fn membership_revision(&self) -> u64 {
|
||||
self.revision
|
||||
}
|
||||
+ /// What the columns hold, not just which of them are resident: a consumer
|
||||
+ /// that keeps chunk contents behind `Arc`s (the acoustics' snapshot) must
|
||||
+ /// be made again when this moves.
|
||||
+ pub fn content_revision(&self) -> u64 {
|
||||
+ self.content
|
||||
+ }
|
||||
+ /// The columns whose residency changed since the last call, and whether
|
||||
+ /// changes were dropped (every column counts as changed, then).
|
||||
+ pub fn take_changed(&mut self) -> (FxHashSet<Key>, bool) {
|
||||
+ let dropped = std::mem::take(&mut self.changed_dropped);
|
||||
+ let changed = self.changed.drain(..).collect();
|
||||
+ (changed, dropped)
|
||||
+ }
|
||||
+ fn changed_column(&mut self, key: Key) {
|
||||
+ if self.changed.len() >= CHANGE_CAP {
|
||||
+ self.changed_dropped = true;
|
||||
+ self.changed.clear();
|
||||
+ }
|
||||
+ self.changed.push_back(key);
|
||||
+ }
|
||||
pub fn insert(&mut self, key: Key, chunk: Arc<Chunk>) -> Option<Arc<Chunk>> {
|
||||
let previous = self.columns.insert(key, chunk);
|
||||
+ self.content = next_revision();
|
||||
if previous.is_none() {
|
||||
self.revision = next_revision();
|
||||
}
|
||||
+ self.changed_column(key);
|
||||
previous
|
||||
}
|
||||
pub fn remove(&mut self, key: &Key) -> Option<Arc<Chunk>> {
|
||||
let previous = self.columns.remove(key);
|
||||
if previous.is_some() {
|
||||
self.revision = next_revision();
|
||||
+ self.content = next_revision();
|
||||
+ self.changed_column(*key);
|
||||
}
|
||||
previous
|
||||
}
|
||||
@@ -53,6 +92,9 @@ impl ChunkMap {
|
||||
if !self.columns.is_empty() {
|
||||
self.columns.clear();
|
||||
self.revision = next_revision();
|
||||
+ self.content = next_revision();
|
||||
+ self.changed_dropped = true;
|
||||
+ self.changed.clear();
|
||||
}
|
||||
}
|
||||
pub fn get_mut(&mut self, key: &Key) -> Option<&mut Arc<Chunk>> {
|
||||
@@ -122,4 +164,55 @@ mod tests {
|
||||
map = ChunkMap::default();
|
||||
assert_ne!(cleared, map.membership_revision());
|
||||
}
|
||||
+
|
||||
+ #[test]
|
||||
+ fn insertions_replacements_and_removals_change_the_content_token_and_are_reported() {
|
||||
+ let mut map = ChunkMap::default();
|
||||
+ let chunk = Arc::new(Chunk::empty(0, 0));
|
||||
+ let (changed, dropped) = map.take_changed();
|
||||
+ assert!(changed.is_empty() && !dropped);
|
||||
+ // An insertion is reported once.
|
||||
+ map.insert((0, 0), chunk.clone());
|
||||
+ let content = map.content_revision();
|
||||
+ let membership = map.membership_revision();
|
||||
+ let had_it = map.take_changed();
|
||||
+ assert_eq!(had_it.0.len(), 1);
|
||||
+ assert!(had_it.0.contains(&(0, 0)));
|
||||
+ // A replacement (a reload with other content): the key set is the
|
||||
+ // same, what the column holds is not.
|
||||
+ let mut other = Chunk::empty(0, 0);
|
||||
+ other.set(0, 0, 0, 9);
|
||||
+ let reload = map.insert((0, 0), Arc::new(other)).is_some();
|
||||
+ assert!(reload);
|
||||
+ assert_eq!(membership, map.membership_revision(), "the keys did not move");
|
||||
+ assert_ne!(content, map.content_revision(), "the content did");
|
||||
+ let reloaded = map.take_changed();
|
||||
+ assert_eq!(reloaded.0.len(), 1);
|
||||
+ assert!(reloaded.0.contains(&(0, 0)));
|
||||
+ // A removal is reported; reads of an idle map report nothing.
|
||||
+ assert!(map.remove(&(0, 0)).is_some());
|
||||
+ let removed = map.take_changed();
|
||||
+ assert_eq!(removed.0.len(), 1);
|
||||
+ assert!(removed.0.contains(&(0, 0)));
|
||||
+ let (idle, dropped) = map.take_changed();
|
||||
+ assert!(idle.is_empty() && !dropped, "{dropped}");
|
||||
+ // Endless change stays bounded: the drop says everything counts.
|
||||
+ for x in 0..1_000 {
|
||||
+ map.insert((x % 5, 0), chunk.clone());
|
||||
+ }
|
||||
+ let (_, dropped) = map.take_changed();
|
||||
+ assert!(dropped);
|
||||
+ // Idle again; a clear of a loaded map says so.
|
||||
+ let (empty, dropped) = map.take_changed();
|
||||
+ assert!(empty.is_empty() && !dropped);
|
||||
+ let was = map.content_revision();
|
||||
+ map.clear();
|
||||
+ let (_, dropped) = map.take_changed();
|
||||
+ assert!(dropped, "a clear loses every column");
|
||||
+ assert_ne!(was, map.content_revision());
|
||||
+ // A clear of an idle map is idle.
|
||||
+ map.clear();
|
||||
+ let (empty, dropped) = map.take_changed();
|
||||
+ assert!(empty.is_empty() && !dropped);
|
||||
+ }
|
||||
}
|
||||
diff --git a/crates/horizon-client/src/game/acoustics.rs b/crates/horizon-client/src/game/acoustics.rs
|
||||
index fe2c26de5..ddaa85a0e 100644
|
||||
--- a/crates/horizon-client/src/game/acoustics.rs
|
||||
+++ b/crates/horizon-client/src/game/acoustics.rs
|
||||
@@ -60,13 +60,16 @@ impl Game<'_> {
|
||||
(table, reflect)
|
||||
}
|
||||
|
||||
- /// The snapshot of the chunks round the listener, made again when a block changed or the
|
||||
- /// listener went far from where it was made.
|
||||
+ /// The snapshot of the chunks round the listener, made again when a block changed, the
|
||||
+ /// resident columns arrived, were replaced or went away (AirDef fork #110), or the listener
|
||||
+ /// went far from where it was made.
|
||||
fn acoustic_snapshot(&mut self) -> Arc<Snapshot> {
|
||||
let at = self.audio.listener;
|
||||
+ let chunk_rev = self.world.chunks.content_revision();
|
||||
if let Some(s) = &self.mods.acoustic.snapshot
|
||||
&& s.epoch == self.world.epoch
|
||||
&& s.revision == self.world.revision
|
||||
+ && s.chunk_rev == chunk_rev
|
||||
&& (s.center[0] - at[0]).abs() < 96.0
|
||||
&& (s.center[2] - at[2]).abs() < 96.0
|
||||
{
|
||||
@@ -87,6 +90,7 @@ impl Game<'_> {
|
||||
reflect,
|
||||
epoch: self.world.epoch,
|
||||
revision: self.world.revision,
|
||||
+ chunk_rev,
|
||||
tick: self.ticks as u64,
|
||||
center: at,
|
||||
});
|
||||
@@ -101,6 +105,15 @@ impl Game<'_> {
|
||||
return;
|
||||
}
|
||||
self.world.sound_changes.watching = true;
|
||||
+ // The columns whose residency changed (a chunk arrived, was replaced by a reload or is
|
||||
+ // gone) count as changed sections for the acoustics (AirDef fork #110).
|
||||
+ let (columns, dropped) = self.world.chunks.take_changed();
|
||||
+ for (x, z) in columns {
|
||||
+ self.world.sound_changes.column(x, z);
|
||||
+ }
|
||||
+ if dropped {
|
||||
+ self.world.sound_changes.overflow();
|
||||
+ }
|
||||
if !self.audio.acoustics_wanted() {
|
||||
return;
|
||||
}
|
||||
@@ -109,6 +122,7 @@ impl Game<'_> {
|
||||
epoch: self.world.epoch,
|
||||
overflow,
|
||||
sections,
|
||||
+ residency: self.world.chunks.content_revision(),
|
||||
};
|
||||
let geometry: Arc<dyn Geometry> = self.acoustic_snapshot();
|
||||
self.audio.tick_acoustics(Some(&geometry), &changes);
|
||||
--
|
||||
2.54.0 (Apple Git-157)
|
||||
|
||||
Reference in New Issue
Block a user