Prompt specification
Build or customize the Three.js 3D scene "Vector relationship 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: Vector relationship exploration rig
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/vector-relationship-exploration-rig-x1756
Scene Description Prompt:
Rotate voxel-style vectors to explore angle, dot product, and cross product, including zero-length cases. Three.js from cdnjs, one HTML file.
Working Three.js Starter (vector-relationship-exploration-rig-x1756):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Voxel Vector Lab</title>
<style>
:root {
--bg: #07111d;
--panel: rgba(10, 22, 36, 0.88);
--panel-border: rgba(149, 190, 221, 0.16);
--text: #edf7ff;
--muted: #8fa8bd;
--a: #32d7c5;
--b: #ff5f9f;
--cross: #ffc857;
}
* {
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;
}
button,
input {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.vignette {
position: fixed;
inset: 0;
z-index: 1;
pointer-events: none;
background:
radial-gradient(circle at 42% 45%, transparent 25%, rgba(2, 7, 13, 0.34) 100%),
linear-gradient(180deg, rgba(3, 9, 16, 0.05), rgba(3, 9, 16, 0.22));
}
.brand {
position: fixed;
top: 28px;
left: 30px;
z-index: 3;
width: min(440px, calc(100vw - 450px));
pointer-events: none;
text-shadow: 0 2px 18px rgba(0, 0, 0, 0.35);
}
.eyebrow {
display: inline-flex;
align-items: center;
gap: 9px;
margin-bottom: 12px;
color: #81e9dc;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.eyebrow::before {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--a);
box-shadow: 0 0 16px var(--a);
content: "";
}
.brand h1 {
margin: 0;
font-size: clamp(27px, 3.3vw, 48px);
font-weight: 760;
letter-spacing: -0.045em;
line-height: 1.03;
}
.brand p {
max-width: 400px;
margin: 13px 0 0;
color: #a8bdce;
font-size: 14px;
line-height: 1.55;
}
.panel {
position: fixed;
z-index: 5;
top: 20px;
right: 20px;
bottom: 20px;
width: 382px;
overflow-y: auto;
padding: 18px;
border: 1px solid var(--panel-border);
border-radius: 22px;
background: var(--panel);
box-shadow:
0 24px 70px rgba(0, 0, 0, 0.38),
inset 0 1px 0 rgba(255, 255, 255, 0.035);
backdrop-filter: blur(20px) saturate(125%);
scrollbar-width: thin;
scrollbar-color: #2a4257 transparent;
}
.panel::-webkit-scrollbar {
width: 6px;
}
.panel::-webkit-scrollbar-thumb {
border-radius: 20px;
background: #2a4257;
}
.panel-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 15px;
}
.panel-title {
font-size: 14px;
font-weight: 800;
letter-spacing: 0.02em;
}
.live {
display: inline-flex;
align-items: center;
gap: 6px;
color: #94aabd;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
}
.live::before {
width: 6px;
height: 6px;
border-radius: 50%;
background: #5ef2b2;
box-shadow: 0 0 10px #5ef2b2;
content: "";
}
.reset {
width: 31px;
height: 31px;
padding: 0;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 9px;
background: rgba(255, 255, 255, 0.04);
color: #b9c9d6;
cursor: pointer;
transition: 160ms ease;
}
.reset:hover {
border-color: rgba(255, 255, 255, 0.25);
background: rgba(255, 255, 255, 0.08);
color: white;
transform: rotate(-18deg);
}
.control-card {
margin-bottom: 12px;
padding: 14px 14px 12px;
border: 1px solid rgba(255, 255, 255, 0.075);
border-left: 3px solid var(--vector-color);
border-radius: 14px;
background: rgba(255, 255, 255, 0.025);
}
.control-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
}
.vector-name {
display: flex;
align-items: center;
gap: 9px;
font-size: 13px;
font-weight: 800;
}
.vector-dot {
width: 11px;
height: 11px;
border-radius: 3px;
background: var(--vector-color);
box-shadow: 0 0 14px color-mix(in srgb, var(--vector-color) 65%, transparent);
}
.components {
color: #8199ad;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
white-space: nowrap;
}
.slider-row {
display: grid;
grid-template-columns: 75px 1fr 46px;
align-items: center;
gap: 8px;
min-height: 29px;
}
.slider-row label {
color: #9bb0c2;
font-size: 11px;
}
.slider-row output {
color: #dceaf5;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
text-align: right;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
border-radius: 10px;
outline: none;
background: #26394c;
accent-color: var(--vector-color);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 13px;
height: 13px;
border: 2px solid #dff8ff;
border-radius: 3px;
background: var(--vector-color);
box-shadow: 0 0 10px rgba(0, 0, 0, 0.35);
appearance: none;
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
border: 2px solid #dff8ff;
border-radius: 3px;
background: var(--vector-color);
}
.section-label {
margin: 16px 2px 9px;
color: #718ba0;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.presets {
display: flex;
flex-wrap: wrap;
gap: 7px;
}
.preset {
padding: 7px 9px;
border: 1px solid rgba(255, 255, 255, 0.095);
border-radius: 8px;
background: rgba(255, 255, 255, 0.035);
color: #b4c6d5;
font-size: 10px;
font-weight: 700;
cursor: pointer;
transition: 150ms ease;
}
.preset:hover {
border-color: rgba(126, 221, 255, 0.36);
background: rgba(126, 221, 255, 0.075);
color: white;
transform: translateY(-1px);
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.metric {
min-width: 0;
padding: 12px;
border: 1px solid rgba(255, 255, 255, 0.075);
border-radius: 13px;
background: rgba(1, 8, 15, 0.28);
transition:
border-color 180ms ease,
background 180ms ease;
}
.metric.wide {
grid-column: 1 / -1;
}
.metric-label {
color: #829bb0;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.metric-value {
margin: 6px 0 4px;
overflow: hidden;
color: #f4fbff;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 24px;
font-weight: 750;
letter-spacing: -0.06em;
text-overflow: ellipsis;
white-space: nowrap;
}
.metric.wide .metric-value {
color: var(--cross);
}
.metric-note {
min-height: 28px;
color: #7f98ad;
font-size: 10px;
line-height: 1.4;
}
.metric.acute {
border-color: rgba(50, 215, 197, 0.28);
}
.metric.right {
border-color: rgba(255, 200, 87, 0.36);
background: rgba(255, 200, 87, 0.035);
}
.metric.obtuse {
border-color: rgba(255, 95, 159, 0.3);
}
.metric.undefined {
border-color: rgba(255, 177, 75, 0.48);
background: rgba(255, 177, 75, 0.055);
}
.metric.undefined .metric-value {
color: #ffb14b;
font-size: 19px;
}
.cross-components {
margin-top: 8px;
padding-top: 8px;
border-top: 1px solid rgba(255, 255, 255, 0.065);
color: #91a8ba;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
line-height: 1.5;
}
.formula {
margin-top: 10px;
padding: 10px 12px;
border: 1px solid rgba(255, 255, 255, 0.06);
border-radius: 11px;
background: rgba(255, 255, 255, 0.025);
color: #9cb2c3;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
line-height: 1.6;
text-align: center;
}
.status {
display: none;
margin-top: 10px;
padding: 10px 11px;
border: 1px solid rgba(255, 177, 75, 0.36);
border-radius: 10px;
background: rgba(255, 177, 75, 0.07);
color: #ffc47b;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-align: center;
text-transform: uppercase;
}
.status.show {
display: block;
}
.rule {
display: grid;
gap: 3px;
margin-top: 10px;
color: #718ba0;
font-size: 10px;
line-height: 1.45;
}
.rule strong {
color: #a8bdcd;
font-size: 10px;
}
.legend {
position: fixed;
z-index: 3;
left: 30px;
bottom: 27px;
display: flex;
flex-wrap: wrap;
gap: 14px;
pointer-events: none;
color: #9bb0c1;
font-size: 10px;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 7px;
}
.swatch {
width: 15px;
height: 6px;
border-radius: 2px;
background: var(--color);
box-shadow: 0 0 12px color-mix(in srgb, var(--color) 55%, transparent);
}
.instructions {
position: fixed;
z-index: 3;
left: 30px;
bottom: 54px;
color: #718a9e;
font-size: 10px;
pointer-events: none;
}
@media (max-width: 820px) {
.brand {
top: 15px;
left: 15px;
width: calc(100vw - 30px);
}
.brand h1 {
font-size: 25px;
}
.brand p,
.legend,
.instructions {
display: none;
}
.panel {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 55vh;
border-radius: 18px;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div class="vignette"></div>
<header class="brand">
<div class="eyebrow">Interactive math / vector lab</div>
<h1>Vectors, in every direction.</h1>
<p>
Rotate A and B. The dot product measures alignment; the cross product
finds the perpendicular direction given by the right-hand rule.
</p>
</header>
<aside class="panel">
<div class="panel-head">
<div>
<div class="panel-title">Vector controls</div>
<div class="live">Live calculation</div>
</div>
<button class="reset" id="resetCamera" title="Reset camera" aria-label="Reset camera">
↺
</button>
</div>
<section class="control-card" style="--vector-color: var(--a)">
<div class="control-head">
<div class="vector-name">
<span class="vector-dot"></span>
Vector A
</div>
<div class="components" id="componentsA">x 0.00 y 0.00 z 0.00</div>
</div>
<div class="slider-row">
<label for="magA">Magnitude</label>
<input id="magA" type="range" min="0" max="3" step="0.1" value="3" />
<output id="magAValue">3.0</output>
</div>
<div class="slider-row">
<label for="azA">Azimuth</label>
<input id="azA" type="range" min="0" max="360" step="1" value="30" />
<output id="azAValue">30°</output>
</div>
<div class="slider-row">
<label for="elA">Elevation</label>
<input id="elA" type="range" min="-90" max="90" step="1" value="20" />
<output id="elAValue">20°</output>
</div>
</section>
<section class="control-card" style="--vector-color: var(--b)">
<div class="control-head">
<div class="vector-name">
<span class="vector-dot"></span>
Vector B
</div>
<div class="components" id="componentsB">x 0.00 y 0.00 z 0.00</div>
</div>
<div class="slider-row">
<label for="magB">Magnitude</label>
<input id="magB" type="range" min="0" max="3" step="0.1" value="3" />
<output id="magBValue">3.0</output>
</div>
<div class="slider-row">
<label for="azB">Azimuth</label>
<input id="azB" type="range" min="0" max="360" step="1" value="120" />
<output id="azBValue">120°</output>
</div>
<div class="slider-row">
<label for="elB">Elevation</label>
<input id="elB" type="range" min="-90" max="90" step="1" value="0" />
<output id="elBValue">0°</output>
</div>
</section>
<div class="section-label">Quick configurations</div>
<div class="presets">
<button class="preset" data-preset="perpendicular">⊥ 90°</button>
<button class="preset" data-preset="parallel">∥ 0°</button>
<button class="preset" data-preset="opposite">180°</button>
<button class="preset" data-preset="zeroA">A = 0</button>
<button class="preset" data-preset="zeroB">B = 0</button>
</div>
<div class="section-label">Measurements</div>
<section class="metrics">
<article class="metric" id="angleCard">
<div class="metric-label">Angle θ</div>
<div class="metric-value" id="angleValue">90.0°</div>
<div class="metric-note" id="angleNote"></div>
</article>
<article class="metric" id="dotCard">
<div class="metric-label">Dot product</div>
<div class="metric-value" id="dotValue">0.00</div>
<div class="metric-note" id="dotNote"></div>
</article>
<article class="metric wide" id="crossCard">
<div class="metric-label">Cross product A × B</div>
<div class="metric-value" id="crossValue">0.00</div>
<div class="metric-note" id="crossNote"></div>
<div class="cross-components" id="crossComponents">
x 0.00 y 0.00 z 0.00
</div>
</article>
</section>
<div class="formula">
θ = cos⁻¹(a · b / |a||b|)<br />
a · b = |a||b|cos θ
</div>
<div class="status" id="zeroStatus"></div>
<div class="rule">
<strong>Zero-length rule</strong>
If |a| = 0 or |b| = 0, then a · b = 0 and a × b = 0, while the angle
between the vectors is undefined.
</div>
</aside>
<div class="instructions">
Drag a vector tip to rotate · Drag empty space to orbit · Scroll to zoom
</div>
<div class="legend">
<span class="legend-item">
<span class="swatch" style="--color: var(--a)"></span> Vector A
</span>
<span class="legend-item">
<span class="swatch" style="--color: var(--b)"></span> Vector B
</span>
<span class="legend-item">
<span class="swatch" style="--color: var(--cross)"></span> A × B
</span>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
const DEG = Math.PI / 180;
const EPS = 1e-6;
const X_AXIS = new THREE.Vector3(1, 0, 0);
const Y_AXIS = new THREE.Vector3(0, 1, 0);
const COLORS = {
a: 0x32d7c5,
b: 0xff5f9f,
cross: 0xffc857
};
// ---------------------------------------------------------------------
// Scene and renderer
// ---------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111d);
scene.fog = new THREE.Fog(0x07111d, 20, 43);
const camera = new THREE.PerspectiveCamera(
45,
window.innerWidth / window.innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
$("scene").appendChild(renderer.domElement);
const canvas = renderer.domElement;
canvas.setAttribute("aria-label", "Interactive 3D vector visualization");
canvas.style.cursor = "grab";
scene.add(new THREE.HemisphereLight(0xc9efff, 0x142033, 1.5));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.3);
keyLight.position.set(5, 9, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -12;
keyLight.shadow.camera.right = 12;
keyLight.shadow.camera.top = 12;
keyLight.shadow.camera.bottom = -12;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 35;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x5aa8ff, 1.1);
rimLight.position.set(-7, 2, -6);
scene.add(rimLight);
const grid = new THREE.GridHelper(24, 24, 0x3b5871, 0x183044);
grid.position.y = -3.2;
grid.material.transparent = true;
grid.material.opacity = 0.52;
grid.material.depthWrite = false;
scene.add(grid);
function addAxis(start, end, color) {
const geometry = new THREE.BufferGeometry().setFromPoints([start, end]);
const material = new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.25
});
scene.add(new THREE.Line(geometry, material));
}
addAxis(new THREE.Vector3(-9, 0, 0), new THREE.Vector3(9, 0, 0), 0xff647c);
addAxis(new THREE.Vector3(0, -6, 0), new THREE.Vector3(0, 6, 0), 0x61e6a1);
addAxis(new THREE.Vector3(0, 0, -9), new THREE.Vector3(0, 0, 9), 0x5da7ff);
const core = new THREE.Mesh(
new THREE.BoxGeometry(0.34, 0.34, 0.34),
new THREE.MeshStandardMaterial({
color: 0xe9f8ff,
emissive: 0x398ca3,
emissiveIntensity: 0.65,
roughness: 0.25,
metalness: 0.25,
flatShading: true
})
);
core.castShadow = true;
scene.add(core);
// ---------------------------------------------------------------------
// Voxel arrows and labels
// ---------------------------------------------------------------------
const cubeGeometry = new THREE.BoxGeometry(1, 1, 1);
function createArrowMaterial(color) {
return new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.09,
roughness: 0.34,
metalness: 0.12,
flatShading: true
});
}
const arrowMaterials = {
a: createArrowMaterial(COLORS.a),
b: createArrowMaterial(COLORS.b),
cross: createArrowMaterial(COLORS.cross)
};
function createArrow(material) {
const root = new THREE.Group();
scene.add(root);
return root;
}
const arrowA = createArrow(arrowMaterials.a);
const arrowB = createArrow(arrowMaterials.b);
const arrowCross = createArrow(arrowMaterials.cross);
function addBlock(root, x, y, z, sx, sy, sz) {
const block = new THREE.Mesh(cubeGeometry, root.userData.material);
block.position.set(x, y, z);
block.scale.set(sx, sy, sz);
block.castShadow = true;
block.receiveShadow = true;
root.add(block);
}
function buildVoxelArrow(root, vector) {
root.children.slice().forEach((child) => root.remove(child));
const length = vector.length();
if (length < EPS) {
root.visible = false;
return;
}
root.visible = true;
root.position.set(0, 0, 0);
root.quaternion.setFromUnitVectors(
X_AXIS,
vector.clone().normalize()
);
const cell = Math.min(0.19, length / 5);
const headLength = 3.8 * cell;
const shaftLength = Math.max(0, length - headLength);
const shaftCount = Math.max(1, Math.ceil(shaftLength / (cell * 0.78)));
const step = shaftLength / shaftCount;
// Voxel shaft.
for (let i = 0; i < shaftCount; i++) {
addBlock(
root,
i * step + step * 0.5,
0,
0,
step * 0.96,
cell * 0.88,
cell * 0.88
);
}
// Four-step pyramidal voxel arrowhead.
const base = shaftLength;
for (const y of [-cell, 0, cell]) {
for (const z of [-cell, 0, cell]) {
addBlock(
root,
base + cell * 0.5,
y,
z,
cell * 0.88,
cell * 0.88,
cell * 0.88
);
}
}
for (const y of [-cell * 0.5, cell * 0.5]) {
for (const z of [-cell * 0.5, cell * 0.5]) {
addBlock(
root,
base + cell * 1.45,
y,
z,
cell * 0.84,
cell * 0.84,
cell * 0.84
);
}
}
for (const y of [-cell * 0.5, cell * 0.5]) {
for (const z of [-cell * 0.5, cell * 0.5]) {
addBlock(
root,
base + cell * 2.35,
y,
z,
cell * 0.84,
cell * 0.84,
cell * 0.84
);
}
}
addBlock(
root,
base + cell * 3.3,
0,
0,
cell,
cell,
cell
);
}
arrowA.userData.material = arrowMaterials.a;
arrowB.userData.material = arrowMaterials.b;
arrowCross.userData.material = arrowMaterials.cross;
function createLabel(text, color) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 256;
labelCanvas.height = 128;
const context = labelCanvas.getContext("2d");
const cssColor = `#${color.toString(16).padStart(6, "0")}`;
context.clearRect(0, 0, 256, 128);
context.fillStyle = "rgba(6, 17, 29, 0.86)";
context.strokeStyle = cssColor;
context.lineWidth = 5;
context.beginPath();
context.roundRect(22, 20, 212, 88, 25);
context.fill();
context.stroke();
context.fillStyle = cssColor;
context.font = "700 52px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 128, 65);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(1.02, 0.51, 1);
sprite.renderOrder = 20;
scene.add(sprite);
return sprite;
}
const labelA = createLabel("A", COLORS.a);
const labelB = createLabel("B", COLORS.b);
const labelCross = createLabel("A × B", COLORS.cross);
// Draggable cube handles.
function createHandle(id, color) {
const group = new THREE.Group();
const hitMesh = new THREE.Mesh(
new THREE.BoxGeometry(0.36, 0.36, 0.36),
new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false,
colorWrite: false
})
);
hitMesh.userData.vectorId = id;
group.add(hitMesh);
const outline = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.BoxGeometry(0.25, 0.25, 0.25)),
new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.95
})
);
group.add(outline);
scene.add(group);
return { group, hitMesh, outline };
}
const handles = {
a: createHandle("a", COLORS.a),
b: createHandle("b", COLORS.b)
};
const handleHitMeshes = [handles.a.hitMesh, handles.b.hitMesh];
// Angle arc.
const arcPositions = new Float32Array(65 * 3);
const arcGeometry = new THREE.BufferGeometry();
arcGeometry.setAttribute(
"position",
new THREE.BufferAttribute(arcPositions, 3)
);
arcGeometry.setDrawRange(0, 0);
const angleArc = new THREE.Line(
arcGeometry,
new THREE.LineBasicMaterial({
color: 0xe8f6ff,
transparent: true,
opacity: 0.6,
depthTest: false
})
);
angleArc.renderOrder = 10;
scene.add(angleArc);
// ---------------------------------------------------------------------
// Math and UI updates
// ---------------------------------------------------------------------
function vectorFromControls(prefix) {
const magnitude = Number($(`mag${prefix}`).value);
const azimuth = Number($(`az${prefix}`).value);
const elevation = Number($(`el${prefix}`).value);
const horizontal = magnitude * Math.cos(elevation * DEG);
const vector = new THREE.Vector3(
horizontal * Math.cos(azimuth * DEG),
magnitude * Math.sin(elevation * DEG),
horizontal * Math.sin(azimuth * DEG)
);
return { magnitude, azimuth, elevation, vector };
}
function cleanNumber(value) {
if (Math.abs(value) < 0.005) return 0;
return value;
}
function formatNumber(value) {
return cleanNumber(value).toFixed(2);
}
function formatSigned(value) {
const clean = cleanNumber(value);
return clean > 0 ? `+${clean.toFixed(2)}` : clean.toFixed(2);
}
function setMetricState(id, state) {
const element = $(id);
["acute", "right", "obtuse", "undefined"].forEach((className) => {
element.classList.remove(className);
});
if (state) element.classList.add(state);
}
function updateAngleArc(a, b, angleRadians) {
if (angleRadians === null || angleRadians < 0.001) {
angleArc.visible = false;
arcGeometry.setDrawRange(0, 0);
return;
}
const u = a.clone().normalize();
const v = b.clone().normalize();
const cosAngle = THREE.MathUtils.clamp(u.dot(v), -1, 1);
const sinAngle = Math.sqrt(Math.max(0, 1 - cosAngle * cosAngle));
let w;
if (sinAngle > 1e-5) {
w = v.clone().addScaledVector(u, -cosAngle).normalize();
} else {
const reference = Math.abs(u.y) < 0.9 ? Y_AXIS : X_AXIS;
w = new THREE.Vector3().crossVectors(u, reference).normalize();
}
for (let i = 0; i <= 64; i++) {
const t = angleRadians * (i / 64);
const point = u
.clone()
.multiplyScalar(Math.cos(t))
.addScaledVector(w, Math.sin(t))
.multiplyScalar(1.18);
arcPositions[i * 3] = point.x;
arcPositions[i * 3 + 1] = point.y;
arcPositions[i * 3 + 2] = point.z;
}
arcGeometry.attributes.position.needsUpdate = true;
arcGeometry.setDrawRange(0, 65);
angleArc.visible = true;
}
function update() {
const aData = vectorFromControls("A");
const bData = vectorFromControls("B");
const a = aData.vector;
const b = bData.vector;
const magnitudeA = a.length();
const magnitudeB = b.length();
const dot = a.dot(b);
const cross = new THREE.Vector3().crossVectors(a, b);
const crossMagnitude = cross.length();
// Controls.
$("magAValue").textContent = aData.magnitude.toFixed(1);
$("magBValue").textContent = bData.magnitude.toFixed(1);
$("azAValue").textContent = `${Math.round(aData.azimuth)}°`;
$("azBValue").textContent = `${Math.round(bData.azimuth)}°`;
$("elAValue").textContent = `${Math.round(aData.elevation)}°`;
$("elBValue").textContent = `${Math.round(bData.elevation)}°`;
$("componentsA").textContent =
`x ${formatNumber(a.x)} y ${formatNumber(a.y)} z ${formatNumber(a.z)}`;
$("componentsB").textContent =
`x ${formatNumber(b.x)} y ${formatNumber(b.y)} z ${formatNumber(b.z)}`;
// Arrows.
buildVoxelArrow(arrowA, a);
buildVoxelArrow(arrowB, b);
buildVoxelArrow(arrowCross, cross);
handles.a.group.position.copy(a);
handles.b.group.position.copy(b);
handles.a.group.visible = magnitudeA >= EPS;
handles.b.group.visible = magnitudeB >= EPS;
if (magnitudeA >= EPS) {
labelA.visible = true;
labelA.position.copy(a).addScaledVector(a.clone().normalize(), 0.56);
} else {
labelA.visible = false;
}
if (magnitudeB >= EPS) {
labelB.visible = true;
labelB.position.copy(b).addScaledVector(b.clone().normalize(), 0.56);
} else {
labelB.visible = false;
}
if (crossMagnitude >= EPS) {
labelCross.visible = true;
labelCross.position
.copy(cross)
.addScaledVector(cross.clone().normalize(), 0.62);
} else {
labelCross.visible = false;
}
// Angle.
let angleRadians = null;
if (magnitudeA >= EPS && magnitudeB >= EPS) {
const cosine = THREE.MathUtils.clamp(
dot / (magnitudeA * magnitudeB),
-1,
1
);
angleRadians = Math.acos(cosine);
$("angleValue").textContent = `${(angleRadians / DEG).toFixed(1)}°`;
if (cosine > 1e-5) {
$("angleNote").textContent = "Acute: the vectors point in broadly the same direction.";
setMetricState("angleCard", "acute");
} else if (cosine < -1e-5) {
$("angleNote").textContent = "Obtuse: the vectors point in broadly opposite directions.";
setMetricState("angleCard", "obtuse");
} else {
$("angleNote").textContent = "Right angle: A and B are perpendicular.";
setMetricState("angleCard", "right");
}
} else {
$("angleValue").textContent = "Undefined";
$("angleNote").textContent =
"The angle requires both vectors to have nonzero length.";
setMetricState("angleCard", "undefined");
}
updateAngleArc(a, b, angleRadians);
// Dot product.
$("dotValue").textContent = formatSigned(dot);
if (magnitudeA < EPS || magnitudeB < EPS) {
$("dotNote").textContent =
"A zero-length vector always has a dot product of zero.";
setMetricState("dotCard", "undefined");
} else if (Math.abs(dot) < 1e-5) {
$("dotNote").textContent = "Zero dot product means the vectors are perpendicular.";
setMetricState("dotCard", "right");
} else if (dot > 0) {
$("dotNote").textContent = "Positive dot product: the angle is acute.";
setMetricState("dotCard", "acute");
} else {
$("dotNote").textContent = "Negative dot product: the angle is obtuse.";
setMetricState("dotCard", "obtuse");
}
// Cross product.
$("crossValue").textContent = formatNumber(crossMagnitude);
$("crossComponents").innerHTML =
`x ${formatNumber(cross.x)} ` +
`y ${formatNumber(cross.y)} ` +
`z ${formatNumber(cross.z)}`;
if (magnitudeA < EPS || magnitudeB < EPS) {
$("crossNote").textContent =
"A × B = 0 because at least one vector has zero length.";
} else if (crossMagnitude < EPS) {
$("crossNote").textContent =
"The vectors are parallel, so their cross product is zero.";
} else {
$("crossNote").textContent =
"A × B is perpendicular to both A and B; the arrow follows the right-hand rule.";
}
// Zero-length status.
const status = $("zeroStatus");
const zeroA = magnitudeA < EPS;
const zeroB = magnitudeB < EPS;
if (zeroA && zeroB) {
status.textContent = "Both vectors have zero length";
status.classList.add("show");
} else if (zeroA) {
status.textContent = "Vector A has zero length";
status.classList.add("show");
} else if (zeroB) {
status.textContent = "Vector B has zero length";
status.classList.add("show");
} else {
status.classList.remove("show");
}
}
// ---------------------------------------------------------------------
// Presets
// ---------------------------------------------------------------------
function directionToAngles(direction) {
const normalized = direction.clone().normalize();
const elevation = Math.asin(THREE.MathUtils.clamp(normalized.y, -1, 1)) / DEG;
let azimuth = Math.atan2(normalized.z, normalized.x) / DEG;
if (azimuth < 0) azimuth += 360;
return {
azimuth: Math.round(azimuth),
elevation: Math.round(elevation)
};
}
function setDirection(prefix, direction) {
const angles = directionToAngles(direction);
$(`az${prefix}`).value = angles.azimuth;
$(`el${prefix}`).value = angles.elevation;
}
function applyPreset(name) {
if (name === "zeroA") {
$("magA").value = 0;
} else if (name === "zeroB") {
$("magB").value = 0;
} else {
let aData = vectorFromControls("A");
if (aData.magnitude < EPS) {
$("magA").value = 3;
$("azA").value = 30;
$("elA").value = 20;
aData = vectorFromControls("A");
}
let bMagnitude = Number($("magB").value);
if (bMagnitude < EPS) bMagnitude = 3;
$("magB").value = bMagnitude;
const aDirection = aData.vector.clone().normalize();
if (name === "parallel") {
setDirection("B", aDirection);
} else if (name === "opposite") {
setDirection("B", aDirection.clone().negate());
} else if (name === "perpendicular") {
let perpendicular = new THREE.Vector3().crossVectors(aDirection, Y_AXIS);
if (perpendicular.lengthSq() < 1e-6) {
perpendicular.crossVectors(aDirection, X_AXIS);
}
perpendicular.normalize();
setDirection("B", perpendicular);
}
}
update();
}
document.querySelectorAll("[data-preset]").forEach((button) => {
button.addEventListener("click", () => {
applyPreset(button.dataset.preset);
});
});
[
"magA", "azA", "elA",
"magB", "azB", "elB"
].forEach((id) => {
$(id).addEventListener("input", update);
});
// ---------------------------------------------------------------------
// Direct camera and vector controls
// ---------------------------------------------------------------------
const cameraState = {
yaw: 0.78,
pitch: 0.43,
distance: 17
};
function applyCamera() {
const horizontal = Math.cos(cameraState.pitch) * cameraState.distance;
camera.position.set(
horizontal * Math.cos(cameraState.yaw),
Math.sin(cameraState.pitch) * cameraState.distance,
horizontal * Math.sin(cameraState.yaw)
);
camera.lookAt(0, 0, 0);
}
applyCamera();
$("resetCamera").addEventListener("click", () => {
cameraState.yaw = 0.78;
cameraState.pitch = 0.43;
cameraState.distance = 17;
applyCamera();
});
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let dragState = null;
function updatePointer(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;
}
function pickHandle(event) {
updatePointer(event);
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(handleHitMeshes, false);
for (const intersection of intersections) {
const id = intersection.object.userData.vectorId;
if (handles[id].group.visible) return id;
}
return null;
}
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
const handleId = pickHandle(event);
if (handleId) {
const tip =
handleId === "a"
? vectorFromControls("A").vector
: vectorFromControls("B").vector;
const cameraDirection = camera.getWorldDirection(new THREE.Vector3());
const plane = new THREE.Plane().setFromNormalAndCoplanarPoint(
cameraDirection,
tip
);
dragState = {
kind: "vector",
id: handleId,
plane
};
} else {
dragState = {
kind: "camera",
x: event.clientX,
y: event.clientY
};
}
canvas.setPointerCapture(event.pointerId);
canvas.style.cursor = "grabbing";
event.preventDefault();
});
canvas.addEventListener("pointermove", (event) => {
if (!dragState) {
canvas.style.cursor = pickHandle(event) ? "crosshair" : "grab";
return;
}
if (dragState.kind === "camera") {
const dx = event.clientX - dragState.x;
const dy = event.clientY - dragState.y;
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.005,
-1.3,
1.3
);
dragState.x = event.clientX;
dragState.y = event.clientY;
applyCamera();
} else if (dragState.kind === "vector") {
updatePointer(event);
raycaster.setFromCamera(pointer, camera);
const intersection = new THREE.Vector3();
if (!raycaster.ray.intersectPlane(dragState.plane, intersection)) {
return;
}
if (intersection.lengthSq() < 1e-8) return;
const direction = intersection.normalize();
const angles = directionToAngles(direction);
const prefix = dragState.id.toUpperCase();
$(`az${prefix}`).value = angles.azimuth;
$(`el${prefix}`).value = angles.elevation;
update();
}
});
function endDrag(event) {
if (dragState && canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
dragState = null;
canvas.style.cursor = "grab";
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.distance = THREE.MathUtils.clamp(
cameraState.distance * Math.exp(event.deltaY * 0.001),
7,
30
);
applyCamera();
},
{ passive: false }
);
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
// ---------------------------------------------------------------------
// Resize and animation
// ---------------------------------------------------------------------
function resize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
}
window.addEventListener("resize", resize);
update();
let previousTime = performance.now();
function animate(time) {
requestAnimationFrame(animate);
const delta = Math.min((time - previousTime) / 1000, 0.05);
previousTime = time;
core.rotation.x += delta * 0.32;
core.rotation.y += delta * 0.48;
core.rotation.z += delta * 0.21;
const pulse = 1 + Math.sin(time * 0.0022) * 0.055;
core.scale.setScalar(pulse);
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```