Prompt specification
Build or customize the Three.js 3D scene "Push Timing and Energy Change" 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: Push Timing and Energy Change
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/push-timing-and-energy-change-x3624
Scene Description Prompt:
Create a standalone voxel scene in one HTML file using Three.js from cdnjs. Create an idealized swing experiment with discrete small pushes at selected phases. Display changes in model energy and avoid presenting the demonstration as playground-use instruction.
Verify the behavior against the actual geometry and data in each relevant state. Use schematic labels for deliberately synthetic elements.
Technical checks: Render the swing, controls, and graph in the initial view. Show how choosing the push timing changes the impulse and the measured energy.
Return one complete HTML document. The file must run in a sandbox allowing inline scripts and the cdnjs Three.js r160 module. Construct procedural assets, use local event handlers and avoid remote assets, runtime network requests besides Three.js, pointer lock and native form submission. Keep the main requested geometry visible in the initial view.
Working Three.js Starter (push-timing-and-energy-change-x3624):
```html
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Balanço sintético — impulsos por fase</title>
<style>
:root {
--ink: #17283b;
--muted: #607184;
--paper: rgba(248, 250, 252, 0.92);
--line: rgba(23, 40, 59, 0.14);
--center: #e9a72d;
--left: #e96b5e;
--right: #2aa993;
--accent: #243d58;
--shadow: 0 14px 40px rgba(25, 42, 59, 0.16);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dbe8ee;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button { font: inherit; }
#stage {
position: fixed;
inset: 0;
overflow: hidden;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
touch-action: none;
cursor: grab;
}
#stage canvas.dragging { cursor: grabbing; }
.ui {
position: fixed;
inset: 0;
z-index: 2;
pointer-events: none;
}
.panel {
pointer-events: auto;
background: var(--paper);
border: 1px solid rgba(255, 255, 255, 0.85);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
}
.intro {
position: absolute;
top: 18px;
left: 18px;
width: min(390px, calc(100vw - 36px));
padding: 17px 18px 15px;
border-radius: 16px;
}
.eyebrow {
margin-bottom: 7px;
color: #496176;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(21px, 2.1vw, 30px);
line-height: 1.05;
letter-spacing: -0.035em;
}
.subtitle {
margin: 9px 0 12px;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.disclaimer {
padding: 9px 10px;
border-left: 3px solid var(--center);
border-radius: 3px 8px 8px 3px;
background: rgba(233, 167, 45, 0.11);
color: #5a4b28;
font-size: 11px;
line-height: 1.42;
font-weight: 650;
}
.telemetry {
position: absolute;
top: 18px;
right: 18px;
width: 272px;
padding: 15px;
border-radius: 16px;
}
.panel-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 11px;
}
.panel-title {
font-size: 12px;
font-weight: 850;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.state-pill {
padding: 4px 8px;
border-radius: 999px;
background: rgba(42, 169, 147, 0.14);
color: #177565;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.06em;
text-transform: uppercase;
white-space: nowrap;
}
.state-pill.paused {
background: rgba(233, 167, 45, 0.16);
color: #8a6214;
}
.energy-main {
padding: 11px 12px;
border-radius: 12px;
background: #20384f;
color: white;
}
.energy-main .label {
color: #bfd0dd;
font-size: 10px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.energy-main .value {
margin-top: 2px;
font: 750 30px/1.1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
letter-spacing: -0.05em;
}
.energy-main .value small {
font-size: 12px;
color: #bfd0dd;
letter-spacing: 0;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 9px;
}
.metric {
min-height: 57px;
padding: 9px 10px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.58);
}
.metric .label {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.metric .value {
font: 750 16px/1.1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
.positive { color: #087966; }
.negative { color: #b34c43; }
.readout {
margin-top: 9px;
padding-top: 9px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
.readout strong { color: var(--ink); }
.controls {
position: absolute;
left: 18px;
bottom: 18px;
width: 382px;
padding: 15px;
border-radius: 16px;
}
.helper {
margin: 4px 0 10px;
color: var(--muted);
font-size: 11px;
line-height: 1.42;
}
.phase-row {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
}
.phase-button {
position: relative;
min-height: 48px;
padding: 8px 6px 7px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.72);
color: var(--ink);
cursor: pointer;
transition: transform 120ms ease, border-color 120ms ease, background 120ms ease;
}
.phase-button:hover { transform: translateY(-1px); }
.phase-button:focus-visible, .action:focus-visible {
outline: 3px solid rgba(36, 61, 88, 0.28);
outline-offset: 2px;
}
.phase-button::before {
content: "";
display: block;
width: 10px;
height: 10px;
margin: 0 auto 5px;
border-radius: 3px;
background: var(--phase-color);
}
.phase-button strong {
display: block;
font-size: 11px;
}
.phase-button small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
}
.phase-button.selected {
border-color: var(--phase-color);
background: color-mix(in srgb, var(--phase-color) 12%, white);
box-shadow: inset 0 0 0 1px var(--phase-color);
}
.actions {
display: grid;
grid-template-columns: 1fr auto auto;
gap: 7px;
margin-top: 9px;
}
.action {
min-height: 38px;
padding: 8px 11px;
border: 1px solid var(--line);
border-radius: 9px;
background: white;
color: var(--ink);
font-size: 11px;
font-weight: 780;
cursor: pointer;
transition: transform 120ms ease, background 120ms ease;
}
.action:hover { transform: translateY(-1px); }
.action.primary {
border-color: var(--accent);
background: var(--accent);
color: white;
}
.action.danger {
color: #a64a42;
background: rgba(233, 107, 94, 0.08);
}
.pending {
min-height: 36px;
margin-top: 8px;
padding: 8px 10px;
border-radius: 9px;
background: rgba(23, 40, 59, 0.055);
color: #4c5e70;
font-size: 10px;
line-height: 1.4;
}
.pending.armed {
background: rgba(233, 167, 45, 0.13);
color: #745516;
font-weight: 700;
}
.model-note {
margin-top: 9px;
color: #69798a;
font: 10px/1.45 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
.graph-panel {
position: absolute;
right: 18px;
bottom: 18px;
width: min(430px, calc(100vw - 36px));
padding: 14px 14px 12px;
border-radius: 16px;
}
#energyGraph {
display: block;
width: 100%;
height: 148px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.66);
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 8px 13px;
margin-top: 8px;
color: #5f7081;
font-size: 10px;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 5px;
}
.swatch {
width: 9px;
height: 9px;
border-radius: 2px;
}
.line-key {
width: 17px;
height: 2px;
background: var(--accent);
}
.events {
display: grid;
gap: 4px;
margin-top: 9px;
max-height: 86px;
overflow: auto;
border-top: 1px solid var(--line);
padding-top: 8px;
}
.event {
display: grid;
grid-template-columns: 48px 1fr auto;
gap: 8px;
align-items: center;
color: #536477;
font-size: 10px;
}
.event time {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
.event strong { color: var(--ink); }
.empty-events {
color: #7b8997;
font-size: 10px;
}
#fallback {
position: fixed;
inset: 0;
z-index: 10;
display: none;
place-items: center;
padding: 30px;
background: #e5edf2;
color: #24384e;
text-align: center;
}
@media (max-width: 1000px) {
.intro { width: 330px; }
.telemetry { width: 240px; }
.controls { width: 340px; }
.graph-panel { width: 360px; }
}
@media (max-width: 760px) {
.intro {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 13px;
}
.subtitle { display: none; }
.disclaimer { font-size: 10px; }
.telemetry {
top: 142px;
left: 10px;
right: 10px;
width: auto;
padding: 11px;
}
.metric-grid { grid-template-columns: repeat(4, 1fr); }
.metric { min-height: 49px; padding: 7px; }
.metric .value { font-size: 13px; }
.readout { display: none; }
.controls {
left: 10px;
right: 10px;
bottom: 190px;
width: auto;
padding: 12px;
}
.model-note { display: none; }
.graph-panel {
left: 10px;
right: 10px;
bottom: 10px;
width: auto;
padding: 11px;
}
#energyGraph { height: 105px; }
.events { display: none; }
}
</style>
</head>
<body>
<main id="stage" aria-label="Experimento tridimensional de balanço sintético"></main>
<div class="ui">
<header class="intro panel">
<div class="eyebrow">Experimento numérico voxel</div>
<h1>Balanço: impulso por fase</h1>
<p class="subtitle">
Um pêndulo idealizado recebe pequenos impulsos discretos em fases selecionadas.
A curva usa a energia mecânica calculada pelo próprio modelo em execução.
</p>
<div class="disclaimer">
MODELO SINTÉTICO —_elements_,
setas, massas e fases são esquemáticos. Esta visualização não é instrução de uso recreativo
em parque ou playground.
</div>
</header>
<section class="telemetry panel" aria-label="Telemetria do modelo">
<div class="panel-head">
<div class="panel-title">Estado do modelo</div>
<div id="runState" class="state-pill">Simulando</div>
</div>
<div class="energy-main">
<div class="label">Energia mecânica atual</div>
<div class="value"><span id="energyNow">0.0</span> <small>J</small></div>
</div>
<div class="metric-grid">
<div class="metric">
<span class="label">Saldo desde o início</span>
<span id="energyDelta" class="value">0.0 J</span>
</div>
<div class="metric">
<span class="label">Impulsos aplicados</span>
<span id="pushCount" class="value">0</span>
</div>
<div class="metric">
<span class="label">Último ΔE</span>
<span id="lastDelta" class="value">—</span>
</div>
<div class="metric">
<span class="label">Fase instantânea</span>
<span id="phaseNow" class="value">—</span>
</div>
</div>
<div class="readout">
<div><strong>Posição angular:</strong> <span id="angleNow">0.0°</span></div>
<div><strong>Velocidade angular:</strong> <span id="omegaNow">0.00 rad/s</span></div>
<div><strong>Tempo simulado:</strong> <span id="timeNow">0.00 s</span></div>
</div>
</section>
<section class="controls panel" aria-label="Controles do experimento sintético">
<div class="panel-head">
<div class="panel-title">Programar um impulso</div>
</div>
<div class="helper">
Escolha uma fase e programe <strong>um</strong> impulso. A seta indica o sentido do
incremento angular sintético.
</div>
<div class="phase-row" role="group" aria-label="Seleção da fase">
<button type="button" class="phase-button selected" data-phase="center" style="--phase-color: var(--center)">
<strong>Centro</strong>
<small>θ = 0°</small>
</button>
<button type="button" class="phase-button" data-phase="left" style="--phase-color: var(--left)">
<strong>Esquerda</strong>
<small>θ ≤ −37°</small>
</button>
<button type="button" class="phase-button" data-phase="right" style="--phase-color: var(--right)">
<strong>Direita</strong>
<small>θ ≥ 37°</small>
</button>
</div>
<div class="actions">
<button id="programBtn" type="button" class="action primary">Programar próximo impulso</button>
<button id="cancelBtn" type="button" class="action danger" disabled>Cancelar</button>
<button id="pauseBtn" type="button" class="action">Pausar</button>
</div>
<div id="pendingText" class="pending">Nenhum impulso armado.</div>
<div class="actions" style="grid-template-columns: 1fr 1fr; margin-top: 7px;">
<button id="resetBtn" type="button" class="action">Reiniciar modelo</button>
<button id="viewBtn" type="button" class="action">Restaurar câmera</button>
</div>
<div class="model-note">
m = 12 kg · l = 2,35 m · g = 9,81 m/s²<br>
arrasto = 0,015 s⁻¹ · Δ|ω| = 0,22 rad/s<br>
Blocos coloridos = fases · seta vermelha = impulso sintético
</div>
</section>
<section class="graph-panel panel" aria-label="Gráfico de energia">
<div class="panel-head">
<div class="panel-title">Energia mecânica registrada</div>
<div class="state-pill">20 s</div>
</div>
<canvas id="energyGraph" aria-label="Gráfico temporal da energia mecânica em joules"></canvas>
<div class="legend">
<span><i class="line-key"></i> energia calculada</span>
<span><i class="swatch" style="background:#e96b5e"></i> aplicação de impulso</span>
<span><i class="swatch" style="background:#e9a72d"></i> centro</span>
<span><i class="swatch" style="background:#2aa993"></i> direita</span>
<span><i class="swatch" style="background:#e96b5e"></i> esquerda</span>
</div>
<div id="eventLog" class="events" aria-live="polite"></div>
</section>
</div>
<div id="fallback">
<div>
<h2>WebGL não está disponível neste navegador.</h2>
<p>Abra o documento em um navegador com aceleração gráfica habilitada.</p>
</div>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const stage = document.getElementById("stage");
const fallback = document.getElementById("fallback");
let renderer;
try {
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
} catch (error) {
fallback.style.display = "grid";
throw error;
}
renderer.domElement.id = "threeCanvas";
renderer.domElement.tabIndex = 0;
renderer.domElement.setAttribute("aria-label", "Cena voxel tridimensional do balanço sintético");
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
stage.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdbe8ee);
scene.fog = new THREE.Fog(0xdbe8ee, 15, 31);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
80
);
const cameraTarget = new THREE.Vector3(0, 2.65, 0);
const cameraState = {
yaw: 0.34,
phi: 1.24,
radius: 11.6
};
function updateCamera() {
const { yaw, phi, radius } = cameraState;
camera.position.set(
cameraTarget.x + radius * Math.sin(phi) * Math.sin(yaw),
cameraTarget.y + radius * Math.cos(phi),
cameraTarget.z + radius * Math.sin(phi) * Math.cos(yaw)
);
camera.lookAt(cameraTarget);
}
updateCamera();
const hemi = new THREE.HemisphereLight(0xeaf7ff, 0x73806d, 2.15);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff3db, 3.35);
sun.position.set(-6, 11, 7);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -10;
sun.shadow.camera.right = 10;
sun.shadow.camera.top = 11;
sun.shadow.camera.bottom = -7;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 28;
sun.shadow.bias = -0.0005;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x87c9ff, 1.0);
rim.position.set(8, 5, -7);
scene.add(rim);
const palette = {
frame: new THREE.MeshStandardMaterial({ color: 0x30475d, roughness: 0.78, metalness: 0.12 }),
frameLight: new THREE.MeshStandardMaterial({ color: 0x48657d, roughness: 0.72, metalness: 0.12 }),
frameDark: new THREE.MeshStandardMaterial({ color: 0x203448, roughness: 0.82, metalness: 0.08 }),
rope: new THREE.MeshStandardMaterial({ color: 0x7d8f9e, roughness: 0.72, metalness: 0.28 }),
seat: new THREE.MeshStandardMaterial({ color: 0x269f8a, roughness: 0.74 }),
seatDark: new THREE.MeshStandardMaterial({ color: 0x177766, roughness: 0.78 }),
mass: new THREE.MeshStandardMaterial({ color: 0xf0b441, roughness: 0.6 }),
pivot: new THREE.MeshStandardMaterial({ color: 0xe96b5e, roughness: 0.58 }),
center: new THREE.MeshStandardMaterial({ color: 0xe9a72d, roughness: 0.65 }),
left: new THREE.MeshStandardMaterial({ color: 0xe96b5e, roughness: 0.65 }),
right: new THREE.MeshStandardMaterial({ color: 0x2aa993, roughness: 0.65 }),
dark: new THREE.MeshStandardMaterial({ color: 0x24384d, roughness: 0.8 })
};
function addBox(parent, w, h, d, material, x = 0, y = 0, z = 0) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), material);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
let seed = 9137;
function random() {
seed = (seed * 1664525 + 1013904223) >>> 0;
return seed / 4294967296;
}
const tileGeo = new THREE.BoxGeometry(0.50, 0.12, 0.50);
const tileMat = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.96,
metalness: 0
});
const ground = new THREE.InstancedMesh(tileGeo, tileMat, 28 * 18);
ground.receiveShadow = true;
const dummy = new THREE.Object3D();
const colorA = new THREE.Color(0xa9c2b5);
const colorB = new THREE.Color(0x91aea5);
const colorC = new THREE.Color(0xb8c8ba);
let tileIndex = 0;
for (let row = 0; row < 18; row++) {
for (let col = 0; col < 28; col++) {
const height = 0.10 + random() * 0.045;
dummy.position.set(
(col - 13.5) * 0.52,
-height / 2,
(row - 8.5) * 0.52
);
dummy.scale.set(1, height / 0.12, 1);
dummy.updateMatrix();
ground.setMatrixAt(tileIndex, dummy.matrix);
const tint = random();
const color = tint > 0.88 ? colorC : ((row + col) % 2 ? colorA : colorB);
ground.setColorAt(tileIndex, color);
tileIndex++;
}
}
ground.instanceMatrix.needsUpdate = true;
if (ground.instanceColor) ground.instanceColor.needsUpdate = true;
scene.add(ground);
const frame = new THREE.Group();
scene.add(frame);
for (const side of [-1, 1]) {
const x = side * 3.28;
addBox(frame, 0.95, 0.30, 1.35, palette.frameDark, x, 0.15, 0);
addBox(frame, 0.76, 0.16, 1.10, palette.frameLight, x, 0.34, 0);
for (let i = 0; i < 7; i++) {
const material = i % 2 === 0 ? palette.frame : palette.frameLight;
addBox(frame, 0.50, 0.62, 0.56, material, x, 0.61 + i * 0.68, 0);
}
for (let i = 0; i < 3; i++) {
addBox(
frame,
0.34,
0.34,
0.68,
palette.frameDark,
x + side * (0.42 + i * 0.21),
4.48 + i * 0.27,
0
);
}
}
addBox(frame, 7.45, 0.50, 0.66, palette.frame, 0, 5.27, 0);
addBox(frame, 7.05, 0.13, 0.72, palette.frameLight, 0, 5.57, 0);
addBox(frame, 0.66, 0.34, 0.70, palette.frameDark, 0, 4.94, 0.18);
addBox(frame, 0.24, 0.24, 0.82, palette.pivot, 0, 4.92, 0.20);
const phaseMarkerRadius = 2.90;
function addPhaseMarker(angle, material) {
const x = Math.sin(angle) * phaseMarkerRadius;
const y = 4.82 - Math.cos(angle) * phaseMarkerRadius;
const marker = addBox(scene, 0.16, 0.16, 0.16, material, x, y, -0.28);
marker.castShadow = false;
}
addPhaseMarker(0, palette.center);
addPhaseMarker(-0.65, palette.left);
addPhaseMarker(0.65, palette.right);
const pivotHeight = 4.82;
const ropeLength = 2.35;
const swing = new THREE.Group();
swing.position.set(0, pivotHeight, 0.52);
scene.add(swing);
for (const x of [-0.46, 0.46]) {
for (let i = 0; i < 9; i++) {
addBox(
swing,
0.13,
0.20,
0.13,
i % 2 ? palette.rope : palette.frameLight,
x,
-0.20 - i * 0.235,
0
);
}
}
addBox(swing, 1.28, 0.16, 0.58, palette.seat, 0, -ropeLength, 0);
addBox(swing, 1.08, 0.09, 0.48, palette.seatDark, 0, -ropeLength - 0.10, 0);
addBox(swing, 1.28, 0.46, 0.13, palette.seatDark, 0, -ropeLength + 0.27, -0.24);
addBox(swing, 0.10, 0.38, 0.46, palette.seat, -0.63, -ropeLength + 0.18, 0);
addBox(swing, 0.10, 0.38, 0.46, palette.seat, 0.63, -ropeLength + 0.18, 0);
addBox(swing, 0.42, 0.42, 0.42, palette.mass, 0, -ropeLength + 0.29, 0.02);
const arrowMaterial = new THREE.MeshStandardMaterial({
color: 0xf06458,
emissive: 0xa5241c,
emissiveIntensity: 0.7,
roughness: 0.5,
transparent: true,
opacity: 0,
depthTest: false
});
const pushArrow = new THREE.Group();
addBox(pushArrow, 0.72, 0.13, 0.13, arrowMaterial, 0.18, 0, 0);
addBox(pushArrow, 0.18, 0.38, 0.13, arrowMaterial, 0.61, 0, 0);
addBox(pushArrow, 0.18, 0.17, 0.13, arrowMaterial, 0.79, 0, 0);
pushArrow.visible = false;
pushArrow.renderOrder = 20;
scene.add(pushArrow);
const params = {
mass: 12,
length: ropeLength,
gravity: 9.81,
damping: 0.015,
pushDeltaOmega: 0.22,
phaseAngle: 0.65,
initialAngle: 0.52
};
const sim = {
theta: params.initialAngle,
omega: 0,
time: 0,
running: true,
selectedPhase: "center",
pending: null,
pushes: 0,
initialEnergy: 0,
lastPush: null,
events: [],
history: []
};
const phaseNames = {
center: "Centro",
left: "Lateral esquerda",
right: "Lateral direita"
};
const phaseColors = {
center: "#e9a72d",
left: "#e96b5e",
right: "#2aa993"
};
function mechanicalEnergy(theta = sim.theta, omega = sim.omega) {
const inertia = params.mass * params.length * params.length;
const kinetic = 0.5 * inertia * omega * omega;
const potential =
params.mass * params.gravity * params.length * (1 - Math.cos(theta));
return kinetic + potential;
}
function phaseReached(phase, previousTheta, currentTheta) {
if (phase === "center") {
const crossedZero =
(previousTheta > 0 && currentTheta <= 0) ||
(previousTheta < 0 && currentTheta >= 0);
return crossedZero || Math.abs(currentTheta) < 0.00001;
}
if (phase === "left") return currentTheta <= -params.phaseAngle;
if (phase === "right") return currentTheta >= params.phaseAngle;
return false;
}
function applyPendingImpulse() {
if (!sim.pending) return;
if (!phaseReached(sim.pending.phase, sim.previousTheta, sim.theta)) return;
const phase = sim.pending.phase;
const before = mechanicalEnergy();
const direction = Math.sign(sim.omega) || 1;
const deltaOmega = direction * params.pushDeltaOmega;
sim.omega += deltaOmega;
const after = mechanicalEnergy();
const deltaEnergy = after - before;
sim.pushes++;
sim.lastPush = {
phase,
time: sim.time,
before,
after,
deltaEnergy,
deltaOmega
};
sim.events.push(sim.lastPush);
sim.pending = null;
pushArrow.visible = true;
arrowMaterial.opacity = 1;
pushArrow.userData.flash = 1;
pushArrow.userData.direction = direction;
updateUI();
renderEventLog();
}
const FIXED_STEP = 1 / 120;
let accumulator = 0;
let lastHistoryTime = 0;
function stepSimulation(dt) {
const previousTheta = sim.theta;
const angularAcceleration =
-(params.gravity / params.length) * Math.sin(sim.theta) -
params.damping * sim.omega;
sim.omega += angularAcceleration * dt;
sim.theta += sim.omega * dt;
sim.previousTheta = previousTheta;
sim.time += dt;
applyPendingImpulse();
if (sim.time - lastHistoryTime >= 0.05) {
sim.history.push({ time: sim.time, energy: mechanicalEnergy() });
lastHistoryTime = sim.time;
if (sim.history.length > 1600) sim.history.shift();
}
}
function resetExperiment() {
sim.theta = params.initialAngle;
sim.previousTheta = sim.theta;
sim.omega = 0;
sim.time = 0;
sim.running = true;
sim.pending = null;
sim.pushes = 0;
sim.lastPush = null;
sim.events = [];
sim.initialEnergy = mechanicalEnergy();
sim.history = [{ time: 0, energy: sim.initialEnergy }];
lastHistoryTime = 0;
accumulator = 0;
pushArrow.visible = false;
arrowMaterial.opacity = 0;
updateUI();
renderEventLog();
drawGraph();
}
function selectPhase(phase) {
sim.selectedPhase = phase;
document.querySelectorAll(".phase-button").forEach(button => {
button.classList.toggle("selected", button.dataset.phase === phase);
button.setAttribute("aria-pressed", String(button.dataset.phase === phase));
});
updatePendingText();
}
function updatePendingText() {
const pendingText = document.getElementById("pendingText");
const cancelBtn = document.getElementById("cancelBtn");
if (sim.pending) {
pendingText.classList.add("armed");
pendingText.textContent =
`Armado para ${phaseNames[sim.pending.phase]}. ` +
"O incremento será aplicado quando essa fase for atingida.";
cancelBtn.disabled = false;
} else {
pendingText.classList.remove("armed");
pendingText.textContent =
`Fase selecionada: ${phaseNames[sim.selectedPhase]}. Nenhum impulso armado.`;
cancelBtn.disabled = true;
}
}
function updateUI() {
const energy = mechanicalEnergy();
const delta = energy - sim.initialEnergy;
const runState = document.getElementById("runState");
const pauseBtn = document.getElementById("pauseBtn");
document.getElementById("energyNow").textContent = energy.toFixed(1);
const deltaElement = document.getElementById("energyDelta");
deltaElement.textContent = `${delta >= 0 ? "+" : ""}${delta.toFixed(1)} J`;
deltaElement.className = `value ${delta >= 0 ? "positive" : "negative"}`;
document.getElementById("pushCount").textContent = String(sim.pushes);
const lastDelta = document.getElementById("lastDelta");
if (sim.lastPush) {
lastDelta.textContent = `+${sim.lastPush.deltaEnergy.toFixed(2)} J`;
lastDelta.className = "value positive";
} else {
lastDelta.textContent = "—";
lastDelta.className = "value";
}
let phaseText = "Centro";
if (sim.theta < -0.04) phaseText = "Esquerda";
if (sim.theta > 0.04) phaseText = "Direita";
document.getElementById("phaseNow").textContent = phaseText;
document.getElementById("angleNow").textContent =
`${(sim.theta * 180 / Math.PI).toFixed(1)}°`;
document.getElementById("omegaNow").textContent =
`${sim.omega.toFixed(2)} rad/s`;
document.getElementById("timeNow").textContent =
`${sim.time.toFixed(2)} s`;
runState.textContent = sim.running ? "Simulando" : "Pausado";
runState.classList.toggle("paused", !sim.running);
pauseBtn.textContent = sim.running ? "Pausar" : "Continuar";
updatePendingText();
}
function renderEventLog() {
const log = document.getElementById("eventLog");
if (!sim.events.length) {
log.innerHTML = '<div class="empty-events">Nenhum impulso aplicado neste ciclo.</div>';
return;
}
const recent = sim.events.slice(-5).reverse();
log.innerHTML = recent.map(event => `
<div class="event">
<time>${event.time.toFixed(2)} s</time>
<span><strong>${phaseNames[event.phase]}</strong> · Δω ${event.deltaOmega >= 0 ? "+" : ""}${event.deltaOmega.toFixed(2)} rad/s</span>
<strong class="positive">+${event.deltaEnergy.toFixed(2)} J</strong>
</div>
`).join("");
}
const graphCanvas = document.getElementById("energyGraph");
const graphContext = graphCanvas.getContext("2d");
let graphWidth = 0;
let graphHeight = 0;
function resizeGraph() {
const rect = graphCanvas.getBoundingClientRect();
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const width = Math.max(1, Math.round(rect.width * dpr));
const height = Math.max(1, Math.round(rect.height * dpr));
if (graphCanvas.width !== width || graphCanvas.height !== height) {
graphCanvas.width = width;
graphCanvas.height = height;
}
graphWidth = rect.width;
graphHeight = rect.height;
}
function drawGraph() {
resizeGraph();
const ctx = graphContext;
if (!ctx || graphWidth < 20 || graphHeight < 20) return;
ctx.setTransform(
Math.min(window.devicePixelRatio || 1, 2),
0,
0,
Math.min(window.devicePixelRatio || 1, 2),
0,
0
);
ctx.clearRect(0, 0, graphWidth, graphHeight);
const pad = { left: 42, right: 12, top: 12, bottom: 24 };
const plotW = graphWidth - pad.left - pad.right;
const plotH = graphHeight - pad.top - pad.bottom;
const endTime = Math.max(20, sim.time);
const startTime = Math.max(0, endTime - 20);
const currentEnergy = mechanicalEnergy();
const visible = sim.history.filter(point => point.time >= startTime);
const points = visible.concat([{ time: sim.time, energy: currentEnergy }]);
let maxEnergy = 10;
for (const point of points) maxEnergy = Math.max(maxEnergy, point.energy);
for (const event of sim.events) {
if (event.time >= startTime) maxEnergy = Math.max(maxEnergy, event.after);
}
const yMax = Math.ceil((maxEnergy * 1.08) / 10) * 10;
const xFor = time => pad.left + ((time - startTime) / (endTime - startTime)) * plotW;
const yFor = energy => pad.top + plotH - (energy / yMax) * plotH;
ctx.fillStyle = "rgba(36, 61, 88, 0.045)";
ctx.fillRect(pad.left, pad.top, plotW, plotH);
ctx.font = "10px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace";
ctx.textBaseline = "middle";
for (let i = 0; i <= 4; i++) {
const energy = yMax * i / 4;
const y = yFor(energy);
ctx.strokeStyle = "rgba(36, 61, 88, 0.11)";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(pad.left, y);
ctx.lineTo(pad.left + plotW, y);
ctx.stroke();
ctx.fillStyle = "#718091";
ctx.textAlign = "right";
ctx.fillText(energy.toFixed(0), pad.left - 6, y);
}
const tickCount = 4;
for (let i = 0; i <= tickCount; i++) {
const time = startTime + (endTime - startTime) * i / tickCount;
const x = xFor(time);
ctx.strokeStyle = "rgba(36, 61, 88, 0.08)";
ctx.beginPath();
ctx.moveTo(x, pad.top);
ctx.lineTo(x, pad.top + plotH);
ctx.stroke();
ctx.fillStyle = "#718091";
ctx.textAlign = i === 0 ? "left" : (i === tickCount ? "right" : "center");
ctx.textBaseline = "top";
ctx.fillText(`${time.toFixed(0)} s`, x, pad.top + plotH + 6);
}
ctx.save();
ctx.beginPath();
ctx.rect(pad.left, pad.top - 2, plotW, plotH + 4);
ctx.clip();
ctx.strokeStyle = "#243d58";
ctx.lineWidth = 2.25;
ctx.lineJoin = "round";
ctx.lineCap = "round";
ctx.beginPath();
points.forEach((point, index) => {
const x = xFor(point.time);
const y = yFor(point.energy);
if (index === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.stroke();
for (const event of sim.events) {
if (event.time < startTime || event.time > endTime) continue;
const x = xFor(event.time);
const y = yFor(event.after);
ctx.strokeStyle = "rgba(233, 107, 94, 0.7)";
ctx.lineWidth = 1;
ctx.setLineDash([3, 3]);
ctx.beginPath();
ctx.moveTo(x, pad.top);
ctx.lineTo(x, pad.top + plotH);
ctx.stroke();
ctx.setLineDash([]);
ctx.fillStyle = phaseColors[event.phase];
ctx.beginPath();
ctx.arc(x, y, 3.8, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = "#fff";
ctx.lineWidth = 1.4;
ctx.stroke();
}
const lastX = xFor(sim.time);
const lastY = yFor(currentEnergy);
ctx.fillStyle = "#243d58";
ctx.beginPath();
ctx.arc(lastX, lastY, 3.2, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
ctx.fillStyle = "#5f7081";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText("J", 8, 5);
}
document.querySelectorAll(".phase-button").forEach(button => {
button.addEventListener("click", () => selectPhase(button.dataset.phase));
});
document.getElementById("programBtn").addEventListener("click", () => {
sim.pending = {
phase: sim.selectedPhase,
armedAt: sim.time
};
updateUI();
});
document.getElementById("cancelBtn").addEventListener("click", () => {
sim.pending = null;
updateUI();
});
document.getElementById("pauseBtn").addEventListener("click", () => {
sim.running = !sim.running;
accumulator = 0;
updateUI();
});
document.getElementById("resetBtn").addEventListener("click", resetExperiment);
document.getElementById("viewBtn").addEventListener("click", () => {
cameraState.yaw = 0.34;
cameraState.phi = 1.24;
cameraState.radius = 11.6;
updateCamera();
});
const canvas = renderer.domElement;
let dragging = false;
let pointerX = 0;
let pointerY = 0;
canvas.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
canvas.classList.add("dragging");
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraState.yaw -= dx * 0.005;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi + dy * 0.005,
0.46,
1.48
);
updateCamera();
});
function endDrag(event) {
dragging = false;
canvas.classList.remove("dragging");
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
7,
18
);
updateCamera();
}, { passive: false });
canvas.addEventListener("dblclick", () => {
cameraState.yaw = 0.34;
cameraState.phi = 1.24;
cameraState.radius = 11.6;
updateCamera();
});
window.addEventListener("keydown", event => {
if (event.target instanceof HTMLButtonElement) return;
if (event.code === "Space") {
event.preventDefault();
sim.running = !sim.running;
accumulator = 0;
updateUI();
}
if (event.key.toLowerCase() === "r") resetExperiment();
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
resizeGraph();
drawGraph();
});
resetExperiment();
let lastFrame = performance.now();
let lastUIUpdate = 0;
let lastGraphUpdate = 0;
function animate(now) {
requestAnimationFrame(animate);
const frameDelta = Math.min((now - lastFrame) / 1000, 0.05);
lastFrame = now;
if (sim.running) {
accumulator += frameDelta;
while (accumulator >= FIXED_STEP) {
stepSimulation(FIXED_STEP);
accumulator -= FIXED_STEP;
}
}
swing.rotation.z = sim.theta;
const seatX = Math.sin(sim.theta) * params.length;
const seatY = pivotHeight - Math.cos(sim.theta) * params.length;
pushArrow.position.set(seatX, seatY, 0.93);
pushArrow.rotation.z = sim.theta + (pushArrow.userData.direction < 0 ? Math.PI : 0);
if (pushArrow.userData.flash > 0) {
pushArrow.userData.flash = Math.max(0, pushArrow.userData.flash - frameDelta / 0.9);
arrowMaterial.opacity = pushArrow.userData.flash;
const scale = 0.84 + (1 - pushArrow.userData.flash) * 0.28;
pushArrow.scale.setScalar(scale);
pushArrow.visible = pushArrow.userData.flash > 0.001;
}
if (now - lastUIUpdate > 80) {
updateUI();
lastUIUpdate = now;
}
if (now - lastGraphUpdate > 50) {
drawGraph();
lastGraphUpdate = now;
}
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```