voxels: more blocks + inventory
- Commit
49a80b902233893b7775163be6c5a73f9364fafa- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-29 16:52 UTC (4 months ago)
- Parents
1495bbc
Diff
games/voxels/src/main/AndroidManifest.xml
diff --git a/games/voxels/src/main/AndroidManifest.xml b/games/voxels/src/main/AndroidManifest.xmlindex fd21f7ddc5..a4270d91d1 100644--- a/games/voxels/src/main/AndroidManifest.xml+++ b/games/voxels/src/main/AndroidManifest.xml@@ -11,7 +11,7 @@ android:theme="@style/Theme.General"> <activity android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"- android:name=".MainActivity"+ android:name=".MenuActivity" android:screenOrientation="sensorLandscape" android:exported="true" android:theme="@style/Theme.General">@@ -20,5 +20,11 @@ <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>+ <activity+ android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+ android:name=".MainActivity"+ android:screenOrientation="sensorLandscape"+ android:exported="false"+ android:theme="@style/Theme.General" /> </application> </manifest>
games/voxels/src/main/assets/block/birch_leaves.png
diff --git a/games/voxels/src/main/assets/block/birch_leaves.png b/games/voxels/src/main/assets/block/birch_leaves.pngnew file mode 100644index 0000000000..1ea855f93bBinary files /dev/null and b/games/voxels/src/main/assets/block/birch_leaves.png differ
games/voxels/src/main/assets/block/birch_log_top.png
diff --git a/games/voxels/src/main/assets/block/birch_log_top.png b/games/voxels/src/main/assets/block/birch_log_top.pngnew file mode 100644index 0000000000..cdeca39e08Binary files /dev/null and b/games/voxels/src/main/assets/block/birch_log_top.png differ
games/voxels/src/main/assets/block/birch_planks.png
diff --git a/games/voxels/src/main/assets/block/birch_planks.png b/games/voxels/src/main/assets/block/birch_planks.pngnew file mode 100644index 0000000000..539987f3c2Binary files /dev/null and b/games/voxels/src/main/assets/block/birch_planks.png differ
games/voxels/src/main/assets/block/bookshelf.png
diff --git a/games/voxels/src/main/assets/block/bookshelf.png b/games/voxels/src/main/assets/block/bookshelf.pngnew file mode 100644index 0000000000..e2ab6ce6adBinary files /dev/null and b/games/voxels/src/main/assets/block/bookshelf.png differ
games/voxels/src/main/assets/block/coal_ore.png
diff --git a/games/voxels/src/main/assets/block/coal_ore.png b/games/voxels/src/main/assets/block/coal_ore.pngnew file mode 100644index 0000000000..7252ab2c94Binary files /dev/null and b/games/voxels/src/main/assets/block/coal_ore.png differ
games/voxels/src/main/assets/block/crafting_table_top.png
diff --git a/games/voxels/src/main/assets/block/crafting_table_top.png b/games/voxels/src/main/assets/block/crafting_table_top.pngnew file mode 100644index 0000000000..62b46a3a82Binary files /dev/null and b/games/voxels/src/main/assets/block/crafting_table_top.png differ
games/voxels/src/main/assets/block/diamond_block.png
diff --git a/games/voxels/src/main/assets/block/diamond_block.png b/games/voxels/src/main/assets/block/diamond_block.pngnew file mode 100644index 0000000000..4d6b8d68b1Binary files /dev/null and b/games/voxels/src/main/assets/block/diamond_block.png differ
games/voxels/src/main/assets/block/diamond_ore.png
diff --git a/games/voxels/src/main/assets/block/diamond_ore.png b/games/voxels/src/main/assets/block/diamond_ore.pngnew file mode 100644index 0000000000..fb1c4e367eBinary files /dev/null and b/games/voxels/src/main/assets/block/diamond_ore.png differ
games/voxels/src/main/assets/block/diorite.png
diff --git a/games/voxels/src/main/assets/block/diorite.png b/games/voxels/src/main/assets/block/diorite.pngnew file mode 100644index 0000000000..4e9d498b41Binary files /dev/null and b/games/voxels/src/main/assets/block/diorite.png differ
games/voxels/src/main/assets/block/emerald_block.png
diff --git a/games/voxels/src/main/assets/block/emerald_block.png b/games/voxels/src/main/assets/block/emerald_block.pngnew file mode 100644index 0000000000..4f1020066cBinary files /dev/null and b/games/voxels/src/main/assets/block/emerald_block.png differ
games/voxels/src/main/assets/block/emerald_ore.png
diff --git a/games/voxels/src/main/assets/block/emerald_ore.png b/games/voxels/src/main/assets/block/emerald_ore.pngnew file mode 100644index 0000000000..fc5553e867Binary files /dev/null and b/games/voxels/src/main/assets/block/emerald_ore.png differ
games/voxels/src/main/assets/block/furnace_top.png
diff --git a/games/voxels/src/main/assets/block/furnace_top.png b/games/voxels/src/main/assets/block/furnace_top.pngnew file mode 100644index 0000000000..62874777e0Binary files /dev/null and b/games/voxels/src/main/assets/block/furnace_top.png differ
games/voxels/src/main/assets/block/gravel.png
diff --git a/games/voxels/src/main/assets/block/gravel.png b/games/voxels/src/main/assets/block/gravel.pngnew file mode 100644index 0000000000..8ed6b93942Binary files /dev/null and b/games/voxels/src/main/assets/block/gravel.png differ
games/voxels/src/main/assets/block/iron_block.png
diff --git a/games/voxels/src/main/assets/block/iron_block.png b/games/voxels/src/main/assets/block/iron_block.pngnew file mode 100644index 0000000000..78b0c1cd9aBinary files /dev/null and b/games/voxels/src/main/assets/block/iron_block.png differ
games/voxels/src/main/assets/block/iron_ore.png
diff --git a/games/voxels/src/main/assets/block/iron_ore.png b/games/voxels/src/main/assets/block/iron_ore.pngnew file mode 100644index 0000000000..c53ef4af59Binary files /dev/null and b/games/voxels/src/main/assets/block/iron_ore.png differ
games/voxels/src/main/assets/block/mossy_cobblestone.png
diff --git a/games/voxels/src/main/assets/block/mossy_cobblestone.png b/games/voxels/src/main/assets/block/mossy_cobblestone.pngnew file mode 100644index 0000000000..44c37294b8Binary files /dev/null and b/games/voxels/src/main/assets/block/mossy_cobblestone.png differ
games/voxels/src/main/assets/block/netherrack.png
diff --git a/games/voxels/src/main/assets/block/netherrack.png b/games/voxels/src/main/assets/block/netherrack.pngnew file mode 100644index 0000000000..97cd32fb8fBinary files /dev/null and b/games/voxels/src/main/assets/block/netherrack.png differ
games/voxels/src/main/assets/block/polished_diorite.png
diff --git a/games/voxels/src/main/assets/block/polished_diorite.png b/games/voxels/src/main/assets/block/polished_diorite.pngnew file mode 100644index 0000000000..049c6b51b9Binary files /dev/null and b/games/voxels/src/main/assets/block/polished_diorite.png differ
games/voxels/src/main/assets/block/redstone_ore.png
diff --git a/games/voxels/src/main/assets/block/redstone_ore.png b/games/voxels/src/main/assets/block/redstone_ore.pngnew file mode 100644index 0000000000..552a3b4c2fBinary files /dev/null and b/games/voxels/src/main/assets/block/redstone_ore.png differ
games/voxels/src/main/assets/block/spruce_leaves.png
diff --git a/games/voxels/src/main/assets/block/spruce_leaves.png b/games/voxels/src/main/assets/block/spruce_leaves.pngnew file mode 100644index 0000000000..df7fc3e5efBinary files /dev/null and b/games/voxels/src/main/assets/block/spruce_leaves.png differ
games/voxels/src/main/assets/block/spruce_log_top.png
diff --git a/games/voxels/src/main/assets/block/spruce_log_top.png b/games/voxels/src/main/assets/block/spruce_log_top.pngnew file mode 100644index 0000000000..0f11faaca5Binary files /dev/null and b/games/voxels/src/main/assets/block/spruce_log_top.png differ
games/voxels/src/main/assets/block/spruce_planks.png
diff --git a/games/voxels/src/main/assets/block/spruce_planks.png b/games/voxels/src/main/assets/block/spruce_planks.pngnew file mode 100644index 0000000000..fa743a37b2Binary files /dev/null and b/games/voxels/src/main/assets/block/spruce_planks.png differ
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 39e60f1a8d..775242568b 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@@ -12,6 +12,7 @@ import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color+import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import com.vayunmathur.games.voxels.ui.*@@ -26,11 +27,16 @@ class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge()+ // World to load: passed by MenuActivity. Fall back to a default world if launched directly.+ val worldDir = intent.getStringExtra("world_dir")+ ?: java.io.File(filesDir, "worlds/default").apply { mkdirs() }.absolutePath+ val worldSeed = intent.getIntExtra("world_seed", 0xB10CCA) if (VoxelsNative.isAvailable) {- try { VoxelsNative.nativeInit(filesDir.absolutePath) } catch (e: Exception) {+ try { VoxelsNative.nativeInit(worldDir, worldSeed) } catch (e: Exception) { android.util.Log.e("VoxelsMain", "nativeInit failed", e) } }+ com.vayunmathur.games.voxels.util.SoundFx.init(this) setContent { VoxelsTheme { var inventoryJson by remember { mutableStateOf("""{"selected":0,"slots":[{"id":3,"count":64},{"id":2,"count":64},{"id":1,"count":64},{"id":4,"count":16},{"id":10,"count":32},{"id":6,"count":32},{"id":7,"count":16},{"id":8,"count":16},{"id":9,"count":16}]}""") }@@ -38,6 +44,12 @@ class MainActivity : ComponentActivity() { var showDebug by remember { mutableStateOf(true) } var flying by remember { mutableStateOf(false) } var sneaking by remember { mutableStateOf(false) }+ var inventoryOpen by remember { mutableStateOf(false) }+ var paused by remember { mutableStateOf(false) }+ val activity = LocalContext.current as? android.app.Activity+ var invStartTab by remember { mutableStateOf(0) }+ var recipesJson by remember { mutableStateOf("[]") }+ LaunchedEffect(Unit) { if (VoxelsNative.isAvailable) try { recipesJson = VoxelsNative.getRecipesJson() } catch (_: Exception) {} } var achievementsManager by remember { mutableStateOf<VoxelsAchievementsManager?>(null) } val newAchievement by (achievementsManager?.newAchievement?.collectAsState() ?: remember { mutableStateOf(null) }) @@ -91,23 +103,19 @@ class MainActivity : ComponentActivity() { } } - // World interaction: tap a block face to place adjacent, long-press to break.- // This layer sits above the world surface but below the joysticks/hotbar, so those- // controls consume their own touches while taps elsewhere hit the world.- if (VoxelsNative.isAvailable) {- Box(Modifier.fillMaxSize().pointerInput(Unit) {- detectTapGestures(- onTap = { off -> try { VoxelsNative.placeBlockAt(off.x, off.y) } catch (_: Exception) {} },- onLongPress = { off -> try { VoxelsNative.breakBlockAt(off.x, off.y) } catch (_: Exception) {} }- )- })- }-- // Look: drag anywhere on the right half to spawn a floating look stick at the touch.+ // Fullscreen world interaction + floating look: drag on the right half looks around;+ // tap places a block and long-press breaks one — on either half of the screen. if (VoxelsNative.isAvailable) { FloatingLookJoystick(- modifier = Modifier.align(Alignment.CenterEnd).fillMaxHeight().fillMaxWidth(0.5f),- onLookRate = { ry, rp -> try { VoxelsNative.onLookInput(ry, rp) } catch (_: Exception) {} }+ modifier = Modifier.fillMaxSize(),+ onLookRate = { ry, rp -> try { VoxelsNative.onLookInput(ry, rp) } catch (_: Exception) {} },+ onPlace = { off -> try {+ when (VoxelsNative.placeBlockAt(off.x, off.y)) {+ 1 -> com.vayunmathur.games.voxels.util.SoundFx.playPlace()+ 11, 12 -> { invStartTab = 2; inventoryOpen = true } // crafting table / furnace+ }+ } catch (_: Exception) {} },+ onBreak = { off -> try { if (VoxelsNative.breakBlockAt(off.x, off.y)) com.vayunmathur.games.voxels.util.SoundFx.playBreak() } catch (_: Exception) {} } ) } @@ -158,13 +166,15 @@ class MainActivity : ComponentActivity() { Box(Modifier.align(Alignment.BottomCenter).padding(bottom = 12.dp)) { Hotbar(inventoryJson = inventoryJson,- onSelect = { slot -> if (VoxelsNative.isAvailable) try { VoxelsNative.selectSlot(slot) } catch (_: Exception) {} })+ onSelect = { slot -> if (VoxelsNative.isAvailable) try { VoxelsNative.selectSlot(slot) } catch (_: Exception) {} },+ onOpenInventory = { invStartTab = 0; inventoryOpen = true }) } Row(Modifier.align(Alignment.TopCenter).fillMaxWidth().padding(top = 36.dp, start = 12.dp, end = 12.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.Top) { Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {+ IconButton(onClick = { paused = true }) { IconMenu() } IconButton(onClick = { showDebug = !showDebug }) { IconSettings() } } }@@ -176,6 +186,28 @@ class MainActivity : ComponentActivity() { AchievementNotification(ach) { achievementsManager?.dismissNotification() } } }++ if (inventoryOpen && VoxelsNative.isAvailable) {+ InventoryOverlay(inventoryJson = inventoryJson, recipesJson = recipesJson, onClose = { inventoryOpen = false }, startTab = invStartTab)+ }++ if (paused) {+ Box(+ Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.6f))+ .pointerInput(Unit) { detectTapGestures { } }, // swallow taps behind the menu+ contentAlignment = Alignment.Center+ ) {+ Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(14.dp)) {+ Text("Paused", style = MaterialTheme.typography.headlineMedium, color = Color.White)+ Button(onClick = { paused = false }, modifier = Modifier.width(240.dp)) { Text("Resume") }+ Button(onClick = {+ // onDestroy() saves the world and tears down the engine; finishing+ // returns to MenuActivity (still on the back stack).+ activity?.finish()+ }, modifier = Modifier.width(240.dp)) { Text("Save & Quit to Menu") }+ }+ }+ } } } }
games/voxels/src/main/java/com/vayunmathur/games/voxels/MenuActivity.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/MenuActivity.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/MenuActivity.ktnew file mode 100644index 0000000000..481ffe3f4a--- /dev/null+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/MenuActivity.kt@@ -0,0 +1,84 @@+package com.vayunmathur.games.voxels++import android.content.Intent+import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import com.vayunmathur.games.voxels.ui.MenuScreen+import com.vayunmathur.games.voxels.ui.WorldCreatorScreen+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.ui.Surface+import com.vayunmathur.games.voxels.util.WorldInfo+import com.vayunmathur.games.voxels.util.WorldManager++// Launcher screen: lists saved worlds and hosts the world creator. Playing a world starts+// MainActivity (the game) with the world's save directory + seed passed as intent extras.+class MenuActivity : ComponentActivity() {+ // Bumped on each onResume so the world list reloads when returning from the game+ // (keeps last-played ordering fresh).+ private var resumeTick by mutableStateOf(0)++ override fun onResume() {+ super.onResume()+ resumeTick+++ }++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ enableEdgeToEdge()+ setContent {+ // Standard app theme (Material You / system colors), matching the other apps — the menu+ // isn't part of the in-game world so it shouldn't use the green Voxels palette.+ DynamicTheme {+ var creating by remember { mutableStateOf(false) }+ var worlds by remember { mutableStateOf(WorldManager.listWorlds(this)) }+ LaunchedEffect(resumeTick) { worlds = WorldManager.listWorlds(this@MenuActivity) }++ Surface(Modifier.fillMaxSize()) {+ Box(Modifier.fillMaxSize()) {+ if (creating) {+ WorldCreatorScreen(+ onBack = { creating = false },+ onCreate = { name, seedText ->+ val seed = WorldManager.resolveSeed(seedText)+ val world = WorldManager.createWorld(this@MenuActivity, name, seed, System.currentTimeMillis())+ worlds = WorldManager.listWorlds(this@MenuActivity)+ creating = false+ play(world)+ }+ )+ } else {+ MenuScreen(+ worlds = worlds,+ onPlay = { play(it) },+ onDelete = { world ->+ WorldManager.deleteWorld(this@MenuActivity, world.id)+ worlds = WorldManager.listWorlds(this@MenuActivity)+ },+ onCreate = { creating = true }+ )+ }+ }+ }+ }+ }+ }++ private fun play(world: WorldInfo) {+ WorldManager.touch(this, world.id, System.currentTimeMillis())+ startActivity(Intent(this, MainActivity::class.java).apply {+ putExtra("world_dir", world.dir)+ putExtra("world_seed", world.meta.seed)+ putExtra("world_name", world.meta.name)+ })+ }+}
games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/Hotbar.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/Hotbar.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/Hotbar.ktindex 7099d57c90..fb1c29ea14 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/Hotbar.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/Hotbar.kt@@ -32,32 +32,49 @@ data class InvSlot(val id: Int, val count: Int) @Serializable data class InventoryState(val selected: Int = 0, val slots: List<InvSlot> = List(9) { InvSlot(0, 0) }) -private val blockNames = mapOf(+val blockNames = mapOf( 0 to "·", 1 to "Stone", 2 to "Dirt", 3 to "Grass", 4 to "Wood", 5 to "Leaves",- 6 to "Sand", 7 to "Glass", 8 to "Cobble", 9 to "Brick", 10 to "Planks", 11 to "Snow", 12 to "Water", 13 to "Bedrock"+ 6 to "Sand", 7 to "Glass", 8 to "Cobble", 9 to "Brick", 10 to "Planks", 11 to "Snow", 12 to "Water", 13 to "Bedrock",+ 14 to "Gravel", 15 to "Mossy", 16 to "Diorite", 17 to "Pol. Diorite", 18 to "Coal Ore", 19 to "Iron Ore",+ 20 to "Diamond Ore", 21 to "Redstone", 22 to "Emerald Ore", 23 to "Iron", 24 to "Diamond", 25 to "Emerald",+ 26 to "Birch Log", 27 to "Birch Plank", 28 to "Birch Leaf", 29 to "Spruce Log", 30 to "Spruce Plank", 31 to "Spruce Leaf",+ 32 to "Netherrack", 33 to "Bookshelf", 34 to "Crafting Table", 35 to "Furnace" ) -private val blockIconFile = mapOf(- 1 to "deepslate.png",- 2 to "dirt.png",- 3 to "grass_block_top.png",- 4 to "oak_log_top.png",- 5 to "oak_leaves.png",- 6 to "sand.png",- 7 to "ice.png",- 8 to "cobblestone.png",- 9 to "bricks.png",- 10 to "oak_planks.png",- 11 to "packed_ice.png",- 12 to "blue_ice.png",- 13 to "bedrock.png"+val blockIconFile = mapOf(+ 1 to "deepslate.png", 2 to "dirt.png", 3 to "grass_block_top.png", 4 to "oak_log_top.png", 5 to "oak_leaves.png",+ 6 to "sand.png", 7 to "ice.png", 8 to "cobblestone.png", 9 to "bricks.png", 10 to "oak_planks.png",+ 11 to "packed_ice.png", 12 to "blue_ice.png", 13 to "bedrock.png",+ 14 to "gravel.png", 15 to "mossy_cobblestone.png", 16 to "diorite.png", 17 to "polished_diorite.png",+ 18 to "coal_ore.png", 19 to "iron_ore.png", 20 to "diamond_ore.png", 21 to "redstone_ore.png", 22 to "emerald_ore.png",+ 23 to "iron_block.png", 24 to "diamond_block.png", 25 to "emerald_block.png",+ 26 to "birch_log_top.png", 27 to "birch_planks.png", 28 to "birch_leaves.png",+ 29 to "spruce_log_top.png", 30 to "spruce_planks.png", 31 to "spruce_leaves.png",+ 32 to "netherrack.png", 33 to "bookshelf.png", 34 to "crafting_table_top.png", 35 to "furnace_top.png" ) +// Creative catalog, split into tabs.+val catalogNatural = listOf(3, 2, 1, 6, 14, 16, 17, 15, 4, 5, 26, 28, 29, 31, 11, 32, 13)+val catalogOres = listOf(18, 19, 20, 21, 22, 23, 24, 25)+val catalogBuilding = listOf(10, 27, 30, 8, 9, 7, 33, 34, 35)++@Composable+fun rememberBlockIcon(id: Int): androidx.compose.ui.graphics.ImageBitmap? {+ val ctx = LocalContext.current+ return remember(id) {+ val fileName = blockIconFile[id] ?: return@remember null+ try {+ android.graphics.BitmapFactory.decodeStream(ctx.assets.open("block/$fileName"))?.asImageBitmap()+ } catch (_: Exception) { null }+ }+}+ @Composable fun Hotbar( inventoryJson: String, onSelect: (Int) -> Unit,- modifier: Modifier = Modifier+ modifier: Modifier = Modifier,+ onOpenInventory: () -> Unit = {} ) { val state = try { Json { ignoreUnknownKeys = true }.decodeFromString<InventoryState>(inventoryJson)@@ -69,7 +86,7 @@ fun Hotbar( modifier = modifier.fillMaxWidth().padding(8.dp), horizontalArrangement = Arrangement.spacedBy(4.dp, Alignment.CenterHorizontally) ) {- state.slots.forEachIndexed { idx, slot ->+ state.slots.take(9).forEachIndexed { idx, slot -> val isSel = idx == state.selected val iconBitmap = remember(slot.id) { val fileName = blockIconFile[slot.id]@@ -103,6 +120,14 @@ fun Hotbar( } } }+ // Single inventory "…" tile at the end of the hotbar (opens the full inventory).+ Box(+ modifier = Modifier.size(52.dp).clip(RoundedCornerShape(8.dp))+ .background(Color.Black.copy(alpha = 0.55f))+ .border(1.dp, Color.White.copy(alpha = 0.18f), RoundedCornerShape(8.dp))+ .clickable { onOpenInventory() },+ contentAlignment = Alignment.Center+ ) { Text("…", color = Color.White, style = MaterialTheme.typography.titleLarge) } } }
games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/InventoryScreen.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/InventoryScreen.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/InventoryScreen.ktnew file mode 100644index 0000000000..144ff9b6c8--- /dev/null+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/InventoryScreen.kt@@ -0,0 +1,265 @@+package com.vayunmathur.games.voxels.ui++import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.detectDragGestures+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.foundation.layout.*+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.*+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.FilterQuality+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.boundsInWindow+import androidx.compose.ui.layout.onGloballyPositioned+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.games.voxels.util.VoxelsNative+import com.vayunmathur.library.ui.Text+import kotlinx.serialization.json.Json+import kotlin.math.roundToInt++private data class DragState(val from: Int, val pos: Offset, val id: Int, val count: Int)++@Composable+fun InventoryOverlay(inventoryJson: String, recipesJson: String, onClose: () -> Unit, startTab: Int = 0) {+ val inv = remember(inventoryJson) {+ try { Json { ignoreUnknownKeys = true }.decodeFromString<InventoryState>(inventoryJson) } catch (_: Exception) { InventoryState() }+ }+ val slots = inv.slots+ var leftTab by remember { mutableStateOf(startTab) } // 0 Inventory, 1 Outfit, 2 Crafting+ var catTab by remember { mutableStateOf(0) }+ val bounds = remember { mutableStateMapOf<Int, Rect>() }+ var drag by remember { mutableStateOf<DragState?>(null) }+ val density = LocalDensity.current++ Box(+ Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.6f))+ .pointerInput(Unit) { detectTapGestures { onClose() } }+ ) {+ Row(+ Modifier.align(Alignment.Center).fillMaxWidth(0.94f).fillMaxHeight(0.86f)+ .clip(RoundedCornerShape(14.dp)).background(Color(0xF01A1E1A))+ .pointerInput(Unit) { detectTapGestures { } } // swallow taps on the panel+ .padding(12.dp),+ horizontalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ // Left tabs (top→bottom: Crafting, Outfit, Inventory).+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {+ TabButton("Crafting", leftTab == 2) { leftTab = 2 }+ TabButton("Outfit", leftTab == 1) { leftTab = 1 }+ TabButton("Inventory", leftTab == 0) { leftTab = 0 }+ Spacer(Modifier.weight(1f))+ TabButton("Close", false) { onClose() }+ }++ // Center content.+ Box(Modifier.weight(1f).fillMaxHeight(), contentAlignment = Alignment.TopCenter) {+ when (leftTab) {+ 0 -> InventoryGrid(slots, bounds, onDragStart = { i, off ->+ val s = slots.getOrNull(i) ?: InvSlot(0, 0)+ if (s.id != 0) drag = DragState(i, (bounds[i]?.topLeft ?: Offset.Zero) + off, s.id, s.count)+ }, onDragMove = { d -> drag = drag?.let { it.copy(pos = it.pos + d) } },+ onDragEnd = {+ drag?.let { dr ->+ val target = bounds.entries.firstOrNull { it.value.contains(dr.pos) }?.key+ if (target != null && target != dr.from) try { VoxelsNative.moveItem(dr.from, target) } catch (_: Exception) {}+ }+ drag = null+ }, onDragCancel = { drag = null })+ 1 -> Text("Outfit — coming soon", color = Color.White.copy(0.7f), modifier = Modifier.padding(24.dp))+ else -> CraftingTable(recipesJson)+ }+ }++ // Right catalog (creative): tap a block to add a stack.+ Column(Modifier.width(236.dp).fillMaxHeight(), horizontalAlignment = Alignment.CenterHorizontally) {+ Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {+ TabButton("Natural", catTab == 0) { catTab = 0 }+ TabButton("Ores", catTab == 1) { catTab = 1 }+ TabButton("Build", catTab == 2) { catTab = 2 }+ }+ Spacer(Modifier.height(8.dp))+ val cat = when (catTab) { 0 -> catalogNatural; 1 -> catalogOres; else -> catalogBuilding }+ CatalogGrid(cat) { id -> try { VoxelsNative.giveBlock(id) } catch (_: Exception) {} }+ }+ }++ // Floating dragged item.+ drag?.let { d ->+ val icon = rememberBlockIcon(d.id)+ val half = with(density) { 24.dp.toPx() }+ Box(Modifier.offset { IntOffset((d.pos.x - half).roundToInt(), (d.pos.y - half).roundToInt()) }.size(48.dp)) {+ if (icon != null) Image(bitmap = icon, contentDescription = null, modifier = Modifier.fillMaxSize(), filterQuality = FilterQuality.None)+ }+ }+ }+}++@Composable+private fun TabButton(label: String, selected: Boolean, onClick: () -> Unit) {+ Box(+ Modifier.width(96.dp).height(40.dp).clip(RoundedCornerShape(8.dp))+ .background(if (selected) Color(0xFF3A6B3A) else Color.White.copy(alpha = 0.10f))+ .border(1.dp, Color.White.copy(alpha = if (selected) 0.5f else 0.15f), RoundedCornerShape(8.dp))+ .clickable { onClick() },+ contentAlignment = Alignment.Center+ ) { Text(label, color = Color.White.copy(0.95f), fontSize = 14.sp, fontWeight = FontWeight.SemiBold) }+}++@Composable+private fun SlotBox(index: Int, slot: InvSlot, bounds: MutableMap<Int, Rect>, drag: Boolean,+ onDragStart: (Int, Offset) -> Unit, onDragMove: (Offset) -> Unit,+ onDragEnd: () -> Unit, onDragCancel: () -> Unit) {+ val icon = rememberBlockIcon(slot.id)+ Box(+ Modifier.size(46.dp).onGloballyPositioned { bounds[index] = it.boundsInWindow() }+ .clip(RoundedCornerShape(6.dp)).background(Color.Black.copy(alpha = 0.45f))+ .border(1.dp, Color.White.copy(alpha = 0.12f), RoundedCornerShape(6.dp))+ .pointerInput(index) {+ detectDragGestures(+ onDragStart = { off -> onDragStart(index, off) },+ onDrag = { change, amount -> change.consume(); onDragMove(amount) },+ onDragEnd = { onDragEnd() },+ onDragCancel = { onDragCancel() }+ )+ },+ contentAlignment = Alignment.Center+ ) {+ if (slot.id != 0) {+ if (icon != null) Image(bitmap = icon, contentDescription = null, modifier = Modifier.size(30.dp), filterQuality = FilterQuality.None)+ else Text(blockNames[slot.id]?.take(2) ?: "", color = Color.White, fontSize = 10.sp)+ if (slot.count > 1) Box(Modifier.align(Alignment.BottomEnd)) { Text("${slot.count}", color = Color.White, fontSize = 10.sp) }+ }+ }+}++@Composable+private fun InventoryGrid(slots: List<InvSlot>, bounds: MutableMap<Int, Rect>,+ onDragStart: (Int, Offset) -> Unit, onDragMove: (Offset) -> Unit,+ onDragEnd: () -> Unit, onDragCancel: () -> Unit) {+ fun cell(i: Int) = @Composable { SlotBox(i, slots.getOrNull(i) ?: InvSlot(0, 0), bounds, true, onDragStart, onDragMove, onDragEnd, onDragCancel) }+ Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Text("Inventory — drag to rearrange", color = Color.White.copy(0.6f), fontSize = 12.sp)+ Spacer(Modifier.height(4.dp))+ for (row in 0 until 3) {+ Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {+ for (col in 0 until 9) { cell(9 + row * 9 + col)() }+ }+ }+ Spacer(Modifier.height(10.dp))+ Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {+ for (col in 0 until 9) { cell(col)() } // hotbar+ }+ }+}++@Composable+private fun CatalogGrid(ids: List<Int>, onPick: (Int) -> Unit) {+ Column(+ Modifier.fillMaxHeight().verticalScroll(rememberScrollState()),+ verticalArrangement = Arrangement.spacedBy(4.dp), horizontalAlignment = Alignment.CenterHorizontally+ ) {+ ids.chunked(4).forEach { rowIds ->+ Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {+ rowIds.forEach { id ->+ val icon = rememberBlockIcon(id)+ Box(+ Modifier.size(48.dp).clip(RoundedCornerShape(6.dp)).background(Color.Black.copy(alpha = 0.4f))+ .border(1.dp, Color.White.copy(alpha = 0.15f), RoundedCornerShape(6.dp))+ .clickable { onPick(id) },+ contentAlignment = Alignment.Center+ ) {+ if (icon != null) Image(bitmap = icon, contentDescription = blockNames[id], modifier = Modifier.size(32.dp), filterQuality = FilterQuality.None)+ else Text(blockNames[id]?.take(2) ?: "", color = Color.White, fontSize = 10.sp)+ }+ }+ }+ }+ }+}++@Composable+private fun GridCell(id: Int, count: Int) {+ val icon = if (id != 0) rememberBlockIcon(id) else null+ Box(+ Modifier.size(50.dp).clip(RoundedCornerShape(6.dp)).background(Color.Black.copy(alpha = 0.4f))+ .border(1.dp, Color.White.copy(alpha = 0.15f), RoundedCornerShape(6.dp)),+ contentAlignment = Alignment.Center+ ) {+ if (icon != null) Image(bitmap = icon, contentDescription = null, modifier = Modifier.size(34.dp), filterQuality = FilterQuality.None)+ if (count > 1) Box(Modifier.align(Alignment.BottomEnd).padding(1.dp)) { Text("$count", color = Color.White, fontSize = 11.sp) }+ }+}++@Composable+private fun CraftingTable(recipesJson: String) {+ val recipes = remember(recipesJson) {+ try {+ val arr = org.json.JSONArray(recipesJson)+ (0 until arr.length()).map { i ->+ val o = arr.getJSONObject(i)+ Recipe(o.getInt("in"), o.getInt("inN"), o.getInt("out"), o.getInt("outN"))+ }+ } catch (_: Exception) { emptyList() }+ }+ var sel by remember { mutableStateOf(0) }+ val r = recipes.getOrNull(sel)+ Row(Modifier.fillMaxSize(), horizontalArrangement = Arrangement.spacedBy(16.dp)) {+ // Left: product picker.+ Column(Modifier.width(160.dp).fillMaxHeight().verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Text("Products", color = Color.White.copy(0.6f), fontSize = 12.sp)+ recipes.forEachIndexed { i, rec ->+ val icon = rememberBlockIcon(rec.outId)+ Row(+ Modifier.fillMaxWidth().clip(RoundedCornerShape(6.dp))+ .background(if (i == sel) Color(0xFF3A6B3A) else Color.White.copy(alpha = 0.08f))+ .clickable { sel = i }.padding(6.dp),+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)+ ) {+ if (icon != null) Image(bitmap = icon, contentDescription = null, modifier = Modifier.size(26.dp), filterQuality = FilterQuality.None)+ Text(blockNames[rec.outId] ?: "", color = Color.White.copy(0.95f), fontSize = 12.sp)+ }+ }+ }+ // Right: the crafting table (2x2 grid) with the selected recipe placed + its product.+ Column(Modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(12.dp)) {+ Text("Crafting Table", color = Color.White.copy(0.6f), fontSize = 12.sp)+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {+ for (row in 0 until 2) {+ Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {+ for (col in 0 until 2) {+ val idx = row * 2 + col+ if (r == null) { GridCell(0, 0) }+ else if (r.inN > 4) { GridCell(if (idx == 0) r.inId else 0, if (idx == 0) r.inN else 0) }+ else { GridCell(if (idx < r.inN) r.inId else 0, 0) }+ }+ }+ }+ }+ Text("→", color = Color.White.copy(0.8f), fontSize = 24.sp)+ GridCell(r?.outId ?: 0, r?.outN ?: 0)+ }+ Box(+ Modifier.clip(RoundedCornerShape(8.dp)).background(Color(0xFF3A6B3A))+ .clickable { if (r != null) try { VoxelsNative.craft(sel) } catch (_: Exception) {} }+ .padding(horizontal = 24.dp, vertical = 8.dp)+ ) { Text("Craft", color = Color.White, fontSize = 15.sp, fontWeight = FontWeight.SemiBold) }+ }+ }+}++private data class Recipe(val inId: Int, val inN: Int, val outId: Int, val outN: Int)
games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/Joystick.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/Joystick.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/Joystick.ktindex 707d182d28..693fe84175 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/Joystick.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/Joystick.kt@@ -121,32 +121,48 @@ private fun lookCurve(v: Float): Float { return if (v < 0f) -shaped else shaped } -// A floating look joystick: drag anywhere within this region and the stick materializes at the touch-// origin, rotating the camera by displacement from there (rate-based, same curve as the move stick).-// Non-drag touches are not consumed, so taps fall through to the world (place/break).+// Fullscreen world-interaction + floating look stick. A drag that STARTS on the right half spawns a+// look joystick at the touch origin; taps place a block and long-presses break one — anywhere on the+// screen (so build/break works on both halves). Move joystick / buttons sit above this and take their+// own touches. @Composable-fun FloatingLookJoystick(modifier: Modifier, onLookRate: (Float, Float) -> Unit) {+fun FloatingLookJoystick(+ modifier: Modifier,+ onLookRate: (Float, Float) -> Unit,+ onPlace: (Offset) -> Unit,+ onBreak: (Offset) -> Unit,+) { var origin by remember { mutableStateOf(Offset.Zero) } var knob by remember { mutableStateOf(Offset.Zero) } var active by remember { mutableStateOf(false) }- Box(modifier.pointerInput(Unit) {- val maxR = 70.dp.toPx()- detectDragGestures(- onDragStart = { off -> origin = off; knob = Offset.Zero; active = true; onLookRate(0f, 0f) },- onDrag = { change, drag ->- change.consume()- val nk = knob + drag- val dist = hypot(nk.x, nk.y)- knob = if (dist > maxR && dist > 0.001f) nk * (maxR / dist) else nk- val nx = knob.x / maxR- val ny = knob.y / maxR- val mag = sqrt(nx * nx + ny * ny)- if (mag < 0.1f) onLookRate(0f, 0f) else onLookRate(lookCurve(-nx), lookCurve(ny))- },- onDragEnd = { active = false; knob = Offset.Zero; onLookRate(0f, 0f) },- onDragCancel = { active = false; knob = Offset.Zero; onLookRate(0f, 0f) }- )- }) {+ Box(modifier+ .pointerInput(Unit) {+ val maxR = 70.dp.toPx()+ detectDragGestures(+ onDragStart = { off -> if (off.x > size.width / 2f) { origin = off; knob = Offset.Zero; active = true; onLookRate(0f, 0f) } },+ onDrag = { change, drag ->+ if (active) {+ change.consume()+ val nk = knob + drag+ val dist = hypot(nk.x, nk.y)+ knob = if (dist > maxR && dist > 0.001f) nk * (maxR / dist) else nk+ val nx = knob.x / maxR+ val ny = knob.y / maxR+ val mag = sqrt(nx * nx + ny * ny)+ if (mag < 0.1f) onLookRate(0f, 0f) else onLookRate(lookCurve(-nx), lookCurve(ny))+ }+ },+ onDragEnd = { if (active) { active = false; knob = Offset.Zero; onLookRate(0f, 0f) } },+ onDragCancel = { if (active) { active = false; knob = Offset.Zero; onLookRate(0f, 0f) } }+ )+ }+ .pointerInput(Unit) {+ detectTapGestures(+ onTap = { off -> onPlace(off) },+ onLongPress = { off -> onBreak(off) }+ )+ }+ ) { if (active) { Canvas(Modifier.fillMaxSize()) { drawCircle(color = Color.White.copy(alpha = 0.18f), radius = 70.dp.toPx(), center = origin)
games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/MenuScreens.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/MenuScreens.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/MenuScreens.ktnew file mode 100644index 0000000000..34c477624e--- /dev/null+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/MenuScreens.kt@@ -0,0 +1,134 @@+package com.vayunmathur.games.voxels.ui++import android.text.format.DateUtils+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.widthIn+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.text.input.KeyboardType+import androidx.compose.ui.unit.dp+import com.vayunmathur.games.voxels.util.WorldInfo+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.IconPlay+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Text++@Composable+fun MenuScreen(+ worlds: List<WorldInfo>,+ onPlay: (WorldInfo) -> Unit,+ onDelete: (WorldInfo) -> Unit,+ onCreate: () -> Unit,+) {+ Box(Modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.TopCenter) {+ Column(+ Modifier.fillMaxWidth().widthIn(max = 560.dp),+ horizontalAlignment = Alignment.CenterHorizontally+ ) {+ Text("Voxels", style = MaterialTheme.typography.displaySmall, color = MaterialTheme.colorScheme.primary)+ Text("Select a world", style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onBackground)+ Spacer(Modifier.height(20.dp))++ if (worlds.isEmpty()) {+ Box(Modifier.fillMaxWidth().height(220.dp), contentAlignment = Alignment.Center) {+ Text("No worlds yet — create one to start.", color = MaterialTheme.colorScheme.onBackground)+ }+ } else {+ LazyColumn(+ Modifier.fillMaxWidth().weight(1f, fill = false),+ verticalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ items(worlds, key = { it.id }) { world ->+ WorldRow(world = world, onPlay = { onPlay(world) }, onDelete = { onDelete(world) })+ }+ }+ Spacer(Modifier.height(16.dp))+ }++ Button(onClick = onCreate, modifier = Modifier.fillMaxWidth()) {+ Text("Create New World")+ }+ }+ }+}++@Composable+private fun WorldRow(world: WorldInfo, onPlay: () -> Unit, onDelete: () -> Unit) {+ Card(modifier = Modifier.fillMaxWidth().clickable { onPlay() }) {+ Row(+ Modifier.fillMaxWidth().padding(16.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(Modifier.weight(1f)) {+ Text(world.meta.name, style = MaterialTheme.typography.titleLarge, color = MaterialTheme.colorScheme.onSurface)+ val last = DateUtils.getRelativeTimeSpanString(world.meta.lastPlayed).toString()+ Text("Seed: ${world.meta.seed} • $last", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f))+ }+ IconButton(onClick = onDelete) { IconDelete(tint = MaterialTheme.colorScheme.error) }+ IconButton(onClick = onPlay) { IconPlay(tint = MaterialTheme.colorScheme.primary) }+ }+ }+}++@Composable+fun WorldCreatorScreen(+ onBack: () -> Unit,+ onCreate: (name: String, seedText: String) -> Unit,+) {+ var name by remember { mutableStateOf("") }+ var seed by remember { mutableStateOf("") }+ Box(Modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.TopCenter) {+ Column(+ Modifier.fillMaxWidth().widthIn(max = 480.dp),+ horizontalAlignment = Alignment.CenterHorizontally+ ) {+ Text("Create World", style = MaterialTheme.typography.headlineMedium, color = MaterialTheme.colorScheme.primary)+ Spacer(Modifier.height(24.dp))+ OutlinedTextField(+ value = name,+ onValueChange = { name = it },+ label = { Text("World name") },+ singleLine = true,+ modifier = Modifier.fillMaxWidth()+ )+ Spacer(Modifier.height(12.dp))+ OutlinedTextField(+ value = seed,+ onValueChange = { seed = it },+ label = { Text("Seed") },+ placeholder = { Text("Leave blank for random") },+ supportingText = { Text("A number, or any text (hashed to a seed).") },+ singleLine = true,+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),+ modifier = Modifier.fillMaxWidth()+ )+ Spacer(Modifier.height(24.dp))+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ OutlinedButton(onClick = onBack, modifier = Modifier.weight(1f)) { Text("Cancel") }+ Button(onClick = { onCreate(name, seed) }, modifier = Modifier.weight(1f)) { Text("Create & Play") }+ }+ }+ }+}
games/voxels/src/main/java/com/vayunmathur/games/voxels/util/SoundFx.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/SoundFx.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/SoundFx.ktnew file mode 100644index 0000000000..17f8628254--- /dev/null+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/SoundFx.kt@@ -0,0 +1,62 @@+package com.vayunmathur.games.voxels.util++import android.content.Context+import android.media.SoundPool+import java.io.File+import kotlin.math.exp+import kotlin.math.sin+import kotlin.random.Random++// Lightweight procedural SFX: synthesizes short break/place blips into cached WAVs and plays them via+// SoundPool. No audio assets required. All calls are best-effort (never throw into the UI).+object SoundFx {+ private const val SR = 22050+ private var pool: SoundPool? = null+ private var breakId = 0+ private var placeId = 0++ fun init(ctx: Context) {+ if (pool != null) return+ try {+ val p = SoundPool.Builder().setMaxStreams(4).build()+ breakId = p.load(wav(ctx, "vox_break.wav", gen(150.0, 0.14, 0.55, true)), 1)+ placeId = p.load(wav(ctx, "vox_place.wav", gen(520.0, 0.07, 0.4, false)), 1)+ pool = p+ } catch (_: Throwable) {}+ }++ fun playBreak() { try { pool?.play(breakId, 0.6f, 0.6f, 1, 0, 1f) } catch (_: Throwable) {} }+ fun playPlace() { try { pool?.play(placeId, 0.6f, 0.6f, 1, 0, 1f) } catch (_: Throwable) {} }++ // Decaying tone (or noise burst); mono 16-bit PCM.+ private fun gen(freq: Double, dur: Double, amp: Double, noise: Boolean): ShortArray {+ val n = (SR * dur).toInt()+ val out = ShortArray(n)+ for (i in 0 until n) {+ val t = i.toDouble() / SR+ val env = exp(-t * 20.0)+ val s = if (noise) (Random.nextDouble() * 2.0 - 1.0) else sin(2.0 * Math.PI * freq * t)+ out[i] = (s * env * amp * Short.MAX_VALUE).toInt().coerceIn(-32768, 32767).toShort()+ }+ return out+ }++ private fun wav(ctx: Context, name: String, pcm: ShortArray): String {+ val f = File(ctx.cacheDir, name)+ val dataLen = pcm.size * 2+ val bytes = ByteArray(44 + dataLen)+ fun le32(off: Int, v: Int) { bytes[off]=(v and 0xff).toByte(); bytes[off+1]=((v shr 8) and 0xff).toByte(); bytes[off+2]=((v shr 16) and 0xff).toByte(); bytes[off+3]=((v shr 24) and 0xff).toByte() }+ fun le16(off: Int, v: Int) { bytes[off]=(v and 0xff).toByte(); bytes[off+1]=((v shr 8) and 0xff).toByte() }+ "RIFF".toByteArray().copyInto(bytes, 0)+ le32(4, 36 + dataLen)+ "WAVE".toByteArray().copyInto(bytes, 8)+ "fmt ".toByteArray().copyInto(bytes, 12)+ le32(16, 16); le16(20, 1); le16(22, 1)+ le32(24, SR); le32(28, SR * 2); le16(32, 2); le16(34, 16)+ "data".toByteArray().copyInto(bytes, 36)+ le32(40, dataLen)+ for (i in pcm.indices) le16(44 + i * 2, pcm[i].toInt())+ f.writeBytes(bytes)+ return f.absolutePath+ }+}
games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsNative.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsNative.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsNative.ktindex c33fb2aeb4..34dae200b1 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsNative.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsNative.kt@@ -12,7 +12,7 @@ object VoxelsNative { Log.e("VoxelsNative", "System.loadLibrary(voxels_engine) failed", t) false }- external fun nativeInit(filesDir: String): Boolean+ external fun nativeInit(filesDir: String, seed: Int): Boolean external fun surfaceCreated(surface: Surface) external fun surfaceChanged(width: Int, height: Int) external fun surfaceDestroyed()@@ -24,8 +24,13 @@ object VoxelsNative { external fun setSneak(on: Boolean) external fun toggleFly() external fun breakBlockAt(x: Float, y: Float): Boolean- external fun placeBlockAt(x: Float, y: Float): Boolean+ // 0 = nothing, 1 = placed, 11 = open crafting, 12 = open furnace+ external fun placeBlockAt(x: Float, y: Float): Int external fun selectSlot(slot: Int)+ external fun moveItem(from: Int, to: Int)+ external fun giveBlock(id: Int)+ external fun craft(recipe: Int): Boolean+ external fun getRecipesJson(): String external fun getInventoryJson(): String external fun getDebugJson(): String external fun getStatsJson(): String
games/voxels/src/main/java/com/vayunmathur/games/voxels/util/WorldManager.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/WorldManager.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/WorldManager.ktnew file mode 100644index 0000000000..62caae9151--- /dev/null+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/WorldManager.kt@@ -0,0 +1,81 @@+package com.vayunmathur.games.voxels.util++import android.content.Context+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json+import java.io.File+import kotlin.random.Random++// On-disk metadata for a single world, stored as `world.json` inside the world's directory.+@Serializable+data class WorldMeta(+ val name: String,+ val seed: Int,+ val created: Long,+ val lastPlayed: Long,+)++// A world plus its resolved id (directory name) and absolute save path. Not persisted directly.+data class WorldInfo(+ val id: String,+ val dir: String,+ val meta: WorldMeta,+)++object WorldManager {+ private val json = Json { ignoreUnknownKeys = true; prettyPrint = true }++ private fun worldsRoot(ctx: Context): File = File(ctx.filesDir, "worlds").apply { mkdirs() }++ // All worlds, most-recently-played first.+ fun listWorlds(ctx: Context): List<WorldInfo> {+ val root = worldsRoot(ctx)+ val dirs = root.listFiles { f -> f.isDirectory } ?: return emptyList()+ return dirs.mapNotNull { dir ->+ val metaFile = File(dir, "world.json")+ if (!metaFile.exists()) return@mapNotNull null+ try {+ val meta = json.decodeFromString<WorldMeta>(metaFile.readText())+ WorldInfo(id = dir.name, dir = dir.absolutePath, meta = meta)+ } catch (_: Exception) { null }+ }.sortedByDescending { it.meta.lastPlayed }+ }++ // Resolve a free-text seed field to an Int: a number is used directly; other text is hashed;+ // blank produces a fresh random seed.+ fun resolveSeed(text: String): Int {+ val t = text.trim()+ if (t.isEmpty()) return Random.nextInt()+ t.toIntOrNull()?.let { return it }+ t.toLongOrNull()?.let { return it.toInt() }+ return t.hashCode()+ }++ fun createWorld(ctx: Context, name: String, seed: Int, now: Long): WorldInfo {+ val root = worldsRoot(ctx)+ // Unique directory id derived from the creation time (worlds can share display names).+ var id = "w_$now"+ var i = 1+ while (File(root, id).exists()) { id = "w_${now}_$i"; i++ }+ val dir = File(root, id).apply { mkdirs() }+ val displayName = name.trim().ifEmpty { "New World" }+ val meta = WorldMeta(name = displayName, seed = seed, created = now, lastPlayed = now)+ File(dir, "world.json").writeText(json.encodeToString(WorldMeta.serializer(), meta))+ return WorldInfo(id = id, dir = dir.absolutePath, meta = meta)+ }++ // Bump lastPlayed so the world floats to the top of the list.+ fun touch(ctx: Context, id: String, now: Long) {+ val dir = File(worldsRoot(ctx), id)+ val metaFile = File(dir, "world.json")+ if (!metaFile.exists()) return+ try {+ val meta = json.decodeFromString<WorldMeta>(metaFile.readText())+ metaFile.writeText(json.encodeToString(WorldMeta.serializer(), meta.copy(lastPlayed = now)))+ } catch (_: Exception) {}+ }++ fun deleteWorld(ctx: Context, id: String) {+ File(worldsRoot(ctx), id).deleteRecursively()+ }+}
games/voxels/src/main/rust/build.rs
diff --git a/games/voxels/src/main/rust/build.rs b/games/voxels/src/main/rust/build.rsindex ffa30cc644..6b953615a2 100644--- a/games/voxels/src/main/rust/build.rs+++ b/games/voxels/src/main/rust/build.rs@@ -13,6 +13,15 @@ fn main() { let sky_frag = shaders_dir.join("sky.frag"); let sky_vert_spv = shaders_dir.join("sky.vert.spv"); let sky_frag_spv = shaders_dir.join("sky.frag.spv");+ let cloud_frag = shaders_dir.join("cloud.frag");+ let cloud_frag_spv = shaders_dir.join("cloud.frag.spv");+ let shadow_vert = shaders_dir.join("shadow.vert");+ let shadow_vert_spv = shaders_dir.join("shadow.vert.spv");+ let water_vert = shaders_dir.join("water.vert");+ let water_frag = shaders_dir.join("water.frag");+ let water_vert_spv = shaders_dir.join("water.vert.spv");+ let water_frag_spv = shaders_dir.join("water.frag.spv");+ let post = [("post.vert","post.vert.spv"), ("bright.frag","bright.frag.spv"), ("blur.frag","blur.frag.spv"), ("composite.frag","composite.frag.spv")]; let atlas_bin = shaders_dir.join("atlas.bin"); if !atlas_bin.exists() {@@ -33,6 +42,13 @@ fn main() { let _ = Command::new(glslc_path).arg("-o").arg(&frag_spv).arg(&frag).status(); let _ = Command::new(glslc_path).arg("-o").arg(&sky_vert_spv).arg(&sky_vert).status(); let _ = Command::new(glslc_path).arg("-o").arg(&sky_frag_spv).arg(&sky_frag).status();+ let _ = Command::new(glslc_path).arg("-o").arg(&cloud_frag_spv).arg(&cloud_frag).status();+ let _ = Command::new(glslc_path).arg("-o").arg(&shadow_vert_spv).arg(&shadow_vert).status();+ let _ = Command::new(glslc_path).arg("-o").arg(&water_vert_spv).arg(&water_vert).status();+ let _ = Command::new(glslc_path).arg("-o").arg(&water_frag_spv).arg(&water_frag).status();+ for (src, spv) in &post {+ let _ = Command::new(glslc_path).arg("-o").arg(shaders_dir.join(spv)).arg(shaders_dir.join(src)).status();+ } } if !vert_spv.exists() { std::fs::write(&vert_spv, minimal_vert_spv()).ok(); }@@ -40,11 +56,27 @@ fn main() { // include_bytes! requires these to exist even if glslc is unavailable. if !sky_vert_spv.exists() { std::fs::write(&sky_vert_spv, minimal_vert_spv()).ok(); } if !sky_frag_spv.exists() { std::fs::write(&sky_frag_spv, minimal_frag_spv()).ok(); }+ if !cloud_frag_spv.exists() { std::fs::write(&cloud_frag_spv, minimal_frag_spv()).ok(); }+ if !shadow_vert_spv.exists() { std::fs::write(&shadow_vert_spv, minimal_vert_spv()).ok(); }+ if !water_vert_spv.exists() { std::fs::write(&water_vert_spv, minimal_vert_spv()).ok(); }+ if !water_frag_spv.exists() { std::fs::write(&water_frag_spv, minimal_frag_spv()).ok(); }+ for (src, spv) in &post {+ let p = shaders_dir.join(spv);+ if !p.exists() { std::fs::write(&p, if src.ends_with(".vert") { minimal_vert_spv() } else { minimal_frag_spv() }).ok(); }+ } println!("cargo:rerun-if-changed=shaders/block.vert"); println!("cargo:rerun-if-changed=shaders/block.frag"); println!("cargo:rerun-if-changed=shaders/sky.vert"); println!("cargo:rerun-if-changed=shaders/sky.frag");+ println!("cargo:rerun-if-changed=shaders/cloud.frag");+ println!("cargo:rerun-if-changed=shaders/shadow.vert");+ println!("cargo:rerun-if-changed=shaders/water.vert");+ println!("cargo:rerun-if-changed=shaders/water.frag");+ println!("cargo:rerun-if-changed=shaders/post.vert");+ println!("cargo:rerun-if-changed=shaders/bright.frag");+ println!("cargo:rerun-if-changed=shaders/blur.frag");+ println!("cargo:rerun-if-changed=shaders/composite.frag"); println!("cargo:rerun-if-changed=shaders/atlas.bin"); println!("cargo:rerun-if-changed=build.rs"); }
games/voxels/src/main/rust/shaders/atlas.bin
diff --git a/games/voxels/src/main/rust/shaders/atlas.bin b/games/voxels/src/main/rust/shaders/atlas.binindex ceef2932f2..cf71dd3059 100644Binary files a/games/voxels/src/main/rust/shaders/atlas.bin and b/games/voxels/src/main/rust/shaders/atlas.bin differ
games/voxels/src/main/rust/shaders/block.frag
diff --git a/games/voxels/src/main/rust/shaders/block.frag b/games/voxels/src/main/rust/shaders/block.fragindex e5c17d2b57..de6e97534c 100644--- a/games/voxels/src/main/rust/shaders/block.frag+++ b/games/voxels/src/main/rust/shaders/block.frag@@ -6,6 +6,7 @@ layout(location=3) in float fragDist; layout(location=4) in vec3 fragWorldPos; layout(location=5) in vec3 fragNormal; layout(location=6) in float fragTile;+layout(location=7) in vec4 fragLightPos; layout(binding=0) uniform Ubo { mat4 viewProj;@@ -20,14 +21,17 @@ layout(binding=0) uniform Ubo { float cloudShadow; vec3 ambientColor; float _pad2;+ mat4 lightViewProj; }; layout(binding=1) uniform sampler2D atlasTex;+layout(binding=2) uniform sampler2D shadowMap; layout(location=0) out vec4 outColor; -// Atlas is 4 cols x 8 rows.-const vec2 TILE_SPAN = vec2(1.0/4.0, 1.0/8.0);+// Atlas is 8 cols x 8 rows.+const vec2 TILE_SPAN = vec2(1.0/8.0, 1.0/8.0);+const float ATLAS_COLS = 8.0; // --- Cloud coverage (matches sky.frag) for cloud shadows on the ground. --- const float CLOUD_MID = 165.0;@@ -46,29 +50,62 @@ float cloudShadowFactor(vec3 wp, vec3 s){ float t = (CLOUD_MID - wp.y) / s.y; if (t <= 0.0) return 1.0; vec3 cp = wp + s * t;- vec3 q = cp*0.0045 + vec3(time*0.010, 0.0, time*0.006);- float d = smoothstep(1.0-COVERAGE, 1.0, fbm2(q));+ vec3 q = cp*0.0045 + vec3(time*0.06, time*0.04, time*0.045); // match sky.frag cloud animation+ q += 0.7*(fbm2(q*0.55) - 0.5); // approx domain warp (match sky)+ float d = smoothstep(1.0-COVERAGE, 1.0-COVERAGE*0.25, fbm2(q)); return 1.0 - clamp(d * cloudShadow, 0.0, 0.8); } +// Sun shadow map: 1 = lit, 0 = fully shadowed. 3x3 PCF with slope-scaled bias.+const float SHADOW_TEXEL = 1.0 / 2048.0;+float sunShadow(vec4 lightPos, float ndotl) {+ vec3 lp = lightPos.xyz / lightPos.w; // Vulkan clip: xy in [-1,1], z in [0,1]+ vec2 uv = lp.xy * 0.5 + 0.5;+ if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0 || lp.z > 1.0 || lp.z < 0.0) return 1.0;+ float bias = max(0.0016 * (1.0 - ndotl), 0.0004);+ float cur = lp.z - bias;+ float sum = 0.0;+ for (int y = -1; y <= 1; y++) {+ for (int x = -1; x <= 1; x++) {+ float d = texture(shadowMap, uv + vec2(x, y) * SHADOW_TEXEL).r;+ sum += cur <= d ? 1.0 : 0.0;+ }+ }+ return sum / 9.0;+}+ void main() { // Wrap the per-block uv into this face's atlas tile so greedy-merged faces tile (no stretch).+ vec2 fuv = fract(fragUv); float tile = fragTile;- vec2 origin = vec2(mod(tile, 4.0) * TILE_SPAN.x, floor(tile / 4.0 + 0.001) * TILE_SPAN.y);- vec2 auv = origin + fract(fragUv) * TILE_SPAN;- vec4 texColor = texture(atlasTex, auv);- if (texColor.a < 0.05) discard;+ vec4 texColor;+ vec3 albedo;+ if (tile > 99.0) {+ // Grass side: dirt base + the tinted grass_block_side_overlay fringe, composited in one quad+ // (perfectly aligned with the top face, no z-fight offset).+ vec2 dirtUV = vec2(mod(1.0, ATLAS_COLS) * TILE_SPAN.x, floor(1.0 / ATLAS_COLS + 0.001) * TILE_SPAN.y) + fuv * TILE_SPAN;+ vec2 ovUV = vec2(mod(16.0, ATLAS_COLS) * TILE_SPAN.x, floor(16.0 / ATLAS_COLS + 0.001) * TILE_SPAN.y) + fuv * TILE_SPAN;+ vec3 dirt = texture(atlasTex, dirtUV).rgb;+ vec4 ov = texture(atlasTex, ovUV);+ albedo = mix(dirt, ov.rgb * fragColor, ov.a);+ texColor = vec4(albedo, 1.0);+ } else {+ vec2 origin = vec2(mod(tile, ATLAS_COLS) * TILE_SPAN.x, floor(tile / ATLAS_COLS + 0.001) * TILE_SPAN.y);+ texColor = texture(atlasTex, origin + fuv * TILE_SPAN);+ if (texColor.a < 0.05) discard;+ albedo = texColor.rgb * fragColor;+ } - vec3 albedo = texColor.rgb * fragColor; vec3 n = normalize(fragNormal); // true per-face normal (stable regardless of camera) vec3 s = normalize(sunDir); float NdotL = max(dot(n, s), 0.0);- float shadow = cloudShadowFactor(fragWorldPos, s);+ // Sun visibility = cloud shadow * shadow-map (terrain self/occluder shadows).+ float shadow = cloudShadowFactor(fragWorldPos, s) * sunShadow(fragLightPos, NdotL); // Hemisphere ambient: sky above is brighter than the ground bounce below. float hemi = 0.5 + 0.5 * n.y; vec3 ambient = ambientColor * mix(0.55, 1.0, hemi);- float aoFactor = 0.7 + 0.3 * fragAo;+ float aoFactor = mix(0.5, 1.0, fragAo); // per-corner ambient occlusion vec3 lit = albedo * (sunColor * NdotL * shadow + ambient) * aoFactor; @@ -76,7 +113,11 @@ void main() { fog = clamp(fog, 0.0, 0.85); vec3 col = mix(lit, fogColor, fog); - col = col / (col + vec3(0.55)); // same tonemap as the sky pass- col = pow(col, vec3(0.85));- outColor = vec4(col, texColor.a);+ // Underwater: tint deep blue and darken with distance.+ if (playerPos.w > 0.5) {+ float uw = clamp(1.0 - exp(-fragDist * 0.05), 0.0, 0.85);+ col = mix(col, vec3(0.05, 0.20, 0.32), uw) * 0.75;+ }++ outColor = vec4(col, texColor.a); // linear HDR; tonemap happens in the composite pass }
games/voxels/src/main/rust/shaders/block.frag.spv
diff --git a/games/voxels/src/main/rust/shaders/block.frag.spv b/games/voxels/src/main/rust/shaders/block.frag.spvindex 577514b4db..fc9b364b8b 100644Binary files a/games/voxels/src/main/rust/shaders/block.frag.spv and b/games/voxels/src/main/rust/shaders/block.frag.spv differ
games/voxels/src/main/rust/shaders/block.vert
diff --git a/games/voxels/src/main/rust/shaders/block.vert b/games/voxels/src/main/rust/shaders/block.vertindex 27a53ef216..42fd6c3ee2 100644--- a/games/voxels/src/main/rust/shaders/block.vert+++ b/games/voxels/src/main/rust/shaders/block.vert@@ -19,6 +19,7 @@ layout(binding=0) uniform Ubo { float cloudShadow; vec3 ambientColor; float _pad2;+ mat4 lightViewProj; }; layout(location=0) out vec2 fragUv;@@ -28,6 +29,7 @@ layout(location=3) out float fragDist; layout(location=4) out vec3 fragWorldPos; layout(location=5) out vec3 fragNormal; layout(location=6) out float fragTile;+layout(location=7) out vec4 fragLightPos; void main() { gl_Position = viewProj * vec4(inPos, 1.0);@@ -38,4 +40,5 @@ void main() { fragNormal = inNormal; fragTile = inTileIdx; fragDist = length(inPos - playerPos.xyz);+ fragLightPos = lightViewProj * vec4(inPos, 1.0); }
games/voxels/src/main/rust/shaders/block.vert.spv
diff --git a/games/voxels/src/main/rust/shaders/block.vert.spv b/games/voxels/src/main/rust/shaders/block.vert.spvindex d47451e849..1c0ceab18e 100644Binary files a/games/voxels/src/main/rust/shaders/block.vert.spv and b/games/voxels/src/main/rust/shaders/block.vert.spv differ
games/voxels/src/main/rust/shaders/blur.frag
diff --git a/games/voxels/src/main/rust/shaders/blur.frag b/games/voxels/src/main/rust/shaders/blur.fragnew file mode 100644index 0000000000..012483dbad--- /dev/null+++ b/games/voxels/src/main/rust/shaders/blur.frag@@ -0,0 +1,18 @@+#version 450+// Separable 5-tap Gaussian blur. `pc.param.xy` = uv step along the blur axis.+layout(location=0) in vec2 vUv;+layout(binding=0) uniform sampler2D src;+layout(binding=1) uniform sampler2D unused;+layout(push_constant) uniform PC { vec4 param; } pc;+layout(location=0) out vec4 outColor;+void main() {+ vec2 d = pc.param.xy;+ vec3 s = texture(src, vUv).rgb * 0.227027;+ vec2 o1 = d * 1.3846153846;+ vec2 o2 = d * 3.2307692308;+ s += texture(src, vUv + o1).rgb * 0.3162162162;+ s += texture(src, vUv - o1).rgb * 0.3162162162;+ s += texture(src, vUv + o2).rgb * 0.0702702703;+ s += texture(src, vUv - o2).rgb * 0.0702702703;+ outColor = vec4(s, 1.0);+}
games/voxels/src/main/rust/shaders/blur.frag.spv
diff --git a/games/voxels/src/main/rust/shaders/blur.frag.spv b/games/voxels/src/main/rust/shaders/blur.frag.spvnew file mode 100644index 0000000000..d68cf77a56Binary files /dev/null and b/games/voxels/src/main/rust/shaders/blur.frag.spv differ
games/voxels/src/main/rust/shaders/bright.frag
diff --git a/games/voxels/src/main/rust/shaders/bright.frag b/games/voxels/src/main/rust/shaders/bright.fragnew file mode 100644index 0000000000..95a7315066--- /dev/null+++ b/games/voxels/src/main/rust/shaders/bright.frag@@ -0,0 +1,14 @@+#version 450+// Bright-pass: keep only HDR values above a threshold (feeds the bloom blur). Runs at half res, so the+// bilinear sample also downsamples.+layout(location=0) in vec2 vUv;+layout(binding=0) uniform sampler2D src;+layout(binding=1) uniform sampler2D unused;+layout(location=0) out vec4 outColor;+void main() {+ vec3 c = texture(src, vUv).rgb;+ float b = max(max(c.r, c.g), c.b);+ const float threshold = 1.05;+ float k = clamp((b - threshold) / max(b, 1e-4), 0.0, 1.0);+ outColor = vec4(c * k, 1.0);+}
games/voxels/src/main/rust/shaders/bright.frag.spv
diff --git a/games/voxels/src/main/rust/shaders/bright.frag.spv b/games/voxels/src/main/rust/shaders/bright.frag.spvnew file mode 100644index 0000000000..2a1cb1d892Binary files /dev/null and b/games/voxels/src/main/rust/shaders/bright.frag.spv differ
games/voxels/src/main/rust/shaders/cloud.frag
diff --git a/games/voxels/src/main/rust/shaders/cloud.frag b/games/voxels/src/main/rust/shaders/cloud.fragnew file mode 100644index 0000000000..c0a2700637--- /dev/null+++ b/games/voxels/src/main/rust/shaders/cloud.frag@@ -0,0 +1,161 @@+#version 450+// Volumetric clouds as a real depth-tested layer at a fixed world-space altitude slab+// [CLOUD_BOT, CLOUD_TOP]. Raymarched from the camera through the slab for ANY view direction, so you+// can stand under them, fly up into them, or look down on them from above. Per-fragment gl_FragDepth+// (entry point of the slab) lets terrain occlude clouds and clouds occlude terrain behind them.+layout(location=0) in vec2 vNdc;++layout(binding=0) uniform Ubo {+ mat4 viewProj;+ vec3 sunDir;+ float time;+ vec3 fogColor;+ float fogDensity;+ vec4 playerPos;+ float dayFactor;+ mat4 invViewProj;+ vec3 sunColor;+ float cloudShadow;+ vec3 ambientColor;+ float _pad2;+};++layout(location=0) out vec4 outColor;++const float PI = 3.14159265;++// ---- Sky background colour (used as cloud ambient; matches sky.frag) -----------------------------+vec3 skyColor(vec3 d, vec3 s) {+ d = normalize(d);+ s = normalize(s);+ float mu = dot(d, s);+ float h = clamp(d.y, 0.0, 1.0);+ float sunUp = smoothstep(-0.10, 0.22, s.y);+ vec3 betaR = vec3(0.19, 0.45, 1.0);+ float phaseR = 0.75 * (1.0 + mu * mu);+ float viewAir = 1.0 / (h * 0.85 + 0.15);+ float sunAir = 1.0 / (max(s.y, 0.0) * 0.9 + 0.12);+ vec3 sunTransmit = exp(-betaR * sunAir * 0.35);+ vec3 day = betaR * phaseR * (0.10 + 0.30 * viewAir) * sunTransmit;+ day = mix(day, vec3(dot(day, vec3(0.33)) + 0.30), (1.0 - h) * 0.35);+ float low = 1.0 - sunUp;+ vec3 warm = vec3(1.0, 0.42, 0.18);+ float warmMix = low * (0.35 + 0.65 * max(mu, 0.0) * max(mu, 0.0)) * (1.0 - h * 0.6);+ day = mix(day, warm, clamp(warmMix, 0.0, 0.8));+ vec3 night = mix(vec3(0.015, 0.02, 0.05), vec3(0.03, 0.05, 0.10), h);+ float twi = smoothstep(-0.22, 0.02, s.y) * (1.0 - sunUp);+ night += vec3(0.18, 0.08, 0.10) * twi * (1.0 - h * 0.7);+ return max(mix(night, day, sunUp), vec3(0.0));+}++// ---- Noise ---------------------------------------------------------------------------------------+float hash(vec3 p) {+ p = fract(p * 0.3183099 + 0.1);+ p *= 17.0;+ return fract(p.x * p.y * p.z * (p.x + p.y + p.z));+}+float vnoise(vec3 x) {+ vec3 i = floor(x);+ vec3 f = fract(x);+ f = f * f * (3.0 - 2.0 * f);+ return mix(mix(mix(hash(i + vec3(0,0,0)), hash(i + vec3(1,0,0)), f.x),+ mix(hash(i + vec3(0,1,0)), hash(i + vec3(1,1,0)), f.x), f.y),+ mix(mix(hash(i + vec3(0,0,1)), hash(i + vec3(1,0,1)), f.x),+ mix(hash(i + vec3(0,1,1)), hash(i + vec3(1,1,1)), f.x), f.y), f.z);+}+float fbm2(vec3 p) { return 0.6 * vnoise(p) + 0.4 * vnoise(p * 2.03 + 1.7); }++// ---- Cloud volume --------------------------------------------------------------------------------+const float CLOUD_BOT = 120.0;+const float CLOUD_TOP = 210.0;+const float COVERAGE = 0.47;+const float SIGMA_V = 0.12;+const float SIGMA_L = 0.02;++float cloudDensity(vec3 p) {+ vec3 q = p * 0.0045 + vec3(time * 0.06, time * 0.04, time * 0.045);+ q += 0.7 * (fbm2(q * 0.55) - 0.5);+ float base = fbm2(q);+ float d = smoothstep(1.0 - COVERAGE, 1.0 - COVERAGE * 0.25, base);+ d -= 0.15 * fbm2(q * 3.0 + vec3(0.0, time * 0.2, 0.0) + 4.0);+ float hn = (p.y - CLOUD_BOT) / (CLOUD_TOP - CLOUD_BOT);+ float grad = smoothstep(0.0, 0.28, hn) * smoothstep(1.0, 0.5, hn);+ return clamp(d, 0.0, 1.0) * grad;+}+float cloudDensityLow(vec3 p) {+ vec3 q = p * 0.0045 + vec3(time * 0.06, time * 0.04, time * 0.045);+ float base = fbm2(q);+ float d = smoothstep(1.0 - COVERAGE, 1.0 - COVERAGE * 0.25, base);+ float hn = (p.y - CLOUD_BOT) / (CLOUD_TOP - CLOUD_BOT);+ float grad = smoothstep(0.0, 0.28, hn) * smoothstep(1.0, 0.5, hn);+ return clamp(d, 0.0, 1.0) * grad;+}++float hgPhase(float mu, float g) {+ float g2 = g * g;+ return (1.0 - g2) / (4.0 * PI * pow(max(1.0 + g2 - 2.0 * g * mu, 1e-3), 1.5));+}++void main() {+ vec4 np = invViewProj * vec4(vNdc, 0.0, 1.0);+ vec4 fp = invViewProj * vec4(vNdc, 1.0, 1.0);+ vec3 rd = normalize(fp.xyz / fp.w - np.xyz / np.w);+ vec3 ro = playerPos.xyz;+ vec3 s = normalize(sunDir);++ // Intersect the ray with the fixed altitude slab for ANY direction (up, level, or down).+ float t0, t1;+ if (abs(rd.y) < 1e-4) {+ if (ro.y < CLOUD_BOT || ro.y > CLOUD_TOP) discard; // level ray, outside the slab -> no clouds+ t0 = 0.0; t1 = 4000.0;+ } else {+ float ta = (CLOUD_BOT - ro.y) / rd.y;+ float tb = (CLOUD_TOP - ro.y) / rd.y;+ t0 = max(min(ta, tb), 0.0);+ t1 = max(ta, tb);+ if (t1 <= 0.0) discard; // slab entirely behind the camera+ }+ t1 = min(t1, 6000.0);+ if (t1 <= t0) discard;++ // Depth of the slab entry point -> lets the depth test occlude clouds behind terrain and vice+ // versa. (Writing gl_FragDepth disables early-z, but the discards above skip the cheap cases.)+ vec3 entry = ro + rd * t0;+ vec4 clip = viewProj * vec4(entry, 1.0);+ gl_FragDepth = clamp(clip.z / clip.w, 0.0, 1.0);++ const int STEPS = 14;+ float stepLen = (t1 - t0) / float(STEPS);+ float t = t0 + stepLen * hash(rd * 91.7);+ vec3 sunCol = sunColor;+ vec3 skyBg = skyColor(rd, s);+ vec3 ambient = skyBg * 0.5 + ambientColor * 0.4;+ float mu = dot(rd, s);+ float phase = mix(hgPhase(mu, 0.70), hgPhase(mu, -0.20), 0.35);++ float transmittance = 1.0;+ vec3 scattered = vec3(0.0);+ for (int i = 0; i < STEPS; i++) {+ vec3 p = ro + rd * t;+ float dens = cloudDensity(p);+ if (dens > 0.01) {+ float od = 0.0;+ float ls = 45.0;+ for (int j = 0; j < 2; j++) {+ od += cloudDensityLow(p + s * ls * (float(j) + 0.7)) * ls;+ }+ float lightT = exp(-od * SIGMA_L);+ float powder = 1.0 - exp(-dens * 2.0);+ vec3 lum = sunCol * lightT * (phase * 2.0 + 0.6) * powder + ambient;+ float att = exp(-dens * stepLen * SIGMA_V);+ scattered += transmittance * (1.0 - att) * lum;+ transmittance *= att;+ if (transmittance < 0.02) break;+ }+ t += stepLen;+ }++ float alpha = 1.0 - transmittance;+ if (alpha < 0.003) discard; // nothing hit along this ray+ outColor = vec4(scattered, alpha); // premultiplied: blend ONE, ONE_MINUS_SRC_ALPHA over the scene+}
games/voxels/src/main/rust/shaders/cloud.frag.spv
diff --git a/games/voxels/src/main/rust/shaders/cloud.frag.spv b/games/voxels/src/main/rust/shaders/cloud.frag.spvnew file mode 100644index 0000000000..582076c3a6Binary files /dev/null and b/games/voxels/src/main/rust/shaders/cloud.frag.spv differ
games/voxels/src/main/rust/shaders/composite.frag
diff --git a/games/voxels/src/main/rust/shaders/composite.frag b/games/voxels/src/main/rust/shaders/composite.fragnew file mode 100644index 0000000000..70524a4561--- /dev/null+++ b/games/voxels/src/main/rust/shaders/composite.frag@@ -0,0 +1,39 @@+#version 450+// Composite: FXAA on the HDR image, add bloom, tonemap+gamma to the swapchain.+// pc.param.xy = texel size (1/width, 1/height), pc.param.z = bloom intensity.+layout(location=0) in vec2 vUv;+layout(binding=0) uniform sampler2D hdrTex;+layout(binding=1) uniform sampler2D bloomTex;+layout(push_constant) uniform PC { vec4 param; } pc;+layout(location=0) out vec4 outColor;++float luma(vec3 c) { return dot(c, vec3(0.299, 0.587, 0.114)); }++void main() {+ vec2 texel = pc.param.xy;+ vec3 c = texture(hdrTex, vUv).rgb;+ vec3 nw = texture(hdrTex, vUv + vec2(-1.0, -1.0) * texel).rgb;+ vec3 ne = texture(hdrTex, vUv + vec2( 1.0, -1.0) * texel).rgb;+ vec3 sw = texture(hdrTex, vUv + vec2(-1.0, 1.0) * texel).rgb;+ vec3 se = texture(hdrTex, vUv + vec2( 1.0, 1.0) * texel).rgb;+ float lM = luma(c), lNW = luma(nw), lNE = luma(ne), lSW = luma(sw), lSE = luma(se);+ float lMin = min(lM, min(min(lNW, lNE), min(lSW, lSE)));+ float lMax = max(lM, max(max(lNW, lNE), max(lSW, lSE)));++ vec3 aa = c;+ if (lMax - lMin > 0.05 * lMax + 0.02) { // only on edges+ vec2 dir = vec2(-((lNW + lNE) - (lSW + lSE)), ((lNW + lSW) - (lNE + lSE)));+ float reduce = max((lNW + lNE + lSW + lSE) * 0.25 * 0.125, 1.0 / 128.0);+ float rcp = 1.0 / (min(abs(dir.x), abs(dir.y)) + reduce);+ dir = clamp(dir * rcp, -8.0, 8.0) * texel;+ vec3 rA = 0.5 * (texture(hdrTex, vUv + dir * (1.0/3.0 - 0.5)).rgb + texture(hdrTex, vUv + dir * (2.0/3.0 - 0.5)).rgb);+ vec3 rB = rA * 0.5 + 0.25 * (texture(hdrTex, vUv + dir * -0.5).rgb + texture(hdrTex, vUv + dir * 0.5).rgb);+ float lB = luma(rB);+ aa = (lB < lMin || lB > lMax) ? rA : rB;+ }++ vec3 col = aa + texture(bloomTex, vUv).rgb * pc.param.z;+ col = col / (col + vec3(0.55)); // tonemap+ col = pow(col, vec3(0.85)); // gamma lift+ outColor = vec4(col, 1.0);+}
games/voxels/src/main/rust/shaders/composite.frag.spv
diff --git a/games/voxels/src/main/rust/shaders/composite.frag.spv b/games/voxels/src/main/rust/shaders/composite.frag.spvnew file mode 100644index 0000000000..cf1a7c537dBinary files /dev/null and b/games/voxels/src/main/rust/shaders/composite.frag.spv differ
games/voxels/src/main/rust/shaders/post.vert
diff --git a/games/voxels/src/main/rust/shaders/post.vert b/games/voxels/src/main/rust/shaders/post.vertnew file mode 100644index 0000000000..f134bf61e8--- /dev/null+++ b/games/voxels/src/main/rust/shaders/post.vert@@ -0,0 +1,8 @@+#version 450+// Fullscreen triangle with 0..1 uv (uv.y=0 at the top, matching Vulkan framebuffer/texture origin).+layout(location=0) out vec2 vUv;+void main() {+ vec2 p = vec2(float((gl_VertexIndex << 1) & 2), float(gl_VertexIndex & 2));+ vUv = p;+ gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);+}
games/voxels/src/main/rust/shaders/post.vert.spv
diff --git a/games/voxels/src/main/rust/shaders/post.vert.spv b/games/voxels/src/main/rust/shaders/post.vert.spvnew file mode 100644index 0000000000..d9c05ea395Binary files /dev/null and b/games/voxels/src/main/rust/shaders/post.vert.spv differ
games/voxels/src/main/rust/shaders/shadow.vert
diff --git a/games/voxels/src/main/rust/shaders/shadow.vert b/games/voxels/src/main/rust/shaders/shadow.vertnew file mode 100644index 0000000000..1d8210e787--- /dev/null+++ b/games/voxels/src/main/rust/shaders/shadow.vert@@ -0,0 +1,23 @@+#version 450+// Depth-only pass: rasterize terrain from the sun's point of view into the shadow map.+layout(location=0) in vec3 inPos;++layout(binding=0) uniform Ubo {+ mat4 viewProj;+ vec3 sunDir;+ float time;+ vec3 fogColor;+ float fogDensity;+ vec4 playerPos;+ float dayFactor;+ mat4 invViewProj;+ vec3 sunColor;+ float cloudShadow;+ vec3 ambientColor;+ float _pad2;+ mat4 lightViewProj;+};++void main() {+ gl_Position = lightViewProj * vec4(inPos, 1.0);+}
games/voxels/src/main/rust/shaders/shadow.vert.spv
diff --git a/games/voxels/src/main/rust/shaders/shadow.vert.spv b/games/voxels/src/main/rust/shaders/shadow.vert.spvnew file mode 100644index 0000000000..62c78c21cdBinary files /dev/null and b/games/voxels/src/main/rust/shaders/shadow.vert.spv differ
games/voxels/src/main/rust/shaders/sky.frag
diff --git a/games/voxels/src/main/rust/shaders/sky.frag b/games/voxels/src/main/rust/shaders/sky.fragindex 6cb9439023..1edc3e2d25 100644--- a/games/voxels/src/main/rust/shaders/sky.frag+++ b/games/voxels/src/main/rust/shaders/sky.frag@@ -78,12 +78,27 @@ const float SIGMA_V = 0.12; // view-ray extinction per density-length const float SIGMA_L = 0.02; // light-ray extinction per density-length float cloudDensity(vec3 p) {- vec3 q = p * 0.0045 + vec3(time * 0.010, 0.0, time * 0.006); // wind drift+ // Fast wind drift (x,z) + moving vertical slice (y) so shapes race across and morph.+ vec3 q = p * 0.0045 + vec3(time * 0.06, time * 0.04, time * 0.045);+ // Domain warp: shift the sample position by a lower-frequency noise so clouds are billowy/rounded+ // instead of grid-aligned rectangular lumps from the raw value noise (cheap 1-tap warp).+ q += 0.7 * (fbm2(q * 0.55) - 0.5); float base = fbm2(q);- float d = smoothstep(1.0 - COVERAGE, 1.0, base);- d -= 0.20 * fbm2(q * 3.1 + 4.0); // erode edges+ float d = smoothstep(1.0 - COVERAGE, 1.0 - COVERAGE * 0.25, base); // softer, fluffier edges+ d -= 0.15 * fbm2(q * 3.0 + vec3(0.0, time * 0.2, 0.0) + 4.0); // evolving wispy detail float hn = (p.y - CLOUD_BOT) / (CLOUD_TOP - CLOUD_BOT);- float grad = smoothstep(0.0, 0.18, hn) * smoothstep(1.0, 0.6, hn); // feather top/bottom+ float grad = smoothstep(0.0, 0.28, hn) * smoothstep(1.0, 0.5, hn); // rounder top/bottom+ return clamp(d, 0.0, 1.0) * grad;+}++// Cheap density for the sun-ward light march: base coverage only, no domain warp or detail octave.+// Self-shadowing is low-frequency, so dropping the fine noise here is nearly invisible but ~3x cheaper.+float cloudDensityLow(vec3 p) {+ vec3 q = p * 0.0045 + vec3(time * 0.06, time * 0.04, time * 0.045);+ float base = fbm2(q);+ float d = smoothstep(1.0 - COVERAGE, 1.0 - COVERAGE * 0.25, base);+ float hn = (p.y - CLOUD_BOT) / (CLOUD_TOP - CLOUD_BOT);+ float grad = smoothstep(0.0, 0.28, hn) * smoothstep(1.0, 0.5, hn); return clamp(d, 0.0, 1.0) * grad; } @@ -122,7 +137,7 @@ vec4 renderClouds(vec3 ro, vec3 rd, vec3 s, vec3 skyBg, float sunUp) { float od = 0.0; float ls = 45.0; for (int j = 0; j < 2; j++) {- od += cloudDensity(p + s * ls * (float(j) + 0.7)) * ls;+ od += cloudDensityLow(p + s * ls * (float(j) + 0.7)) * ls; } float lightT = exp(-od * SIGMA_L); float powder = 1.0 - exp(-dens * 2.0);@@ -145,11 +160,11 @@ void main() { vec3 s = normalize(sunDir); float sunUp = smoothstep(-0.10, 0.22, s.y); + // Sky background only. Clouds are a separate depth-tested volumetric pass (cloud.frag) so they+ // sit at a real world altitude and interact with terrain depth. vec3 col = skyColor(dir, s);- vec4 clouds = renderClouds(playerPos.xyz, dir, s, col, sunUp);- col = col * clouds.a + clouds.rgb; // composite clouds over sky - col = col / (col + vec3(0.55)); // gentle tonemap- col = pow(col, vec3(0.85));- outColor = vec4(col, 1.0);+ if (playerPos.w > 0.5) { col = mix(col, vec3(0.05, 0.20, 0.32), 0.85); } // underwater++ outColor = vec4(col, 1.0); // linear HDR; tonemap in composite }
games/voxels/src/main/rust/shaders/sky.frag.spv
diff --git a/games/voxels/src/main/rust/shaders/sky.frag.spv b/games/voxels/src/main/rust/shaders/sky.frag.spvindex 514c69a766..cd0ede904a 100644Binary files a/games/voxels/src/main/rust/shaders/sky.frag.spv and b/games/voxels/src/main/rust/shaders/sky.frag.spv differ
games/voxels/src/main/rust/shaders/water.frag
diff --git a/games/voxels/src/main/rust/shaders/water.frag b/games/voxels/src/main/rust/shaders/water.fragnew file mode 100644index 0000000000..f51aca688b--- /dev/null+++ b/games/voxels/src/main/rust/shaders/water.frag@@ -0,0 +1,65 @@+#version 450+layout(location=0) in vec3 fragWorldPos;+layout(location=1) in float fragDist;+layout(location=2) in vec3 fragNormal;++layout(binding=0) uniform Ubo {+ mat4 viewProj;+ vec3 sunDir;+ float time;+ vec3 fogColor;+ float fogDensity;+ vec4 playerPos; // .w = underwater flag+ float dayFactor;+ mat4 invViewProj;+ vec3 sunColor;+ float cloudShadow;+ vec3 ambientColor;+ float _pad2;+};++layout(location=0) out vec4 outColor;++void main() {+ vec3 s = normalize(sunDir);+ vec3 viewDir = normalize(playerPos.xyz - fragWorldPos);+ vec3 wp = fragWorldPos;++ // Detailed animated surface normal: coarse wave normal + fine moving ripples for sparkle.+ vec3 n = normalize(fragNormal);+ n.x += 0.06 * sin(wp.x * 2.3 + time * 2.5) + 0.04 * sin(wp.z * 3.1 - time * 1.7);+ n.z += 0.06 * sin(wp.z * 2.1 + time * 2.2) + 0.04 * sin(wp.x * 2.9 + time * 1.3);+ n = normalize(n);++ // Fresnel: near-transparent looking straight down, mirror-like at grazing angles.+ float ndv = max(dot(n, viewDir), 0.0);+ float fres = mix(0.04, 1.0, pow(1.0 - ndv, 4.0));++ // Body colour: teal in the shallows, deep blue when looking straight down into it.+ vec3 shallow = vec3(0.06, 0.30, 0.36);+ vec3 deep = vec3(0.015, 0.08, 0.14);+ vec3 body = mix(shallow, deep, ndv);+ // Cheap sky reflection colour, brighter when the sun is up.+ vec3 skyRefl = mix(vec3(0.30, 0.45, 0.60), vec3(0.55, 0.72, 0.95), clamp(s.y, 0.0, 1.0)) + sunColor * 0.10;+ vec3 col = mix(body, skyRefl, fres);+ // Darken with the day/night cycle so water doesn't glow at night while the terrain is dark.+ // (Sun glint below uses sunColor, which is already ~0 at night, so it stays correct.)+ col *= mix(0.06, 1.0, clamp(dayFactor, 0.0, 1.0));++ // Sharp sun glint + a broad sheen.+ vec3 hlf = normalize(s + viewDir);+ float nh = max(dot(n, hlf), 0.0);+ col += sunColor * (pow(nh, 400.0) * 1.6 + pow(nh, 40.0) * 0.12);++ // More transparent looking down (see the floor), opaque/reflective at grazing angles.+ float alpha = mix(0.55, 0.95, fres);++ // Distance fog toward the horizon so the ocean fades into the sky instead of ending abruptly.+ float fog = clamp(1.0 - exp(-fragDist * fogDensity), 0.0, 0.9);+ col = mix(col, fogColor, fog);+ alpha = mix(alpha, 1.0, fog);++ if (playerPos.w > 0.5) { col = mix(col, vec3(0.05, 0.20, 0.32), 0.6); alpha = 0.85; }++ outColor = vec4(col, alpha); // linear HDR; tonemap in composite+}
games/voxels/src/main/rust/shaders/water.frag.spv
diff --git a/games/voxels/src/main/rust/shaders/water.frag.spv b/games/voxels/src/main/rust/shaders/water.frag.spvnew file mode 100644index 0000000000..250ae3a6c6Binary files /dev/null and b/games/voxels/src/main/rust/shaders/water.frag.spv differ
games/voxels/src/main/rust/shaders/water.vert
diff --git a/games/voxels/src/main/rust/shaders/water.vert b/games/voxels/src/main/rust/shaders/water.vertnew file mode 100644index 0000000000..dbf1094432--- /dev/null+++ b/games/voxels/src/main/rust/shaders/water.vert@@ -0,0 +1,35 @@+#version 450+layout(location=0) in vec3 inPos;+layout(location=1) in vec2 inUv;+layout(location=2) in vec3 inColor;+layout(location=3) in float inAo;+layout(location=4) in float inTileIdx;+layout(location=5) in vec3 inNormal;++layout(binding=0) uniform Ubo {+ mat4 viewProj;+ vec3 sunDir;+ float time;+ vec3 fogColor;+ float fogDensity;+ vec4 playerPos; // .w = underwater flag+ float dayFactor;+};++layout(location=0) out vec3 fragWorldPos;+layout(location=1) out float fragDist;+layout(location=2) out vec3 fragNormal;++void main() {+ // Keep the surface geometrically flat (uniform sink below the block top) so greedy-mesh+ // T-junctions don't crack; the wave lives entirely in the shading normal (+ frag ripples).+ vec3 p = inPos;+ p.y -= 0.1;+ // Analytic wave normal from a virtual height field (shading only, no vertex displacement).+ float dhx = 0.6 * cos(inPos.x * 0.6 + time * 1.5) * 0.06 + 0.3 * cos((inPos.x + inPos.z) * 0.3 + time * 0.7) * 0.04;+ float dhz = 0.5 * cos(inPos.z * 0.5 + time * 1.1) * 0.06 + 0.3 * cos((inPos.x + inPos.z) * 0.3 + time * 0.7) * 0.04;+ fragNormal = normalize(vec3(-dhx, 1.0, -dhz));+ fragWorldPos = p;+ fragDist = length(p - playerPos.xyz);+ gl_Position = viewProj * vec4(p, 1.0);+}
games/voxels/src/main/rust/shaders/water.vert.spv
diff --git a/games/voxels/src/main/rust/shaders/water.vert.spv b/games/voxels/src/main/rust/shaders/water.vert.spvnew file mode 100644index 0000000000..61ac44276aBinary files /dev/null and b/games/voxels/src/main/rust/shaders/water.vert.spv differ
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 53f8833b22..babb6af056 100644--- a/games/voxels/src/main/rust/src/engine.rs+++ b/games/voxels/src/main/rust/src/engine.rs@@ -32,7 +32,7 @@ fn engine_lock() -> &'static Mutex<Option<EngineState>> { ENGINE.get_or_init(|| Mutex::new(None)) } -pub fn init_engine(files_dir: String) -> bool {+pub fn init_engine(files_dir: String, seed: u32) -> bool { let mut guard = engine_lock().lock().unwrap(); if guard.is_some() { return true; } let save_dir = files_dir.clone();@@ -42,11 +42,9 @@ pub fn init_engine(files_dir: String) -> bool { let inv = { let mut inv = Inventory::default(); inv.selected = ps.inventory.selected.min(8);- for (i, slot) in ps.inventory.slots.iter().enumerate().take(9) {- if i < inv.slots.len() {- inv.slots[i].id = slot.id;- inv.slots[i].count = slot.count;- }+ for (i, slot) in ps.inventory.slots.iter().enumerate().take(inv.slots.len()) {+ inv.slots[i].id = slot.id;+ inv.slots[i].count = slot.count; } inv.placed = ps.stats.placed; inv.broken = ps.stats.broken;@@ -61,7 +59,7 @@ pub fn init_engine(files_dir: String) -> bool { player.yaw = yaw; player.pitch = pitch; - let mut chunks = ChunkMap::new(0xB10CCA, save_dir.clone());+ let mut chunks = ChunkMap::new(seed, save_dir.clone()); chunks.ensure_radius(px as i32, pz as i32); if !had_save {@@ -265,62 +263,67 @@ pub fn tick_and_render() { 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 }; unsafe {- renderer.update_ubo(view_proj, state.player.pos, time);+ renderer.update_ubo(view_proj, state.player.pos, time, underwater); let _ = renderer.draw_frame(); } }+ publish_ui(state); }); } -// UI-polled JSON getters. They use with_engine_try (never block on the render frame) and fall back to-// the last cached value when the render thread holds the lock, so the Compose UI stays smooth.+// UI state caches. The render thread PUBLISHES fresh JSON into these every tick (while it holds the+// engine lock); the UI getters just read the cache. This avoids the UI ever contending with the render+// thread for the engine lock (which it holds ~continuously), so inventory/debug update every frame. static DEBUG_CACHE: OnceLock<Mutex<String>> = OnceLock::new(); static INV_CACHE: OnceLock<Mutex<String>> = OnceLock::new(); static STATS_CACHE: OnceLock<Mutex<String>> = OnceLock::new();--fn cached(cache: &'static OnceLock<Mutex<String>>, default: &str, fresh: Option<String>) -> String {- let m = cache.get_or_init(|| Mutex::new(default.to_string()));- match fresh {- Some(j) => { if let Ok(mut c) = m.lock() { *c = j.clone(); } j }- None => m.lock().map(|c| c.clone()).unwrap_or_else(|_| default.to_string()),- }-}--pub fn get_debug_json() -> String {- let fresh = with_engine_try(|state| {- let fps = if let Some(r) = &state.renderer {- let elapsed = (Instant::now() - state.start_time).as_secs_f32();- if elapsed>0.1 { r.frame_count as f32 / elapsed } else { 0.0 }- } else { 0.0 };- serde_json::json!({- "fps": format!("{:.1}", fps),- "pos": format!("{:.1},{:.1},{:.1}", state.player.pos.x, state.player.pos.y, state.player.pos.z),- "yaw": format!("{:.1}", state.player.yaw.to_degrees()),- "chunks": state.chunks.len(),- "flying": state.player.flying,- "on_ground": state.player.on_ground,- "time": format!("{:.1}s", (Instant::now() - state.start_time).as_secs_f32()),- "meshes": state.renderer.as_ref().map(|r| r.gpu_meshes.len()).unwrap_or(0),- }).to_string()- });- cached(&DEBUG_CACHE, r#"{"error":"no engine"}"#, fresh)+fn cref(c: &'static OnceLock<Mutex<String>>, default: &str) -> &'static Mutex<String> { c.get_or_init(|| Mutex::new(default.to_string())) }++// Called from the render tick (holds the engine lock) to refresh the UI caches.+fn publish_ui(state: &EngineState) {+ let fps = if let Some(r) = &state.renderer {+ let elapsed = (Instant::now() - state.start_time).as_secs_f32();+ if elapsed>0.1 { r.frame_count as f32 / elapsed } else { 0.0 }+ } else { 0.0 };+ let debug = serde_json::json!({+ "fps": format!("{:.1}", fps),+ "pos": format!("{:.1},{:.1},{:.1}", state.player.pos.x, state.player.pos.y, state.player.pos.z),+ "yaw": format!("{:.1}", state.player.yaw.to_degrees()),+ "chunks": state.chunks.len(),+ "flying": state.player.flying,+ "on_ground": state.player.on_ground,+ "time": format!("{:.1}s", (Instant::now() - state.start_time).as_secs_f32()),+ "meshes": state.renderer.as_ref().map(|r| r.gpu_meshes.len()).unwrap_or(0),+ "drawn": state.renderer.as_ref().map(|r| r.drawn_sections).unwrap_or(0),+ "gpu": state.renderer.as_ref().map(|r| {+ let p = r.pass_ms;+ 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 inv = state.inventory.to_json();+ if let Ok(mut c) = cref(&DEBUG_CACHE, "{}").lock() { *c = debug; }+ if let Ok(mut c) = cref(&STATS_CACHE, "{}").lock() { *c = stats; }+ if let Ok(mut c) = cref(&INV_CACHE, r#"{"selected":0,"slots":[]}"#).lock() { *c = inv; } } -pub fn get_inventory_json() -> String {- let fresh = with_engine_try(|state| state.inventory.to_json());- cached(&INV_CACHE, r#"{"selected":0,"slots":[]}"#, fresh)-}--pub fn get_stats_json() -> String {- let fresh = with_engine_try(|state| {- let walked = state.player.walk_dist as i32;- let time = (Instant::now() - state.start_time).as_secs_f32();- let day_t = (time / 120.0) % 1.0;- let night = day_t > 0.5 && day_t < 0.92;- serde_json::json!({ "placed": state.inventory.placed, "broken": state.inventory.broken, "walked": walked, "night": night }).to_string()- });- cached(&STATS_CACHE, "{}", fresh)+pub fn get_debug_json() -> String { cref(&DEBUG_CACHE, r#"{"error":"no engine"}"#).lock().map(|c| c.clone()).unwrap_or_else(|_| "{}".into()) }+pub fn get_inventory_json() -> String { cref(&INV_CACHE, r#"{"selected":0,"slots":[]}"#).lock().map(|c| c.clone()).unwrap_or_else(|_| r#"{"selected":0,"slots":[]}"#.into()) }+pub fn get_stats_json() -> String { cref(&STATS_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_craft(recipe: usize) -> bool { with_engine(|s| s.inventory.craft(recipe)).unwrap_or(false) }+pub fn get_recipes_json() -> String {+ let items: Vec<_> = crate::inventory::RECIPES.iter()+ .map(|(iid, ic, oid, oc)| serde_json::json!({"in": iid, "inN": ic, "out": oid, "outN": oc}))+ .collect();+ serde_json::json!(items).to_string() } // Build a world-space pick ray from a tap at pixel (px, py) using a pinhole model matching the@@ -394,9 +397,18 @@ pub fn break_block_at(px: f32, py: f32) -> bool { }).unwrap_or(false) } -pub fn place_block_at(px: f32, py: f32) -> bool {+// 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| { let (o, d) = screen_ray(state, px, py);- do_place(state, o, d)- }).unwrap_or(false)+ // Tapping an interactive block opens its menu — unless sneaking, which places instead.+ if !state.player.sneaking {+ if let Some(hit) = crate::raycast::raycast(&state.chunks, o, d, 6.0) {+ let (x, y, z) = hit.pos;+ let m = crate::world::block::Block::from_id(state.chunks.get_block_world(x, y, z)).menu();+ if m != 0 { return 10 + m; }+ }+ }+ if do_place(state, o, d) { 1 } else { 0 }+ }).unwrap_or(0) }
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 f617f40dbe..0e0860da7c 100644--- a/games/voxels/src/main/rust/src/inventory.rs+++ b/games/voxels/src/main/rust/src/inventory.rs@@ -1,53 +1,128 @@ use serde::{Deserialize, Serialize}; use crate::world::block::Block; -#[derive(Debug, Clone, Serialize, Deserialize)]+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 } impl Default for InvSlot { fn default() -> Self { Self { id: 0, count: 0 } } } #[derive(Debug, Clone, Serialize, Deserialize)]-pub struct Inventory { pub selected: usize, pub slots: [InvSlot; 9], pub placed: i32, pub broken: i32 }+pub struct Inventory {+ pub selected: usize,+ #[serde(with = "serde_slots")]+ pub slots: [InvSlot; SLOTS],+ pub placed: i32,+ pub broken: i32,+}++// (id, in_count, out_id, out_count) — kept in sync with getRecipesJson for the UI.+pub const RECIPES: [(u8, i32, u8, i32); 10] = [+ (Block::Wood as u8, 1, Block::Planks as u8, 4),+ (Block::BirchLog as u8, 1, Block::BirchPlanks as u8, 4),+ (Block::SpruceLog as u8, 1, Block::SprucePlanks as u8,4),+ (Block::Planks as u8, 4, Block::CraftingTable as u8, 1),+ (Block::Cobble as u8, 8, Block::Furnace as u8, 1),+ (Block::Sand as u8, 2, Block::Glass as u8, 1),+ (Block::Cobble as u8, 4, Block::Stone as u8, 1),+ (Block::Diorite as u8, 4, Block::PolishedDiorite as u8, 4),+ (Block::IronOre as u8, 1, Block::IronBlock as u8, 1),+ (Block::DiamondOre as u8,1, Block::DiamondBlock as u8,1),+]; impl Default for Inventory { fn default() -> Self {- Self {- selected: 0,- slots: std::array::from_fn(|i| match i {- 0 => InvSlot{ id: Block::Grass as u8, count: 64 },- 1 => InvSlot{ id: Block::Dirt as u8, count: 64 },- 2 => InvSlot{ id: Block::Stone as u8, count: 64 },- 3 => InvSlot{ id: Block::Wood as u8, count: 16 },- 4 => InvSlot{ id: Block::Planks as u8, count: 32 },- 5 => InvSlot{ id: Block::Sand as u8, count: 32 },- 6 => InvSlot{ id: Block::Glass as u8, count: 16 },- 7 => InvSlot{ id: Block::Cobble as u8, count: 16 },- 8 => InvSlot{ id: Block::Brick as u8, count: 16 },- _ => InvSlot::default(),- }),- placed: 0, broken: 0,- }+ let mut slots = [InvSlot::default(); SLOTS];+ let start = [+ (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 }; }+ Self { selected: 0, slots, placed: 0, broken: 0 } } } impl Inventory { pub fn selected_block(&self) -> u8 {- if self.selected < 9 { let s = &self.slots[self.selected]; if s.count > 0 { s.id } else { 0 } } else { 0 }+ 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> {- if self.selected >=9 { return None; }+ if self.selected >= HOTBAR { return None; } let slot = &mut self.slots[self.selected];- if slot.count <=0 || slot.id==0 { return None; }+ if slot.count <= 0 || slot.id == 0 { return None; } let id = slot.id;- slot.count -=1;- if slot.count <=0 { slot.id = 0; slot.count = 0; }- self.placed +=1;+ slot.count -= 1;+ if slot.count <= 0 { *slot = InvSlot::default(); }+ self.placed += 1; Some(id) } pub fn add_block(&mut self, id: u8) {- if id==0 { return; }- for slot in self.slots.iter_mut() { if slot.id == id && slot.count < 64 { slot.count +=1; return; } }- for slot in self.slots.iter_mut() { if slot.id==0 { slot.id = id; slot.count = 1; return; } }+ if id == 0 { return; }+ for slot in self.slots.iter_mut() { if slot.id == id && slot.count < STACK { slot.count += 1; return; } }+ for slot in self.slots.iter_mut() { if slot.id == 0 { slot.id = id; slot.count = 1; return; } }+ }+ pub fn select(&mut self, idx: usize) { if idx < HOTBAR { self.selected = idx; } }++ // Drag-and-drop: move/merge/swap the stack in `from` into `to`.+ pub fn move_item(&mut self, from: usize, to: usize) {+ if from >= SLOTS || to >= SLOTS || from == to { return; }+ let a = self.slots[from];+ let b = self.slots[to];+ if a.id == 0 { return; }+ if b.id == 0 {+ self.slots[to] = a; self.slots[from] = InvSlot::default();+ } else if a.id == b.id {+ let space = STACK - b.count;+ let mv = a.count.min(space);+ self.slots[to].count += mv;+ self.slots[from].count -= mv;+ if self.slots[from].count <= 0 { self.slots[from] = InvSlot::default(); }+ } else {+ self.slots[from] = b; self.slots[to] = a;+ }+ }++ // Creative catalog: put a full stack of `id` into the first empty (or matching) slot.+ pub fn give(&mut self, id: u8) {+ 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 select(&mut self, idx: usize) { if idx < 9 { self.selected = idx; } }++ 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) {+ for slot in self.slots.iter_mut() {+ if slot.id == id && n > 0 {+ let take = slot.count.min(n);+ slot.count -= take; n -= take;+ if slot.count <= 0 { *slot = InvSlot::default(); }+ }+ }+ }+ pub fn craft(&mut self, recipe: usize) -> bool {+ let Some(&(iid, ic, oid, oc)) = RECIPES.get(recipe) else { return false; };+ if self.count_of(iid) < ic { return false; }+ self.remove_count(iid, ic);+ for _ in 0..oc { self.add_block(oid); }+ true+ }+ pub fn to_json(&self) -> String { serde_json::to_string(self).unwrap_or_else(|_| r#"{"selected":0,"slots":[]}"#.to_string()) } }++// Serialize the fixed-size slot array as a plain list (serde can't derive for [T; 36]).+mod serde_slots {+ use super::{InvSlot, SLOTS};+ use serde::{Deserializer, Serializer, Deserialize, Serialize};+ pub fn serialize<S: Serializer>(slots: &[InvSlot; SLOTS], s: S) -> Result<S::Ok, S::Error> {+ slots.as_slice().serialize(s)+ }+ pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<[InvSlot; SLOTS], D::Error> {+ let v: Vec<InvSlot> = Vec::deserialize(d)?;+ let mut out = [InvSlot::default(); SLOTS];+ for (i, slot) in v.into_iter().enumerate().take(SLOTS) { out[i] = slot; }+ Ok(out)+ }+}
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 599799694e..e91cf6428b 100644--- a/games/voxels/src/main/rust/src/lib.rs+++ b/games/voxels/src/main/rust/src/lib.rs@@ -23,12 +23,13 @@ pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_nativ mut env: JNIEnv<'l>, _class: JClass<'l>, files_dir: JString<'l>,+ seed: jint, ) -> jboolean { let dir = match get_string(&mut env, &files_dir) { Some(d) => d, None => return 0, };- if engine::init_engine(dir) { 1 } else { 0 }+ if engine::init_engine(dir, seed as u32) { 1 } else { 0 } } #[no_mangle]@@ -171,8 +172,8 @@ pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_place _class: JClass<'l>, x: jfloat, y: jfloat,-) -> jboolean {- if engine::place_block_at(x, y) { 1 } else { 0 }+) -> jint {+ engine::place_block_at(x, y) } #[no_mangle]@@ -186,6 +187,35 @@ pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_selec }); } +#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_moveItem<'l>(+ _env: JNIEnv<'l>, _class: JClass<'l>, from: jint, to: jint,+) {+ if from >= 0 && to >= 0 { engine::inventory_move(from as usize, to as usize); }+}++#[no_mangle]+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); }+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_craft<'l>(+ _env: JNIEnv<'l>, _class: JClass<'l>, recipe: jint,+) -> jboolean {+ if recipe >= 0 && engine::inventory_craft(recipe as usize) { 1 } else { 0 }+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_getRecipesJson<'l>(+ mut env: JNIEnv<'l>, _class: JClass<'l>,+) -> jstring {+ let null = std::ptr::null_mut();+ match env.new_string(engine::get_recipes_json()) { Ok(s) => s.into_raw(), Err(_) => null }+}+ #[no_mangle] pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_getInventoryJson<'l>( mut env: JNIEnv<'l>,
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 7e868f2fef..de9e5f08ca 100644--- a/games/voxels/src/main/rust/src/player.rs+++ b/games/voxels/src/main/rust/src/player.rs@@ -9,11 +9,12 @@ pub struct Player { pub on_ground: bool, pub flying: bool, pub walk_dist: f32,+ pub sneaking: bool, } impl Player { pub fn new(x: f32, y: f32, z: f32) -> Self {- Self { pos: vec3(x,y,z), vel: Vec3::ZERO, yaw: 0.0, pitch: 0.0, on_ground: false, flying: false, walk_dist: 0.0 }+ Self { pos: vec3(x,y,z), vel: Vec3::ZERO, yaw: 0.0, pitch: 0.0, on_ground: false, flying: false, walk_dist: 0.0, sneaking: false } } pub fn eye_pos(&self) -> Vec3 { self.pos + vec3(0.0, 1.62, 0.0) } pub fn forward(&self) -> Vec3 {@@ -23,6 +24,7 @@ impl Player { pub fn right(&self) -> Vec3 { vec3(self.yaw.cos(), 0.0, -self.yaw.sin()).normalize_or_zero() } pub fn tick(&mut self, dt: f32, input: &crate::input::InputState, chunks: &ChunkMap) {+ self.sneaking = input.sneak; let fwd = if self.flying { self.forward() } else {
games/voxels/src/main/rust/src/texture_atlas.rs
diff --git a/games/voxels/src/main/rust/src/texture_atlas.rs b/games/voxels/src/main/rust/src/texture_atlas.rsindex efcf834465..9134f20be7 100644--- a/games/voxels/src/main/rust/src/texture_atlas.rs+++ b/games/voxels/src/main/rust/src/texture_atlas.rs@@ -1,10 +1,10 @@ use ash::vk; use crate::vulkan::buffers::AllocatedBuffer; -pub const ATLAS_TILES_PER_ROW: u32 = 4;+pub const ATLAS_TILES_PER_ROW: u32 = 8; pub const ATLAS_TILE_ROWS: u32 = 8; pub const TILE_SIZE: u32 = 16;-pub const ATLAS_W: u32 = ATLAS_TILES_PER_ROW * TILE_SIZE; // 64+pub const ATLAS_W: u32 = ATLAS_TILES_PER_ROW * TILE_SIZE; // 128 pub const ATLAS_H: u32 = ATLAS_TILE_ROWS * TILE_SIZE; // 128 pub struct TextureAtlas {
games/voxels/src/main/rust/src/vulkan/buffers.rs
diff --git a/games/voxels/src/main/rust/src/vulkan/buffers.rs b/games/voxels/src/main/rust/src/vulkan/buffers.rsindex 1b08f0ea2c..8c85e8f5c7 100644--- a/games/voxels/src/main/rust/src/vulkan/buffers.rs+++ b/games/voxels/src/main/rust/src/vulkan/buffers.rs@@ -46,11 +46,13 @@ pub struct UboData { pub cloud_shadow: f32, // strength of cloud shadows cast on terrain (0..1) pub ambient_color: [f32; 3], pub _pad2: f32,+ // Light-space view-projection for sun shadow mapping (orthographic, from the sun toward the scene).+ pub light_view_proj: [[f32; 4]; 4], } impl Default for UboData { fn default() -> Self {- Self { view_proj: glam::Mat4::IDENTITY.to_cols_array_2d(), sun_dir: [0.2, -1.0, 0.3], time: 0.0, fog_color: [0.53, 0.81, 0.92], fog_density: 0.01, player_pos: [0.0, 70.0, 0.0, 0.0], day_factor: 1.0, _pad: [0.0;3], inv_view_proj: glam::Mat4::IDENTITY.to_cols_array_2d(), sun_color: [1.0, 0.97, 0.9], cloud_shadow: 0.6, ambient_color: [0.45, 0.55, 0.72], _pad2: 0.0 }+ Self { view_proj: glam::Mat4::IDENTITY.to_cols_array_2d(), sun_dir: [0.2, -1.0, 0.3], time: 0.0, fog_color: [0.53, 0.81, 0.92], fog_density: 0.01, player_pos: [0.0, 70.0, 0.0, 0.0], day_factor: 1.0, _pad: [0.0;3], inv_view_proj: glam::Mat4::IDENTITY.to_cols_array_2d(), sun_color: [1.0, 0.97, 0.9], cloud_shadow: 0.6, ambient_color: [0.45, 0.55, 0.72], _pad2: 0.0, light_view_proj: glam::Mat4::IDENTITY.to_cols_array_2d() } } }
games/voxels/src/main/rust/src/vulkan/mod.rs
diff --git a/games/voxels/src/main/rust/src/vulkan/mod.rs b/games/voxels/src/main/rust/src/vulkan/mod.rsindex 02328c6cb1..e432665236 100644--- a/games/voxels/src/main/rust/src/vulkan/mod.rs+++ b/games/voxels/src/main/rust/src/vulkan/mod.rs@@ -1,7 +1,9 @@ pub mod buffers; pub mod context; pub mod pipeline;+pub mod postfx; pub mod renderer;+pub mod shadow; pub mod swapchain; pub use context::{ANativeWindow, VulkanContext};
games/voxels/src/main/rust/src/vulkan/pipeline.rs
diff --git a/games/voxels/src/main/rust/src/vulkan/pipeline.rs b/games/voxels/src/main/rust/src/vulkan/pipeline.rsindex 2385075639..5a834a5fa8 100644--- a/games/voxels/src/main/rust/src/vulkan/pipeline.rs+++ b/games/voxels/src/main/rust/src/vulkan/pipeline.rs@@ -4,33 +4,51 @@ const BLOCK_VERT_SPV: &[u8] = include_bytes!("../../shaders/block.vert.spv"); const BLOCK_FRAG_SPV: &[u8] = include_bytes!("../../shaders/block.frag.spv"); const SKY_VERT_SPV: &[u8] = include_bytes!("../../shaders/sky.vert.spv"); const SKY_FRAG_SPV: &[u8] = include_bytes!("../../shaders/sky.frag.spv");+const CLOUD_FRAG_SPV: &[u8] = include_bytes!("../../shaders/cloud.frag.spv");+const SHADOW_VERT_SPV: &[u8] = include_bytes!("../../shaders/shadow.vert.spv");+const WATER_VERT_SPV: &[u8] = include_bytes!("../../shaders/water.vert.spv");+const WATER_FRAG_SPV: &[u8] = include_bytes!("../../shaders/water.frag.spv");+const POST_VERT_SPV: &[u8] = include_bytes!("../../shaders/post.vert.spv");+const BRIGHT_FRAG_SPV: &[u8] = include_bytes!("../../shaders/bright.frag.spv");+const BLUR_FRAG_SPV: &[u8] = include_bytes!("../../shaders/blur.frag.spv");+const COMPOSITE_FRAG_SPV: &[u8] = include_bytes!("../../shaders/composite.frag.spv"); pub struct Pipelines { pub layout: vk::PipelineLayout, pub pipeline: vk::Pipeline, pub sky_pipeline: vk::Pipeline,+ pub cloud_pipeline: vk::Pipeline,+ pub shadow_pipeline: vk::Pipeline,+ pub water_pipeline: vk::Pipeline,+ pub post_layout: vk::PipelineLayout,+ pub bright_pipeline: vk::Pipeline,+ pub blur_pipeline: vk::Pipeline,+ pub composite_pipeline: vk::Pipeline, pub descriptor_set_layout: vk::DescriptorSetLayout, pub descriptor_pool: vk::DescriptorPool, pub descriptor_set: vk::DescriptorSet, } impl Pipelines { // Classic Vulkan 1.0 RenderPass path - no KHR_dynamic_rendering, avoids Unable to load cmd_begin_rendering- pub unsafe fn new(device: &ash::Device, render_pass: vk::RenderPass, ubo_buffer: vk::Buffer, ubo_size: u64, atlas_view: vk::ImageView, atlas_sampler: vk::Sampler) -> Result<Self, String> {+ pub unsafe fn new(device: &ash::Device, render_pass: vk::RenderPass, shadow_render_pass: vk::RenderPass, composite_rp: vk::RenderPass, post_rp: vk::RenderPass, post_desc_layout: vk::DescriptorSetLayout, ubo_buffer: vk::Buffer, ubo_size: u64, atlas_view: vk::ImageView, atlas_sampler: vk::Sampler, shadow_view: vk::ImageView, shadow_sampler: vk::Sampler) -> Result<Self, String> { let bindings = [ vk::DescriptorSetLayoutBinding::default().binding(0).descriptor_type(vk::DescriptorType::UNIFORM_BUFFER).descriptor_count(1).stage_flags(vk::ShaderStageFlags::VERTEX | vk::ShaderStageFlags::FRAGMENT), vk::DescriptorSetLayoutBinding::default().binding(1).descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER).descriptor_count(1).stage_flags(vk::ShaderStageFlags::FRAGMENT),+ vk::DescriptorSetLayoutBinding::default().binding(2).descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER).descriptor_count(1).stage_flags(vk::ShaderStageFlags::FRAGMENT), ]; let dsl = device.create_descriptor_set_layout(&vk::DescriptorSetLayoutCreateInfo::default().bindings(&bindings), None).map_err(|e| format!("dsl {e:?}"))?; let layouts = [dsl]; let layout = device.create_pipeline_layout(&vk::PipelineLayoutCreateInfo::default().set_layouts(&layouts), None).map_err(|e| format!("layout {e:?}"))?;- let pool_sizes = [vk::DescriptorPoolSize::default().ty(vk::DescriptorType::UNIFORM_BUFFER).descriptor_count(2), vk::DescriptorPoolSize::default().ty(vk::DescriptorType::COMBINED_IMAGE_SAMPLER).descriptor_count(2)];+ let pool_sizes = [vk::DescriptorPoolSize::default().ty(vk::DescriptorType::UNIFORM_BUFFER).descriptor_count(2), vk::DescriptorPoolSize::default().ty(vk::DescriptorType::COMBINED_IMAGE_SAMPLER).descriptor_count(4)]; let pool = device.create_descriptor_pool(&vk::DescriptorPoolCreateInfo::default().pool_sizes(&pool_sizes).max_sets(2), None).map_err(|e| format!("pool {e:?}"))?; let sets = device.allocate_descriptor_sets(&vk::DescriptorSetAllocateInfo::default().descriptor_pool(pool).set_layouts(&layouts)).map_err(|e| format!("alloc {e:?}"))?; let set = sets[0]; let buf_info = vk::DescriptorBufferInfo::default().buffer(ubo_buffer).offset(0).range(ubo_size); let img_info = vk::DescriptorImageInfo::default().image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL).image_view(atlas_view).sampler(atlas_sampler);+ let shadow_info = vk::DescriptorImageInfo::default().image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL).image_view(shadow_view).sampler(shadow_sampler); let writes = [ vk::WriteDescriptorSet::default().dst_set(set).dst_binding(0).descriptor_type(vk::DescriptorType::UNIFORM_BUFFER).buffer_info(std::slice::from_ref(&buf_info)),- vk::WriteDescriptorSet::default().dst_set(set).dst_binding(1).descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER).image_info(std::slice::from_ref(&img_info))+ vk::WriteDescriptorSet::default().dst_set(set).dst_binding(1).descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER).image_info(std::slice::from_ref(&img_info)),+ vk::WriteDescriptorSet::default().dst_set(set).dst_binding(2).descriptor_type(vk::DescriptorType::COMBINED_IMAGE_SAMPLER).image_info(std::slice::from_ref(&shadow_info)) ]; device.update_descriptor_sets(&writes, &[]); let vert_mod = Self::create_module(device, BLOCK_VERT_SPV)?;@@ -76,7 +94,86 @@ impl Pipelines { device.destroy_shader_module(sky_vert_mod, None); device.destroy_shader_module(sky_frag_mod, None); - Ok(Self{layout, pipeline: pipes[0], sky_pipeline: sky_pipes[0], descriptor_set_layout: dsl, descriptor_pool: pool, descriptor_set: set})+ // Cloud pipeline: fullscreen volumetric clouds drawn after the sky. Depth-tested (LEQUAL) against+ // terrain but no depth write; writes gl_FragDepth (slab entry) so terrain occludes clouds and+ // vice versa. Premultiplied-alpha blend (ONE, ONE_MINUS_SRC_ALPHA) composites over the scene.+ let cloud_vert_mod = Self::create_module(device, SKY_VERT_SPV)?;+ let cloud_frag_mod = Self::create_module(device, CLOUD_FRAG_SPV)?;+ let cloud_stages = [+ vk::PipelineShaderStageCreateInfo::default().stage(vk::ShaderStageFlags::VERTEX).module(cloud_vert_mod).name(&entry),+ vk::PipelineShaderStageCreateInfo::default().stage(vk::ShaderStageFlags::FRAGMENT).module(cloud_frag_mod).name(&entry)+ ];+ let cloud_vi = vk::PipelineVertexInputStateCreateInfo::default();+ let cloud_ds = vk::PipelineDepthStencilStateCreateInfo::default().depth_test_enable(true).depth_write_enable(false).depth_compare_op(vk::CompareOp::LESS_OR_EQUAL);+ let cloud_att = vk::PipelineColorBlendAttachmentState::default().color_write_mask(vk::ColorComponentFlags::RGBA).blend_enable(true)+ .src_color_blend_factor(vk::BlendFactor::ONE).dst_color_blend_factor(vk::BlendFactor::ONE_MINUS_SRC_ALPHA).color_blend_op(vk::BlendOp::ADD)+ .src_alpha_blend_factor(vk::BlendFactor::ONE).dst_alpha_blend_factor(vk::BlendFactor::ONE_MINUS_SRC_ALPHA).alpha_blend_op(vk::BlendOp::ADD);+ let cloud_cb = vk::PipelineColorBlendStateCreateInfo::default().attachments(std::slice::from_ref(&cloud_att));+ let cloud_pi = vk::GraphicsPipelineCreateInfo::default().stages(&cloud_stages).vertex_input_state(&cloud_vi).input_assembly_state(&ia).viewport_state(&vp_state).rasterization_state(&raster).multisample_state(&ms).depth_stencil_state(&cloud_ds).color_blend_state(&cloud_cb).dynamic_state(&dyn_state).layout(layout).render_pass(render_pass).subpass(0);+ let cloud_pipes = device.create_graphics_pipelines(vk::PipelineCache::null(), std::slice::from_ref(&cloud_pi), None).map_err(|(_, e)| format!("cloud pipe {e:?}"))?;+ device.destroy_shader_module(cloud_vert_mod, None);+ device.destroy_shader_module(cloud_frag_mod, None);++ // Shadow pipeline: depth-only, renders terrain from the sun into the shadow render pass. No+ // fragment shader / color attachment; depth bias reduces shadow acne.+ let shadow_vert_mod = Self::create_module(device, SHADOW_VERT_SPV)?;+ let shadow_stages = [vk::PipelineShaderStageCreateInfo::default().stage(vk::ShaderStageFlags::VERTEX).module(shadow_vert_mod).name(&entry)];+ let shadow_binding = crate::vulkan::buffers::Vertex::binding_description();+ let shadow_attrs = [vk::VertexInputAttributeDescription::default().binding(0).location(0).format(vk::Format::R32G32B32_SFLOAT).offset(0)];+ let shadow_vi = vk::PipelineVertexInputStateCreateInfo::default().vertex_binding_descriptions(std::slice::from_ref(&shadow_binding)).vertex_attribute_descriptions(&shadow_attrs);+ let shadow_raster = vk::PipelineRasterizationStateCreateInfo::default().polygon_mode(vk::PolygonMode::FILL).cull_mode(vk::CullModeFlags::NONE).front_face(vk::FrontFace::COUNTER_CLOCKWISE).line_width(1.0)+ .depth_bias_enable(true).depth_bias_constant_factor(1.5).depth_bias_slope_factor(2.0);+ let shadow_ds = vk::PipelineDepthStencilStateCreateInfo::default().depth_test_enable(true).depth_write_enable(true).depth_compare_op(vk::CompareOp::LESS);+ let shadow_cb = vk::PipelineColorBlendStateCreateInfo::default(); // no color attachments+ let shadow_pi = vk::GraphicsPipelineCreateInfo::default().stages(&shadow_stages).vertex_input_state(&shadow_vi).input_assembly_state(&ia).viewport_state(&vp_state).rasterization_state(&shadow_raster).multisample_state(&ms).depth_stencil_state(&shadow_ds).color_blend_state(&shadow_cb).dynamic_state(&dyn_state).layout(layout).render_pass(shadow_render_pass).subpass(0);+ let shadow_pipes = device.create_graphics_pipelines(vk::PipelineCache::null(), std::slice::from_ref(&shadow_pi), None).map_err(|(_, e)| format!("shadow pipe {e:?}"))?;+ device.destroy_shader_module(shadow_vert_mod, None);++ // Water pipeline: transparent (alpha blend), depth-tested but no depth write, in the main pass.+ let water_vert_mod = Self::create_module(device, WATER_VERT_SPV)?;+ let water_frag_mod = Self::create_module(device, WATER_FRAG_SPV)?;+ let water_stages = [+ vk::PipelineShaderStageCreateInfo::default().stage(vk::ShaderStageFlags::VERTEX).module(water_vert_mod).name(&entry),+ vk::PipelineShaderStageCreateInfo::default().stage(vk::ShaderStageFlags::FRAGMENT).module(water_frag_mod).name(&entry)+ ];+ let water_ds = vk::PipelineDepthStencilStateCreateInfo::default().depth_test_enable(true).depth_write_enable(false).depth_compare_op(vk::CompareOp::LESS_OR_EQUAL);+ let water_att = vk::PipelineColorBlendAttachmentState::default().color_write_mask(vk::ColorComponentFlags::RGBA).blend_enable(true).src_color_blend_factor(vk::BlendFactor::SRC_ALPHA).dst_color_blend_factor(vk::BlendFactor::ONE_MINUS_SRC_ALPHA).color_blend_op(vk::BlendOp::ADD).src_alpha_blend_factor(vk::BlendFactor::ONE).dst_alpha_blend_factor(vk::BlendFactor::ZERO);+ let water_cb = vk::PipelineColorBlendStateCreateInfo::default().attachments(std::slice::from_ref(&water_att));+ let water_pi = vk::GraphicsPipelineCreateInfo::default().stages(&water_stages).vertex_input_state(&vi).input_assembly_state(&ia).viewport_state(&vp_state).rasterization_state(&raster).multisample_state(&ms).depth_stencil_state(&water_ds).color_blend_state(&water_cb).dynamic_state(&dyn_state).layout(layout).render_pass(render_pass).subpass(0);+ let water_pipes = device.create_graphics_pipelines(vk::PipelineCache::null(), std::slice::from_ref(&water_pi), None).map_err(|(_, e)| format!("water pipe {e:?}"))?;+ device.destroy_shader_module(water_vert_mod, None);+ device.destroy_shader_module(water_frag_mod, None);++ // --- Post-processing pipelines (fullscreen): bloom bright/blur + FXAA composite. ---+ let push = vk::PushConstantRange::default().stage_flags(vk::ShaderStageFlags::FRAGMENT).offset(0).size(16);+ let post_set_layouts = [post_desc_layout];+ let post_layout = device.create_pipeline_layout(&vk::PipelineLayoutCreateInfo::default().set_layouts(&post_set_layouts).push_constant_ranges(std::slice::from_ref(&push)), None).map_err(|e| format!("post layout {e:?}"))?;+ let post_vert_mod = Self::create_module(device, POST_VERT_SPV)?;+ let bright_mod = Self::create_module(device, BRIGHT_FRAG_SPV)?;+ let blur_mod = Self::create_module(device, BLUR_FRAG_SPV)?;+ let composite_mod = Self::create_module(device, COMPOSITE_FRAG_SPV)?;+ let empty_vi = vk::PipelineVertexInputStateCreateInfo::default();+ let post_ds = vk::PipelineDepthStencilStateCreateInfo::default().depth_test_enable(false).depth_write_enable(false);+ let post_att = vk::PipelineColorBlendAttachmentState::default().color_write_mask(vk::ColorComponentFlags::RGBA).blend_enable(false);+ let post_cb = vk::PipelineColorBlendStateCreateInfo::default().attachments(std::slice::from_ref(&post_att));+ let mk_post = |device: &ash::Device, frag: vk::ShaderModule, rp: vk::RenderPass| -> Result<vk::Pipeline, String> {+ let stages = [+ vk::PipelineShaderStageCreateInfo::default().stage(vk::ShaderStageFlags::VERTEX).module(post_vert_mod).name(&entry),+ vk::PipelineShaderStageCreateInfo::default().stage(vk::ShaderStageFlags::FRAGMENT).module(frag).name(&entry),+ ];+ let pi = vk::GraphicsPipelineCreateInfo::default().stages(&stages).vertex_input_state(&empty_vi).input_assembly_state(&ia).viewport_state(&vp_state).rasterization_state(&raster).multisample_state(&ms).depth_stencil_state(&post_ds).color_blend_state(&post_cb).dynamic_state(&dyn_state).layout(post_layout).render_pass(rp).subpass(0);+ let p = device.create_graphics_pipelines(vk::PipelineCache::null(), std::slice::from_ref(&pi), None).map_err(|(_, e)| format!("post pipe {e:?}"))?;+ Ok(p[0])+ };+ let bright_pipeline = mk_post(device, bright_mod, post_rp)?;+ let blur_pipeline = mk_post(device, blur_mod, post_rp)?;+ let composite_pipeline = mk_post(device, composite_mod, composite_rp)?;+ device.destroy_shader_module(post_vert_mod, None);+ device.destroy_shader_module(bright_mod, None);+ device.destroy_shader_module(blur_mod, None);+ device.destroy_shader_module(composite_mod, None);++ Ok(Self{layout, pipeline: pipes[0], sky_pipeline: sky_pipes[0], cloud_pipeline: cloud_pipes[0], shadow_pipeline: shadow_pipes[0], water_pipeline: water_pipes[0], post_layout, bright_pipeline, blur_pipeline, composite_pipeline, descriptor_set_layout: dsl, descriptor_pool: pool, descriptor_set: set}) } unsafe fn create_module(device: &ash::Device, spv: &[u8]) -> Result<vk::ShaderModule, String> { let code = unsafe { std::slice::from_raw_parts(spv.as_ptr() as *const u32, spv.len()/4) };@@ -85,6 +182,13 @@ impl Pipelines { pub unsafe fn destroy(&mut self, device: &ash::Device) { device.destroy_pipeline(self.pipeline, None); device.destroy_pipeline(self.sky_pipeline, None);+ device.destroy_pipeline(self.cloud_pipeline, None);+ device.destroy_pipeline(self.shadow_pipeline, None);+ device.destroy_pipeline(self.water_pipeline, None);+ device.destroy_pipeline(self.bright_pipeline, None);+ device.destroy_pipeline(self.blur_pipeline, None);+ device.destroy_pipeline(self.composite_pipeline, None);+ device.destroy_pipeline_layout(self.post_layout, None); device.destroy_pipeline_layout(self.layout, None); device.destroy_descriptor_pool(self.descriptor_pool, None); device.destroy_descriptor_set_layout(self.descriptor_set_layout, None);
games/voxels/src/main/rust/src/vulkan/postfx.rs
diff --git a/games/voxels/src/main/rust/src/vulkan/postfx.rs b/games/voxels/src/main/rust/src/vulkan/postfx.rsnew file mode 100644index 0000000000..cd69b99be5--- /dev/null+++ b/games/voxels/src/main/rust/src/vulkan/postfx.rs@@ -0,0 +1,157 @@+use ash::vk;+use crate::vulkan::swapchain::Swapchain;++pub const HDR_FORMAT: vk::Format = vk::Format::R16G16B16A16_SFLOAT;++// Offscreen HDR pipeline for bloom + FXAA. The world is rendered to `hdr` (linear HDR), a bright-pass ++// separable blur build the bloom in half-res `bloom_a/bloom_b`, then a composite pass (using the+// swapchain's own render pass) does FXAA + bloom add + tonemap to the swapchain.+pub struct PostFx {+ pub main_rp: vk::RenderPass, // -> hdr (+ depth)+ pub post_rp: vk::RenderPass, // -> a bloom target+ pub sampler: vk::Sampler,+ pub desc_layout: vk::DescriptorSetLayout,+ desc_pool: vk::DescriptorPool,+ pub bright_set: vk::DescriptorSet,+ pub blur_h_set: vk::DescriptorSet,+ pub blur_v_set: vk::DescriptorSet,+ pub composite_set: vk::DescriptorSet,++ pub extent: vk::Extent2D,+ pub bloom_extent: vk::Extent2D,+ hdr_img: vk::Image, hdr_mem: vk::DeviceMemory, pub hdr_view: vk::ImageView,+ ba_img: vk::Image, ba_mem: vk::DeviceMemory, pub bloom_a_view: vk::ImageView,+ bb_img: vk::Image, bb_mem: vk::DeviceMemory, pub bloom_b_view: vk::ImageView,+ pub main_fb: vk::Framebuffer,+ pub bloom_a_fb: vk::Framebuffer,+ pub bloom_b_fb: vk::Framebuffer,+}++unsafe fn mem_type(instance: &ash::Instance, phys: vk::PhysicalDevice, bits: u32, props: vk::MemoryPropertyFlags) -> Result<u32, String> {+ let mp = instance.get_physical_device_memory_properties(phys);+ (0..mp.memory_type_count).find(|&i| (bits & (1<<i))!=0 && mp.memory_types[i as usize].property_flags.contains(props)).ok_or("no mem type".into())+}++unsafe fn make_image(instance: &ash::Instance, device: &ash::Device, phys: vk::PhysicalDevice, w: u32, h: u32, format: vk::Format, usage: vk::ImageUsageFlags, aspect: vk::ImageAspectFlags) -> Result<(vk::Image, vk::DeviceMemory, vk::ImageView), String> {+ let ci = vk::ImageCreateInfo::default().image_type(vk::ImageType::TYPE_2D).format(format)+ .extent(vk::Extent3D{width:w.max(1),height:h.max(1),depth:1}).mip_levels(1).array_layers(1)+ .samples(vk::SampleCountFlags::TYPE_1).tiling(vk::ImageTiling::OPTIMAL).usage(usage).initial_layout(vk::ImageLayout::UNDEFINED);+ let img = device.c
Diff truncated.