Prompt specification
Build or customize the Three.js 3D scene "Refraction interface ray model" 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: Refraction interface ray model
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/refraction-interface-ray-model-x1573
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows two transparent half-spaces with a clear boundary and normal; trace incident and refracted rays using stated refractive indices and Snell's law. Low-poly.
Working Three.js Starter (refraction-interface-ray-model-x1573):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Low-Poly Refraction Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(8, 19, 35, 0.82);
--border: rgba(148, 163, 184, 0.22);
--text: #e5eefb;
--muted: #8da3bd;
--incident: #fbbf24;
--refracted: #22d3ee;
--normal: #e2e8f0;
--air: #7dd3fc;
--glass: #c4b5fd;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 70% 30%, #102843 0%, transparent 45%),
var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
}
canvas {
position: fixed;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
canvas:active {
cursor: grabbing;
}
.panel {
position: fixed;
z-index: 10;
top: 20px;
left: 20px;
width: 340px;
max-height: calc(100vh - 40px);
overflow: auto;
padding: 20px;
border: 1px solid var(--border);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 22px 70px rgba(0, 0, 0, 0.38);
backdrop-filter: blur(18px);
-webkit-backdrop-filter: blur(18px);
}
.eyebrow {
margin-bottom: 7px;
color: var(--refracted);
font-size: 0.69rem;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 1.55rem;
line-height: 1.08;
letter-spacing: -0.035em;
}
.subtitle {
margin: 9px 0 16px;
color: var(--muted);
font-size: 0.84rem;
line-height: 1.5;
}
.equation {
margin-bottom: 17px;
padding: 11px 12px;
border: 1px solid rgba(34, 211, 238, 0.16);
border-radius: 11px;
background: rgba(34, 211, 238, 0.055);
color: #cffafe;
text-align: center;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.92rem;
}
.control {
margin-top: 14px;
}
.control label {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 7px;
color: #dbe8f8;
font-size: 0.78rem;
font-weight: 650;
}
.control output {
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.75rem;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
border-radius: 999px;
appearance: none;
-webkit-appearance: none;
background: #26384f;
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
border: 3px solid #07111f;
border-radius: 50%;
appearance: none;
-webkit-appearance: none;
background: var(--refracted);
box-shadow: 0 0 0 1px rgba(34, 211, 238, 0.4);
}
input[type="range"]::-moz-range-thumb {
width: 10px;
height: 10px;
border: 3px solid #07111f;
border-radius: 50%;
background: var(--refracted);
}
#angle {
accent-color: var(--incident);
}
#angle::-webkit-slider-thumb {
background: var(--incident);
box-shadow: 0 0 0 1px rgba(251, 191, 36, 0.4);
}
#n1::-webkit-slider-thumb,
#n2::-webkit-slider-thumb {
background: var(--glass);
box-shadow: 0 0 0 1px rgba(196, 181, 253, 0.4);
}
.readouts {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
margin-top: 18px;
}
.readout {
padding: 10px 11px;
border: 1px solid var(--border);
border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
}
.readout span {
display: block;
margin-bottom: 3px;
color: var(--muted);
font-size: 0.65rem;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.readout strong {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.95rem;
}
.snell {
margin-top: 10px;
padding: 10px 11px;
border-radius: 10px;
background: rgba(255, 255, 255, 0.035);
color: #cbd5e1;
text-align: center;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.72rem;
line-height: 1.5;
}
.status {
min-height: 42px;
margin-top: 10px;
color: var(--muted);
font-size: 0.76rem;
line-height: 1.45;
}
.legend {
display: grid;
gap: 7px;
margin-top: 14px;
padding-top: 14px;
border-top: 1px solid var(--border);
}
.legend-item {
display: flex;
align-items: center;
gap: 9px;
color: #cbd5e1;
font-size: 0.73rem;
}
.swatch {
width: 23px;
height: 3px;
border-radius: 999px;
background: currentColor;
}
.swatch.dashed {
height: 0;
border-top: 2px dashed currentColor;
background: none;
}
button {
width: 100%;
margin-top: 15px;
padding: 10px 12px;
border: 1px solid rgba(34, 211, 238, 0.32);
border-radius: 10px;
background: rgba(34, 211, 238, 0.1);
color: #cffafe;
font: inherit;
font-size: 0.78rem;
font-weight: 750;
cursor: pointer;
transition: background 150ms ease, transform 150ms ease;
}
button:hover {
background: rgba(34, 211, 238, 0.18);
}
button:active {
transform: translateY(1px);
}
.hint {
position: fixed;
z-index: 5;
right: 20px;
bottom: 18px;
padding: 8px 12px;
border: 1px solid var(--border);
border-radius: 999px;
background: rgba(7, 17, 31, 0.72);
color: var(--muted);
font-size: 0.71rem;
pointer-events: none;
}
.tir-banner {
position: fixed;
z-index: 12;
top: 20px;
right: 20px;
max-width: 310px;
padding: 13px 16px;
border: 1px solid rgba(251, 113, 133, 0.45);
border-radius: 12px;
background: rgba(76, 15, 33, 0.88);
color: #fecdd3;
font-size: 0.78rem;
line-height: 1.45;
box-shadow: 0 16px 45px rgba(0, 0, 0, 0.35);
}
[hidden] {
display: none !important;
}
@media (max-width: 700px) {
.panel {
top: 10px;
left: 10px;
right: 10px;
width: auto;
max-height: 54vh;
padding: 15px;
border-radius: 14px;
}
h1 {
font-size: 1.3rem;
}
.subtitle {
margin-bottom: 12px;
}
.equation {
margin-bottom: 10px;
}
.readouts,
.legend {
margin-top: 11px;
}
.hint {
right: 10px;
bottom: 10px;
}
.tir-banner {
top: auto;
right: 10px;
bottom: 54px;
left: 10px;
max-width: none;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive three-dimensional refraction diagram"></canvas>
<section class="panel" aria-label="Refraction controls and measurements">
<div class="eyebrow">Low-Poly Optics Lab</div>
<h1>Snell’s Law Explorer</h1>
<p class="subtitle">
A ray travels from air into glass. Drag to orbit the scene and use the
wheel to zoom.
</p>
<div class="equation">n₁ sin θ₁ = n₂ sin θ₂</div>
<div class="control">
<label for="angle">
<span>Incident angle θ₁</span>
<output id="angleValue">35.0°</output>
</label>
<input id="angle" type="range" min="0" max="89" step="0.1" value="35">
</div>
<div class="control">
<label for="n1">
<span>Medium 1 · air</span>
<output id="n1Value">n₁ = 1.00</output>
</label>
<input id="n1" type="range" min="0.80" max="2.40" step="0.01" value="1.00">
</div>
<div class="control">
<label for="n2">
<span>Medium 2 · glass</span>
<output id="n2Value">n₂ = 1.52</output>
</label>
<input id="n2" type="range" min="0.80" max="2.40" step="0.01" value="1.52">
</div>
<div class="readouts">
<div class="readout">
<span>Incident angle</span>
<strong id="theta1Readout">35.0°</strong>
</div>
<div class="readout">
<span>Refracted angle</span>
<strong id="theta2Readout">22.2°</strong>
</div>
</div>
<div class="snell" id="snellReadout">
1.00 × sin(35.0°) = 1.52 × sin(22.2°)
</div>
<div class="status" id="statusText">
The refracted ray bends toward the normal because n₂ > n₁.
</div>
<div class="legend" aria-label="Diagram legend">
<div class="legend-item" style="color: var(--incident)">
<span class="swatch"></span>
Incident ray
</div>
<div class="legend-item" style="color: var(--refracted)">
<span class="swatch"></span>
Refracted ray
</div>
<div class="legend-item" style="color: var(--normal)">
<span class="swatch dashed"></span>
Interface normal
</div>
</div>
<button id="reset" type="button">Reset lab and camera</button>
</section>
<div class="hint">Drag: orbit · Wheel: zoom · Double-click: reset view</div>
<div class="tir-banner" id="tirBanner" hidden>
<strong>Total internal reflection</strong><br>
The incident angle exceeds the critical angle, so no propagating
refracted ray exists.
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Renderer and scene
// -------------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.setClearColor(0x07111f, 1);
const scene = new THREE.Scene();
const camera = new THREE.OrthographicCamera(-8, 8, 5, -5, 0.1, 100);
const cameraTarget = new THREE.Vector3(0, 0, 0);
const cameraState = {
azimuth: -0.16,
elevation: 0.08,
distance: 18,
zoom: 1
};
scene.add(new THREE.AmbientLight(0x9bbcff, 1.4));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.1);
keyLight.position.set(5, 7, 9);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x38bdf8, 0.85);
rimLight.position.set(-6, -3, 5);
scene.add(rimLight);
// -------------------------------------------------------------------------
// Low-poly transparent half-spaces
// -------------------------------------------------------------------------
const WIDTH = 12;
const HALF_HEIGHT = 4.6;
const DEPTH = 1.3;
const RAY_Z = 0.82;
function makeHalfSpace(y, color, edgeColor) {
const geometry = new THREE.BoxGeometry(
WIDTH,
HALF_HEIGHT,
DEPTH,
1,
1,
1
);
const material = new THREE.MeshPhongMaterial({
color,
transparent: true,
opacity: 0.115,
side: THREE.DoubleSide,
depthWrite: false,
flatShading: true,
shininess: 35,
specular: 0xffffff
});
const mesh = new THREE.Mesh(geometry, material);
mesh.position.y = y;
mesh.renderOrder = 1;
scene.add(mesh);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry),
new THREE.LineBasicMaterial({
color: edgeColor,
transparent: true,
opacity: 0.38,
depthWrite: false
})
);
edges.position.copy(mesh.position);
edges.renderOrder = 2;
scene.add(edges);
return mesh;
}
makeHalfSpace(HALF_HEIGHT / 2, 0x38bdf8, 0x7dd3fc);
makeHalfSpace(-HALF_HEIGHT / 2, 0x8b5cf6, 0xc4b5fd);
// A thin, explicit boundary at y = 0.
const boundary = new THREE.Mesh(
new THREE.BoxGeometry(WIDTH, 0.035, DEPTH),
new THREE.MeshBasicMaterial({
color: 0xf8fafc,
transparent: true,
opacity: 0.34,
depthWrite: false
})
);
boundary.renderOrder = 3;
scene.add(boundary);
const boundaryLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-WIDTH / 2, 0, DEPTH / 2 + 0.035),
new THREE.Vector3(WIDTH / 2, 0, DEPTH / 2 + 0.035)
]),
new THREE.LineBasicMaterial({
color: 0xf8fafc,
transparent: true,
opacity: 0.9
})
);
boundaryLine.renderOrder = 4;
scene.add(boundaryLine);
// Sparse triangular facet lines provide a restrained low-poly texture.
function addFacetLines(y0, y1, color) {
const positions = [];
const columns = 4;
const rows = 2;
const z = DEPTH / 2 + 0.018;
for (let ix = 0; ix < columns; ix++) {
for (let iy = 0; iy < rows; iy++) {
const x0 = -WIDTH / 2 + (ix * WIDTH) / columns;
const x1 = -WIDTH / 2 + ((ix + 1) * WIDTH) / columns;
const ya = y0 + (iy * (y1 - y0)) / rows;
const yb = y0 + ((iy + 1) * (y1 - y0)) / rows;
if ((ix + iy) % 2 === 0) {
positions.push(x0, ya, z, x1, yb, z);
} else {
positions.push(x0, yb, z, x1, ya, z);
}
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
const lines = new THREE.LineSegments(
geometry,
new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.10,
depthWrite: false
})
);
lines.renderOrder = 2;
scene.add(lines);
}
addFacetLines(0, HALF_HEIGHT, 0x7dd3fc);
addFacetLines(-HALF_HEIGHT, 0, 0xc4b5fd);
// Subtle background construction grid.
{
const positions = [];
for (let x = -6; x <= 6; x += 1.5) {
positions.push(x, -4.6, -1.1, x, 4.6, -1.1);
}
for (let y = -4.5; y <= 4.5; y += 1.5) {
positions.push(-6, y, -1.1, 6, y, -1.1);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
scene.add(
new THREE.LineSegments(
geometry,
new THREE.LineBasicMaterial({
color: 0x7c9bb8,
transparent: true,
opacity: 0.075,
depthWrite: false
})
)
);
}
// -------------------------------------------------------------------------
// Labels made directly from canvas textures
// -------------------------------------------------------------------------
function roundedRect(ctx, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + width, y, x + width, y + height, r);
ctx.arcTo(x + width, y + height, x, y + height, r);
ctx.arcTo(x, y + height, x, y, r);
ctx.arcTo(x, y, x + width, y, r);
ctx.closePath();
}
function createLabel(initialText, color, worldWidth) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 768;
labelCanvas.height = 160;
const ctx = labelCanvas.getContext("2d");
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false,
toneMapped: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(worldWidth, worldWidth * (160 / 768), 1);
sprite.renderOrder = 30;
scene.add(sprite);
function setText(text, textColor = color) {
ctx.clearRect(0, 0, labelCanvas.width, labelCanvas.height);
roundedRect(ctx, 4, 4, 760, 152, 26);
ctx.fillStyle = "rgba(5, 15, 29, 0.82)";
ctx.fill();
ctx.strokeStyle = "rgba(148, 163, 184, 0.25)";
ctx.lineWidth = 2;
ctx.stroke();
let fontSize = 42;
ctx.font = `700 ${fontSize}px ui-monospace, SFMono-Regular, Menlo, monospace`;
while (ctx.measureText(text).width > 710 && fontSize > 24) {
fontSize -= 2;
ctx.font = `700 ${fontSize}px ui-monospace, SFMono-Regular, Menlo, monospace`;
}
ctx.fillStyle = textColor;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 384, 82);
texture.needsUpdate = true;
}
setText(initialText);
return { sprite, setText };
}
const medium1Label = createLabel(
"MEDIUM 1 / AIR / n = 1.00",
"#7dd3fc",
4.15
);
medium1Label.sprite.position.set(-4.25, 2.45, 1.1);
const medium2Label = createLabel(
"MEDIUM 2 / GLASS / n = 1.52",
"#c4b5fd",
4.25
);
medium2Label.sprite.position.set(3.65, -2.65, 1.1);
const normalLabel = createLabel("NORMAL", "#e2e8f0", 1.85);
normalLabel.sprite.position.set(0.9, 3.8, 1.12);
const theta1Label = createLabel("θ₁ = 35.0°", "#fbbf24", 1.65);
const theta2Label = createLabel("θ₂ = 22.2°", "#22d3ee", 1.65);
// -------------------------------------------------------------------------
// Normal, rays, arrows, and angle arcs
// -------------------------------------------------------------------------
const origin = new THREE.Vector3(0, 0, RAY_Z);
const yAxis = new THREE.Vector3(0, 1, 0);
const normalLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, -4.25, RAY_Z + 0.02),
new THREE.Vector3(0, 4.25, RAY_Z + 0.02)
]),
new THREE.LineDashedMaterial({
color: 0xe2e8f0,
dashSize: 0.16,
gapSize: 0.11,
transparent: true,
opacity: 0.85,
depthTest: false,
depthWrite: false
})
);
normalLine.computeLineDistances();
normalLine.renderOrder = 12;
scene.add(normalLine);
function createArrow(color) {
const arrow = new THREE.Mesh(
new THREE.ConeGeometry(0.115, 0.31, 6),
new THREE.MeshBasicMaterial({
color,
depthTest: false,
depthWrite: false
})
);
arrow.renderOrder = 14;
scene.add(arrow);
return arrow;
}
function pointArrow(arrow, direction, position) {
arrow.position.copy(position);
arrow.quaternion.setFromUnitVectors(yAxis, direction.clone().normalize());
}
const normalTopArrow = createArrow(0xe2e8f0);
pointArrow(
normalTopArrow,
new THREE.Vector3(0, 1, 0),
new THREE.Vector3(0, 4.22, RAY_Z + 0.02)
);
const normalBottomArrow = createArrow(0xe2e8f0);
pointArrow(
normalBottomArrow,
new THREE.Vector3(0, -1, 0),
new THREE.Vector3(0, -4.22, RAY_Z + 0.02)
);
const incidentLine = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineBasicMaterial({
color: 0xfbbf24,
depthTest: false,
depthWrite: false
})
);
const refractedLine = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineBasicMaterial({
color: 0x22d3ee,
depthTest: false,
depthWrite: false
})
);
const theta1Arc = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineBasicMaterial({
color: 0xfbbf24,
transparent: true,
opacity: 0.95,
depthTest: false,
depthWrite: false
})
);
const theta2Arc = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineBasicMaterial({
color: 0x22d3ee,
transparent: true,
opacity: 0.95,
depthTest: false,
depthWrite: false
})
);
incidentLine.renderOrder = 10;
refractedLine.renderOrder = 10;
theta1Arc.renderOrder = 11;
theta2Arc.renderOrder = 11;
scene.add(incidentLine, refractedLine, theta1Arc, theta2Arc);
const incidentArrow = createArrow(0xfbbf24);
const refractedArrow = createArrow(0x22d3ee);
const contactPoint = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.095, 0),
new THREE.MeshBasicMaterial({
color: 0xffffff,
depthTest: false,
depthWrite: false
})
);
contactPoint.position.copy(origin);
contactPoint.renderOrder = 15;
scene.add(contactPoint);
function replaceLinePoints(line, points) {
line.geometry.dispose();
line.geometry = new THREE.BufferGeometry().setFromPoints(points);
}
function arcPoints(angle, upper) {
const points = [];
const radius = 0.88;
const segments = 30;
for (let i = 0; i <= segments; i++) {
const a = angle * (i / segments);
if (upper) {
points.push(
new THREE.Vector3(
-radius * Math.sin(a),
radius * Math.cos(a),
RAY_Z + 0.025
)
);
} else {
points.push(
new THREE.Vector3(
radius * Math.sin(a),
-radius * Math.cos(a),
RAY_Z + 0.025
)
);
}
}
return points;
}
// -------------------------------------------------------------------------
// UI and optical calculation
// -------------------------------------------------------------------------
const angleInput = document.querySelector("#angle");
const n1Input = document.querySelector("#n1");
const n2Input = document.querySelector("#n2");
const angleValue = document.querySelector("#angleValue");
const n1Value = document.querySelector("#n1Value");
const n2Value = document.querySelector("#n2Value");
const theta1Readout = document.querySelector("#theta1Readout");
const theta2Readout = document.querySelector("#theta2Readout");
const snellReadout = document.querySelector("#snellReadout");
const statusText = document.querySelector("#statusText");
const tirBanner = document.querySelector("#tirBanner");
function updateOptics() {
const theta1Deg = Number(angleInput.value);
const n1 = Number(n1Input.value);
const n2 = Number(n2Input.value);
const theta1 = THREE.MathUtils.degToRad(theta1Deg);
const sinTheta2 = (n1 * Math.sin(theta1)) / n2;
const totalInternalReflection = sinTheta2 > 1 + 1e-10;
const theta2 = totalInternalReflection
? 0
: Math.asin(Math.min(1, Math.max(-1, sinTheta2)));
const theta2Deg = THREE.MathUtils.radToDeg(theta2);
angleValue.textContent = `${theta1Deg.toFixed(1)}°`;
n1Value.textContent = `n₁ = ${n1.toFixed(2)}`;
n2Value.textContent = `n₂ = ${n2.toFixed(2)}`;
theta1Readout.textContent = `${theta1Deg.toFixed(1)}°`;
theta2Readout.textContent = totalInternalReflection
? "—"
: `${theta2Deg.toFixed(1)}°`;
snellReadout.textContent = totalInternalReflection
? `${n1.toFixed(2)} × sin(${theta1Deg.toFixed(1)}°) > n₂`
: `${n1.toFixed(2)} × sin(${theta1Deg.toFixed(1)}°) = ` +
`${n2.toFixed(2)} × sin(${theta2Deg.toFixed(1)}°)`;
tirBanner.hidden = !totalInternalReflection;
if (totalInternalReflection) {
statusText.textContent =
"The incident angle exceeds the critical angle, so no propagating refracted ray exists.";
} else if (n2 > n1 + 0.005) {
statusText.textContent =
"The refracted ray bends toward the normal because n₂ > n₁.";
} else if (n1 > n2 + 0.005) {
statusText.textContent =
"The refracted ray bends away from the normal because n₁ > n₂.";
} else {
statusText.textContent =
"The two indices are equal, so the ray does not change direction.";
}
// Incident propagation vector: down and to the right.
const incidentDirection = new THREE.Vector3(
Math.sin(theta1),
-Math.cos(theta1),
0
);
// Keep the ray endpoint within the visible upper half-space.
const incidentLength = Math.min(
5.4,
4.4 / Math.max(Math.cos(theta1), 0.2)
);
const incidentStart = origin
.clone()
.addScaledVector(incidentDirection, -incidentLength);
replaceLinePoints(incidentLine, [incidentStart, origin]);
pointArrow(
incidentArrow,
incidentDirection,
origin.clone().addScaledVector(incidentDirection, -1.08)
);
replaceLinePoints(theta1Arc, arcPoints(theta1, true));
const midpoint1 = theta1 / 2;
theta1Label.setText(`θ₁ = ${theta1Deg.toFixed(1)}°`, "#fbbf24");
theta1Label.sprite.position.set(
-0.58 - 0.78 * Math.sin(midpoint1),
0.28 + 0.78 * Math.cos(midpoint1),
RAY_Z + 0.12
);
refractedLine.visible = !totalInternalReflection;
refractedArrow.visible = !totalInternalReflection;
theta2Arc.visible = !totalInternalReflection;
if (totalInternalReflection) {
theta2Label.setText("TIR", "#fb7185");
theta2Label.sprite.position.set(1.25, -0.95, RAY_Z + 0.12);
} else {
// Refracted propagation vector remains down and to the right.
const refractedDirection = new THREE.Vector3(
Math.sin(theta2),
-Math.cos(theta2),
0
);
const refractedEnd = origin
.clone()
.addScaledVector(refractedDirection, 4.5);
replaceLinePoints(refractedLine, [origin, refractedEnd]);
pointArrow(
refractedArrow,
refractedDirection,
origin.clone().addScaledVector(refractedDirection, 1.12)
);
replaceLinePoints(theta2Arc, arcPoints(theta2, false));
const midpoint2 = theta2 / 2;
theta2Label.setText(`θ₂ = ${theta2Deg.toFixed(1)}°`, "#22d3ee");
theta2Label.sprite.position.set(
0.58 + 0.78 * Math.sin(midpoint2),
-0.28 - 0.78 * Math.cos(midpoint2),
RAY_Z + 0.12
);
}
medium1Label.setText(
`MEDIUM 1 / AIR / n = ${n1.toFixed(2)}`,
"#7dd3fc"
);
medium2Label.setText(
`MEDIUM 2 / GLASS / n = ${n2.toFixed(2)}`,
"#c4b5fd"
);
}
angleInput.addEventListener("input", updateOptics);
n1Input.addEventListener("input", updateOptics);
n2Input.addEventListener("input", updateOptics);
// -------------------------------------------------------------------------
// Direct camera controls: orbit, zoom, and reset
// -------------------------------------------------------------------------
function updateCamera() {
const aspect = window.innerWidth / window.innerHeight;
const halfHeight = Math.max(4.9, 6.7 / aspect);
camera.left = -halfHeight * aspect;
camera.right = halfHeight * aspect;
camera.top = halfHeight;
camera.bottom = -halfHeight;
camera.zoom = cameraState.zoom;
const cosElevation = Math.cos(cameraState.elevation);
camera.position.set(
cameraTarget.x +
cameraState.distance *
cosElevation *
Math.sin(cameraState.azimuth),
cameraTarget.y +
cameraState.distance * Math.sin(cameraState.elevation),
cameraTarget.z +
cameraState.distance *
cosElevation *
Math.cos(cameraState.azimuth)
);
camera.lookAt(cameraTarget);
camera.updateProjectionMatrix();
}
function resetCamera() {
cameraState.azimuth = -0.16;
cameraState.elevation = 0.08;
cameraState.zoom = 1;
updateCamera();
}
let dragging = false;
let pointerX = 0;
let pointerY = 0;
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraState.azimuth -= dx * 0.006;
cameraState.elevation = THREE.MathUtils.clamp(
cameraState.elevation + dy * 0.005,
-0.75,
0.75
);
updateCamera();
});
function endDrag(event) {
dragging = false;
if (event.pointerId !== undefined && canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.zoom = THREE.MathUtils.clamp(
cameraState.zoom * Math.exp(-event.deltaY * 0.001),
0.55,
2.6
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetCamera);
document.querySelector("#reset").addEventListener("click", () => {
angleInput.value = "35";
n1Input.value = "1.00";
n2Input.value = "1.52";
updateOptics();
resetCamera();
});
window.addEventListener("resize", () => {
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
updateCamera();
});
// -------------------------------------------------------------------------
// Start
// -------------------------------------------------------------------------
updateOptics();
updateCamera();
const clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
const elapsed = clock.getElapsedTime();
const pulse = 1 + Math.sin(elapsed * 3.2) * 0.07;
contactPoint.scale.setScalar(pulse);
renderer.render(scene, camera);
});
</script>
</body>
</html>
```