Prompt specification
Build or customize the Three.js 3D scene "Wetland Loss Under a Toy Coastal Model" 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: Wetland Loss Under a Toy Coastal Model
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/wetland-loss-under-a-toy-coastal-model-x3924
Scene Description Prompt:
Compare low-poly coasts with different wetland extents under identical waves in an explicitly toy model. Use Three.js from cdnjs in standalone HTML.
Working Three.js Starter (wetland-loss-under-a-toy-coastal-model-x3924):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Marsh Attenuation Sandbox</title>
<style>
:root {
color-scheme: dark;
--bg: #07151c;
--panel: rgba(8, 24, 31, 0.78);
--line: rgba(180, 226, 224, 0.18);
--text: #e9f4ef;
--muted: #9cb6b6;
--aqua: #73e1d2;
--orange: #ffb36a;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, sans-serif;
}
button, input { font: inherit; }
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#viewport canvas:active { cursor: grabbing; }
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
linear-gradient(to bottom, rgba(3, 12, 17, 0.68), transparent 20%),
linear-gradient(to top, rgba(3, 12, 17, 0.55), transparent 24%);
z-index: 1;
}
.topbar {
position: fixed;
z-index: 10;
top: 0;
left: 0;
right: 0;
min-height: 64px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
padding: 10px 18px;
background: rgba(5, 17, 23, 0.88);
border-bottom: 1px solid var(--line);
backdrop-filter: blur(16px);
}
.brand {
display: grid;
grid-template-columns: auto 1fr;
column-gap: 10px;
align-items: center;
min-width: 250px;
}
.brand .code {
grid-row: 1 / 3;
padding: 8px 9px;
color: #092028;
background: var(--aqua);
border-radius: 5px;
font-size: 11px;
font-weight: 900;
letter-spacing: 0.08em;
}
.brand strong {
font-size: 14px;
letter-spacing: 0.015em;
}
.brand small {
color: var(--muted);
font-size: 11px;
}
.global-controls {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 13px;
flex-wrap: wrap;
}
.control {
width: 150px;
}
.control label {
display: flex;
justify-content: space-between;
gap: 10px;
margin-bottom: 4px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.control output {
color: var(--text);
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
accent-color: var(--aqua);
cursor: pointer;
}
.button-row {
display: flex;
gap: 6px;
align-items: center;
}
button {
color: var(--text);
background: rgba(255, 255, 255, 0.055);
border: 1px solid var(--line);
border-radius: 6px;
padding: 8px 10px;
cursor: pointer;
font-size: 11px;
font-weight: 750;
transition: background 120ms, border-color 120ms, transform 120ms;
}
button:hover {
background: rgba(115, 225, 210, 0.13);
border-color: rgba(115, 225, 210, 0.45);
}
button:active { transform: translateY(1px); }
button.active {
color: #092028;
background: var(--aqua);
border-color: var(--aqua);
}
.divider {
position: fixed;
z-index: 3;
top: 64px;
bottom: 0;
left: 50%;
width: 1px;
background: rgba(200, 235, 231, 0.24);
pointer-events: none;
}
.panel {
position: fixed;
z-index: 4;
top: 82px;
bottom: 18px;
width: calc(50% - 32px);
pointer-events: none;
}
.panel-left { left: 16px; }
.panel-right { left: calc(50% + 16px); }
.panel-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 10px;
text-shadow: 0 2px 12px #001015;
}
.eyebrow {
color: var(--aqua);
font-size: 10px;
font-weight: 900;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.panel-heading h2 {
margin: 3px 0 0;
font-size: 20px;
line-height: 1.05;
letter-spacing: -0.025em;
}
.wetland-badge {
flex: none;
padding: 6px 8px;
border: 1px solid rgba(115, 225, 210, 0.35);
border-radius: 5px;
background: rgba(6, 24, 29, 0.74);
color: var(--aqua);
font-size: 11px;
font-weight: 850;
font-variant-numeric: tabular-nums;
}
.wetland-control {
pointer-events: auto;
width: min(250px, 80%);
margin-top: 11px;
padding: 9px 10px;
border: 1px solid var(--line);
border-radius: 7px;
background: var(--panel);
backdrop-filter: blur(10px);
}
.wetland-control label {
display: flex;
justify-content: space-between;
margin-bottom: 7px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.wetland-control output {
color: var(--text);
font-variant-numeric: tabular-nums;
}
.metrics {
position: absolute;
left: 0;
bottom: 0;
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
width: min(610px, 100%);
gap: 7px;
}
.metric {
min-width: 0;
padding: 10px 11px;
border: 1px solid var(--line);
border-radius: 7px;
background: var(--panel);
backdrop-filter: blur(12px);
}
.metric span {
display: block;
overflow: hidden;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.07em;
text-overflow: ellipsis;
text-transform: uppercase;
white-space: nowrap;
}
.metric strong {
display: block;
margin-top: 4px;
font-size: 19px;
font-variant-numeric: tabular-nums;
}
.metric.accent strong { color: var(--aqua); }
.verdict {
position: fixed;
z-index: 7;
top: 73px;
left: 50%;
transform: translateX(-50%);
max-width: min(520px, 44vw);
padding: 7px 11px;
border: 1px solid rgba(255, 179, 106, 0.3);
border-radius: 999px;
background: rgba(8, 24, 31, 0.85);
color: #ffe1bd;
font-size: 10px;
font-weight: 750;
line-height: 1.35;
text-align: center;
pointer-events: none;
}
.hint {
color: var(--muted);
font-size: 10px;
white-space: nowrap;
}
dialog {
width: min(680px, calc(100% - 28px));
padding: 0;
color: var(--text);
border: 1px solid rgba(115, 225, 210, 0.32);
border-radius: 12px;
background: #0a2028;
box-shadow: 0 30px 100px rgba(0, 0, 0, 0.65);
}
dialog::backdrop {
background: rgba(0, 7, 10, 0.72);
backdrop-filter: blur(4px);
}
.dialog-head {
display: flex;
align-items: center;
justify-content: space-between;
padding: 18px 20px;
border-bottom: 1px solid var(--line);
}
.dialog-head h2 {
margin: 0;
font-size: 20px;
}
.dialog-body {
padding: 18px 20px 22px;
color: #c4d8d6;
font-size: 13px;
line-height: 1.6;
}
.dialog-body h3 {
margin: 18px 0 5px;
color: var(--aqua);
font-size: 12px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.dialog-body p:first-child { margin-top: 0; }
code {
color: #ffd2a2;
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
font-size: 0.95em;
}
.warning {
margin-top: 18px;
padding: 11px 13px;
border-left: 3px solid var(--orange);
background: rgba(255, 179, 106, 0.08);
color: #ffe1bd;
}
@media (max-width: 900px) {
.topbar {
align-items: flex-start;
flex-direction: column;
}
.global-controls {
width: 100%;
justify-content: flex-start;
}
.divider { top: 112px; }
.panel { top: 128px; }
.verdict { display: none; }
.panel-heading h2 { font-size: 17px; }
.metric strong { font-size: 16px; }
}
@media (max-width: 620px) {
.topbar { padding: 9px 10px; }
.control { width: 130px; }
.hint { display: none; }
.divider {
top: 50%;
bottom: auto;
left: 0;
width: 100%;
height: 1px;
}
.panel {
width: calc(100% - 20px);
left: 10px;
}
.panel-left {
top: 128px;
bottom: calc(50% + 8px);
}
.panel-right {
top: calc(50% + 8px);
bottom: 10px;
}
.metrics { gap: 4px; }
.metric { padding: 7px; }
.metric span { font-size: 8px; }
.metric strong { font-size: 14px; }
}
</style>
</head>
<body>
<div id="viewport"></div>
<div class="vignette"></div>
<header class="topbar">
<div class="brand">
<div class="code">COAST / 04</div>
<strong>Marsh attenuation sandbox</strong>
<small>Two low-poly coasts · identical incident waves</small>
</div>
<div class="global-controls">
<div class="control">
<label>
Wave height
<output id="heightOutput">1.20 m</output>
</label>
<input id="heightInput" type="range" min="0.4" max="2" step="0.05" value="1.2">
</div>
<div class="control">
<label>
Wave period
<output id="periodOutput">4.2 s</output>
</label>
<input id="periodInput" type="range" min="2" max="8" step="0.1" value="4.2">
</div>
<div class="button-row" aria-label="Wetland comparison presets">
<button class="preset active" data-a="0" data-b="24">0 / 24 m</button>
<button class="preset" data-a="8" data-b="24">8 / 24 m</button>
<button class="preset" data-a="16" data-b="24">16 / 24 m</button>
</div>
<button id="pauseButton">Pause</button>
<button id="resetButton">Reset view</button>
<button id="notesButton">Model notes</button>
<span class="hint">Drag to orbit · wheel to zoom</span>
</div>
</header>
<div class="divider"></div>
<div id="verdict" class="verdict"></div>
<section class="panel panel-left">
<div class="panel-heading">
<div>
<div class="eyebrow">Coast A</div>
<h2>Reference coastline</h2>
</div>
<div id="badge0" class="wetland-badge">0 m wetland</div>
</div>
<div class="wetland-control">
<label>
Wetland extent
<output id="wetlandOutput0">0 m</output>
</label>
<input id="wetlandInput0" type="range" min="0" max="28" step="1" value="0">
</div>
<div class="metrics">
<div class="metric">
<span>Crest at x = 28 m</span>
<strong id="metricH0">—</strong>
</div>
<div class="metric accent">
<span>Height reduction</span>
<strong id="metricReduction0">—</strong>
</div>
<div class="metric">
<span>Planform marsh area</span>
<strong id="metricArea0">—</strong>
</div>
</div>
</section>
<section class="panel panel-right">
<div class="panel-heading">
<div>
<div class="eyebrow">Coast B</div>
<h2>Wetland coastline</h2>
</div>
<div id="badge1" class="wetland-badge">24 m wetland</div>
</div>
<div class="wetland-control">
<label>
Wetland extent
<output id="wetlandOutput1">24 m</output>
</label>
<input id="wetlandInput1" type="range" min="0" max="28" step="1" value="24">
</div>
<div class="metrics">
<div class="metric">
<span>Crest at x = 28 m</span>
<strong id="metricH1">—</strong>
</div>
<div class="metric accent">
<span>Height reduction</span>
<strong id="metricReduction1">—</strong>
</div>
<div class="metric">
<span>Planform marsh area</span>
<strong id="metricArea1">—</strong>
</div>
</div>
</section>
<dialog id="notesDialog">
<div class="dialog-head">
<h2>Explicit toy model</h2>
<form method="dialog">
<button>Close</button>
</form>
</div>
<div class="dialog-body">
<p>
This is a deliberately simplified visual comparison, not a coastal
hydrodynamics solver. Both panels use the same offshore wave height,
period, phase, phase speed, camera, and offshore bathymetry.
</p>
<h3>Wave representation</h3>
<p>
The surface is a traveling sinusoid:
<code>η(x,t) = A(x,W) cos(kx − ωt)</code>, with
<code>ω = 2π/T</code> and
<code>c = √(g·2.4)</code>, so
<code>k = ω/c</code>. Offshore depth is 2.4 m.
</p>
<h3>Simplified shoaling and attenuation</h3>
<p>
Offshore shoaling uses
<code>S(x) = (2.4/d(x))^(1/4)</code>, capped at 1.35.
Inside a wetland of width <code>W</code>, amplitude decays as
<code>A(x,W) = A₀ S(x) exp(−α min(max(x,0),W))</code>,
where <code>α = 0.055 + 0.020H</code> m⁻¹.
Attenuation stops at the landward wetland edge.
</p>
<h3>Comparison metric</h3>
<p>
The orange line is a fixed monitoring transect at
<code>x = 28 m</code>. The displayed crest height is
<code>2A(28,W)</code>. Reduction is measured against the same wave over
a zero-width wetland. Planform marsh area is
<code>64W m²</code> for the displayed 64 m shoreline length.
</p>
<div class="warning">
Intentionally omitted: wave reflection, refraction, diffraction,
currents, sediment transport, vegetation drag resolved in time,
turbulence, inundation, and true fluid dynamics. The values are
illustrative model outputs and should not be used for engineering
or design decisions.
</div>
</div>
</dialog>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------------
// Global model and UI state
// ------------------------------------------------------------------
const state = {
waveHeight: 1.2,
wavePeriod: 4.2,
wetlandWidths: [0, 24],
playing: true,
time: 0
};
const GRAVITY = 9.81;
const OFFSHORE_DEPTH = 2.4;
const GAUGE_X = 28;
const SHORE_LENGTH = 64;
const MAX_WETLAND = 28;
const viewport = document.getElementById("viewport");
const renderer = new THREE.WebGLRenderer({
antialias: true,
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.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
viewport.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
43,
1,
0.1,
500
);
const view = {
target: new THREE.Vector3(-7, -0.4, 0),
radius: 88,
theta: 0.68,
phi: 1.02
};
const panelObjects = [null, null];
const clamp = THREE.MathUtils.clamp;
const lerp = THREE.MathUtils.lerp;
function smoothstep(t) {
t = clamp(t, 0, 1);
return t * t * (3 - 2 * t);
}
function deterministicRandom(seed) {
let value = seed >>> 0;
return function () {
value += 0x6D2B79F5;
let t = value;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function terrainNoise(x, z) {
return (
0.56 * Math.sin(x * 0.39 + z * 0.17) +
0.28 * Math.sin(z * 1.11 - x * 0.23) +
0.16 * Math.sin(x * 1.37 + z * 0.83)
);
}
function terrainHeight(x, z, wetlandWidth) {
const noise = terrainNoise(x, z);
if (x < 0) {
// Sea floor: depth decreases linearly from 2.4 m to 0.75 m.
return -0.75 + 0.0253846154 * x + noise * 0.055;
}
if (wetlandWidth > 0) {
if (x < wetlandWidth) {
// Submerged, vegetated marsh platform.
return -0.42 + 0.012 * x + noise * 0.075;
}
if (x < wetlandWidth + 8) {
const t = (x - wetlandWidth) / 8;
const marshEdge = -0.42 + 0.012 * wetlandWidth;
const landHeight = 0.12 + 0.04 * (wetlandWidth + 8);
return lerp(marshEdge, landHeight, smoothstep(t)) + noise * 0.11;
}
}
return 0.12 + 0.04 * x + noise * 0.14;
}
function offshoreDepth(x) {
return Math.max(0.75, 0.75 - 0.0253846154 * x);
}
function attenuationCoefficient() {
return 0.055 + 0.020 * state.waveHeight;
}
function waveAmplitude(x, wetlandWidth) {
const incidentAmplitude = state.waveHeight * 0.5;
const depth = offshoreDepth(x);
const shoaling = clamp(
Math.pow(OFFSHORE_DEPTH / depth, 0.25),
1,
1.35
);
let amplitude = incidentAmplitude * shoaling;
if (x > 0 && wetlandWidth > 0) {
const distanceInWetland = Math.min(x, wetlandWidth);
amplitude *= Math.exp(
-attenuationCoefficient() * distanceInWetland
);
}
return amplitude;
}
function waveNumber() {
const speed = Math.sqrt(GRAVITY * OFFSHORE_DEPTH);
return (2 * Math.PI / state.wavePeriod) / speed;
}
// ------------------------------------------------------------------
// Low-poly geometry helpers
// ------------------------------------------------------------------
function createTerrain(wetlandWidth) {
const nx = 72;
const nz = 30;
const xMin = -65;
const xMax = 55;
const zMin = -32;
const zMax = 32;
const positions = [];
const colors = [];
const indices = [];
const oceanColor = new THREE.Color(0x49686b);
const marshColor = new THREE.Color(0x4f714f);
const sandColor = new THREE.Color(0xa89e72);
const uplandColor = new THREE.Color(0x89926a);
const color = new THREE.Color();
for (let iz = 0; iz <= nz; iz++) {
const z = lerp(zMin, zMax, iz / nz);
for (let ix = 0; ix <= nx; ix++) {
const x = lerp(xMin, xMax, ix / nx);
const y = terrainHeight(x, z, wetlandWidth);
positions.push(x, y, z);
if (x < 0) {
color.copy(oceanColor).multiplyScalar(
0.78 + 0.20 * (1 - Math.min(1, -x / 65))
);
} else if (
wetlandWidth > 0 &&
x < wetlandWidth + 1.2
) {
color.copy(marshColor).multiplyScalar(
0.82 + 0.12 * Math.sin(x * 0.7 + z * 0.3)
);
} else if (
wetlandWidth > 0 &&
x < wetlandWidth + 8
) {
color.lerpColors(marshColor, sandColor, 0.55);
} else {
color.lerpColors(sandColor, uplandColor, smoothstep(x / 45));
}
const variation = 0.91 + 0.09 * Math.sin(x * 1.7 + z * 0.9);
color.multiplyScalar(variation);
colors.push(color.r, color.g, color.b);
}
}
for (let iz = 0; iz < nz; iz++) {
for (let ix = 0; ix < nx; ix++) {
const a = iz * (nx + 1) + ix;
const b = a + 1;
const c = a + nx + 1;
const d = c + 1;
indices.push(a, c, b, b, c, d);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(colors, 3)
);
geometry.setIndex(indices);
geometry.computeVertexNormals();
const material = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.96,
metalness: 0,
flatShading: true
});
const mesh = new THREE.Mesh(geometry, material);
mesh.receiveShadow = true;
return mesh;
}
function createWater() {
const nx = 88;
const nz = 34;
const xMin = -65;
const xMax = 42;
const zMin = -32;
const zMax = 32;
const positions = [];
const colors = [];
const indices = [];
for (let iz = 0; iz <= nz; iz++) {
const z = lerp(zMin, zMax, iz / nz);
for (let ix = 0; ix <= nx; ix++) {
const x = lerp(xMin, xMax, ix / nx);
positions.push(x, 0, z);
colors.push(0.04, 0.36, 0.45);
}
}
for (let iz = 0; iz < nz; iz++) {
for (let ix = 0; ix < nx; ix++) {
const a = iz * (nx + 1) + ix;
const b = a + 1;
const c = a + nx + 1;
const d = c + 1;
indices.push(a, c, b, b, c, d);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(colors, 3)
);
geometry.setIndex(indices);
geometry.computeVertexNormals();
const material = new THREE.MeshStandardMaterial({
vertexColors: true,
color: 0xffffff,
transparent: true,
opacity: 0.76,
roughness: 0.26,
metalness: 0.06,
depthWrite: false,
side: THREE.DoubleSide,
flatShading: true
});
const mesh = new THREE.Mesh(geometry, material);
mesh.receiveShadow = true;
mesh.renderOrder = 2;
return mesh;
}
function updateWater(water, wetlandWidth) {
const positions = water.geometry.getAttribute("position");
const colors = water.geometry.getAttribute("color");
const k = waveNumber();
const omega = 2 * Math.PI / state.wavePeriod;
const deep = new THREE.Color(0x07546b);
const middle = new THREE.Color(0x188fa0);
const crest = new THREE.Color(0x8be9df);
const temp = new THREE.Color();
const maximumDisplayAmplitude =
state.waveHeight * 0.5 * 1.35;
for (let i = 0; i < positions.count; i++) {
const x = positions.getX(i);
const z = positions.getZ(i);
const amplitude = waveAmplitude(x, wetlandWidth);
const elevation = amplitude * Math.cos(k * x - omega * state.time);
positions.setY(i, elevation);
const normalized = clamp(
elevation / Math.max(0.001, maximumDisplayAmplitude),
-1,
1
);
if (normalized >= 0) {
temp.lerpColors(middle, crest, normalized);
} else {
temp.lerpColors(deep, middle, normalized + 1);
}
const smallFacetVariation =
0.96 + 0.04 * Math.sin(z * 1.7 + x * 0.35);
colors.setXYZ(
i,
temp.r * smallFacetVariation,
temp.g * smallFacetVariation,
temp.b * smallFacetVariation
);
}
positions.needsUpdate = true;
colors.needsUpdate = true;
}
function createVegetation(wetlandWidth) {
if (wetlandWidth <= 0.5) return null;
const count = Math.min(560, Math.floor(wetlandWidth * 19));
const random = deterministicRandom(8713 + wetlandWidth * 117);
const geometry = new THREE.ConeGeometry(0.15, 1.25, 4, 1);
const material = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.94,
flatShading: true
});
const mesh = new THREE.InstancedMesh(
geometry,
material,
count
);
const dummy = new THREE.Object3D();
const color = new THREE.Color();
for (let i = 0; i < count; i++) {
const x = 0.7 + random() * Math.max(0.1, wetlandWidth - 1.4);
const z = -30.5 + random() * 61;
const y = terrainHeight(x, z, wetlandWidth);
const scale = 0.62 + random() * 0.92;
dummy.position.set(x, y + 0.625 * scale, z);
dummy.rotation.set(
(random() - 0.5) * 0.18,
random() * Math.PI * 2,
(random() - 0.5) * 0.18
);
dummy.scale.set(
0.70 + random() * 0.45,
scale,
0.70 + random() * 0.45
);
dummy.updateMatrix();
mesh.setMatrixAt(i, dummy.matrix);
const hue = 0.23 + random() * 0.08;
color.setHSL(hue, 0.40 + random() * 0.15, 0.30 + random() * 0.13);
mesh.setColorAt(i, color);
}
mesh.instanceMatrix.needsUpdate = true;
if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
function createRocks(wetlandWidth) {
const count = 22;
const random = deterministicRandom(4409);
const geometry = new THREE.DodecahedronGeometry(0.48, 0);
const material = new THREE.MeshStandardMaterial({
color: 0x7d817a,
roughness: 0.95,
flatShading: true
});
const mesh = new THREE.InstancedMesh(
geometry,
material,
count
);
const dummy = new THREE.Object3D();
const color = new THREE.Color();
for (let i = 0; i < count; i++) {
const x = -1.8 + random() * 4.2;
const z = -30 + random() * 60;
const y = terrainHeight(x, z, wetlandWidth);
const scale = 0.35 + random() * 0.85;
dummy.position.set(x, y + 0.12 * scale, z);
dummy.rotation.set(
random() * Math.PI,
random() * Math.PI,
random() * Math.PI
);
dummy.scale.set(
scale * (0.8 + random() * 0.7),
scale * (0.55 + random() * 0.45),
scale * (0.8 + random() * 0.7)
);
dummy.updateMatrix();
mesh.setMatrixAt(i, dummy.matrix);
color.setHSL(0.12, 0.08, 0.40 + random() * 0.17);
mesh.setColorAt(i, color);
}
mesh.instanceMatrix.needsUpdate = true;
if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
function makeLabel(text, position, color = "#d8f2ed") {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 96;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(5, 22, 28, 0.78)";
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = "rgba(150, 220, 213, 0.36)";
context.lineWidth = 3;
context.strokeRect(2, 2, canvas.width - 4, canvas.height - 4);
context.fillStyle = color;
context.font = "800 34px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, canvas.width / 2, canvas.height / 2 + 1);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false,
fog: false
});
const sprite = new THREE.Sprite(material);
sprite.position.copy(position);
sprite.scale.set(14, 2.625, 1);
sprite.renderOrder = 20;
return sprite;
}
function createGauge() {
const group = new THREE.Group();
const lineGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(GAUGE_X, 0.62, -29),
new THREE.Vector3(GAUGE_X, 0.62, 29)
]);
const lineMaterial = new THREE.LineDashedMaterial({
color: 0xffb36a,
dashSize: 1.1,
gapSize: 0.7,
transparent: true,
opacity: 0.95
});
const line = new THREE.Line(lineGeometry, lineMaterial);
line.computeLineDistances();
group.add(line);
const poleGeometry = new THREE.CylinderGeometry(
0.065,
0.065,
1.7,
5
);
const poleMaterial = new THREE.MeshStandardMaterial({
color: 0xffb36a,
roughness: 0.55,
emissive: 0x5a2600,
emissiveIntensity: 0.25
});
for (const z of [-29, 29]) {
const pole = new THREE.Mesh(poleGeometry, poleMaterial);
pole.position.set(GAUGE_X, 0.72, z);
pole.castShadow = true;
group.add(pole);
}
return group;
}
// ------------------------------------------------------------------
// Scene construction and disposal
// ------------------------------------------------------------------
function disposePanel(panel) {
if (!panel) return;
panel.scene.traverse(object => {
if (object.geometry) {
object.geometry.dispose();
}
if (object.material) {
const materials = Array.isArray(object.material)
? object.material
: [object.material];
for (const material of materials) {
if (material.map) material.map.dispose();
material.dispose();
}
}
});
renderer.renderLists.dispose();
}
function buildPanel(index, wetlandWidth) {
disposePanel(panelObjects[index]);
const scene = new THREE.Scene();
scene.background = new THREE.Color(
index === 0 ? 0x102934 : 0x102b32
);
scene.fog = new THREE.FogExp2(
index === 0 ? 0x102934 : 0x102b32,
0.0062
);
const hemisphere = new THREE.HemisphereLight(
0xc6e8ed,
0x4b4937,
1.65
);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(
0xffe5be,
2.35
);
sun.position.set(-24, 48, 23);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
sun.shadow.camera.left = -75;
sun.shadow.camera.right = 75;
sun.shadow.camera.top = 55;
sun.shadow.camera.bottom = -55;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 150;
sun.shadow.bias = -0.0008;
sun.target.position.set(-5, 0, 0);
scene.add(sun, sun.target);
const fill = new THREE.DirectionalLight(
0x75d9e2,
0.52
);
fill.position.set(30, 15, -38);
scene.add(fill);
const terrain = createTerrain(wetlandWidth);
scene.add(terrain);
const water = createWater();
scene.add(water);
const vegetation = createVegetation(wetlandWidth);
if (vegetation) scene.add(vegetation);
const rocks = createRocks(wetlandWidth);
scene.add(rocks);
scene.add(createGauge());
scene.add(makeLabel(
"OPEN OCEAN",
new THREE.Vector3(-42, 2.0, -25),
"#a9e7e4"
));
scene.add(makeLabel(
"INCIDENT WAVE",
new THREE.Vector3(-57, 3.1, 24),
"#8be9df"
));
scene.add(makeLabel(
wetlandWidth > 0 ? "MARSH PLATFORM" : "DRY COAST",
new THREE.Vector3(14, 2.1, -27),
"#bfe0a9"
));
scene.add(makeLabel(
"GAUGE x = 28 m",
new THREE.Vector3(28, 2.7, 27),
"#ffd2a2"
));
panelObjects[index] = {
scene,
terrain,
water,
wetlandWidth
};
}
// ------------------------------------------------------------------
// Metrics and interface
// ------------------------------------------------------------------
function metricFor(wetlandWidth) {
const gaugeHeight = 2 * waveAmplitude(GAUGE_X, wetlandWidth);
const baselineHeight = 2 * waveAmplitude(GAUGE_X, 0);
const reduction = 100 * (1 - gaugeHeight / baselineHeight);
const area = wetlandWidth * SHORE_LENGTH;
return { gaugeHeight, reduction, area };
}
function formatArea(area) {
if (area >= 1000) {
return `${(area / 1000).toFixed(2)}k m²`;
}
return `${Math.round(area)} m²`;
}
function updateMetrics() {
for (let i = 0; i < 2; i++) {
const width = state.wetlandWidths[i];
const metric = metricFor(width);
document.getElementById(`metricH${i}`).textContent =
`${metric.gaugeHeight.toFixed(2)} m`;
document.getElementById(`metricReduction${i}`).textContent =
`${metric.reduction.toFixed(0)}%`;
document.getElementById(`metricArea${i}`).textContent =
formatArea(metric.area);
document.getElementById(`badge${i}`).textContent =
`${width} m wetland`;
document.getElementById(`wetlandOutput${i}`).textContent =
`${width} m`;
}
const widthA = state.wetlandWidths[0];
const widthB = state.wetlandWidths[1];
const metricA = metricFor(widthA);
const metricB = metricFor(widthB);
let text;
if (widthA === widthB) {
text =
`Equal wetland extents: both gauges model a ` +
`${metricA.reduction.toFixed(0)}% crest-height reduction.`;
} else {
const highWidth = Math.max(widthA, widthB);
const lowWidth = Math.min(widthA, widthB);
const highMetric = metricFor(highWidth);
const lowMetric = metricFor(lowWidth);
text =
`At H = ${state.waveHeight.toFixed(2)} m and T = ` +
`${state.wavePeriod.toFixed(1)} s, the ${highWidth} m marsh ` +
`gives ${highMetric.gaugeHeight.toFixed(2)} m at the common ` +
`gauge versus ${lowMetric.gaugeHeight.toFixed(2)} m for ` +
`${lowWidth} m.`;
}
document.getElementById("verdict").textContent = text;
}
const heightInput = document.getElementById("heightInput");
const periodInput = document.getElementById("periodInput");
heightInput.addEventListener("input", () => {
state.waveHeight = Number(heightInput.value);
document.getElementById("heightOutput").textContent =
`${state.waveHeight.toFixed(2)} m`;
updateMetrics();
});
periodInput.addEventListener("input", () => {
state.wavePeriod = Number(periodInput.value);
document.getElementById("periodOutput").textContent =
`${state.wavePeriod.toFixed(1)} s`;
updateMetrics();
});
const pendingBuilds = new Set();
function schedulePanelBuild(index) {
pendingBuilds.add(index);
requestAnimationFrame(() => {
for (const pendingIndex of pendingBuilds) {
buildPanel(
pendingIndex,
state.wetlandWidths[pendingIndex]
);
}
pendingBuilds.clear();
updateMetrics();
});
}
for (let i = 0; i < 2; i++) {
const input = document.getElementById(`wetlandInput${i}`);
input.addEventListener("input", () => {
state.wetlandWidths[i] = Number(input.value);
schedulePanelBuild(i);
updateMetrics();
});
}
document.querySelectorAll(".preset").forEach(button => {
button.addEventListener("click", () => {
const a = Number(button.dataset.a);
const b = Number(button.dataset.b);
state.wetlandWidths[0] = a;
state.wetlandWidths[1] = b;
document.getElementById("wetlandInput0").value = a;
document.getElementById("wetlandInput1").value = b;
buildPanel(0, a);
buildPanel(1, b);
document.querySelectorAll(".preset").forEach(other => {
other.classList.toggle(
"active",
other === button
);
});
updateMetrics();
});
});
const pauseButton = document.getElementById("pauseButton");
pauseButton.addEventListener("click", () => {
state.playing = !state.playing;
pauseButton.textContent = state.playing ? "Pause" : "Play";
pauseButton.classList.toggle("active", !state.playing);
});
document.getElementById("notesButton").addEventListener("click", () => {
document.getElementById("notesDialog").showModal();
});
function resetView() {
view.target.set(-7, -0.4, 0);
view.radius = 88;
view.theta = 0.68;
view.phi = 1.02;
}
document.getElementById("resetButton").addEventListener("click", resetView);
// ------------------------------------------------------------------
// Direct camera controls: no OrbitControls or other addons
// ------------------------------------------------------------------
let dragging = false;
let lastPointerX = 0;
let lastPointerY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
view.theta -= dx * 0.005;
view.phi = clamp(view.phi - dy * 0.0045, 0.34, 1.43);
});
function endDrag(event) {
dragging = false;
if (
event.pointerId !== undefined &&
renderer.domElement.hasPointerCapture(event.pointerId)
) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
view.radius = clamp(
view.radius * Math.exp(event.deltaY * 0.001),
42,
145
);
}, { passive: false });
renderer.domElement.addEventListener("dblclick", resetView);
function updateCamera() {
const sinPhi = Math.sin(view.phi);
camera.position.set(
view.target.x + view.radius * sinPhi * Math.cos(view.theta),
view.target.y + view.radius * Math.cos(view.phi),
view.target.z + view.radius * sinPhi * Math.sin(view.theta)
);
camera.lookAt(view.target);
}
// ------------------------------------------------------------------
// Rendering: two scissored viewports sharing one camera
// ------------------------------------------------------------------
function renderViews() {
const width = window.innerWidth;
const height = window.innerHeight;
const stacked = width <= 620;
const views = stacked
? [
{ x: 0, y: height / 2, width, height: height / 2 },
{ x: 0, y: 0, width, height: height / 2 }
]
: [
{ x: 0, y: 0, width: width / 2, height },
{ x: width / 2, y: 0, width: width / 2, height }
];
renderer.setScissorTest(true);
views.forEach((rect, index) => {
const bottom = height - rect.y - rect.height;
camera.aspect = rect.width / rect.height;
camera.updateProjectionMatrix();
updateCamera();
renderer.setViewport(
rect.x,
bottom,
rect.width,
rect.height
);
renderer.setScissor(
rect.x,
bottom,
rect.width,
rect.height
);
renderer.render(
panelObjects[index].scene,
camera
);
});
}
window.addEventListener("resize", () => {
renderer.setSize(window.innerWidth, window.innerHeight);
});
// ------------------------------------------------------------------
// Start and animation loop
// ------------------------------------------------------------------
buildPanel(0, state.wetlandWidths[0]);
buildPanel(1, state.wetlandWidths[1]);
updateMetrics();
let previousTime = performance.now();
function animate(now) {
const delta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (state.playing) {
state.time += delta;
}
for (let i = 0; i < panelObjects.length; i++) {
updateWater(
panelObjects[i].water,
panelObjects[i].wetlandWidth
);
}
renderViews();
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```