Prompt specification
Build or customize the Three.js 3D scene "Rotatable ancestry-tree sculpture" 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: Rotatable ancestry-tree sculpture
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/rotatable-ancestry-tree-sculpture-x0945
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing phylogenetic trees. Build a rooted branching tree with fictional organisms at the tips and labeled shared ancestors; rotate branches around nodes without changing the represented relationships. Low-poly.
Working Three.js Starter (rotatable-ancestry-tree-sculpture-x0945):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Rooted — Phylogenetic Tree Explorer</title>
<style>
:root {
--paper: #f3efe5;
--ink: #26342f;
--muted: #6c746d;
--panel: rgba(248, 246, 239, 0.9);
--line: rgba(45, 58, 51, 0.15);
--accent: #d26d46;
--shadow: 0 18px 55px rgba(44, 51, 43, 0.13);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--paper);
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#scene {
position: fixed;
inset: 0;
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
outline: none;
}
#hud {
position: fixed;
inset: 0;
pointer-events: none;
}
.masthead {
position: absolute;
top: 26px;
left: 28px;
width: min(420px, calc(100vw - 390px));
text-shadow: 0 1px 12px rgba(255, 255, 255, 0.55);
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 9px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.19em;
text-transform: uppercase;
}
.eyebrow::before {
width: 22px;
height: 2px;
content: "";
background: var(--accent);
}
h1 {
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: clamp(36px, 4.4vw, 64px);
font-weight: 500;
letter-spacing: -0.045em;
line-height: 0.98;
}
.masthead p {
max-width: 360px;
margin: 13px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.panel {
position: absolute;
top: 24px;
right: 24px;
width: 326px;
max-height: calc(100vh - 48px);
padding: 20px;
overflow: auto;
pointer-events: auto;
background: var(--panel);
border: 1px solid rgba(255, 255, 255, 0.72);
border-radius: 20px;
box-shadow: var(--shadow);
backdrop-filter: blur(18px) saturate(1.1);
-webkit-backdrop-filter: blur(18px) saturate(1.1);
scrollbar-width: thin;
scrollbar-color: rgba(40, 55, 48, 0.22) transparent;
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
}
.panel-heading strong {
font-size: 12px;
letter-spacing: 0.04em;
}
.panel-heading span {
color: var(--muted);
font-size: 10px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.specimens {
display: grid;
gap: 7px;
}
.specimen {
display: grid;
grid-template-columns: 30px 1fr;
grid-template-rows: auto auto;
gap: 1px 9px;
width: 100%;
padding: 10px 11px;
text-align: left;
cursor: pointer;
background: rgba(255, 255, 255, 0.36);
border: 1px solid var(--line);
border-radius: 12px;
transition:
transform 160ms ease,
border-color 160ms ease,
background 160ms ease,
box-shadow 160ms ease;
}
.specimen:hover {
transform: translateX(-2px);
border-color: rgba(40, 55, 48, 0.28);
background: rgba(255, 255, 255, 0.65);
}
.specimen.active {
border-color: color-mix(in srgb, var(--accent) 62%, transparent);
background: rgba(255, 255, 255, 0.82);
box-shadow: 0 7px 20px rgba(43, 52, 46, 0.08);
}
.specimen-index {
grid-row: 1 / span 2;
align-self: center;
color: var(--accent);
font-family: Georgia, serif;
font-size: 18px;
}
.specimen strong {
font-size: 12px;
font-weight: 750;
}
.specimen small {
color: var(--muted);
font-size: 10px;
}
.divider {
height: 1px;
margin: 19px 0;
background: var(--line);
}
.selection-title {
min-height: 27px;
margin: 5px 0 3px;
font-family: Georgia, "Times New Roman", serif;
font-size: 24px;
line-height: 1.08;
}
.selection-meta {
min-height: 30px;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.mode-switch {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px;
margin: 14px 0 16px;
}
.mode-switch button,
.small-button,
.reset-view {
min-height: 34px;
padding: 7px 9px;
cursor: pointer;
background: rgba(255, 255, 255, 0.5);
border: 1px solid var(--line);
border-radius: 9px;
font-size: 10px;
font-weight: 750;
transition: 150ms ease;
}
.mode-switch button:hover:not(:disabled),
.small-button:hover,
.reset-view:hover {
border-color: rgba(40, 55, 48, 0.3);
background: rgba(255, 255, 255, 0.85);
}
.mode-switch button.active {
color: white;
background: var(--ink);
border-color: var(--ink);
}
button:disabled {
cursor: not-allowed;
opacity: 0.35;
}
.range-label {
display: flex;
align-items: baseline;
justify-content: space-between;
margin-bottom: 7px;
color: var(--muted);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.09em;
text-transform: uppercase;
}
#angleValue {
color: var(--ink);
font-family: Georgia, serif;
font-size: 19px;
font-weight: 500;
letter-spacing: 0;
}
input[type="range"] {
width: 100%;
margin: 3px 0 9px;
accent-color: var(--accent);
cursor: ew-resize;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr 1.35fr;
gap: 6px;
}
.reset-view {
width: 100%;
margin-top: 6px;
}
.lock-note {
display: flex;
gap: 9px;
align-items: flex-start;
margin-top: 15px;
padding: 11px;
color: var(--muted);
background: rgba(53, 68, 60, 0.055);
border-radius: 10px;
font-size: 10px;
line-height: 1.45;
}
.lock-icon {
flex: 0 0 auto;
width: 15px;
height: 15px;
margin-top: 1px;
border: 1px solid color-mix(in srgb, var(--accent) 70%, transparent);
border-radius: 50%;
box-shadow: inset 0 0 0 3px rgba(255, 255, 255, 0.6);
}
.status-bar {
position: absolute;
bottom: 22px;
left: 28px;
display: flex;
gap: 9px;
align-items: center;
max-width: calc(100vw - 400px);
padding: 9px 12px;
color: var(--muted);
background: rgba(248, 246, 239, 0.72);
border: 1px solid rgba(255, 255, 255, 0.65);
border-radius: 999px;
box-shadow: 0 8px 25px rgba(44, 51, 43, 0.08);
backdrop-filter: blur(10px);
font-size: 10px;
}
.status-dot {
width: 6px;
height: 6px;
background: var(--accent);
border-radius: 50%;
box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 18%, transparent);
}
#statusText {
overflow: hidden;
color: var(--ink);
font-weight: 750;
text-overflow: ellipsis;
white-space: nowrap;
}
.status-divider {
opacity: 0.4;
}
#hoverTip {
position: absolute;
z-index: 5;
display: none;
max-width: 220px;
padding: 7px 10px;
pointer-events: none;
color: white;
background: rgba(35, 49, 43, 0.92);
border-radius: 7px;
box-shadow: 0 7px 20px rgba(26, 35, 31, 0.2);
font-size: 10px;
line-height: 1.35;
}
.mobile-note {
display: none;
}
@media (max-width: 900px) {
.masthead {
top: 17px;
left: 18px;
width: calc(100vw - 36px);
}
.masthead p {
display: none;
}
h1 {
font-size: 38px;
}
.panel {
top: auto;
right: 12px;
bottom: 12px;
left: 12px;
width: auto;
max-height: 45vh;
padding: 15px;
border-radius: 16px;
}
.specimens {
grid-template-columns: repeat(3, 1fr);
}
.specimen {
grid-template-columns: 1fr;
grid-template-rows: auto;
gap: 2px;
padding: 8px;
}
.specimen-index,
.specimen small {
display: none;
}
.divider {
margin: 13px 0;
}
.selection-title {
font-size: 20px;
}
.status-bar {
top: 88px;
bottom: auto;
left: 18px;
max-width: calc(100vw - 36px);
}
.desktop-note {
display: none;
}
.mobile-note {
display: inline;
}
}
@media (max-width: 520px) {
.eyebrow {
font-size: 9px;
}
h1 {
font-size: 32px;
}
.status-bar {
padding: 7px 10px;
font-size: 9px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive three-dimensional phylogenetic tree"></canvas>
<div id="hud">
<header class="masthead">
<div class="eyebrow">Rooted · Cladogram archive</div>
<h1>Imagined<br />Lineages</h1>
<p>
Explore fictional evolutionary histories. Every branch remains attached to
the same ancestor while you turn each lineage in space.
</p>
</header>
<aside class="panel" aria-label="Tree controls">
<div class="panel-heading">
<strong>Specimen archive</strong>
<span>03 records</span>
</div>
<div id="specimens" class="specimens"></div>
<div class="divider"></div>
<div class="panel-heading">
<strong>Topology lab</strong>
<span>Interactive</span>
</div>
<div id="selectionName" class="selection-title">The First Frond</div>
<div id="selectionMeta" class="selection-meta"></div>
<div class="mode-switch" aria-label="Rotation target">
<button id="fanMode" type="button" class="active">Turn child fan</button>
<button id="branchMode" type="button">Turn one branch</button>
</div>
<label class="range-label" for="rotation">
<span>Rotation</span>
<output id="angleValue" for="rotation">0°</output>
</label>
<input
id="rotation"
type="range"
min="-180"
max="180"
step="1"
value="0"
aria-label="Selected branch rotation"
/>
<div class="button-row">
<button id="minusAngle" class="small-button" type="button">−15°</button>
<button id="plusAngle" class="small-button" type="button">+15°</button>
<button id="resetSelected" class="small-button" type="button">Reset selected</button>
</div>
<button id="resetTree" class="reset-view" type="button">
Reset all rotations
</button>
<button id="resetView" class="reset-view" type="button">
Reset camera view
</button>
<div class="lock-note">
<span class="lock-icon"></span>
<span>
<strong>Topology is locked.</strong> Rotation changes only the visual
arrangement. Parentage, clades, and tip membership never change.
</span>
</div>
</aside>
<div class="status-bar">
<span class="status-dot"></span>
<strong id="statusText">The Sporewake Archive</strong>
<span class="status-divider">/</span>
<span class="desktop-note">Drag to orbit · Scroll to zoom · Click a node or branch</span>
<span class="mobile-note">Drag · Pinch · Tap</span>
</div>
<div id="hoverTip"></div>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const tip = (label, color) => ({ label, color, children: [] });
const node = (label, color, children) => ({ label, color, children });
const datasets = [
{
id: "sporewake",
name: "Mycofauna",
caption: "The Sporewake Archive",
accent: "#d26d46",
root: node("The First Frond", "#40564c", [
node("Sporekin Clade", "#2f8f83", [
tip("Mossback", "#2f8f83"),
node("Veil Subclade", "#2f8f83", [
tip("Puffcap", "#2f8f83"),
tip("Lanterncap", "#2f8f83")
])
]),
node("Rootling Clade", "#c2813d", [
tip("Cinderroot", "#c2813d"),
tip("Glasswort", "#c2813d"),
tip("Mudfoot", "#c2813d")
]),
node("Crownfeel Clade", "#99618b", [
tip("Sunspore", "#99618b"),
node("Astral Crown", "#99618b", [
tip("Nightbell", "#99618b"),
tip("Dawncap", "#99618b"),
tip("Starburr", "#99618b")
])
])
])
},
{
id: "glasswind",
name: "Aeraliths",
caption: "The Glasswind Survey",
accent: "#4c789f",
root: node("Silent Genesis", "#3d4e63", [
node("Glasswing Order", "#4c789f", [
tip("Frostmoth", "#4c789f"),
node("Clearwing Pact", "#4c789f", [
tip("Windowwing", "#4c789f"),
tip("Shardbat", "#4c789f")
])
]),
node("Emberkin Clan", "#cf6d3f", [
tip("Coalfawn", "#cf6d3f"),
tip("Cinderling", "#cf6d3f"),
tip("Flareback", "#cf6d3f")
]),
node("Whisper Colony", "#8563a6", [
tip("Hushpod", "#8563a6"),
tip("Duskcoil", "#8563a6"),
node("Moonlit Kin", "#8563a6", [
tip("Mothgrace", "#8563a6"),
tip("Tidebell", "#8563a6")
])
])
])
},
{
id: "dawncode",
name: "Lithoflorans",
caption: "The Dawncode Remnant",
accent: "#b49335",
root: node("Dawn Code", "#405b52", [
node("Stonecap Radiation", "#b49335", [
tip("Pebblehorn", "#b49335"),
tip("Mosswalker", "#b49335"),
node("Boulder Kin", "#b49335", [
tip("Granitecalf", "#b49335")
])
]),
node("Skyfin Dynasty", "#438f96", [
tip("Cirrusfin", "#438f96"),
node("Cloudward School", "#438f96", [
tip("Nimbuskite", "#438f96"),
tip("Cloudback", "#438f96")
])
]),
node("Lumen Grove", "#a85d88", [
tip("Glowmoss", "#a85d88"),
tip("Prismleaf", "#a85d88"),
node("Aurora Seed", "#a85d88", [
tip("Aurorabud", "#a85d88"),
tip("Moonseed", "#a85d88")
])
])
])
}
];
const canvas = document.querySelector("#scene");
const specimensElement = document.querySelector("#specimens");
const selectionName = document.querySelector("#selectionName");
const selectionMeta = document.querySelector("#selectionMeta");
const angleValue = document.querySelector("#angleValue");
const rotationInput = document.querySelector("#rotation");
const fanMode = document.querySelector("#fanMode");
const branchMode = document.querySelector("#branchMode");
const statusText = document.querySelector("#statusText");
const hoverTip = document.querySelector("#hoverTip");
let renderer;
try {
renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
} catch (error) {
document.body.innerHTML =
"<p style='padding:2rem;font-family:system-ui'>This visualization requires WebGL.</p>";
throw error;
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color("#f3efe5");
scene.fog = new THREE.Fog("#f3efe5", 16, 31);
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraState = {
theta: 0.13,
phi: 1.46,
radius: window.innerWidth < 700 ? 15.8 : 13.7,
target: new THREE.Vector3(-0.75, -0.55, 0)
};
function updateCamera() {
const { theta, phi, radius, target } = cameraState;
camera.position.set(
target.x + radius * Math.sin(phi) * Math.sin(theta),
target.y + radius * Math.cos(phi),
target.z + radius * Math.sin(phi) * Math.cos(theta)
);
camera.lookAt(target);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xfff8e9, 0x829181, 2.25);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff2d7, 3.1);
keyLight.position.set(5, 9, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -8;
keyLight.shadow.camera.right = 8;
keyLight.shadow.camera.top = 8;
keyLight.shadow.camera.bottom = -8;
keyLight.shadow.bias = -0.0005;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0xa9c7c2, 1.35);
rimLight.position.set(-6, 3, -5);
scene.add(rimLight);
const floor = new THREE.Group();
scene.add(floor);
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0xe5dece,
roughness: 1,
flatShading: true
});
const ground = new THREE.Mesh(new THREE.CircleGeometry(6.2, 32), groundMaterial);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -4.08;
ground.receiveShadow = true;
floor.add(ground);
const pedestal = new THREE.Mesh(
new THREE.CylinderGeometry(1.25, 1.42, 0.2, 12),
new THREE.MeshStandardMaterial({
color: 0xc9c0ae,
roughness: 0.95,
flatShading: true
})
);
pedestal.position.y = -3.98;
pedestal.receiveShadow = true;
pedestal.castShadow = true;
floor.add(pedestal);
const ringMaterial = new THREE.MeshBasicMaterial({
color: 0x9c9e8d,
transparent: true,
opacity: 0.18,
side: THREE.DoubleSide
});
const floorRing = new THREE.Mesh(new THREE.RingGeometry(1.48, 1.51, 48), ringMaterial);
floorRing.rotation.x = -Math.PI / 2;
floorRing.position.y = -3.865;
floor.add(floorRing);
const rockMaterial = new THREE.MeshStandardMaterial({
color: 0xb7b19f,
roughness: 1,
flatShading: true
});
for (let i = 0; i < 11; i++) {
const angle = (i / 11) * Math.PI * 2 + 0.2;
const radius = 1.65 + (i % 3) * 0.18;
const rock = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.08 + (i % 4) * 0.018, 0),
rockMaterial
);
rock.position.set(
Math.cos(angle) * radius,
-3.88 + (i % 2) * 0.025,
Math.sin(angle) * radius
);
rock.scale.set(1.4, 0.65 + (i % 3) * 0.12, 1);
rock.rotation.set(i * 0.3, i * 0.7, i * 0.19);
rock.castShadow = true;
floor.add(rock);
}
const treeHolder = new THREE.Group();
treeHolder.position.set(-0.75, -2.65, 0);
treeHolder.rotation.y = -0.045;
scene.add(treeHolder);
const halo = new THREE.Mesh(
new THREE.TorusGeometry(0.25, 0.022, 6, 36),
new THREE.MeshBasicMaterial({
color: 0xd26d46,
transparent: true,
opacity: 0.86,
depthTest: false
})
);
halo.renderOrder = 20;
scene.add(halo);
let currentDataset = datasets[0];
let treeRoot = null;
let rootNode = null;
let selectedNode = null;
let selectedBranch = null;
let selectionType = "node";
let pickables = [];
let branchRecords = [];
let nodeRecords = [];
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const temporaryVector = new THREE.Vector3();
function roundedRect(context, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
context.beginPath();
context.moveTo(x + r, y);
context.lineTo(x + width - r, y);
context.quadraticCurveTo(x + width, y, x + width, y + r);
context.lineTo(x + width, y + height - r);
context.quadraticCurveTo(
x + width,
y + height,
x + width - r,
y + height
);
context.lineTo(x + r, y + height);
context.quadraticCurveTo(x, y + height, x, y + height - r);
context.lineTo(x, y + r);
context.quadraticCurveTo(x, y, x + r, y);
context.closePath();
}
function createLabel(text, kind, color) {
const dpr = 2;
const canvasPadding = 18;
const fontSize = kind === "tip" ? 25 : 23;
const font = `${kind === "tip" ? 700 : 600} ${fontSize}px system-ui, sans-serif`;
const measureCanvas = document.createElement("canvas");
const measureContext = measureCanvas.getContext("2d");
measureContext.font = font;
const textWidth = measureContext.measureText(text).width;
const width = Math.ceil(textWidth + canvasPadding * 2 + (kind === "tip" ? 14 : 0));
const height = 60;
const labelCanvas = document.createElement("canvas");
labelCanvas.width = width * dpr;
labelCanvas.height = height * dpr;
const context = labelCanvas.getContext("2d");
context.scale(dpr, dpr);
context.font = font;
context.textBaseline = "middle";
roundedRect(context, 1, 1, width - 2, height - 2, 13);
if (kind === "tip") {
context.fillStyle = "rgba(250, 248, 241, 0.94)";
context.fill();
context.strokeStyle = color;
context.lineWidth = 1.5;
context.stroke();
context.beginPath();
context.fillStyle = color;
context.arc(16, height / 2, 4.5, 0, Math.PI * 2);
context.fill();
} else {
context.fillStyle = "rgba(242, 239, 229, 0.82)";
context.fill();
context.strokeStyle = "rgba(52, 66, 59, 0.16)";
context.lineWidth = 1;
context.stroke();
}
context.fillStyle = kind === "tip" ? "#29372f" : "#526058";
context.fillText(text, kind === "tip" ? 28 : canvasPadding, height / 2 + 1);
const texture = new THREE.CanvasTexture(labelCanvas);
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);
const desiredWidth =
kind === "tip"
? Math.min(2.65, Math.max(1.35, 0.8 + text.length * 0.065))
: Math.min(2.1, Math.max(1.25, 0.75 + text.length * 0.05));
sprite.scale.set(desiredWidth, desiredWidth * (height / width), 1);
sprite.renderOrder = 10;
return sprite;
}
function addCylinderBetween(group, start, end, radiusStart, radiusEnd, material) {
const direction = new THREE.Vector3().subVectors(end, start);
const length = direction.length();
const midpoint = new THREE.Vector3()
.addVectors(start, end)
.multiplyScalar(0.5);
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radiusEnd, radiusStart, length, 6, 1, false),
material
);
mesh.position.copy(midpoint);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
mesh.castShadow = true;
group.add(mesh);
return mesh;
}
function addRootBase(group) {
const woodMaterial = new THREE.MeshStandardMaterial({
color: 0x695546,
roughness: 0.95,
flatShading: true
});
addCylinderBetween(
group,
new THREE.Vector3(0, -1.32, 0),
new THREE.Vector3(0, 0, 0),
0.15,
0.105,
woodMaterial
);
const rootEnds = [
new THREE.Vector3(-0.72, -1.34, 0.12),
new THREE.Vector3(0.66, -1.35, -0.12),
new THREE.Vector3(0.18, -1.37, 0.58),
new THREE.Vector3(-0.2, -1.36, -0.55)
];
rootEnds.forEach((end, index) => {
addCylinderBetween(
group,
new THREE.Vector3(0, -0.48 - index * 0.035, 0),
end,
0.065,
0.018,
woodMaterial
);
});
}
function branchLength(depth) {
if (depth === 0) return 1.8;
if (depth === 1) return 1.3;
return 1.0;
}
function childAngles(count, depth) {
if (count === 1) return [0];
const spread = depth === 0 ? 1.82 : depth === 1 ? 1.28 : 1.0;
return Array.from({ length: count }, (_, index) => {
return -spread / 2 + (index * spread) / (count - 1);
});
}
function descendantCount(record) {
return record.data.children.reduce(
(sum, child) =>
sum +
1 +
child.children.reduce(
(childSum, grandchild) =>
childSum +
1 +
grandchild.children.reduce(
(greatSum, greatGrandchild) =>
greatSum +
1 +
greatGrandchild.children.length,
0
),
0
),
0
);
}
function createNode(data, group, incomingBranch, depth, inheritedColor) {
const color = data.color || inheritedColor || "#60746a";
const isTip = data.children.length === 0;
const record = {
data,
group,
depth,
isTip,
incomingBranch,
outgoingBranches: [],
rotationOffset: 0,
markerMaterial: null
};
const markerGeometry = isTip
? new THREE.OctahedronGeometry(0.18, 0)
: depth === 0
? new THREE.DodecahedronGeometry(0.18, 0)
: new THREE.IcosahedronGeometry(0.135, 0);
record.markerMaterial = new THREE.MeshStandardMaterial({
color,
roughness: 0.7,
metalness: 0.02,
flatShading: true,
emissive: 0x000000
});
const marker = new THREE.Mesh(markerGeometry, record.markerMaterial);
marker.castShadow = true;
marker.receiveShadow = true;
marker.userData.pickType = "node";
marker.userData.node = record;
group.add(marker);
pickables.push(marker);
record.marker = marker;
const label = createLabel(data.label, isTip ? "tip" : "ancestor", color);
label.position.set(
isTip ? 0 : -0.08,
isTip ? -0.34 : 0.26,
0.09
);
group.add(label);
const angles = childAngles(data.children.length, depth);
data.children.forEach((childData, index) => {
const length = branchLength(depth);
const baseAngle = angles[index];
const baseTilt = depth === 0 ? 0.025 : index % 2 === 0 ? 0.085 : -0.085;
const pivot = new THREE.Group();
pivot.rotation.set(baseTilt, 0, baseAngle);
group.add(pivot);
const branchColor = childData.color || color;
const material = new THREE.MeshStandardMaterial({
color: branchColor,
roughness: 0.78,
metalness: 0.01,
flatShading: true,
emissive: 0x000000,
emissiveIntensity: 0
});
const baseRadius = depth === 0 ? 0.115 : depth === 1 ? 0.085 : 0.062;
const tipRadius = depth === 0 ? 0.082 : depth === 1 ? 0.06 : 0.037;
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(tipRadius, baseRadius, length, 6, 1, false),
material
);
mesh.position.y = length / 2;
mesh.castShadow = true;
mesh.receiveShadow = true;
pivot.add(mesh);
const childGroup = new THREE.Group();
childGroup.position.y = length;
pivot.add(childGroup);
const branch = {
pivot,
mesh,
material,
baseAngle,
userRotation: 0,
parentNode: record,
childNode: null
};
mesh.userData.pickType = "branch";
mesh.userData.branch = branch;
pickables.push(mesh);
branchRecords.push(branch);
branch.childNode = createNode(
childData,
childGroup,
branch,
depth + 1,
branchColor
);
record.outgoingBranches.push(branch);
});
nodeRecords.push(record);
return record;
}
function disposeTree() {
if (!treeRoot) return;
treeRoot.traverse((object) => {
if (object.geometry) object.geometry.dispose();
const materials = object.material
? Array.isArray(object.material)
? object.material
: [object.material]
: [];
materials.forEach((material) => {
if (material.map) material.map.dispose();
material.dispose();
});
});
treeHolder.remove(treeRoot);
treeRoot = null;
}
function applyAllRotations() {
branchRecords.forEach((branch) => {
const parentOffset = branch.parentNode
? branch.parentNode.rotationOffset
: 0;
branch.pivot.rotation.z =
branch.baseAngle + parentOffset + branch.userRotation;
});
}
function buildTree(dataset) {
disposeTree();
currentDataset = dataset;
branchRecords = [];
nodeRecords = [];
pickables = [];
document.documentElement.style.setProperty("--accent", dataset.accent);
halo.material.color.set(dataset.accent);
statusText.textContent = dataset.caption;
treeRoot = new THREE.Group();
treeHolder.add(treeRoot);
addRootBase(treeRoot);
rootNode = createNode(dataset.root, treeRoot, null, 0, dataset.root.color);
applyAllRotations();
selectedNode = rootNode;
selectedBranch = rootNode.outgoingBranches[0] || null;
setSelection("node", rootNode);
}
function clearHighlights() {
branchRecords.forEach((branch) => {
branch.material.emissive.set(0x000000);
branch.material.emissiveIntensity = 0;
});
nodeRecords.forEach((record) => {
record.markerMaterial.emissive.set(0x000000);
record.markerMaterial.emissiveIntensity = 0;
});
}
function formatAngle(degrees) {
const rounded = Math.round(degrees);
return `${rounded > 0 ? "+" : ""}${rounded}°`;
}
function currentAngle() {
if (selectionType === "branch" && selectedBranch) {
return THREE.MathUtils.radToDeg(selectedBranch.userRotation);
}
if (selectionType === "node" && selectedNode) {
return THREE.MathUtils.radToDeg(selectedNode.rotationOffset);
}
return 0;
}
function updateInspector() {
const degrees = currentAngle();
rotationInput.value = String(Math.round(degrees));
angleValue.textContent = formatAngle(degrees);
fanMode.classList.toggle("active", selectionType === "node");
branchMode.classList.toggle("active", selectionType === "branch");
fanMode.disabled = !selectedNode || selectedNode.outgoingBranches.length === 0;
branchMode.disabled = !selectedBranch;
if (selectionType === "branch" && selectedBranch) {
selectionName.textContent = selectedBranch.childNode.data.label;
selectionMeta.textContent =
`Branch from ${selectedBranch.parentNode.data.label} · ` +
`${descendantCount(selectedBranch.childNode)} descendants`;
} else if (selectedNode) {
selectionName.textContent = selectedNode.data.label;
selectionMeta.textContent = selectedNode.isTip
? `Terminal organism · ${selectedNode.data.label} has no descendants`
: `Shared ancestor · ${descendantCount(selectedNode)} descendants · ` +
`${selectedNode.outgoingBranches.length} direct branches`;
}
}
function setSelection(type, target) {
clearHighlights();
selectionType = type;
if (type === "branch") {
selectedBranch = target;
selectedNode = target.childNode;
target.material.emissive.set(currentDataset.accent);
target.material.emissiveIntensity = 0.34;
if (target.childNode) {
target.childNode.markerMaterial.emissive.set(currentDataset.accent);
target.childNode.markerMaterial.emissiveIntensity = 0.12;
}
} else {
selectedNode = target;
selectedBranch =
target.incomingBranch || target.outgoingBranches[0] || null;
target.markerMaterial.emissive.set(currentDataset.accent);
target.markerMaterial.emissiveIntensity = 0.28;
}
updateInspector();
}
function setAngle(degrees) {
const clamped = THREE.MathUtils.clamp(degrees, -180, 180);
if (selectionType === "branch" && selectedBranch) {
selectedBranch.userRotation = THREE.MathUtils.degToRad(clamped);
} else if (selectionType === "node" && selectedNode) {
selectedNode.rotationOffset = THREE.MathUtils.degToRad(clamped);
}
applyAllRotations();
updateInspector();
}
rotationInput.addEventListener("input", (event) => {
setAngle(Number(event.target.value));
});
document.querySelector("#minusAngle").addEventListener("click", () => {
setAngle(currentAngle() - 15);
});
document.querySelector("#plusAngle").addEventListener("click", () => {
setAngle(currentAngle() + 15);
});
document.querySelector("#resetSelected").addEventListener("click", () => {
setAngle(0);
});
document.querySelector("#resetTree").addEventListener("click", () => {
nodeRecords.forEach((record) => {
record.rotationOffset = 0;
});
branchRecords.forEach((branch) => {
branch.userRotation = 0;
});
applyAllRotations();
updateInspector();
});
fanMode.addEventListener("click", () => {
if (selectedNode && selectedNode.outgoingBranches.length) {
setSelection("node", selectedNode);
}
});
branchMode.addEventListener("click", () => {
if (!selectedBranch && selectedNode) {
selectedBranch =
selectedNode.incomingBranch || selectedNode.outgoingBranches[0];
}
if (selectedBranch) {
setSelection("branch", selectedBranch);
}
});
function resetCamera() {
cameraState.theta = 0.13;
cameraState.phi = 1.46;
cameraState.radius = window.innerWidth < 700 ? 15.8 : 13.7;
cameraState.target.set(
window.innerWidth > 900 ? -0.75 : 0,
-0.55,
0
);
updateCamera();
}
document.querySelector("#resetView").addEventListener("click", resetCamera);
function buildSpecimenButtons() {
specimensElement.innerHTML = datasets
.map(
(dataset, index) => `
<button
class="specimen ${index === 0 ? "active" : ""}"
type="button"
data-index="${index}"
>
<span class="specimen-index">${String(index + 1).padStart(2, "0")}</span>
<strong>${dataset.name}</strong>
<small>${dataset.caption}</small>
</button>
`
)
.join("");
specimensElement.querySelectorAll(".specimen").forEach((button) => {
button.addEventListener("click", () => {
specimensElement.querySelectorAll(".specimen").forEach((entry) => {
entry.classList.remove("active");
});
button.classList.add("active");
buildTree(datasets[Number(button.dataset.index)]);
});
});
}
function pickAt(clientX, clientY) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(pickables, false);
return intersections.length ? intersections[0].object : null;
}
let pointerDown = false;
let pointerMoved = false;
let previousX = 0;
let previousY = 0;
let activePointerId = null;
canvas.addEventListener("pointerdown", (event) => {
pointerDown = true;
pointerMoved = false;
previousX = event.clientX;
previousY = event.clientY;
activePointerId = event.pointerId;
canvas.setPointerCapture(event.pointerId);
canvas.style.cursor = "grabbing";
hoverTip.style.display = "none";
});
canvas.addEventListener("pointermove", (event) => {
if (pointerDown) {
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
if (Math.abs(dx) + Math.abs(dy) > 2) pointerMoved = true;
cameraState.theta -= dx * 0.0055;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.0045,
0.55,
2.35
);
previousX = event.clientX;
previousY = event.clientY;
updateCamera();
return;
}
const hit = pickAt(event.clientX, event.clientY);
if (hit) {
const label =
hit.userData.pickType === "branch"
? hit.userData.branch.childNode.data.label
: hit.userData.node.data.label;
hoverTip.textContent = label;
hoverTip.style.display = "block";
const tooltipWidth = hoverTip.offsetWidth || 120;
const tooltipHeight = hoverTip.offsetHeight || 30;
const x = Math.min(
event.clientX + 13,
window.innerWidth - tooltipWidth - 10
);
const y = Math.min(
event.clientY + 13,
window.innerHeight - tooltipHeight - 10
);
hoverTip.style.left = `${x}px`;
hoverTip.style.top = `${y}px`;
canvas.style.cursor = "pointer";
} else {
hoverTip.style.display = "none";
canvas.style.cursor = "grab";
}
});
canvas.addEventListener("pointerup", (event) => {
const wasClick = !pointerMoved;
pointerDown = false;
canvas.style.cursor = "grab";
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
activePointerId = null;
if (!wasClick) return;
const hit = pickAt(event.clientX, event.clientY);
if (!hit) return;
if (hit.userData.pickType === "branch") {
setSelection("branch", hit.userData.branch);
} else if (hit.userData.pickType === "node") {
setSelection("node", hit.userData.node);
}
});
canvas.addEventListener("pointercancel", () => {
pointerDown = false;
pointerMoved = false;
activePointerId = null;
canvas.style.cursor = "grab";
});
canvas.addEventListener("pointerleave", () => {
if (!pointerDown) {
hoverTip.style.display = "none";
canvas.style.cursor = "grab";
}
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
8.5,
23
);
updateCamera();
},
{ passive: false }
);
window.addEventListener("keydown", (event) => {
if (event.target instanceof HTMLInputElement) return;
if (event.key === "ArrowLeft") {
event.preventDefault();
setAngle(currentAngle() - 5);
} else if (event.key === "ArrowRight") {
event.preventDefault();
setAngle(currentAngle() + 5);
} else if (event.key === "0") {
setAngle(0);
}
});
function onResize() {
const mobile = window.innerWidth <= 900;
const layoutShift = mobile ? 0 : -0.75;
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
treeHolder.position.x = layoutShift;
cameraState.target.x = layoutShift;
updateCamera();
}
window.addEventListener("resize", onResize);
buildSpecimenButtons();
buildTree(currentDataset);
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
let anchor = null;
if (selectionType === "node" && selectedNode) {
anchor = selectedNode.group;
} else if (selectionType === "branch" && selectedBranch) {
anchor = selectedBranch.parentNode.group;
}
if (anchor) {
anchor.getWorldPosition(temporaryVector);
halo.position.copy(temporaryVector);
halo.quaternion.copy(camera.quaternion);
const pulse = 1 + Math.sin(elapsed * 3.2) * 0.045;
halo.scale.setScalar(pulse);
} else {
halo.visible = false;
}
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```