Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion aravath_runtime/golden/replay.hash
Original file line number Diff line number Diff line change
@@ -1 +1 @@
b663da52ea1d566e
0a576578512f25d2
71 changes: 58 additions & 13 deletions aravath_runtime/src/ground.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,38 @@

use std::collections::{HashMap, HashSet};

use astraweave_destruction::command::{Brush, BrushOp, BrushShape};
use astraweave_destruction::{ColumnFns, DestructionWorld};
use astraweave_physics::{Layers, PhysicsWorld};
use astraweave_render::mesh::{CpuMesh, MeshVertex as RenderVertex};
use astraweave_terrain::column_gen::{
self, biome_at as seed_biome, column_material as seed_material,
};
use astraweave_terrain::{
ChunkCoord, ChunkMesh, ColumnStream, DualContouring, MeshVertex, Voxel, VoxelGrid,
};
use glam::{Vec2, Vec3, Vec4};

use crate::island::{self, biome_at, column_material, Biome, MAT_WOOD};

fn column_demolition() -> DestructionWorld {
let mut world = DestructionWorld::new(column_gen::FOREST_WORLD_SEED, 0);
world.bind_column_fns(ColumnFns {
top: column_gen::surface_height,
material: seed_column_material,
});
world
}

fn seed_column_material(x: i32, y: i32, z: i32) -> u16 {
seed_material(
y,
column_gen::surface_height(x, z),
seed_biome(x, z),
column_gen::on_yaqar_road(x, z),
)
}

