Prompt specification
Build or customize the Three.js 3D scene "Hex Courier Distance Comparison" 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: Hex Courier Distance Comparison
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/hex-courier-distance-comparison-x3546
Scene Description Prompt:
Use Three.js from cdnjs to animate shortest paths between two hex cells under uniform costs. Display coordinate distance and distinguish it from Euclidean straight-line distance across the board. Deliver one self-contained HTML file with visible voxel blocks.
Verify the behavior against the actual geometry and data in each relevant state. Use schematic labels for deliberately synthetic elements.
Technical checks: Keep the board and both routes visible without triangles occluding the cells. Distinguish step count, straight-line distance, and distance along the hex grid.
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 (hex-courier-distance-comparison-x3546):
```html
<!doctype html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Caminhos mínimos em malha hexagonal</title>
<style>
:root {
color-scheme: dark;
--bg: #07121e;
--panel: #0b1b2a;
--panel-2: #102638;
--line: rgba(148, 190, 214, 0.17);
--text: #eef8ff;
--muted: #94adbd;
--cyan: #4ce7ff;
--orange: #ffbd69;
--white: #dcecf5;
--green: #81e6b2;
}
* {
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;
}
body {
display: grid;
grid-template-columns: 360px minmax(0, 1fr);
}
aside {
position: relative;
z-index: 5;
min-height: 0;
overflow-y: auto;
padding: 26px 24px 22px;
background:
radial-gradient(circle at 0 0, rgba(76, 231, 255, 0.09), transparent 34%),
linear-gradient(180deg, #0c1d2c 0%, #081724 100%);
border-right: 1px solid var(--line);
box-shadow: 16px 0 45px rgba(0, 0, 0, 0.18);
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 13px;
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 22px;
height: 2px;
border-radius: 2px;
background: var(--cyan);
box-shadow: 0 0 12px rgba(76, 231, 255, 0.7);
}
h1 {
margin: 0;
font-size: clamp(25px, 3vw, 34px);
line-height: 1.08;
letter-spacing: -0.035em;
}
.intro {
margin: 13px 0 20px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.section-label {
margin: 20px 0 9px;
color: #c7dbe7;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.metric {
min-height: 90px;
padding: 13px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(15, 37, 54, 0.72);
}
.metric .name {
min-height: 27px;
color: var(--muted);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.055em;
line-height: 1.25;
text-transform: uppercase;
}
.metric .value {
margin-top: 8px;
color: var(--text);
font-size: 23px;
font-weight: 760;
letter-spacing: -0.035em;
font-variant-numeric: tabular-nums;
}
.metric.coord .value { color: var(--cyan); }
.metric.straight .value { color: var(--white); }
.metric.mesh .value { color: var(--orange); }
.metric .hint {
margin-top: 3px;
color: #7592a4;
font-size: 10px;
}
.coordinate-card,
.route-card,
.method-card {
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(8, 23, 35, 0.68);
}
.coordinate-card {
padding: 12px 13px;
font-size: 12px;
}
.coordinate-row {
display: flex;
justify-content: space-between;
gap: 15px;
padding: 4px 0;
}
.coordinate-row span:first-child {
color: var(--muted);
}
.mono {
font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
font-variant-numeric: tabular-nums;
}
.route-list {
display: grid;
gap: 8px;
}
.route-card {
display: grid;
grid-template-columns: 11px 1fr auto;
align-items: center;
gap: 10px;
padding: 10px 12px;
}
.route-dot {
width: 10px;
height: 10px;
border-radius: 50%;
box-shadow: 0 0 13px currentColor;
}
.route-dot.a {
color: var(--cyan);
background: var(--cyan);
}
.route-dot.b {
color: var(--orange);
background: var(--orange);
}
.route-title {
font-size: 12px;
font-weight: 750;
}
.route-detail {
margin-top: 2px;
overflow: hidden;
color: var(--muted);
font-size: 10px;
text-overflow: ellipsis;
white-space: nowrap;
}
.route-length {
color: #cbdde8;
font-size: 11px;
font-variant-numeric: tabular-nums;
}
.method-card {
padding: 12px 13px;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
.method-card strong {
color: #d7e8f1;
}
.controls {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 13px;
}
button {
min-height: 39px;
padding: 9px 10px;
border: 1px solid rgba(142, 190, 216, 0.2);
border-radius: 10px;
background: #102a3d;
color: #e8f5fc;
font: inherit;
font-size: 11px;
font-weight: 720;
cursor: pointer;
transition: border-color 160ms ease, background 160ms ease, transform 160ms ease, opacity 160ms ease;
}
button:hover:not(:disabled) {
border-color: rgba(76, 231, 255, 0.6);
background: #15354b;
transform: translateY(-1px);
}
button:active:not(:disabled) {
transform: translateY(0);
}
button:disabled {
cursor: default;
opacity: 0.38;
}
button.primary {
border-color: rgba(76, 231, 255, 0.52);
background: linear-gradient(135deg, #14677c, #11495e);
}
button.active {
border-color: var(--cyan);
color: var(--cyan);
box-shadow: inset 0 0 0 1px rgba(76, 231, 255, 0.18);
}
button.wide {
grid-column: 1 / -1;
}
.selection-note {
min-height: 32px;
margin-top: 9px;
color: #7897aa;
font-size: 10px;
line-height: 1.45;
}
#stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 52% 42%, rgba(29, 83, 108, 0.2), transparent 45%),
#07121e;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.stage-top {
position: absolute;
top: 20px;
left: 22px;
right: 22px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 20px;
pointer-events: none;
}
.stage-badge {
padding: 9px 11px;
border: 1px solid rgba(142, 190, 216, 0.15);
border-radius: 10px;
background: rgba(7, 19, 30, 0.68);
color: #a6bfce;
font-size: 10px;
line-height: 1.45;
backdrop-filter: blur(10px);
}
.stage-badge strong {
color: #e5f5fc;
}
.legend {
display: grid;
gap: 7px;
padding: 9px 11px;
border: 1px solid rgba(142, 190, 216, 0.15);
border-radius: 10px;
background: rgba(7, 19, 30, 0.68);
color: #9eb8c8;
font-size: 10px;
backdrop-filter: blur(10px);
}
.legend-item {
display: flex;
align-items: center;
gap: 8px;
white-space: nowrap;
}
.legend-line {
width: 22px;
height: 3px;
border-radius: 3px;
}
.legend-line.cyan {
background: var(--cyan);
box-shadow: 0 0 8px rgba(76, 231, 255, 0.45);
}
.legend-line.orange {
height: 2px;
background: repeating-linear-gradient(90deg, var(--orange) 0 6px, transparent 6px 9px);
}
.legend-line.white {
height: 1px;
background: repeating-linear-gradient(90deg, #dcecf5 0 5px, transparent 5px 8px);
}
.playback {
position: absolute;
left: 22px;
right: 22px;
bottom: 20px;
padding: 13px 15px;
border: 1px solid rgba(142, 190, 216, 0.17);
border-radius: 13px;
background: rgba(7, 19, 30, 0.76);
box-shadow: 0 14px 36px rgba(0, 0, 0, 0.18);
backdrop-filter: blur(12px);
pointer-events: none;
}
.playback-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
color: #c4d8e4;
font-size: 11px;
}
#playbackStatus {
color: #dff4fb;
font-weight: 650;
}
#geodesicCount {
color: var(--muted);
font-variant-numeric: tabular-nums;
}
.progress {
height: 4px;
margin-top: 10px;
overflow: hidden;
border-radius: 8px;
background: rgba(135, 176, 199, 0.14);
}
#progressFill {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--cyan), var(--orange));
box-shadow: 0 0 12px rgba(76, 231, 255, 0.4);
}
@media (max-width: 900px) {
html, body {
overflow: auto;
}
body {
display: block;
}
aside {
max-height: 43vh;
border-right: 0;
border-bottom: 1px solid var(--line);
}
#stage {
height: 57vh;
min-height: 430px;
}
.stage-top {
top: 12px;
left: 12px;
right: 12px;
}
.legend {
display: none;
}
.playback {
left: 12px;
right: 12px;
bottom: 12px;
}
}
@media (max-width: 520px) {
aside {
padding: 19px 16px;
}
h1 {
font-size: 26px;
}
.metrics {
grid-template-columns: 1fr 1fr;
}
.stage-badge {
max-width: 235px;
}
}
</style>
</head>
<body>
<aside>
<div class="eyebrow">Laboratório de rotas hexagonais</div>
<h1>Caminhos mínimos<br>em malha hexagonal</h1>
<p class="intro">
Explore trajetos de custo uniforme entre duas células. Os blocos voxel seguem
os centros das células, enquanto a reta euclidiana mede a distância direta
entre os mesmos pontos.
</p>
<div class="section-label">Medições do estado atual</div>
<div class="metrics">
<div class="metric">
<div class="name">Passos na malha</div>
<div class="value" id="stepsValue">—</div>
<div class="hint">cada aresta custa 1</div>
</div>
<div class="metric coord">
<div class="name">Distância de coordenadas</div>
<div class="value" id="coordValue">—</div>
<div class="hint">métrica hexagonal q/r</div>
</div>
<div class="metric straight">
<div class="name">Reta euclidiana</div>
<div class="value" id="euclidValue">—</div>
<div class="hint">distância entre centros</div>
</div>
<div class="metric mesh">
<div class="name">Trajeto pela malha</div>
<div class="value" id="meshValue">—</div>
<div class="hint">comprimento acumulado</div>
</div>
</div>
<div class="section-label">Coordenadas axiais</div>
<div class="coordinate-card">
<div class="coordinate-row">
<span>Início A</span>
<strong class="mono" id="coordA">—</strong>
</div>
<div class="coordinate-row">
<span>Destino B</span>
<strong class="mono" id="coordB">—</strong>
</div>
<div class="coordinate-row">
<span>Variação Δ(q, r, s)</span>
<strong class="mono" id="coordDelta">—</strong>
</div>
</div>
<div class="section-label">Rotas minimizadoras</div>
<div class="route-list">
<div class="route-card">
<span class="route-dot a"></span>
<div>
<div class="route-title">Rota A</div>
<div class="route-detail" id="routeADetail">—</div>
</div>
<span class="route-length" id="routeALength">—</span>
</div>
<div class="route-card">
<span class="route-dot b"></span>
<div>
<div class="route-title">Alternativa B</div>
<div class="route-detail" id="routeBDetail">—</div>
</div>
<span class="route-length" id="routeBLength">—</span>
</div>
</div>
<div class="section-label">Comparação geométrica</div>
<div class="method-card">
A distância de coordenadas usa
<strong>max(|Δq|, |Δr|, |Δs|)</strong>. A reta euclidiana usa
<strong>√(Δx² + Δz²)</strong> entre os centros. O comprimento da malha
soma as arestas percorridas, que medem <strong>√3</strong> unidades neste tabuleiro.
</div>
<div class="controls">
<button type="button" class="primary" id="playButton">Pausar</button>
<button type="button" id="restartButton">Reiniciar</button>
<button type="button" id="chooseA">Escolher início</button>
<button type="button" id="chooseB">Escolher destino</button>
<button type="button" id="viewA">Centralizar A</button>
<button type="button" id="viewB">Centralizar B</button>
<button type="button" class="wide" id="homeButton">Câmera inicial</button>
</div>
<div class="selection-note" id="selectionNote">
Arraste para orbitar, use a roda para aproximar e Shift + arraste para deslocar.
</div>
</aside>
<main id="stage" aria-label="Visualização tridimensional da malha hexagonal">
<div class="stage-top">
<div class="stage-badge">
<strong>Malha procedural</strong><br>
37 células • arestas de √3 • custo uniforme
</div>
<div class="legend">
<div class="legend-item"><span class="legend-line cyan"></span>rota minimizadora A</div>
<div class="legend-item"><span class="legend-line orange"></span>alternativa minimizadora</div>
<div class="legend-item"><span class="legend-line white"></span>reta euclidiana</div>
</div>
</div>
<div class="playback">
<div class="playback-row">
<span id="playbackStatus">Preparando rota...</span>
<span id="geodesicCount">—</span>
</div>
<div class="progress"><div id="progressFill"></div></div>
</div>
</main>
<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 number2 = new Intl.NumberFormat("pt-BR", {
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07121e);
scene.fog = new THREE.Fog(0x07121e, 23, 48);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
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(42, 1, 0.1, 100);
const hemisphere = new THREE.HemisphereLight(0xbceaff, 0x182536, 1.65);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xf3fbff, 3.1);
keyLight.position.set(7, 13, 9);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -10;
keyLight.shadow.camera.right = 10;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 35;
keyLight.shadow.bias = -0.00035;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x43d9ff, 1.25);
rimLight.position.set(-8, 6, -7);
scene.add(rimLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(70, 70),
new THREE.MeshStandardMaterial({
color: 0x07111b,
roughness: 0.96,
metalness: 0.03
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.24;
floor.receiveShadow = true;
scene.add(floor);
const plinth = new THREE.Mesh(
new THREE.CylinderGeometry(7.45, 7.8, 0.22, 64),
new THREE.MeshStandardMaterial({
color: 0x0a2130,
roughness: 0.78,
metalness: 0.12
})
);
plinth.position.y = -0.12;
plinth.receiveShadow = true;
plinth.castShadow = true;
scene.add(plinth);
const boardGroup = new THREE.Group();
const routeGroup = new THREE.Group();
const markerGroup = new THREE.Group();
const actorGroup = new THREE.Group();
scene.add(boardGroup, routeGroup, markerGroup, actorGroup);
const board = new Map();
const tileMeshes = [];
const tileBaseGeometry = new THREE.CylinderGeometry(0.91, 0.91, 0.30, 6, 1, false);
tileBaseGeometry.rotateY(Math.PI / 6);
const tileCapGeometry = new THREE.CylinderGeometry(0.82, 0.85, 0.12, 6, 1, false);
tileCapGeometry.rotateY(Math.PI / 6);
const tileSideMaterial = new THREE.MeshStandardMaterial({
color: 0x173548,
roughness: 0.8,
metalness: 0.1
});
const tileBottomMaterial = new THREE.MeshStandardMaterial({
color: 0x102635,
roughness: 0.9
});
const DIRECTIONS = [
{ q: 1, r: 0, name: "E" },
{ q: 1, r: -1, name: "NE" },
{ q: 0, r: 1, name: "SE" },
{ q: -1, r: 1, name: "NW" },
{ q: -1, r: 0, name: "W" },
{ q: 0, r: -1, name: "SW" }
];
const keyOf = (q, r) => `${q},${r}`;
const cubeDistance = (a, b) => {
const dq = a.q - b.q;
const dr = a.r - b.r;
const ds = (-a.q - a.r) - (-b.q - b.r);
return Math.max(Math.abs(dq), Math.abs(dr), Math.abs(ds));
};
function axialToWorld(q, r) {
return new THREE.Vector3(
1.5 * q,
0,
Math.sqrt(3) * (r + q / 2)
);
}
function isBoardCell(q, r) {
const s = -q - r;
return Math.max(Math.abs(q), Math.abs(r), Math.abs(s)) <= 3;
}
for (let q = -3; q <= 3; q++) {
for (let r = -3; r <= 3; r++) {
if (!isBoardCell(q, r)) continue;
const center = axialToWorld(q, r);
const radial = Math.max(Math.abs(q), Math.abs(r), Math.abs(-q - r));
const lightness = 0.155 + (3 - radial) * 0.009;
const topMaterial = new THREE.MeshStandardMaterial({
color: new THREE.Color().setHSL(0.545, 0.31, lightness),
emissive: 0x071923,
emissiveIntensity: 0.12,
roughness: 0.72,
metalness: 0.08
});
const base = new THREE.Mesh(
tileBaseGeometry,
[tileSideMaterial, topMaterial, tileBottomMaterial]
);
base.position.set(center.x, 0.20, center.z);
base.castShadow = true;
base.receiveShadow = true;
base.userData.cell = { q, r };
boardGroup.add(base);
tileMeshes.push(base);
const cap = new THREE.Mesh(tileCapGeometry, topMaterial);
cap.position.set(center.x, 0.405, center.z);
cap.castShadow = true;
cap.receiveShadow = true;
cap.userData.cell = { q, r };
boardGroup.add(cap);
tileMeshes.push(cap);
board.set(keyOf(q, r), {
q,
r,
center,
base,
cap,
topMaterial
});
}
}
let startCell = { q: -2, r: 1 };
let endCell = { q: 2, r: -1 };
let routeState = {
distance: 0,
paths: [],
pathA: null,
pathB: null,
meshLength: 0,
euclideanLength: 0
};
function neighbors(cell) {
return DIRECTIONS.map(d => ({
q: cell.q + d.q,
r: cell.r + d.r,
name: d.name
})).filter(n => board.has(keyOf(n.q, n.r)));
}
function bfsDistance(source) {
const distance = new Map([[keyOf(source.q, source.r), 0]]);
const queue = [source];
for (let index = 0; index < queue.length; index++) {
const current = queue[index];
const d = distance.get(keyOf(current.q, current.r));
for (const next of neighbors(current)) {
const key = keyOf(next.q, next.r);
if (distance.has(key)) continue;
distance.set(key, d + 1);
queue.push(next);
}
}
return distance;
}
function allShortestPaths(source, target, maximum = 128) {
if (source.q === target.q && source.r === target.r) {
return [[{ q: source.q, r: source.r }]];
}
const fromSource = bfsDistance(source);
const toTarget = bfsDistance(target);
const total = fromSource.get(keyOf(target.q, target.r));
const paths = [];
function visit(cell, path) {
if (paths.length >= maximum) return;
if (cell.q === target.q && cell.r === target.r) {
paths.push(path.slice());
return;
}
if (path.length > total) return;
for (const next of neighbors(cell)) {
const key = keyOf(next.q, next.r);
const a = fromSource.get(key);
const b = toTarget.get(key);
if (a === undefined || b === undefined) continue;
if (a === path.length && a + b === total) {
path.push({ q: next.q, r: next.r });
visit(next, path);
path.pop();
}
}
}
visit(source, [{ q: source.q, r: source.r }]);
return paths;
}
function pathWorldPoints(path) {
return path.map(cell => axialToWorld(cell.q, cell.r));
}
function pathWorldLength(path) {
const points = pathWorldPoints(path);
let length = 0;
for (let i = 1; i < points.length; i++) {
length += points[i].distanceTo(points[i - 1]);
}
return length;
}
function directionLabels(path) {
const labels = [];
for (let i = 1; i < path.length; i++) {
const dq = path[i].q - path[i - 1].q;
const dr = path[i].r - path[i - 1].r;
const direction = DIRECTIONS.find(item => item.q === dq && item.r === dr);
labels.push(direction ? direction.name : "?");
}
return labels.join(" · ");
}
function clearGroup(group) {
const geometries = new Set();
const materials = new Set();
const textures = new Set();
group.traverse(object => {
if (object.geometry) geometries.add(object.geometry);
const objectMaterials = object.material
? (Array.isArray(object.material) ? object.material : [object.material])
: [];
for (const material of objectMaterials) {
materials.add(material);
if (material.map) textures.add(material.map);
}
});
group.clear();
geometries.forEach(item => item.dispose());
materials.forEach(item => item.dispose());
textures.forEach(item => item.dispose());
}
function cylinderBetween(a, b, radius, material) {
const direction = new THREE.Vector3().subVectors(b, a);
const length = direction.length();
if (length < 0.0001) return null;
const geometry = new THREE.CylinderGeometry(radius, radius, length, 8, 1, false);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.copy(a).add(b).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
mesh.castShadow = true;
return mesh;
}
function addDashedSegment(parent, a, b, radius, material, dashCount = 6) {
const direction = new THREE.Vector3().subVectors(b, a);
const total = direction.length();
const unit = direction.normalize();
const dashLength = total / dashCount;
const visibleLength = dashLength * 0.56;
for (let i = 0; i < dashCount; i++) {
const start = a.clone().addScaledVector(unit, i * dashLength + (dashLength - visibleLength) * 0.5);
const end = start.clone().addScaledVector(unit, visibleLength);
const mesh = cylinderBetween(start, end, radius, material);
if (mesh) parent.add(mesh);
}
}
function drawRoute(path, color, dashed, height) {
if (!path || path.length < 2) return;
const material = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: dashed ? 0.55 : 0.68,
transparent: true,
opacity: dashed ? 0.82 : 0.94,
roughness: 0.42,
metalness: 0.08
});
const points = pathWorldPoints(path);
for (let i = 1; i < points.length; i++) {
const a = points[i - 1].clone();
const b = points[i].clone();
a.y = height;
b.y = height;
if (dashed) {
addDashedSegment(routeGroup, a, b, 0.042, material, 7);
} else {
const segment = cylinderBetween(a, b, 0.052, material);
if (segment) routeGroup.add(segment);
}
}
const nodeGeometry = new THREE.BoxGeometry(0.18, 0.15, 0.18);
const nodeMaterial = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.72,
roughness: 0.38,
metalness: 0.08
});
for (const point of points) {
const node = new THREE.Mesh(nodeGeometry, nodeMaterial);
node.position.set(point.x, 0.555, point.z);
node.castShadow = true;
routeGroup.add(node);
}
}
function drawEuclideanLine() {
const a = axialToWorld(startCell.q, startCell.r);
const b = axialToWorld(endCell.q, endCell.r);
a.y = 0.525;
b.y = 0.525;
const material = new THREE.MeshBasicMaterial({
color: 0xdcecf5,
transparent: true,
opacity: 0.48,
depthWrite: false
});
addDashedSegment(routeGroup, a, b, 0.014, material, 30);
}
function textSprite(text, color) {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 128;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(7, 19, 30, 0.92)";
context.fillRect(10, 17, 236, 94);
context.strokeStyle = color;
context.lineWidth = 5;
context.strokeRect(10, 17, 236, 94);
context.fillStyle = color;
context.font = "bold 58px system-ui";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 128, 65);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(1.12, 0.56, 1);
sprite.renderOrder = 20;
return sprite;
}
function drawEndpointMarkers() {
clearGroup(markerGroup);
const definitions = [
{ cell: startCell, label: "A", color: 0x4ce7ff },
{ cell: endCell, label: "B", color: 0xffbd69 }
];
for (const definition of definitions) {
const point = axialToWorld(definition.cell.q, definition.cell.r);
const color = new THREE.Color(definition.color);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.31, 0.045, 10, 48),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.9
})
);
ring.rotation.x = Math.PI / 2;
ring.position.set(point.x, 0.50, point.z);
markerGroup.add(ring);
const cube = new THREE.Mesh(
new THREE.BoxGeometry(0.34, 0.34, 0.34),
new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.72,
roughness: 0.3,
metalness: 0.12
})
);
cube.position.set(point.x, 0.73, point.z);
cube.castShadow = true;
markerGroup.add(cube);
const label = textSprite(definition.label, `#${color.getHexString()}`);
label.position.set(point.x, 1.31, point.z);
markerGroup.add(label);
}
}
function refreshTileColors() {
for (const cell of board.values()) {
const isA = cell.q === startCell.q && cell.r === startCell.r;
const isB = cell.q === endCell.q && cell.r === endCell.r;
const radial = Math.max(Math.abs(cell.q), Math.abs(cell.r), Math.abs(-cell.q - cell.r));
if (isA) {
cell.topMaterial.color.setHex(0x176779);
cell.topMaterial.emissive.setHex(0x0b5969);
cell.topMaterial.emissiveIntensity = 0.44;
} else if (isB) {
cell.topMaterial.color.setHex(0x76502b);
cell.topMaterial.emissive.setHex(0x6b3d17);
cell.topMaterial.emissiveIntensity = 0.42;
} else {
cell.topMaterial.color.setHSL(0.545, 0.31, 0.155 + (3 - radial) * 0.009);
cell.topMaterial.emissive.setHex(0x071923);
cell.topMaterial.emissiveIntensity = 0.12;
}
}
}
function chooseMostDistinctPath(paths, reference) {
if (!reference || paths.length < 2) return null;
let best = null;
let bestScore = -1;
const referencePoints = pathWorldPoints(reference);
for (const candidate of paths.slice(1)) {
const points = pathWorldPoints(candidate);
let score = 0;
for (let i = 0; i < Math.min(points.length, referencePoints.length); i++) {
score += points[i].distanceTo(referencePoints[i]);
}
if (score > bestScore) {
bestScore = score;
best = candidate;
}
}
return best;
}
function updateRouteData() {
const paths = allShortestPaths(startCell, endCell);
const pathA = paths[0] || null;
const pathB = chooseMostDistinctPath(paths, pathA);
const distance = cubeDistance(startCell, endCell);
const euclideanLength = axialToWorld(startCell.q, startCell.r)
.distanceTo(axialToWorld(endCell.q, endCell.r));
routeState = {
distance,
paths,
pathA,
pathB,
meshLength: pathA ? pathWorldLength(pathA) : 0,
euclideanLength
};
clearGroup(routeGroup);
drawEuclideanLine();
drawRoute(pathA, 0x4ce7ff, false, 0.615);
drawRoute(pathB, 0xffbd69, true, 0.665);
drawEndpointMarkers();
refreshTileColors();
updateInterface();
resetActors();
elapsed = 0;
}
function updateInterface() {
const dq = endCell.q - startCell.q;
const dr = endCell.r - startCell.r;
const ds = (-endCell.q - endCell.r) - (-startCell.q - startCell.r);
document.getElementById("stepsValue").textContent = String(routeState.distance);
document.getElementById("coordValue").textContent = `${routeState.distance} hex`;
document.getElementById("euclidValue").textContent = `${number2.format(routeState.euclideanLength)} u`;
document.getElementById("meshValue").textContent = `${number2.format(routeState.meshLength)} u`;
document.getElementById("coordA").textContent = `(${startCell.q}, ${startCell.r})`;
document.getElementById("coordB").textContent = `(${endCell.q}, ${endCell.r})`;
document.getElementById("coordDelta").textContent = `(${dq}, ${dr}, ${ds})`;
document.getElementById("routeADetail").textContent = routeState.pathA
? directionLabels(routeState.pathA) || "Origem e destino coincidentes"
: "Sem rota";
document.getElementById("routeALength").textContent = routeState.pathA
? `${number2.format(routeState.meshLength)} u`
: "—";
document.getElementById("routeBDetail").textContent = routeState.pathB
? directionLabels(routeState.pathB)
: "Não existe outra rota mínima";
document.getElementById("routeBLength").textContent = routeState.pathB
? `${number2.format(routeState.meshLength)} u`
: "—";
document.getElementById("viewA").disabled = !routeState.pathA;
document.getElementById("viewB").disabled = !routeState.pathB;
document.getElementById("geodesicCount").textContent =
`${routeState.paths.length} ${routeState.paths.length === 1 ? "rota mínima" : "rotas mínimas"}`;
}
function makeActor(color) {
const group = new THREE.Group();
const cubes = [];
const materials = [];
for (let i = 0; i < 4; i++) {
const material = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: i === 0 ? 0.85 : 0.52,
transparent: true,
opacity: i === 0 ? 1 : 0.72 - i * 0.11,
roughness: 0.28,
metalness: 0.08
});
materials.push(material);
const size = i === 0 ? 0.29 : 0.20 - (i - 1) * 0.015;
const cube = new THREE.Mesh(
new THREE.BoxGeometry(size, size, size),
material
);
cube.castShadow = true;
cube.visible = false;
group.add(cube);
cubes.push(cube);
}
const halo = new THREE.Mesh(
new THREE.TorusGeometry(0.26, 0.023, 8, 36),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.7,
depthWrite: false
})
);
halo.rotation.x = Math.PI / 2;
halo.visible = false;
group.add(halo);
actorGroup.add(group);
return { group, cubes, halo };
}
let actorA = null;
let actorB = null;
function resetActors() {
clearGroup(actorGroup);
actorA = makeActor(0x4ce7ff);
actorB = makeActor(0xffbd69);
}
function samplePath(path, progress) {
if (!path || path.length === 0) return new THREE.Vector3();
if (path.length === 1) return axialToWorld(path[0].q, path[0].r);
const value = THREE.MathUtils.clamp(progress, 0, 1);
const scaled = value * (path.length - 1);
const index = Math.min(Math.floor(scaled), path.length - 2);
const local = scaled - index;
const a = axialToWorld(path[index].q, path[index].r);
const b = axialToWorld(path[index + 1].q, path[index + 1].r);
return a.lerp(b, local);
}
function setActor(actor, path, progress, visible) {
if (!actor || !path) return;
for (let i = 0; i < actor.cubes.length; i++) {
const p = progress - i * 0.052;
const cube = actor.cubes[i];
cube.visible = visible && p >= 0;
if (cube.visible) {
const point = samplePath(path, p);
cube.position.set(point.x, 0.77, point.z);
}
}
actor.halo.visible = visible && progress >= 0;
if (actor.halo.visible) {
const point = samplePath(path, progress);
actor.halo.position.set(point.x, 0.63, point.z);
}
}
const CYCLE = 8.7;
const A_DURATION = 3.55;
const B_START = 4.35;
const B_DURATION = 3.55;
let elapsed = 0;
const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
let playing = !reducedMotion;
function updatePlayback() {
const playButton = document.getElementById("playButton");
playButton.textContent = playing ? "Pausar" : "Reproduzir";
const aActive = elapsed <= A_DURATION;
const bActive = elapsed >= B_START && elapsed <= B_START + B_DURATION;
const progressA = THREE.MathUtils.clamp(elapsed / A_DURATION, 0, 1);
const progressB = THREE.MathUtils.clamp((elapsed - B_START) / B_DURATION, 0, 1);
setActor(actorA, routeState.pathA, progressA, aActive);
setActor(actorB, routeState.pathB, progressB, bActive);
document.getElementById("progressFill").style.width = `${(elapsed / CYCLE) * 100}%`;
let message;
if (!routeState.pathA || routeState.distance === 0) {
message = "Início e destino coincidem";
} else if (aActive) {
const step = Math.min(routeState.distance, Math.floor(progressA * routeState.distance) + 1);
message = `Rota A • célula ${step} de ${routeState.distance}`;
} else if (elapsed < B_START) {
message = "Alternativa B • preparando percurso";
} else if (bActive) {
const step = Math.min(routeState.distance, Math.floor(progressB * routeState.distance) + 1);
message = `Alternativa B • célula ${step} de ${routeState.distance}`;
} else {
message = "Duas rotas minimizadoras concluídas";
}
document.getElementById("playbackStatus").textContent = message;
}
const cameraState = {
target: new THREE.Vector3(0, 0.15, 0),
theta: 0.42,
phi: 0.83,
radius: 19.5
};
const cameraGoal = {
target: null,
theta: null,
phi: null,
radius: null
};
function updateCamera() {
if (cameraGoal.target) {
cameraState.target.lerp(cameraGoal.target, 0.075);
cameraState.theta = THREE.MathUtils.lerp(cameraState.theta, cameraGoal.theta, 0.075);
cameraState.phi = THREE.MathUtils.lerp(cameraState.phi, cameraGoal.phi, 0.075);
cameraState.radius = THREE.MathUtils.lerp(cameraState.radius, cameraGoal.radius, 0.075);
}
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);
}
function cancelCameraGoal() {
cameraGoal.target = null;
cameraGoal.theta = null;
cameraGoal.phi = null;
cameraGoal.radius = null;
}
function homeCamera() {
cameraGoal.target = new THREE.Vector3(0, 0.15, 0);
cameraGoal.theta = 0.42;
cameraGoal.phi = 0.83;
cameraGoal.radius = 19.5;
}
function focusPath(path) {
if (!path || path.length === 0) return;
const index = Math.floor((path.length - 1) / 2);
const point = axialToWorld(path[index].q, path[index].r);
cameraGoal.target = new THREE.Vector3(point.x, 0.2, point.z);
cameraGoal.theta = 0.08;
cameraGoal.phi = 0.94;
cameraGoal.radius = 13.2;
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let pointerDown = false;
let pointerMoved = false;
let lastX = 0;
let lastY = 0;
let downX = 0;
let downY = 0;
let hoveredCell = null;
let selectionMode = null;
function updatePointer(event) {
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;
}
function pickedCell(event) {
updatePointer(event);
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(tileMeshes, false);
return intersections.length ? intersections[0].object.userData.cell : null;
}
function setHoveredCell(cell) {
if (hoveredCell === cell) return;
if (hoveredCell && board.has(keyOf(hoveredCell.q, hoveredCell.r))) {
const material = board.get(keyOf(hoveredCell.q, hoveredCell.r)).topMaterial;
if (
!(hoveredCell.q === startCell.q && hoveredCell.r === startCell.r) &&
!(hoveredCell.q === endCell.q && hoveredCell.r === endCell.r)
) {
material.emissive.setHex(0x071923);
material.emissiveIntensity = 0.12;
}
}
hoveredCell = cell;
if (hoveredCell && board.has(keyOf(hoveredCell.q, hoveredCell.r))) {
const material = board.get(keyOf(hoveredCell.q, hoveredCell.r)).topMaterial;
if (
!(hoveredCell.q === startCell.q && hoveredCell.r === startCell.r) &&
!(hoveredCell.q === endCell.q && hoveredCell.r === endCell.r)
) {
material.emissive.setHex(0x155f70);
material.emissiveIntensity = 0.42;
}
}
}
renderer.domElement.addEventListener("pointerdown", event => {
pointerDown = true;
pointerMoved = false;
lastX = downX = event.clientX;
lastY = downY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = selectionMode ? "crosshair" : "grabbing";
});
renderer.domElement.addEventListener("pointermove", event => {
if (!pointerDown) {
if (selectionMode) {
setHoveredCell(pickedCell(event));
} else {
setHoveredCell(null);
}
return;
}
const dx = event.clientX - lastX;
const dy = event.clientY - lastY;
if (Math.hypot(event.clientX - downX, event.clientY - downY) > 4) {
pointerMoved = true;
}
lastX = event.clientX;
lastY = event.clientY;
cancelCameraGoal();
if (event.shiftKey) {
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
const right = new THREE.Vector3().crossVectors(forward, new THREE.Vector3(0, 1, 0)).normalize();
const scale = cameraState.radius * 0.00125;
cameraState.target.addScaledVector(right, -dx * scale);
cameraState.target.addScaledVector(forward, dy * scale);
} else {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(cameraState.phi - dy * 0.005, 0.32, 1.35);
}
});
renderer.domElement.addEventListener("pointerup", event => {
const wasClick = !pointerMoved && Math.hypot(event.clientX - downX, event.clientY - downY) < 6;
pointerDown = false;
renderer.domElement.style.cursor = selectionMode ? "crosshair" : "grab";
if (wasClick && selectionMode) {
const cell = pickedCell(event);
if (cell) {
if (selectionMode === "A") {
startCell = { q: cell.q, r: cell.r };
} else {
endCell = { q: cell.q, r: cell.r };
}
updateRouteData();
}
}
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerDown = false;
});
renderer.domElement.addEventListener("pointerleave", () => {
if (!pointerDown) setHoveredCell(null);
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cancelCameraGoal();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
10.5,
29
);
}, { passive: false });
const chooseAButton = document.getElementById("chooseA");
const chooseBButton = document.getElementById("chooseB");
const selectionNote = document.getElementById("selectionNote");
function setSelectionMode(mode) {
selectionMode = selectionMode === mode ? null : mode;
chooseAButton.classList.toggle("active", selectionMode === "A");
chooseBButton.classList.toggle("active", selectionMode === "B");
chooseAButton.setAttribute("aria-pressed", String(selectionMode === "A"));
chooseBButton.setAttribute("aria-pressed", String(selectionMode === "B"));
renderer.domElement.style.cursor = selectionMode ? "crosshair" : "grab";
selectionNote.textContent = selectionMode === "A"
? "Clique em uma célula do tabuleiro para definir o início A."
: selectionMode === "B"
? "Clique em uma célula do tabuleiro para definir o destino B."
: "Arraste para orbitar, use a roda para aproximar e Shift + arraste para deslocar.";
}
chooseAButton.addEventListener("click", () => setSelectionMode("A"));
chooseBButton.addEventListener("click", () => setSelectionMode("B"));
document.getElementById("playButton").addEventListener("click", () => {
playing = !playing;
updatePlayback();
});
document.getElementById("restartButton").addEventListener("click", () => {
elapsed = 0;
playing = true;
updatePlayback();
});
document.getElementById("homeButton").addEventListener("click", homeCamera);
document.getElementById("viewA").addEventListener("click", () => focusPath(routeState.pathA));
document.getElementById("viewB").addEventListener("click", () => focusPath(routeState.pathB));
function resize() {
const width = Math.max(1, stage.clientWidth);
const height = Math.max(1, stage.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
new ResizeObserver(resize).observe(stage);
resize();
updateCamera();
updateRouteData();
updatePlayback();
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
if (playing) {
elapsed = (elapsed + delta) % CYCLE;
}
updateCamera();
updatePlayback();
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```