voxels: budget chunk generation per frame; queue world taps (#ux-audit)
- Commit
e778a9c6cd42426a60cccd46027d9cb50e9d15ec- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-13 01:43 UTC (23 days ago)
- Parents
6a294f6
Symptom: walking across a chunk border hitched visibly, and taps to place or mine lagged; on slow frames the UI thread itself stalled. Root cause: - simulate() called ChunkMap::ensure_radius every frame, which generates every missing chunk in range at once: crossing a border creates a whole arc (~25 chunks at render distance 12) inside one frame. - MainActivity called placeBlockAt/breakBlockAt on the main thread; they take the engine lock, which the render thread holds for the whole frame including the GPU fence wait, so a tap could block the UI for a frame or more and its effect landed late. Fix: - ChunkMap::ensure_radius_budget generates at most 2 missing chunks per frame, nearest first, except the 3x3 around the player, which always loads at once so the ground is never missing. Unloading is unchanged (shared unload_beyond). Full ensure_radius stays for world load, dimension switches and respawn. - World taps are queued (new engine_actions.rs): a new native queueAction(kind, x, y) pushes to a small queue (capped at 32), the engine handles queued taps at the top of each frame (process_actions -> place_at / break_at, the bodies of place_block_at / break_block_at, which remain as thin wrappers), and results go to a result queue that the UI drains every 16 ms (drainActionResults) to play sounds and open crafting/furnace/ chest/trade/stonecutter screens. Taps, holds and the Use button all use it. User-visible effect: smooth exploring across chunk borders and responsive taps; the UI never waits on the renderer. Verification: new Rust tests chunk_generation_is_budgeted_per_frame (3x3 + budget per call, arrives over several frames) and queued_taps_are_answered_next_frame (nothing before the frame, results in order after it, delivered once). cargo test passes.
Diff
games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.ktindex d12977e189..de4093fdda 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt@@ -98,8 +98,13 @@ import com.vayunmathur.library.util.GameHubComposeHook import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch+import org.json.JSONArray import kotlin.math.PI +// Queued world-tap kinds (engine_part1.rs ACTION_*).+private const val ACTION_PLACE = 0+private const val ACTION_ACT = 1+ class MainActivity : ComponentActivity() { // Pause-menu state lives on the activity so onStop can pause the game: coming back from Home or // the lock screen lands on the pause menu instead of straight into whatever was attacking.@@ -193,6 +198,50 @@ class MainActivity : ComponentActivity() { } // Size of the world view in px; the Use button aims at its centre (the crosshair). var worldSize by remember { mutableStateOf(IntSize.Zero) }+ // Results of queued world taps: sounds, and the menus an interactive block opens.+ LaunchedEffect(Unit) {+ while (isActive && VoxelsNative.isAvailable) {+ val results = try { JSONArray(VoxelsNative.drainActionResults()) } catch (_: Exception) { JSONArray() }+ for (i in 0 until results.length()) {+ val r = results.optJSONArray(i) ?: continue+ val kind = r.optInt(0)+ val code = r.optInt(1)+ // Mine/attack/use: a sound when something happened. Place/interact below.+ if (kind == ACTION_ACT) {+ if (code == 1) com.vayunmathur.games.voxels.platform.SoundFx.playBreak()+ } else when (code) {+ 1 -> com.vayunmathur.games.voxels.platform.SoundFx.playPlace()+ 11 -> { invStartTab = 2; inventoryOpen = true } // crafting table+ 12, 14 -> { // furnace / blast furnace+ furnaceIsBlast = code == 14+ smeltJson = try { VoxelsNative.getSmeltJson() } catch (_: Exception) { "{}" }+ furnaceOpen = true+ }+ 13 -> { // jukebox: play the held disc (or stop)+ val inv = try { com.vayunmathur.games.voxels.ui.voxelsJson.decodeFromString<com.vayunmathur.games.voxels.ui.InventoryState>(inventoryJson) } catch (_: Exception) { null }+ val held = inv?.slots?.getOrNull(inv.selected)?.id ?: 0+ com.vayunmathur.games.voxels.platform.MusicFx.toggle(this@MainActivity, com.vayunmathur.games.voxels.ui.discTrack[held])+ }+ 15 -> stonecutterOpen = true // stonecutter+ // Every villager has its own profession and level, so the stall is+ // read fresh from the one that was tapped.+ 20 -> {+ tradesJson = try { VoxelsNative.getTradesJson() } catch (_: Exception) { "{}" }+ tradeOpen = true+ }+ 30 -> { // chest+ containerJson = try { VoxelsNative.getContainerJson() } catch (_: Exception) { """{"slots":[]}""" }+ chestOpen = true+ // Online clients mirror host state: ask for the real contents.+ if (online) try { VoxelsNative.netRequestContainer() } catch (_: Exception) {}+ com.vayunmathur.games.voxels.platform.SoundFx.playPlace()+ }+ 41 -> com.vayunmathur.games.voxels.platform.SoundFx.playPlace() // ignited a portal+ }+ }+ delay(16)+ }+ } var achievements by remember { mutableStateOf<VoxelsAchievements?>(null) } val newAchievement by (achievements?.newAchievement?.collectAsState() ?: remember { mutableStateOf(null) }) @@ -389,39 +438,10 @@ class MainActivity : ComponentActivity() { VoxelsNative.onLookDelta(-dx * k, (if (settings.invertY) -dy else dy) * k) } catch (_: Exception) {} },- onPlace = { off -> if (!paused) try {- val code = VoxelsNative.placeBlockAt(off.x, off.y)- when (code) {- 1 -> com.vayunmathur.games.voxels.platform.SoundFx.playPlace()- 11 -> { invStartTab = 2; inventoryOpen = true } // crafting table- 12, 14 -> { // furnace / blast furnace- furnaceIsBlast = code == 14- smeltJson = try { VoxelsNative.getSmeltJson() } catch (_: Exception) { "{}" }- furnaceOpen = true- }- 13 -> { // jukebox: play the held disc (or stop)- val inv = try { com.vayunmathur.games.voxels.ui.voxelsJson.decodeFromString<com.vayunmathur.games.voxels.ui.InventoryState>(inventoryJson) } catch (_: Exception) { null }- val held = inv?.slots?.getOrNull(inv.selected)?.id ?: 0- com.vayunmathur.games.voxels.platform.MusicFx.toggle(this@MainActivity, com.vayunmathur.games.voxels.ui.discTrack[held])- }- 15 -> stonecutterOpen = true // stonecutter- // Every villager has its own profession and level, so the stall is- // read fresh from the one that was tapped.- 20 -> {- tradesJson = try { VoxelsNative.getTradesJson() } catch (_: Exception) { "{}" }- tradeOpen = true- }- 30 -> { // chest- containerJson = try { VoxelsNative.getContainerJson() } catch (_: Exception) { """{"slots":[]}""" }- chestOpen = true- // Online clients mirror host state: ask for the real contents.- if (online) try { VoxelsNative.netRequestContainer() } catch (_: Exception) {}- com.vayunmathur.games.voxels.platform.SoundFx.playPlace()- }- 41 -> com.vayunmathur.games.voxels.platform.SoundFx.playPlace() // ignited a portal- }- } catch (_: Exception) {} },- onBreak = { off -> if (!paused) try { if (VoxelsNative.breakBlockAt(off.x, off.y)) com.vayunmathur.games.voxels.platform.SoundFx.playBreak() } catch (_: Exception) {} }+ // Taps are queued for the engine's next frame (never blocking on its lock);+ // results come back through the drain loop below.+ onPlace = { off -> if (!paused) try { VoxelsNative.queueAction(ACTION_PLACE, off.x, off.y) } catch (_: Exception) {} },+ onBreak = { off -> if (!paused) try { VoxelsNative.queueAction(ACTION_ACT, off.x, off.y) } catch (_: Exception) {} } ) } @@ -474,9 +494,7 @@ class MainActivity : ComponentActivity() { // Use/attack whatever is under the crosshair, repeating while held. UseButton(label = stringResource(R.string.use)) { if (VoxelsNative.isAvailable && !paused && worldSize.width > 0) try {- if (VoxelsNative.breakBlockAt(worldSize.width / 2f, worldSize.height / 2f)) {- com.vayunmathur.games.voxels.platform.SoundFx.playBreak()- }+ VoxelsNative.queueAction(ACTION_ACT, worldSize.width / 2f, worldSize.height / 2f) } catch (_: Exception) {} } }
games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/VoxelsNative.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/VoxelsNative.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/VoxelsNative.ktindex d0a0536e9d..e5637df10a 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/VoxelsNative.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/VoxelsNative.kt@@ -45,6 +45,11 @@ object VoxelsNative { external fun setSneak(on: Boolean) external fun toggleFly() external fun breakBlockAt(x: Float, y: Float): Boolean+ // Queue a world tap for the engine's next frame (never blocks): kind 0 place/interact, 1 mine/+ // attack/use; results come back from drainActionResults as [[kind, code], ...] (place codes as+ // for placeBlockAt below, act 1 = something happened).+ external fun queueAction(kind: Int, x: Float, y: Float)+ external fun drainActionResults(): String // 0 = nothing, 1 = placed, 11 crafting table, 12 furnace, 13 jukebox, 14 blast furnace, // 20 villager trade, 30 chest opened, 41 portal lit. external fun placeBlockAt(x: Float, y: Float): Int
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 6ee956ccf2..9d6fb33916 100644--- a/games/voxels/src/main/rust/src/engine.rs+++ b/games/voxels/src/main/rust/src/engine.rs@@ -426,6 +426,7 @@ pub fn rebuild_chunk_meshes(state: &mut EngineState, chunk_pos: crate::world::ch include!("engine_lifecycle.rs"); include!("engine_part1.rs");+include!("engine_actions.rs"); include!("engine_part2.rs"); include!("engine_part3.rs"); include!("engine_part4.rs");
games/voxels/src/main/rust/src/engine_actions.rs
diff --git a/games/voxels/src/main/rust/src/engine_actions.rs b/games/voxels/src/main/rust/src/engine_actions.rsnew file mode 100644index 0000000000..d620c42fa3--- /dev/null+++ b/games/voxels/src/main/rust/src/engine_actions.rs@@ -0,0 +1,38 @@+// ---- Queued world taps ----+// The UI used to call place/break straight into the engine on the main thread, blocking on the engine+// lock for up to a whole frame (the render thread holds it through the GPU fence wait), which made+// taps lag and could stall the UI. Taps are now queued and handled at the start of the next frame;+// their result codes come back through a second queue the UI drains.+/// Place / interact (tap). Result: the `place_block_at` code.+pub const ACTION_PLACE: i32 = 0;+/// Mine / attack / use (hold, Use button). Result: 1 if something happened, else 0.+pub const ACTION_ACT: i32 = 1;+static ACTIONS: Mutex<Vec<(i32, f32, f32)>> = Mutex::new(Vec::new());+static RESULTS: Mutex<Vec<(i32, i32)>> = Mutex::new(Vec::new());+/// Most queued taps kept; a backlog beyond this (engine stalled) drops the oldest.+const MAX_QUEUED_ACTIONS: usize = 32;++/// Queues a world tap at screen pixel (`x`, `y`) for the next frame. Never blocks on the engine.+pub fn queue_action(kind: i32, x: f32, y: f32) {+ if let Ok(mut q) = ACTIONS.lock() {+ if q.len() >= MAX_QUEUED_ACTIONS { let _ = q.remove(0); }+ q.push((kind, x, y));+ }+}++/// Results of handled taps since the last call, as `[[kind, code], ...]` JSON.+pub fn drain_action_results() -> String {+ let taken: Vec<(i32, i32)> = RESULTS.lock().map(|mut r| std::mem::take(&mut *r)).unwrap_or_default();+ serde_json::to_string(&taken).unwrap_or_else(|_| "[]".into())+}++/// Handles every queued tap against the current world (called at the top of each frame).+fn process_actions(state: &mut EngineState) {+ let taken: Vec<(i32, f32, f32)> = ACTIONS.lock().map(|mut q| std::mem::take(&mut *q)).unwrap_or_default();+ if taken.is_empty() { return; }+ let results: Vec<(i32, i32)> = taken.into_iter().map(|(kind, x, y)| {+ let code = if kind == ACTION_PLACE { place_at(state, x, y) } else { i32::from(break_at(state, x, y)) };+ (kind, code)+ }).collect();+ if let Ok(mut r) = RESULTS.lock() { r.extend(results); }+}
games/voxels/src/main/rust/src/engine_part1.rs
diff --git a/games/voxels/src/main/rust/src/engine_part1.rs b/games/voxels/src/main/rust/src/engine_part1.rsindex faa4166a42..57737218df 100644--- a/games/voxels/src/main/rust/src/engine_part1.rs+++ b/games/voxels/src/main/rust/src/engine_part1.rs@@ -1,3 +1,6 @@+/// Chunks generated per frame while exploring (beyond the player's immediate neighbourhood).+const CHUNK_GEN_BUDGET: usize = 2;+ // World mode, chosen when the world was created. Creative (the default, and what every world // created before modes existed gets) allows flight and the free block catalog; survival doesn't. static CREATIVE: AtomicBool = AtomicBool::new(true);@@ -44,6 +47,7 @@ fn step(state: &mut EngineState, dt: f32, paused: bool) { // Drain any decrypted, already-authorized network messages before simulating this frame, so // the net thread never contends for the engine lock (mirrors the publish_ui/CACHE pattern). crate::net::apply_inbound(state);+ process_actions(state); if !paused { simulate(state, dt); } render_frame(state); }@@ -165,7 +169,8 @@ fn simulate(state: &mut EngineState, dt: f32) { let px = state.player.pos.x as i32; let pz = state.player.pos.z as i32;- state.chunks.ensure_radius(px, pz);+ // A few new chunks per frame (nearest first); the player's own neighbourhood always loads.+ state.chunks.ensure_radius_budget(px, pz, CHUNK_GEN_BUDGET, 1); // --- Mobs: AI/physics tick, spawn/despawn near the player. ---
games/voxels/src/main/rust/src/engine_part4.rs
diff --git a/games/voxels/src/main/rust/src/engine_part4.rs b/games/voxels/src/main/rust/src/engine_part4.rsindex fcba78eed9..f00b99d7d9 100644--- a/games/voxels/src/main/rust/src/engine_part4.rs+++ b/games/voxels/src/main/rust/src/engine_part4.rs@@ -256,16 +256,20 @@ fn do_place(state: &mut EngineState, origin: Vec3, dir: Vec3) -> bool { false } -pub fn break_block_at(px: f32, py: f32) -> bool {- with_engine(|state| {- let (o, d) = screen_ray(state, px, py);- do_break(state, o, d)- }).unwrap_or(false)+pub fn break_block_at(px: f32, py: f32) -> bool { with_engine(|state| break_at(state, px, py)).unwrap_or(false) }++/// Mine / attack / use along the ray through screen pixel (`px`, `py`).+fn break_at(state: &mut EngineState, px: f32, py: f32) -> bool {+ let (o, d) = screen_ray(state, px, py);+ do_break(state, o, d) } // Returns: 0 = nothing, 1 = placed a block, 10+menu = tapped an interactive block (open its menu).-pub fn place_block_at(px: f32, py: f32) -> i32 {- with_engine(|state| {+pub fn place_block_at(px: f32, py: f32) -> i32 { with_engine(|state| place_at(state, px, py)).unwrap_or(0) }++/// Place / interact along the ray through screen pixel (`px`, `py`); see `place_block_at`.+fn place_at(state: &mut EngineState, px: f32, py: f32) -> i32 {+ { let (o, d) = screen_ray(state, px, py); // Tapping a villager opens trade; tapping an interactive block opens its menu — unless // sneaking, which places instead.@@ -321,5 +325,5 @@ pub fn place_block_at(px: f32, py: f32) -> i32 { } } if do_place(state, o, d) { 1 } else { 0 }- }).unwrap_or(0)+ } }
games/voxels/src/main/rust/src/engine_part6.rs
diff --git a/games/voxels/src/main/rust/src/engine_part6.rs b/games/voxels/src/main/rust/src/engine_part6.rsindex f5798298ab..82a4ffeeef 100644--- a/games/voxels/src/main/rust/src/engine_part6.rs+++ b/games/voxels/src/main/rust/src/engine_part6.rs@@ -138,4 +138,36 @@ mod state_tests { assert!(p.vel.normalize().dot(dir) > 0.999, "thrown along {:?}, not the touch ray {:?}", p.vel, dir); assert_eq!(s.inventory.slots[0].count, 3); }) }++ // Walking into new terrain generates a few chunks per frame, nearest first, never the ground+ // under the player late.+ #[test]+ fn chunk_generation_is_budgeted_per_frame() { big_stack(|| {+ let mut s = small_state("budget");+ s.chunks.render_distance = 4;+ let far_x = 16 * 40;+ let made = s.chunks.ensure_radius_budget(far_x, 0, 2, 1);+ // The 3x3 around the player always loads (9), nothing beyond the budget.+ assert!((9..=11).contains(&made), "generated {made} chunks in one frame");+ assert!(s.chunks.get(crate::world::chunk::ChunkPos::from_world(far_x, 0)).is_some(), "the player's chunk is missing");+ let mut frames = 1;+ while s.chunks.missing_in_radius(far_x, 0) > 0 { s.chunks.ensure_radius_budget(far_x, 0, 2, 1); frames += 1; assert!(frames < 100); }+ assert!(frames > 5, "everything arrived at once ({frames} frames)");+ }) }++ // Taps are queued and answered on the next frame instead of blocking the UI thread on the lock.+ #[test]+ fn queued_taps_are_answered_next_frame() { big_stack(|| {+ let _serial = GLOBAL_ENGINE_TEST.lock();+ let mut s = small_state("taps");+ s.width = 800; s.height = 400;+ let _ = drain_action_results();+ queue_action(ACTION_PLACE, 400.0, 200.0);+ queue_action(ACTION_ACT, 400.0, 200.0);+ assert_eq!(drain_action_results(), "[]", "answered before the frame ran");+ step(&mut s, 0.016, true);+ let r: Vec<(i32, i32)> = serde_json::from_str(&drain_action_results()).unwrap_or_default();+ assert_eq!(r.iter().map(|(k, _)| *k).collect::<Vec<_>>(), vec![ACTION_PLACE, ACTION_ACT]);+ assert_eq!(drain_action_results(), "[]", "results are delivered once");+ }) } }
games/voxels/src/main/rust/src/lib_jni_input.rs
diff --git a/games/voxels/src/main/rust/src/lib_jni_input.rs b/games/voxels/src/main/rust/src/lib_jni_input.rsindex d1f56dc0bf..c0658a9b0c 100644--- a/games/voxels/src/main/rust/src/lib_jni_input.rs+++ b/games/voxels/src/main/rust/src/lib_jni_input.rs@@ -105,3 +105,33 @@ pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_onLoo ) { input::add_look_delta(dyaw, dpitch); }++/// JNI bridge for `VoxelsNative#queueAction`: queue a world tap (0 place/interact, 1 mine/attack/+/// use) at screen pixel (`x`, `y`) for the next frame. Never blocks on the engine.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_queueAction<'l>(+ _env: EnvUnowned<'l>,+ _class: JClass<'l>,+ kind: jint,+ x: jfloat,+ y: jfloat,+) {+ engine::queue_action(kind, x, y);+}++/// JNI bridge for `VoxelsNative#drainActionResults`: `[[kind, code], ...]` for taps handled since the+/// last call.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_drainActionResults<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+) -> jstring {+ env.with_env(|env| -> jni::errors::Result<jstring> {+ let null = std::ptr::null_mut();+ match env.new_string(engine::drain_action_results()) {+ Ok(s) => Ok(s.into_raw()),+ Err(_) => Ok(null),+ }+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}
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 7abc0cc9f9..56ea632b40 100644--- a/games/voxels/src/main/rust/src/world/chunk_map.rs+++ b/games/voxels/src/main/rust/src/world/chunk_map.rs@@ -78,7 +78,10 @@ impl ChunkMap { if dx*dx + dz*dz > rd*rd + 2 { continue; } self.load_or_gen(ChunkPos(cpos.0 + dx, cpos.1 + dz)); }}- let unload_dist = rd + 2;+ self.unload_beyond(cpos);+ }+ fn unload_beyond(&mut self, cpos: ChunkPos) {+ let unload_dist = self.render_distance + 2; let to_unload: Vec<ChunkPos> = self.chunks.keys().copied() .filter(|p| (p.0 - cpos.0).abs() > unload_dist || (p.1 - cpos.1).abs() > unload_dist) .collect();@@ -91,6 +94,41 @@ impl ChunkMap { } } }+ /// Like `ensure_radius`, but generates at most `max_new` missing chunks per call (nearest first),+ /// so walking into new terrain spreads generation over frames instead of generating a whole arc+ /// of chunks inside one frame. Chunks within `always` of the centre are loaded regardless, so the+ /// ground under the player is never missing.+ pub fn ensure_radius_budget(&mut self, center_x: i32, center_z: i32, max_new: usize, always: i32) -> usize {+ let cpos = ChunkPos::from_world(center_x, center_z);+ let rd = self.render_distance;+ let mut missing: Vec<(i32, i32, ChunkPos)> = Vec::new();+ for dz in -rd..=rd { for dx in -rd..=rd {+ let d2 = dx*dx + dz*dz;+ if d2 > rd*rd + 2 { continue; }+ let p = ChunkPos(cpos.0 + dx, cpos.1 + dz);+ if !self.chunks.contains_key(&p) { missing.push((d2, dx.abs().max(dz.abs()), p)); }+ }}+ missing.sort_by_key(|(d2, _, _)| *d2);+ let mut made = 0;+ for (_, ring, p) in missing {+ if made >= max_new && ring > always { continue; }+ self.load_or_gen(p);+ made += 1;+ }+ self.unload_beyond(cpos);+ made+ }+ /// Chunks that are in range but not loaded yet.+ pub fn missing_in_radius(&self, center_x: i32, center_z: i32) -> usize {+ let cpos = ChunkPos::from_world(center_x, center_z);+ let rd = self.render_distance;+ let mut n = 0;+ for dz in -rd..=rd { for dx in -rd..=rd {+ if dx*dx + dz*dz > rd*rd + 2 { continue; }+ if !self.chunks.contains_key(&ChunkPos(cpos.0 + dx, cpos.1 + dz)) { n += 1; }+ }}+ n+ } pub fn chunks_iter(&self) -> impl Iterator<Item=(&ChunkPos, &Chunk)> { self.chunks.iter() } /// Is this world point inside solid block geometry? Slabs and stairs fill only part of their