Prompt specification
Build or customize the Three.js 3D scene "Floating block displacement tank" 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: Floating block displacement tank
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/floating-block-displacement-tank-x1441
Scene Description Prompt:
Floating block displacement tank. Place a rectangular block partly submerged in a transparent tank and highlight displaced volume; show buoyancy from fluid density, gravity, and submerged volume. Please build this with Three.js from cdnjs in one self-contained HTML file, using low-poly forms.
Working Three.js Starter (floating-block-displacement-tank-x1441):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Displacement Tank — Three.js</title>
<style>
:root {
color-scheme: dark;
--bg: #071118;
--panel: rgba(8, 22, 32, 0.82);
--panel-border: rgba(128, 220, 255, 0.2);
--text: #e9f7ff;
--muted: #88a8b8;
--cyan: #61dcff;
--amber: #ffc857;
--coral: #ff7278;
--green: #68e6a4;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 55% 35%, #102a3a 0%, #081722 40%, #040b11 100%);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--text);
}
#app,
#app canvas {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
}
#app canvas {
display: block;
touch-action: none;
outline: none;
}
.brand {
position: fixed;
z-index: 10;
top: 20px;
left: 24px;
pointer-events: none;
text-shadow: 0 2px 15px rgba(0, 0, 0, 0.7);
}
.brand .eyebrow {
margin-bottom: 5px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.24em;
text-transform: uppercase;
}
.brand h1 {
margin: 0;
font-size: clamp(20px, 2.5vw, 31px);
line-height: 1;
letter-spacing: -0.04em;
}
.brand p {
margin: 7px 0 0;
color: var(--muted);
font-size: 12px;
}
.glass {
border: 1px solid var(--panel-border);
background: var(--panel);
box-shadow:
0 18px 50px rgba(0, 0, 0, 0.28),
inset 0 1px 0 rgba(255, 255, 255, 0.035);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
.panel {
position: fixed;
z-index: 20;
border-radius: 15px;
}
.controls {
top: 110px;
left: 24px;
width: 308px;
padding: 17px;
}
.panel-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 15px;
color: #cce8f4;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.live-badge {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--green);
font-size: 9px;
letter-spacing: 0.14em;
}
.live-badge::before {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 10px var(--green);
content: "";
}
.control {
margin-top: 15px;
}
.control-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 7px;
}
.control label {
color: #bdd3de;
font-size: 12px;
font-weight: 650;
}
.control output {
color: var(--cyan);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
font-weight: 750;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 0;
border-radius: 999px;
appearance: none;
background: linear-gradient(
90deg,
rgba(97, 220, 255, 0.8),
rgba(97, 220, 255, 0.16)
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
border: 2px solid #dff8ff;
border-radius: 50%;
appearance: none;
background: #1a91b7;
box-shadow: 0 0 0 4px rgba(97, 220, 255, 0.12);
}
input[type="range"]::-moz-range-thumb {
width: 12px;
height: 12px;
border: 2px solid #dff8ff;
border-radius: 50%;
background: #1a91b7;
box-shadow: 0 0 0 4px rgba(97, 220, 255, 0.12);
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 18px;
}
button {
min-height: 35px;
border: 1px solid rgba(130, 220, 255, 0.2);
border-radius: 8px;
background: rgba(37, 100, 126, 0.18);
color: #d9f4ff;
font: inherit;
font-size: 11px;
font-weight: 700;
cursor: pointer;
transition:
background 150ms ease,
border-color 150ms ease,
transform 150ms ease;
}
button:hover {
border-color: rgba(97, 220, 255, 0.55);
background: rgba(47, 137, 170, 0.28);
}
button:active {
transform: translateY(1px);
}
.metrics {
top: 24px;
right: 24px;
width: 310px;
padding: 17px;
}
.status {
display: flex;
align-items: center;
gap: 9px;
min-height: 39px;
margin-bottom: 14px;
padding: 9px 11px;
border: 1px solid rgba(104, 230, 164, 0.2);
border-radius: 9px;
background: rgba(104, 230, 164, 0.07);
color: var(--green);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.04em;
}
.status::before {
width: 7px;
height: 7px;
flex: 0 0 auto;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 9px currentColor;
content: "";
}
.status[data-state="warning"] {
border-color: rgba(255, 200, 87, 0.25);
background: rgba(255, 200, 87, 0.08);
color: var(--amber);
}
.status[data-state="danger"] {
border-color: rgba(255, 114, 120, 0.25);
background: rgba(255, 114, 120, 0.08);
color: var(--coral);
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.metric {
min-height: 65px;
padding: 10px;
border: 1px solid rgba(150, 220, 245, 0.1);
border-radius: 9px;
background: rgba(255, 255, 255, 0.025);
}
.metric span {
display: block;
margin-bottom: 7px;
color: var(--muted);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric b {
color: #effaff;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 15px;
}
.metric.cyan b {
color: var(--cyan);
}
.metric.amber b {
color: var(--amber);
}
.metric.coral b {
color: var(--coral);
}
.equations {
margin-top: 11px;
padding: 11px;
border-radius: 9px;
background: rgba(0, 0, 0, 0.17);
color: #a8c4d1;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
line-height: 1.85;
}
.equations b {
color: #e7f7ff;
}
.legend {
position: fixed;
z-index: 15;
right: 24px;
bottom: 22px;
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 13px;
max-width: 430px;
padding: 9px 12px;
border: 1px solid rgba(130, 220, 255, 0.13);
border-radius: 10px;
background: rgba(5, 16, 23, 0.66);
color: #b2c9d5;
font-size: 10px;
backdrop-filter: blur(10px);
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 6px;
white-space: nowrap;
}
.swatch {
width: 9px;
height: 9px;
border-radius: 2px;
background: var(--cyan);
box-shadow: 0 0 8px currentColor;
}
.swatch.amber {
background: var(--amber);
}
.swatch.coral {
background: var(--coral);
}
.swatch.blue {
background: #287fc4;
}
.hint {
position: fixed;
z-index: 12;
bottom: 24px;
left: 24px;
color: rgba(190, 218, 230, 0.65);
font-size: 10px;
pointer-events: none;
}
@media (max-width: 850px) {
.brand {
top: 14px;
left: 14px;
}
.brand p {
display: none;
}
.controls {
top: 74px;
left: 14px;
width: min(285px, calc(100vw - 28px));
padding: 13px;
}
.metrics {
top: auto;
right: 14px;
bottom: 48px;
width: min(285px, calc(100vw - 28px));
padding: 13px;
}
.equations {
display: none;
}
.legend {
right: 14px;
bottom: 12px;
left: 14px;
justify-content: center;
gap: 9px;
}
.hint {
display: none;
}
}
</style>
</head>
<body>
<div id="app"></div>
<header class="brand">
<div class="eyebrow">Interactive Fluid Mechanics</div>
<h1>Displacement Tank</h1>
<p>Archimedes’ principle, live force balance, and submerged volume</p>
</header>
<section class="panel controls glass" aria-label="Simulation controls">
<div class="panel-title">
<span>Experiment Controls</span>
<span class="live-badge">Live</span>
</div>
<div class="control">
<div class="control-head">
<label for="fluidDensity">Fluid density, ρ<sub>f</sub></label>
<output id="fluidValue">1000 kg/m³</output>
</div>
<input
id="fluidDensity"
type="range"
min="800"
max="1300"
step="10"
value="1000"
/>
</div>
<div class="control">
<div class="control-head">
<label for="blockDensity">Block density, ρ<sub>b</sub></label>
<output id="blockValue">600 kg/m³</output>
</div>
<input
id="blockDensity"
type="range"
min="200"
max="1400"
step="10"
value="600"
/>
</div>
<div class="control">
<div class="control-head">
<label for="gravity">Gravity, g</label>
<output id="gravityValue">9.81 m/s²</output>
</div>
<input
id="gravity"
type="range"
min="3"
max="15"
step="0.01"
value="9.81"
/>
</div>
<div class="button-row">
<button id="resetDemo" type="button">Reset experiment</button>
<button id="resetCamera" type="button">Reset camera</button>
</div>
</section>
<section class="panel metrics glass" aria-label="Live measurements">
<div class="panel-title">
<span>Force & Volume Readout</span>
<span>SI units</span>
</div>
<div id="status" class="status">FLOATING · 60% submerged</div>
<div class="metric-grid">
<div class="metric">
<span>Block volume</span>
<b id="totalVolume">6.91 m³</b>
</div>
<div class="metric amber">
<span>Displaced volume</span>
<b id="subVolume">4.15 m³</b>
</div>
<div class="metric cyan">
<span>Buoyancy</span>
<b id="buoyancy">40.7 kN</b>
</div>
<div class="metric coral">
<span>Weight</span>
<b id="weight">40.7 kN</b>
</div>
<div class="metric">
<span>Net vertical force</span>
<b id="netForce">0.0 kN</b>
</div>
<div class="metric">
<span>Submerged</span>
<b id="subPercent">60%</b>
</div>
</div>
<div class="equations">
<div>Buoyancy: <b>B = ρ<sub>f</sub> · g · V<sub>sub</sub></b></div>
<div>Weight: <b>W = ρ<sub>b</sub> · g · V<sub>block</sub></b></div>
<div>Float condition: <b>ρ<sub>b</sub> ≤ ρ<sub>f</sub></b></div>
</div>
</section>
<div class="legend" aria-label="Color legend">
<span class="legend-item">
<i class="swatch"></i> Buoyancy
</span>
<span class="legend-item">
<i class="swatch amber"></i> Displaced volume
</span>
<span class="legend-item">
<i class="swatch coral"></i> Weight / gravity
</span>
<span class="legend-item">
<i class="swatch blue"></i> Fluid
</span>
</div>
<div class="hint">Drag to orbit · Scroll or pinch to zoom · Double-click to reset view</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 fluidSlider = $("fluidDensity");
const blockSlider = $("blockDensity");
const gravitySlider = $("gravity");
const fluidValue = $("fluidValue");
const blockValue = $("blockValue");
const gravityValue = $("gravityValue");
const statusElement = $("status");
const totalVolumeElement = $("totalVolume");
const subVolumeElement = $("subVolume");
const buoyancyElement = $("buoyancy");
const weightElement = $("weight");
const netForceElement = $("netForce");
const subPercentElement = $("subPercent");
const TANK_W = 8.4;
const TANK_D = 5.4;
const TANK_FLOOR = -2.35;
const TANK_TOP = 2.2;
const WATER_Y = 0;
const BLOCK_W = 2.4;
const BLOCK_H = 1.8;
const BLOCK_D = 1.6;
const BLOCK_VOLUME = BLOCK_W * BLOCK_H * BLOCK_D;
let fluidDensity = Number(fluidSlider.value);
let blockDensity = Number(blockSlider.value);
let gravity = Number(gravitySlider.value);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071118);
scene.fog = new THREE.FogExp2(0x071118, 0.026);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
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.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute("aria-label", "Interactive displacement tank simulation");
$("app").appendChild(renderer.domElement);
const hemiLight = new THREE.HemisphereLight(0xbceeff, 0x172027, 2.2);
scene.add(hemiLight);
const keyLight = new THREE.DirectionalLight(0xfff2da, 3.0);
keyLight.position.set(5, 10, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -9;
keyLight.shadow.camera.right = 9;
keyLight.shadow.camera.top = 9;
keyLight.shadow.camera.bottom = -9;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 30;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x55dfff, 1.8);
rimLight.position.set(-7, 4, -6);
scene.add(rimLight);
const floorGrid = new THREE.GridHelper(22, 22, 0x315267, 0x17313f);
floorGrid.position.y = TANK_FLOOR - 0.15;
floorGrid.material.transparent = true;
floorGrid.material.opacity = 0.55;
scene.add(floorGrid);
// ------------------------------------------------------------------
// Tank and fluid
// ------------------------------------------------------------------
const baseMaterial = new THREE.MeshStandardMaterial({
color: 0x18303c,
roughness: 0.72,
metalness: 0.25,
flatShading: true
});
const base = new THREE.Mesh(
new THREE.BoxGeometry(TANK_W + 0.28, 0.18, TANK_D + 0.28),
baseMaterial
);
base.position.y = TANK_FLOOR - 0.09;
base.receiveShadow = true;
scene.add(base);
const glassMaterial = new THREE.MeshPhysicalMaterial({
color: 0xa9e9ff,
transparent: true,
opacity: 0.08,
roughness: 0.08,
metalness: 0,
side: THREE.DoubleSide,
depthWrite: false
});
const tankHeight = TANK_TOP - TANK_FLOOR;
const tankCenterY = (TANK_TOP + TANK_FLOOR) / 2;
function addGlassPanel(width, height, depth, x, y, z) {
const panel = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
glassMaterial
);
panel.position.set(x, y, z);
panel.renderOrder = 5;
scene.add(panel);
return panel;
}
addGlassPanel(0.07, tankHeight, TANK_D, -TANK_W / 2, tankCenterY, 0);
addGlassPanel(0.07, tankHeight, TANK_D, TANK_W / 2, tankCenterY, 0);
addGlassPanel(TANK_W, tankHeight, 0.07, 0, tankCenterY, -TANK_D / 2);
addGlassPanel(TANK_W, tankHeight, 0.07, 0, tankCenterY, TANK_D / 2);
const tankOutline = new THREE.LineSegments(
new THREE.EdgesGeometry(
new THREE.BoxGeometry(TANK_W, tankHeight, TANK_D)
),
new THREE.LineBasicMaterial({
color: 0x79d9f4,
transparent: true,
opacity: 0.46
})
);
tankOutline.position.y = tankCenterY;
scene.add(tankOutline);
const frameMaterial = new THREE.MeshStandardMaterial({
color: 0x376577,
roughness: 0.48,
metalness: 0.55,
transparent: true,
opacity: 0.72
});
for (const x of [-TANK_W / 2, TANK_W / 2]) {
for (const z of [-TANK_D / 2, TANK_D / 2]) {
const post = new THREE.Mesh(
new THREE.BoxGeometry(0.065, tankHeight, 0.065),
frameMaterial
);
post.position.set(x, tankCenterY, z);
scene.add(post);
}
}
const waterDepth = WATER_Y - TANK_FLOOR;
const water = new THREE.Mesh(
new THREE.BoxGeometry(
TANK_W - 0.16,
waterDepth,
TANK_D - 0.16
),
new THREE.MeshPhongMaterial({
color: 0x167db4,
transparent: true,
opacity: 0.16,
shininess: 85,
depthWrite: false,
side: THREE.DoubleSide
})
);
water.position.y = TANK_FLOOR + waterDepth / 2;
water.renderOrder = 1;
scene.add(water);
const surface = new THREE.Mesh(
new THREE.PlaneGeometry(TANK_W - 0.16, TANK_D - 0.16, 8, 6),
new THREE.MeshBasicMaterial({
color: 0x36aee8,
transparent: true,
opacity: 0.28,
side: THREE.DoubleSide,
depthWrite: false
})
);
surface.rotation.x = -Math.PI / 2;
surface.position.y = WATER_Y + 0.012;
surface.renderOrder = 3;
scene.add(surface);
const surfaceGridPoints = [];
for (let x = -3.5; x <= 3.5; x += 0.5) {
surfaceGridPoints.push(
new THREE.Vector3(x, WATER_Y + 0.02, -2.55),
new THREE.Vector3(x, WATER_Y + 0.02, 2.55)
);
}
for (let z = -2.5; z <= 2.5; z += 0.5) {
surfaceGridPoints.push(
new THREE.Vector3(-4.05, WATER_Y + 0.02, z),
new THREE.Vector3(4.05, WATER_Y + 0.02, z)
);
}
const surfaceGrid = new THREE.LineSegments(
new THREE.BufferGeometry().setFromPoints(surfaceGridPoints),
new THREE.LineBasicMaterial({
color: 0xa1e8ff,
transparent: true,
opacity: 0.17
})
);
scene.add(surfaceGrid);
// ------------------------------------------------------------------
// Block and highlighted displaced volume
// ------------------------------------------------------------------
const blockGroup = new THREE.Group();
scene.add(blockGroup);
const blockMaterial = new THREE.MeshStandardMaterial({
color: 0xc98a45,
roughness: 0.62,
metalness: 0.06,
flatShading: true
});
const blockGeometry = new THREE.BoxGeometry(BLOCK_W, BLOCK_H, BLOCK_D);
const block = new THREE.Mesh(blockGeometry, blockMaterial);
block.castShadow = true;
block.receiveShadow = true;
blockGroup.add(block);
const blockEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(blockGeometry),
new THREE.LineBasicMaterial({
color: 0x6c3d1b,
transparent: true,
opacity: 0.9
})
);
block.add(blockEdges);
const displacedFill = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshBasicMaterial({
color: 0xffbd4a,
transparent: true,
opacity: 0.4,
depthTest: false,
depthWrite: false,
side: THREE.DoubleSide
})
);
displacedFill.renderOrder = 20;
scene.add(displacedFill);
const displacedEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.BoxGeometry(1, 1, 1)),
new THREE.LineBasicMaterial({
color: 0xffd66e,
transparent: true,
opacity: 0.95,
depthTest: false,
depthWrite: false
})
);
displacedEdges.renderOrder = 21;
scene.add(displacedEdges);
// ------------------------------------------------------------------
// Canvas-based labels
// ------------------------------------------------------------------
function roundedRect(ctx, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + width, y, x + width, y + height, r);
ctx.arcTo(x + width, y + height, x, y + height, r);
ctx.arcTo(x, y + height, x, y, r);
ctx.arcTo(x, y, x + width, y, r);
ctx.closePath();
}
function createLabel() {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const ctx = canvas.getContext("2d");
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
texture.anisotropy = Math.min(
4,
renderer.capabilities.getMaxAnisotropy()
);
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.renderOrder = 40;
scene.add(sprite);
return {
sprite,
canvas,
ctx,
texture,
lastKey: ""
};
}
function setLabel(label, title, value, accent = "#61dcff") {
const key = `${title}|${value}|${accent}`;
if (label.lastKey === key) return;
label.lastKey = key;
const { ctx, canvas } = label;
ctx.clearRect(0, 0, canvas.width, canvas.height);
roundedRect(ctx, 5, 5, 502, 118, 19);
ctx.fillStyle = "rgba(5, 17, 25, 0.9)";
ctx.fill();
ctx.lineWidth = 3;
ctx.strokeStyle = accent;
ctx.stroke();
roundedRect(ctx, 19, 20, 7, 88, 4);
ctx.fillStyle = accent;
ctx.fill();
ctx.textBaseline = "middle";
ctx.fillStyle = "#a9c5d3";
ctx.font = "700 25px system-ui, sans-serif";
ctx.fillText(title, 43, 40);
ctx.fillStyle = "#f1fbff";
ctx.font = "800 35px ui-monospace, SFMono-Regular, Menlo, monospace";
ctx.fillText(value, 43, 83);
label.texture.needsUpdate = true;
}
const buoyancyLabel = createLabel();
buoyancyLabel.sprite.scale.set(3.25, 0.81, 1);
const weightLabel = createLabel();
weightLabel.sprite.scale.set(3.25, 0.81, 1);
const displacedLabel = createLabel();
displacedLabel.sprite.scale.set(3.3, 0.83, 1);
const waterlineLabel = createLabel();
waterlineLabel.sprite.scale.set(2.55, 0.64, 1);
waterlineLabel.sprite.position.set(-3.45, 0.26, 2.65);
setLabel(waterlineLabel, "WATERLINE", "y = 0.00 m", "#61dcff");
// ------------------------------------------------------------------
// Force arrows
// ------------------------------------------------------------------
const buoyancyArrow = new THREE.ArrowHelper(
new THREE.Vector3(0, 1, 0),
new THREE.Vector3(),
1,
0x61dcff,
0.28,
0.18
);
const weightArrow = new THREE.ArrowHelper(
new THREE.Vector3(0, -1, 0),
new THREE.Vector3(),
1,
0xff7278,
0.28,
0.18
);
function makeArrowVisibleInFront(arrow) {
arrow.line.material.depthTest = false;
arrow.line.material.depthWrite = false;
arrow.cone.material.depthTest = false;
arrow.cone.material.depthWrite = false;
arrow.line.renderOrder = 30;
arrow.cone.renderOrder = 30;
}
makeArrowVisibleInFront(buoyancyArrow);
makeArrowVisibleInFront(weightArrow);
scene.add(buoyancyArrow);
scene.add(weightArrow);
// ------------------------------------------------------------------
// Low-poly bubbles
// ------------------------------------------------------------------
const bubbles = [];
const bubbleGeometry = new THREE.IcosahedronGeometry(0.075, 0);
const bubbleMaterial = new THREE.MeshBasicMaterial({
color: 0xc5f5ff,
transparent: true,
opacity: 0.42,
depthWrite: false
});
for (let i = 0; i < 11; i++) {
const bubble = new THREE.Mesh(bubbleGeometry, bubbleMaterial);
bubble.position.set(
(Math.random() - 0.5) * 7.2,
TANK_FLOOR + Math.random() * 2.1,
(Math.random() - 0.5) * 4.8
);
bubble.userData.speed = 0.12 + Math.random() * 0.18;
bubble.userData.offset = Math.random() * Math.PI * 2;
scene.add(bubble);
bubbles.push(bubble);
}
// ------------------------------------------------------------------
// Equilibrium model
// ------------------------------------------------------------------
function equilibriumY() {
if (blockDensity > fluidDensity) {
return TANK_FLOOR + 0.08 + BLOCK_H / 2;
}
const submergedFraction = Math.min(1, blockDensity / fluidDensity);
const targetSubmergedHeight = BLOCK_H * submergedFraction;
return WATER_Y - targetSubmergedHeight + BLOCK_H / 2;
}
let currentY = equilibriumY();
let targetY = currentY;
blockGroup.position.y = currentY;
function refreshInputs() {
fluidDensity = Number(fluidSlider.value);
blockDensity = Number(blockSlider.value);
gravity = Number(gravitySlider.value);
fluidValue.textContent = `${fluidDensity.toFixed(0)} kg/m³`;
blockValue.textContent = `${blockDensity.toFixed(0)} kg/m³`;
gravityValue.textContent = `${gravity.toFixed(2)} m/s²`;
targetY = equilibriumY();
}
fluidSlider.addEventListener("input", refreshInputs);
blockSlider.addEventListener("input", refreshInputs);
gravitySlider.addEventListener("input", refreshInputs);
$("resetDemo").addEventListener("click", () => {
fluidSlider.value = 1000;
blockSlider.value = 600;
gravitySlider.value = 9.81;
refreshInputs();
currentY = equilibriumY();
});
// ------------------------------------------------------------------
// Direct camera controls: orbit, wheel zoom, and pinch zoom
// ------------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, -0.2, 0);
const defaultCamera = {
theta: 0.78,
phi: 1.04,
radius: 12.3
};
const desiredCamera = { ...defaultCamera };
const actualCamera = { ...defaultCamera };
const pointers = new Map();
let previousPinchDistance = 0;
function pointerDistance() {
const values = [...pointers.values()];
if (values.length < 2) return 0;
return Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
}
renderer.domElement.addEventListener("pointerdown", (event) => {
renderer.domElement.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (pointers.size === 2) {
previousPinchDistance = pointerDistance();
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
const previous = pointers.get(event.pointerId);
if (!previous) return;
const current = { x: event.clientX, y: event.clientY };
pointers.set(event.pointerId, current);
if (pointers.size === 1) {
const dx = current.x - previous.x;
const dy = current.y - previous.y;
desiredCamera.theta -= dx * 0.006;
desiredCamera.phi = THREE.MathUtils.clamp(
desiredCamera.phi - dy * 0.006,
0.38,
1.42
);
} else if (pointers.size === 2) {
const distance = pointerDistance();
if (distance > 0 && previousPinchDistance > 0) {
desiredCamera.radius = THREE.MathUtils.clamp(
desiredCamera.radius *
(previousPinchDistance / distance),
7.2,
18.5
);
}
previousPinchDistance = distance;
}
});
function removePointer(event) {
pointers.delete(event.pointerId);
previousPinchDistance = pointers.size === 2 ? pointerDistance() : 0;
}
renderer.domElement.addEventListener("pointerup", removePointer);
renderer.domElement.addEventListener("pointercancel", removePointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
desiredCamera.radius = THREE.MathUtils.clamp(
desiredCamera.radius * Math.exp(event.deltaY * 0.001),
7.2,
18.5
);
},
{ passive: false }
);
function resetCamera() {
desiredCamera.theta = defaultCamera.theta;
desiredCamera.phi = defaultCamera.phi;
desiredCamera.radius = defaultCamera.radius;
}
$("resetCamera").addEventListener("click", resetCamera);
renderer.domElement.addEventListener("dblclick", resetCamera);
function updateCamera() {
const smoothing = 0.11;
actualCamera.theta +=
(desiredCamera.theta - actualCamera.theta) * smoothing;
actualCamera.phi +=
(desiredCamera.phi - actualCamera.phi) * smoothing;
actualCamera.radius +=
(desiredCamera.radius - actualCamera.radius) * smoothing;
const sinPhi = Math.sin(actualCamera.phi);
camera.position.set(
cameraTarget.x +
actualCamera.radius * sinPhi * Math.cos(actualCamera.theta),
cameraTarget.y + actualCamera.radius * Math.cos(actualCamera.phi),
cameraTarget.z +
actualCamera.radius * sinPhi * Math.sin(actualCamera.theta)
);
camera.lookAt(cameraTarget);
}
// ------------------------------------------------------------------
// Measurements and rendering
// ------------------------------------------------------------------
function forceText(newtons) {
const kilonewtons = newtons / 1000;
return `${kilonewtons.toFixed(1)} kN`;
}
function signedForceText(newtons) {
const kilonewtons = newtons / 1000;
const sign = kilonewtons > 0.05 ? "+" : "";
return `${sign}${kilonewtons.toFixed(1)} kN`;
}
function currentSubmergedHeight() {
const bottom = currentY - BLOCK_H / 2;
const top = currentY + BLOCK_H / 2;
return Math.max(0, Math.min(top, WATER_Y) - bottom);
}
function updateSimulation(dt) {
const response = 1 - Math.exp(-dt * 4.2);
currentY += (targetY - currentY) * response;
if (Math.abs(targetY - currentY) < 0.0005) {
currentY = targetY;
}
blockGroup.position.y = currentY;
const blockBottom = currentY - BLOCK_H / 2;
const blockTop = currentY + BLOCK_H / 2;
const submergedHeight = currentSubmergedHeight();
const submergedTop = Math.min(blockTop, WATER_Y);
displacedFill.visible = displacedEdges.visible = submergedHeight > 0.005;
if (submergedHeight > 0.005) {
displacedFill.scale.set(BLOCK_W, submergedHeight, BLOCK_D);
displacedEdges.scale.set(BLOCK_W, submergedHeight, BLOCK_D);
const submergedCenter = (blockBottom + submergedTop) / 2;
displacedFill.position.set(0, submergedCenter, 0);
displacedEdges.position.set(0, submergedCenter, 0);
}
const displacedVolume = BLOCK_W * BLOCK_D * submergedHeight;
const buoyancyForce = fluidDensity * gravity * displacedVolume;
const weightForce = blockDensity * gravity * BLOCK_VOLUME;
const maximumForce = Math.max(buoyancyForce, weightForce, 1);
const buoyancyLength =
0.3 + 1.9 * (buoyancyForce / maximumForce);
const weightLength =
0.3 + 1.9 * (weightForce / maximumForce);
buoyancyArrow.position.set(-0.86, currentY, 0.98);
weightArrow.position.set(0.86, currentY, 0.98);
buoyancyArrow.setLength(buoyancyLength, 0.28, 0.18);
weightArrow.setLength(weightLength, 0.28, 0.18);
buoyancyLabel.sprite.position.set(
-0.86,
currentY + buoyancyLength + 0.38,
1.02
);
weightLabel.sprite.position.set(
0.86,
currentY - weightLength - 0.37,
1.02
);
displacedLabel.sprite.position.set(
2.5,
Math.max(TANK_FLOOR + 0.35, currentY - 0.15),
0.8
);
return {
displacedVolume,
submergedHeight,
buoyancyForce,
weightForce
};
}
function updateReadout(values) {
const {
displacedVolume,
submergedHeight,
buoyancyForce,
weightForce
} = values;
const submergedPercent = (submergedHeight / BLOCK_H) * 100;
const netForce = buoyancyForce - weightForce;
const moving = Math.abs(targetY - currentY) > 0.025;
totalVolumeElement.textContent = `${BLOCK_VOLUME.toFixed(2)} m³`;
subVolumeElement.textContent = `${displacedVolume.toFixed(2)} m³`;
buoyancyElement.textContent = forceText(buoyancyForce);
weightElement.textContent = forceText(weightForce);
netForceElement.textContent = signedForceText(netForce);
subPercentElement.textContent = `${submergedPercent.toFixed(0)}%`;
setLabel(
buoyancyLabel,
"BUOYANCY",
forceText(buoyancyForce),
"#61dcff"
);
setLabel(
weightLabel,
"WEIGHT / GRAVITY",
forceText(weightForce),
"#ff7278"
);
setLabel(
displacedLabel,
"DISPLACED VOLUME",
`${displacedVolume.toFixed(2)} m³`,
"#ffc857"
);
if (blockDensity > fluidDensity) {
statusElement.dataset.state = moving ? "warning" : "danger";
statusElement.textContent = moving
? "SINKING · BLOCK IS DENSER THAN FLUID"
: "RESTING ON FLOOR · TOO DENSE TO FLOAT";
} else if (Math.abs(blockDensity - fluidDensity) < 1) {
statusElement.dataset.state = "warning";
statusElement.textContent = "NEUTRAL · FULLY SUBMERGED";
} else if (moving) {
statusElement.dataset.state = "warning";
statusElement.textContent = "SETTLING TO FORCE EQUILIBRIUM";
} else {
statusElement.dataset.state = "normal";
statusElement.textContent =
`FLOATING · ${submergedPercent.toFixed(0)}% SUBMERGED`;
}
}
// ------------------------------------------------------------------
// Animation loop
// ------------------------------------------------------------------
refreshInputs();
currentY = equilibriumY();
blockGroup.position.y = currentY;
const clock = new THREE.Clock();
let readoutTimer = 0;
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
updateCamera();
const values = updateSimulation(dt);
for (let i = 0; i < bubbles.length; i++) {
const bubble = bubbles[i];
bubble.position.y += bubble.userData.speed * dt;
bubble.position.x +=
Math.sin(elapsed * 0.8 + bubble.userData.offset) * 0.0008;
bubble.rotation.y += dt * 0.35;
bubble.rotation.x += dt * 0.2;
if (bubble.position.y > WATER_Y - 0.08) {
bubble.position.y = TANK_FLOOR + 0.08;
bubble.position.x = (Math.random() - 0.5) * 7.2;
bubble.position.z = (Math.random() - 0.5) * 4.8;
}
}
readoutTimer += dt;
if (readoutTimer >= 0.08) {
readoutTimer = 0;
updateReadout(values);
}
renderer.render(scene, camera);
}
animate();
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
</script>
</body>
</html>
```