voxels: some fixes
- Commit
b0d217d20c3ef39b7ddd826698ebff3902c2b47b- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-29 21:52 UTC (4 months ago)
- Parents
10a75fd
Diff
camera/src/main/rust/testdata/output.jpg
diff --git a/camera/src/main/rust/testdata/output.jpg b/camera/src/main/rust/testdata/output.jpgindex 87a2648a8f..0be06f243d 100644Binary files a/camera/src/main/rust/testdata/output.jpg and b/camera/src/main/rust/testdata/output.jpg differ
games/voxels/src/main/assets/block/apple.png
diff --git a/games/voxels/src/main/assets/block/apple.png b/games/voxels/src/main/assets/block/apple.pngnew file mode 100644index 0000000000..bacbe4c746Binary files /dev/null and b/games/voxels/src/main/assets/block/apple.png differ
games/voxels/src/main/assets/block/apple_empanada.png
diff --git a/games/voxels/src/main/assets/block/apple_empanada.png b/games/voxels/src/main/assets/block/apple_empanada.pngnew file mode 100644index 0000000000..313a87e955Binary files /dev/null and b/games/voxels/src/main/assets/block/apple_empanada.png differ
games/voxels/src/main/assets/block/baked_potato.png
diff --git a/games/voxels/src/main/assets/block/baked_potato.png b/games/voxels/src/main/assets/block/baked_potato.pngnew file mode 100644index 0000000000..822b12156cBinary files /dev/null and b/games/voxels/src/main/assets/block/baked_potato.png differ
games/voxels/src/main/assets/block/blessing_deep.png
diff --git a/games/voxels/src/main/assets/block/blessing_deep.png b/games/voxels/src/main/assets/block/blessing_deep.pngnew file mode 100644index 0000000000..cec206071eBinary files /dev/null and b/games/voxels/src/main/assets/block/blessing_deep.png differ
games/voxels/src/main/assets/block/blessing_swift.png
diff --git a/games/voxels/src/main/assets/block/blessing_swift.png b/games/voxels/src/main/assets/block/blessing_swift.pngnew file mode 100644index 0000000000..d596f78433Binary files /dev/null and b/games/voxels/src/main/assets/block/blessing_swift.png differ
games/voxels/src/main/assets/block/blessing_warrior.png
diff --git a/games/voxels/src/main/assets/block/blessing_warrior.png b/games/voxels/src/main/assets/block/blessing_warrior.pngnew file mode 100644index 0000000000..3dbbf27d2dBinary files /dev/null and b/games/voxels/src/main/assets/block/blessing_warrior.png differ
games/voxels/src/main/assets/block/bread.png
diff --git a/games/voxels/src/main/assets/block/bread.png b/games/voxels/src/main/assets/block/bread.pngnew file mode 100644index 0000000000..4d63502496Binary files /dev/null and b/games/voxels/src/main/assets/block/bread.png differ
games/voxels/src/main/assets/block/brownie.png
diff --git a/games/voxels/src/main/assets/block/brownie.png b/games/voxels/src/main/assets/block/brownie.pngnew file mode 100644index 0000000000..1162d3a40dBinary files /dev/null and b/games/voxels/src/main/assets/block/brownie.png differ
games/voxels/src/main/assets/block/carrot.png
diff --git a/games/voxels/src/main/assets/block/carrot.png b/games/voxels/src/main/assets/block/carrot.pngnew file mode 100644index 0000000000..36f23b8911Binary files /dev/null and b/games/voxels/src/main/assets/block/carrot.png differ
games/voxels/src/main/assets/block/chocolate_chip_cookie.png
diff --git a/games/voxels/src/main/assets/block/chocolate_chip_cookie.png b/games/voxels/src/main/assets/block/chocolate_chip_cookie.pngnew file mode 100644index 0000000000..985ee44000Binary files /dev/null and b/games/voxels/src/main/assets/block/chocolate_chip_cookie.png differ
games/voxels/src/main/assets/block/coal.png
diff --git a/games/voxels/src/main/assets/block/coal.png b/games/voxels/src/main/assets/block/coal.pngnew file mode 100644index 0000000000..7fe795c1c5Binary files /dev/null and b/games/voxels/src/main/assets/block/coal.png differ
games/voxels/src/main/assets/block/cooked_cod.png
diff --git a/games/voxels/src/main/assets/block/cooked_cod.png b/games/voxels/src/main/assets/block/cooked_cod.pngnew file mode 100644index 0000000000..d582541e14Binary files /dev/null and b/games/voxels/src/main/assets/block/cooked_cod.png differ
games/voxels/src/main/assets/block/cooked_rabbit.png
diff --git a/games/voxels/src/main/assets/block/cooked_rabbit.png b/games/voxels/src/main/assets/block/cooked_rabbit.pngnew file mode 100644index 0000000000..c7a439084dBinary files /dev/null and b/games/voxels/src/main/assets/block/cooked_rabbit.png differ
games/voxels/src/main/assets/block/cooked_salmon.png
diff --git a/games/voxels/src/main/assets/block/cooked_salmon.png b/games/voxels/src/main/assets/block/cooked_salmon.pngnew file mode 100644index 0000000000..7f404717f4Binary files /dev/null and b/games/voxels/src/main/assets/block/cooked_salmon.png differ
games/voxels/src/main/assets/block/cookie.png
diff --git a/games/voxels/src/main/assets/block/cookie.png b/games/voxels/src/main/assets/block/cookie.pngnew file mode 100644index 0000000000..25a7c2711eBinary files /dev/null and b/games/voxels/src/main/assets/block/cookie.png differ
games/voxels/src/main/assets/block/diamond.png
diff --git a/games/voxels/src/main/assets/block/diamond.png b/games/voxels/src/main/assets/block/diamond.pngnew file mode 100644index 0000000000..e726c0250eBinary files /dev/null and b/games/voxels/src/main/assets/block/diamond.png differ
games/voxels/src/main/assets/block/diamond_boots.png
diff --git a/games/voxels/src/main/assets/block/diamond_boots.png b/games/voxels/src/main/assets/block/diamond_boots.pngnew file mode 100644index 0000000000..40db3e200dBinary files /dev/null and b/games/voxels/src/main/assets/block/diamond_boots.png differ
games/voxels/src/main/assets/block/diamond_chestplate.png
diff --git a/games/voxels/src/main/assets/block/diamond_chestplate.png b/games/voxels/src/main/assets/block/diamond_chestplate.pngnew file mode 100644index 0000000000..3cd6c7abc1Binary files /dev/null and b/games/voxels/src/main/assets/block/diamond_chestplate.png differ
games/voxels/src/main/assets/block/diamond_helmet.png
diff --git a/games/voxels/src/main/assets/block/diamond_helmet.png b/games/voxels/src/main/assets/block/diamond_helmet.pngnew file mode 100644index 0000000000..e7376f3e30Binary files /dev/null and b/games/voxels/src/main/assets/block/diamond_helmet.png differ
games/voxels/src/main/assets/block/diamond_leggings.png
diff --git a/games/voxels/src/main/assets/block/diamond_leggings.png b/games/voxels/src/main/assets/block/diamond_leggings.pngnew file mode 100644index 0000000000..2034ffca6fBinary files /dev/null and b/games/voxels/src/main/assets/block/diamond_leggings.png differ
games/voxels/src/main/assets/block/diamond_pickaxe.png
diff --git a/games/voxels/src/main/assets/block/diamond_pickaxe.png b/games/voxels/src/main/assets/block/diamond_pickaxe.pngnew file mode 100644index 0000000000..1d71df36c7Binary files /dev/null and b/games/voxels/src/main/assets/block/diamond_pickaxe.png differ
games/voxels/src/main/assets/block/diamond_sword.png
diff --git a/games/voxels/src/main/assets/block/diamond_sword.png b/games/voxels/src/main/assets/block/diamond_sword.pngnew file mode 100644index 0000000000..df46285739Binary files /dev/null and b/games/voxels/src/main/assets/block/diamond_sword.png differ
games/voxels/src/main/assets/block/emerald.png
diff --git a/games/voxels/src/main/assets/block/emerald.png b/games/voxels/src/main/assets/block/emerald.pngnew file mode 100644index 0000000000..e663d81f82Binary files /dev/null and b/games/voxels/src/main/assets/block/emerald.png differ
games/voxels/src/main/assets/block/fried_egg.png
diff --git a/games/voxels/src/main/assets/block/fried_egg.png b/games/voxels/src/main/assets/block/fried_egg.pngnew file mode 100644index 0000000000..85d38d22c7Binary files /dev/null and b/games/voxels/src/main/assets/block/fried_egg.png differ
games/voxels/src/main/assets/block/glistering_melon_slice.png
diff --git a/games/voxels/src/main/assets/block/glistering_melon_slice.png b/games/voxels/src/main/assets/block/glistering_melon_slice.pngnew file mode 100644index 0000000000..006f682983Binary files /dev/null and b/games/voxels/src/main/assets/block/glistering_melon_slice.png differ
games/voxels/src/main/assets/block/glow_berry_crumble.png
diff --git a/games/voxels/src/main/assets/block/glow_berry_crumble.png b/games/voxels/src/main/assets/block/glow_berry_crumble.pngnew file mode 100644index 0000000000..1d4fb3d5beBinary files /dev/null and b/games/voxels/src/main/assets/block/glow_berry_crumble.png differ
games/voxels/src/main/assets/block/golden_apple.png
diff --git a/games/voxels/src/main/assets/block/golden_apple.png b/games/voxels/src/main/assets/block/golden_apple.pngnew file mode 100644index 0000000000..0f0a907643Binary files /dev/null and b/games/voxels/src/main/assets/block/golden_apple.png differ
games/voxels/src/main/assets/block/gunpowder.png
diff --git a/games/voxels/src/main/assets/block/gunpowder.png b/games/voxels/src/main/assets/block/gunpowder.pngnew file mode 100644index 0000000000..1f2722581bBinary files /dev/null and b/games/voxels/src/main/assets/block/gunpowder.png differ
games/voxels/src/main/assets/block/heart_container.png
diff --git a/games/voxels/src/main/assets/block/heart_container.png b/games/voxels/src/main/assets/block/heart_container.pngnew file mode 100644index 0000000000..bd340e1dfdBinary files /dev/null and b/games/voxels/src/main/assets/block/heart_container.png differ
games/voxels/src/main/assets/block/honey_bottle.png
diff --git a/games/voxels/src/main/assets/block/honey_bottle.png b/games/voxels/src/main/assets/block/honey_bottle.pngnew file mode 100644index 0000000000..4cffe1dd2bBinary files /dev/null and b/games/voxels/src/main/assets/block/honey_bottle.png differ
games/voxels/src/main/assets/block/iron_boots.png
diff --git a/games/voxels/src/main/assets/block/iron_boots.png b/games/voxels/src/main/assets/block/iron_boots.pngnew file mode 100644index 0000000000..517ac9966fBinary files /dev/null and b/games/voxels/src/main/assets/block/iron_boots.png differ
games/voxels/src/main/assets/block/iron_chestplate.png
diff --git a/games/voxels/src/main/assets/block/iron_chestplate.png b/games/voxels/src/main/assets/block/iron_chestplate.pngnew file mode 100644index 0000000000..51c563e207Binary files /dev/null and b/games/voxels/src/main/assets/block/iron_chestplate.png differ
games/voxels/src/main/assets/block/iron_helmet.png
diff --git a/games/voxels/src/main/assets/block/iron_helmet.png b/games/voxels/src/main/assets/block/iron_helmet.pngnew file mode 100644index 0000000000..d2d781211cBinary files /dev/null and b/games/voxels/src/main/assets/block/iron_helmet.png differ
games/voxels/src/main/assets/block/iron_ingot.png
diff --git a/games/voxels/src/main/assets/block/iron_ingot.png b/games/voxels/src/main/assets/block/iron_ingot.pngnew file mode 100644index 0000000000..02d28a6202Binary files /dev/null and b/games/voxels/src/main/assets/block/iron_ingot.png differ
games/voxels/src/main/assets/block/iron_leggings.png
diff --git a/games/voxels/src/main/assets/block/iron_leggings.png b/games/voxels/src/main/assets/block/iron_leggings.pngnew file mode 100644index 0000000000..ab18f46566Binary files /dev/null and b/games/voxels/src/main/assets/block/iron_leggings.png differ
games/voxels/src/main/assets/block/iron_pickaxe.png
diff --git a/games/voxels/src/main/assets/block/iron_pickaxe.png b/games/voxels/src/main/assets/block/iron_pickaxe.pngnew file mode 100644index 0000000000..fce554b9f8Binary files /dev/null and b/games/voxels/src/main/assets/block/iron_pickaxe.png differ
games/voxels/src/main/assets/block/iron_sword.png
diff --git a/games/voxels/src/main/assets/block/iron_sword.png b/games/voxels/src/main/assets/block/iron_sword.pngnew file mode 100644index 0000000000..82745f0d61Binary files /dev/null and b/games/voxels/src/main/assets/block/iron_sword.png differ
games/voxels/src/main/assets/block/jukebox.png
diff --git a/games/voxels/src/main/assets/block/jukebox.png b/games/voxels/src/main/assets/block/jukebox.pngnew file mode 100644index 0000000000..ff39fa2b3cBinary files /dev/null and b/games/voxels/src/main/assets/block/jukebox.png differ
games/voxels/src/main/assets/block/leather.png
diff --git a/games/voxels/src/main/assets/block/leather.png b/games/voxels/src/main/assets/block/leather.pngnew file mode 100644index 0000000000..29355d3b7dBinary files /dev/null and b/games/voxels/src/main/assets/block/leather.png differ
games/voxels/src/main/assets/block/music_disc_11.png
diff --git a/games/voxels/src/main/assets/block/music_disc_11.png b/games/voxels/src/main/assets/block/music_disc_11.pngnew file mode 100644index 0000000000..382093bdccBinary files /dev/null and b/games/voxels/src/main/assets/block/music_disc_11.png differ
games/voxels/src/main/assets/block/music_disc_13.png
diff --git a/games/voxels/src/main/assets/block/music_disc_13.png b/games/voxels/src/main/assets/block/music_disc_13.pngnew file mode 100644index 0000000000..f9d1dd8979Binary files /dev/null and b/games/voxels/src/main/assets/block/music_disc_13.png differ
games/voxels/src/main/assets/block/music_disc_5.png
diff --git a/games/voxels/src/main/assets/block/music_disc_5.png b/games/voxels/src/main/assets/block/music_disc_5.pngnew file mode 100644index 0000000000..ef3cf0b27bBinary files /dev/null and b/games/voxels/src/main/assets/block/music_disc_5.png differ
games/voxels/src/main/assets/block/music_disc_blocks.png
diff --git a/games/voxels/src/main/assets/block/music_disc_blocks.png b/games/voxels/src/main/assets/block/music_disc_blocks.pngnew file mode 100644index 0000000000..1012b95777Binary files /dev/null and b/games/voxels/src/main/assets/block/music_disc_blocks.png differ
games/voxels/src/main/assets/block/music_disc_bounce.png
diff --git a/games/voxels/src/main/assets/block/music_disc_bounce.png b/games/voxels/src/main/assets/block/music_disc_bounce.pngnew file mode 100644index 0000000000..d10020e03dBinary files /dev/null and b/games/voxels/src/main/assets/block/music_disc_bounce.png differ
games/voxels/src/main/assets/block/music_disc_cat.png
diff --git a/games/voxels/src/main/assets/block/music_disc_cat.png b/games/voxels/src/main/assets/block/music_disc_cat.pngnew file mode 100644index 0000000000..5e624d7d28Binary files /dev/null and b/games/voxels/src/main/assets/block/music_disc_cat.png differ
games/voxels/src/main/assets/block/music_disc_chirp.png
diff --git a/games/voxels/src/main/assets/block/music_disc_chirp.png b/games/voxels/src/main/assets/block/music_disc_chirp.pngnew file mode 100644index 0000000000..5e7c720ad8Binary files /dev/null and b/games/voxels/src/main/assets/block/music_disc_chirp.png differ
games/voxels/src/main/assets/block/potion_fire_resistance.png
diff --git a/games/voxels/src/main/assets/block/potion_fire_resistance.png b/games/voxels/src/main/assets/block/potion_fire_resistance.pngnew file mode 100644index 0000000000..3e126fb84bBinary files /dev/null and b/games/voxels/src/main/assets/block/potion_fire_resistance.png differ
games/voxels/src/main/assets/block/potion_healing.png
diff --git a/games/voxels/src/main/assets/block/potion_healing.png b/games/voxels/src/main/assets/block/potion_healing.pngnew file mode 100644index 0000000000..d4fc3a222cBinary files /dev/null and b/games/voxels/src/main/assets/block/potion_healing.png differ
games/voxels/src/main/assets/block/potion_leaping.png
diff --git a/games/voxels/src/main/assets/block/potion_leaping.png b/games/voxels/src/main/assets/block/potion_leaping.pngnew file mode 100644index 0000000000..a24507c1a8Binary files /dev/null and b/games/voxels/src/main/assets/block/potion_leaping.png differ
games/voxels/src/main/assets/block/potion_night_vision.png
diff --git a/games/voxels/src/main/assets/block/potion_night_vision.png b/games/voxels/src/main/assets/block/potion_night_vision.pngnew file mode 100644index 0000000000..06ac079b73Binary files /dev/null and b/games/voxels/src/main/assets/block/potion_night_vision.png differ
games/voxels/src/main/assets/block/potion_regeneration.png
diff --git a/games/voxels/src/main/assets/block/potion_regeneration.png b/games/voxels/src/main/assets/block/potion_regeneration.pngnew file mode 100644index 0000000000..765da581d5Binary files /dev/null and b/games/voxels/src/main/assets/block/potion_regeneration.png differ
games/voxels/src/main/assets/block/potion_strength.png
diff --git a/games/voxels/src/main/assets/block/potion_strength.png b/games/voxels/src/main/assets/block/potion_strength.pngnew file mode 100644index 0000000000..0698c74c93Binary files /dev/null and b/games/voxels/src/main/assets/block/potion_strength.png differ
games/voxels/src/main/assets/block/potion_swiftness.png
diff --git a/games/voxels/src/main/assets/block/potion_swiftness.png b/games/voxels/src/main/assets/block/potion_swiftness.pngnew file mode 100644index 0000000000..d7ab3de06aBinary files /dev/null and b/games/voxels/src/main/assets/block/potion_swiftness.png differ
games/voxels/src/main/assets/block/redstone.png
diff --git a/games/voxels/src/main/assets/block/redstone.png b/games/voxels/src/main/assets/block/redstone.pngnew file mode 100644index 0000000000..1320a40871Binary files /dev/null and b/games/voxels/src/main/assets/block/redstone.png differ
games/voxels/src/main/assets/block/stick.png
diff --git a/games/voxels/src/main/assets/block/stick.png b/games/voxels/src/main/assets/block/stick.pngnew file mode 100644index 0000000000..70d8625881Binary files /dev/null and b/games/voxels/src/main/assets/block/stick.png differ
games/voxels/src/main/assets/block/stone_pickaxe.png
diff --git a/games/voxels/src/main/assets/block/stone_pickaxe.png b/games/voxels/src/main/assets/block/stone_pickaxe.pngnew file mode 100644index 0000000000..60ceb356eeBinary files /dev/null and b/games/voxels/src/main/assets/block/stone_pickaxe.png differ
games/voxels/src/main/assets/block/stone_sword.png
diff --git a/games/voxels/src/main/assets/block/stone_sword.png b/games/voxels/src/main/assets/block/stone_sword.pngnew file mode 100644index 0000000000..76bc2c5cadBinary files /dev/null and b/games/voxels/src/main/assets/block/stone_sword.png differ
games/voxels/src/main/assets/block/warding_stone.png
diff --git a/games/voxels/src/main/assets/block/warding_stone.png b/games/voxels/src/main/assets/block/warding_stone.pngnew file mode 100644index 0000000000..36011e6788Binary files /dev/null and b/games/voxels/src/main/assets/block/warding_stone.png differ
games/voxels/src/main/assets/block/wood_pickaxe.png
diff --git a/games/voxels/src/main/assets/block/wood_pickaxe.png b/games/voxels/src/main/assets/block/wood_pickaxe.pngnew file mode 100644index 0000000000..78b0cf0380Binary files /dev/null and b/games/voxels/src/main/assets/block/wood_pickaxe.png differ
games/voxels/src/main/assets/block/wood_sword.png
diff --git a/games/voxels/src/main/assets/block/wood_sword.png b/games/voxels/src/main/assets/block/wood_sword.pngnew file mode 100644index 0000000000..43a66716f5Binary files /dev/null and b/games/voxels/src/main/assets/block/wood_sword.png differ
games/voxels/src/main/assets/music/CREDITS.txt
diff --git a/games/voxels/src/main/assets/music/CREDITS.txt b/games/voxels/src/main/assets/music/CREDITS.txtnew file mode 100644index 0000000000..739ac6e291--- /dev/null+++ b/games/voxels/src/main/assets/music/CREDITS.txt@@ -0,0 +1,3 @@+Music tracks under mcl_/ are from VoxeLibre (MineClone) mcl_music, by DarkReaven and Jester,+licensed CC-BY-SA / see https://github.com/VoxeLibre/VoxeLibre (mods/PLAYER/mcl_music).+golden.ogg / lullaby.ogg are from the Matcha Flavoured pack by Klei.
games/voxels/src/main/assets/music/golden.ogg
diff --git a/games/voxels/src/main/assets/music/golden.ogg b/games/voxels/src/main/assets/music/golden.oggnew file mode 100644index 0000000000..3ec4efb530Binary files /dev/null and b/games/voxels/src/main/assets/music/golden.ogg differ
games/voxels/src/main/assets/music/lullaby.ogg
diff --git a/games/voxels/src/main/assets/music/lullaby.ogg b/games/voxels/src/main/assets/music/lullaby.oggnew file mode 100644index 0000000000..f7edfd102bBinary files /dev/null and b/games/voxels/src/main/assets/music/lullaby.ogg differ
games/voxels/src/main/assets/music/mcl_forest.ogg
diff --git a/games/voxels/src/main/assets/music/mcl_forest.ogg b/games/voxels/src/main/assets/music/mcl_forest.oggnew file mode 100644index 0000000000..66eecf5f89Binary files /dev/null and b/games/voxels/src/main/assets/music/mcl_forest.ogg differ
games/voxels/src/main/assets/music/mcl_gift.ogg
diff --git a/games/voxels/src/main/assets/music/mcl_gift.ogg b/games/voxels/src/main/assets/music/mcl_gift.oggnew file mode 100644index 0000000000..8af8d35b66Binary files /dev/null and b/games/voxels/src/main/assets/music/mcl_gift.ogg differ
games/voxels/src/main/assets/music/mcl_mining.ogg
diff --git a/games/voxels/src/main/assets/music/mcl_mining.ogg b/games/voxels/src/main/assets/music/mcl_mining.oggnew file mode 100644index 0000000000..dfa90aebeeBinary files /dev/null and b/games/voxels/src/main/assets/music/mcl_mining.ogg differ
games/voxels/src/main/assets/music/mcl_piano.ogg
diff --git a/games/voxels/src/main/assets/music/mcl_piano.ogg b/games/voxels/src/main/assets/music/mcl_piano.oggnew file mode 100644index 0000000000..243d92b04bBinary files /dev/null and b/games/voxels/src/main/assets/music/mcl_piano.ogg differ
games/voxels/src/main/assets/music/mcl_winter.ogg
diff --git a/games/voxels/src/main/assets/music/mcl_winter.ogg b/games/voxels/src/main/assets/music/mcl_winter.oggnew file mode 100644index 0000000000..ef2fb4cb83Binary files /dev/null and b/games/voxels/src/main/assets/music/mcl_winter.ogg 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 775242568b..bbccfce1d0 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@@ -41,6 +41,7 @@ class MainActivity : ComponentActivity() { 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}]}""") } var debugJson by remember { mutableStateOf("Voxels Engine\nInitializing Vulkan...\nMatcha Atlas 64x64") }+ var healthJson by remember { mutableStateOf("{}") } var showDebug by remember { mutableStateOf(true) } var flying by remember { mutableStateOf(false) } var sneaking by remember { mutableStateOf(false) }@@ -49,7 +50,9 @@ class MainActivity : ComponentActivity() { 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 tradesJson by remember { mutableStateOf("[]") }+ var tradeOpen by remember { mutableStateOf(false) }+ LaunchedEffect(Unit) { if (VoxelsNative.isAvailable) try { recipesJson = VoxelsNative.getRecipesJson(); tradesJson = VoxelsNative.getTradesJson() } catch (_: Exception) {} } var achievementsManager by remember { mutableStateOf<VoxelsAchievementsManager?>(null) } val newAchievement by (achievementsManager?.newAchievement?.collectAsState() ?: remember { mutableStateOf(null) }) @@ -61,11 +64,21 @@ class MainActivity : ComponentActivity() { } LaunchedEffect(Unit) {+ var prevHp = 20f while (isActive) { if (VoxelsNative.isAvailable) { try { inventoryJson = VoxelsNative.getInventoryJson() debugJson = VoxelsNative.getDebugJson()+ try {+ healthJson = VoxelsNative.getHealthJson()+ val hp = org.json.JSONObject(healthJson).optDouble("hp", prevHp.toDouble()).toFloat()+ if (hp < prevHp - 0.5f) {+ if (prevHp - hp > 6f) com.vayunmathur.games.voxels.util.SoundFx.playExplode()+ else com.vayunmathur.games.voxels.util.SoundFx.playHurt()+ }+ prevHp = hp+ } catch (_: Exception) {} try { flying = org.json.JSONObject(debugJson).optBoolean("flying", flying) } catch (_: Exception) {} val stats = VoxelsNative.getStatsJson() try {@@ -113,6 +126,12 @@ class MainActivity : ComponentActivity() { when (VoxelsNative.placeBlockAt(off.x, off.y)) { 1 -> com.vayunmathur.games.voxels.util.SoundFx.playPlace() 11, 12 -> { invStartTab = 2; inventoryOpen = true } // crafting table / furnace+ 13 -> { // jukebox: play the held disc (or stop)+ val inv = try { kotlinx.serialization.json.Json { ignoreUnknownKeys = true }.decodeFromString<com.vayunmathur.games.voxels.ui.InventoryState>(inventoryJson) } catch (_: Exception) { null }+ val held = inv?.slots?.getOrNull(inv.selected)?.id ?: 0+ com.vayunmathur.games.voxels.util.MusicFx.toggle(this@MainActivity, com.vayunmathur.games.voxels.ui.discTrack[held])+ }+ 20 -> tradeOpen = true // villager } } catch (_: Exception) {} }, onBreak = { off -> try { if (VoxelsNative.breakBlockAt(off.x, off.y)) com.vayunmathur.games.voxels.util.SoundFx.playBreak() } catch (_: Exception) {} }@@ -164,6 +183,11 @@ class MainActivity : ComponentActivity() { } } + // Health/effects HUD just above the hotbar.+ Box(Modifier.align(Alignment.BottomStart).padding(start = 16.dp, bottom = 78.dp)) {+ HealthOverlay(healthJson)+ }+ Box(Modifier.align(Alignment.BottomCenter).padding(bottom = 12.dp)) { Hotbar(inventoryJson = inventoryJson, onSelect = { slot -> if (VoxelsNative.isAvailable) try { VoxelsNative.selectSlot(slot) } catch (_: Exception) {} },@@ -191,6 +215,10 @@ class MainActivity : ComponentActivity() { InventoryOverlay(inventoryJson = inventoryJson, recipesJson = recipesJson, onClose = { inventoryOpen = false }, startTab = invStartTab) } + if (tradeOpen && VoxelsNative.isAvailable) {+ TradeOverlay(tradesJson = tradesJson, onClose = { tradeOpen = false })+ }+ if (paused) { Box( Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.6f))@@ -214,6 +242,7 @@ class MainActivity : ComponentActivity() { } override fun onDestroy() {+ com.vayunmathur.games.voxels.util.MusicFx.stop() if (VoxelsNative.isAvailable) { try { VoxelsNative.nativeOnDestroy() } catch (_: Exception) {} } super.onDestroy() }
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 236d282c5f..599bf5e12c 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@@ -6,6 +6,7 @@ import androidx.compose.foundation.border 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.fillMaxWidth import androidx.compose.foundation.layout.padding@@ -30,7 +31,10 @@ import kotlinx.serialization.json.Json 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) })+data class InventoryState(val selected: Int = 0, val slots: List<InvSlot> = List(9) { InvSlot(0, 0) }, val armor: List<InvSlot> = emptyList())++// Ids 163..178 are tools/armor whose slot `count` is durability (not a stack size).+fun isDurabilityItem(id: Int) = id in 163..178 val blockNames = mapOf( 0 to "·", 1 to "Stone", 2 to "Dirt", 3 to "Grass", 4 to "Wood", 5 to "Leaves",@@ -47,7 +51,27 @@ val blockNames = mapOf( 61 to "Tube Coral", 62 to "Brain Coral", 63 to "Bubble Coral", 64 to "Fire Coral", 65 to "Horn Coral", 66 to "Kelp", 67 to "Sea Lantern", 68 to "Prismarine", 69 to "Dark Prismarine", 70 to "Dripstone", 71 to "Moss Block", 72 to "Sculk", 73 to "Amethyst", 74 to "Calcite", 75 to "Tuff",- 76 to "Magma", 77 to "Glowstone", 78 to "Obsidian", 79 to "Clay", 80 to "Azalea Leaves"+ 76 to "Magma", 77 to "Glowstone", 78 to "Obsidian", 79 to "Clay", 80 to "Azalea Leaves", 81 to "Warding Stone",+ // Items (128+): consumables + materials.+ 128 to "Estus Flask", 129 to "Heart Container", 130 to "Apple", 131 to "Bread", 132 to "Cooked Fish",+ 133 to "Golden Apple", 134 to "Brownie", 135 to "Carrot", 136 to "Melon Slice", 137 to "Leather", 138 to "Gunpowder",+ 146 to "Baked Potato", 147 to "Cookie", 148 to "Cooked Salmon", 149 to "Fried Egg", 150 to "Cooked Rabbit",+ 151 to "Apple Empanada", 152 to "Glow Berry Crumble", 153 to "Choc-Chip Cookie",+ 154 to "Iron Ingot", 155 to "Diamond", 156 to "Emerald", 157 to "Coal", 158 to "Redstone", 159 to "Stick",+ 160 to "Blessing of Swiftness", 161 to "Blessing of the Warrior", 162 to "Blessing of the Deep",+ 163 to "Wood Pickaxe", 164 to "Wood Sword", 165 to "Stone Pickaxe", 166 to "Stone Sword",+ 167 to "Iron Pickaxe", 168 to "Iron Sword", 169 to "Diamond Pickaxe", 170 to "Diamond Sword",+ 171 to "Iron Helmet", 172 to "Iron Chestplate", 173 to "Iron Leggings", 174 to "Iron Boots",+ 175 to "Diamond Helmet", 176 to "Diamond Chestplate", 177 to "Diamond Leggings", 178 to "Diamond Boots",+ 82 to "Jukebox",+ 179 to "Disc: Golden", 180 to "Disc: Lullaby", 181 to "Disc: Forest", 182 to "Disc: Deep Mining",+ 183 to "Disc: Winter", 184 to "Disc: Piano", 185 to "Disc: Gift"+)++// Music disc item id -> track asset in assets/music/.+val discTrack = mapOf(+ 179 to "golden.ogg", 180 to "lullaby.ogg", 181 to "mcl_forest.ogg", 182 to "mcl_mining.ogg",+ 183 to "mcl_winter.ogg", 184 to "mcl_piano.ogg", 185 to "mcl_gift.ogg" ) val blockIconFile = mapOf(@@ -69,7 +93,20 @@ val blockIconFile = mapOf( 61 to "tube_coral.png", 62 to "brain_coral.png", 63 to "bubble_coral.png", 64 to "fire_coral.png", 65 to "horn_coral.png", 66 to "kelp.png", 67 to "sea_lantern.png", 68 to "prismarine.png", 69 to "dark_prismarine.png", 70 to "dripstone.png", 71 to "moss_block.png", 72 to "sculk.png", 73 to "amethyst.png", 74 to "calcite.png",- 75 to "tuff.png", 76 to "magma.png", 77 to "glowstone.png", 78 to "obsidian.png", 79 to "clay.png", 80 to "azalea_leaves.png"+ 75 to "tuff.png", 76 to "magma.png", 77 to "glowstone.png", 78 to "obsidian.png", 79 to "clay.png", 80 to "azalea_leaves.png", 81 to "warding_stone.png",+ 128 to "honey_bottle.png", 129 to "heart_container.png", 130 to "apple.png", 131 to "bread.png", 132 to "cooked_cod.png",+ 133 to "golden_apple.png", 134 to "brownie.png", 135 to "carrot.png", 136 to "glistering_melon_slice.png", 137 to "leather.png", 138 to "gunpowder.png",+ 146 to "baked_potato.png", 147 to "cookie.png", 148 to "cooked_salmon.png", 149 to "fried_egg.png", 150 to "cooked_rabbit.png",+ 151 to "apple_empanada.png", 152 to "glow_berry_crumble.png", 153 to "chocolate_chip_cookie.png",+ 154 to "iron_ingot.png", 155 to "diamond.png", 156 to "emerald.png", 157 to "coal.png", 158 to "redstone.png", 159 to "stick.png",+ 160 to "blessing_swift.png", 161 to "blessing_warrior.png", 162 to "blessing_deep.png",+ 163 to "wood_pickaxe.png", 164 to "wood_sword.png", 165 to "stone_pickaxe.png", 166 to "stone_sword.png",+ 167 to "iron_pickaxe.png", 168 to "iron_sword.png", 169 to "diamond_pickaxe.png", 170 to "diamond_sword.png",+ 171 to "iron_helmet.png", 172 to "iron_chestplate.png", 173 to "iron_leggings.png", 174 to "iron_boots.png",+ 175 to "diamond_helmet.png", 176 to "diamond_chestplate.png", 177 to "diamond_leggings.png", 178 to "diamond_boots.png",+ 82 to "jukebox.png",+ 179 to "music_disc_13.png", 180 to "music_disc_cat.png", 181 to "music_disc_blocks.png", 182 to "music_disc_chirp.png",+ 183 to "music_disc_5.png", 184 to "music_disc_11.png", 185 to "music_disc_bounce.png" ) // Creative catalog, split into tabs.@@ -77,7 +114,13 @@ val catalogNatural = listOf(3, 2, 40, 46, 60, 39, 41, 71, 1, 6, 38, 36, 37, 14, 4, 5, 26, 28, 29, 31, 47, 48, 50, 51, 80, 11, 42, 43, 44, 32, 13) val catalogOres = listOf(18, 19, 20, 21, 22, 23, 24, 25, 73) val catalogOcean = listOf(61, 62, 63, 64, 65, 66, 67, 68, 69)-val catalogBuilding = listOf(10, 27, 30, 49, 52, 8, 57, 9, 53, 54, 55, 56, 58, 59, 72, 74, 76, 77, 78, 7, 33, 34, 35)+val catalogItems = listOf(128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138,+ 146, 147, 148, 149, 150, 151, 152, 153,+ 154, 155, 156, 157, 158, 159, 160, 161, 162)+val catalogGear = listOf(163, 164, 165, 166, 167, 168, 169, 170,+ 171, 172, 173, 174, 175, 176, 177, 178)+val catalogMusic = listOf(82, 179, 180, 181, 182, 183, 184, 185)+val catalogBuilding = listOf(10, 27, 30, 49, 52, 8, 57, 9, 53, 54, 55, 56, 58, 59, 72, 74, 76, 77, 78, 81, 7, 33, 34, 35) @Composable fun rememberBlockIcon(id: Int): androidx.compose.ui.graphics.ImageBitmap? {@@ -133,7 +176,7 @@ fun Hotbar( Text(text = blockNames[slot.id]?.take(2) ?: "${slot.id}", style = MaterialTheme.typography.labelSmall, color = Color.White) } }- if (slot.count > 1) {+ if (slot.count > 1 && !isDurabilityItem(slot.id)) { Box(Modifier.align(Alignment.BottomEnd).background(Color.Black.copy(alpha = 0.7f), RoundedCornerShape(4.dp)).padding(horizontal = 3.dp, vertical = 1.dp)) { Text(text = "${slot.count}", style = MaterialTheme.typography.labelSmall, color = Color.White) }@@ -152,6 +195,59 @@ fun Hotbar( } } +@Serializable+data class EffJson(val k: String = "", val amp: Int = 0, val t: Int = 0)++@Serializable+data class HealthJson(val hp: Float = 20f, val max: Float = 20f, val absorb: Float = 0f, val dead: Boolean = false, val estus: Int = 0, val effects: List<EffJson> = emptyList())++private val effectNames = mapOf(+ "regen" to "Regen", "poison" to "Poison", "resist" to "Resist", "strength" to "Strength",+ "speed" to "Speed", "haste" to "Haste", "absorb" to "Absorption", "fireres" to "Fire Res",+ "night" to "Night Vis", "jump" to "Leaping", "slow" to "Slowness"+)+private val effectColors = mapOf(+ "regen" to Color(0xFFE573B5), "poison" to Color(0xFF6DA33A), "resist" to Color(0xFF9E9E9E),+ "strength" to Color(0xFF932423), "speed" to Color(0xFF7CAFC6), "haste" to Color(0xFFD9C043),+ "absorb" to Color(0xFFF2C15A), "fireres" to Color(0xFFE0913A),+ "night" to Color(0xFF3B3BA0), "jump" to Color(0xFF34A02C), "slow" to Color(0xFF5A6472)+)++private fun roman(n: Int) = when (n) { 0 -> ""; 1 -> " II"; 2 -> " III"; 3 -> " IV"; else -> " ${n + 1}" }++@Composable+fun HealthOverlay(healthJson: String, modifier: Modifier = Modifier) {+ val h = remember(healthJson) {+ try { Json { ignoreUnknownKeys = true }.decodeFromString<HealthJson>(healthJson) } catch (_: Exception) { HealthJson() }+ }+ Column(modifier, horizontalAlignment = Alignment.Start) {+ // Effects (above the hearts).+ if (h.effects.isNotEmpty()) {+ Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {+ h.effects.forEach { e ->+ Box(Modifier.clip(RoundedCornerShape(4.dp)).background((effectColors[e.k] ?: Color.Gray).copy(alpha = 0.85f)).padding(horizontal = 5.dp, vertical = 1.dp)) {+ Text("${effectNames[e.k] ?: e.k}${roman(e.amp)} ${e.t}s", style = MaterialTheme.typography.labelSmall, color = Color.White)+ }+ }+ }+ }+ // Hearts (each = 2 HP); absorption shown as gold hearts appended.+ val totalHearts = (h.max / 2f).toInt().coerceIn(1, 30)+ Row {+ for (i in 0 until totalHearts) {+ val filled = h.hp / 2f - i+ val c = when { filled >= 1f -> Color(0xFFE23A45); filled >= 0.5f -> Color(0xFFEE8891); else -> Color(0xFF3A1516) }+ Text("♥", color = c, style = MaterialTheme.typography.bodyMedium)+ }+ val absHearts = (h.absorb / 2f).toInt().coerceIn(0, 10)+ for (i in 0 until absHearts) { Text("♥", color = Color(0xFFF2C15A), style = MaterialTheme.typography.bodyMedium) }+ }+ if (h.estus > 0) {+ Text("Estus ×${h.estus}", color = Color(0xFFFFC957), style = MaterialTheme.typography.labelSmall)+ }+ }+}+ @Composable fun DebugOverlay(debugJson: String, modifier: Modifier = Modifier) { Box(modifier = modifier.background(Color.Black.copy(alpha = 0.5f), RoundedCornerShape(6.dp)).padding(6.dp)) {
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.ktindex 247ed5b3e9..b9d070de82 100644--- 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.kt@@ -79,7 +79,7 @@ fun InventoryOverlay(inventoryJson: String, recipesJson: String, onClose: () -> } drag = null }, onDragCancel = { drag = null })- 1 -> Text("Outfit — coming soon", color = Color.White.copy(0.7f), modifier = Modifier.padding(24.dp))+ 1 -> OutfitView(inv.armor) else -> CraftingTable(recipesJson) } }@@ -90,10 +90,13 @@ fun InventoryOverlay(inventoryJson: String, recipesJson: String, onClose: () -> TabButton("Natural", catTab == 0) { catTab = 0 } TabButton("Ores", catTab == 1) { catTab = 1 } TabButton("Ocean", catTab == 3) { catTab = 3 }+ TabButton("Items", catTab == 4) { catTab = 4 }+ TabButton("Gear", catTab == 6) { catTab = 6 }+ TabButton("Music", catTab == 7) { catTab = 7 } TabButton("Build", catTab == 2) { catTab = 2 } } Spacer(Modifier.height(8.dp))- val cat = when (catTab) { 0 -> catalogNatural; 1 -> catalogOres; 3 -> catalogOcean; else -> catalogBuilding }+ val cat = when (catTab) { 0 -> catalogNatural; 1 -> catalogOres; 3 -> catalogOcean; 4 -> catalogItems; 6 -> catalogGear; 7 -> catalogMusic; else -> catalogBuilding } CatalogGrid(cat) { id -> try { VoxelsNative.giveBlock(id) } catch (_: Exception) {} } } }@@ -212,7 +215,7 @@ private fun CraftingTable(recipesJson: String) { 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"))+ Recipe(o.getInt("in"), o.getInt("inN"), o.optInt("in2", 0), o.optInt("in2N", 0), o.getInt("out"), o.getInt("outN")) } } catch (_: Exception) { emptyList() } }@@ -244,9 +247,12 @@ private fun CraftingTable(recipesJson: String) { 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) }+ when {+ r == null -> GridCell(0, 0)+ idx == 0 -> GridCell(r.inId, r.inN)+ idx == 1 && r.in2Id != 0 -> GridCell(r.in2Id, r.in2N)+ else -> GridCell(0, 0)+ } } } }@@ -263,4 +269,27 @@ private fun CraftingTable(recipesJson: String) { } } -private data class Recipe(val inId: Int, val inN: Int, val outId: Int, val outN: Int)+private data class Recipe(val inId: Int, val inN: Int, val in2Id: Int, val in2N: Int, val outId: Int, val outN: Int)++@Composable+private fun OutfitView(armor: List<InvSlot>) {+ val labels = listOf("Helmet", "Chestplate", "Leggings", "Boots")+ Column(Modifier.padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(12.dp)) {+ Text("Equipped Armor", color = Color.White, fontWeight = FontWeight.SemiBold, fontSize = 16.sp)+ Text("Hold an armor piece in-hand to equip it.", color = Color.White.copy(0.6f), fontSize = 12.sp)+ for (i in 0 until 4) {+ val s = armor.getOrNull(i) ?: InvSlot(0, 0)+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {+ Box(+ Modifier.size(48.dp).clip(RoundedCornerShape(8.dp)).background(Color.Black.copy(0.4f))+ .border(1.dp, Color.White.copy(0.15f), RoundedCornerShape(8.dp)),+ contentAlignment = Alignment.Center+ ) {+ val icon = if (s.id != 0) rememberBlockIcon(s.id) else null+ if (icon != null) Image(bitmap = icon, contentDescription = null, modifier = Modifier.size(34.dp), filterQuality = FilterQuality.None)+ }+ Text(if (s.id != 0) (blockNames[s.id] ?: "?") else "${labels[i]}: empty", color = Color.White.copy(if (s.id != 0) 0.95f else 0.5f))+ }+ }+ }+}
games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/TradeScreen.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/TradeScreen.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/TradeScreen.ktnew file mode 100644index 0000000000..1c86b77298--- /dev/null+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/TradeScreen.kt@@ -0,0 +1,80 @@+package com.vayunmathur.games.voxels.ui++import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.foundation.layout.*+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.FilterQuality+import androidx.compose.ui.input.pointer.pointerInput+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++private data class Trade(val cost: Int, val costN: Int, val give: Int, val giveN: Int)++@Composable+fun TradeOverlay(tradesJson: String, onClose: () -> Unit) {+ val trades = remember(tradesJson) {+ try {+ val arr = org.json.JSONArray(tradesJson)+ (0 until arr.length()).map { i ->+ val o = arr.getJSONObject(i)+ Trade(o.getInt("cost"), o.getInt("costN"), o.getInt("give"), o.getInt("giveN"))+ }+ } catch (_: Exception) { emptyList() }+ }+ Box(+ Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.6f)).pointerInput(Unit) { detectTapGestures { onClose() } },+ contentAlignment = Alignment.Center+ ) {+ Column(+ Modifier.fillMaxWidth(0.7f).fillMaxHeight(0.8f).clip(RoundedCornerShape(14.dp)).background(Color(0xF01A1E1A))+ .pointerInput(Unit) { detectTapGestures { } }.padding(16.dp),+ horizontalAlignment = Alignment.CenterHorizontally+ ) {+ Text("Villager Trades", color = Color.White, fontSize = 18.sp)+ Text("Tap a trade to exchange (need the cost items).", color = Color.White.copy(0.6f), fontSize = 12.sp)+ Spacer(Modifier.height(10.dp))+ LazyColumn(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp)) {+ items(trades.withIndex().toList()) { (i, t) ->+ Row(+ Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(Color.White.copy(0.07f))+ .clickable { try { if (VoxelsNative.trade(i)) com.vayunmathur.games.voxels.util.SoundFx.playPlace() } catch (_: Exception) {} }+ .padding(10.dp),+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ ItemChip(t.cost, t.costN)+ Text("→", color = Color.White.copy(0.8f), fontSize = 20.sp)+ ItemChip(t.give, t.giveN)+ }+ }+ }+ Spacer(Modifier.height(8.dp))+ Box(Modifier.clip(RoundedCornerShape(8.dp)).background(Color(0xFF3A6B3A)).clickable { onClose() }.padding(horizontal = 24.dp, vertical = 8.dp)) {+ Text("Close", color = Color.White)+ }+ }+ }+}++@Composable+private fun ItemChip(id: Int, count: Int) {+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {+ val icon = rememberBlockIcon(id)+ Box(Modifier.size(40.dp).clip(RoundedCornerShape(6.dp)).background(Color.Black.copy(0.4f)), contentAlignment = Alignment.Center) {+ if (icon != null) Image(bitmap = icon, contentDescription = null, modifier = Modifier.size(28.dp), filterQuality = FilterQuality.None)+ }+ Text("${count}× ${blockNames[id] ?: id}", color = Color.White, fontSize = 12.sp)+ }+}
games/voxels/src/main/java/com/vayunmathur/games/voxels/util/MusicFx.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/MusicFx.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/MusicFx.ktnew file mode 100644index 0000000000..2eda136513--- /dev/null+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/MusicFx.kt@@ -0,0 +1,35 @@+package com.vayunmathur.games.voxels.util++import android.content.Context+import android.media.MediaPlayer++// Looping jukebox music played from assets/music/*.ogg. Best-effort; never throws into the UI.+object MusicFx {+ private var mp: MediaPlayer? = null+ private var current: String? = null++ // Toggle a track: tapping the jukebox with the same disc stops it; a different disc switches;+ // a null asset (holding no disc) stops.+ fun toggle(ctx: Context, asset: String?) {+ if (asset == null || asset == current) { stop(); return }+ stop()+ try {+ val afd = ctx.assets.openFd("music/$asset")+ val p = MediaPlayer()+ p.setDataSource(afd.fileDescriptor, afd.startOffset, afd.length)+ afd.close()+ p.isLooping = true+ p.setOnPreparedListener { it.start() }+ p.setOnErrorListener { _, _, _ -> stop(); true }+ p.prepareAsync()+ mp = p+ current = asset+ } catch (_: Throwable) { stop() }+ }++ fun stop() {+ try { mp?.let { if (it.isPlaying) it.stop(); it.release() } } catch (_: Throwable) {}+ mp = null+ current = null+ }+}
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.ktindex 17f8628254..f93a4fdc61 100644--- 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.kt@@ -14,19 +14,28 @@ object SoundFx { private var pool: SoundPool? = null private var breakId = 0 private var placeId = 0+ private var hurtId = 0+ private var eatId = 0+ private var explodeId = 0 fun init(ctx: Context) { if (pool != null) return try {- val p = SoundPool.Builder().setMaxStreams(4).build()+ val p = SoundPool.Builder().setMaxStreams(6).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)+ hurtId = p.load(wav(ctx, "vox_hurt.wav", gen(90.0, 0.22, 0.7, true)), 1)+ eatId = p.load(wav(ctx, "vox_eat.wav", gen(200.0, 0.10, 0.4, true)), 1)+ explodeId = p.load(wav(ctx, "vox_explode.wav", gen(60.0, 0.5, 0.9, true)), 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) {} }+ fun playHurt() { try { pool?.play(hurtId, 0.7f, 0.7f, 1, 0, 1f) } catch (_: Throwable) {} }+ fun playEat() { try { pool?.play(eatId, 0.5f, 0.5f, 1, 0, 1f) } catch (_: Throwable) {} }+ fun playExplode() { try { pool?.play(explodeId, 0.9f, 0.9f, 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 {
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 34dae200b1..8103e2b08e 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@@ -30,8 +30,11 @@ object VoxelsNative { external fun moveItem(from: Int, to: Int) external fun giveBlock(id: Int) external fun craft(recipe: Int): Boolean+ external fun trade(index: Int): Boolean external fun getRecipesJson(): String+ external fun getTradesJson(): String external fun getInventoryJson(): String external fun getDebugJson(): String external fun getStatsJson(): String+ external fun getHealthJson(): String }
games/voxels/src/main/rust/Cargo.lock
diff --git a/games/voxels/src/main/rust/Cargo.lock b/games/voxels/src/main/rust/Cargo.lockindex 6a54c10de8..d4b87a3195 100644--- a/games/voxels/src/main/rust/Cargo.lock+++ b/games/voxels/src/main/rust/Cargo.lock@@ -102,17 +102,12 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "jni" version = "0.21.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" dependencies = [ "cesu8",- "cfg-if", "combine", "jni-sys 0.3.1", "log", "thiserror",- "walkdir",- "windows-sys 0.45.0", ] [[package]]@@ -274,15 +269,6 @@ dependencies = [ "rand_core", ] -[[package]]-name = "same-file"-version = "1.0.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"-dependencies = [- "winapi-util",-]- [[package]] name = "serde" version = "1.0.229"@@ -394,112 +380,18 @@ dependencies = [ "serde_json", ] -[[package]]-name = "walkdir"-version = "2.5.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"-dependencies = [- "same-file",- "winapi-util",-]- [[package]] name = "wasi" version = "0.9.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" -[[package]]-name = "winapi-util"-version = "0.1.11"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"-dependencies = [- "windows-sys 0.61.2",-]- [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" -[[package]]-name = "windows-sys"-version = "0.45.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"-dependencies = [- "windows-targets",-]--[[package]]-name = "windows-sys"-version = "0.61.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"-dependencies = [- "windows-link",-]--[[package]]-name = "windows-targets"-version = "0.42.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"-dependencies = [- "windows_aarch64_gnullvm",- "windows_aarch64_msvc",- "windows_i686_gnu",- "windows_i686_msvc",- "windows_x86_64_gnu",- "windows_x86_64_gnullvm",- "windows_x86_64_msvc",-]--[[package]]-name = "windows_aarch64_gnullvm"-version = "0.42.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"--[[package]]-name = "windows_aarch64_msvc"-version = "0.42.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"--[[package]]-name = "windows_i686_gnu"-version = "0.42.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"--[[package]]-name = "windows_i686_msvc"-version = "0.42.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"--[[package]]-name = "windows_x86_64_gnu"-version = "0.42.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"--[[package]]-name = "windows_x86_64_gnullvm"-version = "0.42.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"--[[package]]-name = "windows_x86_64_msvc"-version = "0.42.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"- [[package]] name = "zerocopy" version = "0.8.55"
games/voxels/src/main/rust/Cargo.toml
diff --git a/games/voxels/src/main/rust/Cargo.toml b/games/voxels/src/main/rust/Cargo.tomlindex 3ebc5ef2f8..2bd1e38b88 100644--- a/games/voxels/src/main/rust/Cargo.toml+++ b/games/voxels/src/main/rust/Cargo.toml@@ -1,6 +1,9 @@-# Standalone crate (built directly by Gradle); detached from any parent workspace Cargo.toml. [workspace] +[workspace.dependencies]+# Mirrors root workspace catalog to avoid duplicate JNI/Walkdir/Windows pulling in voxels+jni = { path = "../../../../../third_party/jni-android", version = "0.21" }+ [package] name = "voxels_engine" version = "0.1.0"@@ -13,7 +16,7 @@ name = "voxels_engine" crate-type = ["cdylib", "rlib"] [dependencies]-jni = "0.21"+jni.workspace = true ash = { version = "0.38", default-features = false, features = ["loaded"] } hashbrown = "0.14" noise = "0.8"
games/voxels/src/main/rust/rust-toolchain.toml
diff --git a/games/voxels/src/main/rust/rust-toolchain.toml b/games/voxels/src/main/rust/rust-toolchain.tomldeleted file mode 100644index fa6ac3abd8..0000000000--- a/games/voxels/src/main/rust/rust-toolchain.toml+++ /dev/null@@ -1,3 +0,0 @@-[toolchain]-channel = "1.97.0"-targets = ["aarch64-linux-android"]
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 0db14482a3..034ff37573 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 d376bd9053..6036231648 100644--- a/games/voxels/src/main/rust/shaders/block.frag+++ b/games/voxels/src/main/rust/shaders/block.frag@@ -7,6 +7,7 @@ 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(location=8) in float fragLight; // packed skylight + blocklight*16 layout(binding=0) uniform Ubo { mat4 viewProj;@@ -107,7 +108,14 @@ void main() { vec3 ambient = ambientColor * mix(0.55, 1.0, hemi); float aoFactor = mix(0.5, 1.0, fragAo); // per-corner ambient occlusion - vec3 lit = albedo * (sunColor * NdotL * shadow + ambient) * aoFactor;+ // Dynamic lighting: sky exposure gates sun+ambient (so caves/overhangs go dark), block light is+ // additive emissive (torches/glowstone glow warm). Tiny floor keeps unlit areas barely visible.+ float sky = mod(fragLight, 16.0) / 15.0;+ float blockL = floor(fragLight / 16.0) / 15.0;+ vec3 blockLightCol = vec3(1.0, 0.82, 0.5) * (blockL * blockL);+ vec3 lit = albedo * ((sunColor * NdotL * shadow + ambient) * sky + blockLightCol + vec3(0.02)) * aoFactor;+ // Night Vision (_pad2): lift dark areas to a visible floor.+ if (_pad2 > 0.5) { lit = max(lit, albedo * 0.62 * aoFactor); } float fog = 1.0 - exp(-fragDist * fogDensity); fog = clamp(fog, 0.0, 0.85);
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 77956643a8..54f3b79ee9 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 42fd6c3ee2..a660f8df7d 100644--- a/games/voxels/src/main/rust/shaders/block.vert+++ b/games/voxels/src/main/rust/shaders/block.vert@@ -5,6 +5,7 @@ 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(location=6) in float inLight; layout(binding=0) uniform Ubo { mat4 viewProj;@@ -30,6 +31,7 @@ layout(location=4) out vec3 fragWorldPos; layout(location=5) out vec3 fragNormal; layout(location=6) out float fragTile; layout(location=7) out vec4 fragLightPos;+layout(location=8) out float fragLight; void main() { gl_Position = viewProj * vec4(inPos, 1.0);@@ -41,4 +43,5 @@ void main() { fragTile = inTileIdx; fragDist = length(inPos - playerPos.xyz); fragLightPos = lightViewProj * vec4(inPos, 1.0);+ fragLight = inLight; }
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 1c0ceab18e..352135b471 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/entity_atlas.bin
diff --git a/games/voxels/src/main/rust/shaders/entity_atlas.bin b/games/voxels/src/main/rust/shaders/entity_atlas.binindex fd746157a7..2bd323f93d 100644Binary files a/games/voxels/src/main/rust/shaders/entity_atlas.bin and b/games/voxels/src/main/rust/shaders/entity_atlas.bin 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 643a5f66b1..7c6140c01c 100644--- a/games/voxels/src/main/rust/src/engine.rs+++ b/games/voxels/src/main/rust/src/engine.rs@@ -1,7 +1,7 @@ use crate::world::{ChunkMap, block::Block}; use crate::player::Player; use crate::inventory::Inventory;-use crate::entity::{Mob, MobKind, build_entity_mesh};+use crate::entity::{Mob, MobKind, Particle, build_entity_mesh, tick_particles, append_particles}; use crate::world::mesher; use crate::vulkan::context::{VulkanContext, ANativeWindow}; use crate::vulkan::renderer::VulkanRenderer;@@ -25,6 +25,9 @@ pub struct EngineState { pub mobs: Vec<Mob>, pub spawn_timer: f32, pub spawn_rng: u32,+ pub respawn: Option<Vec3>,+ pub checkpoint_cd: f32,+ pub particles: Vec<Particle>, } unsafe impl Send for EngineState {}@@ -91,6 +94,9 @@ pub fn init_engine(files_dir: String, seed: u32) -> bool { mobs: Vec::new(), spawn_timer: 2.0, spawn_rng: seed ^ 0x9E3779B9,+ respawn: None,+ checkpoint_cd: 0.0,+ particles: Vec::new(), }); INIT_DONE.store(true, Ordering::SeqCst); true@@ -238,6 +244,30 @@ pub fn tick_and_render() { if move_len > 0.9 { input_mut.sprint = true; } state.player.tick(dt, &input_mut, &state.chunks);+ state.player.tick_status(dt);++ // Warding stone checkpoint: standing near one sets respawn + slowly refills Estus (bonfire).+ state.checkpoint_cd = (state.checkpoint_cd - dt).max(0.0);+ {+ let p = state.player.pos;+ let (bx, by, bz) = (p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32);+ let mut near = None;+ 'scan: for dy in -2..=2 { for dx in -4..=4 { for dz in -4..=4 {+ if state.chunks.get_block_world(bx + dx, by + dy, bz + dz) == 81 {+ near = Some(vec3((bx + dx) as f32 + 0.5, (by + dy) as f32 + 1.0, (bz + dz) as f32 + 0.5));+ break 'scan;+ }+ }}}+ if let Some(cp) = near {+ state.respawn = Some(cp);+ if state.checkpoint_cd <= 0.0 {+ state.checkpoint_cd = 2.0;+ let have: i32 = state.inventory.slots.iter().filter(|s| s.id == 128).map(|s| s.count).sum();+ if have < 4 { state.inventory.add_block(128); }+ state.player.add_effect(crate::item::Effect::Regeneration, 2.5, 0);+ }+ }+ } let px = state.player.pos.x as i32; let pz = state.player.pos.z as i32;@@ -256,6 +286,25 @@ pub fn tick_and_render() { let solid = |x: i32, y: i32, z: i32| { let id = chunks.get_block_world(x, y, z); id != 0 && Block::from_id(id).is_solid() }; for m in state.mobs.iter_mut() { m.tick(dt, player_pos, &solid); } }+ // Mob melee contact damage + creeper fuse.+ let mut incoming = 0.0f32;+ let mut explosions: Vec<Vec3> = Vec::new();+ for m in state.mobs.iter_mut() {+ m.attack_cd = (m.attack_cd - dt).max(0.0);+ let d = (m.pos - player_pos).length();+ if m.kind == MobKind::Creeper {+ if d < 3.2 { m.fuse += dt; if m.fuse >= 1.4 { explosions.push(m.pos); m.health = 0.0; } }+ else { m.fuse = (m.fuse - dt * 0.6).max(0.0); }+ } else if m.kind.hostile() && d < 1.7 && m.attack_cd <= 0.0 {+ m.attack_cd = 0.8; incoming += m.kind.contact_damage();+ }+ }+ if incoming > 0.0 { hurt_player(state, incoming); }+ for c in explosions { explode(state, c, 3.0); }+ // Remove dead mobs and auto-collect their drops.+ let mut loot: Vec<u8> = Vec::new();+ state.mobs.retain(|m| if m.health <= 0.0 { loot.extend_from_slice(m.kind.loot()); false } else { true });+ for id in loot { state.inventory.add_block(id); } state.mobs.retain(|m| (m.pos - player_pos).length() < 96.0 && m.pos.y > -8.0); state.spawn_timer -= dt; if state.spawn_timer <= 0.0 {@@ -281,6 +330,8 @@ pub fn tick_and_render() { let night = day_t < 0.25 || day_t > 0.75; let kind = if night { if rand(&mut rng) < 0.5 { MobKind::Zombie } else { MobKind::Creeper }+ } else if rand(&mut rng) < 0.18 {+ MobKind::Villager } else { match (rand(&mut rng) * 4.0) as u32 { 0 => MobKind::Pig, 1 => MobKind::Cow, 2 => MobKind::Sheep, _ => MobKind::Chicken } };@@ -291,7 +342,35 @@ pub fn tick_and_render() { state.spawn_rng = rng; } }- let (entity_verts, entity_indices) = build_entity_mesh(&state.mobs);+ // Death: burn one heart of max HP (floored) and respawn at world spawn — the "lives" system.+ if state.player.dead {+ use crate::world::chunk::CHUNK_HEIGHT;+ state.player.max_health = (state.player.max_health - 2.0).max(crate::player::MIN_MAX_HEALTH);+ state.player.pos = if let Some(rp) = state.respawn {+ rp+ } else {+ state.chunks.ensure_radius(0, 0);+ let mut ty = 80;+ for y in (1..CHUNK_HEIGHT as i32).rev() {+ let id = state.chunks.get_block_world(0, y, 0);+ if id != 0 && Block::from_id(id).is_solid() { ty = y; break; }+ }+ vec3(0.5, ty as f32 + 1.1, 0.5)+ };+ state.player.vel = Vec3::ZERO;+ state.player.health = state.player.max_health;+ state.player.absorption = 0.0;+ state.player.effects.clear();+ state.player.dead = false;+ state.player.air_max_y = state.player.pos.y;+ state.mobs.clear();+ }+ tick_particles(&mut state.particles, dt);+ let (mut entity_verts, mut entity_indices) = build_entity_mesh(&state.mobs);+ {+ let right = state.player.right();+ append_particles(&mut entity_verts, &mut entity_indices, &state.particles, right, Vec3::Y);+ } if let Some(renderer) = state.renderer.as_mut() { if state.needs_resize {@@ -316,8 +395,9 @@ pub fn tick_and_render() { let time = 60.0 + (Instant::now() - state.start_time).as_secs_f32(); let eb = (eye.x.floor() as i32, eye.y.floor() as i32, eye.z.floor() as i32); let underwater = if state.chunks.get_block_world(eb.0, eb.1, eb.2) == 12 { 1.0 } else { 0.0 };+ let nv = if state.player.night_vision() { 1.0 } else { 0.0 }; unsafe {- renderer.update_ubo(view_proj, state.player.pos, time, underwater);+ renderer.update_ubo(view_proj, state.player.pos, time, underwater, nv); renderer.upload_entity_mesh(&entity_verts, &entity_indices); let _ = renderer.draw_frame(); }@@ -332,6 +412,7 @@ pub fn tick_and_render() { static DEBUG_CACHE: OnceLock<Mutex<String>> = OnceLock::new(); static INV_CACHE: OnceLock<Mutex<String>> = OnceLock::new(); static STATS_CACHE: OnceLock<Mutex<String>> = OnceLock::new();+static HEALTH_CACHE: OnceLock<Mutex<String>> = OnceLock::new(); 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.@@ -360,21 +441,36 @@ fn publish_ui(state: &EngineState) { 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();+ let effects: Vec<_> = state.player.effects.iter().map(|e| serde_json::json!({"k": e.kind.key(), "amp": e.amp, "t": e.secs.ceil() as i32})).collect();+ let estus: i32 = state.inventory.slots.iter().filter(|s| s.id == 128).map(|s| s.count).sum();+ let health = serde_json::json!({+ "hp": state.player.health, "max": state.player.max_health, "absorb": state.player.absorption,+ "dead": state.player.dead, "estus": estus, "effects": effects,+ }).to_string(); 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; }+ if let Ok(mut c) = cref(&HEALTH_CACHE, "{}").lock() { *c = health; } } 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 get_health_json() -> String { cref(&HEALTH_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 do_trade(idx: usize) -> bool { with_engine(|s| s.inventory.trade(idx)).unwrap_or(false) }+pub fn get_trades_json() -> String {+ let items: Vec<_> = crate::inventory::TRADES.iter()+ .map(|(c, cn, g, gn)| serde_json::json!({"cost": c, "costN": cn, "give": g, "giveN": gn}))+ .collect();+ serde_json::json!(items).to_string()+} 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}))+ .map(|(i1, c1, i2, c2, oid, oc)| serde_json::json!({"in": i1, "inN": c1, "in2": i2, "in2N": c2, "out": oid, "outN": oc})) .collect(); serde_json::json!(items).to_string() }@@ -398,6 +494,26 @@ fn screen_ray(state: &EngineState, px: f32, py: f32) -> (Vec3, Vec3) { (eye, dir) } +// Apply damage to the player through equipped armor (each defense point cuts ~4%, capped), wearing+// the armor down when a hit actually lands.+fn hurt_player(state: &mut EngineState, amt: f32) {+ let def = state.inventory.armor_defense();+ let reduced = amt * (1.0 - (def * 0.04)).max(0.2);+ let before = state.player.health;+ state.player.damage(reduced);+ if state.player.health < before { state.inventory.damage_armor(); }+}++// Spawn a small burst of particles (capped so the buffer never overflows).+fn spawn_particles(rng: &mut u32, out: &mut Vec<Particle>, center: Vec3, n: usize, color: [f32; 3], speed: f32, life: f32, size: f32) {+ let mut r = |s: &mut u32| { let mut x = *s; x ^= x << 13; x ^= x >> 17; x ^= x << 5; *s = x; (x >> 8) as f32 / 16_777_216.0 * 2.0 - 1.0 };+ for _ in 0..n {+ if out.len() > 500 { break; }+ let v = vec3(r(rng) * speed, r(rng).abs() * speed + 1.0, r(rng) * speed);+ out.push(Particle { pos: center, vel: v, life, max_life: life, size, color });+ }+}+ fn mark_neighbors_dirty(state: &mut EngineState, x: i32, z: i32) { use crate::world::chunk::ChunkPos; let cp = ChunkPos::from_world(x, z);@@ -409,22 +525,132 @@ fn mark_neighbors_dirty(state: &mut EngineState, x: i32, z: i32) { if lz==15 { if let Some(ch) = state.chunks.get_mut(ChunkPos(cp.0, cp.1+1)) { ch.mesh_dirty=true; } } } +// Ray vs mob AABBs: index of the nearest mob hit within `reach` and nearer than `limit`.+fn nearest_mob_hit(state: &EngineState, origin: Vec3, dir: Vec3, reach: f32, limit: f32) -> Option<usize> {+ let mut best: Option<(usize, f32)> = None;+ for (i, m) in state.mobs.iter().enumerate() {+ let h = m.kind.height();+ let min = vec3(m.pos.x - 0.45, m.pos.y, m.pos.z - 0.45);+ let max = vec3(m.pos.x + 0.45, m.pos.y + h, m.pos.z + 0.45);+ let mut tmin = 0.0f32; let mut tmax = reach.min(limit);+ let mut hit = true;+ for a in 0..3 {+ let (o, d, lo, hi) = (origin[a], dir[a], min[a], max[a]);+ if d.abs() < 1e-6 { if o < lo || o > hi { hit = false; break; } }+ else {+ let (mut t1, mut t2) = ((lo - o) / d, (hi - o) / d);+ if t1 > t2 { std::mem::swap(&mut t1, &mut t2); }+ tmin = tmin.max(t1); tmax = tmax.min(t2);+ if tmin > tmax { hit = false; break; }+ }+ }+ if hit && tmin >= 0.0 && best.map(|(_, t)| tmin < t).unwrap_or(true) { best = Some((i, tmin)); }+ }+ best.map(|(i, _)| i)+}+ fn do_break(state: &mut EngineState, origin: Vec3, dir: Vec3) -> bool {- if let Some(hit) = crate::raycast::raycast(&state.chunks, origin, dir, 6.0) {- let (x,y,z) = hit.pos;- let id = state.chunks.get_block_world(x,y,z);+ use crate::item::{self, Effect};+ let sel = state.inventory.selected_block();+ // Equip armor (hold): swap it into its slot, returning any displaced piece to the inventory.+ if item::is_armor(sel) && state.player.eat_cd <= 0.0 {+ if let Some((id, dur)) = state.inventory.take_selected() {+ if let Some(old) = state.inventory.equip_armor(id, dur) { state.inventory.add_item_with_count(old.id, old.count); }+ state.player.eat_cd = 0.4;+ return true;+ }+ }+ // Consumables (hold to use): eat food any time, drink estus / use heart container when applicable.+ if state.player.eat_cd <= 0.0 {+ // Food can be eaten any time (even at full health) to gain its effects.+ if item::is_food(sel) {+ if let Some(id) = state.inventory.consume_selected() {+ if let Some(effs) = item::food_effects(id) { for &(k, s, a) in effs { state.player.add_effect(k, s, a); } }+ state.player.eat_cd = 1.2;+ return true;+ }+ } else if item::is_estus(sel) && state.player.health < state.player.max_health {+ if state.inventory.consume_selected().is_some() {+ state.player.heal(8.0);+ state.player.add_effect(Effect::Regeneration, 3.0, 1);+ state.player.add_effect(Effect::Resistance, 3.0, 0);+ state.player.eat_cd = 0.8;+ return true;+ }+ } else if item::is_heart_container(sel) && state.player.max_health < crate::player::CAP_MAX_HEALTH {+ if state.inventory.consume_selected().is_some() {+ state.player.max_health = (state.player.max_health + 2.0).min(crate::player::CAP_MAX_HEALTH);+ state.player.heal(2.0);+ state.player.eat_cd = 0.8;+ return true;+ }+ }+ }+ // Attack a mob if one is under the cursor within reach and nearer than any block.+ let block_hit = crate::raycast::raycast(&state.chunks, origin, dir, 6.0);+ let block_dist = block_hit.as_ref().map(|h| (vec3(h.pos.0 as f32 + 0.5, h.pos.1 as f32 + 0.5, h.pos.2 as f32 + 0.5) - origin).length()).unwrap_or(f32::INFINITY);+ if state.player.attack_cd <= 0.0 {+ if let Some(idx) = nearest_mob_hit(state, origin, dir, 4.5, block_dist) {+ state.player.attack_cd = 0.45;+ let dmg = 4.0 + item::sword_damage(sel) + item::pick_damage(sel) + state.player.strength_bonus();+ state.inventory.damage_selected();+ let ppos = state.player.pos;+ let mpos;+ {+ let m = &mut state.mobs[idx];+ m.health -= dmg;+ let kb = { let k = m.pos - ppos; vec3(k.x, 0.0, k.z).normalize_or_zero() };+ m.pos += kb * 0.45; m.vel.y = 6.0;+ mpos = m.pos + vec3(0.0, 0.5, 0.0);+ }+ spawn_particles(&mut state.spawn_rng, &mut state.particles, mpos, 6, [0.85, 0.12, 0.12], 3.0, 0.4, 0.09);+ return true;+ }+ }+ // Break a block.+ if let Some(hit) = block_hit {+ let (x, y, z) = hit.pos;+ let id = state.chunks.get_block_world(x, y, z); if id != 0 {- state.chunks.set_block_world(x,y,z, 0);- state.inventory.add_block(id);- state.inventory.broken += 1;+ // Stone/ore only drops when mined with a pickaxe; soft blocks always drop.+ let drops = !Block::from_id(id).needs_pickaxe() || item::is_pickaxe(sel);+ state.chunks.set_block_world(x, y, z, 0);+ if drops { state.inventory.add_block(id); state.inventory.broken += 1; }+ state.inventory.damage_selected(); mark_neighbors_dirty(state, x, z);+ let c = vec3(x as f32 + 0.5, y as f32 + 0.5, z as f32 + 0.5);+ spawn_particles(&mut state.spawn_rng, &mut state.particles, c, 7, [0.55, 0.45, 0.35], 2.6, 0.5, 0.11); return true; } } false } +// Destroy blocks in a sphere and hurt the player — creeper explosions.+fn explode(state: &mut EngineState, center: Vec3, radius: f32) {+ let r = radius.ceil() as i32;+ let (cx, cy, cz) = (center.x.floor() as i32, center.y.floor() as i32, center.z.floor() as i32);+ let mut cols: Vec<(i32, i32)> = Vec::new();+ for dx in -r..=r { for dy in -r..=r { for dz in -r..=r {+ if ((dx*dx + dy*dy + dz*dz) as f32).sqrt() > radius { continue; }+ let (x, y, z) = (cx + dx, cy + dy, cz + dz);+ let id = state.chunks.get_block_world(x, y, z);+ if id != 0 && id != 13 && Block::from_id(id).is_solid() {+ state.chunks.set_block_world(x, y, z, 0);+ cols.push((x, z));+ }+ }}}+ for (x, z) in cols { mark_neighbors_dirty(state, x, z); }+ let pd = (state.player.pos - center).length();+ if pd < radius * 2.0 { hurt_player(state, (1.0 - pd / (radius * 2.0)).max(0.0) * 22.0); }+ spawn_particles(&mut state.spawn_rng, &mut state.particles, center, 30, [0.28, 0.25, 0.22], 6.0, 0.9, 0.3);+ spawn_particles(&mut state.spawn_rng, &mut state.particles, center, 12, [1.0, 0.55, 0.15], 5.0, 0.5, 0.22);+}+ fn do_place(state: &mut EngineState, origin: Vec3, dir: Vec3) -> bool {+ // Items (food, estus, materials) are never placeable as blocks.+ let sel = state.inventory.selected_block();+ if sel == 0 || crate::item::is_item(sel) { return false; } if let Some(hit) = crate::raycast::raycast(&state.chunks, origin, dir, 6.0) { let (px,py,pz) = hit.prev; if state.chunks.get_block_world(px,py,pz) != 0 { return false; }@@ -454,9 +680,15 @@ pub fn break_block_at(px: f32, py: f32) -> bool { pub fn place_block_at(px: f32, py: f32) -> i32 { with_engine(|state| { let (o, d) = screen_ray(state, px, py);- // Tapping an interactive block opens its menu — unless sneaking, which places instead.+ // Tapping a villager opens trade; 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 block_hit = crate::raycast::raycast(&state.chunks, o, d, 6.0);+ let bdist = block_hit.as_ref().map(|h| (vec3(h.pos.0 as f32 + 0.5, h.pos.1 as f32 + 0.5, h.pos.2 as f32 + 0.5) - o).length()).unwrap_or(f32::INFINITY);+ if let Some(idx) = nearest_mob_hit(state, o, d, 4.5, bdist) {+ if state.mobs[idx].kind == MobKind::Villager { return 20; }+ }+ if let Some(hit) = block_hit { 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; }
games/voxels/src/main/rust/src/entity.rs
diff --git a/games/voxels/src/main/rust/src/entity.rs b/games/voxels/src/main/rust/src/entity.rsindex 18e8017357..8ad7a7a0e3 100644--- a/games/voxels/src/main/rust/src/entity.rs+++ b/games/voxels/src/main/rust/src/entity.rs@@ -9,7 +9,7 @@ const CELL: f32 = ENTITY_CELL as f32; const PX: f32 = 1.0 / 16.0; // one skin pixel in blocks #[derive(Clone, Copy, PartialEq, Eq)]-pub enum MobKind { Pig, Cow, Sheep, Chicken, Creeper, Zombie }+pub enum MobKind { Pig, Cow, Sheep, Chicken, Creeper, Zombie, Villager } // A model part: an axis-aligned box textured from the skin. struct Part {@@ -59,13 +59,23 @@ static CHICKEN: &[Part] = &[ ]; impl MobKind {- fn cell(self) -> u32 { match self { MobKind::Pig=>0, MobKind::Cow=>1, MobKind::Sheep=>2, MobKind::Chicken=>3, MobKind::Creeper=>4, MobKind::Zombie=>5 } }+ fn cell(self) -> u32 { match self { MobKind::Pig=>0, MobKind::Cow=>1, MobKind::Sheep=>2, MobKind::Chicken=>3, MobKind::Creeper=>4, MobKind::Zombie=>5, MobKind::Villager=>6 } } pub fn hostile(self) -> bool { matches!(self, MobKind::Creeper | MobKind::Zombie) }- fn speed(self) -> f32 { match self { MobKind::Chicken=>1.6, MobKind::Creeper=>1.5, MobKind::Zombie=>1.7, _=>1.15 } }+ pub fn max_health(self) -> f32 { match self { MobKind::Zombie | MobKind::Creeper => 20.0, MobKind::Villager => 20.0, _ => 10.0 } }+ pub fn height(self) -> f32 { match self { MobKind::Zombie | MobKind::Villager => 1.9, MobKind::Creeper => 1.6, MobKind::Chicken => 0.7, _ => 0.9 } }+ pub fn contact_damage(self) -> f32 { match self { MobKind::Zombie => 4.0, _ => 0.0 } }+ // Item ids dropped on death (auto-collected into the inventory).+ pub fn loot(self) -> &'static [u8] {+ match self {+ MobKind::Pig => &[132], MobKind::Cow => &[137, 132], MobKind::Sheep => &[130], MobKind::Chicken => &[135],+ MobKind::Creeper => &[138], MobKind::Zombie => &[131], MobKind::Villager => &[],+ }+ }+ fn speed(self) -> f32 { match self { MobKind::Chicken=>1.6, MobKind::Creeper=>1.5, MobKind::Zombie=>1.7, MobKind::Villager=>0.9, _=>1.15 } } fn parts(self) -> &'static [Part] { match self { MobKind::Pig | MobKind::Cow | MobKind::Sheep => QUAD,- MobKind::Zombie => BIPED,+ MobKind::Zombie | MobKind::Villager => BIPED, MobKind::Creeper => CREEPER, MobKind::Chicken => CHICKEN, }@@ -77,6 +87,9 @@ pub struct Mob { pub pos: Vec3, pub vel: Vec3, pub yaw: f32,+ pub health: f32,+ pub attack_cd: f32,+ pub fuse: f32, // creeper explosion timer target_yaw: f32, wander: f32, anim: f32,@@ -91,7 +104,8 @@ fn xorshift(s: &mut u32) -> f32 { impl Mob { pub fn new(kind: MobKind, pos: Vec3, seed: u32) -> Self {- Mob { kind, pos, vel: Vec3::ZERO, yaw: 0.0, target_yaw: 0.0, wander: 0.0, anim: 0.0, on_ground: false, rng: seed | 1 }+ Mob { kind, pos, vel: Vec3::ZERO, yaw: 0.0, health: kind.max_health(), attack_cd: 0.0, fuse: 0.0,+ target_yaw: 0.0, wander: 0.0, anim: 0.0, on_ground: false, rng: seed | 1 } } pub fn tick(&mut self, dt: f32, player: Vec3, solid: &dyn Fn(i32, i32, i32) -> bool) {@@ -212,7 +226,7 @@ impl Mob { let (rx, rz) = (wp.x*yc - wp.z*ys, wp.x*ys + wp.z*yc); wp = Vec3::new(rx, wp.y, rz) + self.pos; let uv = [(col + uvc[c][0]) / ATLAS, (row + uvc[c][1]) / ATLAS];- verts.push(Vertex { pos: [wp.x, wp.y, wp.z], uv, color: [1.0,1.0,1.0], ao: 1.0, tile_idx: 0.0, normal: nrm });+ verts.push(Vertex { pos: [wp.x, wp.y, wp.z], uv, color: [1.0,1.0,1.0], ao: 1.0, tile_idx: 0.0, normal: nrm, light: 0.0 }); } indices.extend_from_slice(&[base, base+1, base+2, base, base+2, base+3]); }@@ -227,3 +241,32 @@ pub fn build_entity_mesh(mobs: &[Mob]) -> (Vec<Vertex>, Vec<u32>) { for m in mobs { m.append_mesh(&mut verts, &mut indices); } (verts, indices) }++// ---- Particles: short-lived billboarded quads (block break, hits, explosions). ----+pub struct Particle { pub pos: Vec3, pub vel: Vec3, pub life: f32, pub max_life: f32, pub size: f32, pub color: [f32; 3] }++pub fn tick_particles(ps: &mut Vec<Particle>, dt: f32) {+ for p in ps.iter_mut() {+ p.vel.y -= 14.0 * dt;+ p.pos += p.vel * dt;+ p.life -= dt;+ }+ ps.retain(|p| p.life > 0.0);+}++// UV of the white swatch baked into the entity atlas (cell 15); particles tint it via vertex color.+const PARTICLE_UV: f32 = 0.766;+pub fn append_particles(verts: &mut Vec<Vertex>, indices: &mut Vec<u32>, ps: &[Particle], right: Vec3, up: Vec3) {+ for p in ps {+ let f = (p.life / p.max_life).clamp(0.0, 1.0);+ let s = p.size * (0.35 + 0.65 * f);+ let c = [p.color[0] * (0.4 + 0.6 * f), p.color[1] * (0.4 + 0.6 * f), p.color[2] * (0.4 + 0.6 * f)];+ let (r, u) = (right * s, up * s);+ let corners = [p.pos - r - u, p.pos + r - u, p.pos + r + u, p.pos - r + u];+ let base = verts.len() as u32;+ for cc in corners {+ verts.push(Vertex { pos: [cc.x, cc.y, cc.z], uv: [PARTICLE_UV, PARTICLE_UV], color: c, ao: 1.0, tile_idx: 0.0, normal: [0.0, 1.0, 0.0], light: 0.0 });+ }+ indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);+ }+}
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 0e0860da7c..754ede5b2f 100644--- a/games/voxels/src/main/rust/src/inventory.rs+++ b/games/voxels/src/main/rust/src/inventory.rs@@ -16,20 +16,58 @@ pub struct Inventory { pub slots: [InvSlot; SLOTS], pub placed: i32, pub broken: i32,+ // Equipped armor: 0 helmet, 1 chestplate, 2 leggings, 3 boots. count = remaining durability.+ #[serde(default)]+ pub armor: [InvSlot; 4], } -// (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),+// (in1_id, in1_count, in2_id, in2_count, out_id, out_count). in2_id == 0 means a single ingredient.+// Item ids 154+ are materials/tools (see item.rs). Crafting and smelting both flow through this table+// (the Furnace menu opens the same crafting UI).+pub const RECIPES: [(u8, i32, u8, i32, u8, i32); 34] = [+ (Block::Wood as u8, 1, 0, 0, Block::Planks as u8, 4),+ (Block::BirchLog as u8, 1, 0, 0, Block::BirchPlanks as u8, 4),+ (Block::SpruceLog as u8, 1, 0, 0, Block::SprucePlanks as u8,4),+ (Block::Planks as u8, 4, 0, 0, Block::CraftingTable as u8, 1),+ (Block::Cobble as u8, 8, 0, 0, Block::Furnace as u8, 1),+ (Block::Sand as u8, 2, 0, 0, Block::Glass as u8, 1),+ (Block::Cobble as u8, 4, 0, 0, Block::Stone as u8, 1),+ (Block::Diorite as u8, 4, 0, 0, Block::PolishedDiorite as u8, 4),+ (Block::Planks as u8, 2, 0, 0, 159 /*Stick*/, 4),+ (Block::Clay as u8, 4, 0, 0, Block::Brick as u8, 1),+ // Smelting: ore -> material.+ (Block::CoalOre as u8, 1, 0, 0, 157 /*Coal*/, 1),+ (Block::IronOre as u8, 1, 0, 0, 154 /*Iron Ingot*/, 1),+ (Block::DiamondOre as u8,1, 0, 0, 155 /*Diamond*/, 1),+ (Block::EmeraldOre as u8,1, 0, 0, 156 /*Emerald*/, 1),+ (Block::RedstoneOre as u8,1,0, 0, 158 /*Redstone*/, 1),+ // Material -> block.+ (154, 9, 0, 0, Block::IronBlock as u8, 1),+ (155, 9, 0, 0, Block::DiamondBlock as u8, 1),+ (156, 9, 0, 0, Block::EmeraldBlock as u8, 1),+ // Tools: material + stick(159).+ (Block::Planks as u8, 3, 159, 2, 163, 1), // wood pickaxe+ (Block::Planks as u8, 2, 159, 1, 164, 1), // wood sword+ (Block::Cobble as u8, 3, 159, 2, 165, 1), // stone pickaxe+ (Block::Cobble as u8, 2, 159, 1, 166, 1), // stone sword+ (154, 3, 159, 2, 167, 1), // iron pickaxe+ (154, 2, 159, 1, 168, 1), // iron sword+ (155, 3, 159, 2, 169, 1), // diamond pickaxe+ (155, 2, 159, 1, 170, 1), // diamond sword+ // Armor: material only.+ (154, 5, 0, 0, 171, 1), (154, 8, 0, 0, 172, 1), (154, 7, 0, 0, 173, 1), (154, 4, 0, 0, 174, 1), // iron+ (155, 5, 0, 0, 175, 1), (155, 8, 0, 0, 176, 1), (155, 7, 0, 0, 177, 1), (155, 4, 0, 0, 178, 1), // diamond+];++// Villager trades: (cost_id, cost_count, give_id, give_count). Emerald = item 156.+pub const TRADES: [(u8, i32, u8, i32); 7] = [+ (156, 3, 168, 1), // 3 Emerald -> Iron Sword+ (156, 6, 172, 1), // 6 Emerald -> Iron Chestplate+ (156, 2, 133, 1), // 2 Emerald -> Golden Apple+ (156, 1, 131, 6), // 1 Emerald -> 6 Bread+ (156, 4, 128, 1), // 4 Emerald -> Estus Flask+ (157, 12, 156, 1), // 12 Coal -> 1 Emerald+ (137, 6, 156, 2), // 6 Leather -> 2 Emerald ]; impl Default for Inventory {@@ -40,7 +78,7 @@ impl Default for Inventory { (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 }+ Self { selected: 0, slots, placed: 0, broken: 0, armor: [InvSlot::default(); 4] } } } @@ -102,12 +140,55 @@ impl Inventory { } } 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); }+ let Some(&(i1, c1, i2, c2, oid, oc)) = RECIPES.get(recipe) else { return false; };+ if self.count_of(i1) < c1 { return false; }+ if i2 != 0 && self.count_of(i2) < c2 { return false; }+ self.remove_count(i1, c1);+ if i2 != 0 { self.remove_count(i2, c2); }+ if crate::item::has_durability(oid) { self.add_item_with_count(oid, crate::item::max_durability(oid)); }+ else { for _ in 0..oc { self.add_block(oid); } }+ true+ }+ // Place a non-stacking item (tool/armor) into the first empty slot with a given count (durability).+ pub fn add_item_with_count(&mut self, id: u8, count: i32) {+ for slot in self.slots.iter_mut() { if slot.id == 0 { slot.id = id; slot.count = count; return; } }+ }+ pub fn selected_count(&self) -> i32 { if self.selected < HOTBAR { self.slots[self.selected].count } else { 0 } }+ // Remove the whole selected stack, returning (id, count). Used to equip armor without losing durability.+ pub fn take_selected(&mut self) -> Option<(u8, i32)> {+ if self.selected >= HOTBAR { return None; }+ let s = self.slots[self.selected];+ if s.id == 0 { return None; }+ self.slots[self.selected] = InvSlot::default();+ Some((s.id, s.count))+ }+ // Decrement the selected tool's durability (called on block break / attack); clear it at 0.+ pub fn damage_selected(&mut self) {+ if self.selected >= HOTBAR { return; }+ let s = &mut self.slots[self.selected];+ if s.id != 0 && crate::item::has_durability(s.id) { s.count -= 1; if s.count <= 0 { *s = InvSlot::default(); } }+ }+ // Equip an armor item (with its durability) into its slot; returns any displaced piece.+ pub fn equip_armor(&mut self, id: u8, dur: i32) -> Option<InvSlot> {+ let slot = crate::item::armor_slot(id);+ let old = self.armor[slot];+ self.armor[slot] = InvSlot { id, count: dur };+ if old.id != 0 { Some(old) } else { None }+ }+ // Execute a villager trade if the player can afford it.+ pub fn trade(&mut self, idx: usize) -> bool {+ let Some(&(c, cn, g, gn)) = TRADES.get(idx) else { return false; };+ if self.count_of(c) < cn { return false; }+ self.remove_count(c, cn);+ if crate::item::has_durability(g) { self.add_item_with_count(g, crate::item::max_durability(g)); }+ else { for _ in 0..gn { self.add_block(g); } } true }+ pub fn armor_defense(&self) -> f32 { self.armor.iter().map(|s| if s.id != 0 { crate::item::armor_defense(s.id) } else { 0.0 }).sum() }+ // Wear down each equipped piece by 1 when the player is hurt.+ pub fn damage_armor(&mut self) {+ for s in self.armor.iter_mut() { if s.id != 0 { s.count -= 1; if s.count <= 0 { *s = InvSlot::default(); } } }+ } pub fn to_json(&self) -> String { serde_json::to_string(self).unwrap_or_else(|_| r#"{"selected":0,"slots":[]}"#.to_string()) } }
games/voxels/src/main/rust/src/item.rs
diff --git a/games/voxels/src/main/rust/src/item.rs b/games/voxels/src/main/rust/src/item.rsnew file mode 100644index 0000000000..d7c1244a1c--- /dev/null+++ b/games/voxels/src/main/rust/src/item.rs@@ -0,0 +1,89 @@+// Non-block inventory items (food, consumables, materials) and the status-effect model.+// Inventory ids < ITEM_BASE are blocks; ids >= ITEM_BASE are items and are never placeable.+// Design follows the Matcha/Raspberry survival overhaul: no hunger — food applies Regeneration+// (the heal) plus a themed buff; Estus is a fast multi-charge heal; Heart Containers raise max HP.++#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub enum Effect { Regeneration, Poison, Resistance, Strength, Speed, Haste, Absorption, FireResistance, NightVision, JumpBoost, Slowness }++impl Effect {+ pub fn key(self) -> &'static str {+ match self {+ Effect::Regeneration => "regen",+ Effect::Poison => "poison",+ Effect::Resistance => "resist",+ Effect::Strength => "strength",+ Effect::Speed => "speed",+ Effect::Haste => "haste",+ Effect::Absorption => "absorb",+ Effect::FireResistance => "fireres",+ Effect::NightVision => "night",+ Effect::JumpBoost => "jump",+ Effect::Slowness => "slow",+ }+ }+}++#[derive(Clone, Copy)]+pub struct ActiveEffect { pub kind: Effect, pub secs: f32, pub amp: u8 }++pub const ITEM_BASE: u8 = 128;+pub fn is_item(id: u8) -> bool { id >= ITEM_BASE }+pub fn is_estus(id: u8) -> bool { id == 128 }+pub fn is_heart_container(id: u8) -> bool { id == 129 }+pub fn is_food(id: u8) -> bool { food_effects(id).is_some() }++// ---- Tools & armor (ids 163..178) ----+// Tools 163..170: {wood,stone,iron,diamond} x {pickaxe,sword}. Armor 171..178: {iron,diamond} x+// {helmet,chestplate,leggings,boots}. Durability is stored in the inventory slot's `count`.+pub fn is_tool(id: u8) -> bool { (163..=170).contains(&id) }+pub fn is_pickaxe(id: u8) -> bool { matches!(id, 163 | 165 | 167 | 169) }+pub fn is_sword(id: u8) -> bool { matches!(id, 164 | 166 | 168 | 170) }+pub fn is_armor(id: u8) -> bool { (171..=178).contains(&id) }+pub fn armor_slot(id: u8) -> usize { ((id - 171) % 4) as usize } // 0 helm, 1 chest, 2 legs, 3 boots+pub fn has_durability(id: u8) -> bool { is_tool(id) || is_armor(id) }++pub fn sword_damage(id: u8) -> f32 { match id { 164 => 5.0, 166 => 6.0, 168 => 7.0, 170 => 9.0, _ => 0.0 } }+pub fn pick_damage(id: u8) -> f32 { match id { 163 => 2.0, 165 => 3.0, 167 => 4.0, 169 => 5.0, _ => 0.0 } }+pub fn armor_defense(id: u8) -> f32 {+ match id {+ 171 => 2.0, 172 => 6.0, 173 => 5.0, 174 => 2.0, // iron helm/chest/legs/boots+ 175 => 3.0, 176 => 8.0, 177 => 6.0, 178 => 3.0, // diamond+ _ => 0.0,+ }+}+pub fn max_durability(id: u8) -> i32 {+ match id {+ 163 | 164 => 60, 165 | 166 => 132, 167 | 168 => 250, 169 | 170 => 1562, // wood/stone/iron/diamond tools+ 171..=174 => 240, 175..=178 => 528, // iron/diamond armor+ _ => 0,+ }+}++// Effects applied when a food item is eaten. First entry is the healing Regeneration.+pub fn food_effects(id: u8) -> Option<&'static [(Effect, f32, u8)]> {+ use Effect::*;+ Some(match id {+ 130 => &[(Regeneration, 4.0, 0)], // apple+ 131 => &[(Regeneration, 6.0, 0)], // bread+ 132 => &[(Regeneration, 5.0, 1)], // cooked fish+ 133 => &[(Regeneration, 5.0, 1), (Absorption, 120.0, 0), (Resistance, 30.0, 0), (Strength, 60.0, 0)], // golden apple+ 134 => &[(Regeneration, 3.6, 2), (Haste, 150.0, 1)], // brownie+ 135 => &[(Regeneration, 4.0, 0), (NightVision, 30.0, 0)], // carrot (good for your eyes)+ 136 => &[(Regeneration, 4.0, 1), (Speed, 30.0, 0)], // glistering melon slice+ 146 => &[(Regeneration, 5.0, 0), (FireResistance, 30.0, 0)], // baked potato (hot!)+ 147 => &[(Regeneration, 2.0, 0)], // cookie+ 148 => &[(Regeneration, 5.0, 1)], // cooked salmon+ 149 => &[(Regeneration, 4.0, 0)], // fried egg+ 150 => &[(Regeneration, 5.0, 1), (JumpBoost, 45.0, 0)], // cooked rabbit (leaping)+ 151 => &[(Regeneration, 4.0, 0), (Speed, 20.0, 0)], // apple empanada+ 152 => &[(Regeneration, 4.0, 0), (NightVision, 90.0, 0)], // glow berry crumble+ 153 => &[(Regeneration, 3.0, 0), (Haste, 60.0, 0)], // chocolate chip cookie+ // Blessings: charm consumables granting long multi-effect buffs (Matcha's enchant bundles,+ // reimagined for a game without gear).+ 160 => &[(Speed, 300.0, 1), (JumpBoost, 300.0, 0)], // Blessing of Swiftness+ 161 => &[(Strength, 300.0, 1), (Resistance, 300.0, 0)], // Blessing of the Warrior+ 162 => &[(NightVision, 300.0, 0), (FireResistance, 300.0, 0)], // Blessing of the Deep+ _ => return None,+ })+}
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 c01afff4f5..7bf014c427 100644--- a/games/voxels/src/main/rust/src/lib.rs+++ b/games/voxels/src/main/rust/src/lib.rs@@ -1,5 +1,6 @@ pub mod world; pub mod entity;+pub mod item; pub mod player; pub mod raycast; pub mod input;@@ -217,6 +218,21 @@ pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_getRe 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_trade<'l>(+ _env: JNIEnv<'l>, _class: JClass<'l>, idx: jint,+) -> jboolean {+ if idx >= 0 && engine::do_trade(idx as usize) { 1 } else { 0 }+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_getTradesJson<'l>(+ mut env: JNIEnv<'l>, _class: JClass<'l>,+) -> jstring {+ let null = std::ptr::null_mut();+ match env.new_string(engine::get_trades_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>,@@ -256,6 +272,18 @@ pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_getSt } } +#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_getHealthJson<'l>(+ mut env: JNIEnv<'l>,+ _class: JClass<'l>,+) -> jstring {+ let null = std::ptr::null_mut();+ match env.new_string(engine::get_health_json()) {+ Ok(s) => s.into_raw(),+ Err(_) => null,+ }+}+ #[cfg(test)] mod tests { use crate::world::chunk::{Chunk, ChunkPos};
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 de9e5f08ca..4efd4a0d86 100644--- a/games/voxels/src/main/rust/src/player.rs+++ b/games/voxels/src/main/rust/src/player.rs@@ -1,5 +1,9 @@ use glam::{Vec3, vec3}; use crate::world::{ChunkMap, block::Block};+use crate::item::{Effect, ActiveEffect};++pub const MIN_MAX_HEALTH: f32 = 20.0; // 10 hearts floor (deaths never take you below this)+pub const CAP_MAX_HEALTH: f32 = 60.0; // 30 hearts cap (heart containers) pub struct Player { pub pos: Vec3,@@ -10,11 +14,68 @@ pub struct Player { pub flying: bool, pub walk_dist: f32, pub sneaking: bool,+ // Survival state.+ pub health: f32,+ pub max_health: f32,+ pub absorption: f32,+ pub effects: Vec<ActiveEffect>,+ pub hurt_cd: f32,+ pub attack_cd: f32,+ pub eat_cd: f32,+ pub air_max_y: f32,+ pub dead: 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, sneaking: false }+ 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,+ health: 20.0, max_health: 20.0, absorption: 0.0, effects: Vec::new(), hurt_cd: 0.0, attack_cd: 0.0, eat_cd: 0.0, air_max_y: y, dead: false }+ }++ fn effect_amp(&self, k: Effect) -> Option<u8> { self.effects.iter().filter(|e| e.kind == k).map(|e| e.amp).max() }+ pub fn has_effect(&self, k: Effect) -> bool { self.effect_amp(k).is_some() }+ pub fn speed_mult(&self) -> f32 {+ let sp = self.effect_amp(Effect::Speed).map(|a| a as f32 + 1.0).unwrap_or(0.0);+ let sl = self.effect_amp(Effect::Slowness).map(|a| a as f32 + 1.0).unwrap_or(0.0);+ (1.0 + 0.2 * sp - 0.15 * sl).max(0.25)+ }+ pub fn jump_bonus(&self) -> f32 { 2.2 * self.effect_amp(Effect::JumpBoost).map(|a| a as f32 + 1.0).unwrap_or(0.0) }+ pub fn night_vision(&self) -> bool { self.has_effect(Effect::NightVision) }+ pub fn strength_bonus(&self) -> f32 { 3.0 * self.effect_amp(Effect::Strength).map(|a| a as f32 + 1.0).unwrap_or(0.0) }+ fn resistance_mult(&self) -> f32 { (1.0 - 0.2 * self.effect_amp(Effect::Resistance).map(|a| a as f32 + 1.0).unwrap_or(0.0)).max(0.0) }++ pub fn add_effect(&mut self, kind: Effect, secs: f32, amp: u8) {+ if kind == Effect::Absorption { self.absorption = self.absorption.max((amp as f32 + 1.0) * 4.0); }+ if let Some(e) = self.effects.iter_mut().find(|e| e.kind == kind) {+ if amp >= e.amp { e.amp = amp; }+ e.secs = e.secs.max(secs);+ } else {+ self.effects.push(ActiveEffect { kind, secs, amp });+ }+ }+ pub fn heal(&mut self, amt: f32) { self.health = (self.health + amt).min(self.max_health); }+ pub fn damage(&mut self, amt: f32) {+ if self.dead || self.hurt_cd > 0.0 || amt <= 0.0 { return; }+ let amt = amt * self.resistance_mult();+ let soak = amt.min(self.absorption);+ self.absorption -= soak;+ self.health -= amt - soak;+ self.hurt_cd = 0.4;+ if self.health <= 0.0 { self.health = 0.0; self.dead = true; }+ }++ // Regeneration/poison/absorption expiry + cooldowns. Called every frame.+ pub fn tick_status(&mut self, dt: f32) {+ if self.hurt_cd > 0.0 { self.hurt_cd -= dt; }+ if self.attack_cd > 0.0 { self.attack_cd -= dt; }+ if self.eat_cd > 0.0 { self.eat_cd -= dt; }+ for e in self.effects.iter_mut() { e.secs -= dt; }+ self.effects.retain(|e| e.secs > 0.0);+ if let Some(a) = self.effect_amp(Effect::Regeneration) { self.heal((a as f32 + 1.0) * dt); }+ if let Some(a) = self.effect_amp(Effect::Poison) {+ if self.health > 1.0 { self.health = (self.health - (a as f32 + 1.0) * dt).max(1.0); }+ }+ if !self.has_effect(Effect::Absorption) { self.absorption = 0.0; } } pub fn eye_pos(&self) -> Vec3 { self.pos + vec3(0.0, 1.62, 0.0) } pub fn forward(&self) -> Vec3 {@@ -37,7 +98,7 @@ impl Player { if wish.length_squared() > 0.0 { wish = wish.normalize_or_zero(); } if self.flying {- let speed = 10.0 * if input.sprint { 2.0 } else { 1.0 };+ let speed = 10.0 * self.speed_mult() * if input.sprint { 2.0 } else { 1.0 }; let mut vel = wish * speed; if input.jump_held { vel.y += speed; } // top button (Up) if input.down_held { vel.y -= speed; } // bottom button (Down)@@ -47,7 +108,7 @@ impl Player { self.walk_dist += (vel * dt).length(); } else { let sneaking = input.sneak;- let speed = 4.3 * if sneaking { 0.3 } else if input.sprint { 1.3 } else { 1.0 };+ let speed = 4.3 * self.speed_mult() * if sneaking { 0.3 } else if input.sprint { 1.3 } else { 1.0 }; // Auto-unstuck: if we ended up inside terrain (bad save, block placed onto us, spawn // fractionally embedded) rise until free so the player is never permanently trapped. if self.collides_at(self.pos, chunks) {@@ -89,12 +150,22 @@ impl Player { } // Can't jump while sneaking (must toggle sneak off first). if input.jump_held && self.on_ground && !sneaking {- self.vel.y = 8.5;+ self.vel.y = 8.5 + self.jump_bonus(); self.on_ground = false; } self.pos = new_pos; } if self.pos.y < 0.1 { self.pos.y = 0.1; self.vel.y = 0.0; self.on_ground = true; }+ // Fall damage: track peak airborne height, hurt on landing beyond a safe margin.+ if self.flying {+ self.air_max_y = self.pos.y;+ } else if !self.on_ground {+ if self.pos.y > self.air_max_y { self.air_max_y = self.pos.y; }+ } else {+ let fall = self.air_max_y - self.pos.y;+ if fall > 3.5 { self.damage(fall - 3.5); }+ self.air_max_y = self.pos.y;+ } } // True if there is a solid block just under the player's footprint at `pos` (used so a sneaking
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 8c85e8f5c7..23e2f19a3f 100644--- a/games/voxels/src/main/rust/src/vulkan/buffers.rs+++ b/games/voxels/src/main/rust/src/vulkan/buffers.rs@@ -10,13 +10,14 @@ pub struct Vertex { pub ao: f32, pub tile_idx: f32, pub normal: [f32; 3],+ pub light: f32, } impl Vertex { pub fn binding_description() -> vk::VertexInputBindingDescription { vk::VertexInputBindingDescription::default().binding(0).stride(mem::size_of::<Self>() as u32).input_rate(vk::VertexInputRate::VERTEX) }- pub fn attribute_descriptions() -> [vk::VertexInputAttributeDescription; 6] {+ pub fn attribute_descriptions() -> [vk::VertexInputAttributeDescription; 7] { [ vk::VertexInputAttributeDescription::default().binding(0).location(0).format(vk::Format::R32G32B32_SFLOAT).offset(mem::offset_of!(Vertex, pos) as u32), vk::VertexInputAttributeDescription::default().binding(0).location(1).format(vk::Format::R32G32_SFLOAT).offset(mem::offset_of!(Vertex, uv) as u32),@@ -24,6 +25,7 @@ impl Vertex { vk::VertexInputAttributeDescription::default().binding(0).location(3).format(vk::Format::R32_SFLOAT).offset(mem::offset_of!(Vertex, ao) as u32), vk::VertexInputAttributeDescription::default().binding(0).location(4).format(vk::Format::R32_SFLOAT).offset(mem::offset_of!(Vertex, tile_idx) as u32), vk::VertexInputAttributeDescription::default().binding(0).location(5).format(vk::Format::R32G32B32_SFLOAT).offset(mem::offset_of!(Vertex, normal) as u32),+ vk::VertexInputAttributeDescription::default().binding(0).location(6).format(vk::Format::R32_SFLOAT).offset(mem::offset_of!(Vertex, light) as u32), ] } }
games/voxels/src/main/rust/src/vulkan/renderer.rs
diff --git a/games/voxels/src/main/rust/src/vulkan/renderer.rs b/games/voxels/src/main/rust/src/vulkan/renderer.rsindex 6d39efc999..86cddc11ec 100644--- a/games/voxels/src/main/rust/src/vulkan/renderer.rs+++ b/games/voxels/src/main/rust/src/vulkan/renderer.rs@@ -173,7 +173,7 @@ impl VulkanRenderer { } Ok(()) }- pub unsafe fn update_ubo(&mut self, view_proj: Mat4, player_pos: Vec3, time: f32, underwater: f32) {+ pub unsafe fn update_ubo(&mut self, view_proj: Mat4, player_pos: Vec3, time: f32, underwater: f32, night_vision: f32) { let day_cycle=120.0; let day_t=(time/day_cycle)%1.0; let sun_angle=day_t*std::f32::consts::TAU - std::f32::consts::FRAC_PI_2; let sun_dir=Vec3::new(sun_angle.cos()*0.3, sun_angle.sin(), sun_angle.cos()*0.1).normalize_or_zero();@@ -199,7 +199,7 @@ impl VulkanRenderer { let half = 90.0; let light_proj = Mat4::orthographic_rh(-half, half, -half, half, 1.0, light_dist * 2.0); let light_view_proj = light_proj * light_view;- self.ubo_data=UboData{ view_proj: view_proj.to_cols_array_2d(), sun_dir: sun_dir.to_array(), time, fog_color: fog_color.to_array(), fog_density: 0.008 / (1.0+day_factor*0.8).max(0.2), player_pos: [player_pos.x, player_pos.y, player_pos.z, underwater], day_factor, _pad: [0.0;3], inv_view_proj: inv_view_proj.to_cols_array_2d(), sun_color: sun_color.to_array(), cloud_shadow: 0.6, ambient_color: ambient_color.to_array(), _pad2: 0.0, light_view_proj: light_view_proj.to_cols_array_2d() };+ self.ubo_data=UboData{ view_proj: view_proj.to_cols_array_2d(), sun_dir: sun_dir.to_array(), time, fog_color: fog_color.to_array(), fog_density: 0.008 / (1.0+day_factor*0.8).max(0.2), player_pos: [player_pos.x, player_pos.y, player_pos.z, underwater], day_factor, _pad: [0.0;3], inv_view_proj: inv_view_proj.to_cols_array_2d(), sun_color: sun_color.to_array(), cloud_shadow: 0.6, ambient_color: ambient_color.to_array(), _pad2: night_vision, light_view_proj: light_view_proj.to_cols_array_2d() }; let bytes=unsafe { std::slice::from_raw_parts((&self.ubo_data as *const UboData) as *const u8, std::mem::size_of::<UboData>()) }; self.ubo_buffer.upload(&self.ctx.device, bytes); }
games/voxels/src/main/rust/src/world/block.rs
diff --git a/games/voxels/src/main/rust/src/world/block.rs b/games/voxels/src/main/rust/src/world/block.rsindex a913f39cb6..4fe8b36fad 100644--- a/games/voxels/src/main/rust/src/world/block.rs+++ b/games/voxels/src/main/rust/src/world/block.rs@@ -86,9 +86,11 @@ pub enum Block { Obsidian = 78, Clay = 79, AzaleaLeaves = 80,+ WardingStone = 81,+ Jukebox = 82, } -pub const MAX_BLOCK_ID: u8 = 80;+pub const MAX_BLOCK_ID: u8 = 82; impl Block { pub fn from_id(id: u8) -> Self {@@ -104,7 +106,7 @@ impl Block { // Interactive block menu: 0 = none, 1 = crafting, 2 = furnace. pub fn menu(self) -> i32 {- match self { Self::CraftingTable => 1, Self::Furnace => 2, _ => 0 }+ match self { Self::CraftingTable => 1, Self::Furnace => 2, Self::Jukebox => 3, _ => 0 } } // Atlas tile indices (8x8 atlas). See the atlas generator's TILES order.@@ -191,6 +193,8 @@ impl Block { Self::Obsidian => 114, Self::Clay => 115, Self::AzaleaLeaves => 116,+ Self::WardingStone => 117,+ Self::Jukebox => 118, } } pub fn tile_bottom(self) -> u32 {@@ -239,6 +243,25 @@ impl Block { _ => [1.0, 1.0, 1.0], } }+ // Stone/mineral blocks that only drop when mined with a pickaxe.+ pub fn needs_pickaxe(self) -> bool {+ matches!(self,+ Self::Stone | Self::Cobble | Self::Brick | Self::MossyCobble | Self::Diorite | Self::PolishedDiorite+ | Self::CoalOre | Self::IronOre | Self::DiamondOre | Self::RedstoneOre | Self::EmeraldOre+ | Self::IronBlock | Self::DiamondBlock | Self::EmeraldBlock | Self::Netherrack | Self::Furnace+ | Self::RedSandstone | Self::Sandstone | Self::GraniteBricks | Self::DeepslateBricks | Self::NetherBricks+ | Self::EndStoneBricks | Self::CobbledDeepslate | Self::Prismarine | Self::DarkPrismarine | Self::Dripstone+ | Self::Amethyst | Self::Calcite | Self::Tuff | Self::Magma | Self::Obsidian | Self::PackedIce | Self::BlueIce)+ }+ // Block light emitted (0..15) for dynamic lighting.+ pub fn light_emission(self) -> u8 {+ match self {+ Self::Glowstone | Self::SeaLantern => 15,+ Self::WardingStone => 13,+ Self::Magma => 11,+ _ => 0,+ }+ } pub fn tile_for_dir(self, _dx: i32, dy: i32, _dz: i32) -> u32 { if dy == 1 { self.tile_top() } else if dy == -1 { self.tile_bottom() } else { self.tile_side() } }
games/voxels/src/main/rust/src/world/generator.rs
diff --git a/games/voxels/src/main/rust/src/world/generator.rs b/games/voxels/src/main/rust/src/world/generator.rsindex 1f2360944b..09a7f38606 100644--- a/games/voxels/src/main/rust/src/world/generator.rs+++ b/games/voxels/src/main/rust/src/world/generator.rs@@ -357,6 +357,21 @@ impl TerrainGen { chunk.set_block(x as usize, cy, z as usize, id); }} }+ Biome::Plains | Biome::Meadow | Biome::Forest | Biome::Savanna | Biome::FlowerForest if sr < 6 => {+ // Shrine: a small cobble platform topped with a Warding Stone (natural checkpoint).+ let cy = sh_top;+ for ddx in -1i32..=1 { for ddz in -1i32..=1 {+ let (x, z) = (bx as i32 + ddx, bz as i32 + ddz);+ if x < 0 || x >= 16 || z < 0 || z >= 16 { continue; }+ chunk.set_block(x as usize, cy, z as usize, 8); // cobble platform+ }}+ // Corner pillars + warding stone centre.+ for &(px, pz) in &[(-1i32, -1i32), (1, -1), (-1, 1), (1, 1)] {+ let (x, z) = (bx as i32 + px, bz as i32 + pz);+ if x >= 0 && x < 16 && z >= 0 && z < 16 && cy + 1 < CHUNK_HEIGHT { chunk.set_block(x as usize, cy + 1, z as usize, 1); }+ }+ if cy + 1 < CHUNK_HEIGHT { chunk.set_block(bx, cy + 1, bz, 81); } // warding stone+ } _ => {} } }
games/voxels/src/main/rust/src/world/mesher.rs
diff --git a/games/voxels/src/main/rust/src/world/mesher.rs b/games/voxels/src/main/rust/src/world/mesher.rsindex b8e20e049a..1bccc93089 100644--- a/games/voxels/src/main/rust/src/world/mesher.rs+++ b/games/voxels/src/main/rust/src/world/mesher.rs@@ -1,5 +1,43 @@ use super::block::{Block, GRASS_SIDE_TILE};-use super::chunk::{Chunk, SECTION_SIZE, SECTIONS_PER_CHUNK};+use super::chunk::{Chunk, SECTION_SIZE, SECTIONS_PER_CHUNK, CHUNK_HEIGHT};++// Per-chunk lighting: skylight column tops (highest opaque block per column) and a block-light grid+// (BFS flood from emitters, decreasing by 1 per open cell). Cross-chunk bleed is limited to this+// chunk's own data, which is plenty for caves + torch pools.+fn compute_light(chunk: &Chunk) -> ([[i32; 16]; 16], Vec<u8>) {+ let mut col_top = [[-1i32; 16]; 16];+ for x in 0..16 { for z in 0..16 {+ for y in (0..CHUNK_HEIGHT).rev() {+ let id = chunk.get_block(x, y, z);+ if id != 0 && Block::from_id(id).is_opaque() { col_top[x][z] = y as i32; break; }+ }+ }}+ let mut blk = vec![0u8; 16 * CHUNK_HEIGHT * 16];+ let idx = |x: usize, y: usize, z: usize| (y * 16 + z) * 16 + x;+ let mut q: std::collections::VecDeque<(usize, usize, usize, u8)> = std::collections::VecDeque::new();+ for y in 0..CHUNK_HEIGHT { for z in 0..16 { for x in 0..16 {+ let e = Block::from_id(chunk.get_block(x, y, z)).light_emission();+ if e > 0 { let i = idx(x, y, z); if blk[i] < e { blk[i] = e; q.push_back((x, y, z, e)); } }+ }}}+ while let Some((x, y, z, l)) = q.pop_front() {+ if l <= 1 { continue; }+ let nl = l - 1;+ let nbrs = [(x as i32 + 1, y as i32, z as i32), (x as i32 - 1, y as i32, z as i32),+ (x as i32, y as i32 + 1, z as i32), (x as i32, y as i32 - 1, z as i32),+ (x as i32, y as i32, z as i32 + 1), (x as i32, y as i32, z as i32 - 1)];+ for (nx, ny, nz) in nbrs {+ if nx < 0 || nx >= 16 || nz < 0 || nz >= 16 || ny < 0 || ny >= CHUNK_HEIGHT as i32 { continue; }+ let (nx, ny, nz) = (nx as usize, ny as usize, nz as usize);+ let bid = chunk.get_block(nx, ny, nz);+ if bid != 0 && Block::from_id(bid).is_opaque() { continue; }+ let i = idx(nx, ny, nz);+ if blk[i] < nl { blk[i] = nl; q.push_back((nx, ny, nz, nl)); }+ }+ }+ (col_top, blk)+}+// Pack skylight (low nibble) + blocklight (high nibble) into a u8; decode to the shader's f32.+fn light_to_f32(packed: u8) -> f32 { (packed & 0x0F) as f32 + ((packed >> 4) & 0x0F) as f32 * 16.0 } #[repr(C)] #[derive(Clone, Copy, Debug)]@@ -12,6 +50,8 @@ pub struct Vertex { pub ao: f32, pub tile_idx: f32, pub normal: [f32; 3],+ // Packed lighting: skylight + blocklight*16 (each 0..15). Read by block.frag; 0 elsewhere.+ pub light: f32, } pub struct MeshData {@@ -31,6 +71,19 @@ fn aof(level: u8) -> f32 { level as f32 / 3.0 } pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &dyn Fn(i32,i32,i32)->u8, grass_tint: &dyn Fn(i32,i32)->[f32;3]) -> Vec<Option<MeshData>> { let occ = |ax: i32, ay: i32, az: i32| -> bool { let id = get_neighbor(ax, ay, az); id != 0 && Block::from_id(id).is_opaque() }; let mut result: Vec<Option<MeshData>> = (0..SECTIONS_PER_CHUNK).map(|_| None).collect();+ let ox = chunk.pos.world_origin().0;+ let oz = chunk.pos.world_origin().1;+ // Lighting for the whole chunk column, sampled per exposed face (at the neighbouring air cell).+ let (col_top, blk) = compute_light(chunk);+ let face_light = |wx: i32, wy: i32, wz: i32| -> u8 {+ let lx = (wx - ox).clamp(0, 15) as usize;+ let lz = (wz - oz).clamp(0, 15) as usize;+ let top = col_top[lx][lz];+ let sky = if wy > top { 15 } else { (15 - (top - wy) * 3).max(0) } as u8;+ let by = wy.clamp(0, CHUNK_HEIGHT as i32 - 1) as usize;+ let b = blk[(by * 16 + lz) * 16 + lx];+ sky | (b << 4)+ }; for sec_idx in 0..SECTIONS_PER_CHUNK { let section = match &chunk.sections[sec_idx] { Some(s) if !s.is_empty() => s,@@ -39,8 +92,6 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &dyn Fn(i32,i32,i32)->u8, grass_t let base_y = (sec_idx * SECTION_SIZE) as i32; let mut verts = Vec::with_capacity(1024); let mut indices = Vec::with_capacity(1536);- let ox = chunk.pos.world_origin().0;- let oz = chunk.pos.world_origin().1; let dirs = [(1,0,0,0), (-1,0,0,0), (0,1,0,1), (0,-1,0,1), (0,0,1,2), (0,0,-1,2)]; for &(dx,dy,dz, axis) in &dirs { let nrm = [dx as f32, dy as f32, dz as f32];@@ -48,7 +99,7 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &dyn Fn(i32,i32,i32)->u8, grass_t match axis { 0 => { for x in 0..SECTION_SIZE {- let mut mask = [[None::<(u8,u32,[u8;4])>; 16]; 16];+ let mut mask = [[None::<(u8,u32,[u8;4],u8)>; 16]; 16]; for y in 0..SECTION_SIZE { for z in 0..SECTION_SIZE { let id = section.get(x,y,z); if id == 0 || id == Block::Water as u8 { continue; }@@ -61,18 +112,18 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &dyn Fn(i32,i32,i32)->u8, grass_t let ao = |ys: i32, zs: i32| vao(occ(nb, wy+ys, wz), occ(nb, wy, wz+zs), occ(nb, wy+ys, wz+zs)); let ao4 = if dx==1 { [ao(-1,-1), ao(1,-1), ao(1,1), ao(-1,1)] } else { [ao(-1,1), ao(1,1), ao(1,-1), ao(-1,-1)] };- mask[y][z] = Some((id, tile, ao4));+ mask[y][z] = Some((id, tile, ao4, face_light(wx+dx, wy+dy, wz+dz))); } }} let mut visited = [[false; 16]; 16]; for y in 0..SECTION_SIZE { for z in 0..SECTION_SIZE { if visited[y][z] { continue; }- let Some((bid, tile_idx, ao4)) = mask[y][z] else { continue; };+ let Some((bid, tile_idx, ao4, lpk)) = mask[y][z] else { continue; }; let mut w = 1;- while z + w < SECTION_SIZE && !visited[y][z+w] && mask[y][z+w] == Some((bid, tile_idx, ao4)) { w+=1; }+ while z + w < SECTION_SIZE && !visited[y][z+w] && mask[y][z+w] == Some((bid, tile_idx, ao4, lpk)) { w+=1; } let mut h = 1; 'outer: while y + h < SECTION_SIZE {- for k in 0..w { if visited[y+h][z+k] || mask[y+h][z+k] != Some((bid, tile_idx, ao4)) { break 'outer; } }+ for k in 0..w { if visited[y+h][z+k] || mask[y+h][z+k] != Some((bid, tile_idx, ao4, lpk)) { break 'outer; } } h+=1; } for yy in y..y+h { for zz in z..z+w { visited[yy][zz]=true; } }@@ -91,7 +142,7 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &dyn Fn(i32,i32,i32)->u8, grass_t let wx0 = ox as f32; let wz0 = oz as f32; let by = base_y as f32; let start = verts.len() as u32; for (i,(pos, uv)) in quad.iter().enumerate() {- verts.push(Vertex{ pos: [wx0 + pos[0], by + pos[1], wz0 + pos[2]], uv: *uv, color, ao: aof(ao4[i]), tile_idx: etile, normal: nrm });+ verts.push(Vertex{ pos: [wx0 + pos[0], by + pos[1], wz0 + pos[2]], uv: *uv, color, ao: aof(ao4[i]), tile_idx: etile, normal: nrm, light: light_to_f32(lpk) }); } indices.extend_from_slice(&[start, start+1, start+2, start, start+2, start+3]); }}@@ -99,7 +150,7 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &dyn Fn(i32,i32,i32)->u8, grass_t } 1 => { for y in 0..SECTION_SIZE {- let mut mask = [[None::<(u8,u32,[u8;4])>; 16]; 16];+ let mut mask = [[None::<(u8,u32,[u8;4],u8)>; 16]; 16]; for x in 0..SECTION_SIZE { for z in 0..SECTION_SIZE { let id = section.get(x,y,z); if id==0 || id==Block::Water as u8 { continue; }@@ -112,19 +163,19 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &dyn Fn(i32,i32,i32)->u8, grass_t let ao = |xs: i32, zs: i32| vao(occ(wx+xs, nb, wz), occ(wx, nb, wz+zs), occ(wx+xs, nb, wz+zs)); let ao4 = if dy==1 { [ao(-1,-1), ao(1,-1), ao(1,1), ao(-1,1)] } else { [ao(-1,1), ao(1,1), ao(1,-1), ao(-1,-1)] };- mask[x][z]=Some((id, tile, ao4));+ mask[x][z]=Some((id, tile, ao4, face_light(wx+dx, wy+dy, wz+dz))); } } }} let mut visited = [[false; 16]; 16]; for x in 0..SECTION_SIZE { for z in 0..SECTION_SIZE { if visited[x][z] { continue; }- let Some((bid, tile_idx, ao4)) = mask[x][z] else { continue; };+ let Some((bid, tile_idx, ao4, lpk)) = mask[x][z] else { continue; }; let mut w = 1;- while z+w < SECTION_SIZE && !visited[x][z+w] && mask[x][z+w]==Some((bid, tile_idx, ao4)) { w+=1; }+ while z+w < SECTION_SIZE && !visited[x][z+w] && mask[x][z+w]==Some((bid, tile_idx, ao4, lpk)) { w+=1; } let mut h = 1; 'outer2: while x+h < SECTION_SIZE {- for k in 0..w { if visited[x+h][z+k] || mask[x+h][z+k]!=Some((bid, tile_idx, ao4)) { break 'outer2; } }+ for k in 0..w { if visited[x+h][z+k] || mask[x+h][z+k]!=Some((bid, tile_idx, ao4, lpk)) { break 'outer2; } } h+=1; } for xx in x..x+h { for zz in z..z+w { visited[xx][zz]=true; } }@@ -142,7 +193,7 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &dyn Fn(i32,i32,i32)->u8, grass_t }; let start = verts.len() as u32; for (i,(lp, uv)) in quad.iter().enumerate() {- verts.push(Vertex{ pos: [wx0 + lp[0], by + lp[1], wz0 + lp[2]], uv: *uv, color, ao: aof(ao4[i]), tile_idx: tile_idx as f32, normal: nrm });+ verts.push(Vertex{ pos: [wx0 + lp[0], by + lp[1], wz0 + lp[2]], uv: *uv, color, ao: aof(ao4[i]), tile_idx: tile_idx as f32, normal: nrm, light: light_to_f32(lpk) }); } indices.extend_from_slice(&[start, start+1, start+2, start, start+2, start+3]); }}@@ -150,7 +201,7 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &dyn Fn(i32,i32,i32)->u8, grass_t } 2 => { for z in 0..SECTION_SIZE {- let mut mask = [[None::<(u8,u32,[u8;4])>; 16]; 16];+ let mut mask = [[None::<(u8,u32,[u8;4],u8)>; 16]; 16]; for x in 0..SECTION_SIZE { for y in 0..SECTION_SIZE { let id = section.get(x,y,z); if id==0 || id==Block::Water as u8 { continue; }@@ -162,18 +213,18 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &dyn Fn(i32,i32,i32)->u8, grass_t let ao = |xs: i32, ys: i32| vao(occ(wx+xs, wy, nb), occ(wx, wy+ys, nb), occ(wx+xs, wy+ys, nb)); let ao4 = if dz==1 { [ao(-1,-1), ao(1,-1), ao(1,1), ao(-1,1)] } else { [ao(1,-1), ao(-1,-1), ao(-1,1), ao(1,1)] };- mask[x][y]=Some((id, tile, ao4));+ mask[x][y]=Some((id, tile, ao4, face_light(wx+dx, wy+dy, wz+dz))); } }} let mut visited = [[false; 16]; 16]; for x in 0..SECTION_SIZE { for y in 0..SECTION_SIZE { if visited[x][y] { continue; }- let Some((bid, tile_idx, ao4)) = mask[x][y] else { continue; };+ let Some((bid, tile_idx, ao4, lpk)) = mask[x][y] else { continue; }; let mut w = 1;- while y+w < SECTION_SIZE && !visited[x][y+w] && mask[x][y+w]==Some((bid, tile_idx, ao4)) { w+=1; }+ while y+w < SECTION_SIZE && !visited[x][y+w] && mask[x][y+w]==Some((bid, tile_idx, ao4, lpk)) { w+=1; } let mut h = 1; 'outer3: while x+h < SECTION_SIZE {- for k in 0..w { if visited[x+h][y+k] || mask[x+h][y+k]!=Some((bid, tile_idx, ao4)) { break 'outer3; } }+ for k in 0..w { if visited[x+h][y+k] || mask[x+h][y+k]!=Some((bid, tile_idx, ao4, lpk)) { break 'outer3; } } h+=1; } for xx in x..x+h { for yy in y..y+w { visited[xx][yy]=true; } }@@ -191,7 +242,7 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &dyn Fn(i32,i32,i32)->u8, grass_t }; let start = verts.len() as u32; for (i,(lp, uv)) in quad.iter().enumerate() {- verts.push(Vertex{ pos: [wx0 + lp[0], by + lp[1], wz0 + lp[2]], uv: *uv, color, ao: aof(ao4[i]), tile_idx: etile, normal: nrm });+ verts.push(Vertex{ pos: [wx0 + lp[0], by + lp[1], wz0 + lp[2]], uv: *uv, color, ao: aof(ao4[i]), tile_idx: etile, normal: nrm, light: light_to_f32(lpk) }); } indices.extend_from_slice(&[start, start+1, start+2, start, start+2, start+3]); }}@@ -226,7 +277,7 @@ pub fn mesh_chunk(chunk: &Chunk, get_neighbor: &dyn Fn(i32,i32,i32)->u8, grass_t let quad = [([x0,y0,z0],[u0,v0]), ([x0+hh,y0,z0],[u1,v0]), ([x0+hh,y0,z0+ww],[u1,v1]), ([x0,y0,z0+ww],[u0,v1])]; let start = wverts.len() as u32; for (pos,uv) in quad.iter() {- wverts.push(Vertex{ pos: [wx0+pos[0], by+pos[1], wz0+pos[2]], uv: *uv, color: [1.0,1.0,1.0], ao: 1.0, tile_idx: 13.0, normal: [0.0,1.0,0.0] });+ wverts.push(Vertex{ pos: [wx0+pos[0], by+pos[1], wz0+pos[2]], uv: *uv, color: [1.0,1.0,1.0], ao: 1.0, tile_idx: 13.0, normal: [0.0,1.0,0.0], light: 15.0 }); } windices.extend_from_slice(&[start, start+1, start+2, start, start+2, start+3]); }}