Prompt specification
Build or customize the Three.js 3D scene "Loss surface and gradient arrow" 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: Loss surface and gradient arrow
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/loss-surface-and-gradient-arrow-x1881
Scene Description Prompt:
Use Three.js from cdnjs to build a simple convex bowl surface with a movable parameter point and local gradient arrow; distinguish parameter-space height from a literal physical landscape. Deliver one self-contained HTML file with low-poly forms.
Working Three.js Starter (loss-surface-and-gradient-arrow-x1881):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Convex Parameter Bowl</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(10, 24, 42, 0.88);
--border: rgba(158, 203, 255, 0.16);
--text: #eaf5ff;
--muted: #91a9bf;
--cyan: #64d7ff;
--amber: #ffc857;
--violet: #9a82ff;
}
* {
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 {
display: block;
width: 100%;
height: 100%;
outline: none;
touch-action: none;
cursor: grab;
}
.title {
position: fixed;
z-index: 2;
top: 24px;
left: 26px;
max-width: 560px;
pointer-events: none;
text-shadow: 0 2px 16px rgba(0, 0, 0, 0.45);
}
.eyebrow {
display: inline-flex;
align-items: center;
gap: 8px;
margin-bottom: 10px;
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.eyebrow::before {
width: 20px;
height: 1px;
background: currentColor;
content: "";
}
h1 {
margin: 0;
font-size: clamp(27px, 3.2vw, 47px);
font-weight: 650;
line-height: 1.02;
letter-spacing: -0.045em;
}
.title p {
max-width: 520px;
margin: 13px 0 0;
color: #b7c9d9;
font-size: 14px;
line-height: 1.55;
}
.not-terrain {
color: var(--amber);
font-weight: 750;
}
.panel {
position: fixed;
z-index: 3;
top: 20px;
right: 20px;
width: 350px;
max-height: calc(100vh - 40px);
overflow: auto;
padding: 18px;
border: 1px solid var(--border);
border-radius: 18px;
background: var(--panel);
box-shadow:
0 20px 70px rgba(0, 0, 0, 0.38),
inset 0 1px rgba(255, 255, 255, 0.04);
backdrop-filter: blur(16px) saturate(130%);
scrollbar-width: thin;
scrollbar-color: #38516a transparent;
}
.panel-heading {
display: flex;
align-items: start;
justify-content: space-between;
gap: 14px;
margin-bottom: 16px;
}
.panel-heading h2 {
margin: 0;
font-size: 16px;
letter-spacing: -0.02em;
}
.panel-heading p {
margin: 5px 0 0;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.badge {
flex: 0 0 auto;
padding: 5px 7px;
border: 1px solid rgba(255, 200, 87, 0.28);
border-radius: 999px;
background: rgba(255, 200, 87, 0.08);
color: var(--amber);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.12em;
}
.formula {
margin: 0 0 15px;
padding: 12px 13px;
border: 1px solid rgba(154, 130, 255, 0.19);
border-radius: 12px;
background: rgba(154, 130, 255, 0.07);
font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
font-size: 13px;
line-height: 1.55;
}
.formula span {
color: #c5b9ff;
}
.control {
margin: 13px 0;
}
.control label {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 7px;
color: #c9d9e8;
font-size: 12px;
font-weight: 650;
}
output {
color: var(--cyan);
font-family: "SFMono-Regular", Consolas, monospace;
font-weight: 700;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
border-radius: 999px;
accent-color: var(--cyan);
cursor: ew-resize;
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin: 16px 0;
}
.metric {
min-width: 0;
padding: 10px;
border: 1px solid rgba(158, 203, 255, 0.11);
border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
}
.metric.wide {
grid-column: 1 / -1;
}
.metric-label {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.metric-value {
display: block;
overflow: hidden;
color: var(--text);
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 12px;
text-overflow: ellipsis;
white-space: nowrap;
}
.metric-value.cyan {
color: var(--cyan);
}
.metric-value.amber {
color: var(--amber);
}
.map-card {
margin: 15px 0 12px;
padding: 10px 10px 5px;
border: 1px solid rgba(158, 203, 255, 0.11);
border-radius: 12px;
background: rgba(2, 10, 20, 0.34);
}
.map-title {
display: flex;
justify-content: space-between;
margin: 0 2px 5px;
color: #aebfd0;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.05em;
text-transform: uppercase;
}
#parameterMap {
display: block;
width: 100%;
height: auto;
}
.legend {
display: grid;
gap: 7px;
margin: 12px 0 15px;
color: #aebfd0;
font-size: 11px;
line-height: 1.35;
}
.legend-row {
display: flex;
align-items: center;
gap: 8px;
}
.swatch {
flex: 0 0 auto;
width: 15px;
height: 4px;
border-radius: 4px;
background: var(--cyan);
}
.swatch.amber {
background: var(--amber);
}
.swatch.dashed {
height: 0;
border-top: 2px dashed #7e9ab2;
border-radius: 0;
background: transparent;
}
.buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
button {
padding: 9px 10px;
border: 1px solid rgba(158, 203, 255, 0.16);
border-radius: 9px;
background: rgba(158, 203, 255, 0.07);
color: var(--text);
font: inherit;
font-size: 11px;
font-weight: 700;
cursor: pointer;
transition:
background 140ms ease,
border-color 140ms ease,
transform 140ms ease;
}
button:hover {
border-color: rgba(100, 215, 255, 0.42);
background: rgba(100, 215, 255, 0.12);
}
button:active {
transform: translateY(1px);
}
.hint {
position: fixed;
z-index: 2;
bottom: 18px;
left: 24px;
padding: 8px 11px;
border: 1px solid rgba(158, 203, 255, 0.12);
border-radius: 9px;
background: rgba(7, 17, 31, 0.68);
color: #91a9bf;
font-size: 11px;
pointer-events: none;
backdrop-filter: blur(8px);
}
kbd {
padding: 2px 4px;
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 4px;
background: rgba(255, 255, 255, 0.06);
color: #d9e9f7;
font: inherit;
font-size: 10px;
}
@media (max-width: 760px) {
.title {
top: 13px;
left: 14px;
right: 14px;
}
.title p {
display: none;
}
h1 {
max-width: 360px;
font-size: 27px;
}
.panel {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 48vh;
padding: 14px;
}
.hint {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene" tabindex="0" aria-label="Interactive three-dimensional convex parameter bowl"></canvas>
<header class="title">
<div class="eyebrow">Parametric graph · low-poly study</div>
<h1>Convex bowl,<br>explicitly parameterized.</h1>
<p>
The coordinates <b>u</b> and <b>v</b> select a point in a parameter domain;
<b>h = f(u,v)</b> is the plotted function value.
<span class="not-terrain">This is a graph, not a physical landscape.</span>
</p>
</header>
<aside class="panel">
<div class="panel-heading">
<div>
<h2>Parameter controls</h2>
<p>Move the lifted point on the graph or use either slider.</p>
</div>
<div class="badge">NOT TERRAIN</div>
</div>
<div class="formula">
h = f(u,v) = <span>0.28(u² + v²)</span><br>
∇f = <span>(0.56u, 0.56v)</span>
</div>
<div class="control">
<label for="uInput">
<span>Parameter u</span>
<output id="uValue" for="uInput">0.00</output>
</label>
<input id="uInput" type="range" min="-2" max="2" step="0.01" value="0">
</div>
<div class="control">
<label for="vInput">
<span>Parameter v</span>
<output id="vValue" for="vInput">0.00</output>
</label>
<input id="vInput" type="range" min="-2" max="2" step="0.01" value="0">
</div>
<div class="metrics" aria-live="polite">
<div class="metric">
<span class="metric-label">Graph point</span>
<span class="metric-value cyan" id="pointValue">(0.00, 0.00)</span>
</div>
<div class="metric">
<span class="metric-label">Height h</span>
<span class="metric-value" id="heightValue">0.000</span>
</div>
<div class="metric">
<span class="metric-label">Gradient ∇f</span>
<span class="metric-value amber" id="gradientValue">(0.00, 0.00)</span>
</div>
<div class="metric">
<span class="metric-label">Gradient norm</span>
<span class="metric-value amber" id="gradientNorm">0.000</span>
</div>
<div class="metric wide">
<span class="metric-label">Convexity</span>
<span class="metric-value">∇²f = 0.56 I ≻ 0 · strictly convex</span>
</div>
</div>
<div class="map-card">
<div class="map-title">
<span>Parameter domain (u,v)</span>
<span>Height gauge h</span>
</div>
<svg id="parameterMap" viewBox="0 0 260 190" role="img"
aria-label="Two-dimensional parameter-domain inset with the current point and gradient">
<defs>
<marker id="mapArrowhead" markerWidth="7" markerHeight="7"
refX="6" refY="3.5" orient="auto">
<path d="M0,0 L7,3.5 L0,7 Z" fill="#ffc857"></path>
</marker>
<clipPath id="mapClip">
<rect x="20" y="10" width="180" height="170" rx="3"></rect>
</clipPath>
</defs>
<rect x="20" y="10" width="180" height="170" rx="3"
fill="#0a1c30" stroke="#38536d"></rect>
<g stroke="#284158" stroke-width="1" opacity="0.75">
<path d="M65 10V180 M110 10V180 M155 10V180"></path>
<path d="M20 52.5H200 M20 95H200 M20 137.5H200"></path>
</g>
<g stroke="#9ab1c7" stroke-width="1">
<path d="M20 95H200"></path>
<path d="M110 10V180"></path>
</g>
<text x="195" y="190" fill="#91a9bf" font-size="9" text-anchor="end">u</text>
<text x="13" y="16" fill="#91a9bf" font-size="9">v</text>
<line id="mapGradient" x1="110" y1="95" x2="110" y2="95"
stroke="#ffc857" stroke-width="2.5"
marker-end="url(#mapArrowhead)"></line>
<circle id="mapPointHalo" cx="110" cy="95" r="8"
fill="#64d7ff" opacity="0.16"></circle>
<circle id="mapPoint" cx="110" cy="95" r="4" fill="#64d7ff"></circle>
<g>
<rect x="220" y="10" width="8" height="170" rx="4"
fill="#162a40" stroke="#38536d"></rect>
<rect id="heightFill" x="221.5" y="176" width="5" height="0" rx="2.5"
fill="#9a82ff"></rect>
<circle id="heightDot" cx="224" cy="176" r="5.5"
fill="#eaf5ff" stroke="#9a82ff" stroke-width="2"></circle>
<text x="224" y="5" fill="#91a9bf" font-size="8" text-anchor="middle">2.3</text>
<text x="224" y="188" fill="#91a9bf" font-size="8" text-anchor="middle">0</text>
</g>
</svg>
</div>
<div class="legend">
<div class="legend-row">
<span class="swatch"></span>
<span>Lifted graph point: (u, v, f(u,v)).</span>
</div>
<div class="legend-row">
<span class="swatch dashed"></span>
<span>Dashed stem: the separately plotted value h = f(u,v).</span>
</div>
<div class="legend-row">
<span class="swatch amber"></span>
<span>3D arrow: tangent lift of the parameter gradient ∇f.</span>
</div>
</div>
<div class="buttons">
<button id="centerPoint" type="button">Center point</button>
<button id="resetView" type="button">Reset view</button>
</div>
</aside>
<div class="hint">
<kbd>Left drag</kbd> move point ·
<kbd>Right drag</kbd> orbit ·
<kbd>Wheel</kbd> zoom ·
<kbd>Arrow keys</kbd> nudge point
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setClearColor(0x07111f, 1);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
const scene = new THREE.Scene();
scene.fog = new THREE.FogExp2(0x07111f, 0.035);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
60
);
// Direct camera controls; no addon modules are used.
const cameraState = {
radius: 8.6,
theta: 0.72,
phi: 1.08,
target: new THREE.Vector3(0, 0.65, 0)
};
function updateCamera() {
const { radius, theta, phi, target } = cameraState;
const sinPhi = Math.sin(phi);
camera.position.set(
target.x + radius * sinPhi * Math.cos(theta),
target.y + radius * Math.cos(phi),
target.z + radius * sinPhi * Math.sin(theta)
);
camera.lookAt(target);
}
updateCamera();
scene.add(new THREE.HemisphereLight(0xbdeaff, 0x121a2b, 2.0));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.6);
keyLight.position.set(4, 7, 5);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x8b72ff, 1.15);
rimLight.position.set(-5, 3, -4);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xffc857, 12, 12, 2);
warmLight.position.set(3, 1.5, -2);
scene.add(warmLight);
const DOMAIN = 2;
const SEGMENTS = 16;
const SCALE = 0.28;
const MAX_HEIGHT = 2.3;
const heightFunction = (u, v) => SCALE * (u * u + v * v);
const gradientFunction = (u, v) => [2 * SCALE * u, 2 * SCALE * v];
/*
Build a deliberately faceted graph over the parameter square.
World x = u, world y = h, world z = v.
*/
function buildFacetedSurface() {
const positions = [];
const colors = [];
const lowColor = new THREE.Color("#176181");
const highColor = new THREE.Color("#8a72e8");
const step = (DOMAIN * 2) / SEGMENTS;
function pushTriangle(a, b, c, shade) {
const averageHeight = (a[1] + b[1] + c[1]) / 3;
const t = THREE.MathUtils.clamp(averageHeight / MAX_HEIGHT, 0, 1);
const color = lowColor.clone().lerp(highColor, t).multiplyScalar(shade);
for (const vertex of [a, b, c]) {
positions.push(...vertex);
colors.push(color.r, color.g, color.b);
}
}
for (let iz = 0; iz < SEGMENTS; iz++) {
const v0 = -DOMAIN + iz * step;
const v1 = v0 + step;
for (let ix = 0; ix < SEGMENTS; ix++) {
const u0 = -DOMAIN + ix * step;
const u1 = u0 + step;
const a = [u0, heightFunction(u0, v0), v0];
const b = [u1, heightFunction(u1, v0), v0];
const c = [u0, heightFunction(u0, v1), v1];
const d = [u1, heightFunction(u1, v1), v1];
const shadeA = 0.90 + 0.045 * ((ix * 7 + iz * 11) % 5);
const shadeB = 0.94 + 0.035 * ((ix * 3 + iz * 13 + 2) % 4);
// Winding is chosen so the surface normals point upward.
pushTriangle(a, c, b, shadeA);
pushTriangle(b, c, d, shadeB);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(colors, 3)
);
geometry.computeVertexNormals();
geometry.computeBoundingSphere();
return geometry;
}
const surfaceGeometry = buildFacetedSurface();
const surfaceMaterial = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.78,
metalness: 0.06,
flatShading: true,
transparent: true,
opacity: 0.84,
depthWrite: false,
side: THREE.DoubleSide
});
const surface = new THREE.Mesh(surfaceGeometry, surfaceMaterial);
surface.renderOrder = 2;
scene.add(surface);
const wireframe = new THREE.LineSegments(
new THREE.WireframeGeometry(surfaceGeometry),
new THREE.LineBasicMaterial({
color: 0xc2e7ff,
transparent: true,
opacity: 0.12,
depthWrite: false
})
);
wireframe.renderOrder = 3;
scene.add(wireframe);
// The square tile is explicitly the parameter domain, not a ground plane.
const domainPlane = new THREE.Mesh(
new THREE.PlaneGeometry(DOMAIN * 2, DOMAIN * 2),
new THREE.MeshBasicMaterial({
color: 0x193a55,
transparent: true,
opacity: 0.13,
depthWrite: false,
side: THREE.DoubleSide
})
);
domainPlane.rotation.x = -Math.PI / 2;
domainPlane.position.y = -0.025;
domainPlane.renderOrder = -2;
scene.add(domainPlane);
const gridPositions = [];
const gridStep = 0.5;
for (let value = -DOMAIN; value <= DOMAIN + 0.001; value += gridStep) {
gridPositions.push(
value, 0.006, -DOMAIN,
value, 0.006, DOMAIN,
-DOMAIN, 0.006, value,
DOMAIN, 0.006, value
);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(gridPositions, 3)
);
const grid = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0x6e9bb8,
transparent: true,
opacity: 0.27,
depthWrite: false
})
);
grid.renderOrder = 0;
scene.add(grid);
function makeLabel(text, color = "#dcefff") {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 128;
const context = labelCanvas.getContext("2d");
context.clearRect(0, 0, 512, 128);
context.fillStyle = "rgba(7, 17, 31, 0.82)";
context.beginPath();
context.roundRect(8, 12, 496, 104, 24);
context.fill();
context.strokeStyle = "rgba(160, 205, 240, 0.2)";
context.lineWidth = 2;
context.stroke();
context.fillStyle = color;
context.font = "600 43px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 256, 65);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(1.32, 0.33, 1);
sprite.renderOrder = 20;
return sprite;
}
const axisCorner = new THREE.Vector3(
-DOMAIN - 0.18,
0.015,
-DOMAIN - 0.18
);
function addAxis(direction, length, color) {
const axis = new THREE.ArrowHelper(
direction,
axisCorner,
length,
color,
0.13,
0.065
);
axis.line.material.transparent = true;
axis.line.material.opacity = 0.72;
axis.cone.material.transparent = true;
axis.cone.material.opacity = 0.82;
scene.add(axis);
}
addAxis(new THREE.Vector3(1, 0, 0), DOMAIN * 2 + 0.4, 0x64d7ff);
addAxis(new THREE.Vector3(0, 0, 1), DOMAIN * 2 + 0.4, 0x9a82ff);
addAxis(new THREE.Vector3(0, 1, 0), 2.55, 0xffc857);
const uLabel = makeLabel("u · parameter", "#8de5ff");
uLabel.position.set(DOMAIN + 0.32, 0.08, -DOMAIN - 0.3);
scene.add(uLabel);
const vLabel = makeLabel("v · parameter", "#b6a8ff");
vLabel.position.set(-DOMAIN - 0.38, 0.08, DOMAIN + 0.3);
scene.add(vLabel);
const hLabel = makeLabel("h = f(u,v)", "#ffd77c");
hLabel.position.set(-DOMAIN - 0.42, 2.7, -DOMAIN - 0.3);
scene.add(hLabel);
// The point in the parameter domain.
const parameterMarker = new THREE.Mesh(
new THREE.OctahedronGeometry(0.085, 0),
new THREE.MeshBasicMaterial({
color: 0x64d7ff,
depthTest: false,
depthWrite: false
})
);
parameterMarker.renderOrder = 15;
scene.add(parameterMarker);
const parameterRing = new THREE.Mesh(
new THREE.RingGeometry(0.10, 0.135, 16),
new THREE.MeshBasicMaterial({
color: 0x64d7ff,
transparent: true,
opacity: 0.72,
side: THREE.DoubleSide,
depthTest: false,
depthWrite: false
})
);
parameterRing.rotation.x = -Math.PI / 2;
parameterRing.renderOrder = 14;
scene.add(parameterRing);
// The lifted graph point.
const graphMarker = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.115, 0),
new THREE.MeshStandardMaterial({
color: 0xf2fbff,
emissive: 0x123e57,
emissiveIntensity: 0.65,
roughness: 0.45,
flatShading: true,
depthTest: false,
depthWrite: false
})
);
graphMarker.renderOrder = 18;
scene.add(graphMarker);
// Dashed stem explicitly separates parameter position from function value.
const stem = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(),
new THREE.Vector3()
]),
new THREE.LineDashedMaterial({
color: 0x9bb6cd,
dashSize: 0.075,
gapSize: 0.055,
transparent: true,
opacity: 0.68,
depthTest: false,
depthWrite: false
})
);
stem.renderOrder = 12;
scene.add(stem);
/*
The gradient is a parameter-domain vector. Its 3D display is the
tangent lift of the steepest-ascent direction:
p = (fu, fv)
T = (fu, fu² + fv², fv)
so T is tangent to the graph.
*/
const gradientArrow = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(),
0.82,
0xffc857,
0.18,
0.10
);
gradientArrow.line.material.depthTest = false;
gradientArrow.line.material.depthWrite = false;
gradientArrow.line.material.transparent = true;
gradientArrow.line.material.opacity = 0.95;
gradientArrow.line.renderOrder = 22;
gradientArrow.cone.material.depthTest = false;
gradientArrow.cone.material.depthWrite = false;
gradientArrow.cone.material.transparent = true;
gradientArrow.cone.material.opacity = 0.98;
gradientArrow.cone.renderOrder = 22;
scene.add(gradientArrow);
const uInput = document.querySelector("#uInput");
const vInput = document.querySelector("#vInput");
const uValue = document.querySelector("#uValue");
const vValue = document.querySelector("#vValue");
const pointValue = document.querySelector("#pointValue");
const heightValue = document.querySelector("#heightValue");
const gradientValue = document.querySelector("#gradientValue");
const gradientNorm = document.querySelector("#gradientNorm");
const mapGradient = document.querySelector("#mapGradient");
const mapPoint = document.querySelector("#mapPoint");
const mapPointHalo = document.querySelector("#mapPointHalo");
const heightDot = document.querySelector("#heightDot");
const heightFill = document.querySelector("#heightFill");
let u = 0;
let v = 0;
const clampDomain = (value) =>
THREE.MathUtils.clamp(value, -DOMAIN, DOMAIN);
function updatePoint() {
u = clampDomain(u);
v = clampDomain(v);
const height = heightFunction(u, v);
const [gradientU, gradientV] = gradientFunction(u, v);
const magnitude = Math.hypot(gradientU, gradientV);
uInput.value = u.toFixed(2);
vInput.value = v.toFixed(2);
uValue.textContent = Number(u).toFixed(2);
vValue.textContent = Number(v).toFixed(2);
pointValue.textContent = `(${Number(u).toFixed(2)}, ${Number(v).toFixed(2)})`;
heightValue.textContent = height.toFixed(3);
gradientValue.textContent =
`(${gradientU.toFixed(2)}, ${gradientV.toFixed(2)})`;
gradientNorm.textContent = magnitude.toFixed(3);
const graphPosition = new THREE.Vector3(u, height, v);
const domainPosition = new THREE.Vector3(u, 0.035, v);
graphMarker.position.copy(graphPosition);
parameterMarker.position.copy(domainPosition);
parameterRing.position.set(u, 0.025, v);
stem.geometry.setFromPoints([
new THREE.Vector3(u, 0.015, v),
new THREE.Vector3(u, height, v)
]);
stem.computeLineDistances();
if (magnitude > 0.0001) {
const tangent = new THREE.Vector3(
gradientU,
gradientU * gradientU + gradientV * gradientV,
gradientV
).normalize();
const normal = new THREE.Vector3(
-gradientU,
1,
-gradientV
).normalize();
gradientArrow.visible = true;
gradientArrow.position
.copy(graphPosition)
.addScaledVector(normal, 0.075);
gradientArrow.setDirection(tangent);
gradientArrow.setLength(0.82, 0.18, 0.10);
} else {
gradientArrow.visible = false;
}
// Update the 2D parameter-domain inset.
const mapX = 110 + (u / DOMAIN) * 78;
const mapY = 95 - (v / DOMAIN) * 78;
mapPoint.setAttribute("cx", mapX);
mapPoint.setAttribute("cy", mapY);
mapPointHalo.setAttribute("cx", mapX);
mapPointHalo.setAttribute("cy", mapY);
const arrowEndX = mapX + gradientU * 20;
const arrowEndY = mapY - gradientV * 20;
mapGradient.setAttribute("x1", mapX);
mapGradient.setAttribute("y1", mapY);
mapGradient.setAttribute("x2", arrowEndX);
mapGradient.setAttribute("y2", arrowEndY);
mapGradient.style.display = magnitude > 0.0001 ? "" : "none";
const gaugeBottom = 176;
const gaugeTop = 10;
const gaugeHeight = gaugeBottom - gaugeTop;
const dotY = gaugeBottom - (height / MAX_HEIGHT) * gaugeHeight;
heightDot.setAttribute("cy", dotY);
heightFill.setAttribute("y", dotY);
heightFill.setAttribute("height", Math.max(0, gaugeBottom - dotY));
}
uInput.addEventListener("input", () => {
u = Number(uInput.value);
updatePoint();
});
vInput.addEventListener("input", () => {
v = Number(vInput.value);
updatePoint();
});
document.querySelector("#centerPoint").addEventListener("click", () => {
u = 0;
v = 0;
updatePoint();
});
document.querySelector("#resetView").addEventListener("click", () => {
cameraState.radius = 8.6;
cameraState.theta = 0.72;
cameraState.phi = 1.08;
updateCamera();
});
// Raycasting permits direct manipulation on the faceted graph.
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function raycastSurface(event) {
const bounds = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - bounds.left) / bounds.width) * 2 - 1;
pointer.y = -((event.clientY - bounds.top) / bounds.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
return raycaster.intersectObject(surface, false)[0] || null;
}
let dragMode = null;
let lastPointerX = 0;
let lastPointerY = 0;
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
canvas.focus();
canvas.setPointerCapture(event.pointerId);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
const forceOrbit =
event.button === 2 ||
event.button === 1 ||
event.shiftKey;
if (forceOrbit) {
dragMode = "orbit";
canvas.style.cursor = "grabbing";
return;
}
const hit = raycastSurface(event);
if (hit) {
dragMode = "point";
u = clampDomain(hit.point.x);
v = clampDomain(hit.point.z);
updatePoint();
canvas.style.cursor = "crosshair";
} else {
dragMode = "orbit";
canvas.style.cursor = "grabbing";
}
});
canvas.addEventListener("pointermove", (event) => {
if (dragMode === "point") {
const hit = raycastSurface(event);
if (hit) {
u = clampDomain(hit.point.x);
v = clampDomain(hit.point.z);
updatePoint();
}
} else if (dragMode === "orbit") {
const deltaX = event.clientX - lastPointerX;
const deltaY = event.clientY - lastPointerY;
cameraState.theta -= deltaX * 0.008;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - deltaY * 0.006,
0.34,
1.46
);
updateCamera();
}
lastPointerX = event.clientX;
lastPointerY = event.clientY;
});
function endDrag(event) {
dragMode = null;
canvas.style.cursor = "grab";
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.006,
5.0,
14.0
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("keydown", (event) => {
const amount = event.shiftKey ? 0.2 : 0.05;
let handled = true;
switch (event.key) {
case "ArrowLeft":
u -= amount;
break;
case "ArrowRight":
u += amount;
break;
case "ArrowUp":
v += amount;
break;
case "ArrowDown":
v -= amount;
break;
default:
handled = false;
}
if (handled) {
event.preventDefault();
updatePoint();
}
});
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height, false);
}
window.addEventListener("resize", resize);
resize();
updatePoint();
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```