Prompt specification
Build or customize the Three.js 3D scene "Finite Mirror and Offset Target Aperture" 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: Finite Mirror and Offset Target Aperture
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/finite-mirror-and-offset-target-aperture-x3469
Scene Description Prompt:
Reflect a ray from a finite low-poly mirror toward an offset aperture, checking edge clearance. Use Three.js from cdnjs in one HTML file.
Working Three.js Starter (finite-mirror-and-offset-target-aperture-x3469):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Finite Mirror — Ray Reflection and Aperture Clearance</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(9, 22, 39, 0.86);
--border: rgba(126, 196, 255, 0.18);
--text: #eaf5ff;
--muted: #91a9bf;
--cyan: #62e8ff;
--green: #55efbd;
--red: #ff6474;
--amber: #ffb45f;
}
* {
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;
}
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.brand {
position: fixed;
top: 22px;
left: 24px;
z-index: 5;
pointer-events: none;
max-width: 480px;
}
.brand .eyebrow {
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.brand h1 {
margin: 7px 0 5px;
font-size: clamp(22px, 3vw, 36px);
line-height: 1.05;
letter-spacing: -0.035em;
}
.brand p {
margin: 0;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.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.34);
backdrop-filter: blur(16px);
}
#controls {
top: 20px;
right: 20px;
width: 310px;
padding: 18px;
}
.panel-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 16px;
font-size: 13px;
font-weight: 750;
letter-spacing: 0.02em;
}
.panel-title span {
color: var(--muted);
font-size: 10px;
font-weight: 600;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.control {
margin: 0 0 15px;
}
.control-head {
display: flex;
justify-content: space-between;
gap: 14px;
margin-bottom: 7px;
color: #cbdbea;
font-size: 12px;
}
output {
min-width: 58px;
color: var(--cyan);
font-variant-numeric: tabular-nums;
text-align: right;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
appearance: none;
border-radius: 999px;
outline: none;
background: #20364d;
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
appearance: none;
border: 2px solid #b9f2ff;
border-radius: 50%;
background: #43b9d2;
box-shadow: 0 0 0 4px rgba(98, 232, 255, 0.1);
}
input[type="range"]::-moz-range-thumb {
width: 12px;
height: 12px;
border: 2px solid #b9f2ff;
border-radius: 50%;
background: #43b9d2;
}
.divider {
height: 1px;
margin: 17px 0;
background: var(--border);
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
button {
min-height: 34px;
border: 1px solid rgba(126, 196, 255, 0.24);
border-radius: 9px;
background: rgba(50, 96, 135, 0.2);
color: var(--text);
font: inherit;
font-size: 11px;
font-weight: 700;
cursor: pointer;
}
button:hover {
border-color: rgba(126, 196, 255, 0.5);
background: rgba(50, 96, 135, 0.35);
}
button.warn {
border-color: rgba(255, 180, 95, 0.3);
color: #ffd7aa;
}
.checkbox {
display: flex;
align-items: center;
gap: 8px;
margin-top: 13px;
color: var(--muted);
font-size: 11px;
cursor: pointer;
}
.checkbox input {
accent-color: #48cde7;
}
#metrics {
bottom: 20px;
left: 20px;
width: 310px;
padding: 16px;
}
.status-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 13px;
}
.status-row strong {
font-size: 13px;
letter-spacing: 0.02em;
}
#statusBadge {
padding: 5px 9px;
border: 1px solid currentColor;
border-radius: 999px;
color: var(--green);
background: rgba(85, 239, 189, 0.08);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.11em;
}
.metric {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
padding: 7px 0;
border-top: 1px solid rgba(126, 196, 255, 0.09);
color: var(--muted);
font-size: 11px;
}
.metric b {
color: var(--text);
font-size: 12px;
font-variant-numeric: tabular-nums;
}
.formula {
margin: 12px 0 0;
color: #7590a8;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
line-height: 1.55;
}
.legend {
position: fixed;
right: 22px;
bottom: 22px;
z-index: 5;
display: flex;
flex-wrap: wrap;
gap: 15px;
justify-content: flex-end;
max-width: 460px;
color: var(--muted);
font-size: 10px;
pointer-events: none;
}
.legend span {
display: flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 18px;
height: 3px;
border-radius: 99px;
background: var(--amber);
box-shadow: 0 0 8px currentColor;
}
.swatch.outgoing {
background: var(--cyan);
}
.swatch.edge {
background: var(--green);
}
.tag {
position: fixed;
z-index: 4;
padding: 5px 8px;
border: 1px solid rgba(126, 196, 255, 0.18);
border-radius: 7px;
background: rgba(6, 17, 31, 0.78);
color: #dcecff;
font-size: 10px;
font-weight: 650;
letter-spacing: 0.025em;
pointer-events: none;
transform: translate(-50%, -100%);
white-space: nowrap;
backdrop-filter: blur(6px);
}
.tag::after {
position: absolute;
top: 100%;
left: 50%;
width: 1px;
height: 11px;
background: rgba(126, 196, 255, 0.35);
content: "";
}
.tag.amber {
color: #ffd09a;
}
.tag.cyan {
color: #9ef3ff;
}
.tag.green {
color: #94f8d6;
}
#loading {
position: fixed;
inset: 0;
z-index: 100;
display: grid;
place-items: center;
background: var(--bg);
color: var(--muted);
font-size: 12px;
letter-spacing: 0.12em;
text-transform: uppercase;
transition: opacity 0.35s;
}
#loading.hidden {
opacity: 0;
pointer-events: none;
}
@media (max-width: 760px) {
.brand {
top: 14px;
left: 14px;
max-width: calc(100vw - 28px);
}
.brand p {
display: none;
}
#controls {
top: auto;
right: 10px;
bottom: 10px;
width: min(300px, calc(100vw - 20px));
max-height: 47vh;
overflow: auto;
}
#metrics {
top: 90px;
bottom: auto;
left: 10px;
width: min(260px, calc(100vw - 20px));
}
.legend {
display: none;
}
}
</style>
</head>
<body>
<div id="viewport"></div>
<div id="loading">Loading Three.js core…</div>
<header class="brand">
<div class="eyebrow">Geometric ray check</div>
<h1>Finite Mirror / Offset Aperture</h1>
<p>
Drag to orbit, scroll to zoom, and adjust the target to test whether the
reflected beam clears both the mirror boundary and aperture rim.
</p>
</header>
<section id="controls" class="panel">
<div class="panel-title">
Optical controls
<span>Live simulation</span>
</div>
<div class="control">
<div class="control-head">
<label for="offsetX">Aperture horizontal offset</label>
<output id="offsetXOut">+0.14</output>
</div>
<input id="offsetX" type="range" min="-0.45" max="0.45" step="0.005" value="0.14">
</div>
<div class="control">
<div class="control-head">
<label for="offsetY">Aperture vertical offset</label>
<output id="offsetYOut">+0.08</output>
</div>
<input id="offsetY" type="range" min="-0.45" max="0.45" step="0.005" value="0.08">
</div>
<div class="control">
<div class="control-head">
<label for="apertureRadius">Aperture radius</label>
<output id="apertureRadiusOut">0.30</output>
</div>
<input id="apertureRadius" type="range" min="0.16" max="0.45" step="0.005" value="0.30">
</div>
<div class="control">
<div class="control-head">
<label for="beamRadius">Beam radius</label>
<output id="beamRadiusOut">0.08</output>
</div>
<input id="beamRadius" type="range" min="0.03" max="0.18" step="0.005" value="0.08">
</div>
<div class="divider"></div>
<div class="button-row">
<button id="centerAim" type="button">Center aperture</button>
<button id="stressTest" class="warn" type="button">Force rim clip</button>
</div>
<label class="checkbox">
<input id="showClearance" type="checkbox" checked>
Show clearance geometry
</label>
</section>
<section id="metrics" class="panel">
<div class="status-row">
<strong id="statusTitle">Clearance accepted</strong>
<span id="statusBadge">PASS</span>
</div>
<div class="metric">
<span>Aperture rim clearance</span>
<b id="apClearance">+0.080</b>
</div>
<div class="metric">
<span>Mirror edge clearance</span>
<b id="mirrorClearance">+0.000</b>
</div>
<div class="metric">
<span>Beam-axis aim error</span>
<b id="aimError">0.161</b>
</div>
<div class="metric">
<span>Distance to mirror edge</span>
<b id="edgeDistance">0.000</b>
</div>
<p class="formula">
aperture clearance = aperture radius − beam radius − aim offset<br>
mirror clearance = distance(hit point, polygon edge) − beam radius
</p>
</section>
<div class="legend">
<span><i class="swatch"></i> Incident ray</span>
<span><i class="swatch outgoing"></i> Reflected ray</span>
<span><i class="swatch edge"></i> Mirror edge envelope</span>
</div>
<div id="labelSource" class="tag amber">Ray source</div>
<div id="labelMirror" class="tag green">Finite low-poly mirror</div>
<div id="labelAperture" class="tag cyan">Offset aperture</div>
<div id="labelIncident" class="tag amber">Incident</div>
<div id="labelReflected" class="tag cyan">Reflected</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const viewport = document.getElementById("viewport");
const loading = document.getElementById("loading");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.FogExp2(0x07111f, 0.026);
const camera = new THREE.PerspectiveCamera(
44,
innerWidth / innerHeight,
0.1,
100
);
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;
viewport.appendChild(renderer.domElement);
scene.add(new THREE.HemisphereLight(0xaedcff, 0x142036, 1.35));
const keyLight = new THREE.DirectionalLight(0xd8f2ff, 3.0);
keyLight.position.set(4.5, 6.0, 8.0);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4c91ff, 1.5);
rimLight.position.set(-5, -1, 4);
scene.add(rimLight);
const state = {
offsetX: 0.14,
offsetY: 0.08,
apertureRadius: 0.30,
beamRadius: 0.08,
showClearance: true
};
// -------------------------------------------------------------------------
// Background grid
// -------------------------------------------------------------------------
const grid = new THREE.GridHelper(24, 48, 0x1a4b70, 0x0b2136);
grid.rotation.x = Math.PI / 2;
grid.position.z = -1.35;
grid.material.transparent = true;
grid.material.opacity = 0.5;
grid.material.depthWrite = false;
scene.add(grid);
// -------------------------------------------------------------------------
// Finite low-poly mirror
// Local XY is the mirror plane; local +Z is the reflecting normal.
// -------------------------------------------------------------------------
const mirror = new THREE.Group();
mirror.rotation.set(-0.10, 0.14, -0.10);
scene.add(mirror);
const polygon = [
new THREE.Vector2(-1.95, -1.05),
new THREE.Vector2(-0.90, -1.20),
new THREE.Vector2( 0.30, -1.34),
new THREE.Vector2( 1.48, -0.92),
new THREE.Vector2( 1.72, 0.28),
new THREE.Vector2( 1.08, 1.12),
new THREE.Vector2(-0.38, 1.38),
new THREE.Vector2(-1.45, 1.00)
];
const mirrorShape = new THREE.Shape();
mirrorShape.moveTo(polygon[0].x, polygon[0].y);
for (let i = 1; i < polygon.length; i++) {
mirrorShape.lineTo(polygon[i].x, polygon[i].y);
}
mirrorShape.closePath();
const mirrorBodyGeometry = new THREE.ExtrudeGeometry(mirrorShape, {
depth: 0.10,
bevelEnabled: true,
bevelThickness: 0.018,
bevelSize: 0.025,
bevelSegments: 1,
steps: 1
});
const mirrorBody = new THREE.Mesh(
mirrorBodyGeometry,
new THREE.MeshStandardMaterial({
color: 0x153c5a,
metalness: 0.58,
roughness: 0.23,
emissive: 0x061421,
emissiveIntensity: 0.32
})
);
mirrorBody.position.z = -0.10;
mirror.add(mirrorBody);
// Individually shaded facets give the mirror a low-poly appearance.
const facetPalette = [
0x5aa6c9, 0x4388b3, 0x72b7d5, 0x3979a7,
0x69aacb, 0x4b94be, 0x7abdd7, 0x438eb7
];
for (let i = 0; i < polygon.length; i++) {
const a = polygon[i];
const b = polygon[(i + 1) % polygon.length];
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute([
0, 0, 0.014,
a.x, a.y, 0.014,
b.x, b.y, 0.014
], 3)
);
geometry.computeVertexNormals();
const facet = new THREE.Mesh(
geometry,
new THREE.MeshStandardMaterial({
color: facetPalette[i],
emissive: 0x0b2e46,
emissiveIntensity: 0.25,
metalness: 0.52,
roughness: 0.26,
side: THREE.DoubleSide
})
);
mirror.add(facet);
}
// Cylindrical border remains readable even though WebGL line width is limited.
const edgeMaterial = new THREE.MeshStandardMaterial({
color: 0x9cecff,
emissive: 0x1b7795,
emissiveIntensity: 1.25,
metalness: 0.3,
roughness: 0.28
});
const yAxis = new THREE.Vector3(0, 1, 0);
function addCylinderBetween(parent, a, b, radius, material) {
const direction = new THREE.Vector3().subVectors(b, a);
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radius, radius, direction.length(), 10),
material
);
mesh.position.copy(a).add(b).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(yAxis, direction.normalize());
parent.add(mesh);
return mesh;
}
for (let i = 0; i < polygon.length; i++) {
const a = polygon[i];
const b = polygon[(i + 1) % polygon.length];
addCylinderBetween(
mirror,
new THREE.Vector3(a.x, a.y, 0.035),
new THREE.Vector3(b.x, b.y, 0.035),
0.032,
edgeMaterial
);
}
// Reflection point in mirror-local coordinates.
const hitLocal = new THREE.Vector2(0.10, 0.05);
const hitMarker = new THREE.Mesh(
new THREE.RingGeometry(0.09, 0.125, 32),
new THREE.MeshBasicMaterial({
color: 0xe8fbff,
side: THREE.DoubleSide
})
);
hitMarker.position.set(hitLocal.x, hitLocal.y, 0.055);
mirror.add(hitMarker);
// -------------------------------------------------------------------------
// Reflection geometry
// -------------------------------------------------------------------------
mirror.updateMatrixWorld(true);
const hitPoint = mirror.localToWorld(
new THREE.Vector3(hitLocal.x, hitLocal.y, 0)
);
const mirrorNormal = new THREE.Vector3(0, 0, 1)
.applyQuaternion(mirror.quaternion)
.normalize();
// Incident direction points toward the mirror surface.
const incidentDirectionLocal = new THREE.Vector3(-0.78, 0.24, -0.56).normalize();
const incidentDirection = incidentDirectionLocal
.clone()
.applyQuaternion(mirror.quaternion)
.normalize();
// Reflection about the mirror plane:
// r = d - 2(d dot n)n
const reflectedDirection = incidentDirection
.clone()
.addScaledVector(
mirrorNormal,
-2 * incidentDirection.dot(mirrorNormal)
)
.normalize();
const sourcePosition = hitPoint
.clone()
.addScaledVector(incidentDirection, -3.10);
// The unshifted reflected beam intersects the target plane here.
const idealTargetPoint = hitPoint
.clone()
.addScaledVector(reflectedDirection, 3.25);
// -------------------------------------------------------------------------
// Source marker
// -------------------------------------------------------------------------
const sourceCore = new THREE.Mesh(
new THREE.SphereGeometry(0.12, 24, 16),
new THREE.MeshStandardMaterial({
color: 0xffbd72,
emissive: 0xff7b22,
emissiveIntensity: 3.0,
roughness: 0.22
})
);
sourceCore.position.copy(sourcePosition);
scene.add(sourceCore);
const sourceHalo = new THREE.Mesh(
new THREE.SphereGeometry(0.205, 16, 12),
new THREE.MeshBasicMaterial({
color: 0xffa14d,
wireframe: true,
transparent: true,
opacity: 0.62
})
);
sourceHalo.position.copy(sourcePosition);
scene.add(sourceHalo);
const sourceLight = new THREE.PointLight(0xff8b3d, 18, 7, 2);
sourceLight.position.copy(sourcePosition);
scene.add(sourceLight);
// -------------------------------------------------------------------------
// Target plane and offset aperture
// -------------------------------------------------------------------------
const targetFixed = new THREE.Group();
targetFixed.position.copy(idealTargetPoint);
targetFixed.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 0, 1),
reflectedDirection
);
scene.add(targetFixed);
let apertureVisual = null;
let apertureRingMaterial = null;
let aperturePanelMaterial = null;
function disposeGroup(group) {
group.traverse((object) => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
const materials = Array.isArray(object.material)
? object.material
: [object.material];
materials.forEach((material) => material.dispose());
}
});
}
function rebuildAperture() {
if (apertureVisual) {
targetFixed.remove(apertureVisual);
disposeGroup(apertureVisual);
}
apertureVisual = new THREE.Group();
apertureVisual.position.set(state.offsetX, state.offsetY, 0);
targetFixed.add(apertureVisual);
const radius = state.apertureRadius;
const halfSize = 0.82;
const panelShape = new THREE.Shape();
panelShape.moveTo(-halfSize, -halfSize);
panelShape.lineTo(halfSize, -halfSize);
panelShape.lineTo(halfSize, halfSize);
panelShape.lineTo(-halfSize, halfSize);
panelShape.closePath();
const hole = new THREE.Path();
hole.absarc(0, 0, radius, 0, Math.PI * 2, true);
panelShape.holes.push(hole);
const panelGeometry = new THREE.ExtrudeGeometry(panelShape, {
depth: 0.07,
bevelEnabled: false,
steps: 1
});
aperturePanelMaterial = new THREE.MeshStandardMaterial({
color: 0x263a4e,
emissive: 0x07131e,
emissiveIntensity: 0.35,
metalness: 0.48,
roughness: 0.38,
side: THREE.DoubleSide
});
const panel = new THREE.Mesh(panelGeometry, aperturePanelMaterial);
panel.position.z = -0.035;
apertureVisual.add(panel);
apertureRingMaterial = new THREE.MeshBasicMaterial({
color: 0x55efbd,
side: THREE.DoubleSide,
transparent: true,
opacity: 0.95
});
const ring = new THREE.Mesh(
new THREE.RingGeometry(radius, radius + 0.038, 64),
apertureRingMaterial
);
ring.position.z = 0.055;
apertureVisual.add(ring);
// Four external reticle ticks.
const tickVertices = [];
const tickInner = radius + 0.065;
const tickOuter = radius + 0.145;
for (let i = 0; i < 4; i++) {
const angle = i * Math.PI / 2;
const ca = Math.cos(angle);
const sa = Math.sin(angle);
tickVertices.push(
ca * tickInner, sa * tickInner, 0.075,
ca * tickOuter, sa * tickOuter, 0.075
);
}
const tickGeometry = new THREE.BufferGeometry();
tickGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(tickVertices, 3)
);
const ticks = new THREE.LineSegments(
tickGeometry,
new THREE.LineBasicMaterial({ color: 0xb9edff })
);
apertureVisual.add(ticks);
}
rebuildAperture();
// Ideal reflected beam-axis crossing point.
const idealAimDot = new THREE.Mesh(
new THREE.CircleGeometry(0.026, 20),
new THREE.MeshBasicMaterial({
color: 0xd9fbff,
side: THREE.DoubleSide
})
);
idealAimDot.position.z = 0.09;
targetFixed.add(idealAimDot);
const aimLineGeometry = new THREE.BufferGeometry();
aimLineGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(new Float32Array(6), 3)
);
const aimLineMaterial = new THREE.LineBasicMaterial({
color: 0x55efbd,
transparent: true,
opacity: 0.85
});
const aimLine = new THREE.Line(aimLineGeometry, aimLineMaterial);
targetFixed.add(aimLine);
// -------------------------------------------------------------------------
// Ray geometry
// -------------------------------------------------------------------------
const unitBeamGeometry = new THREE.CylinderGeometry(1, 1, 1, 14, 1, true);
const incidentBeamMaterial = new THREE.MeshBasicMaterial({
color: 0xffa14d,
transparent: true,
opacity: 0.26,
depthWrite: false
});
const reflectedBeamMaterial = new THREE.MeshBasicMaterial({
color: 0x62e8ff,
transparent: true,
opacity: 0.28,
depthWrite: false
});
const incidentBeam = new THREE.Mesh(
unitBeamGeometry,
incidentBeamMaterial
);
scene.add(incidentBeam);
const reflectedBeam = new THREE.Mesh(
unitBeamGeometry,
reflectedBeamMaterial
);
scene.add(reflectedBeam);
function setBeam(mesh, a, b, radius) {
const direction = new THREE.Vector3().subVectors(b, a);
const length = direction.length();
mesh.position.copy(a).add(b).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(yAxis, direction.normalize());
mesh.scale.set(radius, length, radius);
}
const incidentLineGeometry = new THREE.BufferGeometry().setFromPoints([
sourcePosition,
hitPoint
]);
const incidentLine = new THREE.Line(
incidentLineGeometry,
new THREE.LineBasicMaterial({
color: 0xffc281,
transparent: true,
opacity: 0.95
})
);
scene.add(incidentLine);
const reflectedEnd = idealTargetPoint
.clone()
.addScaledVector(reflectedDirection, 0.28);
const reflectedLineGeometry = new THREE.BufferGeometry().setFromPoints([
hitPoint,
reflectedEnd
]);
const reflectedLine = new THREE.Line(
reflectedLineGeometry,
new THREE.LineBasicMaterial({
color: 0xa7f5ff,
transparent: true,
opacity: 0.95
})
);
scene.add(reflectedLine);
// Surface normal at the reflection point.
const normalGeometry = new THREE.BufferGeometry().setFromPoints([
hitPoint.clone().addScaledVector(mirrorNormal, -0.58),
hitPoint.clone().addScaledVector(mirrorNormal, 0.58)
]);
const normalLine = new THREE.Line(
normalGeometry,
new THREE.LineDashedMaterial({
color: 0xe7f7ff,
dashSize: 0.075,
gapSize: 0.045,
transparent: true,
opacity: 0.65
})
);
normalLine.computeLineDistances();
scene.add(normalLine);
// -------------------------------------------------------------------------
// Mirror-edge distance and clearance envelope
// -------------------------------------------------------------------------
function closestPointOnSegment(point, a, b) {
const ab = new THREE.Vector2().subVectors(b, a);
const ap = new THREE.Vector2().subVectors(point, a);
const lengthSquared = ab.lengthSq();
const t = lengthSquared > 0
? THREE.MathUtils.clamp(ap.dot(ab) / lengthSquared, 0, 1)
: 0;
const closest = a.clone().addScaledVector(ab, t);
const distance = point.distanceTo(closest);
return { point: closest, distance, t };
}
function mirrorEdgeInfo(point) {
let closest = null;
for (let i = 0; i < polygon.length; i++) {
const a = polygon[i];
const b = polygon[(i + 1) % polygon.length];
const candidate = closestPointOnSegment(point, a, b);
if (!closest || candidate.distance < closest.distance) {
closest = candidate;
}
}
return closest;
}
const edgeInfo = mirrorEdgeInfo(hitLocal);
const edgeEnvelopeGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(hitLocal.x, hitLocal.y, 0.075),
new THREE.Vector3(edgeInfo.point.x, edgeInfo.point.y, 0.075)
]);
const edgeEnvelope = new THREE.Line(
edgeEnvelopeGeometry,
new THREE.LineBasicMaterial({
color: 0x55efbd,
transparent: true,
opacity: 0.75
})
);
mirror.add(edgeEnvelope);
// -------------------------------------------------------------------------
// Live clearance calculation
// -------------------------------------------------------------------------
const statusBadge = document.getElementById("statusBadge");
const statusTitle = document.getElementById("statusTitle");
const apClearanceElement = document.getElementById("apClearance");
const mirrorClearanceElement = document.getElementById("mirrorClearance");
const aimErrorElement = document.getElementById("aimError");
const edgeDistanceElement = document.getElementById("edgeDistance");
function signed(value, digits = 3) {
const rounded = Math.abs(value) < 1e-8 ? 0 : value;
return `${rounded >= 0 ? "+" : ""}${rounded.toFixed(digits)}`;
}
function updateVisuals() {
const offsetDistance = Math.hypot(state.offsetX, state.offsetY);
const apertureClearance =
state.apertureRadius - state.beamRadius - offsetDistance;
const mirrorClearance = edgeInfo.distance - state.beamRadius;
const passes = apertureClearance >= 0 && mirrorClearance >= 0;
apertureVisual.position.set(state.offsetX, state.offsetY, 0);
const aimPositions = aimLineGeometry.attributes.position;
aimPositions.setXYZ(0, 0, 0, 0.10);
aimPositions.setXYZ(1, state.offsetX, state.offsetY, 0.10);
aimPositions.needsUpdate = true;
aimLineGeometry.computeBoundingSphere();
setBeam(
incidentBeam,
sourcePosition,
hitPoint,
state.beamRadius
);
setBeam(
reflectedBeam,
hitPoint,
reflectedEnd,
state.beamRadius
);
const statusColor = passes ? 0x55efbd : 0xff6474;
apertureRingMaterial.color.setHex(statusColor);
aimLineMaterial.color.setHex(statusColor);
reflectedBeamMaterial.color.setHex(passes ? 0x62e8ff : 0xffa15f);
reflectedLine.material.color.setHex(passes ? 0xa7f5ff : 0xffc28c);
aperturePanelMaterial.emissive.setHex(passes ? 0x07131e : 0x2b0b13);
aperturePanelMaterial.emissiveIntensity = passes ? 0.35 : 0.65;
edgeEnvelope.visible = state.showClearance;
aimLine.visible = state.showClearance && offsetDistance > 0.005;
statusBadge.textContent = passes ? "PASS" : "CLIP";
statusBadge.style.color = passes ? "var(--green)" : "var(--red)";
statusBadge.style.background = passes
? "rgba(85, 239, 189, 0.08)"
: "rgba(255, 100, 116, 0.08)";
statusTitle.textContent = passes
? "Clearance accepted"
: "Beam intersects an edge";
apClearanceElement.textContent = signed(apertureClearance);
apClearanceElement.style.color = apertureClearance >= 0
? "var(--green)"
: "var(--red)";
mirrorClearanceElement.textContent = signed(mirrorClearance);
mirrorClearanceElement.style.color = mirrorClearance >= 0
? "var(--green)"
: "var(--red)";
aimErrorElement.textContent = offsetDistance.toFixed(3);
edgeDistanceElement.textContent = edgeInfo.distance.toFixed(3);
document.getElementById("offsetXOut").textContent = signed(state.offsetX, 2);
document.getElementById("offsetYOut").textContent = signed(state.offsetY, 2);
document.getElementById("apertureRadiusOut").textContent =
state.apertureRadius.toFixed(2);
document.getElementById("beamRadiusOut").textContent =
state.beamRadius.toFixed(2);
}
// -------------------------------------------------------------------------
// UI bindings
// -------------------------------------------------------------------------
function bindRange(id, key, onChange = null) {
const input = document.getElementById(id);
input.addEventListener("input", () => {
state[key] = Number(input.value);
if (onChange) onChange();
updateVisuals();
});
}
bindRange("offsetX", "offsetX");
bindRange("offsetY", "offsetY");
bindRange("apertureRadius", "apertureRadius", rebuildAperture);
bindRange("beamRadius", "beamRadius");
document.getElementById("centerAim").addEventListener("click", () => {
state.offsetX = 0;
state.offsetY = 0;
document.getElementById("offsetX").value = "0";
document.getElementById("offsetY").value = "0";
updateVisuals();
});
document.getElementById("stressTest").addEventListener("click", () => {
const requiredOffset = Math.max(
0,
state.apertureRadius - state.beamRadius + 0.035
);
state.offsetX = Math.min(requiredOffset, 0.45);
state.offsetY = 0;
document.getElementById("offsetX").value = String(state.offsetX);
document.getElementById("offsetY").value = "0";
updateVisuals();
});
document.getElementById("showClearance").addEventListener("change", (event) => {
state.showClearance = event.target.checked;
updateVisuals();
});
// -------------------------------------------------------------------------
// Manual camera controls: no addons are loaded.
// -------------------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, 0, 0.55);
let cameraRadius = 9.6;
let cameraAzimuth = 0.57;
let cameraPolar = 1.02;
function applyCamera() {
const sinPolar = Math.sin(cameraPolar);
camera.position.set(
cameraTarget.x + cameraRadius * sinPolar * Math.sin(cameraAzimuth),
cameraTarget.y + cameraRadius * Math.cos(cameraPolar),
cameraTarget.z + cameraRadius * sinPolar * Math.cos(cameraAzimuth)
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraRadius = 9.6;
cameraAzimuth = 0.57;
cameraPolar = 1.02;
applyCamera();
}
let dragging = false;
let previousX = 0;
let previousY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
previousX = event.clientX;
previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - previousX;
const deltaY = event.clientY - previousY;
cameraAzimuth -= deltaX * 0.006;
cameraPolar = THREE.MathUtils.clamp(
cameraPolar + deltaY * 0.006,
0.22,
Math.PI - 0.22
);
previousX = event.clientX;
previousY = event.clientY;
applyCamera();
});
function endDrag(event) {
dragging = false;
if (event.pointerId !== undefined && renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
5.0,
18.0
);
applyCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
addEventListener("keydown", (event) => {
const step = 0.08;
if (event.key === "ArrowLeft") cameraAzimuth += step;
else if (event.key === "ArrowRight") cameraAzimuth -= step;
else if (event.key === "ArrowUp") cameraPolar -= step;
else if (event.key === "ArrowDown") cameraPolar += step;
else if (event.key === "+" || event.key === "=") cameraRadius -= 0.5;
else if (event.key === "-") cameraRadius += 0.5;
else if (event.key.toLowerCase() === "r") resetCamera;
else return;
cameraPolar = THREE.MathUtils.clamp(cameraPolar, 0.22, Math.PI - 0.22);
cameraRadius = THREE.MathUtils.clamp(cameraRadius, 5, 18);
applyCamera();
event.preventDefault();
});
// -------------------------------------------------------------------------
// Projected HTML labels
// -------------------------------------------------------------------------
const labels = [
{
element: document.getElementById("labelSource"),
position: sourcePosition.clone().add(new THREE.Vector3(0, 0.33, 0))
},
{
element: document.getElementById("labelMirror"),
position: mirror.localToWorld(new THREE.Vector3(-0.1, -1.55, 0.08))
},
{
element: document.getElementById("labelAperture"),
position: new THREE.Vector3()
},
{
element: document.getElementById("labelIncident"),
position: sourcePosition.clone()
.addScaledVector(incidentDirection, 1.50)
.add(new THREE.Vector3(0, 0.15, 0))
},
{
element: document.getElementById("labelReflected"),
position: hitPoint.clone()
.addScaledVector(reflectedDirection, 1.45)
.add(new THREE.Vector3(0, 0.15, 0))
}
];
function updateLabels() {
const apertureWorld = new THREE.Vector3();
apertureVisual.getWorldPosition(apertureWorld);
labels[2].position.copy(apertureWorld).add(new THREE.Vector3(0, 0.47, 0));
for (const label of labels) {
const projected = label.position.clone().project(camera);
const visible = projected.z > -1 && projected.z < 1;
label.element.style.display = visible ? "block" : "none";
if (visible) {
label.element.style.left =
`${(projected.x * 0.5 + 0.5) * innerWidth}px`;
label.element.style.top =
`${(-projected.y * 0.5 + 0.5) * innerHeight}px`;
}
}
}
// -------------------------------------------------------------------------
// Resize and animation
// -------------------------------------------------------------------------
addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const time = clock.getElapsedTime();
const pulse = 1 + Math.sin(time * 3.2) * 0.075;
sourceHalo.scale.setScalar(pulse);
idealAimDot.material.opacity = 0.78 + Math.sin(time * 4.0) * 0.18;
updateLabels();
renderer.render(scene, camera);
}
applyCamera();
updateVisuals();
animate();
requestAnimationFrame(() => {
loading.classList.add("hidden");
setTimeout(() => loading.remove(), 450);
});
</script>
</body>
</html>
```