Prompt specification
Build or customize the Three.js 3D scene "Floor-plan area conservation exhibit" 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: Floor-plan area conservation exhibit
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/floor-plan-area-conservation-exhibit-x1683
Scene Description Prompt:
Compose two room layouts formed from the same set of rigid floor tiles; compare equal usable tile area despite different outlines and boundary lengths. Use Three.js from cdnjs in a single HTML file, with visible voxel blocks.
Technical checks: Keep exactly 24 tiles in both arrangements and calculate each perimeter by counting exposed edges of the displayed tile layout. Verify the measurements with the tile spacing set to zero.
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 (floor-plan-area-conservation-exhibit-x1683):
```html
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mesma área, contornos diferentes</title>
<style>
:root {
color-scheme: dark;
--bg: #07111d;
--panel: rgba(13, 29, 45, 0.86);
--panel-solid: #0d1d2d;
--line: rgba(151, 201, 225, 0.18);
--text: #edf8ff;
--muted: #91adbf;
--cyan: #61e7ff;
--green: #64efbb;
--orange: #ffb45b;
--red: #ff7887;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: var(--text);
}
#app {
width: 100%;
height: 100vh;
height: 100dvh;
display: grid;
grid-template-rows: auto minmax(0, 1fr) auto;
background:
radial-gradient(circle at 50% 0%, rgba(40, 113, 143, 0.18), transparent 38%),
linear-gradient(180deg, #081421, #06101a);
}
header {
position: relative;
z-index: 5;
padding: 18px 24px 14px;
border-bottom: 1px solid var(--line);
background: rgba(7, 17, 29, 0.78);
backdrop-filter: blur(14px);
}
.heading-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-icon {
position: relative;
width: 42px;
height: 42px;
flex: 0 0 auto;
border: 1px solid rgba(97, 231, 255, 0.48);
border-radius: 13px;
background:
linear-gradient(90deg, transparent 46%, rgba(97, 231, 255, 0.22) 47%, rgba(97, 231, 255, 0.22) 53%, transparent 54%),
linear-gradient(0deg, transparent 46%, rgba(97, 231, 255, 0.22) 47%, rgba(97, 231, 255, 0.22) 53%, transparent 54%),
rgba(97, 231, 255, 0.08);
box-shadow: inset 0 0 20px rgba(97, 231, 255, 0.06);
}
.brand-icon::after {
content: "";
position: absolute;
width: 7px;
height: 7px;
right: 6px;
bottom: 6px;
border-radius: 50%;
background: var(--orange);
box-shadow: 0 0 12px rgba(255, 180, 91, 0.7);
}
h1 {
margin: 0;
font-size: clamp(19px, 2vw, 27px);
line-height: 1.15;
letter-spacing: -0.025em;
font-weight: 720;
}
.subtitle {
margin: 5px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.35;
}
.metrics {
display: flex;
align-items: stretch;
justify-content: flex-end;
gap: 8px;
flex-wrap: wrap;
}
.metric {
min-width: 116px;
padding: 8px 11px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(16, 35, 52, 0.66);
}
.metric span {
display: block;
color: var(--muted);
font-size: 10px;
line-height: 1.2;
letter-spacing: 0.075em;
text-transform: uppercase;
}
.metric strong {
display: block;
margin-top: 3px;
font-size: 15px;
font-variant-numeric: tabular-nums;
}
.metric strong em {
color: var(--cyan);
font-style: normal;
}
#stage {
position: relative;
min-height: 0;
overflow: hidden;
isolation: isolate;
}
#stage canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
#stage canvas.dragging {
cursor: grabbing;
}
.world-label {
position: absolute;
z-index: 3;
width: 206px;
padding: 11px 13px 12px;
transform: translate(-50%, calc(-100% - 9px));
pointer-events: none;
border: 1px solid rgba(97, 231, 255, 0.32);
border-radius: 14px;
background:
linear-gradient(145deg, rgba(14, 34, 51, 0.96), rgba(8, 23, 36, 0.92));
box-shadow: 0 14px 35px rgba(0, 0, 0, 0.26);
backdrop-filter: blur(12px);
transition: opacity 120ms ease;
}
.world-label::after {
content: "";
position: absolute;
left: 50%;
bottom: -14px;
width: 1px;
height: 13px;
background: rgba(97, 231, 255, 0.55);
}
.world-label .eyebrow {
display: flex;
align-items: center;
gap: 7px;
color: var(--cyan);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.world-label .eyebrow::before {
content: "";
width: 7px;
height: 7px;
border-radius: 2px;
background: currentColor;
box-shadow: 0 0 10px currentColor;
}
.world-label h2 {
margin: 5px 0 9px;
font-size: 17px;
letter-spacing: -0.015em;
}
.label-stats {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.label-stat {
padding: 6px 7px;
border-radius: 8px;
background: rgba(255, 255, 255, 0.045);
}
.label-stat small {
display: block;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.label-stat b {
display: block;
margin-top: 2px;
font-size: 14px;
font-variant-numeric: tabular-nums;
}
.tile-key {
display: flex;
align-items: center;
gap: 7px;
margin-top: 8px;
color: #b6cad7;
font-size: 10px;
}
.tile-key i {
width: 9px;
height: 9px;
border-radius: 3px;
background: var(--orange);
box-shadow: 0 0 9px rgba(255, 180, 91, 0.42);
}
.difference-badge {
position: absolute;
z-index: 4;
left: 50%;
top: 16px;
transform: translateX(-50%);
padding: 8px 12px;
pointer-events: none;
border: 1px solid rgba(100, 239, 187, 0.33);
border-radius: 999px;
background: rgba(11, 35, 40, 0.82);
color: var(--green);
font-size: 11px;
font-weight: 700;
letter-spacing: 0.035em;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.18);
backdrop-filter: blur(10px);
}
.difference-badge b {
color: #fff;
font-variant-numeric: tabular-nums;
}
footer {
position: relative;
z-index: 5;
padding: 12px 20px 13px;
border-top: 1px solid var(--line);
background: rgba(8, 20, 32, 0.94);
backdrop-filter: blur(14px);
}
.control-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
}
.control-group {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.control-label {
margin-right: 3px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.09em;
text-transform: uppercase;
}
button {
min-height: 34px;
padding: 7px 11px;
border: 1px solid rgba(145, 189, 210, 0.22);
border-radius: 9px;
background: rgba(22, 43, 61, 0.82);
cursor: pointer;
font-size: 11px;
font-weight: 650;
transition: border-color 140ms ease, background 140ms ease, transform 140ms ease;
}
button:hover {
border-color: rgba(97, 231, 255, 0.55);
background: rgba(30, 57, 78, 0.94);
}
button:active {
transform: translateY(1px);
}
button.active,
button[aria-pressed="true"] {
border-color: rgba(97, 231, 255, 0.62);
background: rgba(32, 85, 101, 0.68);
color: #d9fbff;
}
button.primary {
border-color: rgba(100, 239, 187, 0.48);
background: rgba(31, 104, 83, 0.48);
color: #dffff2;
}
button:focus-visible,
input:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: 2px;
}
.gap-control {
display: flex;
align-items: center;
gap: 8px;
min-height: 34px;
padding: 6px 10px;
border: 1px solid rgba(145, 189, 210, 0.17);
border-radius: 9px;
background: rgba(16, 34, 50, 0.72);
}
.gap-control label {
color: var(--muted);
font-size: 10px;
white-space: nowrap;
}
.gap-control output {
min-width: 38px;
color: var(--text);
font-size: 11px;
font-variant-numeric: tabular-nums;
text-align: right;
}
input[type="range"] {
width: 92px;
accent-color: var(--cyan);
cursor: pointer;
}
.status-row {
display: flex;
align-items: center;
gap: 9px;
min-height: 19px;
margin-top: 9px;
color: var(--muted);
font-size: 11px;
}
.status-dot {
width: 7px;
height: 7px;
flex: 0 0 auto;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 9px rgba(97, 231, 255, 0.55);
}
.status-row.ok {
color: #baf7de;
}
.status-row.ok .status-dot {
background: var(--green);
box-shadow: 0 0 9px rgba(100, 239, 187, 0.65);
}
.status-row.error {
color: #ffc0c7;
}
.status-row.error .status-dot {
background: var(--red);
box-shadow: 0 0 9px rgba(255, 120, 135, 0.65);
}
.formula {
margin-left: auto;
color: #718fa2;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
@media (max-width: 980px) {
header {
padding: 13px 15px 11px;
}
.heading-row {
align-items: flex-start;
}
.metrics {
max-width: 55%;
}
.metric {
min-width: 96px;
padding: 6px 8px;
}
.metric strong {
font-size: 13px;
}
footer {
padding: 10px 12px;
}
.control-row {
align-items: flex-start;
}
.formula {
display: none;
}
}
@media (max-width: 680px) {
.heading-row {
display: block;
}
.metrics {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
max-width: none;
margin-top: 11px;
}
.metric {
min-width: 0;
}
.subtitle {
font-size: 11px;
}
.control-row {
display: block;
}
.control-group {
margin-top: 6px;
}
.world-label {
width: 168px;
padding: 9px 10px;
}
.world-label h2 {
font-size: 14px;
}
.difference-badge {
top: 9px;
white-space: nowrap;
font-size: 9px;
}
}
</style>
</head>
<body>
<div id="app">
<header>
<div class="heading-row">
<div class="brand">
<div class="brand-icon" aria-hidden="true"></div>
<div>
<h1>Mesma área, contornos diferentes</h1>
<p class="subtitle">Dois conjuntos de 24 ladrilhos rígidos 1 × 1: a área útil é igual, mas o contorno não.</p>
</div>
</div>
<div class="metrics" aria-label="Resumo comparativo">
<div class="metric">
<span>Área em cada</span>
<strong id="areaMetric">24 u²</strong>
</div>
<div class="metric">
<span>Contornos</span>
<strong id="perimeterMetric">20 u → 24 u</strong>
</div>
<div class="metric">
<span>Arestas expostas</span>
<strong id="edgeMetric">20 → 24</strong>
</div>
<div class="metric">
<span>Adjacências internas</span>
<strong id="adjacencyMetric">38 → 36</strong>
</div>
</div>
</div>
</header>
<main id="stage" aria-label="Cena 3D interativa com os dois arranjos de ladrilhos">
<div id="rectLabel" class="world-label">
<div class="eyebrow">Arranjo A</div>
<h2>Retângulo 4 × 6</h2>
<div class="label-stats">
<div class="label-stat">
<small>Área útil</small>
<b id="rectArea">24 u²</b>
</div>
<div class="label-stat">
<small>Contorno</small>
<b id="rectPerimeter">20 u</b>
</div>
</div>
<div class="tile-key"><i></i> mesmo ladrilho destacado</div>
</div>
<div id="shiftLabel" class="world-label">
<div class="eyebrow">Arranjo B</div>
<h2>Contorno deslocado</h2>
<div class="label-stats">
<div class="label-stat">
<small>Área útil</small>
<b id="shiftArea">24 u²</b>
</div>
<div class="label-stat">
<small>Contorno</small>
<b id="shiftPerimeter">24 u</b>
</div>
</div>
<div class="tile-key"><i></i> mesmo ladrilho reposicionado</div>
</div>
<div id="differenceBadge" class="difference-badge">
mesma área: <b>24 u²</b> · contorno: <b>+4 u</b>
</div>
</main>
<footer>
<div class="control-row">
<div class="control-group">
<span class="control-label">Visualização</span>
<button id="boundaryButton" type="button" aria-pressed="true">Contorno</button>
<button id="gridButton" type="button" aria-pressed="true">Grade</button>
<div class="gap-control">
<label for="gapSlider">Junta visual</label>
<input id="gapSlider" type="range" min="0" max="0.08" step="0.01" value="0">
<output id="gapOutput" for="gapSlider">0,00 u</output>
</div>
</div>
<div class="control-group">
<span class="control-label">Câmera</span>
<button id="compareButton" type="button" class="active">Comparar</button>
<button id="rectButton" type="button">Retângulo</button>
<button id="shiftButton" type="button">Deslocado</button>
<button id="resetButton" type="button">Restaurar vista</button>
</div>
</div>
<div id="statusRow" class="status-row">
<span class="status-dot"></span>
<span id="statusText">Arraste para orbitar, use a roda para aproximar. O teste geométrico começa com junta visual em zero.</span>
<span class="formula">P = 4N − 2A</span>
</div>
</footer>
</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 gapSlider = document.getElementById("gapSlider");
const gapOutput = document.getElementById("gapOutput");
const statusRow = document.getElementById("statusRow");
const statusText = document.getElementById("statusText");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111d);
scene.fog = new THREE.Fog(0x07111d, 27, 58);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(stage.clientWidth, stage.clientHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
stage.prepend(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
38,
stage.clientWidth / stage.clientHeight,
0.1,
100
);
const cameraState = {
theta: 0.28,
phi: 0.84,
radius: 24,
desiredRadius: 24,
target: new THREE.Vector3(0, 0, 0),
desiredTarget: new THREE.Vector3(0, 0, 0)
};
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x + cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y + cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z + cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
updateCamera();
scene.add(new THREE.HemisphereLight(0xbdefff, 0x152033, 2.15));
const keyLight = new THREE.DirectionalLight(0xffffff, 3.4);
keyLight.position.set(-8, 17, 10);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -18;
keyLight.shadow.camera.right = 18;
keyLight.shadow.camera.top = 14;
keyLight.shadow.camera.bottom = -14;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 45;
keyLight.shadow.bias = -0.00035;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x54dfff, 34, 30, 2);
rimLight.position.set(10, 8, -9);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xffad58, 18, 24, 2);
warmLight.position.set(-9, 5, 5);
scene.add(warmLight);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(70, 70),
new THREE.ShadowMaterial({ color: 0x000000, opacity: 0.26 })
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.29;
ground.receiveShadow = true;
scene.add(ground);
const globalGrid = new THREE.GridHelper(48, 48, 0x37657a, 0x183246);
globalGrid.position.y = -0.285;
globalGrid.material.transparent = true;
globalGrid.material.opacity = 0.26;
scene.add(globalGrid);
const starGeometry = new THREE.BufferGeometry();
const starPositions = [];
for (let i = 0; i < 150; i++) {
const angle = Math.random() * Math.PI * 2;
const radius = 17 + Math.random() * 20;
starPositions.push(
Math.cos(angle) * radius,
4 + Math.random() * 15,
Math.sin(angle) * radius
);
}
starGeometry.setAttribute("position", new THREE.Float32BufferAttribute(starPositions, 3));
const stars = new THREE.Points(
starGeometry,
new THREE.PointsMaterial({
color: 0x7abbd1,
size: 0.055,
transparent: true,
opacity: 0.42,
depthWrite: false
})
);
scene.add(stars);
const TILE_SIZE = 1;
const TILE_HEIGHT = 0.28;
const tileGeometry = new THREE.BoxGeometry(TILE_SIZE, TILE_HEIGHT, TILE_SIZE);
const tileEdgeGeometry = new THREE.EdgesGeometry(tileGeometry, 20);
const palette = [
0x2e9ca5,
0x39b8b4,
0x267b91,
0x4ac9c1,
0x328fa2,
0x54d7ca
];
const tileMaterials = palette.map(color =>
new THREE.MeshStandardMaterial({
color,
roughness: 0.62,
metalness: 0.08
})
);
const accentMaterial = new THREE.MeshStandardMaterial({
color: 0xffa94d,
emissive: 0x6e2d00,
emissiveIntensity: 0.28,
roughness: 0.55,
metalness: 0.1
});
const tileEdgeMaterial = new THREE.LineBasicMaterial({
color: 0xb9f6ff,
transparent: true,
opacity: 0.38
});
const horizontalBoundaryGeometry = new THREE.BoxGeometry(1, 0.042, 0.055);
const verticalBoundaryGeometry = new THREE.BoxGeometry(0.055, 0.042, 1);
const boundaryMaterial = new THREE.MeshBasicMaterial({
color: 0x61e7ff,
transparent: true,
opacity: 0.98
});
const rectCells = [];
for (let z = 0; z < 4; z++) {
for (let x = 0; x < 6; x++) {
rectCells.push({ x, z });
}
}
// Exatamente um ladrilho do retângulo é retirado da célula (0, 2)
// e inserido em (6, 2). A área continua 24 e o contorno passa de 20 para 24.
const shiftedCells = rectCells
.filter(cell => !(cell.x === 0 && cell.z === 2))
.concat({ x: 6, z: 2 });
function cellKey(x, z) {
return `${x},${z}`;
}
function computeTopology(cells) {
const occupied = new Set(cells.map(cell => cellKey(cell.x, cell.z)));
const boundary = [];
let adjacencyCount = 0;
const directions = [
{ dx: 1, dz: 0, axis: "x" },
{ dx: -1, dz: 0, axis: "x" },
{ dx: 0, dz: 1, axis: "z" },
{ dx: 0, dz: -1, axis: "z" }
];
for (const cell of cells) {
for (const direction of directions) {
const nx = cell.x + direction.dx;
const nz = cell.z + direction.dz;
if (occupied.has(cellKey(nx, nz))) {
adjacencyCount++;
continue;
}
let a;
let b;
if (direction.axis === "x") {
const edgeX = cell.x + direction.dx * 0.5;
a = { x: edgeX, z: cell.z - 0.5 };
b = { x: edgeX, z: cell.z + 0.5 };
} else {
const edgeZ = cell.z + direction.dz * 0.5;
a = { x: cell.x - 0.5, z: edgeZ };
b = { x: cell.x + 0.5, z: edgeZ };
}
boundary.push({
a,
b,
axis: direction.axis,
length: Math.hypot(b.x - a.x, b.z - a.z),
direction
});
}
}
const perimeter = boundary.reduce((sum, edge) => sum + edge.length, 0);
const formulaPerimeter = 4 * cells.length - 2 * adjacencyCount;
return {
occupied,
boundary,
adjacencyCount,
perimeter,
formulaPerimeter,
area: cells.length * TILE_SIZE * TILE_SIZE
};
}
function boundsOf(cells) {
let minX = Infinity;
let maxX = -Infinity;
let minZ = Infinity;
let maxZ = -Infinity;
for (const cell of cells) {
minX = Math.min(minX, cell.x);
maxX = Math.max(maxX, cell.x);
minZ = Math.min(minZ, cell.z);
maxZ = Math.max(maxZ, cell.z);
}
return {
minX,
maxX,
minZ,
maxZ,
centerX: (minX + maxX) / 2,
centerZ: (minZ + maxZ) / 2,
width: maxX - minX + 1,
depth: maxZ - minZ + 1
};
}
function makeLayout({ id, cells, worldX, accentCell }) {
const group = new THREE.Group();
group.position.x = worldX;
scene.add(group);
const bounds = boundsOf(cells);
const topology = computeTopology(cells);
const tiles = [];
const boundaryGroup = new THREE.Group();
const boundaryEdges = [];
group.add(boundaryGroup);
for (const cell of cells) {
const localX = cell.x - bounds.centerX;
const localZ = cell.z - bounds.centerZ;
const isAccent = cell.x === accentCell.x && cell.z === accentCell.z;
const tile = new THREE.Mesh(
tileGeometry,
isAccent ? accentMaterial : tileMaterials[Math.abs(cell.x + cell.z * 2) % tileMaterials.length]
);
tile.position.set(localX, 0, localZ);
tile.castShadow = true;
tile.receiveShadow = true;
tile.userData = {
cellX: cell.x,
cellZ: cell.z,
accent: isAccent
};
const edges = new THREE.LineSegments(tileEdgeGeometry, tileEdgeMaterial);
edges.renderOrder = 2;
tile.add(edges);
group.add(tile);
tiles.push(tile);
}
// As barras de contorno são geradas a partir das mesmas arestas
// expostas que produzem o valor numérico do perímetro.
for (const edge of topology.boundary) {
const geometry = edge.axis === "x"
? horizontalBoundaryGeometry
: verticalBoundaryGeometry;
const marker = new THREE.Mesh(geometry, boundaryMaterial);
marker.position.set(
(edge.a.x + edge.b.x) / 2,
TILE_HEIGHT / 2 + 0.025,
(edge.a.z + edge.b.z) / 2
);
marker.userData = {
edgeLength: edge.length,
axis: edge.axis
};
boundaryGroup.add(marker);
boundaryEdges.push(marker);
}
const base = new THREE.Mesh(
new THREE.BoxGeometry(bounds.width + 0.72, 0.12, bounds.depth + 0.72),
new THREE.MeshStandardMaterial({
color: 0x102638,
roughness: 0.9,
metalness: 0.02
})
);
base.position.y = -0.2;
base.receiveShadow = true;
group.add(base);
const grid = new THREE.GridHelper(
Math.max(bounds.width, bounds.depth) + 0.6,
Math.max(bounds.width, bounds.depth),
0x2c6277,
0x1b4054
);
grid.position.y = -0.132;
grid.material.transparent = true;
grid.material.opacity = 0.48;
group.add(grid);
return {
id,
group,
cells,
bounds,
topology,
tiles,
boundaryGroup,
boundaryEdges,
grid,
perimeter: topology.perimeter,
area: topology.area,
labelElement: document.getElementById(`${id}Label`),
anchor: new THREE.Vector3(0, 1.25, 0)
};
}
const rectLayout = makeLayout({
id: "rect",
cells: rectCells,
worldX: -5,
accentCell: { x: 0, z: 2 }
});
const shiftedLayout = makeLayout({
id: "shift",
cells: shiftedCells,
worldX: 5.2,
accentCell: { x: 6, z: 2 }
});
const layouts = [rectLayout, shiftedLayout];
function formatDecimal(value) {
return value.toLocaleString("pt-BR", {
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
}
function updateMetricUI() {
document.getElementById("areaMetric").innerHTML =
`${rectLayout.area} = <em>${shiftedLayout.area} u²</em>`;
document.getElementById("perimeterMetric").innerHTML =
`${rectLayout.perimeter} u → <em>${shiftedLayout.perimeter} u</em>`;
document.getElementById("edgeMetric").innerHTML =
`${rectLayout.topology.boundary.length} → <em>${shiftedLayout.topology.boundary.length}</em>`;
document.getElementById("adjacencyMetric").innerHTML =
`${rectLayout.topology.adjacencyCount} → <em>${shiftedLayout.topology.adjacencyCount}</em>`;
document.getElementById("rectArea").textContent = `${rectLayout.area} u²`;
document.getElementById("rectPerimeter").textContent = `${rectLayout.perimeter} u`;
document.getElementById("shiftArea").textContent = `${shiftedLayout.area} u²`;
document.getElementById("shiftPerimeter").textContent = `${shiftedLayout.perimeter} u`;
const difference = shiftedLayout.perimeter - rectLayout.perimeter;
document.getElementById("differenceBadge").innerHTML =
`mesma área: <b>${shiftedLayout.area} u²</b> · contorno: <b>+${difference} u</b>`;
}
updateMetricUI();
function applySpacing(value) {
const gap = THREE.MathUtils.clamp(Number(value), 0, 0.08);
gapSlider.value = gap.toFixed(2);
gapOutput.textContent = `${formatDecimal(gap)} u`;
for (const layout of layouts) {
for (const tile of layout.tiles) {
// Em zero, a largura e a profundidade são exatamente 1 × 1;
// os blocos se tocam e suas faces externas coincidem com o contorno.
tile.scale.x = TILE_SIZE - gap;
tile.scale.z = TILE_SIZE - gap;
}
}
statusRow.className = "status-row";
statusText.textContent = gap === 0
? "Junta visual em zero: os blocos têm dimensão real 1 × 1 e podem ser testados face a face."
: `Junta visual de ${formatDecimal(gap)} u. As métricas continuam descrevendo o passo nominal 1 × 1 da malha; use “Testar geometria” para validar a junta zero.`;
}
applySpacing(0);
function validateLayout(layout) {
const problems = [];
const topology = layout.topology;
if (layout.tiles.length !== 24) {
problems.push(`${layout.id}: número de voxels diferente de 24`);
}
if (topology.boundary.length !== topology.perimeter) {
problems.push(`${layout.id}: número de arestas diferente do perímetro`);
}
if (!THREE.MathUtils.almostEqual(topology.perimeter, topology.formulaPerimeter, 1e-9)) {
problems.push(`${layout.id}: P = 4N − 2A não confere`);
}
for (const tile of layout.tiles) {
if (!THREE.MathUtils.almostEqual(tile.scale.x, 1, 1e-6) ||
!THREE.MathUtils.almostEqual(tile.scale.z, 1, 1e-6)) {
problems.push(`${layout.id}: voxel sem dimensão 1 × 1 na junta zero`);
break;
}
}
for (const edge of layout.boundaryEdges) {
const expected = edge.userData.axis === "x"
? edge.geometry.parameters.width
: edge.geometry.parameters.depth;
if (!THREE.MathUtils.almostEqual(expected, 1, 1e-6) ||
!THREE.MathUtils.almostEqual(edge.userData.edgeLength, 1, 1e-6)) {
problems.push(`${layout.id}: barra de contorno sem comprimento unitário`);
break;
}
}
return problems;
}
function runGeometryAudit() {
// O ensaio relevante é executado no estado de espaçamento visual zero.
gapSlider.value = "0";
applySpacing(0);
const problems = [];
problems.push(...validateLayout(rectLayout));
problems.push(...validateLayout(shiftedLayout));
const expectedRect = rectLayout.perimeter === 20 &&
rectLayout.topology.boundary.length === 20 &&
rectLayout.topology.adjacencyCount === 38;
const expectedShift = shiftedLayout.perimeter === 24 &&
shiftedLayout.topology.boundary.length === 24 &&
shiftedLayout.topology.adjacencyCount === 36;
if (!expectedRect) problems.push("retângulo: valor de referência 20 arestas / 20 u não confere");
if (!expectedShift) problems.push("deslocado: valor de referência 24 arestas / 24 u não confere");
const rectLabelValue = document.getElementById("rectPerimeter").textContent;
const shiftLabelValue = document.getElementById("shiftPerimeter").textContent;
if (!rectLabelValue.includes("20")) problems.push("rótulo do retângulo não corresponde à geometria");
if (!shiftLabelValue.includes("24")) problems.push("rótulo do deslocado não corresponde à geometria");
if (problems.length) {
statusRow.className = "status-row error";
statusText.textContent = `Falha no teste: ${problems.join("; ")}.`;
return;
}
statusRow.className = "status-row ok";
statusText.textContent =
`Teste aprovado na junta zero: retângulo = ${rectLayout.topology.boundary.length} arestas = ${rectLayout.perimeter} u; ` +
`deslocado = ${shiftedLayout.topology.boundary.length} arestas = ${shiftedLayout.perimeter} u. ` +
`Os rótulos foram gerados pela mesma geometria exibida.`;
}
function setStatus(text, mode = "neutral") {
statusRow.className = `status-row${mode === "ok" ? " ok" : mode === "error" ? " error" : ""}`;
statusText.textContent = text;
}
document.getElementById("boundaryButton").addEventListener("click", event => {
const visible = !rectLayout.boundaryGroup.visible;
for (const layout of layouts) {
layout.boundaryGroup.visible = visible;
}
event.currentTarget.setAttribute("aria-pressed", String(visible));
event.currentTarget.classList.toggle("active", visible);
});
document.getElementById("gridButton").addEventListener("click", event => {
const visible = !rectLayout.grid.visible;
for (const layout of layouts) {
layout.grid.visible = visible;
}
globalGrid.visible = visible;
event.currentTarget.setAttribute("aria-pressed", String(visible));
event.currentTarget.classList.toggle("active", visible);
});
gapSlider.addEventListener("input", event => {
applySpacing(event.target.value);
});
document.getElementById("auditButton")?.addEventListener("click", runGeometryAudit);
// Botão de auditoria inserido localmente sem formulário.
const auditButton = document.createElement("button");
auditButton.id = "auditButton";
auditButton.type = "button";
auditButton.className = "primary";
auditButton.textContent = "Testar geometria";
auditButton.addEventListener("click", runGeometryAudit);
document.querySelector(".control-group").appendChild(auditButton);
let focusMode = "compare";
function setFocus(mode) {
focusMode = mode;
const compareRadius = stage.clientWidth / stage.clientHeight < 1.25
? 30
: 24;
if (mode === "compare") {
cameraState.desiredTarget.set(0, 0, 0);
cameraState.desiredRadius = compareRadius;
} else if (mode === "rect") {
cameraState.desiredTarget.set(rectLayout.group.position.x, 0, 0);
cameraState.desiredRadius = 12;
} else if (mode === "shift") {
cameraState.desiredTarget.set(shiftedLayout.group.position.x, 0, 0);
cameraState.desiredRadius = 13;
}
for (const id of ["compareButton", "rectButton", "shiftButton"]) {
document.getElementById(id).classList.toggle("active", id === `${mode}Button`);
}
setStatus(
mode === "compare"
? "Vista comparativa ativa. Arraste para orbitar e use a roda do mouse para aproximar."
: "Vista focal ativa. Clique em “Comparar” para reenquadrar os dois conjuntos."
);
}
document.getElementById("compareButton").addEventListener("click", () => setFocus("compare"));
document.getElementById("rectButton").addEventListener("click", () => setFocus("rect"));
document.getElementById("shiftButton").addEventListener("click", () => setFocus("shift"));
document.getElementById("resetButton").addEventListener("click", () => {
cameraState.theta = 0.28;
cameraState.phi = 0.84;
setFocus("compare");
});
// Controles de câmera implementados diretamente, sem addons.
let dragging = false;
let dragMoved = false;
let previousX = 0;
let previousY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
dragMoved = false;
previousX = event.clientX;
previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.classList.add("dragging");
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
if (Math.abs(dx) + Math.abs(dy) > 1) dragMoved = true;
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(cameraState.phi - dy * 0.005, 0.38, 1.25);
focusMode = "custom";
});
function endDrag(event) {
if (!dragging) return;
dragging = false;
renderer.domElement.classList.remove("dragging");
if (event.pointerId !== undefined && renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
const factor = Math.exp(event.deltaY * 0.001);
cameraState.desiredRadius = THREE.MathUtils.clamp(
cameraState.desiredRadius * factor,
9,
38
);
}, { passive: false });
renderer.domElement.addEventListener("dblclick", () => {
cameraState.theta = 0.28;
cameraState.phi = 0.84;
setFocus("compare");
});
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
renderer.domElement.addEventListener("click", event => {
if (dragMoved) return;
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const tileMeshes = layouts.flatMap(layout => layout.tiles);
const hit = raycaster.intersectObjects(tileMeshes, false)[0];
if (!hit) return;
const data = hit.object.userData;
setStatus(
`Voxel selecionado: célula (${data.cellX}, ${data.cellZ})` +
(data.accent ? " · é o mesmo ladrilho destacado que foi reposicionado." : "."),
"ok"
);
});
function updateWorldLabels() {
scene.updateMatrixWorld();
const width = stage.clientWidth;
const height = stage.clientHeight;
for (const layout of layouts) {
const world = layout.group.localToWorld(layout.anchor.clone());
const projected = world.project(camera);
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
const visible = projected.z > -1 && projected.z < 1;
layout.labelElement.style.left = `${x}px`;
layout.labelElement.style.top = `${y}px`;
layout.labelElement.style.opacity = visible ? "1" : "0";
}
}
function resize() {
const width = Math.max(1, stage.clientWidth);
const height = Math.max(1, stage.clientHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height);
camera.aspect = width / height;
camera.updateProjectionMatrix();
if (focusMode === "compare") {
cameraState.desiredRadius = width / height < 1.25 ? 30 : 24;
}
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(stage);
resize();
function animate() {
cameraState.radius += (cameraState.desiredRadius - cameraState.radius) * 0.1;
cameraState.target.lerp(cameraState.desiredTarget, 0.1);
updateCamera();
updateWorldLabels();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
```