voxels: split oversized Rust files under the 500-line limit
- Commit
4a0951522173390b7b99c3fdbb0cd4c7a578e7a8- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 20:28 UTC (4 days ago)
- Parents
0cf2e81
renderer.rs (977), engine_coverage_tests.rs (711), entity.rs (660), net.rs (584), engine.rs (560), player.rs (524) and world/generator.rs (517) exceeded the 500-line rustFileLength limit. Split each along module lines using the established include! part pattern: whole top-level items move verbatim into *_sN.rs files spliced into the same module, and the VulkanRenderer impl is split across two impl blocks in the same module, so every item, visibility and call path is identical. mesher.rs and vulkan/pipeline.rs stay hand-written for now: each is dominated by a single function whose extraction is a separate refactor. Verified: cargo fmt -p voxels_engine -- --check clean and cargo test -p voxels_engine --locked green (252 passed).
Diff
games/voxels/src/main/rust/src/engine.rs
diff --git a/games/voxels/src/main/rust/src/engine.rs b/games/voxels/src/main/rust/src/engine.rsindex 85c57255a5..ab874eb093 100644--- a/games/voxels/src/main/rust/src/engine.rs+++ b/games/voxels/src/main/rust/src/engine.rs@@ -395,166 +395,4 @@ where /// Seconds between autosaves while the world is being simulated. pub const AUTOSAVE_SECS: f32 = 60.0; -/// Snapshot of everything `player.json` holds.-fn player_save(state: &EngineState) -> crate::world::save::PlayerSave {- use crate::world::save::{InvSlotSave, InventorySave, PlayerSave, ProgressSave, StatsSave};- PlayerSave {- x: state.player.pos.x,- y: state.player.pos.y,- z: state.player.pos.z,- yaw: state.player.yaw,- pitch: state.player.pitch,- inventory: InventorySave {- selected: state.inventory.selected,- slots: state- .inventory- .slots- .iter()- .map(|s| InvSlotSave { id: s.id, count: s.count })- .collect(),- },- stats: StatsSave {- placed: state.inventory.placed,- broken: state.inventory.broken,- walked: state.player.walk_dist as i32,- night_seen: state.night_survived,- },- progress: ProgressSave {- armor: state- .inventory- .armor- .iter()- .map(|s| InvSlotSave { id: s.id, count: s.count })- .collect(),- max_health: state.player.max_health,- dim: state.dim,- dim_pos: state.dim_pos.iter().map(|p| [p.x, p.y, p.z]).collect(),- dim_visited: state.dim_visited.to_vec(),- respawn: state.respawn.map(|p| [p.x, p.y, p.z]),- end_dragon_dead: state.end_dragon_dead,- nether_wither_dead: state.nether_wither_dead,- world_secs: state.world_secs,- best_beacon: state.best_beacon,- deepest_y: state.deepest_y,- blessings: state.player.blessings,- trades_done: state.trades_done.to_vec(),- weather: state.weather,- weather_cd: state.weather_cd,- crafted_recipes: {- let mut bits = vec![0u8; state.crafted_recipes.len().div_ceil(8)];- for (i, c) in state.crafted_recipes.iter().enumerate() {- if *c {- bits[i / 8] |= 1 << (i % 8);- }- }- bits- },- },- }-}--/// Persists the whole world in one consistent pass: every edited chunk (all dimensions, including-/// ones that already scrolled out of range), then the chests, then the player. Called on autosave,-/// from `onStop`, and on teardown, so a background kill or crash loses at most one autosave-/// interval and never leaves chunk edits on disk without the inventory changes that went with them.-pub fn save_world(state: &mut EngineState) {- state.autosave_cd = AUTOSAVE_SECS;- // Only the host persists an online world; clients are transient mirrors of host state.- if crate::net::role() == crate::net::ROLE_CLIENT {- state.chunks.discard_pending();- for m in state.stored.iter_mut().flatten() {- m.discard_pending();- }- return;- }- state.dim_pos[state.dim as usize] = state.player.pos;- state.chunks.save_dirty();- // The stashed dimensions too (each writes to its own save subdir).- for m in state.stored.iter_mut().flatten() {- m.save_dirty();- }- let _ = state.containers.save(&state.save_dir);- let _ = crate::world::save::save_player(&state.save_dir, &player_save(state));-}--/// Counts down the autosave timer by one simulated frame and saves when it runs out.-fn tick_autosave(state: &mut EngineState, dt: f32) {- state.autosave_cd -= dt;- if state.autosave_cd <= 0.0 {- save_world(state);- }-}--/// JNI `nativeSave`: saves now (the activity calls it from `onStop`). No-op before the engine exists.-pub fn save_now() {- with_engine(save_world);-}--pub fn rebuild_chunk_meshes(state: &mut EngineState, chunk_pos: crate::world::chunk::ChunkPos) {- if state.chunks.get(chunk_pos).is_none() {- return;- }- let meshes = {- let chunk = state.chunks.get(chunk_pos).unwrap();- let map_ptr = &state.chunks as *const ChunkMap;- let closure = move |wx: i32, wy: i32, wz: i32| -> (Id, u8) {- unsafe {- ((*map_ptr).get_block_world(wx, wy, wz), (*map_ptr).get_meta_world(wx, wy, wz))- }- };- let tint = move |wx: i32, wz: i32| -> [f32; 3] { unsafe { (*map_ptr).grass_tint(wx, wz) } };- mesher::mesh_chunk(chunk, &closure, &tint)- };- if let Some(renderer) = state.renderer.as_mut() {- for (sec_idx, mesh_opt) in meshes.into_iter().enumerate() {- if let Some(mesh) = mesh_opt {- if mesh.is_empty() {- continue;- }- unsafe {- renderer.enqueue_mesh(chunk_pos.0, sec_idx as i32, chunk_pos.1, Some(mesh));- }- } else {- unsafe {- renderer.enqueue_mesh(chunk_pos.0, sec_idx as i32, chunk_pos.1, None);- }- }- }- }-}--include!("engine_lifecycle.rs");-include!("engine_part1.rs");-include!("engine_actions.rs");-include!("engine_part2.rs");-include!("engine_part3.rs");-include!("engine_part4.rs");-include!("engine_part5.rs");-include!("engine_part6.rs");--#[cfg(test)]-#[path = "engine_coverage_tests.rs"]-mod engine_coverage_tests;--#[cfg(test)]-#[path = "engine_break_tests.rs"]-mod engine_break_tests;-#[cfg(test)]-#[path = "engine_sim_tests.rs"]-mod engine_sim_tests;--#[cfg(test)]-#[path = "engine_combat_tests.rs"]-mod engine_combat_tests;--#[cfg(test)]-#[path = "engine_extra_tests.rs"]-mod engine_extra_tests;--#[cfg(test)]-#[path = "engine_more_tests.rs"]-mod engine_more_tests;--#[cfg(test)]-#[path = "engine_final_tests.rs"]-mod engine_final_tests;+include!("engine_s1.rs");
games/voxels/src/main/rust/src/engine_coverage_tests.rs
diff --git a/games/voxels/src/main/rust/src/engine_coverage_tests.rs b/games/voxels/src/main/rust/src/engine_coverage_tests.rsindex e9d8122272..18147fe172 100644--- a/games/voxels/src/main/rust/src/engine_coverage_tests.rs+++ b/games/voxels/src/main/rust/src/engine_coverage_tests.rs@@ -306,406 +306,4 @@ fn fishing_ambience_weather_and_farmland() { }) } -#[test]-fn break_and_place_interactions() {- big(|| {- let mut s = state("break");- s.player.pos = vec3(0.5, (Y + 1) as f32, 0.5);- s.player.eat_cd = 0.0;- // Eat food, drink estus while hurt, and raise max HP with a heart container.- sel(&mut s, 1027, 2);- let (eo, fd) = (s.player.eye_pos(), s.player.forward());- assert!(do_break(&mut s, eo, fd));- assert!(s.player.has_effect(crate::item::Effect::Regeneration));- s.player.eat_cd = 0.0;- s.player.health = 10.0;- sel(&mut s, 1024, 1);- let (eo, fd) = (s.player.eye_pos(), s.player.forward());- assert!(do_break(&mut s, eo, fd));- assert!(s.player.health > 10.0);- s.player.eat_cd = 0.0;- sel(&mut s, 1025, 1);- let (eo, fd) = (s.player.eye_pos(), s.player.forward());- assert!(do_break(&mut s, eo, fd));- assert_eq!(s.player.max_health, 22.0);- // Equip armor from the hotbar.- s.player.eat_cd = 0.0;- sel(&mut s, 1072, 100);- let (eo, fd) = (s.player.eye_pos(), s.player.forward());- assert!(do_break(&mut s, eo, fd));- assert_eq!(s.inventory.armor[1].id, 1072);- // Throw a snowball, then (with Multishot attuned) a spread of three.- s.player.eat_cd = 0.0;- sel(&mut s, crate::item::SNOWBALL, 5);- let dir = vec3(0.0, 0.0, -1.0);- let eo = s.player.eye_pos();- assert!(do_break(&mut s, eo, dir));- assert_eq!(s.projectiles.len(), 1);- assert!(s.player.blessings.attune(1115));- s.player.eat_cd = 0.0;- let eo = s.player.eye_pos();- assert!(do_break(&mut s, eo, dir));- assert_eq!(s.projectiles.len(), 4, "Multishot throws three");- // Deflect an incoming fireball by attacking it.- s.projectiles.clear();- s.projectiles.push(Projectile {- pos: s.player.eye_pos() + vec3(0.0, 0.0, -2.0),- vel: vec3(0.0, 0.0, 5.0),- life: 5.0,- kind: ProjKind::Fireball,- from_player: false,- damage: 5.0,- explosive: false,- });- s.inventory.selected = 1;- s.inventory.slots[1] = crate::inventory::InvSlot { id: 1, count: 1 };- s.inventory.selected = 1;- let eo = s.player.eye_pos();- assert!(do_break(&mut s, eo, dir), "attacking a fireball deflects it");- assert!(s.projectiles[0].from_player && s.projectiles[0].vel.z < 0.0);- s.projectiles.clear();- // Brush suspicious sand into plain sand plus a find.- put(&mut s, 0, Y, -3, Block::SuspiciousSand as Id);- sel(&mut s, crate::item::BRUSH, 64);- s.player.eat_cd = 0.0;- assert!(do_break(&mut s, vec3(0.5, Y as f32 + 0.5, 0.5), dir));- assert_eq!(s.chunks.get_block_world(0, Y, -3), Block::Sand as Id);- assert!(s.did_brush);- // Break a plain block (drops it), an ore without a pickaxe (no drop), and a ripe crop.- put(&mut s, 0, Y, -3, Block::Dirt as Id);- sel(&mut s, 1, 10);- let dirt = s.inventory.count_of(2);- assert!(do_break(&mut s, vec3(0.5, Y as f32 + 0.5, 0.5), dir));- assert_eq!(s.chunks.get_block_world(0, Y, -3), 0);- assert!(s.inventory.count_of(2) > dirt);- put(&mut s, 0, Y, -3, Block::DiamondOre as Id);- let dia = s.inventory.count_of(Block::DiamondOre as Id);- assert!(do_break(&mut s, vec3(0.5, Y as f32 + 0.5, 0.5), dir));- assert_eq!(- s.inventory.count_of(Block::DiamondOre as Id),- dia,- "ore needs a pickaxe to drop"- );- sel(&mut s, 1065, 100); // diamond pickaxe- put(&mut s, 0, Y, -3, Block::DiamondOre as Id);- assert!(do_break(&mut s, vec3(0.5, Y as f32 + 0.5, 0.5), dir));- assert!(s.inventory.count_of(Block::DiamondOre as Id) > dia);- // Attack the nearest mob in reach.- s.mobs.push(Mob::new(MobKind::Pig, vec3(0.5, (Y + 2) as f32, -2.5), 3));- let mh = s.mobs[0].health;- s.player.attack_cd = 0.0;- let eo = s.player.eye_pos();- assert!(do_break(&mut s, eo, dir));- assert!(s.mobs[0].health < mh);- let eo = s.player.eye_pos();- assert!(- nearest_mob_hit(&s, eo, vec3(0.0, 1.0, 0.0), 6.0, 6.0).is_none(),- "looking away hits nothing"- );- // Place: a cube against a floor, a slab, a doubled slab, and a seed on farmland.- put(&mut s, 10, Y, 10, Block::Stone as Id);- s.player.pos = vec3(10.5, (Y + 4) as f32, 10.5);- sel(&mut s, Block::Dirt as Id, 4);- let (o, d) = down(&mut s, 10, 10);- assert!(do_place(&mut s, o, d));- assert_eq!(s.chunks.get_block_world(10, Y + 1, 10), Block::Dirt as Id);- sel(&mut s, Block::StoneSlab as Id, 4);- assert!(do_place(&mut s, o, d));- assert_eq!(s.chunks.get_block_world(10, Y + 2, 10), Block::StoneSlab as Id);- // Items and empty hands place nothing.- sel(&mut s, 1027, 1);- assert!(!do_place(&mut s, o, d));- sel(&mut s, 0, 0);- assert!(!do_place(&mut s, o, d));- // Planting: farmland only, and the seed is spent.- put(&mut s, 14, Y, 14, Block::Farmland as Id);- s.player.pos = vec3(14.5, (Y + 4) as f32, 14.5);- sel(&mut s, Block::WheatCrop.crop_seed(), 2);- let (o2, d2) = down(&mut s, 14, 14);- assert!(do_place(&mut s, o2, d2), "seed on farmland plants");- assert_eq!(s.chunks.get_block_world(14, Y + 1, 14), Block::WheatCrop as Id);- assert!(!do_place(&mut s, o2, d2), "occupied soil does not eat another seed");- // placement_meta: cubes are 0, slabs follow the clicked face, stairs add facing.- let hit_top = crate::raycast::HitResult {- pos: (0, Y, 0),- prev: (0, Y + 1, 0),- normal: (0, 1, 0),- dist: 1.0,- };- assert_eq!(- placement_meta(Block::Stone, &hit_top, Vec3::ZERO, vec3(0.0, -1.0, 0.0), 0.0),- 0- );- assert_eq!(- placement_meta(Block::StoneSlab, &hit_top, Vec3::ZERO, vec3(0.0, -1.0, 0.0), 0.0)- & META_TOP,- 0- );- let hit_bot = crate::raycast::HitResult { normal: (0, -1, 0), ..hit_top };- assert_ne!(- placement_meta(Block::StoneSlab, &hit_bot, Vec3::ZERO, vec3(0.0, 1.0, 0.0), 0.0)- & META_TOP,- 0- );- let hit_side = crate::raycast::HitResult { normal: (1, 0, 0), ..hit_top };- assert_ne!(- placement_meta(- Block::StoneStairs,- &hit_side,- vec3(0.0, (Y as f32) + 0.75, 0.0),- vec3(-1.0, 0.0, 0.0),- 0.0- ),- 0- );- // Explosions clear solid blocks (not bedrock), spill chests, and hurt nearby players.- put(&mut s, 20, Y, 20, Block::Stone as Id);- put(&mut s, 21, Y, 20, 13);- put(&mut s, 20, Y, 21, Block::Chest as Id);- s.containers.insert_empty((s.dim, 20, Y, 21));- s.player.pos = vec3(20.5, (Y + 1) as f32, 20.5);- s.player.hurt_cd = 0.0;- let hp = s.player.health;- explode(&mut s, vec3(20.5, Y as f32 + 0.5, 20.5), 2.5);- assert_eq!(s.chunks.get_block_world(20, Y, 20), 0);- assert_eq!(s.chunks.get_block_world(21, Y, 20), 13, "bedrock survives");- assert!(s.player.health < hp);- // Smelter state machine (direct, no global engine).- s.smelter = Smelter::default();- tick_smelter(&mut s, 0.1); // inactive: no-op- s.smelter.active = true;- s.smelter.recipe = 999;- tick_smelter(&mut s, 0.1);- assert!(!s.smelter.active, "a bogus recipe stops the furnace");- let recipe = &crate::inventory::SMELTING[0];- s.inventory = crate::inventory::Inventory::empty();- s.inventory.add_item_with_count(recipe.in1, recipe.n1.max(1) + 8);- if recipe.in2 != 0 {- s.inventory.add_item_with_count(recipe.in2, recipe.n2.max(1) + 8);- }- s.inventory.add_item_with_count(1053, 64); // coal fuel, if the recipe does not spare an input- s.smelter = Smelter {- recipe: 0,- active: true,- progress: 0.0,- fuel_left: 0.0,- fuel_max: 0.0,- blast: recipe.blast,- };- for _ in 0..40 {- tick_smelter(&mut s, 1.0);- if s.inventory.count_of(recipe.out) > 0 {- break;- }- }- assert!(- s.inventory.count_of(recipe.out) > 0 || !s.smelter.active,- "smelting must produce or stop cleanly"- );- // Blessings over time: Frost Walker freezes the water underfoot.- assert!(s.player.blessings.attune(1112));- put(&mut s, 0, Y, 0, 12);- s.player.pos = vec3(0.5, Y as f32 + 0.4, 0.5);- tick_blessings(&mut s, 0.1);- assert_eq!(s.chunks.get_block_world(0, Y, 0), 43, "water froze to ice");- assert_eq!(player_reach(&s), 6.0);- assert!(- is_undead(MobKind::Zombie) && is_undead(MobKind::Wither) && !is_undead(MobKind::Pig)- );- assert_eq!(slayer_mult(&s.player, MobKind::Zombie), 1.0);- assert!(s.player.blessings.attune(1103)); // Smite- assert_eq!(slayer_mult(&s.player, MobKind::Zombie), 2.0);- assert_eq!(slayer_mult(&s.player, MobKind::Pig), 1.0);- })-}--#[test]-fn place_at_menus_and_dimension_switch() {- big(|| {- let mut s = state("menus");- s.width = 800;- s.height = 400;- s.player.pos = vec3(0.5, (Y + 1) as f32, 0.5);- s.player.yaw = 0.0;- s.player.pitch = 0.0;- // A villager in front opens trade (20); a sheep with shears is shorn.- s.mobs.push(Mob::new(MobKind::Villager, vec3(0.5, (Y + 1) as f32, -2.0), 3));- assert_eq!(place_at(&mut s, 400.0, 200.0), 20);- s.mobs.clear();- let mut sheep = Mob::new(MobKind::Sheep, vec3(0.5, (Y + 2) as f32, -2.0), 3);- sheep.sheared = false;- s.mobs.push(sheep);- sel(&mut s, 1148, 100);- assert_eq!(place_at(&mut s, 400.0, 200.0), 1);- assert!(s.mobs[0].sheared && s.did_shear);- s.mobs.clear();- // A chest opens its container (30); a furnace opens its menu (10+menu).- put(&mut s, 0, Y + 2, -3, Block::Chest as Id);- sel(&mut s, 1, 1);- assert_eq!(place_at(&mut s, 400.0, 200.0), 30);- assert!(s.open_chest.is_some());- s.open_chest = None;- put(&mut s, 0, Y + 2, -3, Block::Furnace as Id);- let code = place_at(&mut s, 400.0, 200.0);- assert!(code >= 10 && code != 30, "furnace menu code {code}");- // Resting at a warding stone only works at night and skips to dawn.- put(&mut s, 0, Y + 2, -3, Block::WardingStone as Id);- assert_eq!(place_at(&mut s, 400.0, 200.0), 0, "no resting in daylight");- s.world_secs = wrap_world_secs(400.0); // night (day_t ~0.94)- assert!(s.is_night(), "test setup must be night, day_t={}", s.day_t());- assert_eq!(place_at(&mut s, 400.0, 200.0), 1);- assert!(!s.is_night() && s.did_rest);- // Dimension switch: Nether compresses coordinates, End spawns its dragon, and back again.- s.player.pos = vec3(16.5, 80.0, 16.5);- switch_dimension(&mut s, 1);- assert_eq!(s.dim, 1);- assert!(s.mobs.iter().any(|m| m.kind == MobKind::Wither) || s.nether_wither_dead);- switch_dimension(&mut s, 2);- assert_eq!(s.dim, 2);- assert!(s.mobs.iter().any(|m| m.kind == MobKind::Dragon) || s.end_dragon_dead);- switch_dimension(&mut s, 2); // same dim: no-op- assert_eq!(s.dim, 2);- switch_dimension(&mut s, 0);- assert_eq!(s.dim, 0);- // mark_neighbors_dirty flags edge neighbours.- put(&mut s, 0, Y, 0, 1);- if let Some(c) = s.chunks.get_mut(crate::world::chunk::ChunkPos(0, 0)) {- c.mesh_dirty = false;- }- mark_neighbors_dirty(&mut s, 0, 0);- assert!(s- .chunks- .get(crate::world::chunk::ChunkPos(0, 0))- .map(|c| c.mesh_dirty)- .unwrap_or(false));- // Particle bursts are capped.- let mut out = Vec::new();- let mut rng = 99u32;- spawn_particles(- &mut rng,- &mut out,- Burst {- center: Vec3::ZERO,- n: 5000,- color: [1.0, 0.0, 0.0],- speed: 1.0,- life: 1.0,- size: 0.1,- },- );- assert!(out.len() <= 501, "burst cap, got {}", out.len());- })-}--#[test]-fn simulate_combat_death_and_publish() {- big(|| {- let _serial = GLOBAL_ENGINE_TEST.lock();- let mut s = state("sim");- s.player.pos = vec3(0.5, (Y + 1) as f32, 0.5);- put(&mut s, 0, Y, 0, 1);- // A hostile in contact range hits; a creeper fuses and explodes; a blaze shoots.- let mut z = Mob::new(MobKind::Zombie, vec3(0.5, (Y + 1) as f32, 1.5), 3);- z.attack_cd = 0.0;- s.mobs.push(z);- let mut c = Mob::new(MobKind::Creeper, vec3(0.5, (Y + 1) as f32, 1.0), 3);- c.fuse = 1.39;- s.mobs.push(c);- let mut b = Mob::new(MobKind::Blaze, vec3(0.5, (Y + 1) as f32, 10.5), 3);- b.attack_cd = 0.0;- s.mobs.push(b);- s.player.hurt_cd = 0.0;- step(&mut s, 0.05, false);- assert!(- s.projectiles.iter().any(|p| !p.from_player) || s.player.health < 20.0,- "combat must resolve"- );- // Dead mobs pay loot and vanish on the next frame.- s.mobs.push(Mob::new(MobKind::Pig, vec3(0.5, (Y + 1) as f32, 0.5), 3));- s.mobs.last_mut().unwrap().health = 0.0;- step(&mut s, 0.05, false);- assert!(s.mobs.iter().all(|m| m.health > 0.0), "corpses are collected");- // Lava burns an unblessed player standing in it.- put(&mut s, 0, Y + 1, 0, 84);- s.player.pos = vec3(0.5, (Y + 1) as f32, 0.5);- let hp = s.player.health;- step(&mut s, 0.05, false);- assert!(s.player.health < hp, "lava must burn");- put(&mut s, 0, Y + 1, 0, 0);- // Death respawns with reduced max health (floored) and a clean slate.- s.player.dead = true;- s.respawn = Some(vec3(0.5, (Y + 2) as f32, 0.5));- step(&mut s, 0.05, false);- assert!(!s.player.dead && s.player.health == s.player.max_health);- assert_eq!(s.player.pos, vec3(0.5, (Y + 2) as f32, 0.5));- // Paused steps still publish UI; getters read the caches.- step(&mut s, 0.05, true);- let debug: serde_json::Value = serde_json::from_str(&get_debug_json()).unwrap();- assert!(debug["chunks"].as_u64().unwrap_or(0) > 0);- assert!(serde_json::from_str::<serde_json::Value>(&get_inventory_json()).is_ok());- assert!(serde_json::from_str::<serde_json::Value>(&get_stats_json()).is_ok());- assert!(serde_json::from_str::<serde_json::Value>(&get_health_json()).is_ok());- assert!(serde_json::from_str::<serde_json::Value>(&get_smelt_json()).is_ok());- assert!(serde_json::from_str::<serde_json::Value>(&get_ambience_json()).is_ok());- // Creative/paused toggles.- set_creative(true);- assert!(is_creative());- set_paused(true);- assert!(is_paused());- set_paused(false);- assert!(!is_paused());- // tick_and_render_state honours `running`.- s.running = false;- tick_and_render_state(&mut s, Instant::now());- s.running = true;- })-}--#[test]-fn global_engine_api() {- big(|| {- let _serial = GLOBAL_ENGINE_TEST.lock();- destroy_engine();- let g = ENGINE_GEN.fetch_add(1, Ordering::SeqCst) + 1;- assert!(install_state(state("global"), g));- set_creative(true);- inventory_give(42);- inventory_move(0, 1);- let _ = inventory_craft(9); // planks from wood if stocked; result depends on the kit- assert!(get_recipes_json().contains("known"));- assert!(get_cuts_json().starts_with('['));- let _ = do_cut(0);- assert!(get_trades_json().contains("prof"));- let _ = do_trade(0);- assert!(get_smelting_json().starts_with('['));- let _ = start_smelt(0, false);- stop_smelt();- assert_eq!(get_container_json(), r#"{"slots":[]}"#);- with_engine(|s| {- s.open_chest = Some((0, 1, 2, 3));- s.containers.insert_empty((0, 1, 2, 3));- s.inventory.slots[0] = crate::inventory::InvSlot { id: 1, count: 5 };- });- assert!(container_put(0), "put into an open empty chest must move the stack");- assert!(container_take(0), "and taking it back must move it again");- close_container();- request_container_sync(); // no open chest / offline: no-op- // Blessings through the global API: attune a charm in slot 0, then release it.- with_engine(|s| {- s.inventory.slots[0] = crate::inventory::InvSlot { id: 1107, count: 1 };- });- assert!(attune_blessing(0));- assert!(!attune_blessing(0), "the charm was consumed");- assert!(get_blessings_json().contains("Eros") || get_blessings_json().contains("slots"));- assert!(release_blessing(0));- assert!(!release_blessing(0));- assert!(get_blessing_catalog_json().contains("Blessing of"));- assert!(!break_block_at(400.0, 200.0) || place_block_at(400.0, 200.0) >= 0);- save_now();- destroy_engine();- assert!(with_engine(|_| ()).is_none());- // Resizing with no engine still records the surface size for the next load.- resize_renderer(640, 360);- surface_destroyed(); // no engine: must not panic- })-}+include!("engine_coverage_tests_s1.rs");
games/voxels/src/main/rust/src/engine_coverage_tests_s1.rs
diff --git a/games/voxels/src/main/rust/src/engine_coverage_tests_s1.rs b/games/voxels/src/main/rust/src/engine_coverage_tests_s1.rsnew file mode 100644index 0000000000..fed93f0eb6--- /dev/null+++ b/games/voxels/src/main/rust/src/engine_coverage_tests_s1.rs@@ -0,0 +1,403 @@+#[test]+fn break_and_place_interactions() {+ big(|| {+ let mut s = state("break");+ s.player.pos = vec3(0.5, (Y + 1) as f32, 0.5);+ s.player.eat_cd = 0.0;+ // Eat food, drink estus while hurt, and raise max HP with a heart container.+ sel(&mut s, 1027, 2);+ let (eo, fd) = (s.player.eye_pos(), s.player.forward());+ assert!(do_break(&mut s, eo, fd));+ assert!(s.player.has_effect(crate::item::Effect::Regeneration));+ s.player.eat_cd = 0.0;+ s.player.health = 10.0;+ sel(&mut s, 1024, 1);+ let (eo, fd) = (s.player.eye_pos(), s.player.forward());+ assert!(do_break(&mut s, eo, fd));+ assert!(s.player.health > 10.0);+ s.player.eat_cd = 0.0;+ sel(&mut s, 1025, 1);+ let (eo, fd) = (s.player.eye_pos(), s.player.forward());+ assert!(do_break(&mut s, eo, fd));+ assert_eq!(s.player.max_health, 22.0);+ // Equip armor from the hotbar.+ s.player.eat_cd = 0.0;+ sel(&mut s, 1072, 100);+ let (eo, fd) = (s.player.eye_pos(), s.player.forward());+ assert!(do_break(&mut s, eo, fd));+ assert_eq!(s.inventory.armor[1].id, 1072);+ // Throw a snowball, then (with Multishot attuned) a spread of three.+ s.player.eat_cd = 0.0;+ sel(&mut s, crate::item::SNOWBALL, 5);+ let dir = vec3(0.0, 0.0, -1.0);+ let eo = s.player.eye_pos();+ assert!(do_break(&mut s, eo, dir));+ assert_eq!(s.projectiles.len(), 1);+ assert!(s.player.blessings.attune(1115));+ s.player.eat_cd = 0.0;+ let eo = s.player.eye_pos();+ assert!(do_break(&mut s, eo, dir));+ assert_eq!(s.projectiles.len(), 4, "Multishot throws three");+ // Deflect an incoming fireball by attacking it.+ s.projectiles.clear();+ s.projectiles.push(Projectile {+ pos: s.player.eye_pos() + vec3(0.0, 0.0, -2.0),+ vel: vec3(0.0, 0.0, 5.0),+ life: 5.0,+ kind: ProjKind::Fireball,+ from_player: false,+ damage: 5.0,+ explosive: false,+ });+ s.inventory.selected = 1;+ s.inventory.slots[1] = crate::inventory::InvSlot { id: 1, count: 1 };+ s.inventory.selected = 1;+ let eo = s.player.eye_pos();+ assert!(do_break(&mut s, eo, dir), "attacking a fireball deflects it");+ assert!(s.projectiles[0].from_player && s.projectiles[0].vel.z < 0.0);+ s.projectiles.clear();+ // Brush suspicious sand into plain sand plus a find.+ put(&mut s, 0, Y, -3, Block::SuspiciousSand as Id);+ sel(&mut s, crate::item::BRUSH, 64);+ s.player.eat_cd = 0.0;+ assert!(do_break(&mut s, vec3(0.5, Y as f32 + 0.5, 0.5), dir));+ assert_eq!(s.chunks.get_block_world(0, Y, -3), Block::Sand as Id);+ assert!(s.did_brush);+ // Break a plain block (drops it), an ore without a pickaxe (no drop), and a ripe crop.+ put(&mut s, 0, Y, -3, Block::Dirt as Id);+ sel(&mut s, 1, 10);+ let dirt = s.inventory.count_of(2);+ assert!(do_break(&mut s, vec3(0.5, Y as f32 + 0.5, 0.5), dir));+ assert_eq!(s.chunks.get_block_world(0, Y, -3), 0);+ assert!(s.inventory.count_of(2) > dirt);+ put(&mut s, 0, Y, -3, Block::DiamondOre as Id);+ let dia = s.inventory.count_of(Block::DiamondOre as Id);+ assert!(do_break(&mut s, vec3(0.5, Y as f32 + 0.5, 0.5), dir));+ assert_eq!(+ s.inventory.count_of(Block::DiamondOre as Id),+ dia,+ "ore needs a pickaxe to drop"+ );+ sel(&mut s, 1065, 100); // diamond pickaxe+ put(&mut s, 0, Y, -3, Block::DiamondOre as Id);+ assert!(do_break(&mut s, vec3(0.5, Y as f32 + 0.5, 0.5), dir));+ assert!(s.inventory.count_of(Block::DiamondOre as Id) > dia);+ // Attack the nearest mob in reach.+ s.mobs.push(Mob::new(MobKind::Pig, vec3(0.5, (Y + 2) as f32, -2.5), 3));+ let mh = s.mobs[0].health;+ s.player.attack_cd = 0.0;+ let eo = s.player.eye_pos();+ assert!(do_break(&mut s, eo, dir));+ assert!(s.mobs[0].health < mh);+ let eo = s.player.eye_pos();+ assert!(+ nearest_mob_hit(&s, eo, vec3(0.0, 1.0, 0.0), 6.0, 6.0).is_none(),+ "looking away hits nothing"+ );+ // Place: a cube against a floor, a slab, a doubled slab, and a seed on farmland.+ put(&mut s, 10, Y, 10, Block::Stone as Id);+ s.player.pos = vec3(10.5, (Y + 4) as f32, 10.5);+ sel(&mut s, Block::Dirt as Id, 4);+ let (o, d) = down(&mut s, 10, 10);+ assert!(do_place(&mut s, o, d));+ assert_eq!(s.chunks.get_block_world(10, Y + 1, 10), Block::Dirt as Id);+ sel(&mut s, Block::StoneSlab as Id, 4);+ assert!(do_place(&mut s, o, d));+ assert_eq!(s.chunks.get_block_world(10, Y + 2, 10), Block::StoneSlab as Id);+ // Items and empty hands place nothing.+ sel(&mut s, 1027, 1);+ assert!(!do_place(&mut s, o, d));+ sel(&mut s, 0, 0);+ assert!(!do_place(&mut s, o, d));+ // Planting: farmland only, and the seed is spent.+ put(&mut s, 14, Y, 14, Block::Farmland as Id);+ s.player.pos = vec3(14.5, (Y + 4) as f32, 14.5);+ sel(&mut s, Block::WheatCrop.crop_seed(), 2);+ let (o2, d2) = down(&mut s, 14, 14);+ assert!(do_place(&mut s, o2, d2), "seed on farmland plants");+ assert_eq!(s.chunks.get_block_world(14, Y + 1, 14), Block::WheatCrop as Id);+ assert!(!do_place(&mut s, o2, d2), "occupied soil does not eat another seed");+ // placement_meta: cubes are 0, slabs follow the clicked face, stairs add facing.+ let hit_top = crate::raycast::HitResult {+ pos: (0, Y, 0),+ prev: (0, Y + 1, 0),+ normal: (0, 1, 0),+ dist: 1.0,+ };+ assert_eq!(+ placement_meta(Block::Stone, &hit_top, Vec3::ZERO, vec3(0.0, -1.0, 0.0), 0.0),+ 0+ );+ assert_eq!(+ placement_meta(Block::StoneSlab, &hit_top, Vec3::ZERO, vec3(0.0, -1.0, 0.0), 0.0)+ & META_TOP,+ 0+ );+ let hit_bot = crate::raycast::HitResult { normal: (0, -1, 0), ..hit_top };+ assert_ne!(+ placement_meta(Block::StoneSlab, &hit_bot, Vec3::ZERO, vec3(0.0, 1.0, 0.0), 0.0)+ & META_TOP,+ 0+ );+ let hit_side = crate::raycast::HitResult { normal: (1, 0, 0), ..hit_top };+ assert_ne!(+ placement_meta(+ Block::StoneStairs,+ &hit_side,+ vec3(0.0, (Y as f32) + 0.75, 0.0),+ vec3(-1.0, 0.0, 0.0),+ 0.0+ ),+ 0+ );+ // Explosions clear solid blocks (not bedrock), spill chests, and hurt nearby players.+ put(&mut s, 20, Y, 20, Block::Stone as Id);+ put(&mut s, 21, Y, 20, 13);+ put(&mut s, 20, Y, 21, Block::Chest as Id);+ s.containers.insert_empty((s.dim, 20, Y, 21));+ s.player.pos = vec3(20.5, (Y + 1) as f32, 20.5);+ s.player.hurt_cd = 0.0;+ let hp = s.player.health;+ explode(&mut s, vec3(20.5, Y as f32 + 0.5, 20.5), 2.5);+ assert_eq!(s.chunks.get_block_world(20, Y, 20), 0);+ assert_eq!(s.chunks.get_block_world(21, Y, 20), 13, "bedrock survives");+ assert!(s.player.health < hp);+ // Smelter state machine (direct, no global engine).+ s.smelter = Smelter::default();+ tick_smelter(&mut s, 0.1); // inactive: no-op+ s.smelter.active = true;+ s.smelter.recipe = 999;+ tick_smelter(&mut s, 0.1);+ assert!(!s.smelter.active, "a bogus recipe stops the furnace");+ let recipe = &crate::inventory::SMELTING[0];+ s.inventory = crate::inventory::Inventory::empty();+ s.inventory.add_item_with_count(recipe.in1, recipe.n1.max(1) + 8);+ if recipe.in2 != 0 {+ s.inventory.add_item_with_count(recipe.in2, recipe.n2.max(1) + 8);+ }+ s.inventory.add_item_with_count(1053, 64); // coal fuel, if the recipe does not spare an input+ s.smelter = Smelter {+ recipe: 0,+ active: true,+ progress: 0.0,+ fuel_left: 0.0,+ fuel_max: 0.0,+ blast: recipe.blast,+ };+ for _ in 0..40 {+ tick_smelter(&mut s, 1.0);+ if s.inventory.count_of(recipe.out) > 0 {+ break;+ }+ }+ assert!(+ s.inventory.count_of(recipe.out) > 0 || !s.smelter.active,+ "smelting must produce or stop cleanly"+ );+ // Blessings over time: Frost Walker freezes the water underfoot.+ assert!(s.player.blessings.attune(1112));+ put(&mut s, 0, Y, 0, 12);+ s.player.pos = vec3(0.5, Y as f32 + 0.4, 0.5);+ tick_blessings(&mut s, 0.1);+ assert_eq!(s.chunks.get_block_world(0, Y, 0), 43, "water froze to ice");+ assert_eq!(player_reach(&s), 6.0);+ assert!(+ is_undead(MobKind::Zombie) && is_undead(MobKind::Wither) && !is_undead(MobKind::Pig)+ );+ assert_eq!(slayer_mult(&s.player, MobKind::Zombie), 1.0);+ assert!(s.player.blessings.attune(1103)); // Smite+ assert_eq!(slayer_mult(&s.player, MobKind::Zombie), 2.0);+ assert_eq!(slayer_mult(&s.player, MobKind::Pig), 1.0);+ })+}++#[test]+fn place_at_menus_and_dimension_switch() {+ big(|| {+ let mut s = state("menus");+ s.width = 800;+ s.height = 400;+ s.player.pos = vec3(0.5, (Y + 1) as f32, 0.5);+ s.player.yaw = 0.0;+ s.player.pitch = 0.0;+ // A villager in front opens trade (20); a sheep with shears is shorn.+ s.mobs.push(Mob::new(MobKind::Villager, vec3(0.5, (Y + 1) as f32, -2.0), 3));+ assert_eq!(place_at(&mut s, 400.0, 200.0), 20);+ s.mobs.clear();+ let mut sheep = Mob::new(MobKind::Sheep, vec3(0.5, (Y + 2) as f32, -2.0), 3);+ sheep.sheared = false;+ s.mobs.push(sheep);+ sel(&mut s, 1148, 100);+ assert_eq!(place_at(&mut s, 400.0, 200.0), 1);+ assert!(s.mobs[0].sheared && s.did_shear);+ s.mobs.clear();+ // A chest opens its container (30); a furnace opens its menu (10+menu).+ put(&mut s, 0, Y + 2, -3, Block::Chest as Id);+ sel(&mut s, 1, 1);+ assert_eq!(place_at(&mut s, 400.0, 200.0), 30);+ assert!(s.open_chest.is_some());+ s.open_chest = None;+ put(&mut s, 0, Y + 2, -3, Block::Furnace as Id);+ let code = place_at(&mut s, 400.0, 200.0);+ assert!(code >= 10 && code != 30, "furnace menu code {code}");+ // Resting at a warding stone only works at night and skips to dawn.+ put(&mut s, 0, Y + 2, -3, Block::WardingStone as Id);+ assert_eq!(place_at(&mut s, 400.0, 200.0), 0, "no resting in daylight");+ s.world_secs = wrap_world_secs(400.0); // night (day_t ~0.94)+ assert!(s.is_night(), "test setup must be night, day_t={}", s.day_t());+ assert_eq!(place_at(&mut s, 400.0, 200.0), 1);+ assert!(!s.is_night() && s.did_rest);+ // Dimension switch: Nether compresses coordinates, End spawns its dragon, and back again.+ s.player.pos = vec3(16.5, 80.0, 16.5);+ switch_dimension(&mut s, 1);+ assert_eq!(s.dim, 1);+ assert!(s.mobs.iter().any(|m| m.kind == MobKind::Wither) || s.nether_wither_dead);+ switch_dimension(&mut s, 2);+ assert_eq!(s.dim, 2);+ assert!(s.mobs.iter().any(|m| m.kind == MobKind::Dragon) || s.end_dragon_dead);+ switch_dimension(&mut s, 2); // same dim: no-op+ assert_eq!(s.dim, 2);+ switch_dimension(&mut s, 0);+ assert_eq!(s.dim, 0);+ // mark_neighbors_dirty flags edge neighbours.+ put(&mut s, 0, Y, 0, 1);+ if let Some(c) = s.chunks.get_mut(crate::world::chunk::ChunkPos(0, 0)) {+ c.mesh_dirty = false;+ }+ mark_neighbors_dirty(&mut s, 0, 0);+ assert!(s+ .chunks+ .get(crate::world::chunk::ChunkPos(0, 0))+ .map(|c| c.mesh_dirty)+ .unwrap_or(false));+ // Particle bursts are capped.+ let mut out = Vec::new();+ let mut rng = 99u32;+ spawn_particles(+ &mut rng,+ &mut out,+ Burst {+ center: Vec3::ZERO,+ n: 5000,+ color: [1.0, 0.0, 0.0],+ speed: 1.0,+ life: 1.0,+ size: 0.1,+ },+ );+ assert!(out.len() <= 501, "burst cap, got {}", out.len());+ })+}++#[test]+fn simulate_combat_death_and_publish() {+ big(|| {+ let _serial = GLOBAL_ENGINE_TEST.lock();+ let mut s = state("sim");+ s.player.pos = vec3(0.5, (Y + 1) as f32, 0.5);+ put(&mut s, 0, Y, 0, 1);+ // A hostile in contact range hits; a creeper fuses and explodes; a blaze shoots.+ let mut z = Mob::new(MobKind::Zombie, vec3(0.5, (Y + 1) as f32, 1.5), 3);+ z.attack_cd = 0.0;+ s.mobs.push(z);+ let mut c = Mob::new(MobKind::Creeper, vec3(0.5, (Y + 1) as f32, 1.0), 3);+ c.fuse = 1.39;+ s.mobs.push(c);+ let mut b = Mob::new(MobKind::Blaze, vec3(0.5, (Y + 1) as f32, 10.5), 3);+ b.attack_cd = 0.0;+ s.mobs.push(b);+ s.player.hurt_cd = 0.0;+ step(&mut s, 0.05, false);+ assert!(+ s.projectiles.iter().any(|p| !p.from_player) || s.player.health < 20.0,+ "combat must resolve"+ );+ // Dead mobs pay loot and vanish on the next frame.+ s.mobs.push(Mob::new(MobKind::Pig, vec3(0.5, (Y + 1) as f32, 0.5), 3));+ s.mobs.last_mut().unwrap().health = 0.0;+ step(&mut s, 0.05, false);+ assert!(s.mobs.iter().all(|m| m.health > 0.0), "corpses are collected");+ // Lava burns an unblessed player standing in it.+ put(&mut s, 0, Y + 1, 0, 84);+ s.player.pos = vec3(0.5, (Y + 1) as f32, 0.5);+ let hp = s.player.health;+ step(&mut s, 0.05, false);+ assert!(s.player.health < hp, "lava must burn");+ put(&mut s, 0, Y + 1, 0, 0);+ // Death respawns with reduced max health (floored) and a clean slate.+ s.player.dead = true;+ s.respawn = Some(vec3(0.5, (Y + 2) as f32, 0.5));+ step(&mut s, 0.05, false);+ assert!(!s.player.dead && s.player.health == s.player.max_health);+ assert_eq!(s.player.pos, vec3(0.5, (Y + 2) as f32, 0.5));+ // Paused steps still publish UI; getters read the caches.+ step(&mut s, 0.05, true);+ let debug: serde_json::Value = serde_json::from_str(&get_debug_json()).unwrap();+ assert!(debug["chunks"].as_u64().unwrap_or(0) > 0);+ assert!(serde_json::from_str::<serde_json::Value>(&get_inventory_json()).is_ok());+ assert!(serde_json::from_str::<serde_json::Value>(&get_stats_json()).is_ok());+ assert!(serde_json::from_str::<serde_json::Value>(&get_health_json()).is_ok());+ assert!(serde_json::from_str::<serde_json::Value>(&get_smelt_json()).is_ok());+ assert!(serde_json::from_str::<serde_json::Value>(&get_ambience_json()).is_ok());+ // Creative/paused toggles.+ set_creative(true);+ assert!(is_creative());+ set_paused(true);+ assert!(is_paused());+ set_paused(false);+ assert!(!is_paused());+ // tick_and_render_state honours `running`.+ s.running = false;+ tick_and_render_state(&mut s, Instant::now());+ s.running = true;+ })+}++#[test]+fn global_engine_api() {+ big(|| {+ let _serial = GLOBAL_ENGINE_TEST.lock();+ destroy_engine();+ let g = ENGINE_GEN.fetch_add(1, Ordering::SeqCst) + 1;+ assert!(install_state(state("global"), g));+ set_creative(true);+ inventory_give(42);+ inventory_move(0, 1);+ let _ = inventory_craft(9); // planks from wood if stocked; result depends on the kit+ assert!(get_recipes_json().contains("known"));+ assert!(get_cuts_json().starts_with('['));+ let _ = do_cut(0);+ assert!(get_trades_json().contains("prof"));+ let _ = do_trade(0);+ assert!(get_smelting_json().starts_with('['));+ let _ = start_smelt(0, false);+ stop_smelt();+ assert_eq!(get_container_json(), r#"{"slots":[]}"#);+ with_engine(|s| {+ s.open_chest = Some((0, 1, 2, 3));+ s.containers.insert_empty((0, 1, 2, 3));+ s.inventory.slots[0] = crate::inventory::InvSlot { id: 1, count: 5 };+ });+ assert!(container_put(0), "put into an open empty chest must move the stack");+ assert!(container_take(0), "and taking it back must move it again");+ close_container();+ request_container_sync(); // no open chest / offline: no-op+ // Blessings through the global API: attune a charm in slot 0, then release it.+ with_engine(|s| {+ s.inventory.slots[0] = crate::inventory::InvSlot { id: 1107, count: 1 };+ });+ assert!(attune_blessing(0));+ assert!(!attune_blessing(0), "the charm was consumed");+ assert!(get_blessings_json().contains("Eros") || get_blessings_json().contains("slots"));+ assert!(release_blessing(0));+ assert!(!release_blessing(0));+ assert!(get_blessing_catalog_json().contains("Blessing of"));+ assert!(!break_block_at(400.0, 200.0) || place_block_at(400.0, 200.0) >= 0);+ save_now();+ destroy_engine();+ assert!(with_engine(|_| ()).is_none());+ // Resizing with no engine still records the surface size for the next load.+ resize_renderer(640, 360);+ surface_destroyed(); // no engine: must not panic+ })+}
games/voxels/src/main/rust/src/engine_s1.rs
diff --git a/games/voxels/src/main/rust/src/engine_s1.rs b/games/voxels/src/main/rust/src/engine_s1.rsnew file mode 100644index 0000000000..e55e88f6db--- /dev/null+++ b/games/voxels/src/main/rust/src/engine_s1.rs@@ -0,0 +1,163 @@+/// Snapshot of everything `player.json` holds.+fn player_save(state: &EngineState) -> crate::world::save::PlayerSave {+ use crate::world::save::{InvSlotSave, InventorySave, PlayerSave, ProgressSave, StatsSave};+ PlayerSave {+ x: state.player.pos.x,+ y: state.player.pos.y,+ z: state.player.pos.z,+ yaw: state.player.yaw,+ pitch: state.player.pitch,+ inventory: InventorySave {+ selected: state.inventory.selected,+ slots: state+ .inventory+ .slots+ .iter()+ .map(|s| InvSlotSave { id: s.id, count: s.count })+ .collect(),+ },+ stats: StatsSave {+ placed: state.inventory.placed,+ broken: state.inventory.broken,+ walked: state.player.walk_dist as i32,+ night_seen: state.night_survived,+ },+ progress: ProgressSave {+ armor: state+ .inventory+ .armor+ .iter()+ .map(|s| InvSlotSave { id: s.id, count: s.count })+ .collect(),+ max_health: state.player.max_health,+ dim: state.dim,+ dim_pos: state.dim_pos.iter().map(|p| [p.x, p.y, p.z]).collect(),+ dim_visited: state.dim_visited.to_vec(),+ respawn: state.respawn.map(|p| [p.x, p.y, p.z]),+ end_dragon_dead: state.end_dragon_dead,+ nether_wither_dead: state.nether_wither_dead,+ world_secs: state.world_secs,+ best_beacon: state.best_beacon,+ deepest_y: state.deepest_y,+ blessings: state.player.blessings,+ trades_done: state.trades_done.to_vec(),+ weather: state.weather,+ weather_cd: state.weather_cd,+ crafted_recipes: {+ let mut bits = vec![0u8; state.crafted_recipes.len().div_ceil(8)];+ for (i, c) in state.crafted_recipes.iter().enumerate() {+ if *c {+ bits[i / 8] |= 1 << (i % 8);+ }+ }+ bits+ },+ },+ }+}++/// Persists the whole world in one consistent pass: every edited chunk (all dimensions, including+/// ones that already scrolled out of range), then the chests, then the player. Called on autosave,+/// from `onStop`, and on teardown, so a background kill or crash loses at most one autosave+/// interval and never leaves chunk edits on disk without the inventory changes that went with them.+pub fn save_world(state: &mut EngineState) {+ state.autosave_cd = AUTOSAVE_SECS;+ // Only the host persists an online world; clients are transient mirrors of host state.+ if crate::net::role() == crate::net::ROLE_CLIENT {+ state.chunks.discard_pending();+ for m in state.stored.iter_mut().flatten() {+ m.discard_pending();+ }+ return;+ }+ state.dim_pos[state.dim as usize] = state.player.pos;+ state.chunks.save_dirty();+ // The stashed dimensions too (each writes to its own save subdir).+ for m in state.stored.iter_mut().flatten() {+ m.save_dirty();+ }+ let _ = state.containers.save(&state.save_dir);+ let _ = crate::world::save::save_player(&state.save_dir, &player_save(state));+}++/// Counts down the autosave timer by one simulated frame and saves when it runs out.+fn tick_autosave(state: &mut EngineState, dt: f32) {+ state.autosave_cd -= dt;+ if state.autosave_cd <= 0.0 {+ save_world(state);+ }+}++/// JNI `nativeSave`: saves now (the activity calls it from `onStop`). No-op before the engine exists.+pub fn save_now() {+ with_engine(save_world);+}++pub fn rebuild_chunk_meshes(state: &mut EngineState, chunk_pos: crate::world::chunk::ChunkPos) {+ if state.chunks.get(chunk_pos).is_none() {+ return;+ }+ let meshes = {+ let chunk = state.chunks.get(chunk_pos).unwrap();+ let map_ptr = &state.chunks as *const ChunkMap;+ let closure = move |wx: i32, wy: i32, wz: i32| -> (Id, u8) {+ unsafe {+ ((*map_ptr).get_block_world(wx, wy, wz), (*map_ptr).get_meta_world(wx, wy, wz))+ }+ };+ let tint = move |wx: i32, wz: i32| -> [f32; 3] { unsafe { (*map_ptr).grass_tint(wx, wz) } };+ mesher::mesh_chunk(chunk, &closure, &tint)+ };+ if let Some(renderer) = state.renderer.as_mut() {+ for (sec_idx, mesh_opt) in meshes.into_iter().enumerate() {+ if let Some(mesh) = mesh_opt {+ if mesh.is_empty() {+ continue;+ }+ unsafe {+ renderer.enqueue_mesh(chunk_pos.0, sec_idx as i32, chunk_pos.1, Some(mesh));+ }+ } else {+ unsafe {+ renderer.enqueue_mesh(chunk_pos.0, sec_idx as i32, chunk_pos.1, None);+ }+ }+ }+ }+}++include!("engine_lifecycle.rs");+include!("engine_part1.rs");+include!("engine_actions.rs");+include!("engine_part2.rs");+include!("engine_part3.rs");+include!("engine_part4.rs");+include!("engine_part5.rs");+include!("engine_part6.rs");++#[cfg(test)]+#[path = "engine_coverage_tests.rs"]+mod engine_coverage_tests;++#[cfg(test)]+#[path = "engine_break_tests.rs"]+mod engine_break_tests;+#[cfg(test)]+#[path = "engine_sim_tests.rs"]+mod engine_sim_tests;++#[cfg(test)]+#[path = "engine_combat_tests.rs"]+mod engine_combat_tests;++#[cfg(test)]+#[path = "engine_extra_tests.rs"]+mod engine_extra_tests;++#[cfg(test)]+#[path = "engine_more_tests.rs"]+mod engine_more_tests;++#[cfg(test)]+#[path = "engine_final_tests.rs"]+mod engine_final_tests;
games/voxels/src/main/rust/src/entity.rs
diff --git a/games/voxels/src/main/rust/src/entity.rs b/games/voxels/src/main/rust/src/entity.rsindex 82dacbeb69..b89f62a5db 100644--- a/games/voxels/src/main/rust/src/entity.rs+++ b/games/voxels/src/main/rust/src/entity.rs@@ -368,293 +368,4 @@ pub struct Terrain<'a> { pub surface: &'a dyn Fn(f32, f32, f32) -> Option<f32>, } -impl Mob {- pub fn new(kind: MobKind, pos: Vec3, seed: u32) -> Self {- let v = roll_variation(kind, seed);- Mob {- kind,- pos,- vel: Vec3::ZERO,- yaw: 0.0,- health: v.health,- attack_cd: 0.0,- fuse: 0.0,- target_yaw: 0.0,- wander: 0.0,- anim: 0.0,- on_ground: false,- rng: seed | 1,- profession: crate::villager::Profession::from_seed(seed | 1).index() as u8,- max_health: v.health,- speed: v.speed,- elite: v.elite,- repelled: 0.0,- sheared: false,- }- }-- pub fn tick(&mut self, dt: f32, player: Vec3, terrain: &Terrain) {- // Flying bosses (Dragon/Wither): no gravity/collision; orbit + periodic swoop at the player.- if self.kind.flies() {- let _ = terrain;- self.attack_cd = (self.attack_cd - dt).max(0.0);- self.wander -= dt;- if self.wander <= 0.0 {- self.wander = 9.0;- }- // Ghasts hover high and never dive (they attack purely at range); bosses swoop.- let (center, radius, spd, diving) = match self.kind {- MobKind::Dragon => (Vec3::new(0.0, 86.0, 0.0), 30.0, 13.0, self.wander < 2.0),- MobKind::Ghast => (player + Vec3::new(0.0, 14.0, 0.0), 20.0, 6.0, false),- _ => (player + Vec3::new(0.0, 6.0, 0.0), 9.0, 9.0, self.wander < 2.0),- };- let target = if diving {- player + Vec3::new(0.0, 1.0, 0.0)- } else {- let a = self.anim * 0.5;- center + Vec3::new(a.cos() * radius, (a * 1.3).sin() * 3.0, a.sin() * radius)- };- let dir = target - self.pos;- let d = dir.length();- if d > 0.5 {- let v = dir / d;- self.pos += v * spd * dt;- self.yaw = v.x.atan2(-v.z);- }- self.anim += dt * 3.0;- return;- }- self.wander -= dt;- let to_player = player - self.pos;- let pdist = to_player.length();- // Anubis: a warded player is walked away from, not toward.- let warded = self.repelled > 0.0 && pdist < self.repelled;- if self.wander <= 0.0 {- self.wander = 1.5 + xorshift(&mut self.rng) * 3.0;- if warded {- self.target_yaw = (-to_player.x).atan2(to_player.z); // turn tail- } else if self.kind.hostile() && pdist < 22.0 {- self.target_yaw = to_player.x.atan2(-to_player.z); // face the player- } else {- self.target_yaw = (xorshift(&mut self.rng) - 0.5) * std::f32::consts::TAU;- }- // Occasionally idle (stand still).- if !self.kind.hostile() && xorshift(&mut self.rng) < 0.3 {- self.wander = 1.0;- self.target_yaw = self.yaw;- }- }- // A warded mob flees at once rather than waiting for its next wander roll.- if warded {- self.target_yaw = (-to_player.x).atan2(to_player.z);- }- // Ease yaw toward the target.- let mut dyaw = self.target_yaw - self.yaw;- while dyaw > std::f32::consts::PI {- dyaw -= std::f32::consts::TAU;- }- while dyaw < -std::f32::consts::PI {- dyaw += std::f32::consts::TAU;- }- self.yaw += dyaw.clamp(-3.0 * dt, 3.0 * dt);-- let chasing = self.kind.hostile() && pdist < 22.0 && !warded;- let idle = !chasing- && (self.target_yaw - self.yaw).abs() < 0.05- && self.wander < 1.05- && !self.kind.hostile();- let speed = if idle { 0.0 } else { self.speed * if chasing { 1.25 } else { 1.0 } };- // Model front is -Z; rotating (0,0,-1) by yaw gives (sin, 0, -cos).- let fwd = Vec3::new(self.yaw.sin(), 0.0, -self.yaw.cos());-- // Gravity.- self.vel.y -= 24.0 * dt;- self.vel.y = self.vel.y.max(-40.0);-- let at = |x: f32, y: f32, z: f32| (terrain.solid)(x, y, z);- let r = 0.3;- // Horizontal move per axis, blocked by walls, stepping up onto whatever is actually there.- let dx = fwd.x * speed * dt;- if dx != 0.0 {- let nx = self.pos.x + dx + r * dx.signum();- if !at(nx, self.pos.y + 0.2, self.pos.z) && !at(nx, self.pos.y + 1.0, self.pos.z) {- self.pos.x += dx;- } else if let Some(top) = self.step_target(terrain, nx, self.pos.z) {- self.pos.x += dx;- self.pos.y = top;- }- }- let dz = fwd.z * speed * dt;- if dz != 0.0 {- let nz = self.pos.z + dz + r * dz.signum();- if !at(self.pos.x, self.pos.y + 0.2, nz) && !at(self.pos.x, self.pos.y + 1.0, nz) {- self.pos.z += dz;- } else if let Some(top) = self.step_target(terrain, self.pos.x, nz) {- self.pos.z += dz;- self.pos.y = top;- }- }- // Vertical: fall until something is underfoot, then rest on its actual surface.- let prev_y = self.pos.y;- self.pos.y += self.vel.y * dt;- self.on_ground = false;- if self.vel.y <= 0.0 {- if let Some(top) = (terrain.surface)(self.pos.x, self.pos.z, prev_y) {- if self.pos.y <= top {- self.pos.y = top;- self.vel.y = 0.0;- self.on_ground = true;- }- }- }- // Hostiles hop toward the player over small ledges.- if chasing- && self.on_ground- && speed > 0.0- && at(self.pos.x + fwd.x * 0.4, self.pos.y + 0.1, self.pos.z + fwd.z * 0.4)- {- self.vel.y = 8.0;- }- self.anim += speed * dt * 5.5;- }-- /// The height to climb to when a mob walks into something at (x, z): the surface just above its- /// feet, if the rise is at most a block and the mob's body fits standing there. Following the- /// real surface means a slab lifts a mob half a block, not a whole one.- fn step_target(&self, terrain: &Terrain, x: f32, z: f32) -> Option<f32> {- if !self.on_ground {- return None;- }- let top = (terrain.surface)(x, z, self.pos.y + 1.0)?;- let rise = top - self.pos.y;- if rise <= 1e-4 || rise > 1.0 {- return None;- }- let head = self.kind.height().max(1.0);- if (terrain.solid)(x, top + 0.2, z) || (terrain.solid)(x, top + head, z) {- return None;- }- Some(top)- }-- /// A villager wears its profession's colours, an elite burns red, and everything else uses its skin- /// unmodified.- fn tint(&self) -> [f32; 3] {- if self.kind == MobKind::Villager {- crate::villager::Profession::from_index(self.profession as usize).tint()- } else if self.elite {- [1.35, 0.62, 0.55]- } else {- [1.0, 1.0, 1.0]- }- }-- fn append_mesh(&self, verts: &mut Vec<Vertex>, indices: &mut Vec<u32>) {- let col = (self.kind.cell() % 4) as f32 * CELL;- let row = (self.kind.cell() / 4) as f32 * CELL;- // Procedural skins are uniform, so sample the cell centre for every face.- let uniform = self.kind.uniform_skin();- let tint = self.tint();- let (yc, ys) = (self.yaw.cos(), self.yaw.sin());- for part in self.kind.parts() {- let swing = if part.leg != 0.0 { self.anim.sin() * 0.55 * part.leg } else { 0.0 };- let xr = part.x_rot + swing;- let (hx, hy, hz) =- (part.size[0] * PX * 0.5, part.size[1] * PX * 0.5, part.size[2] * PX * 0.5);- let center = Vec3::new(part.pos[0], part.pos[1], part.pos[2]);- // Legs swing about their top; static-rotated parts rotate about their centre.- let pivot_y = if part.leg != 0.0 { center.y + hy } else { center.y };- let (xc, xs) = (xr.cos(), xr.sin());- // Skin-space box unwrap (pixels) for the 6 faces in order +X,-X,+Y,-Y,+Z,-Z.- let (w, h, d) = (part.size[0], part.size[1], part.size[2]);- let (u, v) = (part.uv[0], part.uv[1]);- let rects = [- [u, v + d, u + d, v + d + h], // +X east- [u + d + w, v + d, u + 2.0 * d + w, v + d + h], // -X west- [u + d, v, u + d + w, v + d], // +Y up- [u + d + w, v, u + d + 2.0 * w, v + d], // -Y down- [u + 2.0 * d + w, v + d, u + 2.0 * d + 2.0 * w, v + d + h], // +Z south (back)- [u + d, v + d, u + d + w, v + d + h], // -Z north (front)- ];- // Face corners (CCW) as (x,y,z) multipliers of half-extents.- let faces: [[[f32; 3]; 4]; 6] = [- [[1., -1., -1.], [1., 1., -1.], [1., 1., 1.], [1., -1., 1.]], // +X- [[-1., -1., 1.], [-1., 1., 1.], [-1., 1., -1.], [-1., -1., -1.]], // -X- [[-1., 1., -1.], [-1., 1., 1.], [1., 1., 1.], [1., 1., -1.]], // +Y- [[-1., -1., 1.], [-1., -1., -1.], [1., -1., -1.], [1., -1., 1.]], // -Y- [[1., -1., 1.], [1., 1., 1.], [-1., 1., 1.], [-1., -1., 1.]], // +Z- [[-1., -1., -1.], [-1., 1., -1.], [1., 1., -1.], [1., -1., -1.]], // -Z- ];- let normals = [- [1., 0., 0.],- [-1., 0., 0.],- [0., 1., 0.],- [0., -1., 0.],- [0., 0., 1.],- [0., 0., -1.],- ];- for f in 0..6 {- let base = verts.len() as u32;- let rect = rects[f];- let uvc = [- [rect[0], rect[3]],- [rect[0], rect[1]],- [rect[2], rect[1]],- [rect[2], rect[3]],- ];- // Transform normal (x-rot then yaw).- let mut nrm = normals[f];- {- let (ny, nz) = (nrm[1] * xc - nrm[2] * xs, nrm[1] * xs + nrm[2] * xc);- nrm[1] = ny;- nrm[2] = nz;- let (nx, nz2) = (nrm[0] * yc - nrm[2] * ys, nrm[0] * ys + nrm[2] * yc);- nrm[0] = nx;- nrm[2] = nz2;- }- for c in 0..4 {- let m = faces[f][c];- let mut wp =- Vec3::new(center.x + m[0] * hx, center.y + m[1] * hy, center.z + m[2] * hz);- // x-rotation about pivot.- let (dy, dz) = (wp.y - pivot_y, wp.z - center.z);- wp.y = pivot_y + dy * xc - dz * xs;- wp.z = center.z + dy * xs + dz * xc;- // yaw about Y through the mob origin.- let (rx, rz) = (wp.x * yc - wp.z * ys, wp.x * ys + wp.z * yc);- wp = Vec3::new(rx, wp.y, rz) + self.pos;- let uv = if uniform {- [(col + 32.0) / ATLAS, (row + 32.0) / ATLAS]- } else {- [(col + uvc[c][0]) / ATLAS, (row + uvc[c][1]) / ATLAS]- };- verts.push(Vertex {- pos: [wp.x, wp.y, wp.z],- uv,- color: tint,- ao: 1.0,- tile_idx: 0.0,- normal: nrm,- light: 0.0,- });- }- indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);- }- }- }-}--// Build one vertex/index buffer for all mobs.-pub fn build_entity_mesh(mobs: &[Mob]) -> (Vec<Vertex>, Vec<u32>) {- let mut verts = Vec::new();- let mut indices = Vec::new();- for m in mobs {- m.append_mesh(&mut verts, &mut indices);- }- (verts, indices)-}--include!("entity_part1.rs");-#[cfg(test)]-#[path = "entity_coverage_tests.rs"]-mod entity_coverage_tests;+include!("entity_s1.rs");
games/voxels/src/main/rust/src/entity_s1.rs
diff --git a/games/voxels/src/main/rust/src/entity_s1.rs b/games/voxels/src/main/rust/src/entity_s1.rsnew file mode 100644index 0000000000..46473fdfa8--- /dev/null+++ b/games/voxels/src/main/rust/src/entity_s1.rs@@ -0,0 +1,290 @@+impl Mob {+ pub fn new(kind: MobKind, pos: Vec3, seed: u32) -> Self {+ let v = roll_variation(kind, seed);+ Mob {+ kind,+ pos,+ vel: Vec3::ZERO,+ yaw: 0.0,+ health: v.health,+ attack_cd: 0.0,+ fuse: 0.0,+ target_yaw: 0.0,+ wander: 0.0,+ anim: 0.0,+ on_ground: false,+ rng: seed | 1,+ profession: crate::villager::Profession::from_seed(seed | 1).index() as u8,+ max_health: v.health,+ speed: v.speed,+ elite: v.elite,+ repelled: 0.0,+ sheared: false,+ }+ }++ pub fn tick(&mut self, dt: f32, player: Vec3, terrain: &Terrain) {+ // Flying bosses (Dragon/Wither): no gravity/collision; orbit + periodic swoop at the player.+ if self.kind.flies() {+ let _ = terrain;+ self.attack_cd = (self.attack_cd - dt).max(0.0);+ self.wander -= dt;+ if self.wander <= 0.0 {+ self.wander = 9.0;+ }+ // Ghasts hover high and never dive (they attack purely at range); bosses swoop.+ let (center, radius, spd, diving) = match self.kind {+ MobKind::Dragon => (Vec3::new(0.0, 86.0, 0.0), 30.0, 13.0, self.wander < 2.0),+ MobKind::Ghast => (player + Vec3::new(0.0, 14.0, 0.0), 20.0, 6.0, false),+ _ => (player + Vec3::new(0.0, 6.0, 0.0), 9.0, 9.0, self.wander < 2.0),+ };+ let target = if diving {+ player + Vec3::new(0.0, 1.0, 0.0)+ } else {+ let a = self.anim * 0.5;+ center + Vec3::new(a.cos() * radius, (a * 1.3).sin() * 3.0, a.sin() * radius)+ };+ let dir = target - self.pos;+ let d = dir.length();+ if d > 0.5 {+ let v = dir / d;+ self.pos += v * spd * dt;+ self.yaw = v.x.atan2(-v.z);+ }+ self.anim += dt * 3.0;+ return;+ }+ self.wander -= dt;+ let to_player = player - self.pos;+ let pdist = to_player.length();+ // Anubis: a warded player is walked away from, not toward.+ let warded = self.repelled > 0.0 && pdist < self.repelled;+ if self.wander <= 0.0 {+ self.wander = 1.5 + xorshift(&mut self.rng) * 3.0;+ if warded {+ self.target_yaw = (-to_player.x).atan2(to_player.z); // turn tail+ } else if self.kind.hostile() && pdist < 22.0 {+ self.target_yaw = to_player.x.atan2(-to_player.z); // face the player+ } else {+ self.target_yaw = (xorshift(&mut self.rng) - 0.5) * std::f32::consts::TAU;+ }+ // Occasionally idle (stand still).+ if !self.kind.hostile() && xorshift(&mut self.rng) < 0.3 {+ self.wander = 1.0;+ self.target_yaw = self.yaw;+ }+ }+ // A warded mob flees at once rather than waiting for its next wander roll.+ if warded {+ self.target_yaw = (-to_player.x).atan2(to_player.z);+ }+ // Ease yaw toward the target.+ let mut dyaw = self.target_yaw - self.yaw;+ while dyaw > std::f32::consts::PI {+ dyaw -= std::f32::consts::TAU;+ }+ while dyaw < -std::f32::consts::PI {+ dyaw += std::f32::consts::TAU;+ }+ self.yaw += dyaw.clamp(-3.0 * dt, 3.0 * dt);++ let chasing = self.kind.hostile() && pdist < 22.0 && !warded;+ let idle = !chasing+ && (self.target_yaw - self.yaw).abs() < 0.05+ && self.wander < 1.05+ && !self.kind.hostile();+ let speed = if idle { 0.0 } else { self.speed * if chasing { 1.25 } else { 1.0 } };+ // Model front is -Z; rotating (0,0,-1) by yaw gives (sin, 0, -cos).+ let fwd = Vec3::new(self.yaw.sin(), 0.0, -self.yaw.cos());++ // Gravity.+ self.vel.y -= 24.0 * dt;+ self.vel.y = self.vel.y.max(-40.0);++ let at = |x: f32, y: f32, z: f32| (terrain.solid)(x, y, z);+ let r = 0.3;+ // Horizontal move per axis, blocked by walls, stepping up onto whatever is actually there.+ let dx = fwd.x * speed * dt;+ if dx != 0.0 {+ let nx = self.pos.x + dx + r * dx.signum();+ if !at(nx, self.pos.y + 0.2, self.pos.z) && !at(nx, self.pos.y + 1.0, self.pos.z) {+ self.pos.x += dx;+ } else if let Some(top) = self.step_target(terrain, nx, self.pos.z) {+ self.pos.x += dx;+ self.pos.y = top;+ }+ }+ let dz = fwd.z * speed * dt;+ if dz != 0.0 {+ let nz = self.pos.z + dz + r * dz.signum();+ if !at(self.pos.x, self.pos.y + 0.2, nz) && !at(self.pos.x, self.pos.y + 1.0, nz) {+ self.pos.z += dz;+ } else if let Some(top) = self.step_target(terrain, self.pos.x, nz) {+ self.pos.z += dz;+ self.pos.y = top;+ }+ }+ // Vertical: fall until something is underfoot, then rest on its actual surface.+ let prev_y = self.pos.y;+ self.pos.y += self.vel.y * dt;+ self.on_ground = false;+ if self.vel.y <= 0.0 {+ if let Some(top) = (terrain.surface)(self.pos.x, self.pos.z, prev_y) {+ if self.pos.y <= top {+ self.pos.y = top;+ self.vel.y = 0.0;+ self.on_ground = true;+ }+ }+ }+ // Hostiles hop toward the player over small ledges.+ if chasing+ && self.on_ground+ && speed > 0.0+ && at(self.pos.x + fwd.x * 0.4, self.pos.y + 0.1, self.pos.z + fwd.z * 0.4)+ {+ self.vel.y = 8.0;+ }+ self.anim += speed * dt * 5.5;+ }++ /// The height to climb to when a mob walks into something at (x, z): the surface just above its+ /// feet, if the rise is at most a block and the mob's body fits standing there. Following the+ /// real surface means a slab lifts a mob half a block, not a whole one.+ fn step_target(&self, terrain: &Terrain, x: f32, z: f32) -> Option<f32> {+ if !self.on_ground {+ return None;+ }+ let top = (terrain.surface)(x, z, self.pos.y + 1.0)?;+ let rise = top - self.pos.y;+ if rise <= 1e-4 || rise > 1.0 {+ return None;+ }+ let head = self.kind.height().max(1.0);+ if (terrain.solid)(x, top + 0.2, z) || (terrain.solid)(x, top + head, z) {+ return None;+ }+ Some(top)+ }++ /// A villager wears its profession's colours, an elite burns red, and everything else uses its skin+ /// unmodified.+ fn tint(&self) -> [f32; 3] {+ if self.kind == MobKind::Villager {+ crate::villager::Profession::from_index(self.profession as usize).tint()+ } else if self.elite {+ [1.35, 0.62, 0.55]+ } else {+ [1.0, 1.0, 1.0]+ }+ }++ fn append_mesh(&self, verts: &mut Vec<Vertex>, indices: &mut Vec<u32>) {+ let col = (self.kind.cell() % 4) as f32 * CELL;+ let row = (self.kind.cell() / 4) as f32 * CELL;+ // Procedural skins are uniform, so sample the cell centre for every face.+ let uniform = self.kind.uniform_skin();+ let tint = self.tint();+ let (yc, ys) = (self.yaw.cos(), self.yaw.sin());+ for part in self.kind.parts() {+ let swing = if part.leg != 0.0 { self.anim.sin() * 0.55 * part.leg } else { 0.0 };+ let xr = part.x_rot + swing;+ let (hx, hy, hz) =+ (part.size[0] * PX * 0.5, part.size[1] * PX * 0.5, part.size[2] * PX * 0.5);+ let center = Vec3::new(part.pos[0], part.pos[1], part.pos[2]);+ // Legs swing about their top; static-rotated parts rotate about their centre.+ let pivot_y = if part.leg != 0.0 { center.y + hy } else { center.y };+ let (xc, xs) = (xr.cos(), xr.sin());+ // Skin-space box unwrap (pixels) for the 6 faces in order +X,-X,+Y,-Y,+Z,-Z.+ let (w, h, d) = (part.size[0], part.size[1], part.size[2]);+ let (u, v) = (part.uv[0], part.uv[1]);+ let rects = [+ [u, v + d, u + d, v + d + h], // +X east+ [u + d + w, v + d, u + 2.0 * d + w, v + d + h], // -X west+ [u + d, v, u + d + w, v + d], // +Y up+ [u + d + w, v, u + d + 2.0 * w, v + d], // -Y down+ [u + 2.0 * d + w, v + d, u + 2.0 * d + 2.0 * w, v + d + h], // +Z south (back)+ [u + d, v + d, u + d + w, v + d + h], // -Z north (front)+ ];+ // Face corners (CCW) as (x,y,z) multipliers of half-extents.+ let faces: [[[f32; 3]; 4]; 6] = [+ [[1., -1., -1.], [1., 1., -1.], [1., 1., 1.], [1., -1., 1.]], // +X+ [[-1., -1., 1.], [-1., 1., 1.], [-1., 1., -1.], [-1., -1., -1.]], // -X+ [[-1., 1., -1.], [-1., 1., 1.], [1., 1., 1.], [1., 1., -1.]], // +Y+ [[-1., -1., 1.], [-1., -1., -1.], [1., -1., -1.], [1., -1., 1.]], // -Y+ [[1., -1., 1.], [1., 1., 1.], [-1., 1., 1.], [-1., -1., 1.]], // +Z+ [[-1., -1., -1.], [-1., 1., -1.], [1., 1., -1.], [1., -1., -1.]], // -Z+ ];+ let normals = [+ [1., 0., 0.],+ [-1., 0., 0.],+ [0., 1., 0.],+ [0., -1., 0.],+ [0., 0., 1.],+ [0., 0., -1.],+ ];+ for f in 0..6 {+ let base = verts.len() as u32;+ let rect = rects[f];+ let uvc = [+ [rect[0], rect[3]],+ [rect[0], rect[1]],+ [rect[2], rect[1]],+ [rect[2], rect[3]],+ ];+ // Transform normal (x-rot then yaw).+ let mut nrm = normals[f];+ {+ let (ny, nz) = (nrm[1] * xc - nrm[2] * xs, nrm[1] * xs + nrm[2] * xc);+ nrm[1] = ny;+ nrm[2] = nz;+ let (nx, nz2) = (nrm[0] * yc - nrm[2] * ys, nrm[0] * ys + nrm[2] * yc);+ nrm[0] = nx;+ nrm[2] = nz2;+ }+ for c in 0..4 {+ let m = faces[f][c];+ let mut wp =+ Vec3::new(center.x + m[0] * hx, center.y + m[1] * hy, center.z + m[2] * hz);+ // x-rotation about pivot.+ let (dy, dz) = (wp.y - pivot_y, wp.z - center.z);+ wp.y = pivot_y + dy * xc - dz * xs;+ wp.z = center.z + dy * xs + dz * xc;+ // yaw about Y through the mob origin.+ let (rx, rz) = (wp.x * yc - wp.z * ys, wp.x * ys + wp.z * yc);+ wp = Vec3::new(rx, wp.y, rz) + self.pos;+ let uv = if uniform {+ [(col + 32.0) / ATLAS, (row + 32.0) / ATLAS]+ } else {+ [(col + uvc[c][0]) / ATLAS, (row + uvc[c][1]) / ATLAS]+ };+ verts.push(Vertex {+ pos: [wp.x, wp.y, wp.z],+ uv,+ color: tint,+ ao: 1.0,+ tile_idx: 0.0,+ normal: nrm,+ light: 0.0,+ });+ }+ indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);+ }+ }+ }+}++// Build one vertex/index buffer for all mobs.+pub fn build_entity_mesh(mobs: &[Mob]) -> (Vec<Vertex>, Vec<u32>) {+ let mut verts = Vec::new();+ let mut indices = Vec::new();+ for m in mobs {+ m.append_mesh(&mut verts, &mut indices);+ }+ (verts, indices)+}++include!("entity_part1.rs");+#[cfg(test)]+#[path = "entity_coverage_tests.rs"]+mod entity_coverage_tests;
games/voxels/src/main/rust/src/net.rs
diff --git a/games/voxels/src/main/rust/src/net.rs b/games/voxels/src/main/rust/src/net.rsindex 8e4f3512c2..4a0a5d4e52 100644--- a/games/voxels/src/main/rust/src/net.rs+++ b/games/voxels/src/main/rust/src/net.rs@@ -423,162 +423,4 @@ fn apply_container_op(state: &mut EngineState, key: (u8, i32, i32, i32), take: b } } -/// Host: called from the engine's own container_take/put so other players see the change.-pub fn host_container_changed(state: &EngineState, key: (u8, i32, i32, i32)) {- if is_host() {- host_broadcast_container(state, key);- }-}--// Mark a chunk (and its edge neighbors) for remesh without going through the engine's edit-notify-// hook — used when applying remote data so we don't echo it straight back out.-fn dirty_chunk_and_neighbors(state: &mut EngineState, cx: i32, cz: i32) {- let touch = |s: &mut EngineState, p: ChunkPos| {- if let Some(c) = s.chunks.get_mut(p) {- c.mesh_dirty = true;- }- };- touch(state, ChunkPos(cx, cz));- touch(state, ChunkPos(cx - 1, cz));- touch(state, ChunkPos(cx + 1, cz));- touch(state, ChunkPos(cx, cz - 1));- touch(state, ChunkPos(cx, cz + 1));-}--fn apply_block(state: &mut EngineState, x: i32, y: i32, z: i32, id: Id, meta: u8) {- SUPPRESS_NOTE.store(true, Ordering::SeqCst);- state.chunks.set_block_meta_world(x, y, z, id, meta);- SUPPRESS_NOTE.store(false, Ordering::SeqCst);- let cp = ChunkPos::from_world(x, z);- dirty_chunk_and_neighbors(state, cp.0, cp.1);-}--fn apply_chunk_data(state: &mut EngineState, cx: i32, cz: i32, data: &[u8]) {- let cp = ChunkPos(cx, cz);- state.chunks.load_or_gen(cp);- let mut ok = false;- if let Some(chunk) = state.chunks.get_mut(cp) {- ok = crate::world::save::decode_chunk(data, chunk).is_ok();- if ok {- chunk.mesh_dirty = true;- // `decode_chunk` clears `dirty` (a payload it just read is by- // definition in sync with its source), but a chunk applied from- // the network is a player edit as far as this peer's disk is- // concerned. Without these marks `save_dirty` skips it and- // `unload_beyond` drops it instead of parking it in `pending`,- // so a host would silently revert a client's shipped edits on- // the next save/reload. Local edits get both marks from- // `ChunkMap::set_block_meta_world`; applied chunks must too.- chunk.dirty = true;- chunk.edited = true;- }- }- if ok {- dirty_chunk_and_neighbors(state, cx, cz);- }-}--// ---- Inbound: drain the queue and apply, at the top of each tick ------pub fn apply_inbound(state: &mut EngineState) {- if !is_networked() {- return;- }- let msgs: Vec<NetMsg> = inbox().lock().map(|mut q| std::mem::take(&mut *q)).unwrap_or_default();- if msgs.is_empty() {- return;- }- let r = role();- for msg in msgs {- match msg {- NetMsg::PlayerTransform { device, player } => {- upsert_remote(device, player.pos, player.yaw)- }-- // ---- Host applies validated client intents ----- NetMsg::Join { .. } if r == ROLE_HOST => on_join(state),- NetMsg::EditIntent { dim, x, y, z, id, meta, break_it, .. } if r == ROLE_HOST => {- if dim == state.dim {- let write = if break_it { 0 } else { id };- apply_block(state, x, y, z, write, meta);- if let Ok(mut e) = edited().lock() {- e.insert((ChunkPos::from_world(x, z).0, ChunkPos::from_world(x, z).1));- }- }- }- NetMsg::InvIntent { from, to, .. } if r == ROLE_HOST => {- state.inventory.move_item(from as usize, to as usize);- }- NetMsg::ContainerIntent { key, take, idx, .. } if r == ROLE_HOST => {- let k = (key[0] as u8, key[1], key[2], key[3]);- // idx == u32::MAX is a pure "send me this chest" request (no mutation).- if idx != u32::MAX {- apply_container_op(state, k, take, idx as usize);- }- host_broadcast_container(state, k);- }- // A client's edited chunk, sent upstream: trust it (editor role was checked in Kotlin),- // apply, and re-mark it so the host rebroadcasts the authoritative version.- NetMsg::ChunkData { dim, cx, cz, data } if r == ROLE_HOST => {- if dim == state.dim {- apply_chunk_data(state, cx, cz, &data);- if let Ok(mut e) = edited().lock() {- e.insert((cx, cz));- }- }- }-- // ---- Client applies host snapshots ----- NetMsg::ChunkData { dim, cx, cz, data } if r == ROLE_CLIENT => {- if dim == state.dim {- apply_chunk_data(state, cx, cz, &data);- }- }- NetMsg::BlockEdit { dim, x, y, z, id, meta } if r == ROLE_CLIENT => {- if dim == state.dim {- apply_block(state, x, y, z, id, meta);- }- }- NetMsg::MobSnapshot { mobs } if r == ROLE_CLIENT => {- set_mob_targets(state, mobs);- }- NetMsg::ProjSnapshot { projs } if r == ROLE_CLIENT => {- state.projectiles = projs.iter().map(|d| d.to_proj()).collect();- }- NetMsg::InventorySync { inv } if r == ROLE_CLIENT => {- if let Ok(parsed) = serde_json::from_str::<crate::inventory::Inventory>(&inv) {- state.inventory = parsed;- }- }- NetMsg::ContainerSync { key, slots } if r == ROLE_CLIENT => {- let k = (key[0] as u8, key[1], key[2], key[3]);- state.containers.insert(k, slots);- }- NetMsg::WorldClock { world_secs, weather, weather_cd, rain } if r == ROLE_CLIENT => {- state.world_secs = crate::engine::wrap_world_secs(world_secs);- state.weather = weather;- state.weather_cd = weather_cd;- state.rain = rain;- }- NetMsg::WorldInit { player, .. } if r == ROLE_CLIENT => {- // The host's own transform arrives here first; show them immediately.- upsert_remote("host".to_string(), player.pos, player.yaw);- }- _ => {}- }- }-}--include!("net_part1.rs");-include!("net_bin.rs");-#[cfg(test)]-#[path = "net_tests.rs"]-mod net_tests;--#[cfg(test)]-#[path = "net_coverage_tests.rs"]-mod net_coverage_tests;--#[cfg(test)]-#[path = "net_extra_tests.rs"]-mod net_extra_tests;+include!("net_s1.rs");
games/voxels/src/main/rust/src/net_s1.rs
diff --git a/games/voxels/src/main/rust/src/net_s1.rs b/games/voxels/src/main/rust/src/net_s1.rsnew file mode 100644index 0000000000..8f7787248d--- /dev/null+++ b/games/voxels/src/main/rust/src/net_s1.rs@@ -0,0 +1,159 @@+/// Host: called from the engine's own container_take/put so other players see the change.+pub fn host_container_changed(state: &EngineState, key: (u8, i32, i32, i32)) {+ if is_host() {+ host_broadcast_container(state, key);+ }+}++// Mark a chunk (and its edge neighbors) for remesh without going through the engine's edit-notify+// hook — used when applying remote data so we don't echo it straight back out.+fn dirty_chunk_and_neighbors(state: &mut EngineState, cx: i32, cz: i32) {+ let touch = |s: &mut EngineState, p: ChunkPos| {+ if let Some(c) = s.chunks.get_mut(p) {+ c.mesh_dirty = true;+ }+ };+ touch(state, ChunkPos(cx, cz));+ touch(state, ChunkPos(cx - 1, cz));+ touch(state, ChunkPos(cx + 1, cz));+ touch(state, ChunkPos(cx, cz - 1));+ touch(state, ChunkPos(cx, cz + 1));+}++fn apply_block(state: &mut EngineState, x: i32, y: i32, z: i32, id: Id, meta: u8) {+ SUPPRESS_NOTE.store(true, Ordering::SeqCst);+ state.chunks.set_block_meta_world(x, y, z, id, meta);+ SUPPRESS_NOTE.store(false, Ordering::SeqCst);+ let cp = ChunkPos::from_world(x, z);+ dirty_chunk_and_neighbors(state, cp.0, cp.1);+}++fn apply_chunk_data(state: &mut EngineState, cx: i32, cz: i32, data: &[u8]) {+ let cp = ChunkPos(cx, cz);+ state.chunks.load_or_gen(cp);+ let mut ok = false;+ if let Some(chunk) = state.chunks.get_mut(cp) {+ ok = crate::world::save::decode_chunk(data, chunk).is_ok();+ if ok {+ chunk.mesh_dirty = true;+ // `decode_chunk` clears `dirty` (a payload it just read is by+ // definition in sync with its source), but a chunk applied from+ // the network is a player edit as far as this peer's disk is+ // concerned. Without these marks `save_dirty` skips it and+ // `unload_beyond` drops it instead of parking it in `pending`,+ // so a host would silently revert a client's shipped edits on+ // the next save/reload. Local edits get both marks from+ // `ChunkMap::set_block_meta_world`; applied chunks must too.+ chunk.dirty = true;+ chunk.edited = true;+ }+ }+ if ok {+ dirty_chunk_and_neighbors(state, cx, cz);+ }+}++// ---- Inbound: drain the queue and apply, at the top of each tick ----++pub fn apply_inbound(state: &mut EngineState) {+ if !is_networked() {+ return;+ }+ let msgs: Vec<NetMsg> = inbox().lock().map(|mut q| std::mem::take(&mut *q)).unwrap_or_default();+ if msgs.is_empty() {+ return;+ }+ let r = role();+ for msg in msgs {+ match msg {+ NetMsg::PlayerTransform { device, player } => {+ upsert_remote(device, player.pos, player.yaw)+ }++ // ---- Host applies validated client intents ----+ NetMsg::Join { .. } if r == ROLE_HOST => on_join(state),+ NetMsg::EditIntent { dim, x, y, z, id, meta, break_it, .. } if r == ROLE_HOST => {+ if dim == state.dim {+ let write = if break_it { 0 } else { id };+ apply_block(state, x, y, z, write, meta);+ if let Ok(mut e) = edited().lock() {+ e.insert((ChunkPos::from_world(x, z).0, ChunkPos::from_world(x, z).1));+ }+ }+ }+ NetMsg::InvIntent { from, to, .. } if r == ROLE_HOST => {+ state.inventory.move_item(from as usize, to as usize);+ }+ NetMsg::ContainerIntent { key, take, idx, .. } if r == ROLE_HOST => {+ let k = (key[0] as u8, key[1], key[2], key[3]);+ // idx == u32::MAX is a pure "send me this chest" request (no mutation).+ if idx != u32::MAX {+ apply_container_op(state, k, take, idx as usize);+ }+ host_broadcast_container(state, k);+ }+ // A client's edited chunk, sent upstream: trust it (editor role was checked in Kotlin),+ // apply, and re-mark it so the host rebroadcasts the authoritative version.+ NetMsg::ChunkData { dim, cx, cz, data } if r == ROLE_HOST => {+ if dim == state.dim {+ apply_chunk_data(state, cx, cz, &data);+ if let Ok(mut e) = edited().lock() {+ e.insert((cx, cz));+ }+ }+ }++ // ---- Client applies host snapshots ----+ NetMsg::ChunkData { dim, cx, cz, data } if r == ROLE_CLIENT => {+ if dim == state.dim {+ apply_chunk_data(state, cx, cz, &data);+ }+ }+ NetMsg::BlockEdit { dim, x, y, z, id, meta } if r == ROLE_CLIENT => {+ if dim == state.dim {+ apply_block(state, x, y, z, id, meta);+ }+ }+ NetMsg::MobSnapshot { mobs } if r == ROLE_CLIENT => {+ set_mob_targets(state, mobs);+ }+ NetMsg::ProjSnapshot { projs } if r == ROLE_CLIENT => {+ state.projectiles = projs.iter().map(|d| d.to_proj()).collect();+ }+ NetMsg::InventorySync { inv } if r == ROLE_CLIENT => {+ if let Ok(parsed) = serde_json::from_str::<crate::inventory::Inventory>(&inv) {+ state.inventory = parsed;+ }+ }+ NetMsg::ContainerSync { key, slots } if r == ROLE_CLIENT => {+ let k = (key[0] as u8, key[1], key[2], key[3]);+ state.containers.insert(k, slots);+ }+ NetMsg::WorldClock { world_secs, weather, weather_cd, rain } if r == ROLE_CLIENT => {+ state.world_secs = crate::engine::wrap_world_secs(world_secs);+ state.weather = weather;+ state.weather_cd = weather_cd;+ state.rain = rain;+ }+ NetMsg::WorldInit { player, .. } if r == ROLE_CLIENT => {+ // The host's own transform arrives here first; show them immediately.+ upsert_remote("host".to_string(), player.pos, player.yaw);+ }+ _ => {}+ }+ }+}++include!("net_part1.rs");+include!("net_bin.rs");+#[cfg(test)]+#[path = "net_tests.rs"]+mod net_tests;++#[cfg(test)]+#[path = "net_coverage_tests.rs"]+mod net_coverage_tests;++#[cfg(test)]+#[path = "net_extra_tests.rs"]+mod net_extra_tests;
games/voxels/src/main/rust/src/player.rs
diff --git a/games/voxels/src/main/rust/src/player.rs b/games/voxels/src/main/rust/src/player.rsindex aaa3e33fa7..9a400cdbd1 100644--- a/games/voxels/src/main/rust/src/player.rs+++ b/games/voxels/src/main/rust/src/player.rs@@ -63,462 +63,5 @@ fn landing_damage(peak: f32, y: f32, feather_fall: bool) -> f32 { } } -impl Player {- pub fn new(x: f32, y: f32, z: f32) -> Self {- Self {- pos: vec3(x, y, z),- vel: Vec3::ZERO,- yaw: 0.0,- pitch: 0.0,- on_ground: false,- flying: false,- elytra: false,- gliding: false,- glide_armed: false,- prev_jump: false,- glide_boost: 0.0,- jumps_left: 0,- walk_dist: 0.0,- sneaking: false,- blessings: Attunement::default(),- health: 20.0,- max_health: 20.0,- absorption: 0.0,- effects: Vec::new(),- hurt_cd: 0.0,- attack_cd: 0.0,- eat_cd: 0.0,- air_max_y: y,- dead: false,- combat_cd: 0.0,- }- }-- pub fn blessed(&self, p: Passive) -> bool {- self.blessings.has(p)- }-- fn effect_amp(&self, k: Effect) -> Option<u8> {- self.effects.iter().filter(|e| e.kind == k).map(|e| e.amp).max()- }- pub fn has_effect(&self, k: Effect) -> bool {- self.effect_amp(k).is_some()- }- pub fn speed_mult(&self) -> f32 {- let sp = self.effect_amp(Effect::Speed).map(|a| a as f32 + 1.0).unwrap_or(0.0);- let sl = self.effect_amp(Effect::Slowness).map(|a| a as f32 + 1.0).unwrap_or(0.0);- let traversal = if self.blessed(Passive::Traversal) { 0.25 } else { 0.0 };- (1.0 + 0.2 * sp - 0.15 * sl + traversal).max(0.25)- }- pub fn jump_bonus(&self) -> f32 {- 2.2 * self.effect_amp(Effect::JumpBoost).map(|a| a as f32 + 1.0).unwrap_or(0.0)- }- pub fn night_vision(&self) -> bool {- self.has_effect(Effect::NightVision)- }- pub fn strength_bonus(&self) -> f32 {- 3.0 * self.effect_amp(Effect::Strength).map(|a| a as f32 + 1.0).unwrap_or(0.0)- }- // Ares makes every melee swing land far harder. Sekhmet stacks on top of it once you're bloodied.- pub fn might_mult(&self) -> f32 {- let ares = if self.blessed(Passive::Might) { 1.5 } else { 1.0 };- ares * if self.bloodraging() { BLOODRAGE_DAMAGE } else { 1.0 }- }- /// Sekhmet: cornered and bleeding, you hit harder and soak more.- pub fn bloodraging(&self) -> bool {- self.blessed(Passive::Bloodrage)- && !self.dead- && self.health <= self.max_health * BLOODRAGE_AT- }- fn resistance_mult(&self) -> f32 {- let effects = (1.0- - 0.2 * self.effect_amp(Effect::Resistance).map(|a| a as f32 + 1.0).unwrap_or(0.0))- .max(0.0);- effects * if self.bloodraging() { BLOODRAGE_RESIST } else { 1.0 }- }- /// Camazotz: how much health a melee hit for `dealt` damage gives back.- pub fn lifesteal(&mut self, dealt: f32) {- if self.blessed(Passive::Lifesteal) {- self.heal(dealt * LIFESTEAL_SHARE);- }- }-- pub fn add_effect(&mut self, kind: Effect, secs: f32, amp: u8) {- if kind == Effect::Absorption {- self.absorption = self.absorption.max((amp as f32 + 1.0) * 4.0);- }- if let Some(e) = self.effects.iter_mut().find(|e| e.kind == kind) {- if amp >= e.amp {- e.amp = amp;- }- e.secs = e.secs.max(secs);- } else {- self.effects.push(ActiveEffect { kind, secs, amp });- }- }- pub fn heal(&mut self, amt: f32) {- self.health = (self.health + amt).min(self.max_health);- }- // Firework rocket: while gliding, surge forward and gain a little altitude.- pub fn firework_boost(&mut self) {- if self.gliding {- self.glide_boost = (self.glide_boost + 16.0).min(26.0);- self.vel.y = self.vel.y.max(0.0) + 5.0;- self.air_max_y = self.pos.y;- }- }- pub fn damage(&mut self, amt: f32) {- if self.dead || self.hurt_cd > 0.0 || amt <= 0.0 {- return;- }- let amt = amt * self.resistance_mult();- let soak = amt.min(self.absorption);- self.absorption -= soak;- self.health -= amt - soak;- self.hurt_cd = 0.4;- self.combat_cd = DIVINITY_DELAY;- if self.health <= 0.0 {- self.health = 0.0;- self.dead = true;- }- }- // Aeolus: a landed hit throws you skyward, which is what makes its combos work.- pub fn wind_burst(&mut self) {- if self.blessed(Passive::WindBurst) {- self.vel.y = self.vel.y.max(0.0) + 9.0;- self.on_ground = false;- self.air_max_y = self.pos.y;- }- }-- // Regeneration/poison/absorption expiry + cooldowns. Called every frame.- pub fn tick_status(&mut self, dt: f32) {- if self.hurt_cd > 0.0 {- self.hurt_cd -= dt;- }- if self.combat_cd > 0.0 {- self.combat_cd -= dt;- }- if self.attack_cd > 0.0 {- self.attack_cd -= dt;- }- if self.eat_cd > 0.0 {- self.eat_cd -= dt;- }- for e in self.effects.iter_mut() {- e.secs -= dt;- }- self.effects.retain(|e| e.secs > 0.0);- if let Some(a) = self.effect_amp(Effect::Regeneration) {- self.heal((a as f32 + 1.0) * dt);- }- if let Some(a) = self.effect_amp(Effect::Poison) {- if self.health > 1.0 {- self.health = (self.health - (a as f32 + 1.0) * dt).max(1.0);- }- }- // Absorption from food expires; Athena's shield doesn't, so it sets the floor the potion- // value decays back down to rather than being wiped along with it.- if !self.has_effect(Effect::Absorption) {- let floor = if self.blessed(Passive::Divinity) { DIVINITY_SHIELD } else { 0.0 };- self.absorption = self.absorption.min(floor);- }- // Athena's shield reforms between fights. A larger absorption from food still wins while it- // lasts, since the cap is whichever is higher.- if self.blessed(Passive::Divinity) && self.combat_cd <= 0.0 && !self.dead {- let cap = DIVINITY_SHIELD.max(self.absorption);- self.absorption = (self.absorption + DIVINITY_REGEN * dt).min(cap);- }- }- pub fn eye_pos(&self) -> Vec3 {- self.pos + vec3(0.0, 1.62, 0.0)- }- pub fn forward(&self) -> Vec3 {- let cp = self.pitch.cos();- vec3(-self.yaw.sin() * cp, -self.pitch.sin(), -self.yaw.cos() * cp).normalize_or_zero()- }- pub fn right(&self) -> Vec3 {- vec3(self.yaw.cos(), 0.0, -self.yaw.sin()).normalize_or_zero()- }-- pub fn tick(&mut self, dt: f32, input: &crate::input::InputState, chunks: &ChunkMap) {- self.sneaking = input.sneak;- let jump_edge = input.jump_held && !self.prev_jump;- self.prev_jump = input.jump_held;- // Deploy/retract elytra wings with a mid-air jump tap; retract automatically on the ground.- if self.elytra && jump_edge && !self.on_ground && !self.flying {- self.glide_armed = !self.glide_armed;- }- if self.on_ground || !self.elytra {- self.glide_armed = false;- }- self.glide_boost = (self.glide_boost - 10.0 * dt).max(0.0);- let fwd =- if self.flying { self.forward() } else { vec3(-self.yaw.sin(), 0.0, -self.yaw.cos()) };- let right = self.right();- let mut wish = Vec3::ZERO;- if input.move_forward.abs() > 0.001 {- wish += fwd * input.move_forward;- }- if input.move_right.abs() > 0.001 {- wish += right * input.move_right;- }- if wish.length_squared() > 0.0 {- wish = wish.normalize_or_zero();- }-- if self.flying {- let speed = 10.0 * self.speed_mult() * if input.sprint { 2.0 } else { 1.0 };- let mut vel = wish * speed;- if input.jump_held {- vel.y += speed;- } // top button (Up)- if input.down_held {- vel.y -= speed;- } // bottom button (Down)- let old = self.pos;- self.pos += vel * dt;- if self.collides_at(self.pos, chunks) {- self.pos = old;- }- self.walk_dist += (vel * dt).length();- } else {- let sneaking = input.sneak;- // Cronus lets you sneak at a walking pace instead of a crawl.- let sneak_mult = if self.blessed(Passive::SwiftSneak) { 1.0 } else { 0.3 };- let speed = 4.3- * self.speed_mult()- * if sneaking {- sneak_mult- } else if input.sprint {- 1.3- } else {- 1.0- };- // Auto-unstuck: if we ended up inside terrain (bad save, block placed onto us, spawn- // fractionally embedded) rise until free so the player is never permanently trapped.- if self.collides_at(self.pos, chunks) {- let mut lift = 0.0;- while lift < 3.0 && self.collides_at(self.pos, chunks) {- self.pos.y += 0.1;- lift += 0.1;- }- self.vel.y = 0.0;- }- // Elytra glide: once wings are deployed (mid-air jump tap), sail forward along the look- // direction with a slow, controlled fall instead of walking control.- self.gliding = self.glide_armed && !self.on_ground;- let horiz_vel = if self.gliding {- let f = self.forward();- vec3(f.x, 0.0, f.z).normalize_or_zero() * (11.0 + self.glide_boost)- } else {- vec3(wish.x * speed, 0.0, wish.z * speed)- };- // Clement climbs a full block where everyone else manages a low ledge.- let step_h = if self.blessed(Passive::Traversal) { 1.05 } else { 0.6 };- let mut new_pos = self.pos;- // X axis: step up small ledges when grounded; when sneaking, refuse to walk off edges.- let try_x = vec3(new_pos.x + horiz_vel.x * dt, new_pos.y, new_pos.z);- if !self.collides_at(try_x, chunks) {- if !(sneaking && self.on_ground) || self.supported_at(try_x, chunks) {- new_pos.x = try_x.x;- }- } else if self.on_ground && !sneaking {- // Climb to the surface that blocked us, not by a fixed amount.- if let Some(top) = self.step_up_to(try_x, chunks, new_pos.y, step_h) {- new_pos.x = try_x.x;- new_pos.y = top;- }- }- // Z axis, same rules.- let try_z = vec3(new_pos.x, new_pos.y, new_pos.z + horiz_vel.z * dt);- if !self.collides_at(try_z, chunks) {- if !(sneaking && self.on_ground) || self.supported_at(try_z, chunks) {- new_pos.z = try_z.z;- }- } else if self.on_ground && !sneaking {- if let Some(top) = self.step_up_to(try_z, chunks, new_pos.y, step_h) {- new_pos.z = try_z.z;- new_pos.y = top;- }- }- self.walk_dist +=- (vec3(new_pos.x, 0.0, new_pos.z) - vec3(self.pos.x, 0.0, self.pos.z)).length();- // Vertical: gravity + collision, resting at whatever height horizontal step-up left us at.- // Yamm turns water into something you can actually swim in: buoyant, with jump to rise.- let submerged = (self.blessed(Passive::Deep) || self.blessed(Passive::Conduit))- && self.in_water(chunks);- let base_y = new_pos.y;- if submerged {- self.vel.y = if input.jump_held { 4.5 } else { (self.vel.y - 6.0 * dt).max(-2.0) };- } else {- self.vel.y -= 28.0 * dt;- }- if self.gliding {- self.vel.y = self.vel.y.max(-3.5);- } // slow, gliding descent- new_pos.y = base_y + self.vel.y * dt;- if self.collides_at(new_pos, chunks) {- if self.vel.y <= 0.0 {- // Landing: come to rest exactly on the surface, so a slab holds you half a- // block up instead of at the cell boundary.- let depth = ((base_y - new_pos.y).ceil() as i32 + 2).max(2);- new_pos.y =- self.surface_under(new_pos, chunks, base_y, depth).unwrap_or(base_y);- self.on_ground = true;- } else {- new_pos.y = base_y; // knocked our head on something above- }- self.vel.y = 0.0;- } else {- let mut probe = new_pos;- probe.y -= 0.05;- self.on_ground =- probe.y <= 0.0 || (self.collides_at(probe, chunks) && self.vel.y <= 0.0);- if self.on_ground && self.vel.y <= 0.0 {- self.vel.y = 0.0;- }- }- if self.on_ground {- self.jumps_left = self.extra_jumps();- }- // Swimming is controlled descent, not a fall — don't let a dive bank landing damage.- if submerged {- self.air_max_y = new_pos.y;- }- // Can't jump while sneaking (must toggle sneak off first).- if input.jump_held && self.on_ground && !sneaking {- self.vel.y = 8.5 + self.jump_bonus();- self.on_ground = false;- } else if jump_edge- && !self.on_ground- && !sneaking- && !submerged- && !self.gliding- && !self.flying- && self.jumps_left > 0- {- // Hyacinthus: a second leap out of mid-air.- self.jumps_left -= 1;- self.vel.y = 8.5 + self.jump_bonus();- self.air_max_y = self.pos.y;- }- self.pos = new_pos;- }- if self.pos.y < 0.1 {- self.pos.y = 0.1;- self.vel.y = 0.0;- self.on_ground = true;- }- // Fall damage: track peak airborne height, hurt on landing beyond a safe margin.- // Flying and elytra gliding never accrue fall damage.- if self.flying || self.gliding {- self.air_max_y = self.pos.y;- } else if !self.on_ground {- if self.pos.y > self.air_max_y {- self.air_max_y = self.pos.y;- }- } else {- let dmg =- landing_damage(self.air_max_y, self.pos.y, self.blessed(Passive::FeatherFall));- if dmg > 0.0 {- self.damage(dmg);- }- self.air_max_y = self.pos.y;- }- }-- /// How many mid-air jumps the attuned blessings allow.- fn extra_jumps(&self) -> u8 {- if self.blessed(Passive::DoubleJump) {- 1- } else {- 0- }- }-- /// True when the player's body is inside water.- fn in_water(&self, chunks: &ChunkMap) -> bool {- let (x, z) = (self.pos.x.floor() as i32, self.pos.z.floor() as i32);- let feet = chunks.get_block_world(x, self.pos.y.floor() as i32, z);- let chest = chunks.get_block_world(x, (self.pos.y + 1.0).floor() as i32, z);- feet == 12 || chest == 12- }-- /// The highest surface under the player's footprint at or below `ceiling` — the height they- /// should come to rest at. Probing all four corners means the tallest thing under any part of- /// the body wins, so you stand on a stair's step rather than sinking into it.- fn surface_under(&self, pos: Vec3, chunks: &ChunkMap, ceiling: f32, depth: i32) -> Option<f32> {- let hw = 0.3;- let mut best: Option<f32> = None;- for &dx in &[-hw, hw] {- for &dz in &[-hw, hw] {- if let Some(t) = chunks.surface_below(pos.x + dx, pos.z + dz, ceiling, depth) {- if best.is_none_or(|b| t > b) {- best = Some(t);- }- }- }- }- best- }-- /// The height to climb to when walking into something: the surface just above the feet, if it- /// is within `max_step` and the player actually fits standing on it. Returns the real surface- /// height, so a slab lifts you half a block rather than the full step allowance.- fn step_up_to(&self, pos: Vec3, chunks: &ChunkMap, from_y: f32, max_step: f32) -> Option<f32> {- let target = self.surface_under(pos, chunks, from_y + max_step, 2)?;- if target <= from_y + 1e-4 {- return None;- }- if self.collides_at(vec3(pos.x, target, pos.z), chunks) {- return None;- }- Some(target)- }-- // True if there is something solid to stand on just under the player's footprint at `pos` (used- // so a sneaking player won't walk off ledges). A slab counts only where its solid half reaches.- fn supported_at(&self, pos: Vec3, chunks: &ChunkMap) -> bool {- self.surface_under(pos, chunks, pos.y + 1e-3, 1).is_some_and(|t| pos.y - t < 0.1)- }-- fn collides_at(&self, pos: Vec3, chunks: &ChunkMap) -> bool {- let hw = 0.3;- let min = [pos.x - hw, pos.y, pos.z - hw];- let max = [pos.x + hw, pos.y + 1.8, pos.z + hw];- let x0 = min[0].floor() as i32;- let y0 = min[1].floor() as i32;- let z0 = min[2].floor() as i32;- let x1 = max[0].ceil() as i32;- let y1 = max[1].ceil() as i32;- let z1 = max[2].ceil() as i32;- for x in x0..=x1 {- for y in y0..=y1 {- for z in z0..=z1 {- let id = chunks.get_block_world(x, y, z);- if id == 0 || !Block::from_id(id).is_solid() {- continue;- }- let meta = chunks.get_meta_world(x, y, z);- let cell = [x as f32, y as f32, z as f32];- for b in Block::from_id(id).collision_boxes(meta).as_slice() {- if b.overlaps_at(cell, min, max) {- return true;- }- }- }- }- }- false- }-}--include!("player_part1.rs");-#[cfg(test)]-#[path = "player_coverage_tests.rs"]-mod player_coverage_tests;--#[cfg(test)]-#[path = "player_tick_tests.rs"]-mod player_tick_tests;+include!("player_s1.rs");+include!("player_s2.rs");
games/voxels/src/main/rust/src/player_s1.rs
diff --git a/games/voxels/src/main/rust/src/player_s1.rs b/games/voxels/src/main/rust/src/player_s1.rsnew file mode 100644index 0000000000..245dcd497f--- /dev/null+++ b/games/voxels/src/main/rust/src/player_s1.rs@@ -0,0 +1,452 @@+impl Player {+ pub fn new(x: f32, y: f32, z: f32) -> Self {+ Self {+ pos: vec3(x, y, z),+ vel: Vec3::ZERO,+ yaw: 0.0,+ pitch: 0.0,+ on_ground: false,+ flying: false,+ elytra: false,+ gliding: false,+ glide_armed: false,+ prev_jump: false,+ glide_boost: 0.0,+ jumps_left: 0,+ walk_dist: 0.0,+ sneaking: false,+ blessings: Attunement::default(),+ health: 20.0,+ max_health: 20.0,+ absorption: 0.0,+ effects: Vec::new(),+ hurt_cd: 0.0,+ attack_cd: 0.0,+ eat_cd: 0.0,+ air_max_y: y,+ dead: false,+ combat_cd: 0.0,+ }+ }++ pub fn blessed(&self, p: Passive) -> bool {+ self.blessings.has(p)+ }++ fn effect_amp(&self, k: Effect) -> Option<u8> {+ self.effects.iter().filter(|e| e.kind == k).map(|e| e.amp).max()+ }+ pub fn has_effect(&self, k: Effect) -> bool {+ self.effect_amp(k).is_some()+ }+ pub fn speed_mult(&self) -> f32 {+ let sp = self.effect_amp(Effect::Speed).map(|a| a as f32 + 1.0).unwrap_or(0.0);+ let sl = self.effect_amp(Effect::Slowness).map(|a| a as f32 + 1.0).unwrap_or(0.0);+ let traversal = if self.blessed(Passive::Traversal) { 0.25 } else { 0.0 };+ (1.0 + 0.2 * sp - 0.15 * sl + traversal).max(0.25)+ }+ pub fn jump_bonus(&self) -> f32 {+ 2.2 * self.effect_amp(Effect::JumpBoost).map(|a| a as f32 + 1.0).unwrap_or(0.0)+ }+ pub fn night_vision(&self) -> bool {+ self.has_effect(Effect::NightVision)+ }+ pub fn strength_bonus(&self) -> f32 {+ 3.0 * self.effect_amp(Effect::Strength).map(|a| a as f32 + 1.0).unwrap_or(0.0)+ }+ // Ares makes every melee swing land far harder. Sekhmet stacks on top of it once you're bloodied.+ pub fn might_mult(&self) -> f32 {+ let ares = if self.blessed(Passive::Might) { 1.5 } else { 1.0 };+ ares * if self.bloodraging() { BLOODRAGE_DAMAGE } else { 1.0 }+ }+ /// Sekhmet: cornered and bleeding, you hit harder and soak more.+ pub fn bloodraging(&self) -> bool {+ self.blessed(Passive::Bloodrage)+ && !self.dead+ && self.health <= self.max_health * BLOODRAGE_AT+ }+ fn resistance_mult(&self) -> f32 {+ let effects = (1.0+ - 0.2 * self.effect_amp(Effect::Resistance).map(|a| a as f32 + 1.0).unwrap_or(0.0))+ .max(0.0);+ effects * if self.bloodraging() { BLOODRAGE_RESIST } else { 1.0 }+ }+ /// Camazotz: how much health a melee hit for `dealt` damage gives back.+ pub fn lifesteal(&mut self, dealt: f32) {+ if self.blessed(Passive::Lifesteal) {+ self.heal(dealt * LIFESTEAL_SHARE);+ }+ }++ pub fn add_effect(&mut self, kind: Effect, secs: f32, amp: u8) {+ if kind == Effect::Absorption {+ self.absorption = self.absorption.max((amp as f32 + 1.0) * 4.0);+ }+ if let Some(e) = self.effects.iter_mut().find(|e| e.kind == kind) {+ if amp >= e.amp {+ e.amp = amp;+ }+ e.secs = e.secs.max(secs);+ } else {+ self.effects.push(ActiveEffect { kind, secs, amp });+ }+ }+ pub fn heal(&mut self, amt: f32) {+ self.health = (self.health + amt).min(self.max_health);+ }+ // Firework rocket: while gliding, surge forward and gain a little altitude.+ pub fn firework_boost(&mut self) {+ if self.gliding {+ self.glide_boost = (self.glide_boost + 16.0).min(26.0);+ self.vel.y = self.vel.y.max(0.0) + 5.0;+ self.air_max_y = self.pos.y;+ }+ }+ pub fn damage(&mut self, amt: f32) {+ if self.dead || self.hurt_cd > 0.0 || amt <= 0.0 {+ return;+ }+ let amt = amt * self.resistance_mult();+ let soak = amt.min(self.absorption);+ self.absorption -= soak;+ self.health -= amt - soak;+ self.hurt_cd = 0.4;+ self.combat_cd = DIVINITY_DELAY;+ if self.health <= 0.0 {+ self.health = 0.0;+ self.dead = true;+ }+ }+ // Aeolus: a landed hit throws you skyward, which is what makes its combos work.+ pub fn wind_burst(&mut self) {+ if self.blessed(Passive::WindBurst) {+ self.vel.y = self.vel.y.max(0.0) + 9.0;+ self.on_ground = false;+ self.air_max_y = self.pos.y;+ }+ }++ // Regeneration/poison/absorption expiry + cooldowns. Called every frame.+ pub fn tick_status(&mut self, dt: f32) {+ if self.hurt_cd > 0.0 {+ self.hurt_cd -= dt;+ }+ if self.combat_cd > 0.0 {+ self.combat_cd -= dt;+ }+ if self.attack_cd > 0.0 {+ self.attack_cd -= dt;+ }+ if self.eat_cd > 0.0 {+ self.eat_cd -= dt;+ }+ for e in self.effects.iter_mut() {+ e.secs -= dt;+ }+ self.effects.retain(|e| e.secs > 0.0);+ if let Some(a) = self.effect_amp(Effect::Regeneration) {+ self.heal((a as f32 + 1.0) * dt);+ }+ if let Some(a) = self.effect_amp(Effect::Poison) {+ if self.health > 1.0 {+ self.health = (self.health - (a as f32 + 1.0) * dt).max(1.0);+ }+ }+ // Absorption from food expires; Athena's shield doesn't, so it sets the floor the potion+ // value decays back down to rather than being wiped along with it.+ if !self.has_effect(Effect::Absorption) {+ let floor = if self.blessed(Passive::Divinity) { DIVINITY_SHIELD } else { 0.0 };+ self.absorption = self.absorption.min(floor);+ }+ // Athena's shield reforms between fights. A larger absorption from food still wins while it+ // lasts, since the cap is whichever is higher.+ if self.blessed(Passive::Divinity) && self.combat_cd <= 0.0 && !self.dead {+ let cap = DIVINITY_SHIELD.max(self.absorption);+ self.absorption = (self.absorption + DIVINITY_REGEN * dt).min(cap);+ }+ }+ pub fn eye_pos(&self) -> Vec3 {+ self.pos + vec3(0.0, 1.62, 0.0)+ }+ pub fn forward(&self) -> Vec3 {+ let cp = self.pitch.cos();+ vec3(-self.yaw.sin() * cp, -self.pitch.sin(), -self.yaw.cos() * cp).normalize_or_zero()+ }+ pub fn right(&self) -> Vec3 {+ vec3(self.yaw.cos(), 0.0, -self.yaw.sin()).normalize_or_zero()+ }++ pub fn tick(&mut self, dt: f32, input: &crate::input::InputState, chunks: &ChunkMap) {+ self.sneaking = input.sneak;+ let jump_edge = input.jump_held && !self.prev_jump;+ self.prev_jump = input.jump_held;+ // Deploy/retract elytra wings with a mid-air jump tap; retract automatically on the ground.+ if self.elytra && jump_edge && !self.on_ground && !self.flying {+ self.glide_armed = !self.glide_armed;+ }+ if self.on_ground || !self.elytra {+ self.glide_armed = false;+ }+ self.glide_boost = (self.glide_boost - 10.0 * dt).max(0.0);+ let fwd =+ if self.flying { self.forward() } else { vec3(-self.yaw.sin(), 0.0, -self.yaw.cos()) };+ let right = self.right();+ let mut wish = Vec3::ZERO;+ if input.move_forward.abs() > 0.001 {+ wish += fwd * input.move_forward;+ }+ if input.move_right.abs() > 0.001 {+ wish += right * input.move_right;+ }+ if wish.length_squared() > 0.0 {+ wish = wish.normalize_or_zero();+ }++ if self.flying {+ let speed = 10.0 * self.speed_mult() * if input.sprint { 2.0 } else { 1.0 };+ let mut vel = wish * speed;+ if input.jump_held {+ vel.y += speed;+ } // top button (Up)+ if input.down_held {+ vel.y -= speed;+ } // bottom button (Down)+ let old = self.pos;+ self.pos += vel * dt;+ if self.collides_at(self.pos, chunks) {+ self.pos = old;+ }+ self.walk_dist += (vel * dt).length();+ } else {+ let sneaking = input.sneak;+ // Cronus lets you sneak at a walking pace instead of a crawl.+ let sneak_mult = if self.blessed(Passive::SwiftSneak) { 1.0 } else { 0.3 };+ let speed = 4.3+ * self.speed_mult()+ * if sneaking {+ sneak_mult+ } else if input.sprint {+ 1.3+ } else {+ 1.0+ };+ // Auto-unstuck: if we ended up inside terrain (bad save, block placed onto us, spawn+ // fractionally embedded) rise until free so the player is never permanently trapped.+ if self.collides_at(self.pos, chunks) {+ let mut lift = 0.0;+ while lift < 3.0 && self.collides_at(self.pos, chunks) {+ self.pos.y += 0.1;+ lift += 0.1;+ }+ self.vel.y = 0.0;+ }+ // Elytra glide: once wings are deployed (mid-air jump tap), sail forward along the look+ // direction with a slow, controlled fall instead of walking control.+ self.gliding = self.glide_armed && !self.on_ground;+ let horiz_vel = if self.gliding {+ let f = self.forward();+ vec3(f.x, 0.0, f.z).normalize_or_zero() * (11.0 + self.glide_boost)+ } else {+ vec3(wish.x * speed, 0.0, wish.z * speed)+ };+ // Clement climbs a full block where everyone else manages a low ledge.+ let step_h = if self.blessed(Passive::Traversal) { 1.05 } else { 0.6 };+ let mut new_pos = self.pos;+ // X axis: step up small ledges when grounded; when sneaking, refuse to walk off edges.+ let try_x = vec3(new_pos.x + horiz_vel.x * dt, new_pos.y, new_pos.z);+ if !self.collides_at(try_x, chunks) {+ if !(sneaking && self.on_ground) || self.supported_at(try_x, chunks) {+ new_pos.x = try_x.x;+ }+ } else if self.on_ground && !sneaking {+ // Climb to the surface that blocked us, not by a fixed amount.+ if let Some(top) = self.step_up_to(try_x, chunks, new_pos.y, step_h) {+ new_pos.x = try_x.x;+ new_pos.y = top;+ }+ }+ // Z axis, same rules.+ let try_z = vec3(new_pos.x, new_pos.y, new_pos.z + horiz_vel.z * dt);+ if !self.collides_at(try_z, chunks) {+ if !(sneaking && self.on_ground) || self.supported_at(try_z, chunks) {+ new_pos.z = try_z.z;+ }+ } else if self.on_ground && !sneaking {+ if let Some(top) = self.step_up_to(try_z, chunks, new_pos.y, step_h) {+ new_pos.z = try_z.z;+ new_pos.y = top;+ }+ }+ self.walk_dist +=+ (vec3(new_pos.x, 0.0, new_pos.z) - vec3(self.pos.x, 0.0, self.pos.z)).length();+ // Vertical: gravity + collision, resting at whatever height horizontal step-up left us at.+ // Yamm turns water into something you can actually swim in: buoyant, with jump to rise.+ let submerged = (self.blessed(Passive::Deep) || self.blessed(Passive::Conduit))+ && self.in_water(chunks);+ let base_y = new_pos.y;+ if submerged {+ self.vel.y = if input.jump_held { 4.5 } else { (self.vel.y - 6.0 * dt).max(-2.0) };+ } else {+ self.vel.y -= 28.0 * dt;+ }+ if self.gliding {+ self.vel.y = self.vel.y.max(-3.5);+ } // slow, gliding descent+ new_pos.y = base_y + self.vel.y * dt;+ if self.collides_at(new_pos, chunks) {+ if self.vel.y <= 0.0 {+ // Landing: come to rest exactly on the surface, so a slab holds you half a+ // block up instead of at the cell boundary.+ let depth = ((base_y - new_pos.y).ceil() as i32 + 2).max(2);+ new_pos.y =+ self.surface_under(new_pos, chunks, base_y, depth).unwrap_or(base_y);+ self.on_ground = true;+ } else {+ new_pos.y = base_y; // knocked our head on something above+ }+ self.vel.y = 0.0;+ } else {+ let mut probe = new_pos;+ probe.y -= 0.05;+ self.on_ground =+ probe.y <= 0.0 || (self.collides_at(probe, chunks) && self.vel.y <= 0.0);+ if self.on_ground && self.vel.y <= 0.0 {+ self.vel.y = 0.0;+ }+ }+ if self.on_ground {+ self.jumps_left = self.extra_jumps();+ }+ // Swimming is controlled descent, not a fall — don't let a dive bank landing damage.+ if submerged {+ self.air_max_y = new_pos.y;+ }+ // Can't jump while sneaking (must toggle sneak off first).+ if input.jump_held && self.on_ground && !sneaking {+ self.vel.y = 8.5 + self.jump_bonus();+ self.on_ground = false;+ } else if jump_edge+ && !self.on_ground+ && !sneaking+ && !submerged+ && !self.gliding+ && !self.flying+ && self.jumps_left > 0+ {+ // Hyacinthus: a second leap out of mid-air.+ self.jumps_left -= 1;+ self.vel.y = 8.5 + self.jump_bonus();+ self.air_max_y = self.pos.y;+ }+ self.pos = new_pos;+ }+ if self.pos.y < 0.1 {+ self.pos.y = 0.1;+ self.vel.y = 0.0;+ self.on_ground = true;+ }+ // Fall damage: track peak airborne height, hurt on landing beyond a safe margin.+ // Flying and elytra gliding never accrue fall damage.+ if self.flying || self.gliding {+ self.air_max_y = self.pos.y;+ } else if !self.on_ground {+ if self.pos.y > self.air_max_y {+ self.air_max_y = self.pos.y;+ }+ } else {+ let dmg =+ landing_damage(self.air_max_y, self.pos.y, self.blessed(Passive::FeatherFall));+ if dmg > 0.0 {+ self.damage(dmg);+ }+ self.air_max_y = self.pos.y;+ }+ }++ /// How many mid-air jumps the attuned blessings allow.+ fn extra_jumps(&self) -> u8 {+ if self.blessed(Passive::DoubleJump) {+ 1+ } else {+ 0+ }+ }++ /// True when the player's body is inside water.+ fn in_water(&self, chunks: &ChunkMap) -> bool {+ let (x, z) = (self.pos.x.floor() as i32, self.pos.z.floor() as i32);+ let feet = chunks.get_block_world(x, self.pos.y.floor() as i32, z);+ let chest = chunks.get_block_world(x, (self.pos.y + 1.0).floor() as i32, z);+ feet == 12 || chest == 12+ }++ /// The highest surface under the player's footprint at or below `ceiling` — the height they+ /// should come to rest at. Probing all four corners means the tallest thing under any part of+ /// the body wins, so you stand on a stair's step rather than sinking into it.+ fn surface_under(&self, pos: Vec3, chunks: &ChunkMap, ceiling: f32, depth: i32) -> Option<f32> {+ let hw = 0.3;+ let mut best: Option<f32> = None;+ for &dx in &[-hw, hw] {+ for &dz in &[-hw, hw] {+ if let Some(t) = chunks.surface_below(pos.x + dx, pos.z + dz, ceiling, depth) {+ if best.is_none_or(|b| t > b) {+ best = Some(t);+ }+ }+ }+ }+ best+ }++ /// The height to climb to when walking into something: the surface just above the feet, if it+ /// is within `max_step` and the player actually fits standing on it. Returns the real surface+ /// height, so a slab lifts you half a block rather than the full step allowance.+ fn step_up_to(&self, pos: Vec3, chunks: &ChunkMap, from_y: f32, max_step: f32) -> Option<f32> {+ let target = self.surface_under(pos, chunks, from_y + max_step, 2)?;+ if target <= from_y + 1e-4 {+ return None;+ }+ if self.collides_at(vec3(pos.x, target, pos.z), chunks) {+ return None;+ }+ Some(target)+ }++ // True if there is something solid to stand on just under the player's footprint at `pos` (used+ // so a sneaking player won't walk off ledges). A slab counts only where its solid half reaches.+ fn supported_at(&self, pos: Vec3, chunks: &ChunkMap) -> bool {+ self.surface_under(pos, chunks, pos.y + 1e-3, 1).is_some_and(|t| pos.y - t < 0.1)+ }++ fn collides_at(&self, pos: Vec3, chunks: &ChunkMap) -> bool {+ let hw = 0.3;+ let min = [pos.x - hw, pos.y, pos.z - hw];+ let max = [pos.x + hw, pos.y + 1.8, pos.z + hw];+ let x0 = min[0].floor() as i32;+ let y0 = min[1].floor() as i32;+ let z0 = min[2].floor() as i32;+ let x1 = max[0].ceil() as i32;+ let y1 = max[1].ceil() as i32;+ let z1 = max[2].ceil() as i32;+ for x in x0..=x1 {+ for y in y0..=y1 {+ for z in z0..=z1 {+ let id = chunks.get_block_world(x, y, z);+ if id == 0 || !Block::from_id(id).is_solid() {+ continue;+ }+ let meta = chunks.get_meta_world(x, y, z);+ let cell = [x as f32, y as f32, z as f32];+ for b in Block::from_id(id).collision_boxes(meta).as_slice() {+ if b.overlaps_at(cell, min, max) {+ return true;+ }+ }+ }+ }+ }+ false+ }+}++include!("player_part1.rs");
games/voxels/src/main/rust/src/player_s2.rs
diff --git a/games/voxels/src/main/rust/src/player_s2.rs b/games/voxels/src/main/rust/src/player_s2.rsnew file mode 100644index 0000000000..5f093b9140--- /dev/null+++ b/games/voxels/src/main/rust/src/player_s2.rs@@ -0,0 +1,7 @@+#[cfg(test)]+#[path = "player_coverage_tests.rs"]+mod player_coverage_tests;++#[cfg(test)]+#[path = "player_tick_tests.rs"]+mod player_tick_tests;
games/voxels/src/main/rust/src/vulkan/renderer.rs
diff --git a/games/voxels/src/main/rust/src/vulkan/renderer.rs b/games/voxels/src/main/rust/src/vulkan/renderer.rsindex e32e7a56bd..c4df2cd5ba 100644--- a/games/voxels/src/main/rust/src/vulkan/renderer.rs+++ b/games/voxels/src/main/rust/src/vulkan/renderer.rs@@ -77,901 +77,5 @@ pub struct VulkanRenderer { pub suspended: bool, } -impl VulkanRenderer {- /// Builds the renderer on an existing Vulkan context.- ///- /// # Safety- /// `ctx` must own live Vulkan handles, and this must run on the thread that will own the renderer.- pub unsafe fn new(ctx: VulkanContext, width: u32, height: u32) -> Result<Self, String> {- let swapchain = Swapchain::new(&ctx, width.max(1), height.max(1))?;- let ubo_size = std::mem::size_of::<UboData>() as u64;- let instance = ctx.instance.clone();- let device = ctx.device.clone();- let phys = ctx.physical_device;- let pool_info = vk::CommandPoolCreateInfo::default()- .flags(vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER)- .queue_family_index(ctx.queue_family_index);- let command_pool =- device.create_command_pool(&pool_info, None).map_err(|e| format!("pool {e:?}"))?;- let atlas_pixels = crate::texture_atlas::load_atlas_bin();- let atlas = unsafe {- TextureAtlas::new(&instance, &device, phys, command_pool, ctx.queue, &atlas_pixels)?- };- let entity_pixels = crate::texture_atlas::load_entity_atlas_bin();- let entity_atlas = unsafe {- TextureAtlas::new_sized(- crate::texture_atlas::TextureUpload {- instance: &instance,- device: &device,- phys,- command_pool,- queue: ctx.queue,- },- crate::texture_atlas::ENTITY_ATLAS_W,- crate::texture_atlas::ENTITY_ATLAS_H,- &entity_pixels,- )?- };- // Dynamic host-visible buffers for the per-frame mob mesh.- let entity_vbuf = unsafe {- AllocatedBuffer::new(- &instance,- &device,- phys,- (MAX_ENTITY_VERTS * std::mem::size_of::<VulkanVertex>()) as u64,- vk::BufferUsageFlags::VERTEX_BUFFER,- vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,- )
Diff truncated.