pub struct ChunkPart {
pub material: u16,
pub mesh: CpuMesh,
Expand Down Expand Up @@ -65,6 +88,7 @@ pub struct Ground {
bodies: HashMap<ChunkCoord, u64>,
generated: HashSet<ChunkCoord>,
stream: ColumnStream,
demolition: Box<DestructionWorld>,
scatter: HashMap<ChunkCoord, Vec<PropSpot>>,
/// Chunk the ring was built around, plus the radius. A settled player
/// whose grid is clean skips the set rebuild.
Expand All @@ -89,6 +113,7 @@ impl Ground {
bodies: HashMap::new(),
generated: HashSet::new(),
stream: ColumnStream::new(),
demolition: Box::new(column_demolition()),
scatter: HashMap::new(),
stream_key: None,
}
Expand Down Expand Up @@ -202,22 +227,42 @@ impl Ground {
uploads
}

/// Write air voxels. Caller runs [`Self::sync_dirty`] afterwards.
/// Dig with a destruction brush. Occupancy is the integer column plus the
/// command log. The voxel grid is the mesh of that occupancy.
pub fn dig_sphere(&mut self, center: Vec3, radius: f32) {
let r = radius.ceil() as i32;
let origin = IVecFloor::from_vec(center);
for x in -r..=r {
for y in -r..=r {
for z in -r..=r {
let p = Vec3::new(
(origin.x + x) as f32,
(origin.y + y) as f32,
(origin.z + z) as f32,
);
if p.distance(center) <= radius {
self.grid.set_voxel(p, Voxel::new(0.0, 0));
self.remember(p, 0.0, 0);
let reach = radius.ceil().max(1.0) as i32;
let brush = Brush {
shape: BrushShape::Sphere,
op: BrushOp::Subtract,
origin: [origin.x, origin.y, origin.z],
radius: reach as u16,
half_extents: [1, 1, 1],
strength: 4,
};
if self.demolition.apply_brush_now(brush).is_err() {
return;
}
let limit = reach * reach;
for dz in -reach..=reach {
for dy in -reach..=reach {
for dx in -reach..=reach {
if dx * dx + dy * dy + dz * dz > limit {
continue;
}
let x = origin.x + dx;
let y = origin.y + dy;
let z = origin.z + dz;
let seed = column_gen::surface_height(x, z);
let dug = self.demolition.terrain().surface_y(x, z);
let drop = seed.saturating_sub(dug);
Comment on lines +256 to +258

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Restore brush history when loading terrain edits

When a checkpoint containing earlier digs is loaded, Ground::restore_edits recreates the voxel grid but does not restore this new DestructionWorld, so drop is computed from an empty brush log after a restart or a stale log when loading an older checkpoint in-process. A subsequent dig can therefore remove nothing until the log catches up, or over-dig relative to the restored terrain; persist/replay the demolition commands or rebuild its occupancy alongside the voxel edits.

Useful? React with 👍 / 👎.

let mesh_top = island::surface_height(x, z);
if drop <= 0 || y <= mesh_top.saturating_sub(drop) {
continue;
}
let p = Vec3::new(x as f32, y as f32, z as f32);
self.grid.set_voxel(p, Voxel::new(0.0, 0));
self.remember(p, 0.0, 0);
}
}
}
Expand Down
14 changes: 14 additions & 0 deletions aravath_runtime/src/sim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,8 @@ pub struct Greybox {
/// by asking `catch_up` to spend it.
accumulator: f64,
pub tick: u64,
/// Bridge collapse and the ford. Does not drive the character motor.
pub bridge: Box<crate::bridge_agent::BridgeAgent>,
}

impl Greybox {
Expand Down Expand Up @@ -140,6 +142,7 @@ impl Greybox {
scars: ScarField::new(),
accumulator: 0.0,
tick: 0,
bridge: Box::new(crate::bridge_agent::BridgeAgent::new()),
}
}

Expand Down Expand Up @@ -167,6 +170,7 @@ impl Greybox {
scars: ScarField::new(),
accumulator: 0.0,
tick: 0,
bridge: Box::new(crate::bridge_agent::BridgeAgent::new()),
}
}

Expand Down Expand Up @@ -235,6 +239,8 @@ impl Greybox {
self.combat.toggle_lock(&self.physics, &self.player);
}
self.tick_controls(input.motor);
// Collapse notices update nav tiles. The motor is not called here.
self.bridge.step(self.tick);
if input.dig {
let uploads = self.dig_ahead(2.5);
self.pending_uploads.extend(uploads);
Expand Down Expand Up @@ -308,6 +314,11 @@ impl Greybox {
}
hash.u8(loco_tag(self.graph.state));
hash.f32(self.graph.time);
hash.i32(self.bridge.route_x_milli);
hash.bool(self.bridge.setup_ok);
for value in self.bridge.cut_milli {
hash.i32(value);
}
hash.u64(self.ground.edits.len() as u64);
for edit in &self.ground.edits {
hash.i32(edit.x);
Expand Down Expand Up @@ -834,6 +845,9 @@ mod tests {
fn replay_matches_golden_hash() {
let sim = play(&recorded_script());
let got = format!("{:016x}", sim.state_hash());
// Intended move off b663da52ea1d566e to 0a576578512f25d2: the
// scripted dig is a DestructionCommand brush on the integer columns,
// and the hash includes the bridge-collapse route. The motor is unchanged.
let golden = include_str!("../golden/replay.hash").trim();
assert_eq!(
got, golden,
Expand Down
91 changes: 47 additions & 44 deletions astraweave-author/tests/mutation_resistant_comprehensive_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
//! run_author_script (with a real Rhai script file).

use astraweave_author::MapMeta;
use std::io::Write;

// =========================================================================
// MapMeta — field access, clone, boundary values
Expand Down Expand Up @@ -106,29 +105,42 @@ fn map_meta_min_difficulty() {
// run_author_script — with a real Rhai file
// =========================================================================

/// The loader rejects paths outside the working directory. Keep the file there.
fn script_in_workdir(name: &str, source: &str) -> (tempfile::TempDir, String) {
let root = std::env::current_dir().expect("workdir");
let dir = tempfile::tempdir_in(&root).expect("script dir under workdir");
let file = dir.path().join(name);
std::fs::write(&file, source).expect("write script");
let rel = file
.strip_prefix(&root)
.expect("script stays under workdir");
let text = rel
.components()
.map(|component| component.as_os_str().to_string_lossy().into_owned())
.collect::<Vec<_>>()
.join("/");
(dir, text)
}

#[test]
fn run_author_script_simple() {
let dir = tempfile::tempdir().unwrap();
let script_path = dir.path().join("test.rhai");
let mut f = std::fs::File::create(&script_path).unwrap();
write!(
f,
let (_dir, script_path) = script_in_workdir(
"test.rhai",
r#"
fn configure(meta) {{
fn configure(meta) {
let traps = meta.difficulty * 2;
let terrain_edits = meta.width / 10;
let spawns = meta.enemy_count;
let hints = #{{"tip": "use cover"}};
#{{
let hints = #{"tip": "use cover"};
#{
traps: traps,
terrain_edits: terrain_edits,
spawns: spawns,
hints: hints
}}
}}
"#
)
.unwrap();
}
}
"#,
);

let meta = MapMeta {
width: 100,
Expand All @@ -137,7 +149,7 @@ fn configure(meta) {{
difficulty: 3,
};
let (budget, hints) =
astraweave_author::run_author_script(script_path.to_str().unwrap(), &meta).unwrap();
astraweave_author::run_author_script(&script_path, &meta).expect("script under workdir");

assert_eq!(budget.traps, 6); // difficulty(3) * 2
assert_eq!(budget.terrain_edits, 10); // width(100) / 10
Expand All @@ -147,19 +159,15 @@ fn configure(meta) {{

#[test]
fn run_author_script_defaults_on_missing_keys() {
let dir = tempfile::tempdir().unwrap();
let script_path = dir.path().join("minimal.rhai");
let mut f = std::fs::File::create(&script_path).unwrap();
// Return empty map — defaults: traps=1, terrain_edits=2, spawns=1
write!(
f,
// Empty map — defaults: traps=1, terrain_edits=2, spawns=1
let (_dir, script_path) = script_in_workdir(
"minimal.rhai",
r#"
fn configure(meta) {{
#{{}}
}}
"#
)
.unwrap();
fn configure(meta) {
#{}
}
"#,
);

let meta = MapMeta {
width: 10,
Expand All @@ -168,7 +176,7 @@ fn configure(meta) {{
difficulty: 1,
};
let (budget, hints) =
astraweave_author::run_author_script(script_path.to_str().unwrap(), &meta).unwrap();
astraweave_author::run_author_script(&script_path, &meta).expect("script under workdir");

assert_eq!(budget.traps, 1); // default
assert_eq!(budget.terrain_edits, 2); // default
Expand All @@ -190,29 +198,24 @@ fn run_author_script_nonexistent_file_errors() {

#[test]
fn run_author_script_meta_fields_passed_correctly() {
let dir = tempfile::tempdir().unwrap();
let script_path = dir.path().join("echo.rhai");
let mut f = std::fs::File::create(&script_path).unwrap();
// Echo back all meta fields as hints so we can verify they arrived
write!(
f,
let (_dir, script_path) = script_in_workdir(
"echo.rhai",
r#"
fn configure(meta) {{
#{{
fn configure(meta) {
#{
traps: 1,
terrain_edits: 2,
spawns: 1,
hints: #{{
hints: #{
w: meta.width,
h: meta.height,
e: meta.enemy_count,
d: meta.difficulty
}}
}}
}}
"#
)
.unwrap();
}
}
}
"#,
);

let meta = MapMeta {
width: 42,
Expand All @@ -221,7 +224,7 @@ fn configure(meta) {{
difficulty: 4,
};
let (_, hints) =
astraweave_author::run_author_script(script_path.to_str().unwrap(), &meta).unwrap();
astraweave_author::run_author_script(&script_path, &meta).expect("script under workdir");

assert_eq!(hints["w"], 42);
assert_eq!(hints["h"], 99);
Expand Down
22 changes: 22 additions & 0 deletions astraweave-destruction/src/column_base.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
//! Integer column hook for the Aravath ground.
//!
//! The functions are supplied by the caller (`surface_height` and
//! `column_material` from the terrain crate). This crate does not depend on
//! that crate. `FlatColumnBase` stays the unit-test double.

/// Seed column sampled by function pointer. No heap, no floats.
#[derive(Clone, Copy, Debug)]
pub struct ColumnFns {
pub top: fn(i32, i32) -> i32,
pub material: fn(i32, i32, i32) -> u16,
}

impl ColumnFns {
pub fn top(self, x: i32, z: i32) -> i32 {
(self.top)(x, z)
}

pub fn material(self, x: i32, y: i32, z: i32) -> u16 {
(self.material)(x, y, z)
}
}
24 changes: 24 additions & 0 deletions astraweave-destruction/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#![allow(clippy::too_many_arguments, clippy::needless_range_loop)]

pub mod budget;
pub mod column_base;
pub mod command;
pub mod debris;
pub mod fracture;
Expand Down Expand Up @@ -34,6 +35,7 @@ pub use budget::{
DEMOLITION_TICKS as SHOWCASE_TICKS, MAX_BRUSH_CELLS, MAX_LOG_COMMANDS as LATE_JOIN_CAP,
MAX_NODES_PER_TICK, MAX_SIM_DEBRIS, SLEEP_TICKS, STRESS_ITERS,
};
pub use column_base::ColumnFns;
pub use command::{CommandError as DestructionCommandError, DestructionCommand as Command};
pub use fracture::{bake_bytes, bake_gate, planar_children, BreakRule};
pub use graph::{allows_climb, PieceFlags as FractureFlags};
Expand Down Expand Up @@ -198,6 +200,28 @@ impl DestructionWorld {
&self.terrain
}

/// Seed columns for brush replay. The flat test double stays in place until this is called.
pub fn bind_column_fns(&mut self, fns: ColumnFns) {
self.terrain.set_column_fns(fns);
}

/// Load the brush chunk, record the command, and apply it on this tick.
pub fn apply_brush_now(&mut self, brush: crate::command::Brush) -> Result<(), CommandError> {
let chunk = (
brush.origin[0].div_euclid(crate::octree::CHUNK_EXTENT),
brush.origin[2].div_euclid(crate::octree::CHUNK_EXTENT),
);
self.terrain.load(chunk);
Comment on lines +210 to +214

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Load every chunk touched by an immediate brush

When a sphere overlaps a 32-unit destruction-chunk boundary, this loads only the chunk containing the origin. Terrain::apply_brush records the brush for all touched chunks but rebuilds only loaded slots, and surface_y ignores unloaded slots, so Ground::dig_sphere observes zero drop on the neighboring side and leaves the hole clipped at the seam. Load all touched chunks before ticking the brush, or make the recorded delta queryable without requiring the slot to be loaded.

Useful? React with 👍 / 👎.

self.enqueue(DestructionCommand {
tick: self.tick,
seq: 0,
entity_id: 0,
kind: CommandKind::Brush(brush),
})?;
self.tick();
Ok(())
}

pub fn debris(&self) -> &DebrisPool {
&self.debris
}
Expand Down
Loading
Loading