Prompt specification
Build or customize the Three.js 3D scene "Estuary mangrove nursery fringe" 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: Estuary mangrove nursery fringe
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/estuary-mangrove-nursery-fringe-x0751
Scene Description Prompt:
A voxel mangrove nursery with mudflats, channels, and small fish; changing tides reveal connected aquatic spaces. Three.js from cdnjs, one HTML file.
Working Three.js Starter (estuary-mangrove-nursery-fringe-x0751):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#dce8df">
<title>Voxel Mangrove Nursery</title>
<style>
:root {
--ink: #173b35;
--muted: #56716a;
--paper: rgba(246, 249, 240, 0.82);
--line: rgba(28, 73, 63, 0.16);
--green: #2d6b55;
--aqua: #42a9a0;
--shadow: 0 18px 55px rgba(31, 65, 56, 0.14);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dce8df;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body::after {
content: "";
position: fixed;
inset: 0;
z-index: 2;
pointer-events: none;
opacity: 0.13;
background-image:
radial-gradient(circle at 20% 30%, rgba(255,255,255,.8) 0 1px, transparent 1px),
radial-gradient(circle at 70% 60%, rgba(20,55,45,.35) 0 1px, transparent 1px);
background-size: 8px 8px, 11px 11px;
mix-blend-mode: soft-light;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
outline: none;
}
#scene:active {
cursor: grabbing;
}
.ui {
position: fixed;
z-index: 10;
}
header {
top: 24px;
left: 24px;
width: min(360px, calc(100vw - 48px));
pointer-events: none;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 12px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.2em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 24px;
height: 2px;
background: var(--aqua);
}
h1 {
margin: 0;
font-size: clamp(40px, 5vw, 68px);
font-weight: 760;
line-height: 0.87;
letter-spacing: -0.065em;
text-transform: uppercase;
}
h1 span {
color: var(--green);
font-weight: 420;
}
header p {
max-width: 315px;
margin: 18px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.6;
}
.card {
border: 1px solid var(--line);
border-radius: 20px;
background: var(--paper);
box-shadow: var(--shadow);
backdrop-filter: blur(18px) saturate(1.15);
-webkit-backdrop-filter: blur(18px) saturate(1.15);
}
#tide-panel {
top: 24px;
right: 24px;
width: 326px;
padding: 18px;
}
.panel-head,
.level-row,
.scale-row,
.button-row,
.legend-head {
display: flex;
align-items: center;
justify-content: space-between;
}
.panel-title {
display: flex;
align-items: center;
gap: 9px;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.live-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--aqua);
box-shadow: 0 0 0 5px rgba(66, 169, 160, 0.12);
animation: pulse 2s infinite;
}
@keyframes pulse {
50% {
box-shadow: 0 0 0 8px rgba(66, 169, 160, 0.03);
}
}
#tide-toggle {
width: 34px;
height: 34px;
padding: 0;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.5);
color: var(--ink);
font-size: 13px;
cursor: pointer;
}
.level-row {
margin: 22px 0 13px;
align-items: flex-end;
}
#tide-value {
display: block;
font-size: 38px;
font-weight: 720;
letter-spacing: -0.055em;
line-height: 1;
}
#tide-state {
display: inline-block;
margin-bottom: 5px;
padding: 5px 8px;
border-radius: 8px;
background: rgba(66, 169, 160, 0.12);
color: #287970;
font-size: 9px;
font-weight: 900;
letter-spacing: 0.14em;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 8px 0 0;
appearance: none;
border-radius: 999px;
outline: none;
background:
linear-gradient(90deg,
var(--aqua) 0%,
var(--aqua) var(--range, 50%),
rgba(23, 59, 53, 0.12) var(--range, 50%),
rgba(23, 59, 53, 0.12) 100%);
cursor: ew-resize;
}
input[type="range"]::-webkit-slider-thumb {
width: 18px;
height: 18px;
appearance: none;
border: 4px solid #f4f8ef;
border-radius: 50%;
background: var(--green);
box-shadow: 0 3px 12px rgba(23, 59, 53, 0.25);
}
input[type="range"]::-moz-range-thumb {
width: 12px;
height: 12px;
border: 4px solid #f4f8ef;
border-radius: 50%;
background: var(--green);
box-shadow: 0 3px 12px rgba(23, 59, 53, 0.25);
}
.scale-row {
margin-top: 9px;
color: #71857f;
font-size: 9px;
font-weight: 750;
letter-spacing: 0.13em;
}
.button-row {
margin-top: 17px;
gap: 10px;
}
.button-row button {
flex: 1;
padding: 11px 12px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.48);
color: var(--ink);
font: inherit;
font-size: 11px;
font-weight: 750;
cursor: pointer;
transition: transform .2s, background .2s;
}
.button-row button:hover {
transform: translateY(-1px);
background: rgba(255, 255, 255, 0.82);
}
.button-row button:first-child {
background: var(--green);
color: #f4f8ef;
border-color: var(--green);
}
#legend {
left: 24px;
bottom: 24px;
width: 260px;
padding: 16px 18px;
}
.legend-head {
margin-bottom: 12px;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.legend-items {
display: grid;
gap: 9px;
}
.legend-item {
display: flex;
align-items: center;
gap: 10px;
color: var(--muted);
font-size: 11px;
}
.swatch {
width: 13px;
height: 13px;
border-radius: 4px;
box-shadow: inset 0 0 0 1px rgba(0,0,0,.08);
}
#controls {
right: 24px;
bottom: 24px;
padding: 12px 14px;
display: flex;
align-items: center;
gap: 13px;
}
.control-copy {
color: var(--muted);
font-size: 9px;
font-weight: 760;
letter-spacing: 0.09em;
line-height: 1.7;
text-transform: uppercase;
}
#reset {
width: 34px;
height: 34px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, .58);
color: var(--ink);
cursor: pointer;
font-size: 17px;
}
#loading {
position: fixed;
inset: 0;
z-index: 100;
display: grid;
place-items: center;
background: #dce8df;
transition: opacity .6s, visibility .6s;
}
#loading.hidden {
opacity: 0;
visibility: hidden;
}
.loader {
display: grid;
justify-items: center;
gap: 16px;
color: var(--green);
font-size: 10px;
font-weight: 850;
letter-spacing: .2em;
text-transform: uppercase;
}
.loader-bars {
display: flex;
gap: 5px;
align-items: flex-end;
height: 32px;
}
.loader-bars i {
display: block;
width: 7px;
height: 12px;
background: var(--green);
animation: bars 1s ease-in-out infinite alternate;
}
.loader-bars i:nth-child(2) { animation-delay: .15s; }
.loader-bars i:nth-child(3) { animation-delay: .3s; }
@keyframes bars {
to { height: 32px; background: var(--aqua); }
}
@media (max-width: 720px) {
header {
top: 14px;
left: 14px;
width: calc(100vw - 28px);
}
h1 {
font-size: 37px;
}
header p,
#legend,
#controls {
display: none;
}
#tide-panel {
top: auto;
right: 14px;
bottom: 14px;
width: calc(100vw - 28px);
padding: 15px;
}
#tide-value {
font-size: 31px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel mangrove nursery"></canvas>
<header class="ui">
<div class="eyebrow">Coastal systems · live diorama</div>
<h1>Mangrove<br><span>Nursery</span></h1>
<p>
A tidal voxel study of connected channels, exposed mudflats,
juvenile mangroves, and nursery fish.
</p>
</header>
<section id="tide-panel" class="ui card" aria-label="Tide controls">
<div class="panel-head">
<div class="panel-title">
<span class="live-dot"></span>
Live tidal system
</div>
<button id="tide-toggle" type="button" title="Pause tide" aria-label="Pause tide">Ⅱ</button>
</div>
<div class="level-row">
<span id="tide-value" aria-live="polite">+0.00 m</span>
<span id="tide-state">RISING</span>
</div>
<input id="tide-slider" type="range" min="-26" max="46" value="0"
aria-label="Water level">
<div class="scale-row">
<span>LOW WATER</span>
<span>HIGH WATER</span>
</div>
<div class="button-row">
<button id="shift-tide" type="button">Shift tide</button>
<button id="view-top" type="button">Top view</button>
</div>
</section>
<section id="legend" class="ui card" aria-label="Scene legend">
<div class="legend-head">Nursery key</div>
<div class="legend-items">
<div class="legend-item">
<span class="swatch" style="background:#4f7547"></span>
Juvenile mangrove canopy
</div>
<div class="legend-item">
<span class="swatch" style="background:#9a7952"></span>
Exposed tidal mudflat
</div>
<div class="legend-item">
<span class="swatch" style="background:#3f9d98"></span>
Connected nursery channel
</div>
<div class="legend-item">
<span class="swatch" style="background:#e3a454"></span>
Small nursery fish
</div>
</div>
</section>
<section id="controls" class="ui card" aria-label="Camera controls">
<div class="control-copy">
Drag · orbit<br>
Shift drag · pan<br>
Scroll · zoom
</div>
<button id="reset" type="button" title="Reset camera" aria-label="Reset camera">↺</button>
</section>
<div id="loading">
<div class="loader">
<div class="loader-bars"><i></i><i></i><i></i></div>
Growing the nursery
</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Scene and renderer
// ------------------------------------------------------------
const canvas = document.querySelector("#scene");
const loading = document.querySelector("#loading");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.75));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdce8df);
scene.fog = new THREE.Fog(0xdce8df, 43, 86);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
150
);
const hemisphere = new THREE.HemisphereLight(0xf1f6e8, 0x50685c, 2.25);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff2cc, 3.25);
sun.position.set(-13, 24, 11);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -23;
sun.shadow.camera.right = 23;
sun.shadow.camera.top = 23;
sun.shadow.camera.bottom = -23;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 65;
sun.shadow.bias = -0.00035;
sun.shadow.normalBias = 0.035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x8fc8c4, 0.65);
fill.position.set(16, 8, -13);
scene.add(fill);
const unitBox = new THREE.BoxGeometry(1, 1, 1);
const tempObject = new THREE.Object3D();
const tempColor = new THREE.Color();
// ------------------------------------------------------------
// Deterministic helpers
// ------------------------------------------------------------
function fract(value) {
return value - Math.floor(value);
}
function hash(x, z) {
return fract(Math.sin(x * 127.1 + z * 311.7) * 43758.5453123);
}
function smoothstep(min, max, value) {
const t = THREE.MathUtils.clamp((value - min) / (max - min), 0, 1);
return t * t * (3 - 2 * t);
}
function lerp(a, b, t) {
return a + (b - a) * t;
}
function valueNoise(x, z) {
const ix = Math.floor(x);
const iz = Math.floor(z);
const fx = x - ix;
const fz = z - iz;
const ux = fx * fx * (3 - 2 * fx);
const uz = fz * fz * (3 - 2 * fz);
const a = hash(ix, iz);
const b = hash(ix + 1, iz);
const c = hash(ix, iz + 1);
const d = hash(ix + 1, iz + 1);
return lerp(
lerp(a, b, ux),
lerp(c, d, ux),
uz
);
}
function distanceToSegment(px, pz, ax, az, bx, bz) {
const dx = bx - ax;
const dz = bz - az;
const lengthSquared = dx * dx + dz * dz;
const t = lengthSquared === 0
? 0
: THREE.MathUtils.clamp(
((px - ax) * dx + (pz - az) * dz) / lengthSquared,
0,
1
);
const qx = ax + t * dx;
const qz = az + t * dz;
return Math.hypot(px - qx, pz - qz);
}
// ------------------------------------------------------------
// Channel network and terrain
// ------------------------------------------------------------
const GRID = 31;
const CELL = 1.08;
const HALF = (GRID - 1) * 0.5 * CELL;
const channelDefinitions = [
{
width: 2.05,
points: [
[-13.0, -6.4],
[-8.6, -6.0],
[-4.2, -3.2],
[0.2, -4.0],
[5.0, -1.2],
[9.7, 1.0],
[13.0, 0.1]
]
},
{
width: 1.72,
points: [
[-8.6, -6.0],
[-8.0, -0.8],
[-6.4, 5.2],
[-7.8, 12.4]
]
},
{
width: 1.60,
points: [
[0.2, -4.0],
[1.3, 1.8],
[3.2, 7.1],
[2.0, 13.0]
]
},
{
width: 1.52,
points: [
[5.0, -1.2],
[6.9, -5.8],
[10.5, -9.0],
[13.0, -8.1]
]
},
{
width: 1.38,
points: [
[-4.2, -3.2],
[-3.1, -7.6],
[-1.2, -13.0]
]
}
];
const channels = [];
const channelSegments = [];
for (const definition of channelDefinitions) {
const points = definition.points.map(
([x, z]) => new THREE.Vector3(x, 0, z)
);
for (let i = 0; i < points.length - 1; i++) {
channels.push({
a: points[i],
b: points[i + 1],
width: definition.width
});
channelSegments.push({
ax: points[i].x,
az: points[i].z,
bx: points[i + 1].x,
bz: points[i + 1].z,
width: definition.width
});
}
}
function channelDistance(x, z) {
let nearest = Infinity;
let width = 1.5;
for (const segment of channels) {
const distance = distanceToSegment(
x, z,
segment.a.x, segment.a.z,
segment.b.x, segment.b.z
);
if (distance < nearest) {
nearest = distance;
width = segment.width;
}
}
return { distance: nearest, width };
}
function terrainHeight(x, z) {
const broad = valueNoise(x * 0.19 + 8, z * 0.19 - 3);
const detail = hash(Math.floor(x), Math.floor(z));
const ripple = Math.sin(x * 0.43 + z * 0.21) * 0.045;
let height = 0.20 + broad * 0.30 + detail * 0.075 + ripple;
const channel = channelDistance(x, z);
const influence = 1 - smoothstep(0.42, channel.width, channel.distance);
const bedHeight = -0.58 + detail * 0.09;
height = lerp(height, bedHeight, influence);
// Raised outer rim keeps the tidal sheet inside the diorama.
const edge = Math.max(Math.abs(x), Math.abs(z));
if (edge > 14.25) {
height = Math.max(height, 0.58);
}
return height;
}
const tiles = [];
for (let j = 0; j < GRID; j++) {
for (let i = 0; i < GRID; i++) {
const x = (i - (GRID - 1) / 2) * CELL;
const z = (j - (GRID - 1) / 2) * CELL;
tiles.push({
i,
j,
x,
z,
h: terrainHeight(x, z),
n: hash(i + 17, j - 9)
});
}
}
function heightAt(i, j) {
if (i < 0 || j < 0 || i >= GRID || j >= GRID) return 0.6;
return tiles[j * GRID + i].h;
}
// Base and distant water shelf.
const plotSize = GRID * CELL;
const base = new THREE.Mesh(
new THREE.BoxGeometry(plotSize + 0.8, 0.9, plotSize + 0.8),
new THREE.MeshStandardMaterial({
color: 0x554b3a,
roughness: 1
})
);
base.position.y = -1.65;
base.receiveShadow = true;
base.castShadow = true;
scene.add(base);
const outerWater = new THREE.Mesh(
new THREE.PlaneGeometry(120, 120),
new THREE.MeshStandardMaterial({
color: 0xa7c7c0,
roughness: 0.95,
metalness: 0
})
);
outerWater.rotation.x = -Math.PI / 2;
outerWater.position.y = -2.12;
outerWater.receiveShadow = true;
scene.add(outerWater);
// Terrain tiles are instanced for a low draw-call count.
const terrainMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.97
});
const terrainMesh = new THREE.InstancedMesh(
unitBox,
terrainMaterial,
tiles.length
);
terrainMesh.castShadow = true;
terrainMesh.receiveShadow = true;
const deepMud = new THREE.Color(0x38574d);
const wetMud = new THREE.Color(0x75654b);
const sandyMud = new THREE.Color(0xa08055);
const bank = new THREE.Color(0x8e9066);
const dryBank = new THREE.Color(0x738057);
tiles.forEach((tile, index) => {
const variation = tile.n * 0.18 - 0.09;
if (tile.h < -0.16) {
tempColor.copy(deepMud).lerp(wetMud, tile.n * 0.6);
} else if (tile.h < 0.13) {
tempColor.copy(wetMud).lerp(sandyMud, 0.35 + tile.n * 0.45);
} else if (tile.h < 0.33) {
tempColor.copy(sandyMud).lerp(bank, tile.n * 0.28);
} else {
tempColor.copy(bank).lerp(dryBank, tile.n);
}
tempColor.offsetHSL(0, 0, variation);
const height = tile.h + 1.25;
tempObject.position.set(tile.x, (tile.h - 1.25) / 2, tile.z);
tempObject.rotation.set(0, 0, 0);
tempObject.scale.set(CELL * 0.988, height, CELL * 0.988);
tempObject.updateMatrix();
terrainMesh.setMatrixAt(index, tempObject.matrix);
terrainMesh.setColorAt(index, tempColor);
});
terrainMesh.instanceMatrix.needsUpdate = true;
terrainMesh.instanceColor.needsUpdate = true;
terrainMesh.computeBoundingSphere();
scene.add(terrainMesh);
// ------------------------------------------------------------
// Static voxel batch system
// ------------------------------------------------------------
const barkEntries = [];
const rootEntries = [];
const canopyEntries = [];
const seedlingStemEntries = [];
const seedlingLeafEntries = [];
function addEntry(list, x, y, z, sx, sy, sz, rotation, color) {
list.push({
x, y, z,
sx, sy, sz,
rotation,
color
});
}
const treeCandidates = tiles
.filter(tile =>
tile.h > 0.335 &&
Math.abs(tile.x) < 13.4 &&
Math.abs(tile.z) < 13.4
)
.sort((a, b) => hash(a.i + 4, a.j - 2) - hash(b.i + 4, b.j - 2));
const treeSites = [];
for (const tile of treeCandidates) {
const separated = treeSites.every(tree =>
Math.hypot(tree.x - tile.x, tree.z - tile.z) > 2.35
);
if (separated) {
treeSites.push(tile);
}
if (treeSites.length >= 22) break;
}
const canopyColors = [
0x426c3f,
0x507c43,
0x628947,
0x71964d,
0x365f3d
];
treeSites.forEach((tree, treeIndex) => {
const baseY = tree.h;
const sizeVariation = 0.88 + hash(tree.i, tree.j) * 0.25;
const rotationOffset = hash(tree.j, tree.i) * Math.PI * 2;
// Stepped trunk.
for (let level = 0; level < 6; level++) {
const width = (0.36 - level * 0.026) * sizeVariation;
const offset = Math.sin(level * 1.7 + rotationOffset) * 0.035;
addEntry(
barkEntries,
tree.x + offset,
baseY + 0.28 + level * 0.52,
tree.z + offset * 0.6,
width,
0.58,
width,
0,
level % 2 ? 0x72503a : 0x684a36
);
}
// Horizontal voxel branches.
for (let branch = 0; branch < 4; branch++) {
const angle = rotationOffset + branch * Math.PI * 0.5 + 0.22;
const radius = 0.33;
addEntry(
barkEntries,
tree.x + Math.sin(angle) * radius,
baseY + 2.16 + branch * 0.075,
tree.z + Math.cos(angle) * radius,
0.19,
0.19,
0.95,
angle,
0x654a36
);
}
// Blocky mangrove canopy.
for (let leaf = 0; leaf < 8; leaf++) {
const angle = leaf * 2.399 + rotationOffset;
const radius = leaf === 0 ? 0 : 0.38 + hash(leaf, treeIndex) * 0.42;
const size = (0.72 + hash(leaf + 3, treeIndex) * 0.42) * sizeVariation;
addEntry(
canopyEntries,
tree.x + Math.sin(angle) * radius,
baseY + 2.76 + hash(leaf + 8, treeIndex) * 0.76,
tree.z + Math.cos(angle) * radius,
size,
size * (0.78 + hash(leaf, treeIndex + 8) * 0.28),
size,
angle * 0.12,
canopyColors[(leaf + treeIndex) % canopyColors.length]
);
}
// Stepped prop roots.
for (let root = 0; root < 5; root++) {
const angle = rotationOffset + root * (Math.PI * 2 / 5) + 0.18;
for (let step = 0; step < 3; step++) {
const radius = 0.24 + step * 0.34;
const rootY = baseY + 0.63 - step * 0.19;
addEntry(
rootEntries,
tree.x + Math.sin(angle) * radius,
rootY,
tree.z + Math.cos(angle) * radius,
0.18,
0.18,
0.39,
angle,
step === 0 ? 0x694b36 : 0x74543c
);
}
}
});
// Small propagules and juvenile seedlings on exposed banks.
const seedlingCandidates = tiles
.filter(tile =>
tile.h > -0.08 &&
tile.h < 0.29 &&
hash(tile.i - 8, tile.j + 13) > 0.69
)
.slice(0, 52);
seedlingCandidates.forEach((tile, index) => {
const height = 0.38 + hash(tile.i, tile.j) * 0.28;
const angle = hash(tile.j, tile.i) * Math.PI * 2;
addEntry(
seedlingStemEntries,
tile.x,
tile.h + height / 2,
tile.z,
0.07,
height,
0.07,
0,
0x6b5438
);
for (let side = 0; side < 2; side++) {
addEntry(
seedlingLeafEntries,
tile.x + Math.sin(angle + side * Math.PI) * 0.12,
tile.h + height * (0.72 + side * 0.12),
tile.z + Math.cos(angle + side * Math.PI) * 0.12,
0.28,
0.11,
0.15,
angle + side * Math.PI * 0.5,
canopyColors[(index + side) % canopyColors.length]
);
}
});
function createBatch(entries, material, castShadow = true) {
const mesh = new THREE.InstancedMesh(unitBox, material, entries.length);
entries.forEach((entry, index) => {
tempObject.position.set(entry.x, entry.y, entry.z);
tempObject.rotation.set(0, entry.rotation, 0);
tempObject.scale.set(entry.sx, entry.sy, entry.sz);
tempObject.updateMatrix();
mesh.setMatrixAt(index, tempObject.matrix);
mesh.setColorAt(index, tempColor.set(entry.color));
});
mesh.instanceMatrix.needsUpdate = true;
if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
mesh.computeBoundingSphere();
scene.add(mesh);
return mesh;
}
createBatch(
barkEntries,
new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 1 })
);
createBatch(
rootEntries,
new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 1 })
);
createBatch(
canopyEntries,
new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.94 })
);
createBatch(
seedlingStemEntries,
new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 1 })
);
createBatch(
seedlingLeafEntries,
new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.95 })
);
// ------------------------------------------------------------
// Submerged channel traces
// ------------------------------------------------------------
const channelLineMaterial = new THREE.LineBasicMaterial({
color: 0x9be6d7,
transparent: true,
opacity: 0.32,
depthWrite: false
});
for (const definition of channelDefinitions) {
const geometry = new THREE.BufferGeometry().setFromPoints(
definition.points.map(([x, z]) => new THREE.Vector3(x, -0.465, z))
);
const line = new THREE.Line(geometry, channelLineMaterial);
line.renderOrder = 1;
scene.add(line);
}
// ------------------------------------------------------------
// Tidal water
// ------------------------------------------------------------
const waterSize = plotSize - 0.25;
const waterGeometry = new THREE.PlaneGeometry(waterSize, waterSize, 36, 36);
waterGeometry.rotateX(-Math.PI / 2);
const waterMaterial = new THREE.MeshPhysicalMaterial({
color: 0x4aa9a2,
roughness: 0.19,
metalness: 0.06,
transparent: true,
opacity: 0.59,
depthWrite: false,
side: THREE.DoubleSide
});
const water = new THREE.Mesh(waterGeometry, waterMaterial);
water.position.y = 0;
water.receiveShadow = true;
water.renderOrder = 2;
scene.add(water);
// Pixelated shoreline markers make changing contours legible.
const shorelineMesh = new THREE.InstancedMesh(
unitBox,
new THREE.MeshBasicMaterial({
color: 0xc1f1df,
transparent: true,
opacity: 0.68,
depthWrite: false
}),
tiles.length
);
shorelineMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
shorelineMesh.count = 0;
shorelineMesh.frustumCulled = false;
shorelineMesh.renderOrder = 3;
scene.add(shorelineMesh);
// ------------------------------------------------------------
// Fish
// ------------------------------------------------------------
const FISH_COUNT = 26;
const fishBody = new THREE.InstancedMesh(
unitBox,
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.54,
metalness: 0.03
}),
FISH_COUNT
);
const fishTail = new THREE.InstancedMesh(
unitBox,
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.6
}),
FISH_COUNT
);
const fishEyes = new THREE.InstancedMesh(
unitBox,
new THREE.MeshBasicMaterial({ color: 0x15251f }),
FISH_COUNT * 2
);
[fishBody, fishTail, fishEyes].forEach(mesh => {
mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
mesh.frustumCulled = false;
scene.add(mesh);
});
const fishColors = [
0xe2a24e,
0xd78342,
0xe5c15d,
0x8fb6ad,
0xc8d5c3
];
const fishData = [];
for (let index = 0; index < FISH_COUNT; index++) {
const segment = channelSegments[index % channelSegments.length];
const color = new THREE.Color(fishColors[index % fishColors.length]);
fishBody.setColorAt(index, color);
fishTail.setColorAt(index, color.clone().multiplyScalar(0.73));
fishData.push({
segment,
phase: hash(index * 3, 8) * Math.PI * 2,
speed: 0.18 + hash(index, 13) * 0.17,
size: 0.72 + hash(index + 2, 7) * 0.55,
bob: hash(index + 5, 3) * Math.PI * 2
});
}
fishBody.instanceColor.needsUpdate = true;
fishTail.instanceColor.needsUpdate = true;
// ------------------------------------------------------------
// Surface foam and current markers
// ------------------------------------------------------------
const FOAM_COUNT = 84;
const foamMesh = new THREE.InstancedMesh(
unitBox,
new THREE.MeshBasicMaterial({
color: 0xd8f4e7,
transparent: true,
opacity: 0.5,
depthWrite: false
}),
FOAM_COUNT
);
foamMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
foamMesh.frustumCulled = false;
foamMesh.renderOrder = 4;
scene.add(foamMesh);
const foamData = [];
for (let index = 0; index < FOAM_COUNT; index++) {
foamData.push({
segment: channelSegments[index % channelSegments.length],
offset: hash(index + 5, index - 3),
drift: 0.018 + hash(index, 2) * 0.023,
size: 0.65 + hash(index + 1, 8) * 0.65
});
}
// ------------------------------------------------------------
// Soft suspended particles
// ------------------------------------------------------------
const pollenCount = 90;
const pollenPositions = new Float32Array(pollenCount * 3);
const pollenBase = [];
for (let index = 0; index < pollenCount; index++) {
const x = (hash(index, 4) - 0.5) * 28;
const y = 1 + hash(index + 2, 7) * 5;
const z = (hash(index + 9, 3) - 0.5) * 28;
pollenPositions[index * 3] = x;
pollenPositions[index * 3 + 1] = y;
pollenPositions[index * 3 + 2] = z;
pollenBase.push({ x, y, z, phase: hash(index, 12) * 6.28 });
}
const pollenGeometry = new THREE.BufferGeometry();
pollenGeometry.setAttribute(
"position",
new THREE.BufferAttribute(pollenPositions, 3)
);
const pollen = new THREE.Points(
pollenGeometry,
new THREE.PointsMaterial({
color: 0xe9efc6,
size: 0.055,
transparent: true,
opacity: 0.55,
depthWrite: false,
sizeAttenuation: true
})
);
scene.add(pollen);
// ------------------------------------------------------------
// Custom camera controls
// ------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, 0.45, 0);
let cameraTheta = 0.68;
let cameraPhi = 0.86;
let cameraRadius = 39;
let cameraMode = "orbit";
const pointers = new Map();
let previousX = 0;
let previousY = 0;
let previousPinch = 0;
function updateCamera() {
const sinPhi = Math.sin(cameraPhi);
camera.position.set(
cameraTarget.x + cameraRadius * sinPhi * Math.sin(cameraTheta),
cameraTarget.y + cameraRadius * Math.cos(cameraPhi),
cameraTarget.z + cameraRadius * sinPhi * Math.cos(cameraTheta)
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraTheta = 0.68;
cameraPhi = 0.86;
cameraRadius = 39;
cameraTarget.set(0, 0.45, 0);
updateCamera();
}
function pinchDistance() {
const values = [...pointers.values()];
if (values.length < 2) return 0;
return Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
}
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("pointerdown", event => {
canvas.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (pointers.size === 1) {
cameraMode = event.shiftKey || event.button === 2 ? "pan" : "orbit";
previousX = event.clientX;
previousY = event.clientY;
} else if (pointers.size === 2) {
previousPinch = pinchDistance();
}
});
canvas.addEventListener("pointermove", event => {
if (!pointers.has(event.pointerId)) return;
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (pointers.size === 1) {
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
if (cameraMode === "orbit") {
cameraTheta -= dx * 0.006;
cameraPhi = THREE.MathUtils.clamp(cameraPhi - dy * 0.005, 0.30, 1.43);
} else {
camera.updateMatrixWorld();
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 0);
const up = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 1);
const panScale = cameraRadius * 0.00135;
cameraTarget.addScaledVector(right, -dx * panScale);
cameraTarget.addScaledVector(up, dy * panScale);
cameraTarget.x = THREE.MathUtils.clamp(cameraTarget.x, -8, 8);
cameraTarget.z = THREE.MathUtils.clamp(cameraTarget.z, -8, 8);
cameraTarget.y = THREE.MathUtils.clamp(cameraTarget.y, -1, 4);
}
previousX = event.clientX;
previousY = event.clientY;
} else if (pointers.size === 2) {
const distance = pinchDistance();
if (distance > 0 && previousPinch > 0) {
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * (previousPinch / distance),
18,
64
);
}
previousPinch = distance;
}
});
function releasePointer(event) {
pointers.delete(event.pointerId);
if (pointers.size === 1) {
const remaining = [...pointers.values()][0];
previousX = remaining.x;
previousY = remaining.y;
cameraMode = "orbit";
} else if (pointers.size === 0) {
previousPinch = 0;
}
}
canvas.addEventListener("pointerup", releasePointer);
canvas.addEventListener("pointercancel", releasePointer);
canvas.addEventListener("lostpointercapture", releasePointer);
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
18,
64
);
}, { passive: false });
canvas.addEventListener("dblclick", resetCamera);
// ------------------------------------------------------------
// Tide UI and state
// ------------------------------------------------------------
const tideSlider = document.querySelector("#tide-slider");
const tideValue = document.querySelector("#tide-value");
const tideState = document.querySelector("#tide-state");
const tideToggle = document.querySelector("#tide-toggle");
const shiftTide = document.querySelector("#shift-tide");
const viewTop = document.querySelector("#view-top");
const resetButton = document.querySelector("#reset");
const TIDE_MIN = -0.26;
const TIDE_MAX = 0.46;
const TIDE_PERIOD = 58;
let tidePhase = 1.95;
let tide = TIDE_MIN + (TIDE_MAX - TIDE_MIN) *
(0.5 - 0.5 * Math.cos(tidePhase));
let tideTarget = tide;
let autoTide = true;
let elapsed = 0;
let frame = 0;
function updateSliderStyle() {
const percentage = ((tide - TIDE_MIN) / (TIDE_MAX - TIDE_MIN)) * 100;
tideSlider.style.setProperty("--range", `${percentage}%`);
}
function setTideFromSlider() {
tideTarget = Number(tideSlider.value) / 100;
autoTide = false;
tideToggle.textContent = "▶";
tideToggle.title = "Resume tide";
tideToggle.setAttribute("aria-label", "Resume tide");
}
tideSlider.addEventListener("input", setTideFromSlider);
tideToggle.addEventListener("click", () => {
if (autoTide) {
autoTide = false;
tideToggle.textContent = "▶";
tideToggle.title = "Resume tide";
tideToggle.setAttribute("aria-label", "Resume tide");
} else {
const normalized = THREE.MathUtils.clamp(
(tide - TIDE_MIN) / (TIDE_MAX - TIDE_MIN),
0,
1
);
tidePhase = Math.acos(1 - 2 * normalized);
autoTide = true;
tideToggle.textContent = "Ⅱ";
tideToggle.title = "Pause tide";
tideToggle.setAttribute("aria-label", "Pause tide");
}
});
shiftTide.addEventListener("click", () => {
const normalized = (tide - TIDE_MIN) / (TIDE_MAX - TIDE_MIN);
const nextLevel = normalized < 0.5 ? TIDE_MAX : TIDE_MIN;
tideTarget = nextLevel;
tideSlider.value = Math.round(nextLevel * 100);
autoTide = false;
tideToggle.textContent = "▶";
tideToggle.title = "Resume tide";
tideToggle.setAttribute("aria-label", "Resume tide");
});
viewTop.addEventListener("click", () => {
cameraTheta = 0;
cameraPhi = 0.31;
cameraRadius = 37;
cameraTarget.set(0, 0.3, 0);
});
resetButton.addEventListener("click", resetCamera);
// ------------------------------------------------------------
// Dynamic geometry updates
// ------------------------------------------------------------
const deepWaterColor = new THREE.Color(0x328d89);
const highWaterColor = new THREE.Color(0x61bcb0);
function updateWater(time) {
const normalized = THREE.MathUtils.clamp(
(tide - TIDE_MIN) / (TIDE_MAX - TIDE_MIN),
0,
1
);
water.position.y = tide;
waterMaterial.color.copy(deepWaterColor).lerp(highWaterColor, normalized);
waterMaterial.opacity = 0.52 + normalized * 0.12;
const positions = waterGeometry.attributes.position;
const amplitude = 0.009 + normalized * 0.009;
for (let index = 0; index < positions.count; index++) {
const x = positions.getX(index);
const z = positions.getZ(index);
const wave =
Math.sin(x * 0.67 + time * 1.05) * amplitude +
Math.cos(z * 0.53 - time * 0.82) * amplitude * 0.58;
positions.setY(index, wave);
}
positions.needsUpdate = true;
if (frame % 5 === 0) {
waterGeometry.computeVertexNormals();
}
}
function updateShoreline() {
let count = 0;
for (const tile of tiles) {
if (Math.abs(tile.h - tide) > 0.047) continue;
const gx = heightAt(tile.i + 1, tile.j) -
heightAt(tile.i - 1, tile.j);
const gz = heightAt(tile.i, tile.j + 1) -
heightAt(tile.i, tile.j - 1);
let tx = -gz;
let tz = gx;
const length = Math.hypot(tx, tz);
if (length < 0.001) {
tx = 1;
tz = 0;
} else {
tx /= length;
tz /= length;
}
tempObject.position.set(tile.x, tide + 0.025, tile.z);
tempObject.rotation.set(0, Math.atan2(tx, tz), 0);
tempObject.scale.set(0.12, 0.022, CELL * 0.78);
tempObject.updateMatrix();
shorelineMesh.setMatrixAt(count, tempObject.matrix);
count++;
}
shorelineMesh.count = count;
shorelineMesh.instanceMatrix.needsUpdate = true;
}
function updateFish(time) {
fishData.forEach((fish, index) => {
const segment = fish.segment;
const travel = 0.5 + 0.5 * Math.sin(time * fish.speed + fish.phase);
const direction = Math.cos(time * fish.speed + fish.phase) >= 0 ? 1 : -1;
const x = lerp(segment.ax, segment.bx, travel);
const z = lerp(segment.az, segment.bz, travel);
const y = tide + 0.095 + Math.sin(time * 2.1 + fish.bob) * 0.035;
const dx = (segment.bx - segment.ax) * direction;
const dz = (segment.bz - segment.az) * direction;
const heading = Math.atan2(dx, dz);
const forwardX = Math.sin(heading);
const forwardZ = Math.cos(heading);
const rightX = Math.cos(heading);
const rightZ = -Math.sin(heading);
const size = fish.size;
tempObject.position.set(x, y, z);
tempObject.rotation.set(0, heading, 0);
tempObject.scale.set(0.22 * size, 0.25 * size, 0.54 * size);
tempObject.updateMatrix();
fishBody.setMatrixAt(index, tempObject.matrix);
tempObject.position.set(
x - forwardX * 0.37 * size,
y,
z - forwardZ * 0.37 * size
);
tempObject.rotation.set(0, heading + Math.sin(time * 7 + index) * 0.18, 0);
tempObject.scale.set(0.36 * size, 0.23 * size, 0.13 * size);
tempObject.updateMatrix();
fishTail.setMatrixAt(index, tempObject.matrix);
for (let side = 0; side < 2; side++) {
const eyeOffset = side === 0 ? 1 : -1;
tempObject.position.set(
x + forwardX * 0.18 * size + rightX * 0.105 * size * eyeOffset,
y + 0.075 * size,
z + forwardZ * 0.18 * size + rightZ * 0.105 * size * eyeOffset
);
tempObject.rotation.set(0, heading, 0);
tempObject.scale.set(0.045 * size, 0.045 * size, 0.045 * size);
tempObject.updateMatrix();
fishEyes.setMatrixAt(index * 2 + side, tempObject.matrix);
}
});
fishBody.instanceMatrix.needsUpdate = true;
fishTail.instanceMatrix.needsUpdate = true;
fishEyes.instanceMatrix.needsUpdate = true;
}
function updateFoam(time) {
foamData.forEach((foam, index) => {
const segment = foam.segment;
const travel = (time * foam.drift + foam.offset) % 1;
const x = lerp(segment.ax, segment.bx, travel);
const z = lerp(segment.az, segment.bz, travel);
const heading = Math.atan2(
segment.bx - segment.ax,
segment.bz - segment.az
);
tempObject.position.set(x, tide + 0.034, z);
tempObject.rotation.set(0, heading, 0);
tempObject.scale.set(
0.055 * foam.size,
0.018,
0.19 * foam.size
);
tempObject.updateMatrix();
foamMesh.setMatrixAt(index, tempObject.matrix);
});
foamMesh.instanceMatrix.needsUpdate = true;
}
function updatePollen(time) {
const positions = pollenGeometry.attributes.position;
pollenBase.forEach((particle, index) => {
positions.setXYZ(
index,
particle.x + Math.sin(time * 0.23 + particle.phase) * 0.18,
particle.y + Math.sin(time * 0.36 + particle.phase) * 0.12,
particle.z + Math.cos(time * 0.19 + particle.phase) * 0.18
);
});
positions.needsUpdate = true;
}
function updateUI() {
const signed = `${tide >= 0 ? "+" : ""}${tide.toFixed(2)} m`;
tideValue.textContent = signed;
if (!autoTide) {
tideState.textContent = "HELD";
} else if (tidePhase < Math.PI) {
tideState.textContent = "RISING";
} else {
tideState.textContent = "FALLING";
}
tideSlider.value = Math.round(tide * 100);
updateSliderStyle();
}
// ------------------------------------------------------------
// Resize and animation
// ------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.75));
renderer.setSize(window.innerWidth, window.innerHeight);
});
let previousTime = performance.now();
function animate(now) {
requestAnimationFrame(animate);
const delta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
elapsed += delta;
frame++;
if (autoTide) {
tidePhase = (tidePhase + delta * Math.PI * 2 / TIDE_PERIOD) %
(Math.PI * 2);
tideTarget = TIDE_MIN + (TIDE_MAX - TIDE_MIN) *
(0.5 - 0.5 * Math.cos(tidePhase));
}
tide += (tideTarget - tide) * (1 - Math.exp(-delta * 4.5));
updateCamera();
updateWater(elapsed);
updateShoreline();
updateFish(elapsed);
updateFoam(elapsed);
updatePollen(elapsed);
if (frame % 4 === 0) {
updateUI();
}
renderer.render(scene, camera);
}
updateCamera();
updateWater(0);
updateShoreline();
updateFish(0);
updateFoam(0);
updatePollen(0);
updateUI();
renderer.render(scene, camera);
loading.classList.add("hidden");
requestAnimationFrame(animate);
</script>
</body>
</html>
```