Prompt specification
Build or customize the Three.js 3D scene "One Basketball Arc Under Gravity" 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: One Basketball Arc Under Gravity
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/one-basketball-arc-under-gravity-x3626
Scene Description Prompt:
Animate a ball following a stated gravity-only trajectory from a fixed release point. Display predicted and actual paths and distinguish ideal flight from a full basketball simulation. Use Three.js from cdnjs in a single HTML file, with visible voxel blocks.
Technical checks: Start the ideal projectile sequence at release and give it a positive flight duration. Compare the computed and predicted paths using matched times and report their measured difference.
Return one complete HTML document that works with the cdnjs Three.js r160 module inside a sandbox with scripts allowed. Make the requested subject visible at the default camera. Use procedural assets and local button handlers. Do not use native form submission, pointer lock, external assets or runtime requests other than Three.js.
Working Three.js Starter (one-basketball-arc-under-gravity-x3626):
```html
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laboratório de Trajetórias — Quadra Voxel</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(10, 22, 37, 0.91);
--panel-border: rgba(143, 207, 255, 0.18);
--text: #eaf7ff;
--muted: #91abc2;
--cyan: #50e6ff;
--orange: #ff9d3d;
--green: #83f0ad;
--red: #ff7474;
}
* {
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,
input {
font: inherit;
}
#scene,
#scene canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
}
#scene canvas {
touch-action: none;
cursor: grab;
}
#scene canvas:active {
cursor: grabbing;
}
.topbar {
position: absolute;
top: 18px;
left: 20px;
right: 20px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 18px;
pointer-events: none;
z-index: 5;
}
.title-card {
max-width: 540px;
padding: 14px 17px;
border: 1px solid var(--panel-border);
border-radius: 14px;
background: linear-gradient(135deg, rgba(8, 19, 34, 0.92), rgba(13, 31, 52, 0.74));
box-shadow: 0 14px 40px rgba(0, 0, 0, 0.24);
backdrop-filter: blur(12px);
}
.eyebrow {
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 5px 0 4px;
font-size: clamp(20px, 2.4vw, 31px);
line-height: 1.08;
}
.subtitle {
margin: 0;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.mode-chip {
flex: 0 0 auto;
display: inline-flex;
align-items: center;
gap: 8px;
padding: 10px 13px;
border: 1px solid rgba(255, 157, 61, 0.35);
border-radius: 999px;
background: rgba(43, 27, 17, 0.83);
color: #ffd0a3;
font-size: 12px;
font-weight: 800;
box-shadow: 0 10px 28px rgba(0, 0, 0, 0.22);
}
.mode-chip::before {
content: "";
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--orange);
box-shadow: 0 0 16px var(--orange);
}
#panel {
position: absolute;
top: 112px;
right: 20px;
width: min(355px, calc(100vw - 40px));
max-height: calc(100vh - 206px);
overflow: auto;
padding: 16px;
border: 1px solid var(--panel-border);
border-radius: 16px;
background: var(--panel);
box-shadow: 0 18px 55px rgba(0, 0, 0, 0.35);
backdrop-filter: blur(15px);
z-index: 7;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin: 0 0 10px;
color: #cceaff;
font-size: 12px;
font-weight: 850;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.section-title + .section-title {
margin-top: 17px;
}
.valid-badge {
padding: 4px 7px;
border-radius: 6px;
background: rgba(83, 240, 159, 0.11);
color: var(--green);
font-size: 10px;
letter-spacing: 0.05em;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.metric {
min-height: 72px;
padding: 10px;
border: 1px solid rgba(151, 205, 240, 0.11);
border-radius: 10px;
background: rgba(255, 255, 255, 0.035);
}
.metric.wide {
grid-column: 1 / -1;
}
.metric-label {
color: var(--muted);
font-size: 10px;
line-height: 1.25;
text-transform: uppercase;
letter-spacing: 0.055em;
}
.metric-value {
display: block;
margin-top: 6px;
font-size: 18px;
font-weight: 850;
font-variant-numeric: tabular-nums;
}
.metric-value.cyan {
color: var(--cyan);
}
.metric-value.orange {
color: var(--orange);
}
.metric-value.green {
color: var(--green);
}
.metric-note {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
.formula {
margin-top: 9px;
padding: 10px;
overflow-x: auto;
border-left: 3px solid var(--cyan);
border-radius: 7px;
background: rgba(80, 230, 255, 0.055);
color: #c5f7ff;
font: 12px/1.5 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
white-space: nowrap;
}
.model-note {
margin: 0;
color: #a8bfd2;
font-size: 11px;
line-height: 1.5;
}
.model-note strong {
color: #eaf7ff;
}
.live-box {
padding: 10px;
border-radius: 10px;
background: rgba(0, 0, 0, 0.18);
}
.live-row {
display: flex;
justify-content: space-between;
gap: 12px;
padding: 3px 0;
color: var(--muted);
font-size: 11px;
}
.live-row span:last-child {
color: var(--text);
font-variant-numeric: tabular-nums;
text-align: right;
}
#liveEvent {
margin-top: 7px;
padding-top: 7px;
border-top: 1px solid rgba(255, 255, 255, 0.08);
color: #ffd3a9;
font-size: 11px;
line-height: 1.35;
}
.toggles {
display: flex;
flex-wrap: wrap;
gap: 10px 14px;
margin-top: 11px;
}
.toggle {
display: inline-flex;
align-items: center;
gap: 7px;
color: #c7d9e8;
font-size: 11px;
cursor: pointer;
user-select: none;
}
.toggle input {
width: 15px;
height: 15px;
margin: 0;
accent-color: var(--cyan);
}
#legend {
position: absolute;
left: 20px;
bottom: 93px;
display: flex;
flex-direction: column;
gap: 7px;
padding: 11px 13px;
border: 1px solid var(--panel-border);
border-radius: 12px;
background: rgba(8, 20, 35, 0.83);
backdrop-filter: blur(10px);
z-index: 5;
pointer-events: none;
}
.legend-item {
display: flex;
align-items: center;
gap: 9px;
color: #c9dce9;
font-size: 11px;
}
.legend-line {
width: 31px;
height: 3px;
border-radius: 3px;
background: var(--cyan);
box-shadow: 0 0 9px rgba(80, 230, 255, 0.8);
}
.legend-line.orange {
background: var(--orange);
box-shadow: 0 0 9px rgba(255, 157, 61, 0.75);
}
.legend-line.orange {
background: repeating-linear-gradient(90deg, var(--orange) 0 6px, transparent 6px 9px);
}
#controls {
position: absolute;
left: 20px;
right: 20px;
bottom: 18px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
z-index: 8;
}
.control-group {
display: flex;
flex-wrap: wrap;
gap: 7px;
padding: 7px;
border: 1px solid var(--panel-border);
border-radius: 13px;
background: rgba(8, 20, 35, 0.88);
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.3);
backdrop-filter: blur(12px);
}
button {
min-height: 36px;
padding: 8px 13px;
border: 1px solid rgba(168, 215, 244, 0.16);
border-radius: 8px;
background: rgba(255, 255, 255, 0.055);
color: #dceefa;
font-size: 12px;
font-weight: 750;
cursor: pointer;
transition: background 120ms ease, border-color 120ms ease, transform 120ms ease;
}
button:hover {
background: rgba(255, 255, 255, 0.11);
border-color: rgba(168, 215, 244, 0.34);
}
button:active {
transform: translateY(1px);
}
button.primary {
border-color: rgba(80, 230, 255, 0.45);
background: rgba(80, 230, 255, 0.14);
color: #bdf6ff;
}
button[aria-pressed="true"] {
border-color: rgba(255, 157, 61, 0.65);
background: rgba(255, 157, 61, 0.16);
color: #ffd4a8;
}
.hint {
padding: 8px 11px;
border-radius: 9px;
background: rgba(8, 20, 35, 0.64);
color: #8fa9bd;
font-size: 10px;
}
.world-label {
position: absolute;
z-index: 4;
padding: 5px 8px;
border: 1px solid rgba(80, 230, 255, 0.36);
border-radius: 7px;
background: rgba(5, 18, 31, 0.84);
color: #bcf4ff;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.035em;
pointer-events: none;
transform: translate(-50%, -100%);
white-space: nowrap;
}
#hoopLabel {
border-color: rgba(255, 157, 61, 0.42);
color: #ffd0a1;
}
@media (max-width: 850px) {
.topbar {
top: 10px;
left: 10px;
right: 10px;
}
.title-card {
max-width: calc(100vw - 20px);
padding: 10px 12px;
}
.subtitle,
.mode-chip {
display: none;
}
#panel {
top: 89px;
right: 10px;
width: min(315px, calc(100vw - 20px));
max-height: calc(100vh - 184px);
padding: 12px;
}
#controls {
left: 10px;
right: 10px;
bottom: 10px;
}
.hint {
display: none;
}
#legend {
left: 10px;
bottom: 72px;
}
.metric {
min-height: 63px;
padding: 8px;
}
.metric-value {
font-size: 16px;
}
}
@media (max-height: 650px) {
#panel {
top: 82px;
max-height: calc(100vh - 164px);
}
.formula,
.model-note {
display: none;
}
}
</style>
</head>
<body>
<div id="scene" aria-label="Quadra de basquete tridimensional em estilo voxel"></div>
<div class="topbar">
<div class="title-card">
<div class="eyebrow">Laboratório de física · quadra voxel</div>
<h1>Trajetória da bola</h1>
<p class="subtitle">Compare a previsão analítica de gravidade com a simulação completa de basquete, incluindo ar, aro e quique.</p>
</div>
<div class="mode-chip" id="modeChip">Simulação completa</div>
</div>
<aside id="panel" aria-label="Dados da simulação">
<div class="section-title">
Trajetória ideal
<span class="valid-badge" id="sequenceBadge">SEQUÊNCIA VÁLIDA</span>
</div>
<div class="metric-grid">
<div class="metric">
<span class="metric-label">Voo completo ideal</span>
<span class="metric-value cyan" id="idealDuration">—</span>
<span class="metric-note">Da soltura ao 1º contato com o piso</span>
</div>
<div class="metric">
<span class="metric-label">Amostras desde t₀</span>
<span class="metric-value" id="idealSamples">—</span>
<span class="metric-note" id="sequenceNote">—</span>
</div>
<div class="metric wide">
<span class="metric-label">Raiz física usada</span>
<span class="metric-value green" id="rootResult">—</span>
<span class="metric-note">Somente a raiz positiva; nenhum tempo negativo é aceito.</span>
</div>
</div>
<div class="formula" id="formulaText">t⁺ = (vᵧ + √(vᵧ² + 2g(y₀ − r))) / g</div>
<div class="section-title">Trajetória completa</div>
<div class="metric-grid">
<div class="metric">
<span class="metric-label">1º contato no piso</span>
<span class="metric-value orange" id="fullDuration">—</span>
<span class="metric-note">Integração numérica a 240 Hz</span>
</div>
<div class="metric">
<span class="metric-label">Desvio sincronizado</span>
<span class="metric-value" id="deviationValue">—</span>
<span class="metric-note" id="deviationNote">Comparação no mesmo instante</span>
</div>
<div class="metric wide">
<span class="metric-label">Resultado no aro</span>
<span class="metric-value orange" id="hoopResult">—</span>
<span class="metric-note" id="hoopNote">Posição da bola no plano do aro</span>
</div>
</div>
<p class="model-note">
<strong>Modelos distintos:</strong> a previsão ideal usa somente <strong>g</strong>; a trajetória completa usa gravidade, arrasto, Magnus, colisões, restituição e atrito. Elas não são equivalentes.
</p>
<div class="section-title">Leitura em tempo real</div>
<div class="live-box">
<div class="live-row"><span>Modo</span><span id="liveMode">Completo</span></div>
<div class="live-row"><span>Tempo</span><span id="liveTime">0,000 s</span></div>
<div class="live-row"><span>Posição xyz</span><span id="livePosition">—</span></div>
<div class="live-row"><span>Diferença da ideal</span><span id="liveDifference">—</span></div>
<div id="liveEvent">Pronto para o lançamento.</div>
</div>
<div class="toggles">
<label class="toggle"><input type="checkbox" id="showIdeal" checked> Mostrar ideal</label>
<label class="toggle"><input type="checkbox" id="showFull" checked> Mostrar completa</label>
</div>
</aside>
<div id="legend" aria-label="Legenda das trajetórias">
<div class="legend-item"><span class="legend-line"></span> Previsto: ideal, gravidade apenas</div>
<div class="legend-item"><span class="legend-line orange"></span> Real: basketball completa</div>
</div>
<div id="controls">
<div class="control-group" aria-label="Controles da simulação">
<button type="button" class="primary" id="launchButton">▶ Lançar</button>
<button type="button" id="pauseButton">Pausar</button>
<button type="button" id="resetButton">Reiniciar</button>
<button type="button" data-mode="ideal" aria-pressed="false">Ideal</button>
<button type="button" data-mode="full" aria-pressed="true">Completo</button>
<button type="button" id="cameraButton">Câmera</button>
</div>
<div class="hint">Arraste para orbitar · roda do mouse para aproximar · duplo clique para enquadrar</div>
</div>
<div class="world-label" id="releaseLabel">SOLTURA FIXA</div>
<div class="world-label" id="hoopLabel">ARO</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
const clamp = THREE.MathUtils.clamp;
const lerp = THREE.MathUtils.lerp;
const G = 9.81;
const DRAG = 0.0105;
const MAGNUS = 0.0011;
const BALL_RADIUS = 0.23;
const FIXED_DT = 1 / 240;
const RELEASE = new THREE.Vector3(-5.2, 2.35, 4.8);
const HOOP_CENTER = new THREE.Vector3(0, 3.05, -6.7);
const HOOP_RADIUS = 0.46;
const HOOP_TUBE = 0.05;
const RELEASE_TO_HOOP_TIME = 1.55;
const initialVelocity = new THREE.Vector3(
(HOOP_CENTER.x - RELEASE.x) / RELEASE_TO_HOOP_TIME,
(HOOP_CENTER.y + BALL_RADIUS - RELEASE.y + 0.5 * G * RELEASE_TO_HOOP_TIME ** 2) / RELEASE_TO_HOOP_TIME,
(HOOP_CENTER.z - RELEASE.z) / RELEASE_TO_HOOP_TIME
);
const spin = new THREE.Vector3(0, 0, 30);
function idealPosition(time) {
return new THREE.Vector3(
RELEASE.x + initialVelocity.x * time,
RELEASE.y + initialVelocity.y * time - 0.5 * G * time * time,
RELEASE.z + initialVelocity.z * time
);
}
// A raiz positiva é calculada diretamente para garantir t > 0.
const idealDiscriminant =
initialVelocity.y * initialVelocity.y +
2 * G * Math.max(0, RELEASE.y - BALL_RADIUS);
const idealImpactTime =
(initialVelocity.y + Math.sqrt(idealDiscriminant)) / G;
function buildIdealSamples() {
const count = 121;
const samples = [];
for (let i = 0; i < count; i++) {
const t = idealImpactTime * i / (count - 1);
samples.push({ t, p: idealPosition(t) });
}
return samples;
}
function airAcceleration(position, velocity) {
const acceleration = new THREE.Vector3(0, -G, 0);
const speed = velocity.length();
if (speed > 1e-6) {
acceleration.addScaledVector(velocity, -DRAG * speed);
}
const magnus = new THREE.Vector3()
.crossVectors(spin, velocity)
.multiplyScalar(MAGNUS);
acceleration.add(magnus);
return acceleration;
}
function rk4Step(position, velocity, dt) {
const k1v = airAcceleration(position, velocity);
const k1p = velocity.clone();
const k2v = airAcceleration(
position.clone().addScaledVector(k1p, dt * 0.5),
velocity.clone().addScaledVector(k1v, dt * 0.5)
);
const k2p = velocity.clone().addScaledVector(k1v, dt * 0.5);
const k3v = airAcceleration(
position.clone().addScaledVector(k2p, dt * 0.5),
velocity.clone().addScaledVector(k2v, dt * 0.5)
);
const k3p = velocity.clone().addScaledVector(k2v, dt * 0.5);
const k4v = airAcceleration(
position.clone().addScaledVector(k3p, dt),
velocity.clone().addScaledVector(k3v, dt)
);
const k4p = velocity.clone().addScaledVector(k3v, dt);
const nextPosition = position.clone().addScaledVector(k1p, dt / 6)
.addScaledVector(k2p, dt / 6)
.addScaledVector(k3p, dt / 6)
.addScaledVector(k4p, dt / 6);
const nextVelocity = velocity.clone().addScaledVector(k1v, dt / 6)
.addScaledVector(k2v, dt / 6)
.addScaledVector(k3v, dt / 6)
.addScaledVector(k4v, dt / 6);
return { p: nextPosition, v: nextVelocity };
}
function resolveRimCollision(position, velocity) {
const dx = position.x - HOOP_CENTER.x;
const dz = position.z - HOOP_CENTER.z;
const radialDistance = Math.hypot(dx, dz);
if (radialDistance < 1e-5) return false;
const angle = Math.atan2(dz, dx);
const nearest = new THREE.Vector3(
HOOP_CENTER.x + Math.cos(angle) * HOOP_RADIUS,
HOOP_CENTER.y,
HOOP_CENTER.z + Math.sin(angle) * HOOP_RADIUS
);
const delta = position.clone().sub(nearest);
const minimumDistance = BALL_RADIUS + HOOP_TUBE;
const distance = delta.length();
if (distance >= minimumDistance) return false;
const normal = distance > 1e-6
? delta.multiplyScalar(1 / distance)
: new THREE.Vector3(1, 0, 0);
position.copy(nearest).addScaledVector(normal, minimumDistance);
const normalVelocity = velocity.dot(normal);
if (normalVelocity < 0) {
velocity.addScaledVector(normal, -(1 + 0.56) * normalVelocity);
velocity.multiplyScalar(0.91);
}
return true;
}
function simulateFullBasketball() {
let position = RELEASE.clone();
let velocity = initialVelocity.clone();
let grounded = false;
const samples = [];
const events = [];
let firstFloorTime = null;
const maxSteps = Math.floor(9 / FIXED_DT);
for (let step = 0; step < maxSteps; step++) {
const time = step * FIXED_DT;
const previousPosition = position.clone();
const previousVelocity = velocity.clone();
if (grounded) {
position.addScaledVector(velocity, FIXED_DT);
const friction = Math.exp(-2.7 * FIXED_DT);
velocity.x *= friction;
velocity.z *= friction;
velocity.y = 0;
} else {
const integrated = rk4Step(position, velocity, FIXED_DT);
position = integrated.p;
velocity = integrated.v;
}
// Cruza o plano do aro de +z para -z.
if (previousPosition.z > HOOP_CENTER.z && position.z <= HOOP_CENTER.z) {
const denominator = previousPosition.z - position.z;
const fraction = denominator > 1e-8
? (previousPosition.z - HOOP_CENTER.z) / denominator
: 0;
const crossingX = lerp(previousPosition.x, position.x, fraction);
const crossingY = lerp(previousPosition.y, position.y, fraction);
const radialError = Math.abs(crossingX - HOOP_CENTER.x);
const clearRadius = HOOP_RADIUS - HOOP_TUBE - BALL_RADIUS;
if (radialError <= clearRadius && previousVelocity.y < 0) {
events.push({
t: time + FIXED_DT,
type: "score",
text: "Entrada confirmada na simulação completa."
});
} else {
events.push({
t: time + FIXED_DT,
type: "hoop",
text: `Passou ${radialError.toFixed(3).replace(".", ",")} m ao lado do aro.`
});
}
}
// Tabela: quadro frontal em z = -7,18.
const boardFront = -7.18;
const boardHalfWidth = 1.16;
const boardBottom = 2.66;
const boardTop = 4.08;
if (
position.z - BALL_RADIUS < boardFront &&
position.z > boardFront - 0.35 &&
Math.abs(position.x) < boardHalfWidth + BALL_RADIUS &&
position.y > boardBottom - BALL_RADIUS &&
position.y < boardTop + BALL_RADIUS &&
velocity.z < 0
) {
position.z = boardFront + BALL_RADIUS;
velocity.z = -velocity.z * 0.68;
velocity.x *= 0.88;
events.push({
t: time + FIXED_DT,
type: "board",
text: "Colisão com a tabela."
});
}
if (resolveRimCollision(position, velocity)) {
events.push({
t: time + FIXED_DT,
type: "rim",
text: "Colisão com o aro."
});
}
// Chão: a bola é centroada no raio físico.
if (position.y < BALL_RADIUS && velocity.y < 0) {
position.y = BALL_RADIUS;
if (firstFloorTime === null) {
firstFloorTime = time + FIXED_DT;
events.push({
t: firstFloorTime,
type: "floor",
text: "Primeiro contato com o piso."
});
}
if (Math.abs(velocity.y) < 0.62) {
velocity.y = 0;
grounded = true;
} else {
velocity.y = -velocity.y * 0.76;
grounded = false;
}
velocity.x *= 0.82;
velocity.z *= 0.82;
}
if (step % 4 === 0) {
samples.push({
t: time,
p: position.clone(),
v: velocity.clone()
});
}
}
samples.push({
t: maxSteps * FIXED_DT,
p: position.clone(),
v: velocity.clone()
});
events.sort((a, b) => a.t - b.t);
return { samples, events, firstFloorTime };
}
function sampleAt(samples, time) {
const scaled = clamp(time * 60, 0, samples.length - 1);
const index = Math.floor(scaled);
const nextIndex = Math.min(index + 1, samples.length - 1);
const fraction = scaled - index;
const a = samples[index];
const b = samples[nextIndex];
return {
t: time,
p: a.p.clone().lerp(b.p, fraction),
v: a.v.clone().lerp(b.v, fraction)
};
}
const idealSamples = buildIdealSamples();
const fullSimulation = simulateFullBasketball();
const fullSamples = fullSimulation.samples;
const fullDuration = fullSamples[fullSamples.length - 1].t;
const evaluationTime = 1.5;
const idealAtEvaluation = idealPosition(evaluationTime);
const fullAtEvaluation = sampleAt(fullSamples, evaluationTime).p;
const synchronizedDeviation = idealAtEvaluation.distanceTo(fullAtEvaluation);
const hoopEvent = fullSimulation.events.find((event) => event.type === "hoop" || event.type === "score");
const fmt = (value, digits = 3) =>
value.toLocaleString("pt-BR", {
minimumFractionDigits: digits,
maximumFractionDigits: digits
});
$("idealDuration").textContent = `+${fmt(idealImpactTime)} s`;
$("idealSamples").textContent = `${idealSamples.length}`;
$("sequenceNote").textContent = `t₀ = 0,000 s · t_f = ${fmt(idealImpactTime)} s`;
$("rootResult").textContent = `t⁺ = +${fmt(idealImpactTime)} s`;
$("fullDuration").textContent = fullSimulation.firstFloorTime === null
? "—"
: `+${fmt(fullSimulation.firstFloorTime)} s`;
$("deviationValue").textContent = `${fmt(synchronizedDeviation)} m`;
$("deviationNote").textContent = `3D @ t = ${fmt(evaluationTime, 1)} s, para as duas sequências`;
if (hoopEvent?.type === "score") {
$("hoopResult").textContent = "Entrada";
$("hoopResult").style.color = "var(--green)";
$("hoopNote").textContent = "A bola cruzou o plano do aro dentro da área livre.";
} else {
$("hoopResult").textContent = "Fora do aro";
$("hoopResult").style.color = "var(--orange)";
$("hoopNote").textContent = hoopEvent?.text ?? "Sem passagem registrada pelo aro.";
}
// ---------------------------------------------------------------------
// Cena procedural em Three.js
// ---------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 34, 68);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
$("scene").appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 120);
const cameraTarget = new THREE.Vector3(0, 1.7, -1.0);
const cameraState = {
yaw: 0.66,
pitch: 0.55,
radius: 31
};
function updateCamera() {
const horizontal = Math.cos(cameraState.pitch) * cameraState.radius;
camera.position.set(
cameraTarget.x + Math.sin(cameraState.yaw) * horizontal,
cameraTarget.y + Math.sin(cameraState.pitch) * cameraState.radius,
cameraTarget.z + Math.cos(cameraState.yaw) * horizontal
);
camera.lookAt(cameraTarget);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xbfe8ff, 0x172132, 2.25);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff1d8, 3.4);
keyLight.position.set(10, 22, 13);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -22;
keyLight.shadow.camera.right = 22;
keyLight.shadow.camera.top = 22;
keyLight.shadow.camera.bottom = -22;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 65;
keyLight.shadow.bias = -0.00025;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x52bfff, 1.4);
rimLight.position.set(-15, 10, -12);
scene.add(rimLight);
const standardMaterial = (color, roughness = 0.78, metalness = 0.0) =>
new THREE.MeshStandardMaterial({ color, roughness, metalness });
function addBox(width, height, depth, x, y, z, material, castShadow = true) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
typeof material === "number" ? standardMaterial(material) : material
);
mesh.position.set(x, y, z);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
scene.add(mesh);
return mesh;
}
// Base da arena e piso externo.
addBox(18, 0.42, 23, 0, -0.26, 0, standardMaterial(0x132235));
addBox(31, 0.5, 38, 0, -0.72, 0, standardMaterial(0x0b1727));
// Tacos de madeira da quadra.
const tileColumns = 28;
const tileRows = 42;
const tileGeometry = new THREE.BoxGeometry(0.49, 0.12, 0.49);
const tileMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.83,
metalness: 0
});
const tiles = new THREE.InstancedMesh(tileGeometry, tileMaterial, tileColumns * tileRows);
tiles.receiveShadow = true;
const dummy = new THREE.Object3D();
const woodA = new THREE.Color(0xc98b52);
const woodB = new THREE.Color(0xe0a567);
let tileIndex = 0;
for (let row = 0; row < tileRows; row++) {
for (let column = 0; column < tileColumns; column++) {
const x = (column - (tileColumns - 1) / 2) * 0.5;
const z = (row - (tileRows - 1) / 2) * 0.5;
dummy.position.set(x, -0.06, z);
dummy.updateMatrix();
tiles.setMatrixAt(tileIndex, dummy.matrix);
const color = (row + column) % 3 === 0 ? woodB : woodA;
tiles.setColorAt(tileIndex, color);
tileIndex++;
}
}
tiles.instanceMatrix.needsUpdate = true;
tiles.instanceColor.needsUpdate = true;
scene.add(tiles);
const courtWhite = new THREE.MeshStandardMaterial({
color: 0xf2f4e9,
roughness: 0.62
});
// Linhas retas da quadra.
addBox(0.065, 0.025, 20.55, -6.78, 0.018, 0, courtWhite, false);
addBox(0.065, 0.025, 20.55, 6.78, 0.018, 0, courtWhite, false);
addBox(13.55, 0.025, 0.065, 0, 0.018, -10.25, courtWhite, false);
addBox(13.55, 0.025, 0.065, 0, 0.018, 10.25, courtWhite, false);
addBox(13.55, 0.025, 0.065, 0, 0.018, 0, courtWhite, false);
// Círculo central em pequenos blocos.
const circleMaterial = new THREE.MeshStandardMaterial({ color: 0xf2f4e9, roughness: 0.68 });
for (let i = 0; i < 72; i++) {
const angle = (i / 72) * Math.PI * 2;
const block = new THREE.Mesh(new THREE.BoxGeometry(0.15, 0.025, 0.15), circleMaterial);
block.position.set(Math.cos(angle) * 1.75, 0.02, Math.sin(angle) * 1.75);
block.receiveShadow = true;
scene.add(block);
}
// Área restrita e linha de lance livre, também em blocos.
const freeThrowLine = new THREE.Mesh(
new THREE.BoxGeometry(4.45, 0.025, 0.065),
circleMaterial
);
freeThrowLine.position.set(0, 0.02, -3.8);
scene.add(freeThrowLine);
for (let i = 0; i < 42; i++) {
const angle = -1.15 + (i / 41) * 2.3;
const radius = 5.9;
const x = Math.sin(angle) * radius;
const z = -3.2 - Math.cos(angle) * radius;
const arc = new THREE.Mesh(new THREE.BoxGeometry(0.14, 0.025, 0.14), circleMaterial);
arc.position.set(x, 0.02, z);
scene.add(arc);
}
// Arquibancadas voxel.
const seatGeometry = new THREE.BoxGeometry(0.68, 0.34, 0.62);
const seatMaterial = new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.85 });
const seatRows = [];
for (const side of [-1, 1]) {
for (let row = 0; row < 3; row++) {
for (let z = -9; z <= 9; z += 1.15) {
seatRows.push({ x: side * (7.75 + row * 0.67), y: 0.08 + row * 0.31, z });
}
}
}
const seats = new THREE.InstancedMesh(seatGeometry, seatMaterial, seatRows.length);
const seatColors = [0x246a91, 0x2f849f, 0x355f92, 0x3c7192];
seatRows.forEach((seat, index) => {
dummy.position.set(seat.x, seat.y, seat.z);
dummy.updateMatrix();
seats.setMatrixAt(index, dummy.matrix);
seats.setColorAt(index, new THREE.Color(seatColors[index % seatColors.length]));
});
seats.instanceMatrix.needsUpdate = true;
seats.instanceColor.needsUpdate = true;
seats.receiveShadow = true;
scene.add(seats);
// Estrutura do aro e tabela.
const steel = standardMaterial(0x52677a, 0.46, 0.35);
addBox(0.34, 3.45, 0.34, 0, 1.72, -8.35, steel);
addBox(0.28, 0.28, 1.28, 0, 3.58, -7.82, steel);
const boardMaterial = new THREE.MeshStandardMaterial({
color: 0x9ddcff,
transparent: true,
opacity: 0.32,
roughness: 0.28,
metalness: 0.05,
depthWrite: false
});
addBox(2.32, 1.42, 0.12, 0, 3.76, -7.35, boardMaterial, false);
addBox(2.42, 0.065, 0.16, 0, 4.49, -7.35, courtWhite);
addBox(2.42, 0.065, 0.16, 0, 3.03, -7.35, courtWhite);
addBox(0.065, 1.5, 0.16, -1.18, 3.76, -7.35, courtWhite);
addBox(0.065, 1.5, 0.16, 1.18, 3.76, -7.35, courtWhite);
addBox(0.065, 0.92, 0.17, 0, 3.65, -7.34, courtWhite);
const rimMaterial = standardMaterial(0xff6d24, 0.48, 0.12);
for (let i = 0; i < 32; i++) {
const angle = (i / 32) * Math.PI * 2;
addBox(
0.13,
0.105,
0.13,
HOOP_CENTER.x + Math.cos(angle) * HOOP_RADIUS,
HOOP_CENTER.y,
HOOP_CENTER.z + Math.sin(angle) * HOOP_RADIUS,
rimMaterial
);
}
// Rede voxel.
const netMaterial = standardMaterial(0xf4f1df, 0.82);
for (let strand = 0; strand < 10; strand++) {
const angle = (strand / 10) * Math.PI * 2;
for (let level = 0; level < 5; level++) {
const radius = HOOP_RADIUS * (1 - level * 0.12);
addBox(
0.045,
0.15,
0.045,
Math.cos(angle) * radius,
HOOP_CENTER.y - 0.12 - level * 0.16,
HOOP_CENTER.z + Math.sin(angle) * radius,
netMaterial,
false
);
}
}
// Torres de iluminação voxel.
const lampMaterial = new THREE.MeshBasicMaterial({ color: 0xffe9b0 });
for (const x of [-8.2, 8.2]) {
for (const z of [-10.8, 10.8]) {
for (let level = 0; level < 5; level++) {
addBox(0.28, 0.28, 0.28, x, 0.14 + level * 0.29, z, steel);
}
addBox(0.8, 0.28, 0.34, x, 1.7, z, lampMaterial, false);
}
}
// Marcador da soltura fixa.
const releaseMarkerMaterial = new THREE.MeshBasicMaterial({ color: 0x50e6ff });
for (const dx of [-0.4, 0.4]) {
for (const dy of [-0.4, 0.4]) {
addBox(0.09, 0.09, 0.09, RELEASE.x + dx, RELEASE.y + dy, RELEASE.z, releaseMarkerMaterial, false);
}
}
for (let i = 1; i <= 6; i++) {
addBox(
0.045,
0.045,
0.045,
RELEASE.x,
RELEASE.y - i * 0.18,
RELEASE.z,
new THREE.MeshBasicMaterial({ color: 0x2b9fb7 }),
false
);
}
// Bola de basquete feita com cubos.
const ballGroup = new THREE.Group();
scene.add(ballGroup);
const voxels = [];
const cell = 0.063;
const visualRadius = 0.345;
for (let x = -5; x <= 5; x++) {
for (let y = -5; y <= 5; y++) {
for (let z = -5; z <= 5; z++) {
const radius = Math.hypot(x * cell, y * cell, z * cell);
if (radius <= visualRadius && radius >= visualRadius * 0.70) {
voxels.push({ x: x * cell, y: y * cell, z: z * cell, seam: x === 0 || y === 0 || z === 0 });
}
}
}
}
const ballGeometry = new THREE.BoxGeometry(cell * 0.91, cell * 0.91, cell * 0.91);
const ballMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.69,
metalness: 0.02
});
const ballMesh = new THREE.InstancedMesh(ballGeometry, ballMaterial, voxels.length);
voxels.forEach((voxel, index) => {
dummy.position.set(voxel.x, voxel.y, voxel.z);
dummy.updateMatrix();
ballMesh.setMatrixAt(index, dummy.matrix);
ballMesh.setColorAt(index, new THREE.Color(voxel.seam ? 0x2b1710 : 0xe97925));
});
ballMesh.instanceMatrix.needsUpdate = true;
ballMesh.instanceColor.needsUpdate = true;
ballMesh.castShadow = true;
ballGroup.add(ballMesh);
const ballLight = new THREE.PointLight(0xff9b42, 0.55, 2.4, 2);
ballGroup.add(ballLight);
function makePath(points, color, dashed) {
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = dashed
? new THREE.LineDashedMaterial({
color,
dashSize: 0.28,
gapSize: 0.16,
transparent: true,
opacity: 0.95
})
: new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.92
});
const line = new THREE.Line(geometry, material);
if (dashed) line.computeLineDistances();
return line;
}
function makePathMarkers(points, color, stride, size) {
const selected = [];
for (let i = 0; i < points.length; i += stride) selected.push(points[i]);
const mesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(size, size, size),
new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0.92 }),
selected.length
);
selected.forEach((point, index) => {
dummy.position.copy(point);
dummy.updateMatrix();
mesh.setMatrixAt(index, dummy.matrix);
});
mesh.instanceMatrix.needsUpdate = true;
return mesh;
}
const idealGroup = new THREE.Group();
const fullGroup = new THREE.Group();
scene.add(idealGroup, fullGroup);
const idealPoints = idealSamples.map((sample) => sample.p.clone());
const fullPoints = fullSamples.map((sample) => sample.p.clone());
idealGroup.add(makePath(idealPoints, 0x50e6ff, true));
idealGroup.add(makePathMarkers(idealPoints, 0x50e6ff, 10, 0.07));
fullGroup.add(makePath(fullPoints, 0xff9d3d, false));
fullGroup.add(makePathMarkers(fullPoints, 0xff9d3d, 18, 0.065));
function addImpactMarker(position, color) {
const material = new THREE.MeshBasicMaterial({ color });
for (let i = 0; i < 3; i++) {
const marker = new THREE.Mesh(
new THREE.BoxGeometry(0.09 - i * 0.018, 0.09 - i * 0.018, 0.09 - i * 0.018),
material
);
marker.position.set(position.x, BALL_RADIUS + 0.015, position.z);
marker.position.y += i * 0.11;
scene.add(marker);
}
}
addImpactMarker(idealPosition(idealImpactTime), 0x50e6ff);
if (fullSimulation.firstFloorTime !== null) {
addImpactMarker(sampleAt(fullSamples, fullSimulation.firstFloorTime).p, 0xff9d3d);
}
// ---------------------------------------------------------------------
// Estado e controles locais
// ---------------------------------------------------------------------
let mode = "full";
let elapsed = 0;
let playing = true;
let dragging = false;
let dragX = 0;
let dragY = 0;
const modeButtons = [...document.querySelectorAll("[data-mode]")];
function setMode(nextMode) {
mode = nextMode;
elapsed = 0;
playing = true;
modeButtons.forEach((button) => {
button.setAttribute("aria-pressed", String(button.dataset.mode === mode));
});
$("modeChip").textContent = mode === "ideal" ? "Trajetória ideal" : "Simulação completa";
$("pauseButton").textContent = "Pausar";
}
modeButtons.forEach((button) => {
button.addEventListener("click", () => setMode(button.dataset.mode));
});
$("launchButton").addEventListener("click", () => {
elapsed = 0;
playing = true;
$("pauseButton").textContent = "Pausar";
});
$("pauseButton").addEventListener("click", () => {
playing = !playing;
$("pauseButton").textContent = playing ? "Pausar" : "Continuar";
});
$("resetButton").addEventListener("click", () => {
elapsed = 0;
playing = false;
$("pauseButton").textContent = "Continuar";
});
$("showIdeal").addEventListener("change", (event) => {
idealGroup.visible = event.target.checked;
});
$("showFull").addEventListener("change", (event) => {
fullGroup.visible = event.target.checked;
});
function resetCamera() {
cameraState.yaw = 0.66;
cameraState.pitch = 0.55;
cameraState.radius = 31;
updateCamera();
}
$("cameraButton").addEventListener("click", resetCamera);
// Câmera orbital implementada sem addons.
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
dragX = event.clientX;
dragY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - dragX;
const deltaY = event.clientY - dragY;
dragX = event.clientX;
dragY = event.clientY;
cameraState.yaw -= deltaX * 0.006;
cameraState.pitch = clamp(cameraState.pitch + deltaY * 0.0045, 0.25, 1.28);
updateCamera();
});
renderer.domElement.addEventListener("pointerup", (event) => {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
dragging = false;
});
renderer.domElement.addEventListener("wheel", (event) => {
event.preventDefault();
cameraState.radius = clamp(cameraState.radius + event.deltaY * 0.015, 18, 48);
updateCamera();
}, { passive: false });
renderer.domElement.addEventListener("dblclick", resetCamera);
window.addEventListener("keydown", (event) => {
if (event.code === "Space") {
event.preventDefault();
playing = !playing;
$("pauseButton").textContent = playing ? "Pausar" : "Continuar";
}
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
});
function currentIdealEvent(time) {
if (time >= idealImpactTime) {
return "Contato ideal com o piso; sequência iniciada em t = 0,000 s.";
}
if (time >= RELEASE_TO_HOOP_TIME) {
return "Passagem ideal pelo centro do aro.";
}
return "Voo ideal em curso, somente sob gravidade.";
}
function currentFullEvent(time) {
let latest = null;
for (const event of fullSimulation.events) {
if (event.t <= time + 1e-6) latest = event;
else break;
}
return latest?.text ?? "Voo completo em curso: ar, aro e准备 para o contato.";
}
function updateWorldLabel(element, worldPosition, pixelOffsetY = 0) {
const projected = worldPosition.clone().project(camera);
const visible = projected.z > -1 && projected.z < 1;
element.style.display = visible ? "block" : "none";
if (!visible) return;
const x = (projected.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight + pixelOffsetY;
element.style.left = `${x}px`;
element.style.top = `${y}px`;
}
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
const duration = mode === "ideal" ? idealImpactTime : fullDuration;
if (playing) {
elapsed += delta;
if (elapsed >= duration) {
elapsed = duration;
playing = false;
$("pauseButton").textContent = "Continuar";
}
}
const sample = mode === "ideal"
? { t: elapsed, p: idealPosition(Math.min(elapsed, idealImpactTime)) }
: sampleAt(fullSamples, Math.min(elapsed, fullDuration));
ballGroup.position.copy(sample.p);
ballGroup.rotation.set(elapsed * 2.8, elapsed * 7.5, elapsed * 4.1);
const reference = idealPosition(Math.min(elapsed, idealImpactTime));
const liveDifference = mode === "ideal"
? 0
: sample.p.distanceTo(reference);
$("liveMode").textContent = mode === "ideal" ? "Ideal · gravidade apenas" : "Completo · física + colisões";
$("liveTime").textContent = `${fmt(elapsed)} s`;
$("livePosition").textContent =
`${fmt(sample.p.x, 2)}, ${fmt(sample.p.y, 2)}, ${fmt(sample.p.z, 2)} m`;
$("liveDifference").textContent = mode === "ideal"
? "0,000 m · por definição"
: `${fmt(liveDifference)} m`;
$("liveEvent").textContent = mode === "ideal"
? currentIdealEvent(elapsed)
: currentFullEvent(elapsed);
updateWorldLabel($("releaseLabel"), RELEASE.clone().add(new THREE.Vector3(0, 0.68, 0)), -7);
updateWorldLabel($("hoopLabel"), HOOP_CENTER.clone().add(new THREE.Vector3(0, 0.55, 0)), -3);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```