Prompt specification
Build or customize the Three.js 3D scene "Trellis shape growth puzzle" 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: Trellis shape growth puzzle
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/trellis-shape-growth-puzzle-x1116
Scene Description Prompt:
Create a standalone low-poly scene in one HTML file using Three.js from cdnjs. Create modular trellis pieces and a scripted vine-growth rule; users guide growth toward target regions while preserving an open passage beneath the resulting canopy.
Working Three.js Starter (trellis-shape-growth-puzzle-x1116):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Canopy — Guided Vine Growth</title>
<style>
:root {
color-scheme: light;
--ink: #24352d;
--muted: #607268;
--panel: rgba(248, 250, 244, 0.91);
--line: rgba(49, 78, 62, 0.16);
--green: #3d7049;
--green-dark: #285238;
--cyan: #56a7a4;
--shadow: 0 18px 50px rgba(37, 57, 47, 0.17);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dce8df;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
#panel {
position: fixed;
top: 18px;
left: 18px;
width: min(326px, calc(100vw - 36px));
max-height: calc(100vh - 36px);
overflow: auto;
padding: 20px;
border: 1px solid rgba(255, 255, 255, 0.72);
border-radius: 20px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
z-index: 10;
scrollbar-width: thin;
}
.eyebrow {
margin-bottom: 5px;
color: var(--green);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.17em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 29px;
line-height: 1.03;
letter-spacing: -0.045em;
}
.intro {
margin: 10px 0 18px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin: 16px 0 9px;
color: #3d5045;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.section-title span:last-child {
color: #87958c;
font-weight: 600;
letter-spacing: 0;
text-transform: none;
}
.targets {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
button {
font: inherit;
}
.target {
position: relative;
min-height: 48px;
padding: 10px 10px 10px 35px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.58);
color: #354a3e;
cursor: pointer;
text-align: left;
transition: 160ms ease;
}
.target:hover {
transform: translateY(-1px);
border-color: rgba(61, 112, 73, 0.38);
background: rgba(255, 255, 255, 0.9);
}
.target::before {
content: "";
position: absolute;
top: 15px;
left: 13px;
width: 10px;
height: 10px;
border-radius: 50%;
background: var(--dot);
box-shadow: 0 0 0 4px color-mix(in srgb, var(--dot) 18%, transparent);
}
.target.active {
border-color: var(--green);
background: #e9f1e7;
box-shadow: inset 0 0 0 1px rgba(61, 112, 73, 0.22);
}
.target strong {
display: block;
font-size: 12px;
line-height: 1.2;
}
.target small {
display: block;
margin-top: 3px;
color: #78877e;
font-size: 10px;
}
.route {
margin-top: 10px;
padding: 10px 12px;
border-radius: 11px;
background: rgba(86, 167, 164, 0.1);
color: #426c69;
font-size: 11px;
line-height: 1.45;
}
.control {
margin-top: 13px;
}
.control label {
display: flex;
justify-content: space-between;
margin-bottom: 7px;
color: #4e6256;
font-size: 11px;
font-weight: 650;
}
input[type="range"] {
width: 100%;
accent-color: var(--green);
cursor: pointer;
}
.actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 16px;
}
.action {
min-height: 42px;
padding: 9px 12px;
border: 0;
border-radius: 11px;
font-size: 12px;
font-weight: 750;
cursor: pointer;
transition: 150ms ease;
}
.action:hover {
transform: translateY(-1px);
}
.action.primary {
background: var(--green-dark);
color: white;
}
.action.secondary {
border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.7);
color: #43584b;
}
.rule {
margin-top: 16px;
padding-top: 14px;
border-top: 1px solid var(--line);
color: #718078;
font-size: 10px;
line-height: 1.55;
}
.rule strong {
color: #496052;
}
#hint {
position: fixed;
right: 18px;
bottom: 18px;
padding: 10px 13px;
border: 1px solid rgba(255, 255, 255, 0.68);
border-radius: 12px;
background: rgba(248, 250, 244, 0.78);
color: #52675a;
box-shadow: 0 8px 24px rgba(43, 63, 52, 0.11);
backdrop-filter: blur(10px);
font-size: 11px;
pointer-events: none;
z-index: 8;
}
#status {
position: fixed;
top: 18px;
right: 18px;
display: flex;
align-items: center;
gap: 8px;
padding: 9px 12px;
border: 1px solid rgba(255, 255, 255, 0.68);
border-radius: 999px;
background: rgba(248, 250, 244, 0.82);
color: #4e6657;
box-shadow: 0 8px 24px rgba(43, 63, 52, 0.1);
backdrop-filter: blur(10px);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.05em;
pointer-events: none;
z-index: 8;
}
#status::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: #5ca66a;
box-shadow: 0 0 0 4px rgba(92, 166, 106, 0.14);
}
@media (max-width: 720px) {
#panel {
top: 10px;
left: 10px;
width: min(300px, calc(100vw - 20px));
max-height: 54vh;
padding: 16px;
}
h1 {
font-size: 24px;
}
.intro {
margin-bottom: 12px;
}
#hint {
right: 10px;
bottom: 10px;
max-width: calc(100vw - 20px);
}
#status {
display: none;
}
}
</style>
</head>
<body>
<aside id="panel">
<div class="eyebrow">Interactive Trellis Study</div>
<h1>Canopy</h1>
<p class="intro">
Guide new vine shoots toward a glowing target region. Growth follows the
modular trellis while automatically avoiding the protected central aisle.
</p>
<div class="section-title">
<span>Target region</span>
<span>click a beacon too</span>
</div>
<div class="targets">
<button class="target active" data-target="crown" style="--dot:#df8b65">
<strong>Crown</strong>
<small>Upper center</small>
</button>
<button class="target" data-target="left" style="--dot:#7ca663">
<strong>Left shoulder</strong>
<small>West trellis</small>
</button>
<button class="target" data-target="right" style="--dot:#bd79a4">
<strong>Right shoulder</strong>
<small>East trellis</small>
</button>
<button class="target" data-target="far" style="--dot:#6f9fc5">
<strong>Far crown</strong>
<small>End module</small>
</button>
</div>
<div class="route" id="routeText">Preparing the growth graph…</div>
<div class="control">
<label for="speed">
Growth rate
<span id="speedValue">1.0×</span>
</label>
<input id="speed" type="range" min="0.5" max="2.5" step="0.1" value="1" />
</div>
<div class="control">
<label for="clearance">
Protected clearance
<span id="clearanceValue">2.25 m</span>
</label>
<input
id="clearance"
type="range"
min="2"
max="3.2"
step="0.05"
value="2.25"
/>
</div>
<div class="actions">
<button id="toggleGrowth" class="action primary">Pause growth</button>
<button id="resetGrowth" class="action secondary">Reset vines</button>
</div>
<div class="rule">
<strong>Growth rule:</strong> each shoot samples neighboring supports,
favors nodes with the shortest route to the active target, prefers
upward travel, and rejects central support nodes below the selected
clearance. The cyan volume marks the passage to remain open.
</div>
</aside>
<div id="status">LIVE GROWTH</div>
<div id="hint">Drag to orbit · Shift-drag to pan · Scroll to zoom · Click a beacon to redirect</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Renderer, scene, camera, and light
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdce8df);
scene.fog = new THREE.Fog(0xdce8df, 17, 36);
const camera = new THREE.PerspectiveCamera(
42,
innerWidth / innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
document.body.prepend(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xeaf6ef, 0x6e7259, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff0cf, 3.3);
sun.position.set(7, 12, 6);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -12;
sun.shadow.camera.right = 12;
sun.shadow.camera.top = 12;
sun.shadow.camera.bottom = -12;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 30;
sun.shadow.bias = -0.00035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x9bc8c2, 0.65);
fill.position.set(-8, 5, -7);
scene.add(fill);
const world = new THREE.Group();
const trellisGroup = new THREE.Group();
const vineGroup = new THREE.Group();
const markerGroup = new THREE.Group();
scene.add(world, trellisGroup, vineGroup, markerGroup);
// -------------------------------------------------------------------------
// Shared geometry and materials
// -------------------------------------------------------------------------
const unitBox = new THREE.BoxGeometry(1, 1, 1);
const unitCylinder = new THREE.CylinderGeometry(1, 1, 1, 5);
const leafGeometry = new THREE.CircleGeometry(1, 5);
const bloomGeometry = new THREE.IcosahedronGeometry(0.09, 0);
const materials = {
grass: new THREE.MeshStandardMaterial({
color: 0x91aa78,
roughness: 1,
flatShading: true
}),
path: new THREE.MeshStandardMaterial({
color: 0xd8c7a8,
roughness: 0.94,
flatShading: true
}),
pathDark: new THREE.MeshStandardMaterial({
color: 0xc7b18e,
roughness: 1,
flatShading: true
}),
wood: new THREE.MeshStandardMaterial({
color: 0x876142,
roughness: 0.84,
flatShading: true
}),
woodLight: new THREE.MeshStandardMaterial({
color: 0xa37a50,
roughness: 0.86,
flatShading: true
}),
woodDark: new THREE.MeshStandardMaterial({
color: 0x684a34,
roughness: 0.9,
flatShading: true
}),
soil: new THREE.MeshStandardMaterial({
color: 0x554436,
roughness: 1,
flatShading: true
}),
planter: new THREE.MeshStandardMaterial({
color: 0xb96e4f,
roughness: 0.88,
flatShading: true
}),
trunk: new THREE.MeshStandardMaterial({
color: 0x73543e,
roughness: 1,
flatShading: true
}),
foliage: new THREE.MeshStandardMaterial({
color: 0x6f9460,
roughness: 1,
flatShading: true
}),
foliageLight: new THREE.MeshStandardMaterial({
color: 0x8ca96b,
roughness: 1,
flatShading: true
}),
stone: new THREE.MeshStandardMaterial({
color: 0xa7aa92,
roughness: 1,
flatShading: true
}),
vine: new THREE.MeshStandardMaterial({
color: 0x365c38,
roughness: 0.88,
flatShading: true
}),
leaf: new THREE.MeshStandardMaterial({
color: 0x669553,
roughness: 0.92,
side: THREE.DoubleSide,
flatShading: true
}),
leafLight: new THREE.MeshStandardMaterial({
color: 0x86ad61,
roughness: 0.92,
side: THREE.DoubleSide,
flatShading: true
}),
blossom: new THREE.MeshStandardMaterial({
color: 0xe4a36e,
roughness: 0.72,
flatShading: true
})
};
function box(parent, width, height, depth, material, x, y, z) {
const mesh = new THREE.Mesh(unitBox, material);
mesh.scale.set(width, height, depth);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function beamBetween(parent, a, b, width, depth, material) {
const start = new THREE.Vector3(...a);
const end = new THREE.Vector3(...b);
const direction = new THREE.Vector3().subVectors(end, start);
const length = direction.length();
const mesh = new THREE.Mesh(unitBox, material);
mesh.scale.set(width, length, depth);
mesh.position.copy(start).add(end).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// -------------------------------------------------------------------------
// Ground, walkway, protected passage, and landscape
// -------------------------------------------------------------------------
box(world, 30, 0.2, 30, materials.grass, 0, -0.13, 0);
box(world, 3.65, 0.09, 12.8, materials.path, 0, 0.035, 0);
for (let z = -5.7; z <= 5.7; z += 0.9) {
const paver = box(
world,
3.45,
0.045,
0.72,
Math.random() > 0.55 ? materials.pathDark : materials.path,
(Math.random() - 0.5) * 0.08,
0.095,
z
);
paver.rotation.y = (Math.random() - 0.5) * 0.025;
}
const corridorMaterial = new THREE.MeshBasicMaterial({
color: 0x65bfba,
transparent: true,
opacity: 0.055,
depthWrite: false,
side: THREE.DoubleSide
});
const corridor = new THREE.Mesh(unitBox, corridorMaterial);
corridor.position.set(0, 1.125, 0);
corridor.scale.set(3.8, 2.25, 11.5);
corridor.renderOrder = 2;
scene.add(corridor);
const corridorEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(unitBox),
new THREE.LineBasicMaterial({
color: 0x68bdb7,
transparent: true,
opacity: 0.28
})
);
corridorEdges.position.copy(corridor.position);
corridorEdges.scale.copy(corridor.scale);
scene.add(corridorEdges);
const patchGeometry = new THREE.CircleGeometry(1, 7);
for (let i = 0; i < 28; i++) {
const patch = new THREE.Mesh(
patchGeometry,
i % 3 === 0 ? materials.foliageLight : materials.foliage
);
const angle = Math.random() * Math.PI * 2;
const radius = 7 + Math.random() * 6;
patch.position.set(
Math.cos(angle) * radius,
-0.018,
Math.sin(angle) * radius
);
patch.rotation.x = -Math.PI / 2;
patch.rotation.z = Math.random() * Math.PI;
patch.scale.set(0.5 + Math.random(), 0.3 + Math.random() * 0.7, 1);
patch.receiveShadow = true;
world.add(patch);
}
function addTree(x, z, scale) {
const tree = new THREE.Group();
tree.position.set(x, 0, z);
tree.scale.setScalar(scale);
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.15, 0.23, 1.8, 6),
materials.trunk
);
trunk.position.y = 0.9;
trunk.castShadow = true;
tree.add(trunk);
const crown = new THREE.Mesh(
new THREE.IcosahedronGeometry(1, 0),
materials.foliage
);
crown.position.y = 2.25;
crown.scale.set(1.05, 1.2, 1);
crown.rotation.set(Math.random(), Math.random(), Math.random());
crown.castShadow = true;
tree.add(crown);
const crown2 = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.72, 0),
materials.foliageLight
);
crown2.position.set(0.48, 2.5, -0.12);
crown2.castShadow = true;
tree.add(crown2);
world.add(tree);
}
[
[-9, -8, 1.25],
[-11, 2, 1.05],
[-8, 9, 1.35],
[9, -9, 1.15],
[11, 1, 1.4],
[8, 10, 1.15],
[-5, -12, 1.2],
[4, -13, 1.35]
].forEach((args) => addTree(...args));
for (let i = 0; i < 25; i++) {
const rock = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.12 + Math.random() * 0.17, 0),
materials.stone
);
rock.position.set(
(Math.random() > 0.5 ? 1 : -1) * (2.4 + Math.random() * 7),
0.03,
(Math.random() - 0.5) * 20
);
rock.rotation.set(Math.random(), Math.random(), Math.random());
rock.castShadow = true;
world.add(rock);
}
// -------------------------------------------------------------------------
// Modular trellis
// -------------------------------------------------------------------------
const moduleZ = [-4.5, -1.5, 1.5, 4.5];
const halfWidth = 4.15;
const levelY = [0.62, 1.52, 2.82, 3.78, 4.65];
moduleZ.forEach((z, index) => {
const module = new THREE.Group();
module.position.z = z;
trellisGroup.add(module);
const wood = index % 2 === 0 ? materials.wood : materials.woodLight;
// Uprights.
box(module, 0.2, 4.35, 0.2, wood, -halfWidth, 2.4, 0);
box(module, 0.2, 4.35, 0.2, wood, halfWidth, 2.4, 0);
// Upper beam.
box(module, 8.5, 0.2, 0.2, wood, 0, 4.65, 0);
// Lower crossbeam and center upright.
box(module, 8.5, 0.16, 0.16, materials.woodDark, 0, 2.82, 0);
box(module, 0.12, 1.83, 0.12, materials.woodDark, 0, 3.735, 0);
// Knee braces.
beamBetween(
module,
[-halfWidth, 3.42, 0],
[-3.02, 4.58, 0],
0.14,
0.14,
materials.woodDark
);
beamBetween(
module,
[halfWidth, 3.42, 0],
[3.02, 4.58, 0],
0.14,
0.14,
materials.woodDark
);
// Planters at both bases.
for (const side of [-1, 1]) {
box(
module,
0.64,
0.5,
0.9,
materials.planter,
side * 4.35,
0.25,
0
);
box(
module,
0.53,
0.07,
0.76,
materials.soil,
side * 4.35,
0.53,
0
);
// Static planting around each cutting.
for (let j = 0; j < 5; j++) {
const sprout = new THREE.Mesh(
new THREE.ConeGeometry(0.09, 0.38, 4),
j % 2 ? materials.leaf : materials.leafLight
);
sprout.position.set(
side * 4.35 + (Math.random() - 0.5) * 0.34,
0.7,
(Math.random() - 0.5) * 0.55
);
sprout.rotation.z = (Math.random() - 0.5) * 0.65;
sprout.castShadow = true;
module.add(sprout);
}
}
});
// Longitudinal rails connecting the repeated modules.
for (let i = 0; i < moduleZ.length - 1; i++) {
const z = (moduleZ[i] + moduleZ[i + 1]) / 2;
const length = moduleZ[i + 1] - moduleZ[i];
for (const x of [-halfWidth, halfWidth, 0]) {
const y = x === 0 ? 2.82 : 2.82;
box(
trellisGroup,
x === 0 ? 0.12 : 0.14,
0.14,
length,
materials.woodDark,
x,
y,
z
);
}
for (const x of [-halfWidth, halfWidth, 0]) {
box(
trellisGroup,
x === 0 ? 0.12 : 0.14,
0.14,
length,
woodMaterialForModule(i),
x,
4.65,
z
);
}
}
function woodMaterialForModule(index) {
return index % 2 === 0 ? materials.wood : materials.woodLight;
}
// -------------------------------------------------------------------------
// Support graph used by the scripted growth rule
// -------------------------------------------------------------------------
const graphNodes = new Map();
const graphEdges = new Map();
function addNode(id, x, y, z) {
graphNodes.set(id, new THREE.Vector3(x, y, z));
graphEdges.set(id, []);
}
function connect(a, b) {
if (!graphNodes.has(a) || !graphNodes.has(b)) return;
graphEdges.get(a).push(b);
graphEdges.get(b).push(a);
}
const topX = [-4.15, -3.1, -2.05, -1.025, 0, 1.025, 2.05, 3.1, 4.15];
moduleZ.forEach((z, zi) => {
for (const side of ["L", "R"]) {
const x = side === "L" ? -halfWidth : halfWidth;
levelY.forEach((y, li) => {
addNode(`side-${side}-${zi}-${li}`, x, y, z);
});
for (let li = 0; li < levelY.length - 1; li++) {
connect(`side-${side}-${zi}-${li}`, `side-${side}-${zi}-${li + 1}`);
}
}
topX.forEach((x, xi) => {
addNode(`top-${zi}-${xi}`, x, 4.65, z);
addNode(`lower-${zi}-${xi}`, x, 2.82, z);
});
for (let xi = 0; xi < topX.length - 1; xi++) {
connect(`top-${zi}-${xi}`, `top-${zi}-${xi + 1}`);
connect(`lower-${zi}-${xi}`, `lower-${zi}-${xi + 1}`);
}
connect("top-" + zi + "-0", `side-L-${zi}-4`);
connect("top-" + zi + "-8", `side-R-${zi}-4`);
connect("lower-" + zi + "-0", `side-L-${zi}-2`);
connect("lower-" + zi + "-8", `side-R-${zi}-2`);
connect("lower-" + zi + "-4", "top-" + zi + "-4");
connect(`side-L-${zi}-3`, `top-${zi}-1`);
connect(`side-R-${zi}-3`, `top-${zi}-7`);
});
// Connect matching supports between neighboring modules.
for (let zi = 0; zi < moduleZ.length - 1; zi++) {
for (const side of ["L", "R"]) {
for (let li = 0; li < levelY.length; li++) {
connect(`side-${side}-${zi}-${li}`, `side-${side}-${zi + 1}-${li}`);
}
}
connect(`lower-${zi}-4`, `lower-${zi + 1}-4`);
connect(`top-${zi}-4`, `top-${zi + 1}-4`);
}
function computeDistances(targetId) {
const distances = new Map();
const queue = [];
for (const id of graphNodes.keys()) distances.set(id, Infinity);
distances.set(targetId, 0);
queue.push({ id: targetId, distance: 0 });
while (queue.length) {
queue.sort((a, b) => a.distance - b.distance);
const current = queue.shift();
if (current.distance !== distances.get(current.id)) continue;
for (const neighbor of graphEdges.get(current.id)) {
const nextDistance = current.distance + 1;
if (nextDistance < distances.get(neighbor)) {
distances.set(neighbor, nextDistance);
queue.push({ id: neighbor, distance: nextDistance });
}
}
}
return distances;
}
// -------------------------------------------------------------------------
// Target regions and 3D beacons
// -------------------------------------------------------------------------
const targetDefinitions = {
crown: {
label: "Crown",
node: "top-2-4",
position: new THREE.Vector3(0, 4.98, 1.5),
color: 0xdf8b65
},
left: {
label: "Left shoulder",
node: "side-L-1-3",
position: new THREE.Vector3(-4.4, 4.03, -1.5),
color: 0x7ca663
},
right: {
label: "Right shoulder",
node: "side-R-2-3",
position: new THREE.Vector3(4.4, 4.03, 1.5),
color: 0xbd79a4
},
far: {
label: "Far crown",
node: "top-3-4",
position: new THREE.Vector3(0, 4.98, 4.5),
color: 0x6f9fc5
}
};
const markerPickables = [];
const markerObjects = new Map();
function createLabel(text, color) {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 64;
const context = canvas.getContext("2d");
context.fillStyle = "rgba(249,251,246,0.92)";
context.fillRect(0, 0, 256, 64);
context.strokeStyle = `#${new THREE.Color(color).getHexString()}`;
context.lineWidth = 5;
context.strokeRect(2, 2, 252, 60);
context.fillStyle = "#34483c";
context.font = "700 25px sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 128, 33);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(1.55, 0.39, 1);
return sprite;
}
Object.entries(targetDefinitions).forEach(([id, definition]) => {
const group = new THREE.Group();
group.position.copy(definition.position);
group.userData.targetId = id;
group.userData.baseY = definition.position.y;
const gemMaterial = new THREE.MeshStandardMaterial({
color: definition.color,
emissive: definition.color,
emissiveIntensity: 0.38,
roughness: 0.45,
flatShading: true,
transparent: true,
opacity: 0.72
});
const gem = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.17, 0),
gemMaterial
);
gem.userData.targetId = id;
group.add(gem);
const ringMaterial = new THREE.MeshBasicMaterial({
color: definition.color,
transparent: true,
opacity: 0.55
});
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.31, 0.025, 5, 20),
ringMaterial
);
ring.userData.targetId = id;
group.add(ring);
const label = createLabel(definition.label, definition.color);
label.position.y = 0.47;
group.add(label);
markerGroup.add(group);
markerPickables.push(gem, ring);
markerObjects.set(id, { group, gem, ring, gemMaterial, ringMaterial });
});
// -------------------------------------------------------------------------
// Growth state
// -------------------------------------------------------------------------
let currentTarget = "crown";
let targetDistances = computeDistances(targetDefinitions[currentTarget].node);
let clearance = 2.25;
let growthSpeed = 1;
let running = true;
let growthAccumulator = 0;
let tips = [];
let leafMeshes = [];
const occupancy = new Map();
const usedSegments = new Set();
const sourceNodes = [
"side-L-0-0",
"side-L-1-0",
"side-L-3-0",
"side-R-0-0",
"side-R-2-0",
"side-R-3-0"
];
function resetTipMemory(tip) {
tip.visited = new Set([tip.current]);
tip.done = false;
}
function resetVines() {
for (const child of [...vineGroup.children]) vineGroup.remove(child);
leafMeshes = [];
occupancy.clear();
usedSegments.clear();
tips = [];
sourceNodes.forEach((nodeId, index) => {
tips.push({
id: index,
current: nodeId,
visited: new Set([nodeId]),
steps: 0,
done: false
});
});
running = true;
growthAccumulator = 0;
updateGrowthButton();
updateRouteText();
}
function segmentKey(a, b) {
return [a, b].sort().join("|");
}
function addVineSegment(fromId, toId) {
const key = segmentKey(fromId, toId);
if (usedSegments.has(key)) return;
usedSegments.add(key);
const start = graphNodes.get(fromId);
const end = graphNodes.get(toId);
const direction = new THREE.Vector3().subVectors(end, start);
const length = direction.length();
const segment = new THREE.Mesh(unitCylinder, materials.vine);
segment.scale.set(0.034, length, 0.034);
segment.position.copy(start).add(end).multiplyScalar(0.5);
segment.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
segment.castShadow = true;
vineGroup.add(segment);
}
function addLeaf(position, phase) {
const leaf = new THREE.Mesh(
leafGeometry,
Math.random() > 0.45 ? materials.leaf : materials.leafLight
);
leaf.position.copy(position);
leaf.position.x += (Math.random() - 0.5) * 0.18;
leaf.position.y += (Math.random() - 0.5) * 0.13;
leaf.position.z += (Math.random() - 0.5) * 0.18;
leaf.rotation.set(
Math.random() * Math.PI,
Math.random() * Math.PI,
Math.random() * Math.PI
);
leaf.scale.set(0.13, 0.24, 1);
leaf.castShadow = true;
leaf.userData.phase = phase;
leaf.userData.baseRotationZ = leaf.rotation.z;
vineGroup.add(leaf);
leafMeshes.push(leaf);
}
function violatesClearance(position) {
const insideAisle = Math.abs(position.x) < 1.9;
const insideTrellis = position.z > -5.3 && position.z < 5.3;
return insideAisle && insideTrellis && position.y < clearance + 0.28;
}
function chooseNextNode(tip) {
const currentPosition = graphNodes.get(tip.current);
const neighbors = graphEdges.get(tip.current);
let candidates = neighbors.filter((id) => {
if (tip.visited.has(id)) return false;
return !violatesClearance(graphNodes.get(id));
});
// If a path is temporarily blocked by occupancy, allow a second attempt
// with the visited constraint relaxed.
if (!candidates.length) {
candidates = neighbors.filter(
(id) => !violatesClearance(graphNodes.get(id))
);
}
if (!candidates.length) return null;
const scored = candidates.map((id) => {
const position = graphNodes.get(id);
const distance = targetDistances.get(id) ?? Infinity;
let score = distance * 10;
// Upward light preference prevents stems from hanging downward.
if (position.y < currentPosition.y - 0.08) score += 2.7;
if (currentPosition.y < 2.7 && position.y >= 2.7) score -= 0.8;
// Strongly discourage repeated support use, while allowing a reroute.
score += (occupancy.get(id) || 0) * 1.6;
const key = segmentKey(tip.current, id);
if (usedSegments.has(key)) score += 0.55;
score += Math.random() * 0.32;
return { id, score };
});
scored.sort((a, b) => a.score - b.score);
return scored[0].id;
}
function growStep() {
for (const tip of tips) {
if (tip.done) continue;
const nextId = chooseNextNode(tip);
if (!nextId) {
tip.done = true;
continue;
}
addVineSegment(tip.current, nextId);
tip.visited.add(nextId);
tip.current = nextId;
tip.steps++;
occupancy.set(nextId, (occupancy.get(nextId) || 0) + 1);
if (tip.steps % 2 === 0) {
addLeaf(graphNodes.get(nextId), tip.steps + tip.id * 0.71);
}
if (nextId === targetDefinitions[currentTarget].node) {
tip.done = true;
const bloom = new THREE.Mesh(bloomGeometry, materials.blossom);
bloom.position.copy(graphNodes.get(nextId));
bloom.castShadow = true;
vineGroup.add(bloom);
}
}
}
function updateRouteText() {
const target = targetDefinitions[currentTarget];
const complete = tips.filter((tip) => tip.done).length;
document.getElementById("routeText").textContent =
`${tips.length} shoots → ${target.label} · ` +
`${complete} reached target · ${tips.length - complete} still searching`;
}
function updateGrowthButton() {
document.getElementById("toggleGrowth").textContent = running
? "Pause growth"
: "Resume growth";
}
function activateTarget(id) {
currentTarget = id;
targetDistances = computeDistances(targetDefinitions[id].node);
// Existing stems remain, but active tips are allowed to find a new route.
for (const tip of tips) resetTipMemory(tip);
document.querySelectorAll(".target").forEach((button) => {
const active = button.dataset.target === id;
button.classList.toggle("active", active);
button.setAttribute("aria-pressed", String(active));
});
for (const [markerId, marker] of markerObjects) {
const active = markerId === id;
marker.gemMaterial.opacity = active ? 1 : 0.58;
marker.gemMaterial.emissiveIntensity = active ? 0.9 : 0.28;
marker.ringMaterial.opacity = active ? 0.95 : 0.36;
}
updateRouteText();
}
document.querySelectorAll(".target").forEach((button) => {
button.addEventListener("click", () => activateTarget(button.dataset.target));
});
document.getElementById("toggleGrowth").addEventListener("click", () => {
running = !running;
growthAccumulator = 0;
updateGrowthButton();
});
document.getElementById("resetGrowth").addEventListener("click", resetVines);
document.getElementById("speed").addEventListener("input", (event) => {
growthSpeed = Number(event.target.value);
document.getElementById("speedValue").textContent =
`${growthSpeed.toFixed(1)}×`;
});
document.getElementById("clearance").addEventListener("input", (event) => {
clearance = Number(event.target.value);
document.getElementById("clearanceValue").textContent =
`${clearance.toFixed(2)} m`;
corridor.scale.y = clearance;
corridor.position.y = clearance / 2;
corridorEdges.scale.y = clearance;
corridorEdges.position.y = clearance / 2;
});
// -------------------------------------------------------------------------
// Direct camera controls and beacon picking
// -------------------------------------------------------------------------
const cameraState = {
yaw: 0.58,
pitch: 0.42,
radius: 15.5,
target: new THREE.Vector3(0, 2.15, 0)
};
function updateCamera() {
const { yaw, pitch, radius, target } = cameraState;
camera.position.set(
target.x + radius * Math.cos(pitch) * Math.sin(yaw),
target.y + radius * Math.sin(pitch),
target.z + radius * Math.cos(pitch) * Math.cos(yaw)
);
camera.lookAt(target);
}
updateCamera();
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let dragging = false;
let dragMoved = false;
let dragStart = { x: 0, y: 0 };
let previousPointer = { x: 0, y: 0 };
function setPointerFromEvent(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 pickTarget(event) {
setPointerFromEvent(event);
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(markerPickables, false);
if (hits.length) {
const id = hits[0].object.userData.targetId;
if (id) activateTarget(id);
}
}
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
dragMoved = false;
dragStart = { x: event.clientX, y: event.clientY };
previousPointer = { x: event.clientX, y: event.clientY };
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) {
setPointerFromEvent(event);
raycaster.setFromCamera(pointer, camera);
const hovering = raycaster.intersectObjects(markerPickables, false).length > 0;
renderer.domElement.style.cursor = hovering ? "pointer" : "grab";
return;
}
const dx = event.clientX - previousPointer.x;
const dy = event.clientY - previousPointer.y;
if (
Math.hypot(
event.clientX - dragStart.x,
event.clientY - dragStart.y
) > 4
) {
dragMoved = true;
}
if (event.shiftKey) {
const right = new THREE.Vector3();
const forward = new THREE.Vector3();
camera.matrixWorld.extractBasis(right, forward, new THREE.Vector3());
cameraState.target.addScaledVector(right, -dx * 0.012);
cameraState.target.addScaledVector(forward, -dy * 0.012);
cameraState.target.x = THREE.MathUtils.clamp(
cameraState.target.x,
-6,
6
);
cameraState.target.z = THREE.MathUtils.clamp(
cameraState.target.z,
-7,
7
);
} else {
cameraState.yaw -= dx * 0.005;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.004,
0.12,
1.12
);
}
previousPointer = { x: event.clientX, y: event.clientY };
renderer.domElement.style.cursor = "grabbing";
});
renderer.domElement.addEventListener("pointerup", (event) => {
dragging = false;
renderer.domElement.style.cursor = "grab";
if (!dragMoved && event.button === 0) {
pickTarget(event);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
dragging = false;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.012,
7,
26
);
},
{ passive: false }
);
renderer.domElement.style.cursor = "grab";
// -------------------------------------------------------------------------
// Animation
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
let routeTextTimer = 0;
function animate() {
const delta = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
if (running) {
growthAccumulator += delta * growthSpeed;
const growthInterval = 0.22;
while (growthAccumulator >= growthInterval) {
growStep();
growthAccumulator -= growthInterval;
}
}
for (const leaf of leafMeshes) {
leaf.rotation.z =
leaf.userData.baseRotationZ +
Math.sin(elapsed * 1.35 + leaf.userData.phase) * 0.075;
}
for (const [id, marker] of markerObjects) {
const active = id === currentTarget;
const pulse = active ? 1 + Math.sin(elapsed * 3.2) * 0.08 : 1;
marker.gem.rotation.x += delta * 0.8;
marker.gem.rotation.y += delta * 1.1;
marker.gem.scale.setScalar(pulse);
marker.ring.quaternion.copy(camera.quaternion);
marker.ring.scale.setScalar(active ? 1.1 + Math.sin(elapsed * 3.2) * 0.08 : 0.85);
marker.group.position.y =
marker.group.userData.baseY + Math.sin(elapsed * 1.8 + marker.group.position.z) * 0.035;
}
routeTextTimer += delta;
if (routeTextTimer > 0.35) {
updateRouteText();
routeTextTimer = 0;
}
updateCamera();
renderer.render(scene, camera);
}
function resize() {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
}
addEventListener("resize", resize);
resetVines();
activateTarget("crown");
renderer.setAnimationLoop(animate);
</script>
</body>
</html>
```