Prompt specification
Build or customize the Three.js 3D scene "Pattern Rule Loom Playground" 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: Pattern Rule Loom Playground
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/pattern-rule-loom-playground-x3360
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts woven crossings and repeating textile patterns. Let users edit a small binary weave matrix and see a corresponding raised-strip fabric. Highlight impossible or disconnected structures under the simplified construction rules. Voxel style.
Working Three.js Starter (pattern-rule-loom-playground-x3360):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Binary Weave Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #07111c;
--panel: rgba(12, 25, 39, 0.88);
--panel-solid: #0c1927;
--line: rgba(165, 214, 230, 0.16);
--text: #e7f4f7;
--muted: #8ea8b5;
--warp: #32d6c1;
--warp-dark: #117c75;
--weft: #ff956b;
--weft-dark: #a44f39;
--danger: #ff5f78;
--warning: #ffd166;
--cyan: #8fffea;
}
* {
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,
select {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
outline: none;
touch-action: none;
}
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
radial-gradient(circle at 45% 42%, transparent 20%, rgba(2, 8, 15, 0.24) 78%),
linear-gradient(90deg, rgba(2, 8, 15, 0.12), transparent 30%);
z-index: 1;
}
.brand {
position: fixed;
top: 24px;
left: 28px;
z-index: 3;
pointer-events: none;
text-shadow: 0 2px 18px rgba(0, 0, 0, 0.35);
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.22em;
text-transform: uppercase;
}
.eyebrow::before {
width: 22px;
height: 2px;
content: "";
background: var(--cyan);
box-shadow: 0 0 12px var(--cyan);
}
h1 {
margin: 9px 0 4px;
font-size: clamp(28px, 3vw, 48px);
line-height: 0.96;
letter-spacing: -0.055em;
font-weight: 760;
}
.brand p {
margin: 0;
max-width: 340px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.panel {
position: fixed;
top: 20px;
right: 20px;
bottom: 20px;
z-index: 4;
width: 370px;
padding: 20px;
overflow: auto;
border: 1px solid var(--line);
border-radius: 22px;
background: var(--panel);
box-shadow:
0 28px 80px rgba(0, 0, 0, 0.42),
inset 0 1px 0 rgba(255, 255, 255, 0.045);
backdrop-filter: blur(22px) saturate(130%);
scrollbar-width: thin;
scrollbar-color: #294050 transparent;
}
.panel-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
margin-bottom: 18px;
}
.panel-heading h2 {
margin: 0 0 4px;
font-size: 16px;
letter-spacing: -0.02em;
}
.panel-heading p {
margin: 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.draft-badge {
flex: none;
padding: 7px 9px;
border: 1px solid rgba(143, 255, 234, 0.25);
border-radius: 9px;
color: var(--cyan);
background: rgba(143, 255, 234, 0.06);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
font-weight: 700;
}
.section-label {
display: flex;
align-items: center;
justify-content: space-between;
margin: 16px 0 9px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.section-label span:last-child {
color: #6f8997;
font-weight: 600;
letter-spacing: 0.05em;
text-transform: none;
}
.preset-row {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 7px;
}
.preset,
.small-button,
.view-button {
border: 1px solid var(--line);
border-radius: 10px;
color: #bdd0d8;
background: rgba(255, 255, 255, 0.035);
cursor: pointer;
transition:
border-color 150ms ease,
color 150ms ease,
background 150ms ease,
transform 150ms ease;
}
.preset {
min-height: 34px;
padding: 7px 5px;
font-size: 10px;
font-weight: 750;
}
.preset:hover,
.small-button:hover,
.view-button:hover {
border-color: rgba(143, 255, 234, 0.46);
color: var(--text);
background: rgba(143, 255, 234, 0.08);
transform: translateY(-1px);
}
.preset.active {
border-color: rgba(143, 255, 234, 0.58);
color: var(--cyan);
background: rgba(143, 255, 234, 0.1);
}
.matrix-wrap {
padding: 12px;
border: 1px solid var(--line);
border-radius: 16px;
background:
linear-gradient(rgba(255, 255, 255, 0.018), rgba(255, 255, 255, 0.018)),
rgba(2, 9, 16, 0.34);
}
.matrix-grid {
display: grid;
grid-template-columns: repeat(10, minmax(0, 1fr));
gap: 5px;
user-select: none;
}
.cell {
position: relative;
aspect-ratio: 1;
min-width: 0;
padding: 0;
border: 0;
border-radius: 6px;
cursor: pointer;
color: rgba(255, 255, 255, 0.88);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
font-weight: 800;
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.15),
0 2px 7px rgba(0, 0, 0, 0.18);
transition:
transform 120ms ease,
filter 120ms ease,
outline-color 120ms ease;
}
.cell:hover,
.cell:focus-visible {
z-index: 2;
transform: scale(1.12);
filter: brightness(1.16);
outline: 2px solid white;
outline-offset: 2px;
}
.cell.one {
background: linear-gradient(145deg, #36dfca, #13877f);
}
.cell.zero {
background: linear-gradient(145deg, #ff9b72, #a84c38);
}
.cell.impossible {
box-shadow:
inset 0 0 0 2px var(--danger),
0 0 13px rgba(255, 95, 120, 0.6);
}
.cell.impossible::after {
position: absolute;
top: 2px;
right: 3px;
content: "";
width: 4px;
height: 4px;
border-radius: 50%;
background: #fff;
box-shadow: 0 0 6px var(--danger);
}
.cell.disconnected {
outline: 2px solid var(--warning);
outline-offset: 2px;
box-shadow: 0 0 12px rgba(255, 209, 102, 0.5);
}
.cell.impossible.disconnected {
outline-color: var(--warning);
}
.bit-legend {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 12px;
color: var(--muted);
font-size: 10px;
}
.bit-legend span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 9px;
height: 9px;
border-radius: 3px;
}
.swatch.warp {
background: var(--warp);
}
.swatch.weft {
background: var(--weft);
}
.swatch.danger {
background: var(--danger);
}
.swatch.warning {
background: var(--warning);
}
.controls-row {
display: grid;
grid-template-columns: 1fr auto;
gap: 9px;
align-items: end;
}
.field-label {
display: block;
margin-bottom: 7px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
select {
width: 100%;
height: 36px;
padding: 0 34px 0 11px;
border: 1px solid var(--line);
border-radius: 9px;
outline: none;
color: var(--text);
background: #102131;
font-size: 11px;
cursor: pointer;
}
.small-button {
height: 36px;
padding: 0 12px;
font-size: 10px;
font-weight: 750;
}
.view-controls {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 7px;
}
.view-button {
min-height: 34px;
padding: 6px 4px;
font-size: 10px;
font-weight: 750;
}
details {
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 10px;
line-height: 1.6;
}
summary {
padding: 15px 0 4px;
color: #c5d8df;
cursor: pointer;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
details ul {
margin: 8px 0 0;
padding-left: 17px;
}
details li + li {
margin-top: 7px;
}
.status-card {
position: fixed;
left: 28px;
bottom: 26px;
z-index: 3;
width: min(350px, calc(100vw - 40px));
padding: 14px 16px;
border: 1px solid var(--line);
border-radius: 15px;
background: rgba(9, 22, 34, 0.82);
box-shadow: 0 15px 45px rgba(0, 0, 0, 0.3);
backdrop-filter: blur(16px);
pointer-events: none;
}
.status-row {
display: flex;
align-items: center;
gap: 10px;
}
.status-dot {
width: 9px;
height: 9px;
flex: none;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 13px var(--cyan);
}
.status-card.locked .status-dot {
background: var(--danger);
box-shadow: 0 0 13px var(--danger);
}
.status-card.orphan .status-dot {
background: var(--warning);
box-shadow: 0 0 13px var(--warning);
}
.status-card.both .status-dot {
background: linear-gradient(90deg, var(--danger), var(--warning));
box-shadow: 0 0 13px rgba(255, 209, 102, 0.55);
}
#statusTitle {
font-size: 10px;
font-weight: 850;
letter-spacing: 0.13em;
text-transform: uppercase;
}
#statusDetail {
margin: 5px 0 0 19px;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.hint {
position: fixed;
right: 410px;
bottom: 28px;
z-index: 2;
max-width: 300px;
color: rgba(190, 215, 224, 0.58);
font-size: 10px;
line-height: 1.55;
text-align: right;
pointer-events: none;
}
#cellInfo {
color: rgba(212, 235, 241, 0.85);
}
@media (max-width: 800px) {
.brand {
top: 16px;
left: 18px;
}
.brand p {
display: none;
}
.brand h1 {
font-size: 29px;
}
.panel {
top: auto;
left: 10px;
right: 10px;
bottom: 10px;
width: auto;
max-height: 49vh;
padding: 16px;
border-radius: 18px;
}
.status-card {
top: 92px;
bottom: auto;
left: 18px;
width: 285px;
}
.hint {
display: none;
}
.matrix-wrap {
padding: 9px;
}
.matrix-grid {
gap: 4px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive three-dimensional woven textile"></canvas>
<div class="vignette"></div>
<header class="brand">
<div class="eyebrow">Textile systems / 01</div>
<h1>Binary Weave Lab</h1>
<p>
Edit a crossing draft. The raised voxel ribbons rebuild in real time,
while impossible lifts and disconnected fields are flagged.
</p>
</header>
<aside class="panel">
<div class="panel-heading">
<div>
<h2>Crossing matrix</h2>
<p>Click a bit to reverse the yarn on top.</p>
</div>
<div class="draft-badge">10 × 8</div>
</div>
<div class="section-label">
<span>Pattern presets</span>
<span>one repeat</span>
</div>
<div class="preset-row" id="presets">
<button class="preset active" data-preset="plain">Plain</button>
<button class="preset" data-preset="twill">2/2 Twill</button>
<button class="preset" data-preset="basket">Basket</button>
<button class="preset" data-preset="random">Scatter</button>
</div>
<div class="section-label">
<span>Binary draft</span>
<span>1 = warp over · 0 = weft over</span>
</div>
<div class="matrix-wrap">
<div id="matrix" class="matrix-grid" aria-label="Editable binary weave matrix"></div>
<div class="bit-legend">
<span><i class="swatch warp"></i>Warp above</span>
<span><i class="swatch weft"></i>Weft above</span>
</div>
<div class="bit-legend">
<span><i class="swatch danger"></i>Impossible run</span>
<span><i class="swatch warning"></i>Disconnected lift</span>
</div>
</div>
<div class="section-label">
<span>Fabric layout</span>
<span>matrix repeats as a tile</span>
</div>
<div class="controls-row">
<div>
<label class="field-label" for="repeat">Repeat</label>
<select id="repeat">
<option value="1,1">1 × 1 tile</option>
<option value="2,2" selected>2 × 2 tiles</option>
<option value="3,2">3 × 2 tiles</option>
</select>
</div>
<button id="shuffle" class="small-button">Shuffle draft</button>
</div>
<div class="section-label">
<span>View</span>
<span>custom camera controls</span>
</div>
<div class="view-controls">
<button id="resetView" class="view-button">Reset</button>
<button id="topView" class="view-button">Top</button>
<button id="zoomIn" class="view-button">Zoom +</button>
<button id="zoomOut" class="view-button">Zoom −</button>
</div>
<details>
<summary>Simplified construction rules</summary>
<ul>
<li>
<strong>Impossible:</strong> the same yarn cannot remain on top for
three consecutive crossings. Runs of three or more identical bits
are marked in red.
</li>
<li>
<strong>Disconnected:</strong> all raised <strong>1</strong> cells
should form one 8-connected field. Orphaned fields are marked in
amber.
</li>
<li>
This is a visual construction toy, not a cloth-physics or
yarn-tension simulator.
</li>
</ul>
</details>
</aside>
<div id="statusCard" class="status-card" aria-live="polite">
<div class="status-row">
<span class="status-dot"></span>
<strong id="statusTitle">Structure stable</strong>
</div>
<p id="statusDetail">No locked runs · lift field connected</p>
</div>
<div class="hint">
<div id="cellInfo">Click a crossing in the matrix or directly on the cloth.</div>
<div>Drag to orbit · right-drag to pan · wheel to zoom</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 W = 10;
const H = 8;
const PITCH = 0.86;
const TOP = 0.18;
const matrix = Array.from({ length: H }, (_, r) =>
Array.from({ length: W }, (_, c) => (r + c) % 2)
);
const matrixElement = document.querySelector("#matrix");
const cellButtons = [];
const canvas = document.querySelector("#scene");
const statusCard = document.querySelector("#statusCard");
const statusTitle = document.querySelector("#statusTitle");
const statusDetail = document.querySelector("#statusDetail");
const cellInfo = document.querySelector("#cellInfo");
let validation = {
impossible: new Set(),
disconnected: new Set(),
orphanComponents: 0
};
// ------------------------------------------------------------
// Validation
// ------------------------------------------------------------
function validateMatrix() {
const impossible = new Set();
const disconnected = new Set();
// A run of three identical bits means the same yarn stays on top
// through three consecutive crossings.
for (let r = 0; r < H; r++) {
let start = 0;
while (start < W) {
let end = start + 1;
while (
end < W &&
matrix[r][end] === matrix[r][start]
) {
end++;
}
if (end - start >= 3) {
for (let c = start; c < end; c++) {
impossible.add(r * W + c);
}
}
start = end;
}
}
for (let c = 0; c < W; c++) {
let start = 0;
while (start < H) {
let end = start + 1;
while (
end < H &&
matrix[end][c] === matrix[start][c]
) {
end++;
}
if (end - start >= 3) {
for (let r = start; r < end; r++) {
impossible.add(r * W + c);
}
}
start = end;
}
}
// Find 8-connected components of raised 1-cells.
const visited = new Set();
const components = [];
for (let r = 0; r < H; r++) {
for (let c = 0; c < W; c++) {
const startKey = r * W + c;
if (matrix[r][c] !== 1 || visited.has(startKey)) {
continue;
}
const stack = [[r, c]];
const component = [];
visited.add(startKey);
while (stack.length) {
const [cy, cx] = stack.pop();
component.push([cy, cx]);
for (let dy = -1; dy <= 1; dy++) {
for (let dx = -1; dx <= 1; dx++) {
if (dx === 0 && dy === 0) {
continue;
}
const ny = cy + dy;
const nx = cx + dx;
if (
ny < 0 || ny >= H ||
nx < 0 || nx >= W ||
matrix[ny][nx] !== 1
) {
continue;
}
const key = ny * W + nx;
if (!visited.has(key)) {
visited.add(key);
stack.push([ny, nx]);
}
}
}
}
components.push(component);
}
}
// Keep the largest component and mark all orphan components.
let largestIndex = 0;
for (let i = 1; i < components.length; i++) {
if (components[i].length > components[largestIndex].length) {
largestIndex = i;
}
}
components.forEach((component, index) => {
if (index === largestIndex) {
return;
}
component.forEach(([r, c]) => {
disconnected.add(r * W + c);
});
});
return {
impossible,
disconnected,
orphanComponents: Math.max(0, components.length - 1)
};
}
// ------------------------------------------------------------
// Matrix editor
// ------------------------------------------------------------
function buildEditor() {
const fragment = document.createDocumentFragment();
for (let r = 0; r < H; r++) {
for (let c = 0; c < W; c++) {
const button = document.createElement("button");
button.type = "button";
button.className = "cell";
const inspect = () => {
showCellInfo(r, c);
setHoverForBase(r, c);
};
button.addEventListener("mouseenter", inspect);
button.addEventListener("focus", inspect);
button.addEventListener("mouseleave", () => {
cellInfo.textContent =
"Click a crossing in the matrix or directly on the cloth.";
});
button.addEventListener("click", () => {
matrix[r][c] = 1 - matrix[r][c];
refreshDraft();
showCellInfo(r, c);
});
cellButtons.push(button);
fragment.appendChild(button);
}
}
matrixElement.appendChild(fragment);
}
function updateEditor() {
for (let r = 0; r < H; r++) {
for (let c = 0; c < W; c++) {
const key = r * W + c;
const bit = matrix[r][c];
const button = cellButtons[key];
button.textContent = String(bit);
button.classList.toggle("one", bit === 1);
button.classList.toggle("zero", bit === 0);
button.classList.toggle(
"impossible",
validation.impossible.has(key)
);
button.classList.toggle(
"disconnected",
validation.disconnected.has(key)
);
const state = validation.impossible.has(key)
? ", impossible run"
: validation.disconnected.has(key)
? ", disconnected lift"
: "";
button.setAttribute(
"aria-label",
`Row ${r + 1}, column ${c + 1}, ${
bit ? "warp over" : "weft over"
}${state}`
);
}
}
}
function updateStatus() {
const locked = validation.impossible.size;
const orphan = validation.disconnected.size;
statusCard.classList.remove("locked", "orphan", "both");
if (locked && orphan) {
statusCard.classList.add("both");
statusTitle.textContent = "Two structural faults";
statusDetail.textContent =
`${locked} locked crossings · ${orphan} disconnected lift cells`;
} else if (locked) {
statusCard.classList.add("locked");
statusTitle.textContent = "Impossible lift detected";
statusDetail.textContent =
`${locked} crossings are locked by a run of three or more`;
} else if (orphan) {
statusCard.classList.add("orphan");
statusTitle.textContent = "Disconnected lift field";
statusDetail.textContent =
`${orphan} raised cells form ${validation.orphanComponents} orphan ${
validation.orphanComponents === 1 ? "field" : "fields"
}`;
} else {
statusTitle.textContent = "Structure stable";
statusDetail.textContent =
"No locked runs · lift field connected";
}
}
function refreshDraft() {
validation = validateMatrix();
updateEditor();
updateStatus();
rebuildFabric();
}
function showCellInfo(r, c) {
const bit = matrix[r][c];
const key = r * W + c;
const faults = [];
if (validation.impossible.has(key)) {
faults.push("impossible run");
}
if (validation.disconnected.has(key)) {
faults.push("disconnected lift");
}
cellInfo.textContent =
`R${String(r + 1).padStart(2, "0")} / C${String(c + 1).padStart(2, "0")} · ` +
`${bit ? "warp over" : "weft over"}` +
(faults.length ? ` · ${faults.join(" · ")}` : " · click to invert");
}
function applyPreset(name) {
for (let r = 0; r < H; r++) {
for (let c = 0; c < W; c++) {
if (name === "plain") {
matrix[r][c] = (r + c) % 2;
} else if (name === "twill") {
matrix[r][c] = ((r + c) % 4 < 2) ? 1 : 0;
} else if (name === "basket") {
matrix[r][c] =
(Math.floor(c / 2) + Math.floor(r / 2)) % 2 === 0
? 1
: 0;
} else {
matrix[r][c] = Math.random() < 0.5 ? 1 : 0;
}
}
}
document.querySelectorAll(".preset").forEach((button) => {
button.classList.toggle("active", button.dataset.preset === name);
});
refreshDraft();
}
// ------------------------------------------------------------
// Three.js setup
// ------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111c);
scene.fog = new THREE.FogExp2(0x07111c, 0.028);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
120
);
const hemi = new THREE.HemisphereLight(0xbcefff, 0x142132, 1.55);
scene.add(hemi);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.4);
keyLight.position.set(7, 13, 9);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -18;
keyLight.shadow.camera.right = 18;
keyLight.shadow.camera.top = 18;
keyLight.shadow.camera.bottom = -18;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 50;
keyLight.shadow.bias = -0.00025;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0x5cd8ff, 1.25);
fillLight.position.set(-9, 6, -7);
scene.add(fillLight);
const warmLight = new THREE.PointLight(0xff9d71, 22, 30, 2);
warmLight.position.set(-7, 5, 8);
scene.add(warmLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(100, 100),
new THREE.MeshStandardMaterial({
color: 0x07111b,
roughness: 0.98,
metalness: 0
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.64;
floor.receiveShadow = true;
scene.add(floor);
const floorGrid = new THREE.GridHelper(70, 70, 0x173448, 0x102635);
floorGrid.position.y = -0.625;
floorGrid.material.transparent = true;
floorGrid.material.opacity = 0.36;
scene.add(floorGrid);
const fabricGroup = new THREE.Group();
const pedestalGroup = new THREE.Group();
scene.add(fabricGroup, pedestalGroup);
const materials = {
warpOver: new THREE.MeshStandardMaterial({
color: 0x32d6c1,
roughness: 0.44,
metalness: 0.06
}),
warpUnder: new THREE.MeshStandardMaterial({
color: 0x11766f,
roughness: 0.72,
metalness: 0.02
}),
warpMid: new THREE.MeshStandardMaterial({
color: 0x18968b,
roughness: 0.57,
metalness: 0.03
}),
weftOver: new THREE.MeshStandardMaterial({
color: 0xff956b,
roughness: 0.46,
metalness: 0.05
}),
weftUnder: new THREE.MeshStandardMaterial({
color: 0x9d4935,
roughness: 0.74,
metalness: 0.02
}),
weftMid: new THREE.MeshStandardMaterial({
color: 0xcf684a,
roughness: 0.6,
metalness: 0.03
}),
accent: new THREE.MeshStandardMaterial({
color: 0xeafff9,
roughness: 0.35,
metalness: 0.08
}),
invalid: new THREE.MeshBasicMaterial({
color: 0xff5f78,
toneMapped: false
}),
orphan: new THREE.MeshBasicMaterial({
color: 0xffd166,
toneMapped: false
}),
plinth: new THREE.MeshStandardMaterial({
color: 0x102437,
roughness: 0.78,
metalness: 0.08
}),
mat: new THREE.MeshStandardMaterial({
color: 0x0a1724,
roughness: 0.92,
metalness: 0
})
};
const hoverBaseGeometry = new THREE.BoxGeometry(0.72, 0.58, 0.72);
const hoverGeometry = new THREE.EdgesGeometry(hoverBaseGeometry);
hoverBaseGeometry.dispose();
const hoverLine = new THREE.LineSegments(
hoverGeometry,
new THREE.LineBasicMaterial({
color: 0x9ffff0,
transparent: true,
opacity: 0.95,
depthTest: false
})
);
hoverLine.visible = false;
hoverLine.renderOrder = 20;
scene.add(hoverLine);
let repeatX = 2;
let repeatZ = 2;
let globalCols = W * repeatX;
let globalRows = H * repeatZ;
let pickMesh = null;
let pickMap = [];
const baseCellWorld = new Map();
const dummy = new THREE.Object3D();
function clearGroup(group) {
group.traverse((object) => {
if (object.geometry) {
object.geometry.dispose();
}
});
group.clear();
}
function addBatch(descriptors, material, name, castShadow = true) {
if (!descriptors.length) {
return null;
}
const geometry = new THREE.BoxGeometry(1, 1, 1);
const mesh = new THREE.InstancedMesh(
geometry,
material,
descriptors.length
);
mesh.name = name;
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
descriptors.forEach((descriptor, index) => {
dummy.position.set(
descriptor.x,
descriptor.y,
descriptor.z
);
dummy.rotation.set(
descriptor.rx || 0,
descriptor.ry || 0,
descriptor.rz || 0
);
dummy.scale.set(
descriptor.sx,
descriptor.sy,
descriptor.sz
);
dummy.updateMatrix();
mesh.setMatrixAt(index, dummy.matrix);
});
mesh.instanceMatrix.needsUpdate = true;
mesh.computeBoundingSphere();
fabricGroup.add(mesh);
return mesh;
}
function bitAt(globalRow, globalCol) {
return matrix[globalRow % H][globalCol % W];
}
function rebuildPedestal() {
clearGroup(pedestalGroup);
const width = globalCols * PITCH;
const depth = globalRows * PITCH;
const plinth = new THREE.Mesh(
new THREE.BoxGeometry(width + 1.15, 0.22, depth + 1.15),
materials.plinth
);
plinth.position.y = -0.49;
plinth.castShadow = true;
plinth.receiveShadow = true;
pedestalGroup.add(plinth);
const backing = new THREE.Mesh(
new THREE.BoxGeometry(width + 0.72, 0.075, depth + 0.72),
materials.mat
);
backing.position.y = -0.335;
backing.castShadow = true;
backing.receiveShadow = true;
pedestalGroup.add(backing);
// Small registration studs emphasize the voxel construction.
const studGeometry = new THREE.BoxGeometry(0.13, 0.13, 0.13);
for (const sx of [-1, 1]) {
for (const sz of [-1, 1]) {
const stud = new THREE.Mesh(studGeometry, materials.accent);
stud.position.set(
sx * (width * 0.5 + 0.37),
-0.31,
sz * (depth * 0.5 + 0.37)
);
stud.castShadow = true;
pedestalGroup.add(stud);
}
}
}
function rebuildFabric() {
clearGroup(fabricGroup);
baseCellWorld.clear();
pickMap = [];
globalCols = W * repeatX;
globalRows = H * repeatZ;
const batches = {
warpOver: [],
warpUnder: [],
warpMid: [],
weftOver: [],
weftUnder: [],
weftMid: [],
accent: [],
invalid: [],
orphan: [],
pick: []
};
const crossingLength = 0.54;
const crossingWidth = 0.30;
const crossingHeight = 0.22;
// Crossing blocks.
for (let gr = 0; gr < globalRows; gr++) {
const baseRow = gr % H;
for (let gc = 0; gc < globalCols; gc++) {
const baseCol = gc % W;
const key = baseRow * W + baseCol;
const bit = bitAt(gr, gc);
const x = (gc - (globalCols - 1) * 0.5) * PITCH;
const z = (gr - (globalRows - 1) * 0.5) * PITCH;
if (!baseCellWorld.has(key)) {
baseCellWorld.set(key, { x, z });
}
const warpY = bit === 1 ? TOP : -TOP;
const weftY = bit === 1 ? -TOP : TOP;
batches.warpOver.push({
x,
y: warpY,
z,
sx: crossingWidth,
sy: crossingHeight,
sz: crossingLength
});
batches.weftOver.push({
x,
y: weftY,
z,
sx: crossingLength,
sy: crossingHeight,
sz: crossingWidth
});
// The overpass receives a narrow raised highlight.
batches.accent.push({
x,
y: TOP + 0.137,
z,
sx: bit === 1 ? 0.075 : 0.40,
sy: 0.035,
sz: bit === 1 ? 0.40 : 0.075
});
if (validation.impossible.has(key)) {
const markerY = 0.405;
const half = 0.34;
batches.invalid.push(
{
x: x - half,
y: markerY,
z,
sx: 0.035,
sy: 0.035,
sz: 0.70
},
{
x: x + half,
y: markerY,
z,
sx: 0.035,
sy: 0.035,
sz: 0.70
},
{
x,
y: markerY,
z: z - half,
sx: 0.70,
sy: 0.035,
sz: 0.035
},
{
x,
y: markerY,
z: z + half,
sx: 0.70,
sy: 0.035,
sz: 0.035
}
);
}
if (validation.disconnected.has(key)) {
batches.orphan.push({
x,
y: 0.51,
z,
sx: 0.13,
sy: 0.13,
sz: 0.13,
ry: Math.PI * 0.25
});
}
batches.pick.push({
x,
y: 0.12,
z,
sx: 0.68,
sy: 0.75,
sz: 0.68
});
pickMap.push({ row: baseRow, col: baseCol });
}
}
// Vertical warp segments and their stepped height transitions.
const connectorLength = PITCH - crossingLength;
for (let gc = 0; gc < globalCols; gc++) {
const x = (gc - (globalCols - 1) * 0.5) * PITCH;
for (let gr = 0; gr < globalRows - 1; gr++) {
const z0 = (gr - (globalRows - 1) * 0.5) * PITCH;
const z1 = (gr + 1 - (globalRows - 1) * 0.5) * PITCH;
const h0 = bitAt(gr, gc) === 1 ? TOP : -TOP;
const h1 = bitAt(gr + 1, gc) === 1 ? TOP : -TOP;
const average = (h0 + h1) * 0.5;
batches.warpMid.push({
x,
y: average,
z: (z0 + z1) * 0.5,
sx: crossingWidth,
sy: 0.14,
sz: connectorLength
});
if (Math.abs(h0 - h1) > 0.001) {
batches.warpMid.push({
x,
y: (h0 + average) * 0.5,
z: z0 + crossingLength * 0.5,
sx: crossingWidth,
sy: Math.abs(h0 - average) + 0.14,
sz: 0.09
});
batches.warpMid.push({
x,
y: (h1 + average) * 0.5,
z: z1 - crossingLength * 0.5,
sx: crossingWidth,
sy: Math.abs(h1 - average) + 0.14,
sz: 0.09
});
}
}
}
// Horizontal weft segments and their stepped height transitions.
for (let gr = 0; gr < globalRows; gr++) {
const z = (gr - (globalRows - 1) * 0.5) * PITCH;
for (let gc = 0; gc < globalCols - 1; gc++) {
const x0 = (gc - (globalCols - 1) * 0.5) * PITCH;
const x1 = (gc + 1 - (globalCols - 1) * 0.5) * PITCH;
const h0 = bitAt(gr, gc) === 1 ? -TOP : TOP;
const h1 = bitAt(gr + 1, gc) === 1 ? -TOP : TOP;
const average = (h0 + h1) * 0.5;
batches.weftMid.push({
x: (x0 + x1) * 0.5,
y: average,
z,
sx: connectorLength,
sy: 0.14,
sz: crossingWidth
});
if (Math.abs(h0 - h1) > 0.001) {
batches.weftMid.push({
x: x0 + crossingLength * 0.5,
y: (h0 + average) * 0.5,
z,
sx: 0.09,
sy: Math.abs(h0 - average) + 0.14,
sz: crossingWidth
});
batches.weftMid.push({
x: x1 - crossingLength * 0.5,
y: (h1 + average) * 0.5,
z,
sx: 0.09,
sy: Math.abs(h1 - average) + 0.14,
sz: crossingWidth
});
}
}
}
addBatch(batches.warpOver, materials.warpOver, "Warp overpasses");
addBatch(batches.warpUnder, materials.warpUnder, "Warp underpasses");
addBatch(batches.warpMid, materials.warpMid, "Warp connectors");
addBatch(batches.weftOver, materials.weftOver, "Weft overpasses");
addBatch(batches.weftUnder, materials.weftUnder, "Weft underpasses");
addBatch(batches.weftMid, materials.weftMid, "Weft connectors");
addBatch(batches.accent, materials.accent, "Raised ridges", false);
addBatch(batches.invalid, materials.invalid, "Impossible crossings", false);
addBatch(batches.orphan, materials.orphan, "Disconnected lifts", false);
const pickMaterial = new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false,
colorWrite: false
});
pickMesh = addBatch(
batches.pick,
pickMaterial,
"Crossing hit targets",
false
);
rebuildPedestal();
updateViewDistance();
}
// ------------------------------------------------------------
// Custom camera controls
// ------------------------------------------------------------
const cameraState = {
yaw: -0.58,
pitch: 0.76,
distance: 21,
targetYaw: -0.58,
targetPitch: 0.76,
targetDistance: 21,
target: new THREE.Vector3(),
currentTarget: new THREE.Vector3()
};
function updateViewDistance() {
const width = globalCols * PITCH;
const depth = globalRows * PITCH;
cameraState.targetDistance = Math.max(
10.5,
Math.max(width, depth) * 1.16 + 4
);
}
function resetView() {
cameraState.targetYaw = -0.58;
cameraState.targetPitch = 0.76;
cameraState.target.set(0, 0, 0);
updateViewDistance();
}
function updateCamera() {
const smoothing = 0.095;
cameraState.yaw +=
(cameraState.targetYaw - cameraState.yaw) * smoothing;
cameraState.pitch +=
(cameraState.targetPitch - cameraState.pitch) * smoothing;
cameraState.distance +=
(cameraState.targetDistance - cameraState.distance) * smoothing;
cameraState.currentTarget.lerp(
cameraState.target,
smoothing
);
const cosPitch = Math.cos(cameraState.pitch);
const sinPitch = Math.sin(cameraState.pitch);
camera.position.set(
cameraState.currentTarget.x +
cameraState.distance * cosPitch * Math.sin(cameraState.yaw),
cameraState.currentTarget.y +
cameraState.distance * sinPitch,
cameraState.currentTarget.z +
cameraState.distance * cosPitch * Math.cos(cameraState.yaw)
);
camera.lookAt(cameraState.currentTarget);
}
const pointer = {
down: false,
moved: false,
button: 0,
id: null,
startX: 0,
startY: 0,
lastX: 0,
lastY: 0
};
const raycaster = new THREE.Raycaster();
const ndc = new THREE.Vector2();
function pickCrossing(clientX, clientY) {
if (!pickMesh) {
return null;
}
const rect = canvas.getBoundingClientRect();
ndc.x =
((clientX - rect.left) / rect.width) * 2 - 1;
ndc.y =
-((clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(ndc, camera);
const hits = raycaster.intersectObject(pickMesh, false);
if (!hits.length) {
return null;
}
const instanceId = hits[0].instanceId;
return pickMap[instanceId] || null;
}
function setHoverForBase(row, col) {
const position = baseCellWorld.get(row * W + col);
if (!position) {
hoverLine.visible = false;
return;
}
hoverLine.position.set(position.x, 0.02, position.z);
hoverLine.visible = true;
}
canvas.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0 && event.button !== 2) {
return;
}
pointer.down = true;
pointer.moved = false;
pointer.button = event.button;
pointer.id = event.pointerId;
pointer.startX = event.clientX;
pointer.startY = event.clientY;
pointer.lastX = event.clientX;
pointer.lastY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (pointer.down && event.pointerId === pointer.id) {
const dx = event.clientX - pointer.lastX;
const dy = event.clientY - pointer.lastY;
pointer.lastX = event.clientX;
pointer.lastY = event.clientY;
const travel = Math.hypot(
event.clientX - pointer.startX,
event.clientY - pointer.startY
);
if (travel > 4) {
pointer.moved = true;
}
if (pointer.button === 2 || event.shiftKey) {
const factor = cameraState.distance * 0.0011;
const right = new THREE.Vector3(
Math.cos(cameraState.yaw),
0,
-Math.sin(cameraState.yaw)
);
const forward = new THREE.Vector3(
-Math.sin(cameraState.yaw),
0,
-Math.cos(cameraState.yaw)
);
cameraState.target
.addScaledVector(right, -dx * factor)
.addScaledVector(forward, -dy * factor);
cameraState.target.x = THREE.MathUtils.clamp(
cameraState.target.x,
-5,
5
);
cameraState.target.z = THREE.MathUtils.clamp(
cameraState.target.z,
-5,
5
);
} else {
cameraState.targetYaw -= dx * 0.006;
cameraState.targetPitch = THREE.MathUtils.clamp(
cameraState.targetPitch + dy * 0.005,
0.18,
1.42
);
}
return;
}
const hit = pickCrossing(event.clientX, event.clientY);
if (hit) {
setHoverForBase(hit.row, hit.col);
showCellInfo(hit.row, hit.col);
canvas.style.cursor = "pointer";
} else {
hoverLine.visible = false;
canvas.style.cursor = "grab";
}
});
canvas.addEventListener("pointerup", (event) => {
if (!pointer.down || event.pointerId !== pointer.id) {
return;
}
const wasClick =
!pointer.moved &&
pointer.button === 0 &&
Math.hypot(
event.clientX - pointer.startX,
event.clientY - pointer.startY
) <= 4;
pointer.down = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
if (wasClick) {
const hit = pickCrossing(event.clientX, event.clientY);
if (hit) {
matrix[hit.row][hit.col] =
1 - matrix[hit.row][hit.col];
refreshDraft();
showCellInfo(hit.row, hit.col);
}
}
});
canvas.addEventListener("pointercancel", () => {
pointer.down = false;
pointer.moved = false;
});
canvas.addEventListener("wheel", (event) => {
event.preventDefault();
cameraState.targetDistance = THREE.MathUtils.clamp(
cameraState.targetDistance *
Math.exp(event.deltaY * 0.001),
6,
42
);
}, { passive: false });
// ------------------------------------------------------------
// UI events
// ------------------------------------------------------------
document.querySelectorAll(".preset").forEach((button) => {
button.addEventListener("click", () => {
applyPreset(button.dataset.preset);
});
});
document.querySelector("#shuffle").addEventListener("click", () => {
applyPreset("random");
});
document.querySelector("#repeat").addEventListener("change", (event) => {
const [x, z] = event.target.value.split(",").map(Number);
repeatX = x;
repeatZ = z;
rebuildFabric();
});
document.querySelector("#resetView").addEventListener("click", resetView);
document.querySelector("#topView").addEventListener("click", () => {
cameraState.targetYaw = 0;
cameraState.targetPitch = 1.38;
});
document.querySelector("#zoomIn").addEventListener("click", () => {
cameraState.targetDistance = Math.max(
6,
cameraState.targetDistance * 0.88
);
});
document.querySelector("#zoomOut").addEventListener("click", () => {
cameraState.targetDistance = Math.min(
42,
cameraState.targetDistance * 1.12
);
});
window.addEventListener("keydown", (event) => {
if (event.key.toLowerCase() === "r") {
resetView();
} else if (event.key === "+" || event.key === "=") {
cameraState.targetDistance = Math.max(
6,
cameraState.targetDistance * 0.9
);
} else if (event.key === "-") {
cameraState.targetDistance = Math.min(
42,
cameraState.targetDistance * 1.1
);
}
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
});
// ------------------------------------------------------------
// Start
// ------------------------------------------------------------
buildEditor();
refreshDraft();
updateCamera();
renderer.setAnimationLoop(() => {
updateCamera();
if (hoverLine.visible) {
const pulse = 1 + Math.sin(performance.now() * 0.006) * 0.025;
hoverLine.scale.setScalar(pulse);
hoverLine.material.opacity =
0.76 + Math.sin(performance.now() * 0.006) * 0.18;
}
renderer.render(scene, camera);
});
</script>
</body>
</html>
```