Prompt specification
Build or customize the Three.js 3D scene "Rainbow viewpoint exploration rig" 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: Rainbow viewpoint exploration rig
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/rainbow-viewpoint-exploration-rig-x1240
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing a voxel rainbow-viewing rig above a small field. A movable observer stands between the viewer and a cloud of droplet-location markers, with a fixed sunlight direction behind the observer. Treat the optical calculation as a simplified spherical-droplet model even though the landscape and markers use cubic geometry. Highlight only droplet directions that satisfy the chosen rainbow-angle approximation, and redraw the selected arc when the observer moves. Add a ground projection of the antisolar direction and one enlarged ray-path inset. The rainbow should follow viewing geometry rather than remain painted at a fixed position in the landscape.
Working Three.js Starter (rainbow-viewpoint-exploration-rig-x1240):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Rainbow Viewing Rig</title>
<style>
:root {
color-scheme: dark;
--panel: rgba(8, 18, 32, 0.82);
--panel-border: rgba(155, 213, 255, 0.2);
--text: #e9f5ff;
--muted: #91a9ba;
--cyan: #75e7ff;
--amber: #ffd27d;
--violet: #b59cff;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--text);
background:
radial-gradient(circle at 50% 20%, #17304b 0%, #091727 48%, #050b14 100%);
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
#app {
position: fixed;
inset: 0;
}
.panel {
position: fixed;
z-index: 10;
border: 1px solid var(--panel-border);
background: var(--panel);
box-shadow: 0 18px 55px rgba(0, 0, 0, 0.32);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
header {
top: 18px;
left: 18px;
right: 18px;
min-height: 70px;
border-radius: 16px;
display: flex;
align-items: center;
justify-content: space-between;
padding: 13px 17px;
pointer-events: none;
}
.eyebrow {
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 3px 0 0;
font-size: clamp(17px, 2vw, 24px);
font-weight: 700;
letter-spacing: -0.025em;
}
.header-stats {
display: flex;
align-items: center;
gap: 9px;
flex-wrap: wrap;
justify-content: flex-end;
}
.stat {
min-width: 104px;
padding: 8px 10px;
border: 1px solid rgba(255, 255, 255, 0.09);
border-radius: 10px;
background: rgba(255, 255, 255, 0.035);
}
.stat span {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.stat strong {
display: block;
margin-top: 3px;
font-size: 13px;
font-variant-numeric: tabular-nums;
}
#controls {
left: 18px;
bottom: 18px;
width: 292px;
border-radius: 16px;
padding: 16px;
}
.control-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 14px;
font-size: 12px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.control-title .dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 12px var(--cyan);
}
.control {
margin-top: 14px;
}
.control label {
display: flex;
justify-content: space-between;
gap: 12px;
margin-bottom: 8px;
color: #c9dbe8;
font-size: 12px;
}
output {
color: var(--cyan);
font-weight: 750;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
border-radius: 99px;
appearance: none;
-webkit-appearance: none;
background: linear-gradient(90deg, #4f91b4, #7eeaff);
outline: none;
}
input[type="range"]::-webkit-slider-thumb {
width: 17px;
height: 17px;
border: 3px solid #e7faff;
border-radius: 50%;
appearance: none;
-webkit-appearance: none;
background: #1b526f;
box-shadow: 0 0 0 4px rgba(117, 231, 255, 0.12);
cursor: pointer;
}
input[type="range"]::-moz-range-thumb {
width: 13px;
height: 13px;
border: 3px solid #e7faff;
border-radius: 50%;
background: #1b526f;
box-shadow: 0 0 0 4px rgba(117, 231, 255, 0.12);
cursor: pointer;
}
.control small {
display: block;
margin-top: 7px;
color: var(--muted);
font-size: 10px;
line-height: 1.4;
}
.toggle-row {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 16px;
padding-top: 13px;
border-top: 1px solid rgba(255, 255, 255, 0.08);
color: #c9dbe8;
font-size: 12px;
}
.toggle-row input {
accent-color: var(--cyan);
}
button {
width: 100%;
margin-top: 12px;
padding: 9px 12px;
border: 1px solid rgba(117, 231, 255, 0.25);
border-radius: 9px;
color: var(--text);
background: rgba(117, 231, 255, 0.08);
font: inherit;
font-size: 11px;
font-weight: 750;
cursor: pointer;
}
button:hover {
background: rgba(117, 231, 255, 0.15);
}
#inset {
right: 18px;
bottom: 18px;
width: 440px;
border-radius: 16px;
overflow: hidden;
}
.inset-head {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 14px 8px;
}
.inset-head strong {
font-size: 11px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.inset-head span {
color: var(--muted);
font-size: 10px;
}
#inset svg {
display: block;
width: 100%;
height: auto;
}
.inset-caption {
padding: 0 14px 13px;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.scene-label {
position: fixed;
z-index: 5;
pointer-events: none;
transform: translate(-50%, -100%);
padding: 4px 7px;
border: 1px solid rgba(255, 255, 255, 0.14);
border-radius: 6px;
color: white;
background: rgba(3, 10, 18, 0.72);
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.18);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
white-space: nowrap;
}
#label-anti { color: var(--violet); }
#label-sun { color: var(--amber); }
#hint {
position: fixed;
z-index: 7;
left: 50%;
bottom: 19px;
transform: translateX(-50%);
padding: 7px 11px;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 99px;
color: rgba(232, 246, 255, 0.78);
background: rgba(4, 12, 21, 0.66);
font-size: 10px;
pointer-events: none;
white-space: nowrap;
}
#loading {
position: fixed;
z-index: 50;
inset: 0;
display: grid;
place-items: center;
color: var(--cyan);
background: #07111f;
font-size: 12px;
letter-spacing: 0.14em;
text-transform: uppercase;
}
@media (max-width: 900px) {
#inset { width: 350px; }
#controls { width: 260px; }
.header-stats .stat:nth-child(2) { display: none; }
}
@media (max-width: 680px) {
header {
top: 10px;
left: 10px;
right: 10px;
}
.header-stats { display: none; }
#controls {
left: 10px;
bottom: 10px;
width: 225px;
padding: 12px;
}
#inset {
top: 92px;
right: 10px;
bottom: auto;
width: 260px;
}
.inset-caption, #hint { display: none; }
}
</style>
</head>
<body>
<div id="app"></div>
<header class="panel">
<div>
<div class="eyebrow">Geometric Optics / Voxel Field Study</div>
<h1>Primary Rainbow Viewing Rig</h1>
</div>
<div class="header-stats">
<div class="stat">
<span>Observer</span>
<strong id="observerStat">x = 0.0 m</strong>
</div>
<div class="stat">
<span>Rainbow radius</span>
<strong id="angleStat">42.0°</strong>
</div>
<div class="stat">
<span>Selected droplets</span>
<strong id="dropletStat">0</strong>
</div>
</div>
</header>
<section id="controls" class="panel">
<div class="control-title">
Viewing controls
<span class="dot"></span>
</div>
<div class="control">
<label for="observerRange">
Observer position
<output id="observerOutput">0.0 m</output>
</label>
<input id="observerRange" type="range" min="-5" max="5" step="0.05" value="0">
<small>The observer stays between the viewer and the droplet cloud.</small>
</div>
<div class="control">
<label for="angleRange">
Primary rainbow angle
<output id="angleOutput">42.0°</output>
</label>
<input id="angleRange" type="range" min="38" max="44" step="0.1" value="42">
<small>Simplified one-reflection spherical-droplet approximation.</small>
</div>
<div class="toggle-row">
<label for="coneToggle">Show 42° viewing cone</label>
<input id="coneToggle" type="checkbox" checked>
</div>
<button id="resetButton" type="button">Reset observer and camera</button>
</section>
<section id="inset" class="panel">
<div class="inset-head">
<strong>Enlarged ray-path model</strong>
<span>Primary bow / one internal reflection</span>
</div>
<svg viewBox="0 0 440 235" role="img" aria-label="Enlarged simplified primary rainbow ray path">
<defs>
<radialGradient id="dropFill" cx="35%" cy="30%">
<stop offset="0" stop-color="#d8f6ff" stop-opacity=".46"/>
<stop offset=".7" stop-color="#65b7dc" stop-opacity=".15"/>
<stop offset="1" stop-color="#244d6c" stop-opacity=".34"/>
</radialGradient>
<linearGradient id="sunRay" x1="0" y1="1" x2="1" y2="0">
<stop stop-color="#ffc65f"/>
<stop offset="1" stop-color="#fff1b3"/>
</linearGradient>
<marker id="arrowAmber" markerWidth="7" markerHeight="7"
refX="6" refY="3.5" orient="auto">
<path d="M0,0 L7,3.5 L0,7 Z" fill="#ffd782"/>
</marker>
<marker id="arrowCyan" markerWidth="7" markerHeight="7"
refX="6" refY="3.5" orient="auto">
<path d="M0,0 L7,3.5 L0,7 Z" fill="#8ceeff"/>
</marker>
<marker id="arrowViolet" markerWidth="7" markerHeight="7"
refX="6" refY="3.5" orient="auto">
<path d="M0,0 L7,3.5 L0,7 Z" fill="#b9a6ff"/>
</marker>
</defs>
<rect width="440" height="235" rx="10" fill="#081522"/>
<path d="M18 20 H422" stroke="#ffffff" stroke-opacity=".08"/>
<!-- Sun and incident ray -->
<g transform="translate(58 172)">
<circle r="21" fill="#ffd77e" opacity=".13"/>
<circle r="13" fill="#ffd77e"/>
<g fill="#ffe9a8">
<rect x="-2" y="-25" width="4" height="7"/>
<rect x="-2" y="18" width="4" height="7"/>
<rect x="-25" y="-2" width="7" height="4"/>
<rect x="18" y="-2" width="7" height="4"/>
</g>
</g>
<path d="M79 160 L204 112" fill="none" stroke="url(#sunRay)"
stroke-width="3" marker-end="url(#arrowAmber)"/>
<!-- Droplet -->
<circle cx="224" cy="105" r="43" fill="url(#dropFill)"
stroke="#a8e5ff" stroke-opacity=".55" stroke-width="1.5"/>
<circle cx="212" cy="92" r="8" fill="#fff" opacity=".18"/>
<!-- Internal path -->
<path d="M207 102
C229 83 250 98 239 119
C229 139 202 130 210 110
C216 95 237 94 244 108"
fill="none" stroke="#8ceeff" stroke-width="2.2"
stroke-linecap="round" marker-end="url(#arrowCyan)"/>
<!-- Emergent ray to observer -->
<path d="M242 116 L57 61" fill="none" stroke="#9eeeff"
stroke-width="2.7" marker-end="url(#arrowCyan)"/>
<!-- Observer -->
<g transform="translate(43 50)">
<circle cx="0" cy="11" r="17" fill="#74e5ff" opacity=".08"/>
<rect x="-5" y="-1" width="10" height="13" rx="2" fill="#dcecf5"/>
<circle cy="-7" r="6" fill="#f0d0ad"/>
<path d="M-7 -11 Q0 -19 7 -11" fill="none" stroke="#74e5ff" stroke-width="3"/>
</g>
<text x="32" y="31" fill="#ffd782" font-size="10" font-weight="700">SUNLIGHT</text>
<text x="19" y="47" fill="#9eeeff" font-size="10" font-weight="700">OBSERVER</text>
<text x="200" y="57" fill="#bceeff" font-size="10" font-weight="700">SPHERICAL DROP</text>
<!-- Right-side angular explanation -->
<g transform="translate(290 27)">
<rect width="132" height="178" rx="10" fill="#0d2031" stroke="#ffffff" stroke-opacity=".09"/>
<text x="66" y="22" text-anchor="middle" fill="#91a9ba"
font-size="8" font-weight="700" letter-spacing="1">VIEW GEOMETRY</text>
<circle cx="66" cy="132" r="5" fill="#f3f7fa"/>
<text x="66" y="151" text-anchor="middle" fill="#d9edf8"
font-size="9" font-weight="700">OBSERVER</text>
<path d="M66 128 L47 59" stroke="#b9a6ff" stroke-width="2"
marker-end="url(#arrowViolet)"/>
<path d="M66 128 L91 69" stroke="#8ceeff" stroke-width="2"
marker-end="url(#arrowCyan)"/>
<path d="M61 118 A54 54 0 0 0 58 107" fill="none"
stroke="#ffffff" stroke-width="1.5"/>
<text x="50" y="94" fill="#d7caff" font-size="8">A</text>
<text x="94" y="94" fill="#c7f6ff" font-size="8">V</text>
<text x="69" y="105" text-anchor="middle" fill="#ffffff"
font-size="12" font-weight="800" id="svgAngle">42°</text>
<text x="66" y="169" text-anchor="middle" fill="#91a9ba"
font-size="8">angle from antisolar axis</text>
</g>
<text x="18" y="222" fill="#91a9ba" font-size="9">
Δ ≈ 138° deviation; rainbow radius ≈ 180° − Δ
</text>
</svg>
<div class="inset-caption">
The highlighted locus is recomputed from the observer-to-droplet vector and the
fixed antisolar axis. It is not fixed to the landscape.
</div>
</section>
<div id="label-observer" class="scene-label">Observer</div>
<div id="label-cloud" class="scene-label">Droplet cloud</div>
<div id="label-anti" class="scene-label">Antisolar ground projection</div>
<div id="label-sun" class="scene-label">Fixed sun direction</div>
<div id="hint">Drag observer to move · Drag background to orbit · Scroll to zoom</div>
<div id="loading">Loading voxel optics rig…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const app = document.getElementById("app");
const loading = document.getElementById("loading");
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.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
app.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 34, 72);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
140
);
// Direct camera controls: no examples/addons are used.
const cameraState = {
target: new THREE.Vector3(0, 4.0, -3.5),
distance: 31,
azimuth: 0.32,
elevation: 0.29,
targetDistance: 31,
targetAzimuth: 0.32,
targetElevation: 0.29
};
function updateCamera() {
const { target, distance, azimuth, elevation } = cameraState;
camera.position.set(
target.x + distance * Math.cos(elevation) * Math.sin(azimuth),
target.y + distance * Math.sin(elevation),
target.z + distance * Math.cos(elevation) * Math.cos(azimuth)
);
camera.lookAt(target);
}
updateCamera();
scene.add(new THREE.HemisphereLight(0xb9ddff, 0x243425, 1.75));
// A fixed global sunlight vector. Positive Z is behind the observer.
const sunElevation = THREE.MathUtils.degToRad(12);
const sunDirection = new THREE.Vector3(
0,
Math.sin(sunElevation),
Math.cos(sunElevation)
).normalize();
const antisolarDirection = sunDirection.clone().negate();
const sunLight = new THREE.DirectionalLight(0xffd69a, 2.7);
sunLight.position.copy(sunDirection).multiplyScalar(52);
sunLight.position.add(new THREE.Vector3(0, 2, -3));
sunLight.target.position.set(0, 2, -3);
sunLight.castShadow = true;
sunLight.shadow.mapSize.set(1024, 1024);
sunLight.shadow.camera.left = -20;
sunLight.shadow.camera.right = 20;
sunLight.shadow.camera.top = 20;
sunLight.shadow.camera.bottom = -20;
sunLight.shadow.camera.near = 1;
sunLight.shadow.camera.far = 90;
scene.add(sunLight, sunLight.target);
const fillLight = new THREE.DirectionalLight(0x7ebcff, 0.7);
fillLight.position.set(-15, 13, 8);
scene.add(fillLight);
const world = {
observerX: 0,
rainbowAngle: THREE.MathUtils.degToRad(42),
observerZ: 1,
eyeHeight: 2.08,
cloudZ: -10.35
};
const dummy = new THREE.Object3D();
const eye = new THREE.Vector3();
const temp = new THREE.Vector3();
const temp2 = new THREE.Vector3();
// -----------------------------------------------------------------------
// Voxel landscape
// -----------------------------------------------------------------------
const terrain = new THREE.Group();
scene.add(terrain);
const tileCountX = 29;
const tileCountZ = 24;
const tileGeometry = new THREE.BoxGeometry(0.94, 1, 0.94);
const tileMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.94,
metalness: 0.02
});
const tiles = new THREE.InstancedMesh(
tileGeometry,
tileMaterial,
tileCountX * tileCountZ
);
tiles.receiveShadow = true;
tiles.castShadow = false;
let tileIndex = 0;
for (let ix = 0; ix < tileCountX; ix++) {
for (let iz = 0; iz < tileCountZ; iz++) {
const x = -14 + ix;
const z = -13 + iz;
const path = z > -1 && z < 4 && Math.abs(x) < 12;
const noise =
Math.sin(ix * 1.73 + iz * 0.61) * 0.5 +
Math.cos(ix * 0.47 - iz * 1.31) * 0.5;
const height = path
? 0.20 + 0.04 * Math.sin(ix * 2.1)
: 0.28 + noise * 0.10;
dummy.position.set(x, height * 0.5 - 0.08, z);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, height, 1);
dummy.updateMatrix();
tiles.setMatrixAt(tileIndex, dummy.matrix);
const color = new THREE.Color();
if (path) {
color.setHSL(0.11, 0.24, 0.30 + noise * 0.025);
} else {
color.setHSL(0.29 + noise * 0.025, 0.31, 0.22 + noise * 0.025);
}
tiles.setColorAt(tileIndex, color);
tileIndex++;
}
}
tiles.instanceMatrix.needsUpdate = true;
if (tiles.instanceColor) tiles.instanceColor.needsUpdate = true;
terrain.add(tiles);
function addBox(parent, size, position, color, castShadow = true) {
const geometry = new THREE.BoxGeometry(size.x, size.y, size.z);
const material = new THREE.MeshStandardMaterial({
color,
roughness: 0.78,
metalness: 0.08
});
const mesh = new THREE.Mesh(geometry, material);
mesh.position.copy(position);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// Small cubic shrubs and trees around the field perimeter.
const vegetation = new THREE.Group();
terrain.add(vegetation);
const treePositions = [
[-12, -10], [-10, -11], [-8, -12], [-12, -5], [-13, 1],
[-12, 6], [-9, 7], [-6, 7], [8, 7], [11, 6], [13, 3],
[12, -3], [13, -7], [10, -11], [7, -12], [3, -12],
[-2, -12], [-5, -11]
];
for (const [x, z] of treePositions) {
const tree = new THREE.Group();
tree.position.set(x, 0, z);
tree.scale.setScalar(0.75 + ((x * 13 + z * 7) % 5) * 0.05);
addBox(tree, new THREE.Vector3(0.34, 1.55, 0.34),
new THREE.Vector3(0, 0.75, 0), 0x654a32);
addBox(tree, new THREE.Vector3(1.45, 0.95, 1.35),
new THREE.Vector3(0, 1.8, 0), 0x315f47);
addBox(tree, new THREE.Vector3(0.95, 0.82, 0.92),
new THREE.Vector3(0.13, 2.55, -0.04), 0x3d7657);
vegetation.add(tree);
}
// -----------------------------------------------------------------------
// Cubic droplet cloud and viewing rig
// -----------------------------------------------------------------------
const rig = new THREE.Group();
scene.add(rig);
const frameMaterial = new THREE.MeshStandardMaterial({
color: 0x31475b,
roughness: 0.55,
metalness: 0.42
});
function addFrameBox(size, position) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size.x, size.y, size.z),
frameMaterial
);
mesh.position.copy(position);
mesh.castShadow = true;
rig.add(mesh);
}
addFrameBox(
new THREE.Vector3(0.28, 12.3, 0.28),
new THREE.Vector3(-14.2, 6.0, -11.35)
);
addFrameBox(
new THREE.Vector3(0.28, 12.3, 0.28),
new THREE.Vector3(14.2, 6.0, -11.35)
);
addFrameBox(
new THREE.Vector3(28.7, 0.28, 0.28),
new THREE.Vector3(0, 12.15, -11.35)
);
const markerPoints = [];
const jitter = (n) => {
const v = Math.sin(n * 127.1 + 311.7) * 43758.5453;
return (v - Math.floor(v)) - 0.5;
};
let markerId = 0;
for (let ix = -25; ix <= 25; ix++) {
for (let iy = 0; iy <= 24; iy++) {
for (let layer = 0; layer < 3; layer++) {
const x = ix * 0.55 + jitter(markerId + 1) * 0.16;
const y = 0.42 + iy * 0.49 + jitter(markerId + 2) * 0.13;
const z = world.cloudZ - layer * 0.42 + jitter(markerId + 3) * 0.10;
markerPoints.push(new THREE.Vector3(x, y, z));
markerId++;
}
}
}
const markerGeometry = new THREE.BoxGeometry(0.105, 0.105, 0.105);
const markerMaterial = new THREE.MeshStandardMaterial({
color: 0x7893a8,
roughness: 0.8,
metalness: 0.02
});
const markerMesh = new THREE.InstancedMesh(
markerGeometry,
markerMaterial,
markerPoints.length
);
for (let i = 0; i < markerPoints.length; i++) {
dummy.position.copy(markerPoints[i]);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
markerMesh.setMatrixAt(i, dummy.matrix);
}
markerMesh.instanceMatrix.needsUpdate = true;
rig.add(markerMesh);
const highlightedGeometry = new THREE.BoxGeometry(0.22, 0.22, 0.22);
const highlightedMaterial = new THREE.MeshBasicMaterial({
color: 0xffffff
});
const highlightedMesh = new THREE.InstancedMesh(
highlightedGeometry,
highlightedMaterial,
markerPoints.length
);
highlightedMesh.count = 0;
highlightedMesh.frustumCulled = false;
highlightedMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
rig.add(highlightedMesh);
// -----------------------------------------------------------------------
// Movable cubic observer
// -----------------------------------------------------------------------
const observer = new THREE.Group();
observer.position.set(world.observerX, 0, world.observerZ);
scene.add(observer);
const coat = new THREE.MeshStandardMaterial({
color: 0xffa84d,
roughness: 0.75
});
const pants = new THREE.MeshStandardMaterial({
color: 0x26374c,
roughness: 0.88
});
const skin = new THREE.MeshStandardMaterial({
color: 0xe6b58f,
roughness: 0.9
});
const dark = new THREE.MeshStandardMaterial({
color: 0x172333,
roughness: 0.86
});
function addObserverBox(size, position, material) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size.x, size.y, size.z),
material
);
mesh.position.copy(position);
mesh.castShadow = true;
mesh.receiveShadow = true;
observer.add(mesh);
return mesh;
}
addObserverBox(new THREE.Vector3(0.28, 0.8, 0.30),
new THREE.Vector3(-0.22, 0.40, 0), pants);
addObserverBox(new THREE.Vector3(0.28, 0.8, 0.30),
new THREE.Vector3(0.22, 0.40, 0), pants);
addObserverBox(new THREE.Vector3(0.30, 0.17, 0.48),
new THREE.Vector3(-0.22, 0.08, -0.05), dark);
addObserverBox(new THREE.Vector3(0.30, 0.17, 0.48),
new THREE.Vector3(0.22, 0.08, -0.05), dark);
addObserverBox(new THREE.Vector3(0.82, 0.82, 0.48),
new THREE.Vector3(0, 1.20, 0), coat);
addObserverBox(new THREE.Vector3(0.19, 0.70, 0.24),
new THREE.Vector3(-0.53, 1.22, 0), coat);
addObserverBox(new THREE.Vector3(0.19, 0.70, 0.24),
new THREE.Vector3(0.53, 1.22, 0), coat);
addObserverBox(new THREE.Vector3(0.60, 0.58, 0.56),
new THREE.Vector3(0, 1.91, 0), skin);
addObserverBox(new THREE.Vector3(0.64, 0.15, 0.59),
new THREE.Vector3(0, 2.20, 0.015), dark);
addObserverBox(new THREE.Vector3(0.62, 0.07, 0.17),
new THREE.Vector3(0, 2.15, -0.34), dark);
// A small cyan instrument worn by the observer.
addObserverBox(new THREE.Vector3(0.34, 0.23, 0.12),
new THREE.Vector3(0, 1.35, -0.30),
new THREE.MeshStandardMaterial({
color: 0x6fe6ff,
emissive: 0x1c7189,
emissiveIntensity: 0.5,
roughness: 0.45
})
);
// Invisible, larger hit target for easy dragging.
const observerHit = new THREE.Mesh(
new THREE.BoxGeometry(1.5, 2.7, 1.3),
new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false
})
);
observerHit.position.y = 1.25;
observer.add(observerHit);
// Ground footprint follows the observer.
const footprint = new THREE.Group();
const footprintMaterial = new THREE.MeshBasicMaterial({
color: 0x5cd9f3,
transparent: true,
opacity: 0.56
});
for (let i = 0; i < 12; i++) {
const a = i / 12 * Math.PI * 2;
const block = new THREE.Mesh(
new THREE.BoxGeometry(0.16, 0.035, 0.16),
footprintMaterial
);
block.position.set(Math.cos(a) * 0.72, 0.03, Math.sin(a) * 0.72);
footprint.add(block);
}
scene.add(footprint);
// -----------------------------------------------------------------------
// Sun direction and antisolar ground projection
// -----------------------------------------------------------------------
const sunRayLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(), new THREE.Vector3()]),
new THREE.LineDashedMaterial({
color: 0xffd27d,
dashSize: 0.42,
gapSize: 0.22,
transparent: true,
opacity: 0.78
})
);
scene.add(sunRayLine);
const sunDirectionCube = new THREE.Mesh(
new THREE.BoxGeometry(0.35, 0.35, 0.35),
new THREE.MeshBasicMaterial({ color: 0xffd37d })
);
scene.add(sunDirectionCube);
const antiLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(), new THREE.Vector3()]),
new THREE.LineDashedMaterial({
color: 0xb59cff,
dashSize: 0.30,
gapSize: 0.18,
transparent: true,
opacity: 0.90
})
);
scene.add(antiLine);
const antiGround = new THREE.Group();
const antiMaterial = new THREE.MeshBasicMaterial({
color: 0xb59cff
});
for (let i = 0; i < 16; i++) {
const a = i / 16 * Math.PI * 2;
const block = new THREE.Mesh(
new THREE.BoxGeometry(0.22, 0.08, 0.22),
antiMaterial
);
block.position.set(Math.cos(a) * 0.85, 0.06, Math.sin(a) * 0.85);
block.rotation.y = a;
antiGround.add(block);
}
const antiCore = new THREE.Mesh(
new THREE.BoxGeometry(0.35, 0.13, 0.35),
antiMaterial
);
antiCore.position.y = 0.10;
antiGround.add(antiCore);
scene.add(antiGround);
// -----------------------------------------------------------------------
// Dynamic rainbow arc and viewing cone
// -----------------------------------------------------------------------
const rainbowGroup = new THREE.Group();
scene.add(rainbowGroup);
const coneGroup = new THREE.Group();
scene.add(coneGroup);
const coneLine = new THREE.LineSegments(
new THREE.BufferGeometry(),
new THREE.LineDashedMaterial({
color: 0x8bdcff,
transparent: true,
opacity: 0.22,
dashSize: 0.30,
gapSize: 0.25,
depthWrite: false
})
);
coneGroup.add(coneLine);
// Orthonormal basis around the antisolar axis.
const axisU = new THREE.Vector3(1, 0, 0);
axisU.addScaledVector(
antisolarDirection,
-axisU.dot(antisolarDirection)
).normalize();
const axisV = new THREE.Vector3()
.crossVectors(antisolarDirection, axisU)
.normalize();
function spectrumColor(t, target = new THREE.Color()) {
t = ((t % 1) + 1) % 1;
const hue = (0.99 - t * 0.79) % 1;
return target.setHSL(hue, 0.92, 0.60);
}
function directionAtAngle(phi, angle) {
return new THREE.Vector3()
.copy(antisolarDirection)
.multiplyScalar(Math.cos(angle))
.addScaledVector(axisU, Math.sin(angle) * Math.cos(phi))
.addScaledVector(axisV, Math.sin(angle) * Math.sin(phi))
.normalize();
}
function intersectCloudPlane(direction) {
if (Math.abs(direction.z) < 0.0001) return null;
const t = (world.cloudZ - eye.z) / direction.z;
if (t <= 0) return null;
return eye.clone().addScaledVector(direction, t);
}
let selectedDropletCount = 0;
function updateHighlightedDroplets() {
selectedDropletCount = 0;
const tolerance = THREE.MathUtils.degToRad(0.95);
const color = new THREE.Color();
for (const point of markerPoints) {
temp.copy(point).sub(eye);
const distance = temp.length();
if (distance < 0.001) continue;
temp.multiplyScalar(1 / distance);
const angle = Math.acos(THREE.MathUtils.clamp(
temp.dot(antisolarDirection),
-1,
1
));
if (Math.abs(angle - world.rainbowAngle) > tolerance) continue;
const phi = Math.atan2(temp.dot(axisV), temp.dot(axisU));
dummy.position.copy(point);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
highlightedMesh.setMatrixAt(selectedDropletCount, dummy.matrix);
spectrumColor(phi / (Math.PI * 2) + 0.48, color);
highlightedMesh.setColorAt(selectedDropletCount, color);
selectedDropletCount++;
}
highlightedMesh.count = selectedDropletCount;
highlightedMesh.instanceMatrix.needsUpdate = true;
if (highlightedMesh.instanceColor) {
highlightedMesh.instanceColor.needsUpdate = true;
}
}
function clearRainbowGeometry() {
while (rainbowGroup.children.length) {
const child = rainbowGroup.children[0];
child.geometry?.dispose();
if (child.material) {
if (Array.isArray(child.material)) {
child.material.forEach(m => m.dispose());
} else {
child.material.dispose();
}
}
rainbowGroup.remove(child);
}
}
function updateRainbowArc() {
clearRainbowGeometry();
const samples = [];
const sampleCount = 320;
for (let i = 0; i <= sampleCount; i++) {
const phi = -Math.PI + i / sampleCount * Math.PI * 2;
const direction = directionAtAngle(phi, world.rainbowAngle);
const point = intersectCloudPlane(direction);
const valid = point &&
point.y > 0.28 &&
Math.abs(point.x) < 18;
samples.push({ point, phi, valid });
}
// Find contiguous visible runs. This naturally omits the below-ground arc.
const runs = [];
let run = [];
for (const sample of samples) {
if (sample.valid) {
run.push(sample);
} else {
if (run.length > 1) runs.push(run);
run = [];
}
}
if (run.length > 1) runs.push(run);
for (const visibleRun of runs) {
const points = visibleRun.map(s => s.point);
const curve = new THREE.CatmullRomCurve3(points, false, "centripetal");
const segments = Math.max(24, visibleRun.length * 2);
const geometry = new THREE.TubeGeometry(
curve,
segments,
0.085,
6,
false
);
const colors = new Float32Array(geometry.attributes.position.count * 3);
const startPhase = visibleRun[0].phi / (Math.PI * 2) + 0.48;
const endPhase = visibleRun[visibleRun.length - 1].phi / (Math.PI * 2) + 0.48;
const color = new THREE.Color();
for (let i = 0; i < geometry.attributes.position.count; i++) {
const t = i / Math.max(1, geometry.attributes.position.count - 1);
spectrumColor(
THREE.MathUtils.lerp(startPhase, endPhase, t),
color
);
colors[i * 3] = color.r;
colors[i * 3 + 1] = color.g;
colors[i * 3 + 2] = color.b;
}
geometry.setAttribute("color", new THREE.BufferAttribute(colors, 3));
const arc = new THREE.Mesh(
geometry,
new THREE.MeshBasicMaterial({
vertexColors: true,
transparent: true,
opacity: 0.98,
depthWrite: false
})
);
rainbowGroup.add(arc);
// A wider transparent tube creates a restrained glow without postprocessing.
const glowGeometry = new THREE.TubeGeometry(
curve,
segments,
0.19,
6,
false
);
const glow = new THREE.Mesh(
glowGeometry,
new THREE.MeshBasicMaterial({
vertexColors: true,
transparent: true,
opacity: 0.14,
depthWrite: false,
blending: THREE.AdditiveBlending
})
);
rainbowGroup.add(glow);
}
}
function updateCone() {
const positions = [];
const rayCount = 16;
for (let i = 0; i < rayCount; i++) {
const phi = i / rayCount * Math.PI * 2;
const direction = directionAtAngle(phi, world.rainbowAngle);
const point = intersectCloudPlane(direction);
if (!point) continue;
positions.push(eye.x, eye.y, eye.z, point.x, point.y, point.z);
}
coneLine.geometry.dispose();
coneLine.geometry = new THREE.BufferGeometry();
coneLine.geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
coneLine.computeLineDistances();
}
// -----------------------------------------------------------------------
// Labels
// -----------------------------------------------------------------------
const labelElements = {
observer: document.getElementById("label-observer"),
cloud: document.getElementById("label-cloud"),
anti: document.getElementById("label-anti"),
sun: document.getElementById("label-sun")
};
const labelAnchors = {
observer: new THREE.Vector3(),
cloud: new THREE.Vector3(0, 12.8, -10.5),
anti: new THREE.Vector3(),
sun: new THREE.Vector3()
};
function updateLabels() {
const width = window.innerWidth;
const height = window.innerHeight;
for (const [key, element] of Object.entries(labelElements)) {
const projected = labelAnchors[key].clone().project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
projected.x > -1.08 &&
projected.x < 1.08 &&
projected.y > -1.08 &&
projected.y < 1.08;
element.style.display = visible ? "block" : "none";
if (!visible) continue;
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
element.style.left = `${x}px`;
element.style.top = `${y}px`;
}
}
// -----------------------------------------------------------------------
// Optical update
// -----------------------------------------------------------------------
const observerRange = document.getElementById("observerRange");
const observerOutput = document.getElementById("observerOutput");
const observerStat = document.getElementById("observerStat");
const angleRange = document.getElementById("angleRange");
const angleOutput = document.getElementById("angleOutput");
const angleStat = document.getElementById("angleStat");
const dropletStat = document.getElementById("dropletStat");
const coneToggle = document.getElementById("coneToggle");
const svgAngle = document.getElementById("svgAngle");
function updateOptics() {
observer.position.x = world.observerX;
footprint.position.set(world.observerX, 0, world.observerZ);
eye.set(
world.observerX,
world.eyeHeight,
world.observerZ - 0.28
);
// Fixed sunlight direction, but anchored at the moving observer.
const sunEnd = eye.clone().addScaledVector(sunDirection, 6.2);
sunRayLine.geometry.setFromPoints([eye, sunEnd]);
sunRayLine.computeLineDistances();
sunDirectionCube.position.copy(sunEnd);
// The antisolar ray is the exact opposite of the fixed sun vector.
const groundT = -eye.y / antisolarDirection.y;
const antiGroundPoint = eye.clone().addScaledVector(
antisolarDirection,
groundT
);
antiGround.position.copy(antiGroundPoint);
antiGround.position.y = 0.015;
antiLine.geometry.setFromPoints([eye, antiGroundPoint]);
antiLine.computeLineDistances();
updateHighlightedDroplets();
updateRainbowArc();
updateCone();
labelAnchors.observer.set(world.observerX, 2.75, world.observerZ - 0.15);
labelAnchors.anti.copy(antiGroundPoint).add(new THREE.Vector3(0, 0.45, 0));
labelAnchors.sun.copy(sunEnd).add(new THREE.Vector3(0, 0.35, 0));
observerOutput.textContent = `${world.observerX.toFixed(1)} m`;
observerStat.textContent = `x = ${world.observerX.toFixed(1)} m`;
const angleDegrees = THREE.MathUtils.radToDeg(world.rainbowAngle);
angleOutput.textContent = `${angleDegrees.toFixed(1)}°`;
angleStat.textContent = `${angleDegrees.toFixed(1)}°`;
dropletStat.textContent = String(selectedDropletCount);
svgAngle.textContent = `${angleDegrees.toFixed(1)}°`;
}
observerRange.addEventListener("input", () => {
world.observerX = Number(observerRange.value);
updateOptics();
});
angleRange.addEventListener("input", () => {
world.rainbowAngle = THREE.MathUtils.degToRad(Number(angleRange.value));
updateOptics();
});
coneToggle.addEventListener("change", () => {
coneGroup.visible = coneToggle.checked;
});
document.getElementById("resetButton").addEventListener("click", () => {
world.observerX = 0;
world.rainbowAngle = THREE.MathUtils.degToRad(42);
observerRange.value = "0";
angleRange.value = "42";
cameraState.targetDistance = 31;
cameraState.targetAzimuth = 0.32;
cameraState.targetElevation = 0.29;
updateOptics();
});
// -----------------------------------------------------------------------
// Direct pointer interaction
// -----------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const groundPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
const intersectionPoint = new THREE.Vector3();
let pointerMode = null;
let lastPointerX = 0;
let lastPointerY = 0;
function setPointerFromEvent(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
}
function hitObserver(event) {
setPointerFromEvent(event);
const hits = raycaster.intersectObjects(observer.children, true);
return hits.length > 0;
}
renderer.domElement.addEventListener("pointerdown", event => {
renderer.domElement.setPointerCapture(event.pointerId);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
if (hitObserver(event)) {
pointerMode = "observer";
renderer.domElement.style.cursor = "grabbing";
} else {
pointerMode = "orbit";
renderer.domElement.style.cursor = "move";
}
});
renderer.domElement.addEventListener("pointermove", event => {
setPointerFromEvent(event);
if (pointerMode === "observer") {
if (raycaster.ray.intersectPlane(groundPlane, intersectionPoint)) {
world.observerX = THREE.MathUtils.clamp(
intersectionPoint.x,
-5,
5
);
observerRange.value = world.observerX.toFixed(2);
updateOptics();
}
return;
}
if (pointerMode === "orbit") {
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
cameraState.targetAzimuth -= dx * 0.005;
cameraState.targetElevation = THREE.MathUtils.clamp(
cameraState.targetElevation + dy * 0.004,
0.10,
0.95
);
} else {
renderer.domElement.style.cursor =
hitObserver(event) ? "grab" : "default";
}
lastPointerX = event.clientX;
lastPointerY = event.clientY;
});
function endPointer(event) {
pointerMode = null;
renderer.domElement.style.cursor = "default";
if (event.pointerId !== undefined &&
renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.targetDistance = THREE.MathUtils.clamp(
cameraState.targetDistance * Math.exp(event.deltaY * 0.001),
18,
54
);
}, { passive: false });
renderer.domElement.addEventListener("dblclick", () => {
cameraState.targetDistance = 31;
cameraState.targetAzimuth = 0.32;
cameraState.targetElevation = 0.29;
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
// -----------------------------------------------------------------------
// Animation
// -----------------------------------------------------------------------
updateOptics();
function animate() {
requestAnimationFrame(animate);
cameraState.azimuth = THREE.MathUtils.lerp(
cameraState.azimuth,
cameraState.targetAzimuth,
0.10
);
cameraState.elevation = THREE.MathUtils.lerp(
cameraState.elevation,
cameraState.targetElevation,
0.10
);
cameraState.distance = THREE.MathUtils.lerp(
cameraState.distance,
cameraState.targetDistance,
0.10
);
updateCamera();
updateLabels();
renderer.render(scene, camera);
}
animate();
loading.style.display = "none";
</script>
</body>
</html>
```