voxels: widen block and item ids to 16 bits
- Commit
d7a415c9e163d9c89a5da1c350ef9755a40f56aa- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-05 19:00 UTC (4 months ago)
- Parents
2db6b9d
Diff
games/voxels/src/main/rust/src/ambience.rs
diff --git a/games/voxels/src/main/rust/src/ambience.rs b/games/voxels/src/main/rust/src/ambience.rsindex 3a7e5e233d..eb322ec485 100644--- a/games/voxels/src/main/rust/src/ambience.rs+++ b/games/voxels/src/main/rust/src/ambience.rs@@ -9,6 +9,8 @@ // and doesn't need any). /// Surface classes a footstep can land on. The Kotlin synthesiser picks a timbre per class.+use crate::world::block::Id;+ pub const STEP_STONE: u8 = 0; pub const STEP_WOOD: u8 = 1; pub const STEP_GRASS: u8 = 2;@@ -33,7 +35,7 @@ const CUE_GAP_CALM: f32 = 46.0; const CUE_GAP_TENSE: f32 = 13.0; /// What a footstep on this block should sound like.-pub fn step_material(id: u8) -> u8 {+pub fn step_material(id: Id) -> u8 { match id { 12 => STEP_WATER, 11 | 42 | 43 | 44 => STEP_SNOW,@@ -77,7 +79,7 @@ pub struct Ambience { impl Ambience { /// `walked` is the distance covered this tick, `under` the block being stood on. #[allow(clippy::too_many_arguments)]- pub fn tick(&mut self, dt: f32, walked: f32, on_ground: bool, under: u8, dark: bool, deep: bool, roll: f32) {+ pub fn tick(&mut self, dt: f32, walked: f32, on_ground: bool, under: Id, dark: bool, deep: bool, roll: f32) { if on_ground && under != 0 { self.step_dist += walked; if self.step_dist >= STRIDE {
games/voxels/src/main/rust/src/blessing.rs
diff --git a/games/voxels/src/main/rust/src/blessing.rs b/games/voxels/src/main/rust/src/blessing.rsindex 60113da1b4..a84f66f01c 100644--- a/games/voxels/src/main/rust/src/blessing.rs+++ b/games/voxels/src/main/rust/src/blessing.rs@@ -5,6 +5,8 @@ // of a few permanent slots and grants a passive for the rest of the run. Attunements persist across // sessions and can be unbound at any time, which returns the charm. +use crate::world::block::Id;+ use serde::{Deserialize, Serialize}; /// How many blessings can be attuned at once.@@ -43,7 +45,7 @@ pub enum Passive { } pub struct Blessing {- pub id: u8,+ pub id: Id, pub passive: Passive, /// Icon file in assets/block/, and the name shown in the UI. pub icon: &'static str,@@ -51,7 +53,7 @@ pub struct Blessing { pub effect: &'static str, } -const fn b(id: u8, passive: Passive, icon: &'static str, name: &'static str, effect: &'static str) -> Blessing {+const fn b(id: Id, passive: Passive, icon: &'static str, name: &'static str, effect: &'static str) -> Blessing { Blessing { id, passive, icon, name, effect } } @@ -88,22 +90,22 @@ pub const PANTHEON: [Blessing; 27] = [ b(249, Passive::WardUndead, "blessing_anubis.png", "Blessing of Anubis", "The undead will not come near you"), ]; -pub fn is_blessing(id: u8) -> bool { PANTHEON.iter().any(|b| b.id == id) }-pub fn find(id: u8) -> Option<&'static Blessing> { PANTHEON.iter().find(|b| b.id == id) }+pub fn is_blessing(id: Id) -> bool { PANTHEON.iter().any(|b| b.id == id) }+pub fn find(id: Id) -> Option<&'static Blessing> { PANTHEON.iter().find(|b| b.id == id) } /// The blessings currently bound to the player. Empty slots hold 0. #[derive(Clone, Copy, Debug, Default, Serialize, Deserialize)] pub struct Attunement {- pub slots: [u8; SLOTS],+ pub slots: [Id; SLOTS], } impl Attunement { pub fn has(&self, passive: Passive) -> bool { self.slots.iter().any(|&id| find(id).is_some_and(|b| b.passive == passive)) }- pub fn contains(&self, id: u8) -> bool { self.slots.contains(&id) }+ pub fn contains(&self, id: Id) -> bool { self.slots.contains(&id) } /// Bind a charm to the first free slot. Fails if it's already bound or there's no room.- pub fn attune(&mut self, id: u8) -> bool {+ pub fn attune(&mut self, id: Id) -> bool { if !is_blessing(id) || self.contains(id) { return false; } match self.slots.iter_mut().find(|s| **s == 0) { Some(slot) => { *slot = id; true }@@ -111,7 +113,7 @@ impl Attunement { } } /// Unbind the charm in `slot`, returning it so the caller can hand it back to the player.- pub fn release(&mut self, slot: usize) -> Option<u8> {+ pub fn release(&mut self, slot: usize) -> Option<Id> { let id = *self.slots.get(slot)?; if id == 0 { return None; } self.slots[slot] = 0;
games/voxels/src/main/rust/src/container.rs
diff --git a/games/voxels/src/main/rust/src/container.rs b/games/voxels/src/main/rust/src/container.rsindex 464594cd47..30c08c2663 100644--- a/games/voxels/src/main/rust/src/container.rs+++ b/games/voxels/src/main/rust/src/container.rs@@ -4,6 +4,7 @@ // flat byte per block — so they get their own JSON file next to player.json. use crate::inventory::InvSlot;+use crate::world::block::Id; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::fs;@@ -36,7 +37,7 @@ impl Containers { self.map.get_mut(&key)?.get_mut(idx) } // Merge a stack into the container, returning what wouldn't fit.- pub fn add(&mut self, key: ContainerKey, id: u8, mut count: i32) -> i32 {+ pub fn add(&mut self, key: ContainerKey, id: Id, mut count: i32) -> i32 { let Some(slots) = self.map.get_mut(&key) else { return count; }; if crate::item::has_durability(id) { // Tools and armor never stack: they need a slot of their own to keep their durability.@@ -103,10 +104,10 @@ pub fn roll_loot(x: i32, y: i32, z: i32, dim: u8, lucky: bool) -> Vec<InvSlot> { let mut r = ((x as u64).wrapping_mul(73856093) ^ (y as u64).wrapping_mul(19349663) ^ (z as u64).wrapping_mul(83492791)) | 1; let next = |r: &mut u64| { *r ^= *r << 13; *r ^= *r >> 7; *r ^= *r << 17; *r }; // (item id, max stack from this chest).- let end_pool: [(u8, i32); 9] = [(188, 1), (176, 1), (175, 1), (170, 1), (129, 1), (155, 3), (156, 4), (133, 2), (24, 2)];- let nether_pool: [(u8, i32); 7] = [(192, 6), (194, 2), (195, 2), (157, 8), (154, 4), (133, 1), (138, 3)];- let over_pool: [(u8, i32); 12] = [(157, 8), (154, 4), (155, 1), (156, 2), (131, 4), (133, 1), (168, 1), (128, 1), (138, 3), (137, 2), (193, 2), (223, 3)];- let pool: &[(u8, i32)] = match dim { 2 => &end_pool, 1 => &nether_pool, _ => &over_pool };+ let end_pool: [(Id, i32); 9] = [(188, 1), (176, 1), (175, 1), (170, 1), (129, 1), (155, 3), (156, 4), (133, 2), (24, 2)];+ let nether_pool: [(Id, i32); 7] = [(192, 6), (194, 2), (195, 2), (157, 8), (154, 4), (133, 1), (138, 3)];+ let over_pool: [(Id, i32); 12] = [(157, 8), (154, 4), (155, 1), (156, 2), (131, 4), (133, 1), (168, 1), (128, 1), (138, 3), (137, 2), (193, 2), (223, 3)];+ let pool: &[(Id, i32)] = match dim { 2 => &end_pool, 1 => &nether_pool, _ => &over_pool }; let mut slots = vec![InvSlot::default(); CONTAINER_SLOTS]; // Glaucus turns up more in every chest.@@ -160,6 +161,20 @@ mod tests { assert!(c.get(key).unwrap().iter().all(|s| s.id == 0), "a new chest must start empty"); } + #[test]+ fn every_loot_pool_id_names_something_real() {+ use crate::world::block::is_real_id;+ // Every dimension's pool, sampled across enough positions to hit each entry.+ for dim in 0..3u8 {+ for i in 0..80i32 {+ for s in roll_loot(i * 11, 40, i * 17, dim, i % 2 == 0) {+ if s.id == 0 { continue; }+ assert!(is_real_id(s.id), "dim {dim} loot contains {}, which is nothing", s.id);+ }+ }+ }+ }+ #[test] fn loot_is_deterministic_per_position() { let a = roll_loot(5, 30, 9, 0, false);
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 2f3b6e6e28..2586e64b3f 100644--- a/games/voxels/src/main/rust/src/engine.rs+++ b/games/voxels/src/main/rust/src/engine.rs@@ -1,4 +1,4 @@-use crate::world::{ChunkMap, block::{Block, Shape}};+use crate::world::{ChunkMap, block::{Block, Id, Shape}}; use crate::player::Player; use crate::inventory::Inventory; use crate::entity::{Mob, MobKind, Particle, Projectile, ProjKind, build_entity_mesh, tick_particles, append_particles, append_projectiles};@@ -403,7 +403,7 @@ pub fn rebuild_chunk_meshes(state: &mut EngineState, chunk_pos: crate::world::ch 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| -> (u8, u8) {+ 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] {@@ -629,7 +629,7 @@ pub fn tick_and_render() { } // Remove dead mobs and auto-collect their drops. Glaucus makes ordinary kills pay double, // but not bosses — a second Nether Star would hand out a free extra beacon.- let mut loot: Vec<(u8, bool)> = Vec::new();+ let mut loot: Vec<(Id, bool)> = Vec::new(); state.mobs.retain(|m| if m.health <= 0.0 { // An elite was twice the fight, so it pays twice. let times = if m.elite { 2 } else { 1 };@@ -799,8 +799,8 @@ fn publish_ui(state: &EngineState) { format!("sh{:.1} main{:.1} bloom{:.1} comp{:.1}", p[0], p[1], p[2], p[3]) }).unwrap_or_default(), }).to_string();- let has = |id: u8| state.inventory.slots.iter().any(|s| s.id == id && s.count > 0);- let armor_at_least = |lo: u8, hi: u8| state.inventory.armor.iter().all(|s| s.id >= lo && s.id <= hi);+ let has = |id: Id| state.inventory.slots.iter().any(|s| s.id == id && s.count > 0);+ let armor_at_least = |lo: Id, hi: Id| state.inventory.armor.iter().all(|s| s.id >= lo && s.id <= hi); let stats = serde_json::json!({ "placed": state.inventory.placed, "broken": state.inventory.broken, "walked": state.player.walk_dist as i32, "night": state.night_survived,@@ -865,7 +865,7 @@ pub fn get_smelt_json() -> String { cref(&SMELT_CACHE, "{}").lock().map(|c| c.cl pub fn get_ambience_json() -> String { cref(&AMBIENCE_CACHE, "{}").lock().map(|c| c.clone()).unwrap_or_else(|_| "{}".into()) } pub fn inventory_move(from: usize, to: usize) { with_engine(|s| s.inventory.move_item(from, to)); }-pub fn inventory_give(id: u8) { with_engine(|s| s.inventory.give(id)); }+pub fn inventory_give(id: Id) { with_engine(|s| s.inventory.give(id)); } pub fn inventory_craft(recipe: usize) -> bool { with_engine(|s| s.inventory.craft(recipe)).unwrap_or(false) } pub fn do_trade(idx: usize) -> bool { with_engine(|s| {@@ -946,7 +946,7 @@ fn dim_dir(base: &str, dim: u8) -> String { // Layer k (k=1..4) at depth k must be a full (2k+1)x(2k+1) square of iron/diamond/emerald blocks // centred under the beacon. Tier stops at the first incomplete layer. fn beacon_tier(chunks: &ChunkMap, x: i32, y: i32, z: i32) -> i32 {- let is_mineral = |id: u8| matches!(id, 23 | 24 | 25 | 93 | 94 | 95);+ let is_mineral = |id: Id| matches!(id, 23 | 24 | 25 | 93 | 94 | 95); let mut tier = 0; for k in 1..=4i32 { let mut full = true;@@ -1369,7 +1369,7 @@ fn do_break(state: &mut EngineState, origin: Vec3, dir: Vec3) -> bool { if sel == crate::item::BRUSH { if let Some(hit) = crate::raycast::raycast(&state.chunks, origin, dir, player_reach(state)) { let (x, y, z) = hit.pos;- if state.chunks.get_block_world(x, y, z) == Block::SuspiciousSand as u8 {+ if state.chunks.get_block_world(x, y, z) == Block::SuspiciousSand as Id { let mut r = state.spawn_rng; r ^= r << 13; r ^= r >> 17; r ^= r << 5; state.spawn_rng = r;@@ -1377,7 +1377,7 @@ fn do_break(state: &mut EngineState, origin: Vec3, dir: Vec3) -> bool { if !state.inventory.has_room_for(id, 1) { return false; } state.inventory.add_block(id); state.did_brush = true;- state.chunks.set_block_world(x, y, z, Block::Sand as u8);+ state.chunks.set_block_world(x, y, z, Block::Sand as Id); mark_neighbors_dirty(state, x, z); damage_tool(state); let c = vec3(x as f32 + 0.5, y as f32 + 1.0, z as f32 + 0.5);@@ -1695,9 +1695,9 @@ pub fn get_blessings_json() -> String { pub fn get_blessing_catalog_json() -> String { crate::blessing::catalog_json() } // Ore blocks, for the Fortune blessing.-fn is_ore(id: u8) -> bool { matches!(id, 18..=22 | 90 | 91 | 92) }+fn is_ore(id: Id) -> bool { matches!(id, 18..=22 | 90 | 91 | 92) } // Leaf blocks, which sometimes drop an apple.-fn is_leaves(id: u8) -> bool { matches!(id, 5 | 28 | 31 | 48 | 80) }+fn is_leaves(id: Id) -> bool { matches!(id, 5 | 28 | 31 | 48 | 80) } // Blessings that act over time rather than at a single event: Lu Ban repairs gear a point at a // time, Demeter freezes the water the player walks over.@@ -1778,7 +1778,7 @@ fn tick_farmland(state: &mut EngineState, dt: f32, player_pos: Vec3) { let stage = crate::world::block::crop_stage(meta); if stage >= crate::world::block::CROP_RIPE { continue; } // Crops only grow on tended ground; break the farmland and the field stalls.- if state.chunks.get_block_world(x, y - 1, z) != Block::Farmland as u8 { continue; }+ if state.chunks.get_block_world(x, y - 1, z) != Block::Farmland as Id { continue; } state.chunks.set_block_meta_world(x, y, z, id, crate::world::block::crop_meta(stage + 1)); grown.push((x, z)); }@@ -1804,11 +1804,11 @@ fn harvest_crop(state: &mut EngineState, crop: Block, meta: u8) { /// What a dig site gives up. Matcha's archaeology yields pottery sherds, which this game doesn't /// model, so the pool is the small treasures a buried cache would plausibly hold.-pub fn buried_find(roll: f32) -> u8 {+pub fn buried_find(roll: f32) -> Id { match (roll.clamp(0.0, 0.999) * 100.0) as u32 { 0..=29 => 137, // leather scraps 30..=54 => 236, // copper ingot- 55..=74 => Block::Amethyst as u8,+ 55..=74 => Block::Amethyst as Id, 75..=89 => 237, // gold ingot 90..=96 => 156, // emerald _ => 155, // diamond@@ -1915,10 +1915,10 @@ fn do_place(state: &mut EngineState, origin: Vec3, dir: Vec3) -> bool { if let Some(hit) = crate::raycast::raycast(&state.chunks, origin, dir, player_reach(state)) { let (x, y, z) = hit.pos; let (tx, ty, tz) = (x + hit.normal.0, y + hit.normal.1, z + hit.normal.2);- let on_farmland = state.chunks.get_block_world(x, y, z) == Block::Farmland as u8 && hit.normal.1 == 1;+ let on_farmland = state.chunks.get_block_world(x, y, z) == Block::Farmland as Id && hit.normal.1 == 1; // Plant only once the write is known to have landed, so an unloaded chunk can't eat the seed. if on_farmland && state.chunks.get_block_world(tx, ty, tz) == 0- && state.chunks.set_block_meta_world(tx, ty, tz, crop as u8, crate::world::block::crop_meta(0))+ && state.chunks.set_block_meta_world(tx, ty, tz, crop as Id, crate::world::block::crop_meta(0)) { if state.inventory.consume_selected().is_none() { state.chunks.set_block_world(tx, ty, tz, 0);@@ -1943,7 +1943,7 @@ fn do_place(state: &mut EngineState, origin: Vec3, dir: Vec3) -> bool { // Only the face on the cell's empty side can complete it. if (existing_top && hit.normal.1 == -1) || (!existing_top && hit.normal.1 == 1) { if state.inventory.consume_selected().is_some() {- state.chunks.set_block_world(tx, ty, tz, block.parent() as u8);+ state.chunks.set_block_world(tx, ty, tz, block.parent() as Id); mark_neighbors_dirty(state, tx, tz); return true; }@@ -1996,10 +1996,10 @@ pub fn place_block_at(px: f32, py: f32) -> i32 { // Shearing a sheep: wool now, and the sheep walks away unharmed to regrow it. let held = state.inventory.selected_block(); if crate::item::is_shears(held) && state.mobs[idx].kind == MobKind::Sheep && !state.mobs[idx].sheared {- if !state.inventory.has_room_for(Block::Wool as u8, WOOL_PER_SHEARING) { return 0; }+ if !state.inventory.has_room_for(Block::Wool as Id, WOOL_PER_SHEARING) { return 0; } state.mobs[idx].sheared = true; state.did_shear = true;- for _ in 0..WOOL_PER_SHEARING { state.inventory.add_block(Block::Wool as u8); }+ for _ in 0..WOOL_PER_SHEARING { state.inventory.add_block(Block::Wool as Id); } damage_tool(state); return 1; }@@ -2116,7 +2116,7 @@ mod tests { for i in 0..n { let id = buried_find(i as f32 / n as f32); assert!(id != 0, "an empty dig site");- assert!(id <= crate::world::block::MAX_BLOCK_ID || crate::item::is_item(id), "{id} is not an id");+ assert!(id <= crate::world::block::MAX_LOW_BLOCK_ID || crate::item::is_item(id), "{id} is not an id"); if id == 155 { diamonds += 1; } } let rate = diamonds as f32 / n as f32;
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 216f75ac7c..fe2e16ed1d 100644--- a/games/voxels/src/main/rust/src/entity.rs+++ b/games/voxels/src/main/rust/src/entity.rs@@ -3,6 +3,7 @@ use glam::Vec3; use crate::vulkan::buffers::Vertex; use crate::texture_atlas::{ENTITY_ATLAS_W, ENTITY_CELL};+use crate::world::block::Id; const ATLAS: f32 = ENTITY_ATLAS_W as f32; const CELL: f32 = ENTITY_CELL as f32;@@ -135,7 +136,7 @@ impl MobKind { pub fn hit_radius(self) -> f32 { match self { MobKind::Dragon => 2.2, MobKind::Ghast => 2.0, MobKind::Wither => 1.3, MobKind::Shulker => 0.55, _ => 0.45 } } pub fn contact_damage(self) -> f32 { match self { MobKind::Zombie => 4.0, MobKind::Dragon => 7.0, MobKind::Wither => 6.0, MobKind::Blaze | MobKind::WitherSkeleton => 5.0, MobKind::Shulker => 4.0, _ => 0.0 } } // Item ids dropped on death (auto-collected into the inventory).- pub fn loot(self) -> &'static [u8] {+ pub fn loot(self) -> &'static [Id] { match self { // Livestock give up raw meat (222); it has to be cooked in a furnace before it feeds you. MobKind::Pig => &[222], MobKind::Cow => &[137, 222], MobKind::Sheep => &[222], MobKind::Chicken => &[222, 149],@@ -543,7 +544,7 @@ mod tests { } /// A wide platform so a wandering mob can't stroll off it during the test.- fn platform(w: &mut ChunkMap, id: u8, meta: u8) {+ fn platform(w: &mut ChunkMap, id: Id, meta: u8) { for x in -6..=6 { for z in -6..=6 { w.set_block_meta_world(x, SKY, z, id, meta); } } } @@ -563,7 +564,7 @@ mod tests { #[test] fn a_mob_rests_on_a_slabs_surface() { let mut w = world();- platform(&mut w, Block::StoneSlab as u8, 0);+ platform(&mut w, Block::StoneSlab as Id, 0); let m = settle(&w, MobKind::Pig, SKY as f32 + 3.0); assert!(m.on_ground, "the pig should have landed"); assert!((m.pos.y - (SKY as f32 + 0.5)).abs() < 1e-3,@@ -574,7 +575,7 @@ mod tests { #[test] fn a_mob_rests_a_whole_block_up_on_cubes() { let mut w = world();- platform(&mut w, Block::Stone as u8, 0);+ platform(&mut w, Block::Stone as Id, 0); let m = settle(&w, MobKind::Pig, SKY as f32 + 3.0); assert!((m.pos.y - (SKY as f32 + 1.0)).abs() < 1e-3, "got {}", m.pos.y); }@@ -583,7 +584,7 @@ mod tests { #[test] fn a_mob_stands_on_top_of_a_top_slab() { let mut w = world();- platform(&mut w, Block::StoneSlab as u8, crate::world::block::META_TOP);+ platform(&mut w, Block::StoneSlab as Id, crate::world::block::META_TOP); let m = settle(&w, MobKind::Pig, SKY as f32 + 3.0); assert!((m.pos.y - (SKY as f32 + 1.0)).abs() < 1e-3, "got {}", m.pos.y); }@@ -593,8 +594,8 @@ mod tests { fn a_mob_steps_up_onto_a_slab() { let mut w = world(); // A long floor so the chase never runs off the end, with a slab ledge across the path.- for x in -3..=3 { for z in -20..=3 { w.set_block_world(x, SKY, z, Block::Stone as u8); } }- for x in -3..=3 { w.set_block_meta_world(x, SKY + 1, -3, Block::StoneSlab as u8, 0); }+ for x in -3..=3 { for z in -20..=3 { w.set_block_world(x, SKY, z, Block::Stone as Id); } }+ for x in -3..=3 { w.set_block_meta_world(x, SKY + 1, -3, Block::StoneSlab as Id, 0); } let terrain = Terrain { solid: &|x, y, z| w.solid_at(x, y, z),@@ -675,7 +676,7 @@ mod tests { #[test] fn a_warded_mob_backs_off() { let mut w = world();- for x in -6..=6 { for z in -6..=20 { w.set_block_world(x, SKY, z, Block::Stone as u8); } }+ for x in -6..=6 { for z in -6..=20 { w.set_block_world(x, SKY, z, Block::Stone as Id); } } let terrain = Terrain { solid: &|x, y, z| w.solid_at(x, y, z), surface: &|x, z, ceiling| w.surface_below(x, z, ceiling, 2),
games/voxels/src/main/rust/src/fishing.rs
diff --git a/games/voxels/src/main/rust/src/fishing.rs b/games/voxels/src/main/rust/src/fishing.rsindex b021773089..aee0a07a9e 100644--- a/games/voxels/src/main/rust/src/fishing.rs+++ b/games/voxels/src/main/rust/src/fishing.rs@@ -4,9 +4,11 @@ // lives in the loot pool instead: mostly fish, sometimes junk, occasionally something worth keeping. /// Item 254. Cook it in a furnace for the cooked fish the villagers sell.-pub const RAW_FISH: u8 = 254;+use crate::world::block::Id;++pub const RAW_FISH: Id = 254; /// Item 253.-pub const ROD: u8 = 253;+pub const ROD: Id = 253; /// Shortest and longest wait before a bite. const WAIT_MIN: f32 = 3.0;@@ -60,7 +62,7 @@ impl Fishing { } /// What comes up on the hook. `lucky` is Glaucus (SeaLuck), which trades junk for treasure.-pub fn catch_of_the_day(roll: f32, lucky: bool) -> u8 {+pub fn catch_of_the_day(roll: f32, lucky: bool) -> Id { let r = roll.clamp(0.0, 0.999); // Treasure first, then junk, then the fish that makes up the bulk of every pool. let treasure = if lucky { 0.14 } else { 0.06 };@@ -70,11 +72,11 @@ pub fn catch_of_the_day(roll: f32, lucky: bool) -> u8 { match ((r / treasure) * 4.0) as u32 { 0 => 191, // ender pearl 1 => 156, // emerald- 2 => crate::world::block::Block::SeaLantern as u8,+ 2 => crate::world::block::Block::SeaLantern as Id, _ => 137, // leather (a waterlogged boot, near enough) } } else if r < treasure + junk {- crate::world::block::Block::Kelp as u8+ crate::world::block::Block::Kelp as Id } else { RAW_FISH }@@ -131,9 +133,9 @@ mod tests { for i in 0..n { let id = catch_of_the_day(i as f32 / n as f32, lucky); assert!(id != 0, "the hook came up with nothing");- assert!(id <= crate::world::block::MAX_BLOCK_ID || crate::item::is_item(id), "{id} is not an id");+ assert!(id <= crate::world::block::MAX_LOW_BLOCK_ID || crate::item::is_item(id), "{id} is not an id"); if id == RAW_FISH { fish += 1; }- else if id == crate::world::block::Block::Kelp as u8 { junk += 1; }+ else if id == crate::world::block::Block::Kelp as Id { junk += 1; } else { treasure += 1; } } (fish, junk, treasure)
games/voxels/src/main/rust/src/inventory.rs
diff --git a/games/voxels/src/main/rust/src/inventory.rs b/games/voxels/src/main/rust/src/inventory.rsindex 8286947f82..1765f97752 100644--- a/games/voxels/src/main/rust/src/inventory.rs+++ b/games/voxels/src/main/rust/src/inventory.rs@@ -1,12 +1,12 @@ use serde::{Deserialize, Serialize};-use crate::world::block::Block;+use crate::world::block::{Block, Id}; pub const SLOTS: usize = 36; // 0..9 = hotbar, 9..36 = main inventory pub const HOTBAR: usize = 9; pub const STACK: i32 = 64; #[derive(Debug, Clone, Copy, Serialize, Deserialize)]-pub struct InvSlot { pub id: u8, pub count: i32 }+pub struct InvSlot { pub id: Id, pub count: i32 } impl Default for InvSlot { fn default() -> Self { Self { id: 0, count: 0 } } } #[derive(Debug, Clone, Serialize, Deserialize)]@@ -24,32 +24,32 @@ pub struct Inventory { // (in1_id, in1_count, in2_id, in2_count, out_id, out_count). in2_id == 0 means a single ingredient. // Item ids 154+ are materials/tools (see item.rs). Ore -> material conversions live in SMELTING // instead, since those need a furnace, fuel and time.-pub const RECIPES: [(u8, i32, u8, i32, u8, i32); 96] = [+pub const RECIPES: [(Id, i32, Id, i32, Id, i32); 96] = [ (154, 1, 157, 1, 186, 1), // iron + coal -> flint & steel (154, 2, 0, 0, 252, 1), // iron -> shears (159, 3, 137, 2, 253, 1), // sticks + leather -> fishing rod (159, 1, 236, 1, 255, 1), // stick + copper -> archaeologist's brush (251, 3, 0, 0, 131, 1), // wheat -> bread- (Block::HayBlock as u8, 1, 0, 0, 250, 4), // hay bale -> wheat seeds- (187, 1, Block::Glass as u8, 5, Block::Beacon as u8, 1), // nether star + glass -> beacon+ (Block::HayBlock as Id, 1, 0, 0, 250, 4), // hay bale -> wheat seeds+ (187, 1, Block::Glass as Id, 5, Block::Beacon as Id, 1), // nether star + glass -> beacon (138, 2, 0, 0, 189, 3), // gunpowder -> firework rockets- (Block::Snow as u8, 1, 0, 0, 190, 4), // snow -> snowballs- (Block::Wood as u8, 1, 0, 0, Block::Planks as u8, 4),- (Block::BirchLog as u8, 1, 0, 0, Block::BirchPlanks as u8, 4),- (Block::SpruceLog as u8, 1, 0, 0, Block::SprucePlanks as u8,4),- (Block::Planks as u8, 4, 0, 0, Block::CraftingTable as u8, 1),- (Block::Cobble as u8, 8, 0, 0, Block::Furnace as u8, 1),- (Block::Diorite as u8, 4, 0, 0, Block::PolishedDiorite as u8, 4),- (Block::Planks as u8, 2, 0, 0, 159 /*Stick*/, 4),+ (Block::Snow as Id, 1, 0, 0, 190, 4), // snow -> snowballs+ (Block::Wood as Id, 1, 0, 0, Block::Planks as Id, 4),+ (Block::BirchLog as Id, 1, 0, 0, Block::BirchPlanks as Id, 4),+ (Block::SpruceLog as Id, 1, 0, 0, Block::SprucePlanks as Id,4),+ (Block::Planks as Id, 4, 0, 0, Block::CraftingTable as Id, 1),+ (Block::Cobble as Id, 8, 0, 0, Block::Furnace as Id, 1),+ (Block::Diorite as Id, 4, 0, 0, Block::PolishedDiorite as Id, 4),+ (Block::Planks as Id, 2, 0, 0, 159 /*Stick*/, 4), // Material -> block.- (154, 9, 0, 0, Block::IronBlock as u8, 1),- (155, 9, 0, 0, Block::DiamondBlock as u8, 1),- (156, 9, 0, 0, Block::EmeraldBlock as u8, 1),+ (154, 9, 0, 0, Block::IronBlock as Id, 1),+ (155, 9, 0, 0, Block::DiamondBlock as Id, 1),+ (156, 9, 0, 0, Block::EmeraldBlock as Id, 1), // Tools: material + stick(159).- (Block::Planks as u8, 3, 159, 2, 163, 1), // wood pickaxe- (Block::Planks as u8, 2, 159, 1, 164, 1), // wood sword- (Block::Cobble as u8, 3, 159, 2, 165, 1), // stone pickaxe- (Block::Cobble as u8, 2, 159, 1, 166, 1), // stone sword+ (Block::Planks as Id, 3, 159, 2, 163, 1), // wood pickaxe+ (Block::Planks as Id, 2, 159, 1, 164, 1), // wood sword+ (Block::Cobble as Id, 3, 159, 2, 165, 1), // stone pickaxe+ (Block::Cobble as Id, 2, 159, 1, 166, 1), // stone sword (154, 3, 159, 2, 167, 1), // iron pickaxe (154, 2, 159, 1, 168, 1), // iron sword (155, 3, 159, 2, 169, 1), // diamond pickaxe@@ -63,11 +63,11 @@ pub const RECIPES: [(u8, i32, u8, i32, u8, i32); 96] = [ (196, 2, 159, 1, 198, 1), // adamant sword (196, 5, 0, 0, 199, 1), (196, 8, 0, 0, 200, 1), (196, 7, 0, 0, 201, 1), (196, 4, 0, 0, 202, 1), // Metal storage blocks (silver/steel/adamant also power beacons).- (193, 9, 0, 0, Block::SilverBlock as u8, 1),- (195, 9, 0, 0, Block::SteelBlock as u8, 1),- (196, 9, 0, 0, Block::AdamantBlock as u8, 1),+ (193, 9, 0, 0, Block::SilverBlock as Id, 1),+ (195, 9, 0, 0, Block::SteelBlock as Id, 1),+ (196, 9, 0, 0, Block::AdamantBlock as Id, 1), // A steel-lined furnace: the only place the alloy recipes will smelt.- (Block::Furnace as u8, 1, 195, 5, Block::BlastFurnace as u8, 1),+ (Block::Furnace as Id, 1, 195, 5, Block::BlastFurnace as Id, 1), // Blessings: quicksilver charms bound to a thematic offering. Attuning one grants a permanent // passive (see blessing.rs), so the ingredient cost tracks roughly how strong the passive is. (194, 2, 193, 1, 160, 1), // silver -> Clement, swift of foot@@ -76,28 +76,28 @@ pub const RECIPES: [(u8, i32, u8, i32, u8, i32); 96] = [ (194, 2, 195, 3, 203, 1), // steel -> Daedalus, tools never wear (194, 2, 189, 4, 204, 1), // fireworks -> Icarus, no fall damage (194, 2, 192, 6, 205, 1), // sulfur -> Yama, immune to fire- (194, 2, Block::Obsidian as u8, 4, 206, 1), // Talos, crushing blows+ (194, 2, Block::Obsidian as Id, 4, 206, 1), // Talos, crushing blows (194, 2, 187, 1, 207, 1), // nether star -> the God King, smite the undead (194, 2, 138, 8, 208, 1), // gunpowder -> Arachnae, bane of horrors (194, 2, 196, 2, 209, 1), // adamant -> Prometheus, armor never wears (194, 2, 155, 3, 210, 1), // diamond -> Lu Ban, mending- (194, 2, Block::EmeraldBlock as u8, 1, 211, 1), // Eros, fortune+ (194, 2, Block::EmeraldBlock as Id, 1, 211, 1), // Eros, fortune (194, 2, 191, 3, 212, 1), // ender pearls -> Will, reach- (194, 2, Block::Glowstone as u8, 4, 213, 1), // Hyacinthus, second jump- (194, 2, Block::Purpur as u8, 6, 214, 1), // Aeolus, wind burst- (194, 2, Block::Sculk as u8, 8, 215, 1), // Cronus, swift sneak- (194, 2, Block::BlueIce as u8, 4, 216, 1), // Demeter, frost walker- (194, 2, Block::SeaLantern as u8, 4, 217, 1), // Glaucus, sea luck- (194, 2, Block::Amethyst as u8, 6, 218, 1), // Apollo, marksman+ (194, 2, Block::Glowstone as Id, 4, 213, 1), // Hyacinthus, second jump+ (194, 2, Block::Purpur as Id, 6, 214, 1), // Aeolus, wind burst+ (194, 2, Block::Sculk as Id, 8, 215, 1), // Cronus, swift sneak+ (194, 2, Block::BlueIce as Id, 4, 216, 1), // Demeter, frost walker+ (194, 2, Block::SeaLantern as Id, 4, 217, 1), // Glaucus, sea luck+ (194, 2, Block::Amethyst as Id, 6, 218, 1), // Apollo, marksman (194, 2, 190, 16, 219, 1), // snowballs -> Artemis, multishot- (194, 2, Block::WardingStone as u8, 2, 220, 1), // Warding, thorns- (194, 2, Block::DiamondBlock as u8, 1, 221, 1), // Paris, infinity+ (194, 2, Block::WardingStone as Id, 2, 220, 1), // Warding, thorns+ (194, 2, Block::DiamondBlock as Id, 1, 221, 1), // Paris, infinity // The five late additions cost the alloy tier, so they arrive after the Blast Furnace does.- (194, 2, Block::IronBlock as u8, 2, 245, 1), // Athena, absorption shield- (194, 2, Block::Magma as u8, 4, 246, 1), // Sekhmet, bloodrage+ (194, 2, Block::IronBlock as Id, 2, 245, 1), // Athena, absorption shield+ (194, 2, Block::Magma as Id, 4, 246, 1), // Sekhmet, bloodrage (194, 2, 222, 12, 247, 1), // raw meat -> Camazotz, lifesteal- (194, 2, Block::Prismarine as u8, 8, 248, 1), // Tangaroa, conduit- (194, 2, Block::Sculk as u8, 4, 249, 1), // Anubis, ward undead+ (194, 2, Block::Prismarine as Id, 8, 248, 1), // Tangaroa, conduit+ (194, 2, Block::Sculk as Id, 4, 249, 1), // Anubis, ward undead // --- Matcha's kitchen. Cooked meat is the base ingredient; everything else builds on it. --- (223, 1, 131, 1, 224, 1), // cooked meat + bread -> ramen (223, 2, 135, 2, 225, 1), // cooked meat + carrot -> japanese curry@@ -109,60 +109,60 @@ pub const RECIPES: [(u8, i32, u8, i32, u8, i32); 96] = [ (131, 1, 130, 2, 231, 1), // bread + apple -> bruschetta (131, 1, 149, 1, 232, 1), // bread + fried egg -> french toast (131, 1, 152, 1, 233, 1), // bread + glow berry crumble -> sweet berry danish- (136, 2, Block::Snow as u8, 2, 234, 1), // melon + snow -> melon sorbet+ (136, 2, Block::Snow as Id, 2, 234, 1), // melon + snow -> melon sorbet (223, 3, 131, 1, 235, 1), // cooked meat + bread -> stroganoff (130, 2, 131, 1, 151, 1), // apple + bread -> apple empanada- (130, 1, Block::Glowstone as u8, 1, 152, 1), // apple + glowstone -> glow berry crumble+ (130, 1, Block::Glowstone as Id, 1, 152, 1), // apple + glowstone -> glow berry crumble // --- Bronze: Matcha alloys copper with gold, landing between iron and diamond. --- // 236 copper ingot, 237 gold ingot, 238 bronze ingot. (238, 3, 159, 2, 239, 1), // bronze pickaxe (238, 2, 159, 1, 240, 1), // bronze sword (238, 5, 0, 0, 241, 1), (238, 8, 0, 0, 242, 1), (238, 7, 0, 0, 243, 1), (238, 4, 0, 0, 244, 1),- (236, 9, 0, 0, Block::CopperBlock as u8, 1),- (237, 9, 0, 0, Block::GoldBlock as u8, 1),- (238, 9, 0, 0, Block::BronzeBlock as u8, 1),+ (236, 9, 0, 0, Block::CopperBlock as Id, 1),+ (237, 9, 0, 0, Block::GoldBlock as Id, 1),+ (238, 9, 0, 0, Block::BronzeBlock as Id, 1), // The stonecutter itself: an iron blade on a stone bed.- (Block::Stone as u8, 3, 154, 1, Block::Stonecutter as u8, 1),+ (Block::Stone as Id, 3, 154, 1, Block::Stonecutter as Id, 1), ]; // Furnace recipes. Unlike crafting these cost fuel and take `secs` of real time, and the ones marked // `blast` only run in a Blast Furnace — that gate is what makes the steel/adamant line an unlock // rather than just another recipe. pub struct Smelt {- pub in1: u8, pub n1: i32,- pub in2: u8, pub n2: i32,- pub out: u8, pub out_n: i32,+ pub in1: Id, pub n1: i32,+ pub in2: Id, pub n2: i32,+ pub out: Id, pub out_n: i32, pub secs: f32, pub blast: bool, }-const fn smelt(in1: u8, n1: i32, in2: u8, n2: i32, out: u8, out_n: i32, secs: f32, blast: bool) -> Smelt {+const fn smelt(in1: Id, n1: i32, in2: Id, n2: i32, out: Id, out_n: i32, secs: f32, blast: bool) -> Smelt { Smelt { in1, n1, in2, n2, out, out_n, secs, blast } } pub const SMELTING: [Smelt; 19] = [ smelt(254, 1, 0, 0, 132, 1, 6.0, false), // raw fish -> cooked fish- smelt(Block::CoalOre as u8, 1, 0, 0, 157, 1, 6.0, false), // coal- smelt(Block::IronOre as u8, 1, 0, 0, 154, 1, 8.0, false), // iron ingot- smelt(Block::DiamondOre as u8, 1, 0, 0, 155, 1, 10.0, false),- smelt(Block::EmeraldOre as u8, 1, 0, 0, 156, 1, 10.0, false),- smelt(Block::RedstoneOre as u8, 1, 0, 0, 158, 1, 6.0, false),- smelt(Block::SilverOre as u8, 1, 0, 0, 193, 1, 9.0, false), // silver ingot- smelt(Block::Sand as u8, 2, 0, 0, Block::Glass as u8, 1, 5.0, false),- smelt(Block::Cobble as u8, 4, 0, 0, Block::Stone as u8, 1, 5.0, false),- smelt(Block::Clay as u8, 4, 0, 0, Block::Brick as u8, 1, 6.0, false),+ smelt(Block::CoalOre as Id, 1, 0, 0, 157, 1, 6.0, false), // coal+ smelt(Block::IronOre as Id, 1, 0, 0, 154, 1, 8.0, false), // iron ingot+ smelt(Block::DiamondOre as Id, 1, 0, 0, 155, 1, 10.0, false),+ smelt(Block::EmeraldOre as Id, 1, 0, 0, 156, 1, 10.0, false),+ smelt(Block::RedstoneOre as Id, 1, 0, 0, 158, 1, 6.0, false),+ smelt(Block::SilverOre as Id, 1, 0, 0, 193, 1, 9.0, false), // silver ingot+ smelt(Block::Sand as Id, 2, 0, 0, Block::Glass as Id, 1, 5.0, false),+ smelt(Block::Cobble as Id, 4, 0, 0, Block::Stone as Id, 1, 5.0, false),+ smelt(Block::Clay as Id, 4, 0, 0, Block::Brick as Id, 1, 6.0, false), smelt(222, 1, 0, 0, 223, 1, 6.0, false), // raw meat -> cooked meat smelt(131, 1, 0, 0, 147, 3, 5.0, false), // bread -> cookies (baking)- smelt(Block::CopperOre as u8, 1, 0, 0, 236, 1, 6.0, false), // copper ingot- smelt(Block::GoldOre as u8, 1, 0, 0, 237, 1, 8.0, false), // gold ingot+ smelt(Block::CopperOre as Id, 1, 0, 0, 236, 1, 6.0, false), // copper ingot+ smelt(Block::GoldOre as Id, 1, 0, 0, 237, 1, 8.0, false), // gold ingot smelt(236, 6, 237, 1, 238, 1, 14.0, true), // copper + gold -> bronze // Blast furnace only: the alloy line.- smelt(Block::SulfurOre as u8, 1, 0, 0, 192, 2, 5.0, true), // sulfur- smelt(Block::CinnabarOre as u8, 1, 0, 0, 194, 1, 7.0, true), // quicksilver+ smelt(Block::SulfurOre as Id, 1, 0, 0, 192, 2, 5.0, true), // sulfur+ smelt(Block::CinnabarOre as Id, 1, 0, 0, 194, 1, 7.0, true), // quicksilver smelt(154, 1, 192, 1, 195, 1, 12.0, true), // iron + sulfur -> steel smelt(195, 4, 194, 2, 196, 1, 20.0, true), // steel + quicksilver -> adamant ]; // Seconds of furnace burn a stack item is worth. Anything not listed can't be used as fuel.-pub fn fuel_secs(id: u8) -> f32 {+pub fn fuel_secs(id: Id) -> f32 { match id { 157 => 80.0, // coal 84 => 200.0, // a lava block@@ -174,13 +174,13 @@ pub fn fuel_secs(id: u8) -> f32 { } } // Fuels with no use other than burning, tried before anything a player might be saving.-const DEDICATED_FUELS: [u8; 3] = [157, 84, 192];+const DEDICATED_FUELS: [Id; 3] = [157, 84, 192]; // Villager trades live in `villager.rs`, tiered per profession. Emerald = item 156. // Which shelf of the crafting menu a recipe belongs on. Purely for the UI — the recipe table itself // stays a flat list so indices remain stable.-pub fn recipe_category(out: u8) -> &'static str {+pub fn recipe_category(out: Id) -> &'static str { if crate::blessing::is_blessing(out) { return "blessing"; } if crate::item::food_effects(out).is_some() { return "food"; } if crate::item::is_tool(out) { return "tool"; }@@ -192,7 +192,7 @@ pub fn recipe_category(out: u8) -> &'static str { // The stonecutter: one block in, one shape out, no fuel and no waiting. This is Matcha's stonecutting // book condensed — the pack's hundreds of recipes are almost all "material -> slab/stairs/variant", // which is exactly what `cut_variants` enumerates.-pub struct Cut { pub input: u8, pub output: u8, pub count: i32 }+pub struct Cut { pub input: Id, pub output: Id, pub count: i32 } /// Every stonecutter conversion, derived from the block table so a new slab family is picked up for /// free. A cube yields two slabs or one stair, and either shape converts back to the other.@@ -200,7 +200,7 @@ pub fn cut_variants() -> Vec<Cut> { let mut out = Vec::new(); for material in CUTTABLE { let (Some(slab), Some(stairs)) = (material.slab_of(), material.stairs_of()) else { continue; };- let (m, s, st) = (material as u8, slab as u8, stairs as u8);+ let (m, s, st) = (material as Id, slab as Id, stairs as Id); out.push(Cut { input: m, output: s, count: 2 }); out.push(Cut { input: m, output: st, count: 1 }); out.push(Cut { input: s, output: st, count: 1 });@@ -208,7 +208,7 @@ pub fn cut_variants() -> Vec<Cut> { } // Decorative conversions between whole blocks of the same family. for &(input, output) in DECOR_CUTS {- out.push(Cut { input: input as u8, output: output as u8, count: 1 });+ out.push(Cut { input: input as Id, output: output as Id, count: 1 }); } out }@@ -237,16 +237,16 @@ impl Default for Inventory { (Block::Grass, 64), (Block::Dirt, 64), (Block::Stone, 64), (Block::Wood, 16), (Block::Planks, 32), (Block::Sand, 32), (Block::Glass, 16), (Block::Cobble, 16), (Block::Brick, 16), ];- for (i, (b, c)) in start.iter().enumerate() { slots[i] = InvSlot { id: *b as u8, count: *c }; }+ for (i, (b, c)) in start.iter().enumerate() { slots[i] = InvSlot { id: *b as Id, count: *c }; } Self { selected: 0, slots, placed: 0, broken: 0, armor: [InvSlot::default(); 4] } } } impl Inventory {- pub fn selected_block(&self) -> u8 {+ pub fn selected_block(&self) -> Id { if self.selected < HOTBAR { let s = &self.slots[self.selected]; if s.count > 0 { s.id } else { 0 } } else { 0 } }- pub fn consume_selected(&mut self) -> Option<u8> {+ pub fn consume_selected(&mut self) -> Option<Id> { if self.selected >= HOTBAR { return None; } let slot = &mut self.slots[self.selected]; if slot.count <= 0 || slot.id == 0 { return None; }@@ -256,9 +256,9 @@ impl Inventory { self.placed += 1; Some(id) }- pub fn add_block(&mut self, id: u8) { self.try_add_block(id); }+ pub fn add_block(&mut self, id: Id) { self.try_add_block(id); } // Add one unit, reporting whether it actually fit anywhere.- pub fn try_add_block(&mut self, id: u8) -> bool {+ pub fn try_add_block(&mut self, id: Id) -> bool { if id == 0 { return false; } for slot in self.slots.iter_mut() { if slot.id == id && slot.count < STACK { slot.count += 1; return true; } } for slot in self.slots.iter_mut() { if slot.id == 0 { slot.id = id; slot.count = 1; return true; } }@@ -286,14 +286,14 @@ impl Inventory { } // Creative catalog: put a full stack of `id` into the first empty (or matching) slot.- pub fn give(&mut self, id: u8) {+ pub fn give(&mut self, id: Id) { if id == 0 { return; } for slot in self.slots.iter_mut() { if slot.id == 0 { slot.id = id; slot.count = STACK; return; } } for slot in self.slots.iter_mut() { if slot.id == id { slot.count = STACK; return; } } } - pub fn count_of(&self, id: u8) -> i32 { self.slots.iter().filter(|s| s.id == id).map(|s| s.count).sum() }- fn remove_count(&mut self, id: u8, mut n: i32) {+ pub fn count_of(&self, id: Id) -> i32 { self.slots.iter().filter(|s| s.id == id).map(|s| s.count).sum() }+ fn remove_count(&mut self, id: Id, mut n: i32) { for slot in self.slots.iter_mut() { if slot.id == id && n > 0 { let take = slot.count.min(n);@@ -313,13 +313,13 @@ impl Inventory { true } // Place a non-stacking item (tool/armor) into the first empty slot with a given count (durability).- pub fn add_item_with_count(&mut self, id: u8, count: i32) -> bool {+ pub fn add_item_with_count(&mut self, id: Id, count: i32) -> bool { for slot in self.slots.iter_mut() { if slot.id == 0 { slot.id = id; slot.count = count; return true; } } false } pub fn selected_count(&self) -> i32 { if self.selected < HOTBAR { self.slots[self.selected].count } else { 0 } } // Remove the whole selected stack, returning (id, count). Used to equip armor without losing durability.- pub fn take_selected(&mut self) -> Option<(u8, i32)> {+ pub fn take_selected(&mut self) -> Option<(Id, i32)> { if self.selected >= HOTBAR { return None; } let s = self.slots[self.selected]; if s.id == 0 { return None; }@@ -333,7 +333,7 @@ impl Inventory { if s.id != 0 && crate::item::has_durability(s.id) { s.count -= 1; if s.count <= 0 { *s = InvSlot::default(); } } } // Equip an armor item (with its durability) into its slot; returns any displaced piece.- pub fn equip_armor(&mut self, id: u8, dur: i32) -> Option<InvSlot> {+ pub fn equip_armor(&mut self, id: Id, dur: i32) -> Option<InvSlot> { let slot = crate::item::armor_slot(id); let old = self.armor[slot]; self.armor[slot] = InvSlot { id, count: dur };@@ -379,7 +379,7 @@ impl Inventory { } // Whether `n` of `id` would actually fit. Used to pause a furnace rather than smelt into a full // inventory and drop the result on the floor.- pub fn has_room_for(&self, id: u8, n: i32) -> bool {+ pub fn has_room_for(&self, id: Id, n: i32) -> bool { if crate::item::has_durability(id) { return self.slots.iter().any(|s| s.id == 0); } let mut need = n; for s in self.slots.iter() {@@ -392,7 +392,7 @@ impl Inventory { // active recipe needs as ingredients so the furnace never eats its own input (sulfur is both a // fuel and the second half of the steel recipe). Dedicated fuels are preferred over logs and // planks so a smelt doesn't quietly consume the player's building stock.- pub fn consume_fuel(&mut self, spare: &[u8]) -> Option<f32> {+ pub fn consume_fuel(&mut self, spare: &[Id]) -> Option<f32> { let usable = |s: &InvSlot| s.count > 0 && fuel_secs(s.id) > 0.0 && !spare.contains(&s.id); let idx = self.slots.iter().position(|s| usable(s) && DEDICATED_FUELS.contains(&s.id)) .or_else(|| self.slots.iter().position(usable))?;@@ -467,6 +467,30 @@ mod tests { } } + // Widening the id space means a stray number in a table no longer lands on a block by+ // accident — it lands on nothing at all. Every id in every table has to name something real.+ #[test]+ fn every_id_in_the_tables_names_something_real() {+ use crate::world::block::is_real_id;+ for (i, &(in1, _, in2, _, out, _)) in RECIPES.iter().enumerate() {+ assert!(is_real_id(in1), "recipe {i} takes {in1}, which is nothing");+ assert!(in2 == 0 || is_real_id(in2), "recipe {i} takes {in2}, which is nothing");+ assert!(is_real_id(out), "recipe {i} yields {out}, which is nothing");+ }+ for (i, s) in SMELTING.iter().enumerate() {+ assert!(is_real_id(s.in1), "smelt {i} takes {}, which is nothing", s.in1);+ assert!(s.in2 == 0 || is_real_id(s.in2), "smelt {i} takes {}, which is nothing", s.in2);+ assert!(is_real_id(s.out), "smelt {i} yields {}, which is nothing", s.out);+ }+ for c in cut_variants() {+ assert!(is_real_id(c.input) && is_real_id(c.output), "a cut moves an id that is nothing");+ }+ for b in crate::blessing::PANTHEON.iter() {+ assert!(is_real_id(b.id), "{} has an id that is nothing", b.name);+ }+ for id in DEDICATED_FUELS { assert!(is_real_id(id), "fuel {id} is nothing"); }+ }+ #[test] fn recipe_tables_are_well_formed() { for (i, &(in1, n1, in2, n2, out, out_n)) in RECIPES.iter().enumerate() {@@ -577,10 +601,10 @@ mod tests { fn the_stonecutter_reaches_every_shape() { let cuts = cut_variants(); for m in CUTTABLE {- let slab = m.slab_of().unwrap() as u8;- let stairs = m.stairs_of().unwrap() as u8;- assert!(cuts.iter().any(|c| c.input == m as u8 && c.output == slab), "{m:?} -> slab missing");- assert!(cuts.iter().any(|c| c.input == m as u8 && c.output == stairs), "{m:?} -> stairs missing");+ let slab = m.slab_of().unwrap() as Id;+ let stairs = m.stairs_of().unwrap() as Id;+ assert!(cuts.iter().any(|c| c.input == m as Id && c.output == slab), "{m:?} -> slab missing");+ assert!(cuts.iter().any(|c| c.input == m as Id && c.output == stairs), "{m:?} -> stairs missing"); assert!(cuts.iter().any(|c| c.input == slab && c.output == stairs), "slab -> stairs missing"); assert!(cuts.iter().any(|c| c.input == stairs && c.output == slab), "stairs -> slab missing"); }@@ -594,32 +618,32 @@ mod tests { #[test] fn cutting_consumes_one_block_and_yields_the_shape() { let cuts = cut_variants();- let idx = cuts.iter().position(|c| c.input == Block::Stone as u8 && c.output == Block::StoneSlab as u8).unwrap();+ let idx = cuts.iter().position(|c| c.input == Block::Stone as Id && c.output == Block::StoneSlab as Id).unwrap(); let mut inv = Inventory::default(); for s in inv.slots.iter_mut() { *s = InvSlot::default(); }- inv.slots[0] = InvSlot { id: Block::Stone as u8, count: 3 };+ inv.slots[0] = InvSlot { id: Block::Stone as Id, count: 3 }; assert!(inv.cut(idx));- assert_eq!(inv.count_of(Block::Stone as u8), 2, "one stone consumed");- assert_eq!(inv.count_of(Block::StoneSlab as u8), 2, "a stone block yields two slabs");+ assert_eq!(inv.count_of(Block::Stone as Id), 2, "one stone consumed");+ assert_eq!(inv.count_of(Block::StoneSlab as Id), 2, "a stone block yields two slabs"); // With no input left the cut must refuse rather than conjure slabs.- inv.remove_count(Block::Stone as u8, 99);+ inv.remove_count(Block::Stone as Id, 99); assert!(!inv.cut(idx));- assert_eq!(inv.count_of(Block::StoneSlab as u8), 2);+ assert_eq!(inv.count_of(Block::StoneSlab as Id), 2); } // A full inventory must not let the stonecutter eat the input and drop the result. #[test] fn cutting_into_a_full_inventory_is_refused() { let cuts = cut_variants();- let idx = cuts.iter().position(|c| c.input == Block::Stone as u8 && c.output == Block::StoneSlab as u8).unwrap();+ let idx = cuts.iter().position(|c| c.input == Block::Stone as Id && c.output == Block::StoneSlab as Id).unwrap(); let mut inv = Inventory::default();- for s in inv.slots.iter_mut() { *s = InvSlot { id: Block::Dirt as u8, count: STACK }; }- inv.slots[0] = InvSlot { id: Block::Stone as u8, count: STACK };+ for s in inv.slots.iter_mut() { *s = InvSlot { id: Block::Dirt as Id, count: STACK }; }+ inv.slots[0] = InvSlot { id: Block::Stone as Id, count: STACK }; assert!(!inv.cut(idx), "nowhere to put the slabs");- assert_eq!(inv.count_of(Block::Stone as u8), STACK, "the input must survive a refused cut");+ assert_eq!(inv.count_of(Block::Stone as Id), STACK, "the input must survive a refused cut"); } #[test]@@ -654,9 +678,9 @@ mod tests { #[test] fn trading_into_a_full_inventory_is_refused() { use crate::villager::{Offer, EMERALD};- let bulk = Offer { cost: EMERALD, cost_n: 1, cost2: 0, cost2_n: 0, give: Block::Stone as u8, give_n: 8 };+ let bulk = Offer { cost: EMERALD, cost_n: 1, cost2: 0, cost2_n: 0, give: Block::Stone as Id, give_n: 8 }; let mut inv = Inventory::default();- for s in inv.slots.iter_mut() { *s = InvSlot { id: Block::Dirt as u8, count: STACK }; }+ for s in inv.slots.iter_mut() { *s = InvSlot { id: Block::Dirt as Id, count: STACK }; } inv.slots[0] = InvSlot { id: EMERALD, count: 4 }; assert!(!inv.trade_offer(&bulk), "nowhere to put the stone");
games/voxels/src/main/rust/src/item.rs
diff --git a/games/voxels/src/main/rust/src/item.rs b/games/voxels/src/main/rust/src/item.rsindex 9f2d20f30a..22d6994009 100644--- a/games/voxels/src/main/rust/src/item.rs+++ b/games/voxels/src/main/rust/src/item.rs@@ -1,5 +1,6 @@ // Non-block inventory items (food, consumables, materials) and the status-effect model.-// Inventory ids < ITEM_BASE are blocks; ids >= ITEM_BASE are items and are never placeable.+// Inventory ids outside ITEM_BASE..=ITEM_MAX are blocks; ids inside it are items and are never+// placeable. // Design follows the Matcha/Raspberry survival overhaul: no hunger — food applies Regeneration // (the heal) plus a themed buff; Estus is a fast multi-charge heal; Heart Containers raise max HP. @@ -27,42 +28,47 @@ impl Effect { #[derive(Clone, Copy)] pub struct ActiveEffect { pub kind: Effect, pub secs: f32, pub amp: u8 } -pub const ITEM_BASE: u8 = 128;+use crate::world::block::Id;++pub const ITEM_BASE: Id = 128;+/// The item window's upper bound. Blocks resume at `BLOCK_HIGH_BASE` one past it, so the numbers+/// already written into saves keep their meaning and both kinds have room to grow.+pub const ITEM_MAX: Id = 1023; // Matcha alloy line: 192 Sulfur, 193 Silver Ingot, 194 Quicksilver, 195 Steel Ingot, // 196 Adamant Ingot, 197/198 adamant pickaxe/sword, 199..202 adamant armor.-pub fn is_item(id: u8) -> bool { id >= ITEM_BASE }-pub fn is_estus(id: u8) -> bool { id == 128 }-pub fn is_heart_container(id: u8) -> bool { id == 129 }-pub fn is_food(id: u8) -> bool { food_effects(id).is_some() }+pub fn is_item(id: Id) -> bool { (ITEM_BASE..=ITEM_MAX).contains(&id) }+pub fn is_estus(id: Id) -> bool { id == 128 }+pub fn is_heart_container(id: Id) -> bool { id == 129 }+pub fn is_food(id: Id) -> bool { food_effects(id).is_some() } // ---- Tools & armor ---- // Tools 163..170: {wood,stone,iron,diamond} x {pickaxe,sword}. Armor 171..178: {iron,diamond} x // {helmet,chestplate,leggings,boots}. Matcha's bronze sits between iron and diamond at 239..244, // and adamant tops the ladder at 197..202. Durability is stored in the inventory slot's `count`.-pub fn is_tool(id: u8) -> bool { (163..=170).contains(&id) || matches!(id, 197 | 198 | 239 | 240 | 252 | 253 | 255) }+pub fn is_tool(id: Id) -> bool { (163..=170).contains(&id) || matches!(id, 197 | 198 | 239 | 240 | 252 | 253 | 255) } /// Item 255. Brushing suspicious sand is the only thing it does.-pub const BRUSH: u8 = 255;+pub const BRUSH: Id = 255; /// Shears: used on a sheep rather than on terrain, so they're a tool that mines nothing.-pub fn is_shears(id: u8) -> bool { id == 252 }-pub fn is_pickaxe(id: u8) -> bool { matches!(id, 163 | 165 | 167 | 169 | 197 | 239) }-pub fn is_sword(id: u8) -> bool { matches!(id, 164 | 166 | 168 | 170 | 198 | 240) }-pub fn is_elytra(id: u8) -> bool { id == 188 }-pub fn is_armor(id: u8) -> bool {+pub fn is_shears(id: Id) -> bool { id == 252 }+pub fn is_pickaxe(id: Id) -> bool { matches!(id, 163 | 165 | 167 | 169 | 197 | 239) }+pub fn is_sword(id: Id) -> bool { matches!(id, 164 | 166 | 168 | 170 | 198 | 240) }+pub fn is_elytra(id: Id) -> bool { id == 188 }+pub fn is_armor(id: Id) -> bool { (171..=178).contains(&id) || (199..=202).contains(&id) || (241..=244).contains(&id) || id == 188 } // elytra occupies the chest slot-pub fn armor_slot(id: u8) -> usize {+pub fn armor_slot(id: Id) -> usize { if id == 188 { 1 } else if id >= 241 { (id - 241) as usize } else if id >= 199 { (id - 199) as usize } else { ((id - 171) % 4) as usize } } // 0 helm, 1 chest, 2 legs, 3 boots-pub fn is_flint_steel(id: u8) -> bool { id == 186 }-pub fn is_firework(id: u8) -> bool { id == 189 }-pub fn has_durability(id: u8) -> bool { is_tool(id) || is_armor(id) || id == 186 }+pub fn is_flint_steel(id: Id) -> bool { id == 186 }+pub fn is_firework(id: Id) -> bool { id == 189 }+pub fn has_durability(id: Id) -> bool { is_tool(id) || is_armor(id) || id == 186 } -pub fn sword_damage(id: u8) -> f32 { match id { 164 => 5.0, 166 => 6.0, 168 => 7.0, 240 => 8.0, 170 => 9.0, 198 => 11.0, _ => 0.0 } }-pub fn pick_damage(id: u8) -> f32 { match id { 163 => 2.0, 165 => 3.0, 167 => 4.0, 239 => 4.5, 169 => 5.0, 197 => 6.0, _ => 0.0 } }-pub fn armor_defense(id: u8) -> f32 {+pub fn sword_damage(id: Id) -> f32 { match id { 164 => 5.0, 166 => 6.0, 168 => 7.0, 240 => 8.0, 170 => 9.0, 198 => 11.0, _ => 0.0 } }+pub fn pick_damage(id: Id) -> f32 { match id { 163 => 2.0, 165 => 3.0, 167 => 4.0, 239 => 4.5, 169 => 5.0, 197 => 6.0, _ => 0.0 } }+pub fn armor_defense(id: Id) -> f32 { match id { 171 => 2.0, 172 => 6.0, 173 => 5.0, 174 => 2.0, // iron helm/chest/legs/boots 241 => 2.0, 242 => 7.0, 243 => 5.0, 244 => 3.0, // bronze@@ -72,7 +78,7 @@ pub fn armor_defense(id: u8) -> f32 { _ => 0.0, } }-pub fn max_durability(id: u8) -> i32 {+pub fn max_durability(id: Id) -> i32 { match id { 163 | 164 => 60, 165 | 166 => 132, 167 | 168 => 250, 169 | 170 => 1562, // wood/stone/iron/diamond tools 171..=174 => 240, 175..=178 => 528, // iron/diamond armor@@ -90,7 +96,7 @@ pub fn max_durability(id: u8) -> i32 { } // Effects applied when a food item is eaten. First entry is the healing Regeneration.-pub fn food_effects(id: u8) -> Option<&'static [(Effect, f32, u8)]> {+pub fn food_effects(id: Id) -> Option<&'static [(Effect, f32, u8)]> { use Effect::*; Some(match id { 130 => &[(Regeneration, 4.0, 0)], // apple@@ -132,19 +138,20 @@ pub fn food_effects(id: u8) -> Option<&'static [(Effect, f32, u8)]> { mod tests { use super::*; - // Blocks and items share one u8 id space split at ITEM_BASE. If a new block ever crosses that- // line it would silently become unplaceable, so pin the invariant down.+ // Blocks and items share one id space, split by range at ITEM_BASE..=ITEM_MAX. If a new block+ // ever crossed that line it would silently become unplaceable, so pin the invariant down. #[test] fn block_ids_stay_below_the_item_base() {- assert!(crate::world::block::MAX_BLOCK_ID < ITEM_BASE);- assert!(!is_item(crate::world::block::MAX_BLOCK_ID));+ assert!(crate::world::block::MAX_LOW_BLOCK_ID < ITEM_BASE);+ assert!(!is_item(crate::world::block::MAX_LOW_BLOCK_ID));+ assert!(!is_item(crate::world::block::BLOCK_HIGH_BASE), "the high block window is not items"); } // armor_slot() does range arithmetic over three disjoint id blocks; a wrong mapping would let // a helmet occupy the boots slot. #[test] fn armor_maps_to_the_right_slot() {- for (id, slot) in [(171u8, 0usize), (172, 1), (173, 2), (174, 3), // iron+ for (id, slot) in [(171 as Id, 0usize), (172, 1), (173, 2), (174, 3), // iron (175, 0), (176, 1), (177, 2), (178, 3), // diamond (199, 0), (200, 1), (201, 2), (202, 3), // adamant (188, 1)] { // elytra -> chest@@ -155,7 +162,9 @@ mod tests { #[test] fn tools_and_armor_do_not_overlap() {- for id in 0..=255u8 {+ // Every tool and every piece of armor lives in the legacy 0..=255 window; sweeping the+ // whole u16 range would cost 256x for nothing.+ for id in 0..=255 as Id { assert!(!(is_tool(id) && is_armor(id)), "{id} is both a tool and armor"); // Shears and the fishing rod are the exceptions: tools that neither mine nor fight. if is_tool(id) && !is_shears(id) && id != crate::fishing::ROD && id != BRUSH {@@ -173,7 +182,7 @@ mod tests { fn every_food_is_obtainable() { use crate::inventory::{RECIPES, SMELTING}; let mut missing = Vec::new();- for id in 0..=255u8 {+ for id in 0..=255 as Id { if food_effects(id).is_none() { continue; } let crafted = RECIPES.iter().any(|r| r.4 == id); let smelted = SMELTING.iter().any(|s| s.out == id);@@ -201,7 +210,7 @@ mod tests { fn adamant_outclasses_diamond() { assert!(sword_damage(198) > sword_damage(170)); assert!(pick_damage(197) > pick_damage(169));- for (adamant, diamond) in [(199u8, 175u8), (200, 176), (201, 177), (202, 178)] {+ for (adamant, diamond) in [(199 as Id, 175 as Id), (200, 176), (201, 177), (202, 178)] { assert!(armor_defense(adamant) > armor_defense(diamond), "{adamant} must beat {diamond}"); } assert!(max_durability(197) > max_durability(169));
games/voxels/src/main/rust/src/lib.rs
diff --git a/games/voxels/src/main/rust/src/lib.rs b/games/voxels/src/main/rust/src/lib.rsindex 1213ac6dc4..ce4a79d248 100644--- a/games/voxels/src/main/rust/src/lib.rs+++ b/games/voxels/src/main/rust/src/lib.rs@@ -205,7 +205,9 @@ pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_moveI pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_giveBlock<'l>( _env: JNIEnv<'l>, _class: JClass<'l>, id: jint, ) {- if id > 0 { engine::inventory_give(id as u8); }+ // The only id that crosses JNI as a number rather than as JSON. `as` would wrap a jint that+ // doesn't fit into a different, real block, so refuse it instead.+ if let Ok(id) = crate::world::block::Id::try_from(id) { if id > 0 { engine::inventory_give(id); } } } #[no_mangle]
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 ef2648127f..68eade681a 100644--- a/games/voxels/src/main/rust/src/player.rs+++ b/games/voxels/src/main/rust/src/player.rs@@ -356,8 +356,9 @@ impl Player { #[cfg(test)] mod tests { use super::*;+ use crate::world::block::Id; - fn blessed_player(ids: &[u8]) -> Player {+ fn blessed_player(ids: &[Id]) -> Player { let mut p = Player::new(0.0, 64.0, 0.0); for &id in ids { assert!(p.blessings.attune(id), "could not attune {id}"); } p@@ -429,7 +430,7 @@ mod tests { #[test] fn a_bottom_slab_only_fills_the_lower_half() { let mut w = world();- w.set_block_meta_world(0, SKY, 0, Block::StoneSlab as u8, 0);+ w.set_block_meta_world(0, SKY, 0, Block::StoneSlab as Id, 0); let p = Player::new(0.5, 0.0, 0.5); assert!(!p.collides_at(vec3(0.5, SKY as f32 + 0.5, 0.5), &w), "resting on the slab's surface is clear");@@ -443,12 +444,12 @@ mod tests { let feet = vec3(0.5, SKY as f32 - 0.3, 0.5); // head lands exactly at the slab's underside let mut with_slab = world();- with_slab.set_block_meta_world(0, SKY + 1, 0, Block::StoneSlab as u8, crate::world::block::META_TOP);+ with_slab.set_block_meta_world(0, SKY + 1, 0, Block::StoneSlab as Id, crate::world::block::META_TOP); let p = Player::new(0.5, 0.0, 0.5); assert!(!p.collides_at(feet, &with_slab), "a top slab leaves its lower half open"); let mut with_cube = world();- with_cube.set_block_world(0, SKY + 1, 0, Block::Stone as u8);+ with_cube.set_block_world(0, SKY + 1, 0, Block::Stone as Id); assert!(p.collides_at(feet, &with_cube), "a full cube in the same cell would block"); } @@ -456,7 +457,7 @@ mod tests { #[test] fn stairs_are_open_over_their_low_half() { let mut w = world();- w.set_block_meta_world(0, SKY, 0, Block::StoneStairs as u8, crate::world::block::FACE_NORTH);+ w.set_block_meta_world(0, SKY, 0, Block::StoneStairs as Id, crate::world::block::FACE_NORTH); let p = Player::new(0.0, 0.0, 0.0); // The low half is -Z. The player is 0.6 wide, so their box has to sit well into it. assert!(!p.collides_at(vec3(0.5, SKY as f32 + 0.5, 0.2), &w), "standing on the tread is clear");@@ -474,7 +475,7 @@ mod tests { #[test] fn you_come_to_rest_on_a_slabs_surface() { let mut w = world();- w.set_block_meta_world(0, SKY, 0, Block::StoneSlab as u8, 0);+ w.set_block_meta_world(0, SKY, 0, Block::StoneSlab as Id, 0); let mut p = Player::new(0.5, SKY as f32 + 3.0, 0.5); let input = crate::input::InputState::default(); for _ in 0..120 { p.tick(1.0 / 60.0, &input, &w); }@@ -489,7 +490,7 @@ mod tests { #[test] fn a_full_block_still_holds_you_a_whole_block_up() { let mut w = world();- w.set_block_world(0, SKY, 0, Block::Stone as u8);+ w.set_block_world(0, SKY, 0, Block::Stone as Id); let mut p = Player::new(0.5, SKY as f32 + 3.0, 0.5); let input = crate::input::InputState::default(); for _ in 0..120 { p.tick(1.0 / 60.0, &input, &w); }@@ -498,7 +499,7 @@ mod tests { /// A long floor to walk along, so a test never runs off the end of the world. fn floor(w: &mut ChunkMap, from_z: i32, to_z: i32, cell_y: i32) {- for z in from_z..=to_z { w.set_block_world(0, cell_y, z, Block::Stone as u8); }+ for z in from_z..=to_z { w.set_block_world(0, cell_y, z, Block::Stone as Id); } } // Walking into a slab should climb it, and land on its surface rather than the step allowance.@@ -506,7 +507,7 @@ mod tests { fn you_walk_up_onto_a_slab() { let mut w = world(); floor(&mut w, -20, 1, SKY);- for z in -20..=-2 { w.set_block_meta_world(0, SKY + 1, z, Block::StoneSlab as u8, 0); }+ for z in -20..=-2 { w.set_block_meta_world(0, SKY + 1, z, Block::StoneSlab as Id, 0); } let mut p = Player::new(0.5, SKY as f32 + 1.0, 0.5); p.yaw = 0.0; // facing -Z@@ -528,12 +529,12 @@ mod tests { const STEPS: i32 = 6; for i in 0..STEPS { let z = -2 - i;- for c in 1..=i { w.set_block_world(0, SKY + c, z, Block::Stone as u8); }- w.set_block_meta_world(0, SKY + 1 + i, z, Block::StoneStairs as u8, FACE_SOUTH);+ for c in 1..=i { w.set_block_world(0, SKY + c, z, Block::Stone as Id); }+ w.set_block_meta_world(0, SKY + 1 + i, z, Block::StoneStairs as Id, FACE_SOUTH); } // A landing at the top so the climb has somewhere to finish. for z in -20..=-(2 + STEPS) {- for c in 1..=STEPS { w.set_block_world(0, SKY + c, z, Block::Stone as u8); }+ for c in 1..=STEPS { w.set_block_world(0, SKY + c, z, Block::Stone as Id); } } let mut p = Player::new(0.5, SKY as f32 + 1.0, 0.5);@@ -549,7 +550,7 @@ mod tests { fn a_full_block_still_blocks_you() { let mut w = world(); floor(&mut w, -20, 1, SKY);- w.set_block_world(0, SKY + 1, -2, Block::Stone as u8);+ w.set_block_world(0, SKY + 1, -2, Block::Stone as Id); let mut p = Player::new(0.5, SKY as f32 + 1.0, 0.5); p.yaw = 0.0;@@ -562,7 +563,7 @@ mod tests { #[test] fn sneaking_wont_walk_off_a_slab_ledge() { let mut w = world();- for z in -20..=1 { w.set_block_meta_world(0, SKY, z, Block::StoneSlab as u8, 0); }+ for z in -20..=1 { w.set_block_meta_world(0, SKY, z, Block::StoneSlab as Id, 0); } let p = Player::new(0.5, SKY as f32 + 0.5, 0.5); // Over the slab: supported.
games/voxels/src/main/rust/src/raycast.rs
diff --git a/games/voxels/src/main/rust/src/raycast.rs b/games/voxels/src/main/rust/src/raycast.rsindex 6ef2c35349..ae5f6e9c5c 100644--- a/games/voxels/src/main/rust/src/raycast.rs+++ b/games/voxels/src/main/rust/src/raycast.rs@@ -128,6 +128,7 @@ pub fn raycast(chunks: &ChunkMap, origin: Vec3, dir: Vec3, max_dist: f32) -> Opt #[cfg(test)] mod tests { use super::*;+ use crate::world::block::Id; use crate::world::block::{Block, FACE_NORTH, META_TOP}; use glam::vec3; @@ -143,7 +144,7 @@ mod tests { #[test] fn a_ray_passes_through_a_slabs_empty_half() { let mut w = world();- w.set_block_meta_world(4, SKY, 0, Block::StoneSlab as u8, 0);+ w.set_block_meta_world(4, SKY, 0, Block::StoneSlab as Id, 0); // Aim along +X at 0.75 up the cell, above the slab's solid half. let high = raycast(&w, vec3(0.0, SKY as f32 + 0.75, 0.5), vec3(1.0, 0.0, 0.0), 20.0);@@ -160,7 +161,7 @@ mod tests { #[test] fn looking_down_hits_the_slabs_top_surface() { let mut w = world();- w.set_block_meta_world(0, SKY, 0, Block::StoneSlab as u8, 0);+ w.set_block_meta_world(0, SKY, 0, Block::StoneSlab as Id, 0); let hit = raycast(&w, vec3(0.5, SKY as f32 + 5.0, 0.5), vec3(0.0, -1.0, 0.0), 20.0).expect("must hit"); assert_eq!(hit.pos, (0, SKY, 0)); assert_eq!(hit.normal, (0, 1, 0));@@ -171,7 +172,7 @@ mod tests { #[test] fn a_top_slab_is_hit_from_above_at_the_cell_ceiling() { let mut w = world();- w.set_block_meta_world(0, SKY, 0, Block::StoneSlab as u8, META_TOP);+ w.set_block_meta_world(0, SKY, 0, Block::StoneSlab as Id, META_TOP); let hit = raycast(&w, vec3(0.5, SKY as f32 + 5.0, 0.5), vec3(0.0, -1.0, 0.0), 20.0).expect("must hit"); assert!((hit.dist - 4.0).abs() < 1e-3, "a top slab's surface is the cell ceiling"); }@@ -180,7 +181,7 @@ mod tests { #[test] fn cubes_still_hit_at_the_cell_boundary() { let mut w = world();- w.set_block_world(4, SKY, 0, Block::Stone as u8);+ w.set_block_world(4, SKY, 0, Block::Stone as Id); let hit = raycast(&w, vec3(0.0, SKY as f32 + 0.5, 0.5), vec3(1.0, 0.0, 0.0), 20.0).expect("must hit"); assert_eq!(hit.pos, (4, SKY, 0)); assert_eq!(hit.normal, (-1, 0, 0));@@ -193,7 +194,7 @@ mod tests { #[test] fn stairs_are_open_above_their_low_half() { let mut w = world();- w.set_block_meta_world(4, SKY, 0, Block::StoneStairs as u8, FACE_NORTH);+ w.set_block_meta_world(4, SKY, 0, Block::StoneStairs as Id, FACE_NORTH); // z = 0.25 is the low (north) half, 0.75 up the cell is above the tread. assert!(raycast(&w, vec3(0.0, SKY as f32 + 0.75, 0.25), vec3(1.0, 0.0, 0.0), 20.0).is_none()); // z = 0.75 is under the tall step, so the same height is solid.
games/voxels/src/main/rust/src/villager.rs
diff --git a/games/voxels/src/main/rust/src/villager.rs b/games/voxels/src/main/rust/src/villager.rsindex d9b5beaadd..18db06ce07 100644--- a/games/voxels/src/main/rust/src/villager.rs+++ b/games/voxels/src/main/rust/src/villager.rs@@ -10,30 +10,32 @@ // player could never find "their" librarian again. A shared counter in `ProgressSave` keeps the // progression real. +use crate::world::block::Id;+ use crate::item::{has_durability, max_durability}; -pub const EMERALD: u8 = 156;+pub const EMERALD: Id = 156; /// One line on a villager's trade list. `cost2` of 0 means a single-ingredient trade. #[derive(Clone, Copy)] pub struct Offer {- pub cost: u8,+ pub cost: Id, pub cost_n: i32,- pub cost2: u8,+ pub cost2: Id, pub cost2_n: i32,- pub give: u8,+ pub give: Id, pub give_n: i32, } // Constructors, so the tables below read as sentences and can't transpose a cost for a give.-const fn buy(emeralds: i32, give: u8, give_n: i32) -> Offer {+const fn buy(emeralds: i32, give: Id, give_n: i32) -> Offer { Offer { cost: EMERALD, cost_n: emeralds, cost2: 0, cost2_n: 0, give, give_n } }-const fn sell(cost: u8, cost_n: i32, emeralds: i32) -> Offer {+const fn sell(cost: Id, cost_n: i32, emeralds: i32) -> Offer { Offer { cost, cost_n, cost2: 0, cost2_n: 0, give: EMERALD, give_n: emeralds } } /// Emeralds plus raw material for one finished piece — the smiths' signature trade.-const fn forge(emeralds: i32, mat: u8, mat_n: i32, give: u8) -> Offer {+const fn forge(emeralds: i32, mat: Id, mat_n: i32, give: Id) -> Offer { Offer { cost: EMERALD, cost_n: emeralds, cost2: mat, cost2_n: mat_n, give, give_n: 1 } } @@ -254,11 +256,7 @@ pub fn give_count(offer: &Offer) -> i32 { #[cfg(test)] mod tests { use super::*;- use crate::world::block::MAX_BLOCK_ID;-- fn is_real_id(id: u8) -> bool {- id != 0 && (id <= MAX_BLOCK_ID || crate::item::is_item(id))- }+ use crate::world::block::{is_real_id, MAX_LOW_BLOCK_ID}; // A typo in a trade table is invisible until a player taps it and receives Air, so every id in // every tier of every profession gets checked.
games/voxels/src/main/rust/src/world/block.rs
diff --git a/games/voxels/src/main/rust/src/world/block.rs b/games/voxels/src/main/rust/src/world/block.rsindex 4d04076c6a..efeecf3220 100644--- a/games/voxels/src/main/rust/src/world/block.rs+++ b/games/voxels/src/main/rust/src/world/block.rs@@ -1,9 +1,11 @@ use serde::{Deserialize, Serialize}; -pub type BlockId = u8;+/// One id space for blocks and items, 16 bits wide. The split is by range, not by width:+/// `ITEM_BASE..=ITEM_MAX` is items and everything else is a block. See `item.rs`.+pub type Id = u16; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]-#[repr(u8)]+#[repr(u16)] pub enum Block { Air = 0, Stone = 1,@@ -140,7 +142,19 @@ pub enum Block { MelonCrop = 123, } -pub const MAX_BLOCK_ID: u8 = 123;+/// Blocks live in two windows either side of the item range. The low window is the original+/// `u8` numbering, frozen so no saved chunk needs remapping; new blocks go in the high window.+pub const MAX_LOW_BLOCK_ID: Id = 123;+pub const BLOCK_HIGH_BASE: Id = 1024;+/// One below `BLOCK_HIGH_BASE` while the high window is empty, which makes the range check below+/// match nothing rather than matching `Air`.+pub const MAX_HIGH_BLOCK_ID: Id = BLOCK_HIGH_BASE - 1;++/// Every id that names a real block, low window then high. The plain `0..=MAX` loop that used to+/// work would now walk the item window and half of nothing.+pub fn all_block_ids() -> impl Iterator<Item = Id> {+ (0..=MAX_LOW_BLOCK_ID).chain(BLOCK_HIGH_BASE..=MAX_HIGH_BLOCK_ID)+} /// Growth stage occupies meta bits 3-4 (bits 0-2 are facing and top-half, used by slabs and stairs). pub const CROP_STAGE_SHIFT: u8 = 3;@@ -149,6 +163,13 @@ pub const CROP_RIPE: u8 = 3; pub fn crop_stage(meta: u8) -> u8 { (meta & CROP_STAGE_MASK) >> CROP_STAGE_SHIFT } pub fn crop_meta(stage: u8) -> u8 { (stage.min(CROP_RIPE) << CROP_STAGE_SHIFT) & CROP_STAGE_MASK } +/// Does an id name something a player can actually hold — a real block, or an id in the item+/// window? The data tables are full of bare numbers, and a typo there yields Air in silence.+#[cfg(test)]+pub fn is_real_id(id: Id) -> bool {+ id != 0 && (Block::from_id(id) != Block::Air || crate::item::is_item(id))+}+ /// The geometry a block occupies within its cell. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Shape { Cube, Slab, Stairs }@@ -187,10 +208,12 @@ impl Boxes { } impl Block {- pub fn from_id(id: u8) -> Self {- if id <= MAX_BLOCK_ID { unsafe { std::mem::transmute(id) } } else { Self::Air }+ pub fn from_id(id: Id) -> Self {+ let known = id <= MAX_LOW_BLOCK_ID+ || (BLOCK_HIGH_BASE..=MAX_HIGH_BLOCK_ID).contains(&id);+ if known { unsafe { std::mem::transmute(id) } } else { Self::Air } }- pub fn id(self) -> u8 { self as u8 }+ pub fn id(self) -> Id { self as Id } pub fn is_air(self) -> bool { matches!(self, Self::Air) } pub fn is_solid(self) -> bool { !matches!(self, Self::Air | Self::Water | Self::Glass | Self::Lava | Self::NetherPortal | Self::EndPortal) && !self.is_crop() } pub fn is_transparent(self) -> bool {@@ -204,14 +227,14 @@ impl Block { /// Crops grow on farmland and are harvested rather than mined. pub fn is_crop(self) -> bool { matches!(self, Self::WheatCrop | Self::CarrotCrop | Self::MelonCrop) } /// The seed that plants this crop, and what a ripe one yields.- pub fn crop_seed(self) -> u8 {+ pub fn crop_seed(self) -> Id { match self { Self::WheatCrop => 250, Self::CarrotCrop => 135, Self::MelonCrop => 136, _ => 0 } }- pub fn crop_yield(self) -> u8 {+ pub fn crop_yield(self) -> Id { match self { Self::WheatCrop => 251, Self::CarrotCrop => 135, Self::MelonCrop => 136, _ => 0 } } /// The crop a given seed plants, if any.- pub fn crop_from_seed(seed: u8) -> Option<Self> {+ pub fn crop_from_seed(seed: Id) -> Option<Self> { match seed { 250 => Some(Self::WheatCrop), 135 => Some(Self::CarrotCrop), 136 => Some(Self::MelonCrop), _ => None } } @@ -567,13 +590,27 @@ mod tests { #[test] fn every_id_up_to_the_max_maps_to_a_distinct_block() {- for id in 0..=MAX_BLOCK_ID {+ for id in all_block_ids() { assert_eq!(Block::from_id(id).id(), id, "id {id} did not round-trip"); }- // Ids above the max must not be mistaken for real blocks.- assert_eq!(Block::from_id(MAX_BLOCK_ID + 1), Block::Air);- // Blocks and items share one u8 space; crossing ITEM_BASE would make a block unplaceable.- assert!(MAX_BLOCK_ID < crate::item::ITEM_BASE);+ // Ids in the gap between the windows must not be mistaken for real blocks.+ assert_eq!(Block::from_id(MAX_LOW_BLOCK_ID + 1), Block::Air);+ assert_eq!(Block::from_id(BLOCK_HIGH_BASE - 1), Block::Air);+ assert_eq!(Block::from_id(Id::MAX), Block::Air);+ // The whole item window has to read back as air, or a stray item id in a chunk would+ // transmute into a block that doesn't exist.+ for id in crate::item::ITEM_BASE..=crate::item::ITEM_MAX {+ assert_eq!(Block::from_id(id), Block::Air, "item id {id} decoded as a block");+ }+ }++ // The three windows must stay disjoint and in order, or an id would mean two things at once.+ #[test]+ fn the_id_windows_do_not_overlap() {+ assert!(MAX_LOW_BLOCK_ID < crate::item::ITEM_BASE);+ assert!(crate::item::ITEM_BASE <= crate::item::ITEM_MAX);+ assert!(crate::item::ITEM_MAX < BLOCK_HIGH_BASE);+ for id in all_block_ids() { assert!(!crate::item::is_item(id), "block {id} sits in the item window"); } } #[test]@@ -679,7 +716,7 @@ mod tests { #[test] fn crops_are_walkable_and_plantable() { let mut seen = 0;- for id in 0..=MAX_BLOCK_ID {+ for id in all_block_ids() { let b = Block::from_id(id); if !b.is_crop() { continue; } seen += 1;@@ -692,7 +729,7 @@ mod tests { } assert_eq!(seen, 3, "expected three crops"); assert_eq!(Block::crop_from_seed(0), None);- assert_eq!(Block::crop_from_seed(Block::Stone as u8), None);+ assert_eq!(Block::crop_from_seed(Block::Stone as Id), None); // Glass is the mirror image: it fills the cell but lets light straight through. assert!(!Block::Glass.blocks_light());
games/voxels/src/main/rust/src/world/chunk.rs
diff --git a/games/voxels/src/main/rust/src/world/chunk.rs b/games/voxels/src/main/rust/src/world/chunk.rsindex b7930067c1..bd21865613 100644--- a/games/voxels/src/main/rust/src/world/chunk.rs+++ b/games/voxels/src/main/rust/src/world/chunk.rs@@ -1,3 +1,5 @@+use super::block::Id;+ pub const CHUNK_SIZE: usize = 16; pub const SECTION_SIZE: usize = 16; pub const SECTIONS_PER_CHUNK: usize = 16;@@ -9,15 +11,16 @@ impl ChunkPos { pub fn world_origin(self) -> (i32, i32) { (self.0 * CHUNK_SIZE as i32, self.1 * CHUNK_SIZE as i32) } } // `meta` carries the per-voxel state that doesn't fit in the block id (slab half, stair facing). It-// is allocated only once a section actually stores a non-zero value: generated terrain is all plain-// cubes, so the vast majority of resident sections stay at 8 bytes instead of 4 KB.+// stays one byte wide while ids are two. It is allocated only once a section actually stores a+// non-zero value: generated terrain is all plain cubes, so the vast majority of resident sections+// stay at 8 bytes instead of 4 KB. #[derive(Clone)]-pub struct BlockSection { pub blocks: [u8; 4096], pub meta: Option<Box<[u8; 4096]>>, pub non_air: usize, }+pub struct BlockSection { pub blocks: [Id; 4096], pub meta: Option<Box<[u8; 4096]>>, pub non_air: usize, } impl BlockSection { pub fn empty() -> Self { Self { blocks: [0;4096], meta: None, non_air:0 } } fn idx(x: usize, y: usize, z: usize) -> usize { y*256+z*16+x }- pub fn get(&self, x: usize, y: usize, z: usize) -> u8 { self.blocks[Self::idx(x,y,z)] }- pub fn set(&mut self, x: usize, y: usize, z: usize, id: u8) {+ pub fn get(&self, x: usize, y: usize, z: usize) -> Id { self.blocks[Self::idx(x,y,z)] }+ pub fn set(&mut self, x: usize, y: usize, z: usize, id: Id) { let i=Self::idx(x,y,z); let prev=self.blocks[i]; if prev!=0 && id==0 { self.non_air=self.non_air.saturating_sub(1); } else if prev==0 && id!=0 { self.non_air+=1; } self.blocks[i]=id;@@ -40,7 +43,7 @@ pub struct Chunk { } impl Chunk { pub fn new(pos: ChunkPos) -> Self { Self { pos, sections: std::array::from_fn(|_| None), generated:false, dirty:false, mesh_dirty:true } }- pub fn get_block(&self, x: usize, y: usize, z: usize) -> u8 {+ pub fn get_block(&self, x: usize, y: usize, z: usize) -> Id { if y>=CHUNK_HEIGHT { return 0; } let sec=y/SECTION_SIZE; let ly=y%SECTION_SIZE; if let Some(s)=&self.sections[sec] { s.get(x,ly,z) } else { 0 } }@@ -48,8 +51,8 @@ impl Chunk { if y>=CHUNK_HEIGHT { return 0; } let sec=y/SECTION_SIZE; let ly=y%SECTION_SIZE; if let Some(s)=&self.sections[sec] { s.get_meta(x,ly,z) } else { 0 } }- pub fn set_block(&mut self, x: usize, y: usize, z: usize, id: u8) { self.set_block_meta(x, y, z, id, 0); }- pub fn set_block_meta(&mut self, x: usize, y: usize, z: usize, id: u8, meta: u8) {+ pub fn set_block(&mut self, x: usize, y: usize, z: usize, id: Id) { self.set_block_meta(x, y, z, id, 0); }+ pub fn set_block_meta(&mut self, x: usize, y: usize, z: usize, id: Id, meta: u8) { if y>=CHUNK_HEIGHT { return; } let sec=y/SECTION_SIZE; let ly=y%SECTION_SIZE; if self.sections[sec].is_none() { if id==0 { return; } self.sections[sec]=Some(BlockSection::empty()); } if let Some(s)=self.sections[sec].as_mut() {
games/voxels/src/main/rust/src/world/chunk_map.rs
diff --git a/games/voxels/src/main/rust/src/world/chunk_map.rs b/games/voxels/src/main/rust/src/world/chunk_map.rsindex ea063a4b95..a8b9f46fa9 100644--- a/games/voxels/src/main/rust/src/world/chunk_map.rs+++ b/games/voxels/src/main/rust/src/world/chunk_map.rs@@ -1,4 +1,4 @@-use super::block::Block;+use super::block::{Block, Id}; use super::chunk::{Chunk, ChunkPos, CHUNK_SIZE, CHUNK_HEIGHT}; use super::generator::TerrainGen; use super::save;@@ -17,7 +17,7 @@ impl ChunkMap { Self { chunks: HashMap::new(), gen: TerrainGen::new_dim(seed, dim), save_dir, render_distance: 12 } } pub fn dim(&self) -> u8 { self.gen.dim }- pub fn get_block_world(&self, wx: i32, wy: i32, wz: i32) -> u8 {+ pub fn get_block_world(&self, wx: i32, wy: i32, wz: i32) -> Id { if wy < 0 || wy >= CHUNK_HEIGHT as i32 { return 0; } let cp = ChunkPos::from_world(wx, wz); if let Some(chunk) = self.chunks.get(&cp) {@@ -35,10 +35,10 @@ impl ChunkMap { chunk.get_meta(lx, wy as usize, lz) } else { 0 } }- pub fn set_block_world(&mut self, wx: i32, wy: i32, wz: i32, id: u8) -> bool {+ pub fn set_block_world(&mut self, wx: i32, wy: i32, wz: i32, id: Id) -> bool { self.set_block_meta_world(wx, wy, wz, id, 0) }- pub fn set_block_meta_world(&mut self, wx: i32, wy: i32, wz: i32, id: u8, meta: u8) -> bool {+ pub fn set_block_meta_world(&mut self, wx: i32, wy: i32, wz: i32, id: Id, meta: u8) -> bool { if wy < 0 || wy >= CHUNK_HEIGHT as i32 { return false; } let cp = ChunkPos::from_world(wx, wz); if !self.chunks.contains_key(&cp) { self.load_or_gen(cp); }
games/voxels/src/main/rust/src/world/generator.rs
diff --git a/games/voxels/src/main/rust/src/world/generator.rs b/games/voxels/src/main/rust/src/world/generator.rsindex 254787973b..5aee66d9cd 100644--- a/games/voxels/src/main/rust/src/world/generator.rs+++ b/games/voxels/src/main/rust/src/world/generator.rs@@ -1,4 +1,5 @@ use super::chunk::{Chunk, CHUNK_SIZE, CHUNK_HEIGHT};+use super::block::Id; use crate::world::perlin::NoiseFn; use crate::world::perlin::Perlin; use std::collections::hash_map::DefaultHasher;@@ -29,7 +30,7 @@ const B_BLACKSMITH: u8 = 5; const B_CHURCH: u8 = 6; // Level a village column: dirt foundation down a few blocks, clear terrain above up to `clear_to`.-fn level_column(chunk: &mut Chunk, lx: usize, lz: usize, base: usize, clear_to: usize, floor: u8) {+fn level_column(chunk: &mut Chunk, lx: usize, lz: usize, base: usize, clear_to: usize, floor: Id) { for dyb in 1..=3 { if base >= dyb { chunk.set_block(lx, base - dyb, lz, 2); } } // dirt foundation chunk.set_block(lx, base, lz, floor); for dy in 1..=clear_to { if base + dy < CHUNK_HEIGHT { chunk.set_block(lx, base + dy, lz, 0); } }@@ -101,7 +102,7 @@ fn render_building(chunk: &mut Chunk, ox: i32, oz: i32, bx: i32, bz: i32, w: i32 } // Blacksmith forge: furnace + magma fire + iron-block anvil inside. if kind == B_BLACKSMITH {- for &(dx, dz, dy, id) in &[(1i32, 1i32, 1usize, 35u8), (2, 1, 0, 76), (3, 1, 1, 23)] {+ for &(dx, dz, dy, id) in &[(1i32, 1i32, 1usize, 35 as Id), (2, 1, 0, 76), (3, 1, 1, 23)] { let (wx, wz) = (bx + dx, bz + dz); if in_chunk(wx, wz, ox, oz) { chunk.set_block((wx - ox) as usize, base + dy, (wz - oz) as usize, id); } }@@ -285,7 +286,7 @@ pub struct TerrainGen { // Ore/stone-variant veins, richest first so a rare vein wins where two overlap. // (block id, noise offset, noise scale, threshold, min y, max y)-type Vein = (u8, f64, f64, f64, i32, i32);+type Vein = (Id, f64, f64, f64, i32, i32); const OVERWORLD_VEINS: [Vein; 11] = [ (22, 947.0, 0.115, 0.80, 62, 118), // emerald — mountains only, the rarest surface find (20, 823.0, 0.105, 0.78, 5, 20), // diamond — deepest@@ -385,7 +386,7 @@ impl TerrainGen { } } // Surface + subsurface block for a biome at surface height `h` (before the sea/beach override).- fn surface_blocks(&self, biome: Biome, h: usize, wx: f64, wz: f64) -> (u8, u8) {+ fn surface_blocks(&self, biome: Biome, h: usize, wx: f64, wz: f64) -> (Id, Id) { use Biome::*; match biome { Desert => (6, 38), // sand / sandstone@@ -408,7 +409,7 @@ impl TerrainGen { } } // Plant a simple tree: a trunk of `log` topped with a `leaf` canopy. Shared by all wooded biomes.- fn plant_tree(&self, chunk: &mut Chunk, dx: usize, dz: usize, h: usize, log: u8, leaf: u8, trunk_h: usize) {+ fn plant_tree(&self, chunk: &mut Chunk, dx: usize, dz: usize, h: usize, log: Id, leaf: Id, trunk_h: usize) { for ty in 1..=trunk_h { let y = h + ty; if y < CHUNK_HEIGHT { chunk.set_block(dx, y, dz, log); }@@ -455,7 +456,7 @@ impl TerrainGen { } // The block that fills a solid underground cell: an ore/variant vein if one passes here, // otherwise deepslate at depth or plain stone.- fn stone_at(&self, veins: &[Vein], wx: f64, y: i32, wz: f64, base: u8) -> u8 {+ fn stone_at(&self, veins: &[Vein], wx: f64, y: i32, wz: f64, base: Id) -> Id { for &(id, off, scale, thresh, y0, y1) in veins { if y < y0 || y > y1 { continue; } if self.perlin_ore.get([wx * scale + off, y as f64 * scale, wz * scale - off]) > thresh { return id; }@@ -463,7 +464,7 @@ impl TerrainGen { base } // Deepslate replaces stone below DEEPSLATE_Y, with a noisy band so the boundary isn't a flat line.- fn deep_base(&self, wx: f64, y: i32, wz: f64) -> u8 {+ fn deep_base(&self, wx: f64, y: i32, wz: f64) -> Id { let jitter = self.perlin_detail.get([wx * 0.06, wz * 0.06]) * 5.0; if (y as f64) < DEEPSLATE_Y as f64 + jitter { 57 } else { 1 } }@@ -594,12 +595,12 @@ impl TerrainGen { } if h > 0 && !self.cave_at(wx, h as f64, wz) { // Beaches: sand where the ground meets the sea (snowy biomes get snowy beaches).- let surface: u8 = if h < 62 {+ let surface: Id = if h < 62 { match biome { Biome::Badlands => 36, Biome::SnowyPlains | Biome::SnowyTaiga | Biome::IceSpikes | Biome::FrozenPeaks | Biome::SnowySlopes => 11, _ => 6 } } else { surface_top }; // Buried finds hide in sand, wherever sand happens to be the surface. let surface = if matches!(surface, 6 | 36) && hash3(wx as i32, wz as i32, 0x5A9D) % 900 == 0 {- crate::world::block::Block::SuspiciousSand as u8+ crate::world::block::Block::SuspiciousSand as Id } else { surface }; chunk.set_block(dx, h, dz, surface); if h > 1 && !self.cave_at(wx, (h-1) as f64, wz) { chunk.set_block(dx, h - 1, dz, sub); }@@ -702,7 +703,7 @@ impl TerrainGen { match kind { 3 => { // warm: coral reef if r < 90 {- let coral = 61 + ((hasher.finish() >> 8) % 5) as u8;+ let coral = 61 + ((hasher.finish() >> 8) % 5) as Id; chunk.set_block(dx, y, dz, coral); if r < 20 && y + 1 < Self::SEA_LEVEL { chunk.set_block(dx, y + 1, dz, coral); } } else if r < 96 { chunk.set_block(dx, y, dz, 67); } // sea lantern@@ -944,16 +945,16 @@ mod tests { } } }- let pct = |id: u8| counts.get(&id).copied().unwrap_or(0) as f64 * 100.0 / total as f64;+ let pct = |id: Id| counts.get(&id).copied().unwrap_or(0) as f64 * 100.0 / total as f64; for (id, name, lo, hi) in [- (18u8, "coal", 0.5, 4.0),- (19u8, "iron", 0.2, 2.5),- (21u8, "redstone", 0.02, 0.6),- (20u8, "diamond", 0.005, 0.3),- (22u8, "emerald", 0.002, 0.3),- (90u8, "silver", 0.02, 0.8),- (97u8, "copper", 0.3, 3.0),- (98u8, "gold", 0.01, 0.5),+ (18 as Id, "coal", 0.5, 4.0),+ (19 as Id, "iron", 0.2, 2.5),+ (21 as Id, "redstone", 0.02, 0.6),+ (20 as Id, "diamond", 0.005, 0.3),+ (22 as Id, "emerald", 0.002, 0.3),+ (90 as Id, "silver", 0.02, 0.8),+ (97 as Id, "copper", 0.3, 3.0),+ (98 as Id, "gold", 0.01, 0.5), ] { let p = pct(id); println!("{name}: {p:.4}%");
games/voxels/src/main/rust/src/world/mesher.rs
diff --git a/games/voxels/src/main/rust/src/world/mesher.rs b/games/voxels/src/main/rust/src/world/mesher.rsindex 8251793e1a..ad3d66a239 100644--- a/games/voxels/src/main/rust/src/world/mesher.rs+++ b/games/voxels/src/main/rust/src/world/mesher.rs@@ -1,8 +1,8 @@-use super::block::{Aabb, Block, Shape, GRASS_SIDE_TILE};+use super::block::{Aabb, Block, Id, Shape, GRASS_SIDE_TILE}; use super::chunk::{Chunk, SECTION_SIZE, SECTIONS_PER_CHUNK, CHUNK_HEIGHT}; /// A neighbour lookup: block id plus its meta byte, since occlusion now depends on both.-pub type Neighbor<'a> = dyn Fn(i32, i32, i32) -> (u8, u8) + 'a;+pub type Neighbor<'a> = dyn Fn(i32, i32, i32) -> (Id, u8) + 'a; // Per-chunk lighting: skylight column tops (highest opaque block per column) and a block-light grid // (BFS flood from emitters, decreasing by 1 per open cell). Cross-chunk bleed is limited to this@@ -181,10 +181,10 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &Neighbor, grass_tint: &dyn Fn(i3 match axis { 0 => { for x in 0..SECTION_SIZE {- let mut mask = [[None::<(u8,u32,[u8;4],u8)>; 16]; 16];+ let mut mask = [[None::<(Id,u32,[u8;4],u8)>; 16]; 16]; for y in 0..SECTION_SIZE { for z in 0..SECTION_SIZE { let id = section.get(x,y,z);- if id == 0 || id == Block::Water as u8 { continue; }+ if id == 0 || id == Block::Water as Id { continue; } if Block::from_id(id).shape() != Shape::Cube { continue; } // emitted as boxes below let wx = ox + x as i32; let wy = base_y + y as i32; let wz = oz + z as i32; if !hidden(wx, wy, wz, dx, dy, dz) {@@ -212,7 +212,7 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &Neighbor, grass_tint: &dyn Fn(i3 let y0 = y as f32; let z0 = z as f32; let ww = w as f32; let hh = h as f32; let (u0,v0,u1,v1) = (0.0f32, 0.0f32, ww, hh); // Grass side: sentinel tile so the shader composites dirt + tinted overlay in one quad.- let is_grass = bid == Block::Grass as u8;+ let is_grass = bid == Block::Grass as Id; let color = if is_grass { grass_tint(ox + x as i32, oz + z as i32) } else { Block::from_id(bid).color() }; let etile = if is_grass { GRASS_SIDE_TILE as f32 } else { tile_idx as f32 }; let quad = if dx==1 {@@ -231,10 +231,10 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &Neighbor, grass_tint: &dyn Fn(i3 } 1 => { for y in 0..SECTION_SIZE {- let mut mask = [[None::<(u8,u32,[u8;4],u8)>; 16]; 16];+ let mut mask = [[None::<(Id,u32,[u8;4],u8)>; 16]; 16]; for x in 0..SECTION_SIZE { for z in 0..SECTION_SIZE { let id = section.get(x,y,z);- if id==0 || id==Block::Water as u8 { continue; }+ if id==0 || id==Block::Water as Id { continue; } if Block::from_id(id).shape() != Shape::Cube { continue; } let wx = ox + x as i32; let wy = base_y + y as i32; let wz = oz + z as i32; if !hidden(wx, wy, wz, dx, dy, dz) {@@ -263,7 +263,7 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &Neighbor, grass_tint: &dyn Fn(i3 let y0 = y as f32 + if dy==1 { 1.0 } else { 0.0 }; let x0 = x as f32; let z0 = z as f32; let ww = w as f32; let hh = h as f32; let (u0,v0,u1,v1) = (0.0f32, 0.0f32, hh, ww);- let color = if bid == Block::Grass as u8 && dy == 1 {+ let color = if bid == Block::Grass as Id && dy == 1 { grass_tint(ox + x as i32, oz + z as i32) } else { Block::from_id(bid).color() }; let wx0 = ox as f32; let wz0 = oz as f32; let by = base_y as f32;@@ -282,10 +282,10 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &Neighbor, grass_tint: &dyn Fn(i3 } 2 => { for z in 0..SECTION_SIZE {- let mut mask = [[None::<(u8,u32,[u8;4],u8)>; 16]; 16];+ let mut mask = [[None::<(Id,u32,[u8;4],u8)>; 16]; 16]; for x in 0..SECTION_SIZE { for y in 0..SECTION_SIZE { let id = section.get(x,y,z);- if id==0 || id==Block::Water as u8 { continue; }+ if id==0 || id==Block::Water as Id { continue; } if Block::from_id(id).shape() != Shape::Cube { continue; } let wx = ox + x as i32; let wy = base_y + y as i32; let wz = oz + z as i32; if !hidden(wx, wy, wz, dx, dy, dz) {@@ -312,7 +312,7 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &Neighbor, grass_tint: &dyn Fn(i3 let z0 = z as f32 + if dz==1 { 1.0 } else { 0.0 }; let x0 = x as f32; let y0 = y as f32; let ww = w as f32; let hh = h as f32; let (u0,v0,u1,v1) = (0.0f32, 0.0f32, hh, ww);- let is_grass = bid == Block::Grass as u8;+ let is_grass = bid == Block::Grass as Id; let color = if is_grass { grass_tint(ox + x as i32, oz + z as i32) } else { Block::from_id(bid).color() }; let etile = if is_grass { GRASS_SIDE_TILE as f32 } else { tile_idx as f32 }; let wx0 = ox as f32; let wz0 = oz as f32; let by = base_y as f32;@@ -338,10 +338,10 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &Neighbor, grass_tint: &dyn Fn(i3 for y in 0..SECTION_SIZE { let mut wmask = [[false; 16]; 16]; for x in 0..SECTION_SIZE { for z in 0..SECTION_SIZE {- if section.get(x,y,z) != Block::Water as u8 { continue; }+ if section.get(x,y,z) != Block::Water as Id { continue; } let wx = ox + x as i32; let wy = base_y + y as i32; let wz = oz + z as i32; let above = get_neighbor(wx, wy+1, wz).0;- if above != Block::Water as u8 && !(above != 0 && Block::from_id(above).is_opaque()) {+ if above != Block::Water as Id && !(above != 0 && Block::from_id(above).is_opaque()) { wmask[x][z] = true; } }}@@ -420,7 +420,7 @@ mod tests { #[test] fn a_lone_slab_is_meshed() { let mut c = Chunk::new(ChunkPos(0,0));- c.set_block_meta(2, 10, 2, Block::StoneSlab as u8, 0);+ c.set_block_meta(2, 10, 2, Block::StoneSlab as Id, 0); let m = mesh_alone(&c); assert_eq!(vert_count(&m), 24, "a free-standing slab shows all six faces"); @@ -437,12 +437,12 @@ mod tests { #[test] fn a_cube_next_to_a_slab_keeps_its_face() { let mut with_slab = Chunk::new(ChunkPos(0,0));- with_slab.set_block(5, 10, 5, Block::Stone as u8);- with_slab.set_block_meta(6, 10, 5, Block::StoneSlab as u8, 0);+ with_slab.set_block(5, 10, 5, Block::Stone as Id);+ with_slab.set_block_meta(6, 10, 5, Block::StoneSlab as Id, 0); let mut with_cube = Chunk::new(ChunkPos(0,0));- with_cube.set_block(5, 10, 5, Block::Stone as u8);- with_cube.set_block(6, 10, 5, Block::Stone as u8);+ with_cube.set_block(5, 10, 5, Block::Stone as Id);+ with_cube.set_block(6, 10, 5, Block::Stone as Id); let slab_faces = count_faces_at(&mesh_alone(&with_slab), 6.0, [1.0, 0.0, 0.0]); let cube_faces = count_faces_at(&mesh_alone(&with_cube), 6.0, [1.0, 0.0, 0.0]);@@ -462,9 +462,9 @@ mod tests { #[test] fn a_slab_roof_casts_shadow() { // The light packed into the floor block's up-facing quad, under an optional roof.- let floor_light = |roof: Option<u8>| -> f32 {+ let floor_light = |roof: Option<Id>| -> f32 { let mut c = Chunk::new(ChunkPos(0, 0));- c.set_block(8, 10, 8, Block::Stone as u8);+ c.set_block(8, 10, 8, Block::Stone as Id); if let Some(r) = roof { c.set_block_meta(8, 14, 8, r, 0); } let m = mesh_alone(&c); m.iter().flatten()@@ -474,9 +474,9 @@ mod tests { .light }; let open_sky = floor_light(None);- let under_slab = floor_light(Some(Block::StoneSlab as u8));- let under_stairs = floor_light(Some(Block::StoneStairs as u8));- let under_glass = floor_light(Some(Block::Glass as u8));+ let under_slab = floor_light(Some(Block::StoneSlab as Id));+ let under_stairs = floor_light(Some(Block::StoneStairs as Id));+ let under_glass = floor_light(Some(Block::Glass as Id)); assert!(under_slab < open_sky, "a slab roof must dim the floor ({under_slab} vs {open_sky})"); assert!(under_stairs < open_sky, "so must a stair roof ({under_stairs} vs {open_sky})");@@ -488,7 +488,7 @@ mod tests { #[test] fn stairs_drop_only_the_sealed_internal_face() { let mut c = Chunk::new(ChunkPos(0,0));- c.set_block_meta(3, 10, 3, Block::StoneStairs as u8, crate::world::block::FACE_NORTH);+ c.set_block_meta(3, 10, 3, Block::StoneStairs as Id, crate::world::block::FACE_NORTH); let m = mesh_alone(&c); let md = m.iter().flatten().next().expect("stairs must mesh");
games/voxels/src/main/rust/src/world/save.rs
diff --git a/games/voxels/src/main/rust/src/world/save.rs b/games/voxels/src/main/rust/src/world/save.rsindex dc602f2e94..fc8f8c1b93 100644--- a/games/voxels/src/main/rust/src/world/save.rs+++ b/games/voxels/src/main/rust/src/world/save.rs@@ -28,7 +28,7 @@ fn encode_chunk(chunk: &Chunk) -> Vec<u8> { for sec_opt in chunk.sections.iter() { let Some(sec) = sec_opt else { data.push(0); continue; }; data.push(1);- for &id in sec.blocks.iter() { data.extend_from_slice(&(id as u16).to_le_bytes()); }+ for &id in sec.blocks.iter() { data.extend_from_slice(&id.to_le_bytes()); } match sec.meta.as_ref().filter(|m| m.iter().any(|&v| v != 0)) { Some(meta) => { data.push(1); data.extend_from_slice(&meta[..]); } None => data.push(0),@@ -61,16 +61,13 @@ fn decode_chunk(bytes: &[u8], chunk: &mut Chunk) -> std::io::Result<()> { let flag = bytes[off]; off+=1; if flag != 1 { continue; } if off + block_bytes > bytes.len() { return Err(bad("section overflow")); }- let mut blocks = [0u8; 4096];+ let mut blocks = [0 as crate::world::block::Id; 4096]; if wide_ids { for (i, cell) in blocks.iter_mut().enumerate() {- let raw = u16::from_le_bytes([bytes[off + i*2], bytes[off + i*2 + 1]]);- // Ids this build has no room for read back as air rather than as a wrapped-around- // block, which would be a wrong block rather than a missing one.- *cell = u8::try_from(raw).unwrap_or(0);+ *cell = u16::from_le_bytes([bytes[off + i*2], bytes[off + i*2 + 1]]); } } else {- blocks.copy_from_slice(&bytes[off..off+4096]);+ for (i, cell) in blocks.iter_mut().enumerate() { *cell = bytes[off + i] as u16; } } off+=block_bytes; let mut meta = None;@@ -142,7 +139,7 @@ impl Default for ProgressSave { #[derive(serde::Serialize, serde::Deserialize, Default, Debug, Clone)] pub struct InventorySave { pub selected: usize, pub slots: Vec<InvSlotSave> } #[derive(serde::Serialize, serde::Deserialize, Default, Debug, Clone)]-pub struct InvSlotSave { pub id: u8, pub count: i32 }+pub struct InvSlotSave { pub id: crate::world::block::Id, pub count: i32 } #[derive(serde::Serialize, serde::Deserialize, Default, Debug, Clone)] pub struct StatsSave { pub placed: i32, pub broken: i32, pub walked: i32, pub night_seen: bool } @@ -177,7 +174,7 @@ mod tests { data.push(SECTIONS_PER_CHUNK as u8); for sec in chunk.sections.iter() { match sec {- Some(s) => { data.push(1); data.extend_from_slice(&s.blocks); }+ Some(s) => { data.push(1); data.extend(s.blocks.iter().map(|&b| b as u8)); } None => data.push(0), } }@@ -194,7 +191,7 @@ mod tests { match sec { Some(s) => { data.push(1);- data.extend_from_slice(&s.blocks);+ data.extend(s.blocks.iter().map(|&b| b as u8)); match s.meta.as_ref() { Some(m) => { data.push(1); data.extend_from_slice(&m[..]); } None => data.push(0),@@ -256,13 +253,17 @@ mod tests { original.set_block(0, 0, 0, 1); original.set_block(15, 255, 15, 123); original.set_block_meta(8, 64, 8, 102, 0b100);- original.set_block_meta(9, 64, 8, 103, 3);+ original.set_block(0, 255, 0, 123);+ // An id from the high block window, which only VOX3 is wide enough to carry.+ original.set_block(1, 255, 0, crate::world::block::BLOCK_HIGH_BASE); let encoded = encode_chunk(&original); assert_eq!(&encoded[0..4], b"VOX3"); let mut loaded = Chunk::new(ChunkPos(7, 7)); decode_chunk(&encoded, &mut loaded).expect("VOX3 must decode");+ assert_eq!(loaded.get_block(1, 255, 0), crate::world::block::BLOCK_HIGH_BASE,+ "a wide id must survive the round trip intact"); for (a, b) in original.sections.iter().zip(loaded.sections.iter()) { match (a, b) { (Some(a), Some(b)) => {@@ -284,7 +285,7 @@ mod tests { // A spread of ids and metas across several sections, including the extremes. for i in 0..64 { let x = i % 16; let z = (i / 16) % 16;- original.set_block(x, i, z, (i as u8 % 123) + 1);+ original.set_block(x, i, z, (i as crate::world::block::Id % 123) + 1); } original.set_block_meta(4, 100, 4, 103, 2); original.set_block_meta(5, 100, 4, 102, 0b100);