From 72ca89429213731b714c16265fee15c1382cbf30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Drago=C8=99-Andrei=20Bobu?= Date: Tue, 13 Oct 2026 23:31:34 +0300 Subject: [PATCH 1/7] feat(voxel): deterministic editable world with bounded persistence and chunk coordinates --- experiments/voxel-frontier/world-core.mjs | 95 +++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 experiments/voxel-frontier/world-core.mjs diff --git a/experiments/voxel-frontier/world-core.mjs b/experiments/voxel-frontier/world-core.mjs new file mode 100644 index 0000000..77727ea --- /dev/null +++ b/experiments/voxel-frontier/world-core.mjs @@ -0,0 +1,95 @@ +/** + * Deterministic, renderer-independent voxel world. + * Block centers occupy integer coordinates. A block occupies [c-.5, c+.5]. + * Keep this module free of Three.js/DOM dependencies so it can be unit tested. + */ +export const WORLD_RADIUS = 13; +export const MAX_HEIGHT = 32; +export const CHUNK_SIZE = 8; +export const BLOCK_TYPES = Object.freeze(['grass', 'stone', 'wood']); +export const blockKey = (x, y, z) => `${x},${y},${z}`; +export const chunkIndex = coordinate => Math.floor(coordinate / CHUNK_SIZE); +export const chunkKey = (x, z) => `${chunkIndex(x)},${chunkIndex(z)}`; + +export function groundHeight(x, z) { + return Math.max(0, Math.floor(2.1 + Math.sin(x / 3.5) * 1.2 + Math.cos(z / 4.1) * 1.3)); +} + +export class VoxelWorld { + constructor({ radius = WORLD_RADIUS, edits = {}, onChange = null } = {}) { + this.radius = radius; + this.blocks = new Map(); + this.edits = {}; + this.onChange = onChange; + for (let x = -radius; x <= radius; x++) { + for (let z = -radius; z <= radius; z++) { + const height = groundHeight(x, z); + for (let y = -1; y <= height; y++) { + this.blocks.set(blockKey(x, y, z), y === height ? 'grass' : 'stone'); + } + } + } + for (let x = -radius + 3; x < radius - 3; x += 6) { + for (let z = -radius + 3; z < radius - 3; z += 7) { + const h = groundHeight(x, z); + this.blocks.set(blockKey(x, h + 1, z), 'wood'); + this.blocks.set(blockKey(x, h + 2, z), 'wood'); + } + } + if (edits && typeof edits === 'object' && !Array.isArray(edits)) { + for (const [id, kind] of Object.entries(edits).slice(0, 10000)) { + const match = /^(-?\d+),(-?\d+),(-?\d+)$/.exec(id); + if (!match) continue; + const [x, y, z] = match.slice(1).map(Number); + if (!this.inBounds(x, y, z) || y === -1) continue; + if (kind !== null && !BLOCK_TYPES.includes(kind)) continue; + if (kind === null) this.blocks.delete(id); + else this.blocks.set(id, kind); + this.edits[id] = kind; + } + } + } + + inBounds(x, y, z) { + return Number.isInteger(x) && Number.isInteger(y) && Number.isInteger(z) + && Math.abs(x) <= this.radius && Math.abs(z) <= this.radius + && y >= -1 && y <= MAX_HEIGHT; + } + + get(x, y, z) { + return this.blocks.get(blockKey(x, y, z)) ?? null; + } + + solid(x, y, z) { + return this.blocks.has(blockKey(x, y, z)); + } + + set(x, y, z, kind) { + if (!this.inBounds(x, y, z) || y === -1) return false; + if (kind !== null && !BLOCK_TYPES.includes(kind)) return false; + const id = blockKey(x, y, z); + const previous = this.blocks.get(id) ?? null; + if (previous === kind) return false; + if (kind === null) this.blocks.delete(id); + else this.blocks.set(id, kind); + this.edits[id] = kind; + this.onChange?.({ x, y, z, previous, kind }); + return true; + } + + highestAt(x, z) { + for (let y = MAX_HEIGHT; y >= -1; y--) if (this.solid(x, y, z)) return y; + return -1; + } + + forEach(callback) { + for (const [id, kind] of this.blocks) { + const [x, y, z] = id.split(',').map(Number); + callback(kind, x, y, z); + } + } + + exportEdits() { + return { ...this.edits }; + } +} From 1e00d73b043d88f34b1395d931e1f39a2ea5db6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Drago=C8=99-Andrei=20Bobu?= Date: Tue, 13 Oct 2026 23:32:17 +0300 Subject: [PATCH 2/7] feat(voxel): physics module scaffold --- experiments/voxel-frontier/player-physics.mjs | 1 + 1 file changed, 1 insertion(+) create mode 100644 experiments/voxel-frontier/player-physics.mjs diff --git a/experiments/voxel-frontier/player-physics.mjs b/experiments/voxel-frontier/player-physics.mjs new file mode 100644 index 0000000..39f689c --- /dev/null +++ b/experiments/voxel-frontier/player-physics.mjs @@ -0,0 +1 @@ +export const EYE_HEIGHT = 1.6; From dc2ceaf05a66d3e9836cf56f3f44aba697810612 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Drago=C8=99-Andrei=20Bobu?= Date: Tue, 13 Oct 2026 23:34:28 +0300 Subject: [PATCH 3/7] feat(voxel): chunked exposed-face meshing and first-person physics with deterministic tests --- experiments/tests/voxel-world.test.mjs | 109 ++++++++ experiments/voxel-frontier/game.js | 233 +++++++++--------- experiments/voxel-frontier/player-physics.mjs | 43 +++- experiments/voxel-frontier/world-render.mjs | 115 +++++++++ 4 files changed, 381 insertions(+), 119 deletions(-) create mode 100644 experiments/tests/voxel-world.test.mjs create mode 100644 experiments/voxel-frontier/world-render.mjs diff --git a/experiments/tests/voxel-world.test.mjs b/experiments/tests/voxel-world.test.mjs new file mode 100644 index 0000000..6e54c95 --- /dev/null +++ b/experiments/tests/voxel-world.test.mjs @@ -0,0 +1,109 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { VoxelWorld, groundHeight, chunkIndex, blockKey } from '../voxel-frontier/world-core.mjs'; +import { canOccupy, spawnPlayer, stepPlayer, EYE_HEIGHT } from '../voxel-frontier/player-physics.mjs'; + +test('terrain is deterministic and has continuous bedrock', () => { + const a = new VoxelWorld({ radius: 4 }), b = new VoxelWorld({ radius: 4 }); + assert.deepEqual([...a.blocks], [...b.blocks]); + for (let x = -4; x <= 4; x++) for (let z = -4; z <= 4; z++) { + assert.equal(a.get(x, -1, z), 'stone'); + assert.equal(a.get(x, groundHeight(x, z), z), 'grass'); + } +}); + +test('block edits can be persisted, replayed, and deleted', () => { + const changes = []; + const world = new VoxelWorld({ radius: 4, onChange: c => changes.push(c) }); + assert.equal(world.set(0, 10, 0, 'wood'), true); + assert.equal(world.get(0, 10, 0), 'wood'); + assert.equal(world.set(0, 10, 0, 'wood'), false); + assert.equal(world.set(0, 10, 0, null), true); + assert.equal(world.get(0, 10, 0), null); + assert.equal(changes.length, 2); + const reloaded = new VoxelWorld({ radius: 4, edits: world.exportEdits() }); + assert.equal(reloaded.get(0, 10, 0), null); + assert.equal(reloaded.get(0, -1, 0), 'stone'); +}); + +test('invalid coordinates and bedrock edits are rejected', () => { + const world = new VoxelWorld({ radius: 4 }); + assert.equal(world.set(0, -1, 0, null), false); + assert.equal(world.set(10, 2, 0, 'wood'), false); + assert.equal(world.set(0, 100, 0, 'wood'), false); + assert.equal(world.set(0, 8, 0, 'unknown'), false); + assert.equal(world.get(0, -1, 0), 'stone'); +}); + +test('malformed saved edits cannot inject blocks outside the playable world', () => { + const world = new VoxelWorld({ radius: 4, edits: { + '999,2,2': 'stone', '0,-1,0': null, '0,10,0': 'wood', '0,11,0': 'lava', + '__proto__': 'stone' + } }); + assert.equal(world.get(0, 10, 0), 'wood'); + assert.equal(world.get(0, 11, 0), null); + assert.equal(world.get(0, -1, 0), 'stone'); + assert.equal(world.get(999, 2, 2), null); +}); + +test('negative chunk coordinates use mathematical floor', () => { + assert.equal(chunkIndex(-1), -1); + assert.equal(chunkIndex(-8), -1); + assert.equal(chunkIndex(-9), -2); + assert.equal(chunkIndex(8), 1); + assert.equal(blockKey(-1, 2, 3), '-1,2,3'); +}); + +const floorWorld = obstacle => ({ + radius: 20, + solid(x, y, z) { + return y <= 0 || (x === 1 && z === 0 && obstacle.includes(y)); + }, + highestAt() { return 0; } +}); + +test('player spawns above solid ground and has eye height', () => { + const world = floorWorld([]); + const p = spawnPlayer(world, 0, 0); + assert.equal(p.y, .5); + assert.equal(p.y + EYE_HEIGHT, 2.1); + assert.equal(canOccupy(world, p.x, p.y, p.z), true); + assert.equal(canOccupy(world, p.x, p.y - .1, p.z), false); +}); + +test('player cannot walk through a two-block wall', () => { + const world = floorWorld([1, 2]); + const p = spawnPlayer(world, 0, 0); + p.yaw = 0; + for (let i = 0; i < 12; i++) stepPlayer(world, p, { strafe: 1 }, .05); + assert.ok(p.x < .23, 'player should stop before wall'); + assert.ok(p.y < .6, 'player should not step up a two-block wall'); +}); + +test('player can climb a one-block step', () => { + const world = floorWorld([1]); + const p = spawnPlayer(world, 0, 0); + p.yaw = 0; + for (let i = 0; i < 12; i++) stepPlayer(world, p, { strafe: 1 }, .05); + assert.ok(p.x > .3, 'player should move across the step'); + assert.ok(p.y >= 1.49, 'player should stand on top of step'); +}); + +test('jump arcs and lands on the ground', () => { + const world = floorWorld([]); + const p = spawnPlayer(world, 0, 0); + stepPlayer(world, p, { jump: true }, .016); + assert.ok(p.y > .5); + assert.ok(p.vy > 0); + for (let i = 0; i < 160; i++) stepPlayer(world, p, {}, .016); + assert.ok(Math.abs(p.y - .5) < .001, 'jump should land exactly on ground'); + assert.equal(p.grounded, true); +}); + +test('long falls do not tunnel through solid terrain', () => { + const world = floorWorld([]); + const p = spawnPlayer(world, 0, 0); + p.y = 30; p.vy = 0; p.grounded = false; + for (let i = 0; i < 200; i++) stepPlayer(world, p, {}, .05); + assert.ok(Math.abs(p.y - .5) < .001); +}); diff --git a/experiments/voxel-frontier/game.js b/experiments/voxel-frontier/game.js index 483e90b..7f4c5f0 100644 --- a/experiments/voxel-frontier/game.js +++ b/experiments/voxel-frontier/game.js @@ -1,4 +1,7 @@ import * as THREE from 'three'; +import { VoxelWorld, BLOCK_TYPES } from './world-core.mjs'; +import { spawnPlayer, stepPlayer, canOccupy, PLAYER_RADIUS, PLAYER_HEIGHT, EYE_HEIGHT } from './player-physics.mjs'; +import { ChunkRenderer } from './world-render.mjs'; const game = document.querySelector('#game'); const hud = document.querySelector('#stats'); @@ -7,163 +10,157 @@ const start = document.querySelector('#start'); const error = document.querySelector('#error'); const scene = new THREE.Scene(); scene.background = new THREE.Color(0x9bc6cf); -scene.fog = new THREE.Fog(0x9bc6cf, 18, 54); -const camera = new THREE.PerspectiveCamera(77, innerWidth / innerHeight, 0.05, 90); +scene.fog = new THREE.Fog(0x9bc6cf, 18, 57); +const camera = new THREE.PerspectiveCamera(76, innerWidth / innerHeight, .05, 90); +camera.rotation.order = 'YXZ'; const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: 'high-performance' }); renderer.setPixelRatio(Math.min(devicePixelRatio, 2)); renderer.setSize(innerWidth, innerHeight); -renderer.shadowMap.enabled = false; game.prepend(renderer.domElement); -scene.add(new THREE.HemisphereLight(0xe5f4ff, 0x4d5b3e, 2.0)); -const sun = new THREE.DirectionalLight(0xfff1c6, 2.2); +scene.add(new THREE.HemisphereLight(0xe6f3ff, 0x56633d, 2)); +const sun = new THREE.DirectionalLight(0xffefc4, 2.3); sun.position.set(-12, 26, 18); scene.add(sun); -const size = 13; const materials = { grass: new THREE.MeshLambertMaterial({ color: 0x729b5d }), stone: new THREE.MeshLambertMaterial({ color: 0x8d9da0 }), wood: new THREE.MeshLambertMaterial({ color: 0x9e704b }) }; -const box = new THREE.BoxGeometry(1, 1, 1); -const map = new Map(); -const meshes = []; -const key = (x, y, z) => x + ',' + y + ',' + z; -const groundHeight = (x, z) => Math.max(0, Math.floor(2.1 + Math.sin(x / 3.5) * 1.2 + Math.cos(z / 4.1) * 1.3)); const editsKey = 'voxel-frontier-world-v1'; -let edits = {}; -try { edits = JSON.parse(localStorage.getItem(editsKey) || '{}') || {}; } catch { edits = {}; } -function notify(message) { - toast.textContent = message; -} -function addBlock(x, y, z, kind, record = false) { - const id = key(x, y, z); - if (map.has(id)) return false; - const m = new THREE.Mesh(box, materials[kind] || materials.stone); - m.position.set(x, y, z); - m.userData = { x, y, z, kind }; - scene.add(m); - map.set(id, m); - meshes.push(m); - if (record) { edits[id] = kind; save(); } - return true; -} -function removeBlock(m, record = false) { - const { x, y, z } = m.userData; - const id = key(x, y, z); - if (!map.delete(id)) return; - scene.remove(m); - const index = meshes.indexOf(m); - if (index !== -1) meshes.splice(index, 1); - if (record) { edits[id] = null; save(); } -} -function save() { - try { localStorage.setItem(editsKey, JSON.stringify(edits)); } catch {} -} -for (let x = -size; x <= size; x++) for (let z = -size; z <= size; z++) { - const h = groundHeight(x, z); - for (let y = -1; y <= h; y++) addBlock(x, y, z, y === h ? 'grass' : 'stone'); -} -for (let x = -size + 3; x < size - 3; x += 6) { - for (let z = -size + 3; z < size - 3; z += 7) { - const h = groundHeight(x, z); - addBlock(x, h + 1, z, 'wood'); - addBlock(x, h + 2, z, 'wood'); +let savedEdits = {}; +try { savedEdits = JSON.parse(localStorage.getItem(editsKey) || '{}'); } catch {} +let chunks; +const world = new VoxelWorld({ + edits: savedEdits, + onChange(change) { + try { localStorage.setItem(editsKey, JSON.stringify(world.exportEdits())); } catch {} + chunks?.updateAt(change.x, change.z); + window.dispatchEvent(new CustomEvent('voxel:block-change', { detail: change })); } -} -for (const [id, kind] of Object.entries(edits)) { - const [x, y, z] = id.split(',').map(Number); - const old = map.get(id); - if (old) removeBlock(old); - if (kind) addBlock(x, y, z, kind); -} -const player = { x: 0, z: 5, yaw: 0, pitch: -0.12, blocks: 0 }; +}); +chunks = new ChunkRenderer(THREE, scene, world, materials); +const player = spawnPlayer(world); const pressed = new Set(); -let selected = 'grass'; -let playing = false; +let selected = 'grass', playing = false, mined = 0; let lastFrame = performance.now(); -player.yaw = -0.2; -function playerHeight() { - const x = Math.max(-size, Math.min(size, Math.round(player.x))); - const z = Math.max(-size, Math.min(size, Math.round(player.z))); - for (let y = 12; y >= -1; y--) if (map.has(key(x, y, z))) return y + 2.18; - return 3; -} -camera.position.set(player.x, playerHeight(), player.z); const raycaster = new THREE.Raycaster(); -raycaster.far = 7; -function blockAction(place) { +raycaster.far = 6.5; +const highlight = new THREE.LineSegments( + new THREE.EdgesGeometry(new THREE.BoxGeometry(1.012, 1.012, 1.012)), + new THREE.LineBasicMaterial({ color: 0xfff4d4, transparent: true, opacity: .72 }) +); +highlight.visible = false; +scene.add(highlight); +function notify(message) { toast.textContent = message; } +function selectBlock(kind) { + if (!BLOCK_TYPES.includes(kind)) return false; + selected = kind; + document.querySelectorAll('#hotbar button').forEach(button => + button.classList.toggle('active', button.dataset.block === kind)); + notify('Selected ' + kind); + return true; +} +function target() { raycaster.setFromCamera({ x: 0, y: 0 }, camera); - const hit = raycaster.intersectObjects(meshes, false)[0]; - if (!hit) return notify('Find a block within reach'); - const m = hit.object; + return chunks.pick(raycaster); +} +function intersectsPlayer(x, y, z) { + return Math.abs(player.x - x) < PLAYER_RADIUS + .5 + && Math.abs(player.z - z) < PLAYER_RADIUS + .5 + && player.y < y + .5 && player.y + PLAYER_HEIGHT > y - .5; +} +function blockAction(place) { + const hit = target(); + if (!hit) { notify('Move closer to a block'); return false; } if (place) { - const pos = m.position.clone().add(hit.face.normal); - if (Math.abs(pos.x - player.x) < .7 && Math.abs(pos.z - player.z) < .7 && Math.abs(pos.y - camera.position.y + 1) < 1.5) return; - if (addBlock(Math.round(pos.x), Math.round(pos.y), Math.round(pos.z), selected, true)) notify('Placed ' + selected); - } else { - const { y } = m.userData; - if (y <= -1) return notify('Bedrock stays intact'); - removeBlock(m, true); - player.blocks++; - hud.textContent = 'Blocks mined: ' + player.blocks; - notify('Mined ' + m.userData.kind + ' · ' + player.blocks + ' blocks'); + const { x, y, z } = hit.adjacent; + if (intersectsPlayer(x, y, z)) { notify('Cannot build inside yourself'); return false; } + if (!world.set(x, y, z, selected)) { notify('Cannot place a block there'); return false; } + notify('Placed ' + selected); + return true; } + if (hit.y <= -1) { notify('Bedrock stays intact'); return false; } + const kind = world.get(hit.x, hit.y, hit.z); + if (!kind || !world.set(hit.x, hit.y, hit.z, null)) return false; + mined++; + hud.textContent = 'Blocks mined: ' + mined; + notify('Mined ' + kind + ' · ' + mined + ' blocks'); + return true; } -renderer.domElement.addEventListener('click', () => { +renderer.domElement.addEventListener('mousedown', event => { if (!playing) return; - if (document.pointerLockElement !== renderer.domElement) renderer.domElement.requestPointerLock?.(); - else blockAction(false); + if (event.button === 2) { event.preventDefault(); blockAction(true); return; } + if (event.button !== 0) return; + if (document.pointerLockElement !== renderer.domElement) { + renderer.domElement.requestPointerLock?.().catch(() => notify('Mouse lock unavailable. Use keyboard controls.')); + return; + } + blockAction(false); }); -renderer.domElement.addEventListener('contextmenu', e => { e.preventDefault(); if (playing) blockAction(true); }); -document.addEventListener('mousemove', e => { +renderer.domElement.addEventListener('contextmenu', event => event.preventDefault()); +document.addEventListener('mousemove', event => { if (document.pointerLockElement !== renderer.domElement) return; - player.yaw -= e.movementX * 0.002; - player.pitch = THREE.MathUtils.clamp(player.pitch - e.movementY * 0.002, -1.48, 1.48); + player.yaw -= event.movementX * .002; + player.pitch = THREE.MathUtils.clamp(player.pitch - event.movementY * .002, -1.48, 1.48); }); -document.addEventListener('keydown', e => { - if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Space'].includes(e.code)) e.preventDefault(); - pressed.add(e.code); - if (e.code === 'Digit1' || e.code === 'Digit2' || e.code === 'Digit3') { - selected = ['grass', 'stone', 'wood'][Number(e.code.slice(-1)) - 1]; - document.querySelectorAll('#hotbar button').forEach(button => button.classList.toggle('active', button.dataset.block === selected)); - notify('Selected ' + selected); - } +document.addEventListener('pointerlockchange', () => { + if (playing && document.pointerLockElement !== renderer.domElement) notify('Click the world to capture your mouse'); +}); +document.addEventListener('keydown', event => { + if (['ArrowUp','ArrowDown','ArrowLeft','ArrowRight','Space'].includes(event.code)) event.preventDefault(); + pressed.add(event.code); + if (/^Digit[123]$/.test(event.code)) selectBlock(BLOCK_TYPES[Number(event.code.slice(-1)) - 1]); }); -document.addEventListener('keyup', e => pressed.delete(e.code)); -document.querySelectorAll('#hotbar button').forEach(button => button.addEventListener('click', () => { - selected = button.dataset.block; - document.querySelectorAll('#hotbar button').forEach(b => b.classList.toggle('active', b === button)); -})); +document.addEventListener('keyup', event => pressed.delete(event.code)); +window.addEventListener('blur', () => pressed.clear()); +document.querySelectorAll('#hotbar button').forEach(button => + button.addEventListener('click', () => selectBlock(button.dataset.block))); document.querySelector('#play').addEventListener('click', () => { playing = true; start.classList.add('hidden'); - renderer.domElement.requestPointerLock?.().catch(() => {}); - notify('Explore. Mine. Build.'); + renderer.domElement.requestPointerLock?.().catch(() => notify('Click the world to capture your mouse')); + notify('WASD move · Space jump · Shift sprint · Mine and build'); }); window.addEventListener('resize', () => { camera.aspect = innerWidth / innerHeight; camera.updateProjectionMatrix(); renderer.setSize(innerWidth, innerHeight); }); +window.addEventListener('error', event => { error.textContent = 'Game error: ' + event.message; }); + +window.voxelFrontier = Object.freeze({ + world, player, camera, scene, + selectBlock, + get selectedBlock() { return selected; }, + get playing() { return playing; }, + get minedBlocks() { return mined; }, + mine: () => blockAction(false), + place: () => blockAction(true), + resetWorld() { try { localStorage.removeItem(editsKey); } catch {} location.reload(); } +}); + function tick(now) { requestAnimationFrame(tick); - const dt = Math.min(.05, (now - lastFrame) / 1000); + const dt = Math.min(.05, Math.max(0, (now - lastFrame) / 1000)); lastFrame = now; if (playing) { - const fwd = Number(pressed.has('KeyW') || pressed.has('ArrowUp')) - Number(pressed.has('KeyS') || pressed.has('ArrowDown')); - const side = Number(pressed.has('KeyD') || pressed.has('ArrowRight')) - Number(pressed.has('KeyA') || pressed.has('ArrowLeft')); - const len = Math.hypot(fwd, side) || 1; - const speed = pressed.has('ShiftLeft') ? 8 : 5; - const dx = (-Math.sin(player.yaw) * fwd + Math.cos(player.yaw) * side) / len * speed * dt; - const dz = (-Math.cos(player.yaw) * fwd - Math.sin(player.yaw) * side) / len * speed * dt; - player.x = THREE.MathUtils.clamp(player.x + dx, -size + .7, size - .7); - player.z = THREE.MathUtils.clamp(player.z + dz, -size + .7, size - .7); - camera.position.set(player.x, THREE.MathUtils.lerp(camera.position.y, playerHeight(), Math.min(1, dt * 9)), player.z); - camera.rotation.order = 'YXZ'; - camera.rotation.y = player.yaw; - camera.rotation.x = player.pitch; + const forward = Number(pressed.has('KeyW') || pressed.has('ArrowUp')) - + Number(pressed.has('KeyS') || pressed.has('ArrowDown')); + const strafe = Number(pressed.has('KeyD') || pressed.has('ArrowRight')) - + Number(pressed.has('KeyA') || pressed.has('ArrowLeft')); + stepPlayer(world, player, { + forward, strafe, sprint: pressed.has('ShiftLeft') || pressed.has('ShiftRight'), + jump: pressed.has('Space') + }, dt); } + camera.position.set(player.x, player.y + EYE_HEIGHT, player.z); + camera.rotation.y = player.yaw; + camera.rotation.x = player.pitch; + if (playing && document.pointerLockElement === renderer.domElement) { + const hit = target(); + highlight.visible = !!hit; + if (hit) highlight.position.set(hit.x, hit.y, hit.z); + } else highlight.visible = false; renderer.render(scene, camera); } -window.addEventListener('error', e => { error.textContent = 'Rendering error: ' + e.message; }); requestAnimationFrame(tick); diff --git a/experiments/voxel-frontier/player-physics.mjs b/experiments/voxel-frontier/player-physics.mjs index 39f689c..9aeaaaf 100644 --- a/experiments/voxel-frontier/player-physics.mjs +++ b/experiments/voxel-frontier/player-physics.mjs @@ -1 +1,42 @@ -export const EYE_HEIGHT = 1.6; +export const EYE_HEIGHT=1.60,PLAYER_RADIUS=.28,PLAYER_HEIGHT=1.78; +const EPS=.000001; +export function canOccupy(world,x,y,z){ +for(let bx=Math.ceil(x-PLAYER_RADIUS-.5+EPS);bx<=Math.floor(x+PLAYER_RADIUS+.5-EPS);bx++) +for(let bz=Math.ceil(z-PLAYER_RADIUS-.5+EPS);bz<=Math.floor(z+PLAYER_RADIUS+.5-EPS);bz++) +for(let by=Math.ceil(y-.5+EPS);by<=Math.floor(y+PLAYER_HEIGHT+.5-EPS);by++) +if(world.solid(bx,by,bz))return false; +return true; +} +export function spawnPlayer(world,x=0,z=5){return {x,y:world.highestAt(Math.round(x),Math.round(z))+.5,z,vy:0,yaw:-.2,pitch:-.12,grounded:true};} +function moveHorizontal(world,p,axis,delta){ +if(!delta)return; +const x=axis==='x'?p.x+delta:p.x,z=axis==='z'?p.z+delta:p.z; +if(canOccupy(world,x,p.y,z)){p[axis]+=delta;return;} +if(p.grounded&&canOccupy(world,p.x,p.y+1.001,p.z)&&canOccupy(world,x,p.y+1.001,z)){p.y+=1.001;p.vy=0;p[axis]+=delta;} +} +function moveVertical(world,p,delta){ +if(!delta)return; +const target=p.y+delta; +if(canOccupy(world,p.x,target,p.z)){p.y=target;return;} +let safe=p.y,blocked=target; +for(let i=0;i<17;i++){const middle=(safe+blocked)/2;if(canOccupy(world,p.x,middle,p.z))safe=middle;else blocked=middle;} +p.y=safe;p.vy=0;if(delta<0)p.grounded=true; +} +export function stepPlayer(world,p,input,elapsed){ +const dt=Math.max(0,Math.min(.05,elapsed));if(!dt)return p; +const f=Math.max(-1,Math.min(1,input.forward||0)),s=Math.max(-1,Math.min(1,input.strafe||0)); +const length=Math.hypot(f,s)||1,speed=input.sprint?7.4:4.9; +const dx=(-Math.sin(p.yaw)*f+Math.cos(p.yaw)*s)/length*speed*dt; +const dz=(-Math.cos(p.yaw)*f-Math.sin(p.yaw)*s)/length*speed*dt; +const max=world.radius-PLAYER_RADIUS-.22; +moveHorizontal(world,p,'x',Math.max(-max,Math.min(max,p.x+dx))-p.x); +moveHorizontal(world,p,'z',Math.max(-max,Math.min(max,p.z+dz))-p.z); +p.grounded=!canOccupy(world,p.x,p.y-.035,p.z); +if(input.jump&&p.grounded){p.vy=8;p.grounded=false;} +if(!p.grounded)p.vy=Math.max(-24,p.vy-21*dt); +else if(p.vy<0)p.vy=0; +const vertical=p.vy*dt,steps=Math.max(1,Math.ceil(Math.abs(vertical)/.24)); +for(let i=0;i