diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..68776e1 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,6 @@ +# AirDef Project Rules + +- Active gameplay worktree is `/Users/chexit/Documents/zcode/airdef/gameplay/village-defense` (do NOT edit `/Users/chexit/Documents/zcode/airdef/airdef`). +- After completing and verifying any task that modifies code or docs, **always commit and push directly to `origin/kimi-work`** (`git push origin HEAD:kimi-work`) without asking the user first. +- If the `horizon/` engine submodule was modified, commit and push it to `ssh://git@gitea.maoniao.team:2222/chexit/horizon-airdef.git` (`HEAD:refs/heads/kimi-work`) first, then include the updated `horizon` gitlink in the main commit to `origin/kimi-work`. +- Stage only the relevant project files explicitly — never stage untracked build artifacts such as `tools/model-preview/{Cargo.lock,target/}` or untracked `target/` directories inside `horizon/`. diff --git a/airdef-mod/src/sim/orders.rs b/airdef-mod/src/sim/orders.rs index f7d2c1d..4838a09 100644 --- a/airdef-mod/src/sim/orders.rs +++ b/airdef-mod/src/sim/orders.rs @@ -37,11 +37,15 @@ impl Sam { fn finish_move(sam: &mut Sam, routes: &mut route::Routes, index: usize, now: u64, why: Option, out: &mut Out) { if let Some(why) = why { - let report = sam.job.take().is_none_or(|job| { - routes.unreachable.insert((sam.id, job), now + route::UNREACHABLE_FOR).is_none() - }); - if report { - out.messages.push(format!("{} №{}: {}", sam.kind.name(), index + 1, why.text())); + if sam.kind == SamKind::Tzm { + sam.job = None; + } else { + let report = sam.job.take().is_none_or(|job| { + routes.unreachable.insert((sam.id, job), now + route::UNREACHABLE_FOR).is_none() + }); + if report { + out.messages.push(format!("{} №{}: {}", sam.kind.name(), index + 1, why.text())); + } } } routes.map.remove(&sam.id); @@ -122,17 +126,34 @@ impl Sim { let route = routes.map.entry(sam.id).or_insert_with(|| route::Route::new(sam.pos, to, 0.0, sam.kind, now)); let (go, last) = match route.drive(ground, now, sam.pos, share) { route::Drive::Wait(why) => { - if sam.job.is_none() && route.waited(now) > 40 && !route.told { + if sam.kind != SamKind::Tzm && sam.job.is_none() && route.waited(now) > 40 && !route.told { route.told = true; out.messages.push(format!("{} №{}: {}", sam.kind.name(), n + 1, why.text())); } continue; } + route::Drive::Lift(target_y) => { + let dy = target_y - sam.pos.y; + if dy.abs() <= 0.25 { + sam.pos.y = target_y; + route.finish_lift(sam.pos); + out.sound("minecraft:block.piston.contract", sam.pos, 1.5, 0.7); + } else { + sam.pos.y += dy.clamp(-0.25, 0.25); + if now % 4 == 0 { + out.particles("minecraft:campfire_cosy_smoke", sam.pos, 0.35, DVec3::new(0.0, 0.04, 0.0), 0.01, 2); + } + if now % 20 == 0 { + out.sound("minecraft:block.piston.extend", sam.pos, 1.0, 0.8); + } + } + continue; + } route::Drive::Fail(why) => { - if why == route::Why::NoWay && route.approach_works() { + if matches!(why, route::Why::NoWay | route::Why::NoMap) && route.approach_works() { continue; } - if matches!(why, route::Why::NoWay | route::Why::Stuck) + if (sam.kind == SamKind::Tzm || matches!(why, route::Why::NoWay | route::Why::Stuck)) && route.try_works(ground, sam.pos, now, out) { continue; @@ -144,6 +165,20 @@ impl Sim { }; let flat = horizontal(go - sam.pos); if last && flat.length() < SPEED * 2.0 { + if sam.kind == SamKind::Tzm && route.work_approach() { + if route.reached(sam.pos) { + finish_move(sam, routes, n, now, None, out); + out.sound("minecraft:block.piston.contract", sam.pos, 2.0, 0.6); + continue; + } + if route.is_engineered() { + route.resume_after_works(sam.pos); + continue; + } + if route.try_works(ground, sam.pos, now, out) { + continue; + } + } let why = if route.work_approach() { if route.try_works(ground, sam.pos, now, out) { continue; @@ -152,7 +187,7 @@ impl Sim { } else { // A partial route already made measurable progress. A delivery // continues from here when the next stretch of terrain is ready. - (route.partial && sam.job.is_none()).then_some(route::Why::Partial) + (route.partial && sam.job.is_none() && sam.kind != SamKind::Tzm).then_some(route::Why::Partial) }; finish_move(sam, routes, n, now, why, out); out.sound("minecraft:block.piston.contract", sam.pos, 2.0, 0.6); @@ -174,6 +209,10 @@ impl Sim { route::Clearance::Clear(height) => height, route::Clearance::Pending => { if route.wait_ahead() { + if sam.kind == SamKind::Tzm && route.try_works(ground, sam.pos, now, out) { + route.ahead_ok(); + continue; + } finish_move(sam, routes, n, now, Some(route::Why::NoMap), out); } continue; @@ -185,6 +224,9 @@ impl Sim { sam.yaw = sam.heading; continue; } + if sam.kind == SamKind::Tzm && route.is_engineered() && route.try_works(ground, sam.pos, now, out) { + continue; + } route.blocked_ahead(next, sam.pos); continue; } @@ -192,6 +234,9 @@ impl Sim { route.ahead_ok(); let rise = y - sam.pos.y; if rise > route::STEP_UP || rise < -route::STEP_DOWN { + if sam.kind == SamKind::Tzm && route.is_engineered() && route.try_works(ground, sam.pos, now, out) { + continue; + } route.blocked_ahead(next, sam.pos); continue; } diff --git a/airdef-mod/src/sim/route.rs b/airdef-mod/src/sim/route.rs index 23520ed..3dcd2d8 100644 --- a/airdef-mod/src/sim/route.rs +++ b/airdef-mod/src/sim/route.rs @@ -12,12 +12,22 @@ use std::collections::{BinaryHeap, HashSet}; pub(super) const WORK_PER_TICK: usize = 600; /// Cells opened for one route before it settles for the nearest it got. const MAX_NODES: usize = 24_000; +/// Fast recheck budget once a reload truck has entered engineering mode. +const MAX_RECHECK_NODES: usize = 2_400; /// Ticks the search waits for land the game has not told of, before the vehicle goes as far as is known. const WAIT_MAP: u64 = 300; /// Ticks a driver waits for the column ahead. const WAIT_AHEAD: u32 = 200; /// Searches again, after a way was found blocked on the march, before giving up. const REPLANS: u32 = 16; +/// Reload trucks switch to autonomous road/bridge/lift construction quickly. +const TRUCK_REPLANS: u32 = 3; +/// Maximum engineering segments/lifts per move order for a reload truck. +const MAX_TRUCK_WORKS: u16 = 128; +/// Maximum vertical blocks lifted in one lift tower stage. +const LIFT_STEP: i32 = 24; +/// Maximum depth searched downward for structural bridge/lift support pillars. +const PILLAR_DEPTH: i32 = 24; /// The tallest step a vehicle climbs between two columns, and the deepest drop it takes. pub(super) const STEP_UP: f64 = 1.5; pub(super) const STEP_DOWN: f64 = 3.5; @@ -60,6 +70,8 @@ pub(super) enum Drive { Wait(Why), /// Drive at this point; whether it is the last, and the route ends short of the order. Go(DVec3, bool), + /// Ride a constructed vertical lift tower to `target_y`. + Lift(f64), /// Stop here, and say why. Fail(Why), } @@ -148,14 +160,13 @@ fn support(ground: &mut Ground, x: i32, z: i32, near: f64, up: f64, down: f64, n return Eval::Bad; } let mut section = None; - match ground.world.road_block(&mut section, x, top, z, now) { - None => return Eval::Pending, - // The motion-blocking map includes the surface of an open body of water. - Some(Some(true)) => {} - Some(_) => return Eval::Bad, - } if top <= high { - return Eval::Ok((top + 1) as f32); + match ground.world.road_block(&mut section, x, top, z, now) { + None => return Eval::Pending, + // The motion-blocking map includes the surface of an open body of water. + Some(Some(true)) => return Eval::Ok((top + 1) as f32), + Some(_) => return Eval::Bad, + } } for y in (low..=high).rev() { match ground.world.road_block(&mut section, x, y, z, now) { @@ -186,6 +197,7 @@ impl PartialOrd for Open { enum Phase { Search, Follow, + Lift { target_y: f64, settle: u8 }, } /// One vehicle's way to its destination. @@ -215,7 +227,8 @@ pub(super) struct Route { truck: bool, work_approach: bool, work_wait: u32, - works: u8, + works: u16, + build_settle: u8, phase: Phase, pts: Vec, next: usize, @@ -286,11 +299,12 @@ impl Route { stuck_since: None, near: ((0, 0), f64::MAX), expanded: 0, - goal_checked: slack > 0.0, - truck: kind == SamKind::Tzm && slack > 0.0, + goal_checked: slack > 0.0 || kind == SamKind::Tzm, + truck: kind == SamKind::Tzm, work_approach: false, work_wait: 0, works: 0, + build_settle: 0, phase: Phase::Search, pts: Vec::new(), next: 0, @@ -316,10 +330,13 @@ impl Route { horizontal(self.centre(c) - self.dest).length() } fn is_goal(&self, c: (i32, i32)) -> bool { + let Some(info) = self.cells.get(&c) else { + return false; + }; if self.slack == 0.0 { - return c == self.cell_of(self.dest); + return c == self.cell_of(self.dest) + && (!self.truck || (f64::from(info.h) - self.dest.y).abs() <= 2.5); } - let Some(info) = self.cells.get(&c) else { return false }; let p = self.centre(c); DVec3::new(p.x, f64::from(info.h), p.z).distance(self.dest) <= self.slack } @@ -522,7 +539,8 @@ impl Route { } // Let pending footprint queries settle before opening a broad, less useful frontier. // Otherwise three trucks can saturate the shared world budget without ever moving. - if self.expanded >= MAX_NODES { + let node_cap = if self.truck && self.works > 0 { MAX_RECHECK_NODES } else { MAX_NODES }; + if self.expanded >= node_cap { self.settle(now); return; } @@ -600,7 +618,8 @@ impl Route { self.bad.insert(c); } self.replans += 1; - if self.replans > REPLANS { + let limit = if self.truck { TRUCK_REPLANS } else { REPLANS }; + if self.replans > limit { self.failed = Some(Why::Stuck); } else { self.restart(pos); @@ -621,6 +640,17 @@ impl Route { /// What the vehicle at `pos` does: works the search on its share of the tick, then follows the way. pub(super) fn drive(&mut self, ground: &mut Ground, now: u64, pos: DVec3, budget: usize) -> Drive { + if let Phase::Lift { target_y, settle } = &mut self.phase { + if *settle > 0 { + *settle -= 1; + return Drive::Wait(Why::Map); + } + return Drive::Lift(*target_y); + } + if self.build_settle > 0 { + self.build_settle -= 1; + return Drive::Wait(Why::Map); + } if self.phase == Phase::Search && self.failed.is_none() { self.search(ground, now, budget); } @@ -637,9 +667,40 @@ impl Route { Drive::Go(self.pts[self.next], self.next + 1 >= self.pts.len()) } + pub(super) fn goal_slack(&self) -> f64 { + if self.slack > 0.0 { self.slack } else { 2.0 } + } + + pub(super) fn reached(&self, pos: DVec3) -> bool { + pos.distance(self.dest) <= self.goal_slack() + } + + pub(super) fn is_engineered(&self) -> bool { + self.works > 0 + } + + pub(super) fn resume_after_works(&mut self, pos: DVec3) { + self.failed = None; + self.work_approach = false; + self.restart(pos); + } + + pub(super) fn finish_lift(&mut self, pos: DVec3) { + self.failed = None; + if self.reached(pos) { + self.pts = vec![pos]; + self.next = 0; + self.phase = Phase::Follow; + self.work_approach = false; + self.partial = false; + } else { + self.resume_after_works(pos); + } + } + /// Let an automatic delivery approach the nearest reachable spot before trying local roadwork. pub(super) fn approach_works(&mut self) -> bool { - if !self.truck || self.works >= 2 || self.near.0 == self.start + if !self.truck || self.works >= MAX_TRUCK_WORKS || self.near.0 == self.start || self.to_goal(self.start) - self.near.1 < f64::from(self.cell) { return false; @@ -654,90 +715,316 @@ impl Route { self.work_approach } - /// Make a short local crossing only after route search or motion finds a blockage. - /// Returns true while waiting for terrain data or after requesting the edits. + /// Autonomous engineering builder for reload trucks: builds 1:2 ramps/staircases, bridges with support pillars, + /// clears dense trees/rock walls/tunnels, and constructs vertical lift towers so any complex is reachable. + /// Returns true while waiting for terrain chunks or after emitting construction commands. pub(super) fn try_works(&mut self, ground: &mut Ground, pos: DVec3, now: u64, out: &mut Out) -> bool { - if !self.truck || self.works >= 2 || self.work_wait >= 60 { + if !self.truck || self.works >= MAX_TRUCK_WORKS { return false; } - self.work_wait += 1; - let direction = horizontal(self.dest - pos); - let (dx, dz) = if direction.x.abs() >= direction.z.abs() { - (if direction.x >= 0.0 { 1 } else { -1 }, 0) - } else { - (0, if direction.z >= 0.0 { 1 } else { -1 }) - }; - let coord = |row: i32, side: i32| ( - pos.x.floor() as i32 + dx * row + dz * side, - pos.z.floor() as i32 + dz * row + dx * side, - ); - let width = self.chassis.radius.ceil() as i32; - let start = pos.y.round() as i32; - let (ex, ez) = coord(10, 0); - let Some(Some(end)) = ground.column(ex, ez, 1024) else { - ground.want_chunk((ex >> 4, ez >> 4)); + if self.reached(pos) { + self.failed = None; + self.pts = vec![pos]; + self.next = 0; + self.phase = Phase::Follow; + self.work_approach = false; + self.partial = false; return true; - }; - let end = end.round() as i32; - if (end - start).abs() > 2 || !(-63..=320).contains(&start) || !(-63..=320).contains(&end) { + } + let hdist = horizontal(self.dest - pos).length(); + let dy = self.dest.y - pos.y; + let lift_radius = (self.goal_slack() + 2.0).max(11.0); + if dy.abs() > 2.5 && hdist <= lift_radius { + return self.build_lift(ground, pos, out); + } + self.build_segment(ground, pos, now, out) + } + + fn build_lift(&mut self, ground: &mut Ground, pos: DVec3, out: &mut Out) -> bool { + let start_y = (pos.y.round() as i32).clamp(-62, 315); + let goal_y = (self.dest.y.round() as i32).clamp(-62, 315); + let stage_y = (start_y + (goal_y - start_y).clamp(-LIFT_STEP, LIFT_STEP)).clamp(-62, 315); + if stage_y == start_y { return false; } + let cx = pos.x.floor() as i32; + let cz = pos.z.floor() as i32; + let w = self.chassis.radius.ceil() as i32; + let y_lo = start_y.min(stage_y); + let y_hi = start_y.max(stage_y); let mut commands = Vec::new(); - for row in 1..=10 { - let level = start + ((end - start) as f64 * f64::from(row) / 10.0).round() as i32; - let mut deck = false; - for side in -width..=width { - let (x, z) = coord(row, side); - let Some(Some(top)) = ground.column(x, z, 1024) else { - ground.want_chunk((x >> 4, z >> 4)); - return true; - }; - let top = top.round() as i32; - if top > level + 2 { - return false; - } - let p = DVec3::new(f64::from(x) + 0.5, f64::from(level), f64::from(z) + 0.5); - match ground.world.sweep(p + DVec3::Y * 0.25, p - DVec3::Y * 0.25, false, now) { - world::Sweep::Hit { .. } if top >= level => {} - world::Sweep::Hit { .. } | world::Sweep::Clear => deck = true, - _ => return true, - } - if top > level { - // Only shallow natural cover is cleared. Vanilla fills preserve other materials. - for block in ["short_grass", "fern", "snow", "dirt", "grass_block", "sand", "gravel"] { - commands.push(format!("fill {x} {level} {z} {x} {} {z} minecraft:air replace minecraft:{block}", top - 1)); - } - } - } - if deck { - let (ax, az) = coord(row, -width); - let (bx, bz) = coord(row, width); - let y = level - 1; - for block in ["air", "water"] { - commands.push(format!("fill {ax} {y} {az} {bx} {y} {bz} minecraft:cobblestone replace minecraft:{block}")); - } + // Clear vertical lift shaft headroom so trees/overhangs/rock never block the climb. + commands.push(format!( + "fill {} {} {} {} {} {} minecraft:air", + cx - w, y_lo, cz - w, cx + w, (y_hi + 6).min(319), cz + w + )); + // Four corner stone-brick lift towers plus foundation columns below the shaft bottom. + let top_t = (y_hi + 4).min(319); + let bot_t = (y_lo - 1).max(-63); + let found_bot = (y_lo - PILLAR_DEPTH).max(-63); + for (px, pz) in [(cx - w - 1, cz - w - 1), (cx - w - 1, cz + w + 1), (cx + w + 1, cz - w - 1), (cx + w + 1, cz + w + 1)] { + commands.push(format!("fill {px} {bot_t} {pz} {px} {top_t} {pz} minecraft:stone_bricks")); + if found_bot < bot_t { + commands.push(format!("fill {px} {found_bot} {pz} {px} {} {pz} minecraft:stone_bricks keep", bot_t - 1)); + commands.push(format!("fill {px} {found_bot} {pz} {px} {} {pz} minecraft:stone_bricks replace minecraft:water", bot_t - 1)); } } - if commands.is_empty() || out.commands.len() + commands.len() > 192 { - return false; + // Solid landing platform at the target elevation of this lift stage. + let deck_y = (stage_y - 1).clamp(-63, 318); + commands.push(format!( + "fill {} {deck_y} {} {} {deck_y} {} minecraft:cobblestone replace minecraft:water", + cx - w, cz - w, cx + w, cz + w + )); + commands.push(format!( + "fill {} {deck_y} {} {} {deck_y} {} minecraft:stone_bricks", + cx - w, cz - w, cx + w, cz + w + )); + if out.commands.len() + commands.len() > 220 { + return true; } out.commands.extend(commands); - let centre = pos + DVec3::new(f64::from(dx * 5), 0.0, f64::from(dz * 5)); - ground.forget(centre, 9); - let (cx, cz) = (centre.x.floor() as i32, centre.z.floor() as i32); + let r = w + 4; + ground.forget(pos, r); let mut chunks = Vec::new(); - for x in (cx - 9).div_euclid(16)..=(cx + 9).div_euclid(16) { - for z in (cz - 9).div_euclid(16)..=(cz + 9).div_euclid(16) { + for x in (cx - r).div_euclid(16)..=(cx + r).div_euclid(16) { + for z in (cz - r).div_euclid(16)..=(cz + r).div_euclid(16) { + ground.want_chunk((x, z)); chunks.push((x, z)); } } ground.world.columns_changed(&chunks); - self.works += 1; + self.works = self.works.saturating_add(1); self.replans = 0; + self.work_wait = 0; self.failed = None; self.bad.clear(); self.cells.clear(); - self.restart(pos); + self.work_approach = false; + self.phase = Phase::Lift { target_y: f64::from(stage_y), settle: 3 }; + true + } + + fn build_segment(&mut self, ground: &mut Ground, pos: DVec3, now: u64, out: &mut Out) -> bool { + let direction = horizontal(self.dest - pos); + let (dx, dz, axis_rem) = if direction.x.abs() >= direction.z.abs() { + (if direction.x >= 0.0 { 1 } else { -1 }, 0, direction.x.abs()) + } else { + (0, if direction.z >= 0.0 { 1 } else { -1 }, direction.z.abs()) + }; + let len = (axis_rem.ceil() as i32).clamp(2, 6); + let w = self.chassis.radius.ceil() as i32; + let base_x = pos.x.floor() as i32; + let base_z = pos.z.floor() as i32; + let coord = |row: i32, side: i32| (base_x + dx * row + dz * side, base_z + dz * row + dx * side); + + let row_min = -3; + let row_max = len + 3; + let start_y = (pos.y.round() as i32).clamp(-62, 315); + let goal_y = (self.dest.y.round() as i32).clamp(-62, 315); + let max_step = (len / 2).max(1); + + // Inspect columns & wait briefly for missing terrain chunks before conservatively building through. + let mut missing_chunk = false; + let mut max_water_y: Option = None; + let mut col_top: HashMap<(i32, i32), i32> = HashMap::new(); + for row in row_min..=row_max { + for side in -w..=w { + let (x, z) = coord(row, side); + match ground.column(x, z, 1024) { + Some(Some(top)) => { + let t = top.round() as i32; + col_top.insert((x, z), t); + let mut sec = None; + if row >= 0 + && row <= len + && ground.world.road_block(&mut sec, x, t - 1, z, now) == Some(Some(false)) + && ground.world.road_block(&mut sec, x, t - 2, z, now) == Some(Some(false)) + { + let wy = t.clamp(-62, 315); + max_water_y = Some(max_water_y.map_or(wy, |m: i32| m.max(wy))); + } + } + Some(None) => {} + None => { + missing_chunk = true; + ground.want_chunk((x >> 4, z >> 4)); + } + } + } + } + if missing_chunk && self.work_wait < 40 { + self.work_wait += 1; + return true; + } + + let mut target_dy = (goal_y - start_y).clamp(-max_step, max_step); + if let Some(wy) = max_water_y { + let min_end = (wy - start_y).min(max_step); + if target_dy < min_end { + target_dy = min_end; + } + } + let end_y = (start_y + target_dy).clamp(-62, 315); + let level_at = |row: i32| -> i32 { + if row <= 0 { + start_y + } else if row >= len { + end_y + } else { + (start_y + (target_dy * row) / len).clamp(-62, 315) + } + }; + + let mut commands = Vec::new(); + let force = self.work_wait >= 40; + let mut pillar_rows = Vec::new(); + let mut rail_rows = Vec::new(); + for row in row_min..=row_max { + let level = level_at(row); + let deck_y = (level - 1).clamp(-63, 318); + let (ax, az) = coord(row, -w); + let (bx, bz) = coord(row, w); + + // 1. Clear overhanging foliage, trees, snow, cliffs or cave walls above roadbed. + let mut need_clear = false; + 'clr: for side in -w..=w { + let (x, z) = coord(row, side); + if let Some(&t) = col_top.get(&(x, z)) + && t > level + { + let mut sec = None; + for y in level..=(level + 6).min(319) { + match ground.world.road_block(&mut sec, x, y, z, now) { + Some(Some(true)) => { + need_clear = true; + break 'clr; + } + None if force => { + need_clear = true; + break 'clr; + } + _ => {} + } + } + } + } + if need_clear { + commands.push(format!( + "fill {ax} {level} {az} {bx} {} {bz} minecraft:air", + (level + 6).min(319) + )); + } + + // 2. Build solid deck across water, ravines, gaps, or stepped slopes. + let mut need_deck = false; + for side in -w..=w { + let (x, z) = coord(row, side); + let mut sec = None; + let solid = ground.world.road_block(&mut sec, x, deck_y, z, now); + if solid != Some(Some(true)) && (solid.is_some() || force) { + need_deck = true; + break; + } + } + if need_deck { + commands.push(format!("fill {ax} {deck_y} {az} {bx} {deck_y} {bz} minecraft:cobblestone replace minecraft:water")); + commands.push(format!("fill {ax} {deck_y} {az} {bx} {deck_y} {bz} minecraft:cobblestone replace minecraft:air")); + commands.push(format!("fill {ax} {deck_y} {az} {bx} {deck_y} {bz} minecraft:stone_bricks")); + } + + // 3. Detect suspended span for vertical support pillars and bridge edge walls. + if (0..=len).contains(&row) { + let mut suspended = false; + for edge in [-w, w] { + let (ex, ez) = coord(row, edge); + let mut sec = None; + if ground.world.road_block(&mut sec, ex, deck_y - 1, ez, now) != Some(Some(true)) { + suspended = true; + break; + } + } + if suspended { + if row == 0 || row == len || row.rem_euclid(4) == 0 { + pillar_rows.push((row, deck_y)); + } + rail_rows.push((row, level)); + } + } + } + + for (row, deck_y) in pillar_rows { + if deck_y <= -62 { + continue; + } + let top_p = deck_y - 1; + let min_p = (deck_y - PILLAR_DEPTH).max(-63); + for edge in [-w, w] { + let (px, pz) = coord(row, edge); + let mut sec = None; + let mut bot_p = min_p; + for y in (min_p..=top_p).rev() { + if ground.world.road_block(&mut sec, px, y, pz, now) == Some(Some(true)) { + bot_p = (y + 1).min(top_p); + break; + } + } + if bot_p <= top_p { + commands.push(format!("fill {px} {bot_p} {pz} {px} {top_p} {pz} minecraft:stone_bricks keep")); + commands.push(format!("fill {px} {bot_p} {pz} {px} {top_p} {pz} minecraft:stone_bricks replace minecraft:water")); + } + } + } + + // Batch low stone bridge curbs outside the truck chassis on elevated/water spans. + for (row, level) in rail_rows { + if commands.len() >= 180 { + break; + } + for side in [-(w + 1), w + 1] { + let (rx, rz) = coord(row, side); + commands.push(format!("fill {rx} {level} {rz} {rx} {level} {rz} minecraft:cobblestone_wall keep")); + } + } + + if out.commands.len() + commands.len() > 220 { + return true; + } + out.commands.extend(commands); + + let mid_row = len / 2; + let (mx, mz) = coord(mid_row, 0); + let centre = DVec3::new(f64::from(mx) + 0.5, f64::from(end_y), f64::from(mz) + 0.5); + let radius = len / 2 + w + 4; + ground.forget(centre, radius); + let mut chunks = Vec::new(); + for x in (mx - radius).div_euclid(16)..=(mx + radius).div_euclid(16) { + for z in (mz - radius).div_euclid(16)..=(mz + radius).div_euclid(16) { + ground.want_chunk((x, z)); + chunks.push((x, z)); + } + } + ground.world.columns_changed(&chunks); + + let (ex, ez) = coord(len, 0); + let dest_pt = if horizontal(self.dest - DVec3::new(f64::from(ex) + 0.5, f64::from(end_y), f64::from(ez) + 0.5)).length() + < self.goal_slack() * 0.5 + { + DVec3::new(self.dest.x, f64::from(end_y), self.dest.z) + } else { + DVec3::new(f64::from(ex) + 0.5, f64::from(end_y), f64::from(ez) + 0.5) + }; + self.works = self.works.saturating_add(1); + self.replans = 0; + self.work_wait = 0; + self.failed = None; + self.bad.clear(); + self.cells.clear(); + self.pts = vec![dest_pt]; + self.next = 0; + self.partial = true; + self.work_approach = true; + self.build_settle = 2; + self.phase = Phase::Follow; true } @@ -1059,4 +1346,185 @@ mod tests { let (sim, _, _) = march_kind(SamKind::S400, walls, walls, DVec3::new(60.5, 64.0, 0.5), 5000); assert!(!sim.sams[0].moving() && sim.sams[0].pos.distance(DVec3::new(60.5, 64.0, 0.5)) < 3.0, "pos={:?} state={:?}", sim.sams[0].pos, sim.sams[0].state); } + + #[derive(Clone, Copy, PartialEq, Eq)] + enum Voxel { + Air, + Water, + Solid, + } + + struct EditableWorld Voxel> { + base: F, + edits: HashMap<(i32, i32, i32), Voxel>, + } + + impl Voxel> EditableWorld { + fn new(base: F) -> Self { + Self { base, edits: HashMap::new() } + } + + fn get(&self, x: i32, y: i32, z: i32) -> Voxel { + self.edits.get(&(x, y, z)).copied().unwrap_or_else(|| (self.base)(x, y, z)) + } + + fn motion_top(&self, x: i32, z: i32) -> i32 { + for y in (20..=140).rev() { + if self.get(x, y, z) != Voxel::Air { + return y + 1; + } + } + 20 + } + + fn apply(&mut self, commands: Vec) { + for cmd in commands { + let w: Vec<&str> = cmd.split_whitespace().collect(); + assert!(w.len() >= 8 && w[0] == "fill", "unexpected command: {cmd}"); + let x0: i32 = w[1].parse().unwrap(); + let y0: i32 = w[2].parse().unwrap(); + let z0: i32 = w[3].parse().unwrap(); + let x1: i32 = w[4].parse().unwrap(); + let y1: i32 = w[5].parse().unwrap(); + let z1: i32 = w[6].parse().unwrap(); + let target = if w[7] == "minecraft:air" { Voxel::Air } else { Voxel::Solid }; + let mode = w.get(8).copied(); + let filter = w.get(9).copied().map(|b| match b { + "minecraft:water" => Voxel::Water, + "minecraft:air" => Voxel::Air, + _ => Voxel::Solid, + }); + for y in y0.min(y1)..=y0.max(y1) { + for z in z0.min(z1)..=z0.max(z1) { + for x in x0.min(x1)..=x0.max(x1) { + let cur = self.get(x, y, z); + let apply = match (mode, filter) { + (Some("keep"), _) => cur == Voxel::Air, + (Some("replace"), Some(f)) => cur == f, + _ => true, + }; + if apply { + self.edits.insert((x, y, z), target); + } + } + } + } + } + } + } + + impl Voxel> world::WorldSource for EditableWorld { + fn solid(&self, x: i32, y: i32, z: i32) -> Option { + Some(self.get(x, y, z) == Voxel::Solid) + } + } + + fn drive_tzm Voxel>(from: DVec3, to: DVec3, world_fn: F, ticks: u32) -> (Sim, EditableWorld, Out) { + let mut world = EditableWorld::new(world_fn); + let mut sim = Sim::new(7); + sim.damage = false; + let id = sim.id(); + sim.sams.push(Sam::new(id, SamKind::Tzm, from, 0.0)); + sim.sams[0].job = Some(42); + assert!(sim.order_move_near(0, to, HANDOVER - 0.75)); + let mut ground = Ground::default(); + let mut out = Out::default(); + for _ in 0..ticks { + sim.tick += 1; + let cols = ground.take_wanted().into_iter().map(|(x, z)| (x, z, world.motion_top(x, z))).collect(); + ground.answer(cols, sim.tick); + let secs = ground.world.take_wanted(sim.tick); + ground.world.serve(&world, secs, sim.tick); + sim.step_moves(&mut ground, &mut out); + world.apply(out.commands.drain(..).collect()); + if !sim.sams[0].moving() { + break; + } + } + (sim, world, out) + } + + #[test] + fn a_supply_truck_builds_stairs_and_pillars_up_a_mountain_to_an_elevated_sam() { + let from = DVec3::new(4.5, 64.0, 0.5); + let to = DVec3::new(68.5, 82.0, 0.5); + let (sim, world, out) = drive_tzm(from, to, |x, y, _| { + let floor = if x < 20 { 64 } else if x < 42 { 76 } else { 82 }; + if y < floor { Voxel::Solid } else { Voxel::Air } + }, 3000); + assert!(!sim.sams[0].moving(), "still moving at {:?}", sim.sams[0].pos); + assert!(sim.sams[0].pos.distance(to) <= HANDOVER, "pos={:?} to={to:?}", sim.sams[0].pos); + assert!(out.messages.is_empty(), "{:?}", out.messages); + assert!(sim.routes.unreachable.is_empty()); + assert!(world.edits.iter().any(|(&(x, y, _), &v)| x >= 20 && y >= 64 && v == Voxel::Solid)); + } + + #[test] + fn a_supply_truck_uses_lift_to_reach_a_sam_on_a_tall_tree_or_spire() { + let from = DVec3::new(8.5, 64.0, 0.5); + let to = DVec3::new(38.5, 82.0, 0.5); + let (sim, world, out) = drive_tzm(from, to, |x, y, z| { + let spire = (36..=40).contains(&x) && (-2..=2).contains(&z); + let floor = if spire { 82 } else { 64 }; + if y < floor { Voxel::Solid } else { Voxel::Air } + }, 2500); + assert!(!sim.sams[0].moving(), "still moving at {:?}", sim.sams[0].pos); + assert!(sim.sams[0].pos.distance(to) <= HANDOVER, "pos={:?} to={to:?}", sim.sams[0].pos); + assert!(sim.sams[0].pos.y >= 81.0, "expected truck on elevated spire, got {:?}", sim.sams[0].pos); + assert!(out.messages.is_empty(), "{:?}", out.messages); + assert!(sim.routes.unreachable.is_empty()); + assert!(world.edits.iter().any(|(&(_, y, _), &v)| y >= 78 && v == Voxel::Solid)); + } + + #[test] + fn a_supply_truck_descends_into_a_deep_ravine_and_clears_forest_without_complaining() { + let from = DVec3::new(4.5, 64.0, 0.5); + let to = DVec3::new(48.5, 48.0, 0.5); + let (sim, _world, out) = drive_tzm(from, to, |x, y, z| { + if (14..22).contains(&x) && z.abs() <= 6 && (64..74).contains(&y) { + return Voxel::Solid; // Dense trees and canopy blocking headroom. + } + let floor = if x < 24 { + 64 + } else if z.abs() >= 6 { + 72 + } else { + 48 + }; + if y < floor { Voxel::Solid } else { Voxel::Air } + }, 3000); + assert!(!sim.sams[0].moving(), "still moving at {:?}", sim.sams[0].pos); + assert!(sim.sams[0].pos.distance(to) <= HANDOVER, "pos={:?} to={to:?}", sim.sams[0].pos); + assert!(out.messages.is_empty(), "{:?}", out.messages); + assert!(sim.routes.unreachable.is_empty()); + } + + #[test] + fn a_supply_truck_bridges_a_wide_canyon_with_support_pillars() { + let from = DVec3::new(8.5, 64.0, 0.5); + let to = DVec3::new(60.5, 64.0, 0.5); + let (sim, world, out) = drive_tzm(from, to, |x, y, _| { + if (20..48).contains(&x) { + if y < 54 { + Voxel::Solid + } else if y < 64 { + Voxel::Water + } else { + Voxel::Air + } + } else if y < 64 { + Voxel::Solid + } else { + Voxel::Air + } + }, 3000); + assert!(!sim.sams[0].moving(), "still moving at {:?}", sim.sams[0].pos); + assert!(sim.sams[0].pos.distance(to) <= HANDOVER, "pos={:?} to={to:?}", sim.sams[0].pos); + assert!(out.messages.is_empty(), "{:?}", out.messages); + assert!(sim.routes.unreachable.is_empty()); + assert!( + world.edits.iter().any(|(&(x, y, _), &v)| (20..48).contains(&x) && (54..63).contains(&y) && v == Voxel::Solid), + "expected vertical bridge support pillars under deck in canyon" + ); + } }