Prompt specification
Build or customize the Three.js 3D scene "Tilting a connected-level device" 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: Tilting a connected-level device
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/tilting-a-connected-level-device-x1450
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows liquid levels in communicating vessels. Rotate a rigid U-shaped tube while allowing the liquid surfaces to settle horizontally; distinguish world-level water surfaces from the container's changing orientation. Stylized solid forms.
Technical checks: At both +35° and −35°, keep the settled liquid surfaces visible inside both transparent legs. Keep the surface meshes within the tube and unobstructed.
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 (tilting-a-connected-level-device-x1450):
```html
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="data:,">
<title>Vasos Comunicantes — nível horizontal no mundo</title>
<style>
:root {
--ink: #18383c;
--muted: #60777a;
--glass: rgba(255, 255, 255, 0.78);
--line: rgba(37, 92, 98, 0.16);
--aqua: #26b9c6;
--mint: #a9f4e9;
--green: #31866e;
--amber: #c87835;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #eeeae1;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#scene:active { cursor: grabbing; }
.panel {
position: fixed;
z-index: 5;
border: 1px solid rgba(255, 255, 255, 0.72);
background: var(--glass);
box-shadow:
0 18px 50px rgba(35, 61, 63, 0.10),
inset 0 0 0 1px var(--line);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
.info {
top: 22px;
left: 22px;
width: min(350px, calc(100vw - 44px));
padding: 20px 20px 18px;
border-radius: 22px;
}
.eyebrow {
margin: 0 0 6px;
color: var(--aqua);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(25px, 3vw, 34px);
line-height: 1.03;
letter-spacing: -0.04em;
}
.intro {
margin: 10px 0 17px;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.controls {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 8px;
margin-bottom: 15px;
}
button {
appearance: none;
border: 1px solid rgba(31, 92, 99, 0.18);
border-radius: 12px;
padding: 10px 8px;
background: rgba(255, 255, 255, 0.68);
color: var(--ink);
font: inherit;
font-size: 12px;
font-weight: 750;
cursor: pointer;
transition: transform 150ms ease, background 150ms ease, border-color 150ms ease;
}
button:hover {
transform: translateY(-1px);
border-color: rgba(31, 150, 160, 0.45);
background: #fff;
}
button:focus-visible {
outline: 3px solid rgba(38, 185, 198, 0.28);
outline-offset: 2px;
}
button.active {
border-color: var(--aqua);
background: #dff8f7;
color: #11656d;
}
.status-row,
.readout-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
}
.status-row {
padding: 11px 12px;
border-radius: 13px;
background: rgba(227, 241, 239, 0.72);
border: 1px solid rgba(49, 134, 110, 0.12);
}
.status-label {
display: flex;
align-items: center;
gap: 9px;
font-size: 12px;
font-weight: 750;
}
.status-dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 0 5px rgba(49, 134, 110, 0.10);
}
.status-row.settling .status-dot {
background: var(--amber);
box-shadow: 0 0 0 5px rgba(200, 120, 53, 0.12);
animation: pulse 700ms ease-in-out infinite alternate;
}
@keyframes pulse {
to { transform: scale(0.72); opacity: 0.55; }
}
.status-detail {
color: var(--muted);
font-size: 10px;
text-align: right;
}
.angle-card {
display: grid;
grid-template-columns: 64px 1fr;
gap: 14px;
align-items: center;
margin-top: 14px;
padding-top: 14px;
border-top: 1px solid var(--line);
}
.dial {
position: relative;
width: 60px;
height: 60px;
border: 1px solid rgba(38, 185, 198, 0.28);
border-radius: 50%;
background:
linear-gradient(90deg, transparent 49%, rgba(38, 185, 198, 0.13) 49%, rgba(38, 185, 198, 0.13) 51%, transparent 51%),
radial-gradient(circle at 50% 50%, rgba(38, 185, 198, 0.10) 0 2px, transparent 3px);
}
.dial::before,
.dial::after {
position: absolute;
top: 50%;
color: #789093;
font-size: 9px;
font-weight: 700;
transform: translateY(-50%);
}
.dial::before { content: "+35"; left: 3px; }
.dial::after { content: "−35"; right: 3px; }
.needle {
position: absolute;
left: 50%;
bottom: 50%;
width: 2px;
height: 23px;
border-radius: 2px;
background: var(--aqua);
transform-origin: 50% 100%;
transform: translateX(-50%) rotate(0deg);
transition: transform 80ms linear;
}
.needle::after {
content: "";
position: absolute;
left: 50%;
bottom: -4px;
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--aqua);
transform: translateX(-50%);
}
.angle-value {
margin: 0;
font-size: 24px;
font-weight: 800;
letter-spacing: -0.04em;
}
.angle-subtitle {
margin: 3px 0 0;
color: var(--muted);
font-size: 11px;
}
.readouts {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
margin-top: 14px;
}
.readout {
min-width: 0;
padding: 10px 9px;
border-radius: 12px;
background: rgba(255, 255, 255, 0.54);
border: 1px solid rgba(37, 92, 98, 0.10);
}
.readout span {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.readout strong {
display: block;
overflow: hidden;
color: var(--ink);
font-size: 14px;
white-space: nowrap;
text-overflow: ellipsis;
}
.legend {
top: 22px;
right: 22px;
width: 255px;
padding: 15px 16px;
border-radius: 18px;
}
.legend h2 {
margin: 0 0 10px;
font-size: 12px;
letter-spacing: 0.03em;
}
.legend-item {
display: flex;
align-items: flex-start;
gap: 9px;
margin: 8px 0;
color: var(--muted);
font-size: 11px;
line-height: 1.35;
}
.swatch {
flex: 0 0 auto;
width: 14px;
height: 8px;
margin-top: 3px;
border-radius: 5px;
}
.swatch.liquid { background: var(--aqua); }
.swatch.surface { background: var(--mint); border: 1px solid #3fa9aa; }
.swatch.world {
height: 0;
border-top: 2px dashed #70898b;
border-radius: 0;
}
.gravity {
right: 28px;
top: 190px;
width: 92px;
padding: 11px;
border-radius: 15px;
text-align: center;
}
.gravity-arrow {
display: block;
margin-bottom: 4px;
color: #637d80;
font-size: 30px;
line-height: 1;
}
.gravity span {
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
}
.hint {
position: fixed;
z-index: 4;
left: 50%;
bottom: 18px;
padding: 9px 14px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.67);
border: 1px solid rgba(255, 255, 255, 0.74);
color: #62777a;
font-size: 10px;
transform: translateX(-50%);
backdrop-filter: blur(10px);
pointer-events: none;
white-space: nowrap;
}
#loading {
position: fixed;
z-index: 20;
inset: 0;
display: grid;
place-items: center;
background: #eeeae1;
color: var(--muted);
font-size: 13px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
@media (max-width: 820px) {
.info {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 15px;
}
h1 { font-size: 24px; }
.intro { margin: 7px 0 11px; }
.legend, .gravity { display: none; }
.readouts { margin-top: 10px; }
.hint { bottom: 9px; }
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Experimento tridimensional de vasos comunicantes"></canvas>
<section class="panel info" aria-label="Controles do experimento">
<p class="eyebrow">Laboratório de hidrostática</p>
<h1>Vasos comunicantes</h1>
<p class="intro">
O tubo é rígido, mas o líquido se acomoda em uma superfície livre horizontal.
Compare o nível no mundo com as alturas medidas ao longo das pernas inclinadas.
</p>
<div class="controls">
<button type="button" id="tiltLeft" aria-pressed="false">−35°</button>
<button type="button" id="upright" class="active" aria-pressed="true">Vertical</button>
<button type="button" id="tiltRight" aria-pressed="false">+35°</button>
</div>
<div class="status-row" id="statusRow">
<div class="status-label">
<span class="status-dot"></span>
<span id="statusText">Settled</span>
</div>
<span class="status-detail" id="statusDetail">nível comum confirmado</span>
</div>
<div class="angle-card">
<div class="dial" aria-hidden="true"><div class="needle" id="needle"></div></div>
<div>
<p class="angle-value" id="angleValue">0°</p>
<p class="angle-subtitle">orientação do tubo</p>
</div>
</div>
<div class="readouts">
<div class="readout">
<span>Nível no mundo</span>
<strong id="worldLevel">—</strong>
</div>
<div class="readout">
<span>Coluna esquerda</span>
<strong id="leftLevel">—</strong>
</div>
<div class="readout">
<span>Coluna direita</span>
<strong id="rightLevel">—</strong>
</div>
</div>
</section>
<aside class="panel legend" aria-label="Legenda">
<h2>Leia as duas referências</h2>
<div class="legend-item"><span class="swatch liquid"></span><span>Líquido: volume conservado durante a rotação.</span></div>
<div class="legend-item"><span class="swatch surface"></span><span>Superfícies livres: horizontais no mundo.</span></div>
<div class="legend-item"><span class="swatch world"></span><span>Linha tracejada: referência horizontal do mundo.</span></div>
</aside>
<aside class="panel gravity" aria-label="Direção da gravidade">
<span class="gravity-arrow">↓</span>
<span>GRAVIDADE</span>
</aside>
<div class="hint">Arraste para orbitar · role para aproximar · duplo clique para restaurar a câmera</div>
<div id="loading">Preparando o experimento…</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const canvas = document.getElementById("scene");
const loading = document.getElementById("loading");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.localClippingEnabled = true;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xeeeae1);
scene.fog = new THREE.Fog(0xeeeae1, 13, 24);
const camera = new THREE.PerspectiveCamera(38, window.innerWidth / window.innerHeight, 0.1, 60);
// Direct camera controls, implemented without addons.
const cameraState = {
azimuth: 0.58,
elevation: 0.30,
radius: 10.4,
target: new THREE.Vector3(0.38, 2.45, 0)
};
function updateCamera() {
const { azimuth, elevation, radius, target } = cameraState;
const horizontal = Math.cos(elevation) * radius;
camera.position.set(
target.x + Math.sin(azimuth) * horizontal,
target.y + Math.sin(elevation) * radius,
target.z + Math.cos(azimuth) * horizontal
);
camera.lookAt(target);
}
updateCamera();
const hemi = new THREE.HemisphereLight(0xf8fbff, 0x9b8e78, 2.25);
scene.add(hemi);
const keyLight = new THREE.DirectionalLight(0xfff8e9, 3.0);
keyLight.position.set(-5, 8, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -6;
keyLight.shadow.camera.right = 6;
keyLight.shadow.camera.top = 8;
keyLight.shadow.camera.bottom = -3;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 20;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0xb7f6ff, 1.35);
rimLight.position.set(6, 4, -5);
scene.add(rimLight);
// Geometry of the rigid U-shaped channel.
const ARM_HEIGHT = 3.65;
const OUTER_RADIUS = 1.55;
const INNER_RADIUS = 0.85;
const FLUID_OUTER = OUTER_RADIUS - 0.06;
const FLUID_INNER = INNER_RADIUS + 0.06;
const DEPTH = 1.16;
const BASE_Y = 1.58;
const FILL_FRACTION = 0.56;
const vessel = new THREE.Group();
vessel.position.set(0, BASE_Y, 0);
scene.add(vessel);
function halfAnnulusShape(rOuter, rInner, segments = 48) {
const shape = new THREE.Shape();
shape.moveTo(-rOuter, 0);
for (let i = 1; i <= segments; i++) {
const a = Math.PI + (i / segments) * Math.PI;
shape.lineTo(rOuter * Math.cos(a), rOuter * Math.sin(a));
}
shape.lineTo(rInner, 0);
for (let i = 1; i <= segments; i++) {
const a = 2 * Math.PI - (i / segments) * Math.PI;
shape.lineTo(rInner * Math.cos(a), rInner * Math.sin(a));
}
shape.closePath();
return shape;
}
function rectangleShape(x0, x1, y0, y1) {
const shape = new THREE.Shape();
shape.moveTo(x0, y0);
shape.lineTo(x1, y0);
shape.lineTo(x1, y1);
shape.lineTo(x0, y1);
shape.closePath();
return shape;
}
function extrudedShape(shape) {
const geometry = new THREE.ExtrudeGeometry(shape, {
depth: DEPTH,
bevelEnabled: false,
curveSegments: 48,
steps: 1
});
geometry.translate(0, 0, -DEPTH / 2);
return geometry;
}
// The world-horizontal clipping plane is updated from the conserved-volume calculation.
const clipPlane = new THREE.Plane(new THREE.Vector3(0, -1, 0), BASE_Y + 1.5);
const liquidMaterial = new THREE.MeshStandardMaterial({
color: 0x27b8c8,
emissive: 0x064c55,
emissiveIntensity: 0.22,
roughness: 0.30,
metalness: 0.02,
clippingPlanes: [clipPlane],
clipShadows: true
});
const liquidMeshes = [];
function addLiquid(shape) {
const mesh = new THREE.Mesh(extrudedShape(shape), liquidMaterial);
mesh.renderOrder = 1;
vessel.add(mesh);
liquidMeshes.push(mesh);
}
addLiquid(rectangleShape(-FLUID_OUTER, -FLUID_INNER, 0, ARM_HEIGHT));
addLiquid(rectangleShape(FLUID_INNER, FLUID_OUTER, 0, ARM_HEIGHT));
addLiquid(halfAnnulusShape(FLUID_OUTER, FLUID_INNER));
// Transparent front and back sheets. No opaque plates or protruding brackets are used.
const glassMaterial = new THREE.MeshPhysicalMaterial({
color: 0xd5fbff,
transparent: true,
opacity: 0.14,
roughness: 0.18,
metalness: 0,
side: THREE.DoubleSide,
depthWrite: false
});
const glassMeshes = [];
function addGlassSheet(shape, z) {
const mesh = new THREE.Mesh(new THREE.ShapeGeometry(shape, 48), glassMaterial);
mesh.position.z = z;
mesh.renderOrder = 4;
vessel.add(mesh);
glassMeshes.push(mesh);
}
const frontSheetShapes = [
rectangleShape(-OUTER_RADIUS, -INNER_RADIUS, 0, ARM_HEIGHT),
rectangleShape(INNER_RADIUS, OUTER_RADIUS, 0, ARM_HEIGHT),
halfAnnulusShape(OUTER_RADIUS, INNER_RADIUS)
];
frontSheetShapes.forEach(shape => {
addGlassSheet(shape, DEPTH / 2 + 0.012);
addGlassSheet(shape, -DEPTH / 2 - 0.012);
});
const wallMaterial = new THREE.MeshPhysicalMaterial({
color: 0x9ee9ec,
transparent: true,
opacity: 0.22,
roughness: 0.22,
metalness: 0,
depthWrite: false,
side: THREE.DoubleSide
});
function addWall(shape) {
const mesh = new THREE.Mesh(extrudedShape(shape), wallMaterial);
mesh.renderOrder = 5;
vessel.add(mesh);
}
// Outer vertical walls.
addWall(rectangleShape(-OUTER_RADIUS, -OUTER_RADIUS + 0.08, 0, ARM_HEIGHT));
addWall(rectangleShape(OUTER_RADIUS - 0.08, OUTER_RADIUS, 0, ARM_HEIGHT));
// Inner vertical walls.
addWall(rectangleShape(-INNER_RADIUS - 0.08, -INNER_RADIUS, 0, ARM_HEIGHT));
addWall(rectangleShape(INNER_RADIUS, INNER_RADIUS + 0.08, 0, ARM_HEIGHT));
// Curved bottom walls.
addWall(halfAnnulusShape(OUTER_RADIUS, OUTER_RADIUS - 0.08));
addWall(halfAnnulusShape(INNER_RADIUS + 0.08, INNER_RADIUS));
// Fine cyan rim lines, not dark plates.
const rimMaterial = new THREE.LineBasicMaterial({
color: 0x4aaab1,
transparent: true,
opacity: 0.48
});
function addRimLine(points, z) {
const geometry = new THREE.BufferGeometry().setFromPoints(
points.map(p => new THREE.Vector3(p[0], p[1], z))
);
vessel.add(new THREE.Line(geometry, rimMaterial));
}
[-DEPTH / 2 - 0.025, DEPTH / 2 + 0.025].forEach(z => {
addRimLine([[-OUTER_RADIUS, ARM_HEIGHT], [-INNER_RADIUS, ARM_HEIGHT]], z);
addRimLine([[INNER_RADIUS, ARM_HEIGHT], [OUTER_RADIUS, ARM_HEIGHT]], z);
});
// Explicit horizontal free surfaces. Their vertices are recalculated in world coordinates.
const capGeometry = new THREE.BufferGeometry();
capGeometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(18), 3)
);
capGeometry.setAttribute(
"normal",
new THREE.BufferAttribute(new Float32Array([
0, 1, 0, 0, 1, 0, 0, 1, 0,
0, 1, 0, 0, 1, 0, 0, 1, 0
]), 3)
);
const capMaterial = new THREE.MeshStandardMaterial({
color: 0xb7f7eb,
emissive: 0x0a7271,
emissiveIntensity: 0.20,
roughness: 0.24,
metalness: 0,
side: THREE.DoubleSide
});
const leftCap = new THREE.Mesh(capGeometry.clone(), capMaterial);
const rightCap = new THREE.Mesh(capGeometry.clone(), capMaterial);
leftCap.frustumCulled = false;
rightCap.frustumCulled = false;
leftCap.renderOrder = 3;
rightCap.renderOrder = 3;
scene.add(leftCap, rightCap);
function writeCap(mesh, x1, x2, worldY) {
const positions = mesh.geometry.attributes.position.array;
const z1 = -DEPTH / 2;
const z2 = DEPTH / 2;
const values = [
x1, worldY, z1,
x2, worldY, z1,
x2, worldY, z2,
x1, worldY, z1,
x2, worldY, z2,
x1, worldY, z2
];
positions.set(values);
mesh.geometry.attributes.position.needsUpdate = true;
mesh.visible = x2 - x1 > 0.001;
}
// Dashed world-level guide, deliberately behind the vessel.
const guideGeometry = new THREE.BufferGeometry();
guideGeometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(6), 3)
);
const guide = new THREE.Line(
guideGeometry,
new THREE.LineDashedMaterial({
color: 0x6f898b,
dashSize: 0.13,
gapSize: 0.095,
transparent: true,
opacity: 0.58
})
);
guide.frustumCulled = false;
scene.add(guide);
const guideEndGeometry = new THREE.BufferGeometry();
guideEndGeometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(12), 3)
);
const guideEnds = new THREE.LineSegments(
guideEndGeometry,
new THREE.LineBasicMaterial({
color: 0x789395,
transparent: true,
opacity: 0.55
})
);
guideEnds.frustumCulled = false;
scene.add(guideEnds);
// Stylized support and gravity reference.
const pedestal = new THREE.Mesh(
new THREE.CylinderGeometry(2.45, 2.65, 0.24, 64),
new THREE.MeshStandardMaterial({
color: 0xd5ddd8,
roughness: 0.84,
metalness: 0
})
);
pedestal.position.y = -0.14;
pedestal.receiveShadow = true;
scene.add(pedestal);
const pivotRing = new THREE.Mesh(
new THREE.TorusGeometry(1.83, 0.035, 10, 80),
new THREE.MeshStandardMaterial({
color: 0x54aeb2,
roughness: 0.45,
metalness: 0.08
})
);
pivotRing.rotation.x = Math.PI / 2;
pivotRing.position.y = 0.015;
scene.add(pivotRing);
const gravityArrow = new THREE.ArrowHelper(
new THREE.Vector3(0, -1, 0),
new THREE.Vector3(3.18, 4.75, 0),
1.35,
0x6d8587,
0.22,
0.12
);
scene.add(gravityArrow);
// Conservative liquid-volume calculation.
//
// For any rigid-tube angle, this integrates the exact 2D liquid domain
// below the horizontal world plane. A binary search then finds the common
// surface height that preserves the selected amount of liquid.
const totalLiquidArea =
0.5 * Math.PI * (FLUID_OUTER ** 2 - FLUID_INNER ** 2) +
2 * (FLUID_OUTER - FLUID_INNER) * ARM_HEIGHT;
const targetLiquidArea = totalLiquidArea * FILL_FRACTION;
function areaBelowWorldHeight(angle, height, slices = 220) {
const s = Math.sin(angle);
const c = Math.cos(angle);
const step = (2 * FLUID_OUTER) / slices;
let area = 0;
for (let i = 0; i < slices; i++) {
const x = -FLUID_OUTER + (i + 0.5) * step;
const cut = (height - s * x) / c;
// Lower semicircular channel.
const outerY = -Math.sqrt(Math.max(0, FLUID_OUTER ** 2 - x ** 2));
let low = outerY;
let high = 0;
if (Math.abs(x) < FLUID_INNER) {
high = -Math.sqrt(Math.max(0, FLUID_INNER ** 2 - x ** 2));
}
if (cut > low) {
area += Math.max(0, Math.min(high, cut) - low) * step;
}
// Two vertical arms.
if (x >= -FLUID_OUTER && x <= -FLUID_INNER) {
area += Math.max(0, Math.min(ARM_HEIGHT, cut)) * step;
} else if (x >= FLUID_INNER && x <= FLUID_OUTER) {
area += Math.max(0, Math.min(ARM_HEIGHT, cut)) * step;
}
}
return area;
}
function equilibriumHeight(angle) {
let low = -FLUID_OUTER - ARM_HEIGHT;
let high = ARM_HEIGHT + FLUID_OUTER;
for (let i = 0; i < 32; i++) {
const middle = (low + high) * 0.5;
if (areaBelowWorldHeight(angle, middle) < targetLiquidArea) {
low = middle;
} else {
high = middle;
}
}
return (low + high) * 0.5;
}
// Intersections of the world-horizontal plane with an arm's local rectangle.
function surfaceSegment(x0, x1, angle, localHeight) {
const s = Math.sin(angle);
const c = Math.cos(angle);
const corners = [
{ x: x0, y: 0 },
{ x: x1, y: 0 },
{ x: x1, y: ARM_HEIGHT },
{ x: x0, y: ARM_HEIGHT }
];
const intersections = [];
const epsilon = 1e-7;
function addPoint(point) {
if (!intersections.some(p =>
Math.abs(p.x - point.x) < 1e-5 &&
Math.abs(p.y - point.y) < 1e-5
)) {
intersections.push(point);
}
}
for (let i = 0; i < corners.length; i++) {
const a = corners[i];
const b = corners[(i + 1) % corners.length];
const fa = s * a.x + c * a.y - localHeight;
const fb = s * b.x + c * b.y - localHeight;
if (Math.abs(fa) < epsilon) addPoint(a);
if ((fa < -epsilon && fb > epsilon) || (fa > epsilon && fb < -epsilon)) {
const t = fa / (fa - fb);
addPoint({
x: a.x + (b.x - a.x) * t,
y: a.y + (b.y - a.y) * t
});
}
}
if (intersections.length < 2) return null;
const transformed = intersections.map(p => ({
x: Math.cos(angle) * p.x - Math.sin(angle) * p.y,
y: Math.sin(angle) * p.x + Math.cos(angle) * p.y
}));
transformed.sort((a, b) => a.x - b.x);
return { x1: transformed[0].x, x2: transformed[transformed.length - 1].x };
}
// UI and interaction state.
const statusRow = document.getElementById("statusRow");
const statusText = document.getElementById("statusText");
const statusDetail = document.getElementById("statusDetail");
const angleValue = document.getElementById("angleValue");
const needle = document.getElementById("needle");
const worldLevelEl = document.getElementById("worldLevel");
const leftLevelEl = document.getElementById("leftLevel");
const rightLevelEl = document.getElementById("rightLevel");
const buttons = {
left: document.getElementById("tiltLeft"),
upright: document.getElementById("upright"),
right: document.getElementById("tiltRight")
};
const state = {
currentAngle: 0,
targetAngle: 0,
angularVelocity: 0,
settling: false
};
function setTarget(angle, activeName) {
state.targetAngle = angle;
state.settling = true;
statusRow.classList.add("settling");
statusText.textContent = "Settling…";
statusDetail.textContent = "ajustando o nível comum";
Object.entries(buttons).forEach(([name, button]) => {
const active = name === activeName;
button.classList.toggle("active", active);
button.setAttribute("aria-pressed", String(active));
});
}
buttons.left.addEventListener("click", () => {
setTarget(-THREE.MathUtils.degToRad(35), "left");
});
buttons.right.addEventListener("click", () => {
setTarget(THREE.MathUtils.degToRad(35), "right");
});
buttons.upright.addEventListener("click", () => {
setTarget(0, "upright");
});
// Direct orbit controls.
let dragging = false;
let previousX = 0;
let previousY = 0;
canvas.addEventListener("pointerdown", event => {
dragging = true;
previousX = event.clientX;
previousY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
cameraState.azimuth -= dx * 0.006;
cameraState.elevation = THREE.MathUtils.clamp(
cameraState.elevation + dy * 0.0045,
-0.05,
0.78
);
updateCamera();
});
function endDrag(event) {
dragging = false;
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 + event.deltaY * 0.007,
7.0,
14.0
);
updateCamera();
}, { passive: false });
canvas.addEventListener("dblclick", () => {
cameraState.azimuth = 0.58;
cameraState.elevation = 0.30;
cameraState.radius = 10.4;
cameraState.target.set(0.38, 2.45, 0);
updateCamera();
});
function resize() {
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
}
window.addEventListener("resize", resize);
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.04);
// Critically damped rigid-body orientation.
const acceleration =
(state.targetAngle - state.currentAngle) * 42 -
state.angularVelocity * 13;
state.angularVelocity += acceleration * dt;
state.currentAngle += state.angularVelocity * dt;
if (
Math.abs(state.targetAngle - state.currentAngle) < 0.0007 &&
Math.abs(state.angularVelocity) < 0.001
) {
state.currentAngle = state.targetAngle;
state.angularVelocity = 0;
if (state.settling) {
state.settling = false;
statusRow.classList.remove("settling");
statusText.textContent = "Settled";
statusDetail.textContent = "nível comum confirmado";
}
}
vessel.rotation.z = state.currentAngle;
// Compute and apply the conserved-volume equilibrium for the actual angle.
const localHeight = equilibriumHeight(state.currentAngle);
const worldHeight = BASE_Y + localHeight;
clipPlane.constant = worldHeight;
const leftSegment = surfaceSegment(
-FLUID_OUTER, -FLUID_INNER, state.currentAngle, localHeight
);
const rightSegment = surfaceSegment(
FLUID_INNER, FLUID_OUTER, state.currentAngle, localHeight
);
if (leftSegment) {
writeCap(leftCap, leftSegment.x1, leftSegment.x2, worldHeight);
} else {
leftCap.visible = false;
}
if (rightSegment) {
writeCap(rightCap, rightSegment.x1, rightSegment.x2, worldHeight);
} else {
rightCap.visible = false;
}
// Horizontal world reference.
const guidePositions = guideGeometry.attributes.position.array;
guidePositions.set([-2.92, worldHeight, -0.79, 2.92, worldHeight, -0.79]);
guideGeometry.attributes.position.needsUpdate = true;
guide.computeLineDistances();
const endPositions = guideEndGeometry.attributes.position.array;
endPositions.set([
-2.92, worldHeight - 0.10, -0.79,
-2.92, worldHeight + 0.10, -0.79,
2.92, worldHeight - 0.10, -0.79,
2.92, worldHeight + 0.10, -0.79
]);
guideEndGeometry.attributes.position.needsUpdate = true;
// Data displayed to the learner.
const degrees = THREE.MathUtils.radToDeg(state.currentAngle);
const roundedDegrees = Math.abs(degrees) < 0.05 ? 0 : Math.round(degrees);
angleValue.textContent = `${roundedDegrees > 0 ? "+" : ""}${roundedDegrees}°`;
needle.style.transform = `translateX(-50%) rotate(${degrees}deg)`;
const cosine = Math.cos(state.currentAngle);
const sine = Math.sin(state.currentAngle);
const leftCenter = -(FLUID_INNER + FLUID_OUTER) * 0.5;
const rightCenter = (FLUID_INNER + FLUID_OUTER) * 0.5;
const leftLocalHeight = (localHeight - sine * leftCenter) / cosine;
const rightLocalHeight = (localHeight - sine * rightCenter) / cosine;
worldLevelEl.textContent = `${worldHeight.toFixed(2)} u`;
leftLevelEl.textContent = `${leftLocalHeight.toFixed(2)} u`;
rightLevelEl.textContent = `${rightLocalHeight.toFixed(2)} u`;
renderer.render(scene, camera);
}
animate();
loading.remove();
</script>
</body>
</html>
```