Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(anatomy): render machine specs as interactive isometric wireframes with shader effects and real part motion
nirholas3bc212b01939
diff --git a/src/anatomy/anatomy.css b/src/anatomy/anatomy.cssnew file mode 100644index 000000000..3d280f554--- /dev/null+++ b/src/anatomy/anatomy.css@@ -0,0 +1,785 @@+/* Anatomy explorer (src/anatomy/runtime.js). Self-contained: it reads the+ site tokens when they exist and falls back to its own palette so the same+ stylesheet works inside three.ws pages and in standalone skill output. */++.anx {+ --anx-bg: #0b0e14;+ --anx-panel: rgba(17, 21, 30, 0.92);+ --anx-panel-solid: #11151e;+ --anx-raise: rgba(255, 255, 255, 0.06);+ --anx-raise-2: rgba(255, 255, 255, 0.1);+ --anx-line: rgba(255, 255, 255, 0.09);+ --anx-line-2: rgba(255, 255, 255, 0.16);+ --anx-ink: #e9edf5;+ --anx-dim: #8b95a8;+ --anx-accent: #5eb0ff;+ --anx-accent-ink: #04111f;+ --anx-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);+ --anx-font: var(--font-body, 'Inter', system-ui, -apple-system, 'Segoe UI', sans-serif);+ --anx-display: var(--font-display, 'Space Grotesk', 'Inter', system-ui, sans-serif);+ --anx-mono: var(--font-mono, 'JetBrains Mono', ui-monospace, monospace);+ --anx-side: 320px;++ position: relative;+ display: grid;+ grid-template-columns: minmax(0, 1fr) var(--anx-side);+ grid-template-rows: auto minmax(0, 1fr) auto;+ grid-template-areas:+ 'head head'+ 'stage side'+ 'tools side';+ width: 100%;+ height: 100%;+ min-height: 420px;+ background: var(--anx-bg);+ color: var(--anx-ink);+ font-family: var(--anx-font);+ font-size: 14px;+ line-height: 1.5;+ border-radius: inherit;+ overflow: hidden;+ outline: none;+ isolation: isolate;+}++.anx[data-anx-theme='light'] {+ --anx-bg: #f5f6f8;+ --anx-panel: rgba(255, 255, 255, 0.94);+ --anx-panel-solid: #ffffff;+ --anx-raise: rgba(13, 18, 32, 0.05);+ --anx-raise-2: rgba(13, 18, 32, 0.09);+ --anx-line: rgba(13, 18, 32, 0.09);+ --anx-line-2: rgba(13, 18, 32, 0.16);+ --anx-ink: #141a26;+ --anx-dim: #5c6577;+ --anx-accent: #1f6fff;+ --anx-accent-ink: #ffffff;+ --anx-shadow: 0 12px 36px rgba(20, 30, 50, 0.14);+}++.anx:focus-visible {+ box-shadow: inset 0 0 0 2px var(--anx-accent);+}++.anx *,+.anx *::before,+.anx *::after {+ box-sizing: border-box;+}++.anx.is-collapsed {+ grid-template-columns: minmax(0, 1fr) 0;+}++.anx.is-collapsed .anx-side {+ display: none;+}++.anx.is-fullscreen {+ border-radius: 0;+}++/* ── header (standalone pages) ─────────────────────────────────────────── */++.anx-header {+ grid-area: head;+ padding: 18px 20px 12px;+ border-bottom: 1px solid var(--anx-line);+}++.anx-title {+ margin: 0;+ font-family: var(--anx-display);+ font-size: 22px;+ font-weight: 600;+ letter-spacing: -0.01em;+ line-height: 1.2;+}++.anx-subtitle {+ margin: 4px 0 0;+ color: var(--anx-dim);+}++/* ── stage ─────────────────────────────────────────────────────────────── */++.anx-stage {+ grid-area: stage;+ position: relative;+ min-height: 0;+ overflow: hidden;+ touch-action: none;+}++.anx-canvas {+ display: block;+ width: 100%;+ height: 100%;+ cursor: grab;+}++.anx-canvas:active {+ cursor: grabbing;+}++.anx-labels {+ position: absolute;+ inset: 0;+ pointer-events: none;+ overflow: hidden;+}++.anx-label {+ position: absolute;+ top: 0;+ left: 0;+ padding: 2px 8px;+ border: 1px solid var(--anx-line-2);+ border-radius: 999px;+ background: var(--anx-panel);+ color: var(--anx-ink);+ font-size: 11.5px;+ font-weight: 500;+ white-space: nowrap;+ max-width: 220px;+ overflow: hidden;+ text-overflow: ellipsis;+ will-change: transform;+ backdrop-filter: blur(6px);+}++.anx-label::after {+ content: '';+ position: absolute;+ left: 50%;+ bottom: -9px;+ width: 1px;+ height: 8px;+ background: var(--anx-line-2);+}++.anx-label.is-active {+ border-color: var(--anx-accent);+ color: var(--anx-accent);+}++.anx-tooltip {+ position: absolute;+ top: 0;+ left: 0;+ z-index: 4;+ display: flex;+ flex-direction: column;+ gap: 1px;+ padding: 7px 10px;+ max-width: 240px;+ border: 1px solid var(--anx-line-2);+ border-radius: 8px;+ background: var(--anx-panel-solid);+ box-shadow: var(--anx-shadow);+ pointer-events: none;+ font-size: 12.5px;+}++.anx-tip-group {+ color: var(--anx-dim);+ font-size: 11.5px;+}++.anx-hint {+ position: absolute;+ left: 14px;+ bottom: 12px;+ color: var(--anx-dim);+ font-size: 11.5px;+ pointer-events: none;+ opacity: 0.8;+}++.anx.is-touring .anx-hint {+ display: none;+}++.anx-flash {+ position: absolute;+ top: 14px;+ left: 50%;+ z-index: 6;+ transform: translateX(-50%);+ padding: 8px 14px;+ border: 1px solid var(--anx-line-2);+ border-radius: 8px;+ background: var(--anx-panel-solid);+ box-shadow: var(--anx-shadow);+ font-size: 13px;+}++/* ── tour card ─────────────────────────────────────────────────────────── */++.anx-tour {+ position: absolute;+ left: 14px;+ bottom: 14px;+ z-index: 5;+ width: min(400px, calc(100% - 28px));+ padding: 14px 16px 12px;+ border: 1px solid var(--anx-line-2);+ border-radius: 12px;+ background: var(--anx-panel);+ box-shadow: var(--anx-shadow);+ backdrop-filter: blur(10px);+ animation: anx-rise 0.28s ease-out;+}++@keyframes anx-rise {+ from {+ opacity: 0;+ transform: translateY(8px);+ }+}++.anx-tour-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+}++.anx-tour-title {+ margin: 4px 0 6px;+ font-family: var(--anx-display);+ font-size: 17px;+ font-weight: 600;+ line-height: 1.3;+}++.anx-tour-body {+ max-height: 34vh;+ overflow-y: auto;+ color: var(--anx-ink);+ font-size: 13.5px;+}++.anx-tour-body p,+.anx-ibody p,+.anx-summary p {+ margin: 0 0 8px;+}++.anx-tour-foot {+ display: flex;+ align-items: center;+ justify-content: space-between;+ margin-top: 8px;+}++.anx-tour-nav {+ display: flex;+ gap: 6px;+}++.anx-dots {+ display: flex;+ gap: 5px;+}++.anx-dots span {+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: var(--anx-line-2);+}++.anx-dots span.is-on {+ background: var(--anx-accent);+ width: 16px;+ border-radius: 3px;+}++/* ── toolbar ───────────────────────────────────────────────────────────── */++.anx-toolbar {+ grid-area: tools;+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 6px 14px;+ padding: 8px 12px;+ border-top: 1px solid var(--anx-line);+ background: var(--anx-panel);+}++.anx-tgroup {+ display: flex;+ align-items: center;+ gap: 6px;+}++.anx-tgroup-end {+ margin-left: auto;+}++.anx-ticon {+ display: inline-flex;+ color: var(--anx-dim);+}++.anx-btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: 6px;+ min-width: 34px;+ height: 34px;+ padding: 0 8px;+ border: 1px solid transparent;+ border-radius: 8px;+ background: transparent;+ color: var(--anx-ink);+ font: inherit;+ font-weight: 500;+ cursor: pointer;+ transition: background-color 0.12s, border-color 0.12s, color 0.12s;+}++.anx-btn:hover:not(:disabled) {+ background: var(--anx-raise-2);+}++.anx-btn:active:not(:disabled) {+ transform: translateY(1px);+}++.anx-btn:focus-visible,+.anx-select:focus-visible,+.anx-range:focus-visible,+.anx-tab:focus-visible,+.anx-pname:focus-visible,+.anx-eye:focus-visible,+.anx-step:focus-visible,+.anx-cta:focus-visible {+ outline: 2px solid var(--anx-accent);+ outline-offset: 1px;+}++.anx-btn[aria-pressed='true'] {+ background: color-mix(in srgb, var(--anx-accent) 16%, transparent);+ border-color: color-mix(in srgb, var(--anx-accent) 40%, transparent);+ color: var(--anx-accent);+}++.anx-btn:disabled {+ opacity: 0.4;+ cursor: default;+}++.anx-btn-sm {+ min-width: 28px;+ height: 28px;+ padding: 0 4px;+}++.anx-btn-primary {+ background: var(--anx-accent);+ color: var(--anx-accent-ink);+ padding: 0 12px;+}++.anx-btn-primary:hover:not(:disabled) {+ background: color-mix(in srgb, var(--anx-accent) 86%, var(--anx-ink));+}++.anx-select {+ height: 34px;+ padding: 0 8px;+ border: 1px solid var(--anx-line-2);+ border-radius: 8px;+ background: var(--anx-raise);+ color: var(--anx-ink);+ font: inherit;+ font-size: 13px;+ cursor: pointer;+}++.anx-select:hover {+ border-color: var(--anx-dim);+}++.anx-select option {+ background: var(--anx-panel-solid);+ color: var(--anx-ink);+}++.anx-range {+ width: 96px;+ accent-color: var(--anx-accent);+ cursor: pointer;+}++.anx-range:disabled {+ opacity: 0.35;+ cursor: default;+}++/* ── side panel ────────────────────────────────────────────────────────── */++.anx-side {+ grid-area: side;+ display: flex;+ flex-direction: column;+ min-height: 0;+ border-left: 1px solid var(--anx-line);+ background: var(--anx-panel);+}++.anx-tabs {+ display: flex;+ gap: 4px;+ padding: 8px 8px 0;+ border-bottom: 1px solid var(--anx-line);+}++.anx-tab {+ padding: 8px 12px;+ border: 0;+ border-bottom: 2px solid transparent;+ background: none;+ color: var(--anx-dim);+ font: inherit;+ font-weight: 500;+ cursor: pointer;+}++.anx-tab:hover {+ color: var(--anx-ink);+}++.anx-tab[aria-selected='true'] {+ color: var(--anx-ink);+ border-bottom-color: var(--anx-accent);+}++.anx-pane {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ padding: 6px 0 16px;+ scrollbar-width: thin;+}++.anx-pad {+ padding: 10px 14px;+}++.anx-muted {+ color: var(--anx-dim);+}++.anx-pgroup + .anx-pgroup {+ margin-top: 6px;+}++.anx-gtitle {+ display: flex;+ justify-content: space-between;+ margin: 8px 14px 4px;+ color: var(--anx-dim);+ font-family: var(--anx-mono);+ font-size: 10.5px;+ font-weight: 500;+ letter-spacing: 0.08em;+ text-transform: uppercase;+}++.anx-gtitle::after {+ content: attr(data-count);+ opacity: 0.7;+}++.anx-plist {+ margin: 0;+ padding: 0 6px;+ list-style: none;+}++.anx-prow {+ display: flex;+ align-items: center;+ border-radius: 7px;+}++.anx-prow:hover {+ background: var(--anx-raise);+}++.anx-prow.is-selected {+ background: color-mix(in srgb, var(--anx-accent) 14%, transparent);+}++.anx-prow.is-hidden .anx-pname {+ opacity: 0.45;+}++.anx-pname {+ flex: 1;+ display: flex;+ align-items: center;+ gap: 9px;+ min-width: 0;+ padding: 6px 8px;+ border: 0;+ background: none;+ color: inherit;+ font: inherit;+ text-align: left;+ cursor: pointer;+ border-radius: 7px;+}++.anx-ptext {+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.anx-swatch {+ flex: none;+ width: 10px;+ height: 10px;+ border-radius: 3px;+ background: var(--c);+ box-shadow: 0 0 0 1px var(--anx-line-2);+}++.anx-swatch.is-fx {+ border-radius: 50%;+ box-shadow: 0 0 8px var(--c);+}++.anx-count {+ flex: none;+ color: var(--anx-dim);+ font-family: var(--anx-mono);+ font-size: 11px;+}++.anx-moving {+ flex: none;+ display: inline-flex;+ color: var(--anx-accent);+}++.anx-moving svg {+ width: 13px;+ height: 13px;+}++.anx-eye {+ flex: none;+ display: inline-flex;+ padding: 6px 8px;+ border: 0;+ background: none;+ color: var(--anx-dim);+ cursor: pointer;+ opacity: 0;+ border-radius: 6px;+}++.anx-eye svg {+ width: 15px;+ height: 15px;+}++.anx-prow:hover .anx-eye,+.anx-prow.is-hidden .anx-eye,+.anx-eye:focus-visible {+ opacity: 1;+}++.anx-eye:hover {+ color: var(--anx-ink);+}++@media (hover: none) {+ .anx-eye {+ opacity: 1;+ }+}++/* ── inspector ─────────────────────────────────────────────────────────── */++.anx-inspector {+ flex: none;+ max-height: 46%;+ overflow-y: auto;+ padding: 12px 14px;+ border-bottom: 1px solid var(--anx-line);+ animation: anx-rise 0.2s ease-out;+}++.anx-ihead {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 8px;+}++.anx-eyebrow {+ color: var(--anx-dim);+ font-family: var(--anx-mono);+ font-size: 10.5px;+ letter-spacing: 0.08em;+ text-transform: uppercase;+}++.anx-ititle {+ margin: 2px 0 0;+ font-family: var(--anx-display);+ font-size: 17px;+ font-weight: 600;+ line-height: 1.25;+}++.anx-imeta {+ display: flex;+ flex-wrap: wrap;+ gap: 5px;+ margin: 8px 0;+}++.anx-imeta span {+ padding: 2px 8px;+ border: 1px solid var(--anx-line-2);+ border-radius: 999px;+ color: var(--anx-dim);+ font-size: 11.5px;+}++.anx-ibody {+ font-size: 13.5px;+}++/* ── tour list ─────────────────────────────────────────────────────────── */++.anx-summary {+ margin-bottom: 12px;+ font-size: 13.5px;+}++.anx-cta {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ width: 100%;+ justify-content: center;+ padding: 9px 14px;+ border: 0;+ border-radius: 9px;+ background: var(--anx-accent);+ color: var(--anx-accent-ink);+ font: inherit;+ font-weight: 600;+ cursor: pointer;+}++.anx-cta:hover {+ background: color-mix(in srgb, var(--anx-accent) 86%, var(--anx-ink));+}++.anx-steps {+ margin: 4px 0 0;+ padding: 0 6px;+ list-style: none;+}++.anx-step {+ display: flex;+ align-items: center;+ gap: 10px;+ width: 100%;+ padding: 7px 8px;+ border: 0;+ border-radius: 7px;+ background: none;+ color: inherit;+ font: inherit;+ text-align: left;+ cursor: pointer;+}++.anx-step:hover {+ background: var(--anx-raise);+}++.anx-step.is-active {+ background: color-mix(in srgb, var(--anx-accent) 14%, transparent);+}++.anx-stepn {+ flex: none;+ display: inline-grid;+ place-items: center;+ width: 22px;+ height: 22px;+ border: 1px solid var(--anx-line-2);+ border-radius: 50%;+ color: var(--anx-dim);+ font-family: var(--anx-mono);+ font-size: 11px;+}++.anx-step.is-active .anx-stepn {+ border-color: var(--anx-accent);+ background: var(--anx-accent);+ color: var(--anx-accent-ink);+}++/* ── narrow screens: panel becomes a sheet under the stage ─────────────── */++@media (max-width: 760px) {+ .anx {+ grid-template-columns: minmax(0, 1fr);+ grid-template-rows: auto minmax(300px, 1fr) auto auto;+ grid-template-areas:+ 'head'+ 'stage'+ 'tools'+ 'side';+ }++ .anx.is-collapsed {+ grid-template-columns: minmax(0, 1fr);+ }++ .anx-side {+ max-height: 46vh;+ border-left: 0;+ border-top: 1px solid var(--anx-line);+ }++ .anx-toolbar {+ gap: 6px 8px;+ padding: 6px 8px;+ }++ .anx-range {+ width: 72px;+ }++ .anx-hint {+ display: none;+ }++ .anx-tgroup-end {+ margin-left: 0;+ }+}++@media (prefers-reduced-motion: reduce) {+ .anx-tour,+ .anx-inspector {+ animation: none;+ }+}diff --git a/src/anatomy/effects.js b/src/anatomy/effects.jsnew file mode 100644index 000000000..c0a87c1ab--- /dev/null+++ b/src/anatomy/effects.js@@ -0,0 +1,628 @@+// Anatomy effects: the shader-driven matter that makes a machine read as+// working: flame in a combustor, an exhaust plume with shock diamonds, plasma+// in a reactor, water in a pipe, smoke, steam, sparks, electric arcs, a glow,+// and particles streaming along a flow path.+//+// Every builder returns { object, update(time, dt, frame), setDim(f), dispose() }.+// `frame` carries per-frame viewer state (pixel scale, theme) so the effects+// never reach into the viewer. Volumes are built along +Y from the emitter+// origin and turned onto the spec axis by the effect frame.++import * as THREE from 'three';+import { Line2 } from 'three/addons/lines/Line2.js';+import { LineGeometry } from 'three/addons/lines/LineGeometry.js';++const Y = new THREE.Vector3(0, 1, 0);+const AXIS_VEC = { x: new THREE.Vector3(1, 0, 0), y: new THREE.Vector3(0, 1, 0), z: new THREE.Vector3(0, 0, 1) };++// Ashima / Stefan Gustavson 3D simplex noise (MIT), plus a 4-octave fbm.+const NOISE_GLSL = /* glsl */ `+vec3 mod289(vec3 x){return x-floor(x*(1.0/289.0))*289.0;}+vec4 mod289(vec4 x){return x-floor(x*(1.0/289.0))*289.0;}+vec4 permute(vec4 x){return mod289(((x*34.0)+1.0)*x);}+vec4 taylorInvSqrt(vec4 r){return 1.79284291400159-0.85373472095314*r;}+float snoise(vec3 v){+ const vec2 C=vec2(1.0/6.0,1.0/3.0);+ const vec4 D=vec4(0.0,0.5,1.0,2.0);+ vec3 i=floor(v+dot(v,C.yyy));+ vec3 x0=v-i+dot(i,C.xxx);+ vec3 g=step(x0.yzx,x0.xyz);+ vec3 l=1.0-g;+ vec3 i1=min(g.xyz,l.zxy);+ vec3 i2=max(g.xyz,l.zxy);+ vec3 x1=x0-i1+C.xxx;+ vec3 x2=x0-i2+C.yyy;+ vec3 x3=x0-D.yyy;+ i=mod289(i);+ vec4 p=permute(permute(permute(i.z+vec4(0.0,i1.z,i2.z,1.0))+i.y+vec4(0.0,i1.y,i2.y,1.0))+i.x+vec4(0.0,i1.x,i2.x,1.0));+ float n_=0.142857142857;+ vec3 ns=n_*D.wyz-D.xzx;+ vec4 j=p-49.0*floor(p*ns.z*ns.z);+ vec4 x_=floor(j*ns.z);+ vec4 y_=floor(j-7.0*x_);+ vec4 x=x_*ns.x+ns.yyyy;+ vec4 y=y_*ns.x+ns.yyyy;+ vec4 h=1.0-abs(x)-abs(y);+ vec4 b0=vec4(x.xy,y.xy);+ vec4 b1=vec4(x.zw,y.zw);+ vec4 s0=floor(b0)*2.0+1.0;+ vec4 s1=floor(b1)*2.0+1.0;+ vec4 sh=-step(h,vec4(0.0));+ vec4 a0=b0.xzyw+s0.xzyw*sh.xxyy;+ vec4 a1=b1.xzyw+s1.xzyw*sh.zzww;+ vec3 p0=vec3(a0.xy,h.x);+ vec3 p1=vec3(a0.zw,h.y);+ vec3 p2=vec3(a1.xy,h.z);+ vec3 p3=vec3(a1.zw,h.w);+ vec4 norm=taylorInvSqrt(vec4(dot(p0,p0),dot(p1,p1),dot(p2,p2),dot(p3,p3)));+ p0*=norm.x;p1*=norm.y;p2*=norm.z;p3*=norm.w;+ vec4 m=max(0.6-vec4(dot(x0,x0),dot(x1,x1),dot(x2,x2),dot(x3,x3)),0.0);+ m=m*m;+ return 42.0*dot(m*m,vec4(dot(p0,x0),dot(p1,x1),dot(p2,x2),dot(p3,x3)));+}+float fbm(vec3 p){+ float f=0.0;float a=0.5;+ for(int i=0;i<4;i++){f+=a*snoise(p);p*=2.02;a*=0.5;}+ return f*0.5+0.5;+}+`;++const VOLUME_VERT = /* glsl */ `+uniform float uTime;+uniform float uSpeed;+uniform float uWobble;+varying vec2 vUv;+varying vec3 vPos;+varying float vFacing;+${NOISE_GLSL}+void main(){+ vUv = uv;+ vPos = position;+ vec3 p = position;+ if (uWobble > 0.0) {+ float w = snoise(vec3(p.x * 2.0, p.y * 1.5 - uTime * uSpeed * 3.0, p.z * 2.0));+ p.xz *= 1.0 + w * uWobble * uv.y;+ }+ vec4 mv = modelViewMatrix * vec4(p, 1.0);+ vec3 n = normalize(normalMatrix * normal);+ vec3 v = isOrthographic ? vec3(0.0, 0.0, 1.0) : normalize(-mv.xyz);+ vFacing = abs(dot(n, v));+ gl_Position = projectionMatrix * mv;+}+`;++// uMode: 0 flame, 1 exhaust, 2 plasma, 3 water stream, 4 water pool.+const VOLUME_FRAG = /* glsl */ `+uniform float uTime;+uniform float uSpeed;+uniform float uIntensity;+uniform float uDim;+uniform float uMode;+uniform float uScale;+uniform vec3 uColorA;+uniform vec3 uColorB;+varying vec2 vUv;+varying vec3 vPos;+varying float vFacing;+${NOISE_GLSL}+void main(){+ float t = uTime * uSpeed;+ float ang = vUv.x * 6.2831853;+ vec3 col;+ float alpha;+ if (uMode < 0.5) {+ float n = fbm(vec3(cos(ang) * 1.2, sin(ang) * 1.2, vUv.y * 4.0 - t * 2.6));+ float along = 1.0 - vUv.y;+ float body = pow(vFacing, 1.3);+ float base = smoothstep(0.0, 0.05, vUv.y);+ float tongue = smoothstep(0.15, 0.75, n + along * 0.55);+ alpha = body * base * pow(along, 0.7) * (0.35 + tongue);+ col = mix(uColorB, uColorA, clamp(body * along * 1.1 + n * 0.25, 0.0, 1.0));+ } else if (uMode < 1.5) {+ float n = fbm(vec3(cos(ang), sin(ang), vUv.y * 6.0 - t * 4.0));+ float along = 1.0 - vUv.y;+ float body = pow(vFacing, 1.6);+ float diamonds = pow(0.5 + 0.5 * cos(vUv.y * 34.0), 4.0) * smoothstep(0.0, 0.1, vUv.y) * pow(along, 1.4);+ alpha = body * pow(along, 0.55) * (0.45 + 0.45 * n) + diamonds * body * 0.9;+ col = mix(uColorB, uColorA, clamp(diamonds * 1.4 + body * along * 0.6, 0.0, 1.0));+ } else if (uMode < 2.5) {+ vec3 q = vPos / max(uScale, 0.0001) * 1.6;+ float n = fbm(q + vec3(t * 0.6, -t * 0.45, t * 0.3));+ float n2 = fbm(q * 2.3 - vec3(t * 0.9, t * 0.2, -t * 0.5));+ float rim = pow(1.0 - vFacing, 2.2);+ float filament = smoothstep(0.55, 0.85, n) + smoothstep(0.6, 0.9, n2) * 0.6;+ alpha = 0.18 + rim * 0.85 + filament * 0.7;+ col = mix(uColorB, uColorA, clamp(filament * 0.8 + rim * 0.5, 0.0, 1.0));+ } else if (uMode < 3.5) {+ float n = fbm(vec3(cos(ang) * 2.0, sin(ang) * 2.0, vUv.y * 7.0 - t * 3.2));+ float streak = smoothstep(0.55, 0.82, n);+ float edge = pow(1.0 - vFacing, 1.5);+ alpha = 0.42 + streak * 0.4 + edge * 0.25;+ col = mix(uColorB, uColorA, clamp(streak * 0.9 + edge * 0.4, 0.0, 1.0));+ } else {+ vec3 q = vPos / max(uScale, 0.0001) * 2.5;+ float n = fbm(vec3(q.x - t * 0.5, q.y * 0.5, q.z + t * 0.35));+ float caustic = smoothstep(0.6, 0.78, n);+ alpha = 0.5 + caustic * 0.35;+ col = mix(uColorB, uColorA, caustic);+ }+ alpha = clamp(alpha * uIntensity * uDim, 0.0, 1.0);+ if (alpha < 0.003) discard;+ gl_FragColor = vec4(col, alpha);+}+`;++const POINTS_VERT = /* glsl */ `+attribute float aAlpha;+attribute float aSize;+uniform float uPixelScale;+varying float vAlpha;+void main(){+ vAlpha = aAlpha;+ vec4 mv = modelViewMatrix * vec4(position, 1.0);+ gl_PointSize = max(1.0, aSize * uPixelScale);+ gl_Position = projectionMatrix * mv;+}+`;++const POINTS_FRAG = /* glsl */ `+uniform vec3 uColor;+uniform float uDim;+uniform float uHard;+varying float vAlpha;+void main(){+ float d = length(gl_PointCoord - 0.5);+ float a = uHard > 0.5 ? smoothstep(0.5, 0.2, d) : smoothstep(0.5, 0.0, d);+ a *= vAlpha * uDim;+ if (a < 0.003) discard;+ gl_FragColor = vec4(uColor, a);+}+`;++function blendingFor(frame) {+ return frame?.dark ? THREE.AdditiveBlending : THREE.NormalBlending;+}++function volumeMaterial({ mode, colorA, colorB, intensity, speed, wobble = 0, scale = 1 }) {+ return new THREE.ShaderMaterial({+ vertexShader: VOLUME_VERT,+ fragmentShader: VOLUME_FRAG,+ uniforms: {+ uTime: { value: 0 },+ uSpeed: { value: speed },+ uWobble: { value: wobble },+ uIntensity: { value: intensity },+ uDim: { value: 1 },+ uMode: { value: mode },+ uScale: { value: scale },+ uColorA: { value: new THREE.Color(colorA) },+ uColorB: { value: new THREE.Color(colorB) },+ },+ transparent: true,+ depthWrite: false,+ side: THREE.DoubleSide,+ });+}++function pointsMaterial(color, hard = false) {+ return new THREE.ShaderMaterial({+ vertexShader: POINTS_VERT,+ fragmentShader: POINTS_FRAG,+ uniforms: {+ uColor: { value: new THREE.Color(color) },+ uDim: { value: 1 },+ uHard: { value: hard ? 1 : 0 },+ uPixelScale: { value: 100 },+ },+ transparent: true,+ depthWrite: false,+ });+}++/** A group whose +Y points along the effect's axis and direction. */+function effectFrame(eff) {+ const g = new THREE.Group();+ g.position.set(...eff.position);+ const dir = AXIS_VEC[eff.axis].clone().multiplyScalar(eff.direction);+ g.quaternion.setFromUnitVectors(Y, dir);+ return g;+}++function syncBlending(materials, frame, state) {+ const dark = Boolean(frame.dark);+ if (state.dark === dark) return;+ state.dark = dark;+ for (const m of materials) {+ m.blending = blendingFor(frame);+ m.needsUpdate = true;+ }+}++function volumeEffect(eff) {+ const frame = effectFrame(eff);+ const materials = [];+ const geoms = [];+ const add = (geom, mat) => {+ geoms.push(geom);+ materials.push(mat);+ const mesh = new THREE.Mesh(geom, mat);+ mesh.renderOrder = 10;+ frame.add(mesh);+ return mesh;+ };+ const scale = Math.max(eff.radius, eff.length * 0.25);++ if (eff.type === 'flame' || eff.type === 'exhaust') {+ const mode = eff.type === 'flame' ? 0 : 1;+ const outer = new THREE.CylinderGeometry(Math.max(eff.radiusEnd, 0.001), eff.radius, eff.length, 40, 24, true);+ outer.translate(0, eff.length / 2, 0);+ add(outer, volumeMaterial({ mode, colorA: eff.color, colorB: eff.color2, intensity: eff.intensity, speed: eff.speed, wobble: mode === 0 ? 0.14 : 0.04 }));+ const coreLen = eff.length * (mode === 0 ? 0.62 : 0.85);+ const core = new THREE.CylinderGeometry(Math.max(eff.radiusEnd * 0.4, 0.001), eff.radius * 0.55, coreLen, 32, 16, true);+ core.translate(0, coreLen / 2, 0);+ add(core, volumeMaterial({ mode, colorA: '#ffffff', colorB: eff.color, intensity: eff.intensity * 0.9, speed: eff.speed * 1.2, wobble: mode === 0 ? 0.1 : 0.02 }));+ } else if (eff.type === 'plasma') {+ const form = eff.form || 'sphere';+ let geom;+ if (form === 'torus') {+ geom = new THREE.TorusGeometry(eff.radius, Math.max(eff.radiusEnd, eff.radius * 0.08), 32, 128);+ geom.rotateX(Math.PI / 2);+ } else if (form === 'column') {+ geom = new THREE.CylinderGeometry(eff.radiusEnd, eff.radius, eff.length, 40, 16, true);+ geom.translate(0, eff.length / 2, 0);+ } else {+ geom = new THREE.SphereGeometry(eff.radius, 48, 32);+ }+ add(geom, volumeMaterial({ mode: 2, colorA: eff.color, colorB: eff.color2, intensity: eff.intensity, speed: eff.speed, scale }));+ } else if (eff.type === 'water') {+ if (eff.form === 'pool' && eff.size) {+ const geom = new THREE.BoxGeometry(...eff.size);+ add(geom, volumeMaterial({ mode: 4, colorA: eff.color, colorB: eff.color2, intensity: eff.intensity, speed: eff.speed, scale: Math.max(...eff.size) * 0.5 }));+ } else {+ const geom = new THREE.CylinderGeometry(Math.max(eff.radiusEnd, 0.001), eff.radius, eff.length, 32, 12, true);+ geom.translate(0, eff.length / 2, 0);+ add(geom, volumeMaterial({ mode: 3, colorA: eff.color, colorB: eff.color2, intensity: eff.intensity, speed: eff.speed }));+ }+ }++ const state = { dark: null };+ return {+ object: frame,+ update(time, _dt, f) {+ syncBlending(materials, f, state);+ for (const m of materials) m.uniforms.uTime.value = time;+ },+ setDim(d) {+ for (const m of materials) m.uniforms.uDim.value = d;+ },+ dispose() {+ for (const g of geoms) g.dispose();+ for (const m of materials) m.dispose();+ },+ };+}++// Deterministic per-effect randomness so a shared link looks the same twice.+function rng(seed) {+ let s = 0;+ for (const ch of String(seed)) s = (Math.imul(s, 31) + ch.charCodeAt(0)) | 0;+ s = s >>> 0 || 1;+ return () => {+ s ^= s << 13;+ s ^= s >>> 17;+ s ^= s << 5;+ return ((s >>> 0) % 1_000_000) / 1_000_000;+ };+}++function particleEffect(eff) {+ const frame = effectFrame(eff);+ const n = eff.count;+ const rand = rng(eff.id);+ const pos = new Float32Array(n * 3);+ const vel = new Float32Array(n * 3);+ const age = new Float32Array(n);+ const life = new Float32Array(n);+ const alpha = new Float32Array(n);+ const size = new Float32Array(n);+ const sparks = eff.type === 'sparks';+ const steam = eff.type === 'steam';+ const baseLife = sparks ? 0.9 : steam ? 1.8 : 2.8;+ const rise = eff.length / baseLife;++ const spawn = (i, initial) => {+ const a = rand() * Math.PI * 2;+ const r = Math.sqrt(rand()) * eff.radius;+ pos[i * 3] = Math.cos(a) * r;+ pos[i * 3 + 1] = 0;+ pos[i * 3 + 2] = Math.sin(a) * r;+ if (sparks) {+ const spread = 0.9;+ vel[i * 3] = (rand() - 0.5) * 2 * spread * rise;+ vel[i * 3 + 1] = (0.6 + rand() * 0.9) * rise * 1.6;+ vel[i * 3 + 2] = (rand() - 0.5) * 2 * spread * rise;+ } else {+ vel[i * 3] = (rand() - 0.5) * 0.25 * rise;+ vel[i * 3 + 1] = (0.75 + rand() * 0.5) * rise;+ vel[i * 3 + 2] = (rand() - 0.5) * 0.25 * rise;+ }+ life[i] = baseLife * (0.7 + rand() * 0.6);+ age[i] = initial ? rand() * life[i] : 0;+ };+ for (let i = 0; i < n; i++) spawn(i, true);++ const geom = new THREE.BufferGeometry();+ geom.setAttribute('position', new THREE.BufferAttribute(pos, 3).setUsage(THREE.DynamicDrawUsage));+ geom.setAttribute('aAlpha', new THREE.BufferAttribute(alpha, 1).setUsage(THREE.DynamicDrawUsage));+ geom.setAttribute('aSize', new THREE.BufferAttribute(size, 1).setUsage(THREE.DynamicDrawUsage));+ geom.boundingSphere = new THREE.Sphere(new THREE.Vector3(0, eff.length / 2, 0), eff.length + eff.radius * 3);+ const mat = pointsMaterial(eff.type === 'smoke' ? eff.color2 : eff.color, sparks);+ const points = new THREE.Points(geom, mat);+ points.renderOrder = 11;+ points.frustumCulled = false;+ frame.add(points);++ const state = { dark: null };+ let dim = 1;+ return {+ object: frame,+ update(_time, dt, f) {+ syncBlending([mat], sparks ? { dark: true } : f, state);+ mat.uniforms.uPixelScale.value = f.pixelScale;+ // Light theme: steam is white on a white page, so it borrows its+ // cooler second color to stay visible.+ if (steam) mat.uniforms.uColor.value.set(f.dark ? eff.color : eff.color2);+ const step = Math.min(dt, 0.05) * eff.speed;+ for (let i = 0; i < n; i++) {+ age[i] += step;+ if (age[i] >= life[i]) spawn(i, false);+ if (sparks) vel[i * 3 + 1] -= 9.8 * 0.35 * rise * step;+ pos[i * 3] += vel[i * 3] * step;+ pos[i * 3 + 1] += vel[i * 3 + 1] * step;+ pos[i * 3 + 2] += vel[i * 3 + 2] * step;+ const k = age[i] / life[i];+ if (sparks) {+ alpha[i] = (1 - k) * eff.intensity;+ size[i] = eff.radius * 0.18;+ } else {+ // Puffs drift outward and grow as they rise.+ pos[i * 3] *= 1 + step * 0.35;+ pos[i * 3 + 2] *= 1 + step * 0.35;+ alpha[i] = Math.sin(Math.PI * k) * (steam ? 0.55 : 0.6) * eff.intensity;+ size[i] = eff.radius * (0.9 + k * 2.6);+ }+ }+ mat.uniforms.uDim.value = dim;+ geom.attributes.position.needsUpdate = true;+ geom.attributes.aAlpha.needsUpdate = true;+ geom.attributes.aSize.needsUpdate = true;+ },+ setDim(d) {+ dim = d;+ },+ dispose() {+ geom.dispose();+ mat.dispose();+ },+ };+}++let glowTexture = null;+function getGlowTexture() {+ if (glowTexture) return glowTexture;+ const c = document.createElement('canvas');+ c.width = c.height = 128;+ const ctx = c.getContext('2d');+ const g = ctx.createRadialGradient(64, 64, 0, 64, 64, 64);+ g.addColorStop(0, 'rgba(255,255,255,1)');+ g.addColorStop(0.25, 'rgba(255,255,255,0.55)');+ g.addColorStop(0.6, 'rgba(255,255,255,0.12)');+ g.addColorStop(1, 'rgba(255,255,255,0)');+ ctx.fillStyle = g;+ ctx.fillRect(0, 0, 128, 128);+ glowTexture = new THREE.CanvasTexture(c);+ glowTexture.colorSpace = THREE.SRGBColorSpace;+ return glowTexture;+}++function glowEffect(eff) {+ const frame = effectFrame(eff);+ const mat = new THREE.SpriteMaterial({ map: getGlowTexture(), color: new THREE.Color(eff.color), transparent: true, depthWrite: false });+ const sprite = new THREE.Sprite(mat);+ sprite.renderOrder = 12;+ frame.add(sprite);+ const base = eff.radius * 2.4;+ const state = { dark: null };+ let dim = 1;+ return {+ object: frame,+ update(time, _dt, f) {+ syncBlending([mat], f, state);+ const pulse = 1 + 0.12 * Math.sin(time * eff.speed * Math.PI * 2);+ sprite.scale.setScalar(base * pulse);+ mat.opacity = Math.min(1, 0.85 * eff.intensity) * dim;+ mat.color.set(f.dark ? eff.color : eff.color2);+ },+ setDim(d) {+ dim = d;+ },+ dispose() {+ mat.dispose();+ },+ };+}++function jagged(from, to, rand, depth, roughness) {+ let pts = [from.clone(), to.clone()];+ let amp = from.distanceTo(to) * roughness;+ for (let d = 0; d < depth; d++) {+ const next = [pts[0]];+ for (let i = 0; i < pts.length - 1; i++) {+ const a = pts[i];+ const b = pts[i + 1];+ const mid = a.clone().add(b).multiplyScalar(0.5);+ mid.x += (rand() - 0.5) * amp;+ mid.y += (rand() - 0.5) * amp;+ mid.z += (rand() - 0.5) * amp;+ next.push(mid, b);+ }+ pts = next;+ amp *= 0.55;+ }+ return pts;+}++function electricEffect(eff, ctx) {+ const group = new THREE.Group();+ const from = new THREE.Vector3(...eff.from);+ const to = new THREE.Vector3(...eff.to);+ const rand = rng(eff.id);+ const arcs = [];+ const materials = [];+ for (let k = 0; k < 3; k++) {+ const geom = new LineGeometry();+ geom.setPositions(new Float32Array(jagged(from, to, rand, 5, 0.22).flatMap((p) => [p.x, p.y, p.z])));+ const mat = ctx.lineMaterial({ color: k === 0 ? eff.color : eff.color2, width: k === 0 ? 2.6 : 1.4, transparent: true, opacity: k === 0 ? 1 : 0.7 });+ const line = new Line2(geom, mat);+ line.renderOrder = 12;+ group.add(line);+ arcs.push(line);+ materials.push(mat);+ }+ const glowMat = new THREE.SpriteMaterial({ map: getGlowTexture(), color: new THREE.Color(eff.color2), transparent: true, depthWrite: false, blending: THREE.AdditiveBlending });+ for (const p of [from, to]) {+ const s = new THREE.Sprite(glowMat);+ s.position.copy(p);+ s.scale.setScalar(Math.max(eff.radius, from.distanceTo(to) * 0.12));+ group.add(s);+ }+ let next = 0;+ let dim = 1;+ return {+ object: group,+ update(time) {+ if (time < next) return;+ next = time + (0.05 + rand() * 0.07) / Math.max(eff.speed, 0.1);+ for (const line of arcs) {+ const pts = jagged(from, to, rand, 5, 0.22);+ line.geometry.setPositions(new Float32Array(pts.flatMap((p) => [p.x, p.y, p.z])));+ }+ const flicker = 0.65 + rand() * 0.35;+ for (const [i, m] of materials.entries()) m.opacity = (i === 0 ? 1 : 0.7) * flicker * dim * Math.min(1, eff.intensity);+ glowMat.opacity = flicker * dim;+ },+ setDim(d) {+ dim = d;+ },+ dispose() {+ for (const l of arcs) l.geometry.dispose();+ glowMat.dispose();+ },+ };+}++/** Build one spec effect. `ctx.lineMaterial(opts)` makes a resolution-tracked fat-line material. */+export function buildEffect(eff, ctx) {+ switch (eff.type) {+ case 'flame':+ case 'exhaust':+ case 'plasma':+ case 'water':+ return volumeEffect(eff);+ case 'smoke':+ case 'steam':+ case 'sparks':+ return particleEffect(eff);+ case 'electric':+ return electricEffect(eff, ctx);+ case 'glow':+ return glowEffect(eff);+ default:+ return null;+ }+}++/**+ * A flow: particles streaming along a path, over a dashed guide line, with+ * arrowheads showing direction. Fuel, air, current, coolant.+ */+export function buildFlow(flow, ctx) {+ const group = new THREE.Group();+ const curve = new THREE.CatmullRomCurve3(+ flow.path.map((p) => new THREE.Vector3(...p)),+ flow.closed,+ 'centripetal',+ );+ const length = curve.getLength();+ const guidePts = curve.getSpacedPoints(Math.min(400, Math.max(32, Math.round(length * 20))));+ const guideGeom = new LineGeometry();+ guideGeom.setPositions(new Float32Array(guidePts.flatMap((p) => [p.x, p.y, p.z])));+ const guideMat = ctx.lineMaterial({ color: flow.color, width: 1.2, dashed: true, dashSize: length / 60, gapSize: length / 90, transparent: true, opacity: 0.55 });+ const guide = new Line2(guideGeom, guideMat);+ guide.computeLineDistances();+ group.add(guide);++ const arrowMat = new THREE.MeshBasicMaterial({ color: new THREE.Color(flow.color), transparent: true, opacity: 0.9 });+ const arrowSize = Math.max(length / 70, 0.04) * flow.size;+ const arrowGeom = new THREE.ConeGeometry(arrowSize * 0.55, arrowSize * 1.6, 12);+ const arrows = [];+ for (const u of flow.closed ? [0.12, 0.45, 0.78] : [0.3, 0.62, 0.94]) {+ const m = new THREE.Mesh(arrowGeom, arrowMat);+ m.position.copy(curve.getPointAt(u));+ m.quaternion.setFromUnitVectors(Y, curve.getTangentAt(u).normalize());+ group.add(m);+ arrows.push(m);+ }++ const n = flow.count;+ const pos = new Float32Array(n * 3);+ const alpha = new Float32Array(n).fill(1);+ const size = new Float32Array(n).fill(arrowSize * 1.1);+ const geom = new THREE.BufferGeometry();+ geom.setAttribute('position', new THREE.BufferAttribute(pos, 3).setUsage(THREE.DynamicDrawUsage));+ geom.setAttribute('aAlpha', new THREE.BufferAttribute(alpha, 1));+ geom.setAttribute('aSize', new THREE.BufferAttribute(size, 1));+ const mat = pointsMaterial(flow.color, true);+ const points = new THREE.Points(geom, mat);+ points.frustumCulled = false;+ points.renderOrder = 11;+ group.add(points);++ const tmp = new THREE.Vector3();+ let dim = 1;+ // Speed is in path lengths per second at 1x; flows of very different+ // lengths stay readable because particles keep their spacing.+ return {+ object: group,+ curve,+ update(time, _dt, f) {+ mat.uniforms.uPixelScale.value = f.pixelScale;+ const travel = time * flow.speed;+ for (let i = 0; i < n; i++) {+ let u = (i / n + travel) % 1;+ if (!flow.closed) {+ alpha[i] = Math.min(1, u * 8, (1 - u) * 8);+ }+ curve.getPointAt(u, tmp);+ pos[i * 3] = tmp.x;+ pos[i * 3 + 1] = tmp.y;+ pos[i * 3 + 2] = tmp.z;+ }+ geom.attributes.position.needsUpdate = true;+ if (!flow.closed) geom.attributes.aAlpha.needsUpdate = true;+ mat.uniforms.uDim.value = dim;+ },+ setDim(d) {+ dim = d;+ guideMat.opacity = 0.55 * d;+ arrowMat.opacity = 0.9 * d;+ },+ dispose() {+ guideGeom.dispose();+ arrowGeom.dispose();+ arrowMat.dispose();+ geom.dispose();+ mat.dispose();+ },+ };+}diff --git a/src/anatomy/runtime.js b/src/anatomy/runtime.jsnew file mode 100644index 000000000..567ac273f--- /dev/null+++ b/src/anatomy/runtime.js@@ -0,0 +1,495 @@+// Anatomy runtime: mounts a full interactive machine explorer for one spec.+//+// The mount function returns a controller. Its update method takes a grown+// spec while one streams in (progressive mode keeps the camera steady), and+// dispose tears everything down.+//+// The same runtime powers /anatomy, /anatomy/:id permalinks and the standalone+// HTML the agent skill writes (via the /anatomy-runtime.js bundle).++import { AnatomyViewer } from './viewer.js';+import { normalizeSpec } from './spec.js';++const ICONS = {+ play: '<path d="M7 5v14l11-7z" fill="currentColor"/>',+ pause: '<path d="M7 5h4v14H7zM13 5h4v14h-4z" fill="currentColor"/>',+ explode: '<path d="M12 3v5M12 16v5M3 12h5M16 12h5M6 6l3 3M15 15l3 3M18 6l-3 3M9 15l-3 3" stroke="currentColor" stroke-width="1.8" fill="none" stroke-linecap="round"/>',+ section: '<path d="M4 4h16v16H4z" stroke="currentColor" stroke-width="1.6" fill="none"/><path d="M12 4v16" stroke="currentColor" stroke-width="1.8" stroke-dasharray="2 2"/><path d="M12 4h8v16h-8z" fill="currentColor" opacity=".25"/>',+ xray: '<circle cx="12" cy="12" r="7.5" stroke="currentColor" stroke-width="1.6" fill="none"/><circle cx="12" cy="12" r="3.5" stroke="currentColor" stroke-width="1.6" fill="none" stroke-dasharray="2 1.6"/>',+ labels: '<path d="M4 6h10l4 4-4 4H4z" stroke="currentColor" stroke-width="1.6" fill="none" stroke-linejoin="round"/><path d="M7 18h10" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/>',+ reset: '<path d="M5 12a7 7 0 1 0 2.1-5" stroke="currentColor" stroke-width="1.8" fill="none" stroke-linecap="round"/><path d="M4 4v4h4" stroke="currentColor" stroke-width="1.8" fill="none" stroke-linecap="round" stroke-linejoin="round"/>',+ camera: '<path d="M4 8h3l2-3h6l2 3h3v11H4z" stroke="currentColor" stroke-width="1.6" fill="none" stroke-linejoin="round"/><circle cx="12" cy="13" r="3.5" stroke="currentColor" stroke-width="1.6" fill="none"/>',+ full: '<path d="M4 9V4h5M15 4h5v5M20 15v5h-5M9 20H4v-5" stroke="currentColor" stroke-width="1.8" fill="none" stroke-linecap="round"/>',+ eye: '<path d="M2 12s3.6-6 10-6 10 6 10 6-3.6 6-10 6S2 12 2 12z" stroke="currentColor" stroke-width="1.6" fill="none"/><circle cx="12" cy="12" r="2.8" fill="currentColor"/>',+ eyeOff: '<path d="M3 3l18 18M10.6 6.1A10.7 10.7 0 0 1 12 6c6.4 0 10 6 10 6a17 17 0 0 1-3.1 3.7M6.5 7.6C3.8 9.3 2 12 2 12s3.6 6 10 6c1.6 0 3-.4 4.2-.9" stroke="currentColor" stroke-width="1.6" fill="none" stroke-linecap="round"/>',+ tour: '<path d="M5 4h11l3 3v13H5z" stroke="currentColor" stroke-width="1.6" fill="none" stroke-linejoin="round"/><path d="M8 10h8M8 14h8M8 18h5" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/>',+ prev: '<path d="M15 5l-7 7 7 7" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/>',+ next: '<path d="M9 5l7 7-7 7" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/>',+ close: '<path d="M6 6l12 12M18 6L6 18" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>',+ spin: '<path d="M20 12a8 8 0 1 1-3-6.2" stroke="currentColor" stroke-width="1.8" fill="none" stroke-linecap="round"/><path d="M18 3v4h-4" stroke="currentColor" stroke-width="1.8" fill="none" stroke-linecap="round" stroke-linejoin="round"/>',+ panel: '<rect x="3" y="4" width="18" height="16" rx="2" stroke="currentColor" stroke-width="1.6" fill="none"/><path d="M15 4v16" stroke="currentColor" stroke-width="1.6"/>',+};++const icon = (name) => `<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false">${ICONS[name]}</svg>`;++function h(tag, attrs = {}, children = []) {+ const el = document.createElement(tag);+ for (const [k, v] of Object.entries(attrs)) {+ if (v == null || v === false) continue;+ if (k === 'class') el.className = v;+ else if (k === 'html') el.innerHTML = v;+ else if (k === 'text') el.textContent = v;+ else if (k.startsWith('on')) el.addEventListener(k.slice(2), v);+ else el.setAttribute(k, v === true ? '' : v);+ }+ for (const c of [].concat(children)) if (c != null) el.append(c);+ return el;+}++const SHAPE_NAMES = {+ box: 'Block',+ cylinder: 'Cylinder',+ tube: 'Tube',+ cone: 'Cone',+ sphere: 'Sphere',+ capsule: 'Capsule',+ torus: 'Ring',+ gear: 'Gear',+ rotor: 'Bladed rotor',+ lathe: 'Turned profile',+ extrude: 'Extruded profile',+ spring: 'Spring',+ pipe: 'Pipe',+};++function describeMotion(m) {+ if (m.type === 'spin') {+ const rpm = Math.abs(m.speed) * 60;+ return `Spins about ${m.axis.toUpperCase()} (${rpm >= 10 ? Math.round(rpm) : rpm.toFixed(1)} rpm shown)`;+ }+ if (m.type === 'oscillate') return m.kind === 'rotate' ? `Rocks ±${Math.abs(m.amplitude)}° about ${m.axis.toUpperCase()}` : `Reciprocates along ${m.axis.toUpperCase()}`;+ if (m.type === 'crank') return `Driven by a crank along ${m.axis.toUpperCase()} (stroke ${(m.radius * 2).toFixed(2)})`;+ if (m.type === 'pulse') return 'Pulses';+ return '';+}++function paragraphs(text) {+ const frag = document.createDocumentFragment();+ for (const p of String(text || '').split(/\n{2,}/)) if (p.trim()) frag.append(h('p', { text: p.trim() }));+ return frag;+}++/**+ * Mount the explorer. `spec` may be raw (it is normalized here) or already+ * normalized. Options:+ * theme 'auto' | 'dark' | 'light'+ * compact start with the side panel collapsed (embeds, narrow screens)+ * header render the title block inside the explorer (standalone pages)+ * onSelect (partId|null) => void+ */+export function mountAnatomy(el, specIn, opts = {}) {+ const root = h('div', { class: 'anx', tabindex: '0', role: 'application', 'aria-label': 'Machine explorer' });+ const stage = h('div', { class: 'anx-stage' });+ const tooltip = h('div', { class: 'anx-tooltip', role: 'status', hidden: true });+ const side = h('aside', { class: 'anx-side', 'aria-label': 'Parts and tour' });+ const toolbar = h('div', { class: 'anx-toolbar', role: 'toolbar', 'aria-label': 'View controls' });+ const tourCard = h('section', { class: 'anx-tour', hidden: true, 'aria-live': 'polite' });+ const hint = h('div', { class: 'anx-hint', text: 'Drag to rotate · Scroll to zoom · Click a part' });+ const header = opts.header ? h('header', { class: 'anx-header' }) : null;+ stage.append(tooltip, tourCard, hint);+ root.append(...[header, stage, side, toolbar].filter(Boolean));+ el.append(root);++ let spec = null;+ let selected = null;+ let step = -1;+ let explodeTarget = 0;+ let explodeValue = 0;+ let explodeRaf = 0;+ const compact = opts.compact ?? window.matchMedia?.('(max-width: 760px)').matches;+ if (compact) root.classList.add('is-collapsed');++ const viewer = new AnatomyViewer(stage, {+ theme: opts.theme || 'auto',+ onHover: (id, ev) => showTooltip(id, ev),+ onSelect: (id) => select(id),+ });++ // ------------------------------------------------------------- toolbar++ const btn = (name, label, onClick, extra = {}) => h('button', { type: 'button', class: 'anx-btn', 'aria-label': label, title: label, html: icon(name), onclick: onClick, ...extra });+ const playBtn = btn('pause', 'Pause (Space)', () => setPlaying(!viewer.state.playing), { 'aria-pressed': 'true' });+ const speedSel = h('select', { class: 'anx-select', 'aria-label': 'Animation speed', title: 'Animation speed' }, [+ ...[0.1, 0.25, 0.5, 1, 2].map((s) => h('option', { value: String(s), text: `${s}x`, selected: s === 1 })),+ ]);+ speedSel.addEventListener('change', () => viewer.setSpeed(Number(speedSel.value)));+ const explodeInput = h('input', { type: 'range', min: '0', max: '1', step: '0.01', value: '0', class: 'anx-range', 'aria-label': 'Explode parts' });+ explodeInput.addEventListener('input', () => {+ explodeTarget = explodeValue = Number(explodeInput.value);+ viewer.setExplode(explodeValue);+ explodeBtn.setAttribute('aria-pressed', String(explodeValue > 0));+ });+ const explodeBtn = btn('explode', 'Explode view (E)', () => animateExplode(explodeTarget > 0 ? 0 : 0.8), { 'aria-pressed': 'false' });+ const sectionSel = h('select', { class: 'anx-select', 'aria-label': 'Section cut axis', title: 'Section cut' }, [+ h('option', { value: '', text: 'No cut' }),+ h('option', { value: 'z', text: 'Cut Z' }),+ h('option', { value: 'x', text: 'Cut X' }),+ h('option', { value: 'y', text: 'Cut Y' }),+ ]);+ const sectionInput = h('input', { type: 'range', min: '0', max: '1', step: '0.005', value: '0.5', class: 'anx-range', 'aria-label': 'Section cut position', disabled: true });+ sectionSel.addEventListener('change', () => applySectionUI(sectionSel.value || null));+ sectionInput.addEventListener('input', () => viewer.setSection(viewer.state.section, Number(sectionInput.value)));+ const xrayBtn = btn('xray', 'X-ray (X)', () => toggle(xrayBtn, (on) => viewer.setXray(on)), { 'aria-pressed': 'false' });+ const labelsBtn = btn('labels', 'Labels (L)', () => toggle(labelsBtn, (on) => viewer.setLabels(on)), { 'aria-pressed': 'true' });+ const viewSel = h('select', { class: 'anx-select', 'aria-label': 'Camera view', title: 'Camera view' }, [+ h('option', { value: 'iso', text: 'Isometric' }),+ h('option', { value: 'front', text: 'Front' }),+ h('option', { value: 'side', text: 'Side' }),+ h('option', { value: 'top', text: 'Top' }),+ ]);+ viewSel.addEventListener('change', () => viewer.setView(viewSel.value));+ const resetBtn = btn('reset', 'Reset view (R)', () => {+ viewSel.value = 'iso';+ viewer.resetView();+ });+ const shotBtn = btn('camera', 'Save image', () => saveImage());+ const fullBtn = btn('full', 'Fullscreen (F)', () => toggleFullscreen());+ const panelBtn = btn('panel', 'Toggle parts panel', () => {+ root.classList.toggle('is-collapsed');+ panelBtn.setAttribute('aria-pressed', String(!root.classList.contains('is-collapsed')));+ }, { 'aria-pressed': String(!compact) });++ toolbar.append(+ h('div', { class: 'anx-tgroup' }, [playBtn, speedSel]),+ h('div', { class: 'anx-tgroup' }, [explodeBtn, explodeInput]),+ h('div', { class: 'anx-tgroup' }, [h('span', { class: 'anx-ticon', html: icon('section') }), sectionSel, sectionInput]),+ h('div', { class: 'anx-tgroup' }, [xrayBtn, labelsBtn, viewSel, resetBtn]),+ h('div', { class: 'anx-tgroup anx-tgroup-end' }, [shotBtn, fullBtn, panelBtn]),+ );++ function toggle(button, fn) {+ const on = button.getAttribute('aria-pressed') !== 'true';+ button.setAttribute('aria-pressed', String(on));+ fn(on);+ }++ function setPlaying(on) {+ viewer.setPlaying(on);+ playBtn.innerHTML = icon(on ? 'pause' : 'play');+ playBtn.setAttribute('aria-pressed', String(on));+ playBtn.setAttribute('aria-label', on ? 'Pause (Space)' : 'Play (Space)');+ playBtn.title = on ? 'Pause (Space)' : 'Play (Space)';+ }++ function animateExplode(to) {+ explodeTarget = to;+ explodeBtn.setAttribute('aria-pressed', String(to > 0));+ cancelAnimationFrame(explodeRaf);+ const from = explodeValue;+ const start = performance.now();+ const run = (now) => {+ const k = Math.min(1, (now - start) / 650);+ const e = 1 - (1 - k) ** 3;+ explodeValue = from + (to - from) * e;+ viewer.setExplode(explodeValue);+ explodeInput.value = String(explodeValue);+ if (k < 1) explodeRaf = requestAnimationFrame(run);+ };+ explodeRaf = requestAnimationFrame(run);+ }++ function applySectionUI(axis) {+ sectionSel.value = axis || '';+ sectionInput.disabled = !axis;+ viewer.setSection(axis, Number(sectionInput.value));+ }++ async function saveImage() {+ shotBtn.disabled = true;+ try {+ const blob = await viewer.screenshot();+ if (!blob) throw new Error('The browser could not capture the canvas.');+ const a = h('a', { href: URL.createObjectURL(blob), download: `${(spec?.title || 'machine').toLowerCase().replace(/[^a-z0-9]+/g, '-')}.png` });+ document.body.append(a);+ a.click();+ a.remove();+ setTimeout(() => URL.revokeObjectURL(a.href), 4000);+ } catch (err) {+ flash(err.message || 'Could not save the image.');+ } finally {+ shotBtn.disabled = false;+ }+ }++ function toggleFullscreen() {+ if (document.fullscreenElement) document.exitFullscreen?.();+ else root.requestFullscreen?.().catch(() => flash('Fullscreen is blocked in this frame.'));+ }++ const flashEl = h('div', { class: 'anx-flash', role: 'alert', hidden: true });+ stage.append(flashEl);+ let flashTimer = 0;+ function flash(msg) {+ flashEl.textContent = msg;+ flashEl.hidden = false;+ clearTimeout(flashTimer);+ flashTimer = setTimeout(() => (flashEl.hidden = true), 3200);+ }++ // ------------------------------------------------------------- tooltip++ let lastTip = null;+ function showTooltip(id, ev) {+ if (!id || !spec || !ev) {+ tooltip.hidden = true;+ lastTip = null;+ return;+ }+ const part = spec.parts.find((p) => p.id === id);+ if (!part) return;+ if (lastTip !== id) {+ tooltip.replaceChildren(h('strong', { text: part.name }), part.group ? h('span', { class: 'anx-tip-group', text: part.group }) : null);+ lastTip = id;+ }+ const rect = stage.getBoundingClientRect();+ const x = ev.clientX - rect.left;+ const y = ev.clientY - rect.top;+ tooltip.hidden = false;+ const flip = x > rect.width - 220;+ tooltip.style.transform = `translate(${flip ? x - tooltip.offsetWidth - 14 : x + 14}px, ${y + 14}px)`;+ }++ // ----------------------------------------------------------- side panel++ const tabs = h('div', { class: 'anx-tabs', role: 'tablist' });+ const partsTab = h('button', { type: 'button', class: 'anx-tab', role: 'tab', 'aria-selected': 'true', text: 'Parts' });+ const tourTab = h('button', { type: 'button', class: 'anx-tab', role: 'tab', 'aria-selected': 'false', text: 'How it works' });+ tabs.append(partsTab, tourTab);+ const partsPane = h('div', { class: 'anx-pane', role: 'tabpanel' });+ const tourPane = h('div', { class: 'anx-pane', role: 'tabpanel', hidden: true });+ const inspector = h('section', { class: 'anx-inspector', hidden: true, 'aria-live': 'polite' });+ side.append(tabs, inspector, partsPane, tourPane);+ const showTab = (which) => {+ partsTab.setAttribute('aria-selected', String(which === 'parts'));+ tourTab.setAttribute('aria-selected', String(which === 'tour'));+ partsPane.hidden = which !== 'parts';+ tourPane.hidden = which !== 'tour';+ };+ partsTab.addEventListener('click', () => showTab('parts'));+ tourTab.addEventListener('click', () => showTab('tour'));++ const rowById = new Map();+ function renderParts() {+ rowById.clear();+ const groups = new Map();+ for (const p of spec.parts) {+ const g = p.group || 'Parts';+ if (!groups.has(g)) groups.set(g, []);+ groups.get(g).push(p);+ }+ const frag = document.createDocumentFragment();+ for (const [g, list] of groups) {+ const ul = h('ul', { class: 'anx-plist' });+ for (const p of list) {+ const color = viewer.parts.get(p.id)?.color.getStyle() || '#888';+ const vis = h('button', { type: 'button', class: 'anx-eye', 'aria-label': `Hide ${p.name}`, title: 'Hide', html: icon('eye') });+ vis.addEventListener('click', (e) => {+ e.stopPropagation();+ const hidden = !viewer.hidden.has(p.id);+ viewer.setPartVisible(p.id, !hidden);+ vis.innerHTML = icon(hidden ? 'eyeOff' : 'eye');+ vis.setAttribute('aria-label', `${hidden ? 'Show' : 'Hide'} ${p.name}`);+ vis.title = hidden ? 'Show' : 'Hide';+ row.classList.toggle('is-hidden', hidden);+ });+ const count = p.repeat?.count > 1 ? h('span', { class: 'anx-count', text: `×${p.repeat.count}` }) : null;+ const moving = p.motion.length ? h('span', { class: 'anx-moving', title: 'Moves', html: icon('spin') }) : null;+ const name = h('button', { type: 'button', class: 'anx-pname' }, [h('span', { class: 'anx-swatch', style: `--c:${color}` }), h('span', { class: 'anx-ptext', text: p.name }), count, moving]);+ name.addEventListener('click', () => select(selected === p.id ? null : p.id, { focus: true }));+ name.addEventListener('mouseenter', () => viewer.setHover(p.id));+ name.addEventListener('mouseleave', () => viewer.setHover(null));+ const row = h('li', { class: 'anx-prow', 'data-part': p.id }, [name, vis]);+ if (viewer.hidden.has(p.id)) row.classList.add('is-hidden');+ rowById.set(p.id, row);+ ul.append(row);+ }+ frag.append(h('div', { class: 'anx-pgroup' }, [h('h3', { class: 'anx-gtitle', text: `${g}`, 'data-count': String(list.length) }), ul]));+ }+ const extras = [...spec.effects.map((e) => ['Effect', e]), ...spec.flows.map((f) => ['Flow', f])];+ if (extras.length) {+ const ul = h('ul', { class: 'anx-plist' });+ for (const [kind, e] of extras) {+ const b = h('button', { type: 'button', class: 'anx-pname' }, [h('span', { class: 'anx-swatch is-fx', style: `--c:${e.color}` }), h('span', { class: 'anx-ptext', text: e.name }), h('span', { class: 'anx-count', text: kind === 'Flow' ? 'flow' : e.type })]);+ b.addEventListener('click', () => {+ selectExtra(e, kind);+ });+ ul.append(h('li', { class: 'anx-prow' }, [b]));+ }+ frag.append(h('div', { class: 'anx-pgroup' }, [h('h3', { class: 'anx-gtitle', text: 'Effects and flows', 'data-count': String(extras.length) }), ul]));+ }+ partsPane.replaceChildren(frag);+ if (selected && rowById.has(selected)) rowById.get(selected).classList.add('is-selected');+ }++ function renderInspector(item, kind) {+ if (!item) {+ inspector.hidden = true;+ return;+ }+ const meta = [];+ if (kind === 'part') {+ meta.push(SHAPE_NAMES[item.shape.type] || item.shape.type);+ if (item.repeat?.count > 1) meta.push(`${item.repeat.count} copies`);+ for (const m of item.motion) meta.push(describeMotion(m));+ } else meta.push(kind === 'Flow' ? 'Flow path' : `${item.type[0].toUpperCase()}${item.type.slice(1)} effect`);+ const close = h('button', { type: 'button', class: 'anx-btn anx-btn-sm', 'aria-label': 'Close details', html: icon('close'), onclick: () => select(null) });+ inspector.replaceChildren(+ h('div', { class: 'anx-ihead' }, [h('div', {}, [item.group ? h('div', { class: 'anx-eyebrow', text: item.group }) : null, h('h2', { class: 'anx-ititle', text: item.name })]), close]),+ h('div', { class: 'anx-imeta' }, meta.filter(Boolean).map((m) => h('span', { text: m }))),+ item.description ? h('div', { class: 'anx-ibody' }, [paragraphs(item.description)]) : h('p', { class: 'anx-ibody anx-muted', text: 'No description for this part.' }),+ );+ inspector.hidden = false;+ }++ function select(id, { focus = false } = {}) {+ if (!spec) return;+ selected = id && spec.parts.some((p) => p.id === id) ? id : null;+ viewer.setSelected(selected);+ for (const [pid, row] of rowById) row.classList.toggle('is-selected', pid === selected);+ renderInspector(selected ? spec.parts.find((p) => p.id === selected) : null, 'part');+ if (selected) {+ showTab('parts');+ if (root.classList.contains('is-collapsed') && !compact) root.classList.remove('is-collapsed');+ rowById.get(selected)?.scrollIntoView({ block: 'nearest' });+ }+ if (focus && step < 0) viewer.focusOn(selected ? [selected] : null);+ opts.onSelect?.(selected);+ }++ function selectExtra(item, kind) {+ selected = null;+ viewer.setSelected(null);+ for (const row of rowById.values()) row.classList.remove('is-selected');+ renderInspector(item, kind);+ if (step < 0) viewer.focusOn([item.id]);+ }++ // ---------------------------------------------------------------- tour++ function renderTourPane() {+ if (!spec.steps.length) {+ tourPane.replaceChildren(h('p', { class: 'anx-muted anx-pad', text: 'This machine has no guided tour. Click any part to read what it does.' }));+ tourTab.hidden = true;+ return;+ }+ tourTab.hidden = false;+ const start = h('button', { type: 'button', class: 'anx-cta', html: `${icon('tour')}<span>Start the tour</span>`, onclick: () => setStep(0) });+ const ol = h('ol', { class: 'anx-steps' });+ spec.steps.forEach((s, i) => {+ const b = h('button', { type: 'button', class: 'anx-step', onclick: () => setStep(i) }, [h('span', { class: 'anx-stepn', text: String(i + 1) }), h('span', { text: s.title })]);+ if (i === step) b.classList.add('is-active');+ ol.append(h('li', {}, [b]));+ });+ tourPane.replaceChildren(h('div', { class: 'anx-pad' }, [spec.summary ? h('div', { class: 'anx-summary' }, [paragraphs(spec.summary)]) : null, start]), ol);+ }++ function setStep(i) {+ if (!spec?.steps.length) return;+ if (i < 0 || i >= spec.steps.length) {+ step = -1;+ tourCard.hidden = true;+ viewer.setFocus(null);+ root.classList.remove('is-touring');+ renderTourPane();+ return;+ }+ step = i;+ const s = spec.steps[i];+ root.classList.add('is-touring');+ viewer.setFocus(s.focus);+ const prev = h('button', { type: 'button', class: 'anx-btn', 'aria-label': 'Previous step', html: icon('prev'), disabled: i === 0, onclick: () => setStep(i - 1) });+ const last = i === spec.steps.length - 1;+ const next = h('button', { type: 'button', class: 'anx-btn anx-btn-primary', 'aria-label': last ? 'Finish tour' : 'Next step', html: last ? '<span>Done</span>' : icon('next'), onclick: () => setStep(last ? -1 : i + 1) });+ const exit = h('button', { type: 'button', class: 'anx-btn anx-btn-sm', 'aria-label': 'Exit tour', html: icon('close'), onclick: () => setStep(-1) });+ const dots = h('div', { class: 'anx-dots', 'aria-hidden': 'true' }, spec.steps.map((_, k) => h('span', { class: k === i ? 'is-on' : '' })));+ tourCard.replaceChildren(+ h('div', { class: 'anx-tour-head' }, [h('span', { class: 'anx-eyebrow', text: `Step ${i + 1} of ${spec.steps.length}` }), exit]),+ h('h2', { class: 'anx-tour-title', text: s.title }),+ h('div', { class: 'anx-tour-body' }, [paragraphs(s.body)]),+ h('div', { class: 'anx-tour-foot' }, [dots, h('div', { class: 'anx-tour-nav' }, [prev, next])]),+ );+ tourCard.hidden = false;+ renderTourPane();+ }++ // ---------------------------------------------------------------- header++ function renderHeader() {+ if (!header) return;+ header.replaceChildren(h('h1', { class: 'anx-title', text: spec.title }), spec.subtitle ? h('p', { class: 'anx-subtitle', text: spec.subtitle }) : null);+ }++ // ------------------------------------------------------------- keyboard++ function onKey(e) {+ if (e.target.closest('input, select, textarea') || e.metaKey || e.ctrlKey || e.altKey) return;+ const k = e.key;+ if (k === ' ') setPlaying(!viewer.state.playing);+ else if (k === 'ArrowRight' && spec?.steps.length) setStep(step < 0 ? 0 : Math.min(step + 1, spec.steps.length - 1));+ else if (k === 'ArrowLeft' && step > 0) setStep(step - 1);+ else if (k === 'Escape') {+ if (step >= 0) setStep(-1);+ else select(null, { focus: true });+ } else if (k === 'e' || k === 'E') animateExplode(explodeTarget > 0 ? 0 : 0.8);+ else if (k === 'x' || k === 'X') xrayBtn.click();+ else if (k === 'l' || k === 'L') labelsBtn.click();+ else if (k === 'r' || k === 'R') resetBtn.click();+ else if (k === 'f' || k === 'F') toggleFullscreen();+ else return;+ e.preventDefault();+ }+ root.addEventListener('keydown', onKey);+ const onFs = () => root.classList.toggle('is-fullscreen', document.fullscreenElement === root);+ document.addEventListener('fullscreenchange', onFs);++ // ---------------------------------------------------------------- load++ function update(next, { progressive = false } = {}) {+ const normalized = next?.version && Array.isArray(next.parts) && next.view ? next : normalizeSpec(next, { strict: !progressive }).spec;+ spec = normalized;+ const res = viewer.load(spec, { progressive });+ if (!progressive) {+ if (spec.view.explode > 0 && explodeTarget === 0) animateExplode(spec.view.explode);+ else viewer.setExplode(explodeValue);+ if (spec.view.section && !viewer.state.section) applySectionUI(spec.view.section);+ } else viewer.setExplode(explodeValue);+ if (selected && !spec.parts.some((p) => p.id === selected)) selected = null;+ if (step >= spec.steps.length) step = -1;+ renderParts();+ renderTourPane();+ renderHeader();+ root.classList.toggle('has-tour', spec.steps.length > 0);+ if (res.truncated) flash('This machine is very large; some repeated copies were left out.');+ return res;+ }++ if (specIn) update(specIn);++ return {+ viewer,+ root,+ update,+ select,+ setStep,+ get spec() {+ return spec;+ },+ dispose() {+ cancelAnimationFrame(explodeRaf);+ clearTimeout(flashTimer);+ document.removeEventListener('fullscreenchange', onFs);+ viewer.dispose();+ root.remove();+ },+ };+}diff --git a/src/anatomy/shapes.js b/src/anatomy/shapes.jsnew file mode 100644index 000000000..a579e0910--- /dev/null+++ b/src/anatomy/shapes.js@@ -0,0 +1,353 @@+// Anatomy geometry: one spec shape → a smooth fill mesh plus a technical+// line drawing of it.+//+// The look is an engineering illustration, not a triangle wireframe: surfaces+// of revolution are drawn with meridians and parallels, extrusions and gears+// with their real crease edges, sweeps with a centreline and section rings.+// Every builder works along +Y and orient() turns the result onto the spec's+// axis, so "axis": "x" means the same thing for every shape.++import * as THREE from 'three';+import { RoundedBoxGeometry } from 'three/addons/geometries/RoundedBoxGeometry.js';+import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';++const FILL_SEGMENTS = 48;+const MERIDIANS = 12;+const CIRCLE_SEGMENTS = 48;+const TAU = Math.PI * 2;++function orient(geom, axis) {+ if (axis === 'x') geom.rotateZ(-Math.PI / 2);+ else if (axis === 'z') geom.rotateX(Math.PI / 2);+ return geom;+}++function orientPositions(positions, axis) {+ if (axis === 'y') return positions;+ const out = new Float32Array(positions.length);+ for (let i = 0; i < positions.length; i += 3) {+ const x = positions[i];+ const y = positions[i + 1];+ const z = positions[i + 2];+ if (axis === 'x') {+ out[i] = y;+ out[i + 1] = -x;+ out[i + 2] = z;+ } else {+ out[i] = x;+ out[i + 1] = -z;+ out[i + 2] = y;+ }+ }+ return out;+}++function edgePositions(geom, threshold = 20) {+ const edges = new THREE.EdgesGeometry(geom, threshold);+ const arr = Float32Array.from(edges.getAttribute('position').array);+ edges.dispose();+ return arr;+}++function circleSegments(out, r, y, segments = CIRCLE_SEGMENTS) {+ if (r < 1e-5) return;+ for (let i = 0; i < segments; i++) {+ const a0 = (i / segments) * TAU;+ const a1 = ((i + 1) / segments) * TAU;+ out.push(Math.cos(a0) * r, y, Math.sin(a0) * r, Math.cos(a1) * r, y, Math.sin(a1) * r);+ }+}++/**+ * Lines for a surface of revolution about +Y: a parallel (circle) at each+ * ring point and a meridian (the profile itself) at evenly spaced angles.+ * `profile` and `rings` are [radius, y] pairs.+ */+function revolutionLines(profile, rings = profile, meridians = MERIDIANS) {+ const out = [];+ for (const [r, y] of rings) circleSegments(out, r, y);+ for (let m = 0; m < meridians; m++) {+ const a = (m / meridians) * TAU;+ const c = Math.cos(a);+ const s = Math.sin(a);+ for (let i = 0; i < profile.length - 1; i++) {+ const [r0, y0] = profile[i];+ const [r1, y1] = profile[i + 1];+ out.push(c * r0, y0, s * r0, c * r1, y1, s * r1);+ }+ }+ return new Float32Array(out);+}++function lathe(profile, segments = FILL_SEGMENTS) {+ const pts = profile.map(([r, y]) => new THREE.Vector2(Math.max(r, 0), y));+ return new THREE.LatheGeometry(pts, segments);+}++function arcProfile(radius, from, to, steps, cx = 0, cy = 0) {+ const out = [];+ for (let i = 0; i <= steps; i++) {+ const t = from + ((to - from) * i) / steps;+ out.push([cx + Math.cos(t) * radius, cy + Math.sin(t) * radius]);+ }+ return out;+}++function gearShape({ teeth, radius, toothDepth, bore }) {+ const shape = new THREE.Shape();+ const root = radius - toothDepth;+ const step = TAU / teeth;+ // Trapezoidal teeth: root land, flank up, tip land, flank down.+ for (let i = 0; i < teeth; i++) {+ const a = i * step;+ const pts = [+ [root, a],+ [root, a + step * 0.18],+ [radius, a + step * 0.32],+ [radius, a + step * 0.58],+ [root, a + step * 0.72],+ ];+ for (const [j, [r, t]] of pts.entries()) {+ const x = Math.cos(t) * r;+ const y = Math.sin(t) * r;+ if (i === 0 && j === 0) shape.moveTo(x, y);+ else shape.lineTo(x, y);+ }+ }+ shape.closePath();+ if (bore > 0) {+ const hole = new THREE.Path();+ hole.absarc(0, 0, bore, 0, TAU, true);+ shape.holes.push(hole);+ }+ return shape;+}++// Extrude a 2D shape along +Y, centred on y = 0.+function extrudeY(shape, depth, curveSegments = 24) {+ const g = new THREE.ExtrudeGeometry(shape, { depth, bevelEnabled: false, curveSegments });+ g.translate(0, 0, -depth / 2);+ g.rotateX(-Math.PI / 2);+ return g;+}++function rotorGeometry(s) {+ const parts = [];+ const span = Math.max(s.radius - s.hubRadius, s.radius * 0.05);+ const spanSegs = 6;+ for (let b = 0; b < s.blades; b++) {+ const blade = new THREE.BoxGeometry(span, s.chord, s.thickness, spanSegs, 1, 1);+ blade.translate(s.hubRadius + span / 2 - s.radius * 0.01, 0, 0);+ const p = blade.getAttribute('position');+ const v = new THREE.Vector3();+ for (let i = 0; i < p.count; i++) {+ v.fromBufferAttribute(p, i);+ const t = (v.x - s.hubRadius) / span;+ const ang = THREE.MathUtils.degToRad(s.pitch - s.twist * (t - 0.5));+ const y = v.y * Math.cos(ang) - v.z * Math.sin(ang);+ const z = v.y * Math.sin(ang) + v.z * Math.cos(ang);+ // Blades taper slightly toward the tip.+ const taper = 1 - 0.25 * Math.max(0, t);+ p.setXYZ(i, v.x, y * taper, z);+ }+ blade.computeVertexNormals();+ blade.rotateY((b / s.blades) * TAU);+ parts.push(blade.toNonIndexed());+ blade.dispose();+ }+ const hubLen = Math.max(s.hubLength, s.chord * 1.1);+ const hub = new THREE.CylinderGeometry(s.hubRadius, s.hubRadius, hubLen, 32, 1).toNonIndexed();+ parts.push(hub);+ for (const g of parts) {+ if (g.getAttribute('uv')) g.deleteAttribute('uv');+ }+ const merged = mergeGeometries(parts, false);+ for (const g of parts) g.dispose();+ merged.computeVertexNormals();+ return { merged, hubLen };+}++function helixCurve(radius, turns, length) {+ const pts = [];+ const n = Math.max(24, Math.ceil(turns * 24));+ for (let i = 0; i <= n; i++) {+ const t = i / n;+ const a = t * turns * TAU;+ pts.push(new THREE.Vector3(Math.cos(a) * radius, -length / 2 + t * length, Math.sin(a) * radius));+ }+ return new THREE.CatmullRomCurve3(pts);+}++function sweepLines(curve, radius, rings = 8, samples = 64) {+ const out = [];+ const pts = curve.getSpacedPoints(samples);+ for (let i = 0; i < pts.length - 1; i++) out.push(pts[i].x, pts[i].y, pts[i].z, pts[i + 1].x, pts[i + 1].y, pts[i + 1].z);+ const frames = curve.computeFrenetFrames(rings, false);+ for (let r = 0; r <= rings; r++) {+ const u = r / rings;+ const c = curve.getPointAt(u);+ const n = frames.normals[r];+ const b = frames.binormals[r];+ const seg = 20;+ for (let i = 0; i < seg; i++) {+ const a0 = (i / seg) * TAU;+ const a1 = ((i + 1) / seg) * TAU;+ const p0 = c.clone().addScaledVector(n, Math.cos(a0) * radius).addScaledVector(b, Math.sin(a0) * radius);+ const p1 = c.clone().addScaledVector(n, Math.cos(a1) * radius).addScaledVector(b, Math.sin(a1) * radius);+ out.push(p0.x, p0.y, p0.z, p1.x, p1.y, p1.z);+ }+ }+ return new Float32Array(out);+}++/**+ * Build one shape. Returns { fill: BufferGeometry, lines: Float32Array } where+ * `lines` holds line-segment endpoint pairs (x0 y0 z0 x1 y1 z1 ...).+ */+export function buildShape(shape) {+ switch (shape.type) {+ case 'box': {+ const [w, h, d] = shape.size;+ const fill = shape.radius > 0 ? new RoundedBoxGeometry(w, h, d, 3, shape.radius) : new THREE.BoxGeometry(w, h, d);+ const plain = new THREE.BoxGeometry(w, h, d);+ const lines = edgePositions(plain, 10);+ plain.dispose();+ return { fill, lines };+ }+ case 'cylinder': {+ const { radiusTop: rt, radiusBottom: rb, length: l, open } = shape;+ const fill = orient(new THREE.CylinderGeometry(rt, rb, l, FILL_SEGMENTS, 1, open), shape.axis);+ const profile = [+ [rb, -l / 2],+ [rt, l / 2],+ ];+ return { fill, lines: orientPositions(revolutionLines(profile), shape.axis) };+ }+ case 'cone': {+ const l = shape.length;+ const fill = orient(new THREE.ConeGeometry(shape.radius, l, FILL_SEGMENTS, 1), shape.axis);+ const profile = [+ [shape.radius, -l / 2],+ [0, l / 2],+ ];+ return { fill, lines: orientPositions(revolutionLines(profile, [profile[0]]), shape.axis) };+ }+ case 'tube': {+ const { outerRadius: ro, innerRadius: ri, length: l } = shape;+ const profile = [+ [ri, -l / 2],+ [ro, -l / 2],+ [ro, l / 2],+ [ri, l / 2],+ [ri, -l / 2],+ ];+ const fill = orient(lathe(profile), shape.axis);+ return { fill, lines: orientPositions(revolutionLines(profile, profile.slice(0, 4)), shape.axis) };+ }+ case 'sphere': {+ const r = shape.radius;+ const hemi = shape.hemisphere;+ const fill = orient(new THREE.SphereGeometry(r, FILL_SEGMENTS, 32, 0, TAU, 0, hemi ? Math.PI / 2 : Math.PI), shape.axis);+ const from = hemi ? 0 : -Math.PI / 2;+ const profile = arcProfile(r, from, Math.PI / 2, 24);+ const rings = arcProfile(r, from, Math.PI / 2, hemi ? 4 : 8).filter(([x]) => x > r * 0.05);+ // arcProfile yields [x, y] = [r cos t, r sin t]: x is the ring radius.+ return { fill, lines: orientPositions(revolutionLines(profile, rings), shape.axis) };+ }+ case 'capsule': {+ const { radius: r, length: l } = shape;+ const body = Math.max(l - 2 * r, 0);+ const fill = orient(new THREE.CapsuleGeometry(r, body, 12, FILL_SEGMENTS), shape.axis);+ const top = arcProfile(r, 0, Math.PI / 2, 10, 0, body / 2);+ const bottom = arcProfile(r, -Math.PI / 2, 0, 10, 0, -body / 2);+ const profile = [...bottom, ...top];+ const rings = [+ [r, -body / 2],+ [r, body / 2],+ [r * Math.cos(Math.PI / 4), body / 2 + r * Math.sin(Math.PI / 4)],+ [r * Math.cos(Math.PI / 4), -body / 2 - r * Math.sin(Math.PI / 4)],+ ];+ return { fill, lines: orientPositions(revolutionLines(profile, rings), shape.axis) };+ }+ case 'torus': {+ const { radius: R, tube: t } = shape;+ const arc = THREE.MathUtils.degToRad(shape.arc);+ // TorusGeometry lies in XY around Z; turn it so its axis is +Y.+ const fill = new THREE.TorusGeometry(R, t, 24, 96, arc);+ fill.rotateX(Math.PI / 2);+ orient(fill, shape.axis);+ const out = [];+ const minor = 16;+ const majorLines = 8;+ const ringCount = Math.max(6, Math.round((24 * arc) / TAU));+ for (let k = 0; k <= ringCount; k++) {+ if (arc >= TAU - 1e-6 && k === ringCount) break;+ const a = (k / ringCount) * arc;+ for (let i = 0; i < minor; i++) {+ const b0 = (i / minor) * TAU;+ const b1 = ((i + 1) / minor) * TAU;+ const p = (b) => [(R + t * Math.cos(b)) * Math.cos(a), t * Math.sin(b), (R + t * Math.cos(b)) * Math.sin(a)];+ out.push(...p(b0), ...p(b1));+ }+ }+ for (let j = 0; j < majorLines; j++) {+ const b = (j / majorLines) * TAU;+ const r = R + t * Math.cos(b);+ const y = t * Math.sin(b);+ const seg = 64;+ for (let i = 0; i < seg; i++) {+ const a0 = (i / seg) * arc;+ const a1 = ((i + 1) / seg) * arc;+ out.push(Math.cos(a0) * r, y, Math.sin(a0) * r, Math.cos(a1) * r, y, Math.sin(a1) * r);+ }+ }+ return { fill, lines: orientPositions(new Float32Array(out), shape.axis) };+ }+ case 'gear': {+ const fill = orient(extrudeY(gearShape(shape), shape.thickness, 24), shape.axis);+ const lines = edgePositions(fill, 25);+ return { fill, lines };+ }+ case 'rotor': {+ const { merged } = rotorGeometry(shape);+ orient(merged, shape.axis);+ return { fill: merged, lines: edgePositions(merged, 28) };+ }+ case 'lathe': {+ const profile = shape.profile;+ const fill = orient(lathe(profile), shape.axis);+ return { fill, lines: orientPositions(revolutionLines(profile), shape.axis) };+ }+ case 'extrude': {+ const s = new THREE.Shape(shape.points.map(([u, v]) => new THREE.Vector2(u, v)));+ const g = new THREE.ExtrudeGeometry(s, { depth: shape.depth, bevelEnabled: false, curveSegments: 12 });+ g.translate(0, 0, -shape.depth / 2);+ if (shape.axis === 'y') g.rotateX(-Math.PI / 2);+ else if (shape.axis === 'x') g.rotateY(Math.PI / 2);+ return { fill: g, lines: edgePositions(g, 20) };+ }+ case 'spring': {+ const curve = helixCurve(shape.radius, shape.turns, shape.length);+ const tubular = Math.min(1600, Math.max(48, Math.ceil(shape.turns * 32)));+ const fill = orient(new THREE.TubeGeometry(curve, tubular, shape.wire, 8, false), shape.axis);+ const pts = curve.getSpacedPoints(tubular);+ const out = [];+ for (let i = 0; i < pts.length - 1; i++) out.push(pts[i].x, pts[i].y, pts[i].z, pts[i + 1].x, pts[i + 1].y, pts[i + 1].z);+ return { fill, lines: orientPositions(new Float32Array(out), shape.axis) };+ }+ case 'pipe': {+ const curve = new THREE.CatmullRomCurve3(+ shape.path.map((p) => new THREE.Vector3(...p)),+ shape.closed,+ 'centripetal',+ );+ const tubular = Math.min(400, Math.max(24, shape.path.length * 16));+ const fill = new THREE.TubeGeometry(curve, tubular, shape.radius, 12, shape.closed);+ return { fill, lines: sweepLines(curve, shape.radius, Math.min(24, shape.path.length * 3)) };+ }+ default: {+ const fill = new THREE.BoxGeometry(1, 1, 1);+ return { fill, lines: edgePositions(fill) };+ }+ }+}diff --git a/src/anatomy/stream.js b/src/anatomy/stream.jsnew file mode 100644index 000000000..1f039e60b--- /dev/null+++ b/src/anatomy/stream.js@@ -0,0 +1,100 @@+// Read a spec while it is still being written.+//+// Claude streams the spec as one JSON document. Waiting for the closing brace+// would leave the stage empty for a minute, so the page scans the text so far+// and pulls out every array element that is already complete: each finished+// part appears the moment its closing brace arrives. The scanner tracks+// strings and escapes, so braces inside descriptions never confuse it.++const ARRAY_KEYS = new Set(['parts', 'effects', 'flows', 'steps']);+const STRING_KEYS = new Set(['title', 'subtitle', 'summary']);++/**+ * Scan partial JSON text. Returns+ * { title?, subtitle?, summary?, parts: [], effects: [], flows: [], steps: [] }+ * holding every top-level string field and every array element that has fully+ * arrived. Malformed elements are skipped, never thrown.+ */+export function scanPartialSpec(source) {+ const out = { parts: [], effects: [], flows: [], steps: [] };+ const s = String(source || '');+ const start = s.indexOf('{');+ if (start === -1) return out;++ let depth = 0;+ let inString = false;+ let escaped = false;+ let stringStart = -1;+ let lastKey = null; // most recent key string read at depth 1+ let expectingValue = false; // a ':' was seen after lastKey at depth 1+ let arrayKey = null; // which top-level array we are inside (depth 2)+ let elemStart = -1; // start of the current element at depth 3++ for (let i = start; i < s.length; i++) {+ const ch = s[i];+ if (inString) {+ if (escaped) escaped = false;+ else if (ch === '\\') escaped = true;+ else if (ch === '"') {+ inString = false;+ if (depth === 1) {+ const raw = s.slice(stringStart, i + 1);+ if (expectingValue) {+ if (STRING_KEYS.has(lastKey)) {+ try {+ out[lastKey] = JSON.parse(raw);+ } catch {+ /* incomplete escape; keep scanning */+ }+ }+ expectingValue = false;+ } else {+ try {+ lastKey = JSON.parse(raw);+ } catch {+ lastKey = null;+ }+ }+ }+ }+ continue;+ }+ if (ch === '"') {+ inString = true;+ stringStart = i;+ continue;+ }+ if (ch === ':' && depth === 1) {+ expectingValue = true;+ continue;+ }+ if (ch === ',' && depth === 1) {+ expectingValue = false;+ continue;+ }+ if (ch === '{' || ch === '[') {+ depth++;+ if (depth === 2) {+ arrayKey = ch === '[' && expectingValue && ARRAY_KEYS.has(lastKey) ? lastKey : null;+ expectingValue = false;+ } else if (depth === 3 && arrayKey && ch === '{') {+ elemStart = i;+ }+ continue;+ }+ if (ch === '}' || ch === ']') {+ if (depth === 3 && arrayKey && elemStart !== -1 && ch === '}') {+ try {+ out[arrayKey].push(JSON.parse(s.slice(elemStart, i + 1)));+ } catch {+ /* skip an element the model wrote badly */+ }+ elemStart = -1;+ }+ depth--;+ if (depth === 1) arrayKey = null;+ if (depth <= 0) break;+ }+ }+ return out;+}diff --git a/src/anatomy/viewer.js b/src/anatomy/viewer.jsnew file mode 100644index 000000000..269b44e66--- /dev/null+++ b/src/anatomy/viewer.js@@ -0,0 +1,930 @@+// AnatomyViewer: renders a normalized anatomy spec as an interactive+// isometric engineering illustration.+//+// Each part instance is a chain of three groups. The repeat group holds the+// radial or linear copy transform. The pivot holds the spec position,+// rotation and scale plus the explode offset. The motion group is recomputed+// every frame from the part's spin, oscillate, crank and pulse motions, and+// holds the fill mesh (shaded surface, hidden-line occluder, pick target), the+// fat edge lines, child parts (which inherit the motion) and attached effects.+//+// The viewer owns the WebGL canvas and a label overlay. All other UI lives in+// runtime.js and talks to the viewer through the public methods below.++import * as THREE from 'three';+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';+import { LineSegments2 } from 'three/addons/lines/LineSegments2.js';+import { LineSegmentsGeometry } from 'three/addons/lines/LineSegmentsGeometry.js';+import { LineMaterial } from 'three/addons/lines/LineMaterial.js';+import { buildShape } from './shapes.js';+import { buildEffect, buildFlow } from './effects.js';++const DEG = Math.PI / 180;+const TAU = Math.PI * 2;+const AXIS_VEC = { x: new THREE.Vector3(1, 0, 0), y: new THREE.Vector3(0, 1, 0), z: new THREE.Vector3(0, 0, 1) };+const ISO_DIR = new THREE.Vector3(1, 0.82, 1).normalize();+// A spec can ask for 220 parts x 96 repeats; the viewer stops building+// instances past this so a pathological spec cannot freeze the tab.+const MAX_INSTANCES = 2400;+const MAX_EFFECT_INSTANCES = 96;+const DIM = 0.12;++const PALETTE = ['#4f8dff', '#ff8a3d', '#2fbf9b', '#c46cff', '#f2c14e', '#ff5d73', '#5cc8ff', '#8fd14f', '#b08968', '#9aa5b1'];++const THEMES = {+ dark: { bg: '#0b0e14', grid: '#1d2433', gridCenter: '#2a3448', accent: '#5eb0ff', ink: '#ffffff', inkMix: 0.4, fillMix: 0.42 },+ light: { bg: '#f5f6f8', grid: '#dfe3ea', gridCenter: '#c9d0db', accent: '#1f6fff', ink: '#0d1220', inkMix: 0.6, fillMix: 0 },+};++function hashIndex(s, n) {+ let h = 0;+ for (const ch of String(s)) h = (Math.imul(h, 31) + ch.charCodeAt(0)) | 0;+ return Math.abs(h) % n;+}++function resolveTheme(pref) {+ if (pref === 'dark' || pref === 'light') return pref;+ const attr = document.documentElement.getAttribute('data-theme');+ if (attr === 'dark' || attr === 'light') return attr;+ return window.matchMedia?.('(prefers-color-scheme: light)').matches ? 'light' : 'dark';+}++export class AnatomyViewer {+ /**+ * @param {HTMLElement} container element the canvas and labels mount into+ * @param {object} [opts]+ * @param {'auto'|'dark'|'light'} [opts.theme]+ * @param {(id: string|null, ev?: PointerEvent) => void} [opts.onHover]+ * @param {(id: string|null) => void} [opts.onSelect]+ */+ constructor(container, opts = {}) {+ this.container = container;+ this.opts = opts;+ this.themePref = opts.theme || 'auto';+ this.themeName = resolveTheme(this.themePref);++ this.renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: false, powerPreference: 'high-performance' });+ this.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));+ this.renderer.localClippingEnabled = true;+ this.renderer.toneMapping = THREE.NeutralToneMapping;+ this.renderer.outputColorSpace = THREE.SRGBColorSpace;+ this.canvas = this.renderer.domElement;+ this.canvas.className = 'anx-canvas';+ this.canvas.setAttribute('aria-label', 'Interactive 3D machine view. Drag to rotate, scroll to zoom.');+ this.canvas.setAttribute('role', 'img');+ container.appendChild(this.canvas);++ this.labelLayer = document.createElement('div');+ this.labelLayer.className = 'anx-labels';+ this.labelLayer.setAttribute('aria-hidden', 'true');+ container.appendChild(this.labelLayer);++ this.scene = new THREE.Scene();+ const pmrem = new THREE.PMREMGenerator(this.renderer);+ this.envTexture = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;+ pmrem.dispose();+ this.scene.environment = this.envTexture;+ this.scene.environmentIntensity = 0.75;+ this.key = new THREE.DirectionalLight('#ffffff', 1.4);+ this.key.position.set(4, 9, 6);+ this.scene.add(this.key, new THREE.HemisphereLight('#ffffff', '#445066', 0.55));++ this.camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.01, 1000);+ this.controls = new OrbitControls(this.camera, this.canvas);+ this.controls.enableDamping = true;+ this.controls.dampingFactor = 0.09;+ this.controls.zoomToCursor = true;+ this.controls.minZoom = 0.25;+ this.controls.maxZoom = 12;+ this.controls.addEventListener('start', () => {+ this.tween = null;+ this.autoRotateUntil = 0;+ });++ this.root = new THREE.Group();+ this.scene.add(this.root);+ this.grid = null;++ this.clipPlane = new THREE.Plane(new THREE.Vector3(0, 0, -1), 0);+ this.lineMaterials = new Set();+ this.geomCache = new Map();+ this.state = { playing: true, speed: 1, explode: 0, section: null, sectionPos: 0.5, xray: false, labels: true };+ this.focus = null;+ this.hoverId = null;+ this.selectedId = null;+ this.hidden = new Set();+ this.time = 0;+ this.radius = 1;+ this.tween = null;+ this.dirty = true;+ this.visible = true;+ this.raycaster = new THREE.Raycaster();+ this.pointer = new THREE.Vector2();+ this.pendingPick = null;++ this.reset();+ this.bindEvents();+ this.applyTheme();+ this.resize();+ this.clock = new THREE.Clock();+ this.renderer.setAnimationLoop(() => this.tick());+ }++ // ---------------------------------------------------------------- build++ reset() {+ this.parts = new Map(); // id -> { spec, mats, instances: [{pivot, motion, fill, edges}], children: [] }+ this.motionNodes = [];+ this.effects = [];+ this.flows = [];+ this.pickables = [];+ this.labelParts = [];+ this.instanceCount = 0;+ this.effectCount = 0;+ }++ clearScene() {+ for (const e of [...this.effects, ...this.flows]) {+ e.object.removeFromParent();+ e.dispose();+ }+ for (const p of this.parts.values()) {+ p.mats.fill.dispose();+ p.mats.edge.dispose();+ p.mats.back?.dispose();+ this.lineMaterials.delete(p.mats.edge);+ }+ for (const m of this.lineMaterials) m.dispose();+ this.lineMaterials.clear();+ this.root.clear();+ this.labelLayer.replaceChildren();+ this.reset();+ }++ /**+ * Render a spec. `progressive` keeps the camera where it is and eases it+ * to the new framing, for specs that grow while they stream in.+ */+ load(spec, { progressive = false } = {}) {+ this.spec = spec;+ this.clearScene();+ const byId = new Map(spec.parts.map((p) => [p.id, p]));+ const childrenOf = new Map();+ for (const p of spec.parts) {+ const key = p.parent && byId.has(p.parent) ? p.parent : null;+ if (!childrenOf.has(key)) childrenOf.set(key, []);+ childrenOf.get(key).push(p);+ }+ this.childrenOf = childrenOf;+ const groups = [...new Set(spec.parts.map((p) => p.group).filter(Boolean))];+ for (const p of spec.parts) {+ const base = p.color || PALETTE[(p.group ? groups.indexOf(p.group) : hashIndex(p.id, PALETTE.length)) % PALETTE.length];+ this.parts.set(p.id, { spec: p, color: new THREE.Color(base), mats: this.makeMaterials(p), instances: [], effectAnchors: [] });+ }+ for (const p of childrenOf.get(null) || []) this.buildPart(p, this.root);++ const effectsByParent = new Map();+ for (const e of spec.effects) {+ const k = e.parent && this.parts.has(e.parent) ? e.parent : null;+ if (!effectsByParent.has(k)) effectsByParent.set(k, []);+ effectsByParent.get(k).push(e);+ }+ const ctx = { lineMaterial: (o) => this.makeLineMaterial(o) };+ for (const [parentId, list] of effectsByParent) {+ const anchors = parentId ? this.parts.get(parentId).instances.map((i) => i.motion) : [this.root];+ for (const eff of list) {+ for (const anchor of anchors) {+ if (this.effectCount >= MAX_EFFECT_INSTANCES) break;+ const built = buildEffect(eff, ctx);+ if (!built) continue;+ built.id = eff.id;+ anchor.add(built.object);+ this.effects.push(built);+ this.effectCount++;+ }+ }+ }+ for (const flow of spec.flows) {+ const built = buildFlow(flow, ctx);+ built.id = flow.id;+ this.root.add(built.object);+ this.flows.push(built);+ }+ // Shapes no longer in the spec free their geometry; shapes that are+ // still there (the common case while a spec streams in) are reused.+ for (const key of [...this.geomCache.keys()]) if (!this.geomCacheUsed?.has(key)) this.disposeGeom(key);+ this.geomCacheUsed = null;++ this.pickLabelParts();+ this.computeExplodeDirections();+ this.applyMotion(0);+ this.frameModel(progressive);+ this.applySection();+ this.applyExplode();+ this.refreshLooks();+ this.dirty = true;+ return { instances: this.instanceCount, truncated: this.instanceCount >= MAX_INSTANCES };+ }++ getGeometry(shape) {+ const key = JSON.stringify(shape);+ this.geomCacheUsed ??= new Set();+ this.geomCacheUsed.add(key);+ let g = this.geomCache.get(key);+ if (!g) {+ const { fill, lines } = buildShape(shape);+ fill.computeBoundingBox();+ fill.computeBoundingSphere();+ const lineGeom = new LineSegmentsGeometry();+ lineGeom.setPositions(lines);+ g = { fill, lineGeom, center: fill.boundingBox.getCenter(new THREE.Vector3()) };+ this.geomCache.set(key, g);+ }+ return g;+ }++ disposeGeom(key) {+ const g = this.geomCache.get(key);+ if (!g) return;+ g.fill.dispose();+ g.lineGeom.dispose();+ this.geomCache.delete(key);+ }++ makeLineMaterial({ color = '#ffffff', width = 1.2, dashed = false, dashSize = 0.1, gapSize = 0.05, transparent = false, opacity = 1 } = {}) {+ const m = new LineMaterial({ color: new THREE.Color(color), linewidth: width, dashed, dashSize, gapSize, transparent, opacity, worldUnits: false });+ m.resolution.set(this.width || 1, this.height || 1);+ this.lineMaterials.add(m);+ return m;+ }++ makeMaterials() {+ const fill = new THREE.MeshStandardMaterial({+ color: '#888888',+ metalness: 0.25,+ roughness: 0.55,+ side: THREE.DoubleSide,+ polygonOffset: true,+ polygonOffsetFactor: 1,+ polygonOffsetUnits: 1,+ });+ const edge = this.makeLineMaterial({ width: 1.25 });+ return { fill, edge, back: null, key: '' };+ }++ buildPart(part, parent) {+ const entry = this.parts.get(part.id);+ const rep = part.repeat;+ const count = rep ? rep.count : 1;+ for (let k = 0; k < count; k++) {+ if (this.instanceCount >= MAX_INSTANCES) return;+ this.instanceCount++;+ const repeatNode = new THREE.Group();+ if (rep?.mode === 'radial') {+ const span = rep.angle >= 360 ? (rep.angle / count) * k : count > 1 ? (rep.angle / (count - 1)) * k : 0;+ repeatNode.quaternion.setFromAxisAngle(AXIS_VEC[rep.axis], span * DEG);+ } else if (rep?.mode === 'linear') {+ repeatNode.position.set(rep.offset[0] * k, rep.offset[1] * k, rep.offset[2] * k);+ }+ const pivot = new THREE.Group();+ pivot.position.fromArray(part.position);+ pivot.rotation.set(part.rotation[0] * DEG, part.rotation[1] * DEG, part.rotation[2] * DEG);+ pivot.scale.fromArray(part.scale);+ pivot.userData.base = pivot.position.clone();+ const motion = new THREE.Group();+ motion.userData.motions = part.motion;+ const geom = this.getGeometry(part.shape);+ const fill = new THREE.Mesh(geom.fill, entry.mats.fill);+ fill.userData.partId = part.id;+ const edges = new LineSegments2(geom.lineGeom, entry.mats.edge);+ edges.userData.partId = part.id;+ edges.renderOrder = 2;+ motion.add(fill, edges);+ pivot.add(motion);+ repeatNode.add(pivot);+ parent.add(repeatNode);+ if (part.motion.length) this.motionNodes.push(motion);+ this.pickables.push(fill);+ entry.instances.push({ repeatNode, pivot, motion, fill, edges, center: geom.center });+ for (const child of this.childrenOf.get(part.id) || []) this.buildPart(child, motion);+ }+ }++ pickLabelParts() {+ const explicit = this.spec.parts.filter((p) => p.label === true);+ const pool = explicit.length ? explicit : (this.childrenOf.get(null) || []).filter((p) => p.label !== false).slice(0, 18);+ this.labelParts = pool.map((p) => {+ const el = document.createElement('div');+ el.className = 'anx-label';+ el.textContent = p.name;+ el.dataset.part = p.id;+ this.labelLayer.appendChild(el);+ return { id: p.id, el, w: 0, h: 0 };+ });+ this.labelExtra = new Map();+ }++ // --------------------------------------------------------------- motion++ applyMotion(t) {+ const q = new THREE.Quaternion();+ for (const node of this.motionNodes) {+ node.position.set(0, 0, 0);+ node.quaternion.identity();+ node.scale.set(1, 1, 1);+ for (const m of node.userData.motions) {+ const ph = (m.phase || 0) * DEG;+ if (m.type === 'spin') {+ q.setFromAxisAngle(AXIS_VEC[m.axis], TAU * m.speed * t + ph);+ node.quaternion.multiply(q);+ } else if (m.type === 'oscillate') {+ const s = Math.sin(TAU * m.frequency * t + ph);+ if (m.kind === 'rotate') {+ q.setFromAxisAngle(AXIS_VEC[m.axis], m.amplitude * DEG * s);+ node.quaternion.multiply(q);+ } else {+ node.position.addScaledVector(AXIS_VEC[m.axis], m.amplitude * s);+ }+ } else if (m.type === 'crank') {+ // Slider-crank: piston travel for crank radius r and rod+ // length l, centred so it swings between +r and -r.+ const th = TAU * m.speed * t + ph;+ const r = m.radius;+ const l = m.rod;+ const sin = Math.sin(th);+ const x = r * Math.cos(th) + Math.sqrt(Math.max(l * l - r * r * sin * sin, 0)) - l;+ node.position.addScaledVector(AXIS_VEC[m.axis], x);+ } else if (m.type === 'pulse') {+ node.scale.multiplyScalar(1 + m.amplitude * Math.sin(TAU * m.frequency * t + ph));+ }+ }+ }+ }++ // -------------------------------------------------------------- explode++ computeExplodeDirections() {+ this.root.updateMatrixWorld(true);+ const box = new THREE.Box3();+ for (const f of this.pickables) box.expandByObject(f);+ const center = box.isEmpty() ? new THREE.Vector3() : box.getCenter(new THREE.Vector3());+ const size = box.isEmpty() ? 1 : box.getSize(new THREE.Vector3()).length() / 2;+ const tops = this.childrenOf.get(null) || [];+ const fallback = new THREE.Vector3(0, 1, 0);+ for (const p of this.spec.parts) {+ const entry = this.parts.get(p.id);+ for (const inst of entry.instances) {+ if (p.explode) {+ inst.pivot.userData.explodeDir = new THREE.Vector3().fromArray(p.explode);+ continue;+ }+ if (!tops.includes(p)) {+ inst.pivot.userData.explodeDir = null;+ continue;+ }+ // Top-level parts fly outward from the model centre, scaled by+ // how far they already sit from it so the assembly order holds.+ const c = inst.fill.localToWorld(inst.center.clone());+ const d = c.sub(center);+ const len = d.length();+ const dir = len > size * 0.02 ? d.divideScalar(len) : fallback.clone();+ const parentQ = inst.pivot.parent.getWorldQuaternion(new THREE.Quaternion()).invert();+ dir.applyQuaternion(parentQ).multiplyScalar(size * 0.35 + len * 0.9);+ inst.pivot.userData.explodeDir = dir;+ }+ }+ }++ applyExplode() {+ const k = this.state.explode;+ for (const entry of this.parts.values()) {+ for (const inst of entry.instances) {+ const dir = inst.pivot.userData.explodeDir;+ inst.pivot.position.copy(inst.pivot.userData.base);+ if (dir && k > 0) inst.pivot.position.addScaledVector(dir, k);+ }+ }+ this.dirty = true;+ }++ // -------------------------------------------------------------- framing++ modelBox(ids = null) {+ this.root.updateMatrixWorld(true);+ const box = new THREE.Box3();+ const tmp = new THREE.Box3();+ const want = ids ? this.expandIds(ids) : null;+ for (const f of this.pickables) {+ if (want && !want.has(f.userData.partId)) continue;+ if (this.hidden.has(f.userData.partId)) continue;+ if (!f.geometry.boundingBox) f.geometry.computeBoundingBox();+ tmp.copy(f.geometry.boundingBox).applyMatrix4(f.matrixWorld);+ box.union(tmp);+ }+ if (ids) {+ for (const e of [...this.effects, ...this.flows]) if (ids.includes(e.id)) box.expandByObject(e.object);+ }+ return box;+ }++ frameModel(progressive) {+ this.root.position.set(0, 0, 0);+ const box = this.modelBox();+ if (box.isEmpty()) return;+ const center = box.getCenter(new THREE.Vector3());+ this.root.position.copy(center).negate();+ const size = box.getSize(new THREE.Vector3());+ this.radius = Math.max(size.length() / 2, 0.05);+ this.modelSize = size;+ this.modelMin = box.min.clone().sub(center);+ this.updateGrid();+ this.updateFrustum();+ const dist = this.radius * 6;+ this.camera.near = 0.01;+ this.camera.far = dist * 4;+ if (!progressive || !this.framed) {+ this.controls.target.set(0, 0, 0);+ this.camera.position.copy(ISO_DIR).multiplyScalar(dist);+ this.camera.zoom = 1;+ this.camera.updateProjectionMatrix();+ this.controls.update();+ this.framed = true;+ } else {+ this.tween = { target: new THREE.Vector3(), zoom: 1 };+ }+ this.camera.updateProjectionMatrix();+ }++ updateGrid() {+ if (this.grid) {+ this.grid.removeFromParent();+ this.grid.geometry.dispose();+ this.grid.material.dispose();+ }+ const extent = Math.max(this.modelSize.x, this.modelSize.z) * 1.8 + this.radius * 0.5;+ const step = 10 ** Math.floor(Math.log10(extent / 12));+ const divisions = Math.min(200, Math.max(4, Math.round(extent / step)));+ const t = THEMES[this.themeName];+ this.grid = new THREE.GridHelper(divisions * step, divisions, t.gridCenter, t.grid);+ this.grid.material.transparent = true;+ this.grid.material.opacity = 0.9;+ this.grid.material.depthWrite = false;+ this.grid.position.y = this.modelMin.y - this.radius * 0.04;+ this.grid.renderOrder = -1;+ this.scene.add(this.grid);+ }++ updateFrustum() {+ const aspect = (this.width || 1) / (this.height || 1);+ const half = this.radius * 1.12;+ const fitW = aspect >= 1 ? half * aspect : half;+ const fitH = aspect >= 1 ? half : half / aspect;+ this.camera.left = -fitW;+ this.camera.right = fitW;+ this.camera.top = fitH;+ this.camera.bottom = -fitH;+ this.camera.updateProjectionMatrix();+ }++ /** Ease the camera to frame a set of parts, or the whole model when ids is empty. */+ focusOn(ids) {+ if (!ids?.length) {+ this.tween = { target: new THREE.Vector3(), zoom: 1 };+ return;+ }+ const box = this.modelBox(ids);+ if (box.isEmpty()) return;+ const c = box.getCenter(new THREE.Vector3());+ const r = Math.max(box.getSize(new THREE.Vector3()).length() / 2, this.radius * 0.12);+ const zoom = THREE.MathUtils.clamp(this.radius / (r * 1.35), 1, 5);+ this.tween = { target: c, zoom };+ }++ resetView() {+ const dist = this.radius * 6;+ this.tween = null;+ this.controls.target.set(0, 0, 0);+ this.camera.position.copy(ISO_DIR).multiplyScalar(dist);+ this.camera.zoom = 1;+ this.camera.updateProjectionMatrix();+ this.controls.update();+ this.dirty = true;+ }++ /** Snap to an orthographic view: 'iso', 'front', 'side', 'top'. */+ setView(name) {+ const dirs = { iso: ISO_DIR, front: new THREE.Vector3(0, 0, 1), side: new THREE.Vector3(1, 0, 0), top: new THREE.Vector3(0, 1, 0.0001) };+ const dir = (dirs[name] || ISO_DIR).clone().normalize();+ this.camera.position.copy(this.controls.target).addScaledVector(dir, this.radius * 6);+ this.camera.updateProjectionMatrix();+ this.controls.update();+ this.dirty = true;+ }++ // ---------------------------------------------------------------- looks++ expandIds(ids) {+ const out = new Set();+ const visit = (id) => {+ if (out.has(id)) return;+ out.add(id);+ for (const c of this.childrenOf?.get(id) || []) visit(c.id);+ };+ for (const id of ids) visit(id);+ return out;+ }++ refreshLooks() {+ const focusSet = this.focus ? this.expandIds(this.focus) : null;+ this.focusSet = focusSet;+ const t = THEMES[this.themeName];+ const bg = new THREE.Color(t.bg);+ const ink = new THREE.Color(t.ink);+ const accent = new THREE.Color(t.accent);+ for (const [id, entry] of this.parts) {+ const p = entry.spec;+ const dimmed = focusSet ? !focusSet.has(id) : false;+ const hovered = this.hoverId === id;+ const selected = this.selectedId === id;+ const hidden = this.hidden.has(id);+ const { fill, edge } = entry.mats;+ let style = p.style;+ if (this.state.xray && style === 'solid') style = 'xray';++ let opacity = 1;+ let transparent = false;+ let depthWrite = true;+ let colorWrite = true;+ if (style === 'glass') {+ opacity = 0.2;+ transparent = true;+ depthWrite = false;+ } else if (style === 'ghost') {+ opacity = 0.06;+ transparent = true;+ depthWrite = false;+ } else if (style === 'xray') {+ opacity = 0.1;+ transparent = true;+ depthWrite = false;+ } else if (style === 'wire') {+ colorWrite = false;+ depthWrite = false;+ }+ if (dimmed && colorWrite) {+ opacity = Math.min(opacity, 0.05);+ transparent = true;+ depthWrite = false;+ }+ fill.color.copy(entry.color).lerp(bg, t.fillMix);+ fill.opacity = opacity;+ fill.emissive.copy(entry.color).multiplyScalar(p.glow * 0.9);+ if (selected) fill.emissive.lerp(accent, 0.35);+ const key = `${transparent}|${depthWrite}|${colorWrite}`;+ if (key !== entry.mats.key) {+ fill.transparent = transparent;+ fill.depthWrite = depthWrite;+ fill.colorWrite = colorWrite;+ fill.needsUpdate = true;+ entry.mats.key = key;+ }++ const edgeColor = entry.color.clone().lerp(ink, t.inkMix);+ if (p.glow > 0 && this.themeName === 'dark') edgeColor.lerp(new THREE.Color('#ffffff'), p.glow * 0.3);+ edge.color.copy(hovered || selected ? accent : edgeColor);+ let edgeOpacity = style === 'ghost' ? 0.35 : style === 'glass' ? 0.85 : style === 'xray' ? 0.75 : 1;+ if (dimmed) edgeOpacity *= 0.16;+ edge.opacity = edgeOpacity;+ if (edge.transparent !== edgeOpacity < 1) {+ edge.transparent = edgeOpacity < 1;+ edge.needsUpdate = true;+ }+ edge.linewidth = hovered ? 2.6 : selected ? 2.2 : style === 'ghost' ? 1 : 1.25;+ for (const inst of entry.instances) {+ inst.fill.visible = !hidden;+ inst.edges.visible = !hidden;+ inst.fill.renderOrder = transparent ? 1 : 0;+ }+ }+ const effectDim = (id) => (focusSet && !focusSet.has(id) ? DIM : 1);+ for (const e of this.effects) e.setDim(effectDim(e.id));+ for (const f of this.flows) f.setDim(effectDim(f.id));+ this.dirty = true;+ }++ setFocus(ids) {+ this.focus = ids?.length ? ids : null;+ this.refreshLooks();+ this.focusOn(this.focus);+ }++ setHover(id) {+ if (this.hoverId === id) return;+ this.hoverId = id;+ this.canvas.style.cursor = id ? 'pointer' : '';+ this.refreshLooks();+ }++ setSelected(id) {+ this.selectedId = id;+ this.refreshLooks();+ }++ setPartVisible(id, visible) {+ if (visible) this.hidden.delete(id);+ else this.hidden.add(id);+ this.refreshLooks();+ }++ setXray(on) {+ this.state.xray = Boolean(on);+ this.refreshLooks();+ }++ setLabels(on) {+ this.state.labels = Boolean(on);+ this.labelLayer.hidden = !on;+ this.dirty = true;+ }++ setPlaying(on) {+ this.state.playing = Boolean(on);+ this.dirty = true;+ }++ setSpeed(s) {+ this.state.speed = s;+ }++ setExplode(k) {+ this.state.explode = THREE.MathUtils.clamp(k, 0, 1);+ this.applyExplode();+ }++ /** Cut the model with a plane normal to `axis` at `pos` (0..1 across the model). */+ setSection(axis, pos = this.state.sectionPos) {+ this.state.section = axis || null;+ this.state.sectionPos = THREE.MathUtils.clamp(pos, 0, 1);+ this.applySection();+ }++ applySection() {+ const axis = this.state.section;+ const planes = axis ? [this.clipPlane] : null;+ if (axis) {+ const half = (this.modelSize?.[axis] || 1) / 2;+ const c = -half * 1.02 + this.state.sectionPos * half * 2.04;+ this.clipPlane.normal.copy(AXIS_VEC[axis]).negate();+ this.clipPlane.constant = c;+ }+ for (const entry of this.parts.values()) {+ const { fill, edge } = entry.mats;+ const had = Boolean(fill.clippingPlanes?.length);+ fill.clippingPlanes = planes;+ edge.clippingPlanes = planes;+ if (had !== Boolean(planes)) {+ fill.needsUpdate = true;+ edge.needsUpdate = true;+ }+ if (axis) this.ensureCaps(entry);+ for (const inst of entry.instances) if (inst.back) inst.back.visible = Boolean(axis) && !this.hidden.has(entry.spec.id) && entry.spec.style === 'solid';+ }+ this.dirty = true;+ }++ // Section caps: back faces drawn in a flat cut colour read as solid+ // material where the plane slices through a closed part.+ ensureCaps(entry) {+ if (!entry.mats.back) {+ entry.mats.back = new THREE.MeshBasicMaterial({ side: THREE.BackSide, clippingPlanes: [this.clipPlane] });+ }+ entry.mats.back.color.copy(entry.color).lerp(new THREE.Color(THEMES[this.themeName].bg), 0.55);+ for (const inst of entry.instances) {+ if (inst.back) continue;+ inst.back = new THREE.Mesh(inst.fill.geometry, entry.mats.back);+ inst.back.raycast = () => {};+ inst.fill.parent.add(inst.back);+ }+ }++ // ---------------------------------------------------------------- theme++ setTheme(pref) {+ this.themePref = pref;+ this.applyTheme();+ }++ applyTheme() {+ this.themeName = resolveTheme(this.themePref);+ const t = THEMES[this.themeName];+ this.scene.background = new THREE.Color(t.bg);+ (this.container.closest('.anx') || this.container).dataset.anxTheme = this.themeName;+ if (this.modelSize) this.updateGrid();+ for (const entry of this.parts.values()) if (entry.mats.back) entry.mats.back.color.copy(entry.color).lerp(new THREE.Color(t.bg), 0.55);+ this.refreshLooks();+ }++ // --------------------------------------------------------------- events++ bindEvents() {+ this.onResize = () => this.resize();+ this.resizeObserver = new ResizeObserver(this.onResize);+ this.resizeObserver.observe(this.container);+ this.visObserver = new IntersectionObserver((entries) => {+ this.visible = entries.some((e) => e.isIntersecting);+ });+ this.visObserver.observe(this.container);+ this.themeObserver = new MutationObserver(() => {+ if (this.themePref === 'auto') this.applyTheme();+ });+ this.themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });++ let down = null;+ this.onPointerDown = (e) => {+ down = { x: e.clientX, y: e.clientY };+ };+ this.onPointerMove = (e) => {+ if (e.buttons) return;+ this.pendingPick = { x: e.clientX, y: e.clientY, ev: e };+ };+ this.onPointerUp = (e) => {+ if (!down || Math.hypot(e.clientX - down.x, e.clientY - down.y) > 5) return;+ down = null;+ const id = this.pick(e.clientX, e.clientY);+ this.opts.onSelect?.(id);+ };+ this.onPointerLeave = () => {+ this.pendingPick = null;+ this.setHover(null);+ this.opts.onHover?.(null);+ };+ this.canvas.addEventListener('pointerdown', this.onPointerDown);+ this.canvas.addEventListener('pointermove', this.onPointerMove);+ this.canvas.addEventListener('pointerup', this.onPointerUp);+ this.canvas.addEventListener('pointerleave', this.onPointerLeave);+ }++ pick(clientX, clientY) {+ const rect = this.canvas.getBoundingClientRect();+ this.pointer.set(((clientX - rect.left) / rect.width) * 2 - 1, -((clientY - rect.top) / rect.height) * 2 + 1);+ this.raycaster.setFromCamera(this.pointer, this.camera);+ const hits = this.raycaster.intersectObjects(this.pickables, false);+ const clip = this.state.section ? this.clipPlane : null;+ for (const h of hits) {+ const id = h.object.userData.partId;+ if (!h.object.visible || this.hidden.has(id)) continue;+ if (clip && clip.distanceToPoint(h.point) < 0) continue;+ if (this.focusSet && !this.focusSet.has(id)) continue;+ return id;+ }+ return null;+ }++ resize() {+ const r = this.container.getBoundingClientRect();+ this.width = Math.max(1, Math.round(r.width));+ this.height = Math.max(1, Math.round(r.height));+ this.renderer.setSize(this.width, this.height, false);+ this.canvas.style.width = '100%';+ this.canvas.style.height = '100%';+ for (const m of this.lineMaterials) m.resolution.set(this.width, this.height);+ this.updateFrustum();+ this.dirty = true;+ }++ // ----------------------------------------------------------------- loop++ tick() {+ const dt = Math.min(this.clock.getDelta(), 0.1);+ if (!this.visible || document.hidden) return;+ if (this.pendingPick) {+ const { x, y, ev } = this.pendingPick;+ this.pendingPick = null;+ const id = this.pick(x, y);+ if (id !== this.hoverId) {+ this.setHover(id);+ }+ this.opts.onHover?.(id, ev);+ }+ if (this.tween) {+ const k = 1 - Math.exp(-dt * 7);+ this.controls.target.lerp(this.tween.target, k);+ const offset = this.camera.position.clone().sub(this.controls.target).normalize().multiplyScalar(this.radius * 6);+ this.camera.position.copy(this.controls.target).add(offset);+ this.camera.zoom += (this.tween.zoom - this.camera.zoom) * k;+ this.camera.updateProjectionMatrix();+ if (this.controls.target.distanceTo(this.tween.target) < this.radius * 1e-3 && Math.abs(this.camera.zoom - this.tween.zoom) < 1e-3) this.tween = null;+ this.dirty = true;+ }+ const moved = this.controls.update();+ if (moved) this.dirty = true;+ const animating = this.state.playing && this.state.speed > 0;+ if (animating) {+ this.time += dt * this.state.speed * (this.spec?.view?.speed ?? 1);+ this.applyMotion(this.time);+ }+ if (!animating && !this.dirty) return;++ const frame = {+ dark: this.themeName === 'dark',+ pixelScale: (this.renderer.getPixelRatio() * this.height * this.camera.zoom) / (this.camera.top - this.camera.bottom),+ };+ const effectDt = animating ? dt * this.state.speed : 0;+ for (const e of this.effects) e.update(this.time, effectDt, frame);+ for (const f of this.flows) f.update(this.time, effectDt, frame);+ this.renderer.render(this.scene, this.camera);+ if (this.state.labels) this.updateLabels();+ this.dirty = false;+ this.opts.onFrame?.();+ }++ /** Project label anchors to screen and hide the ones that would overlap. */+ updateLabels() {+ const placed = [];+ const v = new THREE.Vector3();+ const order = [...this.labelParts].sort((a, b) => {+ const pa = a.id === this.selectedId || a.id === this.hoverId || this.focusSet?.has(a.id) ? 0 : 1;+ const pb = b.id === this.selectedId || b.id === this.hoverId || this.focusSet?.has(b.id) ? 0 : 1;+ return pa - pb;+ });+ for (const label of order) {+ const entry = this.parts.get(label.id);+ const inst = entry?.instances[0];+ const show = inst && !this.hidden.has(label.id) && (!this.focusSet || this.focusSet.has(label.id));+ if (!show) {+ label.el.hidden = true;+ continue;+ }+ v.copy(inst.center);+ inst.fill.localToWorld(v);+ v.project(this.camera);+ const x = (v.x * 0.5 + 0.5) * this.width;+ const y = (-v.y * 0.5 + 0.5) * this.height;+ if (!label.w) {+ label.el.hidden = false;+ label.w = label.el.offsetWidth;+ label.h = label.el.offsetHeight;+ }+ const rect = { l: x - label.w / 2, t: y - label.h - 10, r: x + label.w / 2, b: y - 10 };+ const offscreen = rect.l < 0 || rect.r > this.width || rect.t < 0 || y > this.height;+ const overlaps = placed.some((p) => !(rect.r + 4 < p.l || rect.l - 4 > p.r || rect.b + 2 < p.t || rect.t - 2 > p.b));+ if (offscreen || overlaps) {+ label.el.hidden = true;+ continue;+ }+ placed.push(rect);+ label.el.hidden = false;+ label.el.style.transform = `translate(${Math.round(rect.l)}px, ${Math.round(rect.t)}px)`;+ label.el.classList.toggle('is-active', label.id === this.hoverId || label.id === this.selectedId);+ }+ }++ /** Screen position of a part's first instance, for tooltips. */+ screenPoint(id) {+ const inst = this.parts.get(id)?.instances[0];+ if (!inst) return null;+ const v = inst.center.clone();+ inst.fill.localToWorld(v);+ v.project(this.camera);+ return { x: (v.x * 0.5 + 0.5) * this.width, y: (-v.y * 0.5 + 0.5) * this.height };+ }++ /** PNG of the current frame at 2x device resolution. */+ async screenshot() {+ const prev = this.renderer.getPixelRatio();+ this.renderer.setPixelRatio(Math.min(prev * 2, 3));+ this.renderer.setSize(this.width, this.height, false);+ const frame = { dark: this.themeName === 'dark', pixelScale: (this.renderer.getPixelRatio() * this.height * this.camera.zoom) / (this.camera.top - this.camera.bottom) };+ for (const e of this.effects) e.update(this.time, 0, frame);+ for (const f of this.flows) f.update(this.time, 0, frame);+ this.renderer.render(this.scene, this.camera);+ const blob = await new Promise((resolve) => this.canvas.toBlob(resolve, 'image/png'));+ this.renderer.setPixelRatio(prev);+ this.renderer.setSize(this.width, this.height, false);+ this.dirty = true;+ return blob;+ }++ dispose() {+ this.renderer.setAnimationLoop(null);+ this.resizeObserver.disconnect();+ this.visObserver.disconnect();+ this.themeObserver.disconnect();+ this.canvas.removeEventListener('pointerdown', this.onPointerDown);+ this.canvas.removeEventListener('pointermove', this.onPointerMove);+ this.canvas.removeEventListener('pointerup', this.onPointerUp);+ this.canvas.removeEventListener('pointerleave', this.onPointerLeave);+ this.clearScene();+ for (const key of [...this.geomCache.keys()]) this.disposeGeom(key);+ if (this.grid) {+ this.grid.geometry.dispose();+ this.grid.material.dispose();+ }+ this.envTexture.dispose();+ this.controls.dispose();+ this.renderer.dispose();+ this.canvas.remove();+ this.labelLayer.remove();+ }+}