Prompt specification
Build or customize the Three.js 3D scene "Reef fish sheltering beside a coral structure" 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: Reef fish sheltering beside a coral structure
Category: Space & Earth · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/reef-fish-sheltering-beside-a-coral-structure-x3074
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring a low-poly reef fish beside a coral shelter. Use one referenced species with recognizable fins and markings, and make the coral from separated branches around a visible opening. Put the shelter on sand beside a shallow rock ledge. The fish makes a short, slow circuit around it, occasionally pausing, with gentle tail motion and no passage through the branches. This is a modest behavioral vignette rather than a validated ecological simulation.
Working Three.js Starter (reef-fish-sheltering-beside-a-coral-structure-x3074):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Clownfish at a Coral Shelter</title>
<style>
:root {
color-scheme: dark;
--ink: #efffff;
--muted: #b8d8dc;
--glass: rgba(7, 43, 53, 0.58);
--line: rgba(190, 242, 244, 0.2);
--accent: #ffc16d;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #075f73;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#stage {
position: fixed;
inset: 0;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.card {
position: fixed;
z-index: 5;
border: 1px solid var(--line);
background: var(--glass);
box-shadow: 0 16px 45px rgba(0, 20, 26, 0.24);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
}
.intro {
top: 22px;
left: 22px;
width: min(390px, calc(100vw - 44px));
padding: 18px 20px 16px;
border-radius: 16px;
pointer-events: none;
}
.eyebrow {
margin: 0 0 6px;
color: #8ee0df;
font-size: 0.72rem;
font-weight: 750;
letter-spacing: 0.15em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(1.25rem, 2.2vw, 1.7rem);
font-weight: 690;
line-height: 1.12;
letter-spacing: -0.025em;
}
.species {
margin: 8px 0 0;
color: var(--muted);
font-size: 0.9rem;
line-height: 1.45;
}
.species em {
color: #ffe1aa;
}
.note {
margin: 11px 0 0;
padding-top: 10px;
border-top: 1px solid var(--line);
color: #a8c9ce;
font-size: 0.73rem;
line-height: 1.45;
}
.status {
top: 22px;
right: 22px;
display: flex;
align-items: center;
gap: 9px;
padding: 10px 13px;
border-radius: 999px;
color: #d9f5f4;
font-size: 0.78rem;
pointer-events: none;
}
#status-dot {
width: 8px;
height: 8px;
flex: 0 0 auto;
border-radius: 50%;
background: #83e1c5;
box-shadow: 0 0 0 4px rgba(131, 225, 197, 0.13);
}
#status-dot.paused {
background: #ffc16d;
box-shadow: 0 0 0 4px rgba(255, 193, 109, 0.13);
}
.toolbar {
right: 22px;
bottom: 22px;
display: flex;
gap: 8px;
padding: 8px;
border-radius: 13px;
}
button {
appearance: none;
border: 1px solid rgba(199, 240, 240, 0.2);
border-radius: 9px;
padding: 9px 12px;
background: rgba(218, 248, 246, 0.09);
color: #efffff;
font: inherit;
font-size: 0.78rem;
font-weight: 650;
cursor: pointer;
transition:
background 150ms ease,
transform 150ms ease;
}
button:hover {
background: rgba(218, 248, 246, 0.17);
transform: translateY(-1px);
}
button:focus-visible {
outline: 2px solid #ffc16d;
outline-offset: 2px;
}
.hint {
position: fixed;
z-index: 5;
left: 22px;
bottom: 22px;
padding: 9px 12px;
border-radius: 10px;
color: #bfdde0;
font-size: 0.73rem;
pointer-events: none;
}
@media (max-width: 640px) {
.intro {
top: 12px;
left: 12px;
width: calc(100vw - 24px);
padding: 14px 15px;
}
.status {
top: auto;
right: 12px;
bottom: 70px;
}
.toolbar {
right: 12px;
bottom: 12px;
}
.hint {
display: none;
}
.note {
display: none;
}
}
</style>
</head>
<body>
<main id="stage" aria-label="An interactive underwater scene"></main>
<section class="card intro">
<p class="eyebrow">Reef micro-vignette</p>
<h1>Clownfish at a coral shelter</h1>
<p class="species">
Common clownfish, <em>Amphiprion ocellaris</em> — orange body, three
black-edged white bars, and rounded fins.
</p>
<p class="note">
A modest behavioral vignette, not a validated ecological simulation.
</p>
</section>
<div class="card status" role="status" aria-live="polite">
<span id="status-dot"></span>
<span id="status-text">Slow circuit</span>
</div>
<div class="card hint">Drag to orbit · wheel to zoom · Space to pause</div>
<nav class="card toolbar" aria-label="Scene controls">
<button id="pause-button" type="button">Pause motion</button>
<button id="restart-button" type="button">Restart circuit</button>
</nav>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const stage = document.querySelector("#stage");
const pauseButton = document.querySelector("#pause-button");
const restartButton = document.querySelector("#restart-button");
const statusText = document.querySelector("#status-text");
const statusDot = document.querySelector("#status-dot");
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
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;
renderer.domElement.setAttribute(
"aria-label",
"Low-poly common clownfish circling a separated coral shelter beside a rock ledge"
);
renderer.domElement.tabIndex = 0;
stage.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0a7184);
scene.fog = new THREE.FogExp2(0x0a6d7e, 0.026);
const camera = new THREE.PerspectiveCamera(
41,
window.innerWidth / window.innerHeight,
0.1,
80
);
// Camera controls are implemented here rather than using an addon.
const orbit = {
target: new THREE.Vector3(0.28, 0.72, 0),
radius: 8.6,
theta: 0.72,
phi: 1.18,
dragging: false,
pointerX: 0,
pointerY: 0
};
function updateCamera() {
const sinPhi = Math.sin(orbit.phi);
camera.position.set(
orbit.target.x + orbit.radius * sinPhi * Math.sin(orbit.theta),
orbit.target.y + orbit.radius * Math.cos(orbit.phi),
orbit.target.z + orbit.radius * sinPhi * Math.cos(orbit.theta)
);
camera.lookAt(orbit.target);
}
function resetCamera() {
orbit.target.set(0.28, 0.72, 0);
orbit.radius = 8.6;
orbit.theta = 0.72;
orbit.phi = 1.18;
}
renderer.domElement.addEventListener("pointerdown", (event) => {
orbit.dragging = true;
orbit.pointerX = event.clientX;
orbit.pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!orbit.dragging) return;
const dx = event.clientX - orbit.pointerX;
const dy = event.clientY - orbit.pointerY;
orbit.pointerX = event.clientX;
orbit.pointerY = event.clientY;
orbit.theta -= dx * 0.006;
orbit.phi = THREE.MathUtils.clamp(
orbit.phi - dy * 0.005,
0.46,
1.48
);
});
function endPointerDrag(event) {
orbit.dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endPointerDrag);
renderer.domElement.addEventListener("pointercancel", endPointerDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius * Math.exp(event.deltaY * 0.001),
4.8,
13
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
window.addEventListener("keydown", (event) => {
if (event.code === "Space") {
event.preventDefault();
toggleMotion();
} else if (event.code === "ArrowLeft") {
orbit.theta -= 0.1;
} else if (event.code === "ArrowRight") {
orbit.theta += 0.1;
} else if (event.code === "ArrowUp") {
orbit.phi = Math.max(0.46, orbit.phi - 0.08);
} else if (event.code === "ArrowDown") {
orbit.phi = Math.min(1.48, orbit.phi + 0.08);
} else if (event.code === "=" || event.code === "+") {
orbit.radius = Math.max(4.8, orbit.radius - 0.6);
} else if (event.code === "-") {
orbit.radius = Math.min(13, orbit.radius + 0.6);
}
});
// Deterministic randomness keeps the composition stable between reloads.
let randomSeed = 731904;
function random() {
randomSeed =
(randomSeed * 1664525 + 1013904223) >>> 0;
return randomSeed / 4294967296;
}
// Lighting.
scene.add(new THREE.HemisphereLight(0xa5f5f1, 0x4c4932, 1.75));
const sun = new THREE.DirectionalLight(0xfff0c2, 2.7);
sun.position.set(4.5, 8.5, 5.5);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -9;
sun.shadow.camera.right = 9;
sun.shadow.camera.top = 9;
sun.shadow.camera.bottom = -9;
sun.shadow.camera.near = 0.5;
sun.shadow.camera.far = 25;
sun.shadow.normalBias = 0.025;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x69dce8, 0.9);
fill.position.set(-5, 3.5, -4);
scene.add(fill);
const coralGlow = new THREE.PointLight(0xf59ab8, 3.2, 5, 2);
coralGlow.position.set(0, 1.0, -0.15);
scene.add(coralGlow);
// Sand with a low, faceted surface.
const sandGeometry = new THREE.PlaneGeometry(28, 28, 56, 56);
sandGeometry.rotateX(-Math.PI / 2);
const sandPositions = sandGeometry.attributes.position;
const sandColors = [];
const sandBase = new THREE.Color(0xdac58d);
for (let i = 0; i < sandPositions.count; i++) {
const x = sandPositions.getX(i);
const z = sandPositions.getZ(i);
const distance = Math.hypot(x, z);
const flatten = THREE.MathUtils.smoothstep(distance, 1.6, 7.0);
const height =
(Math.sin(x * 0.62 + z * 0.24) * 0.045 +
Math.cos(z * 1.08) * 0.026 +
(random() - 0.5) * 0.035) *
flatten;
sandPositions.setY(i, height - 0.02);
const color = sandBase
.clone()
.multiplyScalar(0.92 + random() * 0.11);
sandColors.push(color.r, color.g, color.b);
}
sandGeometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(sandColors, 3)
);
sandGeometry.computeVertexNormals();
const sand = new THREE.Mesh(
sandGeometry,
new THREE.MeshStandardMaterial({
color: 0xffffff,
vertexColors: true,
roughness: 0.98,
flatShading: true
})
);
sand.receiveShadow = true;
scene.add(sand);
// Subtle curved sand ripples.
const rippleMaterial = new THREE.LineBasicMaterial({
color: 0xf5e9bc,
transparent: true,
opacity: 0.22,
depthWrite: false
});
for (let i = 0; i < 12; i++) {
const curve = new THREE.EllipseCurve(
0,
0,
0.65 + random() * 0.85,
0.22 + random() * 0.25,
random() * Math.PI,
random() * Math.PI + 0.8,
false,
0
);
const points = curve.getPoints(34).map(
(point) =>
new THREE.Vector3(
point.x + (random() - 0.5) * 5.5,
0.018,
point.y + (random() - 0.5) * 4.8
)
);
const ripple = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(points),
rippleMaterial
);
scene.add(ripple);
}
// Small low-poly sand pebbles.
const pebbleGeometry = new THREE.DodecahedronGeometry(0.055, 0);
const pebbleMaterial = new THREE.MeshStandardMaterial({
color: 0xb8a679,
roughness: 1,
flatShading: true
});
const pebbles = new THREE.InstancedMesh(
pebbleGeometry,
pebbleMaterial,
42
);
const dummy = new THREE.Object3D();
for (let i = 0; i < 42; i++) {
const angle = random() * Math.PI * 2;
const radius = 1.5 + random() * 5.8;
const scale = 0.45 + random() * 1.35;
dummy.position.set(
Math.cos(angle) * radius,
0.015,
Math.sin(angle) * radius
);
dummy.rotation.set(random() * 2, random() * 2, random() * 2);
dummy.scale.set(scale, scale * 0.55, scale * 0.82);
dummy.updateMatrix();
pebbles.setMatrixAt(i, dummy.matrix);
}
pebbles.castShadow = true;
pebbles.receiveShadow = true;
scene.add(pebbles);
// Coral shelter: individually modeled, tapered branches leave an open center.
const coral = new THREE.Group();
coral.position.set(-0.12, 0, 0);
coral.rotation.y = -0.04;
scene.add(coral);
const coralMaterials = [
new THREE.MeshStandardMaterial({
color: 0xbe477d,
roughness: 0.83,
flatShading: true
}),
new THREE.MeshStandardMaterial({
color: 0xd35a8c,
roughness: 0.8,
flatShading: true
}),
new THREE.MeshStandardMaterial({
color: 0x9f3f74,
roughness: 0.88,
flatShading: true
})
];
const coralTipMaterial = new THREE.MeshStandardMaterial({
color: 0xee8eae,
roughness: 0.78,
flatShading: true
});
const yAxis = new THREE.Vector3(0, 1, 0);
function addCoralSegment(a, b, radiusA, radiusB, material) {
const start = new THREE.Vector3(...a);
const end = new THREE.Vector3(...b);
const direction = end.clone().sub(start);
const length = direction.length();
const geometry = new THREE.CylinderGeometry(
radiusB,
radiusA,
length,
6,
1,
false
);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.copy(start).add(end).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(yAxis, direction.normalize());
mesh.castShadow = true;
mesh.receiveShadow = true;
coral.add(mesh);
}
function addCoralBranch(points, baseRadius, materialIndex) {
const material = coralMaterials[materialIndex % coralMaterials.length];
for (let i = 0; i < points.length - 1; i++) {
const t0 = i / (points.length - 1);
const t1 = (i + 1) / (points.length - 1);
addCoralSegment(
points[i],
points[i + 1],
baseRadius * (1 - t0 * 0.62),
baseRadius * (1 - t1 * 0.62),
material
);
if (i > 0) {
const joint = new THREE.Mesh(
new THREE.IcosahedronGeometry(
baseRadius * (1 - t0 * 0.62) * 1.05,
0
),
material
);
joint.position.set(...points[i]);
joint.castShadow = true;
coral.add(joint);
}
}
const tip = new THREE.Mesh(
new THREE.IcosahedronGeometry(baseRadius * 0.48, 0),
coralTipMaterial
);
tip.position.set(...points[points.length - 1]);
tip.castShadow = true;
coral.add(tip);
}
const branchDefinitions = [
{
points: [
[-0.78, 0.04, 0.34],
[-0.92, 0.42, 0.29],
[-0.83, 0.78, 0.18],
[-0.98, 1.16, 0.08]
],
radius: 0.145
},
{
points: [
[-0.57, 0.04, 0.08],
[-0.66, 0.46, 0.03],
[-0.55, 0.83, -0.02],
[-0.68, 1.18, -0.08]
],
radius: 0.125
},
{
points: [
[-0.84, 0.74, 0.18],
[-0.68, 1.12, 0.14],
[-0.42, 1.39, 0.08],
[-0.30, 1.68, 0.02]
],
radius: 0.115
},
{
points: [
[0.78, 0.04, 0.34],
[0.92, 0.42, 0.29],
[0.83, 0.78, 0.18],
[0.98, 1.16, 0.08]
],
radius: 0.145
},
{
points: [
[0.57, 0.04, 0.08],
[0.66, 0.46, 0.03],
[0.55, 0.83, -0.02],
[0.68, 1.18, -0.08]
],
radius: 0.125
},
{
points: [
[0.84, 0.74, 0.18],
[0.68, 1.12, 0.14],
[0.42, 1.39, 0.08],
[0.30, 1.68, 0.02]
],
radius: 0.115
},
{
points: [
[-0.83, 0.04, 0.62],
[-1.04, 0.40, 0.55],
[-0.92, 0.78, 0.38],
[-1.08, 1.02, 0.30]
],
radius: 0.11
},
{
points: [
[0.83, 0.04, 0.62],
[1.04, 0.40, 0.55],
[0.92, 0.78, 0.38],
[1.08, 1.02, 0.30]
],
radius: 0.11
},
{
points: [
[-0.50, 0.04, -0.52],
[-0.74, 0.38, -0.48],
[-0.67, 0.75, -0.40],
[-0.85, 1.08, -0.35]
],
radius: 0.10
},
{
points: [
[0.50, 0.04, -0.52],
[0.74, 0.38, -0.48],
[0.67, 0.75, -0.40],
[0.85, 1.08, -0.35]
],
radius: 0.10
}
];
branchDefinitions.forEach((branch, index) => {
addCoralBranch(branch.points, branch.radius, index);
});
// A dark, recessed shape behind the branch opening.
const alcove = new THREE.Mesh(
new THREE.IcosahedronGeometry(1, 2),
new THREE.MeshStandardMaterial({
color: 0x291936,
roughness: 1,
flatShading: true
})
);
alcove.position.set(0, 0.79, -0.34);
alcove.scale.set(0.63, 0.77, 0.27);
alcove.receiveShadow = true;
coral.add(alcove);
const alcoveFloor = new THREE.Mesh(
new THREE.CircleGeometry(0.66, 18),
new THREE.MeshStandardMaterial({
color: 0x9d835b,
roughness: 1
})
);
alcoveFloor.rotation.x = -Math.PI / 2;
alcoveFloor.position.set(0, 0.006, -0.03);
alcoveFloor.receiveShadow = true;
coral.add(alcoveFloor);
// A shallow, flat-topped rock ledge beside the shelter.
const ledgeGroup = new THREE.Group();
ledgeGroup.position.set(3.85, 0, -1.18);
scene.add(ledgeGroup);
const ledgeSideMaterial = new THREE.MeshStandardMaterial({
color: 0x596d6a,
roughness: 0.96,
flatShading: true
});
const ledgeTopMaterial = new THREE.MeshStandardMaterial({
color: 0x81918a,
roughness: 0.94,
flatShading: true
});
const ledge = new THREE.Mesh(
new THREE.CylinderGeometry(1.18, 1.34, 0.30, 7, 1, false),
[ledgeSideMaterial, ledgeTopMaterial, ledgeSideMaterial]
);
ledge.position.y = 0.115;
ledge.scale.z = 0.64;
ledge.rotation.y = 0.18;
ledge.castShadow = true;
ledge.receiveShadow = true;
ledgeGroup.add(ledge);
const rockMaterial = new THREE.MeshStandardMaterial({
color: 0x71827d,
roughness: 1,
flatShading: true
});
[
[-0.45, 0.32, -0.12, 0.38, 0.20, 0.30],
[0.15, 0.34, 0.05, 0.44, 0.25, 0.34],
[0.62, 0.30, -0.16, 0.28, 0.16, 0.25]
].forEach((values, index) => {
const rock = new THREE.Mesh(
new THREE.DodecahedronGeometry(1, 0),
rockMaterial
);
rock.position.set(values[0], values[1], values[2]);
rock.scale.set(values[3], values[4], values[5]);
rock.rotation.set(index * 0.3, index * 0.7, index * 0.2);
rock.castShadow = true;
rock.receiveShadow = true;
ledgeGroup.add(rock);
});
// Common clownfish texture generated locally.
function createClownfishTexture() {
const canvas = document.createElement("canvas");
canvas.width = 1024;
canvas.height = 256;
const context = canvas.getContext("2d");
context.fillStyle = "#ef7920";
context.fillRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < 220; i++) {
context.fillStyle = `rgba(255,205,90,${0.025 + random() * 0.04})`;
context.fillRect(
random() * canvas.width,
random() * canvas.height,
2 + random() * 8,
1 + random() * 3
);
}
function band(center, blackWidth, whiteWidth) {
context.fillStyle = "#111820";
context.fillRect(
center - blackWidth / 2,
0,
blackWidth,
canvas.height
);
context.fillStyle = "#fff8e6";
context.fillRect(
center - whiteWidth / 2,
0,
whiteWidth,
canvas.height
);
}
// Caudal, middle, and head bars.
band(175, 62, 39);
band(515, 66, 42);
band(835, 62, 38);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(
8,
renderer.capabilities.getMaxAnisotropy()
);
return texture;
}
// Custom low-poly body whose UV length follows the fish's head-to-tail axis.
function createClownfishBodyGeometry() {
const rings = [
{ x: -0.58, radius: 0.025 },
{ x: -0.48, radius: 0.17 },
{ x: -0.27, radius: 0.28 },
{ x: 0.02, radius: 0.34 },
{ x: 0.30, radius: 0.31 },
{ x: 0.53, radius: 0.235 },
{ x: 0.70, radius: 0.13 },
{ x: 0.78, radius: 0.018 }
];
const segments = 14;
const positions = [];
const uvs = [];
const indices = [];
rings.forEach((ring, ringIndex) => {
for (let segment = 0; segment <= segments; segment++) {
const angle = (segment / segments) * Math.PI * 2;
positions.push(
ring.x,
Math.sin(angle) * ring.radius * 0.92,
Math.cos(angle) * ring.radius * 0.70
);
uvs.push(
ringIndex / (rings.length - 1),
segment / segments
);
}
});
for (let ring = 0; ring < rings.length - 1; ring++) {
for (let segment = 0; segment < segments; segment++) {
const a = ring * (segments + 1) + segment;
const b = (ring + 1) * (segments + 1) + segment;
const c = b + 1;
const d = a + 1;
indices.push(a, b, d, b, c, d);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setAttribute(
"uv",
new THREE.Float32BufferAttribute(uvs, 2)
);
geometry.setIndex(indices);
geometry.computeVertexNormals();
return geometry;
}
function createShapeGeometry(points) {
const shape = new THREE.Shape();
shape.moveTo(points[0][0], points[0][1]);
for (let i = 1; i < points.length; i++) {
shape.lineTo(points[i][0], points[i][1]);
}
shape.closePath();
return new THREE.ShapeGeometry(shape);
}
const fishRoot = new THREE.Group();
const fishVisual = new THREE.Group();
fishRoot.add(fishVisual);
scene.add(fishRoot);
const fishTexture = createClownfishTexture();
const fishBody = new THREE.Mesh(
createClownfishBodyGeometry(),
new THREE.MeshStandardMaterial({
map: fishTexture,
roughness: 0.56,
metalness: 0,
flatShading: true
})
);
fishBody.castShadow = true;
fishBody.receiveShadow = true;
fishVisual.add(fishBody);
const orangeFinMaterial = new THREE.MeshStandardMaterial({
color: 0xf27a20,
roughness: 0.68,
flatShading: true,
side: THREE.DoubleSide
});
const blackFinMaterial = new THREE.MeshStandardMaterial({
color: 0x111820,
roughness: 0.76,
flatShading: true,
side: THREE.DoubleSide
});
// Rounded, black-edged tail.
const tailPivot = new THREE.Group();
tailPivot.position.set(-0.55, 0, 0);
fishVisual.add(tailPivot);
const tailOuter = new THREE.Mesh(
createShapeGeometry([
[0, 0.03],
[-0.18, 0.22],
[-0.40, 0.31],
[-0.50, 0.19],
[-0.47, 0],
[-0.50, -0.19],
[-0.40, -0.31],
[-0.18, -0.22],
[0, -0.03]
]),
blackFinMaterial
);
tailOuter.castShadow = true;
tailPivot.add(tailOuter);
const tailInner = new THREE.Mesh(
createShapeGeometry([
[0, 0.02],
[-0.14, 0.15],
[-0.32, 0.21],
[-0.39, 0],
[-0.32, -0.21],
[-0.14, -0.15],
[0, -0.02]
]),
orangeFinMaterial
);
tailInner.position.z = 0.006;
tailInner.castShadow = true;
tailPivot.add(tailInner);
// Long rounded dorsal fin.
const dorsalOuter = new THREE.Mesh(
createShapeGeometry([
[-0.43, 0.17],
[-0.33, 0.39],
[-0.10, 0.49],
[0.16, 0.46],
[0.43, 0.28],
[0.47, 0.16]
]),
blackFinMaterial
);
dorsalOuter.castShadow = true;
fishVisual.add(dorsalOuter);
const dorsalInner = new THREE.Mesh(
createShapeGeometry([
[-0.32, 0.20],
[-0.25, 0.32],
[-0.06, 0.39],
[0.14, 0.36],
[0.34, 0.25],
[0.37, 0.19]
]),
orangeFinMaterial
);
dorsalInner.position.z = 0.006;
fishVisual.add(dorsalInner);
// Rounded anal fin.
const analOuter = new THREE.Mesh(
createShapeGeometry([
[-0.34, -0.16],
[-0.20, -0.38],
[0.10, -0.40],
[0.35, -0.24],
[0.40, -0.12]
]),
blackFinMaterial
);
analOuter.castShadow = true;
fishVisual.add(analOuter);
const analInner = new THREE.Mesh(
createShapeGeometry([
[-0.25, -0.19],
[-0.16, -0.31],
[0.08, -0.32],
[0.27, -0.22],
[0.31, -0.15]
]),
orangeFinMaterial
);
analInner.position.z = 0.006;
fishVisual.add(analInner);
// Paired pectoral fins with a subtle flutter.
const pectoralPivots = [];
[-1, 1].forEach((side) => {
const pivot = new THREE.Group();
pivot.position.set(0.25, -0.015, side * 0.215);
pivot.rotation.y = side < 0 ? Math.PI : 0;
fishVisual.add(pivot);
const outer = new THREE.Mesh(
createShapeGeometry([
[0.03, 0.01],
[-0.12, -0.08],
[-0.29, -0.25],
[-0.13, -0.31],
[0.03, -0.12]
]),
blackFinMaterial
);
outer.castShadow = true;
pivot.add(outer);
const inner = new THREE.Mesh(
createShapeGeometry([
[0.01, 0],
[-0.09, -0.07],
[-0.21, -0.20],
[-0.11, -0.24],
[0.01, -0.09]
]),
orangeFinMaterial
);
inner.position.z = 0.006;
pivot.add(inner);
pectoralPivots.push({ pivot, side });
});
// Paired pelvic fins.
[-1, 1].forEach((side) => {
const pelvic = new THREE.Mesh(
createShapeGeometry([
[0.05, 0],
[-0.11, -0.20],
[0.02, -0.31],
[0.15, -0.12]
]),
orangeFinMaterial
);
pelvic.position.set(0.34, -0.23, side * 0.09);
pelvic.rotation.y = side < 0 ? Math.PI : 0;
pelvic.castShadow = true;
fishVisual.add(pelvic);
});
// Dark eyes with small highlights.
[-1, 1].forEach((side) => {
const eye = new THREE.Mesh(
new THREE.SphereGeometry(0.065, 10, 8),
new THREE.MeshStandardMaterial({
color: 0x081016,
roughness: 0.38,
flatShading: true
})
);
eye.position.set(0.54, 0.095, side * 0.177);
eye.scale.z = 0.62;
eye.castShadow = true;
fishVisual.add(eye);
const glint = new THREE.Mesh(
new THREE.SphereGeometry(0.017, 7, 6),
new THREE.MeshBasicMaterial({ color: 0xfffbe8 })
);
glint.position.set(0.558, 0.12, side * 0.216);
fishVisual.add(glint);
});
const mouth = new THREE.Mesh(
new THREE.BoxGeometry(0.075, 0.014, 0.025),
new THREE.MeshBasicMaterial({ color: 0x4a180e })
);
mouth.position.set(0.753, -0.035, 0.083);
fishVisual.add(mouth);
fishVisual.scale.setScalar(0.95);
// Suspended particles provide quiet underwater motion.
const particleCount = 85;
const particlePositions = new Float32Array(particleCount * 3);
const particleBaseX = new Float32Array(particleCount);
const particlePhase = new Float32Array(particleCount);
const particleSpeed = new Float32Array(particleCount);
for (let i = 0; i < particleCount; i++) {
const x = (random() - 0.5) * 13;
const y = 0.25 + random() * 5.8;
const z = (random() - 0.5) * 11;
particlePositions[i * 3] = x;
particlePositions[i * 3 + 1] = y;
particlePositions[i * 3 + 2] = z;
particleBaseX[i] = x;
particlePhase[i] = random() * Math.PI * 2;
particleSpeed[i] = 0.035 + random() * 0.055;
}
const particleGeometry = new THREE.BufferGeometry();
particleGeometry.setAttribute(
"position",
new THREE.BufferAttribute(particlePositions, 3)
);
const particles = new THREE.Points(
particleGeometry,
new THREE.PointsMaterial({
color: 0xd7ffff,
size: 0.028,
transparent: true,
opacity: 0.38,
depthWrite: false,
sizeAttenuation: true
})
);
scene.add(particles);
// The fish follows a small ellipse outside the coral's branch envelope.
// The ellipse's minimum radius is 1.58, while the coral reaches about
// 1.10, so the fish never travels through the separated branches.
const route = {
radiusX: 2.18,
radiusZ: 1.58,
speed: 0.22
};
let routeAngle = 0.55;
let cruiseClock = 0;
let nextPauseAt = 3.8;
let pauseRemaining = 0;
let pauseCount = 0;
let behavior = "cruise";
let manualPaused = false;
let simulationTime = 0;
let tailAmplitude = 0.16;
function restartCircuit() {
routeAngle = 0.55;
cruiseClock = 0;
nextPauseAt = 3.8;
pauseRemaining = 0;
pauseCount = 0;
behavior = "cruise";
}
function toggleMotion() {
manualPaused = !manualPaused;
pauseButton.textContent = manualPaused
? "Resume motion"
: "Pause motion";
}
pauseButton.addEventListener("click", toggleMotion);
restartButton.addEventListener("click", restartCircuit);
function updateFish(deltaTime) {
if (pauseRemaining > 0) {
pauseRemaining -= deltaTime;
behavior = "pause";
} else {
routeAngle =
(routeAngle + route.speed * deltaTime) % (Math.PI * 2);
cruiseClock += deltaTime;
if (cruiseClock >= nextPauseAt) {
pauseRemaining = 1.9 + (pauseCount % 2) * 0.45;
nextPauseAt += 10.3;
pauseCount++;
behavior = "pause";
} else {
behavior = "cruise";
}
}
const x = Math.cos(routeAngle) * route.radiusX;
const z = Math.sin(routeAngle) * route.radiusZ;
fishRoot.position.set(x, 0, z);
const tangentX = -Math.sin(routeAngle) * route.radiusX;
const tangentZ = Math.cos(routeAngle) * route.radiusZ;
// The fish model's forward axis is +X.
fishRoot.rotation.y = Math.atan2(-tangentZ, tangentX);
const bob = Math.sin(simulationTime * 0.82) * 0.025;
fishVisual.position.y = 1.03 + bob;
fishVisual.rotation.z = Math.sin(simulationTime * 0.67) * 0.022;
const targetAmplitude = behavior === "pause" ? 0.075 : 0.16;
tailAmplitude +=
(targetAmplitude - tailAmplitude) *
Math.min(1, deltaTime * 4.0);
const tailFrequency = behavior === "pause" ? 1.25 : 2.25;
tailPivot.rotation.z =
Math.sin(simulationTime * tailFrequency) * tailAmplitude;
pectoralPivots.forEach(({ pivot, side }, index) => {
const flutter =
0.10 + Math.sin(simulationTime * 2.7 + index * 0.4) * 0.11;
pivot.rotation.x = side * flutter;
});
}
function updateParticles(deltaTime) {
const positions = particleGeometry.attributes.position;
for (let i = 0; i < particleCount; i++) {
let y = positions.getY(i) + particleSpeed[i] * deltaTime;
if (y > 6.1) y = 0.18;
positions.setY(i, y);
positions.setX(
i,
particleBaseX[i] +
Math.sin(simulationTime * 0.28 + particlePhase[i]) * 0.075
);
}
positions.needsUpdate = true;
}
function updateStatus() {
let text;
let isPaused = false;
if (manualPaused) {
text = "Motion paused";
isPaused = true;
} else if (behavior === "pause") {
text = "Brief pause beside the shelter";
isPaused = true;
} else {
text = "Slow circuit around the coral";
}
if (statusText.textContent !== text) {
statusText.textContent = text;
}
statusDot.classList.toggle("paused", isPaused);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
updateCamera();
let previousTime = performance.now();
renderer.setAnimationLoop((now) => {
const deltaTime = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (!manualPaused) {
simulationTime += deltaTime;
updateFish(deltaTime);
updateParticles(deltaTime);
}
updateStatus();
updateCamera();
renderer.render(scene, camera);
});
</script>
</body>
</html>
```