29b047abaf
No compatible coordinate-strike loadout is implemented yet. Preserve flight and collision mechanics through explicit test fixtures without allowing generic stock or player position to create a production missile. Physical carriers, typed ammunition and logistics remain to implement. Co-Authored-By: Codex <noreply@openai.com>
1195 lines
51 KiB
Rust
1195 lines
51 KiB
Rust
//! Launch sites (#100): where a raid really starts from. A raid picks its sides (one, two, or four to five),
|
|
//! looks for suitable ground on each side (only land the game has told of: flat, open to the sky, clear in
|
|
//! front, away from the defence), and sets up a site there: a ramp for the drones, a launcher vehicle for the
|
|
//! cruise missiles, a battery for the ballistic ones (at their own range). The raid's drones are jobs of the
|
|
//! sites: each one leaves its site, one at a time, from the stock the site holds.
|
|
//!
|
|
//! The land beyond the render distance is not there until the game loads it, so the search asks for the chunks
|
|
//! of the places it is looking at (`render.load-chunks`, API 22: a few, never a ring; the game generates or reads
|
|
//! them on its workers and keeps them some seconds) and waits for them: a column the game is loading is neither
|
|
//! land nor sea, it is pending. Where nothing can be loaded (a server) or nothing suitable is found within
|
|
//! `SEARCH_TICKS`, the raid is never cancelled for it: the side's site is *off the map* (`offmap`): no kit is drawn,
|
|
//! nothing can be destroyed, and its drones start in the air at the ordered range, cruising over whatever is there.
|
|
use super::*;
|
|
|
|
/// The most candidate places tried for one site, and how long (ticks) a raid waits for the game's answers.
|
|
pub const MAX_TRIES: usize = 90;
|
|
pub const SEARCH_TICKS: u32 = 400;
|
|
/// Candidates asked about ahead of the one being waited for.
|
|
const PREFETCH: usize = 3;
|
|
/// Prefetched candidates ask for their chunks only while fewer than this many are wanted.
|
|
const PREFETCH_CHUNKS: usize = 24;
|
|
/// The footprint's samples (offsets in blocks), the most the ground may differ over it, and how far from
|
|
/// the defence and the objects a site must be.
|
|
const FOOTPRINT: [(f64, f64); 9] = [(0.0, 0.0), (8.0, 0.0), (-8.0, 0.0), (0.0, 8.0), (0.0, -8.0), (6.0, 6.0), (6.0, -6.0), (-6.0, 6.0), (-6.0, -6.0)];
|
|
const FLAT: i32 = 2;
|
|
const KEEP_OUT: f64 = 45.0;
|
|
|
|
/// What a site is for.
|
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
|
pub enum SiteClass {
|
|
/// Drones: a catapult ramp.
|
|
Ramp,
|
|
/// Cruise and supersonic missiles: a launcher vehicle.
|
|
Launcher,
|
|
/// Ballistic missiles: a heavier launcher, far out.
|
|
Battery,
|
|
}
|
|
|
|
impl SiteClass {
|
|
pub fn of(kind: DroneKind) -> SiteClass {
|
|
let spec = kind.spec();
|
|
if spec.ballistic.is_some() {
|
|
SiteClass::Battery
|
|
} else if matches!(spec.class, Class::Drone | Class::Jet) {
|
|
SiteClass::Ramp
|
|
} else {
|
|
SiteClass::Launcher
|
|
}
|
|
}
|
|
/// Whether a site of this class can launch this kind.
|
|
pub fn supports(self, kind: DroneKind) -> bool {
|
|
SiteClass::of(kind) == self
|
|
}
|
|
/// Ticks between two launches from one site.
|
|
pub fn cadence(self) -> u64 {
|
|
match self {
|
|
SiteClass::Ramp => 15,
|
|
SiteClass::Launcher => 25,
|
|
SiteClass::Battery => 50,
|
|
}
|
|
}
|
|
fn slots(self) -> u32 {
|
|
match self {
|
|
SiteClass::Ramp => 4,
|
|
SiteClass::Launcher => 3,
|
|
SiteClass::Battery => 2,
|
|
}
|
|
}
|
|
fn spacing(self) -> f64 {
|
|
match self {
|
|
SiteClass::Ramp => 4.0,
|
|
SiteClass::Launcher => 9.0,
|
|
SiteClass::Battery => 12.0,
|
|
}
|
|
}
|
|
fn model(self) -> &'static str {
|
|
match self {
|
|
SiteClass::Ramp => "airdef:launch_ramp",
|
|
SiteClass::Launcher | SiteClass::Battery => "airdef:launcher_truck",
|
|
}
|
|
}
|
|
fn scale(self) -> f64 {
|
|
match self {
|
|
SiteClass::Ramp => 1.4,
|
|
SiteClass::Launcher => 1.5,
|
|
SiteClass::Battery => 1.9,
|
|
}
|
|
}
|
|
/// The barge's scale: its deck is 3 blocks a side at 1.
|
|
fn barge(self) -> f64 {
|
|
match self {
|
|
SiteClass::Ramp => 4.5,
|
|
_ => 7.0,
|
|
}
|
|
}
|
|
/// Where a drone leaves the kit: blocks ahead of its centre, and up from the ground.
|
|
fn muzzle(self) -> (f64, f64) {
|
|
match self {
|
|
SiteClass::Ramp => (1.8, 1.7),
|
|
SiteClass::Launcher => (2.6, 3.4),
|
|
SiteClass::Battery => (3.2, 4.2),
|
|
}
|
|
}
|
|
/// How steeply a drone leaves it (radians).
|
|
pub fn pitch(self) -> f64 {
|
|
match self {
|
|
SiteClass::Ramp => 0.35,
|
|
SiteClass::Launcher => 0.6,
|
|
SiteClass::Battery => 0.9,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// One launch site of a raid: stable id, side, where, what it can launch, what is left, and when it may launch next.
|
|
#[derive(Clone, Debug)]
|
|
pub struct LaunchSite {
|
|
pub id: u32,
|
|
/// Which side of the raid it is on (0-4) and the enemy's sector of it.
|
|
pub side: u8,
|
|
pub sector: u8,
|
|
pub bearing: f64,
|
|
pub class: SiteClass,
|
|
/// The ground at its centre (the top of the surface), and how far from the raid's centre it is.
|
|
pub pos: DVec3,
|
|
pub range: f64,
|
|
/// On a barge over open water (its `pos` is the water's surface plus the deck).
|
|
pub water: bool,
|
|
/// Rounds left, and the jobs given to it (also how many pads are drawn).
|
|
pub stock: u32,
|
|
pub planned: u32,
|
|
pub alive: bool,
|
|
pub next_free: u64,
|
|
/// Off the map: no land to stand on was found (or none can be loaded), so there is no kit; the drones
|
|
/// start in the air at `pos`'s range.
|
|
pub offmap: bool,
|
|
}
|
|
|
|
impl LaunchSite {
|
|
/// The direction a launch goes: from the site in, towards the raid's centre.
|
|
pub fn inward(&self) -> DVec3 {
|
|
DVec3::new(-self.bearing.sin(), 0.0, -self.bearing.cos())
|
|
}
|
|
fn lateral(&self) -> DVec3 {
|
|
DVec3::new(self.bearing.cos(), 0.0, -self.bearing.sin())
|
|
}
|
|
/// The base of pad `i` on the ground.
|
|
pub fn pad(&self, i: u32) -> DVec3 {
|
|
let n = self.class.slots();
|
|
self.pos + self.lateral() * ((f64::from(i % n) - f64::from(n - 1) / 2.0) * self.class.spacing())
|
|
}
|
|
/// Where a drone of pad `i` leaves the kit.
|
|
pub fn muzzle(&self, i: u32) -> DVec3 {
|
|
let (ahead, up) = self.class.muzzle();
|
|
self.pad(i) + self.inward() * ahead + DVec3::Y * up
|
|
}
|
|
pub fn supports(&self, kind: DroneKind) -> bool {
|
|
self.class.supports(kind)
|
|
}
|
|
}
|
|
|
|
/// The sites in play and the launch jobs given to them: (drone id, site id) for each drone still in the queue.
|
|
#[derive(Default)]
|
|
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.
|
|
pub(super) enum Slot {
|
|
/// Not a site's job (a manual launch, an old save): off it goes.
|
|
Free,
|
|
Go,
|
|
/// An off-map site's drone: it starts in the air, without a launch.
|
|
Air,
|
|
/// The site launched a moment ago.
|
|
Busy,
|
|
/// The site is gone or empty: the job is cancelled.
|
|
Gone,
|
|
}
|
|
|
|
impl Sites {
|
|
pub fn get(&self, id: u32) -> Option<&LaunchSite> {
|
|
self.list.iter().find(|s| s.id == id)
|
|
}
|
|
/// Jobs waiting for a site.
|
|
pub fn pending(&self, id: u32) -> usize {
|
|
self.jobs.iter().filter(|j| j.1 == id).count()
|
|
}
|
|
/// The site a queued drone is a job of.
|
|
pub fn site_of(&self, drone: u32) -> Option<u32> {
|
|
self.jobs.iter().find(|j| j.0 == drone).map(|j| j.1)
|
|
}
|
|
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;
|
|
site.id = self.next;
|
|
let id = site.id;
|
|
self.list.push(site);
|
|
id
|
|
}
|
|
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, 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;
|
|
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 };
|
|
let site = self.jobs[j].1;
|
|
let Some(s) = self.list.iter_mut().find(|s| s.id == site) else {
|
|
self.jobs.swap_remove(j);
|
|
return Slot::Gone;
|
|
};
|
|
if !s.alive || s.stock == 0 {
|
|
self.jobs.swap_remove(j);
|
|
return Slot::Gone;
|
|
}
|
|
if s.next_free > now {
|
|
return Slot::Busy;
|
|
}
|
|
s.stock -= 1;
|
|
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 }
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------- choosing sides and places
|
|
|
|
/// The sides of a raid as bearings: one, two far apart (108° or more), or four to five spread round (at least
|
|
/// 43° apart). The seed decides which.
|
|
pub fn pick_sides(rng: &mut Rng, approach: Approach, bearing: f64) -> Vec<f64> {
|
|
match approach {
|
|
Approach::Sector | Approach::Waves => vec![bearing],
|
|
Approach::TwoSectors => vec![bearing, bearing + std::f64::consts::PI * (0.6 + rng.f() * 0.6)],
|
|
Approach::AllSides => {
|
|
let n = if rng.chance(0.5) { 4 } else { 5 };
|
|
let step = TAU / f64::from(n);
|
|
(0..n).map(|k| bearing + f64::from(k) * step + rng.s() * 0.2 * step).collect()
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
|
pub enum Search {
|
|
Open,
|
|
Found,
|
|
Failed,
|
|
}
|
|
|
|
/// A site wanted by a raid: its side and class, the places to try in order, and how the search stands.
|
|
pub(super) struct Want {
|
|
pub side: usize,
|
|
pub bearing: f64,
|
|
pub class: SiteClass,
|
|
pub range: f64,
|
|
/// The range ordered (`range` is where the site stood in the end).
|
|
pub ordered: f64,
|
|
cands: Vec<(DVec3, bool)>,
|
|
cursor: usize,
|
|
pub found: Option<DVec3>,
|
|
pub water: bool,
|
|
pub state: Search,
|
|
pub jobs: u32,
|
|
pub site: u32,
|
|
}
|
|
|
|
impl Want {
|
|
/// Whether the search has nothing to show for it: the site is off the map.
|
|
pub fn offmap(&self) -> bool {
|
|
self.state == Search::Failed
|
|
}
|
|
}
|
|
|
|
/// The want of this side, class and range, made if there is none yet.
|
|
pub(super) fn want_index(wants: &mut Vec<Want>, centre: DVec3, side: usize, bearing: f64, class: SiteClass, range: f64, lo: f64) -> usize {
|
|
if let Some(i) = wants.iter().position(|w| w.side == side && w.class == class && (w.range - range).abs() < 1.0) {
|
|
return i;
|
|
}
|
|
let out = DVec3::new(bearing.sin(), 0.0, bearing.cos());
|
|
let lat = DVec3::new(bearing.cos(), 0.0, -bearing.sin());
|
|
// In order: known land at the ordered range (round it for most, the ordered range for a ballistic battery),
|
|
// known land nearer in steps, then a barge on open water at the ordered range, then on water nearer.
|
|
// A long range retreats in steps of at most 100 blocks and tries wider rings, not a few huge gaps.
|
|
let near = |from: f64| -> Vec<f64> {
|
|
let min = if class == SiteClass::Battery { lo.min(from).max(80.0) } else { (from * 0.3).max(80.0).max(from - 600.0) };
|
|
(1..=6).map(|i| from - (from - min) * f64::from(i) / 6.0).collect()
|
|
};
|
|
let wide = (range / 500.0).clamp(1.0, 3.0);
|
|
let round: Vec<f64> = if class == SiteClass::Battery {
|
|
vec![range]
|
|
} else {
|
|
[0.0, 24.0, -24.0, 48.0, -48.0, 72.0, -72.0].iter().map(|d| (range + d * wide).max(KEEP_OUT)).collect()
|
|
};
|
|
// A battery may stand where another site of the side does (its range is its own): wider to the sides.
|
|
let laterals: &[f64] = if class == SiteClass::Battery { &[0.0, 20.0, -20.0, 60.0, -60.0] } else { &[0.0, 20.0, -20.0] };
|
|
let mut cands = Vec::new();
|
|
for water in [false, true] {
|
|
for r in round.iter().copied().chain(near(range)) {
|
|
for l in laterals {
|
|
cands.push((centre + out * r + lat * *l, water));
|
|
}
|
|
}
|
|
}
|
|
cands.truncate(MAX_TRIES);
|
|
wants.push(Want { side, bearing, class, range, ordered: range, cands, cursor: 0, found: None, water: false, state: Search::Open, jobs: 0, site: 0 });
|
|
wants.len() - 1
|
|
}
|
|
|
|
enum Verdict {
|
|
/// The game hasn't told enough yet.
|
|
Pending,
|
|
Bad,
|
|
/// Suitable: the surface at its centre, and whether it is water's.
|
|
Good(DVec3, bool),
|
|
}
|
|
|
|
/// The chunks a site at `p` needs: its footprint and the way ahead, up to 14 blocks.
|
|
fn chunks_of(p: DVec3, inward: DVec3) -> Vec<(i32, i32)> {
|
|
let mut out: Vec<(i32, i32)> = Vec::with_capacity(6);
|
|
for (dx, dz) in FOOTPRINT {
|
|
for k in [0.0, 14.0] {
|
|
let c = (((p.x + dx + inward.x * k).floor() as i32) >> 4, ((p.z + dz + inward.z * k).floor() as i32) >> 4);
|
|
if !out.contains(&c) {
|
|
out.push(c);
|
|
}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// Whether a site fits at `p` (x, z): every sample of its footprint is land the game told of and within
|
|
/// `FLAT` blocks of the others, the sky above is open, the way ahead is clear, and nothing of the defence is near.
|
|
/// A column or chunk the game is still loading makes it `Pending`, and the chunks are asked for (unless this is
|
|
/// a look ahead at a later candidate, `ahead`, and many are wanted already).
|
|
fn judge(ground: &mut Ground, p: DVec3, inward: DVec3, keep: &[DVec3], now: u64, ahead: bool) -> Verdict {
|
|
if p.x.abs() > 29_000_000.0 || p.z.abs() > 29_000_000.0 || keep.iter().any(|k| horizontal(*k - p).length() < KEEP_OUT) {
|
|
return Verdict::Bad;
|
|
}
|
|
let (mut lo, mut hi, mut pending) = (i32::MAX, i32::MIN, false);
|
|
for (dx, dz) in FOOTPRINT {
|
|
match ground.column((p.x + dx).floor() as i32, (p.z + dz).floor() as i32, 256) {
|
|
None => pending = true,
|
|
// No land to tell of (the sea, the void): never a site.
|
|
Some(None) => return Verdict::Bad,
|
|
Some(Some(h)) => {
|
|
lo = lo.min(h as i32);
|
|
hi = hi.max(h as i32);
|
|
}
|
|
}
|
|
}
|
|
// The way ahead must be loaded too before it is swept (an unknown stretch is answered "no chunk" and kept
|
|
// for a while): a column in the middle of each chunk it needs says so.
|
|
let chunks = chunks_of(p, inward);
|
|
if !pending {
|
|
for &(cx, cz) in &chunks {
|
|
pending |= ground.column(cx * 16 + 8, cz * 16 + 8, 256).is_none();
|
|
}
|
|
}
|
|
if pending {
|
|
if !ahead || ground.chunks_wanted() < PREFETCH_CHUNKS {
|
|
for c in chunks {
|
|
ground.want_chunk(c);
|
|
}
|
|
}
|
|
return Verdict::Pending;
|
|
}
|
|
if pending {
|
|
return Verdict::Pending;
|
|
}
|
|
if hi - lo > FLAT {
|
|
return Verdict::Bad;
|
|
}
|
|
let top = f64::from(hi);
|
|
let at = DVec3::new(p.x.floor() + 0.5, top, p.z.floor() + 0.5);
|
|
// The game's height is the top of what blocks motion *or holds a fluid*: the block under the surface is
|
|
// solid at the footprint's centre and edges (land), or at none of them (water); a shore is neither.
|
|
let mut solid = 0;
|
|
for (dx, dz) in FOOTPRINT.iter().take(5) {
|
|
let c = DVec3::new((p.x + dx).floor() + 0.5, top, (p.z + dz).floor() + 0.5);
|
|
match ground.world.sweep(c + DVec3::Y * 0.5, c - DVec3::Y * 0.5, false, now) {
|
|
world::Sweep::Hit { .. } => solid += 1,
|
|
world::Sweep::Clear => {}
|
|
world::Sweep::Unknown { pending: true, .. } | world::Sweep::Wait { .. } => {
|
|
return Verdict::Pending;
|
|
}
|
|
world::Sweep::Unknown { .. } => return Verdict::Bad,
|
|
}
|
|
}
|
|
if solid != 0 && solid != 5 {
|
|
return Verdict::Bad;
|
|
}
|
|
let up = ground.world.sweep(at + DVec3::Y * 30.0, at + DVec3::Y * 1.0, false, now);
|
|
let ahead = ground.world.sweep(at + DVec3::Y * 3.0, at + inward * 14.0 + DVec3::Y * 3.0, false, now);
|
|
for s in [up, ahead] {
|
|
match s {
|
|
world::Sweep::Clear => {}
|
|
world::Sweep::Unknown { pending: true, .. } | world::Sweep::Wait { .. } => {
|
|
return Verdict::Pending;
|
|
}
|
|
world::Sweep::Unknown { .. } | world::Sweep::Hit { .. } => return Verdict::Bad,
|
|
}
|
|
}
|
|
Verdict::Good(at, solid == 0)
|
|
}
|
|
|
|
/// Works on the open wants: each tries its places in order, a place the game hasn't told enough of holds the
|
|
/// search (the next few are asked about meanwhile), and a bad place is passed over. After `last` nothing waits.
|
|
/// Returns whether every want is settled.
|
|
pub(super) fn search(wants: &mut [Want], ground: &mut Ground, centre: DVec3, keep: &[DVec3], now: u64, last: bool) -> bool {
|
|
let mut all = true;
|
|
for k in 0..wants.len() {
|
|
if wants[k].state != Search::Open {
|
|
continue;
|
|
}
|
|
// Two sites never share a place: the others' kit is in the way.
|
|
let mut keep: Vec<DVec3> = keep.to_vec();
|
|
keep.extend(wants.iter().filter_map(|o| o.found));
|
|
let w = &mut wants[k];
|
|
let inward = DVec3::new(-w.bearing.sin(), 0.0, -w.bearing.cos());
|
|
loop {
|
|
if w.cursor >= w.cands.len() {
|
|
w.state = Search::Failed;
|
|
break;
|
|
}
|
|
let (cand, water) = w.cands[w.cursor];
|
|
match judge(ground, cand, inward, &keep, now, false) {
|
|
Verdict::Bad => w.cursor += 1,
|
|
// Land when land was asked for, a barge when water was.
|
|
Verdict::Good(_, got) if got != water => w.cursor += 1,
|
|
Verdict::Good(at, _) => {
|
|
w.found = Some(at);
|
|
w.water = water;
|
|
w.range = horizontal(at - centre).length();
|
|
w.state = Search::Found;
|
|
break;
|
|
}
|
|
Verdict::Pending => {
|
|
for k in 1..=PREFETCH {
|
|
if let Some(&(c, _)) = w.cands.get(w.cursor + k) {
|
|
let _ = judge(ground, c, inward, &keep, now, true);
|
|
}
|
|
}
|
|
if last {
|
|
w.state = Search::Failed;
|
|
} else {
|
|
all = false;
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
all
|
|
}
|
|
|
|
// ---------------------------------------------------------------- in the sim
|
|
|
|
/// Id base of the kit's models.
|
|
const KIT: u32 = 0x7400_0000;
|
|
/// The barge's deck over the water.
|
|
pub const DECK: f64 = 0.3;
|
|
|
|
impl Sim {
|
|
/// Takes site `id` out of play (destroyed): its stock is gone and its queued jobs are cancelled. Returns how
|
|
/// many. (The counter-strike, #101, uses this.)
|
|
pub fn destroy_site(&mut self, id: u32) -> u32 {
|
|
// An off-map site is nowhere to be found: nothing to destroy.
|
|
self.end_site(id, false)
|
|
}
|
|
|
|
/// Ends a site's launches wherever it is, off the map too (a strike that would have hit it): the same as
|
|
/// destroying it, without anything to draw.
|
|
pub fn halt_site(&mut self, id: u32) -> u32 {
|
|
self.end_site(id, true)
|
|
}
|
|
|
|
fn end_site(&mut self, id: u32, offmap: bool) -> u32 {
|
|
let Some(s) = self.sites.list.iter_mut().find(|s| s.id == id && (offmap || !s.offmap)) else { return 0 };
|
|
s.alive = false;
|
|
s.stock = 0;
|
|
let ids: Vec<u32> = self.sites.jobs.iter().filter(|j| j.1 == id).map(|j| j.0).collect();
|
|
self.queue.retain(|q| !ids.contains(&q.1.id));
|
|
self.sites.jobs.retain(|j| j.1 != id);
|
|
ids.len() as u32
|
|
}
|
|
|
|
/// Asks a site whether a queued drone may leave now.
|
|
pub(super) fn site_slot(&mut self, drone: u32) -> Slot {
|
|
let now = self.tick;
|
|
self.sites.take(drone, now)
|
|
}
|
|
|
|
/// Draws every site's kit: a ramp or launcher per pad in use, turned to the way the launches go.
|
|
pub(super) fn draw_sites(&self, out: &mut Out) {
|
|
for s in self.sites.list.iter().filter(|s| s.alive && !s.offmap) {
|
|
let rot = DQuat::from_rotation_y(heading_of(s.inward()));
|
|
let sc = s.class.scale();
|
|
if s.water {
|
|
let b = s.class.barge();
|
|
out.model(KIT + (s.id * 8 + 7) * PARTS, "airdef:barge", s.pos - DVec3::Y * (DECK + 0.8 - 0.5 * b), rot, b, false);
|
|
}
|
|
for i in 0..s.planned.min(s.class.slots()) {
|
|
let id = KIT + (s.id * 8 + i) * PARTS;
|
|
out.model(id, s.class.model(), s.pad(i) + DVec3::Y * 0.5 * sc, rot, sc, false);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
pub(super) mod testland {
|
|
use super::*;
|
|
|
|
/// Land from a height function; blocks below it are solid, and the game's height map says the same.
|
|
pub struct Land<F: Fn(i32, i32) -> i32>(pub F);
|
|
impl<F: Fn(i32, i32) -> i32> world::WorldSource for Land<F> {
|
|
fn solid(&self, x: i32, y: i32, z: i32) -> Option<bool> {
|
|
Some(y < (self.0)(x, z))
|
|
}
|
|
}
|
|
|
|
/// What the game answers a tick after the sim asked: heights, and the sections.
|
|
pub fn serve<F: Fn(i32, i32) -> i32>(ground: &mut Ground, land: &Land<F>, now: u64) {
|
|
let columns = ground.take_wanted().into_iter().map(|(x, z)| (x, z, (land.0)(x, z))).collect();
|
|
ground.answer(columns, now);
|
|
let sections = ground.world.take_wanted(now);
|
|
ground.world.serve(land, sections, now);
|
|
}
|
|
|
|
pub fn step<F: Fn(i32, i32) -> i32>(sim: &mut Sim, ground: &mut Ground, land: &Land<F>, out: &mut Out) {
|
|
serve(ground, land, sim.tick);
|
|
sim.step(ground, None, out);
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::testland::*;
|
|
use super::*;
|
|
|
|
fn sep(a: f64, b: f64) -> f64 {
|
|
angle_diff(a, b).abs().to_degrees()
|
|
}
|
|
|
|
fn min_sep(sides: &[f64]) -> f64 {
|
|
let mut m = 360.0f64;
|
|
for i in 0..sides.len() {
|
|
for j in 0..i {
|
|
m = m.min(sep(sides[i], sides[j]));
|
|
}
|
|
}
|
|
m
|
|
}
|
|
|
|
#[test]
|
|
fn sector_modes_give_one_two_or_four_to_five_sides_apart() {
|
|
let mut fours = 0;
|
|
let mut fives = 0;
|
|
for seed in 1..200u64 {
|
|
for approach in Approach::ALL {
|
|
let mut rng = Rng::new(seed);
|
|
let b = rng.f() * TAU;
|
|
let sides = pick_sides(&mut rng, approach, b);
|
|
match approach {
|
|
Approach::Sector | Approach::Waves => assert_eq!(sides.len(), 1),
|
|
Approach::TwoSectors => {
|
|
assert_eq!(sides.len(), 2);
|
|
assert!(min_sep(&sides) >= 100.0, "two sectors only {:.0} deg apart", min_sep(&sides));
|
|
}
|
|
Approach::AllSides => {
|
|
assert!((4..=5).contains(&sides.len()), "{} sides", sides.len());
|
|
assert!(min_sep(&sides) >= 40.0, "all sides: two only {:.0} deg apart", min_sep(&sides));
|
|
if sides.len() == 4 {
|
|
fours += 1;
|
|
} else {
|
|
fives += 1;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
assert!(fours > 20 && fives > 20, "the seed should pick both 4 and 5: {fours} / {fives}");
|
|
}
|
|
|
|
fn flat() -> Land<impl Fn(i32, i32) -> i32> {
|
|
Land(|_, _| 64)
|
|
}
|
|
|
|
fn order(approach: Approach, dist: f64) -> RaidOrder {
|
|
RaidOrder {
|
|
kinds: vec![(DroneKind::Shahed, 6), (DroneKind::Gerbera, 3), (DroneKind::Kh101, 3), (DroneKind::Iskander, 2)],
|
|
approach,
|
|
dist,
|
|
aim: Aim::Objects,
|
|
}
|
|
}
|
|
|
|
/// Orders a raid over `land` and plans it to the end; returns the ticks it took.
|
|
fn plan<F: Fn(i32, i32) -> i32>(sim: &mut Sim, ground: &mut Ground, land: &Land<F>, o: &RaidOrder, out: &mut Out) -> u32 {
|
|
sim.order_raid(o, &[DVec3::new(0.0, 70.0, 0.0)], out);
|
|
let mut n = 0;
|
|
while sim.planning() {
|
|
step(sim, ground, land, out);
|
|
n += 1;
|
|
assert!(n < 1000, "the raid never finished planning");
|
|
}
|
|
n
|
|
}
|
|
|
|
#[test]
|
|
fn sites_per_sector_mode_launch_every_drone_from_a_site_on_a_side() {
|
|
for (approach, sides) in [(Approach::Sector, 1usize), (Approach::TwoSectors, 2), (Approach::AllSides, 5), (Approach::Waves, 1)] {
|
|
let (land, mut ground, mut out) = (flat(), Ground::default(), Out::default());
|
|
let mut sim = Sim::new(21);
|
|
plan(&mut sim, &mut ground, &land, &order(approach, 300.0), &mut out);
|
|
let mut sides_used: Vec<u8> = sim.sites.list.iter().map(|s| s.side).collect();
|
|
sides_used.sort_unstable();
|
|
sides_used.dedup();
|
|
match approach {
|
|
Approach::AllSides => assert!((4..=5).contains(&sides_used.len()), "{} sides", sides_used.len()),
|
|
_ => assert_eq!(sides_used.len(), sides, "{approach:?}"),
|
|
}
|
|
// No hidden extra position: at most a site per class on a side (ramp, launcher, one battery per range).
|
|
assert!(sim.sites.list.len() <= sides_used.len() * 3, "{} sites", sim.sites.list.len());
|
|
// Every drone has a site that supports its kind.
|
|
assert_eq!(sim.queue.len() + sim.drones.len(), 14, "{:?}", out.messages);
|
|
for (_, d) in &sim.queue {
|
|
let site = sim.sites.site_of(d.id).and_then(|id| sim.sites.get(id)).expect("a drone without a source site");
|
|
assert!(site.supports(d.kind), "{:?} from a {:?}", d.kind, site.class);
|
|
// It waits on the site's pad, over its ground.
|
|
assert!(horizontal(d.pos - site.pos).length() < 25.0, "{:?} is {:.0} away from its site", d.kind, horizontal(d.pos - site.pos).length());
|
|
assert!(d.pos.y > site.pos.y && d.pos.y < site.pos.y + 6.0);
|
|
}
|
|
for (i, a) in sim.sites.list.iter().enumerate() {
|
|
for b in &sim.sites.list[..i] {
|
|
assert!(horizontal(a.pos - b.pos).length() >= KEEP_OUT, "two sites on one place");
|
|
}
|
|
}
|
|
// Stock and jobs agree; ground is real: flat at 64.
|
|
for s in &sim.sites.list {
|
|
assert_eq!(s.stock as usize, sim.sites.pending(s.id));
|
|
assert_eq!(s.pos.y, 64.0);
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn ballistic_sites_keep_their_own_range_and_ramps_the_ordered_one() {
|
|
let (land, mut ground, mut out) = (flat(), Ground::default(), Out::default());
|
|
let mut sim = Sim::new(4);
|
|
plan(&mut sim, &mut ground, &land, &order(Approach::Sector, 300.0), &mut out);
|
|
let centre = DVec3::new(0.0, 70.0, 0.0);
|
|
for s in &sim.sites.list {
|
|
let r = horizontal(s.pos - centre).length();
|
|
match s.class {
|
|
SiteClass::Battery => assert!(r > 990.0, "a battery only {r:.0} out"),
|
|
_ => assert!((200.0..=400.0).contains(&r), "{:?} {r:.0} out", s.class),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn launches_start_at_the_site_with_a_real_climb_and_in_turn() {
|
|
let (land, mut ground, mut out) = (flat(), Ground::default(), Out::default());
|
|
let mut sim = Sim::new(9);
|
|
plan(&mut sim, &mut ground, &land, &order(Approach::TwoSectors, 300.0), &mut out);
|
|
let jobs: HashMap<u32, u32> = sim.queue.iter().map(|(_, d)| (d.id, sim.sites.site_of(d.id).unwrap())).collect();
|
|
// One or two may have left in the tick the plan was ready.
|
|
let early = sim.drones.len();
|
|
let stock: u32 = sim.sites.list.iter().map(|s| s.stock).sum();
|
|
assert_eq!(stock as usize + early, 14);
|
|
let mut seen = HashMap::new();
|
|
let mut last_launch: HashMap<u32, u64> = HashMap::new();
|
|
for _ in 0..4000 {
|
|
step(&mut sim, &mut ground, &land, &mut out);
|
|
for d in sim.drones.iter().filter(|d| d.age == 1) {
|
|
let site = sim.sites.get(jobs[&d.id]).unwrap().clone();
|
|
// Its first tick is at the kit, not in the air somewhere.
|
|
assert!(horizontal(d.pos - site.pos).length() < 25.0, "{:?} first seen {:.0} from its site", d.kind, horizontal(d.pos - site.pos).length());
|
|
assert!(d.pos.y - site.pos.y < 12.0, "{:?} first seen {:.1} above the ground", d.kind, d.pos.y - site.pos.y);
|
|
if d.kind.spec().ballistic.is_none() {
|
|
assert!(d.vel.y > 0.0, "{:?} leaves level, not climbing", d.kind);
|
|
}
|
|
// One launch at a time from a site.
|
|
if let Some(t) = last_launch.insert(site.id, sim.tick) {
|
|
assert!(sim.tick - t >= site.class.cadence(), "two launches {} ticks apart", sim.tick - t);
|
|
}
|
|
seen.insert(d.id, d.pos.y);
|
|
}
|
|
}
|
|
assert_eq!(seen.len() + early, 14, "not every drone left a site");
|
|
assert_eq!(sim.sites.list.iter().map(|s| s.stock).sum::<u32>(), 0, "stock left after the raid");
|
|
// The climb is real: an early drone is higher a second later, and clear of the ground.
|
|
assert!(sim.queue.is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn a_site_launches_only_what_it_holds() {
|
|
let mut sim = Sim::new(2);
|
|
let mut ground = Ground::default();
|
|
let mut out = Out::default();
|
|
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: 3,
|
|
planned: 5,
|
|
alive: true,
|
|
next_free: 0,
|
|
offmap: false,
|
|
});
|
|
for i in 0..5 {
|
|
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);
|
|
sim.queue.push((1, d));
|
|
}
|
|
let mut times = Vec::new();
|
|
for _ in 0..80 {
|
|
let before = sim.launched;
|
|
sim.step(&mut ground, None, &mut out);
|
|
if sim.launched > before {
|
|
times.push(sim.tick);
|
|
}
|
|
}
|
|
assert_eq!(sim.launched, 3, "launched {:?}", times);
|
|
assert!(sim.queue.is_empty(), "the unlaunchable jobs stay in the queue");
|
|
assert_eq!(sim.sites.get(id).unwrap().stock, 0);
|
|
assert!(times.windows(2).all(|w| w[1] - w[0] >= SiteClass::Ramp.cadence()), "{times:?}");
|
|
}
|
|
|
|
#[test]
|
|
fn a_destroyed_site_cancels_its_future_jobs() {
|
|
let (land, mut ground, mut out) = (flat(), Ground::default(), Out::default());
|
|
let mut sim = Sim::new(5);
|
|
plan(&mut sim, &mut ground, &land, &order(Approach::Sector, 300.0), &mut out);
|
|
let ramp = sim.sites.list.iter().find(|s| s.class == SiteClass::Ramp).unwrap().id;
|
|
let early = sim.launched as usize;
|
|
let n = sim.sites.pending(ramp);
|
|
assert!(n >= 8 && n <= 9, "{n}");
|
|
assert_eq!(sim.destroy_site(ramp) as usize, n);
|
|
assert_eq!(sim.queue.len() + early + n, 14);
|
|
for _ in 0..3000 {
|
|
step(&mut sim, &mut ground, &land, &mut out);
|
|
}
|
|
assert_eq!(sim.launched as usize + n, 14);
|
|
}
|
|
|
|
/// Runs the sim `ticks` without the game answering anything, and counts what left.
|
|
fn run_blind(sim: &mut Sim, out: &mut Out, ground: &mut Ground, ticks: u32) {
|
|
for _ in 0..ticks {
|
|
sim.step(ground, None, out);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn no_suitable_ground_means_the_raid_launches_off_the_map() {
|
|
// Never answered: unknown ground is not suitable, but nothing is cancelled: every side starts off the map.
|
|
let (mut ground, mut out) = (Ground::default(), Out::default());
|
|
let mut sim = Sim::new(3);
|
|
sim.order_raid(&order(Approach::TwoSectors, 300.0), &[DVec3::new(0.0, 70.0, 0.0)], &mut out);
|
|
let mut n = 0;
|
|
while sim.planning() {
|
|
sim.step(&mut ground, None, &mut out);
|
|
n += 1;
|
|
assert!(n <= SEARCH_TICKS + 5, "a raid waits for ever");
|
|
}
|
|
assert_eq!(sim.queue.len() + sim.launched as usize, 14);
|
|
assert!(!sim.sites.list.is_empty() && sim.sites.list.iter().all(|s| s.offmap), "{:?}", sim.sites.list);
|
|
let said: Vec<_> = out.messages.iter().filter(|m| m.contains("за пределами")).collect();
|
|
assert_eq!(said.len(), 1, "{:?}", out.messages);
|
|
assert!(!out.messages.iter().any(|m| m.contains("отмен")), "{:?}", out.messages);
|
|
run_blind(&mut sim, &mut out, &mut ground, 400);
|
|
assert_eq!(sim.launched, 14, "{:?}", out.messages);
|
|
assert!(sim.queue.is_empty());
|
|
// No kit, and nothing to destroy.
|
|
let mut o2 = Out::default();
|
|
sim.draw_sites(&mut o2);
|
|
assert!(o2.models.is_empty());
|
|
let id = sim.sites.list[0].id;
|
|
assert_eq!(sim.destroy_site(id), 0);
|
|
// A cliff face everywhere (too steep to stand on) and a sea (no land) launch off the map as well.
|
|
for steep in [true, false] {
|
|
let land = Land(move |x, _| if steep { x * 4 } else { -100 });
|
|
let (mut ground, mut out) = (Ground::default(), Out::default());
|
|
let mut sim = Sim::new(3);
|
|
plan(&mut sim, &mut ground, &land, &order(Approach::Sector, 300.0), &mut out);
|
|
assert!(!sim.sites.list.is_empty() && sim.sites.list.iter().all(|s| s.offmap), "steep {steep}");
|
|
assert_eq!(sim.queue.len() + sim.launched as usize, 14, "steep {steep}");
|
|
assert!(!out.messages.iter().any(|m| m.contains("отмен")), "{:?}", out.messages);
|
|
}
|
|
}
|
|
|
|
/// An off-map site's drones start in the air at the height planned over land nobody had read; if the land
|
|
/// turns out higher there by the time they leave, they start above it instead of being born inside the hill.
|
|
#[test]
|
|
fn an_off_map_start_over_a_hill_begins_above_it() {
|
|
let (mut ground, mut out) = (Ground::default(), Out::default());
|
|
let mut sim = Sim::new(3);
|
|
sim.order_raid(&order(Approach::TwoSectors, 300.0), &[DVec3::new(0.0, 70.0, 0.0)], &mut out);
|
|
while sim.planning() {
|
|
sim.step(&mut ground, None, &mut out);
|
|
}
|
|
assert!(sim.sites.list.iter().all(|s| s.offmap));
|
|
let land = Land(|x, z| if x * x + z * z > 200 * 200 { 150 } else { 64 });
|
|
for _ in 0..500 {
|
|
step(&mut sim, &mut ground, &land, &mut out);
|
|
assert!(sim.drones.iter().all(|d| d.age > 3 || d.pos.y > 148.0 || d.flight == Flight::Ballistic), "a drone started inside the hill");
|
|
}
|
|
assert!(sim.launched > 0);
|
|
}
|
|
|
|
/// Chunks that load on request: a column of a chunk asked for answers `PENDING` until `delay` ticks
|
|
/// after the first request, and a chunk never asked for is not there (-64).
|
|
struct Lazy {
|
|
height: i32,
|
|
delay: u64,
|
|
asked: std::cell::RefCell<HashMap<(i32, i32), u64>>,
|
|
most: usize,
|
|
}
|
|
impl Lazy {
|
|
fn loaded(&self, c: (i32, i32), now: u64) -> Option<bool> {
|
|
self.asked.borrow().get(&c).map(|&t| now >= t + self.delay)
|
|
}
|
|
fn tick(&mut self, ground: &mut Ground, now: u64) {
|
|
let chunks = ground.take_chunks();
|
|
self.most = self.most.max(chunks.len());
|
|
for c in chunks {
|
|
self.asked.borrow_mut().entry(c).or_insert(now);
|
|
}
|
|
let cols = ground
|
|
.take_wanted()
|
|
.into_iter()
|
|
.map(|(x, z)| {
|
|
let y = match self.loaded((x >> 4, z >> 4), now) {
|
|
Some(true) => self.height,
|
|
Some(false) => PENDING,
|
|
None => -64,
|
|
};
|
|
(x, z, y)
|
|
})
|
|
.collect();
|
|
ground.answer(cols, now);
|
|
let secs = ground.world.take_wanted(now);
|
|
let view = Seen { lazy: self, now };
|
|
ground.world.serve(&view, secs, now);
|
|
}
|
|
}
|
|
struct Seen<'a> {
|
|
lazy: &'a Lazy,
|
|
now: u64,
|
|
}
|
|
impl world::WorldSource for Seen<'_> {
|
|
fn solid(&self, x: i32, y: i32, z: i32) -> Option<bool> {
|
|
self.lazy.loaded((x >> 4, z >> 4), self.now).filter(|&l| l).map(|_| y < self.lazy.height)
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_column_pending_for_chunk_load_waits_then_finds_a_site() {
|
|
let (mut ground, mut out) = (Ground::default(), Out::default());
|
|
let mut lazy = Lazy { height: 64, delay: 50, asked: Default::default(), most: 0 };
|
|
let mut sim = Sim::new(21);
|
|
sim.order_raid(&order(Approach::TwoSectors, 1500.0), &[DVec3::new(0.0, 70.0, 0.0)], &mut out);
|
|
let mut n = 0;
|
|
while sim.planning() {
|
|
lazy.tick(&mut ground, sim.tick);
|
|
sim.step(&mut ground, None, &mut out);
|
|
n += 1;
|
|
assert!(n < SEARCH_TICKS + 5, "never settled");
|
|
}
|
|
assert!(n > 50, "settled in {n} ticks, before any chunk could be there");
|
|
assert!(sim.sites.list.iter().all(|s| !s.offmap), "{:?} {:?}", sim.sites.list, out.messages);
|
|
assert!(!sim.sites.list.is_empty());
|
|
assert!(lazy.most <= 48 && lazy.most > 0, "{} chunks wanted at once", lazy.most);
|
|
assert!(out.messages.iter().any(|m| m.contains("готовит")), "{:?}", out.messages);
|
|
assert!(!out.messages.iter().any(|m| m.contains("отмен") || m.contains("за пределами")), "{:?}", out.messages);
|
|
// Far ones stand where the raid was ordered (1500 out), not nearer.
|
|
assert!(sim.sites.list.iter().any(|s| s.range > 1400.0), "{:?}", sim.sites.list.iter().map(|s| s.range).collect::<Vec<_>>());
|
|
}
|
|
|
|
#[test]
|
|
fn a_game_that_never_loads_gets_the_same_launch_off_the_map() {
|
|
// The game answers "no chunk" (-64) for what was not asked about, and never loads what was (a server).
|
|
let (mut ground, mut out) = (Ground::default(), Out::default());
|
|
let mut sim = Sim::new(5);
|
|
sim.order_raid(&order(Approach::Sector, 2500.0), &[DVec3::new(0.0, 70.0, 0.0)], &mut out);
|
|
let mut n = 0;
|
|
while sim.planning() {
|
|
let _ = ground.take_chunks();
|
|
let cols = ground.take_wanted().into_iter().map(|(x, z)| (x, z, -64)).collect();
|
|
ground.answer(cols, sim.tick);
|
|
sim.step(&mut ground, None, &mut out);
|
|
n += 1;
|
|
assert!(n < SEARCH_TICKS + 5);
|
|
}
|
|
assert!(sim.sites.list.iter().all(|s| s.offmap));
|
|
assert_eq!(sim.queue.len() + sim.launched as usize, 14);
|
|
// Where they start: at the ordered range, not at the player.
|
|
assert!(sim.queue.iter().all(|q| horizontal(q.1.pos - DVec3::new(0.0, 70.0, 0.0)).length() > 2400.0));
|
|
}
|
|
|
|
#[test]
|
|
fn a_raid_ordered_4000_out_reaches_its_target() {
|
|
let (land, mut ground, mut out) = (flat(), Ground::default(), Out::default());
|
|
let mut sim = Sim::new(9);
|
|
let o = RaidOrder { kinds: vec![(DroneKind::Shahed, 2), (DroneKind::Kh101, 1), (DroneKind::Iskander, 1)], approach: Approach::Sector, dist: 4000.0, aim: Aim::Objects };
|
|
let target = DVec3::new(0.0, 70.0, 0.0);
|
|
sim.order_raid(&o, &[target], &mut out);
|
|
let mut closest = [f64::MAX; 4];
|
|
for _ in 0..16_000 {
|
|
step(&mut sim, &mut ground, &land, &mut out);
|
|
for d in sim.drones.iter().filter(|d| d.alive()) {
|
|
let k = match d.kind {
|
|
DroneKind::Shahed => 0,
|
|
DroneKind::Kh101 => 1,
|
|
_ => 2,
|
|
};
|
|
closest[k] = closest[k].min(horizontal(d.pos - target).length());
|
|
}
|
|
}
|
|
assert_eq!(sim.launched, 4, "{:?}", out.messages);
|
|
assert!(closest.iter().take(3).all(|&c| c < 120.0), "closest approaches {closest:?}");
|
|
assert!(sim.drones.iter().all(|d| !d.alive()), "still flying");
|
|
}
|
|
|
|
/// Land inside a radius of the origin (surface 64), open water outside it (surface 63 over a floor at 50):
|
|
/// the game's height over water is the surface, and the blocks under it are not solid.
|
|
struct Island(f64);
|
|
impl Island {
|
|
fn land(&self, x: i32, z: i32) -> bool {
|
|
f64::from(x).hypot(f64::from(z)) < self.0
|
|
}
|
|
}
|
|
impl world::WorldSource for Island {
|
|
fn solid(&self, x: i32, y: i32, z: i32) -> Option<bool> {
|
|
Some(y < if self.land(x, z) { 64 } else { 50 })
|
|
}
|
|
}
|
|
|
|
fn run_island(radius: f64, seed: u64, o: &RaidOrder) -> (Sim, Out) {
|
|
let (mut ground, mut out, island) = (Ground::default(), Out::default(), Island(radius));
|
|
let mut sim = Sim::new(seed);
|
|
sim.order_raid(o, &[DVec3::new(0.0, 70.0, 0.0)], &mut out);
|
|
for _ in 0..SEARCH_TICKS + 5 {
|
|
let cols = ground.take_wanted().into_iter().map(|(x, z)| (x, z, if island.land(x, z) { 64 } else { 63 })).collect();
|
|
ground.answer(cols, sim.tick);
|
|
let secs = ground.world.take_wanted(sim.tick);
|
|
ground.world.serve(&island, secs, sim.tick);
|
|
sim.step(&mut ground, None, &mut out);
|
|
}
|
|
for _ in 0..3000 {
|
|
let cols = ground.take_wanted().into_iter().map(|(x, z)| (x, z, if island.land(x, z) { 64 } else { 63 })).collect();
|
|
ground.answer(cols, sim.tick);
|
|
let secs = ground.world.take_wanted(sim.tick);
|
|
ground.world.serve(&island, secs, sim.tick);
|
|
sim.step(&mut ground, None, &mut out);
|
|
}
|
|
(sim, out)
|
|
}
|
|
|
|
#[test]
|
|
fn an_all_water_map_gives_barges_and_every_drone_launches() {
|
|
let o = RaidOrder { kinds: vec![(DroneKind::Shahed, 6), (DroneKind::Kh101, 3)], approach: Approach::TwoSectors, dist: 200.0, aim: Aim::Objects };
|
|
// Water from the first block: nothing but the sea round the raid (its centre is the player's slab, not read).
|
|
let (sim, out) = run_island(0.0, 6, &o);
|
|
assert!(!sim.sites.list.is_empty(), "no barge: {:?}", out.messages);
|
|
assert!(sim.sites.list.iter().all(|s| s.water && s.pos.y > 63.0 && s.pos.y < 64.0), "a site that is not on the surface");
|
|
assert_eq!(sim.launched, 9, "{:?}", out.messages);
|
|
let mut o2 = Out::default();
|
|
sim.draw_sites(&mut o2);
|
|
assert!(o2.models.iter().any(|m| m.name == "airdef:barge"));
|
|
}
|
|
|
|
#[test]
|
|
fn land_is_preferred_over_water_when_both_are_known() {
|
|
// An island of radius 260 in the sea; the raid is ordered 300 out: its sites stand on the island, nearer.
|
|
let o = RaidOrder { kinds: vec![(DroneKind::Shahed, 6), (DroneKind::Kh101, 3)], approach: Approach::TwoSectors, dist: 300.0, aim: Aim::Objects };
|
|
let (sim, out) = run_island(260.0, 6, &o);
|
|
assert!(!sim.sites.list.is_empty());
|
|
assert!(sim.sites.list.iter().all(|s| !s.water), "a barge where land was known: {:?} {:?}", out.messages, sim.sites.list.iter().map(|s| (s.class, s.water, s.pos, s.range)).collect::<Vec<_>>());
|
|
assert_eq!(sim.launched, 9);
|
|
}
|
|
|
|
#[test]
|
|
fn a_site_never_stands_in_a_hill_or_under_a_roof() {
|
|
// A hill 40 blocks high round the raid's ring at 300 out (radius 100): the sites find flat land elsewhere.
|
|
let hill = |x: i32, z: i32| {
|
|
let (dx, dz) = (f64::from(x) - 0.0, f64::from(z) - 300.0);
|
|
if dx * dx + dz * dz < 100.0 * 100.0 { 64 + 40 } else { 64 }
|
|
};
|
|
let land = Land(hill);
|
|
let (mut ground, mut out) = (Ground::default(), Out::default());
|
|
let mut sim = Sim::new(8);
|
|
let o = RaidOrder { kinds: vec![(DroneKind::Shahed, 5)], approach: Approach::Sector, dist: 300.0, aim: Aim::Objects };
|
|
plan(&mut sim, &mut ground, &land, &o, &mut out);
|
|
for s in &sim.sites.list {
|
|
for (dx, dz) in FOOTPRINT {
|
|
let h = hill((s.pos.x + dx).floor() as i32, (s.pos.z + dz).floor() as i32);
|
|
assert!((f64::from(h) - s.pos.y).abs() <= f64::from(FLAT), "a site over a slope");
|
|
}
|
|
}
|
|
assert!(!sim.sites.list.is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn repeated_raids_do_not_pile_up_sites_and_clear_removes_them() {
|
|
let (land, mut ground, mut out) = (flat(), Ground::default(), Out::default());
|
|
let mut sim = Sim::new(12);
|
|
plan(&mut sim, &mut ground, &land, &order(Approach::AllSides, 300.0), &mut out);
|
|
let first: Vec<u32> = sim.sites.list.iter().map(|s| s.id).collect();
|
|
for _ in 0..3000 {
|
|
step(&mut sim, &mut ground, &land, &mut out);
|
|
}
|
|
plan(&mut sim, &mut ground, &land, &order(Approach::TwoSectors, 300.0), &mut out);
|
|
assert!(sim.sites.list.iter().all(|s| !first.contains(&s.id)), "old sites stayed");
|
|
assert!(sim.sites.list.len() <= 6);
|
|
sim.clear();
|
|
assert!(sim.sites.list.is_empty() && sim.queue.is_empty());
|
|
let mut o = Out::default();
|
|
sim.draw_sites(&mut o);
|
|
assert!(o.models.is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn the_same_seed_picks_the_same_sites_and_graphics_do_not_move_them() {
|
|
let run = |draw: bool| {
|
|
let (land, mut ground, mut out) = (flat(), Ground::default(), Out::default());
|
|
let mut sim = Sim::new(33);
|
|
plan(&mut sim, &mut ground, &land, &order(Approach::AllSides, 300.0), &mut out);
|
|
if draw {
|
|
// Rendering must not spend the combat randomness.
|
|
let mut o = Out::default();
|
|
sim.draw_sites(&mut o);
|
|
assert!(!o.models.is_empty());
|
|
}
|
|
(sim.sites.list.iter().map(|s| (s.id, s.pos.x.to_bits(), s.pos.z.to_bits(), s.stock)).collect::<Vec<_>>(), sim.queue.iter().map(|q| q.0).collect::<Vec<_>>(), sim.rng.state())
|
|
};
|
|
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,
|
|
aimed: false,
|
|
});
|
|
id
|
|
}
|
|
#[test]
|
|
fn a_wave_keeps_the_site_a_strike_is_still_flying_to() {
|
|
let mut sim = Sim::new(11);
|
|
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_test_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");
|
|
}
|
|
}
|