Prompt specification
Build or customize the Three.js 3D scene "Scout Reveals a Small Valley" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Scout Reveals a Small Valley
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/scout-reveals-a-small-valley-x3542
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing an animation of a scout revealing nearby tiles under a stated visibility radius. Retain previously observed terrain separately from currently visible moving objects. Voxel style.
Working Three.js Starter (scout-reveals-a-small-valley-x3542):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Voxel Scout — Tile Reveal / Fog of War</title>
<style>
:root{
--accent:#63e0ff;
--accent2:#ffc46b;
--panel:rgba(8,13,21,.74);
--line:rgba(99,224,255,.22);
}
*{box-sizing:border-box}
html,body{margin:0;height:100%;overflow:hidden;background:#05080d;color:#d3e6f2;
font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,"Liberation Mono",monospace;}
canvas{display:block}
#app{position:fixed;inset:0}
#hud{position:fixed;inset:0;pointer-events:none;z-index:10}
.panel{
position:absolute;background:var(--panel);border:1px solid var(--line);
border-radius:12px;padding:12px 14px;backdrop-filter:blur(7px);
box-shadow:0 10px 30px rgba(0,0,0,.45);pointer-events:auto;
}
h1{font-size:14px;letter-spacing:.16em;margin:0 0 4px;color:#eaf7ff}
.sub{font-size:11px;color:#7f9bb0;margin-bottom:9px;letter-spacing:.06em}
.rad{font-size:13px;color:var(--accent);font-weight:700;letter-spacing:.05em;margin:6px 0 3px}
.rad span{color:#fff;background:rgba(99,224,255,.16);border:1px solid var(--line);
border-radius:5px;padding:1px 7px;font-size:13px}
.note{font-size:10px;color:#7f9bb0;line-height:1.5;margin-bottom:8px}
.legend{font-size:11px;line-height:1.75;color:#b9d2e2}
.legend div{display:flex;align-items:center;gap:8px}
.sw{width:11px;height:11px;border-radius:3px;display:inline-block;flex:0 0 auto;
box-shadow:0 0 0 1px rgba(255,255,255,.14) inset}
.sw-lit{background:#7ac943}
.sw-mem{background:#3d5570}
.sw-dark{background:#131a24}
.sw-obj{background:var(--accent2);border-radius:50%}
.row{display:flex;justify-content:space-between;gap:14px;font-size:11px;
padding:2px 0;color:#a9c4d6}
.row b{color:#eaf7ff;font-weight:600}
.sep{height:1px;background:var(--line);margin:9px 0}
label.opt{display:flex;align-items:center;gap:8px;font-size:11px;color:#b9d2e2;
margin:6px 0;cursor:pointer}
input[type=range]{width:100%;accent-color:var(--accent);height:14px}
.sliderlab{font-size:10px;color:#7f9bb0;display:flex;justify-content:space-between}
button{font:inherit;font-size:11px;color:#04121a;background:var(--accent);
border:0;border-radius:6px;padding:6px 10px;cursor:pointer;letter-spacing:.05em}
button:hover{filter:brightness(1.12)}
button.ghost{background:transparent;color:var(--accent);border:1px solid var(--line)}
#p-left{top:14px;left:14px;width:288px}
#p-right{top:14px;right:14px;width:236px}
#p-map{bottom:14px;right:14px;width:236px;text-align:center}
#p-help{bottom:14px;left:14px;width:288px;font-size:11px;color:#9db8ca;line-height:1.65}
#p-help b{color:#eaf7ff;font-weight:600}
#minimap{width:206px;height:206px;border-radius:6px;border:1px solid var(--line);
background:#070b11;image-rendering:pixelated}
#status{margin-top:8px;font-size:10px;color:var(--accent2);min-height:14px}
@media (max-width:880px){
#p-help{display:none}
#p-left,#p-right,#p-map{width:200px;padding:9px}
#minimap{width:180px;height:180px}
}
</style>
</head>
<body>
<div id="app"></div>
<div id="hud">
<div class="panel" id="p-left">
<h1>VOXEL SCOUT · TILE REVEAL</h1>
<div class="sub">exploration / fog-of-war demo</div>
<div class="rad">VISIBILITY RADIUS: <span id="radVal">4.5</span> TILES</div>
<div class="note">A tile is <b>visible</b> when the planar (ground-plane XZ) distance
from the scout to the tile centre is ≤ the radius. Seen terrain is <b>remembered</b>
and stays rendered as dim memory after the scout leaves.</div>
<div class="legend">
<div><i class="sw sw-lit"></i>currently visible terrain</div>
<div><i class="sw sw-mem"></i>remembered terrain (retained)</div>
<div><i class="sw sw-dark"></i>never observed (not rendered)</div>
<div><i class="sw sw-obj"></i>moving objects — inside radius only</div>
</div>
</div>
<div class="panel" id="p-right">
<div class="row"><span>tiles discovered</span><b id="sDisc">0 / 900</b></div>
<div class="row"><span>visible now</span><b id="sVis">0</b></div>
<div class="row"><span>objects in view</span><b id="sObj">0</b></div>
<div class="row"><span>scout tile</span><b id="sPos">0, 0</b></div>
<div class="row"><span>fps</span><b id="sFps">–</b></div>
<div class="sep"></div>
<div class="sliderlab"><span>visibility radius</span><span id="radVal2">4.5</span></div>
<input id="radSlider" type="range" min="2" max="9" step="0.5" value="4.5" />
<div class="sliderlab" style="margin-top:6px"><span>scout speed</span><span id="spdVal">3.0</span></div>
<input id="spdSlider" type="range" min="1" max="6" step="0.5" value="3" />
<div class="sep"></div>
<label class="opt"><input id="autoPatrol" type="checkbox" checked /> auto patrol</label>
<label class="opt"><input id="showRing" type="checkbox" checked /> show radius ring</label>
<label class="opt"><input id="showMemory" type="checkbox" checked /> show remembered terrain</label>
<div class="sep"></div>
<button id="resetBtn" class="ghost" style="width:100%">RESET EXPLORATION</button>
</div>
<div class="panel" id="p-map">
<canvas id="minimap" width="206" height="206"></canvas>
<div id="status"></div>
</div>
<div class="panel" id="p-help">
<b>drag</b> orbit · <b>wheel</b> zoom · <b>right-drag / WASD</b> pan ·
<b>click terrain</b> send scout · <b>Q / E</b> rotate · <b>space</b> pause ·
<b>R</b> reset
</div>
</div>
<script type="module">
import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js';
/* ------------------------------------------------------------------ *
* WORLD CONSTANTS
* ------------------------------------------------------------------ */
const N = 30; // grid is N x N tiles
const TILE = 1; // world units per tile
const ORIGIN = -N * TILE / 2; // world coordinate of grid edge
const MAX_INST = 14000;
let RADIUS = 4.5; // <-- THE STATED VISIBILITY RADIUS (in tiles)
let SCOUT_SPEED = 3.0;
/* ------------------------------------------------------------------ *
* RENDERER / SCENE / CAMERA
* ------------------------------------------------------------------ */
const app = document.getElementById('app');
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
app.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x070b12);
scene.fog = new THREE.Fog(0x070b12, 48, 130);
const camera = new THREE.PerspectiveCamera(46, window.innerWidth / window.innerHeight, 0.1, 400);
/* custom orbit camera (no addons) */
const cam = {
target: new THREE.Vector3(0, 1, 0),
az: -0.85, pol: 0.92, dist: 27
};
function updateCamera() {
const sp = Math.sin(cam.pol);
camera.position.set(
cam.target.x + cam.dist * sp * Math.sin(cam.az),
cam.target.y + cam.dist * Math.cos(cam.pol),
cam.target.z + cam.dist * sp * Math.cos(cam.az)
);
camera.lookAt(cam.target);
}
/* lights */
scene.add(new THREE.HemisphereLight(0xa8cbe8, 0x141b26, 1.05));
const sun = new THREE.DirectionalLight(0xfff1d8, 1.75);
sun.position.set(14, 22, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -22; sun.shadow.camera.right = 22;
sun.shadow.camera.top = 22; sun.shadow.camera.bottom = -22;
sun.shadow.camera.near = 1; sun.shadow.camera.far = 70;
sun.shadow.bias = -0.0012; sun.shadow.normalBias = 0.03;
scene.add(sun);
/* ------------------------------------------------------------------ *
* PROCEDURAL VOXEL TERRAIN
* ------------------------------------------------------------------ */
const PAL = {
grass: 0x74c247, grass2: 0x63b23d,
forest: 0x3f9b47,
sand: 0xe0cb90,
water: 0x2c7fd2, deep: 0x1b3357,
rock: 0x8d95a3, snow: 0xedf3fb,
dirt: 0x7b5334, rockDark: 0x5d6470,
trunk: 0x6a4a2d, leaf: 0x2e8c39, leaf2: 0x48ad4e
};
function hash2(x, y) {
const s = Math.sin(x * 127.1 + y * 311.7) * 43758.5453123;
return s - Math.floor(s);
}
function vnoise(x, y) {
const xi = Math.floor(x), yi = Math.floor(y);
const xf = x - xi, yf = y - yi;
const u = xf * xf * (3 - 2 * xf), v = yf * yf * (3 - 2 * yf);
const a = hash2(xi, yi), b = hash2(xi + 1, yi);
const c = hash2(xi, yi + 1), d = hash2(xi + 1, yi + 1);
const ab = a + (b - a) * u, cd = c + (d - c) * u;
return ab + (cd - ab) * v;
}
function fbm(x, y) {
let v = 0, amp = 0.5, f = 1, norm = 0;
for (let o = 0; o < 4; o++) { v += amp * vnoise(x * f, y * f); norm += amp; f *= 2; amp *= 0.5; }
return v / norm;
}
const tiles = []; // one entry per grid cell
const discovered = new Uint8Array(N * N);
const prevVis = new Uint8Array(N * N);
let discoveredCount = 0;
const memTint = new THREE.Color(0x1d2740);
function dimColor(hex) {
const c = new THREE.Color(hex);
return c.lerp(memTint, 0.58).multiplyScalar(0.62);
}
function brightColor(hex) {
const c = new THREE.Color(hex);
return c.multiplyScalar(1.12);
}
function buildTile(i, j) {
const e = fbm(j * 0.155 + 3.7, i * 0.155 + 9.4);
const m = fbm(j * 0.085 + 31.7, i * 0.085 + 5.9);
const raw = e * 6.1 - 1.25;
const levels = Math.max(0, Math.min(5, Math.floor(raw)));
let type;
if (levels === 0) type = 'water';
else if (levels === 1) type = 'sand';
else if (levels >= 5) type = 'snow';
else if (levels === 4 && m > 0.48) type = 'rock';
else if (m > 0.585) type = 'forest';
else type = hash2(j * 5.1, i * 2.3) > 0.5 ? 'grass' : 'grass2';
const cx = ORIGIN + j + 0.5, cz = ORIGIN + i + 0.5;
const cubes = [];
if (type === 'water') {
cubes.push({ x: cx, y: 0.12, z: cz, sx: 1, sy: 0.24, sz: 1, c: PAL.water });
cubes.push({ x: cx, y: -0.44, z: cz, sx: 1, sy: 0.62, sz: 1, c: PAL.deep });
} else {
const surf = PAL[type];
for (let l = 0; l < levels; l++) {
const c = (l === levels - 1) ? surf
: (type === 'rock' || type === 'snow' ? PAL.rockDark : PAL.dirt);
cubes.push({ x: cx, y: l + 0.5, z: cz, sx: 1, sy: 1, sz: 1, c });
}
// decorations
if (type === 'forest' && hash2(j * 3.7 + 1.3, i * 1.9) > 0.78) {
cubes.push({ x: cx, y: levels + 0.6, z: cz, sx: 0.28, sy: 1.2, sz: 0.28, c: PAL.trunk });
cubes.push({ x: cx, y: levels + 1.75, z: cz, sx: 0.95, sy: 0.7, sz: 0.95, c: PAL.leaf });
cubes.push({ x: cx + 0.36, y: levels + 1.32, z: cz + 0.22, sx: 0.62, sy: 0.55, sz: 0.62, c: PAL.leaf2 });
}
if (type === 'rock' && hash2(j * 9.1, i * 4.7 + 2.2) > 0.82) {
cubes.push({ x: cx + 0.18, y: levels + 0.22, z: cz - 0.16, sx: 0.62, sy: 0.44, sz: 0.55, c: PAL.rock });
}
if (type === 'sand' && hash2(j * 2.2, i * 7.7) > 0.86) {
cubes.push({ x: cx - 0.2, y: levels + 0.16, z: cz + 0.24, sx: 0.42, sy: 0.32, sz: 0.4, c: PAL.rock });
}
}
const cM = cubes.map(c => dimColor(c.c));
const cV = cubes.map(c => brightColor(c.c));
const surfHex = (type === 'water' ? PAL.water : PAL[type]);
return {
i, j, type, levels, cubes, cM, cV,
cssBright: '#' + new THREE.Color(surfHex).getHexString(),
cssDim: '#' + dimColor(surfHex).getHexString(),
center: new THREE.Vector3(cx, 0, cz)
};
}
for (let i = 0; i < N; i++) for (let j = 0; j < N; j++) tiles.push(buildTile(i, j));
/* ------------------------------------------------------------------ *
* INSTANCED TERRAIN (memory layer + live layer are separate meshes)
* ------------------------------------------------------------------ */
function cubeGeoWithColor() {
const g = new THREE.BoxGeometry(1, 1, 1);
const n = g.attributes.position.count;
g.setAttribute('color', new THREE.BufferAttribute(new Float32Array(n * 3).fill(1), 3));
return g;
}
const geo = cubeGeoWithColor();
const memMesh = new THREE.InstancedMesh(geo,
new THREE.MeshLambertMaterial({ vertexColors: true }), MAX_INST);
const visMesh = new THREE.InstancedMesh(geo,
new THREE.MeshLambertMaterial({ vertexColors: true }), MAX_INST);
memMesh.count = 0; visMesh.count = 0;
memMesh.frustumCulled = false; visMesh.frustumCulled = false;
memMesh.receiveShadow = true; visMesh.receiveShadow = true;
visMesh.castShadow = true;
scene.add(memMesh, visMesh);
const dummy = new THREE.Object3D();
function fillMesh(mesh, list, useMemory) {
let n = 0;
for (const t of list) {
const cols = useMemory ? t.cM : t.cV;
for (let k = 0; k < t.cubes.length; k++) {
const c = t.cubes[k];
dummy.position.set(c.x, c.y, c.z);
dummy.scale.set(c.sx, c.sy, c.sz);
dummy.rotation.set(0, 0, 0);
dummy.updateMatrix();
mesh.setMatrixAt(n, dummy.matrix);
mesh.setColorAt(n, cols[k]);
if (++n >= MAX_INST) break;
}
}
mesh.count = n;
mesh.instanceMatrix.needsUpdate = true;
if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
}
const visList = [], memList = [];
function rebuildTerrain() {
visList.length = 0; memList.length = 0;
for (let k = 0; k < N * N; k++) {
if (prevVis[k]) visList.push(tiles[k]);
else if (discovered[k]) memList.push(tiles[k]);
}
fillMesh(visMesh, visList, false);
fillMesh(memMesh, memList, true);
}
/* ------------------------------------------------------------------ *
* GROUND / BACKDROP
* ------------------------------------------------------------------ */
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(220, 220),
new THREE.MeshLambertMaterial({ color: 0x080c13 })
);
ground.rotation.x = -Math.PI / 2; ground.position.y = -0.8; ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(N, N, 0x1b2b3c, 0x121a26);
grid.position.y = -0.78;
grid.material.transparent = true; grid.material.opacity = 0.55;
scene.add(grid);
/* stars */
{
const p = new Float32Array(700 * 3);
for (let i = 0; i < 700; i++) {
p[i * 3] = (Math.random() - 0.5) * 260;
p[i * 3 + 1] = 20 + Math.random() * 70;
p[i * 3 + 2] = (Math.random() - 0.5) * 260;
}
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.BufferAttribute(p, 3));
scene.add(new THREE.Points(g, new THREE.PointsMaterial({ color: 0x9fc6e8, size: 0.32, sizeAttenuation: true, transparent: true, opacity: 0.65 })));
}
/* ------------------------------------------------------------------ *
* SCOUT (voxel figure + lantern)
* ------------------------------------------------------------------ */
const matCache = new Map();
function mat(hex) {
if (!matCache.has(hex)) matCache.set(hex, new THREE.MeshLambertMaterial({ color: hex }));
return matCache.get(hex);
}
function vbox(w, h, d, x, y, z, hex) {
const m = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), mat(hex));
m.position.set(x, y, z); m.castShadow = true; return m;
}
const scout = new THREE.Group();
const legL = vbox(0.22, 0.42, 0.24, -0.13, 0.21, 0, 0x3a3f4a);
const legR = vbox(0.22, 0.42, 0.24, 0.13, 0.21, 0, 0x3a3f4a);
const torso = vbox(0.52, 0.56, 0.34, 0, 0.72, 0, 0x1f9e9a);
const belt = vbox(0.54, 0.10, 0.36, 0, 0.50, 0, 0x8a5a2b);
const pack = vbox(0.34, 0.38, 0.20, 0, 0.76, -0.26, 0xc07b3a);
const head = vbox(0.34, 0.32, 0.32, 0, 1.16, 0.02, 0xe8bd94);
const brim = vbox(0.50, 0.07, 0.50, 0, 1.33, 0.02, 0x2d5f7a);
const crown = vbox(0.36, 0.20, 0.36, 0, 1.44, 0.02, 0x35708f);
const eyeL = vbox(0.06, 0.06, 0.03, -0.08, 1.18, 0.19, 0x22242b);
const eyeR = vbox(0.06, 0.06, 0.03, 0.08, 1.18, 0.19, 0x22242b);
const armL = vbox(0.16, 0.40, 0.18, -0.33, 0.74, 0.05, 0x1f9e9a);
const armR = vbox(0.16, 0.40, 0.18, 0.33, 0.74, 0.12, 0x1f9e9a);
const lantern = vbox(0.16, 0.20, 0.16, 0.33, 0.48, 0.20, 0xffd88a);
const lampLight = new THREE.PointLight(0xffcf85, 14, 8, 2);
lampLight.position.set(0.33, 0.52, 0.22);
scout.add(legL, legR, torso, belt, pack, head, brim, crown, eyeL, eyeR, armL, armR, lantern, lampLight);
scene.add(scout);
/* ------------------------------------------------------------------ *
* MOVING OBJECTS (visible ONLY inside the visibility radius)
* ------------------------------------------------------------------ */
const creatures = [];
function makeBoar() {
const g = new THREE.Group();
g.add(vbox(0.56, 0.40, 0.80, 0, 0.42, 0, 0x6d4a2f));
g.add(vbox(0.36, 0.32, 0.32, 0, 0.42, 0.52, 0x7d563a));
g.add(vbox(0.20, 0.14, 0.16, 0, 0.34, 0.70, 0x54382a));
g.add(vbox(0.05, 0.10, 0.05, -0.10, 0.32, 0.76, 0xefe6cf));
g.add(vbox(0.05, 0.10, 0.05, 0.10, 0.32, 0.76, 0xefe6cf));
g.add(vbox(0.14, 0.28, 0.14, -0.20, 0.14, 0.26, 0x4d3423));
g.add(vbox(0.14, 0.28, 0.14, 0.20, 0.14, 0.26, 0x4d3423));
g.add(vbox(0.14, 0.28, 0.14, -0.20, 0.14, -0.26, 0x4d3423));
g.add(vbox(0.14, 0.28, 0.14, 0.20, 0.14, -0.26, 0x4d3423));
return g;
}
function makeRabbit() {
const g = new THREE.Group();
g.add(vbox(0.30, 0.26, 0.42, 0, 0.20, 0, 0xf1f0e9));
g.add(vbox(0.24, 0.22, 0.24, 0, 0.32, 0.24, 0xf7f6f0));
g.add(vbox(0.07, 0.22, 0.06, -0.07, 0.50, 0.22, 0xf7f6f0));
g.add(vbox(0.07, 0.22, 0.06, 0.07, 0.50, 0.22, 0xf7f6f0));
g.add(vbox(0.10, 0.10, 0.10, 0, 0.22, -0.24, 0xffffff));
return g;
}
function makeBird() {
const g = new THREE.Group();
g.add(vbox(0.26, 0.22, 0.42, 0, 0, 0, 0x3f7fd6));
g.add(vbox(0.20, 0.20, 0.20, 0, 0.08, 0.26, 0x63a4ee));
g.add(vbox(0.08, 0.08, 0.12, 0, 0.05, 0.38, 0xffb545));
const wl = new THREE.Group(); wl.position.set(-0.13, 0.04, 0);
wl.add(vbox(0.42, 0.05, 0.22, -0.21, 0, 0, 0x2f6bb8)); g.add(wl);
const wr = new THREE.Group(); wr.position.set(0.13, 0.04, 0);
wr.add(vbox(0.42, 0.05, 0.22, 0.21, 0, 0, 0x2f6bb8)); g.add(wr);
g.userData.wings = [wl, wr];
return g;
}
const kinds = [makeBoar, makeBoar, makeBoar, makeBoar, makeRabbit, makeRabbit, makeRabbit,
makeRabbit, makeRabbit, makeRabbit, makeBird, makeBird, makeBird, makeBird];
function randomLandTile(from) {
for (let tries = 0; tries < 200; tries++) {
const i = Math.floor(Math.random() * N), j = Math.floor(Math.random() * N);
if (tiles[i * N + j].type === 'water') continue;
if (from) {
const d = Math.hypot(i - from.i, j - from.j);
if (d > 14) continue;
}
return tiles[i * N + j];
}
return tiles[Math.floor(Math.random() * tiles.length)];
}
kinds.forEach((fn, k) => {
const obj = fn();
const t = randomLandTile(null);
obj.position.set(t.center.x + (Math.random() - 0.5) * 0.6, t.levels, t.center.z + (Math.random() - 0.5) * 0.6);
scene.add(obj);
creatures.push({
obj, kind: k, target: randomLandTile(t),
speed: 0.9 + Math.random() * 1.4,
phase: Math.random() * Math.PI * 2,
flying: k >= 10,
ground: t
});
});
/* ------------------------------------------------------------------ *
* SCOUT MOVEMENT (A* over land tiles)
* ------------------------------------------------------------------ */
function idxOf(i, j) { return i * N + j; }
function findPath(si, sj, ti, tj) {
if (si === ti && sj === tj) return [];
const size = N * N;
const g = new Float32Array(size).fill(Infinity);
const f = new Float32Array(size).fill(Infinity);
const prev = new Int32Array(size).fill(-1);
const closed = new Uint8Array(size);
const open = [];
const H = (i, j) => Math.hypot(i - ti, j - tj);
const start = idxOf(si, sj), goal = idxOf(ti, tj);
g[start] = 0; f[start] = H(si, sj); open.push(start);
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [1, -1], [-1, 1], [-1, -1]];
let guard = 0;
while (open.length && guard++ < 6000) {
let bi = 0;
for (let k = 1; k < open.length; k++) if (f[open[k]] < f[open[bi]]) bi = k;
const cur = open.splice(bi, 1)[0];
if (cur === goal) break;
closed[cur] = 1;
const ci = (cur / N) | 0, cj = cur % N;
for (const [di, dj] of dirs) {
const ni = ci + di, nj = cj + dj;
if (ni < 0 || nj < 0 || ni >= N || nj >= N) continue;
if (tiles[idxOf(ni, nj)].type === 'water') continue;
if (di && dj && (tiles[idxOf(ci, nj)].type === 'water' || tiles[idxOf(ni, cj)].type === 'water')) continue;
const ni2 = idxOf(ni, nj);
if (closed[ni2]) continue;
const ng = g[cur] + (di && dj ? 1.4142 : 1);
if (ng < g[ni2]) {
g[ni2] = ng; f[ni2] = ng + H(ni, nj); prev[ni2] = cur;
if (!open.includes(ni2)) open.push(ni2);
}
}
}
if (prev[goal] === -1 && goal !== start) return null;
const path = [];
let cur = goal;
while (cur !== start && cur !== -1) { path.push(cur); cur = prev[cur]; }
path.reverse();
return path;
}
function tileOf(x, z) {
const j = Math.floor(x - ORIGIN), i = Math.floor(z - ORIGIN);
if (i < 0 || j < 0 || i >= N || j >= N) return null;
return { i, j, t: tiles[idxOf(i, j)] };
}
function angleLerp(a, b, t) {
let d = ((b - a + Math.PI) % (Math.PI * 2)) - Math.PI;
if (d < -Math.PI) d += Math.PI * 2;
return a + d * t;
}
/* place scout on a land tile near the middle */
let scoutTile;
outer:
for (let r = 0; r < N; r++) {
for (let i = N / 2 - r; i <= N / 2 + r; i++) {
for (let j = N / 2 - r; j <= N / 2 + r; j++) {
if (i < 0 || j < 0 || i >= N || j >= N) continue;
if (tiles[idxOf(i, j)].type !== 'water') { scoutTile = { i, j }; break outer; }
}
}
}
scout.position.set(ORIGIN + scoutTile.j + 0.5, 0, ORIGIN + scoutTile.i + 0.5);
scout.rotation.y = 0.6;
let path = [], pathIdx = 0, idleTimer = 0.4, manualHold = 0, paused = false;
function setDestination(i, j) {
const here = tileOf(scout.position.x, scout.position.z);
if (!here) return false;
const p = findPath(here.i, here.j, i, j);
if (p === null) return false;
path = p; pathIdx = 0; idleTimer = 0; manualHold = 5;
return true;
}
function pickPatrolTarget() {
const here = tileOf(scout.position.x, scout.position.z);
if (!here) return;
let tries = 0;
while (tries++ < 40) {
const i = Math.max(0, Math.min(N - 1, here.i + Math.round((Math.random() - 0.5) * 10)));
const j = Math.max(0, Math.min(N - 1, here.j + Math.round((Math.random() - 0.5) * 10)));
if (tiles[idxOf(i, j)].type === 'water') continue;
const p = findPath(here.i, here.j, i, j);
if (p && p.length) { path = p; pathIdx = 0; idleTimer = 0; return; }
}
}
function updateScout(dt, time) {
if (!paused) {
if (pathIdx >= path.length) {
if (idleTimer > 0) idleTimer -= dt;
else if (autoPatrol.checked && manualHold <= 0) pickPatrolTarget();
} else {
const wp = tiles[path[pathIdx]].center;
const dx = wp.x - scout.position.x, dz = wp.z - scout.position.z;
const d = Math.hypot(dx, dz);
const step = SCOUT_SPEED * dt;
if (d <= step) {
scout.position.x = wp.x; scout.position.z = wp.z;
pathIdx++;
if (pathIdx >= path.length) idleTimer = 0.7 + Math.random() * 0.8;
} else {
scout.position.x += dx / d * step;
scout.position.z += dz / d * step;
scout.rotation.y = angleLerp(scout.rotation.y, Math.atan2(dx, dz), Math.min(1, dt * 12));
}
}
if (manualHold > 0) manualHold -= dt;
}
const moving = pathIdx < path.length && !paused;
const swing = moving ? Math.sin(time * 9) * 0.42 : 0;
legL.rotation.x = swing; legR.rotation.x = -swing;
armL.rotation.x = -swing * 0.7; armR.rotation.x = swing * 0.7;
scout.position.y = moving ? Math.abs(Math.sin(time * 9)) * 0.06 : 0;
// stand on terrain
const here = tileOf(scout.position.x, scout.position.z);
const base = here ? (here.t.type === 'water' ? 0.24 : here.t.levels) : 0;
scout.position.y += base;
}
/* ------------------------------------------------------------------ *
* CREATURE BEHAVIOUR + VISIBILITY CULLING
* ------------------------------------------------------------------ */
function updateCreatures(dt, time) {
for (const c of creatures) {
const p = c.obj.position;
const dx = c.target.center.x - p.x, dz = c.target.center.z - p.z;
const d = Math.hypot(dx, dz);
if (d < 0.5) {
c.target = randomLandTile(c.ground);
} else {
const step = c.speed * dt;
p.x += dx / d * step; p.z += dz / d * step;
c.obj.rotation.y = angleLerp(c.obj.rotation.y, Math.atan2(dx, dz), Math.min(1, dt * 6));
}
const tt = tileOf(p.x, p.z);
const groundY = tt ? (tt.t.type === 'water' ? 0.24 : tt.t.levels) : 0;
if (c.flying) {
p.y = groundY + 3.1 + Math.sin(time * 1.7 + c.phase) * 0.45;
const flap = Math.sin(time * 12 + c.phase) * 0.85;
c.obj.userData.wings[0].rotation.z = flap;
c.obj.userData.wings[1].rotation.z = -flap;
} else {
p.y = groundY + (c.kind >= 4 && c.kind < 10 ? Math.abs(Math.sin(time * 4 + c.phase)) * 0.18 : 0);
}
}
}
/* ------------------------------------------------------------------ *
* VISIBILITY (the core rule)
* ------------------------------------------------------------------ */
let objectsInView = 0;
function updateVisibility() {
let changed = false;
const sx = scout.position.x, sz = scout.position.z;
const i0 = Math.max(0, Math.floor(sz - RADIUS - ORIGIN));
const i1 = Math.min(N - 1, Math.floor(sz + RADIUS - ORIGIN));
const j0 = Math.max(0, Math.floor(sx - RADIUS - ORIGIN));
const j1 = Math.min(N - 1, Math.floor(sx + RADIUS - ORIGIN));
for (let i = i0; i <= i1; i++) {
for (let j = j0; j <= j1; j++) {
const idx = idxOf(i, j);
const t = tiles[idx];
const d = Math.hypot(t.center.x - sx, t.center.z - sz);
const vis = d <= RADIUS ? 1 : 0;
if (vis && !prevVis[idx]) {
changed = true;
if (!discovered[idx]) { discovered[idx] = 1; discoveredCount++; }
} else if (!vis && prevVis[idx]) changed = true;
prevVis[idx] = vis;
}
}
if (changed) rebuildTerrain();
// moving objects: shown ONLY while inside the radius
objectsInView = 0;
for (const c of creatures) {
const d = Math.hypot(c.obj.position.x - sx, c.obj.position.z - sz);
const inView = d <= RADIUS;
c.obj.visible = inView;
if (inView) objectsInView++;
}
}
/* ------------------------------------------------------------------ *
* RADIUS RING + HOVER MARKER
* ------------------------------------------------------------------ */
const ring = new THREE.Mesh(
new THREE.RingGeometry(RADIUS - 0.07, RADIUS + 0.07, 128),
new THREE.MeshBasicMaterial({ color: 0x63e0ff, transparent: true, opacity: 0.45, side: THREE.DoubleSide, depthTest: false })
);
ring.rotation.x = -Math.PI / 2;
ring.renderOrder = 999;
scene.add(ring);
const hoverBox = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.BoxGeometry(1, 1, 1)),
new THREE.LineBasicMaterial({ color: 0x7ff0ff, transparent: true, opacity: 0.85, depthTest: false })
);
hoverBox.renderOrder = 998;
hoverBox.visible = false;
scene.add(hoverBox);
/* ------------------------------------------------------------------ *
* INPUT : custom camera controls + click-to-move
* ------------------------------------------------------------------ */
const dom = renderer.domElement;
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
const groundPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
const hitPoint = new THREE.Vector3();
const keys = {};
let dragging = false, dragBtn = -1, lastX = 0, lastY = 0, moved = 0;
function pointerToNDC(e) {
const r = dom.getBoundingClientRect();
mouse.x = ((e.clientX - r.left) / r.width) * 2 - 1;
mouse.y = -((e.clientY - r.top) / r.height) * 2 + 1;
}
function planeHit() {
raycaster.setFromCamera(mouse, camera);
return raycaster.ray.intersectPlane(groundPlane, hitPoint) ? hitPoint : null;
}
dom.addEventListener('contextmenu', e => e.preventDefault());
dom.addEventListener('pointerdown', e => {
dragging = true; dragBtn = e.button; lastX = e.clientX; lastY = e.clientY; moved = 0;
dom.setPointerCapture(e.pointerId);
});
dom.addEventListener('pointermove', e => {
pointerToNDC(e);
if (dragging) {
const dx = e.clientX - lastX, dy = e.clientY - lastY;
moved += Math.abs(dx) + Math.abs(dy);
lastX = e.clientX; lastY = e.clientY;
if (dragBtn === 2 || e.shiftKey) {
// pan
const right = new THREE.Vector3(Math.cos(cam.az), 0, -Math.sin(cam.az));
const fwd = new THREE.Vector3(-Math.sin(cam.az), 0, -Math.cos(cam.az));
const k = cam.dist * 0.0016;
cam.target.addScaledVector(right, -dx * k).addScaledVector(fwd, -dy * k);
clampTarget();
} else {
cam.az -= dx * 0.005;
cam.pol = Math.max(0.12, Math.min(1.45, cam.pol - dy * 0.004));
}
} else {
// hover marker
const p = planeHit();
if (p) {
const tt = tileOf(p.x, p.z);
if (tt) {
hoverBox.visible = true;
hoverBox.position.set(tt.t.center.x, tt.t.levels + 0.5, tt.t.center.z);
} else hoverBox.visible = false;
} else hoverBox.visible = false;
}
});
dom.addEventListener('pointerup', e => {
if (dragging && moved < 6 && dragBtn === 0) {
pointerToNDC(e);
const p = planeHit();
if (p) {
const tt = tileOf(p.x, p.z);
if (!tt) setStatus('outside the surveyed region');
else if (tt.t.type === 'water') setStatus('scout cannot cross water');
else if (setDestination(tt.i, tt.j)) setStatus(`moving to tile ${tt.i},${tt.j}`);
else setStatus('no land route found');
}
}
dragging = false; dragBtn = -1;
});
dom.addEventListener('wheel', e => {
e.preventDefault();
cam.dist = Math.max(6, Math.min(85, cam.dist * Math.exp(e.deltaY * 0.0011)));
}, { passive: false });
function clampTarget() {
const lim = N * 0.55;
cam.target.x = Math.max(-lim, Math.min(lim, cam.target.x));
cam.target.z = Math.max(-lim, Math.min(lim, cam.target.z));
cam.target.y = 1;
}
window.addEventListener('keydown', e => {
const k = e.key.toLowerCase();
keys[k] = true;
if (k === ' ') { paused = !paused; setStatus(paused ? 'scout paused' : 'scout moving'); e.preventDefault(); }
if (k === 'r') resetExploration();
if (k === 'q') cam.az -= 0.18;
if (k === 'e') cam.az += 0.18;
});
window.addEventListener('keyup', e => { keys[e.key.toLowerCase()] = false; });
function updateKeyPan(dt) {
const right = new THREE.Vector3(Math.cos(cam.az), 0, -Math.sin(cam.az));
const fwd = new THREE.Vector3(-Math.sin(cam.az), 0, -Math.cos(cam.az));
const k = cam.dist * 0.9 * dt;
let used = false;
if (keys['a'] || keys['arrowleft']) { cam.target.addScaledVector(right, -k); used = true; }
if (keys['d'] || keys['arrowright']) { cam.target.addScaledVector(right, k); used = true; }
if (keys['w'] || keys['arrowup']) { cam.target.addScaledVector(fwd, k); used = true; }
if (keys['s'] || keys['arrowdown']) { cam.target.addScaledVector(fwd, -k); used = true; }
if (used) clampTarget();
}
/* ------------------------------------------------------------------ *
* HUD WIRING
* ------------------------------------------------------------------ */
const radSlider = document.getElementById('radSlider');
const spdSlider = document.getElementById('spdSlider');
const autoPatrol = document.getElementById('autoPatrol');
const showRing = document.getElementById('showRing');
const showMemory = document.getElementById('showMemory');
const statusEl = document.getElementById('status');
let statusTimer = 0;
function setStatus(msg) { statusEl.textContent = msg; statusTimer = 2.4; }
radSlider.addEventListener('input', () => {
RADIUS = parseFloat(radSlider.value);
document.getElementById('radVal').textContent = RADIUS.toFixed(1);
document.getElementById('radVal2').textContent = RADIUS.toFixed(1);
ring.geometry.dispose();
ring.geometry = new THREE.RingGeometry(Math.max(0.05, RADIUS - 0.07), RADIUS + 0.07, 128);
prevVis.fill(0); // force full re-evaluation of the radius
rebuildTerrain();
});
spdSlider.addEventListener('input', () => {
SCOUT_SPEED = parseFloat(spdSlider.value);
document.getElementById('spdVal').textContent = SCOUT_SPEED.toFixed(1);
});
showRing.addEventListener('change', () => { ring.visible = showRing.checked; });
showMemory.addEventListener('change', () => { memMesh.visible = showMemory.checked; });
document.getElementById('resetBtn').addEventListener('click', resetExploration);
function resetExploration() {
discovered.fill(0); prevVis.fill(0); discoveredCount = 0;
rebuildTerrain();
setStatus('exploration reset');
}
/* minimap */
const mm = document.getElementById('minimap');
const mctx = mm.getContext('2d');
function drawMinimap() {
const S = mm.width, cell = S / N;
mctx.fillStyle = '#070b11'; mctx.fillRect(0, 0, S, S);
for (let i = 0; i < N; i++) {
for (let j = 0; j < N; j++) {
const idx = idxOf(i, j), t = tiles[idx];
if (prevVis[idx]) {
mctx.fillStyle = t.cssBright;
} else if (discovered[idx]) {
mctx.fillStyle = t.cssDim;
} else continue;
mctx.fillRect(j * cell, i * cell, Math.ceil(cell), Math.ceil(cell));
}
}
// radius circle
const sx = scout.position.x - ORIGIN, sz = scout.position.z - ORIGIN;
mctx.strokeStyle = 'rgba(99,224,255,.75)'; mctx.lineWidth = 1.2;
mctx.beginPath();
mctx.arc(sx * cell, sz * cell, RADIUS * cell, 0, Math.PI * 2);
mctx.stroke();
// creatures that are currently visible
mctx.fillStyle = '#ffc46b';
for (const c of creatures) {
if (!c.obj.visible) continue;
const cx = c.obj.position.x - ORIGIN, cz = c.obj.position.z - ORIGIN;
mctx.beginPath(); mctx.arc(cx * cell, cz * cell, 2.1, 0, Math.PI * 2); mctx.fill();
}
// scout
mctx.fillStyle = '#ffffff';
mctx.beginPath(); mctx.arc(sx * cell, sz * cell, 3.2, 0, Math.PI * 2); mctx.fill();
mctx.strokeStyle = '#63e0ff'; mctx.lineWidth = 1.4; mctx.stroke();
// heading
mctx.strokeStyle = '#ffffff'; mctx.lineWidth = 1.6;
mctx.beginPath();
mctx.moveTo(sx * cell, sz * cell);
mctx.lineTo((sx + Math.sin(scout.rotation.y) * 1.4) * cell, (sz + Math.cos(scout.rotation.y) * 1.4) * cell);
mctx.stroke();
}
/* ------------------------------------------------------------------ *
* MAIN LOOP
* ------------------------------------------------------------------ */
const clock = new THREE.Clock();
let time = 0, hudAcc = 0, fpsAcc = 0, fpsFrames = 0, fps = 0;
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
time += dt;
updateKeyPan(dt);
updateScout(dt, time);
updateCreatures(dt, time);
updateVisibility();
ring.position.set(scout.position.x, 0.06, scout.position.z);
ring.visible = showRing.checked;
updateCamera();
renderer.render(scene, camera);
fpsAcc += dt; fpsFrames++;
if (fpsAcc > 0.5) { fps = Math.round(fpsFrames / fpsAcc); fpsAcc = 0; fpsFrames = 0; }
hudAcc += dt;
if (hudAcc > 0.1) {
hudAcc = 0;
const here = tileOf(scout.position.x, scout.position.z);
document.getElementById('sDisc').textContent = `${discoveredCount} / ${N * N}`;
document.getElementById('sVis').textContent = String(visList.length);
document.getElementById('sObj').textContent = `${objectsInView} / ${creatures.length}`;
document.getElementById('sPos').textContent = here ? `${here.i}, ${here.j}` : '–';
document.getElementById('sFps').textContent = String(fps);
drawMinimap();
}
if (statusTimer > 0) {
statusTimer -= dt;
if (statusTimer <= 0) statusEl.textContent = '';
}
}
animate();
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
</script>
</body>
</html>
```