Build a browser-based Minecraft-style voxel game featuring a procedurally generated 3D block world, first-person controls (WASD movement, mouse look, jumping with gravity/collision), block breaking and placing, multiple block types with a selectable hotbar inventory, day-lighting, and infinite-feeling terrain with trees. Use Three.js for rendering.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Day lighting (directional sun + ambient + sky color)
Crosshair, hotbar UI, loading
Since the build uses vite-plugin-singlefile, everything gets inlined. I need to avoid external assets. I'll use a texture atlas generated procedurally via canvas, or simpler — use flat colors with slight per-face shading for a classic voxel feel. I'll generate texture atlas via canvas for a nicer look with subtle noise texture on grass.
Let me keep it performant by using a Cullable chunk system. Let me build the files.
Let me start with the blocks definition and a noise utility.
Now the blocks definitions:
Now the world generation. I'll use a chunk-based system keyed by chunk coordinates, generating a heightmap with fBm, placing terrain blocks (grass, dirt, stone, sand, water), and trees. I'll store voxels in a typed array per chunk.
I have a lint error for unused surface variable. Let me fix that and remove the redundant import lines.
I need to remove the duplicate import and helper function, plus the redundant re-export. Let me clean up those lines.
Now let me fix the unused surface variable in the tree placement loop.
Also the CS and WH re-export and the end export { CHUNK_SIZE as CS, WORLD_HEIGHT as WH } — CHUNK_SIZE and WORLD_HEIGHT are already imported. Let me check the file end and clean up. Actually _renderDistance isn't there. Let me verify the current file state around those re-exports.
Let me clean up the redundant re-export at the end.
Now let me create the Game engine class. This is the core that manages Three.js rendering, chunk meshes with culled faces, player physics, raycasting for block interaction, and holds UI state.
Let me create the player physics module first.
I left some dead code. Let me clean up the updatePlayer function and remove the unused dirX variable and axisSolid function.
Player module is clean now. Now let me create the main Game engine class. This is the most complex file — it handles Three.js setup, chunk mesh generation (with face culling and per-face shading), camera control, raycasting for block interaction, rendering loop, and day lighting.
This file has a number of issues. I used BlockId.AirIgnore which doesn't exist (it should be BLOCK_AIR), and I have some messy leftover code. Let me rewrite this file cleanly. I'll create a cleaner, more carefully written version.
Let me first check the blocks.ts to add a BLOCK_AIR reference, and fix the FaceDef typing. Let me rewrite Game.ts more carefully.
Let me fix these lint issues. I need to remove the unused addCubeGeometry function, remove the unused cm variable in this.chunkMeshes.forEach, and fix the addFace call to use this.addFace, and remove the unused by variable.
Now let me fix the cm unused variable in buildChunkColumn, the addFace call, and the unused by in rebuildAround.
Now let me fix the addFace call (it's inside the class, so should be this.addFace), and the unused by variable. Let me view those sections.
Let me fix the addFace call (remove dead target.indices.push line and fix the reference). And rename the unused by param to _by.
No more lint errors in Game.ts. Now let me create the React App component with the HUD (crosshair, hotbar, controls overlay).
Now let me add scroll-wheel hotbar selection. Let me add a wheel event in the Game. Also I need to make sure the game canvas doesn't block the start button clicks when not locked. But since the canvas is only appended under the overlay, and the overlay is on top (z-30), clicks on the Play button work. The canvas mousedown handler requests pointer lock only when the overlay is gone. But when overlay is visible, the overlay blocks the canvas so mousedown won't fire on canvas. Good.
Let me add scroll wheel support to Game and also ensure block placement doesn't happen through water when aiming. Let me add the wheel listener.
I need to add the onWheel handler method and remove the listener in dispose.
Now let me update the index.html title and run the build.
The build succeeded. Let me review the game logic for a couple of potential issues before finalizing:
Water rendering logic — I have a check if (id === BlockId.Water && nid === BlockId.Water) continue; to hide shared water faces. That's correct.
Block placement through water — The raycastPlace finds the first solid block and places in the empty cell before it. Good, water is non-solid so it'll be treated as pass-through.
Dead variable translucent check in buildChunkMesh — I use translucent in the surface logic. Good.
Let me double-check the BlockId.AirIgnore reference — I removed all of those, they now correctly use BLOCK_AIR.
One concern: In blocks.ts, BLOCK_AIR = 0, and Uint8Array default is 0, so air blocks default correctly.
Let me verify there are no remaining references that could cause runtime issues. Let me check the water surface — when water is at y <= SEA_LEVEL, and it's a surface (air above), it renders. Good.
Let me also verify the buildChunkMesh handles the transparent builders correctly — when transparent.positions.length > 0. Good.
One thing to double check: the getNeighbor function returns getBlock(baseX + lx, y, baseZ + lz) for out-of-bounds, which handles cross-chunk faces. Good.
Let me also reconsider the spawn — the player spawns at (8.5, ground+1.01, 8.5). The ground scan uses isSolidAt(Math.floor(sx), y, Math.floor(sz)) which finds the highest solid Y. Good.
Now, there's one subtle issue with the chunk rebuild during interaction: when I break or place a block at night near chunk edges, rebuildAround rebuilds the correct chunks. And setBlockAt mutates the cached chunk data. But there's a subtlety: when the world generator caches chunks and a neighbor chunk is generated it reads block data from its own freshly-generated chunk data (not affected by edits). However the neighbor chunk that shares a boundary still needs its mesh rebuilt, which rebuildAround handles. Good.
However, there is a concern: generateChunk caches chunk data. When I edit a block in chunk A via setBlockAt, it gets the cached data and mutates it. Good — subsequent reads reflect the edit. But buildChunkMesh reads from the cached chunk, so editing then rebuilding shows the change.
One more: when placing/breaking, rebuildAround calls removeChunk then buildChunkMesh which reads current data. Good.
Let me verify the logic reads correctly - there may be an issue where getBlockNeighbor/cross-chunk neighbor generation uses isSolid on the neighbor block. That's fine.
Now, let me consider a potential problem with the water opacity and depth — translucent materials with depthWrite: false render in the transparent pass. Since I use side: DoubleSide, water surfaces visible. Good.
Let me also verify performance: render distance 4 → 9x9=81 chunks, each 16x64x16 with per-block face culling. Building all on the main thread at startup could be slow but acceptable. Could be heavy (81 chunks × up to 16384 blocks each with 6 face checks). Actually 16×64×16 = 16384 blocks per chunk. That's 1.3M blocks total with face culling. Mesh generation might take a couple seconds. Acceptable for a first load, and the "ready" indicator shows.
Actually, this could be quite slow on startup since we synchronously build 81 chunks. Let me reduce the initial render distance or make the first column build async/spread out. But the buildChunkColumn is called in the constructor synchronously and builds ALL at once. To avoid a long freeze, let me change the constructor to build a smaller initial set and let the streaming loop (every 12 frames) build more.
Let me adjust: in the constructor, only build chunks within renderDistance=2 first, and set renderDistance=4 after a few frames. Actually simpler: change buildChunkColumn to only build a few chunks per call. But that complicates.
A cleaner approach: in the constructor, build a 3x3 core, then the streaming loop expands. Let me have buildChunkColumn accept and build all but with a spread-out generation using a queue.
Given the constraints, let me implement a chunk build queue that processes a few chunks per frame. This keeps startup responsive. Let me modify.
Actually, let me reconsider. Building 81 chunks synchronously might take 1-3 seconds which shows a black screen. The overlay shows while ready=false (set via setTimeout 80ms, which happens before world build completes potentially? No — constructor runs synchronously including buildChunkColumn, so setTimeout fires after constructor completes). So the freeze happens before the overlay even renders. That means a visible hang before the "Play" screen appears. Not ideal.
Let me implement a chunk queue to spread generation. I'll modify buildChunkColumn to only generate chunks that are "needed" gradually. Let me restructure:
Keep a chunkQueue: string[] of pending (cx,cz).
Constructor enqueues the full column set.
Each tick processes up to N queue items.
Chunks far from player not yet built are just air until generated.
Let me rewrite the relevant parts.
Let me refactor buildChunkColumn into an enqueue + dequeue approach.
Let me implement a chunk queue to spread out generation. I'll add a chunkQueue field and refactor buildChunkColumn into an enqueueColumn + processQueue approach.
First, add the queue field:
Now let me replace the buildChunkColumn method with buildCore, enqueueColumn, and processQueue methods.
Now let me update the tick loop to call enqueueColumn and processQueue instead of buildChunkColumn.
I need to add the readyNotified field and also remove the constructor's setTimeout that fired onReady. Let me add the field and remove the old setTimeout call.
Now let me build again to verify everything compiles.
The build succeeds. Let me review one important detail — the buildCore builds only a 3x3 core, but the chunkQueue is populated via enqueueColumn which is called only after 8 frames. Before that, the player would see mostly air. Since chunkQueue starts empty and processQueue runs each frame, let me make sure enqueueColumn is called during the core region properly. Actually, let me make the constructor also call enqueueColumn() once so the queue is populated right away.
Let me also double-check the interaction between the core build and queue. In the constructor, buildCore() builds 3x3. Then in tick, after 8 frames enqueueColumn fills the queue for radius 1..4. But radius 1 ring (distance exactly 1) chunks aren't built yet by core (core is -1..+1 which is radius 0 and 1). Wait, core builds dz=-1..1, dx=-1..1 which includes distance 0 and 1. The queue's radius 1 loop has Math.max(abs(dx),abs(dz))===1, and those are already in chunkMeshes so skipped. Good. Then it proceeds to radius 2,3,4. Good.
But between constructor and the first enqueueColumn (8 frames later), the player only has a 3x3 core with air beyond. That's a brief ~0.5s where edges are air. Acceptable but let me just call enqueueColumn() right after buildCore() in the constructor so queue is ready and streaming begins immediately.
Let me add that.
Now, let me reconsider the water/visibly-empty world during startup. Even with the queue, chunks build at 3/frame which for 81 chunks is ~27 frames (~0.45s). That's fine, and the "ready" state gates the Play button.
However, I want to ensure the onReady fires. It fires when chunkQueue.length === 0. With chunksPerFrame=3 it will complete. Good.
Let me also double check: there might be an issue where enqueueColumn recomputes seen from chunkMeshes keys plus existing queue. Since we enqueue once in constructor and again periodically, this is fine.
Now let me think about another issue: the player falls through freshly-generated terrain. When the player spawns at ground+1.01 at a coordinate in the core (chunk 0,0 since pcx/pcz based on pos 8.5/16 → 0). The core is built synchronously in constructor covering chunks -1..1, so spawn area has terrain. Good.
Let me also verify the physics collision uses isSolidAt which calls generateChunk/isSolid from world. For water it returns false (non-solid). So the player doesn't collide with water — they can swim? Actually there's no swimming, they just fall through water to the bottom. That's a standard simplified behavior. Fine.
Now, one concern about breaking water blocks: raycastSolid requires isSolid(id), so it won't target water for breaking (can't break water). And the highlight won't show on water. That's fine — user wants block breaking/placing primarily on terrain.
But handleBlockInteraction for placing via raycastPlace finds first solid block hit and places before it. If aiming at ground underwater through water, it places on the solid surface. Good.
Let me verify there's no issue with the overlapsPlayer for placement — it checks y..y+1 against player box. Good.
Now, let me reconsider the buildChunkMesh transparent water surface. When water has air above, surface renders. When water shares face with other water, skipped. When water is below terrain (covered), sides against dirt — emptyNeighbor || isTranslucent(nid) → dirt is not empty/translucent, so face skipped → water hidden under terrain. Good.
But wait — there's a subtle bug. For a solid block next to water: surface = emptyNeighbor || isTranslucent(nid). If a dirt block has a water neighbor above, the dirt's top face would render because water is translucent → surface=true. Good, we see dirt through... no wait, we render the dirt top face regardless; water is transparent so you see dirt's top through water. Actually both render: dirt face and water face. That gives correct look.
Now let me think about whether the fog/background looks ok with sky. Sky at 0x87ceeb, fog same color. Good.
Let me also verify the highlight LineSegments visible only when locked and a block is targeted. When unlocked, handleBlockInteraction isn't called so highlight stays hidden. But after re-locking, it'll re-appear. Fine. However when unlocked, if it was visible, it stays frozen visible. Let me hide highlight when not locked. Minor. Let me add that in tick: when not locked, hide highlight.
Let me make that small refinement.
Now let me reconsider the tree generation and whether trees look right. In world.ts, trees place trunk from h+1 to h+trunkHeight, and leaves blob. There's a bug in the leaves loop:
This keeps the top-of-trunk block (by === topY). But the topY is at h+trunkHeight, and the trunk occupies up to h+trunkHeight (inclusive). So the trunk's top block is at topY. The leaves at dy===0 (topY) with the corner-skip logic forms a 3x3 cross... Actually radius 1 at dy===0 means only the immediate neighbors (8 around). Combined with skipping the center, that forms a plus-shape + corners? radius 1 → dx,dz in {-1,0,1}, skipping corner when |dx|==|dz|==1 with 50% chance. So a 3x3 with corners sometimes skipped. Good enough canopy top.
But there's an issue: trunk height 4-6, leaves from topY-2 to topY. Since trunk occupies h+1..h+trunkHeight, and topY=h+trunkHeight. Leaves dy from -2..0 → y = topY-2 .. topY = h+trunkHeight-2 .. h+trunkHeight. The dy=-2 row is at h+trunkHeight-2, within the trunk's upper region (trunk goes to h+trunkHeight). So leaves wrap around the trunk top. That's fine, looks like a proper tree.
The Math.random() in tree generation makes terrain non-deterministic per-seed, but that's acceptable for "infinite-feeling" and doesn't break anything.
Now, one concern: the treeAt uses mulberry32 with seed — deterministic. Good.
Let me also check the world.ts uses Math.random() in leaves corners which is fine.
Let me also reconsider the chunk rebuild after tree building — there's no double-tree because each column checked once. Good.
Now let me think about the first-person click-to-lock. In onMouseDown, if !this.isLocked && e.button===0, it requests pointer lock. But the canvas is under the full-screen overlay (z-30) when not locked, so the user can't click the canvas. They click "Play" button instead, which calls requestPointerLock. After locking, overlay hides (locked=true) and canvas receives mouse events. Good. But there's a race: after requestPointerLock from the button click, the pointerlockchange fires async. Good.
However, when the user presses Esc to unlock, the overlay reappears. Good.
Let me verify the mix-blend-difference crosshair works — on a light sky it shows dark, on dark blocks shows light. Good.
Now let me run a final build to confirm everything still compiles.
The build is successful. Let me do a final review of a few key files to make sure the logic is solid and there are no remaining issues. Let me check the world.ts tree/terrain logic and the full Game.ts once more for correctness.
There's a bug in the tree check. In world.ts, the surface, below, above variables are checking the wrong y levels. The ground surface is at height h. The block at h is the surface (grass). But below = getBlockLocal(data, lx, h + 1, lz) checks ABOVE the surface (correct — that's empty air if no tree), and above = getBlockLocal(data, lx, h - 1, lz) checks below. The names are swapped but functionally: surface at h (grass ✓), below at h+1 should be air (✓ for empty surface), above at h-1... that's dirt/stone, not air.
So the check if (above !== BLOCK_AIR || below !== BLOCK_AIR) continue; where above(=h-1, dirt) will never be air, so trees will NEVER generate! That's a bug. Let me fix the variable semantics.
The correct check: the block at h+1 (above surface) should be air, and the block at h should be grass. Let me fix:
js
const surface = getBlockLocal(data, lx, h, lz); // must be grass
const above = getBlockLocal(data, lx, h + 1, lz); // must be air
if (above !== BLOCK_AIR) continue;
if (surface !== BlockId.Grass) continue;
if (!treeAt(...)) continue;
Let me fix this.
Now trees can generate. Let me also reconsider the terrain height numbers. SEA_LEVEL = 18. Heights range 4..56. isDesert = h < 9 (low land near/below sea → sand). isSnow = h > 32 (high land → snow). Water fills h+1..SEA_LEVEL. So with h<9 (desert/sand), water fills up to sea level 18, creating shallow water over sand. Good — beaches. And grass from h=9..32, snow above 32.
Now let me reconsider the tree height range if (h <= SEA_LEVEL + 1 || h > 30) continue; — trees between sea level+2 and 30, on grass. Good.
Now there's a concern about leaves checking by === topY && dx===0 && dz===0 — at top canopy row, skip center to preserve trunk top. But the trunk top block is at topY and it's a Log. If we didn't skip, we'd fill leaves over it in that column but the check getBlockLocal !== BLOCK_AIR prevents overwriting the Log anyway. So that skip is redundant but harmless.
Let me rebuild to confirm.
The build succeeds. Let me do a final review of the Game.ts to make sure everything is consistent, particularly the water rendering logic and mesh building, and check for any leftover issues. Let me read the buildChunkMesh section.
The mesh building logic looks correct. One issue I want to verify: the cross-chunk neighbor check getBlock(baseX + lx, y, baseZ + lz) for out-of-bounds calls the world's getBlock which generates the neighbor chunk if needed. Since chunks generate deterministically and edit propagation is handled by rebuildAround, this works. However, an edited block in an adjacent (already-visited) region uses the cached mutated data. Good.
There is a subtle edge: when the player edits a block and rebuildAround rebuilds the neighbor chunk, that neighbor's mesh correctly reflects the edit because it reads its own cached data (mutated by setBlockAt) plus the edited edge via getBlock. Good.
Now let me verify the whole App flow once more — checking that the HUD doesn't get hidden behind the singlefile build and that fonts/emoji render fine.
The implementation is complete. Let me verify there are no unused imports in blocks.ts (e.g., BLOCK_AIR is exported there). Let me check the top of blocks.ts which I recall exports const BLOCK_AIR = 0.
Yes, BLOCK_AIR = 0 is exported from blocks.ts and used in Game.lts and world.ts. Good.
Let me also double check player.ts imports — it imports isSolidAt from world and THREE. Both used. Good.
Everything builds cleanly. Let me do one last thing: verify the index.css doesn't interfere (it just imports tailwind). The app uses Tailwind classes which are present. Good.
Let me verify the complete app one final time by checking the App.tsx handles the ready state correctly — the Play button only shows when ready. And the loading bar shows until ready. Since onReady fires when the chunk queue empties (initial 81 chunks built at 3/frame = ~27 frames), the loading bar shows briefly. Good.
The game is complete and functional. Let me provide a summary.
Actually, let me reconsider one potential issue: the chunk queue could grow unbounded if the player moves faster than generation. enqueueColumn adds chunks up to radius 4 each time it's called (every 8 frames), and processQueue builds 3/frame. As the player moves, new columns get enqueued. Since radius 4 only and chunks process at 3/frame while enqueue adds the full ring periodically, it should keep up for normal walking speed. If a burst of queued chunks exists, onReady won't fire again (readyNotified once) — fine.
But there's a subtlety: after the initial game loads and readyNotified=true, moving the player enqueues new chunks but onReady won't re-fire (which is correct — for world edits we handle via rebuildAround, not queue). But the new chunks WILL still be built via processQueue each frame. Good — no missing terrain as you explore; it streams in.
However, there's a concern: when exploring, rebuildAround rebuilds chunks synchronously which is fine (single chunk). And new chunks stream via queue. The player might briefly see void at the edge of render distance, but that's normal Minecraft-style chunk streaming.
I'm confident the implementation is complete and correct. Let me finalize.
Let me also make sure the camera near/far planes are appropriate — near 0.05, far 1000. Fog at 230. Good.
The implementation is complete. Let me provide a summary of what was built.The game is complete and builds successfully. Let me verify the full file structure one final time to confirm everything is in place.
I've built a complete, browser-based Minecraft-style voxel game. Here's a summary of what was created:
🏗️ Architecture
src/game/noise.ts — Deterministic, seeded value-noise + fBm (4-octave fractal noise) with a mulberry32 PRNG for terrain generation.
src/game/blocks.ts — Block registry with 12 block types (grass, dirt, stone, sand, water, log, leaves, planks, cobble, glass, brick, snow), each with per-face colors, solidity, translucency, and subtle color jitter to break up flat areas. Includes the 9-slot hotbar definition.
src/game/world.ts — Chunk-based procedural world (16×64×16 chunks) with:
Infinite terrain via seeded noise heightmap (beaches, plains, snowy mountains)
Procedurally generated trees with trunks, layered leaf canopies, and stable hash-based placement
src/game/player.ts — First-person physics: gravity, jumping, sprinting, with axis-separated AABB collision resolution against voxels (horizontal and vertical movement resolved independently).
src/game/Game.ts — The Three.js engine:
Rendering: Chunked meshes with only visible faces emitted (face culling against neighbors), per-face directional shading for a classic flat voxel look, separate opaque/transparent geometry groups, fog + sky for day-lighting (ambient + directional sun + hemisphere light).
Interaction: DDA voxel raycasting — left-click breaks blocks, right-click places from the hotbar; a black box highlight outlines the targeted block.
World streaming: An async chunk queue builds chunks over multiple frames (3/frame) to avoid freezing on startup, plus smooth load/unload as you explore (infinite-feeling).
src/App.tsx — React HUD with a mix-blend crosshair, a styled hotbar with 3D isometric block previews, current-block label, a loading bar, and a controls/start menu overlay (HTML dialog + game click-to-play).
The project builds cleanly into a single inlined HTML file with Three.js bundled.