voxels: generate ore veins and persist armor, hearts, dimension and boss kills
- Commit
384d800e80b41d0b44ceb9c92efe8162c8755e4e- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-05 03:56 UTC (4 months ago)
- Parents
f410094
Diff
games/voxels/src/main/rust/src/engine.rs
diff --git a/games/voxels/src/main/rust/src/engine.rs b/games/voxels/src/main/rust/src/engine.rsindex 353dbc2df0..071149e67f 100644--- a/games/voxels/src/main/rust/src/engine.rs+++ b/games/voxels/src/main/rust/src/engine.rs@@ -41,6 +41,19 @@ pub struct EngineState { pub portal_charge: f32, pub end_dragon_dead: bool, pub nether_wither_dead: bool,+ // Night tracking: `was_night` edge-detects the night->day flip so `night_survived` only latches+ // after the player has actually lived through a full night.+ pub was_night: bool,+ pub night_survived: bool,+}++// The world clock is offset by 60s so a fresh world opens at midday (day_t = 0.5 -> sun overhead).+const DAY_CYCLE: f32 = 120.0;+impl EngineState {+ pub fn world_time(&self) -> f32 { 60.0 + self.start_time.elapsed().as_secs_f32() }+ pub fn day_t(&self) -> f32 { (self.world_time() / DAY_CYCLE) % 1.0 }+ // The sun is below the horizon at both ends of the cycle (day_t = 0 is midnight).+ pub fn is_night(&self) -> bool { let t = self.day_t(); t < 0.25 || t > 0.75 } } unsafe impl Send for EngineState {}@@ -58,7 +71,8 @@ pub fn init_engine(files_dir: String, seed: u32) -> bool { let save_dir = files_dir.clone(); let player_save = crate::world::save::load_player(&save_dir); let had_save = player_save.is_some();- let (px, py, pz, yaw, pitch, inv) = if let Some(ps) = player_save {+ let progress = player_save.as_ref().map(|ps| ps.progress.clone()).unwrap_or_default();+ let (px, py, pz, yaw, pitch, inv) = if let Some(ps) = &player_save { let inv = { let mut inv = Inventory::default(); inv.selected = ps.inventory.selected.min(8);@@ -66,6 +80,9 @@ pub fn init_engine(files_dir: String, seed: u32) -> bool { inv.slots[i].id = slot.id; inv.slots[i].count = slot.count; }+ for (i, slot) in progress.armor.iter().enumerate().take(inv.armor.len()) {+ inv.armor[i] = crate::inventory::InvSlot { id: slot.id, count: slot.count };+ } inv.placed = ps.stats.placed; inv.broken = ps.stats.broken; inv@@ -78,8 +95,13 @@ pub fn init_engine(files_dir: String, seed: u32) -> bool { let mut player = Player::new(px, py, pz); player.yaw = yaw; player.pitch = pitch;+ if had_save {+ player.max_health = progress.max_health.clamp(crate::player::MIN_MAX_HEALTH, crate::player::CAP_MAX_HEALTH);+ player.health = player.max_health;+ } - let mut chunks = ChunkMap::new(seed, save_dir.clone());+ let dim = if progress.dim < 3 { progress.dim } else { 0 };+ let mut chunks = ChunkMap::new_dim(seed, dim_dir(&save_dir, dim), dim); chunks.ensure_radius(px as i32, pz as i32); if !had_save {@@ -91,6 +113,16 @@ pub fn init_engine(files_dir: String, seed: u32) -> bool { } } + let mut dim_pos = [Vec3::ZERO; 3];+ for (i, p) in progress.dim_pos.iter().enumerate().take(3) { dim_pos[i] = vec3(p[0], p[1], p[2]); }+ let mut dim_visited = [false; 3];+ for (i, v) in progress.dim_visited.iter().enumerate().take(3) { dim_visited[i] = *v; }+ dim_visited[dim as usize] = true;+ // Rewind the clock so the world resumes at the time of day it was saved at.+ let start_time = Instant::now()+ .checked_sub(std::time::Duration::from_secs_f32(progress.world_secs.clamp(0.0, 86_400.0)))+ .unwrap_or_else(Instant::now);+ *guard = Some(EngineState { chunks, player,@@ -99,7 +131,7 @@ pub fn init_engine(files_dir: String, seed: u32) -> bool { renderer: None, width: 0, height: 0,- start_time: Instant::now(),+ start_time, last_tick: Instant::now(), window_ptr: None, needs_resize: false,@@ -107,20 +139,22 @@ pub fn init_engine(files_dir: String, seed: u32) -> bool { mobs: Vec::new(), spawn_timer: 2.0, spawn_rng: seed ^ 0x9E3779B9,- respawn: None,+ respawn: progress.respawn.map(|p| vec3(p[0], p[1], p[2])), checkpoint_cd: 0.0, beacon_cd: 0.0, particles: Vec::new(), projectiles: Vec::new(),- dim: 0,+ dim, seed, stored: [None, None, None],- dim_pos: [Vec3::ZERO; 3],- dim_visited: [true, false, false],+ dim_pos,+ dim_visited, portal_armed: true, portal_charge: 0.0,- end_dragon_dead: false,- nether_wither_dead: false,+ end_dragon_dead: progress.end_dragon_dead,+ nether_wither_dead: progress.nether_wither_dead,+ was_night: false,+ night_survived: player_save.as_ref().map(|ps| ps.stats.night_seen).unwrap_or(false), }); INIT_DONE.store(true, Ordering::SeqCst); true@@ -146,6 +180,7 @@ where F: FnOnce(&mut EngineState) -> R { pub fn destroy_engine() { let mut guard = match engine_lock().lock() { Ok(g) => g, Err(_) => return, }; if let Some(mut state) = guard.take() {+ state.dim_pos[state.dim as usize] = state.player.pos; let ps = crate::world::save::PlayerSave { x: state.player.pos.x, y: state.player.pos.y,@@ -160,7 +195,18 @@ pub fn destroy_engine() { placed: state.inventory.placed, broken: state.inventory.broken, walked: state.player.walk_dist as i32,- night_seen: state.inventory.placed > 0 && state.start_time.elapsed().as_secs() > 60,+ night_seen: state.night_survived,+ },+ progress: crate::world::save::ProgressSave {+ armor: state.inventory.armor.iter().map(|s| crate::world::save::InvSlotSave{ id: s.id, count: s.count }).collect(),+ max_health: state.player.max_health,+ dim: state.dim,+ dim_pos: state.dim_pos.iter().map(|p| [p.x, p.y, p.z]).collect(),+ dim_visited: state.dim_visited.to_vec(),+ respawn: state.respawn.map(|p| [p.x, p.y, p.z]),+ end_dragon_dead: state.end_dragon_dead,+ nether_wither_dead: state.nether_wither_dead,+ world_secs: state.start_time.elapsed().as_secs_f32(), }, }; let _ = crate::world::save::save_player(&state.save_dir, &ps);@@ -269,6 +315,12 @@ pub fn tick_and_render() { let move_len = (input.move_forward*input.move_forward + input.move_right*input.move_right).sqrt(); if move_len > 0.9 { input_mut.sprint = true; } + // Latch "survived a night" on the night -> day flip, as long as the player is alive and in+ // the overworld (the Nether and End have no day cycle).+ let night_now = state.is_night();+ if state.was_night && !night_now && !state.player.dead && state.dim == 0 { state.night_survived = true; }+ state.was_night = night_now;+ // Elytra equipped in the chest slot enables gliding. state.player.elytra = state.inventory.armor[1].id == 188; state.player.tick(dt, &input_mut, &state.chunks);@@ -435,10 +487,7 @@ pub fn tick_and_render() { if id != 0 && Block::from_id(id).is_solid() { gy = Some(y); break; } } if let Some(gy) = gy {- let world_time = 60.0 + (Instant::now() - state.start_time).as_secs_f32();- let day_t = (world_time / 120.0) % 1.0;- // Sun is below the horizon (night) near the ends of the cycle; ~noon at day_t=0.5.- let night = day_t < 0.25 || day_t > 0.75;+ let night = state.is_night(); let kind = if state.dim == 1 { // Nether: hostile natives only (Ghasts are rarer floating threats). match (rand(&mut rng) * 8.0) as u32 { 0 => MobKind::Ghast, 1 | 2 => MobKind::Blaze, 3 | 4 => MobKind::WitherSkeleton, _ => MobKind::Zombie }@@ -500,6 +549,8 @@ pub fn tick_and_render() { append_projectiles(&mut entity_verts, &mut entity_indices, &state.projectiles, right, Vec3::Y); } + // Start at midday (day_t=0.5 -> sun overhead) so the world is lit when the app opens.+ let time = state.world_time(); if let Some(renderer) = state.renderer.as_mut() { if state.needs_resize { let w = state.width; let h = state.height;@@ -520,7 +571,6 @@ pub fn tick_and_render() { let vulkan_correction = Mat4::from_cols_array(&[1.0,0.0,0.0,0.0, 0.0,-1.0,0.0,0.0, 0.0,0.0,0.5,0.0, 0.0,0.0,0.5,1.0]); let view_proj = Mat4::from_rotation_z(pre_rot_angle) * vulkan_correction * proj * view; // Start at midday (day_t=0.5 -> sun overhead) so the world is lit when the app opens.- let time = 60.0 + (Instant::now() - state.start_time).as_secs_f32(); let eb = (eye.x.floor() as i32, eye.y.floor() as i32, eye.z.floor() as i32); let underwater = if state.chunks.get_block_world(eb.0, eb.1, eb.2) == 12 { 1.0 } else { 0.0 }; let nv = if state.player.night_vision() { 1.0 } else { 0.0 };@@ -566,9 +616,10 @@ 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 time = (Instant::now() - state.start_time).as_secs_f32();- let day_t = (time / 120.0) % 1.0;- let stats = serde_json::json!({ "placed": state.inventory.placed, "broken": state.inventory.broken, "walked": state.player.walk_dist as i32, "night": day_t > 0.5 && day_t < 0.92 }).to_string();+ let stats = serde_json::json!({+ "placed": state.inventory.placed, "broken": state.inventory.broken,+ "walked": state.player.walk_dist as i32, "night": state.night_survived,+ }).to_string(); let inv = state.inventory.to_json(); let effects: Vec<_> = state.player.effects.iter().map(|e| serde_json::json!({"k": e.kind.key(), "amp": e.amp, "t": e.secs.ceil() as i32})).collect(); let estus: i32 = state.inventory.slots.iter().filter(|s| s.id == 128).map(|s| s.count).sum();
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 a9f924daa2..6cb351990c 100644--- a/games/voxels/src/main/rust/src/world/generator.rs+++ b/games/voxels/src/main/rust/src/world/generator.rs@@ -278,10 +278,27 @@ pub struct TerrainGen { perlin_detail: Perlin, perlin_cave: Perlin, perlin_biome: Perlin,+ perlin_ore: Perlin, seed: u32, pub dim: u8, // 0 overworld, 1 nether, 2 end } +// 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);+const OVERWORLD_VEINS: [Vein; 8] = [+ (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+ (21, 601.0, 0.100, 0.72, 5, 30), // redstone+ (19, 137.0, 0.090, 0.68, 5, 74), // iron+ (18, 7.0, 0.080, 0.62, 5, 112), // coal โ large shallow seams+ (14, 311.0, 0.060, 0.70, 5, 100), // gravel pockets+ (16, 419.0, 0.055, 0.66, 5, 96), // diorite blobs+ (75, 733.0, 0.050, 0.66, 5, 34), // tuff blobs, deep+];+// Below this depth plain stone becomes deepslate (with a noisy transition band above it).+const DEEPSLATE_Y: i32 = 16;+ impl TerrainGen { pub fn new(seed: u32) -> Self { Self::new_dim(seed, 0) } pub fn new_dim(seed: u32, dim: u8) -> Self {@@ -290,6 +307,7 @@ impl TerrainGen { perlin_detail: Perlin::new(seed.wrapping_add(101)), perlin_cave: Perlin::new(seed.wrapping_add(202)), perlin_biome: Perlin::new(seed.wrapping_add(303)),+ perlin_ore: Perlin::new(seed.wrapping_add(404)), seed, dim, }@@ -427,6 +445,20 @@ impl TerrainGen { let depth_bias = ((60.0 - y) / 55.0).clamp(0.0, 1.0) as f64; // more/bigger caverns deeper cheese > (0.70 - 0.16 * depth_bias) }+ // 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 {+ 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; }+ }+ 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 {+ 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 }+ } // Underground biome for cave decoration, from depth + humidity. fn cave_kind(&self, wx: f64, wz: f64, y: i32) -> u8 { if y < 20 { return 0; } // deep dark@@ -539,7 +571,8 @@ impl TerrainGen { let stone_top = h.saturating_sub(4); for y in 5..stone_top { if !self.cave_at(wx, y as f64, wz) {- chunk.set_block(dx, y, dz, 1);+ let base = self.deep_base(wx, y as i32, wz);+ chunk.set_block(dx, y, dz, self.stone_at(&OVERWORLD_VEINS, wx, y as i32, wz, base)); } } let (surface_top, sub) = self.surface_blocks(biome, h, wx, wz);@@ -617,7 +650,7 @@ impl TerrainGen { while y + 1 < top { let here = chunk.get_block(dx, y, dz); let above = chunk.get_block(dx, y + 1, dz);- if here == 1 && above == 0 {+ if matches!(here, 1 | 57) && above == 0 { // Cave floor. let kind = self.cave_kind(wx, wz, y as i32); let mut hasher = DefaultHasher::new();@@ -628,7 +661,7 @@ impl TerrainGen { 1 => { if r < 40 { chunk.set_block(dx, y, dz, 71); } if r < 6 { chunk.set_block(dx, y + 1, dz, 80); } if r == 7 { chunk.set_block(dx, y + 1, dz, 77); } } // moss / azalea / glow _ => { if r < 25 { chunk.set_block(dx, y, dz, 70); } } // dripstone }- } else if here == 0 && above == 1 {+ } else if here == 0 && matches!(above, 1 | 57) { // Cave ceiling: hanging dripstone in dry caves. if self.cave_kind(wx, wz, y as i32) == 2 { let mut hasher = DefaultHasher::new();@@ -875,3 +908,40 @@ impl TerrainGen { }} } }++#[cfg(test)]+mod tests {+ use super::*;++ // Sanity-check ore rarity: sample the vein fields over a large volume and assert each ore lands+ // in a plausible band. Guards against a threshold tweak silently flooding or emptying the world.+ #[test]+ fn ore_density_is_plausible() {+ let gen = TerrainGen::new(12345);+ let mut counts = std::collections::HashMap::new();+ let mut total = 0u32;+ for wx in (-256..256).step_by(2) {+ for wz in (-256..256).step_by(2) {+ for y in (5..120).step_by(3) {+ let base = gen.deep_base(wx as f64, y, wz as f64);+ let id = gen.stone_at(&OVERWORLD_VEINS, wx as f64, y, wz as f64, base);+ total += 1;+ *counts.entry(id).or_insert(0u32) += 1;+ }+ }+ }+ let pct = |id: u8| 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),+ ] {+ let p = pct(id);+ println!("{name}: {p:.4}%");+ assert!(p >= lo && p <= hi, "{name} at {p:.4}% of stone, expected {lo}..{hi}%");+ }+ assert!(pct(57) > 5.0, "deepslate should fill the lower world, got {:.2}%", pct(57));+ }+}
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 09e9eeecc7..ef192c03cf 100644--- a/games/voxels/src/main/rust/src/world/save.rs+++ b/games/voxels/src/main/rust/src/world/save.rs@@ -50,7 +50,36 @@ pub fn load_chunk(base: &str, _pos: ChunkPos, chunk: &mut Chunk) -> std::io::Res } #[derive(serde::Serialize, serde::Deserialize, Default, Debug, Clone)]-pub struct PlayerSave { pub x: f32, pub y: f32, pub z: f32, pub yaw: f32, pub pitch: f32, pub inventory: InventorySave, pub stats: StatsSave }+pub struct PlayerSave {+ pub x: f32, pub y: f32, pub z: f32, pub yaw: f32, pub pitch: f32,+ pub inventory: InventorySave, pub stats: StatsSave,+ // Everything below was added after the first save format; `default` keeps old saves loadable.+ #[serde(default)] pub progress: ProgressSave,+}+// Progression that used to reset on every quit: equipped armor, earned max health, which dimension+// the player is standing in (and where they were in the others), and one-time boss kills.+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]+pub struct ProgressSave {+ #[serde(default)] pub armor: Vec<InvSlotSave>,+ #[serde(default = "default_max_health")] pub max_health: f32,+ #[serde(default)] pub dim: u8,+ #[serde(default)] pub dim_pos: Vec<[f32; 3]>,+ #[serde(default)] pub dim_visited: Vec<bool>,+ #[serde(default)] pub respawn: Option<[f32; 3]>,+ #[serde(default)] pub end_dragon_dead: bool,+ #[serde(default)] pub nether_wither_dead: bool,+ #[serde(default)] pub world_secs: f32,+}+fn default_max_health() -> f32 { 20.0 }+impl Default for ProgressSave {+ fn default() -> Self {+ Self {+ armor: Vec::new(), max_health: default_max_health(), dim: 0,+ dim_pos: Vec::new(), dim_visited: Vec::new(), respawn: None,+ end_dragon_dead: false, nether_wither_dead: false, world_secs: 0.0,+ }+ }+} #[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)]@@ -75,3 +104,44 @@ pub fn load_player(base: &str) -> Option<PlayerSave> { let s = fs::read_to_string(&path).ok()?; serde_json::from_str(&s).ok() }++#[cfg(test)]+mod tests {+ use super::*;++ // A player.json written before ProgressSave existed must still load, defaulting to a fresh+ // progression rather than failing and wiping the world.+ #[test]+ fn legacy_player_json_still_loads() {+ let legacy = r#"{"x":1.0,"y":80.0,"z":-3.0,"yaw":0.5,"pitch":0.0,+ "inventory":{"selected":2,"slots":[{"id":3,"count":64}]},+ "stats":{"placed":7,"broken":9,"walked":42,"night_seen":true}}"#;+ let ps: PlayerSave = serde_json::from_str(legacy).expect("legacy save must parse");+ assert_eq!(ps.inventory.selected, 2);+ assert_eq!(ps.stats.placed, 7);+ assert_eq!(ps.progress.max_health, 20.0);+ assert_eq!(ps.progress.dim, 0);+ assert!(!ps.progress.end_dragon_dead);+ }++ #[test]+ fn progress_round_trips() {+ let mut ps = PlayerSave::default();+ ps.progress.max_health = 34.0;+ ps.progress.dim = 1;+ ps.progress.armor = vec![InvSlotSave { id: 175, count: 400 }];+ ps.progress.dim_pos = vec![[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [0.0; 3]];+ ps.progress.dim_visited = vec![true, true, false];+ ps.progress.respawn = Some([8.0, 70.0, 9.0]);+ ps.progress.nether_wither_dead = true;+ ps.progress.world_secs = 372.5;+ let back: PlayerSave = serde_json::from_str(&serde_json::to_string(&ps).unwrap()).unwrap();+ assert_eq!(back.progress.max_health, 34.0);+ assert_eq!(back.progress.dim, 1);+ assert_eq!(back.progress.armor[0].id, 175);+ assert_eq!(back.progress.dim_visited, vec![true, true, false]);+ assert_eq!(back.progress.respawn, Some([8.0, 70.0, 9.0]));+ assert!(back.progress.nether_wither_dead);+ assert_eq!(back.progress.world_secs, 372.5);+ }+}
library/src/main/java/com/vayunmathur/library/sensor/OrientationManager.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/sensor/OrientationManager.kt b/library/src/main/java/com/vayunmathur/library/sensor/OrientationManager.ktsimilarity index 100%rename from astronomy/src/main/java/com/vayunmathur/astronomy/domain/sensor/OrientationManager.ktrename to library/src/main/java/com/vayunmathur/library/sensor/OrientationManager.kt
library/vision/src/main/rust/src/camera.rs
diff --git a/camera/src/main/rust/src/camera.rs b/library/vision/src/main/rust/src/camera.rssimilarity index 100%rename from camera/src/main/rust/src/camera.rsrename to library/vision/src/main/rust/src/camera.rs
library/vision/src/main/rust/src/features.rs
diff --git a/camera/src/main/rust/src/features.rs b/library/vision/src/main/rust/src/features.rssimilarity index 100%rename from camera/src/main/rust/src/features.rsrename to library/vision/src/main/rust/src/features.rs
library/vision/src/main/rust/src/geometry.rs
diff --git a/camera/src/main/rust/src/geometry.rs b/library/vision/src/main/rust/src/geometry.rssimilarity index 100%rename from camera/src/main/rust/src/geometry.rsrename to library/vision/src/main/rust/src/geometry.rs
library/vision/src/main/rust/src/imgbuf.rs
diff --git a/camera/src/main/rust/src/imgbuf.rs b/library/vision/src/main/rust/src/imgbuf.rssimilarity index 100%rename from camera/src/main/rust/src/imgbuf.rsrename to library/vision/src/main/rust/src/imgbuf.rs
library/vision/src/main/rust/src/linalg.rs
diff --git a/camera/src/main/rust/src/linalg.rs b/library/vision/src/main/rust/src/linalg.rssimilarity index 100%rename from camera/src/main/rust/src/linalg.rsrename to library/vision/src/main/rust/src/linalg.rs