Prompt specification
Build or customize the Three.js 3D scene "Bar-magnet field direction 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: Bar-magnet field direction model
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/bar-magnet-field-direction-model-x1649
Scene Description Prompt:
Make a low-poly Three.js scene in a self-contained HTML file using cdnjs: bar-magnet field direction model. Build a bar magnet with selected external field arrows and return paths through the body; show closed loops and clarify that field lines are visualization guides.
Working Three.js Starter (bar-magnet-field-direction-model-x1649):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bar Magnet — Closed Field-Line Model</title>
<style>
:root {
color-scheme: dark;
--bg: #07101d;
--panel: rgba(10, 23, 40, 0.78);
--border: rgba(148, 183, 214, 0.18);
--text: #eaf3ff;
--muted: #9bb0c8;
--cyan: #36d6e7;
--amber: #ffc857;
--north: #ff5a67;
--south: #438cff;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--text);
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene canvas:active {
cursor: grabbing;
}
.hud {
position: fixed;
inset: 0;
pointer-events: none;
}
header {
position: absolute;
top: 24px;
left: 28px;
max-width: 520px;
}
.eyebrow {
display: inline-flex;
align-items: center;
gap: 9px;
margin-bottom: 10px;
padding: 7px 10px;
border: 1px solid rgba(54, 214, 231, 0.28);
border-radius: 999px;
background: rgba(19, 53, 70, 0.55);
color: #9ef5ff;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.eyebrow::before {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 12px var(--cyan);
content: "";
}
h1 {
margin: 0;
font-size: clamp(28px, 4vw, 52px);
line-height: 0.98;
letter-spacing: -0.045em;
}
.subtitle {
max-width: 470px;
margin: 12px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.legend {
position: absolute;
top: 170px;
left: 28px;
width: min(290px, calc(100vw - 56px));
padding: 16px;
border: 1px solid var(--border);
border-radius: 16px;
background: var(--panel);
box-shadow: 0 16px 40px rgba(0, 0, 0, 0.18);
backdrop-filter: blur(16px);
}
.legend-title {
margin-bottom: 13px;
color: #d9e8f8;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.legend-row {
display: grid;
grid-template-columns: 31px 1fr;
gap: 10px;
align-items: start;
margin-top: 11px;
}
.swatch {
position: relative;
width: 31px;
height: 18px;
margin-top: 2px;
}
.swatch::before {
position: absolute;
top: 8px;
left: 0;
width: 31px;
height: 3px;
border-radius: 4px;
background: var(--swatch);
box-shadow: 0 0 9px color-mix(in srgb, var(--swatch) 65%, transparent);
content: "";
}
.swatch::after {
position: absolute;
top: 3px;
right: 1px;
width: 0;
height: 0;
border-top: 6px solid transparent;
border-bottom: 6px solid transparent;
border-left: 10px solid var(--swatch);
content: "";
}
.legend-row strong {
display: block;
margin-bottom: 3px;
font-size: 12px;
letter-spacing: 0.01em;
}
.legend-row span {
display: block;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.pole-row {
display: flex;
gap: 8px;
margin-top: 14px;
padding-top: 13px;
border-top: 1px solid var(--border);
}
.pole {
flex: 1;
padding: 8px;
border-radius: 10px;
background: rgba(255, 255, 255, 0.035);
color: var(--muted);
font-size: 10px;
text-align: center;
}
.pole b {
display: block;
margin-bottom: 2px;
font-size: 15px;
}
.pole.n b {
color: var(--north);
}
.pole.s b {
color: var(--south);
}
.notice {
position: absolute;
bottom: 26px;
left: 28px;
width: min(355px, calc(100vw - 56px));
padding: 15px 16px;
border: 1px solid rgba(255, 200, 87, 0.22);
border-radius: 14px;
background: rgba(24, 25, 32, 0.78);
backdrop-filter: blur(16px);
}
.notice-title {
margin-bottom: 6px;
color: #ffe3a4;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.notice p {
margin: 0;
color: #bac5d2;
font-size: 11px;
line-height: 1.55;
}
.controls {
position: absolute;
right: 28px;
bottom: 26px;
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 8px;
max-width: 520px;
pointer-events: auto;
}
button {
min-height: 39px;
padding: 0 14px;
border: 1px solid var(--border);
border-radius: 11px;
background: rgba(11, 25, 43, 0.86);
color: #dceaff;
font: inherit;
font-size: 11px;
font-weight: 700;
cursor: pointer;
backdrop-filter: blur(14px);
transition:
border-color 160ms ease,
background 160ms ease,
transform 160ms ease;
}
button:hover {
border-color: rgba(54, 214, 231, 0.5);
background: rgba(18, 40, 62, 0.94);
transform: translateY(-1px);
}
button.active {
border-color: rgba(54, 214, 231, 0.5);
background: rgba(26, 67, 82, 0.84);
color: #a8f7ff;
}
.hint {
position: absolute;
right: 28px;
top: 28px;
padding: 9px 12px;
border: 1px solid var(--border);
border-radius: 999px;
background: rgba(8, 19, 34, 0.62);
color: #8fa7c1;
font-size: 10px;
letter-spacing: 0.04em;
backdrop-filter: blur(12px);
}
@media (max-width: 760px) {
header {
top: 17px;
left: 18px;
right: 18px;
}
.subtitle {
max-width: 360px;
font-size: 11px;
}
.legend {
top: auto;
bottom: 162px;
left: 18px;
width: 245px;
padding: 12px;
}
.legend-row {
margin-top: 8px;
}
.notice {
left: 18px;
bottom: 18px;
width: calc(100vw - 36px);
padding: 11px 13px;
}
.notice p {
font-size: 10px;
}
.controls {
right: 18px;
bottom: 100px;
left: 18px;
justify-content: flex-start;
}
button {
min-height: 35px;
padding: 0 11px;
font-size: 10px;
}
.hint {
display: none;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div class="hud">
<header>
<div class="eyebrow">Closed-loop visualization</div>
<h1>Bar Magnet<br>Field Map</h1>
<p class="subtitle">
Selected field arrows travel from the north pole to the south pole
outside the magnet, then return through the body from south to north.
</p>
</header>
<section class="legend" aria-label="Scene legend">
<div class="legend-title">Direction key</div>
<div class="legend-row">
<div class="swatch" style="--swatch: var(--cyan)"></div>
<div>
<strong>External field: N → S</strong>
<span>Cyan arrowheads mark direction on selected guides.</span>
</div>
</div>
<div class="legend-row">
<div class="swatch" style="--swatch: var(--amber)"></div>
<div>
<strong>Internal return: S → N</strong>
<span>Amber paths show the modeled path through the magnet.</span>
</div>
</div>
<div class="pole-row">
<div class="pole s"><b>S</b>SOUTH POLE</div>
<div class="pole n"><b>N</b>NORTH POLE</div>
</div>
</section>
<section class="notice">
<div class="notice-title">Visualization guide — not a physical object</div>
<p>
Field lines are conceptual guides used to represent the magnetic field.
They are not wires, strings, energy streams, or paths followed by
particles. Only selected lines and arrows are emphasized.
</p>
</section>
<div class="hint">Drag to orbit · Scroll to zoom · Double-click to reset</div>
<div class="controls">
<button id="pauseBtn" type="button">Pause flow</button>
<button id="guidesBtn" class="active" type="button">Guides: ON</button>
<button id="xrayBtn" class="active" type="button">X-ray: ON</button>
<button id="resetBtn" type="button">Reset view</button>
</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Renderer and scene
// ------------------------------------------------------------
const host = document.getElementById("scene");
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
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;
host.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07101d);
scene.fog = new THREE.Fog(0x07101d, 13, 29);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
80
);
const cameraTarget = new THREE.Vector3(0, -0.05, 0);
const orbit = {
yaw: 0.72,
pitch: 1.02,
radius: 12.2,
targetYaw: 0.72,
targetPitch: 1.02,
targetRadius: 12.2
};
function updateCamera() {
const spherical = new THREE.Spherical(
orbit.radius,
orbit.pitch,
orbit.yaw
);
camera.position.setFromSpherical(spherical).add(cameraTarget);
camera.lookAt(cameraTarget);
}
updateCamera();
// ------------------------------------------------------------
// Lighting
// ------------------------------------------------------------
scene.add(new THREE.HemisphereLight(0x9fd9ff, 0x111827, 2.2));
const keyLight = new THREE.DirectionalLight(0xffe7cc, 3.4);
keyLight.position.set(5, 9, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -8;
keyLight.shadow.camera.right = 8;
keyLight.shadow.camera.top = 8;
keyLight.shadow.camera.bottom = -8;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x42d8ff, 2.1);
rimLight.position.set(-6, 3, -7);
scene.add(rimLight);
const warmFill = new THREE.PointLight(0xffb85c, 12, 12, 2);
warmFill.position.set(2, -0.5, 3);
scene.add(warmFill);
// ------------------------------------------------------------
// Ground and subtle background particles
// ------------------------------------------------------------
const platform = new THREE.Mesh(
new THREE.CylinderGeometry(11.5, 11.5, 0.28, 32),
new THREE.MeshStandardMaterial({
color: 0x0b1726,
roughness: 0.95,
metalness: 0.05,
flatShading: true
})
);
platform.position.y = -2.9;
platform.receiveShadow = true;
scene.add(platform);
const grid = new THREE.GridHelper(24, 32, 0x31506c, 0x20364d);
grid.position.y = -2.745;
grid.material.transparent = true;
grid.material.opacity = 0.23;
scene.add(grid);
const dustGeometry = new THREE.BufferGeometry();
const dustPositions = [];
for (let i = 0; i < 180; i++) {
const radius = 8 + Math.random() * 15;
const theta = Math.random() * Math.PI * 2;
const y = -2 + Math.random() * 12;
dustPositions.push(
Math.cos(theta) * radius,
y,
Math.sin(theta) * radius
);
}
dustGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(dustPositions, 3)
);
const dust = new THREE.Points(
dustGeometry,
new THREE.PointsMaterial({
color: 0x6484a4,
size: 0.035,
transparent: true,
opacity: 0.38,
depthWrite: false
})
);
scene.add(dust);
// ------------------------------------------------------------
// Bar magnet
// ------------------------------------------------------------
const magnet = new THREE.Group();
scene.add(magnet);
const MAGNET_LENGTH = 5.2;
const HALF = MAGNET_LENGTH / 2;
const MAGNET_HEIGHT = 1.24;
const MAGNET_DEPTH = 1.24;
const CAP_LENGTH = 0.48;
const BODY_LENGTH = MAGNET_LENGTH - CAP_LENGTH * 2;
const bodyMaterial = new THREE.MeshStandardMaterial({
color: 0x93a8bd,
roughness: 0.38,
metalness: 0.18,
transparent: true,
opacity: 0.2,
depthWrite: false,
flatShading: true
});
const northMaterial = new THREE.MeshStandardMaterial({
color: 0xef4d5b,
roughness: 0.35,
metalness: 0.15,
transparent: true,
opacity: 0.68,
depthWrite: false,
flatShading: true
});
const southMaterial = new THREE.MeshStandardMaterial({
color: 0x347cf0,
roughness: 0.35,
metalness: 0.15,
transparent: true,
opacity: 0.68,
depthWrite: false,
flatShading: true
});
const body = new THREE.Mesh(
new THREE.BoxGeometry(BODY_LENGTH, MAGNET_HEIGHT, MAGNET_DEPTH),
bodyMaterial
);
body.castShadow = true;
magnet.add(body);
const northCap = new THREE.Mesh(
new THREE.BoxGeometry(CAP_LENGTH, MAGNET_HEIGHT, MAGNET_DEPTH),
northMaterial
);
northCap.position.x = HALF - CAP_LENGTH / 2;
northCap.castShadow = true;
magnet.add(northCap);
const southCap = new THREE.Mesh(
new THREE.BoxGeometry(CAP_LENGTH, MAGNET_HEIGHT, MAGNET_DEPTH),
southMaterial
);
southCap.position.x = -HALF + CAP_LENGTH / 2;
southCap.castShadow = true;
magnet.add(southCap);
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0xc7def2,
transparent: true,
opacity: 0.48
});
function addEdges(mesh) {
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(mesh.geometry),
edgeMaterial
);
edges.position.copy(mesh.position);
magnet.add(edges);
}
addEdges(body);
addEdges(northCap);
addEdges(southCap);
// Thin rings make the pole faces easy to identify.
const northRing = new THREE.Mesh(
new THREE.TorusGeometry(0.48, 0.025, 5, 32),
new THREE.MeshBasicMaterial({
color: 0xff7a83,
transparent: true,
opacity: 0.82
})
);
northRing.rotation.y = Math.PI / 2;
northRing.position.x = HALF + 0.015;
magnet.add(northRing);
const southRing = new THREE.Mesh(
new THREE.TorusGeometry(0.48, 0.025, 5, 32),
new THREE.MeshBasicMaterial({
color: 0x6da3ff,
transparent: true,
opacity: 0.82
})
);
southRing.rotation.y = Math.PI / 2;
southRing.position.x = -HALF - 0.015;
magnet.add(southRing);
// Canvas-generated pole labels keep the file asset-free.
function makePoleLabel(letter, color) {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 256;
const context = canvas.getContext("2d");
context.clearRect(0, 0, 256, 256);
context.beginPath();
context.arc(128, 128, 102, 0, Math.PI * 2);
context.fillStyle = "rgba(4, 12, 22, 0.82)";
context.fill();
context.lineWidth = 12;
context.strokeStyle = color;
context.stroke();
context.fillStyle = "#ffffff";
context.font = "900 132px Arial, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(letter, 128, 135);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(0.78, 0.78, 0.78);
sprite.renderOrder = 20;
return sprite;
}
const northLabel = makePoleLabel("N", "#ff5a67");
northLabel.position.set(2.03, 0, 0.83);
magnet.add(northLabel);
const southLabel = makePoleLabel("S", "#438cff");
southLabel.position.set(-2.03, 0, 0.83);
magnet.add(southLabel);
// ------------------------------------------------------------
// Closed field loops
//
// Each loop consists of:
// 1. An external curve from N to S.
// 2. An internal return curve from S to N.
//
// The loops lie in planes through the magnet's X axis.
// ------------------------------------------------------------
const fieldGroup = new THREE.Group();
const internalGroup = new THREE.Group();
const internalArrowGroup = new THREE.Group();
const particleGroup = new THREE.Group();
const internalParticleGroup = new THREE.Group();
fieldGroup.add(internalGroup);
fieldGroup.add(internalArrowGroup);
fieldGroup.add(particleGroup);
fieldGroup.add(internalParticleGroup);
scene.add(fieldGroup);
const externalColor = 0x36d6e7;
const guideColor = 0x2b829a;
const internalColor = 0xffc857;
const externalArrowGeometry = new THREE.ConeGeometry(0.13, 0.36, 5);
const internalArrowGeometry = new THREE.ConeGeometry(0.105, 0.29, 5);
const particleGeometry = new THREE.OctahedronGeometry(0.065, 0);
const up = new THREE.Vector3(0, 1, 0);
const particles = [];
const internalParticles = [];
function radialPoint(angle, x, radius) {
return new THREE.Vector3(
x,
Math.cos(angle) * radius,
Math.sin(angle) * radius
);
}
function makeExternalCurve(angle, scale) {
const points = [
radialPoint(angle, HALF, 0),
radialPoint(angle, HALF + 0.72, 0.025 * scale),
radialPoint(angle, HALF + 1.78, 0.28 * scale),
radialPoint(angle, HALF + 2.38, 0.92 * scale),
radialPoint(angle, HALF + 1.65, 1.72 * scale),
radialPoint(angle, HALF - 0.22, 2.23 * scale),
radialPoint(angle, -HALF - 1.08, 2.23 * scale),
radialPoint(angle, -HALF - 1.78, 1.48 * scale),
radialPoint(angle, -HALF - 0.76, 0.18 * scale),
radialPoint(angle, -HALF, 0)
];
return new THREE.CatmullRomCurve3(
points,
false,
"centripetal",
0.5
);
}
function makeInternalCurve(angle, scale) {
const points = [
radialPoint(angle, -HALF, 0),
radialPoint(angle, -HALF + 0.58, 0.045 * scale),
radialPoint(angle, -1.25, 0.14 * scale),
radialPoint(angle, 1.25, 0.14 * scale),
radialPoint(angle, HALF - 0.58, 0.045 * scale),
radialPoint(angle, HALF, 0)
];
return new THREE.CatmullRomCurve3(
points,
false,
"centripetal",
0.5
);
}
function addArrow(curve, t, geometry, color, group, size = 1) {
const arrow = new THREE.Mesh(
geometry,
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.96,
depthWrite: false
})
);
const point = curve.getPointAt(t);
const tangent = curve.getTangentAt(t).normalize();
arrow.position.copy(point);
arrow.quaternion.setFromUnitVectors(up, tangent);
arrow.scale.setScalar(size);
arrow.renderOrder = 8;
group.add(arrow);
return arrow;
}
// Six radial planes form a compact, low-poly field cage.
const loopDefinitions = [
{ angle: 0, scale: 1.02, highlighted: true },
{ angle: Math.PI / 3, scale: 0.94, highlighted: false },
{ angle: Math.PI / 2, scale: 1.00, highlighted: true },
{ angle: Math.PI, scale: 0.97, highlighted: false },
{ angle: 4 * Math.PI / 3, scale: 0.90, highlighted: true },
{ angle: 5 * Math.PI / 3, scale: 0.96, highlighted: false }
];
loopDefinitions.forEach((definition, loopIndex) => {
const externalCurve = makeExternalCurve(
definition.angle,
definition.scale
);
const internalCurve = makeInternalCurve(
definition.angle,
definition.scale
);
const externalMaterial = new THREE.MeshBasicMaterial({
color: definition.highlighted ? externalColor : guideColor,
transparent: true,
opacity: definition.highlighted ? 0.88 : 0.24,
depthWrite: false
});
const internalMaterial = new THREE.MeshBasicMaterial({
color: internalColor,
transparent: true,
opacity: definition.highlighted ? 0.9 : 0.2,
depthWrite: false,
depthTest: false
});
const externalTube = new THREE.Mesh(
new THREE.TubeGeometry(
externalCurve,
72,
definition.highlighted ? 0.032 : 0.014,
4,
false
),
externalMaterial
);
externalTube.renderOrder = 3;
fieldGroup.add(externalTube);
const internalTube = new THREE.Mesh(
new THREE.TubeGeometry(
internalCurve,
28,
definition.highlighted ? 0.032 : 0.012,
4,
false
),
internalMaterial
);
internalTube.renderOrder = 5;
internalGroup.add(internalTube);
if (definition.highlighted) {
// Selected external arrows: N to S.
[0.08, 0.27, 0.47, 0.67, 0.86].forEach((t, arrowIndex) => {
addArrow(
externalCurve,
t,
externalArrowGeometry,
externalColor,
fieldGroup,
arrowIndex === 2 ? 1.12 : 1
);
});
// Internal return arrows: S to N.
[0.22, 0.5, 0.78].forEach((t) => {
addArrow(
internalCurve,
t,
internalArrowGeometry,
internalColor,
internalArrowGroup,
1
);
});
// Moving markers make the modeled direction easier to follow.
for (let i = 0; i < 2; i++) {
const marker = new THREE.Mesh(
particleGeometry,
new THREE.MeshBasicMaterial({
color: 0xd8fbff,
transparent: true,
opacity: 0.88,
depthWrite: false
})
);
marker.renderOrder = 9;
particleGroup.add(marker);
particles.push({
mesh: marker,
curve: externalCurve,
phase: (loopIndex * 0.17 + i * 0.48) % 1,
speed: 0.105 + i * 0.012
});
const internalMarker = new THREE.Mesh(
particleGeometry,
new THREE.MeshBasicMaterial({
color: 0xffe3a0,
transparent: true,
opacity: 0.9,
depthWrite: false
})
);
internalMarker.renderOrder = 10;
internalParticleGroup.add(internalMarker);
internalParticles.push({
mesh: internalMarker,
curve: internalCurve,
phase: (loopIndex * 0.21 + i * 0.5) % 1,
speed: 0.12 + i * 0.01
});
}
}
});
// Small nodes emphasize where the external and internal portions meet.
const northNode = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.09, 0),
new THREE.MeshBasicMaterial({ color: externalColor })
);
northNode.position.x = HALF;
fieldGroup.add(northNode);
const southNode = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.09, 0),
new THREE.MeshBasicMaterial({ color: externalColor })
);
southNode.position.x = -HALF;
fieldGroup.add(southNode);
// ------------------------------------------------------------
// UI behavior
// ------------------------------------------------------------
const pauseButton = document.getElementById("pauseBtn");
const guidesButton = document.getElementById("guidesBtn");
const xrayButton = document.getElementById("xrayBtn");
const resetButton = document.getElementById("resetBtn");
let flowRunning = true;
let guidesVisible = true;
let xrayEnabled = true;
function setXray(enabled) {
xrayEnabled = enabled;
bodyMaterial.opacity = enabled ? 0.2 : 0.94;
bodyMaterial.depthWrite = !enabled;
bodyMaterial.needsUpdate = true;
northMaterial.opacity = enabled ? 0.68 : 0.96;
southMaterial.opacity = enabled ? 0.68 : 0.96;
northMaterial.depthWrite = !enabled;
southMaterial.depthWrite = !enabled;
northMaterial.needsUpdate = true;
southMaterial.needsUpdate = true;
internalGroup.visible = enabled;
internalArrowGroup.visible = enabled;
internalParticleGroup.visible = enabled;
xrayButton.textContent = `X-ray: ${enabled ? "ON" : "OFF"}`;
xrayButton.classList.toggle("active", enabled);
}
pauseButton.addEventListener("click", () => {
flowRunning = !flowRunning;
pauseButton.textContent = flowRunning ? "Pause flow" : "Resume flow";
pauseButton.classList.toggle("active", !flowRunning);
});
guidesButton.addEventListener("click", () => {
guidesVisible = !guidesVisible;
fieldGroup.visible = guidesVisible;
guidesButton.textContent = `Guides: ${guidesVisible ? "ON" : "OFF"}`;
guidesButton.classList.toggle("active", guidesVisible);
});
xrayButton.addEventListener("click", () => {
setXray(!xrayEnabled);
});
function resetView() {
orbit.targetYaw = 0.72;
orbit.targetPitch = 1.02;
orbit.targetRadius = 12.2;
}
resetButton.addEventListener("click", resetView);
renderer.domElement.addEventListener("dblclick", resetView);
// ------------------------------------------------------------
// Direct camera controls: drag to orbit, wheel/pinch to zoom
// ------------------------------------------------------------
let dragging = false;
let pointerX = 0;
let pointerY = 0;
const activePointers = new Map();
let pinchDistance = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
activePointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (activePointers.size === 1) {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
} else if (activePointers.size === 2) {
const points = [...activePointers.values()];
pinchDistance = Math.hypot(
points[0].x - points[1].x,
points[0].y - points[1].y
);
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!activePointers.has(event.pointerId)) return;
activePointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (activePointers.size === 2) {
const points = [...activePointers.values()];
const distance = Math.hypot(
points[0].x - points[1].x,
points[0].y - points[1].y
);
if (pinchDistance > 0 && distance > 0) {
orbit.targetRadius = THREE.MathUtils.clamp(
orbit.targetRadius * (pinchDistance / distance),
7.2,
19
);
}
pinchDistance = distance;
return;
}
if (!dragging) return;
const deltaX = event.clientX - pointerX;
const deltaY = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
orbit.targetYaw -= deltaX * 0.006;
orbit.targetPitch = THREE.MathUtils.clamp(
orbit.targetPitch - deltaY * 0.005,
0.3,
Math.PI - 0.3
);
});
function releasePointer(event) {
activePointers.delete(event.pointerId);
if (activePointers.size === 0) {
dragging = false;
}
if (activePointers.size < 2) {
pinchDistance = 0;
}
}
renderer.domElement.addEventListener("pointerup", releasePointer);
renderer.domElement.addEventListener("pointercancel", releasePointer);
renderer.domElement.addEventListener("lostpointercapture", releasePointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.targetRadius = THREE.MathUtils.clamp(
orbit.targetRadius * Math.exp(event.deltaY * 0.001),
7.2,
19
);
},
{ passive: false }
);
// Keyboard shortcuts.
window.addEventListener("keydown", (event) => {
if (event.code === "Space") {
event.preventDefault();
pauseButton.click();
} else if (event.key.toLowerCase() === "g") {
guidesButton.click();
} else if (event.key.toLowerCase() === "x") {
xrayButton.click();
} else if (event.key.toLowerCase() === "r") {
resetView();
}
});
// ------------------------------------------------------------
// Resize and animation
// ------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
const clock = new THREE.Clock();
let elapsed = 0;
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
if (flowRunning) {
elapsed += delta;
}
orbit.yaw += (orbit.targetYaw - orbit.yaw) * 0.08;
orbit.pitch += (orbit.targetPitch - orbit.pitch) * 0.08;
orbit.radius += (orbit.targetRadius - orbit.radius) * 0.08;
updateCamera();
if (flowRunning && guidesVisible) {
particles.forEach((particle) => {
const u = (elapsed * particle.speed + particle.phase) % 1;
particle.mesh.position.copy(particle.curve.getPointAt(u));
});
internalParticles.forEach((particle) => {
const u = (elapsed * particle.speed + particle.phase) % 1;
particle.mesh.position.copy(particle.curve.getPointAt(u));
});
}
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```