Prompt specification
Build or customize the Three.js 3D scene "Lens equation exploration rail" 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: Lens equation exploration rail
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/lens-equation-exploration-rail-x1560
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing image formation by a thin lens. Allow moving the object and changing focal length; compute signed image distance consistently, identify magnification, and handle the focal-position limit without numerical failure. Low-poly.
Working Three.js Starter (lens-equation-exploration-rail-x1560):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Thin Lens — Image Formation</title>
<style>
:root {
color-scheme: dark;
--panel: rgba(9, 18, 34, 0.92);
--border: rgba(150, 190, 255, 0.18);
--text: #eaf3ff;
--muted: #9fb2cc;
--accent: #ffb454;
--cyan: #58d9ff;
--green: #70e0a8;
--red: #ff7f91;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #07111f;
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#scene {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.panel {
position: fixed;
z-index: 10;
top: 18px;
right: 18px;
width: min(360px, calc(100vw - 36px));
max-height: calc(100vh - 36px);
overflow: auto;
padding: 18px;
border: 1px solid var(--border);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.38);
backdrop-filter: blur(16px);
}
h1 {
margin: 0;
font-size: 22px;
letter-spacing: -0.02em;
}
.subtitle {
margin: 5px 0 16px;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.equation {
margin: 12px 0;
padding: 10px 12px;
border: 1px solid var(--border);
border-radius: 10px;
background: rgba(255, 255, 255, 0.035);
font-family: Georgia, "Times New Roman", serif;
font-size: 18px;
text-align: center;
}
.control {
margin-top: 16px;
}
.control label,
.control-title {
display: flex;
justify-content: space-between;
gap: 12px;
align-items: baseline;
margin-bottom: 8px;
font-size: 13px;
font-weight: 650;
}
output {
color: var(--accent);
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
accent-color: var(--accent);
cursor: pointer;
}
.range-ends {
display: flex;
justify-content: space-between;
margin-top: 2px;
color: var(--muted);
font-size: 10px;
}
.buttons {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 16px;
}
button {
border: 1px solid var(--border);
border-radius: 9px;
padding: 9px 11px;
background: rgba(255, 255, 255, 0.055);
color: var(--text);
font: inherit;
font-size: 12px;
cursor: pointer;
}
button:hover {
background: rgba(255, 255, 255, 0.1);
}
button.primary {
border-color: rgba(255, 180, 84, 0.42);
background: rgba(255, 180, 84, 0.13);
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 17px;
}
.metric {
min-height: 68px;
padding: 10px;
border: 1px solid var(--border);
border-radius: 10px;
background: rgba(255, 255, 255, 0.035);
}
.metric span {
display: block;
margin-bottom: 6px;
color: var(--muted);
font-size: 10px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric strong {
display: block;
font-size: 13px;
line-height: 1.35;
font-variant-numeric: tabular-nums;
}
.classification {
margin-top: 10px;
padding: 10px 11px;
border-left: 3px solid var(--cyan);
border-radius: 8px;
background: rgba(88, 217, 255, 0.08);
color: var(--cyan);
font-size: 13px;
font-weight: 700;
line-height: 1.4;
}
.classification.real {
border-color: var(--green);
background: rgba(112, 224, 168, 0.08);
color: var(--green);
}
.classification.virtual {
border-color: var(--cyan);
}
.classification.limit {
border-color: var(--red);
background: rgba(255, 127, 145, 0.08);
color: var(--red);
}
.note {
margin-top: 13px;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.check {
display: flex;
align-items: center;
gap: 8px;
margin-top: 13px;
color: var(--muted);
font-size: 12px;
}
.check input {
accent-color: var(--cyan);
}
.hint {
position: fixed;
z-index: 5;
left: 18px;
bottom: 18px;
max-width: min(570px, calc(100vw - 36px));
padding: 10px 13px;
border: 1px solid var(--border);
border-radius: 12px;
background: rgba(7, 17, 31, 0.78);
color: #c7d8ed;
font-size: 12px;
line-height: 1.45;
pointer-events: none;
backdrop-filter: blur(10px);
}
.legend {
display: inline-flex;
gap: 13px;
margin-top: 5px;
color: var(--muted);
}
.legend i {
display: inline-block;
width: 10px;
height: 10px;
margin-right: 5px;
border-radius: 2px;
vertical-align: -1px;
}
@media (max-width: 720px) {
.panel {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 48vh;
padding: 14px;
}
.hint {
top: 10px;
right: 10px;
bottom: auto;
left: 10px;
}
h1 {
font-size: 18px;
}
.subtitle {
margin-bottom: 9px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive 3D thin-lens diagram"></canvas>
<aside class="panel">
<h1>Thin-Lens Image Formation</h1>
<div class="subtitle">
Move the orange object, change the focal length, and inspect the signed
image distance and transverse magnification.
</div>
<div class="equation">1/f = 1/d<sub>o</sub> + 1/d<sub>i</sub></div>
<div class="control">
<label for="objectDistance">
<span>Object distance d<sub>o</sub></span>
<output id="objectDistanceValue"></output>
</label>
<input
id="objectDistance"
type="range"
min="25"
max="180"
step="1"
value="90"
>
<div class="range-ends">
<span>Near lens</span>
<span>Farther away</span>
</div>
</div>
<div class="control">
<label for="focalLength">
<span>Focal length f</span>
<output id="focalLengthValue"></output>
</label>
<input
id="focalLength"
type="range"
min="25"
max="100"
step="1"
value="60"
>
<div class="range-ends">
<span>Short focus</span>
<span>Long focus</span>
</div>
</div>
<div class="buttons">
<button id="focusLimit" class="primary" type="button">
Object at focal point
</button>
<button id="resetView" type="button">Reset view</button>
</div>
<div class="metrics" aria-live="polite">
<div class="metric">
<span>Object distance</span>
<strong id="objectDistanceMetric"></strong>
</div>
<div class="metric">
<span>Focal length</span>
<strong id="focalLengthMetric"></strong>
</div>
<div class="metric">
<span>Signed image distance</span>
<strong id="imageDistanceMetric"></strong>
</div>
<div class="metric">
<span>Magnification m = −d<sub>i</sub>/d<sub>o</sub></span>
<strong id="magnificationMetric"></strong>
</div>
</div>
<div id="classification" class="classification"></div>
<label class="check">
<input id="showRays" type="checkbox" checked>
Show construction rays
</label>
<div class="note">
Sign convention: d<sub>o</sub> > 0 for an object left of the lens.
d<sub>i</sub> > 0 means a real image to the right; d<sub>i</sub> < 0
means a virtual image to the left. Negative magnification is inverted;
positive magnification is upright.
</div>
<div class="note">
At d<sub>o</sub> = f there is no finite image plane: the emerging rays
are parallel, d<sub>i</sub> tends to infinity, and |m| tends to infinity.
The solver detects this case before division.
</div>
</aside>
<div class="hint">
Drag the <strong style="color:#ffb454">orange object</strong> along the
optical axis. Drag the background to orbit; use the mouse wheel to zoom.
<div class="legend">
<span><i style="background:#58d9ff"></i>Lens/image</span>
<span><i style="background:#ffd166"></i>Real rays</span>
<span><i style="background:#70e0a8"></i>Virtual back-projection</span>
</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Model and sign convention
//
// Lens is at x = 0. The object is at x = -d_o.
//
// 1/f = 1/d_o + 1/d_i
//
// d_i > 0: real image to the right of the lens.
// d_i < 0: virtual image to the left of the lens.
// m = -d_i/d_o.
//
// The focal-position case is checked before division, avoiding Infinity/NaN
// propagation into the scene geometry.
// -------------------------------------------------------------------------
const EPSILON = 1e-10;
function solveThinLens(distanceObject, focalLength) {
if (
!Number.isFinite(distanceObject) ||
!Number.isFinite(focalLength) ||
distanceObject <= 0 ||
focalLength <= 0
) {
return {
atLimit: false,
invalid: true,
di: NaN,
m: NaN
};
}
const denominator = 1 / focalLength - 1 / distanceObject;
// At d_o = f, the denominator is exactly zero in exact arithmetic.
// The tolerance also catches values indistinguishable from the limit
// after floating-point arithmetic.
if (Math.abs(denominator) < EPSILON) {
return {
atLimit: true,
invalid: false,
di: Infinity,
m: Infinity
};
}
const di = 1 / denominator;
const m = -di / distanceObject;
return {
atLimit: false,
invalid: !Number.isFinite(di) || !Number.isFinite(m),
di,
m
};
}
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 420, 760);
const camera = new THREE.OrthographicCamera(-100, 100, 100, -100, 0.1, 1200);
camera.position.set(0, 80, 300);
const hemisphere = new THREE.HemisphereLight(0xb8dcff, 0x162033, 2.2);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.0);
keyLight.position.set(-80, 150, 160);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -260;
keyLight.shadow.camera.right = 360;
keyLight.shadow.camera.top = 180;
keyLight.shadow.camera.bottom = -180;
keyLight.shadow.camera.far = 600;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x58d9ff, 1.7);
rimLight.position.set(140, 70, -120);
scene.add(rimLight);
const objectHeight = 26;
const rayRightLimit = 340;
const imageDisplayLimit = 360;
const state = {
distanceObject: 90,
focalLength: 60,
showRays: true,
solution: null
};
const orbit = {
target: new THREE.Vector3(-30, 0, 0),
yaw: 0.22,
pitch: 0.34,
distance: 310,
viewHeight: 180,
bounds: {
left: -220,
right: 340
}
};
// -------------------------------------------------------------------------
// Materials and low-poly geometry
// -------------------------------------------------------------------------
const flatMaterial = (color, options = {}) =>
new THREE.MeshStandardMaterial({
color,
flatShading: true,
roughness: 0.72,
metalness: 0.08,
...options
});
function createArrow(material) {
const group = new THREE.Group();
const shaft = new THREE.Mesh(
new THREE.CylinderGeometry(1.8, 2.3, 18, 6),
material
);
shaft.position.y = 9;
shaft.castShadow = true;
group.add(shaft);
const head = new THREE.Mesh(
new THREE.ConeGeometry(5, 8, 6),
material
);
head.position.y = 22;
head.castShadow = true;
group.add(head);
const base = new THREE.Mesh(
new THREE.CylinderGeometry(5, 6, 2, 8),
material
);
base.position.y = 1;
base.castShadow = true;
group.add(base);
return group;
}
function createLabel(text, color = "#dcecff") {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 128;
const context = labelCanvas.getContext("2d");
context.clearRect(0, 0, labelCanvas.width, labelCanvas.height);
context.fillStyle = "rgba(5, 14, 27, 0.78)";
context.fillRect(0, 0, labelCanvas.width, labelCanvas.height);
context.strokeStyle = color;
context.lineWidth = 5;
context.strokeRect(3, 3, labelCanvas.width - 6, labelCanvas.height - 6);
context.fillStyle = color;
context.font = "bold 46px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, labelCanvas.width / 2, labelCanvas.height / 2 + 2);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(25, 6.25, 1);
sprite.renderOrder = 20;
return sprite;
}
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(760, 220),
flatMaterial(0x0c192a, { roughness: 0.95 })
);
floor.rotation.x = -Math.PI / 2;
floor.position.set(55, -18, 0);
floor.receiveShadow = true;
scene.add(floor);
const opticalAxis = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-230, 0, 0),
new THREE.Vector3(350, 0, 0)
]),
new THREE.LineDashedMaterial({
color: 0x8fa8c7,
dashSize: 3,
gapSize: 2,
transparent: true,
opacity: 0.62
})
);
opticalAxis.computeLineDistances();
scene.add(opticalAxis);
const tickPoints = [];
for (let x = -220; x <= 340; x += 20) {
tickPoints.push(
new THREE.Vector3(x, -1.4, 0),
new THREE.Vector3(x, 1.4, 0)
);
}
const ticks = new THREE.LineSegments(
new THREE.BufferGeometry().setFromPoints(tickPoints),
new THREE.LineBasicMaterial({
color: 0x66809f,
transparent: true,
opacity: 0.48
})
);
scene.add(ticks);
// Lens: a thin, faceted disk in the y-z plane.
const lensGroup = new THREE.Group();
const lensMaterial = flatMaterial(0x58d9ff, {
transparent: true,
opacity: 0.34,
roughness: 0.18,
metalness: 0.12,
depthWrite: false
});
const lens = new THREE.Mesh(
new THREE.CylinderGeometry(13, 13, 1.6, 12),
lensMaterial
);
lens.rotation.z = Math.PI / 2;
lens.castShadow = true;
lensGroup.add(lens);
const lensRing = new THREE.Mesh(
new THREE.TorusGeometry(13.2, 0.72, 6, 16),
flatMaterial(0x8be8ff, {
emissive: 0x123a4d,
emissiveIntensity: 0.6
})
);
lensRing.rotation.y = Math.PI / 2;
lensGroup.add(lensRing);
scene.add(lensGroup);
const lensLabel = createLabel("THIN LENS", "#8be8ff");
lensLabel.position.set(0, 21, 0);
lensLabel.scale.set(27, 6.75, 1);
scene.add(lensLabel);
const focalMarker = new THREE.Mesh(
new THREE.OctahedronGeometry(2.3, 0),
flatMaterial(0xffd166, {
emissive: 0x6b4a00,
emissiveIntensity: 0.55
})
);
scene.add(focalMarker);
const focalLabel = createLabel("F′", "#ffd166");
focalLabel.scale.set(9, 4.5, 1);
scene.add(focalLabel);
const objectMaterial = flatMaterial(0xffa938, {
emissive: 0x4a1f00,
emissiveIntensity: 0.35
});
const objectGroup = createArrow(objectMaterial);
scene.add(objectGroup);
const objectLabel = createLabel("OBJECT", "#ffb454");
objectLabel.scale.set(23, 5.75, 1);
scene.add(objectLabel);
const imageMaterial = flatMaterial(0x69e3ff, {
transparent: true,
opacity: 0.82,
emissive: 0x073847,
emissiveIntensity: 0.45,
depthWrite: false
});
const imageGroup = createArrow(imageMaterial);
scene.add(imageGroup);
const imagePlaneMaterial = new THREE.MeshBasicMaterial({
color: 0x58d9ff,
transparent: true,
opacity: 0.11,
side: THREE.DoubleSide,
depthWrite: false
});
const imagePlane = new THREE.Mesh(
new THREE.PlaneGeometry(1, 1),
imagePlaneMaterial
);
imagePlane.rotation.y = Math.PI / 2;
scene.add(imagePlane);
const imageLabel = createLabel("IMAGE", "#69e3ff");
imageLabel.scale.set(20, 5, 1);
scene.add(imageLabel);
const offRightLabel = createLabel("IMAGE OFF-SCREEN →", "#69e3ff");
offRightLabel.scale.set(37, 9.25, 1);
offRightLabel.visible = false;
scene.add(offRightLabel);
const offLeftLabel = createLabel("← IMAGE OFF-SCREEN", "#69e3ff");
offLeftLabel.scale.set(37, 9.25, 1);
offLeftLabel.visible = false;
scene.add(offLeftLabel);
// -------------------------------------------------------------------------
// Construction rays
// -------------------------------------------------------------------------
function createLine(color, dashed = false, opacity = 1) {
const material = dashed
? new THREE.LineDashedMaterial({
color,
dashSize: 5,
gapSize: 4,
transparent: true,
opacity
})
: new THREE.LineBasicMaterial({
color,
transparent: true,
opacity
});
const line = new THREE.Line(new THREE.BufferGeometry(), material);
scene.add(line);
return line;
}
const incidentParallel = createLine(0xffd166);
const incidentCentral = createLine(0xffb454);
const outgoingParallel = createLine(0xffd166);
const outgoingCentral = createLine(0xffb454);
const virtualParallel = createLine(0x70e0a8, true, 0.95);
const virtualCentral = createLine(0x70e0a8, true, 0.95);
const allRayLines = [
incidentParallel,
incidentCentral,
outgoingParallel,
outgoingCentral,
virtualParallel,
virtualCentral
];
function setLine(line, points, dashed = false) {
line.geometry.dispose();
line.geometry = new THREE.BufferGeometry().setFromPoints(points);
if (dashed) {
line.computeLineDistances();
}
}
function clearRay(line) {
line.geometry.dispose();
line.geometry = new THREE.BufferGeometry();
}
// -------------------------------------------------------------------------
// Scene updates
// -------------------------------------------------------------------------
function updateRays(solution) {
const doValue = state.distanceObject;
const fValue = state.focalLength;
const objectTip = new THREE.Vector3(
-doValue,
objectHeight,
0.5
);
const lensCenter = new THREE.Vector3(0, 0, 0.5);
const lensParallel = new THREE.Vector3(0, objectHeight, 0.5);
setLine(incidentParallel, [objectTip, lensParallel]);
setLine(incidentCentral, [objectTip, lensCenter]);
const rayEnd = rayRightLimit;
if (solution.atLimit) {
// At the focal point the two outgoing rays are parallel.
const centralSlope = -objectHeight / doValue;
const parallelSlope = -objectHeight / fValue;
setLine(outgoingCentral, [
lensCenter,
new THREE.Vector3(
rayEnd,
centralSlope * rayEnd,
0.5
)
]);
setLine(outgoingParallel, [
lensParallel,
new THREE.Vector3(
rayEnd,
objectHeight + parallelSlope * rayEnd,
0.5
)
]);
clearRay(virtualParallel);
clearRay(virtualCentral);
return;
}
const di = solution.di;
const centralSlope = -objectHeight / doValue;
const parallelSlope = -objectHeight / fValue;
if (di > 0) {
// Real image: the outgoing rays physically meet at the image plane.
const endX = Math.min(di, rayEnd);
setLine(outgoingCentral, [
lensCenter,
new THREE.Vector3(endX, centralSlope * endX, 0.5)
]);
setLine(outgoingParallel, [
lensParallel,
new THREE.Vector3(
endX,
objectHeight + parallelSlope * endX,
0.5
)
]);
clearRay(virtualParallel);
clearRay(virtualCentral);
} else {
// Virtual image: outgoing rays diverge to the right. Dashed segments
// are their backward extensions to the virtual image on the left.
setLine(outgoingCentral, [
lensCenter,
new THREE.Vector3(
rayEnd,
centralSlope * rayEnd,
0.5
)
]);
setLine(outgoingParallel, [
lensParallel,
new THREE.Vector3(
rayEnd,
objectHeight + parallelSlope * rayEnd,
0.5
)
]);
const extensionX = Math.max(di, -rayRightLimit);
setLine(
virtualCentral,
[
lensCenter,
new THREE.Vector3(
extensionX,
centralSlope * extensionX,
0.5
)
],
true
);
setLine(
virtualParallel,
[
lensParallel,
new THREE.Vector3(
extensionX,
objectHeight + parallelSlope * extensionX,
0.5
)
],
true
);
}
}
function updateScene() {
const solution = solveThinLens(
state.distanceObject,
state.focalLength
);
state.solution = solution;
objectGroup.position.x = -state.distanceObject;
objectLabel.position.set(-state.distanceObject, 36, 0);
focalMarker.position.set(state.focalLength, 0, 0);
focalLabel.position.set(state.focalLength, 8, 0);
const finiteUsableImage =
!solution.atLimit &&
!solution.invalid &&
Math.abs(solution.di) <= imageDisplayLimit;
imageGroup.visible = finiteUsableImage;
imagePlane.visible = finiteUsableImage;
imageLabel.visible = finiteUsableImage;
if (finiteUsableImage) {
const di = solution.di;
const m = solution.m;
const imageY = m * objectHeight;
imageGroup.position.set(di, 0, 0);
imageGroup.scale.set(m, m, m);
const planeHeight = Math.max(Math.abs(imageY), 30);
imagePlane.position.set(di, imageY / 2, 0);
imagePlane.scale.set(44, planeHeight, 1);
imageLabel.position.set(
di,
imageY + (m < 0 ? -9 : 9),
0
);
}
updateRays(solution);
for (const line of allRayLines) {
line.visible = state.showRays;
}
updateReadouts(solution);
}
function signedDistance(value) {
const sign = value > 0 ? "+" : "−";
return `${sign}${Math.abs(value).toFixed(1)} cm`;
}
function updateReadouts(solution) {
const doValue = state.distanceObject;
const fValue = state.focalLength;
document.querySelector("#objectDistanceValue").textContent =
`${doValue.toFixed(1)} cm`;
document.querySelector("#focalLengthValue").textContent =
`${fValue.toFixed(1)} cm`;
document.querySelector("#objectDistanceMetric").textContent =
`${doValue.toFixed(1)} cm, left of lens`;
document.querySelector("#focalLengthMetric").textContent =
`${fValue.toFixed(1)} cm, converging`;
const classification =
document.querySelector("#classification");
classification.className = "classification";
if (solution.atLimit) {
document.querySelector("#imageDistanceMetric").textContent =
"No finite value; ∞ limit";
document.querySelector("#magnificationMetric").textContent =
"Unbounded; |m| → ∞";
classification.classList.add("limit");
classification.textContent =
"At the focal point — no finite image; outgoing rays are parallel.";
} else if (solution.invalid) {
document.querySelector("#imageDistanceMetric").textContent =
"Invalid parameter set";
document.querySelector("#magnificationMetric").textContent =
"Not defined";
classification.classList.add("limit");
classification.textContent = "The supplied lens parameters are invalid.";
} else {
const di = solution.di;
const m = solution.m;
document.querySelector("#imageDistanceMetric").textContent =
`${signedDistance(di)} — ${di > 0 ? "real, right" : "virtual, left"}`;
const orientation = m < 0 ? "inverted" : "upright";
const magnificationText = `${m < 0 ? "−" : "+"}${Math.abs(m).toFixed(3)}×`;
document.querySelector("#magnificationMetric").textContent =
`${magnificationText} — ${orientation}`;
if (di > 0) {
classification.classList.add("real");
classification.textContent =
"Real image — inverted and formed on the far side of the lens.";
} else {
classification.classList.add("virtual");
classification.textContent =
"Virtual image — upright and formed by backward ray extensions.";
}
}
if (
!Number.isFinite(solution.di) ||
Math.abs(solution.di) > imageDisplayLimit
) {
classification.textContent +=
" The image lies beyond the displayed schematic range.";
}
}
// -------------------------------------------------------------------------
// Custom camera controls, implemented without Three.js addons
// -------------------------------------------------------------------------
function updateCamera() {
const cosPitch = Math.cos(orbit.pitch);
const sinPitch = Math.sin(orbit.pitch);
camera.position.set(
orbit.target.x +
orbit.distance * Math.sin(orbit.yaw) * cosPitch,
orbit.target.y +
orbit.distance * sinPitch,
orbit.target.z +
orbit.distance * Math.cos(orbit.yaw) * cosPitch
);
camera.lookAt(orbit.target);
camera.updateMatrixWorld();
}
function updateProjection() {
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const aspect = Math.max(width / Math.max(height, 1), 0.1);
camera.left = (-orbit.viewHeight * aspect) / 2;
camera.right = (orbit.viewHeight * aspect) / 2;
camera.top = orbit.viewHeight / 2;
camera.bottom = -orbit.viewHeight / 2;
camera.updateProjectionMatrix();
}
function fitView(resetOrbit = false) {
const solution = state.solution;
let left = -Math.max(state.distanceObject + 30, 80);
let right = 125;
if (solution && !solution.atLimit && !solution.invalid) {
const di = solution.di;
if (di > 0 && di <= imageDisplayLimit) {
right = Math.max(right, di + 28);
} else if (di < 0 && di >= -imageDisplayLimit) {
left = Math.min(left, di - 28);
} else if (di > imageDisplayLimit) {
right = rayRightLimit;
} else if (di < -imageDisplayLimit) {
left = -rayRightLimit;
}
}
orbit.bounds.left = left;
orbit.bounds.right = right;
orbit.target.x = (left + right) / 2;
orbit.target.y = 0;
if (resetOrbit) {
orbit.yaw = 0.22;
orbit.pitch = 0.34;
}
const aspect = Math.max(
canvas.clientWidth / Math.max(canvas.clientHeight, 1),
0.1
);
const horizontalExtent = Math.max(right - left, 150);
orbit.viewHeight = Math.max(
105,
(horizontalExtent / Math.max(aspect, 0.75)) * 1.12
);
camera.zoom = 1;
const offRight =
solution &&
!solution.atLimit &&
solution.di > imageDisplayLimit;
const offLeft =
solution &&
!solution.atLimit &&
solution.di < -imageDisplayLimit;
offRightLabel.visible = Boolean(offRight);
offLeftLabel.visible = Boolean(offLeft);
offRightLabel.position.set(right - 6, 16, 0);
offLeftLabel.position.set(left + 6, 16, 0);
updateProjection();
updateCamera();
}
function resize() {
renderer.setSize(
canvas.clientWidth,
canvas.clientHeight,
false
);
updateProjection();
updateCamera();
}
window.addEventListener("resize", resize);
// -------------------------------------------------------------------------
// Direct object dragging
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
const dragPoint = new THREE.Vector3();
let pointerMode = null;
let dragOffset = 0;
let previousPointerX = 0;
let previousPointerY = 0;
function updatePointer(event) {
const rect = canvas.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);
}
canvas.addEventListener("pointerdown", (event) => {
updatePointer(event);
const hits = raycaster.intersectObject(objectGroup, true);
if (hits.length > 0) {
const intersection = raycaster.ray.intersectPlane(
dragPlane,
dragPoint
);
if (intersection) {
pointerMode = "object";
dragOffset = objectGroup.position.x - dragPoint.x;
canvas.setPointerCapture(event.pointerId);
canvas.style.cursor = "grabbing";
return;
}
}
pointerMode = "orbit";
previousPointerX = event.clientX;
previousPointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
canvas.style.cursor = "grabbing";
});
canvas.addEventListener("pointermove", (event) => {
if (pointerMode === "object") {
updatePointer(event);
const intersection = raycaster.ray.intersectPlane(
dragPlane,
dragPoint
);
if (intersection) {
const newX = THREE.MathUtils.clamp(
dragPoint.x + dragOffset,
-180,
-25
);
state.distanceObject = -newX;
document.querySelector("#objectDistance").value =
state.distanceObject;
updateScene();
}
} else if (pointerMode === "orbit") {
const deltaX = event.clientX - previousPointerX;
const deltaY = event.clientY - previousPointerY;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
orbit.yaw -= deltaX * 0.006;
orbit.pitch = THREE.MathUtils.clamp(
orbit.pitch + deltaY * 0.005,
-0.25,
1.12
);
updateCamera();
} else {
updatePointer(event);
const hovering =
raycaster.intersectObject(objectGroup, true).length > 0;
canvas.style.cursor = hovering ? "grab" : "default";
}
});
function finishPointer(event) {
if (pointerMode === "object") {
fitView(false);
}
pointerMode = null;
canvas.style.cursor = "default";
if (
event &&
canvas.hasPointerCapture &&
canvas.hasPointerCapture(event.pointerId)
) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", finishPointer);
canvas.addEventListener("pointercancel", finishPointer);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
camera.zoom = THREE.MathUtils.clamp(
camera.zoom * Math.exp(-event.deltaY * 0.001),
0.45,
6
);
camera.updateProjectionMatrix();
},
{ passive: false }
);
// -------------------------------------------------------------------------
// Interface
// -------------------------------------------------------------------------
const objectSlider = document.querySelector("#objectDistance");
const focalSlider = document.querySelector("#focalLength");
objectSlider.addEventListener("input", () => {
state.distanceObject = Number(objectSlider.value);
updateScene();
fitView(false);
});
focalSlider.addEventListener("input", () => {
state.focalLength = Number(focalSlider.value);
updateScene();
fitView(false);
});
document.querySelector("#showRays").addEventListener("change", (event) => {
state.showRays = event.target.checked;
updateScene();
});
document.querySelector("#focusLimit").addEventListener("click", () => {
state.distanceObject = state.focalLength;
objectSlider.value = state.distanceObject;
updateScene();
fitView(false);
});
document.querySelector("#resetView").addEventListener("click", () => {
fitView(true);
});
// Start with a conventional real-image configuration.
resize();
updateScene();
fitView(true);
renderer.setAnimationLoop(() => {
renderer.render(scene, camera);
});
</script>
</body>
</html>
```