Prompt specification
Build or customize the Three.js 3D scene "Dimensional-consistency puzzle board" 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: Dimensional-consistency puzzle board
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/dimensional-consistency-puzzle-board-x1752
Scene Description Prompt:
Let users combine symbolic quantities into candidate formulas and highlight incompatible dimensions; verify simple cases such as speed, area, and density without claiming dimensional analysis proves correctness. Build this with Three.js from cdnjs as a low-poly scene in one self-contained HTML file.
Working Three.js Starter (dimensional-consistency-puzzle-board-x1752):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dimension Forge</title>
<style>
:root {
--ink: #172826;
--muted: #647572;
--paper: #fbfaf4;
--panel: #ffffff;
--line: #dce5df;
--green: #167a68;
--green-soft: #e4f3ed;
--orange: #c66a2b;
--orange-soft: #fff0df;
--red: #c74646;
--red-soft: #fde8e6;
--blue: #315c7a;
--shadow: 0 18px 50px rgba(31, 58, 51, 0.11);
}
* {
box-sizing: border-box;
}
html {
color-scheme: light;
}
body {
margin: 0;
min-width: 320px;
min-height: 100vh;
color: var(--ink);
background:
radial-gradient(circle at 8% 0%, #e4f0e7 0, transparent 32rem),
radial-gradient(circle at 95% 10%, #f8e8d5 0, transparent 30rem),
#f2f4ee;
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
select {
font: inherit;
}
button {
color: inherit;
}
.app {
width: min(1580px, 100%);
margin: 0 auto;
padding: 18px;
}
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
padding: 10px 4px 18px;
}
.brand {
display: flex;
align-items: center;
gap: 14px;
}
.brand-mark {
position: relative;
width: 45px;
height: 45px;
flex: 0 0 auto;
transform: rotate(-8deg);
}
.brand-mark::before,
.brand-mark::after,
.brand-mark span {
position: absolute;
display: block;
content: "";
border-radius: 5px;
box-shadow: 0 5px 14px rgba(24, 61, 52, 0.14);
}
.brand-mark::before {
width: 24px;
height: 24px;
left: 2px;
top: 3px;
background: #55b9aa;
transform: skewY(18deg);
}
.brand-mark::after {
width: 24px;
height: 24px;
right: 2px;
bottom: 2px;
background: #ee9d62;
transform: skewY(-18deg);
}
.brand-mark span {
width: 22px;
height: 22px;
left: 12px;
top: 12px;
background: #6c78a8;
transform: rotate(45deg);
opacity: 0.94;
}
.eyebrow {
margin: 0 0 3px;
color: var(--green);
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(1.45rem, 2.4vw, 2.15rem);
line-height: 1;
letter-spacing: -0.045em;
}
.header-note {
max-width: 490px;
margin: 0;
padding: 11px 15px;
border: 1px solid #e8d7bd;
border-radius: 13px;
color: #72502f;
background: rgba(255, 248, 232, 0.88);
font-size: 0.84rem;
line-height: 1.45;
}
.workspace {
display: grid;
grid-template-columns: minmax(390px, 440px) minmax(0, 1fr);
gap: 18px;
align-items: start;
}
.control-panel {
position: sticky;
top: 18px;
max-height: calc(100vh - 36px);
overflow: auto;
padding: 20px;
border: 1px solid rgba(207, 219, 212, 0.9);
border-radius: 23px;
background: rgba(255, 255, 255, 0.94);
box-shadow: var(--shadow);
scrollbar-width: thin;
scrollbar-color: #c9d6cf transparent;
}
.section {
padding-bottom: 20px;
margin-bottom: 20px;
border-bottom: 1px solid var(--line);
}
.section:last-child {
padding-bottom: 0;
margin-bottom: 0;
border-bottom: 0;
}
.section-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 11px;
}
.section-heading h2 {
margin: 0;
font-size: 0.95rem;
letter-spacing: -0.015em;
}
.step {
display: inline-grid;
width: 25px;
height: 25px;
place-items: center;
margin-right: 8px;
border-radius: 8px;
color: white;
background: var(--ink);
font-size: 0.73rem;
font-weight: 800;
vertical-align: 1px;
}
.hint {
margin: 0 0 12px;
color: var(--muted);
font-size: 0.79rem;
line-height: 1.45;
}
.quantity-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px;
}
.quantity-card {
display: grid;
grid-template-columns: 34px minmax(0, 1fr);
grid-template-rows: auto auto;
gap: 1px 8px;
min-height: 60px;
padding: 9px;
text-align: left;
border: 1px solid var(--line);
border-radius: 12px;
background: #fbfcf9;
cursor: pointer;
transition:
transform 120ms ease,
border-color 120ms ease,
box-shadow 120ms ease;
}
.quantity-card:hover {
z-index: 1;
transform: translateY(-2px);
border-color: #80b8a9;
box-shadow: 0 7px 15px rgba(44, 92, 78, 0.09);
}
.quantity-card:active {
transform: translateY(0);
}
.quantity-card .symbol {
grid-row: 1 / 3;
display: grid;
width: 34px;
height: 34px;
place-items: center;
align-self: center;
border-radius: 9px;
color: #24594f;
background: #e1f0e9;
font-family: Georgia, "Times New Roman", serif;
font-size: 1.23rem;
font-weight: 700;
}
.quantity-card .name {
overflow: hidden;
font-size: 0.79rem;
font-weight: 750;
text-overflow: ellipsis;
white-space: nowrap;
}
.quantity-card .dims {
overflow: hidden;
color: var(--muted);
font-size: 0.66rem;
text-overflow: ellipsis;
white-space: nowrap;
}
.number-row {
display: flex;
flex-wrap: wrap;
gap: 7px;
margin-top: 11px;
}
.number-button {
padding: 6px 10px;
border: 1px solid var(--line);
border-radius: 9px;
color: #425955;
background: #f7f9f6;
font-size: 0.75rem;
font-weight: 750;
cursor: pointer;
}
.number-button:hover {
border-color: #8cb6a9;
background: #eef7f2;
}
.token-display {
display: flex;
min-height: 94px;
align-items: center;
flex-wrap: wrap;
gap: 6px;
padding: 13px;
overflow: auto;
border: 1px dashed #bdccc4;
border-radius: 15px;
background:
linear-gradient(#fbfcf9, #fbfcf9) padding-box,
repeating-linear-gradient(
45deg,
transparent 0 8px,
rgba(45, 93, 78, 0.03) 8px 10px
);
}
.token-placeholder {
width: 100%;
color: #8a9994;
font-size: 0.82rem;
text-align: center;
}
.token {
position: relative;
display: inline-flex;
min-width: 48px;
min-height: 48px;
align-items: center;
justify-content: center;
gap: 5px;
padding: 7px 10px;
border: 1px solid #b7cec3;
border-radius: 11px;
color: #18483e;
background: #e3f1eb;
cursor: pointer;
transition:
transform 120ms ease,
border-color 120ms ease,
background 120ms ease;
}
.token:hover {
transform: translateY(-2px);
border-color: #5a9d8c;
}
.token::after {
position: absolute;
top: 3px;
right: 5px;
color: #6f8b82;
content: "×";
font-size: 0.65rem;
opacity: 0;
transition: opacity 120ms ease;
}
.token:hover::after {
opacity: 1;
}
.token.incompatible {
border-color: #db6962;
color: #8d2727;
background: var(--red-soft);
box-shadow: 0 0 0 3px rgba(199, 70, 70, 0.1);
}
.token-symbol {
font-family: Georgia, "Times New Roman", serif;
font-size: 1.25rem;
font-weight: 700;
}
.token-unit {
color: inherit;
font-size: 0.63rem;
opacity: 0.7;
}
.operator {
min-width: 29px;
color: #536862;
font-family: Georgia, "Times New Roman", serif;
font-size: 1.3rem;
font-weight: 700;
text-align: center;
}
.builder-toolbar {
display: flex;
flex-wrap: wrap;
gap: 7px;
margin-top: 10px;
}
.tool-button,
.action-button,
.primary-button {
border: 1px solid var(--line);
border-radius: 10px;
background: white;
cursor: pointer;
transition:
transform 120ms ease,
border-color 120ms ease,
background 120ms ease;
}
.tool-button:hover,
.action-button:hover,
.primary-button:hover {
transform: translateY(-1px);
border-color: #8cb6a9;
}
.tool-button {
min-width: 39px;
height: 37px;
color: #294e45;
font-family: Georgia, "Times New Roman", serif;
font-size: 1.15rem;
font-weight: 700;
}
.tool-button:hover {
background: #edf6f1;
}
.actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 12px;
}
.action-button,
.primary-button {
padding: 9px 12px;
font-size: 0.76rem;
font-weight: 750;
}
.action-button.danger {
color: #99413b;
background: #fff8f6;
}
.primary-button {
border-color: var(--ink);
color: white;
background: var(--ink);
}
.primary-button:hover {
background: #27433d;
}
.select-label {
display: block;
margin: 15px 0 7px;
color: var(--muted);
font-size: 0.72rem;
font-weight: 750;
letter-spacing: 0.05em;
text-transform: uppercase;
}
select {
width: 100%;
padding: 10px 12px;
border: 1px solid var(--line);
border-radius: 10px;
color: var(--ink);
background: #fbfcf9;
font-size: 0.82rem;
outline: none;
}
select:focus {
border-color: #5c9d8b;
box-shadow: 0 0 0 3px rgba(55, 129, 108, 0.1);
}
.result-card {
margin-top: 15px;
padding: 14px;
border: 1px solid var(--line);
border-radius: 14px;
background: #fafbf8;
}
.result-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 11px;
}
.result-title strong {
font-size: 0.82rem;
}
.status-pill {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 5px 8px;
border-radius: 999px;
font-size: 0.65rem;
font-weight: 800;
white-space: nowrap;
}
.status-pill::before {
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
content: "";
}
.status-pill.good {
color: var(--green);
background: var(--green-soft);
}
.status-pill.bad {
color: var(--red);
background: var(--red-soft);
}
.status-pill.warn {
color: var(--orange);
background: var(--orange-soft);
}
.status-pill.neutral {
color: #6d7e79;
background: #e9eeeb;
}
.dimension-chips {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
margin: 10px 0;
}
.dimension-chip {
display: flex;
min-height: 48px;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 9px 10px;
border: 1px solid #d8e3dc;
border-radius: 10px;
background: white;
}
.dimension-chip small {
color: var(--muted);
font-family: Georgia, "Times New Roman", serif;
font-size: 1rem;
font-weight: 700;
}
.dimension-chip strong {
font-size: 0.83rem;
}
.dimension-chip.zero {
opacity: 0.48;
}
.dimension-chip.negative {
color: #a0473f;
border-color: #edc9c4;
background: #fff9f7;
}
.dimension-chip.positive {
color: #176f60;
border-color: #bcd9ce;
background: #f2faf6;
}
.dimension-summary {
color: #344e48;
font-family: Georgia, "Times New Roman", serif;
font-size: 1rem;
font-weight: 700;
}
.comparison {
min-height: 42px;
margin-top: 11px;
padding-top: 10px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 0.76rem;
line-height: 1.45;
}
.comparison.good {
color: var(--green);
}
.comparison.warn {
color: var(--orange);
}
.comparison.bad {
color: var(--red);
}
.comparison small {
display: block;
margin-top: 3px;
color: var(--muted);
}
.error-box {
display: none;
margin-top: 10px;
padding: 9px 11px;
border: 1px solid #efc1bc;
border-radius: 10px;
color: #943631;
background: var(--red-soft);
font-size: 0.76rem;
line-height: 1.4;
}
.error-box.visible {
display: block;
}
.reference-list {
display: grid;
gap: 8px;
}
.reference-card {
display: grid;
grid-template-columns: 38px minmax(0, 1fr) auto;
align-items: center;
gap: 10px;
width: 100%;
padding: 10px;
text-align: left;
border: 1px solid var(--line);
border-radius: 12px;
background: #fbfcf9;
cursor: pointer;
transition:
transform 120ms ease,
border-color 120ms ease,
background 120ms ease;
}
.reference-card:hover,
.reference-card.active {
transform: translateX(2px);
border-color: #80ad9f;
background: #f0f8f3;
}
.reference-icon {
display: grid;
width: 38px;
height: 38px;
place-items: center;
border-radius: 10px;
color: white;
font-family: Georgia, "Times New Roman", serif;
font-size: 1.05rem;
font-weight: 700;
}
.reference-icon.speed {
background: #4a8fbd;
}
.reference-icon.area {
background: #4ba58c;
}
.reference-icon.density {
background: #c77a49;
}
.reference-name {
display: block;
margin-bottom: 2px;
font-size: 0.8rem;
font-weight: 800;
}
.reference-formula {
display: block;
color: var(--muted);
font-size: 0.69rem;
}
.reference-dims {
color: #39554d;
font-family: Georgia, "Times New Roman", serif;
font-size: 0.76rem;
font-weight: 700;
white-space: nowrap;
}
.reference-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-top: 10px;
}
.reference-status {
color: var(--green);
font-size: 0.69rem;
font-weight: 750;
}
.science-note {
padding: 12px;
border-left: 3px solid #dfa45f;
border-radius: 3px 11px 11px 3px;
color: #705538;
background: #fff8e9;
font-size: 0.75rem;
line-height: 1.5;
}
.science-note strong {
color: #5a4329;
}
.scene-panel {
position: relative;
height: calc(100vh - 112px);
min-height: 650px;
overflow: hidden;
border: 1px solid rgba(196, 211, 202, 0.95);
border-radius: 25px;
background: #e7eee8;
box-shadow: var(--shadow);
}
#viewport {
position: absolute;
inset: 0;
}
#viewport canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
outline: none;
touch-action: none;
}
.scene-top {
position: absolute;
z-index: 2;
top: 20px;
left: 22px;
right: 22px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 18px;
pointer-events: none;
}
.scene-kicker {
margin: 0 0 6px;
color: #3f655a;
font-size: 0.68rem;
font-weight: 850;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.scene-title {
margin: 0;
font-size: clamp(1.25rem, 2vw, 1.9rem);
letter-spacing: -0.04em;
}
.scene-subtitle {
max-width: 440px;
margin: 7px 0 0;
color: #587068;
font-size: 0.78rem;
line-height: 1.45;
}
.scene-actions {
display: flex;
gap: 8px;
pointer-events: auto;
}
.scene-button {
padding: 8px 11px;
border: 1px solid rgba(110, 139, 127, 0.38);
border-radius: 10px;
color: #335a50;
background: rgba(255, 255, 255, 0.74);
backdrop-filter: blur(8px);
font-size: 0.72rem;
font-weight: 750;
cursor: pointer;
}
.scene-button:hover {
background: rgba(255, 255, 255, 0.95);
}
.scene-bottom {
position: absolute;
z-index: 2;
right: 20px;
bottom: 18px;
left: 20px;
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 14px;
pointer-events: none;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 7px;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 9px;
border: 1px solid rgba(110, 139, 127, 0.25);
border-radius: 999px;
color: #466159;
background: rgba(255, 255, 255, 0.73);
backdrop-filter: blur(8px);
font-size: 0.67rem;
font-weight: 750;
}
.legend-dot {
width: 8px;
height: 8px;
border-radius: 3px;
}
.legend-dot.length {
background: #3ba897;
}
.legend-dot.mass {
background: #dc8251;
}
.legend-dot.time {
background: #6e70a8;
}
.camera-hint {
color: #587068;
font-size: 0.68rem;
text-align: right;
}
.scene-panel.pulse {
animation: scene-pulse 400ms ease;
}
@keyframes scene-pulse {
50% {
box-shadow:
0 0 0 5px rgba(73, 153, 133, 0.16),
var(--shadow);
}
}
@media (max-width: 980px) {
.workspace {
grid-template-columns: 1fr;
}
.control-panel {
position: static;
max-height: none;
}
.scene-panel {
height: 620px;
min-height: 520px;
}
}
@media (max-width: 620px) {
.app {
padding: 10px;
}
.topbar {
align-items: flex-start;
flex-direction: column;
gap: 12px;
}
.header-note {
font-size: 0.76rem;
}
.control-panel {
padding: 15px;
border-radius: 18px;
}
.scene-panel {
height: 510px;
min-height: 510px;
border-radius: 18px;
}
.scene-top {
top: 15px;
left: 15px;
right: 15px;
}
.scene-subtitle {
display: none;
}
.scene-bottom {
right: 13px;
bottom: 13px;
left: 13px;
}
.camera-hint {
display: none;
}
.quantity-grid {
grid-template-columns: 1fr 1fr;
}
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
scroll-behavior: auto !important;
transition-duration: 0.01ms !important;
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
}
}
</style>
</head>
<body>
<div class="app">
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"><span></span></div>
<div>
<p class="eyebrow">Interactive dimensional lab</p>
<h1>Dimension Forge</h1>
</div>
</div>
<p class="header-note">
Dimensional consistency is a <strong>necessary filter</strong>, not proof.
A correct-looking formula can still be physically wrong.
</p>
</header>
<main class="workspace">
<aside class="control-panel" aria-label="Formula builder">
<section class="section">
<div class="section-heading">
<h2><span class="step">1</span>Choose quantities</h2>
</div>
<p class="hint">
Click a quantity to add it to the formula. Consecutive quantities
are multiplied automatically.
</p>
<div id="quantityGrid" class="quantity-grid"></div>
<div class="number-row" aria-label="Dimensionless numbers">
<button class="number-button" data-number="one">1</button>
<button class="number-button" data-number="two">2</button>
<button class="number-button" data-number="three">3</button>
<button class="number-button" data-number="negOne">−1</button>
</div>
</section>
<section class="section">
<div class="section-heading">
<h2><span class="step">2</span>Build a candidate</h2>
</div>
<p class="hint">
Add an operator between terms. Click a quantity token to remove it.
</p>
<div
id="tokenDisplay"
class="token-display"
aria-label="Candidate formula"
aria-live="polite"
></div>
<div class="builder-toolbar" aria-label="Formula operators">
<button class="tool-button" data-op="*" title="Multiply">×</button>
<button class="tool-button" data-op="/" title="Divide">÷</button>
<button class="tool-button" data-op="+" title="Add">+</button>
<button class="tool-button" data-op="-" title="Subtract">−</button>
<button class="tool-button" data-op="^" title="Exponent">^</button>
</div>
<div class="actions">
<button id="clearButton" class="action-button">Clear</button>
<button id="mismatchButton" class="action-button danger">
Try incompatible terms
</button>
</div>
<label class="select-label" for="targetSelect">
Compare dimensions with
</label>
<select id="targetSelect">
<option value="">No reference quantity</option>
</select>
</section>
<section class="section">
<div class="section-heading">
<h2><span class="step">3</span>Inspect the result</h2>
</div>
<div class="result-card">
<div class="result-title">
<strong>Dimension signature</strong>
<span id="statusPill" class="status-pill neutral">Waiting</span>
</div>
<div id="dimensionSummary" class="dimension-summary">
Add quantities to begin.
</div>
<div id="dimensionChips" class="dimension-chips"></div>
<div id="comparison" class="comparison">
Select a reference quantity to compare the dimension signature.
</div>
<div id="errorBox" class="error-box"></div>
</div>
<div class="actions">
<button id="checkButton" class="primary-button">Check dimensions</button>
</div>
</section>
<section class="section">
<div class="section-heading">
<h2>Simple reference checks</h2>
</div>
<p class="hint">
Load a canonical expression and inspect its dimensions.
</p>
<div id="referenceList" class="reference-list"></div>
<div class="reference-footer">
<span id="referenceStatus" class="reference-status">
Calculator checks have not been run.
</span>
<button id="runReferencesButton" class="action-button">
Run checks
</button>
</div>
</section>
<section class="section">
<div class="science-note">
<strong>Important:</strong> dimensional analysis cannot prove that
a formula is physically correct. Many incorrect formulas have
valid dimensions. Confirm candidates using measurements, limiting
cases, conservation laws, and physical reasoning.
</div>
</section>
</aside>
<section id="scenePanel" class="scene-panel" aria-label="Low-poly dimension scene">
<div id="viewport"></div>
<div class="scene-top">
<div>
<p class="scene-kicker">The dimension bench</p>
<h2 class="scene-title">Candidate geometry</h2>
<p class="scene-subtitle">
The towers respond to the exponents of length, mass, and time.
Red indicates an internal dimensional conflict.
</p>
</div>
<div class="scene-actions">
<button id="resetViewButton" class="scene-button">Reset view</button>
</div>
</div>
<div class="scene-bottom">
<div class="legend" aria-label="Dimension legend">
<span class="legend-item">
<span class="legend-dot length"></span> Length · L
</span>
<span class="legend-item">
<span class="legend-dot mass"></span> Mass · M
</span>
<span class="legend-item">
<span class="legend-dot time"></span> Time · T
</span>
</div>
<div class="camera-hint">
Drag to orbit · Wheel to zoom · Right-drag to pan
</div>
</div>
</section>
</main>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Quantity catalogue. Dimensions are exponents of [L, M, T].
// ------------------------------------------------------------
const quantities = {
distance: {
symbol: "d",
name: "distance",
unit: "m",
dims: [1, 0, 0]
},
time: {
symbol: "t",
name: "time",
unit: "s",
dims: [0, 0, 1]
},
mass: {
symbol: "m",
name: "mass",
unit: "kg",
dims: [0, 1, 0]
},
speed: {
symbol: "v",
name: "speed",
unit: "m/s",
dims: [1, 0, -1]
},
acceleration: {
symbol: "a",
name: "acceleration",
unit: "m/s²",
dims: [1, 0, -2]
},
area: {
symbol: "A",
name: "area",
unit: "m²",
dims: [2, 0, 0]
},
volume: {
symbol: "V",
name: "volume",
unit: "m³",
dims: [3, 0, 0]
},
density: {
symbol: "ρ",
name: "density",
unit: "kg/m³",
dims: [-3, 1, 0]
},
force: {
symbol: "F",
name: "force",
unit: "N",
dims: [1, 1, -2]
},
energy: {
symbol: "E",
name: "energy",
unit: "J",
dims: [2, 1, -2]
},
power: {
symbol: "P",
name: "power",
unit: "W",
dims: [2, 1, -3]
},
pressure: {
symbol: "p",
name: "pressure",
unit: "Pa",
dims: [-1, 1, -2]
},
frequency: {
symbol: "f",
name: "frequency",
unit: "Hz",
dims: [0, 0, -1]
},
one: {
symbol: "1",
name: "one",
unit: "",
dims: [0, 0, 0],
scalar: true
},
two: {
symbol: "2",
name: "two",
unit: "",
dims: [0, 0, 0],
scalar: true
},
three: {
symbol: "3",
name: "three",
unit: "",
dims: [0, 0, 0],
scalar: true
},
negOne: {
symbol: "−1",
name: "negative one",
unit: "",
dims: [0, 0, 0],
scalar: true
}
};
const dimensionBases = ["L", "M", "T"];
const dimensionNames = ["length", "mass", "time"];
const operatorSymbols = {
"*": "×",
"/": "÷",
"+": "+",
"-": "−",
"^": "^"
};
const state = {
tokens: [],
target: ""
};
const quantityGrid = document.querySelector("#quantityGrid");
const tokenDisplay = document.querySelector("#tokenDisplay");
const targetSelect = document.querySelector("#targetSelect");
const statusPill = document.querySelector("#statusPill");
const dimensionSummary = document.querySelector("#dimensionSummary");
const dimensionChips = document.querySelector("#dimensionChips");
const comparison = document.querySelector("#comparison");
const errorBox = document.querySelector("#errorBox");
const superscript = {
"-": "⁻",
0: "⁰",
1: "¹",
2: "²",
3: "³",
4: "⁴",
5: "⁵",
6: "⁶",
7: "⁷",
8: "⁸",
9: "⁹"
};
function superscriptNumber(value) {
return String(value)
.split("")
.map(character => superscript[character] ?? character)
.join("");
}
function prettyDimensions(dims) {
const parts = [];
dimensionBases.forEach((base, index) => {
if (dims[index] !== 0) {
parts.push(`${base}${superscriptNumber(dims[index])}`);
}
});
return parts.length ? parts.join(" · ") : "dimensionless";
}
function sameDimensions(a, b) {
return a.every((value, index) => value === b[index]);
}
function quantityToken(key) {
return { type: "quantity", key };
}
function operatorToken(value) {
return { type: "operator", value };
}
// ------------------------------------------------------------
// Build palette and reference controls.
// ------------------------------------------------------------
const physicalQuantityKeys = Object.keys(quantities).filter(
key => !quantities[key].scalar
);
quantityGrid.innerHTML = physicalQuantityKeys
.map(key => {
const quantity = quantities[key];
return `
<button
class="quantity-card"
type="button"
data-quantity="${key}"
title="Add ${quantity.name} (${prettyDimensions(quantity.dims)})"
>
<span class="symbol">${quantity.symbol}</span>
<span class="name">${quantity.name}</span>
<span class="dims">
${prettyDimensions(quantity.dims)}${quantity.unit ? " · " + quantity.unit : ""}
</span>
</button>
`;
})
.join("");
targetSelect.insertAdjacentHTML(
"beforeend",
physicalQuantityKeys
.map(key => {
const quantity = quantities[key];
return `
<option value="${key}">
${quantity.name} — ${prettyDimensions(quantity.dims)}
</option>
`;
})
.join("")
);
const referenceCases = [
{
id: "speed",
name: "Speed",
icon: "v",
formula: "distance ÷ time",
expected: [1, 0, -1],
tokens: [
quantityToken("distance"),
operatorToken("/"),
quantityToken("time")
],
target: "speed"
},
{
id: "area",
name: "Area",
icon: "A",
formula: "distance × distance",
expected: [2, 0, 0],
tokens: [
quantityToken("distance"),
operatorToken("*"),
quantityToken("distance")
],
target: "area"
},
{
id: "density",
name: "Density",
icon: "ρ",
formula: "mass ÷ volume",
expected: [-3, 1, 0],
tokens: [
quantityToken("mass"),
operatorToken("/"),
quantityToken("volume")
],
target: "density"
}
];
document.querySelector("#referenceList").innerHTML =
referenceCases
.map(
reference => `
<button
class="reference-card"
type="button"
data-reference="${reference.id}"
>
<span class="reference-icon ${reference.id}">
${reference.icon}
</span>
<span>
<span class="reference-name">${reference.name}</span>
<span class="reference-formula">${reference.formula}</span>
</span>
<span class="reference-dims">
${prettyDimensions(reference.expected)}
</span>
</button>
`
)
.join("");
// ------------------------------------------------------------
// Dimensional expression parser.
//
// Rules implemented:
// - multiplication/division combine exponents;
// - addition/subtraction require equal dimensions;
// - exponents must be dimensionless whole numbers.
// ------------------------------------------------------------
function evaluateTokens(tokens) {
const badIndices = new Set();
if (!tokens.length) {
return {
empty: true,
valid: false,
error: "",
dims: null,
incompatible: [],
badIndices
};
}
for (let index = 0; index < tokens.length; index += 1) {
const expectedType = index % 2 === 0 ? "quantity" : "operator";
if (tokens[index].type !== expectedType) {
badIndices.add(index);
return {
empty: false,
valid: false,
error: "The expression must alternate between quantities and operators.",
dims: null,
incompatible: [],
badIndices
};
}
}
let cursor = 0;
const incompatible = [];
function parseFactor() {
const token = tokens[cursor];
if (!token || token.type !== "quantity") {
throw Object.assign(new Error("A quantity is missing."), {
tokenIndex: cursor
});
}
const quantity = quantities[token.key];
const tokenIndex = cursor;
cursor += 1;
let dims = [...quantity.dims];
const indices = [tokenIndex];
if (
tokens[cursor]?.type === "operator" &&
tokens[cursor].value === "^"
) {
cursor += 1;
const exponentToken = tokens[cursor];
if (!exponentToken || exponentToken.type !== "quantity") {
throw Object.assign(
new Error("An exponent must be a dimensionless whole number."),
{ tokenIndex: cursor }
);
}
const exponentQuantity = quantities[exponentToken.key];
const exponentIndex = cursor;
cursor += 1;
if (!exponentQuantity.scalar) {
badIndices.add(exponentIndex);
throw Object.assign(
new Error("The exponent must be dimensionless."),
{ tokenIndex: exponentIndex }
);
}
const exponent = Number(
exponentQuantity.symbol.replace("−", "-")
);
if (!Number.isInteger(exponent)) {
badIndices.add(exponentIndex);
throw Object.assign(
new Error("The exponent must be a whole number."),
{ tokenIndex: exponentIndex }
);
}
dims = dims.map(value => value * exponent);
indices.push(exponentIndex);
}
return { dims, indices };
}
function parseTerm() {
let left = parseFactor();
while (
tokens[cursor]?.type === "operator" &&
(tokens[cursor].value === "*" || tokens[cursor].value === "/")
) {
const operator = tokens[cursor].value;
cursor += 1;
const right = parseFactor();
left = {
dims: left.dims.map((value, index) =>
operator === "*"
? value + right.dims[index]
: value - right.dims[index]
),
indices: [...left.indices, ...right.indices]
};
}
return left;
}
function parseExpression() {
let left = parseTerm();
while (
tokens[cursor]?.type === "operator" &&
(tokens[cursor].value === "+" || tokens[cursor].value === "-")
) {
const operator = tokens[cursor].value;
cursor += 1;
const right = parseTerm();
const compatible = sameDimensions(left.dims, right.dims);
if (!compatible) {
incompatible.push({
leftDims: [...left.dims],
rightDims: [...right.dims],
leftIndices: [...left.indices],
rightIndices: [...right.indices]
});
left.indices.forEach(index => badIndices.add(index));
right.indices.forEach(index => badIndices.add(index));
}
left = {
dims: left.dims.map((value, index) =>
operator === "+"
? value + right.dims[index]
: value - right.dims[index]
),
indices: [...left.indices, ...right.indices]
};
}
return left;
}
try {
const node = parseExpression();
if (cursor !== tokens.length) {
throw Object.assign(
new Error("The expression could not be fully parsed."),
{ tokenIndex: cursor }
);
}
return {
empty: false,
valid: incompatible.length === 0,
error: "",
dims: node.dims,
incompatible,
badIndices
};
} catch (error) {
if (Number.isInteger(error.tokenIndex)) {
badIndices.add(error.tokenIndex);
}
return {
empty: false,
valid: false,
error: error.message,
dims: null,
incompatible,
badIndices
};
}
}
// ------------------------------------------------------------
// UI rendering.
// ------------------------------------------------------------
function formatFormula(tokens) {
return tokens
.map(token => {
if (token.type === "operator") {
return operatorSymbols[token.value];
}
return quantities[token.key].symbol;
})
.join(" ");
}
function renderTokens(result) {
if (!state.tokens.length) {
tokenDisplay.innerHTML = `
<div class="token-placeholder">
Your candidate formula will appear here.
</div>
`;
return;
}
tokenDisplay.innerHTML = state.tokens
.map((token, index) => {
if (token.type === "operator") {
return `
<span class="operator" aria-hidden="true">
${operatorSymbols[token.value]}
</span>
`;
}
const quantity = quantities[token.key];
const incompatible = result.badIndices.has(index);
return `
<button
class="token ${incompatible ? "incompatible" : ""}"
type="button"
data-token-index="${index}"
title="Remove ${quantity.name}"
aria-label="Remove ${quantity.name}"
>
<span class="token-symbol">${quantity.symbol}</span>
${quantity.unit ? `<span class="token-unit">${quantity.unit}</span>` : ""}
</button>
`;
})
.join("");
}
function renderDimensionChips(dims) {
if (!dims) {
dimensionChips.innerHTML = `
<div class="dimension-chip zero"><small>L</small><strong>—</strong></div>
<div class="dimension-chip zero"><small>M</small><strong>—</strong></div>
<div class="dimension-chip zero"><small>T</small><strong>—</strong></div>
`;
return;
}
dimensionChips.innerHTML = dimensionBases
.map((base, index) => {
const exponent = dims[index];
const kind =
exponent > 0 ? "positive" : exponent < 0 ? "negative" : "zero";
return `
<div class="dimension-chip ${kind}">
<small>${base}</small>
<strong>${exponent}</strong>
</div>
`;
})
.join("");
}
function updateUI() {
const result = evaluateTokens(state.tokens);
const target = state.target ? quantities[state.target] : null;
renderTokens(result);
renderDimensionChips(result.valid ? result.dims : null);
errorBox.classList.toggle("visible", Boolean(result.error));
errorBox.textContent = result.error;
let statusKind = "neutral";
let statusText = "Waiting";
let summary = "Add quantities to begin.";
let comparisonHTML = `
Select a reference quantity to compare the dimension signature.
`;
if (!result.empty && result.error) {
statusKind = "bad";
statusText = "Invalid expression";
summary = "The candidate needs another quantity or a valid operator.";
comparisonHTML = "Resolve the parsing issue before comparing dimensions.";
} else if (!result.empty && !result.valid) {
statusKind = "bad";
statusText = "Incompatible dimensions";
summary = "The highlighted terms have different dimensions.";
comparisonHTML = `
<strong>Cannot combine these terms:</strong>
${result.incompatible
.map(
mismatch =>
`${prettyDimensions(mismatch.leftDims)} versus ${prettyDimensions(mismatch.rightDims)}`
)
.join("; ")}.
Terms joined by + or − must have matching dimensions.
`;
} else if (!result.empty && result.valid) {
summary = prettyDimensions(result.dims);
if (!target) {
statusKind = "good";
statusText = "Compatible";
comparisonHTML = `
The candidate is internally dimensionally consistent.
Choose a reference to compare its signature.
`;
} else if (sameDimensions(result.dims, target.dims)) {
statusKind = "good";
statusText = "Reference match";
comparisonHTML = `
✓ The candidate matches <strong>${target.name}</strong>'s dimensions.
<small>
This is a dimension match only. It does not prove that the
physical formula is correct.
</small>
`;
} else {
statusKind = "warn";
statusText = "Different dimensions";
comparisonHTML = `
The candidate has <strong>${prettyDimensions(result.dims)}</strong>,
while ${target.name} requires
<strong>${prettyDimensions(target.dims)}</strong>.
<small>The expression is internally consistent but does not match the reference.</small>
`;
}
}
statusPill.className = `status-pill ${statusKind}`;
statusPill.textContent = statusText;
dimensionSummary.textContent = summary;
comparison.className = `comparison ${statusKind}`;
comparison.innerHTML = comparisonHTML;
updateScene(result, target);
updateActiveReference();
}
function addQuantity(key) {
if (!quantities[key]) return;
if (!state.tokens.length) {
state.tokens.push(quantityToken(key));
} else if (state.tokens.at(-1).type === "operator") {
state.tokens.push(quantityToken(key));
} else {
state.tokens.push(operatorToken("*"));
state.tokens.push(quantityToken(key));
}
updateUI();
}
function addOperator(value) {
if (!state.tokens.length) return;
if (state.tokens.at(-1).type === "operator") {
state.tokens[state.tokens.length - 1] = operatorToken(value);
} else {
state.tokens.push(operatorToken(value));
}
updateUI();
}
function removeQuantityAt(index) {
const token = state.tokens[index];
if (!token || token.type !== "quantity") return;
state.tokens.splice(index, 1);
if (index > 0 && state.tokens[index - 1]?.type === "operator") {
state.tokens.splice(index - 1, 1);
}
while (
state.tokens.length &&
state.tokens.at(-1).type === "operator"
) {
state.tokens.pop();
}
updateUI();
}
function setFormula(tokens, target = "") {
state.tokens = tokens.map(token => ({ ...token }));
state.target = target;
targetSelect.value = target;
updateUI();
}
quantityGrid.addEventListener("click", event => {
const button = event.target.closest("[data-quantity]");
if (button) addQuantity(button.dataset.quantity);
});
document.querySelectorAll("[data-number]").forEach(button => {
button.addEventListener("click", () => {
addQuantity(button.dataset.number);
});
});
document.querySelectorAll("[data-op]").forEach(button => {
button.addEventListener("click", () => {
addOperator(button.dataset.op);
});
});
tokenDisplay.addEventListener("click", event => {
const token = event.target.closest("[data-token-index]");
if (token) {
removeQuantityAt(Number(token.dataset.tokenIndex));
}
});
targetSelect.addEventListener("change", () => {
state.target = targetSelect.value;
updateUI();
});
document.querySelector("#clearButton").addEventListener("click", () => {
state.tokens = [];
state.target = "";
targetSelect.value = "";
updateUI();
});
document.querySelector("#mismatchButton").addEventListener("click", () => {
setFormula(
[
quantityToken("distance"),
operatorToken("+"),
quantityToken("time")
],
""
);
});
document.querySelector("#checkButton").addEventListener("click", () => {
updateUI();
const panel = document.querySelector("#scenePanel");
panel.classList.remove("pulse");
void panel.offsetWidth;
panel.classList.add("pulse");
});
document.querySelector("#referenceList").addEventListener(
"click",
event => {
const button = event.target.closest("[data-reference]");
if (!button) return;
const reference = referenceCases.find(
item => item.id === button.dataset.reference
);
if (reference) {
setFormula(reference.tokens, reference.target);
}
}
);
function updateActiveReference() {
document.querySelectorAll("[data-reference]").forEach(button => {
button.classList.toggle(
"active",
button.dataset.reference === state.target
);
});
}
document.querySelector("#runReferencesButton").addEventListener(
"click",
() => {
const passed = referenceCases.filter(reference => {
const result = evaluateTokens(reference.tokens);
return result.valid && sameDimensions(result.dims, reference.expected);
}).length;
const status = document.querySelector("#referenceStatus");
status.textContent =
`${passed}/${referenceCases.length} dimension arithmetic checks pass`;
status.style.color = passed === referenceCases.length
? "var(--green)"
: "var(--red)";
}
);
// ------------------------------------------------------------
// Three.js scene.
// ------------------------------------------------------------
const viewport = document.querySelector("#viewport");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe7eee8);
scene.fog = new THREE.Fog(0xe7eee8, 13, 25);
const camera = new THREE.PerspectiveCamera(
39,
1,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute(
"aria-label",
"Interactive low-poly scene showing dimension exponents"
);
viewport.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(
0xf8fff9,
0x8e9d91,
2.35
);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff2d9, 3.1);
keyLight.position.set(5, 9, 6);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -7;
keyLight.shadow.camera.right = 7;
keyLight.shadow.camera.top = 7;
keyLight.shadow.camera.bottom = -7;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0x9cc8ff, 1.15);
fillLight.position.set(-6, 4, -4);
scene.add(fillLight);
const world = new THREE.Group();
scene.add(world);
function material(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.78,
metalness: 0.02,
flatShading: true,
...options
});
}
function addBox(
width,
height,
depth,
color,
x,
y,
z,
parent = world
) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material(color)
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// Low-poly ground and workbench.
const ground = new THREE.Mesh(
new THREE.CylinderGeometry(9.2, 9.2, 0.28, 10),
material(0xdce6dd)
);
ground.position.y = -1.14;
ground.receiveShadow = true;
world.add(ground);
addBox(5.6, 0.26, 3.65, 0x466c61, 0, -0.61, 0);
addBox(5.85, 0.12, 3.88, 0x789087, 0, -0.48, 0);
const legPositions = [
[-2.25, -1.05, -1.35],
[2.25, -1.05, -1.35],
[-2.25, -1.05, 1.35],
[2.25, -1.05, 1.35]
];
legPositions.forEach(([x, y, z]) => {
addBox(0.28, 1.15, 0.28, 0x34574f, x, y, z);
});
// A low-poly ruler along the front of the bench.
const ruler = addBox(4.7, 0.08, 0.28, 0xe1b36d, 0, -0.37, 1.53);
ruler.rotation.y = -0.035;
for (let index = 0; index < 13; index += 1) {
const tick = addBox(
0.025,
0.018,
index % 3 === 0 ? 0.19 : 0.12,
0x705737,
-2.15 + index * 0.36,
-0.318,
1.48
);
tick.rotation.y = -0.035;
}
function roundedRect(ctx, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + width - r, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + r);
ctx.lineTo(x + width, y + height - r);
ctx.quadraticCurveTo(
x + width,
y + height,
x + width - r,
y + height
);
ctx.lineTo(x + r, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
}
function createDynamicLabel(initialText, color) {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 96;
const context = canvas.getContext("2d");
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(0.92, 0.345, 1);
sprite.renderOrder = 12;
function setText(text) {
context.clearRect(0, 0, canvas.width, canvas.height);
roundedRect(context, 12, 12, 232, 72, 22);
context.fillStyle = "rgba(255, 255, 255, 0.91)";
context.fill();
context.strokeStyle = color;
context.lineWidth = 5;
context.stroke();
context.fillStyle = color;
context.font = "bold 40px Georgia, serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 128, 49);
texture.needsUpdate = true;
}
setText(initialText);
return { sprite, setText };
}
const axisColors = [0x36a38f, 0xdb8050, 0x6c6fa5];
const axisCssColors = ["#278f7d", "#c96e3d", "#5d6094"];
const towers = [];
function createDimensionTower(index, x) {
const group = new THREE.Group();
group.position.set(x, -0.35, -0.42);
world.add(group);
const base = new THREE.Mesh(
new THREE.CylinderGeometry(0.58, 0.65, 0.18, 8),
material(0xb7c7bd)
);
base.position.y = 0.02;
base.receiveShadow = true;
group.add(base);
const blocks = [];
for (let blockIndex = 0; blockIndex < 4; blockIndex += 1) {
const block = addBox(
0.58,
0.38,
0.58,
axisColors[index],
0,
0.31 + blockIndex * 0.41,
0,
group
);
block.rotation.y = (blockIndex % 2 ? 1 : -1) * 0.035;
blocks.push(block);
}
const label = createDynamicLabel(
`${dimensionBases[index]}⁰`,
axisCssColors[index]
);
label.sprite.position.set(0, 2.08, 0);
group.add(label.sprite);
towers.push({ blocks, label });
}
createDimensionTower(0, -1.55);
createDimensionTower(1, 0);
createDimensionTower(2, 1.55);
// Central candidate core.
const coreMaterial = material(0x4f9f8d, {
emissive: 0x123a32,
emissiveIntensity: 0.22,
roughness: 0.46
});
const core = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.67, 0),
coreMaterial
);
core.position.set(0, 0.55, 0.58);
core.castShadow = true;
world.add(core);
const haloMaterial = material(0x4f9f8d, {
emissive: 0x173e35,
emissiveIntensity: 0.18
});
const halo = new THREE.Mesh(
new THREE.TorusGeometry(0.92, 0.055, 6, 32),
haloMaterial
);
halo.position.copy(core.position);
halo.rotation.x = Math.PI / 2;
world.add(halo);
// Dynamic formula card.
const formulaCanvas = document.createElement("canvas");
formulaCanvas.width = 1024;
formulaCanvas.height = 320;
const formulaContext = formulaCanvas.getContext("2d");
const formulaTexture = new THREE.CanvasTexture(formulaCanvas);
formulaTexture.colorSpace = THREE.SRGBColorSpace;
const formulaSprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: formulaTexture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
formulaSprite.position.set(0, 2.65, 0.2);
formulaSprite.scale.set(4.9, 1.53, 1);
formulaSprite.renderOrder = 20;
world.add(formulaSprite);
function drawFormulaCard(result, target) {
const context = formulaContext;
const status = result.empty
? "neutral"
: result.error || !result.valid
? "bad"
: target &&
!sameDimensions(result.dims, target.dims)
? "warn"
: "good";
const border =
status === "bad"
? "#c74646"
: status === "warn"
? "#c66a2b"
: status === "good"
? "#167a68"
: "#789087";
context.clearRect(0, 0, formulaCanvas.width, formulaCanvas.height);
roundedRect(context, 15, 15, 994, 290, 34);
context.fillStyle = "rgba(255, 253, 247, 0.96)";
context.fill();
context.lineWidth = 8;
context.strokeStyle = border;
context.stroke();
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = "#658078";
context.font = "700 24px system-ui, sans-serif";
context.fillText(
"CANDIDATE DIMENSION SIGNATURE",
512,
58
);
context.fillStyle = "#1b302c";
context.font = "bold 56px Georgia, serif";
const formula = formatFormula(state.tokens) || "Build a formula";
context.fillText(formula, 512, 128, 900);
context.fillStyle = border;
context.font = "700 32px Georgia, serif";
const dimensionText = result.valid
? prettyDimensions(result.dims)
: result.empty
? "No dimension result"
: "Mixed or invalid dimensions";
context.fillText(dimensionText, 512, 194, 880);
context.fillStyle = "#60776f";
context.font = "500 23px system-ui, sans-serif";
let footer = "Choose a reference quantity to compare";
if (result.error) {
footer = result.error;
} else if (!result.valid) {
footer = "Incompatible terms are highlighted in the builder";
} else if (target) {
footer = sameDimensions(result.dims, target.dims)
? `Reference dimension match: ${target.name} · not proof of correctness`
: `Reference expects: ${prettyDimensions(target.dims)}`;
}
context.fillText(footer, 512, 255, 900);
formulaTexture.needsUpdate = true;
}
function updateScene(result, target) {
const status = result.empty
? "neutral"
: result.error || !result.valid
? "bad"
: target &&
!sameDimensions(result.dims, target.dims)
? "warn"
: "good";
const colors = {
neutral: 0x648ba0,
good: 0x42a28d,
warn: 0xd68b4d,
bad: 0xd1544f
};
coreMaterial.color.setHex(colors[status]);
coreMaterial.emissive.setHex(colors[status]);
coreMaterial.emissiveIntensity = status === "bad" ? 0.34 : 0.18;
haloMaterial.color.setHex(colors[status]);
haloMaterial.emissive.setHex(colors[status]);
towers.forEach((tower, index) => {
const exponent = result.valid ? result.dims[index] : 0;
const count = result.valid
? Math.min(4, Math.max(0, Math.abs(exponent)))
: 0;
tower.blocks.forEach((block, blockIndex) => {
block.visible = blockIndex < count;
});
tower.label.setText(
`${dimensionBases[index]}${superscriptNumber(exponent)}`
);
});
drawFormulaCard(result, target);
}
// Decorative low-poly objects.
const floatingObjects = [];
function addFloatingGeometry(geometry, color, x, y, z) {
const object = new THREE.Mesh(geometry, material(color));
object.position.set(x, y, z);
object.castShadow = true;
world.add(object);
floatingObjects.push({
object,
originY: y,
phase: Math.random() * Math.PI * 2
});
}
addFloatingGeometry(
new THREE.TetrahedronGeometry(0.33),
0xe7a568,
-3.25,
1.55,
-1.2
);
addFloatingGeometry(
new THREE.OctahedronGeometry(0.29),
0x7a9fbe,
3.2,
1.9,
-1.55
);
addFloatingGeometry(
new THREE.IcosahedronGeometry(0.25),
0x8d78a4,
2.9,
0.55,
1.2
);
// ------------------------------------------------------------
// Custom camera controls: orbit, pan and zoom.
// No Three.js addons are used.
// ------------------------------------------------------------
const cameraState = {
yaw: 0.57,
pitch: 0.51,
radius: 9.15,
target: new THREE.Vector3(0, 0.5, 0)
};
function updateCamera() {
const horizontal = cameraState.radius * Math.cos(cameraState.pitch);
camera.position.set(
cameraState.target.x + horizontal * Math.sin(cameraState.yaw),
cameraState.target.y + cameraState.radius * Math.sin(cameraState.pitch),
cameraState.target.z + horizontal * Math.cos(cameraState.yaw)
);
camera.lookAt(cameraState.target);
camera.updateMatrixWorld();
}
function resetCamera() {
cameraState.yaw = 0.57;
cameraState.pitch = 0.51;
cameraState.radius = 9.15;
cameraState.target.set(0, 0.5, 0);
updateCamera();
}
document.querySelector("#resetViewButton").addEventListener(
"click",
resetCamera
);
const pointer = {
active: false,
id: null,
x: 0,
y: 0,
button: 0
};
renderer.domElement.addEventListener("pointerdown", event => {
pointer.active = true;
pointer.id = event.pointerId;
pointer.x = event.clientX;
pointer.y = event.clientY;
pointer.button = event.button;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!pointer.active || event.pointerId !== pointer.id) return;
const dx = event.clientX - pointer.x;
const dy = event.clientY - pointer.y;
pointer.x = event.clientX;
pointer.y = event.clientY;
if (pointer.button === 2) {
const right = new THREE.Vector3().setFromMatrixColumn(
camera.matrixWorld,
0
);
const up = new THREE.Vector3().setFromMatrixColumn(
camera.matrixWorld,
1
);
const scale = cameraState.radius * 0.0012;
cameraState.target.addScaledVector(right, -dx * scale);
cameraState.target.addScaledVector(up, dy * scale);
} else {
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.005,
0.12,
1.34
);
}
updateCamera();
});
function endPointer(event) {
if (event.pointerId !== pointer.id) return;
pointer.active = false;
pointer.id = null;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener(
"contextmenu",
event => event.preventDefault()
);
renderer.domElement.addEventListener(
"wheel",
event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
5.2,
15.5
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
function resizeRenderer() {
const width = Math.max(1, viewport.clientWidth);
const height = Math.max(1, viewport.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
const resizeObserver = new ResizeObserver(resizeRenderer);
resizeObserver.observe(viewport);
// ------------------------------------------------------------
// Start.
// ------------------------------------------------------------
updateCamera();
resizeRenderer();
setFormula(
[
quantityToken("distance"),
operatorToken("/"),
quantityToken("time")
],
"speed"
);
const reduceMotion = window.matchMedia(
"(prefers-reduced-motion: reduce)"
).matches;
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
if (!reduceMotion) {
core.rotation.y = elapsed * 0.48;
core.rotation.x = Math.sin(elapsed * 0.42) * 0.13;
core.position.y = 0.55 + Math.sin(elapsed * 1.35) * 0.055;
halo.rotation.z = elapsed * 0.24;
floatingObjects.forEach(({ object, originY, phase }) => {
object.rotation.x = elapsed * 0.24 + phase;
object.rotation.y = elapsed * 0.31 + phase * 0.5;
object.position.y = originY + Math.sin(elapsed * 0.8 + phase) * 0.11;
});
}
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```