Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 | 'use client' /** * Storybook inspection bench for the abacus generator (Gitea epic #5). * * The studio's render core with the studio amputated: give it any `Params` * patch and an `only=` pass, and it runs the REAL pipeline — `exportDefines` → * the same `/openscad/scad-worker.js` the app serves → an STL → three.js. No * mock geometry and no second copy of the model: what a story shows is exactly * what `abacus.scad` emits for that config, at export `$fn`. * * Every instance carries a **Download STL** action, so any story is directly * test-printable — a lone bead can go on a plate by itself to check the fit in * a printed frame without reprinting the frame. * * `AbacusStudioViewer` can't serve here: it takes no props and reads its whole * design off `useAbacusStudio()`, and its shell-classification recolor pass is * meaningless for a single part (a lone bead has one role). So this is a much * smaller scene — one flat-shaded solid on a grid, orbit, fit-to-part camera. * * Unlike the eink bench there is no `__SB_A11Y_RENDERLESS__` escape hatch: this * repo runs no storybook a11y gate / test-runner (nothing sets that flag), so * there is no headless visit to skip the WebGL render for. Add one alongside * the gate if that ever lands. * * This is a story-only harness (it lives beside its `.stories.tsx`); it is never * imported by the app shell. */ import { type CSSProperties, useCallback, useEffect, useMemo, useRef, useState } from 'react' import * as THREE from 'three' import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js' import { STLLoader } from 'three/examples/jsm/loaders/STLLoader.js' import { defaultParams, exportDefines, type Params, type RenderPass } from './abacus-model' import { useAbacusScad } from './useAbacusScad' /** Bench preview $fn. Manifold makes high $fn nearly free on parts this small, * so a story renders at the quality you'd inspect a fillet at, not the studio's * drag-time 32. (The whole-abacus stories still pay for it — see `Frame`.) */ const PREVIEW_FN = 64 /** Downloads always render at full quality regardless of the preview $fn. */ const EXPORT_FN = 64 // ---- camera bookmarks ------------------------------------------------------- // The .scad is Z-up; the scene rotates it −90° about X, so model +X → world +X, // model +Y → world −Z, model +Z → world +Y (up). Directions below are therefore // stated in WORLD space, as unit-ish eye offsets from the part's center. They're // derived from that axis mapping rather than tuned against a render, so they stay // correct for any part at any scale — the fit below supplies the distance. /** A labelled "look at it from here" button. `eye` is a direction, not a * position: the camera is placed along it far enough to frame the whole part, * scaled by `zoom` (>1 = closer). */ export interface PartVantage { readonly label: string readonly eye: readonly [number, number, number] readonly zoom?: number } const RESET: PartVantage = { label: 'Reset', eye: [1, 0.75, 1.4] } /** Straight down the model's Y axis: the X–Z profile. This is the view the bead's * belt line lives in — capture body up to base z 7, blend to the frame's top face * at 8, dome to the tip — so it's the one that shows a silhouette change. */ const PROFILE_X: PartVantage = { label: 'Profile (X–Z)', eye: [0, 0.12, 1], zoom: 1.15 } /** Down the model's X axis: the Y–Z profile (the bead's short axis). */ const PROFILE_Y: PartVantage = { label: 'Profile (Y–Z)', eye: [1, 0.12, 0], zoom: 1.15 } const TOP: PartVantage = { label: 'Top', eye: [0.001, 1, 0.28] } const BOTTOM: PartVantage = { label: 'Bottom', eye: [0.001, -1, 0.28] } const DEFAULT_VANTAGES: readonly PartVantage[] = [RESET, PROFILE_X, PROFILE_Y, TOP, BOTTOM] // ---- mesh measurement ------------------------------------------------------- /** SIGNED volume, Σ(a · (b × c))/6 over the triangles — deliberately NOT `abs()`. * A negative reading means the solid is inside-out (its faces wind the wrong * way), which OpenSCAD raises no warning for: Manifold cheerfully builds a * consistently inverted body and an implicit union then SUBTRACTS it. That is * a real bug this repo has shipped once, in the bead cap's hand-written * `polyhedron`, and every other check we had — support functions, corner gaps, * bounding boxes — is winding-blind. So the readout shows the sign, and flags * it. Translation-invariant, so it doesn't matter that the caller re-seats the * part on the grid first. */ function signedVolumeMm3(geo: THREE.BufferGeometry): number { const p = geo.getAttribute('position') let v = 0 for (let i = 0; i < p.count; i += 3) { const ax = p.getX(i) const ay = p.getY(i) const az = p.getZ(i) const bx = p.getX(i + 1) const by = p.getY(i + 1) const bz = p.getZ(i + 1) const cx = p.getX(i + 2) const cy = p.getY(i + 2) const cz = p.getZ(i + 2) v += (ax * (by * cz - bz * cy) + ay * (bz * cx - bx * cz) + az * (bx * cy - by * cx)) / 6 } return v } type Measured = { tris: number /** model-space extents, mm: [X, Y, Z] */ size: [number, number, number] volume: number ms: number } // ---- the scene -------------------------------------------------------------- type SceneApi = { /** swap in a fresh STL; returns what the readout reports */ swap: (stl: ArrayBuffer) => Omit<Measured, 'ms'> /** fly to a vantage (fits the current part) */ aim: (v: PartVantage) => void } const fmt = (n: number) => n.toFixed(2) const passTag = (pass?: RenderPass): string => !pass ? 'assembly' : pass.only === 'text_plugs' ? `text_plugs-${pass.group}` : pass.only export interface AbacusPartBenchProps { /** Design knobs to render, merged over {@link defaultParams}. A bare `{}` (the * default) renders the stock abacus — which is the right baseline for a part * story: it's the geometry every other story is a deviation from. */ readonly params?: Partial<Params> /** Which `only=` slice to render. Omit for the whole abacus. */ readonly pass?: RenderPass /** Preview $fn (default {@link PREVIEW_FN}). */ readonly fn?: number /** $fn for the downloaded STL (default {@link EXPORT_FN}). */ readonly exportFn?: number /** Camera buttons; defaults to the profile/top/bottom set. Empty hides the bar. */ readonly vantages?: readonly PartVantage[] /** Show the triangle / extents / volume caption. */ readonly showReadout?: boolean /** Viewport height in px for a FIXED-height box — for grids that tile several * benches. Omit and the bench fills the iframe with the chrome overlaid. */ readonly height?: number } /** Stable default so a bare `<AbacusPartBench />` doesn't re-render every pass. */ const NO_PATCH: Partial<Params> = {} export function AbacusPartBench({ params: patch = NO_PATCH, pass, fn = PREVIEW_FN, exportFn = EXPORT_FN, vantages = DEFAULT_VANTAGES, showReadout = true, height, }: AbacusPartBenchProps) { const params = useMemo<Params>(() => ({ ...defaultParams, ...patch, fn }), [patch, fn]) // Everything the worker is actually told, as one string: the render effect keys // off THIS, not object identity, so Storybook re-minting the args literal on // every render can't re-fire a 3-second WASM solve. const renderKey = useMemo(() => exportDefines(params, pass).join(' '), [params, pass]) const [status, setStatus] = useState('booting…') const [error, setError] = useState<string | null>(null) const [measured, setMeasured] = useState<Measured | null>(null) const [downloading, setDownloading] = useState(false) const [ready, setReady] = useState(false) const mountRef = useRef<HTMLDivElement | null>(null) const sceneRef = useRef<SceneApi | null>(null) // live mirrors for the render effect / download handler, which must not take a // dep on values that change identity every render const paramsRef = useRef(params) paramsRef.current = params const passRef = useRef(pass) passRef.current = pass const onReady = useCallback(() => setReady(true), []) const noop = useCallback(() => {}, []) const { exportStl } = useAbacusScad({ onMain: noop, onPlug: noop, onReady }) const exportRef = useRef(exportStl) exportRef.current = exportStl // ---- mount-once three.js scene ------------------------------------------- useEffect(() => { const mount = mountRef.current if (!mount) return const w0 = mount.clientWidth || 800 const h0 = mount.clientHeight || 600 const renderer = new THREE.WebGLRenderer({ antialias: true }) renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)) renderer.setSize(w0, h0) mount.appendChild(renderer.domElement) const scene = new THREE.Scene() scene.background = new THREE.Color(0x0f1216) const camera = new THREE.PerspectiveCamera(40, w0 / h0, 0.1, 20000) const controls = new OrbitControls(camera, renderer.domElement) controls.enableDamping = true scene.add(new THREE.HemisphereLight(0xffffff, 0x33333f, 1.1)) // headlamp: moved onto the camera every frame, so orbiting under the part // lights its underside (a fixed key leaves foot undercuts unreadable) const key = new THREE.DirectionalLight(0xffffff, 1.35) scene.add(key) const fill = new THREE.DirectionalLight(0xaac4ff, 0.45) fill.position.set(-120, 60, -80) scene.add(fill) // model group carries the Z-up → Y-up rotation; the part is re-seated inside // it so its footprint is centered on the origin and its lowest point rests on // the grid — the print pose, and the pose a "does this sit flat?" read wants. const model = new THREE.Group() model.rotation.x = -Math.PI / 2 scene.add(model) const grid = new THREE.GridHelper(400, 40, 0x2b3440, 0x1b2129) grid.position.y = -0.05 scene.add(grid) const mat = new THREE.MeshStandardMaterial({ color: 0xc8d2dc, roughness: 0.55, metalness: 0.05, // a lone slice can be a thin section; showing backfaces keeps it readable side: THREE.DoubleSide, flatShading: false, }) let mesh: THREE.Mesh | null = null // world-space framing of the current part, refreshed on every swap let target = new THREE.Vector3() let radius = 50 const loader = new STLLoader() const aim = (v: PartVantage) => { const dir = new THREE.Vector3(v.eye[0], v.eye[1], v.eye[2]) if (dir.lengthSq() === 0) dir.set(0, 1, 0.001) dir.normalize() // frame the bounding sphere: half-angle of the smaller of the two FOVs const vFov = (camera.fov * Math.PI) / 180 const hFov = 2 * Math.atan(Math.tan(vFov / 2) * camera.aspect) const dist = radius / Math.sin(Math.min(vFov, hFov) / 2) / (v.zoom ?? 1) camera.position.copy(target).addScaledVector(dir, dist) // near/far bracket the PART's scale, not this shot's distance — the user // dollies freely with OrbitControls after a vantage click, and a clip plane // pinned to the initial distance would slice the part on the way in. camera.near = radius / 50 camera.far = radius * 50 camera.updateProjectionMatrix() controls.target.copy(target) controls.update() } const swap = (stl: ArrayBuffer) => { const geo = loader.parse(stl) const volume = signedVolumeMm3(geo) geo.computeBoundingBox() const bb = geo.boundingBox ?? new THREE.Box3() const size = new THREE.Vector3() bb.getSize(size) // re-seat: centered in model X/Y, sitting on model z = 0 geo.translate(-(bb.min.x + bb.max.x) / 2, -(bb.min.y + bb.max.y) / 2, -bb.min.z) geo.computeVertexNormals() if (mesh) { model.remove(mesh) mesh.geometry.dispose() } mesh = new THREE.Mesh(geo, mat) model.add(mesh) // the part now spans world Y 0..size.z, centered on X/Z radius = Math.max(1e-3, 0.5 * Math.hypot(size.x, size.y, size.z)) target = new THREE.Vector3(0, size.z / 2, 0) aim(RESET) return { tris: geo.getAttribute('position').count / 3, size: [size.x, size.y, size.z] as [number, number, number], volume, } } sceneRef.current = { swap, aim } const onResize = () => { const w = mount.clientWidth || w0 const h = mount.clientHeight || h0 camera.aspect = w / h camera.updateProjectionMatrix() renderer.setSize(w, h) } const ro = new ResizeObserver(onResize) ro.observe(mount) let raf = 0 const loop = () => { raf = requestAnimationFrame(loop) controls.update() key.position.copy(camera.position) // The grid is the "sits flat on the plate" reference, so it belongs at the // part's base — but from underneath (the Bottom vantage, where foot // undercuts live) it just draws lines across the thing you came to see. grid.visible = camera.position.y > 0 renderer.render(scene, camera) } loop() return () => { cancelAnimationFrame(raf) ro.disconnect() controls.dispose() mesh?.geometry.dispose() mat.dispose() grid.geometry.dispose() ;(grid.material as THREE.Material).dispose() renderer.dispose() renderer.domElement.remove() sceneRef.current = null } }, []) // ---- render on config change --------------------------------------------- useEffect(() => { if (!ready) return let cancelled = false setError(null) setStatus('rendering…') const t0 = performance.now() exportRef .current(paramsRef.current, passRef.current, fn) .then((stl) => { if (cancelled) return const ms = Math.round(performance.now() - t0) const m = sceneRef.current?.swap(stl) setMeasured(m ? { ...m, ms } : null) setStatus(`$fn ${fn} · ${ms} ms`) }) .catch((e: unknown) => { if (cancelled) return setError(String((e as Error)?.message ?? e)) setStatus('error') }) return () => { // NOTE: the worker keeps rendering — this only drops the result. A story // switch mid-solve costs one wasted render, never a torn scene. cancelled = true } }, [ready, renderKey, fn]) const download = useCallback(async () => { setDownloading(true) try { const stl = await exportRef.current(paramsRef.current, passRef.current, exportFn) const url = URL.createObjectURL(new Blob([stl], { type: 'model/stl' })) const a = document.createElement('a') a.href = url a.download = `abacus-${passTag(passRef.current)}.stl` a.click() URL.revokeObjectURL(url) } catch (e) { setError(String((e as Error)?.message ?? e)) } finally { setDownloading(false) } }, [exportFn]) // No explicit height ⇒ full-bleed: the stage fills the iframe and the chrome // floats over it. An explicit height ⇒ a fixed box for comparison grids. const filling = height === undefined // Two contrast regimes, same reasoning as the eink bench: floating chrome sits // on its own dark panel over the 3D stage; a fixed box draws dark-on-light and // the consumer must place it on a light card. const panel: CSSProperties | null = filling ? { background: '#12161c', border: '1px solid #2b3440', borderRadius: 8 } : null const labelColor = filling ? '#8b97a4' : '#52606d' const valueColor = filling ? '#e7e9ee' : '#1f2933' // stays off the red↔green axis — the ⚠ glyph and the words carry the meaning const alarmColor = filling ? '#f0a23c' : '#b42318' const downloadButton = ( <button type="button" data-component="AbacusPartBench" data-element="download-stl" data-action="download" onClick={download} disabled={downloading || !ready} style={{ background: '#1f2933', color: '#ffffff', border: '1px solid #1f2933', borderRadius: 6, padding: '6px 12px', font: '600 13px system-ui, sans-serif', cursor: downloading || !ready ? 'default' : 'pointer', opacity: downloading || !ready ? 0.6 : 1, pointerEvents: 'auto', }} > {downloading ? 'Rendering STL…' : '⭳ Download STL'} </button> ) const statusText = ( <span style={{ font: '500 12px system-ui, sans-serif', color: filling ? '#cdd5df' : '#3b4754' }} > {passTag(pass)} · {status} </span> ) const cameraBar = vantages.length > 0 ? ( // a real <fieldset> rather than role="group": same grouping semantics, no // ARIA needed, and the browser's default chrome is reset below. <fieldset aria-label="Camera" data-component="AbacusPartBench" data-element="camera-bar" style={{ margin: 0, border: 'none', ...panel, display: 'flex', gap: 6, flexWrap: 'wrap', padding: filling ? '6px 8px' : 0, pointerEvents: 'auto', }} > {vantages.map((v) => ( <button key={v.label} type="button" data-action="aim-camera" onClick={() => sceneRef.current?.aim(v)} style={{ background: '#232b36', color: '#e7e9ee', border: '1px solid #38424f', borderRadius: 6, padding: '5px 10px', font: '600 12px system-ui, sans-serif', cursor: 'pointer', }} > {v.label} </button> ))} </fieldset> ) : null const readout = showReadout && measured ? ( <dl data-component="AbacusPartBench" data-element="readout" style={{ display: 'grid', gridTemplateColumns: 'auto 1fr', gap: '2px 12px', margin: 0, font: '500 12px ui-monospace, monospace', color: valueColor, // display-only: let orbit drags fall through to the canvas behind it ...(filling ? { ...panel, position: 'absolute', left: 14, bottom: 14, zIndex: 2, padding: '10px 14px', pointerEvents: 'none', } : {}), }} > <dt style={{ color: labelColor }}>extents</dt> <dd style={{ margin: 0 }}> {fmt(measured.size[0])} × {fmt(measured.size[1])} × {fmt(measured.size[2])} mm </dd> <dt style={{ color: labelColor }}>volume</dt> <dd style={{ margin: 0, color: measured.volume < 0 ? alarmColor : valueColor }}> {fmt(measured.volume)} mm³ {measured.volume < 0 ? ' ⚠ inside-out (faces wind inward)' : ''} </dd> <dt style={{ color: labelColor }}>triangles</dt> <dd style={{ margin: 0 }}>{measured.tris.toLocaleString()}</dd> <dt style={{ color: labelColor }}>render</dt> <dd style={{ margin: 0 }}>{measured.ms} ms</dd> </dl> ) : null const errorNode = error ? ( <p role="alert" data-component="AbacusPartBench" data-element="error" style={{ color: alarmColor, font: '500 13px system-ui, sans-serif', margin: 0, ...(filling ? { ...panel, position: 'absolute', right: 14, bottom: 14, zIndex: 2, maxWidth: '60%', padding: '8px 12px', } : {}), }} > Render error: {error} </p> ) : null const stage = ( <div ref={mountRef} data-component="AbacusPartBench" data-element="stage" style={{ position: 'absolute', inset: 0 }} /> ) if (filling) { return ( <div data-component="AbacusPartBench" style={{ position: 'relative', width: '100%', height: '100dvh', minHeight: 320, overflow: 'hidden', background: '#0f1216', fontFamily: 'system-ui, sans-serif', }} > {stage} <div style={{ position: 'absolute', top: 14, left: 14, zIndex: 2, display: 'flex', alignItems: 'center', gap: 10, maxWidth: '44%', ...panel, padding: '6px 10px', pointerEvents: 'none', }} > {downloadButton} {statusText} </div> {cameraBar ? ( <div style={{ position: 'absolute', top: 14, right: 14, zIndex: 2, maxWidth: '52%' }}> {cameraBar} </div> ) : null} {readout} {errorNode} </div> ) } return ( <div data-component="AbacusPartBench" style={{ display: 'flex', flexDirection: 'column', gap: 8, fontFamily: 'system-ui, sans-serif', }} > <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}> {downloadButton} {statusText} {cameraBar} </div> <div style={{ width: '100%', height, position: 'relative', background: '#0f1216', borderRadius: 8, overflow: 'hidden', }} > {stage} </div> {errorNode} {readout} </div> ) } |