Prompt specification
Build or customize the Three.js 3D scene "Three-axis coordinate pegboard" 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: Three-axis coordinate pegboard
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/three-axis-coordinate-pegboard-x1689
Scene Description Prompt:
Build perpendicular labeled axes and a sparse grid with movable points; project each point to its coordinate components and distinguish units from grid indices. Use Three.js from cdnjs in a single HTML file, with low-poly forms.
Working Three.js Starter (three-axis-coordinate-pegboard-x1689):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Three.js Component Field</title>
<style>
:root {
color-scheme: dark;
--bg: #071019;
--panel: rgba(10, 20, 31, 0.86);
--border: rgba(150, 180, 205, 0.18);
--text: #edf5fb;
--muted: #91a5b8;
--x: #ff6674;
--y: #62e6a2;
--z: #62adff;
--point: #ffb454;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#stage {
position: fixed;
inset: 0;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#stage canvas:active {
cursor: grabbing;
}
.panel {
position: fixed;
z-index: 10;
border: 1px solid var(--border);
border-radius: 16px;
background: var(--panel);
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
.intro {
top: 20px;
left: 20px;
width: min(340px, calc(100vw - 40px));
padding: 18px 19px;
}
.eyebrow {
margin: 0 0 7px;
color: #a8bdd0;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 23px;
line-height: 1.08;
letter-spacing: -0.03em;
}
.subtitle {
margin: 10px 0 15px;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 5px 8px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 999px;
color: #c7d4df;
background: rgba(255, 255, 255, 0.035);
font-size: 11px;
}
.dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 9px currentColor;
}
.x { color: var(--x); }
.y { color: var(--y); }
.z { color: var(--z); }
.p { color: var(--point); }
.inspector {
top: 20px;
right: 20px;
width: min(315px, calc(100vw - 40px));
padding: 17px;
}
.inspector-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 13px;
}
.inspector h2 {
margin: 0;
font-size: 16px;
}
.count {
padding: 4px 8px;
border-radius: 999px;
color: #9fb2c3;
background: rgba(255, 255, 255, 0.055);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.scale-note {
margin-bottom: 14px;
padding: 10px 11px;
border: 1px solid rgba(98, 173, 255, 0.18);
border-radius: 10px;
color: #a9bfd1;
background: rgba(98, 173, 255, 0.055);
font-size: 11px;
line-height: 1.45;
}
.scale-note strong {
color: #e8f3fc;
}
.coordinates {
display: grid;
gap: 7px;
}
.coordinate {
display: grid;
grid-template-columns: 28px 1fr auto;
align-items: center;
gap: 8px;
padding: 9px 10px;
border: 1px solid rgba(255, 255, 255, 0.065);
border-radius: 10px;
background: rgba(255, 255, 255, 0.027);
}
.axis-key {
font-size: 11px;
font-weight: 900;
}
.coordinate strong {
display: block;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 13px;
}
.coordinate small {
display: block;
margin-top: 2px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
}
.component {
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-top: 13px;
}
button {
min-height: 36px;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 9px;
color: #dce8f2;
background: rgba(255, 255, 255, 0.055);
font: inherit;
font-size: 11px;
font-weight: 750;
cursor: pointer;
transition:
background 150ms ease,
border-color 150ms ease,
transform 150ms ease;
}
button:hover {
border-color: rgba(255, 255, 255, 0.22);
background: rgba(255, 255, 255, 0.1);
}
button:active {
transform: translateY(1px);
}
button.active {
border-color: rgba(98, 230, 162, 0.42);
color: #dffbed;
background: rgba(98, 230, 162, 0.11);
}
button.danger:hover {
border-color: rgba(255, 102, 116, 0.45);
color: #ffd8dc;
background: rgba(255, 102, 116, 0.1);
}
.instructions {
bottom: 20px;
left: 20px;
max-width: min(560px, calc(100vw - 40px));
padding: 13px 15px;
color: #aebfce;
font-size: 11px;
line-height: 1.5;
}
.instructions strong {
color: #eff7fd;
}
kbd {
display: inline-block;
min-width: 22px;
margin: 0 2px;
padding: 2px 5px;
border: 1px solid rgba(255, 255, 255, 0.17);
border-bottom-color: rgba(255, 255, 255, 0.28);
border-radius: 5px;
color: #eef7ff;
background: rgba(255, 255, 255, 0.07);
font: 10px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
text-align: center;
}
@media (max-width: 760px) {
.intro {
top: 12px;
left: 12px;
width: calc(100vw - 24px);
}
.intro .subtitle,
.intro .legend {
display: none;
}
.inspector {
top: auto;
right: 12px;
bottom: 64px;
width: min(285px, calc(100vw - 24px));
}
.instructions {
right: 12px;
bottom: 12px;
left: 12px;
max-width: none;
}
}
</style>
</head>
<body>
<div id="stage" aria-label="Interactive three-dimensional coordinate system"></div>
<section class="panel intro">
<p class="eyebrow">Coordinate visualization</p>
<h1>Component Field</h1>
<p class="subtitle">
Perpendicular axes, a sparse lattice, and movable low-poly samples.
Every point is projected onto the X, Y, and Z component axes.
</p>
<div class="legend">
<span class="x"><i class="dot"></i>X component</span>
<span class="y"><i class="dot"></i>Y component</span>
<span class="z"><i class="dot"></i>Z component</span>
<span class="p"><i class="dot"></i>Sample</span>
</div>
</section>
<aside class="panel inspector">
<div class="inspector-head">
<h2 id="selectedTitle">P1</h2>
<span class="count" id="pointCount">3 points</span>
</div>
<div class="scale-note">
<strong>Axes show metres.</strong>
Muted lattice labels show grid indices.
<br />1 grid index = <strong>2.00 m</strong>.
</div>
<div class="coordinates" id="coordinates"></div>
<div class="buttons">
<button id="addButton" type="button">+ Add point</button>
<button id="snapButton" class="active" type="button" aria-pressed="true">
Snap: on
</button>
<button id="removeButton" class="danger" type="button">Remove</button>
<button id="resetButton" type="button">Reset scene</button>
</div>
</aside>
<div class="panel instructions">
<strong>Navigate:</strong> drag empty space to orbit · right-drag to pan ·
wheel to zoom.<br />
<strong>Move a point:</strong> drag it on the XZ plane ·
hold <kbd>Shift</kbd> for XY · hold <kbd>Alt</kbd> for YZ.
</div>
<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");
// ---------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------
const GRID_LIMIT = 5;
const METERS_PER_INDEX = 2;
const CELL = METERS_PER_INDEX;
const WORLD_LIMIT = GRID_LIMIT * CELL;
const AXES = {
x: { color: 0xff6674, css: "#ff6674", key: "i", title: "X AXIS · m" },
y: { color: 0x62e6a2, css: "#62e6a2", key: "j", title: "Y AXIS · m" },
z: { color: 0x62adff, css: "#62adff", key: "k", title: "Z AXIS · m" }
};
const POINT_COLOR = 0xffb454;
const POINT_CSS = "#ffb454";
let nextPointNumber = 1;
let selectedId = null;
let snapEnabled = true;
const initialPoints = [
[-2, 1, -1],
[1, 2, 1],
[3, 0, -2]
];
// ---------------------------------------------------------------------
// Renderer, scene, and camera
// ---------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071019);
scene.fog = new THREE.FogExp2(0x071019, 0.025);
const camera = new THREE.PerspectiveCamera(
43,
innerWidth / innerHeight,
0.1,
120
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
stage.appendChild(renderer.domElement);
const ambient = new THREE.AmbientLight(0x91abc2, 1.45);
scene.add(ambient);
const keyLight = new THREE.DirectionalLight(0xffffff, 2.2);
keyLight.position.set(8, 14, 9);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4e8fff, 1.1);
rimLight.position.set(-10, 4, -8);
scene.add(rimLight);
const orbit = {
theta: 0.72,
phi: 0.98,
radius: 25,
target: new THREE.Vector3(0, 1.1, 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);
camera.updateMatrixWorld();
}
updateCamera();
// ---------------------------------------------------------------------
// Canvas sprite labels
// ---------------------------------------------------------------------
function roundedRect(ctx, x, y, w, h, r) {
const radius = Math.min(r, w / 2, h / 2);
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + w - radius, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + radius);
ctx.lineTo(x + w, y + h - radius);
ctx.quadraticCurveTo(x + w, y + h, x + w - radius, y + h);
ctx.lineTo(x + radius, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
}
function hexToRgba(hex, alpha) {
const value = hex.replace("#", "");
const n = parseInt(value, 16);
const r = (n >> 16) & 255;
const g = (n >> 8) & 255;
const b = n & 255;
return `rgba(${r},${g},${b},${alpha})`;
}
function drawLabel(sprite, text, color = "#dce8f2", kind = "unit") {
const { canvas, ctx, texture } = sprite.userData;
ctx.clearRect(0, 0, canvas.width, canvas.height);
const isPoint = kind === "point";
const isIndex = kind === "index";
roundedRect(ctx, 3, 3, canvas.width - 6, canvas.height - 6, 17);
ctx.fillStyle = isPoint
? hexToRgba(color, 0.96)
: isIndex
? "rgba(7,15,24,0.86)"
: "rgba(7,15,24,0.82)";
ctx.fill();
ctx.lineWidth = isPoint ? 3 : isIndex ? 3 : 4;
ctx.strokeStyle = isPoint
? "rgba(255,255,255,0.55)"
: isIndex
? "rgba(125,145,165,0.4)"
: hexToRgba(color, 0.75);
ctx.stroke();
ctx.fillStyle = isPoint ? "#101820" : isIndex ? "#8fa3b5" : color;
ctx.font = isPoint
? "800 35px ui-monospace, SFMono-Regular, Menlo, monospace"
: isIndex
? "700 28px ui-monospace, SFMono-Regular, Menlo, monospace"
: "750 30px ui-monospace, SFMono-Regular, Menlo, monospace";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, canvas.width / 2, canvas.height / 2 + 1);
texture.needsUpdate = true;
}
function createLabel(
text,
color = "#dce8f2",
kind = "unit",
width = 1.6
) {
const canvas = document.createElement("canvas");
canvas.width = 384;
canvas.height = 96;
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.renderOrder = 20;
sprite.userData = {
canvas,
ctx: canvas.getContext("2d"),
texture,
width
};
sprite.scale.set(width, width / 4, 1);
drawLabel(sprite, text, color, kind);
return sprite;
}
function setLabel(sprite, text, color, kind) {
const current = sprite.userData.text;
if (current !== text) {
sprite.userData.text = text;
drawLabel(sprite, text, color, kind);
}
}
// ---------------------------------------------------------------------
// Sparse lattice
// ---------------------------------------------------------------------
const floorMaterial = new THREE.MeshBasicMaterial({
color: 0x183044,
transparent: true,
opacity: 0.085,
depthWrite: false,
side: THREE.DoubleSide
});
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(WORLD_LIMIT * 2.35, WORLD_LIMIT * 2.35),
floorMaterial
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.025;
scene.add(floor);
const majorVertices = [];
const minorVertices = [];
for (let index = -GRID_LIMIT; index <= GRID_LIMIT; index++) {
const coordinate = index * CELL;
const target = index % 2 === 0 ? majorVertices : minorVertices;
target.push(
-WORLD_LIMIT, 0.015, coordinate,
WORLD_LIMIT, 0.015, coordinate
);
target.push(
coordinate, 0.015, -WORLD_LIMIT,
coordinate, 0.015, WORLD_LIMIT
);
}
function addGridLines(vertices, color, opacity) {
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(vertices, 3)
);
const material = new THREE.LineBasicMaterial({
color,
transparent: true,
opacity
});
scene.add(new THREE.LineSegments(geometry, material));
}
addGridLines(majorVertices, 0x63839b, 0.3);
addGridLines(minorVertices, 0x41576a, 0.14);
const latticeTitle = createLabel(
"GRID INDICES · i / j / k",
"#8399ab",
"index",
2.25
);
latticeTitle.position.set(0, 0.18, WORLD_LIMIT + 1.25);
scene.add(latticeTitle);
for (const index of [-4, -2, 0, 2, 4]) {
const coordinate = index * CELL;
const xIndexLabel = createLabel(
`i ${index < 0 ? "−" : index > 0 ? "+" : ""}${Math.abs(index)}`,
"#8399ab",
"index",
1.05
);
xIndexLabel.position.set(coordinate, 0.18, WORLD_LIMIT + 0.62);
scene.add(xIndexLabel);
const zIndexLabel = createLabel(
`k ${index < 0 ? "−" : index > 0 ? "+" : ""}${Math.abs(index)}`,
"#8399ab",
"index",
1.05
);
zIndexLabel.position.set(WORLD_LIMIT + 0.65, 0.18, coordinate);
scene.add(zIndexLabel);
}
// A separate muted ruler makes the Y grid indices distinct from metre ticks.
const yIndexRuler = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-WORLD_LIMIT - 1.25, -8, 0.55),
new THREE.Vector3(-WORLD_LIMIT - 1.25, 8, 0.55)
]),
new THREE.LineBasicMaterial({
color: 0x667b8d,
transparent: true,
opacity: 0.42
})
);
scene.add(yIndexRuler);
for (const index of [-4, -2, 0, 2, 4]) {
const y = index * CELL;
const tick = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-WORLD_LIMIT - 1.5, y, 0.55),
new THREE.Vector3(-WORLD_LIMIT - 1, y, 0.55)
]),
new THREE.LineBasicMaterial({
color: 0x7c91a2,
transparent: true,
opacity: 0.48
})
);
scene.add(tick);
const label = createLabel(
`j ${index < 0 ? "−" : index > 0 ? "+" : ""}${Math.abs(index)}`,
"#8399ab",
"index",
1.05
);
label.position.set(-WORLD_LIMIT - 2.05, y, 0.55);
scene.add(label);
}
// ---------------------------------------------------------------------
// Perpendicular labelled axes
// ---------------------------------------------------------------------
function createAxis(axisName) {
const axis = AXES[axisName];
const color = axis.color;
const shaft = new THREE.Mesh(
new THREE.CylinderGeometry(0.027, 0.027, WORLD_LIMIT * 2, 6),
new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.28,
roughness: 0.7,
flatShading: true
})
);
if (axisName === "x") shaft.rotation.z = -Math.PI / 2;
if (axisName === "z") shaft.rotation.x = Math.PI / 2;
scene.add(shaft);
const arrow = new THREE.Mesh(
new THREE.ConeGeometry(0.17, 0.5, 6),
new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.24,
roughness: 0.65,
flatShading: true
})
);
if (axisName === "x") {
arrow.rotation.z = -Math.PI / 2;
arrow.position.x = WORLD_LIMIT + 0.25;
} else if (axisName === "y") {
arrow.position.y = WORLD_LIMIT + 0.25;
} else {
arrow.rotation.x = Math.PI / 2;
arrow.position.z = WORLD_LIMIT + 0.25;
}
scene.add(arrow);
const title = createLabel(axis.title, axis.css, "unit", 2.05);
if (axisName === "x") title.position.set(WORLD_LIMIT + 1.35, 0.42, 0.42);
if (axisName === "y") title.position.set(0.42, WORLD_LIMIT + 1.15, 0.42);
if (axisName === "z") title.position.set(0.42, 0.42, WORLD_LIMIT + 1.35);
scene.add(title);
// Bright labels are physical-unit ticks.
for (const index of [-4, -2, 2, 4]) {
const coordinate = index * CELL;
const meters = index * METERS_PER_INDEX;
const text = `${meters < 0 ? "−" : "+"}${Math.abs(meters)} m`;
const label = createLabel(text, axis.css, "unit", 1.15);
if (axisName === "x") {
label.position.set(coordinate, 0.34, 0.34);
scene.add(tickLine(
new THREE.Vector3(coordinate, 0, -0.16),
new THREE.Vector3(coordinate, 0, 0.16),
color
));
} else if (axisName === "y") {
label.position.set(0.34, coordinate, 0.34);
scene.add(tickLine(
new THREE.Vector3(-0.16, coordinate, 0),
new THREE.Vector3(0.16, coordinate, 0),
color
));
} else {
label.position.set(0.34, 0.34, coordinate);
scene.add(tickLine(
new THREE.Vector3(0, -0.16, coordinate),
new THREE.Vector3(0, 0.16, coordinate),
color
));
}
scene.add(label);
}
}
function tickLine(a, b, color) {
return new THREE.Line(
new THREE.BufferGeometry().setFromPoints([a, b]),
new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.88
})
);
}
createAxis("x");
createAxis("y");
createAxis("z");
const origin = new THREE.Mesh(
new THREE.OctahedronGeometry(0.13, 0),
new THREE.MeshStandardMaterial({
color: 0xdbe8f2,
emissive: 0xffffff,
emissiveIntensity: 0.15,
flatShading: true
})
);
scene.add(origin);
const originLabel = createLabel("O · 0 m", "#dbe8f2", "unit", 1.25);
originLabel.position.set(0.35, 0.52, 0.52);
scene.add(originLabel);
// ---------------------------------------------------------------------
// Points and component projections
// ---------------------------------------------------------------------
const points = [];
const pickableMeshes = [];
function createProjection(color) {
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(new Float32Array(6), 3)
);
const line = new THREE.Line(
geometry,
new THREE.LineDashedMaterial({
color,
dashSize: 0.24,
gapSize: 0.14,
transparent: true,
opacity: 0.72
})
);
line.frustumCulled = false;
scene.add(line);
const marker = new THREE.Mesh(
new THREE.OctahedronGeometry(0.13, 0),
new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.38,
flatShading: true
})
);
scene.add(marker);
const label = createLabel("", "#ffffff", "unit", 1.55);
scene.add(label);
return { line, marker, label };
}
function createPoint(grid) {
const id = nextPointNumber++;
const group = new THREE.Group();
scene.add(group);
const geometry = new THREE.OctahedronGeometry(0.37, 0);
const material = new THREE.MeshStandardMaterial({
color: POINT_COLOR,
emissive: POINT_COLOR,
emissiveIntensity: 0.12,
metalness: 0.08,
roughness: 0.68,
flatShading: true
});
const mesh = new THREE.Mesh(geometry, material);
mesh.userData.pointId = id;
group.add(mesh);
pickableMeshes.push(mesh);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry),
new THREE.LineBasicMaterial({
color: 0x6b431d,
transparent: true,
opacity: 0.8
})
);
group.add(edges);
const halo = new THREE.Mesh(
new THREE.TorusGeometry(0.53, 0.035, 4, 16),
new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.9
})
);
halo.visible = false;
group.add(halo);
const label = createLabel(
`P${id}`,
POINT_CSS,
"point",
0.8
);
label.position.set(0, 0.66, 0);
group.add(label);
const point = {
id,
grid: grid.clone(),
group,
mesh,
material,
halo,
label,
projections: {
x: createProjection(AXES.x.color),
y: createProjection(AXES.y.color),
z: createProjection(AXES.z.color)
}
};
points.push(point);
updatePoint(point);
return point;
}
function updatePoint(point) {
const world = point.grid.clone().multiplyScalar(CELL);
point.group.position.copy(world);
const target = {
x: new THREE.Vector3(world.x, 0, 0),
y: new THREE.Vector3(0, world.y, 0),
z: new THREE.Vector3(0, 0, world.z)
};
const labelOffsets = {
x: new THREE.Vector3(0, 0.27, 0.3),
y: new THREE.Vector3(0.31, 0, 0.3),
z: new THREE.Vector3(0.31, 0.27, 0)
};
for (const axisName of ["x", "y", "z"]) {
const projection = point.projections[axisName];
const end = target[axisName];
const positions = projection.line.geometry.getAttribute("position");
positions.setXYZ(0, world.x, world.y, world.z);
positions.setXYZ(1, end.x, end.y, end.z);
positions.needsUpdate = true;
projection.line.geometry.computeBoundingSphere();
projection.line.computeLineDistances();
projection.marker.position.copy(end);
projection.label.position.copy(end).add(labelOffsets[axisName]);
const meters = point.grid[axisName] * METERS_PER_INDEX;
const meterText = `${meters < 0 ? "−" : meters > 0 ? "+" : ""}${Math.abs(meters).toFixed(1)} m`;
setLabel(
projection.label,
`${axisName.toUpperCase()} ${meterText}`,
AXES[axisName].css,
"unit"
);
}
const selected = selectedId === point.id;
point.halo.visible = selected;
point.material.emissiveIntensity = selected ? 0.42 : 0.12;
point.mesh.scale.setScalar(selected ? 1.13 : 1);
}
function updateAllPoints() {
points.forEach(updatePoint);
updateInspector();
}
for (const coordinates of initialPoints) {
const point = createPoint(new THREE.Vector3(...coordinates));
if (selectedId === null) selectedId = point.id;
}
// ---------------------------------------------------------------------
// Inspector
// ---------------------------------------------------------------------
const selectedTitle = document.querySelector("#selectedTitle");
const pointCount = document.querySelector("#pointCount");
const coordinatesElement = document.querySelector("#coordinates");
updateAllPoints();
function signed(value, digits = 2) {
if (Math.abs(value) < 0.000001) {
return (0).toFixed(digits);
}
return `${value > 0 ? "+" : "−"}${Math.abs(value).toFixed(digits)}`;
}
function updateInspector() {
const point = points.find((entry) => entry.id === selectedId);
if (!point) {
selectedTitle.textContent = "No point";
coordinatesElement.innerHTML = "";
pointCount.textContent = `${points.length} points`;
return;
}
selectedTitle.textContent = `P${point.id}`;
pointCount.textContent = `${points.length} point${points.length === 1 ? "" : "s"}`;
coordinatesElement.innerHTML = ["x", "y", "z"].map((axisName) => {
const index = point.grid[axisName];
const meters = index * METERS_PER_INDEX;
return `
<div class="coordinate">
<span class="axis-key ${axisName}">${axisName.toUpperCase()}</span>
<div>
<strong>${signed(meters, 2)} m</strong>
<small>grid ${AXES[axisName].key} = ${signed(index, 2)}</small>
</div>
<span class="component">${axisName} component</span>
</div>
`;
}).join("");
}
document.querySelector("#addButton").addEventListener("click", () => {
const candidate = new THREE.Vector3(
Math.round((Math.random() * 6) - 3),
Math.round((Math.random() * 6) - 3),
Math.round((Math.random() * 6) - 3)
);
const exists = points.some((point) =>
point.grid.distanceTo(candidate) < 0.01
);
if (exists) candidate.set(0, 1, 0);
const point = createPoint(candidate);
selectedId = point.id;
updateAllPoints();
});
document.querySelector("#removeButton").addEventListener("click", () => {
const index = points.findIndex((point) => point.id === selectedId);
if (index < 0 || points.length === 1) return;
const point = points[index];
scene.remove(point.group);
pickableMeshes.splice(pickableMeshes.indexOf(point.mesh), 1);
for (const axisName of ["x", "y", "z"]) {
const projection = point.projections[axisName];
scene.remove(projection.line);
scene.remove(projection.marker);
scene.remove(projection.label);
projection.line.geometry.dispose();
projection.line.material.dispose();
projection.marker.geometry.dispose();
projection.marker.material.dispose();
projection.label.material.map.dispose();
projection.label.material.dispose();
}
point.group.traverse((child) => {
if (child.geometry) child.geometry.dispose();
if (child.material) child.material.dispose();
});
points.splice(index, 1);
selectedId = points[0].id;
updateAllPoints();
});
const snapButton = document.querySelector("#snapButton");
snapButton.addEventListener("click", () => {
snapEnabled = !snapEnabled;
snapButton.classList.toggle("active", snapEnabled);
snapButton.setAttribute("aria-pressed", String(snapEnabled));
snapButton.textContent = `Snap: ${snapEnabled ? "on" : "off"}`;
});
document.querySelector("#resetButton").addEventListener("click", () => {
points.forEach((point, index) => {
if (initialPoints[index]) {
point.grid.set(...initialPoints[index]);
}
});
selectedId = points[0]?.id ?? null;
orbit.theta = 0.72;
orbit.phi = 0.98;
orbit.radius = 25;
orbit.target.set(0, 1.1, 0);
updateCamera();
updateAllPoints();
});
// ---------------------------------------------------------------------
// Direct camera controls and point dragging
// ---------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let dragState = null;
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 getDragPlane(point, event) {
const world = point.grid.clone().multiplyScalar(CELL);
if (event.shiftKey) {
return new THREE.Plane(
new THREE.Vector3(0, 0, 1),
-world.z
);
}
if (event.altKey) {
return new THREE.Plane(
new THREE.Vector3(1, 0, 0),
-world.x
);
}
return new THREE.Plane(
new THREE.Vector3(0, 1, 0),
-world.y
);
}
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0 && event.button !== 1 && event.button !== 2) return;
event.preventDefault();
renderer.domElement.setPointerCapture(event.pointerId);
setPointerFromEvent(event);
if (event.button === 0) {
const hits = raycaster.intersectObjects(pickableMeshes, false);
if (hits.length) {
const point = points.find(
(entry) => entry.id === hits[0].object.userData.pointId
);
selectedId = point.id;
updateAllPoints();
const plane = getDragPlane(point, event);
const hit = new THREE.Vector3();
if (raycaster.ray.intersectPlane(plane, hit)) {
dragState = {
type: "point",
point,
plane,
startHit: hit.clone(),
startGrid: point.grid.clone(),
mode: event.shiftKey ? "xy" : event.altKey ? "yz" : "xz"
};
return;
}
}
}
dragState = {
type: event.button === 0 ? "orbit" : "pan",
startX: event.clientX,
startY: event.clientY
};
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragState) return;
event.preventDefault();
setPointerFromEvent(event);
if (dragState.type === "point") {
const hit = new THREE.Vector3();
if (!raycaster.ray.intersectPlane(dragState.plane, hit)) return;
const delta = hit.clone().sub(dragState.startHit).divideScalar(CELL);
const grid = dragState.point.grid;
if (dragState.mode === "xz") {
grid.x = dragState.startGrid.x + delta.x;
grid.z = dragState.startGrid.z + delta.z;
} else if (dragState.mode === "xy") {
grid.x = dragState.startGrid.x + delta.x;
grid.y = dragState.startGrid.y + delta.y;
} else {
grid.y = dragState.startGrid.y + delta.y;
grid.z = dragState.startGrid.z + delta.z;
}
if (snapEnabled) {
grid.x = Math.round(grid.x);
grid.y = Math.round(grid.y);
grid.z = Math.round(grid.z);
}
grid.x = THREE.MathUtils.clamp(grid.x, -GRID_LIMIT, GRID_LIMIT);
grid.y = THREE.MathUtils.clamp(grid.y, -GRID_LIMIT, GRID_LIMIT);
grid.z = THREE.MathUtils.clamp(grid.z, -GRID_LIMIT, GRID_LIMIT);
updatePoint(dragState.point);
updateInspector();
return;
}
const dx = event.clientX - dragState.startX;
const dy = event.clientY - dragState.startY;
dragState.startX = event.clientX;
dragState.startY = event.clientY;
if (dragState.type === "orbit") {
orbit.theta -= dx * 0.006;
orbit.phi = THREE.MathUtils.clamp(
orbit.phi - dy * 0.006,
0.14,
Math.PI - 0.14
);
} else {
const right = new THREE.Vector3().setFromMatrixColumn(
camera.matrix,
0
);
const up = new THREE.Vector3().setFromMatrixColumn(
camera.matrix,
1
);
const worldPerPixel =
(2 * orbit.radius * Math.tan(THREE.MathUtils.degToRad(camera.fov / 2))) /
innerHeight;
orbit.target.addScaledVector(right, -dx * worldPerPixel);
orbit.target.addScaledVector(up, dy * worldPerPixel);
}
updateCamera();
});
function finishDrag(event) {
if (dragState && renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
dragState = null;
}
renderer.domElement.addEventListener("pointerup", finishDrag);
renderer.domElement.addEventListener("pointercancel", finishDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius * Math.exp(event.deltaY * 0.001),
11,
46
);
updateCamera();
},
{ passive: false }
);
// ---------------------------------------------------------------------
// Resize and render loop
// ---------------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
});
function animate() {
requestAnimationFrame(animate);
for (const point of points) {
if (point.halo.visible) {
point.halo.quaternion.copy(camera.quaternion);
}
}
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```