| <!DOCTYPE html> |
| <html lang="en"> |
| <head> |
| <meta charset="UTF-8" /> |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"/> |
| <title>Three.js Forest with Orbit + Arrow Move + Lighting + Stars</title> |
| <style> |
| :root { color-scheme: dark; } |
| html, body { height: 100%; } |
| body { |
| margin: 0; |
| overflow: hidden; |
| background: #0a0f12; |
| font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, "Apple Color Emoji", "Segoe UI Emoji"; |
| } |
| .ui { |
| position: absolute; |
| top: 12px; |
| left: 12px; |
| padding: 10px 12px; |
| background: rgba(0,0,0,0.35); |
| border: 1px solid rgba(255,255,255,0.1); |
| border-radius: 8px; |
| backdrop-filter: blur(6px); |
| -webkit-backdrop-filter: blur(6px); |
| color: #cfe3d4; |
| font-size: 12px; |
| line-height: 1.4; |
| user-select: none; |
| max-width: 360px; |
| } |
| .ui h1 { |
| margin: 0 0 6px 0; |
| font-size: 14px; |
| font-weight: 600; |
| color: #e8f5ea; |
| letter-spacing: 0.3px; |
| } |
| .ui .row { |
| display: flex; |
| align-items: center; |
| gap: 8px; |
| margin: 6px 0; |
| } |
| .ui label { |
| min-width: 90px; |
| color: #cde2cf; |
| } |
| .ui input[type=range] { width: 180px; } |
| .ui .hint { opacity: 0.85; font-size: 11px; margin-top: 6px; } |
| .kbd { |
| display: inline-block; |
| padding: 1px 6px; |
| border: 1px solid rgba(255,255,255,0.2); |
| border-radius: 4px; |
| background: rgba(255,255,255,0.06); |
| font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; |
| font-size: 11px; |
| line-height: 16px; |
| } |
| </style> |
| </head> |
| <body> |
| <div class="ui"> |
| <h1>Procedural Forest</h1> |
| <div class="row"> |
| <label for="density">Density</label> |
| <input id="density" type="range" min="50" max="1200" value="550" /> |
| <span id="densityVal">550</span> |
| </div> |
| <div class="row"> |
| <label for="wind">Wind</label> |
| <input id="wind" type="range" min="0" max="100" value="35" /> |
| <span id="windVal">0.35</span> |
| </div> |
| <div class="row"> |
| <label for="size">Area</label> |
| <input id="size" type="range" min="150" max="600" value="350" /> |
| <span id="sizeVal">350</span> |
| </div> |
|
|
| <h1 style="margin-top:10px;">Lighting</h1> |
| <div class="row"> |
| <label for="sunInt">Sun Intensity</label> |
| <input id="sunInt" type="range" min="0" max="2000" value="1000" /> |
| <span id="sunIntVal">10.00</span> |
| </div> |
| <div class="row"> |
| <label for="sunElev">Sun Elev</label> |
| <input id="sunElev" type="range" min="5" max="85" value="60" /> |
| <span id="sunElevVal">60°</span> |
| </div> |
| <div class="row"> |
| <label for="sunAzim">Sun Azim</label> |
| <input id="sunAzim" type="range" min="0" max="360" value="145" /> |
| <span id="sunAzimVal">145°</span> |
| </div> |
| <div class="row"> |
| <label for="hemi">Sky/Amb</label> |
| <input id="hemi" type="range" min="0" max="150" value="60" /> |
| <span id="hemiVal">0.60</span> |
| </div> |
|
|
| <div class="hint"> |
| Orbit: Left drag • Pan: Right drag • Zoom: Wheel<br/> |
| Move camera with <span class="kbd">↑</span><span class="kbd">↓</span><span class="kbd">←</span><span class="kbd">→</span> • Boost: <span class="kbd">Shift</span><br/> |
| Tip: Click the canvas once to ensure it has focus for arrow keys. |
| </div> |
| </div> |
|
|
| <script type="importmap"> |
| { |
| "imports": { |
| "three": "https://unpkg.com/three@0.160.0/build/three.module.js", |
| "three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/" |
| } |
| } |
| </script> |
| <script type="module"> |
| import * as THREE from 'three'; |
| import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; |
| |
| const renderer = new THREE.WebGLRenderer({ antialias: true }); |
| renderer.setSize(window.innerWidth, window.innerHeight); |
| renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); |
| renderer.shadowMap.enabled = true; |
| renderer.shadowMap.type = THREE.PCFSoftShadowMap; |
| renderer.domElement.tabIndex = 0; |
| document.body.appendChild(renderer.domElement); |
| |
| const scene = new THREE.Scene(); |
| scene.fog = new THREE.FogExp2(0x0d1713, 0.0022); |
| |
| |
| const hemiLight = new THREE.HemisphereLight(0xbfdde3, 0x1e3222, 0.6); |
| scene.add(hemiLight); |
| |
| const dirLight = new THREE.DirectionalLight(0xfff4d6, 3.0); |
| dirLight.position.set(-60, 120, 40); |
| dirLight.castShadow = true; |
| dirLight.shadow.mapSize.set(2048, 2048); |
| const cam = dirLight.shadow.camera; |
| const shadowExtent = 300; |
| cam.left = -shadowExtent; |
| cam.right = shadowExtent; |
| cam.top = shadowExtent; |
| cam.bottom = -shadowExtent; |
| cam.near = 10; |
| cam.far = 400; |
| scene.add(dirLight); |
| |
| |
| const densityEl = document.getElementById('density'); |
| const densityValEl = document.getElementById('densityVal'); |
| const windEl = document.getElementById('wind'); |
| const windValEl = document.getElementById('windVal'); |
| const sizeEl = document.getElementById('size'); |
| const sizeValEl = document.getElementById('sizeVal'); |
| |
| const sunIntEl = document.getElementById('sunInt'); |
| const sunIntValEl = document.getElementById('sunIntVal'); |
| const sunElevEl = document.getElementById('sunElev'); |
| const sunElevValEl = document.getElementById('sunElevVal'); |
| const sunAzimEl = document.getElementById('sunAzim'); |
| const sunAzimValEl = document.getElementById('sunAzimVal'); |
| const hemiEl = document.getElementById('hemi'); |
| const hemiValEl = document.getElementById('hemiVal'); |
| |
| |
| function setSunFromUI() { |
| const intensity = Number(sunIntEl.value) / 100; |
| dirLight.intensity = intensity; |
| sunIntValEl.textContent = intensity.toFixed(2); |
| |
| const elevDeg = Number(sunElevEl.value); |
| const azimDeg = Number(sunAzimEl.value); |
| sunElevValEl.textContent = elevDeg + '°'; |
| sunAzimValEl.textContent = azimDeg + '°'; |
| |
| |
| const elev = THREE.MathUtils.degToRad(elevDeg); |
| const azim = THREE.MathUtils.degToRad(azimDeg); |
| const r = 200; |
| const y = Math.sin(elev) * r; |
| const x = Math.cos(elev) * Math.cos(azim) * r; |
| const z = Math.cos(elev) * Math.sin(azim) * r; |
| dirLight.position.set(x, y, z); |
| dirLight.target.position.set(0, 0, 0); |
| dirLight.target.updateMatrixWorld(); |
| } |
| |
| function setHemiFromUI() { |
| const hemiIntensity = Number(hemiEl.value) / 100; |
| hemiLight.intensity = hemiIntensity; |
| hemiValEl.textContent = hemiIntensity.toFixed(2); |
| } |
| |
| function setWindFromUI() { |
| const w = Number(windEl.value) / 100; |
| wind.strength = w; |
| windValEl.textContent = w.toFixed(2); |
| windUniforms.uStrength.value = w; |
| } |
| |
| function setDensityFromUI() { |
| const d = Number(densityEl.value); |
| densityValEl.textContent = String(d); |
| regenerateForest(d, areaSize.value); |
| regenerateDecor(areaSize.value); |
| } |
| |
| function setAreaFromUI() { |
| const s = Number(sizeEl.value); |
| areaSize.value = s; |
| sizeValEl.textContent = String(s); |
| regenerateForest(Number(densityEl.value), s); |
| regenerateDecor(s); |
| } |
| |
| sunIntEl.addEventListener('input', setSunFromUI); |
| sunElevEl.addEventListener('input', setSunFromUI); |
| sunAzimEl.addEventListener('input', setSunFromUI); |
| hemiEl.addEventListener('input', setHemiFromUI); |
| windEl.addEventListener('input', setWindFromUI); |
| densityEl.addEventListener('change', setDensityFromUI); |
| sizeEl.addEventListener('change', setAreaFromUI); |
| |
| |
| const areaSize = { value: 350 }; |
| const groundSegments = 256; |
| const groundGeo = new THREE.PlaneGeometry(1000, 1000, groundSegments, groundSegments); |
| groundGeo.rotateX(-Math.PI / 2); |
| const pos = groundGeo.attributes.position; |
| const tmp = new THREE.Vector3(); |
| for (let i = 0; i < pos.count; i++) { |
| tmp.fromBufferAttribute(pos, i); |
| const nx = tmp.x * 0.01; |
| const nz = tmp.z * 0.01; |
| const h = |
| Math.sin(nx) * Math.cos(nz) * 1.2 + |
| Math.sin(nx * 0.21 + 2.7) * Math.sin(nz * 0.19 + 1.5) * 0.7 + |
| Math.cos(nx * 0.07 - 1.1) * Math.sin(nz * 0.09 + 0.4) * 2.0; |
| pos.setY(i, h); |
| } |
| groundGeo.computeVertexNormals(); |
| |
| function makeGrassTexture(w = 256, h = 256) { |
| const size = w * h * 3; |
| const data = new Uint8Array(size); |
| for (let y = 0; y < h; y++) { |
| for (let x = 0; x < w; x++) { |
| const i = (y * w + x) * 3; |
| const u = x / w, v = y / h; |
| const noise = |
| Math.sin(u * 20.0) * 0.5 + Math.cos(v * 18.0) * 0.5 + |
| Math.sin((u + v) * 8.0) * 0.4; |
| const base = 80 + noise * 40; |
| const g = THREE.MathUtils.clamp(base + (v - 0.5) * 30, 50, 190); |
| const r = g * 0.6; |
| const b = g * 0.5; |
| data[i] = r; data[i + 1] = g; data[i + 2] = b; |
| } |
| } |
| const tex = new THREE.DataTexture(data, w, h, THREE.RGBFormat); |
| tex.wrapS = tex.wrapT = THREE.RepeatWrapping; |
| tex.needsUpdate = true; |
| return tex; |
| } |
| const grassTex = makeGrassTexture(256, 256); |
| grassTex.repeat.set(20, 20); |
| const groundMat = new THREE.MeshStandardMaterial({ |
| map: grassTex, |
| roughness: 1.0, |
| metalness: 0.0, |
| color: new THREE.Color(0x5c8b63).multiplyScalar(0.9) |
| }); |
| const ground = new THREE.Mesh(groundGeo, groundMat); |
| ground.receiveShadow = true; |
| scene.add(ground); |
| |
| |
| const treeGroup = new THREE.Group(); |
| scene.add(treeGroup); |
| |
| const trunkGeo = new THREE.CylinderGeometry(1, 1.8, 10, 8, 1, false); |
| trunkGeo.translate(0, 5, 0); |
| |
| function makeFoliageGeometry() { |
| const g = new THREE.BufferGeometry(); |
| const geometries = []; |
| |
| const cone1 = new THREE.ConeGeometry(6, 10, 8); |
| cone1.translate(0, 14, 0); geometries.push(cone1); |
| const cone2 = new THREE.ConeGeometry(5, 9, 8); |
| cone2.translate(0, 20, 0); geometries.push(cone2); |
| const cone3 = new THREE.ConeGeometry(4, 8, 8); |
| cone3.translate(0, 25, 0); geometries.push(cone3); |
| const sph = new THREE.SphereGeometry(3.5, 8, 6); |
| sph.translate(0, 28.5, 0); geometries.push(sph); |
| |
| let totalVertices = 0, totalIndices = 0; |
| for (const geo of geometries) { |
| geo.computeVertexNormals(); |
| totalVertices += geo.attributes.position.count; |
| totalIndices += geo.index ? geo.index.count : geo.attributes.position.count; |
| } |
| const posArr = new Float32Array(totalVertices * 3); |
| const normArr = new Float32Array(totalVertices * 3); |
| const uvArr = new Float32Array(totalVertices * 2); |
| const indexArr = new Uint32Array(totalIndices); |
| |
| let vOffset = 0, iOffset = 0, baseVertex = 0; |
| for (const geo of geometries) { |
| const p = geo.attributes.position.array; |
| const n = geo.attributes.normal.array; |
| const u = geo.attributes.uv ? geo.attributes.uv.array : new Float32Array(geo.attributes.position.count * 2); |
| posArr.set(p, vOffset * 3); |
| normArr.set(n, vOffset * 3); |
| uvArr.set(u, vOffset * 2); |
| |
| if (geo.index) { |
| const idx = geo.index.array; |
| for (let i = 0; i < idx.length; i++) indexArr[iOffset + i] = idx[i] + baseVertex; |
| iOffset += idx.length; |
| } else { |
| for (let i = 0; i < geo.attributes.position.count; i++) indexArr[iOffset++] = baseVertex + i; |
| } |
| baseVertex += geo.attributes.position.count; |
| vOffset += geo.attributes.position.count; |
| } |
| g.setAttribute('position', new THREE.BufferAttribute(posArr, 3)); |
| g.setAttribute('normal', new THREE.BufferAttribute(normArr, 3)); |
| g.setAttribute('uv', new THREE.BufferAttribute(uvArr, 2)); |
| g.setIndex(new THREE.BufferAttribute(indexArr, 1)); |
| g.computeBoundingSphere(); g.computeBoundingBox(); |
| return g; |
| } |
| |
| const foliageGeo = makeFoliageGeometry(); |
| |
| const trunkMat = new THREE.MeshStandardMaterial({ |
| color: 0x6b4f32, roughness: 0.9, metalness: 0.0 |
| }); |
| const foliageMat = new THREE.MeshStandardMaterial({ |
| color: 0x2f6b3d, roughness: 0.8, metalness: 0.0 |
| }); |
| |
| let trunkInstanced, foliageInstanced; |
| function makeInstancedMeshes(count) { |
| if (trunkInstanced) treeGroup.remove(trunkInstanced); |
| if (foliageInstanced) treeGroup.remove(foliageInstanced); |
| trunkInstanced = new THREE.InstancedMesh(trunkGeo, trunkMat, count); |
| trunkInstanced.castShadow = true; trunkInstanced.receiveShadow = true; |
| foliageInstanced = new THREE.InstancedMesh(foliageGeo, foliageMat, count); |
| foliageInstanced.castShadow = true; foliageInstanced.receiveShadow = true; |
| treeGroup.add(trunkInstanced, foliageInstanced); |
| } |
| |
| const wind = { strength: 0.35 }; |
| const rng = (seed => () => { seed = (seed * 1664525 + 1013904223) % 4294967296; return seed / 4294967296; })(123456789); |
| |
| const groundHeightAt = (x, z) => { |
| const nx = x * 0.01, nz = z * 0.01; |
| return Math.sin(nx) * Math.cos(nz) * 1.2 + |
| Math.sin(nx * 0.21 + 2.7) * Math.sin(nz * 0.19 + 1.5) * 0.7 + |
| Math.cos(nx * 0.07 - 1.1) * Math.sin(nz * 0.09 + 0.4) * 2.0; |
| }; |
| |
| let treeData = []; |
| function regenerateForest(count, radius = areaSize.value) { |
| makeInstancedMeshes(count); |
| treeData.length = 0; |
| |
| const minSpacing = 4.0; |
| const ext = radius; |
| const attempts = count * 8; |
| const points = []; |
| for (let i = 0; i < attempts && points.length < count; i++) { |
| const x = (rng() * 2 - 1) * ext; |
| const z = (rng() * 2 - 1) * ext; |
| const h = groundHeightAt(x, z); |
| const hx = groundHeightAt(x + 1.0, z); |
| const hz = groundHeightAt(x, z + 1.0); |
| const slope = Math.hypot(hx - h, hz - h); |
| if (slope > 1.2) continue; |
| |
| let ok = true; |
| for (let p = 0; p < points.length; p++) { |
| const dx = x - points[p].x; |
| const dz = z - points[p].z; |
| if (dx * dx + dz * dz < minSpacing * minSpacing) { ok = false; break; } |
| } |
| if (!ok) continue; |
| |
| const t = { |
| x, z, h, |
| scale: 0.8 + rng() * 1.6, |
| type: rng() < 0.7 ? 'pine' : 'round', |
| swayPhase: rng() * Math.PI * 2, |
| swayAmp: 0.02 + rng() * 0.04 |
| }; |
| points.push({ x, z }); |
| treeData.push(t); |
| } |
| |
| const m = new THREE.Matrix4(); |
| const q = new THREE.Quaternion(); |
| const up = new THREE.Vector3(0, 1, 0); |
| for (let i = 0; i < treeData.length; i++) { |
| const t = treeData[i]; |
| q.setFromAxisAngle(up, rng() * Math.PI * 2); |
| m.compose(new THREE.Vector3(t.x, t.h, t.z), q, new THREE.Vector3(1, t.scale, 1)); |
| trunkInstanced.setMatrixAt(i, m); |
| |
| const foliageScale = 0.9 * t.scale; |
| m.compose(new THREE.Vector3(t.x, t.h, t.z), q, new THREE.Vector3(foliageScale, foliageScale, foliageScale)); |
| foliageInstanced.setMatrixAt(i, m); |
| |
| const baseLeaf = new THREE.Color(0x2f6b3d); |
| const shade = 0.8 + rng() * 0.4; |
| const tint = baseLeaf.clone().multiplyScalar(shade); |
| foliageInstanced.setColorAt(i, tint); |
| |
| const trunkColor = new THREE.Color(0x5c3f28).offsetHSL(0, 0, (rng() - 0.5) * 0.05); |
| trunkInstanced.setColorAt(i, trunkColor); |
| } |
| trunkInstanced.instanceColor = new THREE.InstancedBufferAttribute(trunkInstanced.instanceColor.array, 3); |
| foliageInstanced.instanceColor = new THREE.InstancedBufferAttribute(foliageInstanced.instanceColor.array, 3); |
| trunkInstanced.instanceMatrix.needsUpdate = true; |
| foliageInstanced.instanceMatrix.needsUpdate = true; |
| } |
| |
| const windUniforms = { uTime: { value: 0 }, uStrength: { value: wind.strength } }; |
| foliageMat.onBeforeCompile = (shader) => { |
| shader.uniforms.uTime = windUniforms.uTime; |
| shader.uniforms.uStrength = windUniforms.uStrength; |
| shader.vertexShader = ` |
| uniform float uTime; |
| uniform float uStrength; |
| ` + shader.vertexShader.replace( |
| '#include <begin_vertex>', |
| ` |
| #include <begin_vertex> |
| float sway = sin(uTime * 1.7 + position.y * 0.35) * 0.5 + sin(uTime * 0.9 + position.y * 0.7) * 0.5; |
| transformed.x += sway * uStrength * (0.4 + position.y * 0.06); |
| transformed.z += cos(uTime * 1.1 + position.y * 0.42) * uStrength * (0.3 + position.y * 0.05); |
| ` |
| ); |
| }; |
| foliageMat.needsUpdate = true; |
| |
| |
| const decoGroup = new THREE.Group(); scene.add(decoGroup); |
| function makeRockGeometry() { |
| const geo = new THREE.IcosahedronGeometry(1.0, 1); |
| const arr = geo.attributes.position.array; |
| for (let i = 0; i < arr.length; i += 3) { |
| const r = 0.7 + rng() * 0.6; |
| arr[i] *= r; arr[i + 1] *= (0.6 + rng() * 0.4 + 0.2); arr[i + 2] *= r; |
| } |
| geo.computeVertexNormals(); |
| return geo; |
| } |
| const rockGeo = makeRockGeometry(); |
| const rockMat = new THREE.MeshStandardMaterial({ color: 0x808a8f, roughness: 0.95, metalness: 0.0 }); |
| const rocksInst = new THREE.InstancedMesh(rockGeo, rockMat, 400); |
| rocksInst.castShadow = true; rocksInst.receiveShadow = true; decoGroup.add(rocksInst); |
| |
| const grassBladeGeo = new THREE.PlaneGeometry(0.08, 1.2, 1, 3); |
| grassBladeGeo.translate(0, 0.6, 0); |
| const grassMat = new THREE.MeshStandardMaterial({ color: 0x5aa35f, side: THREE.DoubleSide, roughness: 1.0, metalness: 0.0 }); |
| const grassInst = new THREE.InstancedMesh(grassBladeGeo, grassMat, 2000); |
| grassInst.castShadow = false; grassInst.receiveShadow = true; decoGroup.add(grassInst); |
| |
| function regenerateDecor(radius = areaSize.value) { |
| const m = new THREE.Matrix4(); |
| const q = new THREE.Quaternion(); |
| |
| const rockCount = rocksInst.count; |
| const rockExt = radius * 0.95; |
| for (let i = 0; i < rockCount; i++) { |
| const x = (rng() * 2 - 1) * rockExt; |
| const z = (rng() * 2 - 1) * rockExt; |
| const h = groundHeightAt(x, z); |
| q.setFromAxisAngle(new THREE.Vector3(0,1,0), rng() * Math.PI * 2); |
| const s = 0.6 + rng() * 2.0; |
| m.compose(new THREE.Vector3(x, h, z), q, new THREE.Vector3(s, s * (0.6 + rng() * 0.4), s)); |
| rocksInst.setMatrixAt(i, m); |
| const shade = 0.8 + rng() * 0.3; |
| const c = new THREE.Color().setRGB(0.6 * shade, 0.66 * shade, 0.72 * shade); |
| rocksInst.setColorAt(i, c); |
| } |
| rocksInst.instanceMatrix.needsUpdate = true; |
| if (!rocksInst.instanceColor) rocksInst.instanceColor = new THREE.InstancedBufferAttribute(new Float32Array(rockCount * 3), 3); |
| rocksInst.instanceColor.needsUpdate = true; |
| |
| const grassCount = grassInst.count; |
| const grassExt = radius; |
| for (let i = 0; i < grassCount; i++) { |
| const x = (rng() * 2 - 1) * grassExt; |
| const z = (rng() * 2 - 1) * grassExt; |
| const h = groundHeightAt(x, z); |
| q.setFromAxisAngle(new THREE.Vector3(0,1,0), rng() * Math.PI * 2); |
| const s = 0.7 + rng() * 0.6; |
| m.compose(new THREE.Vector3(x, h, z), q, new THREE.Vector3(s, s, s)); |
| grassInst.setMatrixAt(i, m); |
| const g = 0.7 + rng() * 0.3; |
| const col = new THREE.Color(0x5aa35f).multiplyScalar(g); |
| grassInst.setColorAt(i, col); |
| } |
| grassInst.instanceMatrix.needsUpdate = true; |
| if (!grassInst.instanceColor) grassInst.instanceColor = new THREE.InstancedBufferAttribute(new Float32Array(grassCount * 3), 3); |
| grassInst.instanceColor.needsUpdate = true; |
| } |
| |
| |
| const particleGeo = new THREE.BufferGeometry(); |
| const PCOUNT = 800; |
| const positions = new Float32Array(PCOUNT * 3); |
| const speeds = new Float32Array(PCOUNT); |
| const pColors = new Float32Array(PCOUNT * 3); |
| for (let i = 0; i < PCOUNT; i++) { |
| positions[i * 3] = (rng() * 2 - 1) * 250; |
| positions[i * 3 + 1] = 1 + rng() * 12; |
| positions[i * 3 + 2] = (rng() * 2 - 1) * 250; |
| speeds[i] = 0.2 + rng() * 0.6; |
| const c = new THREE.Color().setHSL(0.14 + rng() * 0.05, 0.4, 0.6 + rng() * 0.2); |
| pColors[i * 3] = c.r; pColors[i * 3 + 1] = c.g; pColors[i * 3 + 2] = c.b; |
| } |
| particleGeo.setAttribute('position', new THREE.BufferAttribute(positions, 3)); |
| particleGeo.setAttribute('aSpeed', new THREE.BufferAttribute(speeds, 1)); |
| particleGeo.setAttribute('color', new THREE.BufferAttribute(pColors, 3)); |
| const particleMat = new THREE.PointsMaterial({ size: 0.6, sizeAttenuation: true, transparent: true, opacity: 0.7, depthWrite: false, vertexColors: true }); |
| const particles = new THREE.Points(particleGeo, particleMat); |
| scene.add(particles); |
| |
| |
| const waterGeo = new THREE.PlaneGeometry(200, 8, 1, 1); |
| waterGeo.rotateX(-Math.PI / 2); |
| const waterMat = new THREE.MeshPhysicalMaterial({ |
| color: 0x2a5b6b, roughness: 0.25, metalness: 0.0, |
| transmission: 0.2, thickness: 0.2, transparent: true, opacity: 0.85, |
| clearcoat: 0.4, clearcoatRoughness: 0.3 |
| }); |
| const water = new THREE.Mesh(waterGeo, waterMat); |
| water.position.set(0, groundHeightAt(0, 0) - 0.2, 0); |
| water.receiveShadow = true; |
| scene.add(water); |
| |
| |
| const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 1200); |
| camera.position.set(60, 40, 80); |
| const controls = new OrbitControls(camera, renderer.domElement); |
| controls.enableDamping = true; controls.dampingFactor = 0.05; |
| controls.maxPolarAngle = Math.PI * 0.495; |
| controls.target.set(0, 8, 0); controls.update(); |
| |
| |
| regenerateForest(550, areaSize.value); |
| regenerateDecor(areaSize.value); |
| |
| |
| setSunFromUI(); |
| setHemiFromUI(); |
| setWindFromUI(); |
| setAreaFromUI(); |
| |
| |
| function addStars() { |
| const starGeo = new THREE.BufferGeometry(); |
| const STAR_COUNT = 4000; |
| const starPos = new Float32Array(STAR_COUNT * 3); |
| const starCol = new Float32Array(STAR_COUNT * 3); |
| |
| |
| const radiusMin = 500; |
| const radiusMax = 900; |
| for (let i = 0; i < STAR_COUNT; i++) { |
| const u = rng(); |
| const v = rng(); |
| const theta = 2 * Math.PI * u; |
| const phi = Math.acos(2 * v - 1); |
| const r = radiusMin + rng() * (radiusMax - radiusMin); |
| const x = r * Math.sin(phi) * Math.cos(theta); |
| const y = r * Math.cos(phi); |
| const z = r * Math.sin(phi) * Math.sin(theta); |
| starPos[i * 3] = x; |
| starPos[i * 3 + 1] = y; |
| starPos[i * 3 + 2] = z; |
| |
| const twinkle = 0.85 + rng() * 0.3; |
| const c = new THREE.Color().setHSL(0.57 + rng() * 0.1, 0.1 + rng() * 0.2, 0.9 * twinkle); |
| starCol[i * 3] = c.r; starCol[i * 3 + 1] = c.g; starCol[i * 3 + 2] = c.b; |
| } |
| starGeo.setAttribute('position', new THREE.BufferAttribute(starPos, 3)); |
| starGeo.setAttribute('color', new THREE.BufferAttribute(starCol, 3)); |
| |
| const starMat = new THREE.PointsMaterial({ |
| size: 1.4, |
| sizeAttenuation: true, |
| depthWrite: false, |
| transparent: true, |
| opacity: 0.95, |
| vertexColors: true |
| }); |
| |
| const stars = new THREE.Points(starGeo, starMat); |
| stars.renderOrder = -1; |
| scene.add(stars); |
| |
| |
| const skyGeo = new THREE.SphereGeometry(1200, 32, 16); |
| skyGeo.scale(-1, 1, 1); |
| const skyMat = new THREE.MeshBasicMaterial({ |
| color: 0x0b1216 |
| }); |
| const sky = new THREE.Mesh(skyGeo, skyMat); |
| scene.add(sky); |
| |
| |
| return { stars, sky }; |
| } |
| const starfield = addStars(); |
| |
| |
| |
| densityEl.addEventListener('input', () => { |
| const count = parseInt(densityEl.value, 10); |
| densityVal.textContent = count; |
| regenerateForest(count, areaSize.value); |
| }); |
| windEl.addEventListener('input', () => { |
| const v = parseInt(windEl.value, 10) / 100; |
| wind.strength = v; |
| windUniforms.uStrength.value = v; |
| windVal.textContent = v.toFixed(2); |
| }); |
| sizeEl.addEventListener('input', () => { |
| const v = parseInt(sizeEl.value, 10); |
| areaSize.value = v; |
| sizeVal.textContent = v; |
| regenerateForest(parseInt(densityEl.value, 10), v); |
| regenerateDecor(v); |
| }); |
| |
| function updateSunFromUI() { |
| const intensity = parseInt(sunIntEl.value, 10) / 100; |
| const elevDeg = parseInt(sunElevEl.value, 10); |
| const azimDeg = parseInt(sunAzimEl.value, 10); |
| const elev = THREE.MathUtils.degToRad(elevDeg); |
| const azim = THREE.MathUtils.degToRad(azimDeg); |
| |
| dirLight.intensity = intensity; |
| const r = 180; |
| const y = Math.sin(elev) * r; |
| const horiz = Math.cos(elev) * r; |
| const x = Math.cos(azim) * horiz; |
| const z = Math.sin(azim) * horiz; |
| dirLight.position.set(x, y, z); |
| |
| sunIntVal.textContent = intensity.toFixed(2); |
| sunElevVal.textContent = elevDeg + '°'; |
| sunAzimVal.textContent = azimDeg + '°'; |
| } |
| function updateHemiFromUI() { |
| const v = parseInt(hemiEl.value, 10) / 100; |
| hemiLight.intensity = v; |
| hemiVal.textContent = v.toFixed(2); |
| } |
| sunIntEl.addEventListener('input', updateSunFromUI); |
| sunElevEl.addEventListener('input', updateSunFromUI); |
| sunAzimEl.addEventListener('input', updateSunFromUI); |
| hemiEl.addEventListener('input', updateHemiFromUI); |
| updateSunFromUI(); |
| updateHemiFromUI(); |
| |
| |
| const keys = { ArrowUp: false, ArrowDown: false, ArrowLeft: false, ArrowRight: false, ShiftLeft: false, ShiftRight: false }; |
| function setKey(code, down) { |
| if (code in keys) { |
| keys[code] = down; |
| return true; |
| } |
| return false; |
| } |
| |
| window.addEventListener('keydown', (e) => { |
| const hit = setKey(e.key || e.code, true) || setKey(e.code, true); |
| if (hit) { e.preventDefault(); } |
| }, { passive: false }); |
| window.addEventListener('keyup', (e) => { |
| const hit = setKey(e.key || e.code, false) || setKey(e.code, false); |
| if (hit) { e.preventDefault(); } |
| }, { passive: false }); |
| |
| window.addEventListener('keydown', (e) => { |
| if (e.key === 'w' || e.key === 'W') { keys.ArrowUp = true; e.preventDefault(); } |
| if (e.key === 's' || e.key === 'S') { keys.ArrowDown = true; e.preventDefault(); } |
| if (e.key === 'a' || e.key === 'A') { keys.ArrowLeft = true; e.preventDefault(); } |
| if (e.key === 'd' || e.key === 'D') { keys.ArrowRight = true; e.preventDefault(); } |
| }, { passive: false }); |
| window.addEventListener('keyup', (e) => { |
| if (e.key === 'w' || e.key === 'W') { keys.ArrowUp = false; e.preventDefault(); } |
| if (e.key === 's' || e.key === 'S') { keys.ArrowDown = false; e.preventDefault(); } |
| if (e.key === 'a' || e.key === 'A') { keys.ArrowLeft = false; e.preventDefault(); } |
| if (e.key === 'd' || e.key === 'D') { keys.ArrowRight = false; e.preventDefault(); } |
| }, { passive: false }); |
| |
| function updateKeyboardMovement(dt) { |
| const speedBase = 25; |
| const boost = (keys.ShiftLeft || keys.ShiftRight) ? 3.0 : 1.0; |
| const speed = speedBase * boost; |
| |
| let inputX = 0, inputZ = 0; |
| if (keys.ArrowUp) inputZ -= 1; |
| if (keys.ArrowDown) inputZ += 1; |
| if (keys.ArrowLeft) inputX -= 1; |
| if (keys.ArrowRight) inputX += 1; |
| |
| if (inputX !== 0 || inputZ !== 0) { |
| const forward = new THREE.Vector3(); |
| camera.getWorldDirection(forward); |
| forward.y = 0; forward.normalize(); |
| |
| const right = new THREE.Vector3().crossVectors(forward, new THREE.Vector3(0,1,0)).normalize(); |
| |
| const move = new THREE.Vector3() |
| .addScaledVector(forward, inputZ) |
| .addScaledVector(right, inputX) |
| .normalize() |
| .multiplyScalar(speed * dt); |
| |
| camera.position.add(move); |
| controls.target.add(move); |
| } |
| } |
| |
| |
| const clock = new THREE.Clock(); |
| function animate() { |
| requestAnimationFrame(animate); |
| const t = clock.getElapsedTime(); |
| const dt = clock.getDelta(); |
| |
| windUniforms.uTime.value = t; |
| |
| |
| const posAttr = particles.geometry.getAttribute('position'); |
| const spdAttr = particles.geometry.getAttribute('aSpeed'); |
| for (let i = 0; i < PCOUNT; i++) { |
| const y = posAttr.getY(i); |
| const x = posAttr.getX(i); |
| const z = posAttr.getZ(i); |
| const s = spdAttr.getX(i); |
| const nx = x + Math.sin(t * 0.6 + i) * 0.02; |
| const nz = z + Math.cos(t * 0.5 + i * 1.3) * 0.02; |
| let ny = y + (Math.sin(t * s + i) * 0.003 + 0.002); |
| if (ny > 14) ny = 1 + rng() * 2; |
| posAttr.setXYZ(i, nx, ny, nz); |
| } |
| posAttr.needsUpdate = true; |
| |
| |
| if (starfield && starfield.stars) { |
| starfield.stars.rotation.y = t * 0.002; |
| starfield.stars.rotation.x = Math.sin(t * 0.05) * 0.02; |
| } |
| |
| |
| updateKeyboardMovement(dt); |
| |
| controls.update(); |
| renderer.render(scene, camera); |
| } |
| animate(); |
| |
| window.addEventListener('resize', () => { |
| camera.aspect = window.innerWidth / window.innerHeight; |
| camera.updateProjectionMatrix(); |
| renderer.setSize(window.innerWidth, window.innerHeight); |
| }); |
| |
| |
| renderer.domElement.addEventListener('pointerdown', () => renderer.domElement.focus()); |
| </script> |
| </body> |
| </html> |