Prompt specification
Build or customize the Three.js 3D scene "Design a New Step Pattern" 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: Design a New Step Pattern
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/design-a-new-step-pattern-x3620
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing hopscotch and patterned foot placement. Create a puzzle where users arrange numbered tiles and support symbols. Replay a schematic avatar and reject transitions exceeding the explicitly declared toy jump range. Low-poly.
Working Three.js Starter (design-a-new-step-pattern-x3620):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hop / 07 — Pattern Lock</title>
<style>
:root {
color-scheme: dark;
--bg: #09111d;
--panel: rgba(13, 24, 39, 0.92);
--line: rgba(153, 190, 220, 0.18);
--text: #e8f2fa;
--muted: #91a8bb;
--cyan: #52e3d0;
--orange: #ff9c62;
--violet: #ae9cff;
--red: #ff6174;
--yellow: #ffd166;
}
* {
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;
}
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.ui {
position: fixed;
inset: 0;
pointer-events: none;
}
.topbar {
position: absolute;
top: 22px;
left: 24px;
right: 24px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 20px;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
text-shadow: 0 2px 18px rgba(0, 0, 0, 0.5);
}
.brand-mark {
width: 48px;
height: 48px;
display: grid;
place-items: center;
border: 1px solid rgba(82, 227, 208, 0.55);
background: rgba(9, 20, 34, 0.76);
color: var(--cyan);
font-size: 24px;
font-weight: 900;
transform: rotate(-4deg);
box-shadow: inset 0 0 22px rgba(82, 227, 208, 0.08);
}
.brand h1 {
margin: 0;
font-size: 21px;
line-height: 1;
letter-spacing: 0.13em;
font-weight: 850;
}
.brand p {
margin: 7px 0 0;
color: var(--muted);
font-size: 11px;
letter-spacing: 0.19em;
text-transform: uppercase;
}
.range-pill {
pointer-events: auto;
min-width: 190px;
padding: 11px 15px;
border: 1px solid rgba(255, 156, 98, 0.42);
background: rgba(17, 25, 37, 0.85);
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.22);
backdrop-filter: blur(12px);
}
.range-pill span,
.range-pill small {
display: block;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.range-pill strong {
display: block;
margin: 2px 0;
color: var(--orange);
font-size: 25px;
letter-spacing: 0.02em;
}
.panel {
pointer-events: auto;
position: absolute;
top: 98px;
right: 24px;
width: min(330px, calc(100vw - 48px));
max-height: calc(100vh - 185px);
overflow: auto;
padding: 18px;
border: 1px solid var(--line);
background: var(--panel);
box-shadow: 0 22px 70px rgba(0, 0, 0, 0.38);
backdrop-filter: blur(16px);
scrollbar-width: thin;
scrollbar-color: #35506a transparent;
}
.eyebrow {
margin: 0 0 7px;
color: var(--cyan);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.2em;
text-transform: uppercase;
}
.panel h2 {
margin: 0;
font-size: 22px;
letter-spacing: -0.025em;
}
.objective {
margin: 10px 0 17px;
color: #afc0cf;
font-size: 12px;
line-height: 1.55;
}
.objective b {
color: var(--text);
}
.section {
margin-top: 17px;
padding-top: 15px;
border-top: 1px solid var(--line);
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.17em;
text-transform: uppercase;
}
.section-title span:last-child {
color: #60788c;
font-size: 8px;
}
.tile-grid {
display: grid;
grid-template-columns: repeat(7, 1fr);
gap: 6px;
}
.tile-btn {
position: relative;
min-width: 0;
height: 52px;
padding: 5px 2px;
border: 1px solid rgba(145, 168, 187, 0.25);
border-radius: 0;
background: rgba(255, 255, 255, 0.035);
color: var(--text);
cursor: pointer;
transition: transform 120ms ease, border-color 120ms ease, background 120ms ease;
}
.tile-btn:hover {
transform: translateY(-2px);
border-color: var(--tile);
background: color-mix(in srgb, var(--tile) 14%, transparent);
}
.tile-btn.selected {
transform: translateY(-2px);
border-color: var(--tile);
background: color-mix(in srgb, var(--tile) 24%, transparent);
box-shadow: 0 0 0 1px var(--tile);
}
.tile-number {
display: block;
color: var(--tile);
font-size: 19px;
font-weight: 900;
line-height: 1;
}
.tile-state {
display: block;
margin-top: 5px;
overflow: hidden;
color: var(--muted);
font-size: 6px;
font-weight: 750;
letter-spacing: 0.06em;
text-overflow: ellipsis;
white-space: nowrap;
}
.support-list {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.support-btn {
display: grid;
grid-template-columns: 31px 1fr;
grid-template-rows: 1fr 1fr;
column-gap: 9px;
align-items: center;
min-height: 59px;
padding: 8px;
border: 1px solid rgba(145, 168, 187, 0.24);
background: rgba(255, 255, 255, 0.035);
color: var(--text);
text-align: left;
cursor: pointer;
}
.support-btn:hover,
.support-btn.selected {
border-color: var(--support);
background: color-mix(in srgb, var(--support) 13%, transparent);
}
.support-icon {
grid-row: 1 / 3;
display: grid;
place-items: center;
width: 31px;
height: 31px;
border: 1px solid var(--support);
color: var(--support);
font-size: 21px;
font-weight: 900;
}
.support-name {
align-self: end;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.support-state {
align-self: start;
margin-top: 2px;
color: var(--muted);
font-size: 8px;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.action {
min-height: 40px;
border: 1px solid rgba(145, 168, 187, 0.28);
background: rgba(255, 255, 255, 0.045);
color: var(--text);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.12em;
text-transform: uppercase;
cursor: pointer;
transition: transform 120ms ease, border-color 120ms ease, background 120ms ease;
}
.action:hover {
transform: translateY(-1px);
border-color: var(--cyan);
background: rgba(82, 227, 208, 0.1);
}
.action.primary {
grid-column: 1 / 3;
border-color: var(--cyan);
background: var(--cyan);
color: #08201d;
}
.action.primary:hover {
background: #7aefdf;
}
.action:disabled {
cursor: wait;
opacity: 0.55;
transform: none;
}
.checklist {
display: grid;
gap: 7px;
}
.check-row {
display: grid;
grid-template-columns: 9px 1fr auto;
align-items: center;
gap: 8px;
color: #b9c8d5;
font-size: 10px;
}
.check-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: #506476;
}
.check-row b {
color: #70879a;
font-size: 8px;
letter-spacing: 0.1em;
}
.check-row[data-state="pass"] .check-dot {
background: var(--cyan);
box-shadow: 0 0 9px rgba(82, 227, 208, 0.65);
}
.check-row[data-state="pass"] b {
color: var(--cyan);
}
.check-row[data-state="fail"] .check-dot {
background: var(--red);
box-shadow: 0 0 9px rgba(255, 97, 116, 0.6);
}
.check-row[data-state="fail"] b {
color: var(--red);
}
.foot-pattern {
display: grid;
grid-template-columns: repeat(8, 1fr);
gap: 4px;
}
.foot-step {
display: grid;
place-items: center;
height: 30px;
border: 1px solid rgba(145, 168, 187, 0.18);
color: var(--step);
font-size: 11px;
font-weight: 900;
background: color-mix(in srgb, var(--step) 9%, transparent);
}
.microcopy {
margin: 9px 0 0;
color: #73899c;
font-size: 9px;
line-height: 1.5;
}
.status {
pointer-events: auto;
position: absolute;
left: 24px;
bottom: 24px;
width: min(600px, calc(100vw - 48px));
min-height: 54px;
display: grid;
grid-template-columns: 12px 1fr;
align-items: center;
gap: 12px;
padding: 12px 16px;
border: 1px solid var(--line);
background: rgba(10, 20, 33, 0.9);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.3);
backdrop-filter: blur(14px);
}
.status-dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 12px rgba(82, 227, 208, 0.65);
}
.status[data-tone="error"] .status-dot {
background: var(--red);
box-shadow: 0 0 12px rgba(255, 97, 116, 0.65);
}
.status[data-tone="warn"] .status-dot {
background: var(--yellow);
box-shadow: 0 0 12px rgba(255, 209, 102, 0.6);
}
#statusText {
color: #c6d4df;
font-size: 11px;
line-height: 1.45;
}
.camera-hint {
position: absolute;
left: 24px;
bottom: 89px;
color: #71889c;
font-size: 9px;
letter-spacing: 0.06em;
}
@media (max-width: 760px) {
.topbar {
top: 14px;
left: 14px;
right: 14px;
}
.brand h1 {
font-size: 17px;
}
.brand p {
display: none;
}
.range-pill {
min-width: 145px;
padding: 8px 11px;
}
.range-pill strong {
font-size: 20px;
}
.panel {
top: auto;
right: 10px;
bottom: 10px;
width: calc(100vw - 20px);
max-height: 43vh;
padding: 14px;
}
.status {
left: 10px;
bottom: calc(43vh + 20px);
width: calc(100vw - 20px);
}
.camera-hint {
display: none;
}
.tile-btn {
height: 45px;
}
}
</style>
</head>
<body>
<div id="viewport"></div>
<div class="ui">
<header class="topbar">
<div class="brand">
<div class="brand-mark">H</div>
<div>
<h1>HOP / 07</h1>
<p>Pattern lock · spatial sequencing toy</p>
</div>
</div>
<div class="range-pill" aria-label="Declared toy jump range">
<span>Toy jump range</span>
<strong>3.20 u</strong>
<small>Measured on ground plane XZ</small>
</div>
</header>
<aside class="panel">
<p class="eyebrow">Objective 07</p>
<h2>Build a legal hop chain</h2>
<p class="objective">
Arrange numbered tiles into a continuous <b>1 → 7</b> route.
Every transition, including <b>START → 1</b> and <b>7 → GOAL</b>,
must be no farther than <b>3.20 world units</b>.
Supports mark required landings; they never extend the jump range.
</p>
<section class="section">
<div class="section-title">
<span>Numbered tiles</span>
<span>Click to select</span>
</div>
<div id="tileInventory" class="tile-grid"></div>
<p class="microcopy">
Select a tile, then select another tile to swap. Select a tile and an
empty pad to move it.
</p>
</section>
<section class="section">
<div class="section-title">
<span>Support symbols</span>
<span>Place on a tile</span>
</div>
<div class="support-list">
<button class="support-btn" id="springButton" style="--support: var(--yellow)">
<span class="support-icon">⌁</span>
<span class="support-name">Spring</span>
<span class="support-state" id="springState">Required on 4</span>
</button>
<button class="support-btn" id="braceButton" style="--support: var(--violet)">
<span class="support-icon">Π</span>
<span class="support-name">Brace</span>
<span class="support-state" id="braceState">Required on 6</span>
</button>
</div>
<p class="microcopy">
Select a support, then click its destination tile. Selecting the same
tile again removes that support.
</p>
</section>
<section class="section">
<div class="section-title">
<span>Validation</span>
<span>Strict toy limits</span>
</div>
<div class="checklist">
<div class="check-row" id="rangeCheck">
<span class="check-dot"></span>
<span>All eight transitions ≤ 3.20 u</span>
<b data-state="pending">PENDING</b>
</div>
<div class="check-row" id="springCheck">
<span class="check-dot"></span>
<span>Spring support on tile 4</span>
<b data-state="pending">PENDING</b>
</div>
<div class="check-row" id="braceCheck">
<span class="check-dot"></span>
<span>Brace support on tile 6</span>
<b data-state="pending">PENDING</b>
</div>
</div>
</section>
<section class="section">
<div class="section-title">
<span>Foot pattern</span>
<span>Automatic alternation</span>
</div>
<div class="foot-pattern" id="footPattern"></div>
<p class="microcopy">
The replay always alternates left and right feet. Foot markers on the
tiles show the required landing pattern.
</p>
</section>
<section class="section actions">
<button id="replayButton" class="action primary">Replay avatar</button>
<button id="resetButton" class="action">Reset layout</button>
<button id="cameraButton" class="action">Reset camera</button>
</section>
</aside>
<div id="status" class="status" data-tone="info" role="status" aria-live="polite">
<span class="status-dot"></span>
<span id="statusText">Arrange the tiles, place both supports, then replay the schematic avatar.</span>
</div>
<div class="camera-hint">
Drag empty space to orbit · wheel to zoom · R to replay · C to reset camera
</div>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Core puzzle constants
// -------------------------------------------------------------------------
const JUMP_RANGE = 3.20;
const PAD_COUNT = 9;
const PAD_SPACING = 2.05;
const TILE_COUNT = 7;
const GROUND_Y = 0;
const START = new THREE.Vector3(0, 0, 4.15);
const GOAL = new THREE.Vector3(0, 0, -4.15);
const TILE_COLORS = [
0x52e3d0,
0xff9c62,
0xae9cff,
0xffd166,
0x6db9ff,
0xff7f9e,
0x8ee36b
];
const FOOT_COLORS = {
L: 0xff9c62,
R: 0x52e3d0
};
const INITIAL_LAYOUT = {
1: 4,
2: 0,
3: 3,
4: 2,
5: 5,
6: 6,
7: 7
};
// -------------------------------------------------------------------------
// Renderer, scene, lighting
// -------------------------------------------------------------------------
const viewport = document.getElementById("viewport");
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
viewport.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x09111d);
scene.fog = new THREE.Fog(0x09111d, 18, 38);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraTarget = new THREE.Vector3(0, 0.25, 0);
let cameraTheta = 0.48;
let cameraPhi = 0.86;
let cameraRadius = 14.2;
function updateCamera() {
const sinPhi = Math.sin(cameraPhi);
camera.position.set(
cameraTarget.x + cameraRadius * sinPhi * Math.sin(cameraTheta),
cameraTarget.y + cameraRadius * Math.cos(cameraPhi),
cameraTarget.z + cameraRadius * sinPhi * Math.cos(cameraTheta)
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraTheta = 0.48;
cameraPhi = 0.86;
cameraRadius = 14.2;
updateCamera();
}
updateCamera();
scene.add(new THREE.HemisphereLight(0xb9ddff, 0x1d2535, 2.0));
const keyLight = new THREE.DirectionalLight(0xfff0d8, 3.1);
keyLight.position.set(5, 11, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -10;
keyLight.shadow.camera.right = 10;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 30;
keyLight.shadow.bias = -0.0007;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x53cfff, 1.4);
rimLight.position.set(-7, 5, -8);
scene.add(rimLight);
// -------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------
function padPosition(index) {
const row = Math.floor(index / 3);
const col = index % 3;
return new THREE.Vector3(
(col - 1) * PAD_SPACING,
0,
(1 - row) * PAD_SPACING
);
}
function makeTextTexture(text, options = {}) {
const canvas = document.createElement("canvas");
canvas.width = options.width || 256;
canvas.height = options.height || 256;
const ctx = canvas.getContext("2d");
if (options.background) {
ctx.fillStyle = options.background;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
if (options.border) {
ctx.strokeStyle = options.border;
ctx.lineWidth = options.borderWidth || 8;
ctx.strokeRect(
options.borderWidth || 8,
options.borderWidth || 8,
canvas.width - 2 * (options.borderWidth || 8),
canvas.height - 2 * (options.borderWidth || 8)
);
}
ctx.fillStyle = options.color || "#ffffff";
ctx.font = options.font || "900 150px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, canvas.width / 2, canvas.height / 2);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(4, renderer.capabilities.getMaxAnisotropy());
return texture;
}
function makeTextSprite(text, color, background = "rgba(8,18,31,0.86)") {
const texture = makeTextTexture(text, {
width: 512,
height: 128,
color,
background,
border: color,
borderWidth: 5,
font: "900 55px Arial"
});
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
toneMapped: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(1.65, 0.42, 1);
sprite.renderOrder = 20;
return sprite;
}
function cylinderBetween(a, b, radius, material, radialSegments = 6) {
const direction = new THREE.Vector3().subVectors(b, a);
const length = direction.length();
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radius, radius, length, radialSegments),
material
);
mesh.position.copy(a).add(b).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
return mesh;
}
// -------------------------------------------------------------------------
// Board, pads, labels and decorative range scale
// -------------------------------------------------------------------------
const boardGroup = new THREE.Group();
scene.add(boardGroup);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(80, 80),
new THREE.MeshStandardMaterial({
color: 0x0b1522,
roughness: 0.96,
metalness: 0.02
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.28;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(40, 40, 0x26384a, 0x152536);
grid.position.y = -0.27;
grid.material.transparent = true;
grid.material.opacity = 0.35;
scene.add(grid);
const board = new THREE.Mesh(
new THREE.BoxGeometry(8.55, 0.26, 8.55),
new THREE.MeshStandardMaterial({
color: 0x142337,
roughness: 0.88,
metalness: 0.08,
flatShading: true
})
);
board.position.y = -0.13;
board.receiveShadow = true;
board.castShadow = true;
boardGroup.add(board);
const boardEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(board.geometry),
new THREE.LineBasicMaterial({
color: 0x35526c,
transparent: true,
opacity: 0.75
})
);
boardEdges.position.copy(board.position);
boardGroup.add(boardEdges);
const clickables = [];
const padMeshes = [];
for (let i = 0; i < PAD_COUNT; i++) {
const position = padPosition(i);
const pad = new THREE.Mesh(
new THREE.BoxGeometry(1.68, 0.09, 1.68),
new THREE.MeshStandardMaterial({
color: 0x17283c,
roughness: 0.86,
metalness: 0.06,
flatShading: true
})
);
pad.position.set(position.x, 0.045, position.z);
pad.receiveShadow = true;
pad.userData.padIndex = i;
clickables.push(pad);
padMeshes.push(pad);
boardGroup.add(pad);
const padEdge = new THREE.LineSegments(
new THREE.EdgesGeometry(pad.geometry),
new THREE.LineBasicMaterial({
color: 0x28455e,
transparent: true,
opacity: 0.8
})
);
padEdge.position.copy(pad.position);
boardGroup.add(padEdge);
}
function createEndpoint(position, label, color) {
const group = new THREE.Group();
group.position.set(position.x, 0, position.z);
const base = new THREE.Mesh(
new THREE.CylinderGeometry(0.72, 0.78, 0.12, 8),
new THREE.MeshStandardMaterial({
color,
roughness: 0.62,
metalness: 0.1,
flatShading: true
})
);
base.position.y = 0.06;
base.castShadow = true;
base.receiveShadow = true;
group.add(base);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.86, 0.035, 6, 32),
new THREE.MeshBasicMaterial({ color })
);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.14;
group.add(ring);
const text = makeTextSprite(label, `#${new THREE.Color(color).getHexString()}`);
text.position.y = 0.88;
group.add(text);
boardGroup.add(group);
return group;
}
createEndpoint(START, "START", 0xff9c62);
createEndpoint(GOAL, "GOAL", 0x52e3d0);
const scaleMaterial = new THREE.MeshBasicMaterial({
color: 0xff9c62,
transparent: true,
opacity: 0.8
});
const scaleStart = new THREE.Vector3(2.75, 0.11, 2.85);
const scaleEnd = new THREE.Vector3(
scaleStart.x + JUMP_RANGE,
scaleStart.y,
scaleStart.z
);
boardGroup.add(cylinderBetween(scaleStart, scaleEnd, 0.025, scaleMaterial));
for (const point of [scaleStart, scaleEnd]) {
boardGroup.add(
cylinderBetween(
point.clone().add(new THREE.Vector3(0, 0, -0.17)),
point.clone().add(new THREE.Vector3(0, 0, 0.17)),
0.025,
scaleMaterial
)
);
}
const rangeLabel = makeTextSprite("MAX 3.20 u", "#ff9c62");
rangeLabel.position.set(scaleStart.x + JUMP_RANGE / 2, 0.72, scaleStart.z);
boardGroup.add(rangeLabel);
// -------------------------------------------------------------------------
// Tiles, support symbols and footprint markers
// -------------------------------------------------------------------------
const tileObjects = {};
const selectionMaterial = new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.95
});
const supportMaterials = {
spring: new THREE.MeshStandardMaterial({
color: 0xffd166,
roughness: 0.55,
metalness: 0.25,
flatShading: true
}),
brace: new THREE.MeshStandardMaterial({
color: 0xae9cff,
roughness: 0.58,
metalness: 0.18,
flatShading: true
})
};
const supportGeometries = {
springRing: new THREE.TorusGeometry(0.16, 0.035, 5, 12),
springPlate: new THREE.BoxGeometry(0.42, 0.055, 0.42),
braceTop: new THREE.BoxGeometry(0.43, 0.065, 0.09),
braceLeg: new THREE.BoxGeometry(0.065, 0.32, 0.09)
};
const footSoleGeometry = new THREE.SphereGeometry(1, 7, 4);
const footToeGeometry = new THREE.SphereGeometry(0.038, 6, 4);
function createFootMarker(number) {
const foot = number % 2 === 1 ? "L" : "R";
const color = FOOT_COLORS[foot];
const group = new THREE.Group();
group.position.set(0.46, 0.405, 0.02);
const sole = new THREE.Mesh(
footSoleGeometry,
new THREE.MeshBasicMaterial({ color })
);
sole.scale.set(0.085, 0.028, 0.19);
sole.position.z = -0.025;
group.add(sole);
for (let i = 0; i < 3; i++) {
const toe = new THREE.Mesh(
footToeGeometry,
new THREE.MeshBasicMaterial({ color })
);
toe.position.set((i - 1) * 0.052, 0.005, -0.16 - (i === 1 ? 0.015 : 0));
group.add(toe);
}
const label = makeTextSprite(foot, `#${new THREE.Color(color).getHexString()}`);
label.scale.set(0.34, 0.16, 1);
label.position.set(0, 0.31, 0.07);
group.add(label);
return group;
}
function makeSupport(symbol) {
const group = new THREE.Group();
if (symbol === "spring") {
for (let i = 0; i < 3; i++) {
const ring = new THREE.Mesh(
supportGeometries.springRing,
supportMaterials.spring
);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.54 + i * 0.1;
ring.castShadow = true;
group.add(ring);
}
const plate = new THREE.Mesh(
supportGeometries.springPlate,
supportMaterials.spring
);
plate.position.y = 0.85;
plate.castShadow = true;
group.add(plate);
} else {
const top = new THREE.Mesh(
supportGeometries.braceTop,
supportMaterials.brace
);
top.position.y = 0.79;
top.castShadow = true;
group.add(top);
for (const x of [-0.18, 0.18]) {
const leg = new THREE.Mesh(
supportGeometries.braceLeg,
supportMaterials.brace
);
leg.position.set(x, 0.63, 0);
leg.castShadow = true;
group.add(leg);
}
}
return group;
}
for (let number = 1; number <= TILE_COUNT; number++) {
const color = TILE_COLORS[number - 1];
const group = new THREE.Group();
const bodyMaterial = new THREE.MeshStandardMaterial({
color,
roughness: 0.68,
metalness: 0.08,
flatShading: true,
emissive: 0x000000
});
const body = new THREE.Mesh(
new THREE.CylinderGeometry(0.72, 0.78, 0.24, 8),
bodyMaterial
);
body.position.y = 0.23;
body.castShadow = true;
body.receiveShadow = true;
body.userData.tileNumber = number;
clickables.push(body);
group.add(body);
const numberTexture = makeTextTexture(String(number), {
color: "#102030",
font: "900 154px Arial"
});
const numberPlane = new THREE.Mesh(
new THREE.PlaneGeometry(0.88, 0.88),
new THREE.MeshBasicMaterial({
map: numberTexture,
transparent: true,
depthWrite: false,
toneMapped: false,
polygonOffset: true,
polygonOffsetFactor: -1
})
);
numberPlane.rotation.x = -Math.PI / 2;
numberPlane.position.y = 0.356;
numberPlane.renderOrder = 3;
group.add(numberPlane);
const selectionRing = new THREE.Mesh(
new THREE.TorusGeometry(0.86, 0.035, 6, 32),
selectionMaterial
);
selectionRing.rotation.x = Math.PI / 2;
selectionRing.position.y = 0.39;
selectionRing.visible = false;
group.add(selectionRing);
const supportAnchor = new THREE.Group();
supportAnchor.position.x = -0.43;
group.add(supportAnchor);
group.add(createFootMarker(number));
boardGroup.add(group);
tileObjects[number] = {
group,
body,
bodyMaterial,
numberPlane,
selectionRing,
supportAnchor
};
}
// -------------------------------------------------------------------------
// Puzzle state
// -------------------------------------------------------------------------
let tilePad = {};
let padTile = Array(PAD_COUNT).fill(null);
let supportByTile = {};
let selectedTile = null;
let selectedSupport = null;
let lastValidation = null;
let pathSegments = [];
const pathGroup = new THREE.Group();
scene.add(pathGroup);
let animation = null;
let invalidFlashTimer = null;
// -------------------------------------------------------------------------
// UI
// -------------------------------------------------------------------------
const tileButtons = {};
const tileInventory = document.getElementById("tileInventory");
for (let number = 1; number <= TILE_COUNT; number++) {
const button = document.createElement("button");
button.className = "tile-btn";
button.style.setProperty("--tile", `#${new THREE.Color(TILE_COLORS[number - 1]).getHexString()}`);
button.setAttribute("aria-label", `Select numbered tile ${number}`);
button.innerHTML = `
<span class="tile-number">${number}</span>
<span class="tile-state">ON BOARD</span>
`;
button.addEventListener("click", () => {
selectedSupport = null;
selectedTile = selectedTile === number ? null : number;
syncSelection();
setStatus(
selectedTile === null
? "Selection cleared."
: `Tile ${number} selected. Select another tile to swap, or an empty pad to move it.`,
"info"
);
});
tileInventory.appendChild(button);
tileButtons[number] = button;
}
const springButton = document.getElementById("springButton");
const braceButton = document.getElementById("braceButton");
const springState = document.getElementById("springState");
const braceState = document.getElementById("braceState");
const replayButton = document.getElementById("replayButton");
const resetButton = document.getElementById("resetButton");
const cameraButton = document.getElementById("cameraButton");
const statusElement = document.getElementById("status");
const statusText = document.getElementById("statusText");
const footPattern = document.getElementById("footPattern");
for (let i = 0; i < 8; i++) {
const foot = i % 2 === 0 ? "L" : "R";
const step = document.createElement("div");
step.className = "foot-step";
step.style.setProperty("--step", `#${new THREE.Color(FOOT_COLORS[foot]).getHexString()}`);
step.textContent = foot;
step.title = `Hop ${i + 1}: ${foot} foot`;
footPattern.appendChild(step);
}
function setStatus(message, tone = "info") {
statusText.textContent = message;
statusElement.dataset.tone = tone;
}
function findSupportTile(symbol) {
for (const [number, placedSymbol] of Object.entries(supportByTile)) {
if (placedSymbol === symbol) return Number(number);
}
return null;
}
function setCheck(element, state, label) {
element.dataset.state = state;
element.querySelector("b").textContent = label;
}
function updateChecklist() {
const rangeState = element => {
if (!lastValidation) {
setCheck(element, "pending", "PENDING");
} else if (lastValidation.kind === "range") {
setCheck(element, "fail", "REJECTED");
} else if (lastValidation.rangeOk) {
setCheck(element, "pass", "PASS");
} else {
setCheck(element, "pending", "PENDING");
}
};
rangeState(document.getElementById("rangeCheck"));
const springTile = findSupportTile("spring");
const braceTile = findSupportTile("brace");
setCheck(
document.getElementById("springCheck"),
springTile === null ? "pending" : springTile === 4 ? "pass" : "fail",
springTile === null ? "PENDING" : springTile === 4 ? "PASS" : `ON ${springTile}`
);
setCheck(
document.getElementById("braceCheck"),
braceTile === null ? "pending" : braceTile === 6 ? "pass" : "fail",
braceTile === null ? "PENDING" : braceTile === 6 ? "PASS" : `ON ${braceTile}`
);
}
function syncSelection() {
for (let number = 1; number <= TILE_COUNT; number++) {
const button = tileButtons[number];
const placed = tilePad[number] !== null && tilePad[number] !== undefined;
button.classList.toggle("selected", selectedTile === number);
button.querySelector(".tile-state").textContent = placed
? `PAD ${tilePad[number] + 1}`
: "TRAY";
}
springButton.classList.toggle("selected", selectedSupport === "spring");
braceButton.classList.toggle("selected", selectedSupport === "brace");
const springTile = findSupportTile("spring");
const braceTile = findSupportTile("brace");
springState.textContent = springTile === null ? "Required on 4" : `On tile ${springTile}`;
braceState.textContent = braceTile === null ? "Required on 6" : `On tile ${braceTile}`;
for (let number = 1; number <= TILE_COUNT; number++) {
tileObjects[number].selectionRing.visible = selectedTile === number;
}
}
// -------------------------------------------------------------------------
// Layout and path rendering
// -------------------------------------------------------------------------
function refreshSupports() {
for (let number = 1; number <= TILE_COUNT; number++) {
const anchor = tileObjects[number].supportAnchor;
while (anchor.children.length) {
anchor.remove(anchor.children[0]);
}
const symbol = supportByTile[number];
if (symbol) {
anchor.add(makeSupport(symbol));
}
}
}
function clearPathSegments() {
for (const child of [...pathGroup.children]) {
pathGroup.remove(child);
child.geometry.dispose();
child.material.dispose();
}
pathSegments = [];
}
function addPathSegment(a, b, fromLabel, toLabel) {
const start = a.clone();
const end = b.clone();
start.y = 0.47;
end.y = 0.47;
const material = new THREE.MeshBasicMaterial({
color: 0x647a91,
transparent: true,
opacity: 0.42,
depthWrite: false
});
const segment = cylinderBetween(start, end, 0.028, material, 6);
segment.renderOrder = 2;
pathGroup.add(segment);
pathSegments.push({
mesh: segment,
material,
fromLabel,
toLabel
});
}
function rebuildPreviewPath() {
clearPathSegments();
const nodes = [{
position: START.clone(),
label: "START"
}];
for (let number = 1; number <= TILE_COUNT; number++) {
const pad = tilePad[number];
if (pad === null || pad === undefined) break;
nodes.push({
position: padPosition(pad),
label: `TILE ${number}`
});
}
if (nodes.length === TILE_COUNT + 1) {
nodes.push({
position: GOAL.clone(),
label: "GOAL"
});
}
for (let i = 0; i < nodes.length - 1; i++) {
addPathSegment(
nodes[i].position,
nodes[i + 1].position,
nodes[i].label,
nodes[i + 1].label
);
}
}
function refreshBoard() {
for (let number = 1; number <= TILE_COUNT; number++) {
const pad = tilePad[number];
if (pad !== null && pad !== undefined) {
const position = padPosition(pad);
tileObjects[number].group.position.set(position.x, 0, position.z);
} else {
tileObjects[number].group.visible = false;
}
tileObjects[number].bodyMaterial.emissive.set(0x000000);
}
for (let i = 0; i < PAD_COUNT; i++) {
const occupied = padTile[i] !== null;
padMeshes[i].material.color.set(occupied ? 0x243a53 : 0x17283c);
padMeshes[i].material.emissive.set(occupied ? 0x07111c : 0x000000);
}
refreshSupports();
rebuildPreviewPath();
syncSelection();
updateChecklist();
}
function refreshLayout(announce = true) {
lastValidation = null;
refreshBoard();
if (announce) {
setStatus(
"Layout changed. Replay to validate every hop against the 3.20 u toy range.",
"info"
);
}
}
function resetLayout() {
animation = null;
replayButton.disabled = false;
replayButton.textContent = "Replay avatar";
tilePad = {};
padTile = Array(PAD_COUNT).fill(null);
supportByTile = {};
for (const [number, pad] of Object.entries(INITIAL_LAYOUT)) {
tilePad[Number(number)] = pad;
padTile[pad] = Number(number);
}
selectedTile = null;
selectedSupport = null;
avatar.position.set(START.x, GROUND_Y, START.z);
avatar.rotation.y = Math.PI;
avatarShadow.position.set(START.x, 0.015, START.z);
clearInvalidFlash();
refreshLayout(false);
setStatus(
"Scrambled layout restored. Build a legal 1 → 7 chain and place the spring on 4 and brace on 6.",
"info"
);
}
// -------------------------------------------------------------------------
// Placement and support interactions
// -------------------------------------------------------------------------
function swapTiles(a, b) {
const padA = tilePad[a];
const padB = tilePad[b];
if (padA === null || padA === undefined) {
tilePad[b] = null;
tilePad[a] = padB;
padTile[padB] = a;
} else if (padB === null || padB === undefined) {
tilePad[a] = null;
tilePad[b] = padA;
padTile[padA] = b;
} else {
tilePad[a] = padB;
tilePad[b] = padA;
padTile[padA] = b;
padTile[padB] = a;
}
}
function moveSelectedTileToPad(pad) {
const oldPad = tilePad[selectedTile];
const occupant = padTile[pad];
if (occupant !== null) {
swapTiles(selectedTile, occupant);
} else {
if (oldPad !== null && oldPad !== undefined) {
padTile[oldPad] = null;
}
tilePad[selectedTile] = pad;
padTile[pad] = selectedTile;
}
selectedTile = null;
refreshLayout();
}
function placeSupport(tileNumber) {
const symbol = selectedSupport;
for (const [number, placedSymbol] of Object.entries(supportByTile)) {
if (Number(number) !== tileNumber && placedSymbol === symbol) {
delete supportByTile[Number(number)];
}
}
if (supportByTile[tileNumber] === symbol) {
delete supportByTile[tileNumber];
} else {
supportByTile[tileNumber] = symbol;
}
selectedSupport = null;
refreshLayout();
}
function handleSceneClick(hit) {
if (hit.tileNumber !== undefined) {
if (selectedSupport) {
placeSupport(hit.tileNumber);
return;
}
if (selectedTile !== null && selectedTile !== hit.tileNumber) {
swapTiles(selectedTile, hit.tileNumber);
selectedTile = null;
refreshLayout();
return;
}
selectedTile = hit.tileNumber;
syncSelection();
setStatus(
`Tile ${hit.tileNumber} selected. Select another tile to swap, or an empty pad to move it.`,
"info"
);
return;
}
if (hit.padIndex !== undefined) {
if (selectedTile !== null) {
moveSelectedTileToPad(hit.padIndex);
return;
}
setStatus(
`Pad ${hit.padIndex + 1} selected. Select a numbered tile first.`,
"info"
);
}
}
// -------------------------------------------------------------------------
// Validation
// -------------------------------------------------------------------------
function buildHops() {
const nodes = [{
label: "START",
position: START.clone()
}];
for (let number = 1; number <= TILE_COUNT; number++) {
nodes.push({
label: `TILE ${number}`,
position: padPosition(tilePad[number])
});
}
nodes.push({
label: "GOAL",
position: GOAL.clone()
});
const hops = [];
for (let i = 0; i < nodes.length - 1; i++) {
const from = nodes[i];
const to = nodes[i + 1];
const dx = to.position.x - from.position.x;
const dz = to.position.z - from.position.z;
const distance = Math.hypot(dx, dz);
hops.push({
from,
to,
distance,
foot: i % 2 === 0 ? "L" : "R",
index: i
});
}
return hops;
}
function validateLayout() {
const missing = [];
for (let number = 1; number <= TILE_COUNT; number++) {
if (tilePad[number] === null || tilePad[number] === undefined) {
missing.push(number);
}
}
if (missing.length) {
return {
ok: false,
kind: "missing",
rangeOk: false,
missing
};
}
const hops = buildHops();
// This is the strict, explicitly declared toy limit.
// Supports are deliberately NOT allowed to increase it.
for (const hop of hops) {
if (hop.distance > JUMP_RANGE + 0.00001) {
return {
ok: false,
kind: "range",
rangeOk: false,
hop,
hops
};
}
}
const springTile = findSupportTile("spring");
const braceTile = findSupportTile("brace");
if (springTile !== 4 || braceTile !== 6) {
return {
ok: false,
kind: "support",
rangeOk: true,
springTile,
braceTile,
hops
};
}
return {
ok: true,
kind: "valid",
rangeOk: true,
hops
};
}
function colorPathSegments(result) {
if (!result) {
for (const segment of pathSegments) {
segment.material.color.set(0x647a91);
segment.material.opacity = 0.42;
}
return;
}
if (result.kind === "range") {
for (let i = 0; i < pathSegments.length; i++) {
if (i === result.hop.index) {
pathSegments[i].material.color.set(0xff6174);
pathSegments[i].material.opacity = 1;
} else if (i < result.hop.index) {
pathSegments[i].material.color.set(0x52e3d0);
pathSegments[i].material.opacity = 0.8;
} else {
pathSegments[i].material.color.set(0x647a91);
pathSegments[i].material.opacity = 0.32;
}
}
} else if (result.rangeOk) {
for (const segment of pathSegments) {
segment.material.color.set(0x52e3d0);
segment.material.opacity = 0.88;
}
} else {
for (const segment of pathSegments) {
segment.material.color.set(0xffd166);
segment.material.opacity = 0.55;
}
}
}
function clearInvalidFlash() {
if (invalidFlashTimer !== null) {
clearTimeout(invalidFlashTimer);
invalidFlashTimer = null;
}
for (let number = 1; number <= TILE_COUNT; number++) {
tileObjects[number].bodyMaterial.emissive.set(0x000000);
}
}
function flashInvalidTiles(numbers) {
clearInvalidFlash();
for (const number of numbers) {
tileObjects[number].bodyMaterial.emissive.set(0x7a1020);
}
invalidFlashTimer = setTimeout(clearInvalidFlash, 1400);
}
// -------------------------------------------------------------------------
// Schematic low-poly avatar
// -------------------------------------------------------------------------
const avatar = new THREE.Group();
scene.add(avatar);
const avatarMaterials = {
torso: new THREE.MeshStandardMaterial({
color: 0x52e3d0,
roughness: 0.65,
metalness: 0.05,
flatShading: true
}),
head: new THREE.MeshStandardMaterial({
color: 0xeaf5fb,
roughness: 0.75,
metalness: 0.02,
flatShading: true
}),
joint: new THREE.MeshStandardMaterial({
color: 0xffd166,
roughness: 0.6,
metalness: 0.18,
flatShading: true
}),
leftFoot: new THREE.MeshStandardMaterial({
color: FOOT_COLORS.L,
roughness: 0.7,
flatShading: true
}),
rightFoot: new THREE.MeshStandardMaterial({
color: FOOT_COLORS.R,
roughness: 0.7,
flatShading: true
})
};
const torso = new THREE.Mesh(
new THREE.BoxGeometry(0.38, 0.52, 0.25),
avatarMaterials.torso
);
torso.position.y = 0.88;
torso.castShadow = true;
avatar.add(torso);
const neck = new THREE.Mesh(
new THREE.CylinderGeometry(0.075, 0.075, 0.12, 6),
avatarMaterials.joint
);
neck.position.y = 1.19;
avatar.add(neck);
const head = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.23, 0),
avatarMaterials.head
);
head.position.y = 1.43;
head.castShadow = true;
avatar.add(head);
const face = new THREE.Mesh(
new THREE.BoxGeometry(0.13, 0.045, 0.035),
new THREE.MeshBasicMaterial({ color: 0x102030 })
);
face.position.set(0, 1.46, 0.215);
avatar.add(face);
function makeArm(side, color) {
const pivot = new THREE.Group();
pivot.position.set(side * 0.25, 1.08, 0);
const arm = new THREE.Mesh(
new THREE.CylinderGeometry(0.052, 0.065, 0.43, 6),
color
);
arm.position.y = -0.215;
arm.castShadow = true;
pivot.add(arm);
const hand = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.075, 0),
avatarMaterials.joint
);
hand.position.y = -0.45;
pivot.add(hand);
avatar.add(pivot);
return pivot;
}
function makeLeg(side, footMaterial) {
const pivot = new THREE.Group();
pivot.position.set(side * 0.115, 0.56, 0);
const leg = new THREE.Mesh(
new THREE.CylinderGeometry(0.057, 0.07, 0.38, 6),
avatarMaterials.torso
);
leg.position.y = -0.19;
leg.castShadow = true;
pivot.add(leg);
const knee = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.072, 0),
avatarMaterials.joint
);
knee.position.y = -0.38;
pivot.add(knee);
const foot = new THREE.Mesh(
new THREE.BoxGeometry(0.14, 0.09, 0.25),
footMaterial
);
foot.position.set(0, -0.43, 0.055);
foot.castShadow = true;
pivot.add(foot);
avatar.add(pivot);
return pivot;
}
const leftArm = makeArm(-1, avatarMaterials.torso);
const rightArm = makeArm(1, avatarMaterials.torso);
const leftLeg = makeLeg(-1, avatarMaterials.leftFoot);
const rightLeg = makeLeg(1, avatarMaterials.rightFoot);
const avatarLabel = makeTextSprite("SCHEMATIC", "#52e3d0");
avatarLabel.scale.set(1.05, 0.27, 1);
avatarLabel.position.y = 1.88;
avatar.add(avatarLabel);
const avatarShadow = new THREE.Mesh(
new THREE.CircleGeometry(0.43, 16),
new THREE.MeshBasicMaterial({
color: 0x000000,
transparent: true,
opacity: 0.28,
depthWrite: false
})
);
avatarShadow.rotation.x = -Math.PI / 2;
scene.add(avatarShadow);
// -------------------------------------------------------------------------
// Replay animation
// -------------------------------------------------------------------------
const pulses = [];
const pulseGeometry = new THREE.TorusGeometry(0.72, 0.025, 6, 32);
function spawnPulse(position) {
const material = new THREE.MeshBasicMaterial({
color: 0x52e3d0,
transparent: true,
opacity: 0.85,
depthWrite: false
});
const pulse = new THREE.Mesh(pulseGeometry, material);
pulse.rotation.x = Math.PI / 2;
pulse.position.set(position.x, 0.43, position.z);
scene.add(pulse);
pulses.push({
mesh: pulse,
material,
start: performance.now()
});
}
function beginAnimation(hops) {
animation = {
hops,
index: 0,
started: performance.now()
};
avatar.position.set(START.x, GROUND_Y, START.z);
avatar.rotation.y = Math.PI;
replayButton.disabled = true;
replayButton.textContent = "Replaying…";
beginSegment(0);
}
function beginSegment(index) {
const hop = animation.hops[index];
const dx = hop.to.position.x - hop.from.position.x;
const dz = hop.to.position.z - hop.from.position.z;
animation.index = index;
animation.started = performance.now();
animation.duration = Math.max(520, 560 + hop.distance * 48);
animation.hopHeight = 0.72 + hop.distance * 0.17;
avatar.rotation.y = Math.atan2(dx, dz);
setStatus(
`Hop ${index + 1}/8 · ${hop.from.label} → ${hop.to.label} · ` +
`${hop.foot} foot · ${hop.distance.toFixed(2)} u / ${JUMP_RANGE.toFixed(2)} u max`,
"info"
);
}
function updateAnimation(now) {
if (!animation) return;
const hop = animation.hops[animation.index];
const raw = (now - animation.started) / animation.duration;
const t = Math.max(0, Math.min(1, raw));
const eased = t * t * (3 - 2 * t);
const arc = Math.sin(Math.PI * t);
avatar.position.x = THREE.MathUtils.lerp(
hop.from.position.x,
hop.to.position.x,
eased
);
avatar.position.z = THREE.MathUtils.lerp(
hop.from.position.z,
hop.to.position.z,
eased
);
avatar.position.y = GROUND_Y + arc * animation.hopHeight;
const swing = Math.sin(Math.PI * t);
leftLeg.rotation.x = -0.72 * swing;
rightLeg.rotation.x = 0.72 * swing;
leftArm.rotation.x = 0.58 * swing;
rightArm.rotation.x = -0.58 * swing;
avatarShadow.position.x = avatar.position.x;
avatarShadow.position.z = avatar.position.z;
avatarShadow.material.opacity = 0.25 * (1 - arc * 0.65);
avatarShadow.scale.setScalar(1 - arc * 0.2);
if (t >= 1) {
avatar.position.x = hop.to.position.x;
avatar.position.z = hop.to.position.z;
avatar.position.y = GROUND_Y;
leftLeg.rotation.x = 0;
rightLeg.rotation.x = 0;
leftArm.rotation.x = 0;
rightArm.rotation.x = 0;
spawnPulse(hop.to.position);
if (animation.index >= animation.hops.length - 1) {
animation = null;
replayButton.disabled = false;
replayButton.textContent = "Replay avatar";
setStatus(
`Replay complete. All 8 transitions are within the declared ${JUMP_RANGE.toFixed(2)} u toy jump range.`,
"info"
);
} else {
beginSegment(animation.index + 1);
}
}
}
function replay() {
if (animation) return;
const result = validateLayout();
lastValidation = result;
updateChecklist();
colorPathSegments(result);
if (!result.ok) {
if (result.kind === "missing") {
setStatus(
`REJECTED: place all seven numbered tiles. Missing tile${result.missing.length > 1 ? "s" : ""} ` +
`${result.missing.join(", ")}.`,
"error"
);
return;
}
if (result.kind === "range") {
const { hop } = result;
flashInvalidTiles(
hop.from.label.startsWith("TILE")
? [Number(hop.from.label.split(" ")[1])]
: []
);
setStatus(
`REJECTED: ${hop.from.label} → ${hop.to.label} is ${hop.distance.toFixed(2)} u, ` +
`exceeding the declared ${JUMP_RANGE.toFixed(2)} u toy jump range. No hop was replayed.`,
"error"
);
return;
}
const springMessage = result.springTile === null
? "spring is missing"
: `spring must be on tile 4, not tile ${result.springTile}`;
const braceMessage = result.braceTile === null
? "brace is missing"
: `brace must be on tile 6, not tile ${result.braceTile}`;
setStatus(
`Range accepted, but support placement rejected: ${springMessage}; ${braceMessage}.`,
"warn"
);
return;
}
beginAnimation(result.hops);
}
// -------------------------------------------------------------------------
// Direct camera controls and raycast picking
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function pick(event) {
const rect = renderer.domElement.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);
const hits = raycaster.intersectObjects(clickables, false);
return hits.length ? hits[0].object.userData : null;
}
let pointerDown = null;
renderer.domElement.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
const hit = pick(event);
const orbiting = !hit;
pointerDown = {
x: event.clientX,
y: event.clientY,
lastX: event.clientX,
lastY: event.clientY,
moved: false,
orbiting,
hit
};
if (orbiting) {
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "grabbing";
}
});
renderer.domElement.addEventListener("pointermove", event => {
if (pointerDown) {
const totalDistance = Math.hypot(
event.clientX - pointerDown.x,
event.clientY - pointerDown.y
);
if (totalDistance > 4) pointerDown.moved = true;
if (pointerDown.orbiting) {
const dx = event.clientX - pointerDown.lastX;
const dy = event.clientY - pointerDown.lastY;
cameraTheta -= dx * 0.006;
cameraPhi = THREE.MathUtils.clamp(cameraPhi + dy * 0.005, 0.42, 1.25);
updateCamera();
}
pointerDown.lastX = event.clientX;
pointerDown.lastY = event.clientY;
} else {
renderer.domElement.style.cursor = pick(event) ? "pointer" : "grab";
}
});
renderer.domElement.addEventListener("pointerup", event => {
if (!pointerDown) return;
const wasOrbiting = pointerDown.orbiting;
const moved = pointerDown.moved;
const hit = pointerDown.hit;
pointerDown = null;
renderer.domElement.style.cursor = "grab";
if (!wasOrbiting && !moved && hit) {
handleSceneClick(hit);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerDown = null;
renderer.domElement.style.cursor = "grab";
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
9.2,
21
);
updateCamera();
}, { passive: false });
renderer.domElement.addEventListener("contextmenu", event => {
event.preventDefault();
});
renderer.domElement.addEventListener("dblclick", resetCamera);
// -------------------------------------------------------------------------
// Buttons and keyboard
// -------------------------------------------------------------------------
springButton.addEventListener("click", () => {
selectedTile = null;
selectedSupport = selectedSupport === "spring" ? null : "spring";
syncSelection();
setStatus(
selectedSupport
? "Spring selected. Click the destination tile; click it again to remove the spring."
: "Spring selection cleared.",
"info"
);
});
braceButton.addEventListener("click", () => {
selectedTile = null;
selectedSupport = selectedSupport === "brace" ? null : "brace";
syncSelection();
setStatus(
selectedSupport
? "Brace selected. Click the destination tile; click it again to remove the brace."
: "Brace selection cleared.",
"info"
);
});
replayButton.addEventListener("click", replay);
resetButton.addEventListener("click", resetLayout);
cameraButton.addEventListener("click", resetCamera);
window.addEventListener("keydown", event => {
if (event.key.toLowerCase() === "r") {
replay();
} else if (event.key.toLowerCase() === "c") {
resetCamera();
} else if (event.key === "Escape") {
selectedTile = null;
selectedSupport = null;
syncSelection();
setStatus("Selection cleared.", "info");
}
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
// -------------------------------------------------------------------------
// Main loop
// -------------------------------------------------------------------------
resetLayout();
function animate(now) {
requestAnimationFrame(animate);
if (animation) {
updateAnimation(now);
} else {
avatar.position.y = GROUND_Y + Math.sin(now * 0.0022) * 0.012;
}
for (let i = pulses.length - 1; i >= 0; i--) {
const pulse = pulses[i];
const life = (now - pulse.start) / 650;
if (life >= 1) {
scene.remove(pulse.mesh);
pulse.material.dispose();
pulses.splice(i, 1);
} else {
pulse.mesh.scale.setScalar(1 + life * 0.75);
pulse.material.opacity = (1 - life) * 0.8;
}
}
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```