Prompt specification
Build or customize the Three.js 3D scene "Vertex-angle tiling 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: Vertex-angle tiling puzzle
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/vertex-angle-tiling-puzzle-x1744
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts gap-free polygon tessellations. Let users assemble a small set of polygon corners around a point; compute the angle sum and indicate gaps or overlap before extending the pattern. Voxel style.
Working Three.js Starter (vertex-angle-tiling-puzzle-x1744):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Voxel Vertex Lab</title>
<style>
:root {
--bg: #071018;
--panel: rgba(10, 20, 29, 0.88);
--panel-border: rgba(139, 205, 224, 0.16);
--text: #edf8fb;
--muted: #8da8b3;
--cyan: #4ddcff;
--green: #5ee6a8;
--amber: #ffc857;
--red: #ff4567;
--purple: #b38cff;
--coral: #ff786b;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button {
font: inherit;
}
#app,
#scene {
position: fixed;
inset: 0;
}
#scene {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
#scene:active {
cursor: grabbing;
}
.panel {
position: fixed;
z-index: 5;
border: 1px solid var(--panel-border);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(18px);
-webkit-backdrop-filter: blur(18px);
}
header {
position: fixed;
z-index: 4;
top: 20px;
left: 22px;
display: flex;
align-items: center;
gap: 12px;
pointer-events: none;
}
.logo {
width: 42px;
height: 42px;
position: relative;
border: 1px solid rgba(77, 220, 255, 0.4);
border-radius: 11px;
background: rgba(77, 220, 255, 0.08);
transform: rotate(8deg);
}
.logo::before,
.logo::after {
content: "";
position: absolute;
width: 13px;
height: 13px;
background: var(--cyan);
box-shadow: 12px 12px 0 rgba(94, 230, 168, 0.78);
}
.logo::before {
top: 8px;
left: 8px;
}
.logo::after {
display: none;
}
h1 {
margin: 0;
font-size: 18px;
line-height: 1.1;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.subtitle {
margin-top: 5px;
color: var(--muted);
font-size: 12px;
}
#controls {
top: 90px;
left: 20px;
width: 330px;
max-height: calc(100vh - 112px);
padding: 18px;
overflow: auto;
scrollbar-width: thin;
scrollbar-color: #284553 transparent;
}
#status {
top: 20px;
right: 20px;
width: 294px;
padding: 18px;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
color: #b8ced7;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.step {
display: inline-grid;
place-items: center;
width: 23px;
height: 23px;
margin-right: 7px;
border: 1px solid rgba(77, 220, 255, 0.24);
border-radius: 7px;
color: var(--cyan);
background: rgba(77, 220, 255, 0.07);
letter-spacing: 0;
}
.corner-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.corner {
position: relative;
min-height: 84px;
padding: 12px 10px;
border: 1px solid rgba(154, 196, 211, 0.14);
border-radius: 12px;
color: var(--text);
background: rgba(255, 255, 255, 0.035);
cursor: pointer;
transition: 150ms ease;
}
.corner:hover {
transform: translateY(-1px);
border-color: rgba(255, 255, 255, 0.28);
background: rgba(255, 255, 255, 0.06);
}
.corner.selected {
border-color: var(--cyan);
box-shadow: inset 0 0 0 1px rgba(77, 220, 255, 0.18),
0 0 22px rgba(77, 220, 255, 0.08);
background: rgba(77, 220, 255, 0.085);
}
.corner svg {
display: block;
width: 35px;
height: 35px;
margin: 0 auto 8px;
color: var(--corner);
filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.3));
}
.corner strong {
display: block;
font-size: 12px;
}
.corner small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 11px;
}
.primary,
.secondary {
width: 100%;
border-radius: 11px;
cursor: pointer;
transition: 150ms ease;
}
.primary {
margin-top: 11px;
padding: 11px 13px;
border: 1px solid rgba(77, 220, 255, 0.52);
color: #041017;
background: var(--cyan);
font-weight: 800;
box-shadow: 0 8px 24px rgba(77, 220, 255, 0.13);
}
.primary:hover:not(:disabled) {
background: #8beaff;
transform: translateY(-1px);
}
.secondary {
padding: 9px 10px;
border: 1px solid rgba(154, 196, 211, 0.17);
color: #c8dbe2;
background: rgba(255, 255, 255, 0.035);
font-size: 12px;
font-weight: 700;
}
.secondary:hover:not(:disabled) {
color: white;
border-color: rgba(255, 255, 255, 0.3);
background: rgba(255, 255, 255, 0.07);
}
button:disabled {
cursor: not-allowed;
opacity: 0.38;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 9px;
}
.sequence {
display: flex;
flex-wrap: wrap;
gap: 7px;
min-height: 38px;
margin-top: 10px;
}
.sequence-empty {
display: flex;
align-items: center;
color: #66818d;
font-size: 12px;
}
.sequence-chip {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 7px 9px;
border: 1px solid color-mix(in srgb, var(--chip), transparent 66%);
border-radius: 8px;
color: var(--chip);
background: color-mix(in srgb, var(--chip), transparent 91%);
font-size: 11px;
font-weight: 800;
cursor: pointer;
}
.sequence-chip:hover {
background: color-mix(in srgb, var(--chip), transparent 82%);
}
.sequence-chip span:last-child {
color: #aec3cb;
font-size: 10px;
}
.help {
margin: 10px 0 0;
color: #718d99;
font-size: 11px;
line-height: 1.5;
}
.eyebrow {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.sum {
display: flex;
align-items: baseline;
gap: 7px;
margin-top: 6px;
}
#sumValue {
font-size: 46px;
font-weight: 850;
line-height: 1;
letter-spacing: -0.05em;
font-variant-numeric: tabular-nums;
}
.sum small {
color: #6f8b98;
font-size: 15px;
font-weight: 700;
}
.meter {
position: relative;
height: 9px;
margin: 17px 0 12px;
overflow: hidden;
border-radius: 20px;
background: rgba(255, 255, 255, 0.07);
}
#meterFill,
#meterOver {
position: absolute;
top: 0;
bottom: 0;
left: 0;
transition: width 180ms ease, left 180ms ease;
}
#meterFill {
width: 0;
border-radius: inherit;
background: var(--amber);
}
#meterOver {
width: 0;
background: var(--red);
}
.verdict {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 7px 9px;
border-radius: 8px;
color: var(--amber);
background: rgba(255, 200, 87, 0.1);
font-size: 11px;
font-weight: 850;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.verdict::before {
content: "";
width: 7px;
height: 7px;
border-radius: 2px;
background: currentColor;
box-shadow: 0 0 10px currentColor;
}
.verdict.exact {
color: var(--green);
background: rgba(94, 230, 168, 0.1);
}
.verdict.overlap {
color: var(--red);
background: rgba(255, 69, 103, 0.1);
}
#statusMessage {
min-height: 50px;
margin: 12px 0;
color: #91aab5;
font-size: 12px;
line-height: 1.55;
}
#extendButton {
margin-top: 0;
}
#extendButton.ready {
color: #06120d;
border-color: var(--green);
background: var(--green);
box-shadow: 0 8px 24px rgba(94, 230, 168, 0.12);
}
#extensionInfo {
min-height: 35px;
margin-top: 10px;
color: #78939e;
font-size: 11px;
line-height: 1.45;
}
#hint {
position: fixed;
z-index: 3;
left: 50%;
bottom: 17px;
transform: translateX(-50%);
padding: 8px 12px;
border: 1px solid rgba(139, 205, 224, 0.1);
border-radius: 20px;
color: #6e8995;
background: rgba(7, 16, 24, 0.62);
font-size: 10px;
white-space: nowrap;
pointer-events: none;
}
#toast {
position: fixed;
z-index: 10;
left: 50%;
bottom: 58px;
transform: translate(-50%, 10px);
padding: 9px 13px;
border: 1px solid rgba(77, 220, 255, 0.3);
border-radius: 9px;
color: #dff9ff;
background: rgba(8, 24, 33, 0.95);
font-size: 12px;
opacity: 0;
pointer-events: none;
transition: 180ms ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 850px) {
header {
top: 12px;
left: 13px;
}
h1 {
font-size: 14px;
}
.subtitle,
.logo {
display: none;
}
#status {
top: 48px;
right: 10px;
left: 10px;
width: auto;
padding: 13px;
}
#sumValue {
font-size: 32px;
}
.meter {
margin: 10px 0;
}
#statusMessage {
min-height: 0;
margin: 8px 0;
}
#controls {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 44vh;
padding: 13px;
}
#hint {
display: none;
}
}
</style>
</head>
<body>
<div id="app">
<canvas id="scene"></canvas>
<header>
<div class="logo"></div>
<div>
<h1>Voxel Vertex Lab</h1>
<div class="subtitle">Build a corner cluster. Prove the angle. Grow the tiling.</div>
</div>
</header>
<aside id="controls" class="panel">
<div class="section-title">
<span><span class="step">1</span>Choose a corner</span>
<span>interior angle</span>
</div>
<div class="corner-grid">
<button class="corner selected" data-n="3" style="--corner: var(--coral)">
<svg viewBox="0 0 40 40" aria-hidden="true">
<polygon points="20,4 36,34 4,34" fill="currentColor" />
</svg>
<strong>Triangle</strong>
<small>60° corner</small>
</button>
<button class="corner" data-n="4" style="--corner: var(--cyan)">
<svg viewBox="0 0 40 40" aria-hidden="true">
<polygon points="4,4 36,4 36,36 4,36" fill="currentColor" />
</svg>
<strong>Square</strong>
<small>90° corner</small>
</button>
<button class="corner" data-n="5" style="--corner: var(--purple)">
<svg viewBox="0 0 40 40" aria-hidden="true">
<polygon points="20,3 37,15 31,35 9,35 3,15" fill="currentColor" />
</svg>
<strong>Pentagon</strong>
<small>108° corner</small>
</button>
<button class="corner" data-n="6" style="--corner: var(--green)">
<svg viewBox="0 0 40 40" aria-hidden="true">
<polygon points="13,3 31,11 37,30 20,38 3,30 9,11" fill="currentColor" />
</svg>
<strong>Hexagon</strong>
<small>120° corner</small>
</button>
</div>
<button id="addButton" class="primary">+ Add triangle corner</button>
<div class="section-title" style="margin-top: 18px">
<span><span class="step">2</span>Arrange the vertex</span>
<span id="cornerCount">0 corners</span>
</div>
<div id="sequence" class="sequence">
<div class="sequence-empty">No corners placed yet.</div>
</div>
<div class="button-row">
<button id="undoButton" class="secondary">Undo</button>
<button id="clearButton" class="secondary">Clear</button>
<button id="viewButton" class="secondary" style="grid-column: 1 / -1">
Reset camera view
</button>
</div>
<p class="help">
Order matters. Click the white hub to add the selected corner, or use
“Add corner.” Click a sequence chip to remove it.
</p>
</aside>
<aside id="status" class="panel">
<div class="eyebrow">Vertex check</div>
<div class="sum">
<span id="sumValue">0°</span>
<small>/ 360°</small>
</div>
<div class="meter">
<div id="meterFill"></div>
<div id="meterOver"></div>
</div>
<div id="verdict" class="verdict">Empty vertex</div>
<p id="statusMessage">
Add polygon corners around the central point to test whether their
angles close without a gap or overlap.
</p>
<button id="extendButton" class="primary" disabled>
Extend tessellation
</button>
<div id="extensionInfo">
The 360° check must pass before the pattern can grow.
</div>
</aside>
<div id="hint">Drag to orbit · Scroll to zoom · Click the hub to add</div>
<div id="toast"></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 canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071018);
scene.fog = new THREE.Fog(0x071018, 16, 34);
const camera = new THREE.OrthographicCamera(-7, 7, 5, -5, 0.1, 100);
camera.position.set(8, 9, 10);
camera.lookAt(0, 0, 0);
const world = new THREE.Group();
scene.add(world);
const dynamic = new THREE.Group();
world.add(dynamic);
const cubeGeometry = new THREE.BoxGeometry(1, 1, 1);
scene.add(new THREE.HemisphereLight(0xbdeeff, 0x182331, 2.2));
const keyLight = new THREE.DirectionalLight(0xffffff, 3.1);
keyLight.position.set(5, 10, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -9;
keyLight.shadow.camera.right = 9;
keyLight.shadow.camera.top = 9;
keyLight.shadow.camera.bottom = -9;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 30;
keyLight.shadow.bias = -0.0007;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4ddcff, 1.4);
rimLight.position.set(-7, 5, -7);
scene.add(rimLight);
const floor = new THREE.Mesh(
new THREE.BoxGeometry(28, 0.22, 28),
new THREE.MeshStandardMaterial({
color: 0x0a141d,
roughness: 0.96,
metalness: 0.02
})
);
floor.position.y = -0.16;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(28, 28, 0x1b3b49, 0x102733);
grid.position.y = -0.035;
grid.material.transparent = true;
grid.material.opacity = 0.55;
scene.add(grid);
const PRESETS = {
3: { name: "Triangle", angle: 60, color: 0xff786b },
4: { name: "Square", angle: 90, color: 0x4ddcff },
5: { name: "Pentagon", angle: 108, color: 0xb38cff },
6: { name: "Hexagon", angle: 120, color: 0x5ee6a8 }
};
const GAP_COLOR = 0xffc857;
const OVERLAP_COLOR = 0xff4567;
const CELL_SIZE = 0.19;
const VOXEL_SIZE = 0.181;
let selected = 3;
let sequence = [];
let extensionDepth = 0;
let hubTargets = [];
let lastConflictPairs = 0;
let toastTimer = 0;
const ui = {
add: document.querySelector("#addButton"),
undo: document.querySelector("#undoButton"),
clear: document.querySelector("#clearButton"),
view: document.querySelector("#viewButton"),
sequence: document.querySelector("#sequence"),
count: document.querySelector("#cornerCount"),
sum: document.querySelector("#sumValue"),
meterFill: document.querySelector("#meterFill"),
meterOver: document.querySelector("#meterOver"),
verdict: document.querySelector("#verdict"),
message: document.querySelector("#statusMessage"),
extend: document.querySelector("#extendButton"),
extensionInfo: document.querySelector("#extensionInfo"),
toast: document.querySelector("#toast")
};
function interiorAngle(n) {
return ((n - 2) * 180) / n;
}
function angleSum() {
return sequence.reduce((sum, n) => sum + interiorAngle(n), 0);
}
function formatAngle(value) {
return Number.isInteger(value)
? `${value}°`
: `${value.toFixed(1)}°`;
}
function signedArea(points) {
let area = 0;
for (let i = 0; i < points.length; i++) {
const a = points[i];
const b = points[(i + 1) % points.length];
area += a.x * b.z - b.x * a.z;
}
return area / 2;
}
function pointInConvexPolygon(point, polygon) {
let positive = 0;
let negative = 0;
const epsilon = 1e-7;
for (let i = 0; i < polygon.length; i++) {
const a = polygon[i];
const b = polygon[(i + 1) % polygon.length];
const cross =
(b.x - a.x) * (point.z - a.z) -
(b.z - a.z) * (point.x - a.x);
if (cross > epsilon) positive++;
if (cross < -epsilon) negative++;
}
return positive === 0 || negative === 0;
}
// A regular polygon with one vertex at the central point.
// Its first edge points along startAngle.
function regularPolygon(n, startAngle) {
const alpha = interiorAngle(n) * Math.PI / 180;
const radius = 1 / (2 * Math.sin(Math.PI / n));
const middle = startAngle * Math.PI / 180 + alpha / 2;
const center = {
x: radius * Math.cos(middle),
z: radius * Math.sin(middle)
};
const vertices = [];
const firstVertexAngle = middle + Math.PI;
for (let i = 0; i < n; i++) {
const angle = firstVertexAngle + (i * Math.PI * 2) / n;
vertices.push({
x: center.x + radius * Math.cos(angle),
z: center.z + radius * Math.sin(angle)
});
}
return vertices;
}
function polygonCentroid(points) {
const result = { x: 0, z: 0 };
for (const p of points) {
result.x += p.x / points.length;
result.z += p.z / points.length;
}
return result;
}
function polygonKey(polygon) {
const c = polygonCentroid(polygon.vertices);
return `${polygon.n}:${c.x.toFixed(3)}:${c.z.toFixed(3)}`;
}
function edgeKey(a, b) {
const ka = `${a.x.toFixed(3)},${a.z.toFixed(3)}`;
const kb = `${b.x.toFixed(3)},${b.z.toFixed(3)}`;
return ka < kb ? `${ka}|${kb}` : `${kb}|${ka}`;
}
function reflectPolygon(points, a, b) {
const dx = b.x - a.x;
const dz = b.z - a.z;
const lengthSquared = dx * dx + dz * dz;
const reflected = points.map((p) => {
const t =
((p.x - a.x) * dx + (p.z - a.z) * dz) / lengthSquared;
const projection = {
x: a.x + t * dx,
z: a.z + t * dz
};
return {
x: 2 * projection.x - p.x,
z: 2 * projection.z - p.z
};
});
if (signedArea(reflected) < 0) reflected.reverse();
return reflected;
}
function projectPolygon(points, axis) {
let min = Infinity;
let max = -Infinity;
for (const p of points) {
const value = p.x * axis.x + p.z * axis.z;
min = Math.min(min, value);
max = Math.max(max, value);
}
return { min, max };
}
function polygonsOverlap(a, b) {
const epsilon = 1e-5;
for (const polygon of [a, b]) {
for (let i = 0; i < polygon.length; i++) {
const p = polygon[i];
const q = polygon[(i + 1) % polygon.length];
const edge = { x: q.x - p.x, z: q.z - p.z };
const length = Math.hypot(edge.x, edge.z);
if (length < epsilon) continue;
const axis = {
x: -edge.z / length,
z: edge.x / length
};
const pa = projectPolygon(a, axis);
const pb = projectPolygon(b, axis);
if (
pa.max <= pb.min + epsilon ||
pb.max <= pa.min + epsilon
) {
return false;
}
}
}
return true;
}
function buildPolygons() {
let cursor = 0;
const core = [];
for (const n of sequence) {
const angle = interiorAngle(n);
const end = cursor + angle;
core.push({
n,
vertices: regularPolygon(n, cursor),
level: 0,
core: true,
overflow: end > 360,
conflict: false
});
cursor = end;
}
const all = core.slice();
if (extensionDepth > 0 && Math.abs(angleSum() - 360) < 0.001) {
const edgeOwners = new Map();
const polygonKeys = new Set(all.map(polygonKey));
function registerEdges(polygon) {
for (let i = 0; i < polygon.vertices.length; i++) {
const a = polygon.vertices[i];
const b = polygon.vertices[(i + 1) % polygon.vertices.length];
const key = edgeKey(a, b);
if (!edgeOwners.has(key)) edgeOwners.set(key, []);
edgeOwners.get(key).push(polygon);
}
}
all.forEach(registerEdges);
let frontier = core.slice();
for (let level = 1; level <= extensionDepth; level++) {
const next = [];
for (const polygon of frontier) {
if (all.length >= 90) break;
for (let i = 0; i < polygon.vertices.length; i++) {
const a = polygon.vertices[i];
const b = polygon.vertices[(i + 1) % polygon.vertices.length];
const key = edgeKey(a, b);
const owners = edgeOwners.get(key) || [];
// Another polygon already occupies the other side of this edge.
if (owners.some((owner) => owner !== polygon)) continue;
const vertices = reflectPolygon(polygon.vertices, a, b);
const reflected = {
n: polygon.n,
vertices,
level,
core: false,
overflow: false,
conflict: false
};
const reflectedKey = polygonKey(reflected);
if (polygonKeys.has(reflectedKey)) continue;
polygonKeys.add(reflectedKey);
edgeOwners.get(key).push(reflected);
registerEdges(reflected);
all.push(reflected);
next.push(reflected);
}
}
frontier = next;
if (!frontier.length) break;
}
}
let conflictPairs = 0;
for (let i = 0; i < all.length; i++) {
for (let j = i + 1; j < all.length; j++) {
if (polygonsOverlap(all[i].vertices, all[j].vertices)) {
all[i].conflict = true;
all[j].conflict = true;
conflictPairs++;
}
}
}
lastConflictPairs = conflictPairs;
return all;
}
function voxelizePolygon(vertices) {
const cells = [];
const xs = vertices.map((v) => v.x);
const zs = vertices.map((v) => v.z);
const minX = Math.min(...xs);
const maxX = Math.max(...xs);
const minZ = Math.min(...zs);
const maxZ = Math.max(...zs);
const startX = Math.ceil(minX / CELL_SIZE) * CELL_SIZE;
const startZ = Math.ceil(minZ / CELL_SIZE) * CELL_SIZE;
for (let x = startX; x <= maxX; x += CELL_SIZE) {
for (let z = startZ; z <= maxZ; z += CELL_SIZE) {
if (pointInConvexPolygon({ x, z }, vertices)) {
cells.push({ x, z });
}
}
}
return cells;
}
function clearDynamic() {
for (const child of [...dynamic.children]) {
dynamic.remove(child);
if (child.material) child.material.dispose();
}
hubTargets = [];
}
function createInstanceMesh(matrices, color, height, emissive = 0x000000) {
if (!matrices.length) return;
const material = new THREE.MeshStandardMaterial({
color,
roughness: 0.72,
metalness: 0.04,
emissive,
emissiveIntensity: 0.12
});
const mesh = new THREE.InstancedMesh(
cubeGeometry,
material,
matrices.length
);
matrices.forEach((matrix, index) => mesh.setMatrixAt(index, matrix));
mesh.instanceMatrix.needsUpdate = true;
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.computeBoundingSphere();
dynamic.add(mesh);
}
function makeMatrix(x, y, z, scaleX, scaleY, scaleZ) {
const matrix = new THREE.Matrix4();
matrix.compose(
new THREE.Vector3(x, y, z),
new THREE.Quaternion(),
new THREE.Vector3(scaleX, scaleY, scaleZ)
);
return matrix;
}
function addPolygonVoxels(polygons) {
const buckets = new Map();
for (const polygon of polygons) {
let color = PRESETS[polygon.n].color;
let height = polygon.level === 0 ? 0.22 : 0.16;
let emissive = 0x000000;
if (polygon.conflict) {
color = OVERLAP_COLOR;
height = 0.27;
emissive = 0x4a0714;
} else if (polygon.overflow) {
color = OVERLAP_COLOR;
height = 0.25;
emissive = 0x35030d;
} else if (polygon.level > 0) {
color = new THREE.Color(PRESETS[polygon.n].color)
.multiplyScalar(0.57)
.getHex();
height = 0.15;
}
const key = `${color}-${height}-${emissive}`;
if (!buckets.has(key)) {
buckets.set(key, {
color,
height,
emissive,
matrices: []
});
}
const bucket = buckets.get(key);
for (const cell of voxelizePolygon(polygon.vertices)) {
bucket.matrices.push(
makeMatrix(
cell.x,
bucket.height / 2,
cell.z,
VOXEL_SIZE,
bucket.height,
VOXEL_SIZE
)
);
}
}
for (const bucket of buckets.values()) {
createInstanceMesh(
bucket.matrices,
bucket.color,
bucket.height,
bucket.emissive
);
}
}
function addAngularIndicator(startAngle, endAngle, color) {
if (endAngle <= startAngle) return;
const matrices = [];
const step = 7.5;
const count = Math.max(1, Math.ceil((endAngle - startAngle) / step));
const actualStep = (endAngle - startAngle) / count;
for (let i = 0; i < count; i++) {
const angle = (startAngle + actualStep * (i + 0.5)) * Math.PI / 180;
for (const radius of [0.78, 1.16, 1.54]) {
matrices.push(
makeMatrix(
Math.cos(angle) * radius,
0.34,
Math.sin(angle) * radius,
0.15,
0.08,
0.15
)
);
}
}
createInstanceMesh(matrices, color, 0.08, color);
}
function addHub() {
const exact = Math.abs(angleSum() - 360) < 0.001;
const color = exact ? 0xf4ffff : 0xcceef7;
const base = new THREE.Mesh(
cubeGeometry,
new THREE.MeshStandardMaterial({
color,
roughness: 0.5,
metalness: 0.15,
emissive: exact ? 0x1b6b50 : 0x102a34,
emissiveIntensity: 0.35
})
);
base.position.y = 0.12;
base.scale.set(0.46, 0.24, 0.46);
base.castShadow = true;
base.userData.addCorner = true;
dynamic.add(base);
hubTargets.push(base);
const top = new THREE.Mesh(
cubeGeometry,
new THREE.MeshStandardMaterial({
color,
roughness: 0.42,
metalness: 0.2,
emissive: exact ? 0x1f8e66 : 0x153844,
emissiveIntensity: 0.42
})
);
top.position.y = 0.35;
top.scale.set(0.25, 0.25, 0.25);
top.castShadow = true;
top.userData.addCorner = true;
dynamic.add(top);
hubTargets.push(top);
}
function rebuild() {
clearDynamic();
const polygons = buildPolygons();
addPolygonVoxels(polygons);
const total = angleSum();
if (total < 360) {
addAngularIndicator(total, 360, GAP_COLOR);
} else if (total > 360) {
addAngularIndicator(0, total - 360, OVERLAP_COLOR);
}
addHub();
updateUI();
}
function updateSequenceUI() {
ui.count.textContent = `${sequence.length} corner${sequence.length === 1 ? "" : "s"}`;
if (!sequence.length) {
ui.sequence.innerHTML =
'<div class="sequence-empty">No corners placed yet.</div>';
return;
}
ui.sequence.innerHTML = "";
sequence.forEach((n, index) => {
const preset = PRESETS[n];
const chip = document.createElement("button");
chip.className = "sequence-chip";
chip.style.setProperty("--chip", `#${preset.color.toString(16).padStart(6, "0")}`);
chip.title = `Remove ${preset.name.toLowerCase()} ${index + 1}`;
chip.innerHTML = `
<span>${preset.name.slice(0, 3).toUpperCase()}</span>
<span>${preset.angle}° ×</span>
`;
chip.addEventListener("click", () => {
sequence.splice(index, 1);
extensionDepth = 0;
rebuild();
});
ui.sequence.appendChild(chip);
});
}
function updateUI() {
const total = angleSum();
const difference = 360 - total;
const exact = Math.abs(difference) < 0.001;
ui.sum.textContent = formatAngle(total);
updateSequenceUI();
ui.meterFill.style.width = `${Math.min(total / 360, 1) * 100}%`;
if (total > 360) {
const overflowPercent = Math.min((total - 360) / 360, 1) * 100;
ui.meterOver.style.left = `${100 - overflowPercent}%`;
ui.meterOver.style.width = `${overflowPercent}%`;
} else {
ui.meterOver.style.left = "100%";
ui.meterOver.style.width = "0%";
}
ui.verdict.classList.remove("exact", "overlap");
if (exact) {
ui.verdict.classList.add("exact");
ui.verdict.textContent = "Perfect vertex";
ui.meterFill.style.background = "var(--green)";
ui.message.textContent =
"The corners add up to exactly 360°. There is no angular gap and no overlap.";
ui.extend.disabled = false;
ui.extend.classList.add("ready");
if (extensionDepth === 0) {
ui.extend.textContent = "Extend tessellation";
ui.extensionInfo.textContent =
"The vertex is ready. Extend across the exposed polygon edges to grow an edge-to-edge tiling.";
} else if (extensionDepth === 1) {
ui.extend.textContent = "Grow another ring";
ui.extensionInfo.textContent = lastConflictPairs
? `${lastConflictPairs} polygon collision${lastConflictPairs === 1 ? "" : "s"} detected. The red blocks mark conflicting growth.`
: "One clean ring has been added. Continue growing to test the ordering farther.";
} else {
ui.extend.textContent = "Maximum preview depth";
ui.extensionInfo.textContent = lastConflictPairs
? `${lastConflictPairs} polygon collision${lastConflictPairs === 1 ? "" : "s"} detected in the extended patch.`
: "Two clean rings have been added. The local motif grows without polygon collisions.";
}
} else if (difference > 0) {
ui.verdict.textContent = `Gap · ${formatAngle(difference)}`;
ui.meterFill.style.background = "var(--amber)";
ui.message.textContent =
`The corners are short by ${formatAngle(difference)}. Add another corner or remove one to close the vertex.`;
ui.extend.disabled = true;
ui.extend.classList.remove("ready");
ui.extend.textContent = "Extend tessellation";
ui.extensionInfo.textContent =
"The 360° check must pass before the pattern can grow.";
} else {
ui.verdict.classList.add("overlap");
ui.verdict.textContent = `Overlap · ${formatAngle(-difference)}`;
ui.meterFill.style.background = "var(--red)";
ui.message.textContent =
`The corners exceed a full turn by ${formatAngle(-difference)}. Remove or replace a corner to remove the overlap.`;
ui.extend.disabled = true;
ui.extend.classList.remove("ready");
ui.extend.textContent = "Extend tessellation";
ui.extensionInfo.textContent =
"The 360° check must pass before the pattern can grow.";
}
ui.undo.disabled = !sequence.length;
ui.clear.disabled = !sequence.length;
}
function showToast(message) {
ui.toast.textContent = message;
ui.toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => ui.toast.classList.remove("show"), 1800);
}
function selectCorner(n) {
selected = n;
document.querySelectorAll(".corner").forEach((button) => {
button.classList.toggle("selected", Number(button.dataset.n) === n);
});
ui.add.textContent = `+ Add ${PRESETS[n].name.toLowerCase()} corner`;
}
function addCorner() {
if (sequence.length >= 12) {
showToast("This small-set builder is limited to 12 corners.");
return;
}
sequence.push(selected);
extensionDepth = 0;
rebuild();
}
function undo() {
if (!sequence.length) return;
sequence.pop();
extensionDepth = 0;
rebuild();
}
function clearAll() {
sequence = [];
extensionDepth = 0;
rebuild();
}
function extendTessellation() {
if (Math.abs(angleSum() - 360) > 0.001) return;
extensionDepth = Math.min(2, extensionDepth + 1);
rebuild();
}
document.querySelectorAll(".corner").forEach((button) => {
button.addEventListener("click", () => selectCorner(Number(button.dataset.n)));
});
ui.add.addEventListener("click", addCorner);
ui.undo.addEventListener("click", undo);
ui.clear.addEventListener("click", clearAll);
ui.extend.addEventListener("click", extendTessellation);
ui.view.addEventListener("click", () => {
world.rotation.set(0, 0, 0);
camera.zoom = 1;
camera.updateProjectionMatrix();
});
// Camera controls implemented directly without Three.js addons.
let dragging = false;
let moved = false;
let previousX = 0;
let previousY = 0;
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
moved = false;
previousX = event.clientX;
previousY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
if (Math.abs(dx) + Math.abs(dy) > 2) moved = true;
world.rotation.y += dx * 0.007;
world.rotation.x = THREE.MathUtils.clamp(
world.rotation.x + dy * 0.004,
-0.42,
0.32
);
previousX = event.clientX;
previousY = event.clientY;
});
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
canvas.addEventListener("pointerup", (event) => {
dragging = false;
if (moved || !hubTargets.length) return;
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(hubTargets, false);
if (hits.length) addCorner();
});
canvas.addEventListener("pointercancel", () => {
dragging = false;
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
camera.zoom = THREE.MathUtils.clamp(
camera.zoom * (event.deltaY > 0 ? 0.92 : 1.08),
0.65,
1.85
);
camera.updateProjectionMatrix();
},
{ passive: false }
);
window.addEventListener("keydown", (event) => {
if (event.ctrlKey || event.metaKey) {
if (event.key.toLowerCase() === "z") {
event.preventDefault();
undo();
}
return;
}
if (event.target instanceof HTMLButtonElement) return;
if (["1", "2", "3", "4"].includes(event.key)) {
selectCorner({ 1: 3, 2: 4, 3: 5, 4: 6 }[event.key]);
}
if (event.code === "Space") {
event.preventDefault();
addCorner();
}
});
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
const viewHeight = aspect < 1 ? 9 / aspect : 9;
camera.left = (-viewHeight * aspect) / 2;
camera.right = (viewHeight * aspect) / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
}
window.addEventListener("resize", resize);
resize();
selectCorner(3);
rebuild();
function animate(time) {
requestAnimationFrame(animate);
const pulse = 1 + Math.sin(time * 0.0026) * 0.035;
if (hubTargets[1]) hubTargets[1].scale.y = 0.25 * pulse;
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```