Prompt specification
Build or customize the Three.js 3D scene "Latency-Free Timing Practice Puzzle" 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: Latency-Free Timing Practice Puzzle
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/latency-free-timing-practice-puzzle-x3632
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows a low-poly paddle-contact prediction puzzle on a small table. Before each trial, freeze the scene with a ball at a known starting point and display a few possible paddle positions. The player chooses where the paddle will be, then starts a deterministic replay of the ball's trajectory. Mark the actual contact point if the ball intersects the paddle's valid surface; otherwise show where it passes. Let the player retry the identical shot with another choice. Score the selected geometry and predicted contact rather than reaction speed, and keep a faint trace of the previous attempt for comparison.
Working Three.js Starter (latency-free-timing-practice-puzzle-x3632):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Contact Lab — Paddle Prediction Puzzle</title>
<style>
:root {
--bg: #09131c;
--panel: rgba(15, 29, 41, 0.86);
--panel-strong: rgba(12, 24, 34, 0.96);
--line: rgba(255, 255, 255, 0.12);
--muted: #8ea4b3;
--text: #edf7f5;
--cyan: #58e0c0;
--amber: #ffd166;
--red: #ff786f;
--blue: #72b9ff;
}
* { 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 { font: inherit; }
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
cursor: grab;
touch-action: none;
}
#scene:active { cursor: grabbing; }
.brand {
position: fixed;
z-index: 10;
top: 20px;
left: 22px;
width: 310px;
padding: 16px 18px;
border: 1px solid var(--line);
border-radius: 18px;
background: linear-gradient(145deg, rgba(17, 34, 46, 0.92), rgba(8, 18, 27, 0.72));
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.25);
backdrop-filter: blur(16px);
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 14px var(--cyan);
}
h1 {
margin: 7px 0 4px;
font-size: 24px;
line-height: 1;
letter-spacing: -0.04em;
}
.subtitle {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.shot-meta {
display: flex;
gap: 8px;
margin-top: 13px;
flex-wrap: wrap;
}
.chip {
padding: 6px 8px;
border: 1px solid var(--line);
border-radius: 8px;
color: #b9cad4;
background: rgba(255,255,255,0.035);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.dock {
position: fixed;
z-index: 20;
top: 18px;
right: 18px;
width: 330px;
max-height: calc(100vh - 36px);
overflow: auto;
padding: 17px;
border: 1px solid var(--line);
border-radius: 20px;
background: var(--panel);
box-shadow: 0 22px 70px rgba(0, 0, 0, 0.35);
backdrop-filter: blur(18px);
scrollbar-width: thin;
scrollbar-color: rgba(255,255,255,0.18) transparent;
}
.panel-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.panel-title span:last-child {
color: var(--muted);
font-size: 9px;
letter-spacing: 0.08em;
}
.step {
padding: 12px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(255,255,255,0.025);
transition: border-color 180ms, background 180ms, opacity 180ms;
}
.step + .step { margin-top: 10px; }
.step.active {
border-color: rgba(88, 224, 192, 0.46);
background: rgba(88, 224, 192, 0.055);
}
.step.done { opacity: 0.58; }
.step-head {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 10px;
}
.step-number {
display: grid;
place-items: center;
width: 24px;
height: 24px;
flex: 0 0 24px;
border-radius: 8px;
background: rgba(255,255,255,0.07);
color: var(--cyan);
font-size: 11px;
font-weight: 900;
}
.step-title {
font-size: 13px;
font-weight: 800;
}
.step-help {
margin-left: auto;
color: var(--muted);
font-size: 9px;
text-align: right;
}
.candidate-list {
display: grid;
gap: 7px;
}
.candidate {
width: 100%;
display: grid;
grid-template-columns: 35px 1fr 15px;
align-items: center;
gap: 10px;
padding: 9px;
border: 1px solid rgba(255,255,255,0.09);
border-radius: 11px;
color: var(--text);
background: rgba(255,255,255,0.025);
text-align: left;
cursor: pointer;
transition: 160ms ease;
}
.candidate:hover:not(:disabled) {
transform: translateX(-2px);
border-color: rgba(255,255,255,0.25);
background: rgba(255,255,255,0.055);
}
.candidate.selected {
border-color: var(--accent);
background: color-mix(in srgb, var(--accent) 10%, transparent);
box-shadow: inset 3px 0 0 var(--accent);
}
.candidate:disabled { cursor: default; opacity: 0.5; }
.candidate-code {
display: grid;
place-items: center;
width: 34px;
height: 34px;
border: 1px solid var(--accent);
border-radius: 9px;
color: var(--accent);
background: color-mix(in srgb, var(--accent) 9%, transparent);
font-size: 14px;
font-weight: 900;
}
.candidate b {
display: block;
margin-bottom: 2px;
font-size: 11px;
}
.candidate small {
display: block;
color: var(--muted);
font-size: 9px;
}
.candidate-check {
color: var(--accent);
font-size: 13px;
opacity: 0;
}
.candidate.selected .candidate-check { opacity: 1; }
.map-wrap {
position: relative;
margin-top: 3px;
overflow: hidden;
border: 1px solid rgba(255,255,255,0.1);
border-radius: 12px;
background: #08131c;
}
#impactMap {
display: block;
width: 100%;
height: auto;
cursor: crosshair;
outline: none;
}
#impactMap:focus { box-shadow: inset 0 0 0 2px var(--cyan); }
.map-caption {
display: flex;
justify-content: space-between;
margin-top: 7px;
color: var(--muted);
font-size: 9px;
}
#predictionReadout {
color: #d7e6eb;
font-variant-numeric: tabular-nums;
}
.score-rule {
margin-top: 12px;
padding: 10px;
border-radius: 10px;
color: var(--muted);
background: rgba(0,0,0,0.16);
font-size: 9px;
line-height: 1.5;
}
.score-rule strong { color: var(--text); }
.result {
margin-top: 10px;
padding: 14px;
border: 1px solid rgba(255,255,255,0.12);
border-radius: 14px;
background: rgba(0,0,0,0.18);
}
.result-status {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 11px;
}
#resultTitle {
margin: 0;
font-size: 20px;
letter-spacing: -0.035em;
}
.result-status span {
color: var(--muted);
font-size: 9px;
text-transform: uppercase;
letter-spacing: 0.1em;
}
.score-row {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px;
margin-top: 9px;
color: #c8d7df;
font-size: 10px;
}
.score-row strong {
color: var(--text);
font-variant-numeric: tabular-nums;
}
.bar {
grid-column: 1 / -1;
height: 4px;
overflow: hidden;
border-radius: 99px;
background: rgba(255,255,255,0.07);
}
.bar i {
display: block;
width: 0;
height: 100%;
border-radius: inherit;
background: var(--cyan);
transition: width 500ms ease;
}
.total-row {
display: flex;
align-items: flex-end;
justify-content: space-between;
margin-top: 13px;
padding-top: 11px;
border-top: 1px solid var(--line);
}
.total-row small {
color: var(--muted);
font-size: 9px;
line-height: 1.5;
}
#totalScore {
font-size: 30px;
font-weight: 900;
line-height: 1;
letter-spacing: -0.06em;
}
#resultCopy {
margin: 10px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.result-footer {
display: flex;
justify-content: space-between;
margin-top: 11px;
color: var(--muted);
font-size: 9px;
}
#deltaScore { color: var(--cyan); }
.controls {
position: fixed;
z-index: 30;
left: 50%;
bottom: 20px;
display: flex;
align-items: center;
gap: 9px;
padding: 8px;
border: 1px solid var(--line);
border-radius: 16px;
background: rgba(9, 20, 29, 0.9);
box-shadow: 0 16px 45px rgba(0,0,0,0.35);
backdrop-filter: blur(16px);
transform: translateX(-50%);
}
.btn {
min-height: 42px;
padding: 0 17px;
border: 1px solid rgba(255,255,255,0.13);
border-radius: 10px;
color: var(--text);
background: rgba(255,255,255,0.055);
font-size: 11px;
font-weight: 800;
cursor: pointer;
transition: 150ms ease;
}
.btn:hover:not(:disabled) {
transform: translateY(-1px);
border-color: rgba(255,255,255,0.3);
background: rgba(255,255,255,0.09);
}
.btn.primary {
min-width: 205px;
border-color: rgba(88,224,192,0.55);
color: #082019;
background: var(--cyan);
box-shadow: 0 8px 24px rgba(88,224,192,0.16);
}
.btn.primary:hover:not(:disabled) { background: #75ead0; }
.btn:disabled {
opacity: 0.38;
cursor: not-allowed;
}
.btn.retry {
border-color: rgba(255,209,102,0.5);
color: #ffe3a0;
background: rgba(255,209,102,0.09);
}
.toast {
position: fixed;
z-index: 25;
top: 22px;
left: 50%;
max-width: min(540px, calc(100vw - 720px));
padding: 10px 15px;
border: 1px solid rgba(88,224,192,0.28);
border-radius: 12px;
color: #cde7e0;
background: rgba(9, 23, 31, 0.88);
box-shadow: 0 12px 40px rgba(0,0,0,0.25);
font-size: 11px;
text-align: center;
opacity: 0;
pointer-events: none;
transform: translate(-50%, -12px);
transition: 220ms ease;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
.legend {
position: fixed;
z-index: 10;
left: 22px;
bottom: 22px;
display: flex;
gap: 13px;
padding: 10px 12px;
border: 1px solid var(--line);
border-radius: 12px;
color: var(--muted);
background: rgba(10, 22, 31, 0.76);
backdrop-filter: blur(12px);
font-size: 9px;
}
.legend span {
display: flex;
align-items: center;
gap: 6px;
}
.dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--cyan);
}
.dot.white { background: white; }
.dot.red { background: var(--red); }
.dot.gray { background: rgba(255,255,255,0.3); }
.hidden { display: none !important; }
@media (max-width: 900px) {
.brand {
top: 12px;
left: 12px;
width: 260px;
}
.dock {
top: auto;
right: 12px;
bottom: 84px;
width: 300px;
max-height: 58vh;
}
.toast {
top: 145px;
max-width: calc(100vw - 30px);
}
.legend { display: none; }
}
@media (max-width: 590px) {
.brand {
width: calc(100vw - 24px);
padding: 12px 14px;
}
.brand h1 { font-size: 19px; }
.brand .subtitle { display: none; }
.dock {
left: 12px;
right: 12px;
bottom: 80px;
width: auto;
max-height: 47vh;
}
.controls {
bottom: 10px;
width: calc(100vw - 20px);
}
.controls .btn { flex: 1; padding: 0 10px; }
.controls .btn.primary { min-width: 0; }
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive low-poly paddle prediction table"></canvas>
<section class="brand">
<div class="eyebrow">Contact Lab / Trial 03</div>
<h1>Paddle Prediction</h1>
<p class="subtitle">
Choose a paddle, predict the impact point, then replay the same fixed shot.
Geometry and prediction are scored—not reaction speed.
</p>
<div class="shot-meta">
<span class="chip">Fixed shot · FIX-07</span>
<span class="chip">Start · −2.80, 2.60, +2.20</span>
</div>
</section>
<aside class="dock">
<div class="panel-title">
<span>Trial Setup</span>
<span id="phaseLabel">Choose placement</span>
</div>
<section id="step1" class="step active">
<div class="step-head">
<div class="step-number">1</div>
<div class="step-title">Choose paddle geometry</div>
<div class="step-help">Three possible placements</div>
</div>
<div class="candidate-list">
<button class="candidate" data-index="0" style="--accent:#ff8a65">
<span class="candidate-code">A</span>
<span>
<b>Left · narrow</b>
<small>1.40 × 1.55 · x −1.75</small>
</span>
<span class="candidate-check">●</span>
</button>
<button class="candidate" data-index="1" style="--accent:#58e0c0">
<span class="candidate-code">B</span>
<span>
<b>Center · balanced</b>
<small>1.90 × 1.55 · x 0.00</small>
</span>
<span class="candidate-check">●</span>
</button>
<button class="candidate" data-index="2" style="--accent:#ffd166">
<span class="candidate-code">C</span>
<span>
<b>Right · low</b>
<small>1.65 × 1.30 · x +1.85</small>
</span>
<span class="candidate-check">●</span>
</button>
</div>
</section>
<section id="step2" class="step">
<div class="step-head">
<div class="step-number">2</div>
<div class="step-title">Predict the impact point</div>
<div class="step-help">Click map or 3D plane</div>
</div>
<div class="map-wrap">
<svg
id="impactMap"
viewBox="0 0 270 145"
tabindex="0"
role="img"
aria-label="Side-view impact map. Click to place the predicted contact point."
>
<defs>
<pattern id="grid" width="30" height="22" patternUnits="userSpaceOnUse">
<path d="M 30 0 L 0 0 0 22" fill="none" stroke="#29404e" stroke-width="0.6"/>
</pattern>
</defs>
<rect x="12" y="12" width="246" height="120" rx="8" fill="url(#grid)"/>
<rect x="12" y="12" width="246" height="120" rx="8" fill="none" stroke="#36515f"/>
<line x1="135" y1="12" x2="135" y2="132" stroke="#527081" stroke-dasharray="3 4" opacity="0.5"/>
<rect id="mapPaddle" x="0" y="0" width="0" height="0" rx="2"
fill="#58e0c0" fill-opacity="0.16" stroke="#58e0c0" stroke-width="1.5"
visibility="hidden"/>
<circle id="mapPrediction" cx="135" cy="72" r="5"
fill="#ffffff" stroke="#071019" stroke-width="2"
visibility="hidden"/>
<circle id="mapActual" cx="135" cy="72" r="6"
fill="#58e0c0" stroke="#071019" stroke-width="2"
visibility="hidden"/>
<text x="18" y="28" fill="#6f8998" font-size="8">HIGH</text>
<text x="18" y="126" fill="#6f8998" font-size="8">TABLE</text>
<text x="231" y="126" fill="#6f8998" font-size="8">+X</text>
</svg>
</div>
<div class="map-caption">
<span>Impact elevation</span>
<span id="predictionReadout">Not placed</span>
</div>
</section>
<section id="resultPanel" class="result hidden">
<div class="result-status">
<h2 id="resultTitle">Contact</h2>
<span>Shot evaluated</span>
</div>
<div class="score-row">
<span>Selected geometry</span><strong id="geometryScore">60 / 60</strong>
<div class="bar"><i id="geometryBar"></i></div>
</div>
<div class="score-row">
<span>Impact prediction</span><strong id="predictionScore">40 / 40</strong>
<div class="bar"><i id="predictionBar"></i></div>
</div>
<div class="total-row">
<small>
Best <strong id="bestScore">0</strong><br />
Previous <span id="previousScore">—</span>
</small>
<div id="totalScore">100</div>
</div>
<p id="resultCopy"></p>
<div class="result-footer">
<span>Reaction time ignored</span>
<span id="deltaScore">First attempt</span>
</div>
</section>
<div class="score-rule">
<strong>Scoring:</strong> selected geometry 60 points + predicted impact 40 points.
Retry with another placement. The incoming shot remains identical.
</div>
</aside>
<div id="toast" class="toast"></div>
<div class="controls">
<button id="resetBtn" class="btn" title="Reset the current answer and preserve comparison traces">
Reset
</button>
<button id="startBtn" class="btn primary" disabled>
Start deterministic replay
</button>
<button id="retryBtn" class="btn retry hidden">
Retry same shot
</button>
</div>
<div class="legend">
<span><i class="dot white"></i> Your prediction</span>
<span><i class="dot"></i> Contact</span>
<span><i class="dot red"></i> Pass point</span>
<span><i class="dot gray"></i> Previous trace</span>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Constants and deterministic shot
// -------------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
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.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x09131c);
scene.fog = new THREE.Fog(0x09131c, 13, 28);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
80
);
const cameraTarget = new THREE.Vector3(0, 0.72, 0);
const orbit = {
radius: 11.7,
theta: 0.53,
phi: 1.02,
minRadius: 8.0,
maxRadius: 16.0
};
function updateCamera() {
const s = Math.sin(orbit.phi);
camera.position.set(
cameraTarget.x + orbit.radius * s * Math.sin(orbit.theta),
cameraTarget.y + orbit.radius * Math.cos(orbit.phi),
cameraTarget.z + orbit.radius * s * Math.cos(orbit.theta)
);
camera.lookAt(cameraTarget);
}
updateCamera();
const hemi = new THREE.HemisphereLight(0xc9f4ff, 0x17212a, 1.65);
scene.add(hemi);
const key = new THREE.DirectionalLight(0xfff0cf, 3.1);
key.position.set(-4.5, 8.5, 5.5);
key.castShadow = true;
key.shadow.mapSize.set(2048, 2048);
key.shadow.camera.left = -7;
key.shadow.camera.right = 7;
key.shadow.camera.top = 7;
key.shadow.camera.bottom = -7;
key.shadow.camera.near = 1;
key.shadow.camera.far = 24;
key.shadow.bias = -0.00035;
scene.add(key);
const rim = new THREE.DirectionalLight(0x58e0c0, 1.25);
rim.position.set(5, 4, -6);
scene.add(rim);
const contactLight = new THREE.PointLight(0x58e0c0, 5, 8, 2);
contactLight.position.set(0, 2, -0.7);
scene.add(contactLight);
const BALL_RADIUS = 0.15;
const PADDLE_Z = -1.15;
const PREVIEW_Z = -1.06;
const REPLAY_DURATION = 3400;
const TRAIL_SAMPLES = 360;
const PADDLES = [
{ id: "A", name: "Left · narrow", x: -1.75, y: 1.15, w: 1.40, h: 1.55, color: 0xff8a65 },
{ id: "B", name: "Center · balanced", x: 0.00, y: 1.05, w: 1.90, h: 1.55, color: 0x58e0c0 },
{ id: "C", name: "Right · low", x: 1.85, y: 0.90, w: 1.65, h: 1.30, color: 0xffd166 }
];
function pathAt(t) {
return new THREE.Vector3(
-2.8 + 4.65 * t,
2.6 - 1.25 * t - 1.23 * t * t,
2.2 - 4.6 * t
);
}
const PADDLE_CROSS_T = (2.2 - PADDLE_Z) / 4.6;
function rectangleFor(def) {
return {
x0: def.x - def.w / 2,
x1: def.x + def.w / 2,
y0: def.y - def.h / 2,
y1: def.y + def.h / 2
};
}
function closestPointOnRectangle(point, rect) {
return new THREE.Vector3(
THREE.MathUtils.clamp(point.x, rect.x0, rect.x1),
THREE.MathUtils.clamp(point.y, rect.y0, rect.y1),
PADDLE_Z
);
}
function evaluatePlacement(index) {
const def = PADDLES[index];
const rect = rectangleFor(def);
const crossing = pathAt(PADDLE_CROSS_T);
const closest = closestPointOnRectangle(crossing, rect);
const distance = Math.hypot(crossing.x - closest.x, crossing.y - closest.y);
const hit = distance <= BALL_RADIUS;
const actual = hit ? closest.clone() : crossing.clone();
actual.z = PADDLE_Z;
return { hit, actual, distance, rect, def };
}
function pathForSelection(t, outcome) {
if (!outcome.hit || t <= PADDLE_CROSS_T) {
const p = pathAt(t);
p.y = Math.max(BALL_RADIUS, p.y);
return p;
}
const crossing = pathAt(PADDLE_CROSS_T);
const remaining = 1 - PADDLE_CROSS_T;
const outgoing = new THREE.Vector3(
4.65 * remaining,
-0.887,
4.6 * remaining
);
const u = (t - PADDLE_CROSS_T) / remaining;
return crossing.clone().addScaledVector(outgoing, u);
}
// -------------------------------------------------------------------------
// Procedural low-poly environment
// -------------------------------------------------------------------------
const floor = new THREE.Mesh(
new THREE.CircleGeometry(24, 48),
new THREE.MeshStandardMaterial({ color: 0x0d1921, roughness: 0.96, flatShading: true })
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -2.16;
floor.receiveShadow = true;
scene.add(floor);
const floorRing = new THREE.Mesh(
new THREE.RingGeometry(8.6, 8.68, 64),
new THREE.MeshBasicMaterial({
color: 0x315260,
transparent: true,
opacity: 0.2,
side: THREE.DoubleSide
})
);
floorRing.rotation.x = -Math.PI / 2;
floorRing.position.y = -2.145;
scene.add(floorRing);
const tableTop = new THREE.Mesh(
new THREE.BoxGeometry(8.8, 0.34, 5.6),
new THREE.MeshStandardMaterial({
color: 0x17464d,
roughness: 0.72,
metalness: 0.06,
flatShading: true
})
);
tableTop.position.y = -0.17;
tableTop.receiveShadow = true;
tableTop.castShadow = true;
scene.add(tableTop);
const tableFrame = new THREE.Mesh(
new THREE.BoxGeometry(9.05, 0.24, 5.85),
new THREE.MeshStandardMaterial({
color: 0x8f7047,
roughness: 0.65,
metalness: 0.12,
flatShading: true
})
);
tableFrame.position.y = -0.43;
tableFrame.castShadow = true;
scene.add(tableFrame);
const legMaterial = new THREE.MeshStandardMaterial({
color: 0x2b3e49,
roughness: 0.72,
metalness: 0.18,
flatShading: true
});
for (const x of [-3.65, 3.65]) {
for (const z of [-2.05, 2.05]) {
const leg = new THREE.Mesh(
new THREE.CylinderGeometry(0.16, 0.22, 1.55, 6),
legMaterial
);
leg.position.set(x, -1.35, z);
leg.castShadow = true;
scene.add(leg);
}
}
const trimMaterial = new THREE.MeshStandardMaterial({
color: 0x3b7072,
roughness: 0.55,
metalness: 0.12
});
for (const z of [-2.78, 2.78]) {
const strip = new THREE.Mesh(new THREE.BoxGeometry(8.8, 0.055, 0.055), trimMaterial);
strip.position.set(0, 0.015, z);
scene.add(strip);
}
for (const x of [-4.38, 4.38]) {
const strip = new THREE.Mesh(new THREE.BoxGeometry(0.055, 0.055, 5.6), trimMaterial);
strip.position.set(x, 0.015, 0);
scene.add(strip);
}
const gridVertices = [];
for (let x = -4.2; x <= 4.21; x += 0.6) {
gridVertices.push(x, 0.012, -2.72, x, 0.012, 2.72);
}
for (let z = -2.7; z <= 2.71; z += 0.6) {
gridVertices.push(-4.32, 0.012, z, 4.32, 0.012, z);
}
const tableGrid = new THREE.LineSegments(
new THREE.BufferGeometry().setAttribute(
"position",
new THREE.Float32BufferAttribute(gridVertices, 3)
),
new THREE.LineBasicMaterial({
color: 0x87c3bd,
transparent: true,
opacity: 0.07
})
);
scene.add(tableGrid);
const centerLine = new THREE.Mesh(
new THREE.BoxGeometry(0.035, 0.018, 5.25),
new THREE.MeshBasicMaterial({ color: 0xc1eee4, transparent: true, opacity: 0.2 })
);
centerLine.position.y = 0.025;
scene.add(centerLine);
// Small table target markings.
for (const radius of [0.55, 1.0]) {
const mark = new THREE.Mesh(
new THREE.RingGeometry(radius - 0.018, radius + 0.018, 40),
new THREE.MeshBasicMaterial({
color: 0x8ad8ca,
transparent: true,
opacity: 0.12,
side: THREE.DoubleSide
})
);
mark.rotation.x = -Math.PI / 2;
mark.position.set(0, 0.029, 1.1);
scene.add(mark);
}
function makeLabel(text, color = "#eafaf6", accent = null) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 128;
const ctx = labelCanvas.getContext("2d");
ctx.fillStyle = "rgba(7, 18, 27, 0.84)";
ctx.beginPath();
ctx.roundRect(8, 8, 496, 112, 24);
ctx.fill();
if (accent) {
ctx.fillStyle = accent;
ctx.fillRect(8, 8, 15, 112);
}
ctx.strokeStyle = "rgba(255,255,255,0.17)";
ctx.lineWidth = 3;
ctx.stroke();
ctx.font = "800 54px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = color;
ctx.fillText(text, 256, 66);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(1.45, 0.36, 1);
return sprite;
}
// Known launch point.
const start = pathAt(0);
const startBeacon = makeLabel("START · FIXED", "#f5fbf8", "#ffd166");
startBeacon.position.set(start.x - 0.08, start.y + 0.43, start.z);
scene.add(startBeacon);
const startRing = new THREE.Mesh(
new THREE.TorusGeometry(0.30, 0.018, 6, 32),
new THREE.MeshBasicMaterial({
color: 0xffd166,
transparent: true,
opacity: 0.65
})
);
startRing.position.copy(start);
scene.add(startRing);
const startFootRing = new THREE.Mesh(
new THREE.TorusGeometry(0.31, 0.018, 6, 32),
new THREE.MeshBasicMaterial({
color: 0xffd166,
transparent: true,
opacity: 0.36
})
);
startFootRing.rotation.x = Math.PI / 2;
startFootRing.position.set(start.x, 0.04, start.z);
scene.add(startFootRing);
const launchGuide = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([pathAt(0), pathAt(0.18)]),
new THREE.LineDashedMaterial({
color: 0xffd166,
transparent: true,
opacity: 0.24,
dashSize: 0.12,
gapSize: 0.12
})
);
launchGuide.computeLineDistances();
scene.add(launchGuide);
// -------------------------------------------------------------------------
// Paddle candidates
// -------------------------------------------------------------------------
const candidateGroups = [];
const candidateHitMeshes = [];
function makePaddle(def, index) {
const group = new THREE.Group();
group.position.set(def.x, def.y, PADDLE_Z);
const faceMaterial = new THREE.MeshStandardMaterial({
color: def.color,
emissive: def.color,
emissiveIntensity: 0.06,
roughness: 0.72,
metalness: 0.05,
transparent: true,
opacity: 0.18,
side: THREE.DoubleSide,
flatShading: true
});
const frameMaterial = new THREE.MeshStandardMaterial({
color: def.color,
emissive: def.color,
emissiveIntensity: 0.04,
roughness: 0.58,
metalness: 0.12,
transparent: true,
opacity: 0.28,
flatShading: true
});
const face = new THREE.Mesh(
new THREE.BoxGeometry(def.w, def.h, 0.12),
faceMaterial
);
face.castShadow = true;
face.receiveShadow = true;
face.userData.candidateIndex = index;
group.add(face);
candidateHitMeshes.push(face);
const top = new THREE.Mesh(
new THREE.BoxGeometry(def.w + 0.15, 0.075, 0.18),
frameMaterial
);
top.position.y = def.h / 2;
const bottom = new THREE.Mesh(
new THREE.BoxGeometry(def.w + 0.15, 0.075, 0.18),
frameMaterial
);
bottom.position.y = -def.h / 2;
const left = new THREE.Mesh(
new THREE.BoxGeometry(0.075, def.h + 0.12, 0.18),
frameMaterial
);
left.position.x = -def.w / 2;
const right = new THREE.Mesh(
new THREE.BoxGeometry(0.075, def.h + 0.12, 0.18),
frameMaterial
);
right.position.x = def.w / 2;
const handle = new THREE.Mesh(
new THREE.BoxGeometry(0.14, 0.67, 0.14),
frameMaterial
);
handle.position.y = -def.h / 2 - 0.33;
handle.rotation.z = index === 0 ? -0.13 : index === 2 ? 0.13 : 0;
group.add(top, bottom, left, right, handle);
const label = makeLabel(def.id, "#ffffff", `#${def.color.toString(16).padStart(6, "0")}`);
label.position.set(0, def.h / 2 + 0.34, 0.03);
label.scale.set(0.72, 0.18, 1);
group.add(label);
scene.add(group);
candidateGroups.push({ group, faceMaterial, frameMaterial, label });
}
PADDLES.forEach(makePaddle);
function updateCandidateVisuals() {
PADDLES.forEach((def, i) => {
const item = candidateGroups[i];
const isSelected = i === selectedIndex;
if (isSelected) {
item.faceMaterial.opacity = state === "select" ? 0.82 : 0.64;
item.frameMaterial.opacity = 0.98;
item.faceMaterial.emissiveIntensity = 0.24;
item.frameMaterial.emissiveIntensity = 0.18;
item.label.material.opacity = 1;
} else {
item.faceMaterial.opacity = state === "replay" || state === "result" ? 0.07 : 0.13;
item.frameMaterial.opacity = state === "replay" || state === "result" ? 0.12 : 0.24;
item.faceMaterial.emissiveIntensity = 0.025;
item.frameMaterial.emissiveIntensity = 0.025;
item.label.material.opacity = state === "replay" || state === "result" ? 0.35 : 0.72;
}
});
}
// Prediction plane and marker.
const predictionPlane = new THREE.Mesh(
new THREE.PlaneGeometry(5.3, 2.65),
new THREE.MeshBasicMaterial({
color: 0x58e0c0,
transparent: true,
opacity: 0.055,
side: THREE.DoubleSide,
depthWrite: false
})
);
predictionPlane.position.set(0, 1.475, PREVIEW_Z);
predictionPlane.visible = false;
scene.add(predictionPlane);
const planeEdge = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.PlaneGeometry(5.3, 2.65)),
new THREE.LineBasicMaterial({
color: 0x58e0c0,
transparent: true,
opacity: 0.34
})
);
planeEdge.position.copy(predictionPlane.position);
planeEdge.visible = false;
scene.add(planeEdge);
const predictionMarker = new THREE.Group();
const predictionCore = new THREE.Mesh(
new THREE.OctahedronGeometry(0.105, 0),
new THREE.MeshBasicMaterial({ color: 0xffffff })
);
const predictionRing = new THREE.Mesh(
new THREE.TorusGeometry(0.17, 0.018, 6, 32),
new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.8
})
);
predictionMarker.add(predictionCore, predictionRing);
predictionMarker.visible = false;
scene.add(predictionMarker);
// Ball.
const ball = new THREE.Mesh(
new THREE.IcosahedronGeometry(BALL_RADIUS, 1),
new THREE.MeshStandardMaterial({
color: 0xf9f871,
emissive: 0x8b6d14,
emissiveIntensity: 0.18,
roughness: 0.42,
metalness: 0.03,
flatShading: true
})
);
ball.position.copy(start);
ball.castShadow = true;
scene.add(ball);
const ballHalo = new THREE.Mesh(
new THREE.TorusGeometry(BALL_RADIUS + 0.055, 0.012, 6, 28),
new THREE.MeshBasicMaterial({
color: 0xf9f871,
transparent: true,
opacity: 0.35
})
);
ball.add(ballHalo);
const impactFlash = new THREE.Mesh(
new THREE.TorusGeometry(0.22, 0.025, 6, 36),
new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0,
depthWrite: false
})
);
impactFlash.position.set(0, 0, PADDLE_Z + 0.08);
impactFlash.visible = false;
scene.add(impactFlash);
// -------------------------------------------------------------------------
// UI state and scoring
// -------------------------------------------------------------------------
const candidateButtons = [...document.querySelectorAll(".candidate")];
const step1 = document.querySelector("#step1");
const step2 = document.querySelector("#step2");
const phaseLabel = document.querySelector("#phaseLabel");
const startBtn = document.querySelector("#startBtn");
const resetBtn = document.querySelector("#resetBtn");
const retryBtn = document.querySelector("#retryBtn");
const resultPanel = document.querySelector("#resultPanel");
const resultTitle = document.querySelector("#resultTitle");
const geometryScoreEl = document.querySelector("#geometryScore");
const predictionScoreEl = document.querySelector("#predictionScore");
const geometryBar = document.querySelector("#geometryBar");
const predictionBar = document.querySelector("#predictionBar");
const totalScoreEl = document.querySelector("#totalScore");
const bestScoreEl = document.querySelector("#bestScore");
const previousScoreEl = document.querySelector("#previousScore");
const deltaScoreEl = document.querySelector("#deltaScore");
const resultCopy = document.querySelector("#resultCopy");
const predictionReadout = document.querySelector("#predictionReadout");
const map = document.querySelector("#impactMap");
const mapPaddle = document.querySelector("#mapPaddle");
const mapPrediction = document.querySelector("#mapPrediction");
const mapActual = document.querySelector("#mapActual");
const toast = document.querySelector("#toast");
let toastTimer = 0;
let state = "select";
let selectedIndex = null;
let predictionPoint = null;
let currentOutcome = null;
let replayStart = 0;
let currentTrace = null;
let currentMarker = null;
let bestScore = 0;
let flashTriggered = false;
const traceRecords = [];
const markerRecords = [];
const attemptScores = [];
function notify(message, duration = 3800) {
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("show"), duration);
}
const MAP = {
x0: -2.65,
x1: 2.65,
y0: 0.15,
y1: 2.80,
left: 12,
right: 258,
top: 12,
bottom: 132
};
function mapX(x) {
return MAP.left + (x - MAP.x0) / (MAP.x1 - MAP.x0) * (MAP.right - MAP.left);
}
function mapY(y) {
return MAP.bottom - (y - MAP.y0) / (MAP.y1 - MAP.y0) * (MAP.bottom - MAP.top);
}
function updateHUD() {
candidateButtons.forEach((button, index) => {
button.classList.toggle("selected", index === selectedIndex);
button.disabled = state === "replay" || state === "result";
});
step1.classList.toggle("active", state === "select");
step1.classList.toggle("done", state !== "select");
step2.classList.toggle("active", state === "predict" || state === "ready");
step2.classList.toggle("done", state === "replay" || state === "result");
if (state === "select") phaseLabel.textContent = "Choose placement";
if (state === "predict") phaseLabel.textContent = "Place prediction";
if (state === "ready") phaseLabel.textContent = "Ready to replay";
if (state === "replay") phaseLabel.textContent = "Deterministic replay";
if (state === "result") phaseLabel.textContent = "Attempt complete";
startBtn.disabled = state !== "ready";
startBtn.textContent = state === "replay" ? "Replaying…" : "Start deterministic replay";
retryBtn.classList.toggle("hidden", state !== "result");
resetBtn.disabled = state === "replay";
}
function selectCandidate(index) {
if (state !== "select" && state !== "predict") return;
selectedIndex = index;
predictionPoint = null;
currentOutcome = null;
state = "predict";
const def = PADDLES[index];
mapPaddle.setAttribute("x", mapX(def.x - def.w / 2));
mapPaddle.setAttribute("y", mapY(def.y + def.h / 2));
mapPaddle.setAttribute("width", def.w / (MAP.x1 - MAP.x0) * (MAP.right - MAP.left));
mapPaddle.setAttribute("height", def.h / (MAP.y1 - MAP.y0) * (MAP.bottom - MAP.top));
mapPaddle.setAttribute("fill", `#${def.color.toString(16).padStart(6, "0")}`);
mapPaddle.setAttribute("stroke", `#${def.color.toString(16).padStart(6, "0")}`);
mapPaddle.setAttribute("visibility", "visible");
predictionPlane.visible = true;
planeEdge.visible = true;
predictionMarker.visible = false;
mapPrediction.setAttribute("visibility", "hidden");
mapActual.setAttribute("visibility", "hidden");
predictionReadout.textContent = "Not placed";
updateCandidateVisuals();
updateHUD();
notify(`${def.id} selected. Now place the predicted impact point on the map or glowing plane.`);
}
function setPrediction(point) {
if (state !== "predict" && state !== "ready") return;
if (selectedIndex === null) return;
point.x = THREE.MathUtils.clamp(point.x, MAP.x0, MAP.x1);
point.y = THREE.MathUtils.clamp(point.y, MAP.y0, MAP.y1);
point.z = PREVIEW_Z;
predictionPoint = point.clone();
predictionMarker.position.set(point.x, point.y, PREVIEW_Z + 0.045);
predictionMarker.visible = true;
mapPrediction.setAttribute("cx", mapX(point.x));
mapPrediction.setAttribute("cy", mapY(point.y));
mapPrediction.setAttribute("visibility", "visible");
predictionReadout.textContent = `x ${point.x.toFixed(2)}, y ${point.y.toFixed(2)}`;
state = "ready";
updateHUD();
}
function makeTrace(outcome) {
const positions = new Float32Array(TRAIL_SAMPLES * 3);
for (let i = 0; i < TRAIL_SAMPLES; i++) {
const t = i / (TRAIL_SAMPLES - 1);
const p = pathForSelection(t, outcome);
positions[i * 3] = p.x;
positions[i * 3 + 1] = p.y;
positions[i * 3 + 2] = p.z;
}
const geometry = new THREE.BufferGeometry();
const attribute = new THREE.BufferAttribute(positions, 3);
attribute.setUsage(THREE.DynamicDrawUsage);
geometry.setAttribute("position", attribute);
geometry.setDrawRange(0, 1);
const material = new THREE.LineBasicMaterial({
color: 0xb9fff0,
transparent: true,
opacity: 0.88,
depthWrite: false
});
const line = new THREE.Line(geometry, material);
line.frustumCulled = false;
scene.add(line);
return line;
}
function beginReplay() {
if (state !== "ready" || selectedIndex === null || !predictionPoint) return;
if (currentTrace) currentTrace.material.opacity = 0.13;
for (const marker of markerRecords) setMarkerOpacity(marker, 0.17);
currentOutcome = evaluatePlacement(selectedIndex);
currentTrace = makeTrace(currentOutcome);
traceRecords.push(currentTrace);
while (traceRecords.length > 4) {
const old = traceRecords.shift();
scene.remove(old);
old.geometry.dispose();
old.material.dispose();
}
state = "replay";
replayStart = performance.now();
flashTriggered = false;
impactFlash.visible = false;
resultPanel.classList.add("hidden");
predictionPlane.visible = false;
planeEdge.visible = false;
predictionMarker.scale.setScalar(0.88);
updateCandidateVisuals();
updateHUD();
notify("Fixed shot replaying. Score depends only on geometry and prediction accuracy.", 2600);
}
function setMarkerOpacity(marker, opacity) {
marker.traverse((object) => {
if (object.material) object.material.opacity = opacity;
});
}
function makeOutcomeMarker(outcome) {
const group = new THREE.Group();
group.position.copy(outcome.actual);
const color = outcome.hit ? 0x58e0c0 : 0xff786f;
const core = new THREE.Mesh(
new THREE.SphereGeometry(0.105, 12, 8),
new THREE.MeshBasicMaterial({ color })
);
core.position.z = 0.11;
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.19, 0.025, 7, 36),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.95,
depthWrite: false
})
);
ring.position.z = 0.12;
const label = makeLabel(
outcome.hit ? "CONTACT" : "PASS POINT",
outcome.hit ? "#dffff7" : "#ffe4e1",
outcome.hit ? "#58e0c0" : "#ff786f"
);
label.position.set(0, 0.32, 0.13);
label.scale.set(0.95, 0.24, 1);
group.add(core, ring, label);
scene.add(group);
return group;
}
function finishReplay() {
if (state !== "replay" || !currentOutcome) return;
state = "result";
ball.position.copy(pathForSelection(1, currentOutcome));
currentTrace.material.opacity = 0.48;
currentMarker = makeOutcomeMarker(currentOutcome);
markerRecords.push(currentMarker);
while (markerRecords.length > 4) {
const old = markerRecords.shift();
scene.remove(old);
}
const geometryPoints = currentOutcome.hit
? 60
: Math.round(
60 * Math.pow(
Math.max(0, 1 - currentOutcome.distance / 2.3),
1.45
)
);
const predictionDistance = Math.hypot(
predictionPoint.x - currentOutcome.actual.x,
predictionPoint.y - currentOutcome.actual.y
);
const predictionPoints = Math.round(
40 * Math.pow(
Math.max(0, 1 - predictionDistance / 2.5),
1.3
)
);
const total = geometryPoints + predictionPoints;
const previous = attemptScores.length ? attemptScores[attemptScores.length - 1] : null;
attemptScores.push(total);
bestScore = Math.max(bestScore, total);
resultTitle.textContent = currentOutcome.hit ? "Contact" : "Clean pass";
resultTitle.style.color = currentOutcome.hit ? "var(--cyan)" : "var(--red)";
geometryScoreEl.textContent = `${geometryPoints} / 60`;
predictionScoreEl.textContent = `${predictionPoints} / 40`;
geometryBar.style.width = `${(geometryPoints / 60) * 100}%`;
geometryBar.style.background = currentOutcome.hit ? "var(--cyan)" : "var(--amber)";
predictionBar.style.width = `${(predictionPoints / 40) * 100}%`;
totalScoreEl.textContent = total;
bestScoreEl.textContent = bestScore;
previousScoreEl.textContent = previous === null ? "—" : previous;
if (previous === null) {
deltaScoreEl.textContent = "First attempt";
} else {
const delta = total - previous;
deltaScoreEl.textContent = `${delta >= 0 ? "+" : ""}${delta} vs previous`;
deltaScoreEl.style.color = delta >= 0 ? "var(--cyan)" : "var(--red)";
}
const geometryCopy = currentOutcome.hit
? `The ball intersected the ${currentOutcome.def.w.toFixed(2)} × ${currentOutcome.def.h.toFixed(2)} valid surface.`
: `The ball passed ${currentOutcome.distance.toFixed(2)} units outside the selected valid surface.`;
resultCopy.textContent =
`${geometryCopy} Your marker was ${predictionDistance.toFixed(2)} units from the marked outcome.`;
mapActual.setAttribute("cx", mapX(currentOutcome.actual.x));
mapActual.setAttribute("cy", mapY(currentOutcome.actual.y));
mapActual.setAttribute("fill", currentOutcome.hit ? "#58e0c0" : "#ff786f");
mapActual.setAttribute("visibility", "visible");
resultPanel.classList.remove("hidden");
predictionMarker.scale.setScalar(1);
updateCandidateVisuals();
updateHUD();
notify(
currentOutcome.hit
? `Contact confirmed. Geometry 60/60; total ${total}.`
: `No intersection. The pass point is marked; total ${total}.`,
4300
);
}
function resetAttempt() {
if (state === "replay") return;
if (currentTrace) currentTrace.material.opacity = 0.13;
if (currentMarker) setMarkerOpacity(currentMarker, 0.17);
state = "select";
selectedIndex = null;
predictionPoint = null;
currentOutcome = null;
currentTrace = null;
currentMarker = null;
ball.position.copy(start);
ball.rotation.set(0, 0, 0);
predictionMarker.visible = false;
predictionPlane.visible = false;
planeEdge.visible = false;
mapPaddle.setAttribute("visibility", "hidden");
mapPrediction.setAttribute("visibility", "hidden");
mapActual.setAttribute("visibility", "hidden");
predictionReadout.textContent = "Not placed";
resultPanel.classList.add("hidden");
impactFlash.visible = false;
updateCandidateVisuals();
updateHUD();
notify("Same shot, new choice. The previous attempt remains as a faint comparison trace.");
}
// -------------------------------------------------------------------------
// Pointer interaction and direct camera controls
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const drag = {
active: false,
moved: false,
startX: 0,
startY: 0,
lastX: 0,
lastY: 0
};
function setPointer(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;
}
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
drag.active = true;
drag.moved = false;
drag.startX = drag.lastX = event.clientX;
drag.startY = drag.lastY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!drag.active) return;
const dx = event.clientX - drag.lastX;
const dy = event.clientY - drag.lastY;
if (
Math.abs(event.clientX - drag.startX) +
Math.abs(event.clientY - drag.startY) > 5
) {
drag.moved = true;
}
if (drag.moved) {
orbit.theta -= dx * 0.006;
orbit.phi = THREE.MathUtils.clamp(orbit.phi - dy * 0.004, 0.58, 1.34);
updateCamera();
}
drag.lastX = event.clientX;
drag.lastY = event.clientY;
});
canvas.addEventListener("pointerup", (event) => {
if (!drag.active) return;
drag.active = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
if (!drag.moved) handleSceneClick(event);
});
canvas.addEventListener("pointercancel", () => {
drag.active = false;
});
canvas.addEventListener("wheel", (event) => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius + event.deltaY * 0.008,
orbit.minRadius,
orbit.maxRadius
);
updateCamera();
}, { passive: false });
function handleSceneClick(event) {
if (state !== "select" && state !== "predict" && state !== "ready") return;
setPointer(event);
raycaster.setFromCamera(pointer, camera);
const candidateHits = raycaster.intersectObjects(candidateHitMeshes, false);
if (candidateHits.length) {
const index = candidateHits[0].object.userData.candidateIndex;
if (state === "select") {
selectCandidate(index);
} else if (index !== selectedIndex) {
selectCandidate(index);
} else {
const point = new THREE.Vector3();
const plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), -PREVIEW_Z);
if (raycaster.ray.intersectPlane(plane, point)) setPrediction(point);
}
return;
}
if (state === "predict" || state === "ready") {
const point = new THREE.Vector3();
const plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), -PREVIEW_Z);
if (raycaster.ray.intersectPlane(plane, point)) setPrediction(point);
}
}
// 2D impact-map controls.
function mapEventToWorld(event) {
const rect = map.getBoundingClientRect();
const x = (event.clientX - rect.left) / rect.width * 270;
const y = (event.clientY - rect.top) / rect.height * 145;
return new THREE.Vector3(
MAP.x0 + (x - MAP.left) / (MAP.right - MAP.left) * (MAP.x1 - MAP.x0),
MAP.y1 - (y - MAP.top) / (MAP.bottom - MAP.top) * (MAP.y1 - MAP.y0),
PREVIEW_Z
);
}
map.addEventListener("pointerdown", (event) => {
if (state !== "predict" && state !== "ready") return;
event.preventDefault();
setPrediction(mapEventToWorld(event));
});
map.addEventListener("keydown", (event) => {
if (state !== "predict" && state !== "ready") return;
const step = event.shiftKey ? 0.25 : 0.08;
const base = predictionPoint
? predictionPoint.clone()
: new THREE.Vector3(PADDLES[selectedIndex].x, PADDLES[selectedIndex].y, PREVIEW_Z);
if (event.key === "ArrowLeft") base.x -= step;
else if (event.key === "ArrowRight") base.x += step;
else if (event.key === "ArrowUp") base.y += step;
else if (event.key === "ArrowDown") base.y -= step;
else return;
event.preventDefault();
setPrediction(base);
});
candidateButtons.forEach((button) => {
button.addEventListener("click", () => {
selectCandidate(Number(button.dataset.index));
});
});
startBtn.addEventListener("click", beginReplay);
resetBtn.addEventListener("click", resetAttempt);
retryBtn.addEventListener("click", resetAttempt);
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
window.addEventListener("resize", resize);
renderer.setAnimationLoop(() => {
if (state === "replay" && currentOutcome) {
const elapsed = performance.now() - replayStart;
const t = THREE.MathUtils.clamp(elapsed / REPLAY_DURATION, 0, 1);
ball.position.copy(pathForSelection(t, currentOutcome));
ball.rotation.x += 0.045;
ball.rotation.z += 0.028;
const count = Math.max(2, Math.floor(t * (TRAIL_SAMPLES - 1)) + 1);
currentTrace.geometry.setDrawRange(0, count);
predictionMarker.rotation.z += 0.015;
predictionMarker.scale.setScalar(0.88 + Math.sin(elapsed * 0.008) * 0.025);
if (!flashTriggered && t >= PADDLE_CROSS_T) {
flashTriggered = true;
const crossing = pathAt(PADDLE_CROSS_T);
impactFlash.position.set(crossing.x, crossing.y, PADDLE_Z + 0.08);
impactFlash.visible = true;
impactFlash.material.color.set(currentOutcome.hit ? 0x58e0c0 : 0xff786f);
}
if (impactFlash.visible) {
const flashAge = Math.max(0, (t - PADDLE_CROSS_T) / 0.12);
impactFlash.scale.setScalar(1 + flashAge * 3.4);
impactFlash.material.opacity = Math.max(0, 0.8 * (1 - flashAge));
}
if (t >= 1) finishReplay();
} else {
predictionRing.rotation.z += 0.01;
startRing.rotation.z += 0.006;
}
renderer.render(scene, camera);
});
updateCandidateVisuals();
updateHUD();
notify("Choose one of the three paddle placements. The ball is frozen at the known start point.", 5200);
</script>
</body>
</html>
```