Prompt specification
Build or customize the Three.js 3D scene "Cooperative playground design 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: Cooperative playground design puzzle
Category: Architecture & Cities · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/cooperative-playground-design-puzzle-x0444
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring inclusive playground access. Create configurable play modules that require different actions to guide a ball to a goal; users connect modules so participants share outcomes without needing identical movement abilities. Low-poly.
Working Three.js Starter (cooperative-playground-design-puzzle-x0444):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>CommonGround — Inclusive Play Lab</title>
<style>
:root {
--ink: #173b33;
--muted: #667a72;
--paper: #fffdf7;
--cream: #f5f0e4;
--green: #205747;
--lime: #c5eb75;
--coral: #ff806f;
--blue: #687cff;
--teal: #39c4b2;
--yellow: #ffc95d;
--line: #dfe6dc;
--shadow: 0 18px 45px rgba(30, 66, 54, 0.13);
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
background: #edf2e9;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body {
overflow: hidden;
}
button,
input,
select {
font: inherit;
}
button {
color: inherit;
}
button:focus-visible,
input:focus-visible,
select:focus-visible,
canvas:focus-visible {
outline: 3px solid var(--blue);
outline-offset: 3px;
}
.app {
height: 100vh;
display: grid;
grid-template-rows: 72px minmax(0, 1fr);
}
header {
position: relative;
z-index: 20;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 0 22px;
background: rgba(255, 253, 247, 0.96);
border-bottom: 1px solid var(--line);
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.brand-mark {
position: relative;
width: 42px;
height: 42px;
flex: 0 0 auto;
border-radius: 14px;
background: var(--green);
box-shadow: inset 0 -5px 0 rgba(0, 0, 0, 0.08);
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
background: var(--lime);
border-radius: 50%;
}
.brand-mark::before {
width: 12px;
height: 12px;
left: 8px;
top: 9px;
}
.brand-mark::after {
width: 18px;
height: 18px;
right: 6px;
bottom: 6px;
}
.brand-copy {
min-width: 0;
}
.brand-copy strong {
display: block;
font-size: 18px;
letter-spacing: -0.02em;
white-space: nowrap;
}
.brand-copy span {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 12px;
white-space: nowrap;
}
.header-meta {
display: flex;
align-items: center;
gap: 9px;
}
.shared-pill,
.help-pill {
display: inline-flex;
align-items: center;
gap: 8px;
min-height: 34px;
padding: 0 12px;
border-radius: 999px;
font-size: 12px;
font-weight: 750;
white-space: nowrap;
}
.shared-pill {
color: #164a3b;
background: #e5f4cb;
border: 1px solid #c9e69f;
}
.shared-pill::before {
content: "";
width: 8px;
height: 8px;
border-radius: 50%;
background: #55a33c;
box-shadow: 0 0 0 4px rgba(85, 163, 60, 0.12);
}
.help-pill {
color: var(--muted);
background: #f1f3ec;
border: 1px solid var(--line);
}
main {
min-height: 0;
display: grid;
grid-template-columns: minmax(0, 1fr) 366px;
}
#stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #e8f0e5;
}
#viewport,
#labels-layer {
position: absolute;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
#labels-layer {
z-index: 4;
pointer-events: none;
overflow: hidden;
}
.module-tag,
.port-button {
position: absolute;
left: 0;
top: 0;
pointer-events: auto;
will-change: transform;
}
.module-tag {
display: flex;
align-items: center;
gap: 7px;
min-height: 29px;
max-width: 180px;
padding: 5px 9px;
border: 1px solid rgba(255, 255, 255, 0.7);
border-radius: 10px;
background: rgba(255, 253, 247, 0.94);
color: var(--ink);
box-shadow: 0 7px 18px rgba(31, 61, 50, 0.15);
font-size: 11px;
font-weight: 800;
cursor: pointer;
white-space: nowrap;
}
.module-tag.selected {
border-color: var(--green);
box-shadow: 0 0 0 2px rgba(32, 87, 71, 0.18),
0 8px 20px rgba(31, 61, 50, 0.17);
}
.module-tag .tag-dot {
width: 8px;
height: 8px;
flex: 0 0 auto;
border-radius: 50%;
}
.module-tag .tag-action {
color: var(--muted);
font-size: 9px;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.port-button {
width: 34px;
height: 26px;
padding: 0;
border: 2px solid #fff;
border-radius: 9px;
background: var(--green);
color: white;
box-shadow: 0 5px 12px rgba(31, 61, 50, 0.2);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.04em;
cursor: crosshair;
}
.port-button.in {
background: #ffffff;
color: var(--green);
border-color: var(--green);
}
.port-button.pending {
background: var(--coral);
color: white;
border-color: white;
animation: portPulse 0.85s ease-in-out infinite alternate;
}
@keyframes portPulse {
to {
transform: translate(-50%, -50%) scale(1.14);
box-shadow: 0 0 0 7px rgba(255, 128, 111, 0.19);
}
}
.scene-toolbar {
position: absolute;
z-index: 7;
top: 18px;
left: 18px;
right: 18px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
pointer-events: none;
}
.route-status,
.scene-help {
border: 1px solid rgba(255, 255, 255, 0.8);
background: rgba(255, 253, 247, 0.88);
box-shadow: 0 8px 22px rgba(31, 61, 50, 0.1);
backdrop-filter: blur(10px);
}
.route-status {
display: flex;
align-items: center;
gap: 9px;
min-height: 36px;
padding: 0 12px;
border-radius: 12px;
color: var(--muted);
font-size: 11px;
font-weight: 750;
}
.route-status .status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #62ae45;
}
.route-status.invalid .status-dot {
background: var(--coral);
}
.scene-help {
padding: 9px 12px;
border-radius: 12px;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
text-align: right;
pointer-events: auto;
}
.scene-help button {
display: block;
margin-left: auto;
padding: 0;
border: 0;
background: transparent;
color: var(--green);
font-size: 10px;
font-weight: 800;
cursor: pointer;
}
.prompt-card {
position: absolute;
z-index: 8;
left: 18px;
bottom: 100px;
width: min(390px, calc(100% - 36px));
padding: 16px;
border: 1px solid rgba(255, 255, 255, 0.8);
border-radius: 18px;
background: rgba(255, 253, 247, 0.94);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
}
.prompt-overline {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
color: var(--green);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.13em;
text-transform: uppercase;
}
#prompt-score {
color: var(--muted);
letter-spacing: 0;
}
.prompt-card h2 {
margin: 8px 0 5px;
font-size: 20px;
line-height: 1.15;
letter-spacing: -0.035em;
}
.prompt-card p {
min-height: 35px;
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.48;
}
.progress-track {
height: 6px;
margin-top: 13px;
overflow: hidden;
border-radius: 999px;
background: #e4e9df;
}
#progress-fill {
display: block;
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--teal), var(--lime));
transition: width 0.3s ease;
}
.contributors {
display: flex;
flex-wrap: wrap;
gap: 5px;
min-height: 21px;
margin-top: 10px;
}
.contributor-chip {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 4px 7px;
border-radius: 999px;
background: #eef3e8;
color: var(--green);
font-size: 9px;
font-weight: 800;
}
.playbar {
position: absolute;
z-index: 9;
left: 18px;
right: 18px;
bottom: 18px;
display: flex;
align-items: center;
gap: 9px;
min-height: 62px;
padding: 10px;
border: 1px solid rgba(255, 255, 255, 0.82);
border-radius: 18px;
background: rgba(255, 253, 247, 0.94);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
}
.primary-button,
.secondary-button,
.danger-button {
min-height: 40px;
padding: 0 16px;
border-radius: 12px;
font-size: 12px;
font-weight: 850;
cursor: pointer;
transition: transform 0.15s ease, opacity 0.15s ease, background 0.15s ease;
}
.primary-button {
border: 0;
background: var(--green);
color: white;
box-shadow: 0 6px 0 #123e32;
}
.primary-button:hover:not(:disabled),
.secondary-button:hover:not(:disabled),
.danger-button:hover:not(:disabled) {
transform: translateY(-1px);
}
.primary-button:active:not(:disabled) {
transform: translateY(3px);
box-shadow: 0 2px 0 #123e32;
}
.primary-button:disabled,
.secondary-button:disabled {
cursor: not-allowed;
opacity: 0.48;
}
.secondary-button {
border: 1px solid var(--line);
background: #f3f5ee;
color: var(--ink);
}
.danger-button {
border: 1px solid #f0c5bd;
background: #fff0ec;
color: #9d493c;
}
.playbar .legend {
margin-left: auto;
padding-right: 5px;
color: var(--muted);
font-size: 10px;
line-height: 1.4;
text-align: right;
}
#toast {
position: absolute;
z-index: 30;
top: 68px;
left: 50%;
max-width: min(430px, calc(100% - 30px));
padding: 10px 14px;
border-radius: 12px;
background: var(--ink);
color: white;
box-shadow: var(--shadow);
font-size: 11px;
font-weight: 700;
text-align: center;
opacity: 0;
pointer-events: none;
transform: translate(-50%, -8px);
transition: opacity 0.2s ease, transform 0.2s ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
aside {
min-height: 0;
overflow-y: auto;
background: var(--paper);
border-left: 1px solid var(--line);
scrollbar-width: thin;
scrollbar-color: #c7d2c4 transparent;
}
.panel-section {
padding: 19px 18px;
border-bottom: 1px solid var(--line);
}
.section-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
}
.section-heading h2 {
margin: 0;
font-size: 15px;
letter-spacing: -0.02em;
}
.section-heading p {
margin: 4px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.small-badge {
flex: 0 0 auto;
padding: 5px 7px;
border-radius: 8px;
background: #edf4e7;
color: var(--green);
font-size: 9px;
font-weight: 850;
}
.palette {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
}
.palette-button {
min-height: 57px;
padding: 8px 5px;
border: 1px solid var(--line);
border-radius: 12px;
background: #f8f8f1;
cursor: pointer;
font-size: 10px;
font-weight: 800;
}
.palette-button:hover {
background: #eef4e8;
border-color: #cbd9c7;
}
.palette-icon {
display: grid;
place-items: center;
width: 25px;
height: 25px;
margin: 0 auto 5px;
border-radius: 8px;
color: white;
font-size: 11px;
font-weight: 900;
}
.module-list {
display: grid;
gap: 6px;
max-height: 194px;
margin-top: 12px;
overflow-y: auto;
scrollbar-width: thin;
}
.module-row {
display: grid;
grid-template-columns: 9px minmax(0, 1fr) auto;
align-items: center;
gap: 9px;
width: 100%;
min-height: 48px;
padding: 7px 9px;
border: 1px solid transparent;
border-radius: 11px;
background: #f4f5ee;
text-align: left;
cursor: pointer;
}
.module-row:hover {
background: #eef2e8;
}
.module-row.selected {
border-color: #a9c8aa;
background: #eaf2e5;
}
.module-row .row-dot {
width: 9px;
height: 9px;
border-radius: 50%;
}
.module-row strong,
.module-row small {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.module-row strong {
font-size: 11px;
}
.module-row small {
margin-top: 3px;
color: var(--muted);
font-size: 9px;
}
.action-chip {
padding: 5px 6px;
border-radius: 7px;
background: white;
color: var(--green);
font-size: 8px;
font-weight: 850;
text-transform: uppercase;
}
.field {
display: grid;
gap: 6px;
margin-bottom: 12px;
}
.field label,
.field-label {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
}
.field label output {
color: var(--green);
}
input[type="text"],
select {
width: 100%;
height: 38px;
padding: 0 10px;
border: 1px solid var(--line);
border-radius: 10px;
background: #f8f8f2;
color: var(--ink);
font-size: 11px;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 4px 0;
accent-color: var(--green);
cursor: pointer;
}
.range-ends {
display: flex;
justify-content: space-between;
color: #97a39b;
font-size: 8px;
}
.button-row {
display: flex;
gap: 7px;
margin-top: 13px;
}
.button-row button {
flex: 1;
min-height: 36px;
padding: 0 10px;
border-radius: 10px;
font-size: 10px;
font-weight: 800;
cursor: pointer;
}
.empty-state {
padding: 18px 12px;
border: 1px dashed #ccd6ca;
border-radius: 12px;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
text-align: center;
}
.participant-list {
display: grid;
gap: 8px;
}
.participant-card {
padding: 10px;
border: 1px solid var(--line);
border-radius: 13px;
background: #f8f8f2;
}
.participant-card.contributed {
border-color: #a8ca85;
background: #f0f7e5;
}
.participant-top {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 8px;
}
.avatar {
display: grid;
place-items: center;
width: 32px;
height: 32px;
flex: 0 0 auto;
border-radius: 10px;
color: white;
font-size: 11px;
font-weight: 900;
}
.participant-name {
min-width: 0;
}
.participant-name strong,
.participant-name small {
display: block;
}
.participant-name strong {
font-size: 11px;
}
.participant-name small {
margin-top: 2px;
color: var(--muted);
font-size: 9px;
}
.participant-state {
margin-left: auto;
padding: 4px 6px;
border-radius: 7px;
background: #e9eee6;
color: var(--muted);
font-size: 8px;
font-weight: 850;
text-transform: uppercase;
}
.participant-card.contributed .participant-state {
background: #dceec6;
color: #477530;
}
.tap-button {
width: 100%;
min-height: 37px;
border: 0;
border-radius: 10px;
background: var(--coral);
color: white;
font-size: 11px;
font-weight: 850;
cursor: pointer;
}
.tap-button:active {
transform: scale(0.98);
}
.tilt-row {
display: grid;
grid-template-columns: 28px 1fr 36px;
align-items: center;
gap: 8px;
}
.tilt-row span {
color: var(--muted);
font-size: 9px;
}
.tilt-row output {
padding: 5px;
border-radius: 7px;
background: #e8ece4;
color: var(--green);
font-size: 9px;
font-weight: 800;
text-align: center;
}
.access-note {
margin: 12px 0 0;
padding: 10px;
border-radius: 11px;
background: #edf5e6;
color: #4d6d57;
font-size: 10px;
line-height: 1.45;
}
.access-note strong {
color: var(--green);
}
@media (max-width: 900px) {
body {
overflow: auto;
}
.app {
height: auto;
min-height: 100vh;
grid-template-rows: 68px auto;
}
main {
display: grid;
grid-template-columns: 1fr;
grid-template-rows: minmax(520px, 64vh) auto;
}
aside {
overflow: visible;
border-top: 1px solid var(--line);
border-left: 0;
}
.help-pill {
display: none;
}
}
@media (max-width: 560px) {
header {
padding: 0 14px;
}
.brand-copy span {
display: none;
}
.shared-pill {
padding: 0 9px;
font-size: 10px;
}
.scene-help {
display: none;
}
.prompt-card {
bottom: 91px;
padding: 13px;
}
.prompt-card h2 {
font-size: 17px;
}
.prompt-card p {
font-size: 11px;
}
.playbar {
gap: 6px;
padding: 8px;
}
.playbar .legend {
display: none;
}
.primary-button,
.secondary-button {
padding: 0 10px;
font-size: 10px;
}
}
</style>
</head>
<body>
<div class="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div class="brand-copy">
<strong>CommonGround</strong>
<span>Inclusive Play Lab</span>
</div>
</div>
<div class="header-meta">
<span class="shared-pill">Shared control</span>
<span class="help-pill">One route · many ways to play</span>
</div>
</header>
<main>
<section id="stage" aria-label="Interactive low-poly playground">
<div id="viewport"></div>
<div id="labels-layer"></div>
<div class="scene-toolbar">
<div id="route-status" class="route-status">
<span class="status-dot"></span>
<span id="route-status-text">Checking route…</span>
</div>
<div class="scene-help">
Drag modules · drag empty space to orbit · scroll to zoom
<button id="reset-view" type="button">Reset camera</button>
</div>
</div>
<div class="prompt-card" aria-live="polite">
<div class="prompt-overline">
<span id="prompt-overline">Next shared move</span>
<span id="prompt-score">Team score 0</span>
</div>
<h2 id="prompt-title">Ready to build a shared route?</h2>
<p id="prompt-text">
Connect the glowing IN and OUT ports, then start the shared run.
</p>
<div class="progress-track" aria-label="Shared route progress">
<span id="progress-fill"></span>
</div>
<div id="contributors" class="contributors"></div>
</div>
<div class="playbar">
<button id="run-button" class="primary-button" type="button">
Start shared run
</button>
<button id="pause-button" class="secondary-button" type="button" disabled>
Pause
</button>
<button id="reset-button" class="secondary-button" type="button">
Reset
</button>
<div class="legend">
Different controls can move the same ball.<br />
Every contribution advances the team.
</div>
</div>
<div id="toast" role="status" aria-live="polite"></div>
</section>
<aside aria-label="Route builder and participant controls">
<section class="panel-section">
<div class="section-heading">
<div>
<h2>Play modules</h2>
<p>Add stops, then connect them into one shared route.</p>
</div>
<span id="module-count" class="small-badge">0 modules</span>
</div>
<div class="palette">
<button class="palette-button" data-add-type="launch" type="button">
<span class="palette-icon" style="background:#ffc95d">↗</span>
Launch
</button>
<button class="palette-button" data-add-type="ramp" type="button">
<span class="palette-icon" style="background:#687cff">◩</span>
Ramp
</button>
<button class="palette-button" data-add-type="bounce" type="button">
<span class="palette-icon" style="background:#ff806f">⌁</span>
Bounce
</button>
<button class="palette-button" data-add-type="fan" type="button">
<span class="palette-icon" style="background:#39c4b2">✣</span>
Fan
</button>
<button class="palette-button" data-add-type="goal" type="button">
<span class="palette-icon" style="background:#7ebd54">◎</span>
Goal
</button>
</div>
<div id="module-list" class="module-list"></div>
</section>
<section class="panel-section">
<div class="section-heading">
<div>
<h2>Configure module</h2>
<p>Change the required input, strength, curve, and route link.</p>
</div>
</div>
<div id="config-content"></div>
</section>
<section class="panel-section">
<div class="section-heading">
<div>
<h2>Participant controls</h2>
<p>Any teammate can use a compatible control.</p>
</div>
<span class="small-badge">3 ways</span>
</div>
<div class="participant-list">
<article id="participant-maya" class="participant-card">
<div class="participant-top">
<div class="avatar" style="background:#ff806f">M</div>
<div class="participant-name">
<strong>Maya</strong>
<small>Tap pad · Space</small>
</div>
<span class="participant-state">Ready</span>
</div>
<button id="maya-button" class="tap-button" type="button">
Tap to contribute
</button>
</article>
<article id="participant-noah" class="participant-card">
<div class="participant-top">
<div class="avatar" style="background:#687cff">N</div>
<div class="participant-name">
<strong>Noah</strong>
<small>Tilt slider · Arrow keys</small>
</div>
<span class="participant-state">Ready</span>
</div>
<div class="tilt-row">
<span>Left</span>
<input
id="noah-slider"
type="range"
min="-100"
max="100"
value="25"
aria-label="Noah's tilt control"
/>
<output id="noah-output">25</output>
</div>
</article>
<article id="participant-ari" class="participant-card">
<div class="participant-top">
<div class="avatar" style="background:#39b89e">A</div>
<div class="participant-name">
<strong>Ari</strong>
<small>Hold button · H key</small>
</div>
<span class="participant-state">Ready</span>
</div>
<button id="ari-button" class="tap-button" type="button">
Press and hold to contribute
</button>
</article>
</div>
<p class="access-note">
<strong>Designed for shared access:</strong>
set a module to “Any input” to let the route work with tap, tilt,
or hold. You can also assign one stop to a specific participant.
</p>
</section>
</aside>
</main>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (selector) => document.querySelector(selector);
const stage = $("#stage");
const viewport = $("#viewport");
const labelsLayer = $("#labels-layer");
const moduleDefs = {
launch: {
name: "Launch pad",
short: "Launch",
color: 0xffc95d,
action: "tap",
strength: 72,
curve: 0,
height: 55,
symbol: "↗"
},
ramp: {
name: "Tilt ramp",
short: "Ramp",
color: 0x687cff,
action: "tilt",
strength: 55,
curve: 20,
height: 35,
symbol: "◩"
},
bounce: {
name: "Bounce pad",
short: "Bounce",
color: 0xff806f,
action: "hold",
strength: 58,
curve: 0,
height: 72,
symbol: "⌁"
},
fan: {
name: "Steer fan",
short: "Fan",
color: 0x39c4b2,
action: "tilt",
strength: 48,
curve: 42,
height: 35,
symbol: "✣"
},
goal: {
name: "Shared goal",
short: "Goal",
color: 0x7ebd54,
action: "auto",
strength: 50,
curve: 0,
height: 30,
symbol: "◎"
}
};
const actionLabels = {
tap: "Tap",
tilt: "Tilt",
hold: "Hold",
any: "Any input",
auto: "Auto assist"
};
const participants = {
maya: { name: "Maya", action: "tap", color: "#ff806f" },
noah: { name: "Noah", action: "tilt", color: "#687cff" },
ari: { name: "Ari", action: "hold", color: "#39b89e" },
assist: { name: "Auto assist", action: "auto", color: "#7ebd54" }
};
const modules = new Map();
let nextModuleId = 1;
let selectedId = null;
let pendingSourceId = null;
let runState = "idle";
let currentId = null;
let segment = null;
let reachedCount = 0;
let teamScore = 0;
let autoTimer = null;
let toastTimer = null;
const contributions = new Map();
// ----- Three.js setup -----
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe8f0e5);
scene.fog = new THREE.Fog(0xe8f0e5, 24, 42);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.domElement.tabIndex = 0;
renderer.domElement.setAttribute(
"aria-label",
"Low-poly playground. Drag modules to rearrange them, or use the route builder."
);
viewport.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xf6fff2, 0x78917e, 2.15);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff5da, 3.2);
sun.position.set(-7, 14, 7);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -12;
sun.shadow.camera.right = 12;
sun.shadow.camera.top = 12;
sun.shadow.camera.bottom = -12;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 35;
sun.shadow.bias = -0.0004;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0xc8ddff, 1.1);
rimLight.position.set(9, 7, -8);
scene.add(rimLight);
const board = new THREE.Group();
scene.add(board);
function standardMaterial(color, extra = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.76,
metalness: 0.02,
flatShading: true,
...extra
});
}
function addMesh(group, geometry, material, position, rotation) {
const mesh = new THREE.Mesh(geometry, material);
if (position) mesh.position.set(...position);
if (rotation) mesh.rotation.set(...rotation);
mesh.castShadow = true;
mesh.receiveShadow = true;
group.add(mesh);
return mesh;
}
const grassBase = addMesh(
board,
new THREE.CylinderGeometry(6.75, 7.1, 0.48, 12),
standardMaterial(0x9fca83),
[0, -0.34, 0]
);
grassBase.receiveShadow = true;
addMesh(
board,
new THREE.CylinderGeometry(6.35, 6.55, 0.14, 12),
standardMaterial(0xe8dfc5),
[0, -0.03, 0]
);
// Low-poly perimeter trees and small flowers.
const treePositions = [
[-5.5, -1.6], [-4.9, 3.8], [-3.2, 5.25], [-0.4, 5.75],
[2.2, 5.45], [4.65, 3.8], [5.45, 0.8], [5.3, -2.6],
[3.3, -4.9], [-0.5, -5.6], [-3.6, -4.7]
];
treePositions.forEach(([x, z], index) => {
const tree = new THREE.Group();
tree.position.set(x, 0, z);
tree.rotation.y = index * 0.67;
addMesh(
tree,
new THREE.CylinderGeometry(0.09, 0.12, 0.55, 6),
standardMaterial(0x8e6546),
[0, 0.25, 0]
);
addMesh(
tree,
new THREE.ConeGeometry(0.4, 0.95, 7),
standardMaterial(index % 2 ? 0x4b9d70 : 0x64ae78),
[0, 0.8, 0]
);
addMesh(
tree,
new THREE.ConeGeometry(0.29, 0.7, 7),
standardMaterial(0x76bb7b),
[0, 1.18, 0]
);
board.add(tree);
});
const flowerGeometry = new THREE.OctahedronGeometry(0.07, 0);
[
[-4.6, 0.2, 0xff806f], [-1.5, -4.5, 0xffc95d],
[1.8, 4.5, 0x687cff], [4.7, -0.7, 0xff806f],
[-4.1, -3.6, 0x39c4b2], [3.8, 3.2, 0xffc95d]
].forEach(([x, z, color]) => {
const flower = new THREE.Mesh(
flowerGeometry,
standardMaterial(color)
);
flower.position.set(x, 0.09, z);
flower.castShadow = true;
board.add(flower);
});
const routeGroup = new THREE.Group();
scene.add(routeGroup);
const selectionRing = new THREE.Mesh(
new THREE.TorusGeometry(0.78, 0.035, 6, 36),
new THREE.MeshBasicMaterial({ color: 0x205747 })
);
selectionRing.rotation.x = -Math.PI / 2;
selectionRing.position.y = 0.075;
selectionRing.visible = false;
scene.add(selectionRing);
const ball = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.29, 1),
standardMaterial(0xfffdf1, { roughness: 0.42 })
);
ball.castShadow = true;
ball.receiveShadow = true;
scene.add(ball);
const ballAccent = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.295, 0),
new THREE.MeshBasicMaterial({
color: 0xff806f,
wireframe: true,
transparent: true,
opacity: 0.24
})
);
ball.add(ballAccent);
const trailMeshes = [];
for (let i = 0; i < 8; i++) {
const trail = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.12 - i * 0.009, 0),
new THREE.MeshBasicMaterial({
color: 0x39c4b2,
transparent: true,
opacity: 0.22 - i * 0.02,
depthWrite: false
})
);
trail.visible = false;
scene.add(trail);
trailMeshes.push(trail);
}
const trailHistory = [];
// ----- Module construction -----
function rampGeometry() {
const geometry = new THREE.BufferGeometry();
const vertices = new Float32Array([
-0.55, 0, -0.43,
0.55, 0, -0.43,
0.00, 0.48, -0.43,
-0.55, 0, 0.43,
0.55, 0, 0.43,
0.00, 0.48, 0.43
]);
const indices = [
0, 2, 1,
3, 4, 5,
0, 1, 4, 0, 4, 3,
1, 2, 5, 1, 5, 4,
2, 0, 3, 2, 3, 5
];
geometry.setAttribute("position", new THREE.BufferAttribute(vertices, 3));
geometry.setIndex(indices);
geometry.computeVertexNormals();
return geometry;
}
function createModuleVisual(module) {
const group = module.group;
const def = moduleDefs[module.type];
addMesh(
group,
new THREE.CylinderGeometry(0.7, 0.8, 0.16, 12),
standardMaterial(0xfff9e8),
[0, 0.08, 0]
);
addMesh(
group,
new THREE.CylinderGeometry(0.57, 0.62, 0.06, 12),
standardMaterial(def.color),
[0, 0.19, 0]
);
if (module.type === "launch") {
const rail = addMesh(
group,
new THREE.BoxGeometry(0.9, 0.12, 0.54),
standardMaterial(0xffe3a0),
[0, 0.38, 0]
);
rail.rotation.z = -0.2;
addMesh(
group,
new THREE.ConeGeometry(0.15, 0.38, 5),
standardMaterial(0xff806f),
[0.27, 0.65, 0],
[0, 0, -0.35]
);
}
if (module.type === "ramp") {
addMesh(
group,
rampGeometry(),
standardMaterial(0x8795ff),
[0, 0.22, 0]
);
addMesh(
group,
new THREE.BoxGeometry(0.08, 0.58, 0.08),
standardMaterial(0x4356c7),
[-0.48, 0.28, 0.32]
);
}
if (module.type === "bounce") {
addMesh(
group,
new THREE.CylinderGeometry(0.23, 0.32, 0.35, 10),
standardMaterial(0xd95e51),
[0, 0.38, 0]
);
const ring = addMesh(
group,
new THREE.TorusGeometry(0.38, 0.065, 6, 18),
standardMaterial(0xffb1a5),
[0, 0.62, 0],
[-Math.PI / 2, 0, 0]
);
ring.castShadow = true;
}
if (module.type === "fan") {
addMesh(
group,
new THREE.CylinderGeometry(0.08, 0.12, 1.05, 8),
standardMaterial(0x248d84),
[0, 0.67, 0]
);
addMesh(
group,
new THREE.IcosahedronGeometry(0.2, 1),
standardMaterial(0xffc95d),
[0, 1.18, 0]
);
for (let i = 0; i < 4; i++) {
const angle = (Math.PI * 2 * i) / 4;
const blade = addMesh(
group,
new THREE.BoxGeometry(0.78, 0.07, 0.15),
standardMaterial(i % 2 ? 0x5be0cd : 0x39c4b2),
[0, 1.18, 0]
);
blade.rotation.y = angle;
}
}
if (module.type === "goal") {
addMesh(
group,
new THREE.BoxGeometry(0.13, 0.95, 0.13),
standardMaterial(0x487e3d),
[-0.45, 0.68, 0]
);
addMesh(
group,
new THREE.BoxGeometry(0.13, 0.95, 0.13),
standardMaterial(0x487e3d),
[0.45, 0.68, 0]
);
addMesh(
group,
new THREE.BoxGeometry(1.03, 0.13, 0.13),
standardMaterial(0x487e3d),
[0, 1.12, 0]
);
addMesh(
group,
new THREE.TorusGeometry(0.24, 0.035, 6, 18),
standardMaterial(0xc5eb75),
[0, 0.7, 0.13]
);
}
// Small physical port markers reinforce the projected HTML controls.
addMesh(
group,
new THREE.IcosahedronGeometry(0.1, 0),
standardMaterial(0x205747),
[-0.8, 0.28, 0.34]
);
addMesh(
group,
new THREE.IcosahedronGeometry(0.1, 0),
standardMaterial(0x205747),
[0.8, 0.28, 0.34]
);
}
function findOpenPosition() {
const candidates = [
[-3.7, -3.1], [0, -3.25], [3.7, -3.1],
[-4.5, 0], [4.5, 0], [-3.8, 3.4],
[0, 3.5], [3.8, 3.4]
];
for (const [x, z] of candidates) {
let available = true;
for (const module of modules.values()) {
if (Math.hypot(module.group.position.x - x, module.group.position.z - z) < 1.25) {
available = false;
break;
}
}
if (available) return { x, z };
}
const angle = modules.size * 1.73;
return {
x: Math.cos(angle) * 4.3,
z: Math.sin(angle) * 4.3
};
}
function addModule(type, position = null) {
const def = moduleDefs[type];
const module = {
id: `module-${nextModuleId++}`,
type,
name: def.name,
action: def.action,
owner: "any",
strength: def.strength,
curve: def.curve,
height: def.height,
next: null,
group: new THREE.Group(),
dom: {}
};
const pos = position || findOpenPosition();
module.group.position.set(pos.x, 0, pos.z);
module.group.userData.moduleId = module.id;
createModuleVisual(module);
scene.add(module.group);
modules.set(module.id, module);
const tag = document.createElement("button");
tag.className = "module-tag";
tag.type = "button";
tag.setAttribute("aria-label", `Select ${module.name}`);
tag.addEventListener("click", () => selectModule(module.id));
labelsLayer.appendChild(tag);
module.dom.tag = tag;
const input = document.createElement("button");
input.className = "port-button in";
input.type = "button";
input.textContent = "IN";
input.title = `Connect into ${module.name}`;
input.addEventListener("click", () => handleInputPort(module.id));
labelsLayer.appendChild(input);
module.dom.input = input;
const output = document.createElement("button");
output.className = "port-button";
output.type = "button";
output.textContent = "OUT";
output.title = `Connect out of ${module.name}`;
output.addEventListener("click", () => handleOutputPort(module.id));
labelsLayer.appendChild(output);
module.dom.output = output;
updateModuleTag(module);
return module;
}
function updateModuleTag(module) {
const def = moduleDefs[module.type];
module.dom.tag.innerHTML = `
<span class="tag-dot" style="background:#${def.color.toString(16).padStart(6, "0")}"></span>
<span>${module.name}</span>
<span class="tag-action">${actionLabels[module.action]}</span>
`;
module.dom.tag.classList.toggle("selected", selectedId === module.id);
}
function disposeObject(object) {
object.traverse((child) => {
if (child.geometry) child.geometry.dispose();
if (child.material) {
const materials = Array.isArray(child.material)
? child.material
: [child.material];
materials.forEach((material) => material.dispose());
}
});
}
function deleteModule(id) {
const module = modules.get(id);
if (!module) return;
clearTimeout(autoTimer);
modules.forEach((other) => {
if (other.next === id) other.next = null;
});
scene.remove(module.group);
disposeObject(module.group);
module.dom.tag.remove();
module.dom.input.remove();
module.dom.output.remove();
modules.delete(id);
if (selectedId === id) selectedId = null;
if (currentId === id) resetRun();
refreshAll();
showToast(`${module.name} removed from the route.`);
}
function duplicateModule(id) {
const source = modules.get(id);
if (!source) return;
const copy = addModule(source.type, {
x: source.group.position.x + 0.85,
z: source.group.position.z + 0.85
});
copy.name = `${source.name} copy`;
copy.action = source.action;
copy.owner = source.owner;
copy.strength = source.strength;
copy.curve = source.curve;
copy.height = source.height;
selectModule(copy.id);
refreshAll();
showToast("Module duplicated. Connect its OUT port to continue the route.");
}
// ----- Route graph and visuals -----
function connectModules(sourceId, targetId) {
if (sourceId === targetId) {
showToast("A module cannot connect to itself.");
return;
}
const source = modules.get(sourceId);
const target = modules.get(targetId);
if (!source || !target) return;
// Prevent closed loops because the shared run follows one directed chain.
let cursor = target;
const visited = new Set();
while (cursor) {
if (cursor.id === source.id) {
showToast("That connection would create a loop.");
return;
}
if (visited.has(cursor.id)) break;
visited.add(cursor.id);
cursor = cursor.next ? modules.get(cursor.next) : null;
}
source.next = target.id;
pendingSourceId = null;
refreshAll();
showToast(`${source.name} now leads to ${target.name}.`);
}
function handleOutputPort(id) {
pendingSourceId = pendingSourceId === id ? null : id;
updatePortStates();
if (pendingSourceId) {
const module = modules.get(id);
showToast(`Choose an IN port to connect ${module.name}.`);
}
}
function handleInputPort(id) {
if (!pendingSourceId) {
showToast("Select an OUT port first, then choose this IN port.");
return;
}
connectModules(pendingSourceId, id);
}
function updatePortStates() {
modules.forEach((module) => {
module.dom.output.classList.toggle("pending", pendingSourceId === module.id);
module.dom.input.classList.toggle("pending", Boolean(pendingSourceId));
});
}
function refreshRouteGeometry() {
while (routeGroup.children.length) {
const child = routeGroup.children[0];
routeGroup.remove(child);
disposeObject(child);
}
modules.forEach((module) => {
if (!module.next) return;
const target = modules.get(module.next);
if (!target) return;
const from = module.group.position.clone();
from.y = 0.075;
const to = target.group.position.clone();
to.y = 0.075;
const direction = to.clone().sub(from);
direction.y = 0;
if (direction.lengthSq() < 0.001) direction.set(1, 0, 0);
direction.normalize();
const perpendicular = new THREE.Vector3(-direction.z, 0, direction.x);
const control = from.clone().lerp(to, 0.5);
control.addScaledVector(perpendicular, THREE.MathUtils.clamp(module.curve / 90, -0.8, 0.8));
control.y = 0.075;
const curve = new THREE.QuadraticBezierCurve3(from, control, to);
const tube = new THREE.Mesh(
new THREE.TubeGeometry(curve, 24, 0.035, 6, false),
new THREE.MeshBasicMaterial({
color: module.type === "goal" ? 0x7ebd54 : 0x39a99d,
transparent: true,
opacity: 0.78
})
);
tube.receiveShadow = true;
routeGroup.add(tube);
});
}
function getRouteChain() {
const start = [...modules.values()].find((module) => module.type === "launch");
if (!start) return { chain: [], cycle: false, hasGoal: false };
const chain = [start];
const seen = new Set([start.id]);
let current = start;
let cycle = false;
while (current.next) {
const next = modules.get(current.next);
if (!next) break;
if (seen.has(next.id)) {
cycle = true;
break;
}
seen.add(next.id);
chain.push(next);
current = next;
}
return {
chain,
cycle,
hasGoal: chain.some((module) => module.type === "goal")
};
}
function updateRouteStatus() {
const route = getRouteChain();
const linkCount = [...modules.values()].filter((module) => module.next).length;
const valid = route.hasGoal && !route.cycle && route.chain.length > 1;
const status = $("#route-status");
status.classList.toggle("invalid", !valid);
$("#route-status-text").textContent = valid
? `${route.chain.length} stops · ${linkCount} links · route ready`
: `${modules.size} modules · ${linkCount} links · route incomplete`;
}
// ----- Sidebar rendering -----
function renderModuleList() {
const list = $("#module-list");
list.innerHTML = "";
$("#module-count").textContent = `${modules.size} module${modules.size === 1 ? "" : "s"}`;
if (!modules.size) {
list.innerHTML = '<div class="empty-state">Add a module to begin the shared route.</div>';
return;
}
const route = getRouteChain();
const order = new Map(route.chain.map((module, index) => [module.id, index + 1]));
[...modules.values()].forEach((module) => {
const row = document.createElement("button");
row.type = "button";
row.className = `module-row${selectedId === module.id ? " selected" : ""}`;
const color = `#${moduleDefs[module.type].color.toString(16).padStart(6, "0")}`;
const next = module.next ? modules.get(module.next) : null;
const orderText = order.has(module.id) ? `Stop ${order.get(module.id)}` : "Not on start route";
row.innerHTML = `
<span class="row-dot" style="background:${color}"></span>
<span>
<strong>${module.name}</strong>
<small>${orderText} · ${next ? `Next: ${next.name}` : "Open route"}</small>
</span>
<span class="action-chip">${actionLabels[module.action]}</span>
`;
row.addEventListener("click", () => selectModule(module.id));
list.appendChild(row);
});
}
function selectModule(id) {
selectedId = id;
const module = modules.get(id);
if (module) {
selectionRing.visible = true;
selectionRing.position.set(
module.group.position.x,
0.075,
module.group.position.z
);
} else {
selectionRing.visible = false;
}
renderModuleList();
renderConfig();
modules.forEach(updateModuleTag);
}
function renderConfig() {
const container = $("#config-content");
const module = modules.get(selectedId);
if (!module) {
container.innerHTML = `
<div class="empty-state">
Select a module in the scene or list to configure its action,
power, curve, and next connection.
</div>
`;
return;
}
const options = [...modules.values()]
.filter((other) => other.id !== module.id)
.map((other) => `
<option value="${other.id}" ${other.id === module.next ? "selected" : ""}>
${other.name}
</option>
`).join("");
container.innerHTML = `
<div class="field">
<label for="module-name">Module name</label>
<input id="module-name" type="text" value="${module.name.replace(/"/g, """)}" />
</div>
<div class="field">
<label for="module-action">Required action</label>
<select id="module-action">
<option value="tap" ${module.action === "tap" ? "selected" : ""}>Tap</option>
<option value="tilt" ${module.action === "tilt" ? "selected" : ""}>Tilt</option>
<option value="hold" ${module.action === "hold" ? "selected" : ""}>Hold</option>
<option value="any" ${module.action === "any" ? "selected" : ""}>Any input</option>
<option value="auto" ${module.action === "auto" ? "selected" : ""}>Auto assist</option>
</select>
</div>
<div class="field">
<label for="module-owner">Who can contribute?</label>
<select id="module-owner">
<option value="any" ${module.owner === "any" ? "selected" : ""}>Any teammate</option>
<option value="maya" ${module.owner === "maya" ? "selected" : ""}>Maya</option>
<option value="noah" ${module.owner === "noah" ? "selected" : ""}>Noah</option>
<option value="ari" ${module.owner === "ari" ? "selected" : ""}>Ari</option>
</select>
</div>
<div class="field">
<label for="module-power">
Strength
<output id="power-output">${module.strength}%</output>
</label>
<input id="module-power" type="range" min="0" max="100" value="${module.strength}" />
<div class="range-ends"><span>Gentle</span><span>Powerful</span></div>
</div>
<div class="field">
<label for="module-curve">
Directional curve
<output id="curve-output">${module.curve}</output>
</label>
<input id="module-curve" type="range" min="-100" max="100" value="${module.curve}" />
<div class="range-ends"><span>Left</span><span>Straight</span><span>Right</span></div>
</div>
<div class="field">
<label for="module-height">
Bounce height
<output id="height-output">${module.height}%</output>
</label>
<input id="module-height" type="range" min="0" max="100" value="${module.height}" />
<div class="range-ends"><span>Low</span><span>High</span></div>
</div>
<div class="field">
<label for="module-next">Next module</label>
<select id="module-next">
<option value="">Open route</option>
${options}
</select>
</div>
<div class="button-row">
<button id="duplicate-module" class="secondary-button" type="button">Duplicate</button>
<button id="delete-module" class="danger-button" type="button">Delete</button>
</div>
`;
$("#module-name").addEventListener("change", (event) => {
module.name = event.target.value.trim() || moduleDefs[module.type].name;
updateModuleTag(module);
renderModuleList();
});
$("#module-action").addEventListener("change", (event) => {
module.action = event.target.value;
updateModuleTag(module);
renderModuleList();
if (runState === "waiting" && currentId === module.id) {
enterModule(module.id, false);
}
});
$("#module-owner").addEventListener("change", (event) => {
module.owner = event.target.value;
if (runState === "waiting" && currentId === module.id) {
updatePrompt();
}
});
$("#module-power").addEventListener("input", (event) => {
module.strength = Number(event.target.value);
$("#power-output").textContent = `${module.strength}%`;
});
$("#module-curve").addEventListener("input", (event) => {
module.curve = Number(event.target.value);
$("#curve-output").textContent = module.curve;
refreshRouteGeometry();
});
$("#module-height").addEventListener("input", (event) => {
module.height = Number(event.target.value);
$("#height-output").textContent = `${module.height}%`;
});
$("#module-next").addEventListener("change", (event) => {
if (event.target.value) {
connectModules(module.id, event.target.value);
} else {
module.next = null;
refreshAll();
showToast(`${module.name} is now an open route.`);
}
});
$("#duplicate-module").addEventListener("click", () => duplicateModule(module.id));
$("#delete-module").addEventListener("click", () => deleteModule(module.id));
}
function refreshAll() {
renderModuleList();
renderConfig();
modules.forEach(updateModuleTag);
updatePortStates();
refreshRouteGeometry();
updateRouteStatus();
if (selectedId && modules.has(selectedId)) {
const module = modules.get(selectedId);
selectionRing.visible = true;
selectionRing.position.set(
module.group.position.x,
0.075,
module.group.position.z
);
} else {
selectionRing.visible = false;
}
}
// ----- Shared run logic -----
function startRun() {
clearTimeout(autoTimer);
const route = getRouteChain();
if (!route.chain.length) {
showToast("Add a Launch pad before starting the shared run.");
return;
}
if (route.cycle) {
showToast("Remove the loop in the route before starting.");
return;
}
if (!route.hasGoal) {
showToast("Connect the route to a Shared Goal before starting.");
return;
}
pendingSourceId = null;
updatePortStates();
contributions.clear();
teamScore = 0;
reachedCount = 0;
segment = null;
const start = route.chain[0];
currentId = start.id;
ball.position.set(start.group.position.x, 0.5, start.group.position.z);
ball.rotation.set(0, 0, 0);
trailHistory.length = 0;
enterModule(start.id);
showToast("Shared run started. Follow the team prompt.");
}
function enterModule(id, countVisit = true) {
clearTimeout(autoTimer);
const module = modules.get(id);
if (!module) return;
currentId = id;
if (countVisit) reachedCount += 1;
if (module.type === "goal") {
completeRun();
return;
}
runState = "waiting";
updatePrompt();
updateControls();
if (module.action === "auto") {
autoTimer = setTimeout(() => {
if (runState !== "waiting" || currentId !== id) return;
contributions.set("assist", (contributions.get("assist") || 0) + 1);
teamScore += 10;
advanceFromCurrent(0.5);
}, 650);
}
}
function performAction(participantId, value = 0.75) {
if (runState !== "waiting") {
showToast("The ball is moving. Wait for the next shared prompt.");
return false;
}
const module = modules.get(currentId);
const participant = participants[participantId];
if (!module || !participant) return false;
if (module.owner !== "any" && module.owner !== participantId) {
showToast(`${module.name} is assigned to ${participants[module.owner].name}.`);
return false;
}
if (module.action !== "any" && module.action !== participant.action) {
showToast(`This stop needs ${actionLabels[module.action].toLowerCase()}.`);
return false;
}
contributions.set(participantId, (contributions.get(participantId) || 0) + 1);
teamScore += Math.round(10 + module.strength * 0.35);
advanceFromCurrent(value);
return true;
}
function advanceFromCurrent(actionValue) {
const module = modules.get(currentId);
if (!module || !module.next) {
runState = "blocked";
updatePrompt();
updateControls();
showToast("This route is open. Connect it to another module.");
return;
}
const target = modules.get(module.next);
if (!target) return;
const from = module.group.position.clone();
const to = target.group.position.clone();
const distance = from.distanceTo(to);
segment = {
sourceId: module.id,
targetId: target.id,
from,
to,
t: 0,
duration: THREE.MathUtils.clamp(distance / (2.2 + module.strength / 80), 0.95, 2.5),
actionValue
};
runState = "running";
updatePrompt();
updateControls();
}
function completeRun() {
runState = "complete";
segment = null;
teamScore += 100;
ball.position.y = 0.52;
spawnConfetti();
updatePrompt();
updateControls();
showToast("Goal reached! The whole team shared the outcome.");
}
function resetRun() {
clearTimeout(autoTimer);
runState = "idle";
currentId = null;
segment = null;
reachedCount = 0;
teamScore = 0;
contributions.clear();
const start = [...modules.values()].find((module) => module.type === "launch");
if (start) {
ball.position.set(start.group.position.x, 0.5, start.group.position.z);
} else {
ball.position.set(0, 0.5, 0);
}
trailHistory.length = 0;
updatePrompt();
updateControls();
}
function togglePause() {
if (runState === "running") {
runState = "paused";
updatePrompt();
updateControls();
} else if (runState === "paused") {
runState = "running";
updatePrompt();
updateControls();
}
}
function updatePrompt() {
const title = $("#prompt-title");
const text = $("#prompt-text");
const overline = $("#prompt-overline");
const progress = $("#progress-fill");
const route = getRouteChain();
const total = Math.max(1, route.chain.length - 1);
if (runState === "idle") {
overline.textContent = "Next shared move";
title.textContent = "Ready to build a shared route?";
text.textContent = "Connect the glowing IN and OUT ports, then start the shared run.";
progress.style.width = "0%";
} else if (runState === "waiting") {
const module = modules.get(currentId);
overline.textContent = "Waiting for a shared contribution";
title.textContent = `${module.name} · ${actionLabels[module.action]}`;
if (module.owner !== "any") {
text.textContent = `${participants[module.owner].name} is assigned to this stop. Use the matching control to move the team forward.`;
} else if (module.action === "any") {
text.textContent = "Any compatible control can move the team forward—use tap, tilt, or hold.";
} else {
text.textContent = `Any teammate can use the ${actionLabels[module.action].toLowerCase()} control. No identical movement ability is required.`;
}
progress.style.width = `${Math.min(100, ((reachedCount - 1) / total) * 100)}%`;
} else if (runState === "running") {
overline.textContent = "Shared move in motion";
title.textContent = "The team is moving the ball";
text.textContent = "The module’s strength and direction are shaping the path for everyone.";
progress.style.width = `${Math.min(100, ((reachedCount - 1) / total) * 100)}%`;
} else if (runState === "paused") {
overline.textContent = "Route paused";
title.textContent = "Take a shared pause";
text.textContent = "Resume when the team is ready. The current ball position is preserved.";
} else if (runState === "complete") {
overline.textContent = "Shared outcome";
title.textContent = "Goal reached together";
text.textContent = "Every participant helped move the same ball through a route designed for different abilities.";
progress.style.width = "100%";
} else if (runState === "blocked") {
overline.textContent = "Route needs a connection";
title.textContent = "This path is open";
text.textContent = "Connect this module to another stop to continue the shared run.";
}
$("#prompt-score").textContent = `Team score ${teamScore}`;
renderContributors();
renderParticipantStates();
}
function renderContributors() {
const container = $("#contributors");
container.innerHTML = "";
if (!contributions.size) {
container.innerHTML = '<span class="contributor-chip">No contributions yet</span>';
return;
}
[...contributions.entries()].forEach(([id, count]) => {
const participant = participants[id];
const chip = document.createElement("span");
chip.className = "contributor-chip";
chip.textContent = `${participant.name} × ${count}`;
container.appendChild(chip);
});
}
function renderParticipantStates() {
Object.keys(participants).forEach((id) => {
if (id === "assist") return;
const card = $(`#participant-${id}`);
const state = card.querySelector(".participant-state");
const count = contributions.get(id) || 0;
card.classList.toggle("contributed", count > 0);
state.textContent = count ? `Helped × ${count}` : "Ready";
});
}
function updateControls() {
const runButton = $("#run-button");
const pauseButton = $("#pause-button");
if (runState === "waiting") {
runButton.textContent = "Waiting for input";
runButton.disabled = true;
} else if (runState === "running") {
runButton.textContent = "Ball in motion";
runButton.disabled = true;
} else if (runState === "paused") {
runButton.textContent = "Route paused";
runButton.disabled = true;
} else if (runState === "complete") {
runButton.textContent = "Run again";
runButton.disabled = false;
} else {
runButton.textContent = "Start shared run";
runButton.disabled = false;
}
pauseButton.disabled = runState !== "running" && runState !== "paused";
pauseButton.textContent = runState === "paused" ? "Resume" : "Pause";
}
function showToast(message) {
clearTimeout(toastTimer);
const toast = $("#toast");
toast.textContent = message;
toast.classList.add("show");
toastTimer = setTimeout(() => toast.classList.remove("show"), 2600);
}
// ----- Confetti -----
const confetti = [];
function spawnConfetti() {
const colors = [0xff806f, 0x687cff, 0x39c4b2, 0xffc95d, 0xc5eb75];
for (let i = 0; i < 36; i++) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(0.09, 0.035, 0.15),
standardMaterial(colors[i % colors.length])
);
mesh.position.copy(ball.position);
mesh.position.y += 0.8;
mesh.castShadow = true;
scene.add(mesh);
const angle = Math.random() * Math.PI * 2;
const speed = 1.5 + Math.random() * 2.5;
confetti.push({
mesh,
velocity: new THREE.Vector3(
Math.cos(angle) * speed,
2.2 + Math.random() * 3,
Math.sin(angle) * speed
),
spin: new THREE.Vector3(
Math.random() * 5,
Math.random() * 5,
Math.random() * 5
),
life: 2.4
});
}
}
function updateConfetti(dt) {
for (let i = confetti.length - 1; i >= 0; i--) {
const item = confetti[i];
item.life -= dt;
item.velocity.y -= 5.6 * dt;
item.mesh.position.addScaledVector(item.velocity, dt);
item.mesh.rotation.x += item.spin.x * dt;
item.mesh.rotation.y += item.spin.y * dt;
item.mesh.rotation.z += item.spin.z * dt;
if (item.life <= 0 || item.mesh.position.y < -1) {
scene.remove(item.mesh);
disposeObject(item.mesh);
confetti.splice(i, 1);
}
}
}
// ----- Camera and direct pointer controls -----
let cameraYaw = 0.64;
let cameraPitch = 0.78;
let cameraRadius = 18.5;
const cameraTarget = new THREE.Vector3(0, 0, 0);
function updateCamera() {
camera.position.set(
cameraTarget.x + cameraRadius * Math.sin(cameraPitch) * Math.sin(cameraYaw),
cameraTarget.y + cameraRadius * Math.cos(cameraPitch),
cameraTarget.z + cameraRadius * Math.sin(cameraPitch) * Math.cos(cameraYaw)
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraYaw = 0.64;
cameraPitch = 0.78;
cameraRadius = 18.5;
updateCamera();
}
updateCamera();
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
const dragPoint = new THREE.Vector3();
const pointerState = {
mode: null,
id: null,
lastX: 0,
lastY: 0,
startX: 0,
startY: 0,
moved: false,
offset: new THREE.Vector3()
};
function setRayFromEvent(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);
}
function findModuleHit(event) {
setRayFromEvent(event);
const hits = raycaster.intersectObjects(
[...modules.values()].map((module) => module.group),
true
);
for (const hit of hits) {
let object = hit.object;
while (object) {
if (object.userData.moduleId) {
return { module: modules.get(object.userData.moduleId), point: hit.point };
}
object = object.parent;
}
}
return null;
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0 && event.button !== 2) return;
renderer.domElement.setPointerCapture(event.pointerId);
pointerState.mode = "orbit";
pointerState.id = null;
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
pointerState.startX = event.clientX;
pointerState.startY = event.clientY;
pointerState.moved = false;
const hit = findModuleHit(event);
if (hit && event.button === 0) {
pointerState.mode = "drag";
pointerState.id = hit.module.id;
selectModule(hit.module.id);
if (raycaster.ray.intersectPlane(dragPlane, dragPoint)) {
pointerState.offset.copy(hit.module.group.position).sub(dragPoint);
}
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointerState.mode) return;
const dx = event.clientX - pointerState.lastX;
const dy = event.clientY - pointerState.lastY;
if (Math.hypot(
event.clientX - pointerState.startX,
event.clientY - pointerState.startY
) > 4) {
pointerState.moved = true;
}
if (pointerState.mode === "orbit") {
cameraYaw -= dx * 0.006;
cameraPitch = THREE.MathUtils.clamp(cameraPitch + dy * 0.005, 0.45, 1.25);
updateCamera();
} else if (pointerState.mode === "drag" && pointerState.id) {
setRayFromEvent(event);
if (raycaster.ray.intersectPlane(dragPlane, dragPoint)) {
const module = modules.get(pointerState.id);
if (!module) return;
const position = dragPoint.clone().add(pointerState.offset);
const radius = Math.hypot(position.x, position.z);
if (radius > 5.65) {
position.x *= 5.65 / radius;
position.z *= 5.65 / radius;
}
module.group.position.x = position.x;
module.group.position.z = position.z;
selectionRing.position.set(position.x, 0.075, position.z);
refreshRouteGeometry();
}
}
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
});
function endPointer(event) {
if (pointerState.mode === "drag" && pointerState.id && !pointerState.moved) {
selectModule(pointerState.id);
}
pointerState.mode = null;
pointerState.id = null;
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener("contextmenu", (event) => event.preventDefault());
renderer.domElement.addEventListener("wheel", (event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(cameraRadius + event.deltaY * 0.012, 12, 25);
updateCamera();
}, { passive: false });
renderer.domElement.addEventListener("dblclick", resetCamera);
// ----- Projected DOM labels -----
function placeOverlay(element, worldPosition) {
const projected = worldPosition.clone().project(camera);
const width = labelsLayer.clientWidth;
const height = labelsLayer.clientHeight;
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
const visible = projected.z > -1 && projected.z < 1;
element.style.visibility = visible ? "visible" : "hidden";
element.style.transform = `translate(-50%, -50%) translate(${x}px, ${y}px)`;
}
function updateOverlayPositions() {
modules.forEach((module) => {
module.group.updateWorldMatrix(true, false);
const tagPosition = module.group.localToWorld(new THREE.Vector3(0, 1.62, 0));
const inputPosition = module.group.localToWorld(new THREE.Vector3(-0.8, 0.28, 0.34));
const outputPosition = module.group.localToWorld(new THREE.Vector3(0.8, 0.28, 0.34));
placeOverlay(module.dom.tag, tagPosition);
placeOverlay(module.dom.input, inputPosition);
placeOverlay(module.dom.output, outputPosition);
});
}
// ----- Participant controls and keyboard access -----
$("#maya-button").addEventListener("click", () => performAction("maya", 0.85));
const noahSlider = $("#noah-slider");
const noahOutput = $("#noah-output");
noahSlider.addEventListener("input", () => {
noahOutput.value = noahSlider.value;
});
noahSlider.addEventListener("change", () => {
performAction("noah", Number(noahSlider.value) / 100);
});
let holdStart = 0;
let holdTimer = null;
let holdFired = false;
const ariButton = $("#ari-button");
ariButton.addEventListener("pointerdown", (event) => {
event.preventDefault();
ariButton.setPointerCapture(event.pointerId);
holdStart = performance.now();
holdFired = false;
holdTimer = setTimeout(() => {
holdFired = true;
performAction("ari", 1);
}, 350);
});
ariButton.addEventListener("pointerup", () => {
clearTimeout(holdTimer);
const elapsed = performance.now() - holdStart;
if (!holdFired && elapsed >= 120) {
performAction("ari", 0.7);
} else if (!holdFired) {
showToast("Hold Ari’s button a little longer, or press H.");
}
});
ariButton.addEventListener("pointercancel", () => clearTimeout(holdTimer));
ariButton.addEventListener("click", (event) => {
if (event.detail === 0) performAction("ari", 1);
});
document.addEventListener("keydown", (event) => {
const tag = event.target.tagName;
if (["INPUT", "SELECT", "TEXTAREA", "BUTTON"].includes(tag)) return;
if (event.code === "Space") {
event.preventDefault();
performAction("maya", 0.85);
} else if (event.key.toLowerCase() === "h") {
event.preventDefault();
performAction("ari", 1);
} else if (event.key === "ArrowLeft" || event.key === "ArrowRight") {
event.preventDefault();
const delta = event.key === "ArrowLeft" ? -10 : 10;
noahSlider.value = String(
THREE.MathUtils.clamp(Number(noahSlider.value) + delta, -100, 100)
);
noahOutput.value = noahSlider.value;
performAction("noah", Number(noahSlider.value) / 100);
}
});
$("#run-button").addEventListener("click", startRun);
$("#pause-button").addEventListener("click", togglePause);
$("#reset-button").addEventListener("click", resetRun);
$("#reset-view").addEventListener("click", resetCamera);
document.querySelectorAll("[data-add-type]").forEach((button) => {
button.addEventListener("click", () => {
const module = addModule(button.dataset.addType);
selectModule(module.id);
refreshAll();
showToast(`${module.name} added. Use its OUT port to connect the route.`);
});
});
// ----- Initial route -----
const launch = addModule("launch", { x: -4.55, z: 1.35 });
const ramp = addModule("ramp", { x: -2.3, z: -1.15 });
const bounce = addModule("bounce", { x: 0, z: 1.35 });
const fan = addModule("fan", { x: 2.3, z: -1.15 });
const goal = addModule("goal", { x: 4.55, z: 1.35 });
launch.next = ramp.id;
ramp.next = bounce.id;
bounce.next = fan.id;
fan.next = goal.id;
selectModule(launch.id);
refreshAll();
updatePrompt();
updateControls();
// ----- Resize and animation loop -----
function resize() {
const width = viewport.clientWidth;
const height = viewport.clientHeight;
if (!width || !height) return;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(viewport);
resize();
const clock = new THREE.Clock();
function updateBall(dt) {
if (runState === "running" && segment) {
const source = modules.get(segment.sourceId);
segment.t = Math.min(1, segment.t + dt / segment.duration);
const t = segment.t;
const arch = Math.sin(Math.PI * t);
const position = segment.from.clone().lerp(segment.to, t);
const direction = segment.to.clone().sub(segment.from);
direction.y = 0;
if (direction.lengthSq() < 0.001) direction.set(1, 0, 0);
direction.normalize();
const perpendicular = new THREE.Vector3(-direction.z, 0, direction.x);
const curveAmount = source
? (source.curve / 100) * arch * (0.7 + Math.abs(segment.actionValue) * 0.35)
: 0;
position.addScaledVector(perpendicular, curveAmount);
position.y = 0.49;
if (source) {
if (source.type === "launch") {
position.y += arch * (0.55 + source.strength / 100 * 1.8);
} else if (source.type === "bounce") {
position.y += Math.abs(Math.sin(Math.PI * t * 3)) *
(0.18 + source.height / 100 * 1.55);
} else if (source.type === "ramp") {
position.y += arch * 0.18;
} else if (source.type === "fan") {
position.y += arch * 0.32;
}
}
ball.position.copy(position);
ball.rotation.x += dt * 3.2;
ball.rotation.z += dt * 2.1;
if (t >= 1) {
const targetId = segment.targetId;
segment = null;
currentId = targetId;
const target = modules.get(targetId);
ball.position.set(target.group.position.x, 0.5, target.group.position.z);
enterModule(targetId);
}
}
trailHistory.unshift(ball.position.clone());
if (trailHistory.length > 20) trailHistory.pop();
trailMeshes.forEach((mesh, index) => {
const historyIndex = Math.min(index + 1, trailHistory.length - 1);
const history = trailHistory[historyIndex];
if (history) {
mesh.visible = runState === "running" || runState === "paused";
mesh.position.copy(history);
mesh.scale.setScalar(1 - index * 0.08);
} else {
mesh.visible = false;
}
});
}
renderer.setAnimationLoop(() => {
const dt = Math.min(clock.getDelta(), 0.05);
updateBall(dt);
updateConfetti(dt);
updateOverlayPositions();
renderer.render(scene, camera);
});
</script>
</body>
</html>
```