Sunsets, volumetric clouds and fog in HD (fork patch 23, #53); missiles and drones collide with the world through new world queries (patch 24, API level 12; #42, #43); a direct hit destroys a system, strikes scatter by kind with a small miss chance (#49, #59)
build / mod (push) Successful in 3m24s
build / mod (push) Successful in 3m24s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -28,7 +28,72 @@ impl MissileKind {
|
||||
}
|
||||
}
|
||||
|
||||
/// A strike that ends farther than this from its aim point misses (the lethal radius of a point target).
|
||||
pub(super) const MISS_RADIUS: f64 = 3.0;
|
||||
/// A system's hull, as a cylinder: its radius (× scale) and how far above the ground it reaches (× scale).
|
||||
const HULL_RADIUS: f64 = 2.2;
|
||||
const HULL_TOP: f64 = 3.0;
|
||||
|
||||
impl DroneKind {
|
||||
/// Strike accuracy: the CEP (blocks; half the strikes land within it, the scatter is Rayleigh)
|
||||
/// and the share of strikes with a rare gross navigation fault, which lands beyond `MISS_RADIUS`.
|
||||
pub(super) fn accuracy(self) -> (f64, f64) {
|
||||
match self {
|
||||
DroneKind::Shahed => (1.2, 0.03),
|
||||
DroneKind::Geran3 => (1.0, 0.03),
|
||||
DroneKind::Lancet => (0.8, 0.02),
|
||||
DroneKind::Gerbera => (1.5, 0.04),
|
||||
DroneKind::Kh101 => (1.3, 0.05),
|
||||
DroneKind::Kalibr => (1.3, 0.05),
|
||||
DroneKind::Kh22 => (1.6, 0.06),
|
||||
DroneKind::Zircon => (1.5, 0.06),
|
||||
DroneKind::Iskander => (1.4, 0.06),
|
||||
DroneKind::Kinzhal => (1.5, 0.06),
|
||||
// The bus and its blocks: the blocks are aimed by the split, so only the bus's own error applies.
|
||||
DroneKind::Oreshnik | DroneKind::OreshnikBlock | DroneKind::OreshnikSub => (1.6, 0.08),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Sim {
|
||||
/// The aim error of a new strike: drawn once from the seed, the drone keeps it for its whole flight.
|
||||
pub(super) fn aim_error(&mut self, kind: DroneKind) -> DVec3 {
|
||||
let (cep, gross) = kind.accuracy();
|
||||
let angle = self.rng.f() * std::f64::consts::TAU;
|
||||
let r = if self.rng.chance(gross) {
|
||||
MISS_RADIUS + cep * (0.5 + 2.5 * self.rng.f())
|
||||
} else {
|
||||
// Rayleigh with its median at the CEP.
|
||||
let u = 1.0 - self.rng.f();
|
||||
cep * (-2.0 * u.ln() / (2.0 * std::f64::consts::LN_2)).sqrt()
|
||||
};
|
||||
DVec3::new(angle.cos() * r, 0.0, angle.sin() * r)
|
||||
}
|
||||
|
||||
/// An armed warhead reached `pos` (its last step was `vel`): a system whose hull it swept through is
|
||||
/// destroyed at once, whatever the blast would have done to it. A near miss is only splash.
|
||||
pub(super) fn direct_hit(&mut self, pos: DVec3, vel: DVec3, tnt: u32, out: &mut Out) {
|
||||
if !self.damage || tnt == 0 {
|
||||
return;
|
||||
}
|
||||
let from = pos - vel;
|
||||
for i in 0..self.sams.len() {
|
||||
let sam = &self.sams[i];
|
||||
if !sam.alive() {
|
||||
continue;
|
||||
}
|
||||
let s = sam.kind.spec().scale;
|
||||
let hit = (0..=8).any(|k| {
|
||||
let p = from.lerp(pos, k as f64 / 8.0);
|
||||
let across = DVec3::new(p.x - sam.pos.x, 0.0, p.z - sam.pos.z).length();
|
||||
across <= HULL_RADIUS * s && p.y >= sam.pos.y - 1.0 && p.y <= sam.pos.y + HULL_TOP * s
|
||||
});
|
||||
if hit {
|
||||
self.destroy(i, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A blast of `power` (0 to 4) at `pos`: the systems and objects round it take damage.
|
||||
pub(super) fn blast_damage(&mut self, pos: DVec3, power: usize, out: &mut Out) {
|
||||
let (reach, hit) = (REACH[power], HIT[power]);
|
||||
|
||||
@@ -19,6 +19,7 @@ mod logistics;
|
||||
mod orders;
|
||||
mod units;
|
||||
mod why;
|
||||
pub mod world;
|
||||
#[cfg(test)]
|
||||
mod regress;
|
||||
pub use ew::EW_RADIUS;
|
||||
@@ -211,6 +212,8 @@ pub struct Ground {
|
||||
asked: std::collections::HashSet<(i32, i32)>,
|
||||
/// The tick of the last full clean-up (a big cache would otherwise be scanned on every answer).
|
||||
swept: u64,
|
||||
/// The blocks themselves (issues #42, #43): what stops a flight.
|
||||
pub world: world::WorldCache,
|
||||
}
|
||||
|
||||
/// Ticks between full clean-ups of a big ground cache.
|
||||
@@ -251,10 +254,32 @@ impl Ground {
|
||||
self.asked.clear();
|
||||
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).
|
||||
pub fn sweep(&mut self, a: DVec3, b: DVec3, skip_start: bool, now: u64) -> world::Sweep {
|
||||
self.world.sweep(a, b, skip_start, now)
|
||||
}
|
||||
/// Has the sections along a flight read before it gets there.
|
||||
pub fn ahead(&mut self, pos: DVec3, vel: DVec3, ticks: f64, now: u64) {
|
||||
self.world.look_ahead(pos, vel, ticks, now);
|
||||
}
|
||||
/// Whether `pos` is in the land by the column's height (`below`, as `at` gave it), given what the sweep
|
||||
/// of this step saw: over blocks known and open, the height only counts where its top block is known
|
||||
/// to be open, a fluid's surface (not a roof or a bridge deck above the flight, nor a block unread).
|
||||
pub fn ground_hit(&mut self, below: Option<f64>, pos: DVec3, offset: f64, sweep: &world::Sweep, now: u64) -> bool {
|
||||
let Some(g) = below else { return false };
|
||||
if pos.y > g + offset {
|
||||
return false;
|
||||
}
|
||||
match sweep {
|
||||
world::Sweep::Clear => self.world.is_known_open(pos.x.floor() as i32, g.floor() as i32 - 1, pos.z.floor() as i32, now),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
/// Explosions change the land: forget what was known round them.
|
||||
fn forget(&mut self, at: DVec3, radius: i32) {
|
||||
let (cx, cz) = (at.x.floor() as i32, at.z.floor() as i32);
|
||||
self.known.retain(|&(x, z), _| (x - cx).abs() > radius || (z - cz).abs() > radius);
|
||||
self.world.touched(at, f64::from(radius) + 2.0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1172,6 +1197,8 @@ pub struct Sim {
|
||||
pub tick: u64,
|
||||
pub kills: u32,
|
||||
pub hits: u32,
|
||||
/// Drones that struck the land or a building short of their aim.
|
||||
pub crashes: u32,
|
||||
pub launched: u32,
|
||||
/// Explosions damage the land (primed TNT through commands).
|
||||
pub damage: bool,
|
||||
@@ -1225,6 +1252,7 @@ impl Sim {
|
||||
tick: 0,
|
||||
kills: 0,
|
||||
hits: 0,
|
||||
crashes: 0,
|
||||
launched: 0,
|
||||
damage: true,
|
||||
shader: false,
|
||||
@@ -1289,6 +1317,8 @@ impl Sim {
|
||||
fn add_drone(&mut self, kind: DroneKind, from: DVec3, dir: DVec3, target: DVec3) {
|
||||
let id = self.id();
|
||||
let spec = kind.spec();
|
||||
// Its navigation error: it flies to, and strikes at, a point off the aim it was given.
|
||||
let target = target + self.aim_error(kind);
|
||||
let (vel, flight) = if spec.ballistic.is_some() {
|
||||
// An arc from `from` to `target` at the kind's horizontal speed.
|
||||
let flat = horizontal(target - from);
|
||||
@@ -1373,7 +1403,7 @@ impl Sim {
|
||||
self.update_sight(ground);
|
||||
self.step_lights(out);
|
||||
self.step_sams(out);
|
||||
self.step_missiles(out);
|
||||
self.step_missiles(ground, out);
|
||||
self.step_fx(ground, out);
|
||||
self.draw_targets(out);
|
||||
self.step_wrecks(out);
|
||||
@@ -1394,10 +1424,14 @@ impl Sim {
|
||||
// Warheads that reached their aim (for the replays): drone, kind, where, TNT; and splits.
|
||||
let mut impacts: Vec<(u32, DroneKind, DVec3, u32)> = Vec::new();
|
||||
let mut splits: Vec<(u32, DVec3)> = Vec::new();
|
||||
// Drones that struck the land or a building short of their aim: drone, kind, where, TNT.
|
||||
let mut crashes: Vec<(u32, DroneKind, DVec3, u32)> = Vec::new();
|
||||
for d in &mut self.drones {
|
||||
d.age += 1;
|
||||
let spec = d.kind.spec();
|
||||
let below = ground.at(d.pos, now);
|
||||
let from = d.pos;
|
||||
ground.ahead(d.pos, d.vel, 20.0, now);
|
||||
// Near its aim it looks at the land there again: a platform or hilltop blown away
|
||||
// meanwhile, it goes for what is left below, not for the air where it stood.
|
||||
if d.flight != Flight::Falling
|
||||
@@ -1412,11 +1446,15 @@ impl Sim {
|
||||
d.vel *= 0.985;
|
||||
d.spin += 0.35;
|
||||
d.pos += d.vel;
|
||||
let sweep = ground.sweep(from, d.pos, d.age <= 3, now);
|
||||
if let Some((_, p)) = sweep.hit() {
|
||||
d.pos = p;
|
||||
}
|
||||
if self.rng.chance(0.5) {
|
||||
out.particles("minecraft:large_smoke", d.pos, 0.2, DVec3::new(0.0, 0.05, 0.0), 0.02, 1);
|
||||
}
|
||||
out.particles("minecraft:flame", d.pos, 0.25, DVec3::ZERO, 0.02, 2);
|
||||
if below.is_some_and(|g| d.pos.y <= g + 0.3) || d.age > 600 {
|
||||
if sweep.hit().is_some() || ground.ground_hit(below, d.pos, 0.3, &sweep, now) || d.age > 600 {
|
||||
// The wreck's warhead may still go off where it lands.
|
||||
let warhead = if spec.decoy || !self.rng.chance(0.35) { 0 } else { spec.warhead.min(2) };
|
||||
boom.push((d.pos, warhead, true));
|
||||
@@ -1439,13 +1477,24 @@ impl Sim {
|
||||
d.vel = turn(d.vel, d.target - d.pos, spec.turn) * sp;
|
||||
}
|
||||
d.pos += d.vel;
|
||||
let sweep = ground.sweep(from, d.pos, d.age <= 3, now);
|
||||
if let Some((_, p)) = sweep.hit() {
|
||||
d.pos = p;
|
||||
}
|
||||
let speed = d.vel.length();
|
||||
let landed = sweep.hit().is_some() || ground.ground_hit(below, d.pos, 0.2, &sweep, now);
|
||||
let hit = d.pos.distance(d.target) < speed.max(2.0)
|
||||
|| below.is_some_and(|g| d.pos.y <= g + 0.2)
|
||||
|| landed
|
||||
|| (d.vel.y < 0.0 && d.pos.y < d.target.y - 1.0 && horizontal(d.target - d.pos).length() < speed * 2.0)
|
||||
|| d.age > 4000;
|
||||
if hit {
|
||||
boom.push((d.pos, spec.warhead, false));
|
||||
// Into the land or a building short of its aim: a crash, not a hit.
|
||||
if landed && d.pos.distance(d.target) >= speed.max(2.0) + 6.0 {
|
||||
crashes.push((d.id, d.kind, d.pos, spec.warhead));
|
||||
removed.push(d.id);
|
||||
continue;
|
||||
}
|
||||
impacts.push((d.id, d.kind, d.pos, spec.warhead));
|
||||
removed.push(d.id);
|
||||
self.hits += 1;
|
||||
@@ -1546,10 +1595,22 @@ impl Sim {
|
||||
let speed = if d.flight == Flight::Dive { spec.speed * 1.35 } else { spec.speed };
|
||||
d.vel = new * speed;
|
||||
d.pos += d.vel;
|
||||
let sweep = ground.sweep(from, d.pos, d.age <= 3, now);
|
||||
if let Some((_, p)) = sweep.hit() {
|
||||
d.pos = p;
|
||||
}
|
||||
let at_target = d.pos.distance(d.target) < speed.max(1.5);
|
||||
let in_ground = below.is_some_and(|g| d.pos.y <= g + 0.2);
|
||||
let in_ground = sweep.hit().is_some() || ground.ground_hit(below, d.pos, 0.2, &sweep, now);
|
||||
if at_target || in_ground || d.age > 8000 {
|
||||
boom.push((d.pos, spec.warhead, spec.decoy));
|
||||
// Into the land or a building short of its aim: a crash, not a hit.
|
||||
if in_ground && d.pos.distance(d.target) >= speed.max(1.5) + 3.0 {
|
||||
if !spec.decoy {
|
||||
crashes.push((d.id, d.kind, d.pos, spec.warhead));
|
||||
}
|
||||
removed.push(d.id);
|
||||
continue;
|
||||
}
|
||||
if !spec.decoy {
|
||||
impacts.push((d.id, d.kind, d.pos, spec.warhead));
|
||||
}
|
||||
@@ -1580,6 +1641,17 @@ impl Sim {
|
||||
for (drone, pos) in splits {
|
||||
self.log(pos, record::EventKind::Split { drone });
|
||||
}
|
||||
for (drone, kind, pos, tnt) in crashes {
|
||||
self.crashes += 1;
|
||||
let power = match tnt {
|
||||
0 => 0,
|
||||
1 | 2 => 1,
|
||||
3..=5 => 2,
|
||||
6 | 7 => 3,
|
||||
_ => 4,
|
||||
};
|
||||
self.log(pos, record::EventKind::Crash { drone, kind, power });
|
||||
}
|
||||
for (drone, kind, pos, tnt) in impacts {
|
||||
if let Some(sector) = self.drones.iter().find(|x| x.id == drone).map(|x| x.sector as usize) {
|
||||
self.learn(sector, false);
|
||||
@@ -1594,6 +1666,8 @@ impl Sim {
|
||||
let object = self.targets.iter().position(|t| t.distance(pos) < 16.0);
|
||||
let sam = self.sams.iter().enumerate().find(|(_, s)| s.alive() && s.pos.distance(pos) < 12.0).map(|(i, s)| (s.kind, i));
|
||||
self.log(pos, record::EventKind::Hit { drone, kind, power, object, sam });
|
||||
let vel = self.drones.iter().find(|x| x.id == drone).map_or(DVec3::ZERO, |x| x.vel);
|
||||
self.direct_hit(pos, vel, tnt, out);
|
||||
}
|
||||
for (pos, warhead, small) in boom {
|
||||
self.explode(pos, warhead, small, ground, player, out);
|
||||
@@ -2061,9 +2135,11 @@ impl Sim {
|
||||
|
||||
// ------------------------------------------------ interceptors
|
||||
|
||||
fn step_missiles(&mut self, out: &mut Out) {
|
||||
fn step_missiles(&mut self, ground: &mut Ground, out: &mut Out) {
|
||||
let now = self.tick;
|
||||
let mut done: Vec<(u32, Option<u32>, bool, u32)> = Vec::new(); // (missile, target, kill, sam)
|
||||
let (mut missed, mut expired, mut orphaned) = (0u32, 0u32, 0u32);
|
||||
let mut blocked = 0u32;
|
||||
let sams_fit: HashMap<u32, f64> = self.sams.iter().map(|s| (s.id, s.fitness())).collect();
|
||||
for m in &mut self.missiles {
|
||||
m.age += 1;
|
||||
@@ -2091,13 +2167,16 @@ impl Sim {
|
||||
let before = m.pos;
|
||||
m.vel = new * speed;
|
||||
m.pos += m.vel;
|
||||
// The first block on the way this tick; a fuse that goes off earlier along the way still counts.
|
||||
ground.ahead(m.pos, m.vel, 10.0, now);
|
||||
let world = ground.sweep(before, m.pos, m.age <= 12, now).hit();
|
||||
if let Some(t) = target {
|
||||
// Closest approach this tick, both moving (fast targets cross a fuse in a tick).
|
||||
let rel0 = (t.pos - t.vel) - before;
|
||||
let rel1 = t.pos - m.pos;
|
||||
let delta = rel1 - rel0;
|
||||
let k = (-rel0.dot(delta) / delta.length_squared().max(1e-9)).clamp(0.0, 1.0);
|
||||
if (rel0 + delta * k).length() < spec.fuse {
|
||||
if (rel0 + delta * k).length() < spec.fuse && world.is_none_or(|(w, _)| k <= w) {
|
||||
// A target faster than the interceptor is hard to hit.
|
||||
let ratio = (spec.speed / t.vel.length().max(0.1)).min(1.0).powf(1.5);
|
||||
let fit = sams_fit.get(&m.sam).copied().unwrap_or(1.0);
|
||||
@@ -2107,6 +2186,13 @@ impl Sim {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if let Some((_, p)) = world {
|
||||
// The land or a building is in the way: the interceptor is lost there.
|
||||
m.pos = p;
|
||||
blocked += 1;
|
||||
done.push((m.id, None, false, m.sam));
|
||||
continue;
|
||||
}
|
||||
if m.age > spec.life || (target.is_none() && m.age > 30) {
|
||||
// Its target gone (shot down by another, or lost), or its life spent chasing one.
|
||||
if target.is_none() {
|
||||
@@ -2151,6 +2237,7 @@ impl Sim {
|
||||
t.missed += missed;
|
||||
t.expired += expired;
|
||||
t.orphaned += orphaned;
|
||||
t.blocked += blocked;
|
||||
});
|
||||
for (mid, target, kill, sam) in done {
|
||||
if let Some(i) = self.missiles.iter().position(|m| m.id == mid) {
|
||||
|
||||
@@ -39,6 +39,8 @@ pub enum EventKind {
|
||||
SamLost { sam: u32, kind: SamKind, index: usize },
|
||||
/// The Oreshnik's bus or a block splitting.
|
||||
Split { drone: u32 },
|
||||
/// A drone's warhead went off against the land or a building short of its aim.
|
||||
Crash { drone: u32, kind: DroneKind, power: u32 },
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -61,6 +63,8 @@ pub struct Tally {
|
||||
pub tracks_lost: u32,
|
||||
/// Times a system ran dry and began waiting for a reload truck.
|
||||
pub ammo_waits: u32,
|
||||
/// Interceptors lost against the land or a building on their way.
|
||||
pub blocked: u32,
|
||||
}
|
||||
|
||||
impl Tally {
|
||||
@@ -71,6 +75,7 @@ impl Tally {
|
||||
orphaned: self.orphaned.saturating_sub(start.orphaned),
|
||||
tracks_lost: self.tracks_lost.saturating_sub(start.tracks_lost),
|
||||
ammo_waits: self.ammo_waits.saturating_sub(start.ammo_waits),
|
||||
blocked: self.blocked.saturating_sub(start.blocked),
|
||||
}
|
||||
}
|
||||
/// The non-zero counts as a line, or nothing.
|
||||
@@ -81,6 +86,7 @@ impl Tally {
|
||||
(self.orphaned, "ракет остались без цели"),
|
||||
(self.tracks_lost, "потерь трека"),
|
||||
(self.ammo_waits, "ожиданий БК"),
|
||||
(self.blocked, "ракет разбились о препятствие"),
|
||||
]
|
||||
.into_iter()
|
||||
.filter(|p| p.0 > 0)
|
||||
@@ -312,7 +318,7 @@ impl Sim {
|
||||
}
|
||||
let size = match e.kind {
|
||||
EventKind::Kill { .. } => 3.5,
|
||||
EventKind::Hit { power, .. } => [2.5, 4.5, 7.0, 10.0, 13.0][(power as usize).min(4)],
|
||||
EventKind::Hit { power, .. } | EventKind::Crash { power, .. } => [2.5, 4.5, 7.0, 10.0, 13.0][(power as usize).min(4)],
|
||||
EventKind::SamLost { .. } => 8.0,
|
||||
EventKind::Split { .. } => 2.0,
|
||||
};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Regression tests for the issues filed on Gitea (each names its issue).
|
||||
use super::*;
|
||||
use super::raid::Grid;
|
||||
use super::damage::MISS_RADIUS;
|
||||
|
||||
// #1: [bug] Запросы рельефа голодают: часть направлений РЛС никогда не получает высоты
|
||||
#[test]
|
||||
@@ -222,3 +223,281 @@ fn drive_arrives_without_overshoot() {
|
||||
assert!(left.abs() < 1e-9 && vel == 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
// #49: a direct hit by an armed drone destroys the system at once, not with a dent of its health
|
||||
#[test]
|
||||
fn armed_strike_on_a_system_destroys_it_at_once() {
|
||||
let centre = DVec3::new(0.0, 70.0, 0.0);
|
||||
let hull = 2.2 * SamKind::Patriot.spec().scale;
|
||||
for kind in [DroneKind::Lancet, DroneKind::Shahed] {
|
||||
let mut destroyed = 0;
|
||||
for seed in 1..=40 {
|
||||
let mut sim = Sim::new(seed);
|
||||
let id = sim.id();
|
||||
sim.sams.push(Sam::new(id, SamKind::Patriot, centre, 0.0));
|
||||
let mut ground = Ground::default();
|
||||
sim.add_drone(kind, DVec3::new(0.0, 120.0, 0.0), DVec3::NEG_Y, centre);
|
||||
let mut out = Out::default();
|
||||
let mut impact = None;
|
||||
for _ in 0..400 {
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
if let Some(b) = sim.blasts.first() {
|
||||
impact = Some(b.at);
|
||||
break;
|
||||
}
|
||||
if sim.drones.is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let at = impact.expect("the strike must go off");
|
||||
let inside = DVec3::new(at.x, 0.0, at.z).distance(DVec3::new(centre.x, 0.0, centre.z)) <= hull && at.y < centre.y + 3.0;
|
||||
let dead = !sim.sams[0].alive();
|
||||
if inside {
|
||||
assert!(dead, "{kind:?} seed {seed} struck the hull at {at:?} but the system lives");
|
||||
}
|
||||
destroyed += dead as u32;
|
||||
}
|
||||
assert!(destroyed >= 30, "{kind:?}: only {destroyed}/40 direct strikes destroyed the system");
|
||||
}
|
||||
}
|
||||
|
||||
// #49: a near miss is only splash, an unarmed body is no direct hit, the top of the hull counts
|
||||
#[test]
|
||||
fn near_miss_and_unarmed_body_are_not_direct_hits() {
|
||||
let mut sim = Sim::new(1);
|
||||
let id = sim.id();
|
||||
sim.sams.push(Sam::new(id, SamKind::Patriot, DVec3::new(0.0, 70.0, 0.0), 0.0));
|
||||
let down = DVec3::new(0.0, -2.0, 0.0);
|
||||
sim.direct_hit(DVec3::new(6.0, 71.0, 0.0), down, 3, &mut Out::default());
|
||||
assert!(sim.sams[0].alive(), "a near miss six blocks off destroyed the system");
|
||||
sim.direct_hit(DVec3::new(0.0, 71.0, 0.0), down, 0, &mut Out::default());
|
||||
assert!(sim.sams[0].alive(), "an unarmed body destroyed the system");
|
||||
sim.direct_hit(DVec3::new(0.0, 73.0, 0.0), down, 1, &mut Out::default());
|
||||
assert!(!sim.sams[0].alive(), "an armed warhead into the top of the hull did not destroy the system");
|
||||
}
|
||||
|
||||
// #59: a strike misses at a small, kind-specific rate; its scatter is the kind's CEP (half land within it)
|
||||
#[test]
|
||||
fn strike_scatter_matches_each_kinds_cep_and_miss_rate() {
|
||||
const N: u64 = 5000;
|
||||
for kind in DroneKind::ALL {
|
||||
let mut sim = Sim::new(7);
|
||||
let (cep, gross) = kind.accuracy();
|
||||
let sigma = cep / (2.0 * std::f64::consts::LN_2).sqrt();
|
||||
let expected = (1.0 - gross) * (-MISS_RADIUS * MISS_RADIUS / (2.0 * sigma * sigma)).exp() + gross;
|
||||
let (mut misses, mut within, mut farthest) = (0u64, 0u64, 0.0f64);
|
||||
for _ in 0..N {
|
||||
let e = sim.aim_error(kind);
|
||||
assert_eq!(e.y, 0.0);
|
||||
let r = e.length();
|
||||
within += (r <= cep) as u64;
|
||||
if r > MISS_RADIUS {
|
||||
misses += 1;
|
||||
farthest = farthest.max(r);
|
||||
}
|
||||
}
|
||||
let rate = misses as f64 / N as f64;
|
||||
let half = within as f64 / N as f64;
|
||||
assert!((rate - expected).abs() < 0.015, "{kind:?}: miss rate {rate:.4}, expected {expected:.4}");
|
||||
assert!((0.005..=0.20).contains(&rate), "{kind:?}: miss rate {rate:.4} is not a small share (the IRBM bus is the loosest)");
|
||||
assert!((half - 0.5 * (1.0 - gross)).abs() < 0.03, "{kind:?}: {half:.3} of strikes within the CEP {cep}");
|
||||
assert!(farthest < MISS_RADIUS + 4.0 * cep, "{kind:?}: a miss {farthest:.2} blocks out, far from the aim");
|
||||
}
|
||||
}
|
||||
|
||||
// #59: the drone flies to its own error point and bursts there: the miss lands near the aim, by the CEP
|
||||
#[test]
|
||||
fn strikes_burst_near_their_aim_within_the_kinds_cep() {
|
||||
let aim = DVec3::new(0.0, 70.0, 0.0);
|
||||
for kind in [DroneKind::Shahed, DroneKind::Lancet] {
|
||||
let cep = kind.accuracy().0;
|
||||
let mut misses = 0;
|
||||
for seed in 1..=60 {
|
||||
let mut sim = Sim::new(seed);
|
||||
let mut ground = Ground::default();
|
||||
sim.add_drone(kind, DVec3::new(0.0, 120.0, 0.0), DVec3::NEG_Y, aim);
|
||||
let mut out = Out::default();
|
||||
let mut impact = None;
|
||||
for _ in 0..400 {
|
||||
sim.step(&mut ground, None, &mut out);
|
||||
if let Some(b) = sim.blasts.first() {
|
||||
impact = Some(b.at);
|
||||
break;
|
||||
}
|
||||
if sim.drones.is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let at = impact.expect("the strike must go off");
|
||||
let off = DVec3::new(at.x - aim.x, 0.0, at.z - aim.z).length();
|
||||
assert!(off < MISS_RADIUS + 4.0 * cep + 2.0, "{kind:?} seed {seed} burst {off:.2} blocks from its aim");
|
||||
misses += (off > MISS_RADIUS) as u32;
|
||||
}
|
||||
assert!(misses <= 6, "{kind:?}: {misses}/60 strikes missed");
|
||||
}
|
||||
}
|
||||
|
||||
// ---- #42, #43: flights are swept against the blocks of the world (a synthetic world stands in for the game)
|
||||
|
||||
/// Blocks from a function: `Some(solid)`, or `None` where there is no chunk.
|
||||
struct Blocks<F: Fn(i32, i32, i32) -> Option<bool>>(F);
|
||||
impl<F: Fn(i32, i32, i32) -> Option<bool>> world::WorldSource for Blocks<F> {
|
||||
fn solid(&self, x: i32, y: i32, z: i32) -> Option<bool> {
|
||||
(self.0)(x, y, z)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the sections a flight along `a` to `b` needs, as the game would answer them over a few ticks.
|
||||
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 wanted = ground.world.take_wanted(0);
|
||||
ground.world.serve(src, wanted, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// One tick of the drones with the game answering what was asked.
|
||||
fn fly(sim: &mut Sim, ground: &mut Ground, src: &dyn world::WorldSource) {
|
||||
sim.tick += 1;
|
||||
sim.step_drones(ground, None, &mut Out::default());
|
||||
let wanted = ground.world.take_wanted(sim.tick);
|
||||
ground.world.serve(src, wanted, sim.tick);
|
||||
}
|
||||
|
||||
// #42: a drone that crosses a one-block wall in a tick explodes at the wall, and that is no hit on its aim
|
||||
#[test]
|
||||
fn fast_drone_must_not_cross_a_one_block_wall() {
|
||||
let src = Blocks(|x, y, z| Some(y < 64 || (x == 3 && (64..141).contains(&y) && z.abs() < 50)));
|
||||
let mut sim = Sim::new(1);
|
||||
sim.damage = false;
|
||||
let mut ground = Ground::default();
|
||||
sim.add_drone(DroneKind::Zircon, DVec3::new(0.0, 100.0, 0.0), DVec3::X, DVec3::new(1000.0, 100.0, 0.0));
|
||||
sim.drones[0].flight = Flight::Dive;
|
||||
warm(&mut ground, &src, DVec3::new(0.0, 100.0, 0.0), DVec3::new(30.0, 100.0, 0.0));
|
||||
fly(&mut sim, &mut ground, &src);
|
||||
assert!(sim.drones.is_empty(), "crossed the wall in one tick");
|
||||
let at = sim.blasts.first().expect("no blast").at;
|
||||
assert!((at.x - 3.0).abs() < 0.05 && (at.y - 100.0).abs() < 1.5, "burst at {at:?}, not at the wall face x=3");
|
||||
assert_eq!((sim.crashes, sim.hits), (1, 0), "a wall in the way is a crash, not a hit on the aim");
|
||||
assert!(sim.replays.iter().chain(sim.rec.iter()).all(|r| r.events.iter().all(|e| !matches!(e.kind, record::EventKind::Hit { .. }))));
|
||||
}
|
||||
|
||||
// #42: a drone flying into a hill side explodes at the face of the hill
|
||||
#[test]
|
||||
fn drone_flying_into_a_hill_explodes_at_its_face() {
|
||||
// Flat at 64 to x=50, then a slope of 1:1.
|
||||
let height = |x: i32| 64 + (x - 50).max(0);
|
||||
let src = Blocks(move |x, y, _| Some(y < height(x)));
|
||||
for kind in [DroneKind::Shahed, DroneKind::Zircon] {
|
||||
let mut sim = Sim::new(3);
|
||||
sim.damage = false;
|
||||
let mut ground = Ground::default();
|
||||
sim.add_drone(kind, DVec3::new(0.0, 80.0, 0.0), DVec3::X, DVec3::new(600.0, 80.0, 0.0));
|
||||
sim.drones[0].flight = Flight::Dive;
|
||||
for _ in 0..300 {
|
||||
if sim.drones.is_empty() {
|
||||
break;
|
||||
}
|
||||
fly(&mut sim, &mut ground, &src);
|
||||
}
|
||||
assert!(sim.drones.is_empty(), "{kind:?} flew on");
|
||||
let at = sim.blasts.first().expect("no blast").at;
|
||||
// The slope meets y=80 at x=66.
|
||||
assert!(at.x > 62.0 && at.x < 67.5, "{kind:?} burst at {at:?}, not at the hill face (x~66)");
|
||||
assert_eq!(sim.crashes, 1, "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
// #42: an interceptor cannot pass through a wall to its target, and does not kill it from behind the wall
|
||||
#[test]
|
||||
fn missile_cannot_pass_through_a_wall() {
|
||||
let src = Blocks(|x, y, z| Some(y < 64 || (x == 3 && (64..141).contains(&y) && z.abs() < 50)));
|
||||
let mut sim = Sim::new(1);
|
||||
let mut ground = Ground::default();
|
||||
// The target stands still just behind the wall, inside the fuse's reach.
|
||||
sim.add_drone(DroneKind::Shahed, DVec3::new(8.5, 100.0, 0.0), DVec3::ZERO, DVec3::new(0.0, 100.0, 900.0));
|
||||
sim.drones[0].vel = DVec3::ZERO;
|
||||
sim.drones[0].engaged = 1;
|
||||
let (target, id) = (sim.drones[0].id, sim.id());
|
||||
sim.missiles.push(Missile { id, kind: MissileKind::Pac3, pos: DVec3::new(0.0, 100.0, 0.0), vel: DVec3::X * 3.0, target, sam: 0, age: 20 });
|
||||
warm(&mut ground, &src, DVec3::new(0.0, 100.0, 0.0), DVec3::new(30.0, 100.0, 0.0));
|
||||
sim.tick = 1;
|
||||
sim.step_missiles(&mut ground, &mut Out::default());
|
||||
assert!(sim.missiles.is_empty(), "the missile is still flying");
|
||||
assert_eq!(sim.kills, 0, "a kill through the wall");
|
||||
assert!(sim.drones[0].alive(), "the target died behind the wall");
|
||||
assert_eq!(sim.drones[0].engaged, 0, "the target stays claimed by a missile that is gone");
|
||||
assert_eq!(sim.tally.blocked, 1);
|
||||
assert!(sim.blasts.iter().all(|b| b.at.x < 3.5), "burst behind the wall");
|
||||
}
|
||||
|
||||
// #42, #43: a bridge deck above the flight is no ground under it
|
||||
#[test]
|
||||
fn flight_under_a_bridge_is_not_a_ground_hit() {
|
||||
let src = Blocks(|_, y, _| Some(y < 64 || y == 140));
|
||||
let mut sim = Sim::new(1);
|
||||
sim.damage = false;
|
||||
let mut ground = Ground::default();
|
||||
// The height map knows only the deck: 141 everywhere.
|
||||
ground.answer((-5..400).map(|x| (x, 0, 141)).collect(), 0);
|
||||
sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 100.0, 0.0), DVec3::X, DVec3::new(2000.0, 100.0, 0.0));
|
||||
warm(&mut ground, &src, DVec3::new(0.0, 100.0, 0.0), DVec3::new(300.0, 100.0, 0.0));
|
||||
for _ in 0..40 {
|
||||
fly(&mut sim, &mut ground, &src);
|
||||
}
|
||||
assert_eq!(sim.drones.len(), 1, "the deck above was taken for the ground");
|
||||
assert_eq!(sim.crashes, 0);
|
||||
}
|
||||
|
||||
// #43: unknown chunks and spent budgets are never air; changes and another world void the cache
|
||||
#[test]
|
||||
fn unknown_is_not_clear_and_changes_invalidate() {
|
||||
let mut ground = Ground::default();
|
||||
let (a, b) = (DVec3::new(0.5, 70.5, 0.5), DVec3::new(30.5, 70.5, 0.5));
|
||||
// Nothing read yet: the segment is unknown and the sections are asked for.
|
||||
assert!(matches!(ground.world.sweep(a, b, false, 1), world::Sweep::Unknown { .. }));
|
||||
let asked = ground.world.take_wanted(1);
|
||||
assert!(asked.contains(&(0, 4, 0)), "{asked:?}");
|
||||
// The game has no chunk there: still unknown, not air.
|
||||
let nothing = Blocks(|_, _, _| None);
|
||||
ground.world.serve(¬hing, asked, 2);
|
||||
assert!(matches!(ground.world.sweep(a, b, false, 3), world::Sweep::Unknown { .. }));
|
||||
// A wall appears in a chunk that now is loaded: found after it is read again.
|
||||
let wall = Blocks(|x, _, _| Some(x == 20));
|
||||
for now in [70, 71, 72] {
|
||||
ground.world.sweep(a, b, false, now);
|
||||
let w = ground.world.take_wanted(now);
|
||||
ground.world.serve(&wall, w, now);
|
||||
}
|
||||
let hit = ground.world.sweep(a, b, false, 73);
|
||||
assert!(matches!(hit, world::Sweep::Hit { block: [20, 70, 0], normal: [-1, 0, 0], .. }), "{hit:?}");
|
||||
// The wall is broken: the game says which section changed, and the next sweep asks again.
|
||||
let open = Blocks(|_, _, _| Some(false));
|
||||
ground.world.changed(7, false, &[(1, 4, 0)]);
|
||||
assert!(matches!(ground.world.sweep(a, b, false, 74), world::Sweep::Hit { .. }), "stale data is used until the answer");
|
||||
let w = ground.world.take_wanted(74);
|
||||
assert!(w.contains(&(1, 4, 0)), "{w:?}");
|
||||
ground.world.serve(&open, w, 75);
|
||||
assert_eq!(ground.world.sweep(a, b, false, 76), world::Sweep::Clear);
|
||||
// Another world: everything goes.
|
||||
ground.world.changed(8, false, &[]);
|
||||
assert!(ground.world.is_empty());
|
||||
}
|
||||
|
||||
// #43: the same wall and tunnel fixtures answer alike by sweep and by sections, and the cache is bounded
|
||||
#[test]
|
||||
fn wall_and_tunnel_fixtures_agree() {
|
||||
let tunnel = Blocks(|x, y, z| Some(y < 60 || (x == 10 && !(y == 70 && z == 0))));
|
||||
let mut ground = Ground::default();
|
||||
for z in [0.5, 1.5] {
|
||||
let (a, b) = (DVec3::new(0.5, 70.5, z), DVec3::new(30.5, 70.5, z));
|
||||
warm(&mut ground, &tunnel, a, b);
|
||||
let r = ground.world.sweep(a, b, false, 1);
|
||||
if z == 0.5 {
|
||||
assert_eq!(r, world::Sweep::Clear, "the tunnel is open");
|
||||
} else {
|
||||
assert!(matches!(r, world::Sweep::Hit { block: [10, 70, 1], .. }), "{r:?}");
|
||||
}
|
||||
}
|
||||
assert!(ground.world.bytes() < 64 * 1024);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,399 @@
|
||||
//! What the game's blocks are to the simulation (issues #42, #43): a cache of
|
||||
//! 16-block sections answered by `render.sections` (a bit per block that
|
||||
//! stops a projectile), a swept segment through it, and the bookkeeping that
|
||||
//! keeps the questions few: the sections along a flight asked for ahead of
|
||||
//! time, at most 64 a tick, nearest need first; changes of the world marking
|
||||
//! sections stale; a bounded cache. A chunk the game doesn't have answers
|
||||
//! `Unknown`, which is never the same as air: the callers fall back to the
|
||||
//! height of the land there and the counters say how often.
|
||||
use glam::DVec3;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// A section: block coordinates divided by 16.
|
||||
pub type Sec = (i32, i32, i32);
|
||||
|
||||
/// Sections asked in one tick (the game's budget).
|
||||
pub const PER_TICK: usize = 64;
|
||||
/// Sections kept; the least recently used go first beyond it.
|
||||
const MAX_SECTIONS: usize = 12_000;
|
||||
/// Ticks before an unanswered or unknown section is asked again.
|
||||
const RETRY: u64 = 60;
|
||||
/// Longest stretch of a flight asked for ahead, in blocks.
|
||||
const AHEAD_MAX: f64 = 192.0;
|
||||
/// Questions waiting: more are dropped (they are asked again when needed).
|
||||
const QUEUE_MAX: usize = 512;
|
||||
|
||||
/// What a section holds, as the game answered.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Fill {
|
||||
/// The game has no such chunk.
|
||||
Unknown,
|
||||
Empty,
|
||||
Full,
|
||||
/// 512 bytes, one bit per block, index `(y & 15) * 256 + (z & 15) * 16 + (x & 15)`.
|
||||
Mixed(Box<[u8; 512]>),
|
||||
}
|
||||
|
||||
/// An answer for a section, as the game gives it.
|
||||
pub struct SectionAnswer {
|
||||
pub sec: Sec,
|
||||
pub fill: Fill,
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
fill: Fill,
|
||||
/// A block changed (or may have) since it was read: asked again when next used.
|
||||
stale: bool,
|
||||
/// The tick it was last used in a sweep.
|
||||
used: u64,
|
||||
/// The tick it was answered.
|
||||
since: u64,
|
||||
}
|
||||
|
||||
/// How a swept segment ended.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Sweep {
|
||||
/// Every block along it is known and none stops it.
|
||||
Clear,
|
||||
/// The first solid block: where the segment meets it, which way the face looks, and the block.
|
||||
Hit { t: f64, point: DVec3, normal: [i32; 3], block: [i32; 3] },
|
||||
/// The walk reached blocks the game doesn't know (before any solid one), `t` of the way.
|
||||
Unknown { t: f64 },
|
||||
}
|
||||
|
||||
impl Sweep {
|
||||
pub fn hit(&self) -> Option<(f64, DVec3)> {
|
||||
match *self {
|
||||
Sweep::Hit { t, point, .. } => Some((t, point)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Counters for the report: questions, unknowns, memory, cost.
|
||||
#[derive(Clone, Copy, Default, Debug)]
|
||||
pub struct WorldStats {
|
||||
pub sweeps: u64,
|
||||
pub cells: u64,
|
||||
pub hits: u64,
|
||||
pub unknown_sweeps: u64,
|
||||
pub sections_asked: u64,
|
||||
pub sections_answered: u64,
|
||||
pub sections_unknown: u64,
|
||||
pub invalidated: u64,
|
||||
pub evicted: u64,
|
||||
pub world_changes: u64,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct WorldCache {
|
||||
secs: HashMap<Sec, Entry>,
|
||||
urgent: Vec<Sec>,
|
||||
ahead: Vec<Sec>,
|
||||
queued: HashSet<Sec>,
|
||||
/// Sections asked, and when.
|
||||
asked: HashMap<Sec, u64>,
|
||||
epoch: u32,
|
||||
pub stats: WorldStats,
|
||||
}
|
||||
|
||||
fn sec_of(x: i32, y: i32, z: i32) -> Sec {
|
||||
(x >> 4, y >> 4, z >> 4)
|
||||
}
|
||||
|
||||
impl WorldCache {
|
||||
/// Memory the cached sections hold, about.
|
||||
pub fn bytes(&self) -> usize {
|
||||
self.secs
|
||||
.values()
|
||||
.map(|e| 48 + if matches!(e.fill, Fill::Mixed(_)) { 512 } else { 0 })
|
||||
.sum()
|
||||
}
|
||||
pub fn len(&self) -> usize {
|
||||
self.secs.len()
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.secs.is_empty()
|
||||
}
|
||||
/// One line for the report.
|
||||
pub fn text(&self) -> String {
|
||||
let s = &self.stats;
|
||||
format!(
|
||||
"мир: {} секций ({} КБ), запросов {}, неизвестно {}, лучей {} (ударов {}, неизв. {}), клеток {}",
|
||||
self.len(),
|
||||
self.bytes() / 1024,
|
||||
s.sections_asked,
|
||||
s.sections_unknown,
|
||||
s.sweeps,
|
||||
s.hits,
|
||||
s.unknown_sweeps,
|
||||
s.cells
|
||||
)
|
||||
}
|
||||
|
||||
/// The game's note of changes: another world voids everything; changed
|
||||
/// sections (or too many to say) are read again when next used.
|
||||
pub fn changed(&mut self, epoch: u32, overflow: bool, sections: &[Sec]) {
|
||||
if epoch != self.epoch {
|
||||
if self.epoch != 0 {
|
||||
self.secs.clear();
|
||||
self.urgent.clear();
|
||||
self.ahead.clear();
|
||||
self.queued.clear();
|
||||
self.asked.clear();
|
||||
}
|
||||
self.epoch = epoch;
|
||||
}
|
||||
if overflow {
|
||||
for e in self.secs.values_mut() {
|
||||
e.stale = true;
|
||||
}
|
||||
self.stats.invalidated += self.secs.len() as u64;
|
||||
}
|
||||
for s in sections {
|
||||
if let Some(e) = self.secs.get_mut(s) {
|
||||
e.stale = true;
|
||||
self.stats.invalidated += 1;
|
||||
}
|
||||
}
|
||||
self.stats.world_changes += sections.len() as u64;
|
||||
}
|
||||
|
||||
/// An explosion is about to change the land: the sections round it are read again.
|
||||
pub fn touched(&mut self, at: DVec3, radius: f64) {
|
||||
let lo = sec_of((at.x - radius).floor() as i32, (at.y - radius).floor() as i32, (at.z - radius).floor() as i32);
|
||||
let hi = sec_of((at.x + radius).floor() as i32, (at.y + radius).floor() as i32, (at.z + radius).floor() as i32);
|
||||
for x in lo.0..=hi.0 {
|
||||
for y in lo.1..=hi.1 {
|
||||
for z in lo.2..=hi.2 {
|
||||
if let Some(e) = self.secs.get_mut(&(x, y, z)) {
|
||||
e.stale = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn answer(&mut self, answers: Vec<SectionAnswer>, now: u64) {
|
||||
for a in answers {
|
||||
self.asked.remove(&a.sec);
|
||||
self.stats.sections_answered += 1;
|
||||
if a.fill == Fill::Unknown {
|
||||
self.stats.sections_unknown += 1;
|
||||
}
|
||||
self.secs.insert(a.sec, Entry { fill: a.fill, stale: false, used: now, since: now });
|
||||
}
|
||||
if self.secs.len() > MAX_SECTIONS {
|
||||
// Whatever wasn't used for a minute goes; if that's not enough, the older half.
|
||||
self.secs.retain(|_, e| now.saturating_sub(e.used) < 1200);
|
||||
if self.secs.len() > MAX_SECTIONS {
|
||||
let mut used: Vec<u64> = self.secs.values().map(|e| e.used).collect();
|
||||
used.sort_unstable();
|
||||
let cut = used[used.len() / 2];
|
||||
self.secs.retain(|_, e| e.used >= cut);
|
||||
}
|
||||
self.stats.evicted += 1;
|
||||
}
|
||||
// Forget questions the game never answered, so they can be asked again.
|
||||
if now % 64 == 0 {
|
||||
self.asked.retain(|_, t| now.saturating_sub(*t) < RETRY);
|
||||
}
|
||||
}
|
||||
|
||||
/// The sections to ask this tick (at most [`PER_TICK`]): the ones a sweep
|
||||
/// needed first, then those along flights.
|
||||
pub fn take_wanted(&mut self, now: u64) -> Vec<Sec> {
|
||||
let mut out = Vec::new();
|
||||
for list in [&mut self.urgent, &mut self.ahead] {
|
||||
let room = PER_TICK - out.len();
|
||||
let n = room.min(list.len());
|
||||
out.extend(list.drain(..n));
|
||||
}
|
||||
for s in &out {
|
||||
self.queued.remove(s);
|
||||
self.asked.insert(*s, now);
|
||||
}
|
||||
self.stats.sections_asked += out.len() as u64;
|
||||
out
|
||||
}
|
||||
|
||||
fn want(&mut self, s: Sec, urgent: bool, now: u64) {
|
||||
if self.queued.contains(&s) || self.asked.get(&s).is_some_and(|&t| now.saturating_sub(t) < RETRY) {
|
||||
return;
|
||||
}
|
||||
if self.urgent.len() + self.ahead.len() >= QUEUE_MAX {
|
||||
return;
|
||||
}
|
||||
if urgent {
|
||||
self.urgent.push(s);
|
||||
} else {
|
||||
self.ahead.push(s);
|
||||
}
|
||||
self.queued.insert(s);
|
||||
}
|
||||
|
||||
/// Asks for the sections along a flight from `pos` at `vel` a tick, `ticks` ahead.
|
||||
pub fn look_ahead(&mut self, pos: DVec3, vel: DVec3, ticks: f64, now: u64) {
|
||||
let mut d = vel * ticks;
|
||||
let len = d.length();
|
||||
if len < 1e-6 {
|
||||
return;
|
||||
}
|
||||
if len > AHEAD_MAX {
|
||||
d *= AHEAD_MAX / len;
|
||||
}
|
||||
// A section at a time along the segment (a section is 16 wide: half-section steps meet each).
|
||||
let steps = (d.length() / 8.0).ceil().max(1.0) as i32;
|
||||
let mut last = None;
|
||||
for i in 0..=steps {
|
||||
let p = pos + d * (i as f64 / steps as f64);
|
||||
let s = sec_of(p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32);
|
||||
if last == Some(s) {
|
||||
continue;
|
||||
}
|
||||
last = Some(s);
|
||||
self.touch(s, false, now);
|
||||
}
|
||||
}
|
||||
|
||||
/// Touches a section the way a sweep or a look needs it: used now, and
|
||||
/// asked again when stale or (after a while) unknown.
|
||||
fn touch(&mut self, s: Sec, urgent: bool, now: u64) -> bool {
|
||||
let Some(e) = self.secs.get_mut(&s) else {
|
||||
self.want(s, urgent, now);
|
||||
return false;
|
||||
};
|
||||
e.used = now;
|
||||
let refresh = e.stale || (e.fill == Fill::Unknown && now.saturating_sub(e.since) >= RETRY);
|
||||
if refresh {
|
||||
self.want(s, urgent, now);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Whether the block at `(x, y, z)` stops a projectile: `None` where the
|
||||
/// game hasn't said. `last` is the section just touched.
|
||||
fn solid(&mut self, last: &mut Option<Sec>, x: i32, y: i32, z: i32, now: u64) -> Option<bool> {
|
||||
let s = sec_of(x, y, z);
|
||||
if *last != Some(s) {
|
||||
*last = Some(s);
|
||||
self.touch(s, true, now);
|
||||
}
|
||||
match &self.secs.get(&s)?.fill {
|
||||
Fill::Unknown => None,
|
||||
Fill::Empty => Some(false),
|
||||
Fill::Full => Some(true),
|
||||
Fill::Mixed(bits) => {
|
||||
let i = ((y & 15) << 8 | (z & 15) << 4 | (x & 15)) as usize;
|
||||
Some(bits[i >> 3] >> (i & 7) & 1 != 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the block is known to hold no solid block, with the sky above it
|
||||
/// in view: used to tell a fluid surface from a roof.
|
||||
pub fn is_known_open(&mut self, x: i32, y: i32, z: i32, now: u64) -> bool {
|
||||
self.solid(&mut None, x, y, z, now) == Some(false)
|
||||
}
|
||||
|
||||
/// Whether the block is known to be solid.
|
||||
pub fn is_known_solid(&mut self, x: i32, y: i32, z: i32, now: u64) -> bool {
|
||||
self.solid(&mut None, x, y, z, now) == Some(true)
|
||||
}
|
||||
|
||||
/// The first solid block along `a` to `b`, by walking the blocks it
|
||||
/// crosses; `skip_start` ignores the block it starts in (a launch from a
|
||||
/// pad that is part of the land).
|
||||
pub fn sweep(&mut self, a: DVec3, b: DVec3, skip_start: bool, now: u64) -> Sweep {
|
||||
self.stats.sweeps += 1;
|
||||
let d = b - a;
|
||||
let mut pos = [a.x.floor() as i32, a.y.floor() as i32, a.z.floor() as i32];
|
||||
let dv = [d.x, d.y, d.z];
|
||||
let av = [a.x, a.y, a.z];
|
||||
let step: [i32; 3] = dv.map(|v| if v > 0.0 { 1 } else { -1 });
|
||||
let mut t_max = [f64::INFINITY; 3];
|
||||
let mut t_delta = [f64::INFINITY; 3];
|
||||
for i in 0..3 {
|
||||
if dv[i] != 0.0 {
|
||||
let edge = f64::from(pos[i]) + if dv[i] > 0.0 { 1.0 } else { 0.0 };
|
||||
t_max[i] = (edge - av[i]) / dv[i];
|
||||
t_delta[i] = (1.0 / dv[i]).abs();
|
||||
}
|
||||
}
|
||||
let mut last: Option<Sec> = None;
|
||||
let mut face = [0i32; 3];
|
||||
let mut t = 0.0f64;
|
||||
let mut first = true;
|
||||
for _ in 0..4096 {
|
||||
self.stats.cells += 1;
|
||||
match self.solid(&mut last, pos[0], pos[1], pos[2], now) {
|
||||
None => {
|
||||
self.stats.unknown_sweeps += 1;
|
||||
return Sweep::Unknown { t };
|
||||
}
|
||||
Some(true) if !(first && skip_start) => {
|
||||
self.stats.hits += 1;
|
||||
return Sweep::Hit { t, point: a + d * t, normal: face, block: pos };
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
first = false;
|
||||
let axis = if t_max[0] < t_max[1] {
|
||||
if t_max[0] < t_max[2] { 0 } else { 2 }
|
||||
} else if t_max[1] < t_max[2] {
|
||||
1
|
||||
} else {
|
||||
2
|
||||
};
|
||||
t = t_max[axis];
|
||||
if t > 1.0 {
|
||||
return Sweep::Clear;
|
||||
}
|
||||
t_max[axis] += t_delta[axis];
|
||||
pos[axis] += step[axis];
|
||||
face = [0; 3];
|
||||
face[axis] = -step[axis];
|
||||
}
|
||||
self.stats.unknown_sweeps += 1;
|
||||
Sweep::Unknown { t }
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the game's blocks come from in tests and the native runner: any
|
||||
/// world that can say what a block is.
|
||||
pub trait WorldSource {
|
||||
/// Whether the block stops a projectile; `None` where there is no chunk.
|
||||
fn solid(&self, x: i32, y: i32, z: i32) -> Option<bool>;
|
||||
}
|
||||
|
||||
/// A [`WorldSource`] as the game would answer `render.query-sections` with it.
|
||||
pub fn section_of(source: &dyn WorldSource, s: Sec) -> Fill {
|
||||
let mut bits = Box::new([0u8; 512]);
|
||||
let (mut set, mut known) = (0u32, 0u32);
|
||||
for i in 0..4096usize {
|
||||
let (x, y, z) = (s.0 * 16 + (i & 15) as i32, s.1 * 16 + (i >> 8) as i32, s.2 * 16 + ((i >> 4) & 15) as i32);
|
||||
match source.solid(x, y, z) {
|
||||
Some(true) => {
|
||||
bits[i >> 3] |= 1 << (i & 7);
|
||||
set += 1;
|
||||
known += 1;
|
||||
}
|
||||
Some(false) => known += 1,
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
match (known, set) {
|
||||
(0, _) => Fill::Unknown,
|
||||
(_, 0) if known == 4096 => Fill::Empty,
|
||||
(_, 4096) => Fill::Full,
|
||||
_ => Fill::Mixed(bits),
|
||||
}
|
||||
}
|
||||
|
||||
impl WorldCache {
|
||||
/// Answers the questions of the last tick from a synthetic world, as the game does one tick later.
|
||||
pub fn serve(&mut self, source: &dyn WorldSource, wanted: Vec<Sec>, now: u64) {
|
||||
let answers = wanted.into_iter().map(|sec| SectionAnswer { sec, fill: section_of(source, sec) }).collect();
|
||||
self.answer(answers, now);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user