diff --git a/.github/architecture/cross-package-and-mirrors.md b/.github/architecture/cross-package-and-mirrors.md index a4e1c4828..85fea4d8f 100644 --- a/.github/architecture/cross-package-and-mirrors.md +++ b/.github/architecture/cross-package-and-mirrors.md @@ -24,7 +24,7 @@ When you change `packages/polycss` or `packages/core` in a way that affects the The DOM snapshot exporter is the current exception to mirrored React/Vue public exports: `exportPolySceneSnapshot` lives in `@layoutit/polycss` because it is browser DOM serialization, not component API. React/Vue callers import it from `@layoutit/polycss` and pass the rendered `.polycss-camera` / `.polycss-scene` element. -**Single renderer runtime.** All DOM/CSS rendering — the canvas atlas pipeline, browser feature detection, direct voxel renderer, shadow orchestrator, base stylesheet (`styles.ts`), render stats, and camera/control engines — lives once in `@layoutit/polycss` and is exported through the side-effect-free `@layoutit/polycss/runtime` subpath. React and Vue are thin Adopt-DOM bindings (`createPolyScene(..., { elements: { cameraEl, sceneEl } })`, `scene.add(..., { wrapper })`, `injectPolyBaseStyles` re-export) rather than parallel renderer implementations. +**Single renderer runtime.** All DOM/CSS rendering — the canvas atlas pipeline, browser feature detection, direct voxel renderer, shadow orchestrator, base stylesheet (`styles.ts`), render stats, and camera/control engines — lives once in `@layoutit/polycss`. Public imperative runtime APIs are exported through the side-effect-free `@layoutit/polycss/runtime` subpath, while lockstep adapter plumbing (gizmo/selection/hit-test/snapshot/standalone-mesh/leaf-descriptor helpers) is fenced behind `@layoutit/polycss/internal`. React and Vue are thin Adopt-DOM bindings (`createPolyScene(..., { elements: { cameraEl, sceneEl } })`, `scene.add(..., { wrapper })`, `injectPolyBaseStyles` re-export) rather than parallel renderer implementations. **CI enforces this and the package boundaries.** `pnpm check:boundaries` (`.github/scripts/check-boundaries.mjs`) fails on any import that violates the package dependency boundaries in [AGENTS.md](../../AGENTS.md), on deep imports into another package's `src` (`DEEP_IMPORT_ALLOWLIST` is empty), and on node builtins outside the Node-only surfaces. It scans `.ts`/`.tsx`/`.mts`/`.cts` **and** `.mjs`/`.cjs`/`.js` sources (so the `packages/skills` CLI is covered). Specifiers are read by a single-pass **lexer**, not a regex over raw source, because pattern-matching is wrong in both directions: it misses valid imports (a comment between the keyword and the specifier, `import(\`x\`)`, a statement split across lines) and matches text that is not code (a commented-out import, an import-shaped string). The lexer skips comments, tracks single/double-quoted strings, template literals including `${}` nesting, and regex literals, and yields `import`/`export … from`, bare `import "x"`, `import()` and `require()` specifiers; a template WITH a substitution is not a static specifier and is ignored rather than crashed on. Quoted strings and regex literals may never span a newline, so a mis-lex in TSX (JSX apostrophes, ``) recovers on the next line instead of swallowing code. The same allow-list is applied to each package's manifest: a `dependencies`, `optionalDependencies`, or `peerDependencies` entry outside the package's allow-list fails even when nothing imports it yet. `devDependencies` are tooling and are not constrained. The allow-list is applied to the RESOLVED dependency, not the manifest key, because the key is not what gets installed. Resolved forms: `npm:[@range]` aliases; `link:`/`file:`/`portal:` local paths and `workspace:` targets (both read through the target directory's own `package.json` name); and `workspace:[@range]` aliases, versioned or not. So `"@layoutit/polycss-core": "npm:@layoutit/polycss-vue@0.2.0"`, `"workspace:@layoutit/polycss-vue"` and `"workspace:../vue"` all fail in React under the allowed key. Only bare ranges and dist-tags (`^0.2.0`, `*`, `latest`, `workspace:^`, `workspace:*`, `workspace:1.2.3`) leave the key standing. Everything else is a **violation, not a pass**: a local or workspace target whose manifest cannot be read, an empty or non-string specifier, and every form whose install target is not determinable from the repo — `catalog:` (the target lives in `pnpm-workspace.yaml`), git specs (`github:`/`gitlab:`/`bitbucket:`/`git+…`/the bare `owner/repo` shorthand), remote tarball URLs, `jsr:` (which installs under a rewritten `@jsr/…` name), and any unrecognised `protocol:`. Falling back to the key for an unresolvable specifier is exactly the bypass, so a package that needs one of those forms must declare it in a shape the checker can see through. diff --git a/.github/architecture/repo-map.md b/.github/architecture/repo-map.md index f68c594d9..798a6aad1 100644 --- a/.github/architecture/repo-map.md +++ b/.github/architecture/repo-map.md @@ -1,20 +1,20 @@ # PolyCSS Repository Map -Tracked production code scanned across `packages/*/src`, `bench/`, and `website/src`: **435 files**, **98,545 lines**. Regenerate with `pnpm map`; verified in CI by `pnpm check:map`. +Tracked production code scanned across `packages/*/src`, `bench/`, and `website/src`: **465 files**, **98,571 lines**. Regenerate with `pnpm map`; verified in CI by `pnpm check:map`. ## 1. Packages & Entry Points | Package | Visibility | Exports | Workspace deps | Src files | Src lines | Test files | |---|---|---|---|---:|---:|---:| -| `packages/core` (`@layoutit/polycss-core`) | npm | `., ./three` | — | 78 | 26,885 | 58 | +| `packages/core` (`@layoutit/polycss-core`) | npm | `., ./three` | — | 99 | 27,290 | 58 | | `packages/domformat` (`@layoutit/polycss-domformat`) | private | `., ./browser` | — | 36 | 13,165 | 0 | | `packages/fonts` (`@layoutit/polycss-fonts`) | npm | `.` | `@layoutit/polycss-core` | 7 | 1,656 | 4 | | `packages/morph` (`@layoutit/polycss-morph`) | npm | `., ./prepare` | `@layoutit/polycss`, `@layoutit/polycss-core` | 49 | 7,629 | 14 | -| `packages/polycss` (`@layoutit/polycss`) | npm | `., ./runtime, ./elements, ./three` | `@layoutit/polycss-core` | 72 | 16,820 | 41 | -| `packages/react` (`@layoutit/polycss-react`) | npm | `., ./three` | `@layoutit/polycss`, `@layoutit/polycss-core` | 44 | 4,653 | 31 | +| `packages/polycss` (`@layoutit/polycss`) | npm | `., ./runtime, ./internal, ./elements, ./three` | `@layoutit/polycss-core` | 73 | 16,933 | 41 | +| `packages/react` (`@layoutit/polycss-react`) | npm | `., ./three` | `@layoutit/polycss`, `@layoutit/polycss-core` | 44 | 4,651 | 31 | | `packages/skills` (`@layoutit/polycss-skills`) | npm | `.` | — | 1 | 415 | 1 | -| `packages/vue` (`@layoutit/polycss-vue`) | npm | `., ./three` | `@layoutit/polycss`, `@layoutit/polycss-core` | 42 | 4,402 | 29 | +| `packages/vue` (`@layoutit/polycss-vue`) | npm | `., ./three` | `@layoutit/polycss`, `@layoutit/polycss-core` | 42 | 4,437 | 29 | ## 2. Canonical Workspace Source Aliases @@ -25,6 +25,7 @@ Single source of truth: [`packages/workspace-aliases.mjs`](../../packages/worksp | `@layoutit/polycss-core/three` | `packages/core/src/three/index.ts` | | `@layoutit/polycss-core` | `packages/core/src/index.ts` | | `@layoutit/polycss/runtime` | `packages/polycss/src/runtime.ts` | +| `@layoutit/polycss/internal` | `packages/polycss/src/internal.ts` | | `@layoutit/polycss/elements` | `packages/polycss/src/elements/index.ts` | | `@layoutit/polycss/three` | `packages/polycss/src/three.ts` | | `@layoutit/polycss` | `packages/polycss/src/index.ts` | @@ -44,35 +45,35 @@ Single source of truth: [`packages/workspace-aliases.mjs`](../../packages/worksp | Fan-in | Lines | File | |---:|---:|---| -| 113 | 644 | `packages/core/src/index.ts` | -| 67 | 248 | `packages/core/src/types.ts` | -| 39 | 247 | `packages/polycss/src/runtime.ts` | -| 32 | 301 | `packages/react/src/index.ts` | -| 30 | 119 | `website/src/components/types.ts` | -| 18 | 218 | `packages/polycss/src/index.ts` | -| 18 | 88 | `website/src/components/GalleryWorkbench/types.ts` | +| 113 | 528 | `packages/core/src/index.ts` | +| 87 | 248 | `packages/core/src/types.ts` | +| 38 | 301 | `packages/react/src/index.ts` | +| 33 | 119 | `website/src/components/types.ts` | +| 29 | 148 | `packages/polycss/src/runtime.ts` | +| 22 | 220 | `packages/polycss/src/index.ts` | +| 20 | 57 | `packages/polycss/src/internal.ts` | +| 19 | 88 | `website/src/components/GalleryWorkbench/types.ts` | +| 17 | 49 | `packages/core/src/math/vec3.ts` | | 17 | 385 | `packages/polycss/src/api/createPolyScene.ts` | | 16 | 45 | `packages/polycss/src/render/textureAtlas.ts` | | 13 | 121 | `packages/polycss/src/api/scene/internalTypes.ts` | -| 13 | 476 | `packages/polycss/src/api/scene/types.ts` | -| 12 | 49 | `packages/core/src/math/vec3.ts` | ### Largest production source files | Lines | File | |---:|---| | 3,578 | `packages/domformat/src/schema.ts` | -| 2,705 | `packages/core/src/merge/optimizePolygons.ts` | -| 2,186 | `packages/core/src/shadow/computeReceiverShadows.ts` | -| 2,010 | `packages/core/src/parser/parseGltf.ts` | | 1,935 | `packages/domformat/src/state/polycss.ts` | -| 1,548 | `packages/core/src/merge/seamRepair.ts` | -| 1,519 | `website/src/components/GalleryWorkbench/GalleryWorkbench.tsx` | -| 1,274 | `website/src/components/VanillaScene/VanillaScene.tsx` | -| 1,214 | `website/src/components/WordArtWorkbench/WordArtWorkbench.tsx` | | 1,192 | `bench/visual-gate.mjs` | | 1,178 | `packages/domformat/src/browser.ts` | | 1,139 | `website/src/components/GalleryWorkbench/presets/presetFiles.ts` | +| 968 | `packages/polycss/src/snapshot/exportPolySceneSnapshot.ts` | +| 963 | `packages/core/src/atlas/plan.ts` | +| 912 | `bench/entries/lifecycle.tsx` | +| 910 | `website/src/components/GalleryWorkbench/GalleryWorkbench.tsx` | +| 885 | `packages/morph/src/contracts/validation.ts` | +| 860 | `packages/domformat/src/state/interaction.ts` | +| 840 | `packages/polycss/src/render/atlas/renderPolygons.ts` | ## 4. Core Render & Control Pipelines diff --git a/.github/scripts/check-boundaries.mjs b/.github/scripts/check-boundaries.mjs index 9d87f17e3..02373e252 100644 --- a/.github/scripts/check-boundaries.mjs +++ b/.github/scripts/check-boundaries.mjs @@ -44,14 +44,23 @@ export const PACKAGE_RULES = { polycss: { allow: ["@layoutit/polycss-core"] }, react: { allow: ["@layoutit/polycss-core", "@layoutit/polycss", "react", "react-dom"], - allowedSubpaths: { "@layoutit/polycss": ["@layoutit/polycss/runtime"] }, + allowedSubpaths: { + "@layoutit/polycss": ["@layoutit/polycss/runtime", "@layoutit/polycss/internal"], + }, }, vue: { allow: ["@layoutit/polycss-core", "@layoutit/polycss", "vue"], - allowedSubpaths: { "@layoutit/polycss": ["@layoutit/polycss/runtime"] }, + allowedSubpaths: { + "@layoutit/polycss": ["@layoutit/polycss/runtime", "@layoutit/polycss/internal"], + }, }, fonts: { allow: ["@layoutit/polycss-core", "earcut"] }, - morph: { allow: ["@layoutit/polycss", "@layoutit/polycss-core"] }, + morph: { + allow: ["@layoutit/polycss", "@layoutit/polycss-core"], + allowedSubpaths: { + "@layoutit/polycss": ["@layoutit/polycss", "@layoutit/polycss/runtime"], + }, + }, domformat: { allow: [] }, // The skill installer copies markdown with node builtins only; it must never // pull a renderer in, or `npx polycss-skills` would install a whole engine. @@ -655,6 +664,10 @@ function checkDeepImportsOutsidePackages(root, violations) { violations.push( `${rel}: deep import into a package's src: "${spec}"`, ); + } else if (spec === "@layoutit/polycss/internal") { + violations.push( + `${rel}: disallowed internal subpath "${spec}" (reserved for @layoutit/polycss-react and @layoutit/polycss-vue)`, + ); } } } diff --git a/.github/scripts/check-boundaries.test.mjs b/.github/scripts/check-boundaries.test.mjs index 85419a0d4..f35d731ad 100644 --- a/.github/scripts/check-boundaries.test.mjs +++ b/.github/scripts/check-boundaries.test.mjs @@ -624,11 +624,17 @@ test("plain ranges, dist-tags and workspace ranges keep the declared key", () => } }); -test("react and vue may only import @layoutit/polycss/runtime from @layoutit/polycss", () => { +test("react and vue may only import @layoutit/polycss/runtime and /internal from @layoutit/polycss", () => { const okRoot = makeRepo( withManifests({ - "packages/react/src/ok.ts": 'import { createPolyScene } from "@layoutit/polycss/runtime";\ncreatePolyScene;\n', - "packages/vue/src/ok.ts": 'import { createPolyScene } from "@layoutit/polycss/runtime";\ncreatePolyScene;\n', + "packages/react/src/ok.ts": + 'import { createPolyScene } from "@layoutit/polycss/runtime";\n' + + 'import { createSelectionController } from "@layoutit/polycss/internal";\n' + + "createPolyScene; createSelectionController;\n", + "packages/vue/src/ok.ts": + 'import { createPolyScene } from "@layoutit/polycss/runtime";\n' + + 'import { createSelectionController } from "@layoutit/polycss/internal";\n' + + "createPolyScene; createSelectionController;\n", }), ); assert.deepEqual(runChecks(okRoot), []); @@ -639,12 +645,16 @@ test("react and vue may only import @layoutit/polycss/runtime from @layoutit/pol "packages/react/src/badRoot.ts": 'import { createPolyScene } from "@layoutit/polycss";\ncreatePolyScene;\n', "packages/react/src/badEl.ts": 'import "@layoutit/polycss/elements";\n', "packages/vue/src/badThree.ts": 'import { mountPolyThreeScene } from "@layoutit/polycss/three";\nmountPolyThreeScene;\n', + "packages/morph/src/badInternal.ts": 'import { createSelectionController } from "@layoutit/polycss/internal";\ncreateSelectionController;\n', + "website/src/badInternal.ts": 'import { createSelectionController } from "@layoutit/polycss/internal";\ncreateSelectionController;\n', }), ); const violations = runChecks(badRoot).sort(); - assert.equal(violations.length, 3); - assert.match(violations[0], /badEl\.ts: disallowed subpath "@layoutit\/polycss\/elements"/); - assert.match(violations[1], /badRoot\.ts: disallowed subpath "@layoutit\/polycss"/); - assert.match(violations[2], /badThree\.ts: disallowed subpath "@layoutit\/polycss\/three"/); + assert.equal(violations.length, 5); + assert.match(violations[0], /badInternal\.ts: disallowed subpath "@layoutit\/polycss\/internal"/); + assert.match(violations[1], /badEl\.ts: disallowed subpath "@layoutit\/polycss\/elements"/); + assert.match(violations[2], /badRoot\.ts: disallowed subpath "@layoutit\/polycss"/); + assert.match(violations[3], /badThree\.ts: disallowed subpath "@layoutit\/polycss\/three"/); + assert.match(violations[4], /website\/src\/badInternal\.ts: disallowed internal subpath "@layoutit\/polycss\/internal"/); cleanup(badRoot); }); diff --git a/.github/scripts/check-packs.mjs b/.github/scripts/check-packs.mjs index c5256a549..ce3cffaef 100644 --- a/.github/scripts/check-packs.mjs +++ b/.github/scripts/check-packs.mjs @@ -110,6 +110,29 @@ export function validateTarballInventory(pkgName, packedManifest, tarEntries) { return errors; } +export function validateInternalSubpathContract(pkgName, packedManifest, distFiles) { + const errors = []; + let importsInternalJs = false; + for (const { name, content } of distFiles) { + const code = content.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/[^\n]*/g, ""); + if (!code.includes("@layoutit/polycss/internal")) continue; + if (/\.d\.[cm]?ts$/.test(name)) { + errors.push(`${pkgName}: public declaration dist/${name} leaks "@layoutit/polycss/internal"`); + } else if (/\.[cm]?js$/.test(name)) { + importsInternalJs = true; + } + } + if (importsInternalJs) { + const polycssSpec = packedManifest.dependencies?.["@layoutit/polycss"]; + if (typeof polycssSpec !== "string" || !/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(polycssSpec)) { + errors.push( + `${pkgName}: imports @layoutit/polycss/internal but packed dependency "@layoutit/polycss" is "${polycssSpec}" instead of an exact lockstep version (use "workspace:*")`, + ); + } + } + return errors; +} + export function extractNamedImportsFromDist(jsSource, targetSpecifier) { const escaped = targetSpecifier.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const re = new RegExp(`import\\s*\\{([^}]*)\\}\\s*from\\s*["']${escaped}["']`, "g"); @@ -234,6 +257,13 @@ export async function checkAllPublishablePacks({ root = repoRoot } = {}) { const tarList = tarListOut.split("\n").filter(Boolean); const packedManifest = JSON.parse(packedPkgJson); const errors = validateTarballInventory(pkgName, packedManifest, tarList); + const distDir = join(dir, "dist"); + if (existsSync(distDir)) { + const distFiles = readdirSync(distDir) + .filter((f) => /\.(?:d\.[cm]?ts|[cm]?js)$/.test(f)) + .map((name) => ({ name, content: readFileSync(join(distDir, name), "utf8") })); + errors.push(...validateInternalSubpathContract(pkgName, packedManifest, distFiles)); + } return { name: pkgName, files: tarList.length, diff --git a/.github/scripts/check-packs.test.mjs b/.github/scripts/check-packs.test.mjs index 895da79d9..90c263213 100644 --- a/.github/scripts/check-packs.test.mjs +++ b/.github/scripts/check-packs.test.mjs @@ -4,6 +4,7 @@ import { collectBarrelValueExports, collectDeclaredEntryPaths, extractNamedImportsFromDist, + validateInternalSubpathContract, validateTarballInventory, } from "./check-packs.mjs"; @@ -101,3 +102,27 @@ test("extractNamedImportsFromDist and collectBarrelValueExports catch new core i ["transformPointMat4"], ); }); + +test("validateInternalSubpathContract rejects .d.ts leaks and non-exact lockstep dependencies", () => { + const ok = validateInternalSubpathContract( + "@layoutit/polycss-react", + { dependencies: { "@layoutit/polycss": "0.3.0" } }, + [ + { name: "chunk-abc.js", content: 'import { foo } from "@layoutit/polycss/internal";' }, + { name: "index.d.ts", content: 'export { pointInMeshElement } from "@layoutit/polycss/runtime";' }, + ], + ); + assert.deepEqual(ok, []); + + const bad = validateInternalSubpathContract( + "@layoutit/polycss-react", + { dependencies: { "@layoutit/polycss": "^0.3.0" } }, + [ + { name: "chunk-abc.js", content: 'import { foo } from "@layoutit/polycss/internal";' }, + { name: "index.d.ts", content: 'import { GizmoMode } from "@layoutit/polycss/internal";' }, + ], + ); + assert.equal(bad.length, 2); + assert.ok(bad.some((e) => e.includes('public declaration dist/index.d.ts leaks "@layoutit/polycss/internal"'))); + assert.ok(bad.some((e) => e.includes('instead of an exact lockstep version'))); +}); diff --git a/AGENTS.md b/AGENTS.md index 24c2bcf8f..0c9bdf30d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,9 +11,9 @@ Monorepo layout (pnpm workspaces): | Package | npm name | Role | |---|---|---| | `packages/core` | `@layoutit/polycss-core` | Pure math: Vec3, Polygon, scene, camera, mesh ops, atlas planning. Zero browser globals (`lib: ES2020` only). | -| `packages/polycss` | `@layoutit/polycss` | Single DOM/CSS renderer (`createPolyScene`, atlas, voxels, shadows, styles, controls) + custom elements (``, etc.) + side-effect-free `@layoutit/polycss/runtime` subpath. Depends on `core` only. | -| `packages/react` | `@layoutit/polycss-react` | Thin Adopt-DOM React components + hooks over `@layoutit/polycss/runtime`. Depends on `core` and `@layoutit/polycss/runtime`. | -| `packages/vue` | `@layoutit/polycss-vue` | Vue 3 mirror of React over `@layoutit/polycss/runtime`. Depends on `core` and `@layoutit/polycss/runtime`. | +| `packages/polycss` | `@layoutit/polycss` | Single DOM/CSS renderer (`createPolyScene`, atlas, voxels, shadows, styles, controls) + custom elements (``, etc.) + side-effect-free `@layoutit/polycss/runtime` public subpath and `@layoutit/polycss/internal` adapter-plumbing subpath. Depends on `core` only. | +| `packages/react` | `@layoutit/polycss-react` | Thin Adopt-DOM React components + hooks over `@layoutit/polycss/runtime` and `@layoutit/polycss/internal`. Depends on `core` and `@layoutit/polycss`. | +| `packages/vue` | `@layoutit/polycss-vue` | Vue 3 mirror of React over `@layoutit/polycss/runtime` and `@layoutit/polycss/internal`. Depends on `core` and `@layoutit/polycss`. | | `packages/fonts` | `@layoutit/polycss-fonts` | Fonts + text → extruded 3D `Polygon[]`. Framework-agnostic. Depends on `core` + `earcut`. | | `packages/morph` | `@layoutit/polycss-morph` | Framework-agnostic prepared-model contracts, Node preparation (`./prepare`), browser loading, retained DOM mounting, sparse deformation, skinning, and playback. No React/Vue mirrors. | | `packages/domformat` | `@layoutit/polycss-domformat` | Private strict-TypeScript `domformat@0` writer, reader, validator, CLI, and browser mount. Producer-neutral wire contract. Not published. | diff --git a/packages/core/src/atlas/edgeRepair.ts b/packages/core/src/atlas/edgeRepair.ts index 2d424050a..7571ddc67 100644 --- a/packages/core/src/atlas/edgeRepair.ts +++ b/packages/core/src/atlas/edgeRepair.ts @@ -40,12 +40,6 @@ export function buildTextureEdgeRepairSets(polygons: Polygon[]): Array edges.size > 0 ? edges : undefined); } -export function resolveSeamBleed(value: unknown, fallback: number): number { - return typeof value === "number" && Number.isFinite(value) - ? Math.max(0, value) - : fallback; -} - export function safePlanSeamBleedAmount( screenPts: number[], edgeIndex: number, diff --git a/packages/core/src/atlas/solidTriangle.ts b/packages/core/src/atlas/solidTriangle.ts index 31ad379dc..d3dc10cce 100644 --- a/packages/core/src/atlas/solidTriangle.ts +++ b/packages/core/src/atlas/solidTriangle.ts @@ -81,29 +81,6 @@ export function intersect2DLines( return [a0[0] + t * rx, a0[1] + t * ry]; } -export function intersect2DLinesRaw( - a0x: number, - a0y: number, - a1x: number, - a1y: number, - b0x: number, - b0y: number, - b1x: number, - b1y: number, -): Vec2 | null { - const rx = a1x - a0x; - const ry = a1y - a0y; - const sx = b1x - b0x; - const sy = b1y - b0y; - const det = rx * sy - ry * sx; - if (Math.abs(det) <= BASIS_EPS) return null; - - const qpx = b0x - a0x; - const qpy = b0y - a0y; - const t = (qpx * sy - qpy * sx) / det; - return [a0x + t * rx, a0y + t * ry]; -} - export function expandClipPoints(points: number[], amount: number): number[] { if (points.length < 6 || amount <= 0) return points; let cx = 0; diff --git a/packages/core/src/atlas/types.ts b/packages/core/src/atlas/types.ts index 5d1186756..501d5e1e0 100644 --- a/packages/core/src/atlas/types.ts +++ b/packages/core/src/atlas/types.ts @@ -240,13 +240,6 @@ export interface TextureAtlasPage { url: string | null; } -export interface RectBrush { - left: number; - top: number; - width: number; - height: number; -} - export interface LocalBasis { xAxis: Vec3; yAxis: Vec3; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 88bb5b917..995fad378 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -176,14 +176,8 @@ export type { AxesHelperOptions, BoxFace, BoxFaceOptions, BoxPolygonsOptions, Ar // ── Controls math (orbit / map, first-person, transform gizmo) ──── export { WHEEL_IDLE_END_MS, - POINTER_DRAG_SPEED, - ZOOM_STEP, - PINCH_AMP, - SCROLL_AMP, ANIM_FRAME_MS, ANIM_DT_CLAMP_MS, - DOLLY_STEP, - invertFactor, applyOrbit, applyPan, normalizeWheelDelta, @@ -195,10 +189,6 @@ export type { PolyControlsCamera, } from "./controls/orbit"; export { - FORWARD_KEYS, - BACK_KEYS, - LEFT_KEYS, - RIGHT_KEYS, JUMP_KEYS, CROUCH_KEYS, isFpvKey, @@ -214,15 +204,10 @@ export type { PolyFirstPersonPhysicsResult, } from "./controls/firstPerson"; export { - COLOR_X, - COLOR_Y, - COLOR_Z, ALPHA_IDLE, ALPHA_HOVER, ALPHA_DRAGGING, SCENE_TILE_SIZE, - FALLBACK_SHAFT_LENGTH, - SHAFT_LENGTH_RATIO, SHAFT_HALF_THICKNESS_RATIO, HEAD_LENGTH_RATIO, HEAD_HALF_THICKNESS_RATIO, @@ -251,14 +236,11 @@ export type { GizmoScreenAxis } from "./controls/gizmo"; // ── Shadow ──────────────────────────────────────────────────────── export { - BAKED_SHADOW_MIN_UP, - BAKED_SHADOW_Z_SQUASH, buildBakedShadowProjectionMatrix, convexHull2D, ensureCcw2D, isBakedShadowCaster, isPointShadowCaster, - polygonSignedArea2D, projectCssVertexToGround, projectCssVertexToGroundFromPoint, } from "./shadow/projection"; @@ -273,7 +255,6 @@ export { } from "./shadow/parametricOverride"; export { clipPolygonToConvex2D } from "./shadow/clipping"; export { - detectMemberSharedEdges, expandConvexHullOutward, groupReceiverFaceGroups, meshScaleVec3, @@ -384,43 +365,17 @@ export { DEFAULT_LIGHT_INTENSITY, DEFAULT_AMBIENT_COLOR, DEFAULT_AMBIENT_INTENSITY, - ATLAS_MAX_SIZE, - ATLAS_PADDING, - MIN_ATLAS_SCALE, - MAX_ATLAS_SCALE, - AUTO_ATLAS_LOW_AREA, - AUTO_ATLAS_MEDIUM_AREA, - AUTO_ATLAS_MAX_BITMAP_SIDE, - AUTO_ATLAS_MAX_DECODED_BYTES_MOBILE, - AUTO_ATLAS_MAX_DECODED_BYTES_DESKTOP, - AUTO_ATLAS_SCALE_GUARD, - COLOR_PARSE_CACHE_MAX, ASYNC_RENDER_BUDGET_MS, - RECT_EPS, BASIS_EPS, - SURFACE_NORMAL_EPS, - SURFACE_DISTANCE_EPS, - SEAM_LIGHT_EPS, TEXTURE_TRIANGLE_BLEED, TEXTURE_EDGE_REPAIR_ALPHA_MIN, TEXTURE_EDGE_REPAIR_SOURCE_ALPHA_MIN, TEXTURE_EDGE_REPAIR_RADIUS, SOLID_TRIANGLE_BLEED, DEFAULT_MATRIX_DECIMALS, - DEFAULT_BORDER_SHAPE_DECIMALS, - DEFAULT_ATLAS_CSS_DECIMALS, - DECIMAL_SCALES, SOLID_QUAD_CANONICAL_SIZE, SOLID_TRIANGLE_CANONICAL_SIZE, - SOLID_TRIANGLE_LARGE_BORDER_CANONICAL_SIZE, - ATLAS_CANONICAL_SIZE_EXPLICIT, - ATLAS_CANONICAL_SIZE_AUTO_DESKTOP, - BORDER_SHAPE_CENTER_PERCENT, - BORDER_SHAPE_POINT_EPS, - BORDER_SHAPE_CANONICAL_SIZE, BORDER_SHAPE_BLEED, - CORNER_SHAPE_POINT_EPS, - CORNER_SHAPE_DUPLICATE_EPS, PROJECTIVE_QUAD_DENOM_EPS, PROJECTIVE_QUAD_MAX_WEIGHT_RATIO, PROJECTIVE_QUAD_BLEED, @@ -439,9 +394,7 @@ export type { TextureTrianglePlan, TextureAtlasPlan, BorderShapeBounds, - BorderShapeGeometry, CornerShapeCorner, - CornerShapeSide, CornerShapeRadius, CornerShapeGeometry, TextureQuality, @@ -454,8 +407,6 @@ export type { SeamBleedInsets, PackedTextureAtlasEntry, PackedPage, - PackingShelf, - PackingPage, PackedAtlas, SolidTriangleBasis, SolidTriangleColorPlan, @@ -465,9 +416,7 @@ export type { SolidTriangleFrame, SolidPaintDefaults, TextureAtlasPage, - RectBrush, LocalBasis, - BasisOptions, BasisHint, PolygonBasisInfo, ProjectiveQuadGuardSettings, @@ -477,44 +426,25 @@ export type { StablePlanBasis, ComputeTextureAtlasPlanOptions, SolidTrianglePlanOptions, - InternalSolidTrianglePlanOptions, } from "./atlas/types"; export { - roundDecimal, formatCssLength, formatMatrix3dValues, - formatAffineMatrix3dColumns, - formatAffineMatrix3dScalars, - formatAffineMatrix3dTransformScalars, - formatScaledMatrixFromPlan, - formatBorderShapeMatrix, formatSolidQuadMatrix, - formatAtlasMatrix, - formatPercent, formatMatrix3d, formatCssLengthPx, formatSolidQuadEntryMatrix, } from "./atlas/matrix"; export { buildTextureEdgeRepairSets, - resolveSeamBleed, - safePlanSeamBleedAmount, - computePlanSeamBleedEdgeAmounts, - seamBleedAmountArray, - computeSeamBleedInsets, buildSeamBleedPolygonSet, buildSeamBleedPolygonEdges, } from "./atlas/edgeRepair"; export { - cachedParsePureColor, parseHex, rgbKey, - parseAlpha, rgbToHex, - textureTintFactors, - tintToCss, shadePolygon, - quantizeCssColor, rgbEqual, stepRgbToward, rgbToCss, @@ -536,37 +466,19 @@ export type { GetSolidPaintDefaultsEnv, } from "./atlas/strategy"; export { - cssPoints, - computeSurfaceNormal, - isConvexPolygonPoints, signedArea2D, - intersect2DLines, - intersect2DLinesRaw, expandClipPoints, - offsetConvexPolygonPoints, - offsetConvexPolygonPointsByEdgeAmounts, - offsetTrianglePoints, - offsetStableTrianglePoints, stableBasisFromPlan, stableTriangleMatrixDecimals, } from "./atlas/solidTriangle"; export { - polygonContainsPoint, - borderShapeBoundsFromPoints, - borderShapeGeometryForPlan, - simplifyCornerShapePoints, - cornerShapePointSides, - sharedCornerShapeSide, - cornerShapeDiagonal, cornerShapeGeometryForPlan, - cssBorderShapeForGeometry, cssBorderShapeForPlan, formatBorderShapeEntryMatrix, formatBorderShapeElementStyle, formatCornerShapeElementStyle, } from "./atlas/borderShape"; export { - computeSolidTriangleColorPlanFromNormal, computeSolidTriangleColorPlan, computeSolidTrianglePlan, computeSolidTrianglePlanFromCssPoints, @@ -575,23 +487,9 @@ export { resolveProjectiveQuadGuards, computeProjectiveQuadCoefficients, computeProjectiveQuadMatrix, - dotVec, crossVec, - isBasisOptimizable, - getPolygonBasisInfo, - compatibleSurface, - compatibleBleedSurface, - seamLightBrightness, - basisAxisKey, - makeLocalBasis, - evaluateIslandAxis, - chooseIslandXAxis, buildBasisHints, - chooseLocalBasis, isFullRectBasis, - computeUvAffine, - computeUvSampleRect, - projectTextureTriangle, computeTextureAtlasPlan, computeTextureAtlasPlanPublic, } from "./atlas/plan"; @@ -605,21 +503,7 @@ export { resolvePolyTextureUrl, } from "./atlas/textureSource"; export { - normalizeAtlasScale, - atlasArea, - autoAtlasScaleCap, - autoAtlasScale, - atlasBitmapMaxSide, - atlasDecodedBytes, - autoAtlasBudgetFactor, - autoAtlasMaxDecodedBytes, - atlasCanonicalSizeForTextureQuality, - applyPackedAtlasCanonicalSize, - applyPackedAtlasLeafSizing, - resolveAtlasLeafBox, atlasCanonicalSizeForEntry, - atlasPadding, - packTextureAtlasPlans, packTextureAtlasPlansWithScaleCore, } from "./atlas/packing"; diff --git a/packages/core/src/merge/optimize/acceptor.ts b/packages/core/src/merge/optimize/acceptor.ts new file mode 100644 index 000000000..e57f958e3 --- /dev/null +++ b/packages/core/src/merge/optimize/acceptor.ts @@ -0,0 +1,153 @@ +import type { Polygon } from "../../types"; +import type { SeamOverlapDiagnostics } from "../seamRepair"; +import { polygonRenderCost } from "./geometry"; +import { + collectTopologyEdgeStats, + seamDiagnosticsWorse, + TOPOLOGY_GAP_TOLERANCE, + topologyGapDiagnosticsWorse, + topologySelfDiagnostics, + trySeamOverlapSafetyDiagnostics, +} from "./topology"; +import type { + BestSafetyDiagnostics, + MeshCandidateSubmission, + TopologyEdgeStats, + TopologyGapDiagnostics, +} from "./types"; + +const AGGRESSIVE_LOSSY_MIN_RENDER_COST_GAIN = 4; +const AGGRESSIVE_LOSSY_MIN_SOURCE_GAIN_RATIO = 0.003; + +export class MeshCandidateAcceptor { + private best: Polygon[]; + private bestCost: number; + private bestDiagnostics: BestSafetyDiagnostics; + private readonly requiredMaxPolygonCount?: number; + + constructor(baseline: Polygon[], requiredMaxPolygonCount?: number) { + this.best = baseline; + this.bestCost = polygonRenderCost(baseline); + this.bestDiagnostics = { polygons: baseline }; + this.requiredMaxPolygonCount = requiredMaxPolygonCount; + } + + get polygons(): Polygon[] { + return this.best; + } + + get cost(): number { + return this.bestCost; + } + + accept(candidate: MeshCandidateSubmission): boolean { + if (candidate.mode === "cost") { + return this.acceptCostCandidate(candidate.polygons, candidate.cost); + } + if (candidate.mode === "dom") { + return this.acceptDomCandidate(candidate.polygons, candidate.cost, candidate.maxPolygonCount); + } + return this.acceptSeamSafeCandidate( + candidate.polygons, + candidate.sourcePolygonCount ?? candidate.polygons.length, + candidate.cost, + candidate.maxPolygonCount, + ); + } + + private acceptCostCandidate( + candidate: Polygon[], + cost = polygonRenderCost(candidate), + ): boolean { + if (cost >= this.bestCost) return false; + this.commit(candidate, cost); + return true; + } + + private acceptDomCandidate( + candidate: Polygon[], + cost = polygonRenderCost(candidate), + maxPolygonCount?: number, + ): boolean { + if (candidate.length >= this.best.length) return false; + if (!this.withinMaxPolygonCount(candidate, maxPolygonCount)) return false; + this.commit(candidate, cost); + return true; + } + + private acceptSeamSafeCandidate( + candidate: Polygon[], + sourcePolygonCount: number, + cost?: number, + maxPolygonCount?: number, + ): boolean { + if (candidate.length >= this.best.length) return false; + if (!this.withinMaxPolygonCount(candidate, maxPolygonCount)) return false; + const minGain = aggressiveLossyMinRenderCostGain(sourcePolygonCount); + if (this.bestCost - candidate.length < minGain) return false; + const candidateCost = cost ?? polygonRenderCost(candidate); + const gain = this.bestCost - candidateCost; + if (gain <= 0) return false; + if (gain < minGain) return false; + const candidateSeam = trySeamOverlapSafetyDiagnostics(candidate); + if (!candidateSeam) return false; + const baselineSeam = this.bestSeamDiagnostics(); + if (!baselineSeam) return false; + if (seamDiagnosticsWorse(candidateSeam, baselineSeam)) return false; + if (topologyGapDiagnosticsWorse( + this.bestTopologyEdges(), + this.bestTopologySelfDiagnostics(), + candidate, + )) return false; + this.commit(candidate, candidateCost, candidateSeam); + return true; + } + + private withinMaxPolygonCount(candidate: Polygon[], maxPolygonCount?: number): boolean { + const limit = maxPolygonCount ?? this.requiredMaxPolygonCount; + return limit === undefined || candidate.length <= limit; + } + + private commit(candidate: Polygon[], cost: number, seam?: SeamOverlapDiagnostics): void { + this.best = candidate; + this.bestCost = cost; + this.bestDiagnostics = { polygons: candidate, seam }; + } + + private resetBestDiagnostics(seam?: SeamOverlapDiagnostics): void { + this.bestDiagnostics = { polygons: this.best, seam }; + } + + private bestSeamDiagnostics(): SeamOverlapDiagnostics | null { + if (this.bestDiagnostics.polygons !== this.best) this.resetBestDiagnostics(); + if (!this.bestDiagnostics.seam) { + const seam = trySeamOverlapSafetyDiagnostics(this.best); + if (!seam) return null; + this.bestDiagnostics.seam = seam; + } + return this.bestDiagnostics.seam; + } + + private bestTopologyEdges(): TopologyEdgeStats { + if (this.bestDiagnostics.polygons !== this.best) this.resetBestDiagnostics(); + if (!this.bestDiagnostics.topologyEdges) { + this.bestDiagnostics.topologyEdges = collectTopologyEdgeStats(this.best); + } + return this.bestDiagnostics.topologyEdges; + } + + private bestTopologySelfDiagnostics(): TopologyGapDiagnostics { + if (this.bestDiagnostics.polygons !== this.best) this.resetBestDiagnostics(); + if (!this.bestDiagnostics.topologySelf) { + this.bestDiagnostics.topologySelf = topologySelfDiagnostics(this.bestTopologyEdges(), TOPOLOGY_GAP_TOLERANCE); + } + return this.bestDiagnostics.topologySelf; + } +} + +function aggressiveLossyMinRenderCostGain(sourcePolygonCount: number): number { + return Math.max( + AGGRESSIVE_LOSSY_MIN_RENDER_COST_GAIN, + sourcePolygonCount * AGGRESSIVE_LOSSY_MIN_SOURCE_GAIN_RATIO, + ); +} diff --git a/packages/core/src/merge/optimize/geometry.ts b/packages/core/src/merge/optimize/geometry.ts new file mode 100644 index 000000000..cc6968fc6 --- /dev/null +++ b/packages/core/src/merge/optimize/geometry.ts @@ -0,0 +1,391 @@ +import { crossVec } from "../../math/vec3"; +import type { Polygon, TextureTriangle, Vec2, Vec3 } from "../../types"; +import { cloneTextureTriangles, fanTextureTriangles } from "../textureTriangles"; +import type { PlaneFit, PreprocessCache, VertexPositionMove } from "./types"; + +export function polygonRenderCost(polygons: Polygon[]): number { + let cost = 0; + for (const polygon of polygons) { + const vertexCount = polygon.vertices.length; + const irregularPenalty = vertexCount <= 4 ? 0 : Math.min(4, vertexCount - 4) * 0.12; + const texturePenalty = polygon.texture || polygon.material?.texture || polygon.textureTriangles?.length ? 0.15 : 0; + cost += 1 + irregularPenalty + texturePenalty; + } + return cost; +} + +export function snappedPolygonsForMerge(polygons: Polygon[], cache?: PreprocessCache): Polygon[] { + if (!cache) return snapGeometryForMerge(polygons); + if (!cache.snapped) cache.snapped = snapGeometryForMerge(polygons); + return cache.snapped; +} + +export function snapGeometryForMerge(polygons: Polygon[]): Polygon[] { + const geometryEpsilon = geometrySnapEpsilon(polygons); + const uvEpsilon = 1e-4; + if (geometryEpsilon <= 0) return polygons; + + const vertices = createVec3Snapper(geometryEpsilon); + const uvs = createVec2Snapper(uvEpsilon); + let anyChanged = false; + + const snapped = polygons.map((polygon) => { + let changed = false; + const snapVertex = (vertex: Vec3): Vec3 => { + const next = vertices.snap(vertex); + if (!eqVec(next, vertex)) changed = true; + return next; + }; + const snappedVertices = polygon.vertices.map(snapVertex); + const snappedUvs = polygon.uvs && polygon.uvs.length === polygon.vertices.length + ? polygon.uvs.map((uv) => { + const next = uvs.snap(uv); + if (!eqUv(next, uv)) changed = true; + return next; + }) + : undefined; + const snappedTextureTriangles = mapTextureTriangleVertices(polygon.textureTriangles, snapVertex); + if (!changed && !polygon.texture) return polygon; + const snappedPolygon: Polygon = { + ...polygon, + vertices: snappedVertices, + ...(snappedUvs ? { uvs: snappedUvs } : {}), + ...(snappedTextureTriangles ? { textureTriangles: snappedTextureTriangles } : {}), + }; + anyChanged = true; + return { + ...snappedPolygon, + ...(snappedPolygon.texture + ? { textureTriangles: textureTrianglesForPolygon(snappedPolygon) } + : {}), + }; + }); + return anyChanged ? snapped : polygons; +} + +export function geometrySnapEpsilon(polygons: Polygon[]): number { + let minX = Infinity; + let minY = Infinity; + let minZ = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + let maxZ = -Infinity; + + for (const polygon of polygons) { + for (const [x, y, z] of polygon.vertices) { + minX = Math.min(minX, x); + minY = Math.min(minY, y); + minZ = Math.min(minZ, z); + maxX = Math.max(maxX, x); + maxY = Math.max(maxY, y); + maxZ = Math.max(maxZ, z); + } + } + + if (!Number.isFinite(minX)) return 0; + const diagonal = Math.hypot(maxX - minX, maxY - minY, maxZ - minZ); + if (diagonal <= 0) return 0; + return Math.min(0.025, Math.max(0.0001, diagonal * 0.00025)); +} + +function createVec3Snapper(epsilon: number) { + const buckets = new Map(); + const cell = (value: number) => Math.floor(value / epsilon); + const key = (x: number, y: number, z: number) => `${x},${y},${z}`; + + return { + snap(input: Vec3): Vec3 { + const cx = cell(input[0]); + const cy = cell(input[1]); + const cz = cell(input[2]); + for (let dx = -1; dx <= 1; dx++) { + for (let dy = -1; dy <= 1; dy++) { + for (let dz = -1; dz <= 1; dz++) { + const bucket = buckets.get(key(cx + dx, cy + dy, cz + dz)); + if (!bucket) continue; + for (const candidate of bucket) { + if (distanceVec(input, candidate) <= epsilon) { + return [candidate[0], candidate[1], candidate[2]]; + } + } + } + } + } + + const snapped: Vec3 = [input[0], input[1], input[2]]; + const bucketKey = key(cx, cy, cz); + const bucket = buckets.get(bucketKey); + if (bucket) bucket.push(snapped); + else buckets.set(bucketKey, [snapped]); + return snapped; + }, + }; +} + +function createVec2Snapper(epsilon: number) { + const buckets = new Map(); + const cell = (value: number) => Math.floor(value / epsilon); + const key = (x: number, y: number) => `${x},${y}`; + + return { + snap(input: Vec2): Vec2 { + const cx = cell(input[0]); + const cy = cell(input[1]); + for (let dx = -1; dx <= 1; dx++) { + for (let dy = -1; dy <= 1; dy++) { + const bucket = buckets.get(key(cx + dx, cy + dy)); + if (!bucket) continue; + for (const candidate of bucket) { + if (Math.hypot(input[0] - candidate[0], input[1] - candidate[1]) <= epsilon) { + return [candidate[0], candidate[1]]; + } + } + } + } + + const snapped: Vec2 = [input[0], input[1]]; + const bucketKey = key(cx, cy); + const bucket = buckets.get(bucketKey); + if (bucket) bucket.push(snapped); + else buckets.set(bucketKey, [snapped]); + return snapped; + }, + }; +} + +export function textureTrianglesForPolygon(polygon: Polygon): TextureTriangle[] | undefined { + if (!polygon.texture) return undefined; + if (polygon.textureTriangles?.length) return cloneTextureTriangles(polygon.textureTriangles); + if (polygon.uvs && polygon.uvs.length === polygon.vertices.length) { + return fanTextureTriangles(polygon.vertices, polygon.uvs); + } + return undefined; +} + +export function textureTrianglesForPolygons(polygons: Polygon[]): TextureTriangle[] | undefined { + const triangles = polygons.flatMap((polygon) => textureTrianglesForPolygon(polygon) ?? []); + return triangles.length > 0 ? triangles : undefined; +} + +export function mapTextureTriangleVertices( + triangles: TextureTriangle[] | undefined, + mapVertex: (vertex: Vec3) => Vec3, +): TextureTriangle[] | undefined { + if (!triangles?.length) return undefined; + return triangles.map((triangle) => ({ + vertices: triangle.vertices.map(mapVertex) as [Vec3, Vec3, Vec3], + uvs: triangle.uvs.map((uv) => [...uv] as Vec2) as [Vec2, Vec2, Vec2], + })); +} + +export function averagedVertexPositionMoves(moves: VertexPositionMove[]): Map { + const totals = new Map(); + for (const move of moves) { + const total = totals.get(move.key); + if (total) { + total.x += move.target[0]; + total.y += move.target[1]; + total.z += move.target[2]; + total.count += 1; + } else { + totals.set(move.key, { + x: move.target[0], + y: move.target[1], + z: move.target[2], + count: 1, + }); + } + } + + const averaged = new Map(); + for (const [key, total] of totals) { + averaged.set(key, [ + total.x / total.count, + total.y / total.count, + total.z / total.count, + ]); + } + return averaged; +} + +export function vertexPositionMovesForProjection(source: Polygon[], projected: Polygon[]): VertexPositionMove[] { + const moves: VertexPositionMove[] = []; + for (let i = 0; i < source.length; i++) { + const sourceVertices = source[i].vertices; + const projectedVertices = projected[i]?.vertices; + if (!projectedVertices || projectedVertices.length !== sourceVertices.length) continue; + for (let j = 0; j < sourceVertices.length; j++) { + moves.push({ + key: vertexKey(sourceVertices[j]), + target: projectedVertices[j], + }); + } + const sourceTriangles = source[i].textureTriangles ?? []; + const projectedTriangles = projected[i]?.textureTriangles ?? []; + for (let j = 0; j < sourceTriangles.length; j++) { + const projectedTriangle = projectedTriangles[j]; + if (!projectedTriangle) continue; + for (let k = 0; k < sourceTriangles[j].vertices.length; k++) { + moves.push({ + key: vertexKey(sourceTriangles[j].vertices[k]), + target: projectedTriangle.vertices[k], + }); + } + } + } + return moves; +} + +export function textureTriangleVertexProjectionMoves(polygons: Polygon[], fit: PlaneFit): VertexPositionMove[] { + const moves: VertexPositionMove[] = []; + for (const polygon of polygons) { + for (const triangle of polygon.textureTriangles ?? []) { + for (const vertex of triangle.vertices) { + moves.push({ + key: vertexKey(vertex), + target: projectVecToPlane(vertex, fit), + }); + } + } + } + return moves; +} + +export function applyVertexPositionMoves(polygons: Polygon[], moves: Map): Polygon[] { + return polygons.map((polygon) => { + let changed = false; + const moveVertex = (vertex: Vec3): Vec3 => { + const target = moves.get(vertexKey(vertex)); + if (!target) return vertex; + changed = true; + return target; + }; + const vertices = polygon.vertices.map(moveVertex); + const textureTriangles = mapTextureTriangleVertices(polygon.textureTriangles, moveVertex); + return changed ? { + ...polygon, + vertices, + ...(textureTriangles ? { textureTriangles } : {}), + } : polygon; + }); +} + +export function materialKeyForPolygon(polygon: Polygon): string { + return [ + polygon.color ?? "#cccccc", + polygon.texture ?? "", + polygon.texture && polygon.textureWrap ? `${polygon.textureWrap.s}/${polygon.textureWrap.t}` : "", + polygon.texture && polygon.textureAlphaMode ? polygon.textureAlphaMode : "", + polygon.uvs ? "uv" : "plain", + polygon.doubleSided === true ? "double-sided" : "single-sided", + ].join("|"); +} + +export function planeOfPolygon(polygon: Polygon): { normal: Vec3; area: number } | null { + const vertices = polygon.vertices; + if (!vertices || vertices.length < 3) return null; + + let nx = 0; + let ny = 0; + let nz = 0; + const origin = vertices[0]; + for (let i = 1; i < vertices.length - 1; i++) { + const a = subVec(vertices[i], origin); + const b = subVec(vertices[i + 1], origin); + const cross = crossVec(a, b); + nx += cross[0]; + ny += cross[1]; + nz += cross[2]; + } + + const len = Math.hypot(nx, ny, nz); + if (len <= 1e-10) return null; + return { + normal: [nx / len, ny / len, nz / len], + area: len / 2, + }; +} + +export function hasTextureMergeState(polygon: Polygon): boolean { + return Boolean(polygon.texture || polygon.material?.texture || polygon.textureTriangles?.length); +} + +export function canUseTexturedLossyMerge(a: Polygon, b: Polygon): boolean { + if (!a.texture || !b.texture || a.texture !== b.texture) return false; + if ((a.textureWrap?.s ?? "") !== (b.textureWrap?.s ?? "")) return false; + if ((a.textureWrap?.t ?? "") !== (b.textureWrap?.t ?? "")) return false; + if ((a.textureAlphaMode ?? "") !== (b.textureAlphaMode ?? "")) return false; + if (a.material?.texture || b.material?.texture) return false; + if (!a.uvs || !b.uvs) return false; + if (a.uvs.length !== a.vertices.length || b.uvs.length !== b.vertices.length) return false; + + const shared = sharedEdgeIndices(a, b); + if (!shared) return false; + const [ai0, ai1, bi0, bi1] = shared; + return eqUv(a.uvs[ai0], b.uvs[bi0]) && eqUv(a.uvs[ai1], b.uvs[bi1]); +} + +export function sharedEdgeIndices(a: Polygon, b: Polygon): [number, number, number, number] | null { + for (let ai0 = 0; ai0 < a.vertices.length; ai0++) { + const ai1 = (ai0 + 1) % a.vertices.length; + for (let bi0 = 0; bi0 < b.vertices.length; bi0++) { + const bi1 = (bi0 + 1) % b.vertices.length; + if (eqVec(a.vertices[ai0], b.vertices[bi0]) && eqVec(a.vertices[ai1], b.vertices[bi1])) { + return [ai0, ai1, bi0, bi1]; + } + if (eqVec(a.vertices[ai0], b.vertices[bi1]) && eqVec(a.vertices[ai1], b.vertices[bi0])) { + return [ai0, ai1, bi1, bi0]; + } + } + } + return null; +} + +export function edgeKey(a: Vec3, b: Vec3): string { + const ak = vertexKey(a); + const bk = vertexKey(b); + return ak < bk ? `${ak}|${bk}` : `${bk}|${ak}`; +} + +export function vertexKey(vertex: Vec3): string { + return `${vertex[0]},${vertex[1]},${vertex[2]}`; +} + +export function eqVec(a: Vec3, b: Vec3): boolean { + return a[0] === b[0] && a[1] === b[1] && a[2] === b[2]; +} + +export function eqUv(a: Vec2, b: Vec2): boolean { + return Math.abs(a[0] - b[0]) <= 1e-4 && Math.abs(a[1] - b[1]) <= 1e-4; +} + +export function subVec(a: Vec3, b: Vec3): Vec3 { + return [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; +} + +export function dotVec(a: Vec3, b: Vec3): number { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +} + +export function distanceVec(a: Vec3, b: Vec3): number { + return Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]); +} + +export function normalizeVec(value: Vec3): Vec3 | null { + const length = Math.hypot(value[0], value[1], value[2]); + if (length <= 1e-10) return null; + return [value[0] / length, value[1] / length, value[2] / length]; +} + +export function signedPlaneDistance(vertex: Vec3, fit: PlaneFit): number { + return dotVec(subVec(vertex, fit.point), fit.normal); +} + +export function projectVecToPlane(vertex: Vec3, fit: PlaneFit): Vec3 { + const distance = signedPlaneDistance(vertex, fit); + return [ + vertex[0] - fit.normal[0] * distance, + vertex[1] - fit.normal[1] * distance, + vertex[2] - fit.normal[2] * distance, + ]; +} diff --git a/packages/core/src/merge/optimize/pairMerge.ts b/packages/core/src/merge/optimize/pairMerge.ts new file mode 100644 index 000000000..111e14a3b --- /dev/null +++ b/packages/core/src/merge/optimize/pairMerge.ts @@ -0,0 +1,426 @@ +import { crossVec } from "../../math/vec3"; +import type { Polygon, Vec2, Vec3 } from "../../types"; +import { + applyVertexPositionMoves, + averagedVertexPositionMoves, + canUseTexturedLossyMerge, + dotVec, + edgeKey, + hasTextureMergeState, + materialKeyForPolygon, + normalizeVec, + planeOfPolygon, + projectVecToPlane, + sharedEdgeIndices, + signedPlaneDistance, + subVec, + textureTrianglesForPolygons, + textureTriangleVertexProjectionMoves, + vertexKey, +} from "./geometry"; +import type { + PairCandidate, + PairCandidateRank, + PlaneFit, + PlaneNormalizeMeta, + PreparedPairCandidate, + PreprocessCache, + ResolvedGeometryNormalizeOptions, + TrianglePairSourceCache, +} from "./types"; + +const PREPARED_PAIR_MAX_ANGLE_DEG = 60; +const PREPARED_PAIR_MAX_BOUNDARY_DISPLACEMENT = 0.06; + +export function mergeIsolatedTrianglePairs( + polygons: Polygon[], + options: ResolvedGeometryNormalizeOptions, + cache?: PreprocessCache, +): Polygon[] { + const source = trianglePairSourceFor(polygons, cache); + + const candidates: PairCandidate[] = []; + for (const prepared of preparedPairCandidatesFor(polygons, source)) { + if (preparedPairCandidateMatchesOptions(prepared, options)) { + candidates.push(prepared.candidate); + } + } + const selected = choosePairCandidates(candidates); + if (selected.length === 0) return polygons; + + return buildIsolatedTrianglePairOutput(polygons, selected); +} + +function trianglePairSourceFor( + polygons: Polygon[], + cache?: PreprocessCache, +): TrianglePairSourceCache { + if (cache?.trianglePairSource?.polygons === polygons) return cache.trianglePairSource; + + const metas = polygons.map((polygon): PlaneNormalizeMeta | null => { + const plane = planeOfPolygon(polygon); + if (!plane) return null; + return { + polygon, + normal: plane.normal, + area: plane.area, + materialKey: materialKeyForPolygon(polygon), + }; + }); + const edgeOwners = new Map(); + for (let i = 0; i < polygons.length; i++) { + const polygon = polygons[i]; + if (polygon.vertices.length !== 3 || !metas[i]) continue; + for (let j = 0; j < polygon.vertices.length; j++) { + const key = edgeKey(polygon.vertices[j], polygon.vertices[(j + 1) % polygon.vertices.length]); + const owners = edgeOwners.get(key); + if (owners) owners.push(i); + else edgeOwners.set(key, [i]); + } + } + + const edgeOwnerPairs: Array<[number, number]> = []; + for (const owners of edgeOwners.values()) { + if (owners.length === 2) edgeOwnerPairs.push([owners[0], owners[1]]); + } + + const source = { polygons, metas, edgeOwnerPairs }; + if (cache) cache.trianglePairSource = source; + return source; +} + +function preparedPairCandidatesFor( + polygons: Polygon[], + source: TrianglePairSourceCache, +): PreparedPairCandidate[] { + if (source.preparedCandidates) return source.preparedCandidates; + const prepared: PreparedPairCandidate[] = []; + for (const [a, b] of source.edgeOwnerPairs) { + const candidate = prepareTrianglePairCandidate(a, b, polygons, source.metas); + if (candidate) prepared.push(candidate); + } + source.preparedCandidates = prepared; + return prepared; +} + +function preparedPairCandidateMatchesOptions( + prepared: PreparedPairCandidate, + options: ResolvedGeometryNormalizeOptions, +): boolean { + const minNormalDot = Math.cos((options.maxAngleDeg * Math.PI) / 180); + return prepared.normalDot >= minNormalDot && + prepared.maxDistance <= Math.min(options.maxPlaneDisplacement, options.maxBoundaryDisplacement); +} + +function buildIsolatedTrianglePairOutput( + polygons: Polygon[], + selected: PairCandidate[], +): Polygon[] { + const replacements = new Map(); + const skipped = new Set(); + const vertexMoves = averagedVertexPositionMoves(selected.flatMap((candidate) => candidate.vertexMoves)); + for (const candidate of selected) { + const outputIndex = Math.min(candidate.a, candidate.b); + replacements.set(outputIndex, candidate.polygon); + skipped.add(Math.max(candidate.a, candidate.b)); + } + + const output: Polygon[] = []; + for (let i = 0; i < polygons.length; i++) { + const replacement = replacements.get(i); + if (replacement) { + output.push(replacement); + continue; + } + if (skipped.has(i)) continue; + output.push(polygons[i]); + } + return vertexMoves.size > 0 ? applyVertexPositionMoves(output, vertexMoves) : output; +} + +function choosePairCandidates(candidates: PairCandidate[]): PairCandidate[] { + if (candidates.length > 3000) return choosePairCandidatesStatic(candidates); + return choosePairCandidatesDynamic(candidates); +} + +function choosePairCandidatesStatic(candidates: PairCandidate[]): PairCandidate[] { + const pairDegrees = new Map(); + for (const candidate of candidates) { + pairDegrees.set(candidate.a, (pairDegrees.get(candidate.a) ?? 0) + 1); + pairDegrees.set(candidate.b, (pairDegrees.get(candidate.b) ?? 0) + 1); + } + + const sorted = [...candidates].sort((a, b) => { + const degreeA = (pairDegrees.get(a.a) ?? 0) + (pairDegrees.get(a.b) ?? 0); + const degreeB = (pairDegrees.get(b.a) ?? 0) + (pairDegrees.get(b.b) ?? 0); + return degreeA - degreeB || a.score - b.score; + }); + + const used = new Set(); + const selected: PairCandidate[] = []; + for (const candidate of sorted) { + if (used.has(candidate.a) || used.has(candidate.b)) continue; + used.add(candidate.a); + used.add(candidate.b); + selected.push(candidate); + } + return selected; +} + +function choosePairCandidatesDynamic(candidates: PairCandidate[]): PairCandidate[] { + const incident = new Map(); + for (let i = 0; i < candidates.length; i++) { + const candidate = candidates[i]; + const aIncident = incident.get(candidate.a); + if (aIncident) aIncident.push(i); + else incident.set(candidate.a, [i]); + const bIncident = incident.get(candidate.b); + if (bIncident) bIncident.push(i); + else incident.set(candidate.b, [i]); + } + + const selected: PairCandidate[] = []; + const live = new Array(candidates.length).fill(true); + const liveIncidentCount = new Map(); + const heap = new PairCandidateRankHeap(); + + for (const [polygon, list] of incident) liveIncidentCount.set(polygon, list.length); + const liveDegree = (candidate: PairCandidate): number => + (liveIncidentCount.get(candidate.a) ?? 0) + (liveIncidentCount.get(candidate.b) ?? 0); + const pushRank = (index: number): void => { + const candidate = candidates[index]; + heap.push({ + degree: liveDegree(candidate), + score: candidate.score, + index, + }); + }; + const invalidate = (index: number, changedPolygons: Set): void => { + if (!live[index]) return; + live[index] = false; + const candidate = candidates[index]; + for (const polygon of [candidate.a, candidate.b]) { + liveIncidentCount.set(polygon, (liveIncidentCount.get(polygon) ?? 0) - 1); + changedPolygons.add(polygon); + } + }; + + for (let i = 0; i < candidates.length; i++) pushRank(i); + + while (heap.size() > 0) { + const rank = heap.pop()!; + if (!live[rank.index]) continue; + + const candidate = candidates[rank.index]; + const degree = liveDegree(candidate); + if (degree !== rank.degree) { + pushRank(rank.index); + continue; + } + + selected.push(candidate); + + const changedPolygons = new Set(); + for (const polygon of [candidate.a, candidate.b]) { + for (const index of incident.get(polygon) ?? []) { + invalidate(index, changedPolygons); + } + } + + for (const polygon of changedPolygons) { + for (const index of incident.get(polygon) ?? []) { + if (live[index]) pushRank(index); + } + } + } + return selected; +} + +class PairCandidateRankHeap { + private items: PairCandidateRank[] = []; + + size(): number { + return this.items.length; + } + + push(item: PairCandidateRank): void { + this.items.push(item); + let index = this.items.length - 1; + while (index > 0) { + const parent = (index - 1) >> 1; + if (comparePairCandidateRanks(this.items[parent], this.items[index]) <= 0) break; + [this.items[parent], this.items[index]] = [this.items[index], this.items[parent]]; + index = parent; + } + } + + pop(): PairCandidateRank | null { + if (this.items.length === 0) return null; + const top = this.items[0]; + const last = this.items.pop()!; + if (this.items.length > 0) { + this.items[0] = last; + let index = 0; + for (;;) { + const left = index * 2 + 1; + const right = left + 1; + let best = index; + if (left < this.items.length && comparePairCandidateRanks(this.items[left], this.items[best]) < 0) best = left; + if (right < this.items.length && comparePairCandidateRanks(this.items[right], this.items[best]) < 0) best = right; + if (best === index) break; + [this.items[index], this.items[best]] = [this.items[best], this.items[index]]; + index = best; + } + } + return top; + } +} + +function comparePairCandidateRanks(a: PairCandidateRank, b: PairCandidateRank): number { + return a.degree - b.degree || a.score - b.score || a.index - b.index; +} + +function prepareTrianglePairCandidate( + aIndex: number, + bIndex: number, + polygons: Polygon[], + metas: Array, +): PreparedPairCandidate | null { + const a = polygons[aIndex]; + const b = polygons[bIndex]; + const aMeta = metas[aIndex]; + const bMeta = metas[bIndex]; + if (!aMeta || !bMeta) return null; + if (a.vertices.length !== 3 || b.vertices.length !== 3) return null; + if (!canApproximatePairMerge(a, b, aMeta, bMeta)) return null; + + const shared = sharedEdgeIndices(a, b); + if (!shared) return null; + const [ai0, ai1, bi0, bi1] = shared; + const bGoesSameDirection = (bi0 + 1) % b.vertices.length === bi1; + if (bGoesSameDirection) return null; + + const normalDot = Math.abs(dotVec(aMeta.normal, bMeta.normal)); + const minNormalDot = Math.cos((PREPARED_PAIR_MAX_ANGLE_DEG * Math.PI) / 180); + if (normalDot < minNormalDot) return null; + + const aThird = (ai1 + 1) % a.vertices.length; + const bThird = 3 - bi0 - bi1; + const ring = [ + a.vertices[ai1], + a.vertices[aThird], + a.vertices[ai0], + b.vertices[bThird], + ]; + const fit = fitPlaneForVertices(ring); + if (!fit) return null; + + let maxDistance = 0; + let squaredDistance = 0; + for (const vertex of ring) { + const distance = Math.abs(signedPlaneDistance(vertex, fit)); + maxDistance = Math.max(maxDistance, distance); + squaredDistance += distance * distance; + } + if (maxDistance > PREPARED_PAIR_MAX_BOUNDARY_DISPLACEMENT) return null; + + const projected = ring.map((vertex) => projectVecToPlane(vertex, fit)); + if (!isConvexPolygon(projected, fit.normal)) return null; + const projectedPlane = planeOfPolygon({ vertices: projected }); + if ( + !projectedPlane || + dotVec(projectedPlane.normal, aMeta.normal) < 0.2 || + dotVec(projectedPlane.normal, bMeta.normal) < 0.2 + ) { + return null; + } + const polygon: Polygon = { + vertices: ring, + color: a.color, + ...(a.doubleSided ? { doubleSided: true } : {}), + ...(a.data ? { data: { ...a.data } } : {}), + }; + if (canUseTexturedLossyMerge(a, b) && a.uvs && b.uvs && a.texture) { + polygon.texture = a.texture; + if (a.textureWrap) polygon.textureWrap = { ...a.textureWrap }; + if (a.textureAlphaMode) polygon.textureAlphaMode = a.textureAlphaMode; + polygon.uvs = [ + [...a.uvs[ai1]] as Vec2, + [...a.uvs[aThird]] as Vec2, + [...a.uvs[ai0]] as Vec2, + [...b.uvs[bThird]] as Vec2, + ]; + const textureTriangles = textureTrianglesForPolygons([a, b]); + if (textureTriangles?.length) polygon.textureTriangles = textureTriangles; + } + + return { + normalDot, + maxDistance, + candidate: { + a: aIndex, + b: bIndex, + polygon, + vertexMoves: [ + ...ring.map((vertex, index) => ({ + key: vertexKey(vertex), + target: projected[index], + })), + ...textureTriangleVertexProjectionMoves([a, b], fit), + ], + score: squaredDistance / ring.length + maxDistance * 0.25 + (1 - normalDot) * 0.1, + }, + }; +} + +function canApproximatePairMerge( + a: Polygon, + b: Polygon, + aMeta: PlaneNormalizeMeta, + bMeta: PlaneNormalizeMeta, +): boolean { + if (aMeta.materialKey !== bMeta.materialKey) return false; + if (hasTextureMergeState(a) || hasTextureMergeState(b)) return canUseTexturedLossyMerge(a, b); + return !a.uvs && !b.uvs && !a.textureTriangles?.length && !b.textureTriangles?.length; +} + +function fitPlaneForVertices(vertices: Vec3[]): PlaneFit | null { + if (vertices.length < 3) return null; + let nx = 0; + let ny = 0; + let nz = 0; + let px = 0; + let py = 0; + let pz = 0; + for (let i = 0; i < vertices.length; i++) { + const current = vertices[i]; + const next = vertices[(i + 1) % vertices.length]; + nx += (current[1] - next[1]) * (current[2] + next[2]); + ny += (current[2] - next[2]) * (current[0] + next[0]); + nz += (current[0] - next[0]) * (current[1] + next[1]); + px += current[0]; + py += current[1]; + pz += current[2]; + } + const normal = normalizeVec([nx, ny, nz]); + if (!normal) return null; + return { + normal, + point: [px / vertices.length, py / vertices.length, pz / vertices.length], + }; +} + +function isConvexPolygon(vertices: Vec3[], normal: Vec3): boolean { + let sign = 0; + for (let i = 0; i < vertices.length; i++) { + const a = vertices[i]; + const b = vertices[(i + 1) % vertices.length]; + const c = vertices[(i + 2) % vertices.length]; + const turn = dotVec(crossVec(subVec(b, a), subVec(c, b)), normal); + if (Math.abs(turn) <= 1e-9) continue; + const nextSign = turn > 0 ? 1 : -1; + if (sign === 0) sign = nextSign; + else if (sign !== nextSign) return false; + } + return true; +} diff --git a/packages/core/src/merge/optimize/planeNormalize.ts b/packages/core/src/merge/optimize/planeNormalize.ts new file mode 100644 index 000000000..99385ad23 --- /dev/null +++ b/packages/core/src/merge/optimize/planeNormalize.ts @@ -0,0 +1,411 @@ +import type { Polygon, Vec3 } from "../../types"; +import { mergePolygons } from "../mergePolygons"; +import { + applyVertexPositionMoves, + averagedVertexPositionMoves, + canUseTexturedLossyMerge, + dotVec, + edgeKey, + eqUv, + geometrySnapEpsilon, + hasTextureMergeState, + mapTextureTriangleVertices, + materialKeyForPolygon, + normalizeVec, + planeOfPolygon, + polygonRenderCost, + projectVecToPlane, + sharedEdgeIndices, + signedPlaneDistance, + snapGeometryForMerge, + snappedPolygonsForMerge, + vertexKey, + vertexPositionMovesForProjection, +} from "./geometry"; +import type { + PlaneFit, + PlaneGroupReplacements, + PlaneNormalizeMeta, + PlanePatchCandidate, + PreprocessCache, + ResolvedGeometryNormalizeOptions, + VertexPositionMove, +} from "./types"; + +export function normalizeGeometryForMerge( + polygons: Polygon[], + options: ResolvedGeometryNormalizeOptions, + cache?: PreprocessCache, +): Polygon[] { + const snapped = snappedPolygonsForMerge(polygons, cache); + const planeEpsilon = planeFitEpsilon(snapped, options); + if (planeEpsilon <= 0) return snapped; + + const metas = snapped.map((polygon): PlaneNormalizeMeta | null => { + const plane = planeOfPolygon(polygon); + if (!plane) return null; + return { + polygon, + normal: plane.normal, + area: plane.area, + materialKey: materialKeyForPolygon(polygon), + }; + }); + const adjacency = buildMergeAdjacency(snapped, metas); + const assigned = new Set(); + const output: Array = Array(snapped.length); + const vertexMoves: VertexPositionMove[] = []; + const writeOutput = (index: number, polygon: Polygon): void => { + output[index] = polygon; + }; + + for (let i = 0; i < snapped.length; i++) { + const meta = metas[i]; + if (assigned.has(i)) continue; + if (!meta) { + writeOutput(i, snapped[i]); + continue; + } + + const group = growPlaneGroup(i, metas, adjacency, assigned, planeEpsilon, options); + for (const index of group) assigned.add(index); + if (group.length < 2) { + writeOutput(i, snapped[i]); + continue; + } + + const replacements = choosePlaneGroupReplacements(group, snapped, metas, adjacency, planeEpsilon, options); + vertexMoves.push(...replacements.vertexMoves); + for (const index of group) { + writeOutput(index, replacements.polygons.get(index) ?? snapped[index]); + } + } + + const projected = output.flatMap((polygon) => polygon ? [polygon] : []); + const moved = vertexMoves.length > 0 + ? applyVertexPositionMoves(projected, averagedVertexPositionMoves(vertexMoves)) + : projected; + return snapGeometryForMerge(moved); +} + +function choosePlaneGroupReplacements( + group: number[], + polygons: Polygon[], + metas: Array, + adjacency: Map>, + planeEpsilon: number, + options: ResolvedGeometryNormalizeOptions, +): PlaneGroupReplacements { + const fullGroup = projectedPlanePatchCandidate(group, polygons, metas, planeEpsilon, options); + if (fullGroup) return replacementsForPlanePatch(fullGroup); + return splitPlaneGroupIntoWinningPatches(group, polygons, metas, adjacency, planeEpsilon, options); +} + +function splitPlaneGroupIntoWinningPatches( + group: number[], + polygons: Polygon[], + metas: Array, + adjacency: Map>, + planeEpsilon: number, + options: ResolvedGeometryNormalizeOptions, +): PlaneGroupReplacements { + const groupSet = new Set(group); + const candidates: PlanePatchCandidate[] = []; + for (const a of group) { + for (const b of adjacency.get(a) ?? []) { + if (a >= b || !groupSet.has(b)) continue; + const candidate = projectedPlanePatchCandidate([a, b], polygons, metas, planeEpsilon, options); + if (candidate) candidates.push(candidate); + } + } + + candidates.sort((a, b) => b.score - a.score); + const used = new Set(); + const replacements = new Map(); + const vertexMoves: VertexPositionMove[] = []; + for (const candidate of candidates) { + if (candidate.indices.some((index) => used.has(index))) continue; + vertexMoves.push(...candidate.vertexMoves); + for (let i = 0; i < candidate.indices.length; i++) { + const index = candidate.indices[i]; + used.add(index); + replacements.set(index, polygons[index]); + } + } + return { polygons: replacements, vertexMoves }; +} + +function replacementsForPlanePatch(candidate: PlanePatchCandidate): PlaneGroupReplacements { + const replacements = new Map(); + for (let i = 0; i < candidate.indices.length; i++) { + replacements.set(candidate.indices[i], candidate.source[i]); + } + return { polygons: replacements, vertexMoves: candidate.vertexMoves }; +} + +function projectedPlanePatchCandidate( + group: number[], + polygons: Polygon[], + metas: Array, + planeEpsilon: number, + options: ResolvedGeometryNormalizeOptions, +): PlanePatchCandidate | null { + const fit = fitPlaneForGroup(group, metas); + if (!fit || !groupWithinPlaneBudget(group, metas, fit, planeEpsilon, options)) return null; + + const source = group.map((index) => polygons[index]); + const projected = source.map((polygon) => projectPolygonToPlane(polygon, fit)); + const sourceCost = polygonRenderCost(mergePolygons(source)); + const projectedCost = polygonRenderCost(mergePolygons(projected)); + if (projectedCost >= sourceCost) return null; + return { + indices: group, + source, + projected, + vertexMoves: vertexPositionMovesForProjection(source, projected), + score: sourceCost - projectedCost, + }; +} + +function planeFitEpsilon( + polygons: Polygon[], + options: ResolvedGeometryNormalizeOptions, +): number { + const geometryEpsilon = geometrySnapEpsilon(polygons); + if (geometryEpsilon <= 0) return 0; + return options.maxPlaneDisplacement; +} + +function buildMergeAdjacency( + polygons: Polygon[], + metas: Array, +): Map> { + const edgeOwners = new Map(); + const adjacency = new Map>(); + + for (let i = 0; i < polygons.length; i++) { + const polygon = polygons[i]; + if (!metas[i] || polygon.vertices.length < 3) continue; + for (let j = 0; j < polygon.vertices.length; j++) { + const key = edgeKey(polygon.vertices[j], polygon.vertices[(j + 1) % polygon.vertices.length]); + const owners = edgeOwners.get(key); + if (owners) owners.push(i); + else edgeOwners.set(key, [i]); + } + } + + for (const owners of edgeOwners.values()) { + for (let a = 0; a < owners.length; a++) { + for (let b = a + 1; b < owners.length; b++) { + const ai = owners[a]; + const bi = owners[b]; + if (canShareMergePatch(polygons[ai], polygons[bi], metas[ai], metas[bi])) { + addAdjacency(adjacency, ai, bi); + addAdjacency(adjacency, bi, ai); + } + } + } + } + + return adjacency; +} + +function canShareMergePatch( + a: Polygon, + b: Polygon, + aMeta: PlaneNormalizeMeta | null, + bMeta: PlaneNormalizeMeta | null, +): boolean { + if (!aMeta || !bMeta) return false; + if (aMeta.materialKey !== bMeta.materialKey) return false; + if (!!a.uvs !== !!b.uvs) return false; + if (hasTextureMergeState(a) || hasTextureMergeState(b)) return canUseTexturedLossyMerge(a, b); + if (!a.uvs || !b.uvs) return true; + + const shared = sharedEdgeIndices(a, b); + if (!shared) return false; + const [ai0, ai1, bi0, bi1] = shared; + return eqUv(a.uvs[ai0], b.uvs[bi0]) && eqUv(a.uvs[ai1], b.uvs[bi1]); +} + +function addAdjacency(adjacency: Map>, from: number, to: number): void { + const values = adjacency.get(from); + if (values) values.add(to); + else adjacency.set(from, new Set([to])); +} + +function growPlaneGroup( + seed: number, + metas: Array, + adjacency: Map>, + assigned: Set, + planeEpsilon: number, + options: ResolvedGeometryNormalizeOptions, +): number[] { + const group = [seed]; + const queued = new Set([seed]); + const queue = [seed]; + + while (queue.length > 0) { + const current = queue.shift()!; + for (const next of adjacency.get(current) ?? []) { + if (assigned.has(next) || queued.has(next)) continue; + const nextMeta = metas[next]; + const seedMeta = metas[seed]; + if (!nextMeta || !seedMeta) continue; + if (nextMeta.materialKey !== seedMeta.materialKey) continue; + if (!canJoinPlaneGroup([...group, next], metas, planeEpsilon, options)) continue; + group.push(next); + queued.add(next); + queue.push(next); + } + } + + return group; +} + +function canJoinPlaneGroup( + group: number[], + metas: Array, + planeEpsilon: number, + options: ResolvedGeometryNormalizeOptions, +): boolean { + const fit = fitPlaneForGroup(group, metas); + return !!fit && groupWithinPlaneBudget(group, metas, fit, planeEpsilon, options); +} + +function fitPlaneForGroup( + group: number[], + metas: Array, +): PlaneFit | null { + const seed = metas[group[0]]; + if (!seed) return null; + + let nx = 0; + let ny = 0; + let nz = 0; + let px = 0; + let py = 0; + let pz = 0; + let weightSum = 0; + + for (const index of group) { + const meta = metas[index]; + if (!meta) return null; + const direction = dotVec(seed.normal, meta.normal) < 0 ? -1 : 1; + const weight = Math.max(meta.area, 1e-6); + nx += meta.normal[0] * direction * weight; + ny += meta.normal[1] * direction * weight; + nz += meta.normal[2] * direction * weight; + for (const vertex of meta.polygon.vertices) { + px += vertex[0]; + py += vertex[1]; + pz += vertex[2]; + weightSum += 1; + } + } + + const normal = normalizeVec([nx, ny, nz]); + if (!normal || weightSum === 0) return null; + const boundaryVertices = groupBoundaryVertexKeys(group, metas); + const boundaryD = planeOffsetRangeForVertices(group, metas, normal, boundaryVertices); + if (boundaryD) { + const d = (boundaryD.min + boundaryD.max) / 2; + return { + normal, + point: [normal[0] * d, normal[1] * d, normal[2] * d], + boundaryVertexKeys: boundaryVertices, + }; + } + + return { + normal, + point: [px / weightSum, py / weightSum, pz / weightSum], + boundaryVertexKeys: boundaryVertices, + }; +} + +function planeOffsetRangeForVertices( + group: number[], + metas: Array, + normal: Vec3, + vertexKeys: Set, +): { min: number; max: number } | null { + let min = Infinity; + let max = -Infinity; + + for (const index of group) { + const meta = metas[index]; + if (!meta) continue; + for (const vertex of meta.polygon.vertices) { + if (!vertexKeys.has(vertexKey(vertex))) continue; + const d = dotVec(vertex, normal); + min = Math.min(min, d); + max = Math.max(max, d); + } + } + + return Number.isFinite(min) && Number.isFinite(max) ? { min, max } : null; +} + +function groupWithinPlaneBudget( + group: number[], + metas: Array, + fit: PlaneFit, + planeEpsilon: number, + options: ResolvedGeometryNormalizeOptions, +): boolean { + const normalDotMin = Math.cos((options.maxAngleDeg * Math.PI) / 180); + const boundaryVertices = fit.boundaryVertexKeys ?? groupBoundaryVertexKeys(group, metas); + for (const index of group) { + const meta = metas[index]; + if (!meta) return false; + if (Math.abs(dotVec(meta.normal, fit.normal)) < normalDotMin) return false; + for (const vertex of meta.polygon.vertices) { + const limit = boundaryVertices.has(vertexKey(vertex)) + ? options.maxBoundaryDisplacement + : planeEpsilon; + if (Math.abs(signedPlaneDistance(vertex, fit)) > limit) return false; + } + } + return true; +} + +function groupBoundaryVertexKeys( + group: number[], + metas: Array, +): Set { + const edgeCounts = new Map(); + + for (const index of group) { + const meta = metas[index]; + if (!meta) continue; + const vertices = meta.polygon.vertices; + for (let i = 0; i < vertices.length; i++) { + const a = vertices[i]; + const b = vertices[(i + 1) % vertices.length]; + const key = edgeKey(a, b); + const current = edgeCounts.get(key); + if (current) current.count += 1; + else edgeCounts.set(key, { count: 1, a, b }); + } + } + + const boundary = new Set(); + for (const edge of edgeCounts.values()) { + if (edge.count !== 1) continue; + boundary.add(vertexKey(edge.a)); + boundary.add(vertexKey(edge.b)); + } + return boundary; +} + +function projectPolygonToPlane(polygon: Polygon, fit: PlaneFit): Polygon { + const projectVertex = (vertex: Vec3): Vec3 => projectVecToPlane(vertex, fit); + const textureTriangles = mapTextureTriangleVertices(polygon.textureTriangles, projectVertex); + return { + ...polygon, + vertices: polygon.vertices.map(projectVertex), + ...(textureTriangles ? { textureTriangles } : {}), + }; +} diff --git a/packages/core/src/merge/optimize/preprocess.ts b/packages/core/src/merge/optimize/preprocess.ts new file mode 100644 index 000000000..93797c826 --- /dev/null +++ b/packages/core/src/merge/optimize/preprocess.ts @@ -0,0 +1,351 @@ +import { cullInteriorPolygons } from "../../cull/cullInteriorPolygons"; +import type { Polygon } from "../../types"; +import { coverPlanarPolygons, type CoverPlanarPolygonsOptions } from "../coverPlanarPolygons"; +import { findOverlappingPolygonDuplicates } from "../dedupeOverlappingPolygons"; +import { mergePolygons } from "../mergePolygons"; +import { simplifyTriangleMeshPolygons } from "../simplifyTriangleMesh"; +import { edgeKey, snappedPolygonsForMerge } from "./geometry"; +import { mergeIsolatedTrianglePairs } from "./pairMerge"; +import { normalizeGeometryForMerge } from "./planeNormalize"; +import type { + IndexFilter, + LossyApproximateOptions, + OptimizeMeshPolygonsOptions, + OptimizeStaticSimplificationOptions, + PreprocessCache, + ResolvedGeometryNormalizeOptions, + StaticSimplificationPlan, +} from "./types"; + +const NORMALIZE_MAX_ANGLE_DEG = 3; +const NORMALIZE_MAX_PLANE_DISPLACEMENT = 0.03; +const NORMALIZE_MAX_BOUNDARY_DISPLACEMENT = 0.02; + +const DEFAULT_NORMALIZE_OPTIONS: ResolvedGeometryNormalizeOptions = { + maxAngleDeg: NORMALIZE_MAX_ANGLE_DEG, + maxPlaneDisplacement: NORMALIZE_MAX_PLANE_DISPLACEMENT, + maxBoundaryDisplacement: NORMALIZE_MAX_BOUNDARY_DISPLACEMENT, + isolatedPairs: false, +}; + +const AUTOMATIC_RECT_COVER_MAX_POLYGONS = 1800; +const AUTOMATIC_RECT_COVER_MIN_TRIANGLE_RATIO = 0.65; +const LARGE_LOSSY_RECT_COVER_MIN_POLYGONS = 1000; +const LARGE_LOSSY_RECT_COVER_MAX_POLYGONS = 2200; +const LARGE_LOSSY_RECT_COVER_MAX_BOUNDARY_EDGES = 350; +const WIDE_LOSSY_VARIANT_MAX_SOURCE_POLYGONS = 700; +const DEFAULT_STATIC_SIMPLIFY_EARLY_STOP_DROP_RATIO = 0.15; +const MIN_STATIC_SIMPLIFY_BASELINE_SOURCE_RATIO = 0.23; +const DEFAULT_RECT_COVER_SMALL_AUTOMATIC_SKIP_MIN_POLYGONS = 24; +const DEFAULT_RECT_COVER_SMALL_AUTOMATIC_SKIP_MAX_POLYGONS = 50; +const DEFAULT_RECT_COVER_MAX_AUTOMATIC_POLYGONS = 1000; +const DEFAULT_RECT_COVER_MAX_BOUNDARY_EDGES = 1000; + +export const DEFAULT_RECT_COVER_OPTIONS: CoverPlanarPolygonsOptions = { + minGroupPolygons: 2, + maxCandidateAxes: 24, +}; + +const AUTOMATIC_LOSSY_RECT_COVER_OPTIONS: CoverPlanarPolygonsOptions = { + ...DEFAULT_RECT_COVER_OPTIONS, + maxCandidateAxes: 1, +}; + +const LARGE_LOSSY_RECT_COVER_OPTIONS: CoverPlanarPolygonsOptions = { + ...DEFAULT_RECT_COVER_OPTIONS, + maxCandidateAxes: 2, +}; + +export function staticSimplificationEarlyStopTarget( + count: number, + options: OptimizeStaticSimplificationOptions, +): number { + const ratio = Number.isFinite(options.earlyStopDropRatio) + ? Math.max(0, options.earlyStopDropRatio!) + : DEFAULT_STATIC_SIMPLIFY_EARLY_STOP_DROP_RATIO; + return Math.max(0, count - Math.max(1, Math.ceil(count * ratio))); +} + +export function hasSourceVertexKeys(polygons: Polygon[]): boolean { + return polygons.some((polygon) => polygon.simplifySourceVertexKeys?.length === polygon.vertices.length); +} + +export function shouldTryStaticSimplification(polygons: Polygon[], baselineOptimized: Polygon[]): boolean { + return polygons.length === 0 || + baselineOptimized.length / polygons.length > MIN_STATIC_SIMPLIFY_BASELINE_SOURCE_RATIO; +} + +export function simplifyTriangleMeshCandidate( + source: Polygon[], + options: OptimizeStaticSimplificationOptions, + vertexKeyMode?: "relaxed" | "source", +): Polygon[] | null { + const candidate = simplifyTriangleMeshPolygons(source, { + ...options.simplifyTriangleMeshOptions, + ...(vertexKeyMode ? { vertexKeyMode } : {}), + }); + if (candidate === source || candidate.length >= source.length) return null; + return candidate; +} + +export function resolveStaticSimplificationPlan( + plan: StaticSimplificationPlan, + options: OptimizeStaticSimplificationOptions, +): Polygon[] | null { + if (plan.precomputed !== undefined) return plan.precomputed; + return simplifyTriangleMeshCandidate(plan.source, options, plan.vertexKeyMode); +} + +export function applyRectCoverCandidate( + polygons: Polygon[], + setting: OptimizeMeshPolygonsOptions["rectCover"], +): Polygon[] { + if (setting === false) return polygons; + const options = resolveRectCoverOptions(polygons, setting); + if (!options) return polygons; + const covered = coverPlanarPolygons(polygons, options); + return covered.length < polygons.length ? covered : polygons; +} + +function resolveRectCoverOptions( + polygons: Polygon[], + setting: OptimizeMeshPolygonsOptions["rectCover"], +): CoverPlanarPolygonsOptions | null { + if (setting && setting !== true) return setting; + + const explicit = setting === true; + const polygonCount = polygons.length; + if (polygonCount > 2200) return null; + if ( + !explicit && + polygonCount >= DEFAULT_RECT_COVER_SMALL_AUTOMATIC_SKIP_MIN_POLYGONS && + polygonCount < DEFAULT_RECT_COVER_SMALL_AUTOMATIC_SKIP_MAX_POLYGONS + ) return null; + if (!explicit && polygonCount > DEFAULT_RECT_COVER_MAX_AUTOMATIC_POLYGONS) return null; + if (!explicit && polygonCount <= 300) { + return { + ...DEFAULT_RECT_COVER_OPTIONS, + maxCandidateAxes: 1, + }; + } + if (polygonCount > 300) { + if (!explicit) { + if (maxPolygonVertexCount(polygons) > 12) return null; + if (polygonBoundaryEdgeCount(polygons) > DEFAULT_RECT_COVER_MAX_BOUNDARY_EDGES) return null; + } + return { + ...DEFAULT_RECT_COVER_OPTIONS, + maxCandidateAxes: Math.min(DEFAULT_RECT_COVER_OPTIONS.maxCandidateAxes ?? 24, 2), + }; + } + return DEFAULT_RECT_COVER_OPTIONS; +} + +export function automaticLossyRectCoverOptions(polygons: Polygon[]): CoverPlanarPolygonsOptions | false { + if (polygons.length > AUTOMATIC_RECT_COVER_MAX_POLYGONS) return false; + if (polygons.length === 0) return false; + if (polygonTriangleCount(polygons) / polygons.length < AUTOMATIC_RECT_COVER_MIN_TRIANGLE_RATIO) { + return false; + } + return AUTOMATIC_LOSSY_RECT_COVER_OPTIONS; +} + +export function automaticLargeLossyRectCoverCandidate(polygons: Polygon[]): CoverPlanarPolygonsOptions | false { + if (polygons.length < LARGE_LOSSY_RECT_COVER_MIN_POLYGONS) return false; + if (polygons.length > LARGE_LOSSY_RECT_COVER_MAX_POLYGONS) return false; + if (maxPolygonVertexCount(polygons) <= 12) return false; + if (polygonBoundaryEdgeCount(polygons) > LARGE_LOSSY_RECT_COVER_MAX_BOUNDARY_EDGES) return false; + return LARGE_LOSSY_RECT_COVER_OPTIONS; +} + +export function automaticWideLossyVariantCandidate(polygons: Polygon[]): boolean { + return polygons.length <= WIDE_LOSSY_VARIANT_MAX_SOURCE_POLYGONS; +} + +function polygonTriangleCount(polygons: Polygon[]): number { + let triangles = 0; + for (const polygon of polygons) { + if (polygon.vertices.length === 3) triangles += 1; + } + return triangles; +} + +function maxPolygonVertexCount(polygons: Polygon[]): number { + let max = 0; + for (const polygon of polygons) { + max = Math.max(max, polygon.vertices.length); + } + return max; +} + +function polygonBoundaryEdgeCount(polygons: Polygon[]): number { + const edges = new Map(); + for (const polygon of polygons) { + for (let i = 0; i < polygon.vertices.length; i++) { + const a = polygon.vertices[i]; + const b = polygon.vertices[(i + 1) % polygon.vertices.length]; + const key = edgeKey(a, b); + edges.set(key, (edges.get(key) ?? 0) + 1); + } + } + let boundary = 0; + for (const count of edges.values()) { + if (count === 1) boundary += 1; + } + return boundary; +} + +function applyIndexFilter(polygons: Polygon[], filter: IndexFilter | undefined): Polygon[] { + if (filter === undefined || filter === null) return polygons; + return filter.map((index) => polygons[index]).filter((polygon): polygon is Polygon => !!polygon); +} + +function keptIndexFilter(input: Polygon[], kept: Polygon[]): IndexFilter { + if (kept === input) return null; + if (kept.length === input.length && kept.every((polygon, index) => polygon === input[index])) { + return null; + } + const keptSet = new Set(kept); + const indices: number[] = []; + for (let i = 0; i < input.length; i++) { + if (keptSet.has(input[i])) indices.push(i); + } + return indices.length === input.length ? null : indices; +} + +function dedupedPolygonsForMerge(polygons: Polygon[], cache?: PreprocessCache): Polygon[] { + if (cache?.deduped) return cache.deduped; + let filter = cache?.dedupedIndices; + if (filter === undefined) { + const dropped = findOverlappingPolygonDuplicates(polygons); + if (dropped.size === 0) { + filter = null; + } else { + filter = []; + for (let i = 0; i < polygons.length; i++) { + if (!dropped.has(i)) filter.push(i); + } + } + if (cache) cache.dedupedIndices = filter; + } + const deduped = applyIndexFilter(polygons, filter); + if (cache) cache.deduped = deduped; + return deduped; +} + +function interiorPolygonsForMerge(polygons: Polygon[], cache?: PreprocessCache): Polygon[] { + if (cache?.skipInteriorCull) return polygons; + if (cache?.interior) return cache.interior; + let filter = cache?.interiorIndices; + if (filter === undefined) { + const kept = cullInteriorPolygons(polygons); + filter = keptIndexFilter(polygons, kept); + if (cache) cache.interiorIndices = filter; + } + const interior = applyIndexFilter(polygons, filter); + if (cache) cache.interior = interior; + return interior; +} + +export function preprocessModelPolygons( + polygons: Polygon[], + normalizeGeometry: boolean | LossyApproximateOptions, + cache?: PreprocessCache, +): Polygon[] { + // Dedup runs FIRST — catches inner/outer shell duplicates and coincident + // doubled-up faces that importers emit as artifacts. Doing it before + // cull + merge means everything downstream operates on the leaner set + // and gets a free speedup as a bonus. Light-independent, runs once. + const deduped = dedupedPolygonsForMerge(polygons, cache); + const interior = interiorPolygonsForMerge(deduped, cache); + const baseline = cache?.baseline ?? mergePolygons(interior); + if (cache && !cache.baseline) cache.baseline = baseline; + if (!normalizeGeometry) return baseline; + + const options = normalizeGeometry === true + ? DEFAULT_NORMALIZE_OPTIONS + : resolveNormalizeOptions(normalizeGeometry); + if (options.isolatedPairs) { + const paired = mergeIsolatedTrianglePairs(snappedInteriorPolygonsForMerge(deduped, cache), options, cache); + let mergedPaired = mergePolygons(paired); + if ( + cache?.snappedInteriorUsesBaselineFilter && + shouldRecheckSnappedInteriorCull(baseline, mergedPaired) + ) { + const exactPaired = mergeIsolatedTrianglePairs( + snappedInteriorPolygonsForMerge(deduped, cache, true), + options, + cache, + ); + const exactMergedPaired = mergePolygons(exactPaired); + if (exactMergedPaired.length < mergedPaired.length) mergedPaired = exactMergedPaired; + } + return mergedPaired.length < baseline.length ? mergedPaired : baseline; + } + const normalizedGeometry = normalizeGeometryForMerge(deduped, options, cache); + const normalizedInterior = cullInteriorPolygons(normalizedGeometry); + const normalized = mergePolygons(normalizedInterior); + return normalized.length < baseline.length ? normalized : baseline; +} + +function snappedInteriorPolygonsForMerge( + polygons: Polygon[], + cache?: PreprocessCache, + exactCull = false, +): Polygon[] { + if (!cache) return cullInteriorPolygons(snappedPolygonsForMerge(polygons)); + if (exactCull && cache.snappedInteriorExact) return cache.snappedInteriorExact; + if (!exactCull && cache.snappedInterior) return cache.snappedInterior; + + const snapped = snappedPolygonsForMerge(polygons, cache); + if (exactCull) { + if (snapped === polygons && cache.deduped === polygons && cache.interior) { + cache.snappedInteriorExactIndices = cache.interiorIndices; + cache.snappedInteriorExact = cache.interior; + return cache.snappedInteriorExact; + } + const kept = cullInteriorPolygons(snapped); + cache.snappedInteriorExactIndices = keptIndexFilter(snapped, kept); + cache.snappedInteriorExact = kept; + return cache.snappedInteriorExact; + } + + if (!cache.snappedInterior) { + if (snapped === polygons && cache.deduped === polygons && cache.interior) { + cache.snappedInteriorIndices = cache.interiorIndices; + cache.snappedInterior = cache.interior; + cache.snappedInteriorUsesBaselineFilter = false; + return cache.snappedInterior; + } + if (cache.reuseSnappedInteriorCull !== false && cache.interiorIndices !== undefined) { + cache.snappedInteriorIndices = cache.interiorIndices; + cache.snappedInterior = applyIndexFilter(snapped, cache.snappedInteriorIndices); + cache.snappedInteriorUsesBaselineFilter = true; + return cache.snappedInterior; + } + if (cache.snappedInteriorIndices === undefined) { + const kept = cullInteriorPolygons(snapped); + cache.snappedInteriorIndices = keptIndexFilter(snapped, kept); + cache.snappedInterior = kept; + cache.snappedInteriorExactIndices = cache.snappedInteriorIndices; + cache.snappedInteriorExact = kept; + cache.snappedInteriorUsesBaselineFilter = false; + } else { + cache.snappedInterior = applyIndexFilter(snapped, cache.snappedInteriorIndices); + } + } + return cache.snappedInterior; +} + +function shouldRecheckSnappedInteriorCull(baseline: Polygon[], candidate: Polygon[]): boolean { + return candidate.length >= baseline.length; +} + +function resolveNormalizeOptions(options: LossyApproximateOptions): ResolvedGeometryNormalizeOptions { + return { + maxAngleDeg: options.maxAngleDeg ?? DEFAULT_NORMALIZE_OPTIONS.maxAngleDeg, + maxPlaneDisplacement: options.maxPlaneDisplacement ?? DEFAULT_NORMALIZE_OPTIONS.maxPlaneDisplacement, + maxBoundaryDisplacement: options.maxBoundaryDisplacement ?? DEFAULT_NORMALIZE_OPTIONS.maxBoundaryDisplacement, + isolatedPairs: options.isolatedPairs ?? DEFAULT_NORMALIZE_OPTIONS.isolatedPairs, + }; +} diff --git a/packages/core/src/merge/optimize/topology.ts b/packages/core/src/merge/optimize/topology.ts new file mode 100644 index 000000000..0be324008 --- /dev/null +++ b/packages/core/src/merge/optimize/topology.ts @@ -0,0 +1,325 @@ +import { boundsOverlap3D as topologySegmentBoundsOverlap } from "../../math/vec3"; +import type { Polygon, Vec3 } from "../../types"; +import { seamOverlapSafetyDiagnostics, type SeamOverlapDiagnostics } from "../seamRepair"; +import { distanceVec, dotVec, edgeKey, subVec } from "./geometry"; +import type { + SegmentOverlapInfo, + TopologyEdgeStats, + TopologyGapDiagnostics, + TopologySegment, + TopologySegmentIndex, +} from "./types"; + +export const TOPOLOGY_GAP_TOLERANCE = 0.045; +const TOPOLOGY_MIN_PARALLEL_DOT = 0.999; +const TOPOLOGY_MIN_OVERLAP = 1e-5; + +export function trySeamOverlapSafetyDiagnostics(polygons: Polygon[]): SeamOverlapDiagnostics | null { + try { + return seamOverlapSafetyDiagnostics(polygons); + } catch (error) { + if (error instanceof RangeError && error.message === "Set maximum size exceeded") return null; + throw error; + } +} + +export function seamDiagnosticsWorse( + candidate: SeamOverlapDiagnostics, + baseline: SeamOverlapDiagnostics, +): boolean { + return candidate.nearPairs > baseline.nearPairs || + candidate.unclosedPairs > baseline.unclosedPairs || + candidate.maxMeasuredGapPx > baseline.maxMeasuredGapPx + 1e-9 || + candidate.maxResidualGapPx > baseline.maxResidualGapPx + 1e-9; +} + +export function topologyGapDiagnosticsWorse( + referenceEdges: TopologyEdgeStats, + referenceDiagnostics: TopologyGapDiagnostics, + candidate: Polygon[], +): boolean { + const candidateEdges = collectTopologyEdgeStats(candidate); + if (topologyExposesReferenceInternalEdge(referenceEdges, candidateEdges, TOPOLOGY_GAP_TOLERANCE)) return true; + return boundaryTJunctionDiagnosticsWorse( + candidateEdges.boundarySegments, + TOPOLOGY_GAP_TOLERANCE, + referenceDiagnostics, + ); +} + +function topologyExposesReferenceInternalEdge( + referenceEdges: TopologyEdgeStats, + candidateEdges: TopologyEdgeStats, + tolerance: number, +): boolean { + if (referenceEdges.internalSegments.length === 0) return false; + const internalIndex = topologyInternalSegmentIndex(referenceEdges, tolerance); + + for (const segment of candidateEdges.boundarySegments) { + if (referenceEdges.boundaryKeys.has(segment.key)) continue; + if (referenceEdges.internalKeys.has(segment.key)) return true; + if (hasOverlappingSegment(segment, internalIndex, tolerance)) return true; + } + + return false; +} + +function topologyInternalSegmentIndex( + edges: TopologyEdgeStats, + tolerance: number, +): TopologySegmentIndex { + if (!edges.internalIndex || edges.internalIndexTolerance !== tolerance) { + edges.internalIndex = buildTopologySegmentIndex(edges.internalSegments, tolerance); + edges.internalIndexTolerance = tolerance; + } + return edges.internalIndex; +} + +function boundaryTJunctionDiagnosticsWorse( + boundarySegments: TopologySegment[], + tolerance: number, + referenceDiagnostics: TopologyGapDiagnostics, +): boolean { + const boundaryIndex = buildTopologySegmentIndex(boundarySegments, tolerance); + const seenPairs = new Set(); + let pairStride = 0; + let tJunctionPairs = 0; + let tJunctionLength = 0; + for (const segment of boundarySegments) pairStride = Math.max(pairStride, segment.index + 1); + for (const segment of boundarySegments) { + for (const other of overlappingSegmentCandidates(segment, boundaryIndex, tolerance)) { + if (other === segment || other.polygon === segment.polygon || other.key === segment.key) continue; + const pairKey = segment.index < other.index + ? segment.index * pairStride + other.index + : other.index * pairStride + segment.index; + if (seenPairs.has(pairKey)) continue; + seenPairs.add(pairKey); + const overlap = segmentOverlap(segment, other, tolerance); + if (!overlap) continue; + tJunctionPairs += 1; + tJunctionLength += overlap.overlapLength; + if ( + tJunctionPairs > referenceDiagnostics.tJunctionPairs || + tJunctionLength > referenceDiagnostics.tJunctionLength + 1e-9 + ) return true; + } + } + return false; +} + +export function topologySelfDiagnostics(edges: TopologyEdgeStats, tolerance: number): TopologyGapDiagnostics { + const diagnostics: TopologyGapDiagnostics = { + tJunctionPairs: 0, + tJunctionLength: 0, + }; + addBoundaryTJunctionDiagnostics(diagnostics, edges.boundarySegments, tolerance); + return diagnostics; +} + +function addBoundaryTJunctionDiagnostics( + diagnostics: TopologyGapDiagnostics, + boundarySegments: TopologySegment[], + tolerance: number, +): void { + const boundaryIndex = buildTopologySegmentIndex(boundarySegments, tolerance); + const seenPairs = new Set(); + let pairStride = 0; + for (const segment of boundarySegments) pairStride = Math.max(pairStride, segment.index + 1); + for (const segment of boundarySegments) { + for (const other of overlappingSegmentCandidates(segment, boundaryIndex, tolerance)) { + if (other === segment || other.polygon === segment.polygon || other.key === segment.key) continue; + const pairKey = segment.index < other.index + ? segment.index * pairStride + other.index + : other.index * pairStride + segment.index; + if (seenPairs.has(pairKey)) continue; + seenPairs.add(pairKey); + const overlap = segmentOverlap(segment, other, tolerance); + if (!overlap) continue; + diagnostics.tJunctionPairs += 1; + diagnostics.tJunctionLength += overlap.overlapLength; + } + } +} + +export function collectTopologyEdgeStats(polygons: Polygon[]): TopologyEdgeStats { + const edges = new Map(); + for (let polygonIndex = 0; polygonIndex < polygons.length; polygonIndex += 1) { + const vertices = polygons[polygonIndex].vertices; + for (let edgeIndex = 0; edgeIndex < vertices.length; edgeIndex += 1) { + const a = vertices[edgeIndex]; + const b = vertices[(edgeIndex + 1) % vertices.length]; + const segment = topologySegment(edgeKey(a, b), polygonIndex, edgeIndex, a, b); + if (!segment) continue; + const current = edges.get(segment.key); + if (current) current.count += 1; + else edges.set(segment.key, { count: 1, segment }); + } + } + + const boundaryKeys = new Set(); + const internalKeys = new Set(); + const boundarySegments: TopologySegment[] = []; + const internalSegments: TopologySegment[] = []; + let boundaryLength = 0; + let index = 0; + for (const edge of edges.values()) { + const segment = { ...edge.segment, index }; + index += 1; + if (edge.count === 1) { + boundaryKeys.add(segment.key); + boundarySegments.push(segment); + boundaryLength += segment.length; + } else { + internalKeys.add(segment.key); + internalSegments.push(segment); + } + } + return { boundaryKeys, internalKeys, boundarySegments, internalSegments, boundaryLength }; +} + +function topologySegment( + key: string, + polygon: number, + edge: number, + a: Vec3, + b: Vec3, +): TopologySegment | null { + const delta = subVec(b, a); + const length = Math.hypot(delta[0], delta[1], delta[2]); + if (length <= 1e-10) return null; + const dir: Vec3 = [delta[0] / length, delta[1] / length, delta[2] / length]; + return { + index: -1, + key, + polygon, + edge, + a, + b, + dir, + length, + minX: Math.min(a[0], b[0]), + minY: Math.min(a[1], b[1]), + minZ: Math.min(a[2], b[2]), + maxX: Math.max(a[0], b[0]), + maxY: Math.max(a[1], b[1]), + maxZ: Math.max(a[2], b[2]), + }; +} + +function buildTopologySegmentIndex(segments: TopologySegment[], tolerance: number): TopologySegmentIndex { + const cellSize = Math.max(tolerance * 8, 0.5); + const cells = new Map(); + for (const segment of segments) { + addTopologySegmentToCells(cells, segment, cellSize, tolerance); + } + return { cellSize, cells }; +} + +function addTopologySegmentToCells( + cells: Map, + segment: TopologySegment, + cellSize: number, + padding: number, +) { + const [minX, minY, minZ] = topologyCellCoords( + [segment.minX - padding, segment.minY - padding, segment.minZ - padding], + cellSize, + ); + const [maxX, maxY, maxZ] = topologyCellCoords( + [segment.maxX + padding, segment.maxY + padding, segment.maxZ + padding], + cellSize, + ); + for (let x = minX; x <= maxX; x += 1) { + for (let y = minY; y <= maxY; y += 1) { + for (let z = minZ; z <= maxZ; z += 1) { + const key = `${x},${y},${z}`; + const bucket = cells.get(key); + if (bucket) bucket.push(segment); + else cells.set(key, [segment]); + } + } + } +} + +function topologyCellCoords(point: Vec3, cellSize: number): [number, number, number] { + return [ + Math.floor(point[0] / cellSize), + Math.floor(point[1] / cellSize), + Math.floor(point[2] / cellSize), + ]; +} + +function overlappingSegmentCandidates( + segment: TopologySegment, + index: ReturnType, + tolerance: number, +): TopologySegment[] { + const out: TopologySegment[] = []; + const seen = new Set(); + const [minX, minY, minZ] = topologyCellCoords( + [segment.minX - tolerance, segment.minY - tolerance, segment.minZ - tolerance], + index.cellSize, + ); + const [maxX, maxY, maxZ] = topologyCellCoords( + [segment.maxX + tolerance, segment.maxY + tolerance, segment.maxZ + tolerance], + index.cellSize, + ); + for (let x = minX; x <= maxX; x += 1) { + for (let y = minY; y <= maxY; y += 1) { + for (let z = minZ; z <= maxZ; z += 1) { + const bucket = index.cells.get(`${x},${y},${z}`); + if (!bucket) continue; + for (const candidate of bucket) { + if (seen.has(candidate)) continue; + seen.add(candidate); + out.push(candidate); + } + } + } + } + return out; +} + +function hasOverlappingSegment( + segment: TopologySegment, + index: ReturnType, + tolerance: number, +): boolean { + for (const candidate of overlappingSegmentCandidates(segment, index, tolerance)) { + const overlap = segmentOverlap(segment, candidate, tolerance); + if (overlap) return true; + } + return false; +} + +function segmentOverlap( + a: TopologySegment, + b: TopologySegment, + tolerance: number, +): SegmentOverlapInfo | null { + if (!topologySegmentBoundsOverlap(a, b, tolerance)) return null; + if (Math.abs(dotVec(a.dir, b.dir)) < TOPOLOGY_MIN_PARALLEL_DOT) return null; + + const bStart = dotVec(subVec(b.a, a.a), a.dir); + const bEnd = dotVec(subVec(b.b, a.a), a.dir); + const overlapStart = Math.max(0, Math.min(bStart, bEnd)); + const overlapEnd = Math.min(a.length, Math.max(bStart, bEnd)); + const overlapLength = overlapEnd - overlapStart; + if (overlapLength <= Math.max(TOPOLOGY_MIN_OVERLAP, Math.min(a.length, b.length) * 1e-4)) { + return null; + } + + const mid = [ + a.a[0] + a.dir[0] * ((overlapStart + overlapEnd) / 2), + a.a[1] + a.dir[1] * ((overlapStart + overlapEnd) / 2), + a.a[2] + a.dir[2] * ((overlapStart + overlapEnd) / 2), + ] as Vec3; + const projected = Math.max(0, Math.min(b.length, dotVec(subVec(mid, b.a), b.dir))); + const closest: Vec3 = [ + b.a[0] + b.dir[0] * projected, + b.a[1] + b.dir[1] * projected, + b.a[2] + b.dir[2] * projected, + ]; + const offset = distanceVec(mid, closest); + return offset <= tolerance ? { overlapLength, offset } : null; +} diff --git a/packages/core/src/merge/optimize/types.ts b/packages/core/src/merge/optimize/types.ts new file mode 100644 index 000000000..65440a9ba --- /dev/null +++ b/packages/core/src/merge/optimize/types.ts @@ -0,0 +1,215 @@ +import type { MeshResolution, Polygon, Vec3 } from "../../types"; +import type { CoverPlanarPolygonsOptions } from "../coverPlanarPolygons"; +import type { SeamOverlapDiagnostics } from "../seamRepair"; +import type { SimplifyTriangleMeshPolygonsOptions } from "../simplifyTriangleMesh"; + +export interface LossyApproximateOptions { + maxAngleDeg?: number; + maxPlaneDisplacement?: number; + maxBoundaryDisplacement?: number; + isolatedPairs?: boolean; +} + +export interface OptimizeMeshPolygonsOptions { + /** Public quality/resolution intent. Defaults to "lossy". */ + meshResolution?: MeshResolution; + /** + * Return as soon as the optimizer finds a result with at most this many + * polygons. Useful for candidate comparisons where the caller already knows + * the maximum DOM leaf count it can accept. + */ + stopAtPolygonCount?: number; + /** + * Run the planar cover pass as an exact candidate for untextured coplanar + * regions. Defaults to true. + */ + rectCover?: boolean | CoverPlanarPolygonsOptions; +} + +export interface ResolvedGeometryNormalizeOptions { + maxAngleDeg: number; + maxPlaneDisplacement: number; + maxBoundaryDisplacement: number; + isolatedPairs: boolean; +} + +export interface PlaneNormalizeMeta { + polygon: Polygon; + normal: Vec3; + area: number; + materialKey: string; +} + +export interface PlaneFit { + normal: Vec3; + point: Vec3; + boundaryVertexKeys?: Set; +} + +export interface PairCandidate { + a: number; + b: number; + polygon: Polygon; + vertexMoves: VertexPositionMove[]; + score: number; +} + +export interface VertexPositionMove { + key: string; + target: Vec3; +} + +export interface PairCandidateRank { + degree: number; + score: number; + index: number; +} + +export interface PlanePatchCandidate { + indices: number[]; + source: Polygon[]; + projected: Polygon[]; + vertexMoves: VertexPositionMove[]; + score: number; +} + +export interface PlaneGroupReplacements { + polygons: Map; + vertexMoves: VertexPositionMove[]; +} + +export interface TrianglePairSourceCache { + polygons: Polygon[]; + metas: Array; + edgeOwnerPairs: Array<[number, number]>; + preparedCandidates?: PreparedPairCandidate[]; +} + +export interface PreparedPairCandidate { + candidate: PairCandidate; + normalDot: number; + maxDistance: number; +} + +export interface TopologySegment { + index: number; + key: string; + polygon: number; + edge: number; + a: Vec3; + b: Vec3; + dir: Vec3; + length: number; + minX: number; + minY: number; + minZ: number; + maxX: number; + maxY: number; + maxZ: number; +} + +export interface TopologyEdgeStats { + boundaryKeys: Set; + internalKeys: Set; + boundarySegments: TopologySegment[]; + internalSegments: TopologySegment[]; + boundaryLength: number; + internalIndex?: TopologySegmentIndex; + internalIndexTolerance?: number; +} + +export interface TopologySegmentIndex { + cellSize: number; + cells: Map; +} + +export interface TopologyGapDiagnostics { + tJunctionPairs: number; + tJunctionLength: number; +} + +export interface SegmentOverlapInfo { + overlapLength: number; + offset: number; +} + +export interface BestSafetyDiagnostics { + polygons: Polygon[]; + seam?: SeamOverlapDiagnostics; + topologyEdges?: TopologyEdgeStats; + topologySelf?: TopologyGapDiagnostics; +} + +export interface PreprocessCache { + skipInteriorCull?: boolean; + reuseSnappedInteriorCull?: boolean; + baseline?: Polygon[]; + deduped?: Polygon[]; + dedupedIndices?: IndexFilter; + interior?: Polygon[]; + interiorIndices?: IndexFilter; + snapped?: Polygon[]; + snappedInterior?: Polygon[]; + snappedInteriorIndices?: IndexFilter; + snappedInteriorUsesBaselineFilter?: boolean; + snappedInteriorExact?: Polygon[]; + snappedInteriorExactIndices?: IndexFilter; + trianglePairSource?: TrianglePairSourceCache; +} + +export interface OptimizeMeshPolygonsRunOptions { + requiredMaxPolygonCount?: number; + skipInteriorCull?: boolean; + skipExactRectCover?: boolean; + simplifiedCandidate?: boolean; + captureVisiblePolygons?: boolean; +} + +export interface OptimizeMeshPolygonsRunResult { + polygons: Polygon[]; + visiblePolygons?: Polygon[]; +} + +export type MeshOptimizationStep = + | { kind: "baselineCandidates" } + | { kind: "initialLossyCandidates" } + | { kind: "finalLossyCandidates" } + | { + kind: "staticSimplificationCandidates"; + options: OptimizeStaticSimplificationOptions; + stopOnAccept: boolean; + }; + +export interface MeshOptimizationPlan { + steps: readonly MeshOptimizationStep[]; +} + +export type MeshCandidateAcceptanceMode = "cost" | "dom" | "seamSafe"; + +export interface MeshCandidateSubmission { + mode: MeshCandidateAcceptanceMode; + polygons: Polygon[]; + cost?: number; + sourcePolygonCount?: number; + maxPolygonCount?: number; +} + +export interface OptimizeStaticSimplificationOptions { + simplifyTriangleMeshOptions?: SimplifyTriangleMeshPolygonsOptions; + earlyStopDropRatio?: number; +} + +export interface OptimizeParseMeshPolygonsOptions extends OptimizeMeshPolygonsOptions { + staticSimplification?: OptimizeStaticSimplificationOptions | false; + useCandidateFirst?: boolean; + skipInteriorCull?: boolean; +} + +export interface StaticSimplificationPlan { + source: Polygon[]; + vertexKeyMode?: "relaxed" | "source"; + precomputed?: Polygon[] | null; + skipInteriorCull?: boolean; +} + +export type IndexFilter = number[] | null; diff --git a/packages/core/src/merge/optimizePolygons.ts b/packages/core/src/merge/optimizePolygons.ts index 2a1fb191f..25c5b0fab 100644 --- a/packages/core/src/merge/optimizePolygons.ts +++ b/packages/core/src/merge/optimizePolygons.ts @@ -1,210 +1,40 @@ -import { cullInteriorPolygons } from "../cull/cullInteriorPolygons"; -import { boundsOverlap3D as topologySegmentBoundsOverlap, crossVec } from "../math/vec3"; -import { findOverlappingPolygonDuplicates } from "./dedupeOverlappingPolygons"; -import type { MeshResolution, Polygon, TextureTriangle, Vec2, Vec3 } from "../types"; -import { coverPlanarPolygons, type CoverPlanarPolygonsOptions } from "./coverPlanarPolygons"; -import { mergePolygons } from "./mergePolygons"; -import { seamOverlapSafetyDiagnostics, type SeamOverlapDiagnostics } from "./seamRepair"; +import type { MeshResolution, Polygon } from "../types"; +import type { CoverPlanarPolygonsOptions } from "./coverPlanarPolygons"; +import { MeshCandidateAcceptor } from "./optimize/acceptor"; +import { polygonRenderCost } from "./optimize/geometry"; import { - simplifyTriangleMeshPolygons, - type SimplifyTriangleMeshPolygonsOptions, -} from "./simplifyTriangleMesh"; -import { cloneTextureTriangles, fanTextureTriangles } from "./textureTriangles"; - -const NORMALIZE_MAX_ANGLE_DEG = 3; -const NORMALIZE_MAX_PLANE_DISPLACEMENT = 0.03; -const NORMALIZE_MAX_BOUNDARY_DISPLACEMENT = 0.02; - -interface LossyApproximateOptions { - maxAngleDeg?: number; - maxPlaneDisplacement?: number; - maxBoundaryDisplacement?: number; - isolatedPairs?: boolean; -} - -export interface OptimizeMeshPolygonsOptions { - /** Public quality/resolution intent. Defaults to "lossy". */ - meshResolution?: MeshResolution; - /** - * Return as soon as the optimizer finds a result with at most this many - * polygons. Useful for candidate comparisons where the caller already knows - * the maximum DOM leaf count it can accept. - */ - stopAtPolygonCount?: number; - /** - * Run the planar cover pass as an exact candidate for untextured coplanar - * regions. Defaults to true. - */ - rectCover?: boolean | CoverPlanarPolygonsOptions; -} - -interface ResolvedGeometryNormalizeOptions { - maxAngleDeg: number; - maxPlaneDisplacement: number; - maxBoundaryDisplacement: number; - isolatedPairs: boolean; -} - -interface PlaneNormalizeMeta { - polygon: Polygon; - normal: Vec3; - area: number; - materialKey: string; -} - -interface PlaneFit { - normal: Vec3; - point: Vec3; - boundaryVertexKeys?: Set; -} - -interface PairCandidate { - a: number; - b: number; - polygon: Polygon; - vertexMoves: VertexPositionMove[]; - score: number; -} - -interface VertexPositionMove { - key: string; - target: Vec3; -} - -interface PairCandidateRank { - degree: number; - score: number; - index: number; -} - -interface PlanePatchCandidate { - indices: number[]; - source: Polygon[]; - projected: Polygon[]; - vertexMoves: VertexPositionMove[]; - score: number; -} - -interface PlaneGroupReplacements { - polygons: Map; - vertexMoves: VertexPositionMove[]; -} - -interface TrianglePairSourceCache { - polygons: Polygon[]; - metas: Array; - edgeOwnerPairs: Array<[number, number]>; - preparedCandidates?: PreparedPairCandidate[]; -} - -interface PreparedPairCandidate { - candidate: PairCandidate; - normalDot: number; - maxDistance: number; -} - -interface TopologySegment { - index: number; - key: string; - polygon: number; - edge: number; - a: Vec3; - b: Vec3; - dir: Vec3; - length: number; - minX: number; - minY: number; - minZ: number; - maxX: number; - maxY: number; - maxZ: number; -} - -interface TopologyEdgeStats { - boundaryKeys: Set; - internalKeys: Set; - boundarySegments: TopologySegment[]; - internalSegments: TopologySegment[]; - boundaryLength: number; - internalIndex?: TopologySegmentIndex; - internalIndexTolerance?: number; -} - -interface TopologySegmentIndex { - cellSize: number; - cells: Map; -} - -interface TopologyGapDiagnostics { - tJunctionPairs: number; - tJunctionLength: number; -} - -interface SegmentOverlapInfo { - overlapLength: number; - offset: number; -} - -interface BestSafetyDiagnostics { - polygons: Polygon[]; - seam?: SeamOverlapDiagnostics; - topologyEdges?: TopologyEdgeStats; - topologySelf?: TopologyGapDiagnostics; -} - -interface PreprocessCache { - skipInteriorCull?: boolean; - reuseSnappedInteriorCull?: boolean; - baseline?: Polygon[]; - deduped?: Polygon[]; - dedupedIndices?: IndexFilter; - interior?: Polygon[]; - interiorIndices?: IndexFilter; - snapped?: Polygon[]; - snappedInterior?: Polygon[]; - snappedInteriorIndices?: IndexFilter; - snappedInteriorUsesBaselineFilter?: boolean; - snappedInteriorExact?: Polygon[]; - snappedInteriorExactIndices?: IndexFilter; - trianglePairSource?: TrianglePairSourceCache; -} - -interface OptimizeMeshPolygonsRunOptions { - requiredMaxPolygonCount?: number; - skipInteriorCull?: boolean; - skipExactRectCover?: boolean; - simplifiedCandidate?: boolean; - captureVisiblePolygons?: boolean; -} - -interface OptimizeMeshPolygonsRunResult { - polygons: Polygon[]; - visiblePolygons?: Polygon[]; -} - -type MeshOptimizationStep = - | { kind: "baselineCandidates" } - | { kind: "initialLossyCandidates" } - | { kind: "finalLossyCandidates" } - | { - kind: "staticSimplificationCandidates"; - options: OptimizeStaticSimplificationOptions; - stopOnAccept: boolean; - }; - -interface MeshOptimizationPlan { - steps: readonly MeshOptimizationStep[]; -} - -type MeshCandidateAcceptanceMode = "cost" | "dom" | "seamSafe"; - -interface MeshCandidateSubmission { - mode: MeshCandidateAcceptanceMode; - polygons: Polygon[]; - cost?: number; - sourcePolygonCount?: number; - maxPolygonCount?: number; -} + applyRectCoverCandidate, + automaticLargeLossyRectCoverCandidate, + automaticLossyRectCoverOptions, + automaticWideLossyVariantCandidate, + DEFAULT_RECT_COVER_OPTIONS, + hasSourceVertexKeys, + preprocessModelPolygons, + resolveStaticSimplificationPlan, + shouldTryStaticSimplification, + simplifyTriangleMeshCandidate, + staticSimplificationEarlyStopTarget, +} from "./optimize/preprocess"; +import type { + LossyApproximateOptions, + MeshCandidateAcceptanceMode, + MeshCandidateSubmission, + MeshOptimizationPlan, + MeshOptimizationStep, + OptimizeMeshPolygonsOptions, + OptimizeMeshPolygonsRunOptions, + OptimizeMeshPolygonsRunResult, + OptimizeParseMeshPolygonsOptions, + OptimizeStaticSimplificationOptions, + PreprocessCache, + StaticSimplificationPlan, +} from "./optimize/types"; + +export type { + OptimizeMeshPolygonsOptions, + OptimizeParseMeshPolygonsOptions, + OptimizeStaticSimplificationOptions, +}; interface MeshCandidateEngineConfig { acceptor?: MeshCandidateAcceptor; @@ -213,33 +43,6 @@ interface MeshCandidateEngineConfig { offerBaseline?: boolean; } -export interface OptimizeStaticSimplificationOptions { - simplifyTriangleMeshOptions?: SimplifyTriangleMeshPolygonsOptions; - earlyStopDropRatio?: number; -} - -export interface OptimizeParseMeshPolygonsOptions extends OptimizeMeshPolygonsOptions { - staticSimplification?: OptimizeStaticSimplificationOptions | false; - useCandidateFirst?: boolean; - skipInteriorCull?: boolean; -} - -interface StaticSimplificationPlan { - source: Polygon[]; - vertexKeyMode?: "relaxed" | "source"; - precomputed?: Polygon[] | null; - skipInteriorCull?: boolean; -} - -type IndexFilter = number[] | null; - -const DEFAULT_NORMALIZE_OPTIONS: ResolvedGeometryNormalizeOptions = { - maxAngleDeg: NORMALIZE_MAX_ANGLE_DEG, - maxPlaneDisplacement: NORMALIZE_MAX_PLANE_DISPLACEMENT, - maxBoundaryDisplacement: NORMALIZE_MAX_BOUNDARY_DISPLACEMENT, - isolatedPairs: false, -}; - const DEFAULT_LOSSY_APPROXIMATE_OPTIONS: Required = { maxAngleDeg: 15, maxPlaneDisplacement: 0.35, @@ -263,18 +66,8 @@ const AGGRESSIVE_LOSSY_APPROXIMATE_VARIANTS: ReadonlyArray= this.bestCost) return false; - this.commit(candidate, cost); - return true; - } - - private acceptDomCandidate( - candidate: Polygon[], - cost = polygonRenderCost(candidate), - maxPolygonCount?: number, - ): boolean { - if (candidate.length >= this.best.length) return false; - if (!this.withinMaxPolygonCount(candidate, maxPolygonCount)) return false; - this.commit(candidate, cost); - return true; - } - - private acceptSeamSafeCandidate( - candidate: Polygon[], - sourcePolygonCount: number, - cost?: number, - maxPolygonCount?: number, - ): boolean { - if (candidate.length >= this.best.length) return false; - if (!this.withinMaxPolygonCount(candidate, maxPolygonCount)) return false; - const minGain = aggressiveLossyMinRenderCostGain(sourcePolygonCount); - if (this.bestCost - candidate.length < minGain) return false; - const candidateCost = cost ?? polygonRenderCost(candidate); - const gain = this.bestCost - candidateCost; - if (gain <= 0) return false; - if (gain < minGain) return false; - const candidateSeam = trySeamOverlapSafetyDiagnostics(candidate); - if (!candidateSeam) return false; - const baselineSeam = this.bestSeamDiagnostics(); - if (!baselineSeam) return false; - if (seamDiagnosticsWorse(candidateSeam, baselineSeam)) return false; - if (topologyGapDiagnosticsWorse( - this.bestTopologyEdges(), - this.bestTopologySelfDiagnostics(), - candidate, - )) return false; - this.commit(candidate, candidateCost, candidateSeam); - return true; - } - - private withinMaxPolygonCount(candidate: Polygon[], maxPolygonCount?: number): boolean { - const limit = maxPolygonCount ?? this.requiredMaxPolygonCount; - return limit === undefined || candidate.length <= limit; - } - - private commit(candidate: Polygon[], cost: number, seam?: SeamOverlapDiagnostics): void { - this.best = candidate; - this.bestCost = cost; - this.bestDiagnostics = { polygons: candidate, seam }; - } - - private resetBestDiagnostics(seam?: SeamOverlapDiagnostics): void { - this.bestDiagnostics = { polygons: this.best, seam }; - } - - private bestSeamDiagnostics(): SeamOverlapDiagnostics | null { - if (this.bestDiagnostics.polygons !== this.best) this.resetBestDiagnostics(); - if (!this.bestDiagnostics.seam) { - const seam = trySeamOverlapSafetyDiagnostics(this.best); - if (!seam) return null; - this.bestDiagnostics.seam = seam; - } - return this.bestDiagnostics.seam; - } - - private bestTopologyEdges(): TopologyEdgeStats { - if (this.bestDiagnostics.polygons !== this.best) this.resetBestDiagnostics(); - if (!this.bestDiagnostics.topologyEdges) { - this.bestDiagnostics.topologyEdges = collectTopologyEdgeStats(this.best); - } - return this.bestDiagnostics.topologyEdges; - } - - private bestTopologySelfDiagnostics(): TopologyGapDiagnostics { - if (this.bestDiagnostics.polygons !== this.best) this.resetBestDiagnostics(); - if (!this.bestDiagnostics.topologySelf) { - this.bestDiagnostics.topologySelf = topologySelfDiagnostics(this.bestTopologyEdges(), TOPOLOGY_GAP_TOLERANCE); - } - return this.bestDiagnostics.topologySelf; - } -} - -function polygonRenderCost(polygons: Polygon[]): number { - let cost = 0; - for (const polygon of polygons) { - const vertexCount = polygon.vertices.length; - const irregularPenalty = vertexCount <= 4 ? 0 : Math.min(4, vertexCount - 4) * 0.12; - const texturePenalty = polygon.texture || polygon.material?.texture || polygon.textureTriangles?.length ? 0.15 : 0; - cost += 1 + irregularPenalty + texturePenalty; - } - return cost; -} - -function trySeamOverlapSafetyDiagnostics(polygons: Polygon[]): SeamOverlapDiagnostics | null { - try { - return seamOverlapSafetyDiagnostics(polygons); - } catch (error) { - if (error instanceof RangeError && error.message === "Set maximum size exceeded") return null; - throw error; - } -} - -function seamDiagnosticsWorse( - candidate: SeamOverlapDiagnostics, - baseline: SeamOverlapDiagnostics, -): boolean { - return candidate.nearPairs > baseline.nearPairs || - candidate.unclosedPairs > baseline.unclosedPairs || - candidate.maxMeasuredGapPx > baseline.maxMeasuredGapPx + 1e-9 || - candidate.maxResidualGapPx > baseline.maxResidualGapPx + 1e-9; -} - -function topologyGapDiagnosticsWorse( - referenceEdges: TopologyEdgeStats, - referenceDiagnostics: TopologyGapDiagnostics, - candidate: Polygon[], -): boolean { - const candidateEdges = collectTopologyEdgeStats(candidate); - if (topologyExposesReferenceInternalEdge(referenceEdges, candidateEdges, TOPOLOGY_GAP_TOLERANCE)) return true; - return boundaryTJunctionDiagnosticsWorse( - candidateEdges.boundarySegments, - TOPOLOGY_GAP_TOLERANCE, - referenceDiagnostics, - ); -} - -function topologyExposesReferenceInternalEdge( - referenceEdges: TopologyEdgeStats, - candidateEdges: TopologyEdgeStats, - tolerance: number, -): boolean { - if (referenceEdges.internalSegments.length === 0) return false; - const internalIndex = topologyInternalSegmentIndex(referenceEdges, tolerance); - - for (const segment of candidateEdges.boundarySegments) { - if (referenceEdges.boundaryKeys.has(segment.key)) continue; - if (referenceEdges.internalKeys.has(segment.key)) return true; - if (hasOverlappingSegment(segment, internalIndex, tolerance)) return true; - } - - return false; -} - -function topologyInternalSegmentIndex( - edges: TopologyEdgeStats, - tolerance: number, -): TopologySegmentIndex { - if (!edges.internalIndex || edges.internalIndexTolerance !== tolerance) { - edges.internalIndex = buildTopologySegmentIndex(edges.internalSegments, tolerance); - edges.internalIndexTolerance = tolerance; - } - return edges.internalIndex; -} - -function boundaryTJunctionDiagnosticsWorse( - boundarySegments: TopologySegment[], - tolerance: number, - referenceDiagnostics: TopologyGapDiagnostics, -): boolean { - const boundaryIndex = buildTopologySegmentIndex(boundarySegments, tolerance); - const seenPairs = new Set(); - let pairStride = 0; - let tJunctionPairs = 0; - let tJunctionLength = 0; - for (const segment of boundarySegments) pairStride = Math.max(pairStride, segment.index + 1); - for (const segment of boundarySegments) { - for (const other of overlappingSegmentCandidates(segment, boundaryIndex, tolerance)) { - if (other === segment || other.polygon === segment.polygon || other.key === segment.key) continue; - const pairKey = segment.index < other.index - ? segment.index * pairStride + other.index - : other.index * pairStride + segment.index; - if (seenPairs.has(pairKey)) continue; - seenPairs.add(pairKey); - const overlap = segmentOverlap(segment, other, tolerance); - if (!overlap) continue; - tJunctionPairs += 1; - tJunctionLength += overlap.overlapLength; - if ( - tJunctionPairs > referenceDiagnostics.tJunctionPairs || - tJunctionLength > referenceDiagnostics.tJunctionLength + 1e-9 - ) return true; - } - } - return false; -} - -function topologySelfDiagnostics(edges: TopologyEdgeStats, tolerance: number): TopologyGapDiagnostics { - const diagnostics: TopologyGapDiagnostics = { - tJunctionPairs: 0, - tJunctionLength: 0, - }; - addBoundaryTJunctionDiagnostics(diagnostics, edges.boundarySegments, tolerance); - return diagnostics; -} - -function addBoundaryTJunctionDiagnostics( - diagnostics: TopologyGapDiagnostics, - boundarySegments: TopologySegment[], - tolerance: number, -): void { - const boundaryIndex = buildTopologySegmentIndex(boundarySegments, tolerance); - const seenPairs = new Set(); - let pairStride = 0; - for (const segment of boundarySegments) pairStride = Math.max(pairStride, segment.index + 1); - for (const segment of boundarySegments) { - for (const other of overlappingSegmentCandidates(segment, boundaryIndex, tolerance)) { - if (other === segment || other.polygon === segment.polygon || other.key === segment.key) continue; - const pairKey = segment.index < other.index - ? segment.index * pairStride + other.index - : other.index * pairStride + segment.index; - if (seenPairs.has(pairKey)) continue; - seenPairs.add(pairKey); - const overlap = segmentOverlap(segment, other, tolerance); - if (!overlap) continue; - diagnostics.tJunctionPairs += 1; - diagnostics.tJunctionLength += overlap.overlapLength; - } - } -} - -function collectTopologyEdgeStats(polygons: Polygon[]): TopologyEdgeStats { - const edges = new Map(); - for (let polygonIndex = 0; polygonIndex < polygons.length; polygonIndex += 1) { - const vertices = polygons[polygonIndex].vertices; - for (let edgeIndex = 0; edgeIndex < vertices.length; edgeIndex += 1) { - const a = vertices[edgeIndex]; - const b = vertices[(edgeIndex + 1) % vertices.length]; - const segment = topologySegment(edgeKey(a, b), polygonIndex, edgeIndex, a, b); - if (!segment) continue; - const current = edges.get(segment.key); - if (current) current.count += 1; - else edges.set(segment.key, { count: 1, segment }); - } - } - - const boundaryKeys = new Set(); - const internalKeys = new Set(); - const boundarySegments: TopologySegment[] = []; - const internalSegments: TopologySegment[] = []; - let boundaryLength = 0; - let index = 0; - for (const edge of edges.values()) { - const segment = { ...edge.segment, index }; - index += 1; - if (edge.count === 1) { - boundaryKeys.add(segment.key); - boundarySegments.push(segment); - boundaryLength += segment.length; - } else { - internalKeys.add(segment.key); - internalSegments.push(segment); - } - } - return { boundaryKeys, internalKeys, boundarySegments, internalSegments, boundaryLength }; -} - -function topologySegment( - key: string, - polygon: number, - edge: number, - a: Vec3, - b: Vec3, -): TopologySegment | null { - const delta = subVec(b, a); - const length = Math.hypot(delta[0], delta[1], delta[2]); - if (length <= 1e-10) return null; - const dir: Vec3 = [delta[0] / length, delta[1] / length, delta[2] / length]; - return { - index: -1, - key, - polygon, - edge, - a, - b, - dir, - length, - minX: Math.min(a[0], b[0]), - minY: Math.min(a[1], b[1]), - minZ: Math.min(a[2], b[2]), - maxX: Math.max(a[0], b[0]), - maxY: Math.max(a[1], b[1]), - maxZ: Math.max(a[2], b[2]), - }; -} - -function buildTopologySegmentIndex(segments: TopologySegment[], tolerance: number): TopologySegmentIndex { - const cellSize = Math.max(tolerance * 8, 0.5); - const cells = new Map(); - for (const segment of segments) { - addTopologySegmentToCells(cells, segment, cellSize, tolerance); - } - return { cellSize, cells }; -} - -function addTopologySegmentToCells( - cells: Map, - segment: TopologySegment, - cellSize: number, - padding: number, -) { - const [minX, minY, minZ] = topologyCellCoords( - [segment.minX - padding, segment.minY - padding, segment.minZ - padding], - cellSize, - ); - const [maxX, maxY, maxZ] = topologyCellCoords( - [segment.maxX + padding, segment.maxY + padding, segment.maxZ + padding], - cellSize, - ); - for (let x = minX; x <= maxX; x += 1) { - for (let y = minY; y <= maxY; y += 1) { - for (let z = minZ; z <= maxZ; z += 1) { - const key = `${x},${y},${z}`; - const bucket = cells.get(key); - if (bucket) bucket.push(segment); - else cells.set(key, [segment]); - } - } - } -} - -function topologyCellCoords(point: Vec3, cellSize: number): [number, number, number] { - return [ - Math.floor(point[0] / cellSize), - Math.floor(point[1] / cellSize), - Math.floor(point[2] / cellSize), - ]; -} - -function overlappingSegmentCandidates( - segment: TopologySegment, - index: ReturnType, - tolerance: number, -): TopologySegment[] { - const out: TopologySegment[] = []; - const seen = new Set(); - const [minX, minY, minZ] = topologyCellCoords( - [segment.minX - tolerance, segment.minY - tolerance, segment.minZ - tolerance], - index.cellSize, - ); - const [maxX, maxY, maxZ] = topologyCellCoords( - [segment.maxX + tolerance, segment.maxY + tolerance, segment.maxZ + tolerance], - index.cellSize, - ); - for (let x = minX; x <= maxX; x += 1) { - for (let y = minY; y <= maxY; y += 1) { - for (let z = minZ; z <= maxZ; z += 1) { - const bucket = index.cells.get(`${x},${y},${z}`); - if (!bucket) continue; - for (const candidate of bucket) { - if (seen.has(candidate)) continue; - seen.add(candidate); - out.push(candidate); - } - } - } - } - return out; -} - -function hasOverlappingSegment( - segment: TopologySegment, - index: ReturnType, - tolerance: number, -): boolean { - for (const candidate of overlappingSegmentCandidates(segment, index, tolerance)) { - const overlap = segmentOverlap(segment, candidate, tolerance); - if (overlap) return true; - } - return false; -} - -function segmentOverlap( - a: TopologySegment, - b: TopologySegment, - tolerance: number, -): SegmentOverlapInfo | null { - if (!topologySegmentBoundsOverlap(a, b, tolerance)) return null; - if (Math.abs(dotVec(a.dir, b.dir)) < TOPOLOGY_MIN_PARALLEL_DOT) return null; - - const bStart = dotVec(subVec(b.a, a.a), a.dir); - const bEnd = dotVec(subVec(b.b, a.a), a.dir); - const overlapStart = Math.max(0, Math.min(bStart, bEnd)); - const overlapEnd = Math.min(a.length, Math.max(bStart, bEnd)); - const overlapLength = overlapEnd - overlapStart; - if (overlapLength <= Math.max(TOPOLOGY_MIN_OVERLAP, Math.min(a.length, b.length) * 1e-4)) { - return null; - } - - const mid = [ - a.a[0] + a.dir[0] * ((overlapStart + overlapEnd) / 2), - a.a[1] + a.dir[1] * ((overlapStart + overlapEnd) / 2), - a.a[2] + a.dir[2] * ((overlapStart + overlapEnd) / 2), - ] as Vec3; - const projected = Math.max(0, Math.min(b.length, dotVec(subVec(mid, b.a), b.dir))); - const closest: Vec3 = [ - b.a[0] + b.dir[0] * projected, - b.a[1] + b.dir[1] * projected, - b.a[2] + b.dir[2] * projected, - ]; - const offset = distanceVec(mid, closest); - return offset <= tolerance ? { overlapLength, offset } : null; -} - -function aggressiveLossyMinRenderCostGain(sourcePolygonCount: number): number { - return Math.max( - AGGRESSIVE_LOSSY_MIN_RENDER_COST_GAIN, - sourcePolygonCount * AGGRESSIVE_LOSSY_MIN_SOURCE_GAIN_RATIO, - ); -} - -function staticSimplificationEarlyStopTarget( - count: number, - options: OptimizeStaticSimplificationOptions, -): number { - const ratio = Number.isFinite(options.earlyStopDropRatio) - ? Math.max(0, options.earlyStopDropRatio!) - : DEFAULT_STATIC_SIMPLIFY_EARLY_STOP_DROP_RATIO; - return Math.max(0, count - Math.max(1, Math.ceil(count * ratio))); -} - -function hasSourceVertexKeys(polygons: Polygon[]): boolean { - return polygons.some((polygon) => polygon.simplifySourceVertexKeys?.length === polygon.vertices.length); -} - -function shouldTryStaticSimplification(polygons: Polygon[], baselineOptimized: Polygon[]): boolean { - return polygons.length === 0 || - baselineOptimized.length / polygons.length > MIN_STATIC_SIMPLIFY_BASELINE_SOURCE_RATIO; -} - -function simplifyTriangleMeshCandidate( - source: Polygon[], - options: OptimizeStaticSimplificationOptions, - vertexKeyMode?: "relaxed" | "source", -): Polygon[] | null { - const candidate = simplifyTriangleMeshPolygons(source, { - ...options.simplifyTriangleMeshOptions, - ...(vertexKeyMode ? { vertexKeyMode } : {}), - }); - if (candidate === source || candidate.length >= source.length) return null; - return candidate; -} - -function resolveStaticSimplificationPlan( - plan: StaticSimplificationPlan, - options: OptimizeStaticSimplificationOptions, -): Polygon[] | null { - if (plan.precomputed !== undefined) return plan.precomputed; - return simplifyTriangleMeshCandidate(plan.source, options, plan.vertexKeyMode); -} - -function applyRectCoverCandidate( - polygons: Polygon[], - setting: OptimizeMeshPolygonsOptions["rectCover"], -): Polygon[] { - if (setting === false) return polygons; - const options = resolveRectCoverOptions(polygons, setting); - if (!options) return polygons; - const covered = coverPlanarPolygons(polygons, options); - return covered.length < polygons.length ? covered : polygons; -} - -function resolveRectCoverOptions( - polygons: Polygon[], - setting: OptimizeMeshPolygonsOptions["rectCover"], -): CoverPlanarPolygonsOptions | null { - if (setting && setting !== true) return setting; - - const explicit = setting === true; - const polygonCount = polygons.length; - if (polygonCount > 2200) return null; - if ( - !explicit && - polygonCount >= DEFAULT_RECT_COVER_SMALL_AUTOMATIC_SKIP_MIN_POLYGONS && - polygonCount < DEFAULT_RECT_COVER_SMALL_AUTOMATIC_SKIP_MAX_POLYGONS - ) return null; - if (!explicit && polygonCount > DEFAULT_RECT_COVER_MAX_AUTOMATIC_POLYGONS) return null; - if (!explicit && polygonCount <= 300) { - return { - ...DEFAULT_RECT_COVER_OPTIONS, - maxCandidateAxes: 1, - }; - } - if (polygonCount > 300) { - if (!explicit) { - if (maxPolygonVertexCount(polygons) > 12) return null; - if (polygonBoundaryEdgeCount(polygons) > DEFAULT_RECT_COVER_MAX_BOUNDARY_EDGES) return null; - } - return { - ...DEFAULT_RECT_COVER_OPTIONS, - maxCandidateAxes: Math.min(DEFAULT_RECT_COVER_OPTIONS.maxCandidateAxes ?? 24, 2), - }; - } - return DEFAULT_RECT_COVER_OPTIONS; -} - -function automaticLossyRectCoverOptions(polygons: Polygon[]): CoverPlanarPolygonsOptions | false { - if (polygons.length > AUTOMATIC_RECT_COVER_MAX_POLYGONS) return false; - if (polygons.length === 0) return false; - if (polygonTriangleCount(polygons) / polygons.length < AUTOMATIC_RECT_COVER_MIN_TRIANGLE_RATIO) { - return false; - } - return AUTOMATIC_LOSSY_RECT_COVER_OPTIONS; -} - -function automaticLargeLossyRectCoverCandidate(polygons: Polygon[]): CoverPlanarPolygonsOptions | false { - if (polygons.length < LARGE_LOSSY_RECT_COVER_MIN_POLYGONS) return false; - if (polygons.length > LARGE_LOSSY_RECT_COVER_MAX_POLYGONS) return false; - if (maxPolygonVertexCount(polygons) <= 12) return false; - if (polygonBoundaryEdgeCount(polygons) > LARGE_LOSSY_RECT_COVER_MAX_BOUNDARY_EDGES) return false; - return LARGE_LOSSY_RECT_COVER_OPTIONS; -} - -function automaticWideLossyVariantCandidate(polygons: Polygon[]): boolean { - return polygons.length <= WIDE_LOSSY_VARIANT_MAX_SOURCE_POLYGONS; -} - -function polygonTriangleCount(polygons: Polygon[]): number { - let triangles = 0; - for (const polygon of polygons) { - if (polygon.vertices.length === 3) triangles += 1; - } - return triangles; -} - -function maxPolygonVertexCount(polygons: Polygon[]): number { - let max = 0; - for (const polygon of polygons) { - max = Math.max(max, polygon.vertices.length); - } - return max; -} - -function polygonBoundaryEdgeCount(polygons: Polygon[]): number { - const edges = new Map(); - for (const polygon of polygons) { - for (let i = 0; i < polygon.vertices.length; i++) { - const a = polygon.vertices[i]; - const b = polygon.vertices[(i + 1) % polygon.vertices.length]; - const key = edgeKey(a, b); - edges.set(key, (edges.get(key) ?? 0) + 1); - } - } - let boundary = 0; - for (const count of edges.values()) { - if (count === 1) boundary += 1; - } - return boundary; -} - -function applyIndexFilter(polygons: Polygon[], filter: IndexFilter | undefined): Polygon[] { - if (filter === undefined || filter === null) return polygons; - return filter.map((index) => polygons[index]).filter((polygon): polygon is Polygon => !!polygon); -} - -function keptIndexFilter(input: Polygon[], kept: Polygon[]): IndexFilter { - if (kept === input) return null; - if (kept.length === input.length && kept.every((polygon, index) => polygon === input[index])) { - return null; - } - const keptSet = new Set(kept); - const indices: number[] = []; - for (let i = 0; i < input.length; i++) { - if (keptSet.has(input[i])) indices.push(i); - } - return indices.length === input.length ? null : indices; -} - -function dedupedPolygonsForMerge(polygons: Polygon[], cache?: PreprocessCache): Polygon[] { - if (cache?.deduped) return cache.deduped; - let filter = cache?.dedupedIndices; - if (filter === undefined) { - const dropped = findOverlappingPolygonDuplicates(polygons); - if (dropped.size === 0) { - filter = null; - } else { - filter = []; - for (let i = 0; i < polygons.length; i++) { - if (!dropped.has(i)) filter.push(i); - } - } - if (cache) cache.dedupedIndices = filter; - } - const deduped = applyIndexFilter(polygons, filter); - if (cache) cache.deduped = deduped; - return deduped; -} - -function interiorPolygonsForMerge(polygons: Polygon[], cache?: PreprocessCache): Polygon[] { - if (cache?.skipInteriorCull) return polygons; - if (cache?.interior) return cache.interior; - let filter = cache?.interiorIndices; - if (filter === undefined) { - const kept = cullInteriorPolygons(polygons); - filter = keptIndexFilter(polygons, kept); - if (cache) cache.interiorIndices = filter; - } - const interior = applyIndexFilter(polygons, filter); - if (cache) cache.interior = interior; - return interior; -} - -function preprocessModelPolygons( - polygons: Polygon[], - normalizeGeometry: boolean | LossyApproximateOptions, - cache?: PreprocessCache, -): Polygon[] { - // Dedup runs FIRST — catches inner/outer shell duplicates and coincident - // doubled-up faces that importers emit as artifacts. Doing it before - // cull + merge means everything downstream operates on the leaner set - // and gets a free speedup as a bonus. Light-independent, runs once. - const deduped = dedupedPolygonsForMerge(polygons, cache); - const interior = interiorPolygonsForMerge(deduped, cache); - const baseline = cache?.baseline ?? mergePolygons(interior); - if (cache && !cache.baseline) cache.baseline = baseline; - if (!normalizeGeometry) return baseline; - - const options = normalizeGeometry === true - ? DEFAULT_NORMALIZE_OPTIONS - : resolveNormalizeOptions(normalizeGeometry); - if (options.isolatedPairs) { - const paired = mergeIsolatedTrianglePairs(snappedInteriorPolygonsForMerge(deduped, cache), options, cache); - let mergedPaired = mergePolygons(paired); - if ( - cache?.snappedInteriorUsesBaselineFilter && - shouldRecheckSnappedInteriorCull(baseline, mergedPaired) - ) { - const exactPaired = mergeIsolatedTrianglePairs( - snappedInteriorPolygonsForMerge(deduped, cache, true), - options, - cache, - ); - const exactMergedPaired = mergePolygons(exactPaired); - if (exactMergedPaired.length < mergedPaired.length) mergedPaired = exactMergedPaired; - } - return mergedPaired.length < baseline.length ? mergedPaired : baseline; - } - const normalizedGeometry = normalizeGeometryForMerge(deduped, options, cache); - const normalizedInterior = cullInteriorPolygons(normalizedGeometry); - const normalized = mergePolygons(normalizedInterior); - return normalized.length < baseline.length ? normalized : baseline; -} - -function snappedPolygonsForMerge(polygons: Polygon[], cache?: PreprocessCache): Polygon[] { - if (!cache) return snapGeometryForMerge(polygons); - if (!cache.snapped) cache.snapped = snapGeometryForMerge(polygons); - return cache.snapped; -} - -function snappedInteriorPolygonsForMerge( - polygons: Polygon[], - cache?: PreprocessCache, - exactCull = false, -): Polygon[] { - if (!cache) return cullInteriorPolygons(snapGeometryForMerge(polygons)); - if (exactCull && cache.snappedInteriorExact) return cache.snappedInteriorExact; - if (!exactCull && cache.snappedInterior) return cache.snappedInterior; - - const snapped = snappedPolygonsForMerge(polygons, cache); - if (exactCull) { - if (snapped === polygons && cache.deduped === polygons && cache.interior) { - cache.snappedInteriorExactIndices = cache.interiorIndices; - cache.snappedInteriorExact = cache.interior; - return cache.snappedInteriorExact; - } - const kept = cullInteriorPolygons(snapped); - cache.snappedInteriorExactIndices = keptIndexFilter(snapped, kept); - cache.snappedInteriorExact = kept; - return cache.snappedInteriorExact; - } - - if (!cache.snappedInterior) { - if (snapped === polygons && cache.deduped === polygons && cache.interior) { - cache.snappedInteriorIndices = cache.interiorIndices; - cache.snappedInterior = cache.interior; - cache.snappedInteriorUsesBaselineFilter = false; - return cache.snappedInterior; - } - if (cache.reuseSnappedInteriorCull !== false && cache.interiorIndices !== undefined) { - cache.snappedInteriorIndices = cache.interiorIndices; - cache.snappedInterior = applyIndexFilter(snapped, cache.snappedInteriorIndices); - cache.snappedInteriorUsesBaselineFilter = true; - return cache.snappedInterior; - } - if (cache.snappedInteriorIndices === undefined) { - const kept = cullInteriorPolygons(snapped); - cache.snappedInteriorIndices = keptIndexFilter(snapped, kept); - cache.snappedInterior = kept; - cache.snappedInteriorExactIndices = cache.snappedInteriorIndices; - cache.snappedInteriorExact = kept; - cache.snappedInteriorUsesBaselineFilter = false; - } else { - cache.snappedInterior = applyIndexFilter(snapped, cache.snappedInteriorIndices); - } - } - return cache.snappedInterior; -} - -function shouldRecheckSnappedInteriorCull(baseline: Polygon[], candidate: Polygon[]): boolean { - return candidate.length >= baseline.length; -} - -function resolveNormalizeOptions(options: LossyApproximateOptions): ResolvedGeometryNormalizeOptions { - return { - maxAngleDeg: options.maxAngleDeg ?? DEFAULT_NORMALIZE_OPTIONS.maxAngleDeg, - maxPlaneDisplacement: options.maxPlaneDisplacement ?? DEFAULT_NORMALIZE_OPTIONS.maxPlaneDisplacement, - maxBoundaryDisplacement: options.maxBoundaryDisplacement ?? DEFAULT_NORMALIZE_OPTIONS.maxBoundaryDisplacement, - isolatedPairs: options.isolatedPairs ?? DEFAULT_NORMALIZE_OPTIONS.isolatedPairs, - }; -} - -function mergeIsolatedTrianglePairs( - polygons: Polygon[], - options: ResolvedGeometryNormalizeOptions, - cache?: PreprocessCache, -): Polygon[] { - const source = trianglePairSourceFor(polygons, cache); - - const candidates: PairCandidate[] = []; - for (const prepared of preparedPairCandidatesFor(polygons, source)) { - if (preparedPairCandidateMatchesOptions(prepared, options)) { - candidates.push(prepared.candidate); - } - } - const selected = choosePairCandidates(candidates); - if (selected.length === 0) return polygons; - - return buildIsolatedTrianglePairOutput(polygons, selected); -} - -function trianglePairSourceFor( - polygons: Polygon[], - cache?: PreprocessCache, -): TrianglePairSourceCache { - if (cache?.trianglePairSource?.polygons === polygons) return cache.trianglePairSource; - - const metas = polygons.map((polygon): PlaneNormalizeMeta | null => { - const plane = planeOfPolygon(polygon); - if (!plane) return null; - return { - polygon, - normal: plane.normal, - area: plane.area, - materialKey: materialKeyForPolygon(polygon), - }; - }); - const edgeOwners = new Map(); - for (let i = 0; i < polygons.length; i++) { - const polygon = polygons[i]; - if (polygon.vertices.length !== 3 || !metas[i]) continue; - for (let j = 0; j < polygon.vertices.length; j++) { - const key = edgeKey(polygon.vertices[j], polygon.vertices[(j + 1) % polygon.vertices.length]); - const owners = edgeOwners.get(key); - if (owners) owners.push(i); - else edgeOwners.set(key, [i]); - } - } - - const edgeOwnerPairs: Array<[number, number]> = []; - for (const owners of edgeOwners.values()) { - if (owners.length === 2) edgeOwnerPairs.push([owners[0], owners[1]]); - } - - const source = { polygons, metas, edgeOwnerPairs }; - if (cache) cache.trianglePairSource = source; - return source; -} - -function preparedPairCandidatesFor( - polygons: Polygon[], - source: TrianglePairSourceCache, -): PreparedPairCandidate[] { - if (source.preparedCandidates) return source.preparedCandidates; - const prepared: PreparedPairCandidate[] = []; - for (const [a, b] of source.edgeOwnerPairs) { - const candidate = prepareTrianglePairCandidate(a, b, polygons, source.metas); - if (candidate) prepared.push(candidate); - } - source.preparedCandidates = prepared; - return prepared; -} - -function preparedPairCandidateMatchesOptions( - prepared: PreparedPairCandidate, - options: ResolvedGeometryNormalizeOptions, -): boolean { - const minNormalDot = Math.cos((options.maxAngleDeg * Math.PI) / 180); - return prepared.normalDot >= minNormalDot && - prepared.maxDistance <= Math.min(options.maxPlaneDisplacement, options.maxBoundaryDisplacement); -} - -function buildIsolatedTrianglePairOutput( - polygons: Polygon[], - selected: PairCandidate[], -): Polygon[] { - const replacements = new Map(); - const skipped = new Set(); - const vertexMoves = averagedVertexPositionMoves(selected.flatMap((candidate) => candidate.vertexMoves)); - for (const candidate of selected) { - const outputIndex = Math.min(candidate.a, candidate.b); - replacements.set(outputIndex, candidate.polygon); - skipped.add(Math.max(candidate.a, candidate.b)); - } - - const output: Polygon[] = []; - for (let i = 0; i < polygons.length; i++) { - const replacement = replacements.get(i); - if (replacement) { - output.push(replacement); - continue; - } - if (skipped.has(i)) continue; - output.push(polygons[i]); - } - return vertexMoves.size > 0 ? applyVertexPositionMoves(output, vertexMoves) : output; -} - -function choosePairCandidates(candidates: PairCandidate[]): PairCandidate[] { - if (candidates.length > 3000) return choosePairCandidatesStatic(candidates); - return choosePairCandidatesDynamic(candidates); -} - -function choosePairCandidatesStatic(candidates: PairCandidate[]): PairCandidate[] { - const pairDegrees = new Map(); - for (const candidate of candidates) { - pairDegrees.set(candidate.a, (pairDegrees.get(candidate.a) ?? 0) + 1); - pairDegrees.set(candidate.b, (pairDegrees.get(candidate.b) ?? 0) + 1); - } - - const sorted = [...candidates].sort((a, b) => { - const degreeA = (pairDegrees.get(a.a) ?? 0) + (pairDegrees.get(a.b) ?? 0); - const degreeB = (pairDegrees.get(b.a) ?? 0) + (pairDegrees.get(b.b) ?? 0); - return degreeA - degreeB || a.score - b.score; - }); - - const used = new Set(); - const selected: PairCandidate[] = []; - for (const candidate of sorted) { - if (used.has(candidate.a) || used.has(candidate.b)) continue; - used.add(candidate.a); - used.add(candidate.b); - selected.push(candidate); - } - return selected; -} - -function choosePairCandidatesDynamic(candidates: PairCandidate[]): PairCandidate[] { - const incident = new Map(); - for (let i = 0; i < candidates.length; i++) { - const candidate = candidates[i]; - const aIncident = incident.get(candidate.a); - if (aIncident) aIncident.push(i); - else incident.set(candidate.a, [i]); - const bIncident = incident.get(candidate.b); - if (bIncident) bIncident.push(i); - else incident.set(candidate.b, [i]); - } - - const selected: PairCandidate[] = []; - const live = new Array(candidates.length).fill(true); - const liveIncidentCount = new Map(); - const heap = new PairCandidateRankHeap(); - - for (const [polygon, list] of incident) liveIncidentCount.set(polygon, list.length); - const liveDegree = (candidate: PairCandidate): number => - (liveIncidentCount.get(candidate.a) ?? 0) + (liveIncidentCount.get(candidate.b) ?? 0); - const pushRank = (index: number): void => { - const candidate = candidates[index]; - heap.push({ - degree: liveDegree(candidate), - score: candidate.score, - index, - }); - }; - const invalidate = (index: number, changedPolygons: Set): void => { - if (!live[index]) return; - live[index] = false; - const candidate = candidates[index]; - for (const polygon of [candidate.a, candidate.b]) { - liveIncidentCount.set(polygon, (liveIncidentCount.get(polygon) ?? 0) - 1); - changedPolygons.add(polygon); - } - }; - - for (let i = 0; i < candidates.length; i++) pushRank(i); - - while (heap.size() > 0) { - const rank = heap.pop()!; - if (!live[rank.index]) continue; - - const candidate = candidates[rank.index]; - const degree = liveDegree(candidate); - if (degree !== rank.degree) { - pushRank(rank.index); - continue; - } - - selected.push(candidate); - - const changedPolygons = new Set(); - for (const polygon of [candidate.a, candidate.b]) { - for (const index of incident.get(polygon) ?? []) { - invalidate(index, changedPolygons); - } - } - - for (const polygon of changedPolygons) { - for (const index of incident.get(polygon) ?? []) { - if (live[index]) pushRank(index); - } - } - } - return selected; -} - -class PairCandidateRankHeap { - private items: PairCandidateRank[] = []; - - size(): number { - return this.items.length; - } - - push(item: PairCandidateRank): void { - this.items.push(item); - let index = this.items.length - 1; - while (index > 0) { - const parent = (index - 1) >> 1; - if (comparePairCandidateRanks(this.items[parent], this.items[index]) <= 0) break; - [this.items[parent], this.items[index]] = [this.items[index], this.items[parent]]; - index = parent; - } - } - - pop(): PairCandidateRank | null { - if (this.items.length === 0) return null; - const top = this.items[0]; - const last = this.items.pop()!; - if (this.items.length > 0) { - this.items[0] = last; - let index = 0; - for (;;) { - const left = index * 2 + 1; - const right = left + 1; - let best = index; - if (left < this.items.length && comparePairCandidateRanks(this.items[left], this.items[best]) < 0) best = left; - if (right < this.items.length && comparePairCandidateRanks(this.items[right], this.items[best]) < 0) best = right; - if (best === index) break; - [this.items[index], this.items[best]] = [this.items[best], this.items[index]]; - index = best; - } - } - return top; - } -} - -function comparePairCandidateRanks(a: PairCandidateRank, b: PairCandidateRank): number { - return a.degree - b.degree || a.score - b.score || a.index - b.index; -} - -function averagedVertexPositionMoves(moves: VertexPositionMove[]): Map { - const totals = new Map(); - for (const move of moves) { - const total = totals.get(move.key); - if (total) { - total.x += move.target[0]; - total.y += move.target[1]; - total.z += move.target[2]; - total.count += 1; - } else { - totals.set(move.key, { - x: move.target[0], - y: move.target[1], - z: move.target[2], - count: 1, - }); - } - } - - const averaged = new Map(); - for (const [key, total] of totals) { - averaged.set(key, [ - total.x / total.count, - total.y / total.count, - total.z / total.count, - ]); - } - return averaged; -} - -function vertexPositionMovesForProjection(source: Polygon[], projected: Polygon[]): VertexPositionMove[] { - const moves: VertexPositionMove[] = []; - for (let i = 0; i < source.length; i++) { - const sourceVertices = source[i].vertices; - const projectedVertices = projected[i]?.vertices; - if (!projectedVertices || projectedVertices.length !== sourceVertices.length) continue; - for (let j = 0; j < sourceVertices.length; j++) { - moves.push({ - key: vertexKey(sourceVertices[j]), - target: projectedVertices[j], - }); - } - const sourceTriangles = source[i].textureTriangles ?? []; - const projectedTriangles = projected[i]?.textureTriangles ?? []; - for (let j = 0; j < sourceTriangles.length; j++) { - const projectedTriangle = projectedTriangles[j]; - if (!projectedTriangle) continue; - for (let k = 0; k < sourceTriangles[j].vertices.length; k++) { - moves.push({ - key: vertexKey(sourceTriangles[j].vertices[k]), - target: projectedTriangle.vertices[k], - }); - } - } - } - return moves; -} - -function textureTriangleVertexProjectionMoves(polygons: Polygon[], fit: PlaneFit): VertexPositionMove[] { - const moves: VertexPositionMove[] = []; - for (const polygon of polygons) { - for (const triangle of polygon.textureTriangles ?? []) { - for (const vertex of triangle.vertices) { - moves.push({ - key: vertexKey(vertex), - target: projectVecToPlane(vertex, fit), - }); - } - } - } - return moves; -} - -function applyVertexPositionMoves(polygons: Polygon[], moves: Map): Polygon[] { - return polygons.map((polygon) => { - let changed = false; - const moveVertex = (vertex: Vec3): Vec3 => { - const target = moves.get(vertexKey(vertex)); - if (!target) return vertex; - changed = true; - return target; - }; - const vertices = polygon.vertices.map(moveVertex); - const textureTriangles = mapTextureTriangleVertices(polygon.textureTriangles, moveVertex); - return changed ? { - ...polygon, - vertices, - ...(textureTriangles ? { textureTriangles } : {}), - } : polygon; - }); -} - -function prepareTrianglePairCandidate( - aIndex: number, - bIndex: number, - polygons: Polygon[], - metas: Array, -): PreparedPairCandidate | null { - const a = polygons[aIndex]; - const b = polygons[bIndex]; - const aMeta = metas[aIndex]; - const bMeta = metas[bIndex]; - if (!aMeta || !bMeta) return null; - if (a.vertices.length !== 3 || b.vertices.length !== 3) return null; - if (!canApproximatePairMerge(a, b, aMeta, bMeta)) return null; - - const shared = sharedEdgeIndices(a, b); - if (!shared) return null; - const [ai0, ai1, bi0, bi1] = shared; - const bGoesSameDirection = (bi0 + 1) % b.vertices.length === bi1; - if (bGoesSameDirection) return null; - - const normalDot = Math.abs(dotVec(aMeta.normal, bMeta.normal)); - const minNormalDot = Math.cos((PREPARED_PAIR_MAX_ANGLE_DEG * Math.PI) / 180); - if (normalDot < minNormalDot) return null; - - const aThird = (ai1 + 1) % a.vertices.length; - const bThird = 3 - bi0 - bi1; - const ring = [ - a.vertices[ai1], - a.vertices[aThird], - a.vertices[ai0], - b.vertices[bThird], - ]; - const fit = fitPlaneForVertices(ring); - if (!fit) return null; - - let maxDistance = 0; - let squaredDistance = 0; - for (const vertex of ring) { - const distance = Math.abs(signedPlaneDistance(vertex, fit)); - maxDistance = Math.max(maxDistance, distance); - squaredDistance += distance * distance; - } - if (maxDistance > PREPARED_PAIR_MAX_BOUNDARY_DISPLACEMENT) return null; - - const projected = ring.map((vertex) => projectVecToPlane(vertex, fit)); - if (!isConvexPolygon(projected, fit.normal)) return null; - const projectedPlane = planeOfPolygon({ vertices: projected }); - if ( - !projectedPlane || - dotVec(projectedPlane.normal, aMeta.normal) < 0.2 || - dotVec(projectedPlane.normal, bMeta.normal) < 0.2 - ) { - return null; - } - const polygon: Polygon = { - vertices: ring, - color: a.color, - ...(a.doubleSided ? { doubleSided: true } : {}), - ...(a.data ? { data: { ...a.data } } : {}), - }; - if (canUseTexturedLossyMerge(a, b) && a.uvs && b.uvs && a.texture) { - polygon.texture = a.texture; - if (a.textureWrap) polygon.textureWrap = { ...a.textureWrap }; - if (a.textureAlphaMode) polygon.textureAlphaMode = a.textureAlphaMode; - polygon.uvs = [ - [...a.uvs[ai1]] as Vec2, - [...a.uvs[aThird]] as Vec2, - [...a.uvs[ai0]] as Vec2, - [...b.uvs[bThird]] as Vec2, - ]; - const textureTriangles = textureTrianglesForPolygons([a, b]); - if (textureTriangles?.length) polygon.textureTriangles = textureTriangles; - } - - return { - normalDot, - maxDistance, - candidate: { - a: aIndex, - b: bIndex, - polygon, - vertexMoves: [ - ...ring.map((vertex, index) => ({ - key: vertexKey(vertex), - target: projected[index], - })), - ...textureTriangleVertexProjectionMoves([a, b], fit), - ], - score: squaredDistance / ring.length + maxDistance * 0.25 + (1 - normalDot) * 0.1, - }, - }; -} - -function fitPlaneForVertices(vertices: Vec3[]): PlaneFit | null { - if (vertices.length < 3) return null; - let nx = 0; - let ny = 0; - let nz = 0; - let px = 0; - let py = 0; - let pz = 0; - for (let i = 0; i < vertices.length; i++) { - const current = vertices[i]; - const next = vertices[(i + 1) % vertices.length]; - nx += (current[1] - next[1]) * (current[2] + next[2]); - ny += (current[2] - next[2]) * (current[0] + next[0]); - nz += (current[0] - next[0]) * (current[1] + next[1]); - px += current[0]; - py += current[1]; - pz += current[2]; - } - const normal = normalizeVec([nx, ny, nz]); - if (!normal) return null; - return { - normal, - point: [px / vertices.length, py / vertices.length, pz / vertices.length], - }; -} - -function isConvexPolygon(vertices: Vec3[], normal: Vec3): boolean { - let sign = 0; - for (let i = 0; i < vertices.length; i++) { - const a = vertices[i]; - const b = vertices[(i + 1) % vertices.length]; - const c = vertices[(i + 2) % vertices.length]; - const turn = dotVec(crossVec(subVec(b, a), subVec(c, b)), normal); - if (Math.abs(turn) <= 1e-9) continue; - const nextSign = turn > 0 ? 1 : -1; - if (sign === 0) sign = nextSign; - else if (sign !== nextSign) return false; - } - return true; -} - -function normalizeGeometryForMerge( - polygons: Polygon[], - options: ResolvedGeometryNormalizeOptions, - cache?: PreprocessCache, -): Polygon[] { - const snapped = snappedPolygonsForMerge(polygons, cache); - const planeEpsilon = planeFitEpsilon(snapped, options); - if (planeEpsilon <= 0) return snapped; - - const metas = snapped.map((polygon): PlaneNormalizeMeta | null => { - const plane = planeOfPolygon(polygon); - if (!plane) return null; - return { - polygon, - normal: plane.normal, - area: plane.area, - materialKey: materialKeyForPolygon(polygon), - }; - }); - const adjacency = buildMergeAdjacency(snapped, metas); - const assigned = new Set(); - const output: Array = Array(snapped.length); - const vertexMoves: VertexPositionMove[] = []; - const writeOutput = (index: number, polygon: Polygon): void => { - output[index] = polygon; - }; - - for (let i = 0; i < snapped.length; i++) { - const meta = metas[i]; - if (assigned.has(i)) continue; - if (!meta) { - writeOutput(i, snapped[i]); - continue; - } - - const group = growPlaneGroup(i, metas, adjacency, assigned, planeEpsilon, options); - for (const index of group) assigned.add(index); - if (group.length < 2) { - writeOutput(i, snapped[i]); - continue; - } - - const replacements = choosePlaneGroupReplacements(group, snapped, metas, adjacency, planeEpsilon, options); - vertexMoves.push(...replacements.vertexMoves); - for (const index of group) { - writeOutput(index, replacements.polygons.get(index) ?? snapped[index]); - } - } - - const projected = output.flatMap((polygon) => polygon ? [polygon] : []); - const moved = vertexMoves.length > 0 - ? applyVertexPositionMoves(projected, averagedVertexPositionMoves(vertexMoves)) - : projected; - return snapGeometryForMerge(moved); -} - -function snapGeometryForMerge(polygons: Polygon[]): Polygon[] { - const geometryEpsilon = geometrySnapEpsilon(polygons); - const uvEpsilon = 1e-4; - if (geometryEpsilon <= 0) return polygons; - - const vertices = createVec3Snapper(geometryEpsilon); - const uvs = createVec2Snapper(uvEpsilon); - let anyChanged = false; - - const snapped = polygons.map((polygon) => { - let changed = false; - const snapVertex = (vertex: Vec3): Vec3 => { - const next = vertices.snap(vertex); - if (!eqVec(next, vertex)) changed = true; - return next; - }; - const snappedVertices = polygon.vertices.map(snapVertex); - const snappedUvs = polygon.uvs && polygon.uvs.length === polygon.vertices.length - ? polygon.uvs.map((uv) => { - const next = uvs.snap(uv); - if (!eqUv(next, uv)) changed = true; - return next; - }) - : undefined; - const snappedTextureTriangles = mapTextureTriangleVertices(polygon.textureTriangles, snapVertex); - if (!changed && !polygon.texture) return polygon; - const snappedPolygon: Polygon = { - ...polygon, - vertices: snappedVertices, - ...(snappedUvs ? { uvs: snappedUvs } : {}), - ...(snappedTextureTriangles ? { textureTriangles: snappedTextureTriangles } : {}), - }; - anyChanged = true; - return { - ...snappedPolygon, - ...(snappedPolygon.texture - ? { textureTriangles: textureTrianglesForPolygon(snappedPolygon) } - : {}), - }; - }); - return anyChanged ? snapped : polygons; -} - -function textureTrianglesForPolygon(polygon: Polygon): TextureTriangle[] | undefined { - if (!polygon.texture) return undefined; - if (polygon.textureTriangles?.length) return cloneTextureTriangles(polygon.textureTriangles); - if (polygon.uvs && polygon.uvs.length === polygon.vertices.length) { - return fanTextureTriangles(polygon.vertices, polygon.uvs); - } - return undefined; -} - -function textureTrianglesForPolygons(polygons: Polygon[]): TextureTriangle[] | undefined { - const triangles = polygons.flatMap((polygon) => textureTrianglesForPolygon(polygon) ?? []); - return triangles.length > 0 ? triangles : undefined; -} - -function mapTextureTriangleVertices( - triangles: TextureTriangle[] | undefined, - mapVertex: (vertex: Vec3) => Vec3, -): TextureTriangle[] | undefined { - if (!triangles?.length) return undefined; - return triangles.map((triangle) => ({ - vertices: triangle.vertices.map(mapVertex) as [Vec3, Vec3, Vec3], - uvs: triangle.uvs.map((uv) => [...uv] as Vec2) as [Vec2, Vec2, Vec2], - })); -} - -function choosePlaneGroupReplacements( - group: number[], - polygons: Polygon[], - metas: Array, - adjacency: Map>, - planeEpsilon: number, - options: ResolvedGeometryNormalizeOptions, -): PlaneGroupReplacements { - const fullGroup = projectedPlanePatchCandidate(group, polygons, metas, planeEpsilon, options); - if (fullGroup) return replacementsForPlanePatch(fullGroup); - return splitPlaneGroupIntoWinningPatches(group, polygons, metas, adjacency, planeEpsilon, options); -} - -function splitPlaneGroupIntoWinningPatches( - group: number[], - polygons: Polygon[], - metas: Array, - adjacency: Map>, - planeEpsilon: number, - options: ResolvedGeometryNormalizeOptions, -): PlaneGroupReplacements { - const groupSet = new Set(group); - const candidates: PlanePatchCandidate[] = []; - for (const a of group) { - for (const b of adjacency.get(a) ?? []) { - if (a >= b || !groupSet.has(b)) continue; - const candidate = projectedPlanePatchCandidate([a, b], polygons, metas, planeEpsilon, options); - if (candidate) candidates.push(candidate); - } - } - - candidates.sort((a, b) => b.score - a.score); - const used = new Set(); - const replacements = new Map(); - const vertexMoves: VertexPositionMove[] = []; - for (const candidate of candidates) { - if (candidate.indices.some((index) => used.has(index))) continue; - vertexMoves.push(...candidate.vertexMoves); - for (let i = 0; i < candidate.indices.length; i++) { - const index = candidate.indices[i]; - used.add(index); - replacements.set(index, polygons[index]); - } - } - return { polygons: replacements, vertexMoves }; -} - -function replacementsForPlanePatch(candidate: PlanePatchCandidate): PlaneGroupReplacements { - const replacements = new Map(); - for (let i = 0; i < candidate.indices.length; i++) { - replacements.set(candidate.indices[i], candidate.source[i]); - } - return { polygons: replacements, vertexMoves: candidate.vertexMoves }; -} - -function projectedPlanePatchCandidate( - group: number[], - polygons: Polygon[], - metas: Array, - planeEpsilon: number, - options: ResolvedGeometryNormalizeOptions, -): PlanePatchCandidate | null { - const fit = fitPlaneForGroup(group, metas); - if (!fit || !groupWithinPlaneBudget(group, metas, fit, planeEpsilon, options)) return null; - - const source = group.map((index) => polygons[index]); - const projected = source.map((polygon) => projectPolygonToPlane(polygon, fit)); - const sourceCost = polygonRenderCost(mergePolygons(source)); - const projectedCost = polygonRenderCost(mergePolygons(projected)); - if (projectedCost >= sourceCost) return null; - return { - indices: group, - source, - projected, - vertexMoves: vertexPositionMovesForProjection(source, projected), - score: sourceCost - projectedCost, - }; -} - -function planeFitEpsilon( - polygons: Polygon[], - options: ResolvedGeometryNormalizeOptions, -): number { - const geometryEpsilon = geometrySnapEpsilon(polygons); - if (geometryEpsilon <= 0) return 0; - return options.maxPlaneDisplacement; -} - -function geometrySnapEpsilon(polygons: Polygon[]): number { - let minX = Infinity; - let minY = Infinity; - let minZ = Infinity; - let maxX = -Infinity; - let maxY = -Infinity; - let maxZ = -Infinity; - - for (const polygon of polygons) { - for (const [x, y, z] of polygon.vertices) { - minX = Math.min(minX, x); - minY = Math.min(minY, y); - minZ = Math.min(minZ, z); - maxX = Math.max(maxX, x); - maxY = Math.max(maxY, y); - maxZ = Math.max(maxZ, z); - } - } - - if (!Number.isFinite(minX)) return 0; - const diagonal = Math.hypot(maxX - minX, maxY - minY, maxZ - minZ); - if (diagonal <= 0) return 0; - return Math.min(0.025, Math.max(0.0001, diagonal * 0.00025)); -} - -function createVec3Snapper(epsilon: number) { - const buckets = new Map(); - const cell = (value: number) => Math.floor(value / epsilon); - const key = (x: number, y: number, z: number) => `${x},${y},${z}`; - - return { - snap(input: Vec3): Vec3 { - const cx = cell(input[0]); - const cy = cell(input[1]); - const cz = cell(input[2]); - for (let dx = -1; dx <= 1; dx++) { - for (let dy = -1; dy <= 1; dy++) { - for (let dz = -1; dz <= 1; dz++) { - const bucket = buckets.get(key(cx + dx, cy + dy, cz + dz)); - if (!bucket) continue; - for (const candidate of bucket) { - if (distanceVec(input, candidate) <= epsilon) { - return [candidate[0], candidate[1], candidate[2]]; - } - } - } - } - } - - const snapped: Vec3 = [input[0], input[1], input[2]]; - const bucketKey = key(cx, cy, cz); - const bucket = buckets.get(bucketKey); - if (bucket) bucket.push(snapped); - else buckets.set(bucketKey, [snapped]); - return snapped; - }, - }; -} - -function createVec2Snapper(epsilon: number) { - const buckets = new Map(); - const cell = (value: number) => Math.floor(value / epsilon); - const key = (x: number, y: number) => `${x},${y}`; - - return { - snap(input: Vec2): Vec2 { - const cx = cell(input[0]); - const cy = cell(input[1]); - for (let dx = -1; dx <= 1; dx++) { - for (let dy = -1; dy <= 1; dy++) { - const bucket = buckets.get(key(cx + dx, cy + dy)); - if (!bucket) continue; - for (const candidate of bucket) { - if (Math.hypot(input[0] - candidate[0], input[1] - candidate[1]) <= epsilon) { - return [candidate[0], candidate[1]]; - } - } - } - } - - const snapped: Vec2 = [input[0], input[1]]; - const bucketKey = key(cx, cy); - const bucket = buckets.get(bucketKey); - if (bucket) bucket.push(snapped); - else buckets.set(bucketKey, [snapped]); - return snapped; - }, - }; -} - -function materialKeyForPolygon(polygon: Polygon): string { - return [ - polygon.color ?? "#cccccc", - polygon.texture ?? "", - polygon.texture && polygon.textureWrap ? `${polygon.textureWrap.s}/${polygon.textureWrap.t}` : "", - polygon.texture && polygon.textureAlphaMode ? polygon.textureAlphaMode : "", - polygon.uvs ? "uv" : "plain", - polygon.doubleSided === true ? "double-sided" : "single-sided", - ].join("|"); -} - -function planeOfPolygon(polygon: Polygon): { normal: Vec3; area: number } | null { - const vertices = polygon.vertices; - if (!vertices || vertices.length < 3) return null; - - let nx = 0; - let ny = 0; - let nz = 0; - const origin = vertices[0]; - for (let i = 1; i < vertices.length - 1; i++) { - const a = subVec(vertices[i], origin); - const b = subVec(vertices[i + 1], origin); - const cross = crossVec(a, b); - nx += cross[0]; - ny += cross[1]; - nz += cross[2]; - } - - const len = Math.hypot(nx, ny, nz); - if (len <= 1e-10) return null; - return { - normal: [nx / len, ny / len, nz / len], - area: len / 2, - }; -} - -function buildMergeAdjacency( - polygons: Polygon[], - metas: Array, -): Map> { - const edgeOwners = new Map(); - const adjacency = new Map>(); - - for (let i = 0; i < polygons.length; i++) { - const polygon = polygons[i]; - if (!metas[i] || polygon.vertices.length < 3) continue; - for (let j = 0; j < polygon.vertices.length; j++) { - const key = edgeKey(polygon.vertices[j], polygon.vertices[(j + 1) % polygon.vertices.length]); - const owners = edgeOwners.get(key); - if (owners) owners.push(i); - else edgeOwners.set(key, [i]); - } - } - - for (const owners of edgeOwners.values()) { - for (let a = 0; a < owners.length; a++) { - for (let b = a + 1; b < owners.length; b++) { - const ai = owners[a]; - const bi = owners[b]; - if (canShareMergePatch(polygons[ai], polygons[bi], metas[ai], metas[bi])) { - addAdjacency(adjacency, ai, bi); - addAdjacency(adjacency, bi, ai); - } - } - } - } - - return adjacency; -} - -function canShareMergePatch( - a: Polygon, - b: Polygon, - aMeta: PlaneNormalizeMeta | null, - bMeta: PlaneNormalizeMeta | null, -): boolean { - if (!aMeta || !bMeta) return false; - if (aMeta.materialKey !== bMeta.materialKey) return false; - if (!!a.uvs !== !!b.uvs) return false; - if (hasTextureMergeState(a) || hasTextureMergeState(b)) return canUseTexturedLossyMerge(a, b); - if (!a.uvs || !b.uvs) return true; - - const shared = sharedEdgeIndices(a, b); - if (!shared) return false; - const [ai0, ai1, bi0, bi1] = shared; - return eqUv(a.uvs[ai0], b.uvs[bi0]) && eqUv(a.uvs[ai1], b.uvs[bi1]); -} - -function canApproximatePairMerge( - a: Polygon, - b: Polygon, - aMeta: PlaneNormalizeMeta, - bMeta: PlaneNormalizeMeta, -): boolean { - if (aMeta.materialKey !== bMeta.materialKey) return false; - if (hasTextureMergeState(a) || hasTextureMergeState(b)) return canUseTexturedLossyMerge(a, b); - return !a.uvs && !b.uvs && !a.textureTriangles?.length && !b.textureTriangles?.length; -} - -function hasTextureMergeState(polygon: Polygon): boolean { - return Boolean(polygon.texture || polygon.material?.texture || polygon.textureTriangles?.length); -} - -function canUseTexturedLossyMerge(a: Polygon, b: Polygon): boolean { - if (!a.texture || !b.texture || a.texture !== b.texture) return false; - if ((a.textureWrap?.s ?? "") !== (b.textureWrap?.s ?? "")) return false; - if ((a.textureWrap?.t ?? "") !== (b.textureWrap?.t ?? "")) return false; - if ((a.textureAlphaMode ?? "") !== (b.textureAlphaMode ?? "")) return false; - if (a.material?.texture || b.material?.texture) return false; - if (!a.uvs || !b.uvs) return false; - if (a.uvs.length !== a.vertices.length || b.uvs.length !== b.vertices.length) return false; - - const shared = sharedEdgeIndices(a, b); - if (!shared) return false; - const [ai0, ai1, bi0, bi1] = shared; - return eqUv(a.uvs[ai0], b.uvs[bi0]) && eqUv(a.uvs[ai1], b.uvs[bi1]); -} - -function addAdjacency(adjacency: Map>, from: number, to: number): void { - const values = adjacency.get(from); - if (values) values.add(to); - else adjacency.set(from, new Set([to])); -} - -function growPlaneGroup( - seed: number, - metas: Array, - adjacency: Map>, - assigned: Set, - planeEpsilon: number, - options: ResolvedGeometryNormalizeOptions, -): number[] { - const group = [seed]; - const queued = new Set([seed]); - const queue = [seed]; - - while (queue.length > 0) { - const current = queue.shift()!; - for (const next of adjacency.get(current) ?? []) { - if (assigned.has(next) || queued.has(next)) continue; - const nextMeta = metas[next]; - const seedMeta = metas[seed]; - if (!nextMeta || !seedMeta) continue; - if (nextMeta.materialKey !== seedMeta.materialKey) continue; - if (!canJoinPlaneGroup([...group, next], metas, planeEpsilon, options)) continue; - group.push(next); - queued.add(next); - queue.push(next); - } - } - - return group; -} - -function canJoinPlaneGroup( - group: number[], - metas: Array, - planeEpsilon: number, - options: ResolvedGeometryNormalizeOptions, -): boolean { - const fit = fitPlaneForGroup(group, metas); - return !!fit && groupWithinPlaneBudget(group, metas, fit, planeEpsilon, options); -} - -function fitPlaneForGroup( - group: number[], - metas: Array, -): PlaneFit | null { - const seed = metas[group[0]]; - if (!seed) return null; - - let nx = 0; - let ny = 0; - let nz = 0; - let px = 0; - let py = 0; - let pz = 0; - let weightSum = 0; - - for (const index of group) { - const meta = metas[index]; - if (!meta) return null; - const direction = dotVec(seed.normal, meta.normal) < 0 ? -1 : 1; - const weight = Math.max(meta.area, 1e-6); - nx += meta.normal[0] * direction * weight; - ny += meta.normal[1] * direction * weight; - nz += meta.normal[2] * direction * weight; - for (const vertex of meta.polygon.vertices) { - px += vertex[0]; - py += vertex[1]; - pz += vertex[2]; - weightSum += 1; - } - } - - const normal = normalizeVec([nx, ny, nz]); - if (!normal || weightSum === 0) return null; - const boundaryVertices = groupBoundaryVertexKeys(group, metas); - const boundaryD = planeOffsetRangeForVertices(group, metas, normal, boundaryVertices); - if (boundaryD) { - const d = (boundaryD.min + boundaryD.max) / 2; - return { - normal, - point: [normal[0] * d, normal[1] * d, normal[2] * d], - boundaryVertexKeys: boundaryVertices, - }; - } - - return { - normal, - point: [px / weightSum, py / weightSum, pz / weightSum], - boundaryVertexKeys: boundaryVertices, - }; -} - -function planeOffsetRangeForVertices( - group: number[], - metas: Array, - normal: Vec3, - vertexKeys: Set, -): { min: number; max: number } | null { - let min = Infinity; - let max = -Infinity; - - for (const index of group) { - const meta = metas[index]; - if (!meta) continue; - for (const vertex of meta.polygon.vertices) { - if (!vertexKeys.has(vertexKey(vertex))) continue; - const d = dotVec(vertex, normal); - min = Math.min(min, d); - max = Math.max(max, d); - } - } - - return Number.isFinite(min) && Number.isFinite(max) ? { min, max } : null; -} - -function groupWithinPlaneBudget( - group: number[], - metas: Array, - fit: PlaneFit, - planeEpsilon: number, - options: ResolvedGeometryNormalizeOptions, -): boolean { - const normalDotMin = Math.cos((options.maxAngleDeg * Math.PI) / 180); - const boundaryVertices = fit.boundaryVertexKeys ?? groupBoundaryVertexKeys(group, metas); - for (const index of group) { - const meta = metas[index]; - if (!meta) return false; - if (Math.abs(dotVec(meta.normal, fit.normal)) < normalDotMin) return false; - for (const vertex of meta.polygon.vertices) { - const limit = boundaryVertices.has(vertexKey(vertex)) - ? options.maxBoundaryDisplacement - : planeEpsilon; - if (Math.abs(signedPlaneDistance(vertex, fit)) > limit) return false; - } - } - return true; -} - -function groupBoundaryVertexKeys( - group: number[], - metas: Array, -): Set { - const edgeCounts = new Map(); - - for (const index of group) { - const meta = metas[index]; - if (!meta) continue; - const vertices = meta.polygon.vertices; - for (let i = 0; i < vertices.length; i++) { - const a = vertices[i]; - const b = vertices[(i + 1) % vertices.length]; - const key = edgeKey(a, b); - const current = edgeCounts.get(key); - if (current) current.count += 1; - else edgeCounts.set(key, { count: 1, a, b }); - } - } - - const boundary = new Set(); - for (const edge of edgeCounts.values()) { - if (edge.count !== 1) continue; - boundary.add(vertexKey(edge.a)); - boundary.add(vertexKey(edge.b)); - } - return boundary; -} - -function projectPolygonToPlane(polygon: Polygon, fit: PlaneFit): Polygon { - const projectVertex = (vertex: Vec3): Vec3 => projectVecToPlane(vertex, fit); - const textureTriangles = mapTextureTriangleVertices(polygon.textureTriangles, projectVertex); - return { - ...polygon, - vertices: polygon.vertices.map(projectVertex), - ...(textureTriangles ? { textureTriangles } : {}), - }; -} - -function sharedEdgeIndices(a: Polygon, b: Polygon): [number, number, number, number] | null { - for (let ai0 = 0; ai0 < a.vertices.length; ai0++) { - const ai1 = (ai0 + 1) % a.vertices.length; - for (let bi0 = 0; bi0 < b.vertices.length; bi0++) { - const bi1 = (bi0 + 1) % b.vertices.length; - if (eqVec(a.vertices[ai0], b.vertices[bi0]) && eqVec(a.vertices[ai1], b.vertices[bi1])) { - return [ai0, ai1, bi0, bi1]; - } - if (eqVec(a.vertices[ai0], b.vertices[bi1]) && eqVec(a.vertices[ai1], b.vertices[bi0])) { - return [ai0, ai1, bi1, bi0]; - } - } - } - return null; -} - -function edgeKey(a: Vec3, b: Vec3): string { - const ak = vertexKey(a); - const bk = vertexKey(b); - return ak < bk ? `${ak}|${bk}` : `${bk}|${ak}`; -} - -function vertexKey(vertex: Vec3): string { - return `${vertex[0]},${vertex[1]},${vertex[2]}`; -} - -function eqVec(a: Vec3, b: Vec3): boolean { - return a[0] === b[0] && a[1] === b[1] && a[2] === b[2]; -} - -function eqUv(a: Vec2, b: Vec2): boolean { - return Math.abs(a[0] - b[0]) <= 1e-4 && Math.abs(a[1] - b[1]) <= 1e-4; -} - -function subVec(a: Vec3, b: Vec3): Vec3 { - return [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; -} - -function dotVec(a: Vec3, b: Vec3): number { - return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; -} - -function distanceVec(a: Vec3, b: Vec3): number { - return Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]); -} - -function normalizeVec(value: Vec3): Vec3 | null { - const length = Math.hypot(value[0], value[1], value[2]); - if (length <= 1e-10) return null; - return [value[0] / length, value[1] / length, value[2] / length]; -} - -function signedPlaneDistance(vertex: Vec3, fit: PlaneFit): number { - return dotVec(subVec(vertex, fit.point), fit.normal); -} - -function projectVecToPlane(vertex: Vec3, fit: PlaneFit): Vec3 { - const distance = signedPlaneDistance(vertex, fit); - return [ - vertex[0] - fit.normal[0] * distance, - vertex[1] - fit.normal[1] * distance, - vertex[2] - fit.normal[2] * distance, - ]; -} diff --git a/packages/core/src/merge/seamRepair.ts b/packages/core/src/merge/seamRepair.ts index f8d78d34a..f92cc0c52 100644 --- a/packages/core/src/merge/seamRepair.ts +++ b/packages/core/src/merge/seamRepair.ts @@ -1,43 +1,33 @@ -import { signedArea2D as signedArea } from "../atlas/solidTriangle"; -import { rotateVec3 as rotateCssVec3 } from "../math/rotation"; -import { boundsOverlap3D as edgeBoundsCouldOverlap, crossVec as cross } from "../math/vec3"; -import type { Polygon, Vec3 } from "../types"; -import type { SeamFacetSplitCandidateReason as SplitReason, SeamFacetSplitOptions as SplitOptions, SeamFacetSplitReport as SplitReport, SeamOverlapCandidate as OverlapCandidate, SeamOverlapCandidateKind as OverlapKind, SeamOverlapDiagnostics as OverlapDiagnostics, SeamOverlapOptions as OverlapOptions } from "./seamRepairTypes"; -export type * from "./seamRepairTypes"; - -type Vec2=[number,number]; - -type Basis={origin:Vec3;normal:Vec3;xAxis:Vec3;yAxis:Vec3;local:Vec2[];area:number}; - -type Meta={basis:Basis|null;cssPoints:Vec3[];capacities:number[];patchable:boolean}; - -type Edge={index:number;polygon:number;edge:number;key:string;a:Vec3;b:Vec3;minX:number;minY:number;minZ:number;maxX:number;maxY:number;maxZ:number;length:number;dir:Vec3;normal:Vec3;outward:Vec3;capacity:number;materialKey:string;color?:string}; - -type Near={gap:number;facingA:number;facingB:number;aStart:number;aEnd:number;bStart:number;bEnd:number}; +import type { Polygon } from "../types"; +import type { + SeamFacetSplitOptions as SplitOptions, + SeamFacetSplitReport as SplitReport, + SeamOverlapCandidate as OverlapCandidate, + SeamOverlapDiagnostics as OverlapDiagnostics, + SeamOverlapOptions as OverlapOptions, +} from "./seamRepairTypes"; +import { + DEFAULT_SEAM_SPLIT_BUDGET, + DEFAULT_TRUE_GAP_OVERLAP_PX, + MAX_NEAR_SEAM_GAP_PX, + resolveSeamFacetSplitOptions, + resolveSeamOverlapOptions, + seamOverlapEnabled, +} from "./seamRepair/geometry"; +import { + buildSeamEdgeAmounts, + emptyDiagnostics, + patchPolygon, +} from "./seamRepair/nearSeam"; +import { + applySeamFacetSplitSelection, + seamFacetSplitPlan, + seamFacetSplitPublicCandidate, + splitPlanFollowUpContext, +} from "./seamRepair/facetSplit"; +import type { FollowUp } from "./seamRepair/facetSplit"; -type Repair={start:number;end:number;amount:number}; - -type Split={rotX:number;rotY:number;viewAware:boolean;passes:number;budget:number}; - -type Overlap={overlapPx:number;maxGapPx:number;capacityScale:number}; - -const DEFAULT_TILE = 50; -const MAX_NEAR_SEAM_GAP_PX = 14; -const MIN_RESIDUAL_PATCH_GAP_PX = 0.25; -const SEAM_SPLIT_INTERNAL_OVERLAP_PX = 1.25; -const SEAM_SPLIT_EDGE_OVERLAP_PX = 0.75; -const DEFAULT_SEAM_SPLIT_BUDGET = 40; -const MIN_PARALLEL_DOT = 0.985; -const MIN_FACING_DOT = 0.5; -const TRUE_GAP_OVERLAP_AMOUNT_RATIO = 0.175; -const DEFAULT_TRUE_GAP_OVERLAP_PX = 1.25; -const NEAR_SEAM_SWEEP_RECORD_LIMIT = 10000; -const NEAR_SEAM_SWEEP_PAIR_LIMIT = 2_000_000; -const NEAR_SEAM_EXTENDED_SWEEP_PAIR_LIMIT = 25_000_000; -const NEAR_SEAM_GRID_AVG_CELLS_PER_RECORD_LIMIT = 256; -const NEAR_SEAM_GRID_MAX_CELLS_PER_RECORD_LIMIT = 8192; -const EPS = 1e-6; -const TOPOLOGY_EPS = 1e-4; +export type * from "./seamRepairTypes"; export const DEFAULT_SEAM_OVERLAP_OPTIONS = { overlapPx: DEFAULT_TRUE_GAP_OVERLAP_PX, @@ -49,1400 +39,6 @@ export const DEFAULT_SEAM_FACET_SPLIT_OPTIONS = { budget: DEFAULT_SEAM_SPLIT_BUDGET, } as const satisfies SplitOptions; -function finiteOr(value: number | undefined, fallback: number) { - return typeof value === "number" && Number.isFinite(value) ? value : fallback; -} - -function resolveSeamOverlapOptions( - options?: number | OverlapOptions, -) { - if (typeof options === "number") { - return { - overlapPx: Math.max(0, options) * TRUE_GAP_OVERLAP_AMOUNT_RATIO, - maxGapPx: MAX_NEAR_SEAM_GAP_PX, - capacityScale: 1, - }; - } - - return { - overlapPx: Math.max(0, finiteOr(options?.overlapPx, DEFAULT_TRUE_GAP_OVERLAP_PX)), - maxGapPx: Math.max(0, finiteOr(options?.maxGapPx, MAX_NEAR_SEAM_GAP_PX)), - capacityScale: Math.max(0, finiteOr(options?.capacityScale, 1)), - }; -} - -function seamOverlapEnabled( - options: Overlap, - rawOptions?: number | OverlapOptions, -) { - return !(typeof rawOptions === "number" && rawOptions <= 0) && options.maxGapPx > EPS && options.capacityScale > EPS; -} - -function resolveSeamFacetSplitOptions(options?: SplitOptions) { - return { - rotX: finiteOr(options?.rotX, 65), - rotY: finiteOr(options?.rotY, 45), - viewAware: options?.viewAware !== false, - passes: Math.max(1, Math.min(3, Math.round(finiteOr(options?.passes, 2)))), - budget: Math.max(0, Math.min(256, Math.round(finiteOr(options?.budget, DEFAULT_SEAM_SPLIT_BUDGET)))), - }; -} - -function cssPoints(vertices: Vec3[]): Vec3[] { - return vertices.map((v): Vec3 => [v[1] * DEFAULT_TILE, v[0] * DEFAULT_TILE, v[2] * DEFAULT_TILE]); -} - -function fromCssPoint(point: Vec3): Vec3 { - return [point[1] / DEFAULT_TILE, point[0] / DEFAULT_TILE, point[2] / DEFAULT_TILE]; -} - -function pointKey(point: Vec3) { - return `${point[0]},${point[1]},${point[2]}`; -} - -function edgeKey(a: Vec3, b: Vec3) { - const ak = pointKey(a); - const bk = pointKey(b); - return ak < bk ? `${ak}|${bk}` : `${bk}|${ak}`; -} - -function sub(a: Vec3, b: Vec3): Vec3 { - return [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; -} - -function length(a: Vec3) { - return Math.hypot(a[0], a[1], a[2]); -} - -function normalize(a: Vec3): Vec3 | null { - const len = length(a); - return len > EPS ? [a[0] / len, a[1] / len, a[2] / len] : null; -} - -function dot(a: Vec3, b: Vec3) { - return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; -} - -function surfaceNormal(points: Vec3[]): Vec3 | null { - if (points.length < 3) return null; - const origin = points[0]; - const normal: Vec3 = [0, 0, 0]; - for (let i = 1; i + 1 < points.length; i += 1) { - const a = sub(points[i], origin); - const b = sub(points[i + 1], origin); - const n = cross(a, b); - normal[0] -= n[0]; - normal[1] -= n[1]; - normal[2] -= n[2]; - } - return normalize(normal); -} - -function localBasis(points: Vec3[]): Basis | null { - const origin = points[0]; - const normal = surfaceNormal(points); - if (!normal) return null; - - let rawXAxis: Vec3 | null = null; - for (let i = 0; i < points.length; i += 1) { - const edge = sub(points[(i + 1) % points.length], points[i]); - if (length(edge) > EPS) { - rawXAxis = edge; - break; - } - } - if (!rawXAxis) return null; - - const projected = dot(rawXAxis, normal); - const xRaw: Vec3 = [ - rawXAxis[0] - projected * normal[0], - rawXAxis[1] - projected * normal[1], - rawXAxis[2] - projected * normal[2], - ]; - const xAxis = normalize(xRaw); - if (!xAxis) return null; - const yAxis = normalize(cross(normal, xAxis)); - if (!yAxis) return null; - - const local = points.map((point): Vec2 => { - const d = sub(point, origin); - return [dot(d, xAxis), dot(d, yAxis)]; - }); - const area = signedArea(local); - return Math.abs(area) > EPS ? { origin, normal, xAxis, yAxis, local, area } : null; -} - -function isWeaklyConvex(points: Vec2[]) { - if (points.length < 3) return false; - let sign = 0; - for (let i = 0; i < points.length; i += 1) { - const a = points[i]; - const b = points[(i + 1) % points.length]; - const c = points[(i + 2) % points.length]; - const crossValue = (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]); - if (Math.abs(crossValue) <= EPS) continue; - const nextSign = Math.sign(crossValue); - if (sign === 0) sign = nextSign; - else if (nextSign !== sign) return false; - } - return true; -} - -function edgeOutward2D(points: Vec2[], area: number, edgeIndex: number): Vec2 | null { - const a = points[edgeIndex]; - const b = points[(edgeIndex + 1) % points.length]; - const dx = b[0] - a[0]; - const dy = b[1] - a[1]; - const edgeLength = Math.hypot(dx, dy); - if (edgeLength <= EPS) return null; - const outwardSign = area > 0 ? 1 : -1; - return [ - outwardSign * (dy / edgeLength), - outwardSign * (-dx / edgeLength), - ]; -} - -function edgeOutward3D(basis: Basis, edgeIndex: number): Vec3 | null { - const outward = edgeOutward2D(basis.local, basis.area, edgeIndex); - if (!outward) return null; - return normalize([ - basis.xAxis[0] * outward[0] + basis.yAxis[0] * outward[1], - basis.xAxis[1] * outward[0] + basis.yAxis[1] * outward[1], - basis.xAxis[2] * outward[0] + basis.yAxis[2] * outward[1], - ]); -} - -function edgeSafeCapacity(points: Vec2[], edgeIndex: number) { - const count = points.length; - const a = points[edgeIndex]; - const b = points[(edgeIndex + 1) % count]; - const dx = b[0] - a[0]; - const dy = b[1] - a[1]; - const edgeLength = Math.hypot(dx, dy); - if (edgeLength <= EPS) return 0; - - const limits = [edgeLength * 0.24]; - let oppositeClearance = Infinity; - for (let i = 0; i < count; i += 1) { - if (i === edgeIndex || i === (edgeIndex + 1) % count) continue; - const p = points[i]; - const distance = Math.abs((p[0] - a[0]) * dy - (p[1] - a[1]) * dx) / edgeLength; - if (distance > EPS) oppositeClearance = Math.min(oppositeClearance, distance); - } - if (Number.isFinite(oppositeClearance)) limits.push(oppositeClearance * 0.32); - - const adjacentChecks: Array<{ origin: Vec2; point: Vec2 }> = [ - { origin: a, point: points[(edgeIndex + count - 1) % count] }, - { origin: b, point: points[(edgeIndex + 2) % count] }, - ]; - for (const adjacent of adjacentChecks) { - const adx = adjacent.point[0] - adjacent.origin[0]; - const ady = adjacent.point[1] - adjacent.origin[1]; - const adjacentLength = Math.hypot(adx, ady); - if (adjacentLength <= EPS) continue; - const sin = Math.abs(dx * ady - dy * adx) / (edgeLength * adjacentLength); - if (sin > EPS) limits.push(adjacentLength * sin * 0.32); - } - - return Math.min(...limits); -} - -function buildPolygonMetas(polygons: Polygon[]) { - return polygons.map((polygon): Meta => { - const css = cssPoints(polygon.vertices); - const basis = localBasis(css); - const patchable = !hasTexture(polygon) && !!basis && isWeaklyConvex(basis.local); - const capacities = patchable - ? basis!.local.map((_, edgeIndex) => edgeSafeCapacity(basis!.local, edgeIndex)) - : []; - return { - basis, - cssPoints: css, - capacities, - patchable, - }; - }); -} - -function hasTexture(polygon: Polygon) { - return !!(polygon.texture || polygon.material?.texture || polygon.textureTriangles?.length); -} - -function materialKey(polygon: Polygon) { - return polygon.material?.key ?? polygon.color ?? ""; -} - -function buildEdgeRecords( - polygons: Polygon[], - metas: Meta[], - capacityScale: number, -) { - const records: Edge[] = []; - for (let polygonIndex = 0; polygonIndex < metas.length; polygonIndex += 1) { - const meta = metas[polygonIndex]; - if (!meta.patchable || !meta.basis) continue; - for (let edgeIndex = 0; edgeIndex < meta.cssPoints.length; edgeIndex += 1) { - const a = meta.cssPoints[edgeIndex]; - const b = meta.cssPoints[(edgeIndex + 1) % meta.cssPoints.length]; - const edge = sub(b, a); - const edgeLength = length(edge); - const dir = normalize(edge); - const outward = edgeOutward3D(meta.basis, edgeIndex); - const capacity = (meta.capacities[edgeIndex] ?? 0) * capacityScale; - if (!dir || !outward || capacity <= EPS || edgeLength <= EPS) continue; - records.push({ - index: records.length, - polygon: polygonIndex, - edge: edgeIndex, - key: edgeKey(a, b), - a, - b, - minX: Math.min(a[0], b[0]), - minY: Math.min(a[1], b[1]), - minZ: Math.min(a[2], b[2]), - maxX: Math.max(a[0], b[0]), - maxY: Math.max(a[1], b[1]), - maxZ: Math.max(a[2], b[2]), - length: edgeLength, - dir, - normal: meta.basis.normal, - outward, - capacity, - materialKey: materialKey(polygons[polygonIndex]), - color: polygons[polygonIndex].color, - }); - } - } - return records; -} - -function compatibleRepairMaterials(a: Edge, b: Edge) { - return a.materialKey === b.materialKey && a.color === b.color; -} - -function sameTopologyPoint(a: Vec3, b: Vec3) { - return length(sub(a, b)) <= TOPOLOGY_EPS; -} - -function edgeRecordsTouch(a: Edge, b: Edge) { - return sameTopologyPoint(a.a, b.a) || - sameTopologyPoint(a.a, b.b) || - sameTopologyPoint(a.b, b.a) || - sameTopologyPoint(a.b, b.b); -} - -function classifyCandidate(a: Edge, b: Edge) { - return compatibleRepairMaterials(a, b) - ? edgeRecordsTouch(a, b) ? "connected-facet" : "true-gap" - : "material-boundary"; -} - -function seamOverlapCandidate( - kind: OverlapKind, - a: Edge, - b: Edge, - info: Near, - targetClosurePx: number, - appliedClosurePx: number, -) { - return { - kind, - aPolygon: a.polygon, - aEdge: a.edge, - bPolygon: b.polygon, - bEdge: b.edge, - aColor: a.color, - bColor: b.color, - aMaterialKey: a.materialKey, - bMaterialKey: b.materialKey, - gapPx: info.gap, - spanPx: info.aEnd - info.aStart, - aStartPx: info.aStart, - aEndPx: info.aEnd, - bStartPx: info.bStart, - bEndPx: info.bEnd, - targetClosurePx, - appliedClosurePx, - residualGapPx: Math.max(0, info.gap - appliedClosurePx), - residualTargetPx: Math.max(0, targetClosurePx - appliedClosurePx), - }; -} - -function addEdgeRepair( - repairs: Array>, - record: Edge, - start: number, - end: number, - amount: number, -) { - const clippedStart = Math.max(0, Math.min(record.length, Math.min(start, end))); - const clippedEnd = Math.max(0, Math.min(record.length, Math.max(start, end))); - if (amount <= EPS || clippedEnd - clippedStart <= EPS) return; - const current = repairs[record.polygon].get(record.edge); - const segment = { start: clippedStart, end: clippedEnd, amount }; - if (current) current.push(segment); - else repairs[record.polygon].set(record.edge, [segment]); -} - -function emptyDiagnostics() { - return { - exactPairs: 0, - nearPairs: 0, - patchedPolygons: 0, - patchedEdges: 0, - maxMeasuredGapPx: 0, - maxAppliedAmountPx: 0, - unclosedPairs: 0, - maxResidualGapPx: 0, - }; -} - -function finishDiagnostics( - repairs: Array>, - diagnostics: OverlapDiagnostics, -) { - let maxAppliedAmountPx = 0; - let patchedEdges = 0; - let patchedPolygons = 0; - for (const polygonRepairs of repairs) { - if (polygonRepairs.size > 0) patchedPolygons += 1; - patchedEdges += polygonRepairs.size; - for (const segments of polygonRepairs.values()) { - for (const segment of segments) { - maxAppliedAmountPx = Math.max(maxAppliedAmountPx, segment.amount); - } - } - } - return { - ...diagnostics, - patchedPolygons, - patchedEdges, - maxAppliedAmountPx, - }; -} - -function buildSeamEdgeAmounts( - polygons: Polygon[], - options: Overlap, - collectCandidates = false, - diagnosticsOnly = false, -) { - const metas = buildPolygonMetas(polygons); - const records = buildEdgeRecords(polygons, metas, options.capacityScale); - const repairs = diagnosticsOnly ? [] : polygons.map(() => new Map()); - const diagnostics = emptyDiagnostics(); - const candidates = collectCandidates ? [] as OverlapCandidate[] : undefined; - if (records.length === 0) { - return { edgeRepairs: repairs, diagnostics, candidates }; - } - - const edgeOwners = new Map(); - for (const record of records) { - const owners = edgeOwners.get(record.key); - if (owners) owners.push(record); - else edgeOwners.set(record.key, [record]); - } - - for (const owners of edgeOwners.values()) { - if (owners.length < 2) continue; - diagnostics.exactPairs += owners.length === 2 ? 1 : owners.length; - } - - buildNearSeamEdgeAmounts(records, edgeOwners, repairs, diagnostics, options, candidates); - return { - edgeRepairs: repairs, - diagnostics: diagnosticsOnly ? diagnostics : finishDiagnostics(repairs, diagnostics), - candidates, - }; -} - -function buildNearSeamEdgeAmounts( - records: Edge[], - edgeOwners: ReadonlyMap, - repairs: Array>, - diagnostics: OverlapDiagnostics, - options: Overlap, - candidates: OverlapCandidate[] | undefined, -) { - const maxGap = options.maxGapPx; - const exactSharedKeys = new Set(); - for (const [key, owners] of edgeOwners) { - if (owners.length > 1) exactSharedKeys.add(key); - } - - const measurePair = (first: Edge, second: Edge) => { - const record = first.index < second.index ? first : second; - const candidate = first.index < second.index ? second : first; - if (candidate.polygon === record.polygon) return; - if (record.key === candidate.key && exactSharedKeys.has(record.key)) return; - if (!candidates && !compatibleRepairMaterials(record, candidate)) return; - if (!edgeBoundsCouldOverlap(record, candidate, maxGap)) return; - if (Math.abs(dot(record.dir, candidate.dir)) < MIN_PARALLEL_DOT) return; - - const info = nearSeamInfo(record, candidate, maxGap); - if (!info) return; - const kind = classifyCandidate(record, candidate); - const targetClosure = info.gap + options.overlapPx; - if (kind === "material-boundary") { - candidates?.push(seamOverlapCandidate(kind, record, candidate, info, targetClosure, 0)); - return; - } - - let remainingClosure = targetClosure; - if (remainingClosure <= MIN_RESIDUAL_PATCH_GAP_PX) { - candidates?.push(seamOverlapCandidate(kind, record, candidate, info, targetClosure, 0)); - return; - } - - const maxClosureA = record.capacity * info.facingA; - const maxClosureB = candidate.capacity * info.facingB; - let closureA = Math.min(maxClosureA, remainingClosure / 2); - let closureB = Math.min(maxClosureB, remainingClosure / 2); - remainingClosure -= closureA + closureB; - if (remainingClosure > EPS) { - const extraA = Math.min(maxClosureA - closureA, remainingClosure); - closureA += extraA; - remainingClosure -= extraA; - } - if (remainingClosure > EPS) { - const extraB = Math.min(maxClosureB - closureB, remainingClosure); - closureB += extraB; - remainingClosure -= extraB; - } - - candidates?.push(seamOverlapCandidate(kind, record, candidate, info, targetClosure, closureA + closureB)); - if (repairs.length > 0 && closureA > EPS) { - addEdgeRepair(repairs, record, info.aStart, info.aEnd, closureA / info.facingA); - } - if (repairs.length > 0 && closureB > EPS) { - addEdgeRepair(repairs, candidate, info.bStart, info.bEnd, closureB / info.facingB); - } - diagnostics.nearPairs += 1; - diagnostics.maxMeasuredGapPx = Math.max(diagnostics.maxMeasuredGapPx, info.gap); - if (remainingClosure > MIN_RESIDUAL_PATCH_GAP_PX) { - diagnostics.unclosedPairs += 1; - diagnostics.maxResidualGapPx = Math.max(diagnostics.maxResidualGapPx, remainingClosure); - } - }; - - const cellSize = Math.max(MAX_NEAR_SEAM_GAP_PX * 2, maxGap * 2); - - if (records.length <= NEAR_SEAM_SWEEP_RECORD_LIMIT) { - const sorted = [...records].sort((a, b) => a.minX - b.minX); - const sweepEnds = new Int32Array(sorted.length); - let sweepPairCount = 0; - for (let i = 0; i + 1 < sorted.length; i += 1) { - const record = sorted[i]; - const maxX = record.maxX + maxGap; - let end = i + 1; - while (end < sorted.length && sorted[end].minX <= maxX) end += 1; - sweepEnds[i] = end; - sweepPairCount += end - i - 1; - if (sweepPairCount > NEAR_SEAM_EXTENDED_SWEEP_PAIR_LIMIT) break; - } - if ( - sweepPairCount <= NEAR_SEAM_SWEEP_PAIR_LIMIT || - ( - sweepPairCount <= NEAR_SEAM_EXTENDED_SWEEP_PAIR_LIMIT && - shouldUseExtendedSweep(records, cellSize, maxGap) - ) - ) { - for (let i = 0; i + 1 < sorted.length; i += 1) { - for (let j = i + 1; j < sweepEnds[i]; j += 1) { - measurePair(sorted[i], sorted[j]); - } - } - return; - } - } - - const cells = new Map(); - for (const record of records) { - addRecordToSegmentCells(cells, record, cellSize, maxGap); - } - - const seenPairs = new Set(); - const recordCount = records.length; - for (const bucket of cells.values()) { - for (let i = 0; i + 1 < bucket.length; i += 1) { - for (let j = i + 1; j < bucket.length; j += 1) { - const first = bucket[i]; - const second = bucket[j]; - const record = first.index < second.index ? first : second; - const candidate = first.index < second.index ? second : first; - const pairKey = record.index * recordCount + candidate.index; - if (seenPairs.has(pairKey)) continue; - seenPairs.add(pairKey); - measurePair(record, candidate); - } - } - } -} - -function cellCoords(point: Vec3, cellSize: number): [number, number, number] { - return [ - Math.floor(point[0] / cellSize), - Math.floor(point[1] / cellSize), - Math.floor(point[2] / cellSize), - ]; -} - -function addRecordToSegmentCells( - cells: Map, - record: Edge, - cellSize: number, - padding: number, -) { - const [minCx, minCy, minCz, maxCx, maxCy, maxCz] = recordSegmentCellBounds(record, cellSize, padding); - for (let x = minCx; x <= maxCx; x += 1) { - for (let y = minCy; y <= maxCy; y += 1) { - for (let z = minCz; z <= maxCz; z += 1) { - const key = `${x},${y},${z}`; - const bucket = cells.get(key); - if (bucket) bucket.push(record); - else cells.set(key, [record]); - } - } - } -} - -function recordSegmentCellBounds(record: Edge, cellSize: number, padding: number): [number, number, number, number, number, number] { - const [minCx, minCy, minCz] = cellCoords([record.minX - padding, record.minY - padding, record.minZ - padding], cellSize); - const [maxCx, maxCy, maxCz] = cellCoords([record.maxX + padding, record.maxY + padding, record.maxZ + padding], cellSize); - return [minCx, minCy, minCz, maxCx, maxCy, maxCz]; -} - -function recordSegmentCellCount(record: Edge, cellSize: number, padding: number) { - const [minCx, minCy, minCz, maxCx, maxCy, maxCz] = recordSegmentCellBounds(record, cellSize, padding); - return (maxCx - minCx + 1) * (maxCy - minCy + 1) * (maxCz - minCz + 1); -} - -function shouldUseExtendedSweep( - records: Edge[], - cellSize: number, - padding: number, -) { - let totalCells = 0; - let maxCells = 0; - for (const record of records) { - const cells = recordSegmentCellCount(record, cellSize, padding); - totalCells += cells; - if (cells > maxCells) maxCells = cells; - if (maxCells > NEAR_SEAM_GRID_MAX_CELLS_PER_RECORD_LIMIT) return true; - } - return totalCells / Math.max(1, records.length) > NEAR_SEAM_GRID_AVG_CELLS_PER_RECORD_LIMIT; -} - -function dotFromPointToEdge(point: Vec3, edgeOrigin: Vec3, edgeDir: Vec3) { - return ( - (point[0] - edgeOrigin[0]) * edgeDir[0] + - (point[1] - edgeOrigin[1]) * edgeDir[1] + - (point[2] - edgeOrigin[2]) * edgeDir[2] - ); -} - -function dotEdgePointToEdge(source: Edge, distance: number, target: Edge) { - return ( - (source.a[0] + source.dir[0] * distance - target.a[0]) * target.dir[0] + - (source.a[1] + source.dir[1] * distance - target.a[1]) * target.dir[1] + - (source.a[2] + source.dir[2] * distance - target.a[2]) * target.dir[2] - ); -} - -function nearSeamInfo(a: Edge, b: Edge, maxGap: number) { - const bStart = dotFromPointToEdge(b.a, a.a, a.dir); - const bEnd = dotFromPointToEdge(b.b, a.a, a.dir); - const overlapStart = Math.max(0, Math.min(bStart, bEnd)); - const overlapEnd = Math.min(a.length, Math.max(bStart, bEnd)); - const overlap = overlapEnd - overlapStart; - const minLength = Math.min(a.length, b.length); - if (overlap < Math.max(0.75, minLength * 0.12)) return null; - - const aMidT = (overlapStart + overlapEnd) / 2; - const aMidX = a.a[0] + a.dir[0] * aMidT; - const aMidY = a.a[1] + a.dir[1] * aMidT; - const aMidZ = a.a[2] + a.dir[2] * aMidT; - const bT = Math.max(0, Math.min( - b.length, - (aMidX - b.a[0]) * b.dir[0] + - (aMidY - b.a[1]) * b.dir[1] + - (aMidZ - b.a[2]) * b.dir[2], - )); - const gapX = b.a[0] + b.dir[0] * bT - aMidX; - const gapY = b.a[1] + b.dir[1] * bT - aMidY; - const gapZ = b.a[2] + b.dir[2] * bT - aMidZ; - const gap = Math.hypot(gapX, gapY, gapZ); - if (gap <= EPS) return null; - if (gap > maxGap) return null; - if (gap > Math.min(maxGap, Math.max(4, minLength * 0.28))) return null; - - const invGap = 1 / gap; - const gapDirX = gapX * invGap; - const gapDirY = gapY * invGap; - const gapDirZ = gapZ * invGap; - const facingA = a.outward[0] * gapDirX + a.outward[1] * gapDirY + a.outward[2] * gapDirZ; - const facingB = -(b.outward[0] * gapDirX + b.outward[1] * gapDirY + b.outward[2] * gapDirZ); - if (facingA < MIN_FACING_DOT || facingB < MIN_FACING_DOT) return null; - const b0T = Math.max(0, Math.min(b.length, dotEdgePointToEdge(a, overlapStart, b))); - const b1T = Math.max(0, Math.min(b.length, dotEdgePointToEdge(a, overlapEnd, b))); - return { - gap, - facingA, - facingB, - aStart: overlapStart, - aEnd: overlapEnd, - bStart: Math.min(b0T, b1T), - bEnd: Math.max(b0T, b1T), - }; -} - -function repairPoint(a: Vec2, b: Vec2, edgeLength: number, distance: number): Vec2 { - const t = edgeLength <= EPS ? 0 : Math.max(0, Math.min(1, distance / edgeLength)); - return [ - a[0] + (b[0] - a[0]) * t, - a[1] + (b[1] - a[1]) * t, - ]; -} - -function pushUniquePoint(points: Vec2[], point: Vec2) { - const last = points[points.length - 1]; - if (last && Math.hypot(last[0] - point[0], last[1] - point[1]) <= EPS) return; - points.push(point); -} - -function normalizeRepairSegments( - segments: Repair[] | undefined, - edgeLength: number, - capacity: number, -) { - if (!segments?.length || edgeLength <= EPS || capacity <= EPS) return []; - const stops = new Set([0, edgeLength]); - for (const segment of segments) { - const start = Math.max(0, Math.min(edgeLength, segment.start)); - const end = Math.max(0, Math.min(edgeLength, segment.end)); - if (end - start <= EPS || segment.amount <= EPS) continue; - stops.add(start); - stops.add(end); - } - - const sortedStops = Array.from(stops).sort((a, b) => a - b); - const normalized: Repair[] = []; - for (let i = 0; i + 1 < sortedStops.length; i += 1) { - const start = sortedStops[i]; - const end = sortedStops[i + 1]; - if (end - start <= EPS) continue; - const mid = (start + end) / 2; - let amount = 0; - for (const segment of segments) { - if (mid + EPS < segment.start || mid - EPS > segment.end) continue; - amount = Math.max(amount, segment.amount); - } - const safeAmount = Math.min(capacity, amount); - if (safeAmount > EPS) normalized.push({ start, end, amount: safeAmount }); - } - return normalized; -} - -function isValidRepairedPolygon(source: Vec2[], repaired: Vec2[]) { - if (repaired.length < 3 || !isWeaklyConvex(repaired)) return false; - const sourceArea = signedArea(source); - const repairedArea = signedArea(repaired); - return Math.sign(repairedArea) === Math.sign(sourceArea) && Math.abs(repairedArea) >= Math.abs(sourceArea) - EPS; -} - -function patchPolygon( - polygon: Polygon, - edgeRepairs: ReadonlyMap, - capacityScale: number, -) { - if (edgeRepairs.size === 0 || polygon.vertices.length < 3 || hasTexture(polygon)) return polygon; - - const points = cssPoints(polygon.vertices); - const basis = localBasis(points); - if (!basis || !isWeaklyConvex(basis.local)) return polygon; - - const repaired: Vec2[] = []; - for (let edgeIndex = 0; edgeIndex < basis.local.length; edgeIndex += 1) { - const a = basis.local[edgeIndex]; - const b = basis.local[(edgeIndex + 1) % basis.local.length]; - const edgeLength = Math.hypot(b[0] - a[0], b[1] - a[1]); - const outward = edgeOutward2D(basis.local, basis.area, edgeIndex); - if (!outward || edgeLength <= EPS) return polygon; - const segments = normalizeRepairSegments( - edgeRepairs.get(edgeIndex), - edgeLength, - edgeSafeCapacity(basis.local, edgeIndex) * capacityScale, - ); - - pushUniquePoint(repaired, a); - let cursor = 0; - for (const segment of segments) { - if (segment.start > cursor + EPS) { - pushUniquePoint(repaired, repairPoint(a, b, edgeLength, segment.start)); - } - - const start = repairPoint(a, b, edgeLength, segment.start); - const end = repairPoint(a, b, edgeLength, segment.end); - pushUniquePoint(repaired, [ - start[0] + outward[0] * segment.amount, - start[1] + outward[1] * segment.amount, - ]); - pushUniquePoint(repaired, [ - end[0] + outward[0] * segment.amount, - end[1] + outward[1] * segment.amount, - ]); - if (segment.end < edgeLength - EPS) pushUniquePoint(repaired, end); - cursor = segment.end; - } - } - - const first = repaired[0]; - const last = repaired[repaired.length - 1]; - if (first && last && Math.hypot(first[0] - last[0], first[1] - last[1]) <= EPS) repaired.pop(); - if (!isValidRepairedPolygon(basis.local, repaired)) return polygon; - - const vertices = repaired.map(([x, y]) => fromCssPoint([ - basis.origin[0] + x * basis.xAxis[0] + y * basis.yAxis[0], - basis.origin[1] + x * basis.xAxis[1] + y * basis.yAxis[1], - basis.origin[2] + x * basis.xAxis[2] + y * basis.yAxis[2], - ])); - return { ...polygon, vertices }; -} - -function isRefinableSeamQuad(polygon: Polygon) { - return polygon.vertices.length === 4 && !hasTexture(polygon); -} - -function quadShapeRisk(meta: Meta) { - const local = meta.basis?.local; - if (!local || local.length !== 4) return 1; - let minX = Infinity; - let minY = Infinity; - let maxX = -Infinity; - let maxY = -Infinity; - for (const [x, y] of local) { - minX = Math.min(minX, x); - minY = Math.min(minY, y); - maxX = Math.max(maxX, x); - maxY = Math.max(maxY, y); - } - const bboxArea = Math.max(EPS, (maxX - minX) * (maxY - minY)); - const fillRatio = Math.max(0, Math.min(1, Math.abs(meta.basis!.area) / bboxArea)); - return 0.75 + (1 - fillRatio) * 2.5; -} - -function cssDistance(a: Vec3, b: Vec3) { - return length(sub(cssPoints([a])[0], cssPoints([b])[0])); -} - -function triangleQuality(a: Vec3, b: Vec3, c: Vec3) { - const ab = cssDistance(a, b); - const bc = cssDistance(b, c); - const ca = cssDistance(c, a); - const longest = Math.max(ab, bc, ca); - if (longest <= EPS) return 0; - const area = length(cross(sub(cssPoints([b])[0], cssPoints([a])[0]), sub(cssPoints([c])[0], cssPoints([a])[0]))) * 0.5; - return area / (longest * longest); -} - -function intersectLocalLines(a0: Vec2, a1: Vec2, b0: Vec2, b1: Vec2): Vec2 | null { - const rx = a1[0] - a0[0]; - const ry = a1[1] - a0[1]; - const sx = b1[0] - b0[0]; - const sy = b1[1] - b0[1]; - const det = rx * sy - ry * sx; - if (Math.abs(det) <= EPS) return null; - const qpx = b0[0] - a0[0]; - const qpy = b0[1] - a0[1]; - const t = (qpx * sy - qpy * sx) / det; - return [a0[0] + t * rx, a0[1] + t * ry]; -} - -function offsetLocalConvexPointsByEdgeAmounts(points: Vec2[], amounts: number[]) { - if (points.length < 3 || points.length !== amounts.length) return null; - const maxAmount = Math.max(0, ...amounts); - if (maxAmount <= EPS) return points; - const area = signedArea(points); - if (Math.abs(area) <= EPS) return null; - const outwardSign = area > 0 ? 1 : -1; - const offsetLines: Array<{ a: Vec2; b: Vec2 }> = []; - for (let i = 0; i < points.length; i += 1) { - const a = points[i]; - const b = points[(i + 1) % points.length]; - const dx = b[0] - a[0]; - const dy = b[1] - a[1]; - const edgeLength = Math.hypot(dx, dy); - if (edgeLength <= EPS) return null; - const amount = Math.max(0, amounts[i]); - const ox = outwardSign * (dy / edgeLength) * amount; - const oy = outwardSign * (-dx / edgeLength) * amount; - offsetLines.push({ - a: [a[0] + ox, a[1] + oy], - b: [b[0] + ox, b[1] + oy], - }); - } - - const expanded: Vec2[] = []; - const maxMiter = Math.max(2, maxAmount * 4); - for (let i = 0; i < points.length; i += 1) { - const prev = offsetLines[(i + points.length - 1) % points.length]; - const next = offsetLines[i]; - const intersection = intersectLocalLines(prev.a, prev.b, next.a, next.b); - if (!intersection) return null; - const original = points[i]; - const dx = intersection[0] - original[0]; - const dy = intersection[1] - original[1]; - const miter = Math.hypot(dx, dy); - expanded.push( - miter > maxMiter - ? [original[0] + (dx / miter) * maxMiter, original[1] + (dy / miter) * maxMiter] - : intersection, - ); - } - return expanded; -} - -function cssPointFromLocal(basis: Basis, point: Vec2): Vec3 { - return [ - basis.origin[0] + basis.xAxis[0] * point[0] + basis.yAxis[0] * point[1], - basis.origin[1] + basis.xAxis[1] * point[0] + basis.yAxis[1] * point[1], - basis.origin[2] + basis.xAxis[2] * point[0] + basis.yAxis[2] * point[1], - ]; -} - -function offsetTriangleVertices(vertices: Vec3[], amounts: [number, number, number]) { - const basis = localBasis(cssPoints(vertices)); - if (!basis) return vertices; - const expanded = offsetLocalConvexPointsByEdgeAmounts(basis.local, amounts); - return expanded - ? expanded.map((point) => fromCssPoint(cssPointFromLocal(basis, point))) - : vertices; -} - -function splitQuadIntoTriangles(polygon: Polygon, edges: ReadonlySet) { - const solid: Polygon = { ...polygon, uvs: undefined, textureTriangles: undefined }; - const [a, b, c, d] = polygon.vertices; - const acQuality = Math.min(triangleQuality(a, b, c), triangleQuality(a, c, d)); - const bdQuality = Math.min(triangleQuality(a, b, d), triangleQuality(b, c, d)); - const seamAmount = (edge: number) => edges.has(edge) ? SEAM_SPLIT_EDGE_OVERLAP_PX : 0; - return acQuality >= bdQuality - ? [ - { ...solid, vertices: offsetTriangleVertices([a, b, c], [seamAmount(0), seamAmount(1), SEAM_SPLIT_INTERNAL_OVERLAP_PX]) }, - { ...solid, vertices: offsetTriangleVertices([a, c, d], [SEAM_SPLIT_INTERNAL_OVERLAP_PX, seamAmount(2), seamAmount(3)]) }, - ] - : [ - { ...solid, vertices: offsetTriangleVertices([a, b, d], [seamAmount(0), SEAM_SPLIT_INTERNAL_OVERLAP_PX, seamAmount(3)]) }, - { ...solid, vertices: offsetTriangleVertices([b, c, d], [seamAmount(1), seamAmount(2), SEAM_SPLIT_INTERNAL_OVERLAP_PX]) }, - ]; -} - -type Cand={key:string;e:[string,string];o:Edge[];r:Edge[];len:number;rank:number;proj:number;s:number;nr:number;sr:number;vr:number;comp:number;sel:boolean;why:SplitReason;cost:number}; - -type FollowUp={endpoints:ReadonlySet}; - -type SplitMode="primary"|"follow-up"; - -type Dist={q1:number;median:number;q3:number;p70:number;p80:number;p88:number;p95:number;p97:number;max:number}; - -function numericDistribution(values: number[]) { - if (values.length === 0) { - return { - q1: Infinity, - median: Infinity, - q3: Infinity, - p70: Infinity, - p80: Infinity, - p88: Infinity, - p95: Infinity, - p97: Infinity, - max: Infinity, - }; - } - const sorted = [...values].sort((a, b) => a - b); - const at = (ratio: number) => sorted[Math.min(sorted.length - 1, Math.floor((sorted.length - 1) * ratio))] ?? 0; - return { - q1: at(0.25), - median: at(0.5), - q3: at(0.75), - p70: at(0.7), - p80: at(0.8), - p88: at(0.88), - p95: at(0.95), - p97: at(0.97), - max: sorted[sorted.length - 1] ?? 0, - }; -} - -function unionFindRoot(parents: number[], index: number): number { - const parent = parents[index]; - if (parent === index) return index; - const root = unionFindRoot(parents, parent); - parents[index] = root; - return root; -} - -function splitPlanFollowUpContext(candidates: Cand[]) { - const endpoints = new Set(); - const components = new Set(); - for (const candidate of candidates) { - if (!candidate.sel) continue; - components.add(candidate.comp); - } - for (const candidate of candidates) { - if (!components.has(candidate.comp)) continue; - for (const endpoint of candidate.e) endpoints.add(endpoint); - } - return { endpoints }; -} - -function splitCandidateTouchesFollowUp( - candidate: Cand, - context: FollowUp | undefined, -) { - if (!context) return true; - return candidate.e.some((endpoint) => context.endpoints.has(endpoint)); -} - -function buildSeamFacetSplitCandidates( - polygons: Polygon[], - metas: Meta[], - edgeOwners: ReadonlyMap, - splitOptions: Split, -) { - const candidates: Cand[] = []; - for (const [key, owners] of edgeOwners) { - if (owners.length !== 2) continue; - const [a, b] = owners; - if (!compatibleRepairMaterials(a, b)) continue; - const refinable = owners.filter((record) => isRefinableSeamQuad(polygons[record.polygon])); - if (refinable.length === 0) continue; - const firstRefinable = refinable[0]; - - const normalRisk = 1 - Math.min(1, Math.abs(dot(a.normal, b.normal))); - const seamLength = Math.max(a.length, b.length); - if (normalRisk < 0.01 && seamLength < 64) continue; - - const shapeRisk = Math.max(...refinable.map((record) => quadShapeRisk(metas[record.polygon]))); - const bothSidesRefinable = refinable.length === 2 ? 1.18 : 1; - const seamRisk = Math.max(0.08, normalRisk); - const projected = splitOptions.viewAware - ? splitCandidateViewMetrics(a, b, splitOptions.rotX, splitOptions.rotY) - : { proj: seamLength, vr: 1 }; - const rankLength = splitOptions.viewAware ? Math.max(projected.proj, seamLength * 0.12) : seamLength; - const viewWeight = splitOptions.viewAware ? 0.18 + projected.vr * 1.82 : 1; - candidates.push({ - key, - e: [pointKey(firstRefinable.a), pointKey(firstRefinable.b)], - o: owners, - r: refinable, - len: seamLength, - rank: rankLength, - proj: projected.proj, - s: rankLength * (0.58 + seamRisk * 2.8) * shapeRisk * bothSidesRefinable * viewWeight, - nr: normalRisk, - sr: shapeRisk, - vr: projected.vr, - comp: -1, - sel: false, - why: "below-threshold", - cost: refinable.length, - }); - } - - const parents = Array.from({ length: candidates.length }, (_, index) => index); - const byEndpoint = new Map(); - for (let index = 0; index < candidates.length; index += 1) { - for (const endpoint of candidates[index].e) { - const previous = byEndpoint.get(endpoint); - if (previous === undefined) { - byEndpoint.set(endpoint, index); - } else { - const rootA = unionFindRoot(parents, previous); - const rootB = unionFindRoot(parents, index); - if (rootA !== rootB) parents[rootB] = rootA; - } - } - } - - const componentIds = new Map(); - for (let index = 0; index < candidates.length; index += 1) { - const root = unionFindRoot(parents, index); - let component = componentIds.get(root); - if (component === undefined) { - component = componentIds.size; - componentIds.set(root, component); - } - candidates[index].comp = component; - } - - return candidates; -} - -function splitCandidateViewMetrics( - a: Edge, - b: Edge, - rotX: number, - rotY: number, -) { - const p0 = rotateCssVec3(a.a, rotX, 0, rotY); - const p1 = rotateCssVec3(a.b, rotX, 0, rotY); - const projectedLength = Math.hypot(p1[0] - p0[0], p1[1] - p0[1]); - const depthA = rotateCssVec3(a.normal, rotX, 0, rotY)[2]; - const depthB = rotateCssVec3(b.normal, rotX, 0, rotY)[2]; - const frontness = Math.max(0, depthA, depthB); - const silhouette = Math.min(1, Math.abs(depthA - depthB)); - return { - proj: projectedLength, - vr: Math.max(0.04, Math.min(1, frontness * 0.85 + silhouette * 0.45)), - }; -} - -function strongestCandidatesByComponent( - candidates: Cand[], -) { - const strongest = new Map(); - for (const candidate of candidates) { - const current = strongest.get(candidate.comp); - if (!current || candidate.s > current.s || (candidate.s === current.s && candidate.len > current.len)) { - strongest.set(candidate.comp, candidate); - } - } - return new Set(strongest.values()); -} - -function splitCandidateBudgetPriority(candidate: Cand) { - const coplanar = Math.max(0, 1 - Math.min(1, candidate.nr)); - const coplanarWeight = 0.35 + coplanar * coplanar * coplanar * 3.65; - const oneSidedWeight = candidate.r.length === 1 ? 1.08 : 1; - return (candidate.rank * coplanarWeight * oneSidedWeight) / Math.sqrt(Math.max(1, candidate.r.length)); -} - -function splitCandidateLikelyCrackPriority(candidate: Cand) { - const coplanar = Math.max(0, 1 - Math.min(1, candidate.nr)); - const visibleWeight = 0.35 + Math.min(1, candidate.vr) * 1.65; - const shapeWeight = 0.7 + Math.min(2.6, candidate.sr) * 0.3; - const oneSidedWeight = candidate.r.length === 1 ? 1.1 : 1; - const visiblePriority = ( - candidate.rank * - (0.6 + coplanar * coplanar * 1.4) * - visibleWeight * - shapeWeight * - oneSidedWeight - ) / Math.sqrt(Math.max(1, candidate.r.length)); - return Math.max(visiblePriority, splitCandidateBudgetPriority(candidate) * 0.75); -} - -function uniqueSplitPolygonCost(candidates: Cand[]) { - const polygons = new Set(); - for (const candidate of candidates) { - for (const record of candidate.r) polygons.add(record.polygon); - } - return polygons.size; -} - -function splitCandidateLikelyCrack(candidate: Cand, lengthStats: Dist) { - return candidate.nr <= 0.25 && - candidate.rank >= lengthStats.median * 1.08 && - candidate.proj >= 24; -} - -function splitCandidateGlobalSeed( - candidate: Cand, - strongScore: number, - strongLength: number, -) { - return candidate.s >= strongScore || candidate.rank >= strongLength; -} - -function seamFacetSplitBudgetPlan( - candidates: Cand[], - mode: SplitMode, - maxBudget: number, - scoreStats: Dist, - lengthStats: Dist, - strongScore: number, - strongLength: number, -) { - const budgetLimit = Math.max(0, Math.floor(maxBudget)); - if (budgetLimit <= 0 || candidates.length === 0 || mode === "follow-up") { - return { budgetLimit, componentBudgets: null }; - } - - const byComponent = new Map(); - for (const candidate of candidates) { - const group = byComponent.get(candidate.comp); - if (group) group.push(candidate); - else byComponent.set(candidate.comp, [candidate]); - } - - const componentBudgets = new Map(); - const scoreSpread = Math.max(EPS, scoreStats.q3 - scoreStats.q1); - const fallbackSeedScore = Math.min(scoreStats.max, Math.max(scoreStats.p95, scoreStats.q3 + scoreSpread)); - let total = 0; - for (const [component, group] of byComponent) { - const primary = group.filter((candidate) => - splitCandidateGlobalSeed(candidate, strongScore, strongLength) || - candidate.s >= fallbackSeedScore - ); - if (primary.length === 0) continue; - - const likely = group.filter((candidate) => splitCandidateLikelyCrack(candidate, lengthStats)); - const primaryCost = uniqueSplitPolygonCost(primary); - const likelyCost = uniqueSplitPolygonCost(likely); - const followUpAllowance = Math.ceil(Math.sqrt(Math.max(0, likelyCost - primaryCost)) * 3); - const componentBudget = Math.min( - uniqueSplitPolygonCost(group), - primaryCost + followUpAllowance, - ); - if (componentBudget <= 0) continue; - componentBudgets.set(component, componentBudget); - total += componentBudget; - } - - if (componentBudgets.size === 0) return { budgetLimit: 0, componentBudgets }; - return { - budgetLimit: Math.min(budgetLimit, total), - componentBudgets, - }; -} - -function selectSeamFacetSplitCandidates( - candidates: Cand[], - mode: SplitMode, - budget: number, -) { - const selected = new Map>(); - if (candidates.length === 0 || budget <= 0) return { selected, budgetLimit: 0 }; - - const scoreStats = numericDistribution(candidates.map((candidate) => candidate.s)); - const lengthStats = numericDistribution(candidates.map((candidate) => candidate.rank)); - const scoreSpread = Math.max(EPS, scoreStats.q3 - scoreStats.q1); - const strongScore = Math.min(scoreStats.max, Math.max(scoreStats.p95, scoreStats.q3 + scoreSpread * 0.85)); - const anchorScore = Math.min(scoreStats.max, Math.max(scoreStats.p80, scoreStats.q3 + scoreSpread * 0.15)); - const sharedPolygonScore = Math.min(scoreStats.max, Math.max(scoreStats.p70, scoreStats.q3)); - const strongLength = Math.max(lengthStats.p97, lengthStats.median * 1.8); - const anchorLength = Math.max(lengthStats.p88, lengthStats.median * 1.35); - const budgetPlan = seamFacetSplitBudgetPlan( - candidates, - mode, - budget, - scoreStats, - lengthStats, - strongScore, - strongLength, - ); - let remainingBudget = budgetPlan.budgetLimit; - if (remainingBudget <= 0) return { selected, budgetLimit: 0 }; - - const anchors = strongestCandidatesByComponent(candidates); - const alreadySplit = new Set(); - const selectedEndpoints = new Set(); - const selectedComponents = new Set(); - const componentSpend = new Map(); - const localReserve = mode === "primary" - ? Math.min(Math.max(0, budgetPlan.budgetLimit - 1), Math.max(2, Math.floor(budgetPlan.budgetLimit * 0.28))) - : 0; - - const sorted = [...candidates].sort((a, b) => - splitCandidateBudgetPriority(b) - splitCandidateBudgetPriority(a) || - (b.s / Math.max(1, b.r.length)) - (a.s / Math.max(1, a.r.length)) || - b.len - a.len - ); - const likelyCrackSorted = [...candidates].sort((a, b) => - splitCandidateLikelyCrackPriority(b) - splitCandidateLikelyCrackPriority(a) || - splitCandidateBudgetPriority(b) - splitCandidateBudgetPriority(a) || - b.len - a.len - ); - - const selectCandidate = (candidate: Cand, reason: SplitReason) => { - candidate.sel = true; - candidate.why = reason; - selectedComponents.add(candidate.comp); - for (const endpoint of candidate.e) selectedEndpoints.add(endpoint); - for (const record of candidate.r) { - alreadySplit.add(record.polygon); - const edges = selected.get(record.polygon); - if (edges) edges.add(record.edge); - else selected.set(record.polygon, new Set([record.edge])); - } - }; - - const withinComponentBudget = (candidate: Cand, marginalCost: number) => { - const componentBudgets = budgetPlan.componentBudgets; - if (marginalCost <= 0 || !componentBudgets) return true; - const componentBudget = componentBudgets.get(candidate.comp) ?? 0; - return (componentSpend.get(candidate.comp) ?? 0) + marginalCost <= componentBudget; - }; - - const recordComponentSpend = (candidate: Cand, marginalCost: number) => { - if (marginalCost <= 0 || !budgetPlan.componentBudgets) return; - componentSpend.set(candidate.comp, (componentSpend.get(candidate.comp) ?? 0) + marginalCost); - }; - - for (const candidate of likelyCrackSorted) { - const marginalCost = candidate.r.reduce( - (total, record) => total + (alreadySplit.has(record.polygon) ? 0 : 1), - 0, - ); - candidate.cost = marginalCost; - if (marginalCost > remainingBudget) continue; - if (!withinComponentBudget(candidate, marginalCost)) continue; - if (marginalCost > 0 && remainingBudget - marginalCost < localReserve) continue; - const isLikelyCrack = splitCandidateLikelyCrack(candidate, lengthStats); - if (!isLikelyCrack) continue; - selectCandidate(candidate, "global-outlier"); - recordComponentSpend(candidate, marginalCost); - remainingBudget -= marginalCost; - if (remainingBudget <= 0) return { selected, budgetLimit: budgetPlan.budgetLimit }; - } - - for (const candidate of sorted) { - if (candidate.sel) continue; - const marginalCost = candidate.r.reduce( - (total, record) => total + (alreadySplit.has(record.polygon) ? 0 : 1), - 0, - ); - candidate.cost = marginalCost; - if (marginalCost > remainingBudget) continue; - if (!withinComponentBudget(candidate, marginalCost)) continue; - if (marginalCost > 0 && remainingBudget - marginalCost < localReserve) continue; - - const twoSided = candidate.r.length === 2; - const isAnchor = anchors.has(candidate) && ( - mode === "primary" || - (mode === "follow-up" && candidate.s >= anchorScore * 1.08 && candidate.rank >= anchorLength) - ) && ( - twoSided - ? candidate.s >= anchorScore || candidate.rank >= anchorLength - : candidate.s >= anchorScore * 1.18 || candidate.rank >= anchorLength * 1.12 - ); - const isGlobalOutlier = twoSided - ? candidate.s >= strongScore || candidate.rank >= strongLength - : candidate.s >= strongScore * 1.35 || candidate.rank >= strongLength * 1.2; - const isSharedPolygonFollowUp = marginalCost === 0 && ( - twoSided - ? candidate.s >= sharedPolygonScore || candidate.rank >= anchorLength - : candidate.s >= sharedPolygonScore * 1.25 || candidate.rank >= anchorLength * 1.12 - ); - if (!isAnchor && !isGlobalOutlier && !isSharedPolygonFollowUp) continue; - - selectCandidate(candidate, isAnchor - ? "component-anchor" - : isGlobalOutlier - ? "global-outlier" - : "shared-polygon"); - recordComponentSpend(candidate, marginalCost); - remainingBudget -= marginalCost; - if (remainingBudget <= 0) return { selected, budgetLimit: budgetPlan.budgetLimit }; - } - - for (const candidate of sorted) { - if (candidate.sel) continue; - const marginalCost = candidate.r.reduce( - (total, record) => total + (alreadySplit.has(record.polygon) ? 0 : 1), - 0, - ); - candidate.cost = marginalCost; - if (marginalCost > 1 || marginalCost > remainingBudget) continue; - if (!withinComponentBudget(candidate, marginalCost)) continue; - const touchesSelectedPolygon = candidate.r.some((record) => alreadySplit.has(record.polygon)); - const touchesSelectedEndpoint = candidate.e.some((endpoint) => selectedEndpoints.has(endpoint)); - const isOneSidedTail = mode === "primary" && - candidate.r.length === 1 && - marginalCost === 1 && - (selectedComponents.has(candidate.comp) || touchesSelectedEndpoint || touchesSelectedPolygon) && - candidate.rank >= anchorLength * 1.05 && - candidate.nr >= 0.16 && - candidate.vr <= 0.32; - if (isOneSidedTail) { - selectCandidate(candidate, "local-follow-up"); - recordComponentSpend(candidate, marginalCost); - remainingBudget -= marginalCost; - if (remainingBudget <= 0) return { selected, budgetLimit: budgetPlan.budgetLimit }; - continue; - } - if (candidate.r.length !== 2) continue; - const isProjectedNeighbor = touchesSelectedPolygon && - marginalCost === 1 && - candidate.proj >= anchorLength * 1.45 && - candidate.vr <= 0.18; - if (!touchesSelectedEndpoint && !isProjectedNeighbor) continue; - const isLocalFollowUp = ( - candidate.s >= sharedPolygonScore * 0.42 || - candidate.rank >= anchorLength * 0.62 - ) && candidate.s <= sharedPolygonScore * 1.1 && candidate.proj >= 24; - if (isLocalFollowUp) { - selectCandidate(candidate, "local-follow-up"); - recordComponentSpend(candidate, marginalCost); - remainingBudget -= marginalCost; - if (remainingBudget <= 0) return { selected, budgetLimit: budgetPlan.budgetLimit }; - } - } - - return { selected, budgetLimit: budgetPlan.budgetLimit }; -} - -function seamFacetSplitPlan( - polygons: Polygon[], - seamOptions: Overlap, - splitOptions: Split, - budget: number, - followUpContext?: FollowUp, -) { - const metas = buildPolygonMetas(polygons); - const records = buildEdgeRecords(polygons, metas, seamOptions.capacityScale); - const edgeOwners = new Map(); - for (const record of records) { - const owners = edgeOwners.get(record.key); - if (owners) owners.push(record); - else edgeOwners.set(record.key, [record]); - } - - const candidates = buildSeamFacetSplitCandidates(polygons, metas, edgeOwners, splitOptions) - .filter((candidate) => splitCandidateTouchesFollowUp(candidate, followUpContext)); - const selection = selectSeamFacetSplitCandidates(candidates, followUpContext ? "follow-up" : "primary", budget); - return { selected: selection.selected, candidates, budgetLimit: selection.budgetLimit }; -} - -function applySeamFacetSplitSelection( - polygons: Polygon[], - selected: ReadonlyMap>, -) { - const out: Polygon[] = []; - for (let i = 0; i < polygons.length; i += 1) { - const polygon = polygons[i]; - const edges = selected.get(i); - if (edges && isRefinableSeamQuad(polygon)) out.push(...splitQuadIntoTriangles(polygon, edges)); - else out.push(polygon); - } - return out; -} - -function seamFacetSplitPublicCandidate(candidate: Cand) { - const [a, b] = candidate.o; - const first = a ?? b; - const second = b ?? a; - return { - key: candidate.key, - aPolygon: first?.polygon ?? -1, - aEdge: first?.edge ?? -1, - bPolygon: second?.polygon ?? -1, - bEdge: second?.edge ?? -1, - color: first?.color ?? second?.color, - materialKey: first?.materialKey ?? second?.materialKey ?? "", - lengthPx: candidate.len, - projectedLengthPx: candidate.proj, - score: candidate.s, - normalRisk: candidate.nr, - shapeRisk: candidate.sr, - viewRisk: candidate.vr, - component: candidate.comp, - marginalCost: candidate.cost, - selected: candidate.sel, - reason: candidate.why, - }; -} - export function seamFacetSplitPolygons( polygons: Polygon[], seamOptions?: number | OverlapOptions, diff --git a/packages/core/src/merge/seamRepair/facetSplit.ts b/packages/core/src/merge/seamRepair/facetSplit.ts new file mode 100644 index 000000000..196ae2620 --- /dev/null +++ b/packages/core/src/merge/seamRepair/facetSplit.ts @@ -0,0 +1,550 @@ +import { rotateVec3 as rotateCssVec3 } from "../../math/rotation"; +import type { Polygon } from "../../types"; +import type { SeamFacetSplitCandidateReason as SplitReason } from "../seamRepairTypes"; +import { + buildEdgeRecords, + buildPolygonMetas, + compatibleRepairMaterials, + dot, + EPS, + pointKey, +} from "./geometry"; +import type { Edge, Meta, Overlap, Split } from "./geometry"; +import { + isRefinableSeamQuad, + quadShapeRisk, + splitQuadIntoTriangles, +} from "./quadSplit"; + +type Cand = { + key: string; + e: [string, string]; + o: Edge[]; + r: Edge[]; + len: number; + rank: number; + proj: number; + s: number; + nr: number; + sr: number; + vr: number; + comp: number; + sel: boolean; + why: SplitReason; + cost: number; +}; + +export type FollowUp = { endpoints: ReadonlySet }; + +type SplitMode = "primary" | "follow-up"; + +type Dist = { + q1: number; + median: number; + q3: number; + p70: number; + p80: number; + p88: number; + p95: number; + p97: number; + max: number; +}; + +function numericDistribution(values: number[]) { + if (values.length === 0) { + return { + q1: Infinity, + median: Infinity, + q3: Infinity, + p70: Infinity, + p80: Infinity, + p88: Infinity, + p95: Infinity, + p97: Infinity, + max: Infinity, + }; + } + const sorted = [...values].sort((a, b) => a - b); + const at = (ratio: number) => sorted[Math.min(sorted.length - 1, Math.floor((sorted.length - 1) * ratio))] ?? 0; + return { + q1: at(0.25), + median: at(0.5), + q3: at(0.75), + p70: at(0.7), + p80: at(0.8), + p88: at(0.88), + p95: at(0.95), + p97: at(0.97), + max: sorted[sorted.length - 1] ?? 0, + }; +} + +function unionFindRoot(parents: number[], index: number): number { + const parent = parents[index]; + if (parent === index) return index; + const root = unionFindRoot(parents, parent); + parents[index] = root; + return root; +} + +export function splitPlanFollowUpContext(candidates: Cand[]) { + const endpoints = new Set(); + const components = new Set(); + for (const candidate of candidates) { + if (!candidate.sel) continue; + components.add(candidate.comp); + } + for (const candidate of candidates) { + if (!components.has(candidate.comp)) continue; + for (const endpoint of candidate.e) endpoints.add(endpoint); + } + return { endpoints }; +} + +function splitCandidateTouchesFollowUp( + candidate: Cand, + context: FollowUp | undefined, +) { + if (!context) return true; + return candidate.e.some((endpoint) => context.endpoints.has(endpoint)); +} + +function buildSeamFacetSplitCandidates( + polygons: Polygon[], + metas: Meta[], + edgeOwners: ReadonlyMap, + splitOptions: Split, +) { + const candidates: Cand[] = []; + for (const [key, owners] of edgeOwners) { + if (owners.length !== 2) continue; + const [a, b] = owners; + if (!compatibleRepairMaterials(a, b)) continue; + const refinable = owners.filter((record) => isRefinableSeamQuad(polygons[record.polygon])); + if (refinable.length === 0) continue; + const firstRefinable = refinable[0]; + + const normalRisk = 1 - Math.min(1, Math.abs(dot(a.normal, b.normal))); + const seamLength = Math.max(a.length, b.length); + if (normalRisk < 0.01 && seamLength < 64) continue; + + const shapeRisk = Math.max(...refinable.map((record) => quadShapeRisk(metas[record.polygon]))); + const bothSidesRefinable = refinable.length === 2 ? 1.18 : 1; + const seamRisk = Math.max(0.08, normalRisk); + const projected = splitOptions.viewAware + ? splitCandidateViewMetrics(a, b, splitOptions.rotX, splitOptions.rotY) + : { proj: seamLength, vr: 1 }; + const rankLength = splitOptions.viewAware ? Math.max(projected.proj, seamLength * 0.12) : seamLength; + const viewWeight = splitOptions.viewAware ? 0.18 + projected.vr * 1.82 : 1; + candidates.push({ + key, + e: [pointKey(firstRefinable.a), pointKey(firstRefinable.b)], + o: owners, + r: refinable, + len: seamLength, + rank: rankLength, + proj: projected.proj, + s: rankLength * (0.58 + seamRisk * 2.8) * shapeRisk * bothSidesRefinable * viewWeight, + nr: normalRisk, + sr: shapeRisk, + vr: projected.vr, + comp: -1, + sel: false, + why: "below-threshold", + cost: refinable.length, + }); + } + + const parents = Array.from({ length: candidates.length }, (_, index) => index); + const byEndpoint = new Map(); + for (let index = 0; index < candidates.length; index += 1) { + for (const endpoint of candidates[index].e) { + const previous = byEndpoint.get(endpoint); + if (previous === undefined) { + byEndpoint.set(endpoint, index); + } else { + const rootA = unionFindRoot(parents, previous); + const rootB = unionFindRoot(parents, index); + if (rootA !== rootB) parents[rootB] = rootA; + } + } + } + + const componentIds = new Map(); + for (let index = 0; index < candidates.length; index += 1) { + const root = unionFindRoot(parents, index); + let component = componentIds.get(root); + if (component === undefined) { + component = componentIds.size; + componentIds.set(root, component); + } + candidates[index].comp = component; + } + + return candidates; +} + +function splitCandidateViewMetrics( + a: Edge, + b: Edge, + rotX: number, + rotY: number, +) { + const p0 = rotateCssVec3(a.a, rotX, 0, rotY); + const p1 = rotateCssVec3(a.b, rotX, 0, rotY); + const projectedLength = Math.hypot(p1[0] - p0[0], p1[1] - p0[1]); + const depthA = rotateCssVec3(a.normal, rotX, 0, rotY)[2]; + const depthB = rotateCssVec3(b.normal, rotX, 0, rotY)[2]; + const frontness = Math.max(0, depthA, depthB); + const silhouette = Math.min(1, Math.abs(depthA - depthB)); + return { + proj: projectedLength, + vr: Math.max(0.04, Math.min(1, frontness * 0.85 + silhouette * 0.45)), + }; +} + +function strongestCandidatesByComponent( + candidates: Cand[], +) { + const strongest = new Map(); + for (const candidate of candidates) { + const current = strongest.get(candidate.comp); + if (!current || candidate.s > current.s || (candidate.s === current.s && candidate.len > current.len)) { + strongest.set(candidate.comp, candidate); + } + } + return new Set(strongest.values()); +} + +function splitCandidateBudgetPriority(candidate: Cand) { + const coplanar = Math.max(0, 1 - Math.min(1, candidate.nr)); + const coplanarWeight = 0.35 + coplanar * coplanar * coplanar * 3.65; + const oneSidedWeight = candidate.r.length === 1 ? 1.08 : 1; + return (candidate.rank * coplanarWeight * oneSidedWeight) / Math.sqrt(Math.max(1, candidate.r.length)); +} + +function splitCandidateLikelyCrackPriority(candidate: Cand) { + const coplanar = Math.max(0, 1 - Math.min(1, candidate.nr)); + const visibleWeight = 0.35 + Math.min(1, candidate.vr) * 1.65; + const shapeWeight = 0.7 + Math.min(2.6, candidate.sr) * 0.3; + const oneSidedWeight = candidate.r.length === 1 ? 1.1 : 1; + const visiblePriority = ( + candidate.rank * + (0.6 + coplanar * coplanar * 1.4) * + visibleWeight * + shapeWeight * + oneSidedWeight + ) / Math.sqrt(Math.max(1, candidate.r.length)); + return Math.max(visiblePriority, splitCandidateBudgetPriority(candidate) * 0.75); +} + +function uniqueSplitPolygonCost(candidates: Cand[]) { + const polygons = new Set(); + for (const candidate of candidates) { + for (const record of candidate.r) polygons.add(record.polygon); + } + return polygons.size; +} + +function splitCandidateLikelyCrack(candidate: Cand, lengthStats: Dist) { + return candidate.nr <= 0.25 && + candidate.rank >= lengthStats.median * 1.08 && + candidate.proj >= 24; +} + +function splitCandidateGlobalSeed( + candidate: Cand, + strongScore: number, + strongLength: number, +) { + return candidate.s >= strongScore || candidate.rank >= strongLength; +} + +function seamFacetSplitBudgetPlan( + candidates: Cand[], + mode: SplitMode, + maxBudget: number, + scoreStats: Dist, + lengthStats: Dist, + strongScore: number, + strongLength: number, +) { + const budgetLimit = Math.max(0, Math.floor(maxBudget)); + if (budgetLimit <= 0 || candidates.length === 0 || mode === "follow-up") { + return { budgetLimit, componentBudgets: null }; + } + + const byComponent = new Map(); + for (const candidate of candidates) { + const group = byComponent.get(candidate.comp); + if (group) group.push(candidate); + else byComponent.set(candidate.comp, [candidate]); + } + + const componentBudgets = new Map(); + const scoreSpread = Math.max(EPS, scoreStats.q3 - scoreStats.q1); + const fallbackSeedScore = Math.min(scoreStats.max, Math.max(scoreStats.p95, scoreStats.q3 + scoreSpread)); + let total = 0; + for (const [component, group] of byComponent) { + const primary = group.filter((candidate) => + splitCandidateGlobalSeed(candidate, strongScore, strongLength) || + candidate.s >= fallbackSeedScore + ); + if (primary.length === 0) continue; + + const likely = group.filter((candidate) => splitCandidateLikelyCrack(candidate, lengthStats)); + const primaryCost = uniqueSplitPolygonCost(primary); + const likelyCost = uniqueSplitPolygonCost(likely); + const followUpAllowance = Math.ceil(Math.sqrt(Math.max(0, likelyCost - primaryCost)) * 3); + const componentBudget = Math.min( + uniqueSplitPolygonCost(group), + primaryCost + followUpAllowance, + ); + if (componentBudget <= 0) continue; + componentBudgets.set(component, componentBudget); + total += componentBudget; + } + + if (componentBudgets.size === 0) return { budgetLimit: 0, componentBudgets }; + return { + budgetLimit: Math.min(budgetLimit, total), + componentBudgets, + }; +} + +function selectSeamFacetSplitCandidates( + candidates: Cand[], + mode: SplitMode, + budget: number, +) { + const selected = new Map>(); + if (candidates.length === 0 || budget <= 0) return { selected, budgetLimit: 0 }; + + const scoreStats = numericDistribution(candidates.map((candidate) => candidate.s)); + const lengthStats = numericDistribution(candidates.map((candidate) => candidate.rank)); + const scoreSpread = Math.max(EPS, scoreStats.q3 - scoreStats.q1); + const strongScore = Math.min(scoreStats.max, Math.max(scoreStats.p95, scoreStats.q3 + scoreSpread * 0.85)); + const anchorScore = Math.min(scoreStats.max, Math.max(scoreStats.p80, scoreStats.q3 + scoreSpread * 0.15)); + const sharedPolygonScore = Math.min(scoreStats.max, Math.max(scoreStats.p70, scoreStats.q3)); + const strongLength = Math.max(lengthStats.p97, lengthStats.median * 1.8); + const anchorLength = Math.max(lengthStats.p88, lengthStats.median * 1.35); + const budgetPlan = seamFacetSplitBudgetPlan( + candidates, + mode, + budget, + scoreStats, + lengthStats, + strongScore, + strongLength, + ); + let remainingBudget = budgetPlan.budgetLimit; + if (remainingBudget <= 0) return { selected, budgetLimit: 0 }; + + const anchors = strongestCandidatesByComponent(candidates); + const alreadySplit = new Set(); + const selectedEndpoints = new Set(); + const selectedComponents = new Set(); + const componentSpend = new Map(); + const localReserve = mode === "primary" + ? Math.min(Math.max(0, budgetPlan.budgetLimit - 1), Math.max(2, Math.floor(budgetPlan.budgetLimit * 0.28))) + : 0; + + const sorted = [...candidates].sort((a, b) => + splitCandidateBudgetPriority(b) - splitCandidateBudgetPriority(a) || + (b.s / Math.max(1, b.r.length)) - (a.s / Math.max(1, a.r.length)) || + b.len - a.len + ); + const likelyCrackSorted = [...candidates].sort((a, b) => + splitCandidateLikelyCrackPriority(b) - splitCandidateLikelyCrackPriority(a) || + splitCandidateBudgetPriority(b) - splitCandidateBudgetPriority(a) || + b.len - a.len + ); + + const selectCandidate = (candidate: Cand, reason: SplitReason) => { + candidate.sel = true; + candidate.why = reason; + selectedComponents.add(candidate.comp); + for (const endpoint of candidate.e) selectedEndpoints.add(endpoint); + for (const record of candidate.r) { + alreadySplit.add(record.polygon); + const edges = selected.get(record.polygon); + if (edges) edges.add(record.edge); + else selected.set(record.polygon, new Set([record.edge])); + } + }; + + const withinComponentBudget = (candidate: Cand, marginalCost: number) => { + const componentBudgets = budgetPlan.componentBudgets; + if (marginalCost <= 0 || !componentBudgets) return true; + const componentBudget = componentBudgets.get(candidate.comp) ?? 0; + return (componentSpend.get(candidate.comp) ?? 0) + marginalCost <= componentBudget; + }; + + const recordComponentSpend = (candidate: Cand, marginalCost: number) => { + if (marginalCost <= 0 || !budgetPlan.componentBudgets) return; + componentSpend.set(candidate.comp, (componentSpend.get(candidate.comp) ?? 0) + marginalCost); + }; + + for (const candidate of likelyCrackSorted) { + const marginalCost = candidate.r.reduce( + (total, record) => total + (alreadySplit.has(record.polygon) ? 0 : 1), + 0, + ); + candidate.cost = marginalCost; + if (marginalCost > remainingBudget) continue; + if (!withinComponentBudget(candidate, marginalCost)) continue; + if (marginalCost > 0 && remainingBudget - marginalCost < localReserve) continue; + const isLikelyCrack = splitCandidateLikelyCrack(candidate, lengthStats); + if (!isLikelyCrack) continue; + selectCandidate(candidate, "global-outlier"); + recordComponentSpend(candidate, marginalCost); + remainingBudget -= marginalCost; + if (remainingBudget <= 0) return { selected, budgetLimit: budgetPlan.budgetLimit }; + } + + for (const candidate of sorted) { + if (candidate.sel) continue; + const marginalCost = candidate.r.reduce( + (total, record) => total + (alreadySplit.has(record.polygon) ? 0 : 1), + 0, + ); + candidate.cost = marginalCost; + if (marginalCost > remainingBudget) continue; + if (!withinComponentBudget(candidate, marginalCost)) continue; + if (marginalCost > 0 && remainingBudget - marginalCost < localReserve) continue; + + const twoSided = candidate.r.length === 2; + const isAnchor = anchors.has(candidate) && ( + mode === "primary" || + (mode === "follow-up" && candidate.s >= anchorScore * 1.08 && candidate.rank >= anchorLength) + ) && ( + twoSided + ? candidate.s >= anchorScore || candidate.rank >= anchorLength + : candidate.s >= anchorScore * 1.18 || candidate.rank >= anchorLength * 1.12 + ); + const isGlobalOutlier = twoSided + ? candidate.s >= strongScore || candidate.rank >= strongLength + : candidate.s >= strongScore * 1.35 || candidate.rank >= strongLength * 1.2; + const isSharedPolygonFollowUp = marginalCost === 0 && ( + twoSided + ? candidate.s >= sharedPolygonScore || candidate.rank >= anchorLength + : candidate.s >= sharedPolygonScore * 1.25 || candidate.rank >= anchorLength * 1.12 + ); + if (!isAnchor && !isGlobalOutlier && !isSharedPolygonFollowUp) continue; + + selectCandidate(candidate, isAnchor + ? "component-anchor" + : isGlobalOutlier + ? "global-outlier" + : "shared-polygon"); + recordComponentSpend(candidate, marginalCost); + remainingBudget -= marginalCost; + if (remainingBudget <= 0) return { selected, budgetLimit: budgetPlan.budgetLimit }; + } + + for (const candidate of sorted) { + if (candidate.sel) continue; + const marginalCost = candidate.r.reduce( + (total, record) => total + (alreadySplit.has(record.polygon) ? 0 : 1), + 0, + ); + candidate.cost = marginalCost; + if (marginalCost > 1 || marginalCost > remainingBudget) continue; + if (!withinComponentBudget(candidate, marginalCost)) continue; + const touchesSelectedPolygon = candidate.r.some((record) => alreadySplit.has(record.polygon)); + const touchesSelectedEndpoint = candidate.e.some((endpoint) => selectedEndpoints.has(endpoint)); + const isOneSidedTail = mode === "primary" && + candidate.r.length === 1 && + marginalCost === 1 && + (selectedComponents.has(candidate.comp) || touchesSelectedEndpoint || touchesSelectedPolygon) && + candidate.rank >= anchorLength * 1.05 && + candidate.nr >= 0.16 && + candidate.vr <= 0.32; + if (isOneSidedTail) { + selectCandidate(candidate, "local-follow-up"); + recordComponentSpend(candidate, marginalCost); + remainingBudget -= marginalCost; + if (remainingBudget <= 0) return { selected, budgetLimit: budgetPlan.budgetLimit }; + continue; + } + if (candidate.r.length !== 2) continue; + const isProjectedNeighbor = touchesSelectedPolygon && + marginalCost === 1 && + candidate.proj >= anchorLength * 1.45 && + candidate.vr <= 0.18; + if (!touchesSelectedEndpoint && !isProjectedNeighbor) continue; + const isLocalFollowUp = ( + candidate.s >= sharedPolygonScore * 0.42 || + candidate.rank >= anchorLength * 0.62 + ) && candidate.s <= sharedPolygonScore * 1.1 && candidate.proj >= 24; + if (isLocalFollowUp) { + selectCandidate(candidate, "local-follow-up"); + recordComponentSpend(candidate, marginalCost); + remainingBudget -= marginalCost; + if (remainingBudget <= 0) return { selected, budgetLimit: budgetPlan.budgetLimit }; + } + } + + return { selected, budgetLimit: budgetPlan.budgetLimit }; +} + +export function seamFacetSplitPlan( + polygons: Polygon[], + seamOptions: Overlap, + splitOptions: Split, + budget: number, + followUpContext?: FollowUp, +) { + const metas = buildPolygonMetas(polygons); + const records = buildEdgeRecords(polygons, metas, seamOptions.capacityScale); + const edgeOwners = new Map(); + for (const record of records) { + const owners = edgeOwners.get(record.key); + if (owners) owners.push(record); + else edgeOwners.set(record.key, [record]); + } + + const candidates = buildSeamFacetSplitCandidates(polygons, metas, edgeOwners, splitOptions) + .filter((candidate) => splitCandidateTouchesFollowUp(candidate, followUpContext)); + const selection = selectSeamFacetSplitCandidates(candidates, followUpContext ? "follow-up" : "primary", budget); + return { selected: selection.selected, candidates, budgetLimit: selection.budgetLimit }; +} + +export function applySeamFacetSplitSelection( + polygons: Polygon[], + selected: ReadonlyMap>, +) { + const out: Polygon[] = []; + for (let i = 0; i < polygons.length; i += 1) { + const polygon = polygons[i]; + const edges = selected.get(i); + if (edges && isRefinableSeamQuad(polygon)) out.push(...splitQuadIntoTriangles(polygon, edges)); + else out.push(polygon); + } + return out; +} + +export function seamFacetSplitPublicCandidate(candidate: Cand) { + const [a, b] = candidate.o; + const first = a ?? b; + const second = b ?? a; + return { + key: candidate.key, + aPolygon: first?.polygon ?? -1, + aEdge: first?.edge ?? -1, + bPolygon: second?.polygon ?? -1, + bEdge: second?.edge ?? -1, + color: first?.color ?? second?.color, + materialKey: first?.materialKey ?? second?.materialKey ?? "", + lengthPx: candidate.len, + projectedLengthPx: candidate.proj, + score: candidate.s, + normalRisk: candidate.nr, + shapeRisk: candidate.sr, + viewRisk: candidate.vr, + component: candidate.comp, + marginalCost: candidate.cost, + selected: candidate.sel, + reason: candidate.why, + }; +} diff --git a/packages/core/src/merge/seamRepair/geometry.ts b/packages/core/src/merge/seamRepair/geometry.ts new file mode 100644 index 000000000..d04b593c4 --- /dev/null +++ b/packages/core/src/merge/seamRepair/geometry.ts @@ -0,0 +1,333 @@ +import { signedArea2D as signedArea } from "../../atlas/solidTriangle"; +import { crossVec as cross } from "../../math/vec3"; +import type { Polygon, Vec3 } from "../../types"; +import type { + SeamFacetSplitOptions as SplitOptions, + SeamOverlapOptions as OverlapOptions, +} from "../seamRepairTypes"; + +export type Vec2 = [number, number]; + +export type Basis = { origin: Vec3; normal: Vec3; xAxis: Vec3; yAxis: Vec3; local: Vec2[]; area: number }; + +export type Meta = { basis: Basis | null; cssPoints: Vec3[]; capacities: number[]; patchable: boolean }; + +export type Edge = { + index: number; + polygon: number; + edge: number; + key: string; + a: Vec3; + b: Vec3; + minX: number; + minY: number; + minZ: number; + maxX: number; + maxY: number; + maxZ: number; + length: number; + dir: Vec3; + normal: Vec3; + outward: Vec3; + capacity: number; + materialKey: string; + color?: string; +}; + +export type Near = { gap: number; facingA: number; facingB: number; aStart: number; aEnd: number; bStart: number; bEnd: number }; + +export type Repair = { start: number; end: number; amount: number }; + +export type Split = { rotX: number; rotY: number; viewAware: boolean; passes: number; budget: number }; + +export type Overlap = { overlapPx: number; maxGapPx: number; capacityScale: number }; + +export const DEFAULT_TILE = 50; +export const MAX_NEAR_SEAM_GAP_PX = 14; +export const DEFAULT_SEAM_SPLIT_BUDGET = 40; +export const TRUE_GAP_OVERLAP_AMOUNT_RATIO = 0.175; +export const DEFAULT_TRUE_GAP_OVERLAP_PX = 1.25; +export const EPS = 1e-6; +export const TOPOLOGY_EPS = 1e-4; + +function finiteOr(value: number | undefined, fallback: number) { + return typeof value === "number" && Number.isFinite(value) ? value : fallback; +} + +export function resolveSeamOverlapOptions( + options?: number | OverlapOptions, +) { + if (typeof options === "number") { + return { + overlapPx: Math.max(0, options) * TRUE_GAP_OVERLAP_AMOUNT_RATIO, + maxGapPx: MAX_NEAR_SEAM_GAP_PX, + capacityScale: 1, + }; + } + + return { + overlapPx: Math.max(0, finiteOr(options?.overlapPx, DEFAULT_TRUE_GAP_OVERLAP_PX)), + maxGapPx: Math.max(0, finiteOr(options?.maxGapPx, MAX_NEAR_SEAM_GAP_PX)), + capacityScale: Math.max(0, finiteOr(options?.capacityScale, 1)), + }; +} + +export function seamOverlapEnabled( + options: Overlap, + rawOptions?: number | OverlapOptions, +) { + return !(typeof rawOptions === "number" && rawOptions <= 0) && options.maxGapPx > EPS && options.capacityScale > EPS; +} + +export function resolveSeamFacetSplitOptions(options?: SplitOptions) { + return { + rotX: finiteOr(options?.rotX, 65), + rotY: finiteOr(options?.rotY, 45), + viewAware: options?.viewAware !== false, + passes: Math.max(1, Math.min(3, Math.round(finiteOr(options?.passes, 2)))), + budget: Math.max(0, Math.min(256, Math.round(finiteOr(options?.budget, DEFAULT_SEAM_SPLIT_BUDGET)))), + }; +} + +export function cssPoints(vertices: Vec3[]): Vec3[] { + return vertices.map((v): Vec3 => [v[1] * DEFAULT_TILE, v[0] * DEFAULT_TILE, v[2] * DEFAULT_TILE]); +} + +export function fromCssPoint(point: Vec3): Vec3 { + return [point[1] / DEFAULT_TILE, point[0] / DEFAULT_TILE, point[2] / DEFAULT_TILE]; +} + +export function pointKey(point: Vec3) { + return `${point[0]},${point[1]},${point[2]}`; +} + +export function edgeKey(a: Vec3, b: Vec3) { + const ak = pointKey(a); + const bk = pointKey(b); + return ak < bk ? `${ak}|${bk}` : `${bk}|${ak}`; +} + +export function sub(a: Vec3, b: Vec3): Vec3 { + return [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; +} + +export function length(a: Vec3) { + return Math.hypot(a[0], a[1], a[2]); +} + +export function normalize(a: Vec3): Vec3 | null { + const len = length(a); + return len > EPS ? [a[0] / len, a[1] / len, a[2] / len] : null; +} + +export function dot(a: Vec3, b: Vec3) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +} + +export function surfaceNormal(points: Vec3[]): Vec3 | null { + if (points.length < 3) return null; + const origin = points[0]; + const normal: Vec3 = [0, 0, 0]; + for (let i = 1; i + 1 < points.length; i += 1) { + const a = sub(points[i], origin); + const b = sub(points[i + 1], origin); + const n = cross(a, b); + normal[0] -= n[0]; + normal[1] -= n[1]; + normal[2] -= n[2]; + } + return normalize(normal); +} + +export function localBasis(points: Vec3[]): Basis | null { + const origin = points[0]; + const normal = surfaceNormal(points); + if (!normal) return null; + + let rawXAxis: Vec3 | null = null; + for (let i = 0; i < points.length; i += 1) { + const edge = sub(points[(i + 1) % points.length], points[i]); + if (length(edge) > EPS) { + rawXAxis = edge; + break; + } + } + if (!rawXAxis) return null; + + const projected = dot(rawXAxis, normal); + const xRaw: Vec3 = [ + rawXAxis[0] - projected * normal[0], + rawXAxis[1] - projected * normal[1], + rawXAxis[2] - projected * normal[2], + ]; + const xAxis = normalize(xRaw); + if (!xAxis) return null; + const yAxis = normalize(cross(normal, xAxis)); + if (!yAxis) return null; + + const local = points.map((point): Vec2 => { + const d = sub(point, origin); + return [dot(d, xAxis), dot(d, yAxis)]; + }); + const area = signedArea(local); + return Math.abs(area) > EPS ? { origin, normal, xAxis, yAxis, local, area } : null; +} + +export function isWeaklyConvex(points: Vec2[]) { + if (points.length < 3) return false; + let sign = 0; + for (let i = 0; i < points.length; i += 1) { + const a = points[i]; + const b = points[(i + 1) % points.length]; + const c = points[(i + 2) % points.length]; + const crossValue = (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]); + if (Math.abs(crossValue) <= EPS) continue; + const nextSign = Math.sign(crossValue); + if (sign === 0) sign = nextSign; + else if (nextSign !== sign) return false; + } + return true; +} + +export function edgeOutward2D(points: Vec2[], area: number, edgeIndex: number): Vec2 | null { + const a = points[edgeIndex]; + const b = points[(edgeIndex + 1) % points.length]; + const dx = b[0] - a[0]; + const dy = b[1] - a[1]; + const edgeLength = Math.hypot(dx, dy); + if (edgeLength <= EPS) return null; + const outwardSign = area > 0 ? 1 : -1; + return [ + outwardSign * (dy / edgeLength), + outwardSign * (-dx / edgeLength), + ]; +} + +export function edgeOutward3D(basis: Basis, edgeIndex: number): Vec3 | null { + const outward = edgeOutward2D(basis.local, basis.area, edgeIndex); + if (!outward) return null; + return normalize([ + basis.xAxis[0] * outward[0] + basis.yAxis[0] * outward[1], + basis.xAxis[1] * outward[0] + basis.yAxis[1] * outward[1], + basis.xAxis[2] * outward[0] + basis.yAxis[2] * outward[1], + ]); +} + +export function edgeSafeCapacity(points: Vec2[], edgeIndex: number) { + const count = points.length; + const a = points[edgeIndex]; + const b = points[(edgeIndex + 1) % count]; + const dx = b[0] - a[0]; + const dy = b[1] - a[1]; + const edgeLength = Math.hypot(dx, dy); + if (edgeLength <= EPS) return 0; + + const limits = [edgeLength * 0.24]; + let oppositeClearance = Infinity; + for (let i = 0; i < count; i += 1) { + if (i === edgeIndex || i === (edgeIndex + 1) % count) continue; + const p = points[i]; + const distance = Math.abs((p[0] - a[0]) * dy - (p[1] - a[1]) * dx) / edgeLength; + if (distance > EPS) oppositeClearance = Math.min(oppositeClearance, distance); + } + if (Number.isFinite(oppositeClearance)) limits.push(oppositeClearance * 0.32); + + const adjacentChecks: Array<{ origin: Vec2; point: Vec2 }> = [ + { origin: a, point: points[(edgeIndex + count - 1) % count] }, + { origin: b, point: points[(edgeIndex + 2) % count] }, + ]; + for (const adjacent of adjacentChecks) { + const adx = adjacent.point[0] - adjacent.origin[0]; + const ady = adjacent.point[1] - adjacent.origin[1]; + const adjacentLength = Math.hypot(adx, ady); + if (adjacentLength <= EPS) continue; + const sin = Math.abs(dx * ady - dy * adx) / (edgeLength * adjacentLength); + if (sin > EPS) limits.push(adjacentLength * sin * 0.32); + } + + return Math.min(...limits); +} + +export function buildPolygonMetas(polygons: Polygon[]) { + return polygons.map((polygon): Meta => { + const css = cssPoints(polygon.vertices); + const basis = localBasis(css); + const patchable = !hasTexture(polygon) && !!basis && isWeaklyConvex(basis.local); + const capacities = patchable + ? basis!.local.map((_, edgeIndex) => edgeSafeCapacity(basis!.local, edgeIndex)) + : []; + return { + basis, + cssPoints: css, + capacities, + patchable, + }; + }); +} + +export function hasTexture(polygon: Polygon) { + return !!(polygon.texture || polygon.material?.texture || polygon.textureTriangles?.length); +} + +export function materialKey(polygon: Polygon) { + return polygon.material?.key ?? polygon.color ?? ""; +} + +export function buildEdgeRecords( + polygons: Polygon[], + metas: Meta[], + capacityScale: number, +) { + const records: Edge[] = []; + for (let polygonIndex = 0; polygonIndex < metas.length; polygonIndex += 1) { + const meta = metas[polygonIndex]; + if (!meta.patchable || !meta.basis) continue; + for (let edgeIndex = 0; edgeIndex < meta.cssPoints.length; edgeIndex += 1) { + const a = meta.cssPoints[edgeIndex]; + const b = meta.cssPoints[(edgeIndex + 1) % meta.cssPoints.length]; + const edge = sub(b, a); + const edgeLength = length(edge); + const dir = normalize(edge); + const outward = edgeOutward3D(meta.basis, edgeIndex); + const capacity = (meta.capacities[edgeIndex] ?? 0) * capacityScale; + if (!dir || !outward || capacity <= EPS || edgeLength <= EPS) continue; + records.push({ + index: records.length, + polygon: polygonIndex, + edge: edgeIndex, + key: edgeKey(a, b), + a, + b, + minX: Math.min(a[0], b[0]), + minY: Math.min(a[1], b[1]), + minZ: Math.min(a[2], b[2]), + maxX: Math.max(a[0], b[0]), + maxY: Math.max(a[1], b[1]), + maxZ: Math.max(a[2], b[2]), + length: edgeLength, + dir, + normal: meta.basis.normal, + outward, + capacity, + materialKey: materialKey(polygons[polygonIndex]), + color: polygons[polygonIndex].color, + }); + } + } + return records; +} + +export function compatibleRepairMaterials(a: Edge, b: Edge) { + return a.materialKey === b.materialKey && a.color === b.color; +} + +export function sameTopologyPoint(a: Vec3, b: Vec3) { + return length(sub(a, b)) <= TOPOLOGY_EPS; +} + +export function edgeRecordsTouch(a: Edge, b: Edge) { + return sameTopologyPoint(a.a, b.a) || + sameTopologyPoint(a.a, b.b) || + sameTopologyPoint(a.b, b.a) || + sameTopologyPoint(a.b, b.b); +} diff --git a/packages/core/src/merge/seamRepair/nearSeam.ts b/packages/core/src/merge/seamRepair/nearSeam.ts new file mode 100644 index 000000000..a6c4defe4 --- /dev/null +++ b/packages/core/src/merge/seamRepair/nearSeam.ts @@ -0,0 +1,512 @@ +import { signedArea2D as signedArea } from "../../atlas/solidTriangle"; +import { boundsOverlap3D as edgeBoundsCouldOverlap } from "../../math/vec3"; +import type { Polygon, Vec3 } from "../../types"; +import type { + SeamOverlapCandidate as OverlapCandidate, + SeamOverlapCandidateKind as OverlapKind, + SeamOverlapDiagnostics as OverlapDiagnostics, +} from "../seamRepairTypes"; +import { + buildEdgeRecords, + buildPolygonMetas, + compatibleRepairMaterials, + cssPoints, + dot, + edgeOutward2D, + edgeRecordsTouch, + edgeSafeCapacity, + EPS, + fromCssPoint, + hasTexture, + isWeaklyConvex, + localBasis, + MAX_NEAR_SEAM_GAP_PX, +} from "./geometry"; +import type { Edge, Near, Overlap, Repair, Vec2 } from "./geometry"; + +const MIN_RESIDUAL_PATCH_GAP_PX = 0.25; +const MIN_PARALLEL_DOT = 0.985; +const MIN_FACING_DOT = 0.5; +const NEAR_SEAM_SWEEP_RECORD_LIMIT = 10000; +const NEAR_SEAM_SWEEP_PAIR_LIMIT = 2_000_000; +const NEAR_SEAM_EXTENDED_SWEEP_PAIR_LIMIT = 25_000_000; +const NEAR_SEAM_GRID_AVG_CELLS_PER_RECORD_LIMIT = 256; +const NEAR_SEAM_GRID_MAX_CELLS_PER_RECORD_LIMIT = 8192; + +function classifyCandidate(a: Edge, b: Edge) { + return compatibleRepairMaterials(a, b) + ? edgeRecordsTouch(a, b) ? "connected-facet" : "true-gap" + : "material-boundary"; +} + +function seamOverlapCandidate( + kind: OverlapKind, + a: Edge, + b: Edge, + info: Near, + targetClosurePx: number, + appliedClosurePx: number, +) { + return { + kind, + aPolygon: a.polygon, + aEdge: a.edge, + bPolygon: b.polygon, + bEdge: b.edge, + aColor: a.color, + bColor: b.color, + aMaterialKey: a.materialKey, + bMaterialKey: b.materialKey, + gapPx: info.gap, + spanPx: info.aEnd - info.aStart, + aStartPx: info.aStart, + aEndPx: info.aEnd, + bStartPx: info.bStart, + bEndPx: info.bEnd, + targetClosurePx, + appliedClosurePx, + residualGapPx: Math.max(0, info.gap - appliedClosurePx), + residualTargetPx: Math.max(0, targetClosurePx - appliedClosurePx), + }; +} + +function addEdgeRepair( + repairs: Array>, + record: Edge, + start: number, + end: number, + amount: number, +) { + const clippedStart = Math.max(0, Math.min(record.length, Math.min(start, end))); + const clippedEnd = Math.max(0, Math.min(record.length, Math.max(start, end))); + if (amount <= EPS || clippedEnd - clippedStart <= EPS) return; + const current = repairs[record.polygon].get(record.edge); + const segment = { start: clippedStart, end: clippedEnd, amount }; + if (current) current.push(segment); + else repairs[record.polygon].set(record.edge, [segment]); +} + +export function emptyDiagnostics() { + return { + exactPairs: 0, + nearPairs: 0, + patchedPolygons: 0, + patchedEdges: 0, + maxMeasuredGapPx: 0, + maxAppliedAmountPx: 0, + unclosedPairs: 0, + maxResidualGapPx: 0, + }; +} + +function finishDiagnostics( + repairs: Array>, + diagnostics: OverlapDiagnostics, +) { + let maxAppliedAmountPx = 0; + let patchedEdges = 0; + let patchedPolygons = 0; + for (const polygonRepairs of repairs) { + if (polygonRepairs.size > 0) patchedPolygons += 1; + patchedEdges += polygonRepairs.size; + for (const segments of polygonRepairs.values()) { + for (const segment of segments) { + maxAppliedAmountPx = Math.max(maxAppliedAmountPx, segment.amount); + } + } + } + return { + ...diagnostics, + patchedPolygons, + patchedEdges, + maxAppliedAmountPx, + }; +} + +export function buildSeamEdgeAmounts( + polygons: Polygon[], + options: Overlap, + collectCandidates = false, + diagnosticsOnly = false, +) { + const metas = buildPolygonMetas(polygons); + const records = buildEdgeRecords(polygons, metas, options.capacityScale); + const repairs = diagnosticsOnly ? [] : polygons.map(() => new Map()); + const diagnostics = emptyDiagnostics(); + const candidates = collectCandidates ? [] as OverlapCandidate[] : undefined; + if (records.length === 0) { + return { edgeRepairs: repairs, diagnostics, candidates }; + } + + const edgeOwners = new Map(); + for (const record of records) { + const owners = edgeOwners.get(record.key); + if (owners) owners.push(record); + else edgeOwners.set(record.key, [record]); + } + + for (const owners of edgeOwners.values()) { + if (owners.length < 2) continue; + diagnostics.exactPairs += owners.length === 2 ? 1 : owners.length; + } + + buildNearSeamEdgeAmounts(records, edgeOwners, repairs, diagnostics, options, candidates); + return { + edgeRepairs: repairs, + diagnostics: diagnosticsOnly ? diagnostics : finishDiagnostics(repairs, diagnostics), + candidates, + }; +} + +function buildNearSeamEdgeAmounts( + records: Edge[], + edgeOwners: ReadonlyMap, + repairs: Array>, + diagnostics: OverlapDiagnostics, + options: Overlap, + candidates: OverlapCandidate[] | undefined, +) { + const maxGap = options.maxGapPx; + const exactSharedKeys = new Set(); + for (const [key, owners] of edgeOwners) { + if (owners.length > 1) exactSharedKeys.add(key); + } + + const measurePair = (first: Edge, second: Edge) => { + const record = first.index < second.index ? first : second; + const candidate = first.index < second.index ? second : first; + if (candidate.polygon === record.polygon) return; + if (record.key === candidate.key && exactSharedKeys.has(record.key)) return; + if (!candidates && !compatibleRepairMaterials(record, candidate)) return; + if (!edgeBoundsCouldOverlap(record, candidate, maxGap)) return; + if (Math.abs(dot(record.dir, candidate.dir)) < MIN_PARALLEL_DOT) return; + + const info = nearSeamInfo(record, candidate, maxGap); + if (!info) return; + const kind = classifyCandidate(record, candidate); + const targetClosure = info.gap + options.overlapPx; + if (kind === "material-boundary") { + candidates?.push(seamOverlapCandidate(kind, record, candidate, info, targetClosure, 0)); + return; + } + + let remainingClosure = targetClosure; + if (remainingClosure <= MIN_RESIDUAL_PATCH_GAP_PX) { + candidates?.push(seamOverlapCandidate(kind, record, candidate, info, targetClosure, 0)); + return; + } + + const maxClosureA = record.capacity * info.facingA; + const maxClosureB = candidate.capacity * info.facingB; + let closureA = Math.min(maxClosureA, remainingClosure / 2); + let closureB = Math.min(maxClosureB, remainingClosure / 2); + remainingClosure -= closureA + closureB; + if (remainingClosure > EPS) { + const extraA = Math.min(maxClosureA - closureA, remainingClosure); + closureA += extraA; + remainingClosure -= extraA; + } + if (remainingClosure > EPS) { + const extraB = Math.min(maxClosureB - closureB, remainingClosure); + closureB += extraB; + remainingClosure -= extraB; + } + + candidates?.push(seamOverlapCandidate(kind, record, candidate, info, targetClosure, closureA + closureB)); + if (repairs.length > 0 && closureA > EPS) { + addEdgeRepair(repairs, record, info.aStart, info.aEnd, closureA / info.facingA); + } + if (repairs.length > 0 && closureB > EPS) { + addEdgeRepair(repairs, candidate, info.bStart, info.bEnd, closureB / info.facingB); + } + diagnostics.nearPairs += 1; + diagnostics.maxMeasuredGapPx = Math.max(diagnostics.maxMeasuredGapPx, info.gap); + if (remainingClosure > MIN_RESIDUAL_PATCH_GAP_PX) { + diagnostics.unclosedPairs += 1; + diagnostics.maxResidualGapPx = Math.max(diagnostics.maxResidualGapPx, remainingClosure); + } + }; + + const cellSize = Math.max(MAX_NEAR_SEAM_GAP_PX * 2, maxGap * 2); + + if (records.length <= NEAR_SEAM_SWEEP_RECORD_LIMIT) { + const sorted = [...records].sort((a, b) => a.minX - b.minX); + const sweepEnds = new Int32Array(sorted.length); + let sweepPairCount = 0; + for (let i = 0; i + 1 < sorted.length; i += 1) { + const record = sorted[i]; + const maxX = record.maxX + maxGap; + let end = i + 1; + while (end < sorted.length && sorted[end].minX <= maxX) end += 1; + sweepEnds[i] = end; + sweepPairCount += end - i - 1; + if (sweepPairCount > NEAR_SEAM_EXTENDED_SWEEP_PAIR_LIMIT) break; + } + if ( + sweepPairCount <= NEAR_SEAM_SWEEP_PAIR_LIMIT || + ( + sweepPairCount <= NEAR_SEAM_EXTENDED_SWEEP_PAIR_LIMIT && + shouldUseExtendedSweep(records, cellSize, maxGap) + ) + ) { + for (let i = 0; i + 1 < sorted.length; i += 1) { + for (let j = i + 1; j < sweepEnds[i]; j += 1) { + measurePair(sorted[i], sorted[j]); + } + } + return; + } + } + + const cells = new Map(); + for (const record of records) { + addRecordToSegmentCells(cells, record, cellSize, maxGap); + } + + const seenPairs = new Set(); + const recordCount = records.length; + for (const bucket of cells.values()) { + for (let i = 0; i + 1 < bucket.length; i += 1) { + for (let j = i + 1; j < bucket.length; j += 1) { + const first = bucket[i]; + const second = bucket[j]; + const record = first.index < second.index ? first : second; + const candidate = first.index < second.index ? second : first; + const pairKey = record.index * recordCount + candidate.index; + if (seenPairs.has(pairKey)) continue; + seenPairs.add(pairKey); + measurePair(record, candidate); + } + } + } +} + +function cellCoords(point: Vec3, cellSize: number): [number, number, number] { + return [ + Math.floor(point[0] / cellSize), + Math.floor(point[1] / cellSize), + Math.floor(point[2] / cellSize), + ]; +} + +function addRecordToSegmentCells( + cells: Map, + record: Edge, + cellSize: number, + padding: number, +) { + const [minCx, minCy, minCz, maxCx, maxCy, maxCz] = recordSegmentCellBounds(record, cellSize, padding); + for (let x = minCx; x <= maxCx; x += 1) { + for (let y = minCy; y <= maxCy; y += 1) { + for (let z = minCz; z <= maxCz; z += 1) { + const key = `${x},${y},${z}`; + const bucket = cells.get(key); + if (bucket) bucket.push(record); + else cells.set(key, [record]); + } + } + } +} + +function recordSegmentCellBounds(record: Edge, cellSize: number, padding: number): [number, number, number, number, number, number] { + const [minCx, minCy, minCz] = cellCoords([record.minX - padding, record.minY - padding, record.minZ - padding], cellSize); + const [maxCx, maxCy, maxCz] = cellCoords([record.maxX + padding, record.maxY + padding, record.maxZ + padding], cellSize); + return [minCx, minCy, minCz, maxCx, maxCy, maxCz]; +} + +function recordSegmentCellCount(record: Edge, cellSize: number, padding: number) { + const [minCx, minCy, minCz, maxCx, maxCy, maxCz] = recordSegmentCellBounds(record, cellSize, padding); + return (maxCx - minCx + 1) * (maxCy - minCy + 1) * (maxCz - minCz + 1); +} + +function shouldUseExtendedSweep( + records: Edge[], + cellSize: number, + padding: number, +) { + let totalCells = 0; + let maxCells = 0; + for (const record of records) { + const cells = recordSegmentCellCount(record, cellSize, padding); + totalCells += cells; + if (cells > maxCells) maxCells = cells; + if (maxCells > NEAR_SEAM_GRID_MAX_CELLS_PER_RECORD_LIMIT) return true; + } + return totalCells / Math.max(1, records.length) > NEAR_SEAM_GRID_AVG_CELLS_PER_RECORD_LIMIT; +} + +function dotFromPointToEdge(point: Vec3, edgeOrigin: Vec3, edgeDir: Vec3) { + return ( + (point[0] - edgeOrigin[0]) * edgeDir[0] + + (point[1] - edgeOrigin[1]) * edgeDir[1] + + (point[2] - edgeOrigin[2]) * edgeDir[2] + ); +} + +function dotEdgePointToEdge(source: Edge, distance: number, target: Edge) { + return ( + (source.a[0] + source.dir[0] * distance - target.a[0]) * target.dir[0] + + (source.a[1] + source.dir[1] * distance - target.a[1]) * target.dir[1] + + (source.a[2] + source.dir[2] * distance - target.a[2]) * target.dir[2] + ); +} + +function nearSeamInfo(a: Edge, b: Edge, maxGap: number) { + const bStart = dotFromPointToEdge(b.a, a.a, a.dir); + const bEnd = dotFromPointToEdge(b.b, a.a, a.dir); + const overlapStart = Math.max(0, Math.min(bStart, bEnd)); + const overlapEnd = Math.min(a.length, Math.max(bStart, bEnd)); + const overlap = overlapEnd - overlapStart; + const minLength = Math.min(a.length, b.length); + if (overlap < Math.max(0.75, minLength * 0.12)) return null; + + const aMidT = (overlapStart + overlapEnd) / 2; + const aMidX = a.a[0] + a.dir[0] * aMidT; + const aMidY = a.a[1] + a.dir[1] * aMidT; + const aMidZ = a.a[2] + a.dir[2] * aMidT; + const bT = Math.max(0, Math.min( + b.length, + (aMidX - b.a[0]) * b.dir[0] + + (aMidY - b.a[1]) * b.dir[1] + + (aMidZ - b.a[2]) * b.dir[2], + )); + const gapX = b.a[0] + b.dir[0] * bT - aMidX; + const gapY = b.a[1] + b.dir[1] * bT - aMidY; + const gapZ = b.a[2] + b.dir[2] * bT - aMidZ; + const gap = Math.hypot(gapX, gapY, gapZ); + if (gap <= EPS) return null; + if (gap > maxGap) return null; + if (gap > Math.min(maxGap, Math.max(4, minLength * 0.28))) return null; + + const invGap = 1 / gap; + const gapDirX = gapX * invGap; + const gapDirY = gapY * invGap; + const gapDirZ = gapZ * invGap; + const facingA = a.outward[0] * gapDirX + a.outward[1] * gapDirY + a.outward[2] * gapDirZ; + const facingB = -(b.outward[0] * gapDirX + b.outward[1] * gapDirY + b.outward[2] * gapDirZ); + if (facingA < MIN_FACING_DOT || facingB < MIN_FACING_DOT) return null; + const b0T = Math.max(0, Math.min(b.length, dotEdgePointToEdge(a, overlapStart, b))); + const b1T = Math.max(0, Math.min(b.length, dotEdgePointToEdge(a, overlapEnd, b))); + return { + gap, + facingA, + facingB, + aStart: overlapStart, + aEnd: overlapEnd, + bStart: Math.min(b0T, b1T), + bEnd: Math.max(b0T, b1T), + }; +} + +function repairPoint(a: Vec2, b: Vec2, edgeLength: number, distance: number): Vec2 { + const t = edgeLength <= EPS ? 0 : Math.max(0, Math.min(1, distance / edgeLength)); + return [ + a[0] + (b[0] - a[0]) * t, + a[1] + (b[1] - a[1]) * t, + ]; +} + +function pushUniquePoint(points: Vec2[], point: Vec2) { + const last = points[points.length - 1]; + if (last && Math.hypot(last[0] - point[0], last[1] - point[1]) <= EPS) return; + points.push(point); +} + +function normalizeRepairSegments( + segments: Repair[] | undefined, + edgeLength: number, + capacity: number, +) { + if (!segments?.length || edgeLength <= EPS || capacity <= EPS) return []; + const stops = new Set([0, edgeLength]); + for (const segment of segments) { + const start = Math.max(0, Math.min(edgeLength, segment.start)); + const end = Math.max(0, Math.min(edgeLength, segment.end)); + if (end - start <= EPS || segment.amount <= EPS) continue; + stops.add(start); + stops.add(end); + } + + const sortedStops = Array.from(stops).sort((a, b) => a - b); + const normalized: Repair[] = []; + for (let i = 0; i + 1 < sortedStops.length; i += 1) { + const start = sortedStops[i]; + const end = sortedStops[i + 1]; + if (end - start <= EPS) continue; + const mid = (start + end) / 2; + let amount = 0; + for (const segment of segments) { + if (mid + EPS < segment.start || mid - EPS > segment.end) continue; + amount = Math.max(amount, segment.amount); + } + const safeAmount = Math.min(capacity, amount); + if (safeAmount > EPS) normalized.push({ start, end, amount: safeAmount }); + } + return normalized; +} + +function isValidRepairedPolygon(source: Vec2[], repaired: Vec2[]) { + if (repaired.length < 3 || !isWeaklyConvex(repaired)) return false; + const sourceArea = signedArea(source); + const repairedArea = signedArea(repaired); + return Math.sign(repairedArea) === Math.sign(sourceArea) && Math.abs(repairedArea) >= Math.abs(sourceArea) - EPS; +} + +export function patchPolygon( + polygon: Polygon, + edgeRepairs: ReadonlyMap, + capacityScale: number, +) { + if (edgeRepairs.size === 0 || polygon.vertices.length < 3 || hasTexture(polygon)) return polygon; + + const points = cssPoints(polygon.vertices); + const basis = localBasis(points); + if (!basis || !isWeaklyConvex(basis.local)) return polygon; + + const repaired: Vec2[] = []; + for (let edgeIndex = 0; edgeIndex < basis.local.length; edgeIndex += 1) { + const a = basis.local[edgeIndex]; + const b = basis.local[(edgeIndex + 1) % basis.local.length]; + const edgeLength = Math.hypot(b[0] - a[0], b[1] - a[1]); + const outward = edgeOutward2D(basis.local, basis.area, edgeIndex); + if (!outward || edgeLength <= EPS) return polygon; + const segments = normalizeRepairSegments( + edgeRepairs.get(edgeIndex), + edgeLength, + edgeSafeCapacity(basis.local, edgeIndex) * capacityScale, + ); + + pushUniquePoint(repaired, a); + let cursor = 0; + for (const segment of segments) { + if (segment.start > cursor + EPS) { + pushUniquePoint(repaired, repairPoint(a, b, edgeLength, segment.start)); + } + + const start = repairPoint(a, b, edgeLength, segment.start); + const end = repairPoint(a, b, edgeLength, segment.end); + pushUniquePoint(repaired, [ + start[0] + outward[0] * segment.amount, + start[1] + outward[1] * segment.amount, + ]); + pushUniquePoint(repaired, [ + end[0] + outward[0] * segment.amount, + end[1] + outward[1] * segment.amount, + ]); + if (segment.end < edgeLength - EPS) pushUniquePoint(repaired, end); + cursor = segment.end; + } + } + + const first = repaired[0]; + const last = repaired[repaired.length - 1]; + if (first && last && Math.hypot(first[0] - last[0], first[1] - last[1]) <= EPS) repaired.pop(); + if (!isValidRepairedPolygon(basis.local, repaired)) return polygon; + + const vertices = repaired.map(([x, y]) => fromCssPoint([ + basis.origin[0] + x * basis.xAxis[0] + y * basis.yAxis[0], + basis.origin[1] + x * basis.xAxis[1] + y * basis.yAxis[1], + basis.origin[2] + x * basis.xAxis[2] + y * basis.yAxis[2], + ])); + return { ...polygon, vertices }; +} diff --git a/packages/core/src/merge/seamRepair/quadSplit.ts b/packages/core/src/merge/seamRepair/quadSplit.ts new file mode 100644 index 000000000..0ab0c5db7 --- /dev/null +++ b/packages/core/src/merge/seamRepair/quadSplit.ts @@ -0,0 +1,143 @@ +import { signedArea2D as signedArea } from "../../atlas/solidTriangle"; +import { crossVec as cross } from "../../math/vec3"; +import type { Polygon, Vec3 } from "../../types"; +import { + cssPoints, + EPS, + fromCssPoint, + hasTexture, + length, + localBasis, + sub, +} from "./geometry"; +import type { Basis, Meta, Vec2 } from "./geometry"; + +const SEAM_SPLIT_INTERNAL_OVERLAP_PX = 1.25; +const SEAM_SPLIT_EDGE_OVERLAP_PX = 0.75; + +export function isRefinableSeamQuad(polygon: Polygon) { + return polygon.vertices.length === 4 && !hasTexture(polygon); +} + +export function quadShapeRisk(meta: Meta) { + const local = meta.basis?.local; + if (!local || local.length !== 4) return 1; + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const [x, y] of local) { + minX = Math.min(minX, x); + minY = Math.min(minY, y); + maxX = Math.max(maxX, x); + maxY = Math.max(maxY, y); + } + const bboxArea = Math.max(EPS, (maxX - minX) * (maxY - minY)); + const fillRatio = Math.max(0, Math.min(1, Math.abs(meta.basis!.area) / bboxArea)); + return 0.75 + (1 - fillRatio) * 2.5; +} + +function cssDistance(a: Vec3, b: Vec3) { + return length(sub(cssPoints([a])[0], cssPoints([b])[0])); +} + +function triangleQuality(a: Vec3, b: Vec3, c: Vec3) { + const ab = cssDistance(a, b); + const bc = cssDistance(b, c); + const ca = cssDistance(c, a); + const longest = Math.max(ab, bc, ca); + if (longest <= EPS) return 0; + const area = length(cross(sub(cssPoints([b])[0], cssPoints([a])[0]), sub(cssPoints([c])[0], cssPoints([a])[0]))) * 0.5; + return area / (longest * longest); +} + +function intersectLocalLines(a0: Vec2, a1: Vec2, b0: Vec2, b1: Vec2): Vec2 | null { + const rx = a1[0] - a0[0]; + const ry = a1[1] - a0[1]; + const sx = b1[0] - b0[0]; + const sy = b1[1] - b0[1]; + const det = rx * sy - ry * sx; + if (Math.abs(det) <= EPS) return null; + const qpx = b0[0] - a0[0]; + const qpy = b0[1] - a0[1]; + const t = (qpx * sy - qpy * sx) / det; + return [a0[0] + t * rx, a0[1] + t * ry]; +} + +function offsetLocalConvexPointsByEdgeAmounts(points: Vec2[], amounts: number[]) { + if (points.length < 3 || points.length !== amounts.length) return null; + const maxAmount = Math.max(0, ...amounts); + if (maxAmount <= EPS) return points; + const area = signedArea(points); + if (Math.abs(area) <= EPS) return null; + const outwardSign = area > 0 ? 1 : -1; + const offsetLines: Array<{ a: Vec2; b: Vec2 }> = []; + for (let i = 0; i < points.length; i += 1) { + const a = points[i]; + const b = points[(i + 1) % points.length]; + const dx = b[0] - a[0]; + const dy = b[1] - a[1]; + const edgeLength = Math.hypot(dx, dy); + if (edgeLength <= EPS) return null; + const amount = Math.max(0, amounts[i]); + const ox = outwardSign * (dy / edgeLength) * amount; + const oy = outwardSign * (-dx / edgeLength) * amount; + offsetLines.push({ + a: [a[0] + ox, a[1] + oy], + b: [b[0] + ox, b[1] + oy], + }); + } + + const expanded: Vec2[] = []; + const maxMiter = Math.max(2, maxAmount * 4); + for (let i = 0; i < points.length; i += 1) { + const prev = offsetLines[(i + points.length - 1) % points.length]; + const next = offsetLines[i]; + const intersection = intersectLocalLines(prev.a, prev.b, next.a, next.b); + if (!intersection) return null; + const original = points[i]; + const dx = intersection[0] - original[0]; + const dy = intersection[1] - original[1]; + const miter = Math.hypot(dx, dy); + expanded.push( + miter > maxMiter + ? [original[0] + (dx / miter) * maxMiter, original[1] + (dy / miter) * maxMiter] + : intersection, + ); + } + return expanded; +} + +function cssPointFromLocal(basis: Basis, point: Vec2): Vec3 { + return [ + basis.origin[0] + basis.xAxis[0] * point[0] + basis.yAxis[0] * point[1], + basis.origin[1] + basis.xAxis[1] * point[0] + basis.yAxis[1] * point[1], + basis.origin[2] + basis.xAxis[2] * point[0] + basis.yAxis[2] * point[1], + ]; +} + +function offsetTriangleVertices(vertices: Vec3[], amounts: [number, number, number]) { + const basis = localBasis(cssPoints(vertices)); + if (!basis) return vertices; + const expanded = offsetLocalConvexPointsByEdgeAmounts(basis.local, amounts); + return expanded + ? expanded.map((point) => fromCssPoint(cssPointFromLocal(basis, point))) + : vertices; +} + +export function splitQuadIntoTriangles(polygon: Polygon, edges: ReadonlySet) { + const solid: Polygon = { ...polygon, uvs: undefined, textureTriangles: undefined }; + const [a, b, c, d] = polygon.vertices; + const acQuality = Math.min(triangleQuality(a, b, c), triangleQuality(a, c, d)); + const bdQuality = Math.min(triangleQuality(a, b, d), triangleQuality(b, c, d)); + const seamAmount = (edge: number) => edges.has(edge) ? SEAM_SPLIT_EDGE_OVERLAP_PX : 0; + return acQuality >= bdQuality + ? [ + { ...solid, vertices: offsetTriangleVertices([a, b, c], [seamAmount(0), seamAmount(1), SEAM_SPLIT_INTERNAL_OVERLAP_PX]) }, + { ...solid, vertices: offsetTriangleVertices([a, c, d], [SEAM_SPLIT_INTERNAL_OVERLAP_PX, seamAmount(2), seamAmount(3)]) }, + ] + : [ + { ...solid, vertices: offsetTriangleVertices([a, b, d], [seamAmount(0), SEAM_SPLIT_INTERNAL_OVERLAP_PX, seamAmount(3)]) }, + { ...solid, vertices: offsetTriangleVertices([b, c, d], [seamAmount(1), seamAmount(2), SEAM_SPLIT_INTERNAL_OVERLAP_PX]) }, + ]; +} diff --git a/packages/core/src/parser/gltf/animation.ts b/packages/core/src/parser/gltf/animation.ts new file mode 100644 index 000000000..6c8eaa777 --- /dev/null +++ b/packages/core/src/parser/gltf/animation.ts @@ -0,0 +1,642 @@ +import type { + Polygon, + PolyTextureAlphaMode, + PolyTextureWrap, + Vec2, + Vec3, +} from "../../types"; +import { transformPointMat4 as transformPoint } from "../../math/vec3"; +import type { ParseAnimationController } from "../types"; +import { readAccessorComponents } from "./binary"; +import { + computeWorldMatrices, + IDENTITY4, + lerpArray, + mulMat4Into, + normalizeQuat, + poseFromNode, + poseLocalMatrix, + slerpQuat, +} from "./transforms"; +import type { + AnimatedPolygonSourceRef, + AnimatedPrimitiveSource, + GltfDoc, + Mat4, + NodePose, + RawTri, + RuntimeAnimationChannel, + RuntimeAnimationClip, + RuntimeAnimationSampler, + RuntimeSourceTriangleMask, +} from "./types"; + +interface GltfAnimationRuntimeInfo { + withPolygonFilter(indices: readonly number[]): ParseAnimationController | undefined; +} + +const GLTF_ANIMATION_RUNTIME_INFO = Symbol("polycss.gltfAnimationRuntimeInfo"); +const POLY_ANIMATION_TRIANGLE_FRAME_SOURCE = Symbol.for("polycss.animation.triangleFrameSource"); + +interface PolyAnimationTriangleFrame { + polygonCount: number; + vertices: Float64Array; + colors?: readonly (string | undefined)[]; + textureFlags?: readonly boolean[]; + solidTriangles?: boolean; +} + +interface GltfAnimationController extends ParseAnimationController { + [GLTF_ANIMATION_RUNTIME_INFO]?: GltfAnimationRuntimeInfo; + [POLY_ANIMATION_TRIANGLE_FRAME_SOURCE]?: ( + clip: number | string, + timeSeconds: number, + ) => PolyAnimationTriangleFrame | null | undefined; +} + +export function filterGltfAnimationController( + animation: ParseAnimationController | undefined, + indices: readonly number[], +): ParseAnimationController | undefined { + return animation + ? (animation as GltfAnimationController)[GLTF_ANIMATION_RUNTIME_INFO]?.withPolygonFilter(indices) + : undefined; +} + +function readMat4Array(doc: GltfDoc, buffers: Uint8Array[], accessorIdx: number | undefined, count: number): Mat4[] { + if (accessorIdx === undefined) { + return Array.from({ length: count }, () => IDENTITY4.slice() as Mat4); + } + const { values, componentCount, count: accCount } = readAccessorComponents(doc, buffers, accessorIdx); + if (componentCount !== 16) { + throw new Error(`parseGltf: inverseBindMatrices accessor ${accessorIdx} is not MAT4`); + } + const out: Mat4[] = []; + for (let i = 0; i < count; i++) { + const sourceIndex = Math.min(i, accCount - 1); + out.push(values.slice(sourceIndex * 16, sourceIndex * 16 + 16) as Mat4); + } + return out; +} + +function samplerValueAt(sampler: RuntimeAnimationSampler, keyIndex: number): number[] { + const cc = sampler.componentCount; + const base = sampler.interpolation === "CUBICSPLINE" + ? (keyIndex * 3 + 1) * cc + : keyIndex * cc; + return sampler.output.slice(base, base + cc); +} + +function sampleAnimationChannel(sampler: RuntimeAnimationSampler, timeSeconds: number, path: string): number[] { + const times = sampler.input; + if (times.length === 0) return []; + if (times.length === 1 || timeSeconds <= times[0]) return samplerValueAt(sampler, 0); + const lastIndex = times.length - 1; + if (timeSeconds >= times[lastIndex]) return samplerValueAt(sampler, lastIndex); + + let lo = 0; + let hi = lastIndex; + while (lo + 1 < hi) { + const mid = (lo + hi) >> 1; + if (times[mid] <= timeSeconds) lo = mid; + else hi = mid; + } + + const t0 = times[lo]; + const t1 = times[lo + 1]; + const amount = t1 > t0 ? (timeSeconds - t0) / (t1 - t0) : 0; + const a = samplerValueAt(sampler, lo); + const b = samplerValueAt(sampler, lo + 1); + if (sampler.interpolation === "STEP") return a; + if (path === "rotation") return slerpQuat(a, b, amount); + return lerpArray(a, b, amount); +} + +function buildRuntimeAnimationClips(doc: GltfDoc, buffers: Uint8Array[]): RuntimeAnimationClip[] { + const runtimeClips: RuntimeAnimationClip[] = []; + for (let i = 0; i < (doc.animations?.length ?? 0); i++) { + const animation = doc.animations![i]!; + const runtimeSamplers = (animation.samplers ?? []).map((sampler): RuntimeAnimationSampler => { + const input = readAccessorComponents(doc, buffers, sampler.input); + const output = readAccessorComponents(doc, buffers, sampler.output); + return { + input: input.values, + output: output.values, + componentCount: output.componentCount, + interpolation: sampler.interpolation ?? "LINEAR", + }; + }); + + const channels: RuntimeAnimationChannel[] = []; + for (const channel of animation.channels ?? []) { + const targetNode = channel.target.node; + const path = channel.target.path; + const sampler = runtimeSamplers[channel.sampler]; + if (targetNode === undefined || !path || !sampler) continue; + if (path !== "translation" && path !== "rotation" && path !== "scale") continue; + channels.push({ sampler, targetNode, path }); + } + const duration = channels.reduce((max, channel) => { + const times = channel.sampler.input; + return Math.max(max, times[times.length - 1] ?? 0); + }, 0); + runtimeClips.push({ + info: { + index: i, + name: animation.name ?? `animation_${i}`, + duration, + channelCount: channels.length, + }, + channels, + }); + } + return runtimeClips; +} + +function sampleRuntimeClipWorldMatrices( + doc: GltfDoc, + basePoses: NodePose[], + clip: RuntimeAnimationClip, + timeSecondsIn: number, +): Mat4[] { + const duration = clip.info.duration; + const timeSeconds = duration > 0 + ? ((timeSecondsIn % duration) + duration) % duration + : Math.max(0, timeSecondsIn); + + const poses = basePoses.map((pose): NodePose => ({ + translation: pose.translation.slice(), + rotation: pose.rotation.slice(), + scale: pose.scale.slice(), + matrix: pose.matrix ? pose.matrix.slice() as Mat4 : undefined, + })); + + for (const channel of clip.channels) { + const pose = poses[channel.targetNode]; + if (!pose) continue; + const value = sampleAnimationChannel(channel.sampler, timeSeconds, channel.path); + pose.matrix = undefined; + if (channel.path === "translation") pose.translation = value.slice(0, 3); + else if (channel.path === "rotation") pose.rotation = normalizeQuat(value.slice(0, 4)); + else if (channel.path === "scale") pose.scale = value.slice(0, 3); + } + + return computeWorldMatrices(doc, poses.map(poseLocalMatrix)); +} + +export function buildAnimationController( + doc: GltfDoc, + buffers: Uint8Array[], + sources: AnimatedPrimitiveSource[], + polygonRefs: Array, + project: (v: Vec3) => Vec3, + projectFrameVertex: (v: Vec3, out: Float64Array, offset: number) => void, +): ParseAnimationController | undefined { + const animations = doc.animations ?? []; + if (animations.length === 0 || sources.length === 0) return undefined; + + const basePoses = (doc.nodes ?? []).map((node) => poseFromNode(node)); + const baseLocalMatrices = basePoses.map(poseLocalMatrix); + const bindWorldMatrices = computeWorldMatrices(doc, baseLocalMatrices); + const skins = (doc.skins ?? []).map((skin) => ({ + joints: skin.joints ?? [], + inverseBindMatrices: readMat4Array(doc, buffers, skin.inverseBindMatrices, skin.joints?.length ?? 0), + })); + const runtimeClips = buildRuntimeAnimationClips(doc, buffers); + + const clips = runtimeClips.map((clip) => clip.info); + if (clips.length === 0) return undefined; + + const sourceMasksFromPolygonFilter = ( + indices: readonly number[], + ): RuntimeSourceTriangleMask[] | undefined => { + const masks = sources.map((source) => new Array(source.triangleMask.length).fill(false)); + for (const index of indices) { + const ref = polygonRefs[index]; + if (!ref) return undefined; + const sourceMask = masks[ref.sourceIndex]; + if (!sourceMask || ref.triangleIndex < 0 || ref.triangleIndex >= sourceMask.length) return undefined; + sourceMask[ref.triangleIndex] = true; + } + + return masks.map((triangleMask, sourceIndex): RuntimeSourceTriangleMask => { + const source = sources[sourceIndex]!; + const used = new Set(); + let triangleOrdinal = 0; + for (let i = 0; i + 2 < source.indices.length; i += 3, triangleOrdinal++) { + if (!triangleMask[triangleOrdinal]) continue; + used.add(source.indices[i]!); + used.add(source.indices[i + 1]!); + used.add(source.indices[i + 2]!); + } + return { + triangleMask, + activeVertices: Array.from(used).sort((a, b) => a - b), + }; + }); + }; + + const polygonFromWorldTri = ( + v0World: Vec3, + v1World: Vec3, + v2World: Vec3, + color: string, + texture: string | undefined, + textureWrap: PolyTextureWrap | undefined, + textureAlphaMode: PolyTextureAlphaMode | undefined, + doubleSided: boolean | undefined, + uvs: Vec2[] | undefined, + ): Polygon | null => { + const v0 = project(v0World); + const v1 = project(v1World); + const v2 = project(v2World); + const polygon: Polygon = { vertices: [v0, v1, v2], color }; + if (texture) polygon.texture = texture; + if (texture && textureWrap) polygon.textureWrap = textureWrap; + if (texture && textureAlphaMode) polygon.textureAlphaMode = textureAlphaMode; + if (doubleSided) polygon.doubleSided = true; + if (uvs) polygon.uvs = uvs; + return polygon; + }; + + const createController = ( + sourceMaskOverrides?: RuntimeSourceTriangleMask[], + ): ParseAnimationController => { + const activeTriangleCapacity = sources.reduce((sum, source, sourceIndex) => { + const mask = sourceMaskOverrides?.[sourceIndex]?.triangleMask ?? source.triangleMask; + let count = 0; + for (let i = 0; i < mask.length; i++) { + if (mask[i]) count++; + } + return sum + count; + }, 0); + let triangleFrameVertices = new Float64Array(Math.max(0, activeTriangleCapacity * 9)); + let triangleFrameColors: Array = new Array(activeTriangleCapacity); + let triangleFrameTextureFlags: boolean[] = new Array(activeTriangleCapacity).fill(false); + const triangleFrame: PolyAnimationTriangleFrame = { + polygonCount: 0, + vertices: triangleFrameVertices, + colors: triangleFrameColors, + textureFlags: triangleFrameTextureFlags, + solidTriangles: true, + }; + const sourceWorldPositionCaches = sources.map( + (source) => new Array(source.positions.length), + ); + const skinJointMatrixCaches: Array> = skins.map((skin) => + skin.joints.map(() => new Array(16) as Mat4) + ); + + const sampleWorldMatrices = ( + clipRef: number | string, + timeSecondsIn: number, + ): Mat4[] | null => { + const clip = typeof clipRef === "number" + ? runtimeClips[clipRef] + : runtimeClips.find((candidate) => candidate.info.name === clipRef); + if (!clip) return null; + return sampleRuntimeClipWorldMatrices(doc, basePoses, clip, timeSecondsIn); + }; + + const computeSourceWorldPositions = ( + sourceIndex: number, + source: AnimatedPrimitiveSource, + sourceMask: RuntimeSourceTriangleMask | undefined, + worldMatrices: Mat4[], + ): Array => { + const activeVertices = sourceMask?.activeVertices; + const worldPositions = sourceWorldPositionCaches[sourceIndex]!; + const writeWorldPosition = (i: number, x: number, y: number, z: number): void => { + const out = worldPositions[i]; + if (out) { + out[0] = x; + out[1] = y; + out[2] = z; + } else { + worldPositions[i] = [x, y, z]; + } + }; + if ( + source.skinIndex !== undefined && + source.joints && + source.weights && + skins[source.skinIndex] + ) { + const skin = skins[source.skinIndex]; + const sourceJoints = source.joints; + const sourceWeights = source.weights; + const jointMatrices = skinJointMatrixCaches[source.skinIndex] ?? []; + for (let jointSlot = 0; jointSlot < skin.joints.length; jointSlot++) { + const jointNode = skin.joints[jointSlot]!; + const jointWorld = worldMatrices[jointNode]; + const inverseBind = skin.inverseBindMatrices[jointSlot]; + const out = jointMatrices[jointSlot] ?? (jointMatrices[jointSlot] = new Array(16) as Mat4); + jointMatrices[jointSlot] = jointWorld && inverseBind + ? mulMat4Into(out, jointWorld, inverseBind) + : undefined; + } + const skinVertex = (i: number): void => { + const bindPosition = source.positions[i]; + let blendedX = 0; + let blendedY = 0; + let blendedZ = 0; + let weightSum = 0; + const joints = sourceJoints[i] ?? []; + const weights = sourceWeights[i] ?? []; + for (let j = 0; j < 4; j++) { + const weight = weights[j] ?? 0; + if (weight <= 0) continue; + const jointSlot = Math.round(joints[j] ?? 0); + const jointMatrix = jointMatrices[jointSlot]; + if (!jointMatrix) continue; + const x = + jointMatrix[0] * bindPosition[0] + + jointMatrix[4] * bindPosition[1] + + jointMatrix[8] * bindPosition[2] + + jointMatrix[12]; + const y = + jointMatrix[1] * bindPosition[0] + + jointMatrix[5] * bindPosition[1] + + jointMatrix[9] * bindPosition[2] + + jointMatrix[13]; + const z = + jointMatrix[2] * bindPosition[0] + + jointMatrix[6] * bindPosition[1] + + jointMatrix[10] * bindPosition[2] + + jointMatrix[14]; + blendedX += x * weight; + blendedY += y * weight; + blendedZ += z * weight; + weightSum += weight; + } + if (weightSum > 0) { + const invWeight = 1 / weightSum; + writeWorldPosition(i, blendedX * invWeight, blendedY * invWeight, blendedZ * invWeight); + } else { + writeWorldPosition( + i, + source.meshBindWorld[0] * bindPosition[0] + + source.meshBindWorld[4] * bindPosition[1] + + source.meshBindWorld[8] * bindPosition[2] + + source.meshBindWorld[12], + source.meshBindWorld[1] * bindPosition[0] + + source.meshBindWorld[5] * bindPosition[1] + + source.meshBindWorld[9] * bindPosition[2] + + source.meshBindWorld[13], + source.meshBindWorld[2] * bindPosition[0] + + source.meshBindWorld[6] * bindPosition[1] + + source.meshBindWorld[10] * bindPosition[2] + + source.meshBindWorld[14], + ); + } + }; + if (activeVertices) { + for (const vertexIndex of activeVertices) skinVertex(vertexIndex); + } else { + for (let i = 0; i < source.positions.length; i++) skinVertex(i); + } + } else { + const meshWorld = source.meshNode !== null + ? (worldMatrices[source.meshNode] ?? source.meshBindWorld) + : source.meshBindWorld; + const transformVertex = (i: number): void => { + const sourcePosition = source.positions[i]; + writeWorldPosition( + i, + meshWorld[0] * sourcePosition[0] + + meshWorld[4] * sourcePosition[1] + + meshWorld[8] * sourcePosition[2] + + meshWorld[12], + meshWorld[1] * sourcePosition[0] + + meshWorld[5] * sourcePosition[1] + + meshWorld[9] * sourcePosition[2] + + meshWorld[13], + meshWorld[2] * sourcePosition[0] + + meshWorld[6] * sourcePosition[1] + + meshWorld[10] * sourcePosition[2] + + meshWorld[14], + ); + }; + if (activeVertices) { + for (const vertexIndex of activeVertices) transformVertex(vertexIndex); + } else { + for (let i = 0; i < source.positions.length; i++) transformVertex(i); + } + } + return worldPositions; + }; + + const sample = (clipRef: number | string, timeSecondsIn: number): Polygon[] => { + const worldMatrices = sampleWorldMatrices(clipRef, timeSecondsIn); + if (!worldMatrices) return []; + const polygons: Polygon[] = []; + + for (let sourceIndex = 0; sourceIndex < sources.length; sourceIndex++) { + const source = sources[sourceIndex]!; + const sourceMask = sourceMaskOverrides?.[sourceIndex]; + const triangleMask = sourceMask?.triangleMask ?? source.triangleMask; + const worldPositions = computeSourceWorldPositions( + sourceIndex, + source, + sourceMask, + worldMatrices, + ); + + let triangleOrdinal = 0; + for (let i = 0; i + 2 < source.indices.length; i += 3, triangleOrdinal++) { + if (!triangleMask[triangleOrdinal]) continue; + const i0 = source.indices[i]; + const i1 = source.indices[i + 1]; + const i2 = source.indices[i + 2]; + const v0 = worldPositions[i0]; + const v1 = worldPositions[i1]; + const v2 = worldPositions[i2]; + if (!v0 || !v1 || !v2) continue; + let triUvs: Vec2[] | undefined; + if (source.uvs && source.texture) { + const u0 = source.uvs[i0], u1 = source.uvs[i1], u2 = source.uvs[i2]; + if (u0 && u1 && u2) triUvs = [u0, u1, u2]; + } + const polygon = polygonFromWorldTri( + v0, + v1, + v2, + source.color, + source.texture, + source.textureWrap, + source.textureAlphaMode, + source.doubleSided, + triUvs, + ); + if (polygon) polygons.push(polygon); + } + } + return polygons; + }; + + const sampleTriangleFrame = ( + clipRef: number | string, + timeSecondsIn: number, + ): PolyAnimationTriangleFrame | null => { + const worldMatrices = sampleWorldMatrices(clipRef, timeSecondsIn); + if (!worldMatrices) return null; + if (triangleFrameVertices.length < activeTriangleCapacity * 9) { + triangleFrameVertices = new Float64Array(activeTriangleCapacity * 9); + triangleFrame.vertices = triangleFrameVertices; + } + if (triangleFrameColors.length < activeTriangleCapacity) { + triangleFrameColors = new Array(activeTriangleCapacity); + triangleFrame.colors = triangleFrameColors; + } + if (triangleFrameTextureFlags.length < activeTriangleCapacity) { + triangleFrameTextureFlags = new Array(activeTriangleCapacity).fill(false); + triangleFrame.textureFlags = triangleFrameTextureFlags; + } + let polygonCount = 0; + let writeOffset = 0; + let hasTexture = false; + + for (let sourceIndex = 0; sourceIndex < sources.length; sourceIndex++) { + const source = sources[sourceIndex]!; + const sourceMask = sourceMaskOverrides?.[sourceIndex]; + const triangleMask = sourceMask?.triangleMask ?? source.triangleMask; + const worldPositions = computeSourceWorldPositions( + sourceIndex, + source, + sourceMask, + worldMatrices, + ); + + let triangleOrdinal = 0; + for (let i = 0; i + 2 < source.indices.length; i += 3, triangleOrdinal++) { + if (!triangleMask[triangleOrdinal]) continue; + const i0 = source.indices[i]!; + const i1 = source.indices[i + 1]!; + const i2 = source.indices[i + 2]!; + const v0 = worldPositions[i0]; + const v1 = worldPositions[i1]; + const v2 = worldPositions[i2]; + if (!v0 || !v1 || !v2) continue; + projectFrameVertex(v0, triangleFrameVertices, writeOffset); + projectFrameVertex(v1, triangleFrameVertices, writeOffset + 3); + projectFrameVertex(v2, triangleFrameVertices, writeOffset + 6); + triangleFrameColors[polygonCount] = source.color; + const textured = !!source.texture; + triangleFrameTextureFlags[polygonCount] = textured; + if (textured) hasTexture = true; + polygonCount++; + writeOffset += 9; + } + } + + triangleFrame.polygonCount = polygonCount; + triangleFrame.solidTriangles = !hasTexture; + return triangleFrame; + }; + + const controller: GltfAnimationController = { clips, sample }; + controller[POLY_ANIMATION_TRIANGLE_FRAME_SOURCE] = sampleTriangleFrame; + controller[GLTF_ANIMATION_RUNTIME_INFO] = { + withPolygonFilter(indices) { + const masks = sourceMasksFromPolygonFilter(indices); + return masks ? createController(masks) : undefined; + }, + }; + return controller; + }; + + return createController(); +} + +function seedTimesForClip(clip: RuntimeAnimationClip): number[] { + const times = new Set(); + const duration = clip.info.duration; + for (const channel of clip.channels) { + for (const time of channel.sampler.input) { + if (!Number.isFinite(time) || time <= 0) continue; + if (duration > 0 && time >= duration) continue; + times.add(time); + } + } + if (duration > 0) { + times.add(duration * 0.25); + times.add(duration * 0.5); + times.add(duration * 0.75); + } + return Array.from(times).sort((a, b) => a - b).slice(0, 128); +} + +function animatedRawTriFrame( + tri: RawTri, + worldMatrices: Mat4[], +): { v0: Vec3; v1: Vec3; v2: Vec3 } | undefined { + const source = tri.source; + if (!source || tri.sourceTriangleIndex === undefined || source.skinIndex !== undefined) return undefined; + const offset = tri.sourceTriangleIndex * 3; + const i0 = source.indices[offset]; + const i1 = source.indices[offset + 1]; + const i2 = source.indices[offset + 2]; + const p0 = i0 !== undefined ? source.positions[i0] : undefined; + const p1 = i1 !== undefined ? source.positions[i1] : undefined; + const p2 = i2 !== undefined ? source.positions[i2] : undefined; + if (!p0 || !p1 || !p2) return undefined; + const meshWorld = source.meshNode !== null + ? (worldMatrices[source.meshNode] ?? source.meshBindWorld) + : source.meshBindWorld; + return { + v0: transformPoint(meshWorld, p0), + v1: transformPoint(meshWorld, p1), + v2: transformPoint(meshWorld, p2), + }; +} + +function sameWorldVertex(a: Vec3, b: Vec3): boolean { + return a[0] === b[0] && a[1] === b[1] && a[2] === b[2]; +} + +function isDegenerateRawTriFrame(frame: { v0: Vec3; v1: Vec3; v2: Vec3 }): boolean { + return ( + sameWorldVertex(frame.v0, frame.v1) || + sameWorldVertex(frame.v0, frame.v2) || + sameWorldVertex(frame.v1, frame.v2) + ); +} + +export function seedCollapsedRawTrisFromAnimation( + doc: GltfDoc, + buffers: Uint8Array[], + rawTris: RawTri[], +): void { + if ( + rawTris.length === 0 || + (doc.animations?.length ?? 0) === 0 || + rawTris.some((tri) => !isDegenerateRawTriFrame(tri)) + ) { + return; + } + const runtimeClips = buildRuntimeAnimationClips(doc, buffers); + if (runtimeClips.length === 0) return; + const basePoses = (doc.nodes ?? []).map((node) => poseFromNode(node)); + const seededFrames: Array<{ v0: Vec3; v1: Vec3; v2: Vec3 } | undefined> = + new Array(rawTris.length); + + for (const clip of runtimeClips) { + for (const time of seedTimesForClip(clip)) { + const worldMatrices = sampleRuntimeClipWorldMatrices(doc, basePoses, clip, time); + for (let i = 0; i < rawTris.length; i++) { + if (seededFrames[i]) continue; + const frame = animatedRawTriFrame(rawTris[i]!, worldMatrices); + if (frame && !isDegenerateRawTriFrame(frame)) seededFrames[i] = frame; + } + } + } + + if (!seededFrames.some(Boolean)) return; + for (let i = 0; i < rawTris.length; i++) { + const frame = seededFrames[i]; + if (!frame) continue; + rawTris[i]!.v0 = frame.v0; + rawTris[i]!.v1 = frame.v1; + rawTris[i]!.v2 = frame.v2; + } +} diff --git a/packages/core/src/parser/gltf/binary.ts b/packages/core/src/parser/gltf/binary.ts new file mode 100644 index 000000000..c484339f0 --- /dev/null +++ b/packages/core/src/parser/gltf/binary.ts @@ -0,0 +1,330 @@ +import { + CHUNK_BIN, + CHUNK_JSON, + COMPONENT_BYTES, + GLB_MAGIC, + MESHOPT_COMPRESSION_EXTENSIONS, + TYPE_COUNT, + type AccessorArray, + type GltfAccessor, + type GltfBufferView, + type GltfDoc, +} from "./types"; + +export function isQuantizedPositionComponentType(componentType: number): boolean { + return ( + componentType === 5120 || + componentType === 5121 || + componentType === 5122 || + componentType === 5123 + ); +} + +export function decodeUtf8(bytes: Uint8Array): string { + const Decoder = (globalThis as unknown as { TextDecoder: new () => { decode: (a: Uint8Array) => string } }).TextDecoder; + return new Decoder().decode(bytes); +} + +/** + * Decode a base64-encoded `data:` URI to bytes. glTF JSON files often embed + * the buffer this way (`data:application/octet-stream;base64,...`). + */ +export function dataUriToBytes(uri: string): Uint8Array { + const comma = uri.indexOf(","); + if (comma < 0) throw new Error("parseGltf: malformed data: URI"); + const meta = uri.slice(5, comma); // strip "data:" + const payload = uri.slice(comma + 1); + if (!meta.includes(";base64")) { + const text = decodeURIComponent(payload); + const out = new Uint8Array(text.length); + for (let i = 0; i < text.length; i++) out[i] = text.charCodeAt(i) & 0xff; + return out; + } + const bin = (globalThis as unknown as { atob: (s: string) => string }).atob(payload); + const out = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); + return out; +} + +export function parseGlbContainer(buf: ArrayBuffer): { doc: GltfDoc; bin: Uint8Array | null } { + const view = new DataView(buf); + if (view.getUint32(0, true) !== GLB_MAGIC) throw new Error("parseGltf: not a GLB (bad magic)"); + const version = view.getUint32(4, true); + if (version !== 2) throw new Error(`parseGltf: only glTF v2 supported (got v${version})`); + + let offset = 12; + let doc: GltfDoc | null = null; + let bin: Uint8Array | null = null; + while (offset < buf.byteLength) { + const len = view.getUint32(offset, true); + const type = view.getUint32(offset + 4, true); + const start = offset + 8; + if (type === CHUNK_JSON) { + const bytes = new Uint8Array(buf, start, len); + doc = JSON.parse(decodeUtf8(bytes)); + } else if (type === CHUNK_BIN) { + bin = new Uint8Array(buf, start, len); + } + offset = start + len; + } + if (!doc) throw new Error("parseGltf: no JSON chunk in GLB"); + return { doc, bin }; +} + +function parseVersionString(value: string | undefined): [number, number] | null { + if (!value) return null; + const match = /^(\d+)\.(\d+)(?:\D.*)?$/.exec(value); + if (!match) return null; + return [Number(match[1]), Number(match[2])]; +} + +export function validateGltfAsset(doc: GltfDoc): void { + const version = parseVersionString(doc.asset?.version); + if (!version || version[0] !== 2) { + throw new Error(`parseGltf: only glTF asset v2 supported (got ${doc.asset?.version ?? "missing"})`); + } + const minVersion = parseVersionString(doc.asset?.minVersion); + if (doc.asset?.minVersion && (!minVersion || minVersion[0] > 2 || (minVersion[0] === 2 && minVersion[1] > 0))) { + throw new Error(`parseGltf: glTF asset requires minVersion ${doc.asset.minVersion}`); + } +} + +export function resolveBuffers( + doc: GltfDoc, + glbBin: Uint8Array | null, + resolveBuffer?: (uri: string) => Uint8Array | Promise, +): Uint8Array[] { + const specs = doc.buffers ?? []; + const requiredExtensions = new Set(doc.extensionsRequired ?? []); + const canSkipMeshoptFallbackBuffers = MESHOPT_COMPRESSION_EXTENSIONS.some((extensionName) => + requiredExtensions.has(extensionName) + ); + return specs.map((buffer, index) => { + const uri = buffer.uri; + if (uri) { + if (uri.startsWith("data:")) return dataUriToBytes(uri); + if (resolveBuffer) { + const result = resolveBuffer(uri); + if (result instanceof Uint8Array) return result; + throw new Error("parseGltf: resolveBuffer returned a Promise; use parseGltf via async if your buffers are external"); + } + throw new Error(`parseGltf: external buffer URI "${uri}" — provide options.resolveBuffer`); + } + if (index === 0 && glbBin) return glbBin; + if ( + canSkipMeshoptFallbackBuffers && + MESHOPT_COMPRESSION_EXTENSIONS.some((extensionName) => buffer.extensions?.[extensionName]) + ) { + return new Uint8Array(0); + } + throw new Error(`parseGltf: buffer[${index}] has no uri and no GLB BIN chunk`); + }); +} + +export function resolveBufferView( + doc: GltfDoc, + buffers: Uint8Array[], + bufferViewIdx: number, +): { buffer: Uint8Array; view: GltfBufferView } { + const view = doc.bufferViews?.[bufferViewIdx]; + const buffer = view ? buffers[view.buffer] : undefined; + if (!view || !buffer) throw new Error(`parseGltf: bad bufferView ${bufferViewIdx}`); + const offset = view.byteOffset ?? 0; + if (offset < 0 || view.byteLength < 0 || offset + view.byteLength > buffer.byteLength) { + throw new Error(`parseGltf: bufferView ${bufferViewIdx} outside buffer ${view.buffer}`); + } + return { buffer, view }; +} + +function assertAccessorFits(acc: GltfAccessor, view: GltfBufferView, stride: number, packedBytes: number): void { + if (acc.count <= 0) return; + const relativeOffset = acc.byteOffset ?? 0; + const byteEnd = relativeOffset + stride * (acc.count - 1) + packedBytes; + if (relativeOffset < 0 || byteEnd > view.byteLength) { + throw new Error("parseGltf: accessor does not fit bufferView"); + } +} + +function resolveAccessorStride(view: GltfBufferView, packedBytes: number): number { + return view.byteStride !== undefined && view.byteStride > 0 ? view.byteStride : packedBytes; +} + +function typedArrayFromValues(componentType: number, values: number[], normalized: boolean | undefined): AccessorArray { + if (normalized || componentType === 5126) return new Float32Array(values); + switch (componentType) { + case 5120: return new Int8Array(values); + case 5121: return new Uint8Array(values); + case 5122: return new Int16Array(values); + case 5123: return new Uint16Array(values); + case 5125: return new Uint32Array(values); + default: throw new Error(`parseGltf: unhandled componentType ${componentType}`); + } +} + +export function readAccessor(doc: GltfDoc, buffers: Uint8Array[], accessorIdx: number): { + array: AccessorArray; + count: number; + componentCount: number; +} { + const acc = doc.accessors?.[accessorIdx]; + if (!acc) throw new Error(`parseGltf: bad accessor ${accessorIdx}`); + const bytesPerComponent = COMPONENT_BYTES[acc.componentType]; + const componentCount = TYPE_COUNT[acc.type]; + if (!bytesPerComponent || !componentCount) { + throw new Error(`parseGltf: unsupported accessor type ${acc.type}/${acc.componentType}`); + } + if (acc.sparse || acc.normalized || acc.bufferView === undefined) { + const { values } = readAccessorComponents(doc, buffers, accessorIdx); + return { array: typedArrayFromValues(acc.componentType, values, acc.normalized), count: acc.count, componentCount }; + } + const { buffer: bin, view } = resolveBufferView(doc, buffers, acc.bufferView); + const offset = (view.byteOffset ?? 0) + (acc.byteOffset ?? 0); + const elements = acc.count * componentCount; + const packedBytes = bytesPerComponent * componentCount; + const stride = resolveAccessorStride(view, packedBytes); + assertAccessorFits(acc, view, stride, packedBytes); + + if (stride === packedBytes) { + const slice = bin.buffer.slice( + bin.byteOffset + offset, + bin.byteOffset + offset + elements * bytesPerComponent, + ); + let array: AccessorArray; + switch (acc.componentType) { + case 5120: array = new Int8Array(slice); break; + case 5121: array = new Uint8Array(slice); break; + case 5122: array = new Int16Array(slice); break; + case 5123: array = new Uint16Array(slice); break; + case 5125: array = new Uint32Array(slice); break; + case 5126: array = new Float32Array(slice); break; + default: throw new Error(`parseGltf: unhandled componentType ${acc.componentType}`); + } + return { array, count: acc.count, componentCount }; + } + + let array: AccessorArray; + switch (acc.componentType) { + case 5120: array = new Int8Array(elements); break; + case 5121: array = new Uint8Array(elements); break; + case 5122: array = new Int16Array(elements); break; + case 5123: array = new Uint16Array(elements); break; + case 5125: array = new Uint32Array(elements); break; + case 5126: array = new Float32Array(elements); break; + default: throw new Error(`parseGltf: unhandled componentType ${acc.componentType}`); + } + + const data = new DataView(bin.buffer); + const start = bin.byteOffset + offset; + let write = 0; + for (let i = 0; i < acc.count; i++) { + const elementOffset = start + i * stride; + for (let c = 0; c < componentCount; c++) { + array[write++] = readRawComponent( + data, + elementOffset + c * bytesPerComponent, + acc.componentType, + ); + } + } + return { array, count: acc.count, componentCount }; +} + +function readRawComponent(data: DataView, offset: number, componentType: number): number { + switch (componentType) { + case 5120: return data.getInt8(offset); + case 5121: return data.getUint8(offset); + case 5122: return data.getInt16(offset, true); + case 5123: return data.getUint16(offset, true); + case 5125: return data.getUint32(offset, true); + case 5126: return data.getFloat32(offset, true); + default: throw new Error(`parseGltf: unhandled componentType ${componentType}`); + } +} + +function normalizeComponent(value: number, componentType: number): number { + switch (componentType) { + case 5120: return Math.max(value / 127, -1); + case 5121: return value / 255; + case 5122: return Math.max(value / 32767, -1); + case 5123: return value / 65535; + default: return value; + } +} + +export function readAccessorComponents(doc: GltfDoc, buffers: Uint8Array[], accessorIdx: number): { + values: number[]; + count: number; + componentCount: number; +} { + const acc = doc.accessors?.[accessorIdx]; + if (!acc) throw new Error(`parseGltf: bad accessor ${accessorIdx}`); + const bytesPerComponent = COMPONENT_BYTES[acc.componentType]; + const componentCount = TYPE_COUNT[acc.type]; + if (!bytesPerComponent || !componentCount) { + throw new Error(`parseGltf: unsupported accessor type ${acc.type}/${acc.componentType}`); + } + const packedBytes = bytesPerComponent * componentCount; + const values = new Array(acc.count * componentCount).fill(0); + if (acc.bufferView !== undefined) { + const { buffer, view } = resolveBufferView(doc, buffers, acc.bufferView); + const start = buffer.byteOffset + (view.byteOffset ?? 0) + (acc.byteOffset ?? 0); + const stride = resolveAccessorStride(view, packedBytes); + assertAccessorFits(acc, view, stride, packedBytes); + const data = new DataView(buffer.buffer); + let write = 0; + for (let i = 0; i < acc.count; i++) { + const elementOffset = start + i * stride; + for (let c = 0; c < componentCount; c++) { + const raw = readRawComponent(data, elementOffset + c * bytesPerComponent, acc.componentType); + values[write++] = acc.normalized ? normalizeComponent(raw, acc.componentType) : raw; + } + } + } + if (acc.sparse) { + const sparse = acc.sparse; + const sparseIndices = sparse.indices; + const sparseIndexBytes = COMPONENT_BYTES[sparseIndices.componentType]; + if ( + sparseIndices.componentType !== 5121 && + sparseIndices.componentType !== 5123 && + sparseIndices.componentType !== 5125 + ) { + throw new Error(`parseGltf: unhandled sparse index componentType ${sparseIndices.componentType}`); + } + const { buffer: indexBuffer, view: indexView } = resolveBufferView(doc, buffers, sparseIndices.bufferView); + const indexStart = indexBuffer.byteOffset + (indexView.byteOffset ?? 0) + (sparseIndices.byteOffset ?? 0); + const indexData = new DataView(indexBuffer.buffer); + const { buffer: valueBuffer, view: valueView } = resolveBufferView(doc, buffers, sparse.values.bufferView); + const valueStart = valueBuffer.byteOffset + (valueView.byteOffset ?? 0) + (sparse.values.byteOffset ?? 0); + const valueData = new DataView(valueBuffer.buffer); + for (let i = 0; i < sparse.count; i++) { + const targetIndex = readRawComponent(indexData, indexStart + i * sparseIndexBytes, sparseIndices.componentType); + for (let c = 0; c < componentCount; c++) { + const raw = readRawComponent(valueData, valueStart + (i * componentCount + c) * bytesPerComponent, acc.componentType); + values[targetIndex * componentCount + c] = acc.normalized ? normalizeComponent(raw, acc.componentType) : raw; + } + } + } + return { values, count: acc.count, componentCount }; +} + +export function readAccessorTupleArray( + doc: GltfDoc, + buffers: Uint8Array[], + accessorIdx: number | undefined, + expectedComponents: number, + expectedCount: number, +): number[][] | undefined { + if (accessorIdx === undefined) return undefined; + const { values, count, componentCount } = readAccessorComponents(doc, buffers, accessorIdx); + if (count !== expectedCount || componentCount < 1) return undefined; + const out: number[][] = []; + for (let i = 0; i < count; i++) { + const tuple: number[] = []; + for (let c = 0; c < expectedComponents; c++) { + tuple.push(values[i * componentCount + c] ?? 0); + } + out.push(tuple); + } + return out; +} diff --git a/packages/core/src/parser/gltf/materials.ts b/packages/core/src/parser/gltf/materials.ts new file mode 100644 index 000000000..2fb967a3d --- /dev/null +++ b/packages/core/src/parser/gltf/materials.ts @@ -0,0 +1,140 @@ +import type { + PolyTextureAlphaMode, + PolyTextureWrap, + PolyTextureWrapMode, +} from "../../types"; +import { resolveBufferView } from "./binary"; +import type { + GltfDoc, + GltfMaterial, + GltfMaterialTextureInfo, + GltfTexture, +} from "./types"; + +export function extractImageUrls( + doc: GltfDoc, + buffers: Uint8Array[], + baseUrl?: string, +): { urls: string[]; objectUrls: string[] } { + const urls: string[] = []; + const objectUrls: string[] = []; + const g = globalThis as unknown as { + Blob: new (parts: ArrayLike[] | Uint8Array[], opts?: { type?: string }) => unknown; + URL: { createObjectURL: (b: unknown) => string; new (u: string, base?: string): { href: string } }; + }; + for (const img of doc.images ?? []) { + if (img.uri) { + if (baseUrl && !img.uri.startsWith("data:")) { + try { + urls.push(new g.URL(img.uri, baseUrl).href); + } catch { + urls.push(img.uri); + } + } else { + urls.push(img.uri); + } + continue; + } + if (img.bufferView !== undefined) { + let bytes: Uint8Array; + try { + const { buffer, view } = resolveBufferView(doc, buffers, img.bufferView); + const offset = view.byteOffset ?? 0; + bytes = buffer.subarray(offset, offset + view.byteLength); + } catch { + urls.push(""); + continue; + } + const mime = img.mimeType ?? "image/png"; + const blob = new g.Blob([bytes], { type: mime }); + const url = g.URL.createObjectURL(blob); + urls.push(url); + objectUrls.push(url); + } else { + urls.push(""); + } + } + return { urls, objectUrls }; +} + +function gltfWrapMode(value: number | undefined): PolyTextureWrapMode { + switch (value ?? 10497) { + case 33071: return "clamp-to-edge"; + case 33648: return "mirrored-repeat"; + case 10497: return "repeat"; + default: return "repeat"; + } +} + +function textureWrapForTexture(doc: GltfDoc, texture: GltfTexture | undefined): PolyTextureWrap { + const sampler = texture?.sampler !== undefined ? doc.samplers?.[texture.sampler] : undefined; + return { + s: gltfWrapMode(sampler?.wrapS), + t: gltfWrapMode(sampler?.wrapT), + }; +} + +export function gltfAlphaMode(value: string | undefined): PolyTextureAlphaMode { + switch (value) { + case "BLEND": return "blend"; + case "MASK": return "mask"; + case "OPAQUE": + default: return "opaque"; + } +} + +export function buildMaterialTextureMap(doc: GltfDoc, imageUrls: string[]): Map { + const out = new Map(); + const mats = doc.materials ?? []; + for (let i = 0; i < mats.length; i++) { + const texIdx = mats[i].pbrMetallicRoughness?.baseColorTexture?.index; + if (texIdx === undefined) continue; + const texture = doc.textures?.[texIdx]; + const sourceIdx = texture?.source; + if (sourceIdx === undefined) continue; + const url = imageUrls[sourceIdx]; + if (url) { + out.set(i, { + url, + wrap: textureWrapForTexture(doc, texture), + alphaMode: gltfAlphaMode(mats[i].alphaMode), + texCoord: mats[i].pbrMetallicRoughness?.baseColorTexture?.texCoord ?? 0, + }); + } + } + return out; +} + +export function colorFromMaterial( + mat: GltfMaterial | undefined, + fallback: string, + alphaMode: PolyTextureAlphaMode, +): string { + const c = mat?.pbrMetallicRoughness?.baseColorFactor; + if (!c || c.length < 3) return fallback; + const clamp01 = (n: number) => Math.max(0, Math.min(1, n)); + const toHex = (n: number) => Math.round(clamp01(n) * 255).toString(16).padStart(2, "0"); + const toByte = (n: number) => Math.round(clamp01(n) * 255); + const alpha = alphaMode === "opaque" ? 1 : clamp01(c[3] ?? 1); + return alpha < 1 + ? `rgba(${toByte(c[0])}, ${toByte(c[1])}, ${toByte(c[2])}, ${Math.round(alpha * 1000) / 1000})` + : `#${toHex(c[0])}${toHex(c[1])}${toHex(c[2])}`; +} + +/** + * Build an idempotent disposer that revokes each minted blob URL exactly + * once. Subsequent calls are no-ops, so component unmount paths can call + * `dispose()` defensively without worrying about double-revoke errors. + */ +export function makeDispose(objectUrls: string[]): () => void { + let disposed = false; + return () => { + if (disposed) return; + disposed = true; + const URL = (globalThis as unknown as { URL?: { revokeObjectURL?: (url: string) => void } }).URL; + if (!URL?.revokeObjectURL) return; + for (const url of objectUrls) { + try { URL.revokeObjectURL(url); } catch { /* swallow — best effort */ } + } + }; +} diff --git a/packages/core/src/parser/gltf/transforms.ts b/packages/core/src/parser/gltf/transforms.ts new file mode 100644 index 000000000..4eb29efa6 --- /dev/null +++ b/packages/core/src/parser/gltf/transforms.ts @@ -0,0 +1,140 @@ +import type { Vec3 } from "../../types"; +import type { GltfDoc, GltfNode, Mat4, NodePose } from "./types"; + +// ── Node transform math ───────────────────────────────────────────────── + +export const IDENTITY4: Mat4 = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]; + +export function mulMat4(a: Mat4, b: Mat4): Mat4 { + const out = new Array(16) as Mat4; + return mulMat4Into(out, a, b); +} + +export function mulMat4Into(out: Mat4, a: Mat4, b: Mat4): Mat4 { + for (let row = 0; row < 4; row++) { + for (let col = 0; col < 4; col++) { + out[col * 4 + row] = + a[0 * 4 + row] * b[col * 4 + 0] + + a[1 * 4 + row] * b[col * 4 + 1] + + a[2 * 4 + row] * b[col * 4 + 2] + + a[3 * 4 + row] * b[col * 4 + 3]; + } + } + return out; +} + +export function trsToMat4(t?: number[], r?: number[], s?: number[]): Mat4 { + const tx = t?.[0] ?? 0, ty = t?.[1] ?? 0, tz = t?.[2] ?? 0; + const qx = r?.[0] ?? 0, qy = r?.[1] ?? 0, qz = r?.[2] ?? 0, qw = r?.[3] ?? 1; + const sx = s?.[0] ?? 1, sy = s?.[1] ?? 1, sz = s?.[2] ?? 1; + + const x2 = qx + qx, y2 = qy + qy, z2 = qz + qz; + const xx = qx * x2, xy = qx * y2, xz = qx * z2; + const yy = qy * y2, yz = qy * z2, zz = qz * z2; + const wx = qw * x2, wy = qw * y2, wz = qw * z2; + + return [ + (1 - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0, + (xy - wz) * sy, (1 - (xx + zz)) * sy, (yz + wx) * sy, 0, + (xz + wy) * sz, (yz - wx) * sz, (1 - (xx + yy)) * sz, 0, + tx, ty, tz, 1, + ]; +} + +export function nodeLocalMatrix(n: GltfNode): Mat4 { + if (n.matrix && n.matrix.length === 16) return n.matrix.slice() as Mat4; + return trsToMat4(n.translation, n.rotation, n.scale); +} + +export function lerpArray(a: number[], b: number[], t: number): number[] { + const out = new Array(Math.min(a.length, b.length)); + for (let i = 0; i < out.length; i++) out[i] = a[i] + (b[i] - a[i]) * t; + return out; +} + +export function normalizeQuat(q: number[]): number[] { + const len = Math.hypot(q[0] ?? 0, q[1] ?? 0, q[2] ?? 0, q[3] ?? 1) || 1; + return [ + (q[0] ?? 0) / len, + (q[1] ?? 0) / len, + (q[2] ?? 0) / len, + (q[3] ?? 1) / len, + ]; +} + +export function slerpQuat(aIn: number[], bIn: number[], t: number): number[] { + const a = normalizeQuat(aIn); + let b = normalizeQuat(bIn); + let cos = a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; + if (cos < 0) { + cos = -cos; + b = [-b[0], -b[1], -b[2], -b[3]]; + } + if (cos > 0.9995) return normalizeQuat(lerpArray(a, b, t)); + const theta = Math.acos(Math.max(-1, Math.min(1, cos))); + const sinTheta = Math.sin(theta); + const wa = Math.sin((1 - t) * theta) / sinTheta; + const wb = Math.sin(t * theta) / sinTheta; + return normalizeQuat([ + a[0] * wa + b[0] * wb, + a[1] * wa + b[1] * wb, + a[2] * wa + b[2] * wb, + a[3] * wa + b[3] * wb, + ]); +} + +export function poseFromNode(node: GltfNode | undefined): NodePose { + return { + translation: node?.translation?.slice() ?? [0, 0, 0], + rotation: node?.rotation?.slice() ?? [0, 0, 0, 1], + scale: node?.scale?.slice() ?? [1, 1, 1], + matrix: node?.matrix && node.matrix.length === 16 ? node.matrix.slice() as Mat4 : undefined, + }; +} + +export function poseLocalMatrix(pose: NodePose): Mat4 { + if (pose.matrix) return pose.matrix.slice() as Mat4; + return trsToMat4(pose.translation, pose.rotation, pose.scale); +} + +function collectSceneRoots(doc: GltfDoc): number[] { + const sceneIdx = doc.scene ?? 0; + const roots = doc.scenes?.[sceneIdx]?.nodes; + if (roots && roots.length > 0) return roots; + return []; +} + +export function computeWorldMatrices(doc: GltfDoc, localMatrices: Mat4[]): Mat4[] { + const nodes = doc.nodes ?? []; + const worlds: Mat4[] = new Array(nodes.length); + const visited = new Set(); + const visiting = new Set(); + + const walk = (nodeIdx: number, parentWorld: Mat4): void => { + if (nodeIdx < 0 || nodeIdx >= nodes.length) return; + if (visiting.has(nodeIdx)) return; + const world = mulMat4(parentWorld, localMatrices[nodeIdx] ?? IDENTITY4); + worlds[nodeIdx] = world; + visited.add(nodeIdx); + visiting.add(nodeIdx); + for (const child of nodes[nodeIdx].children ?? []) walk(child, world); + visiting.delete(nodeIdx); + }; + + const roots = collectSceneRoots(doc); + if (roots.length > 0) { + for (const root of roots) walk(root, IDENTITY4); + } + for (let i = 0; i < nodes.length; i++) { + if (!visited.has(i)) walk(i, IDENTITY4); + } + return worlds; +} + +function sameProjectedVertex(a: Vec3, b: Vec3): boolean { + return a[0] === b[0] && a[1] === b[1] && a[2] === b[2]; +} + +export function isDegenerateProjectedTriangle(v0: Vec3, v1: Vec3, v2: Vec3): boolean { + return sameProjectedVertex(v0, v1) || sameProjectedVertex(v0, v2) || sameProjectedVertex(v1, v2); +} diff --git a/packages/core/src/parser/gltf/types.ts b/packages/core/src/parser/gltf/types.ts new file mode 100644 index 000000000..c9f14ff7d --- /dev/null +++ b/packages/core/src/parser/gltf/types.ts @@ -0,0 +1,308 @@ +import type { + PolyTextureAlphaMode, + PolyTextureWrap, + Vec2, + Vec3, +} from "../../types"; +import type { ParseAnimationClip } from "../types"; + +export interface GltfParseOptions { + /** Largest mesh extent (units). Mesh is uniformly scaled to fit. Default 60. */ + targetSize?: number; + /** Color used when a primitive has no material or no baseColorFactor. */ + defaultColor?: string; + /** + * Override map: glTF material name → CSS color string. Falls back to the + * material's `pbrMetallicRoughness.baseColorFactor` if not in this map. + */ + materialColors?: Record; + /** + * Override map: glTF material name → texture image URL. Takes priority over + * `pbrMetallicRoughness.baseColorTexture`; useful for GLB/GLTF exports that + * preserved UVs but dropped external image references. + */ + materialTextures?: Record; + /** + * Which axis is "up" in the source mesh. + * - "y" (default, glTF spec): cyclic permutation (x,y,z) → (z,x,y) so + * +Y ends up on PolyCSS's +Z (elevation). + * - "z" (Blender-style, FBX2glTF often emits this): identity, no swap. + * Pick "z" if the model lands on its side / lies down instead of + * standing. + */ + upAxis?: "y" | "z"; + /** + * Where to place the mesh-local origin relative to the parsed geometry. + * + * - `"min"` (default): bbox-min sits at local (0,0,0); geometry lives in + * the +X+Y+Z quadrant. This is PolyCSS's historical behavior. + * - `true` (or `"center"`): bbox-center sits at local (0,0,0); geometry + * is centered around the origin. Pair with `scene.add(parse, {position, + * rotation:[...]})` to get three.js-style rotate-in-place around the + * centroid. + */ + center?: boolean | "min" | "center"; + /** + * For .gltf (non-binary) — resolve a glTF buffer URI to its bytes. The + * built-in parser handles GLB binary chunks natively; .gltf files with + * external .bin files need this. + */ + resolveBuffer?: (uri: string) => Promise | Uint8Array; + /** + * Base URL the source file lives at. Used to resolve external image URIs + * (`doc.images[i].uri = "Textures/foo.png"`) against the GLB/glTF's + * location. Without this, relative URIs would resolve against the page, + * which 404s. Pass the same URL you fetched the file from. + */ + baseUrl?: string; +} + +export const GLB_MAGIC = 0x46546c67; // "glTF" little-endian +export const CHUNK_JSON = 0x4e4f534a; +export const CHUNK_BIN = 0x004e4942; + +export const COMPONENT_BYTES: Record = { + 5120: 1, // BYTE + 5121: 1, // UNSIGNED_BYTE + 5122: 2, // SHORT + 5123: 2, // UNSIGNED_SHORT + 5125: 4, // UNSIGNED_INT + 5126: 4, // FLOAT +}; + +export const TYPE_COUNT: Record = { + SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4, MAT2: 4, MAT3: 9, MAT4: 16, +}; + +export const PRIMITIVE_MODE_NAMES: Record = { + 0: "POINTS", + 1: "LINES", + 2: "LINE_LOOP", + 3: "LINE_STRIP", + 4: "TRIANGLES", + 5: "TRIANGLE_STRIP", + 6: "TRIANGLE_FAN", +}; + +export const MESHOPT_COMPRESSION_EXTENSIONS = [ + "EXT_meshopt_compression", + "KHR_meshopt_compression", +] as const; + +export interface GltfAccessor { + bufferView?: number; + byteOffset?: number; + componentType: number; + count: number; + type: string; + normalized?: boolean; + sparse?: { + count: number; + indices: { + bufferView: number; + byteOffset?: number; + componentType: number; + }; + values: { + bufferView: number; + byteOffset?: number; + }; + }; +} +export interface GltfBufferView { + buffer: number; + byteOffset?: number; + byteLength: number; + byteStride?: number; + extensions?: Record; +} +export interface GltfBuffer { + byteLength: number; + uri?: string; + extensions?: Record; +} +export interface GltfTextureInfo { + index: number; // index into doc.textures[] + texCoord?: number; +} +export interface GltfMaterial { + name?: string; + doubleSided?: boolean; + alphaMode?: string; + pbrMetallicRoughness?: { + baseColorFactor?: number[]; + baseColorTexture?: GltfTextureInfo; + }; +} +export interface GltfImage { + uri?: string; + bufferView?: number; + mimeType?: string; +} +export interface GltfTexture { + source?: number; // index into doc.images[] + sampler?: number; // index into doc.samplers[] +} +export interface GltfSampler { + wrapS?: number; + wrapT?: number; +} +export interface GltfPrimitive { + attributes: { POSITION: number;[k: string]: number }; + indices?: number; + material?: number; + extensions?: Record; + targets?: Array<{ POSITION?: number;[k: string]: number | undefined }>; + /** glTF mode: 4 = TRIANGLES, 5 = TRIANGLE_STRIP, 6 = TRIANGLE_FAN. */ + mode?: number; +} +export interface GltfMesh { + name?: string; + primitives: GltfPrimitive[]; + weights?: number[]; +} +export interface GltfNode { + name?: string; + mesh?: number; + skin?: number; + children?: number[]; + weights?: number[]; + /** TRS — PolyCSS reads either matrix or these three components. */ + matrix?: number[]; + translation?: number[]; + rotation?: number[]; // quaternion (x, y, z, w) + scale?: number[]; +} +export interface GltfSkin { + joints: number[]; + inverseBindMatrices?: number; + skeleton?: number; + name?: string; +} +export interface GltfAnimationSampler { + input: number; + output: number; + interpolation?: "LINEAR" | "STEP" | "CUBICSPLINE" | string; +} +export interface GltfAnimationChannel { + sampler: number; + target: { + node?: number; + path?: "translation" | "rotation" | "scale" | string; + }; +} +export interface GltfAnimation { + name?: string; + samplers?: GltfAnimationSampler[]; + channels?: GltfAnimationChannel[]; +} +export interface GltfScene { + nodes?: number[]; +} +export interface GltfDoc { + asset?: { + version?: string; + minVersion?: string; + }; + extensionsRequired?: string[]; + extensionsUsed?: string[]; + scene?: number; + scenes?: GltfScene[]; + nodes?: GltfNode[]; + meshes?: GltfMesh[]; + materials?: GltfMaterial[]; + accessors?: GltfAccessor[]; + bufferViews?: GltfBufferView[]; + buffers?: GltfBuffer[]; + images?: GltfImage[]; + textures?: GltfTexture[]; + samplers?: GltfSampler[]; + skins?: GltfSkin[]; + animations?: GltfAnimation[]; +} + +export type AccessorArray = + | Float32Array + | Uint16Array + | Uint32Array + | Uint8Array + | Int8Array + | Int16Array; + +export interface GltfMaterialTextureInfo { + url: string; + wrap: PolyTextureWrap; + alphaMode: PolyTextureAlphaMode; + texCoord: number; +} + +export type Mat4 = number[]; // length 16, column-major like glTF + +export interface NodePose { + translation: number[]; + rotation: number[]; + scale: number[]; + matrix?: Mat4; +} + +export interface AnimatedPrimitiveSource { + sourceIndex: number; + meshNode: number | null; + meshBindWorld: Mat4; + skinIndex?: number; + positions: Vec3[]; + indices: number[]; + triangleMask: boolean[]; + color: string; + texture?: string; + textureWrap?: PolyTextureWrap; + textureAlphaMode?: PolyTextureAlphaMode; + doubleSided?: boolean; + uvs?: Vec2[]; + joints?: number[][]; + weights?: number[][]; +} + +export interface RuntimeAnimationSampler { + input: number[]; + output: number[]; + componentCount: number; + interpolation: string; +} + +export interface RuntimeAnimationChannel { + sampler: RuntimeAnimationSampler; + targetNode: number; + path: string; +} + +export interface RuntimeAnimationClip { + info: ParseAnimationClip; + channels: RuntimeAnimationChannel[]; +} + +export interface AnimatedPolygonSourceRef { + sourceIndex: number; + triangleIndex: number; +} + +export interface RuntimeSourceTriangleMask { + triangleMask: readonly boolean[]; + activeVertices: readonly number[]; +} + +export interface RawTri { + v0: Vec3; + v1: Vec3; + v2: Vec3; + color: string; + texture?: string; + textureWrap?: PolyTextureWrap; + textureAlphaMode?: PolyTextureAlphaMode; + doubleSided?: boolean; + uvs?: Vec2[]; + simplifySourceVertexKeys?: string[]; + source?: AnimatedPrimitiveSource; + sourceIndex?: number; + sourceTriangleIndex?: number; +} diff --git a/packages/core/src/parser/parseGltf.test.ts b/packages/core/src/parser/parseGltf.test.ts index 49ae31169..673116de5 100644 --- a/packages/core/src/parser/parseGltf.test.ts +++ b/packages/core/src/parser/parseGltf.test.ts @@ -1976,4 +1976,44 @@ describe("parseGltf", () => { expect(result.polygons).toHaveLength(1); }); }); + + describe("error cleanup", () => { + it("revokes minted image blob URLs if parsing throws after image extraction", () => { + const pngHeader = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); + const doc = { + asset: { version: "2.0" }, + scene: 0, + scenes: [{ nodes: [0] }], + nodes: [{ mesh: 0 }], + meshes: [{ primitives: [{ attributes: { POSITION: 0 }, mode: 4 }] }], + // Out-of-bounds bufferView throws during accessor read, AFTER image extraction. + accessors: [{ bufferView: 1, componentType: 5126, count: 3, type: "VEC3" }], + images: [{ bufferView: 0, mimeType: "image/png" }], + bufferViews: [ + { buffer: 0, byteOffset: 0, byteLength: pngHeader.length }, + { buffer: 0, byteOffset: 0, byteLength: 99999 }, + ], + buffers: [{ byteLength: pngHeader.length }], + }; + const glb = buildGlb({ doc, binData: pngHeader }); + const minted: string[] = []; + const revoked: string[] = []; + const createSpy = vi.spyOn(URL, "createObjectURL").mockImplementation(() => { + const url = `blob:test-gltf-${minted.length}`; + minted.push(url); + return url; + }); + const revokeSpy = vi.spyOn(URL, "revokeObjectURL").mockImplementation((url: string) => { + revoked.push(url); + }); + try { + expect(() => parseGltf(glb)).toThrow(); + expect(minted).toHaveLength(1); + expect(revoked).toEqual(minted); + } finally { + createSpy.mockRestore(); + revokeSpy.mockRestore(); + } + }); + }); }); diff --git a/packages/core/src/parser/parseGltf.ts b/packages/core/src/parser/parseGltf.ts index 415bd6b6b..1b50790af 100644 --- a/packages/core/src/parser/parseGltf.ts +++ b/packages/core/src/parser/parseGltf.ts @@ -22,1378 +22,53 @@ * PolyCSS's +Z-up without inverting handedness — a single y↔z swap would * flip every triangle's winding and break backface culling). */ -import type { - Polygon, - PolyTextureAlphaMode, - PolyTextureWrap, - PolyTextureWrapMode, - Vec2, - Vec3, -} from "../types"; +import type { Polygon, Vec2, Vec3 } from "../types"; import { transformPointMat4 as transformPoint } from "../math/vec3"; -import type { ParseAnimationController, ParseAnimationClip, ParseResult } from "./types"; - -export interface GltfParseOptions { - /** Largest mesh extent (units). Mesh is uniformly scaled to fit. Default 60. */ - targetSize?: number; - /** Color used when a primitive has no material or no baseColorFactor. */ - defaultColor?: string; - /** - * Override map: glTF material name → CSS color string. Falls back to the - * material's `pbrMetallicRoughness.baseColorFactor` if not in this map. - */ - materialColors?: Record; - /** - * Override map: glTF material name → texture image URL. Takes priority over - * `pbrMetallicRoughness.baseColorTexture`; useful for GLB/GLTF exports that - * preserved UVs but dropped external image references. - */ - materialTextures?: Record; - /** - * Which axis is "up" in the source mesh. - * - "y" (default, glTF spec): cyclic permutation (x,y,z) → (z,x,y) so - * +Y ends up on PolyCSS's +Z (elevation). - * - "z" (Blender-style, FBX2glTF often emits this): identity, no swap. - * Pick "z" if the model lands on its side / lies down instead of - * standing. - */ - upAxis?: "y" | "z"; - /** - * Where to place the mesh-local origin relative to the parsed geometry. - * - * - `"min"` (default): bbox-min sits at local (0,0,0); geometry lives in - * the +X+Y+Z quadrant. This is PolyCSS's historical behavior. - * - `true` (or `"center"`): bbox-center sits at local (0,0,0); geometry - * is centered around the origin. Pair with `scene.add(parse, {position, - * rotation:[...]})` to get three.js-style rotate-in-place around the - * centroid. - */ - center?: boolean | "min" | "center"; - /** - * For .gltf (non-binary) — resolve a glTF buffer URI to its bytes. The - * built-in parser handles GLB binary chunks natively; .gltf files with - * external .bin files need this. - */ - resolveBuffer?: (uri: string) => Promise | Uint8Array; - /** - * Base URL the source file lives at. Used to resolve external image URIs - * (`doc.images[i].uri = "Textures/foo.png"`) against the GLB/glTF's - * location. Without this, relative URIs would resolve against the page, - * which 404s. Pass the same URL you fetched the file from. - */ - baseUrl?: string; -} - -const GLB_MAGIC = 0x46546c67; // "glTF" little-endian -const CHUNK_JSON = 0x4e4f534a; -const CHUNK_BIN = 0x004e4942; - -const COMPONENT_BYTES: Record = { - 5120: 1, // BYTE - 5121: 1, // UNSIGNED_BYTE - 5122: 2, // SHORT - 5123: 2, // UNSIGNED_SHORT - 5125: 4, // UNSIGNED_INT - 5126: 4, // FLOAT -}; - -const TYPE_COUNT: Record = { - SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4, MAT2: 4, MAT3: 9, MAT4: 16, -}; - -const PRIMITIVE_MODE_NAMES: Record = { - 0: "POINTS", - 1: "LINES", - 2: "LINE_LOOP", - 3: "LINE_STRIP", - 4: "TRIANGLES", - 5: "TRIANGLE_STRIP", - 6: "TRIANGLE_FAN", -}; - -const MESHOPT_COMPRESSION_EXTENSIONS = [ - "EXT_meshopt_compression", - "KHR_meshopt_compression", -] as const; - -function isQuantizedPositionComponentType(componentType: number): boolean { - return ( - componentType === 5120 || - componentType === 5121 || - componentType === 5122 || - componentType === 5123 - ); -} - -interface GltfAccessor { - bufferView?: number; - byteOffset?: number; - componentType: number; - count: number; - type: string; - normalized?: boolean; - sparse?: { - count: number; - indices: { - bufferView: number; - byteOffset?: number; - componentType: number; - }; - values: { - bufferView: number; - byteOffset?: number; - }; - }; -} -interface GltfBufferView { - buffer: number; - byteOffset?: number; - byteLength: number; - byteStride?: number; - extensions?: Record; -} -interface GltfBuffer { - byteLength: number; - uri?: string; - extensions?: Record; -} -interface GltfTextureInfo { - index: number; // index into doc.textures[] - texCoord?: number; -} -interface GltfMaterial { - name?: string; - doubleSided?: boolean; - alphaMode?: string; - pbrMetallicRoughness?: { - baseColorFactor?: number[]; - baseColorTexture?: GltfTextureInfo; - }; -} -interface GltfImage { - uri?: string; - bufferView?: number; - mimeType?: string; -} -interface GltfTexture { - source?: number; // index into doc.images[] - sampler?: number; // index into doc.samplers[] -} -interface GltfSampler { - wrapS?: number; - wrapT?: number; -} -interface GltfPrimitive { - attributes: { POSITION: number;[k: string]: number }; - indices?: number; - material?: number; - extensions?: Record; - targets?: Array<{ POSITION?: number;[k: string]: number | undefined }>; - /** glTF mode: 4 = TRIANGLES, 5 = TRIANGLE_STRIP, 6 = TRIANGLE_FAN. */ - mode?: number; -} -interface GltfMesh { - name?: string; - primitives: GltfPrimitive[]; - weights?: number[]; -} -interface GltfNode { - name?: string; - mesh?: number; - skin?: number; - children?: number[]; - weights?: number[]; - /** TRS — PolyCSS reads either matrix or these three components. */ - matrix?: number[]; - translation?: number[]; - rotation?: number[]; // quaternion (x, y, z, w) - scale?: number[]; -} -interface GltfSkin { - joints: number[]; - inverseBindMatrices?: number; - skeleton?: number; - name?: string; -} -interface GltfAnimationSampler { - input: number; - output: number; - interpolation?: "LINEAR" | "STEP" | "CUBICSPLINE" | string; -} -interface GltfAnimationChannel { - sampler: number; - target: { - node?: number; - path?: "translation" | "rotation" | "scale" | string; - }; -} -interface GltfAnimation { - name?: string; - samplers?: GltfAnimationSampler[]; - channels?: GltfAnimationChannel[]; -} -interface GltfScene { - nodes?: number[]; -} -interface GltfDoc { - asset?: { - version?: string; - minVersion?: string; - }; - extensionsRequired?: string[]; - extensionsUsed?: string[]; - scene?: number; - scenes?: GltfScene[]; - nodes?: GltfNode[]; - meshes?: GltfMesh[]; - materials?: GltfMaterial[]; - accessors?: GltfAccessor[]; - bufferViews?: GltfBufferView[]; - buffers?: GltfBuffer[]; - images?: GltfImage[]; - textures?: GltfTexture[]; - samplers?: GltfSampler[]; - skins?: GltfSkin[]; - animations?: GltfAnimation[]; -} - -function decodeUtf8(bytes: Uint8Array): string { - const Decoder = (globalThis as unknown as { TextDecoder: new () => { decode: (a: Uint8Array) => string } }).TextDecoder; - return new Decoder().decode(bytes); -} - -/** - * Decode a base64-encoded `data:` URI to bytes. glTF JSON files often embed - * the buffer this way (`data:application/octet-stream;base64,...`). - */ -function dataUriToBytes(uri: string): Uint8Array { - const comma = uri.indexOf(","); - if (comma < 0) throw new Error("parseGltf: malformed data: URI"); - const meta = uri.slice(5, comma); // strip "data:" - const payload = uri.slice(comma + 1); - if (!meta.includes(";base64")) { - const text = decodeURIComponent(payload); - const out = new Uint8Array(text.length); - for (let i = 0; i < text.length; i++) out[i] = text.charCodeAt(i) & 0xff; - return out; - } - const bin = (globalThis as unknown as { atob: (s: string) => string }).atob(payload); - const out = new Uint8Array(bin.length); - for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); - return out; -} - -function parseGlbContainer(buf: ArrayBuffer): { doc: GltfDoc; bin: Uint8Array | null } { - const view = new DataView(buf); - if (view.getUint32(0, true) !== GLB_MAGIC) throw new Error("parseGltf: not a GLB (bad magic)"); - const version = view.getUint32(4, true); - if (version !== 2) throw new Error(`parseGltf: only glTF v2 supported (got v${version})`); - - let offset = 12; - let doc: GltfDoc | null = null; - let bin: Uint8Array | null = null; - while (offset < buf.byteLength) { - const len = view.getUint32(offset, true); - const type = view.getUint32(offset + 4, true); - const start = offset + 8; - if (type === CHUNK_JSON) { - const bytes = new Uint8Array(buf, start, len); - doc = JSON.parse(decodeUtf8(bytes)); - } else if (type === CHUNK_BIN) { - bin = new Uint8Array(buf, start, len); - } - offset = start + len; - } - if (!doc) throw new Error("parseGltf: no JSON chunk in GLB"); - return { doc, bin }; -} - -function parseVersionString(value: string | undefined): [number, number] | null { - if (!value) return null; - const match = /^(\d+)\.(\d+)(?:\D.*)?$/.exec(value); - if (!match) return null; - return [Number(match[1]), Number(match[2])]; -} - -function validateGltfAsset(doc: GltfDoc): void { - const version = parseVersionString(doc.asset?.version); - if (!version || version[0] !== 2) { - throw new Error(`parseGltf: only glTF asset v2 supported (got ${doc.asset?.version ?? "missing"})`); - } - const minVersion = parseVersionString(doc.asset?.minVersion); - if (doc.asset?.minVersion && (!minVersion || minVersion[0] > 2 || (minVersion[0] === 2 && minVersion[1] > 0))) { - throw new Error(`parseGltf: glTF asset requires minVersion ${doc.asset.minVersion}`); - } -} - -function resolveBuffers( - doc: GltfDoc, - glbBin: Uint8Array | null, - resolveBuffer?: (uri: string) => Uint8Array | Promise, -): Uint8Array[] { - const specs = doc.buffers ?? []; - const requiredExtensions = new Set(doc.extensionsRequired ?? []); - const canSkipMeshoptFallbackBuffers = MESHOPT_COMPRESSION_EXTENSIONS.some((extensionName) => - requiredExtensions.has(extensionName) - ); - return specs.map((buffer, index) => { - const uri = buffer.uri; - if (uri) { - if (uri.startsWith("data:")) return dataUriToBytes(uri); - if (resolveBuffer) { - const result = resolveBuffer(uri); - if (result instanceof Uint8Array) return result; - throw new Error("parseGltf: resolveBuffer returned a Promise; use parseGltf via async if your buffers are external"); - } - throw new Error(`parseGltf: external buffer URI "${uri}" — provide options.resolveBuffer`); - } - if (index === 0 && glbBin) return glbBin; - if ( - canSkipMeshoptFallbackBuffers && - MESHOPT_COMPRESSION_EXTENSIONS.some((extensionName) => buffer.extensions?.[extensionName]) - ) { - return new Uint8Array(0); - } - throw new Error(`parseGltf: buffer[${index}] has no uri and no GLB BIN chunk`); - }); -} - -function resolveBufferView( - doc: GltfDoc, - buffers: Uint8Array[], - bufferViewIdx: number, -): { buffer: Uint8Array; view: GltfBufferView } { - const view = doc.bufferViews?.[bufferViewIdx]; - const buffer = view ? buffers[view.buffer] : undefined; - if (!view || !buffer) throw new Error(`parseGltf: bad bufferView ${bufferViewIdx}`); - const offset = view.byteOffset ?? 0; - if (offset < 0 || view.byteLength < 0 || offset + view.byteLength > buffer.byteLength) { - throw new Error(`parseGltf: bufferView ${bufferViewIdx} outside buffer ${view.buffer}`); - } - return { buffer, view }; -} - -function assertAccessorFits(acc: GltfAccessor, view: GltfBufferView, stride: number, packedBytes: number): void { - if (acc.count <= 0) return; - const relativeOffset = acc.byteOffset ?? 0; - const byteEnd = relativeOffset + stride * (acc.count - 1) + packedBytes; - if (relativeOffset < 0 || byteEnd > view.byteLength) { - throw new Error("parseGltf: accessor does not fit bufferView"); - } -} - -function resolveAccessorStride(view: GltfBufferView, packedBytes: number): number { - return view.byteStride !== undefined && view.byteStride > 0 ? view.byteStride : packedBytes; -} - -type AccessorArray = Float32Array | Uint16Array | Uint32Array | Uint8Array | Int8Array | Int16Array; - -function typedArrayFromValues(componentType: number, values: number[], normalized: boolean | undefined): AccessorArray { - if (normalized || componentType === 5126) return new Float32Array(values); - switch (componentType) { - case 5120: return new Int8Array(values); - case 5121: return new Uint8Array(values); - case 5122: return new Int16Array(values); - case 5123: return new Uint16Array(values); - case 5125: return new Uint32Array(values); - default: throw new Error(`parseGltf: unhandled componentType ${componentType}`); - } -} - -function readAccessor(doc: GltfDoc, buffers: Uint8Array[], accessorIdx: number): { - array: AccessorArray; - count: number; - componentCount: number; -} { - const acc = doc.accessors?.[accessorIdx]; - if (!acc) throw new Error(`parseGltf: bad accessor ${accessorIdx}`); - const bytesPerComponent = COMPONENT_BYTES[acc.componentType]; - const componentCount = TYPE_COUNT[acc.type]; - if (!bytesPerComponent || !componentCount) { - throw new Error(`parseGltf: unsupported accessor type ${acc.type}/${acc.componentType}`); - } - if (acc.sparse || acc.normalized || acc.bufferView === undefined) { - const { values } = readAccessorComponents(doc, buffers, accessorIdx); - return { array: typedArrayFromValues(acc.componentType, values, acc.normalized), count: acc.count, componentCount }; - } - const { buffer: bin, view } = resolveBufferView(doc, buffers, acc.bufferView); - const offset = (view.byteOffset ?? 0) + (acc.byteOffset ?? 0); - const elements = acc.count * componentCount; - const packedBytes = bytesPerComponent * componentCount; - const stride = resolveAccessorStride(view, packedBytes); - assertAccessorFits(acc, view, stride, packedBytes); - - if (stride === packedBytes) { - const slice = bin.buffer.slice( - bin.byteOffset + offset, - bin.byteOffset + offset + elements * bytesPerComponent, - ); - let array: AccessorArray; - switch (acc.componentType) { - case 5120: array = new Int8Array(slice); break; - case 5121: array = new Uint8Array(slice); break; - case 5122: array = new Int16Array(slice); break; - case 5123: array = new Uint16Array(slice); break; - case 5125: array = new Uint32Array(slice); break; - case 5126: array = new Float32Array(slice); break; - default: throw new Error(`parseGltf: unhandled componentType ${acc.componentType}`); - } - return { array, count: acc.count, componentCount }; - } - - let array: AccessorArray; - switch (acc.componentType) { - case 5120: array = new Int8Array(elements); break; - case 5121: array = new Uint8Array(elements); break; - case 5122: array = new Int16Array(elements); break; - case 5123: array = new Uint16Array(elements); break; - case 5125: array = new Uint32Array(elements); break; - case 5126: array = new Float32Array(elements); break; - default: throw new Error(`parseGltf: unhandled componentType ${acc.componentType}`); - } - - const data = new DataView(bin.buffer); - const start = bin.byteOffset + offset; - let write = 0; - for (let i = 0; i < acc.count; i++) { - const elementOffset = start + i * stride; - for (let c = 0; c < componentCount; c++) { - array[write++] = readRawComponent( - data, - elementOffset + c * bytesPerComponent, - acc.componentType, - ); - } - } - return { array, count: acc.count, componentCount }; -} - -function readRawComponent(data: DataView, offset: number, componentType: number): number { - switch (componentType) { - case 5120: return data.getInt8(offset); - case 5121: return data.getUint8(offset); - case 5122: return data.getInt16(offset, true); - case 5123: return data.getUint16(offset, true); - case 5125: return data.getUint32(offset, true); - case 5126: return data.getFloat32(offset, true); - default: throw new Error(`parseGltf: unhandled componentType ${componentType}`); - } -} - -function normalizeComponent(value: number, componentType: number): number { - switch (componentType) { - case 5120: return Math.max(value / 127, -1); - case 5121: return value / 255; - case 5122: return Math.max(value / 32767, -1); - case 5123: return value / 65535; - default: return value; - } -} - -function readAccessorComponents(doc: GltfDoc, buffers: Uint8Array[], accessorIdx: number): { - values: number[]; - count: number; - componentCount: number; -} { - const acc = doc.accessors?.[accessorIdx]; - if (!acc) throw new Error(`parseGltf: bad accessor ${accessorIdx}`); - const bytesPerComponent = COMPONENT_BYTES[acc.componentType]; - const componentCount = TYPE_COUNT[acc.type]; - if (!bytesPerComponent || !componentCount) { - throw new Error(`parseGltf: unsupported accessor type ${acc.type}/${acc.componentType}`); - } - const packedBytes = bytesPerComponent * componentCount; - const values = new Array(acc.count * componentCount).fill(0); - if (acc.bufferView !== undefined) { - const { buffer, view } = resolveBufferView(doc, buffers, acc.bufferView); - const start = buffer.byteOffset + (view.byteOffset ?? 0) + (acc.byteOffset ?? 0); - const stride = resolveAccessorStride(view, packedBytes); - assertAccessorFits(acc, view, stride, packedBytes); - const data = new DataView(buffer.buffer); - let write = 0; - for (let i = 0; i < acc.count; i++) { - const elementOffset = start + i * stride; - for (let c = 0; c < componentCount; c++) { - const raw = readRawComponent(data, elementOffset + c * bytesPerComponent, acc.componentType); - values[write++] = acc.normalized ? normalizeComponent(raw, acc.componentType) : raw; - } - } - } - if (acc.sparse) { - const sparse = acc.sparse; - const sparseIndices = sparse.indices; - const sparseIndexBytes = COMPONENT_BYTES[sparseIndices.componentType]; - if ( - sparseIndices.componentType !== 5121 && - sparseIndices.componentType !== 5123 && - sparseIndices.componentType !== 5125 - ) { - throw new Error(`parseGltf: unhandled sparse index componentType ${sparseIndices.componentType}`); - } - const { buffer: indexBuffer, view: indexView } = resolveBufferView(doc, buffers, sparseIndices.bufferView); - const indexStart = indexBuffer.byteOffset + (indexView.byteOffset ?? 0) + (sparseIndices.byteOffset ?? 0); - const indexData = new DataView(indexBuffer.buffer); - const { buffer: valueBuffer, view: valueView } = resolveBufferView(doc, buffers, sparse.values.bufferView); - const valueStart = valueBuffer.byteOffset + (valueView.byteOffset ?? 0) + (sparse.values.byteOffset ?? 0); - const valueData = new DataView(valueBuffer.buffer); - for (let i = 0; i < sparse.count; i++) { - const targetIndex = readRawComponent(indexData, indexStart + i * sparseIndexBytes, sparseIndices.componentType); - for (let c = 0; c < componentCount; c++) { - const raw = readRawComponent(valueData, valueStart + (i * componentCount + c) * bytesPerComponent, acc.componentType); - values[targetIndex * componentCount + c] = acc.normalized ? normalizeComponent(raw, acc.componentType) : raw; - } - } - } - return { values, count: acc.count, componentCount }; -} - -function extractImageUrls( - doc: GltfDoc, - buffers: Uint8Array[], - baseUrl?: string, -): { urls: string[]; objectUrls: string[] } { - const urls: string[] = []; - const objectUrls: string[] = []; - const g = globalThis as unknown as { - Blob: new (parts: ArrayLike[] | Uint8Array[], opts?: { type?: string }) => unknown; - URL: { createObjectURL: (b: unknown) => string; new (u: string, base?: string): { href: string } }; - }; - for (const img of doc.images ?? []) { - if (img.uri) { - if (baseUrl && !img.uri.startsWith("data:")) { - try { - urls.push(new g.URL(img.uri, baseUrl).href); - } catch { - urls.push(img.uri); - } - } else { - urls.push(img.uri); - } - continue; - } - if (img.bufferView !== undefined) { - let bytes: Uint8Array; - try { - const { buffer, view } = resolveBufferView(doc, buffers, img.bufferView); - const offset = view.byteOffset ?? 0; - bytes = buffer.subarray(offset, offset + view.byteLength); - } catch { - urls.push(""); - continue; - } - const mime = img.mimeType ?? "image/png"; - const blob = new g.Blob([bytes], { type: mime }); - const url = g.URL.createObjectURL(blob); - urls.push(url); - objectUrls.push(url); - } else { - urls.push(""); - } - } - return { urls, objectUrls }; -} - -interface GltfMaterialTextureInfo { - url: string; - wrap: PolyTextureWrap; - alphaMode: PolyTextureAlphaMode; - texCoord: number; -} - -function gltfWrapMode(value: number | undefined): PolyTextureWrapMode { - switch (value ?? 10497) { - case 33071: return "clamp-to-edge"; - case 33648: return "mirrored-repeat"; - case 10497: return "repeat"; - default: return "repeat"; - } -} - -function textureWrapForTexture(doc: GltfDoc, texture: GltfTexture | undefined): PolyTextureWrap { - const sampler = texture?.sampler !== undefined ? doc.samplers?.[texture.sampler] : undefined; - return { - s: gltfWrapMode(sampler?.wrapS), - t: gltfWrapMode(sampler?.wrapT), - }; -} - -function gltfAlphaMode(value: string | undefined): PolyTextureAlphaMode { - switch (value) { - case "BLEND": return "blend"; - case "MASK": return "mask"; - case "OPAQUE": - default: return "opaque"; - } -} - -function buildMaterialTextureMap(doc: GltfDoc, imageUrls: string[]): Map { - const out = new Map(); - const mats = doc.materials ?? []; - for (let i = 0; i < mats.length; i++) { - const texIdx = mats[i].pbrMetallicRoughness?.baseColorTexture?.index; - if (texIdx === undefined) continue; - const texture = doc.textures?.[texIdx]; - const sourceIdx = texture?.source; - if (sourceIdx === undefined) continue; - const url = imageUrls[sourceIdx]; - if (url) { - out.set(i, { - url, - wrap: textureWrapForTexture(doc, texture), - alphaMode: gltfAlphaMode(mats[i].alphaMode), - texCoord: mats[i].pbrMetallicRoughness?.baseColorTexture?.texCoord ?? 0, - }); - } - } - return out; -} - -function colorFromMaterial( - mat: GltfMaterial | undefined, - fallback: string, - alphaMode: PolyTextureAlphaMode, -): string { - const c = mat?.pbrMetallicRoughness?.baseColorFactor; - if (!c || c.length < 3) return fallback; - const clamp01 = (n: number) => Math.max(0, Math.min(1, n)); - const toHex = (n: number) => Math.round(clamp01(n) * 255).toString(16).padStart(2, "0"); - const toByte = (n: number) => Math.round(clamp01(n) * 255); - const alpha = alphaMode === "opaque" ? 1 : clamp01(c[3] ?? 1); - return alpha < 1 - ? `rgba(${toByte(c[0])}, ${toByte(c[1])}, ${toByte(c[2])}, ${Math.round(alpha * 1000) / 1000})` - : `#${toHex(c[0])}${toHex(c[1])}${toHex(c[2])}`; -} - -// ── Node transform math ───────────────────────────────────────────────── - -type Mat4 = number[]; // length 16, column-major like glTF - -const IDENTITY4: Mat4 = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]; - -function mulMat4(a: Mat4, b: Mat4): Mat4 { - const out = new Array(16) as Mat4; - return mulMat4Into(out, a, b); -} - -function mulMat4Into(out: Mat4, a: Mat4, b: Mat4): Mat4 { - for (let row = 0; row < 4; row++) { - for (let col = 0; col < 4; col++) { - out[col * 4 + row] = - a[0 * 4 + row] * b[col * 4 + 0] + - a[1 * 4 + row] * b[col * 4 + 1] + - a[2 * 4 + row] * b[col * 4 + 2] + - a[3 * 4 + row] * b[col * 4 + 3]; - } - } - return out; -} - -function trsToMat4(t?: number[], r?: number[], s?: number[]): Mat4 { - const tx = t?.[0] ?? 0, ty = t?.[1] ?? 0, tz = t?.[2] ?? 0; - const qx = r?.[0] ?? 0, qy = r?.[1] ?? 0, qz = r?.[2] ?? 0, qw = r?.[3] ?? 1; - const sx = s?.[0] ?? 1, sy = s?.[1] ?? 1, sz = s?.[2] ?? 1; - - const x2 = qx + qx, y2 = qy + qy, z2 = qz + qz; - const xx = qx * x2, xy = qx * y2, xz = qx * z2; - const yy = qy * y2, yz = qy * z2, zz = qz * z2; - const wx = qw * x2, wy = qw * y2, wz = qw * z2; - - return [ - (1 - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0, - (xy - wz) * sy, (1 - (xx + zz)) * sy, (yz + wx) * sy, 0, - (xz + wy) * sz, (yz - wx) * sz, (1 - (xx + yy)) * sz, 0, - tx, ty, tz, 1, - ]; -} - -function nodeLocalMatrix(n: GltfNode): Mat4 { - if (n.matrix && n.matrix.length === 16) return n.matrix.slice() as Mat4; - return trsToMat4(n.translation, n.rotation, n.scale); -} - -function lerpArray(a: number[], b: number[], t: number): number[] { - const out = new Array(Math.min(a.length, b.length)); - for (let i = 0; i < out.length; i++) out[i] = a[i] + (b[i] - a[i]) * t; - return out; -} - -function normalizeQuat(q: number[]): number[] { - const len = Math.hypot(q[0] ?? 0, q[1] ?? 0, q[2] ?? 0, q[3] ?? 1) || 1; - return [ - (q[0] ?? 0) / len, - (q[1] ?? 0) / len, - (q[2] ?? 0) / len, - (q[3] ?? 1) / len, - ]; -} - -function slerpQuat(aIn: number[], bIn: number[], t: number): number[] { - const a = normalizeQuat(aIn); - let b = normalizeQuat(bIn); - let cos = a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; - if (cos < 0) { - cos = -cos; - b = [-b[0], -b[1], -b[2], -b[3]]; - } - if (cos > 0.9995) return normalizeQuat(lerpArray(a, b, t)); - const theta = Math.acos(Math.max(-1, Math.min(1, cos))); - const sinTheta = Math.sin(theta); - const wa = Math.sin((1 - t) * theta) / sinTheta; - const wb = Math.sin(t * theta) / sinTheta; - return normalizeQuat([ - a[0] * wa + b[0] * wb, - a[1] * wa + b[1] * wb, - a[2] * wa + b[2] * wb, - a[3] * wa + b[3] * wb, - ]); -} - -interface NodePose { - translation: number[]; - rotation: number[]; - scale: number[]; - matrix?: Mat4; -} - -function poseFromNode(node: GltfNode | undefined): NodePose { - return { - translation: node?.translation?.slice() ?? [0, 0, 0], - rotation: node?.rotation?.slice() ?? [0, 0, 0, 1], - scale: node?.scale?.slice() ?? [1, 1, 1], - matrix: node?.matrix && node.matrix.length === 16 ? node.matrix.slice() as Mat4 : undefined, - }; -} - -function poseLocalMatrix(pose: NodePose): Mat4 { - if (pose.matrix) return pose.matrix.slice() as Mat4; - return trsToMat4(pose.translation, pose.rotation, pose.scale); -} - -function collectSceneRoots(doc: GltfDoc): number[] { - const sceneIdx = doc.scene ?? 0; - const roots = doc.scenes?.[sceneIdx]?.nodes; - if (roots && roots.length > 0) return roots; - return []; -} - -function computeWorldMatrices(doc: GltfDoc, localMatrices: Mat4[]): Mat4[] { - const nodes = doc.nodes ?? []; - const worlds: Mat4[] = new Array(nodes.length); - const visited = new Set(); - const visiting = new Set(); - - const walk = (nodeIdx: number, parentWorld: Mat4): void => { - if (nodeIdx < 0 || nodeIdx >= nodes.length) return; - if (visiting.has(nodeIdx)) return; - const world = mulMat4(parentWorld, localMatrices[nodeIdx] ?? IDENTITY4); - worlds[nodeIdx] = world; - visited.add(nodeIdx); - visiting.add(nodeIdx); - for (const child of nodes[nodeIdx].children ?? []) walk(child, world); - visiting.delete(nodeIdx); - }; - - const roots = collectSceneRoots(doc); - if (roots.length > 0) { - for (const root of roots) walk(root, IDENTITY4); - } - for (let i = 0; i < nodes.length; i++) { - if (!visited.has(i)) walk(i, IDENTITY4); - } - return worlds; -} - -interface AnimatedPrimitiveSource { - sourceIndex: number; - meshNode: number | null; - meshBindWorld: Mat4; - skinIndex?: number; - positions: Vec3[]; - indices: number[]; - triangleMask: boolean[]; - color: string; - texture?: string; - textureWrap?: PolyTextureWrap; - textureAlphaMode?: PolyTextureAlphaMode; - doubleSided?: boolean; - uvs?: Vec2[]; - joints?: number[][]; - weights?: number[][]; -} - -interface RuntimeAnimationSampler { - input: number[]; - output: number[]; - componentCount: number; - interpolation: string; -} - -interface RuntimeAnimationChannel { - sampler: RuntimeAnimationSampler; - targetNode: number; - path: string; -} - -interface RuntimeAnimationClip { - info: ParseAnimationClip; - channels: RuntimeAnimationChannel[]; -} - -interface AnimatedPolygonSourceRef { - sourceIndex: number; - triangleIndex: number; -} - -interface RuntimeSourceTriangleMask { - triangleMask: readonly boolean[]; - activeVertices: readonly number[]; -} - -interface GltfAnimationRuntimeInfo { - withPolygonFilter(indices: readonly number[]): ParseAnimationController | undefined; -} - -const GLTF_ANIMATION_RUNTIME_INFO = Symbol("polycss.gltfAnimationRuntimeInfo"); -const POLY_ANIMATION_TRIANGLE_FRAME_SOURCE = Symbol.for("polycss.animation.triangleFrameSource"); - -interface PolyAnimationTriangleFrame { - polygonCount: number; - vertices: Float64Array; - colors?: readonly (string | undefined)[]; - textureFlags?: readonly boolean[]; - solidTriangles?: boolean; -} - -interface GltfAnimationController extends ParseAnimationController { - [GLTF_ANIMATION_RUNTIME_INFO]?: GltfAnimationRuntimeInfo; - [POLY_ANIMATION_TRIANGLE_FRAME_SOURCE]?: ( - clip: number | string, - timeSeconds: number, - ) => PolyAnimationTriangleFrame | null | undefined; -} - -export function filterGltfAnimationController( - animation: ParseAnimationController | undefined, - indices: readonly number[], -): ParseAnimationController | undefined { - return animation - ? (animation as GltfAnimationController)[GLTF_ANIMATION_RUNTIME_INFO]?.withPolygonFilter(indices) - : undefined; -} - -function sameProjectedVertex(a: Vec3, b: Vec3): boolean { - return a[0] === b[0] && a[1] === b[1] && a[2] === b[2]; -} - -function isDegenerateProjectedTriangle(v0: Vec3, v1: Vec3, v2: Vec3): boolean { - return sameProjectedVertex(v0, v1) || sameProjectedVertex(v0, v2) || sameProjectedVertex(v1, v2); -} - -function readAccessorTupleArray( - doc: GltfDoc, - buffers: Uint8Array[], - accessorIdx: number | undefined, - expectedComponents: number, - expectedCount: number, -): number[][] | undefined { - if (accessorIdx === undefined) return undefined; - const { values, count, componentCount } = readAccessorComponents(doc, buffers, accessorIdx); - if (count !== expectedCount || componentCount < 1) return undefined; - const out: number[][] = []; - for (let i = 0; i < count; i++) { - const tuple: number[] = []; - for (let c = 0; c < expectedComponents; c++) { - tuple.push(values[i * componentCount + c] ?? 0); - } - out.push(tuple); - } - return out; -} - -function readMat4Array(doc: GltfDoc, buffers: Uint8Array[], accessorIdx: number | undefined, count: number): Mat4[] { - if (accessorIdx === undefined) { - return Array.from({ length: count }, () => IDENTITY4.slice() as Mat4); - } - const { values, componentCount, count: accCount } = readAccessorComponents(doc, buffers, accessorIdx); - if (componentCount !== 16) { - throw new Error(`parseGltf: inverseBindMatrices accessor ${accessorIdx} is not MAT4`); - } - const out: Mat4[] = []; - for (let i = 0; i < count; i++) { - const sourceIndex = Math.min(i, accCount - 1); - out.push(values.slice(sourceIndex * 16, sourceIndex * 16 + 16) as Mat4); - } - return out; -} - -function samplerValueAt(sampler: RuntimeAnimationSampler, keyIndex: number): number[] { - const cc = sampler.componentCount; - const base = sampler.interpolation === "CUBICSPLINE" - ? (keyIndex * 3 + 1) * cc - : keyIndex * cc; - return sampler.output.slice(base, base + cc); -} - -function sampleAnimationChannel(sampler: RuntimeAnimationSampler, timeSeconds: number, path: string): number[] { - const times = sampler.input; - if (times.length === 0) return []; - if (times.length === 1 || timeSeconds <= times[0]) return samplerValueAt(sampler, 0); - const lastIndex = times.length - 1; - if (timeSeconds >= times[lastIndex]) return samplerValueAt(sampler, lastIndex); - - let lo = 0; - let hi = lastIndex; - while (lo + 1 < hi) { - const mid = (lo + hi) >> 1; - if (times[mid] <= timeSeconds) lo = mid; - else hi = mid; - } - - const t0 = times[lo]; - const t1 = times[lo + 1]; - const amount = t1 > t0 ? (timeSeconds - t0) / (t1 - t0) : 0; - const a = samplerValueAt(sampler, lo); - const b = samplerValueAt(sampler, lo + 1); - if (sampler.interpolation === "STEP") return a; - if (path === "rotation") return slerpQuat(a, b, amount); - return lerpArray(a, b, amount); -} - -function buildRuntimeAnimationClips(doc: GltfDoc, buffers: Uint8Array[]): RuntimeAnimationClip[] { - const runtimeClips: RuntimeAnimationClip[] = []; - for (let i = 0; i < (doc.animations?.length ?? 0); i++) { - const animation = doc.animations![i]!; - const runtimeSamplers = (animation.samplers ?? []).map((sampler): RuntimeAnimationSampler => { - const input = readAccessorComponents(doc, buffers, sampler.input); - const output = readAccessorComponents(doc, buffers, sampler.output); - return { - input: input.values, - output: output.values, - componentCount: output.componentCount, - interpolation: sampler.interpolation ?? "LINEAR", - }; - }); - - const channels: RuntimeAnimationChannel[] = []; - for (const channel of animation.channels ?? []) { - const targetNode = channel.target.node; - const path = channel.target.path; - const sampler = runtimeSamplers[channel.sampler]; - if (targetNode === undefined || !path || !sampler) continue; - if (path !== "translation" && path !== "rotation" && path !== "scale") continue; - channels.push({ sampler, targetNode, path }); - } - const duration = channels.reduce((max, channel) => { - const times = channel.sampler.input; - return Math.max(max, times[times.length - 1] ?? 0); - }, 0); - runtimeClips.push({ - info: { - index: i, - name: animation.name ?? `animation_${i}`, - duration, - channelCount: channels.length, - }, - channels, - }); - } - return runtimeClips; -} - -function sampleRuntimeClipWorldMatrices( - doc: GltfDoc, - basePoses: NodePose[], - clip: RuntimeAnimationClip, - timeSecondsIn: number, -): Mat4[] { - const duration = clip.info.duration; - const timeSeconds = duration > 0 - ? ((timeSecondsIn % duration) + duration) % duration - : Math.max(0, timeSecondsIn); - - const poses = basePoses.map((pose): NodePose => ({ - translation: pose.translation.slice(), - rotation: pose.rotation.slice(), - scale: pose.scale.slice(), - matrix: pose.matrix ? pose.matrix.slice() as Mat4 : undefined, - })); - - for (const channel of clip.channels) { - const pose = poses[channel.targetNode]; - if (!pose) continue; - const value = sampleAnimationChannel(channel.sampler, timeSeconds, channel.path); - pose.matrix = undefined; - if (channel.path === "translation") pose.translation = value.slice(0, 3); - else if (channel.path === "rotation") pose.rotation = normalizeQuat(value.slice(0, 4)); - else if (channel.path === "scale") pose.scale = value.slice(0, 3); - } - - return computeWorldMatrices(doc, poses.map(poseLocalMatrix)); -} - -function buildAnimationController( - doc: GltfDoc, - buffers: Uint8Array[], - sources: AnimatedPrimitiveSource[], - polygonRefs: Array, - project: (v: Vec3) => Vec3, - projectFrameVertex: (v: Vec3, out: Float64Array, offset: number) => void, -): ParseAnimationController | undefined { - const animations = doc.animations ?? []; - if (animations.length === 0 || sources.length === 0) return undefined; - - const basePoses = (doc.nodes ?? []).map((node) => poseFromNode(node)); - const baseLocalMatrices = basePoses.map(poseLocalMatrix); - const bindWorldMatrices = computeWorldMatrices(doc, baseLocalMatrices); - const skins = (doc.skins ?? []).map((skin) => ({ - joints: skin.joints ?? [], - inverseBindMatrices: readMat4Array(doc, buffers, skin.inverseBindMatrices, skin.joints?.length ?? 0), - })); - const runtimeClips = buildRuntimeAnimationClips(doc, buffers); - - const clips = runtimeClips.map((clip) => clip.info); - if (clips.length === 0) return undefined; - - const sourceMasksFromPolygonFilter = ( - indices: readonly number[], - ): RuntimeSourceTriangleMask[] | undefined => { - const masks = sources.map((source) => new Array(source.triangleMask.length).fill(false)); - for (const index of indices) { - const ref = polygonRefs[index]; - if (!ref) return undefined; - const sourceMask = masks[ref.sourceIndex]; - if (!sourceMask || ref.triangleIndex < 0 || ref.triangleIndex >= sourceMask.length) return undefined; - sourceMask[ref.triangleIndex] = true; - } - - return masks.map((triangleMask, sourceIndex): RuntimeSourceTriangleMask => { - const source = sources[sourceIndex]!; - const used = new Set(); - let triangleOrdinal = 0; - for (let i = 0; i + 2 < source.indices.length; i += 3, triangleOrdinal++) { - if (!triangleMask[triangleOrdinal]) continue; - used.add(source.indices[i]!); - used.add(source.indices[i + 1]!); - used.add(source.indices[i + 2]!); - } - return { - triangleMask, - activeVertices: Array.from(used).sort((a, b) => a - b), - }; - }); - }; - - const polygonFromWorldTri = ( - v0World: Vec3, - v1World: Vec3, - v2World: Vec3, - color: string, - texture: string | undefined, - textureWrap: PolyTextureWrap | undefined, - textureAlphaMode: PolyTextureAlphaMode | undefined, - doubleSided: boolean | undefined, - uvs: Vec2[] | undefined, - ): Polygon | null => { - const v0 = project(v0World); - const v1 = project(v1World); - const v2 = project(v2World); - const polygon: Polygon = { vertices: [v0, v1, v2], color }; - if (texture) polygon.texture = texture; - if (texture && textureWrap) polygon.textureWrap = textureWrap; - if (texture && textureAlphaMode) polygon.textureAlphaMode = textureAlphaMode; - if (doubleSided) polygon.doubleSided = true; - if (uvs) polygon.uvs = uvs; - return polygon; - }; - - const createController = ( - sourceMaskOverrides?: RuntimeSourceTriangleMask[], - ): ParseAnimationController => { - const activeTriangleCapacity = sources.reduce((sum, source, sourceIndex) => { - const mask = sourceMaskOverrides?.[sourceIndex]?.triangleMask ?? source.triangleMask; - let count = 0; - for (let i = 0; i < mask.length; i++) { - if (mask[i]) count++; - } - return sum + count; - }, 0); - let triangleFrameVertices = new Float64Array(Math.max(0, activeTriangleCapacity * 9)); - let triangleFrameColors: Array = new Array(activeTriangleCapacity); - let triangleFrameTextureFlags: boolean[] = new Array(activeTriangleCapacity).fill(false); - const triangleFrame: PolyAnimationTriangleFrame = { - polygonCount: 0, - vertices: triangleFrameVertices, - colors: triangleFrameColors, - textureFlags: triangleFrameTextureFlags, - solidTriangles: true, - }; - const sourceWorldPositionCaches = sources.map( - (source) => new Array(source.positions.length), - ); - const skinJointMatrixCaches: Array> = skins.map((skin) => - skin.joints.map(() => new Array(16) as Mat4) - ); - - const sampleWorldMatrices = ( - clipRef: number | string, - timeSecondsIn: number, - ): Mat4[] | null => { - const clip = typeof clipRef === "number" - ? runtimeClips[clipRef] - : runtimeClips.find((candidate) => candidate.info.name === clipRef); - if (!clip) return null; - return sampleRuntimeClipWorldMatrices(doc, basePoses, clip, timeSecondsIn); - }; - - const computeSourceWorldPositions = ( - sourceIndex: number, - source: AnimatedPrimitiveSource, - sourceMask: RuntimeSourceTriangleMask | undefined, - worldMatrices: Mat4[], - ): Array => { - const activeVertices = sourceMask?.activeVertices; - const worldPositions = sourceWorldPositionCaches[sourceIndex]!; - const writeWorldPosition = (i: number, x: number, y: number, z: number): void => { - const out = worldPositions[i]; - if (out) { - out[0] = x; - out[1] = y; - out[2] = z; - } else { - worldPositions[i] = [x, y, z]; - } - }; - if ( - source.skinIndex !== undefined && - source.joints && - source.weights && - skins[source.skinIndex] - ) { - const skin = skins[source.skinIndex]; - const sourceJoints = source.joints; - const sourceWeights = source.weights; - const jointMatrices = skinJointMatrixCaches[source.skinIndex] ?? []; - for (let jointSlot = 0; jointSlot < skin.joints.length; jointSlot++) { - const jointNode = skin.joints[jointSlot]!; - const jointWorld = worldMatrices[jointNode]; - const inverseBind = skin.inverseBindMatrices[jointSlot]; - const out = jointMatrices[jointSlot] ?? (jointMatrices[jointSlot] = new Array(16) as Mat4); - jointMatrices[jointSlot] = jointWorld && inverseBind - ? mulMat4Into(out, jointWorld, inverseBind) - : undefined; - } - const skinVertex = (i: number): void => { - const bindPosition = source.positions[i]; - let blendedX = 0; - let blendedY = 0; - let blendedZ = 0; - let weightSum = 0; - const joints = sourceJoints[i] ?? []; - const weights = sourceWeights[i] ?? []; - for (let j = 0; j < 4; j++) { - const weight = weights[j] ?? 0; - if (weight <= 0) continue; - const jointSlot = Math.round(joints[j] ?? 0); - const jointMatrix = jointMatrices[jointSlot]; - if (!jointMatrix) continue; - const x = - jointMatrix[0] * bindPosition[0] + - jointMatrix[4] * bindPosition[1] + - jointMatrix[8] * bindPosition[2] + - jointMatrix[12]; - const y = - jointMatrix[1] * bindPosition[0] + - jointMatrix[5] * bindPosition[1] + - jointMatrix[9] * bindPosition[2] + - jointMatrix[13]; - const z = - jointMatrix[2] * bindPosition[0] + - jointMatrix[6] * bindPosition[1] + - jointMatrix[10] * bindPosition[2] + - jointMatrix[14]; - blendedX += x * weight; - blendedY += y * weight; - blendedZ += z * weight; - weightSum += weight; - } - if (weightSum > 0) { - const invWeight = 1 / weightSum; - writeWorldPosition(i, blendedX * invWeight, blendedY * invWeight, blendedZ * invWeight); - } else { - writeWorldPosition( - i, - source.meshBindWorld[0] * bindPosition[0] + - source.meshBindWorld[4] * bindPosition[1] + - source.meshBindWorld[8] * bindPosition[2] + - source.meshBindWorld[12], - source.meshBindWorld[1] * bindPosition[0] + - source.meshBindWorld[5] * bindPosition[1] + - source.meshBindWorld[9] * bindPosition[2] + - source.meshBindWorld[13], - source.meshBindWorld[2] * bindPosition[0] + - source.meshBindWorld[6] * bindPosition[1] + - source.meshBindWorld[10] * bindPosition[2] + - source.meshBindWorld[14], - ); - } - }; - if (activeVertices) { - for (const vertexIndex of activeVertices) skinVertex(vertexIndex); - } else { - for (let i = 0; i < source.positions.length; i++) skinVertex(i); - } - } else { - const meshWorld = source.meshNode !== null - ? (worldMatrices[source.meshNode] ?? source.meshBindWorld) - : source.meshBindWorld; - const transformVertex = (i: number): void => { - const sourcePosition = source.positions[i]; - writeWorldPosition( - i, - meshWorld[0] * sourcePosition[0] + - meshWorld[4] * sourcePosition[1] + - meshWorld[8] * sourcePosition[2] + - meshWorld[12], - meshWorld[1] * sourcePosition[0] + - meshWorld[5] * sourcePosition[1] + - meshWorld[9] * sourcePosition[2] + - meshWorld[13], - meshWorld[2] * sourcePosition[0] + - meshWorld[6] * sourcePosition[1] + - meshWorld[10] * sourcePosition[2] + - meshWorld[14], - ); - }; - if (activeVertices) { - for (const vertexIndex of activeVertices) transformVertex(vertexIndex); - } else { - for (let i = 0; i < source.positions.length; i++) transformVertex(i); - } - } - return worldPositions; - }; - - const sample = (clipRef: number | string, timeSecondsIn: number): Polygon[] => { - const worldMatrices = sampleWorldMatrices(clipRef, timeSecondsIn); - if (!worldMatrices) return []; - const polygons: Polygon[] = []; - - for (let sourceIndex = 0; sourceIndex < sources.length; sourceIndex++) { - const source = sources[sourceIndex]!; - const sourceMask = sourceMaskOverrides?.[sourceIndex]; - const triangleMask = sourceMask?.triangleMask ?? source.triangleMask; - const worldPositions = computeSourceWorldPositions( - sourceIndex, - source, - sourceMask, - worldMatrices, - ); - - let triangleOrdinal = 0; - for (let i = 0; i + 2 < source.indices.length; i += 3, triangleOrdinal++) { - if (!triangleMask[triangleOrdinal]) continue; - const i0 = source.indices[i]; - const i1 = source.indices[i + 1]; - const i2 = source.indices[i + 2]; - const v0 = worldPositions[i0]; - const v1 = worldPositions[i1]; - const v2 = worldPositions[i2]; - if (!v0 || !v1 || !v2) continue; - let triUvs: Vec2[] | undefined; - if (source.uvs && source.texture) { - const u0 = source.uvs[i0], u1 = source.uvs[i1], u2 = source.uvs[i2]; - if (u0 && u1 && u2) triUvs = [u0, u1, u2]; - } - const polygon = polygonFromWorldTri( - v0, - v1, - v2, - source.color, - source.texture, - source.textureWrap, - source.textureAlphaMode, - source.doubleSided, - triUvs, - ); - if (polygon) polygons.push(polygon); - } - } - return polygons; - }; - - const sampleTriangleFrame = ( - clipRef: number | string, - timeSecondsIn: number, - ): PolyAnimationTriangleFrame | null => { - const worldMatrices = sampleWorldMatrices(clipRef, timeSecondsIn); - if (!worldMatrices) return null; - if (triangleFrameVertices.length < activeTriangleCapacity * 9) { - triangleFrameVertices = new Float64Array(activeTriangleCapacity * 9); - triangleFrame.vertices = triangleFrameVertices; - } - if (triangleFrameColors.length < activeTriangleCapacity) { - triangleFrameColors = new Array(activeTriangleCapacity); - triangleFrame.colors = triangleFrameColors; - } - if (triangleFrameTextureFlags.length < activeTriangleCapacity) { - triangleFrameTextureFlags = new Array(activeTriangleCapacity).fill(false); - triangleFrame.textureFlags = triangleFrameTextureFlags; - } - let polygonCount = 0; - let writeOffset = 0; - let hasTexture = false; - - for (let sourceIndex = 0; sourceIndex < sources.length; sourceIndex++) { - const source = sources[sourceIndex]!; - const sourceMask = sourceMaskOverrides?.[sourceIndex]; - const triangleMask = sourceMask?.triangleMask ?? source.triangleMask; - const worldPositions = computeSourceWorldPositions( - sourceIndex, - source, - sourceMask, - worldMatrices, - ); - - let triangleOrdinal = 0; - for (let i = 0; i + 2 < source.indices.length; i += 3, triangleOrdinal++) { - if (!triangleMask[triangleOrdinal]) continue; - const i0 = source.indices[i]!; - const i1 = source.indices[i + 1]!; - const i2 = source.indices[i + 2]!; - const v0 = worldPositions[i0]; - const v1 = worldPositions[i1]; - const v2 = worldPositions[i2]; - if (!v0 || !v1 || !v2) continue; - projectFrameVertex(v0, triangleFrameVertices, writeOffset); - projectFrameVertex(v1, triangleFrameVertices, writeOffset + 3); - projectFrameVertex(v2, triangleFrameVertices, writeOffset + 6); - triangleFrameColors[polygonCount] = source.color; - const textured = !!source.texture; - triangleFrameTextureFlags[polygonCount] = textured; - if (textured) hasTexture = true; - polygonCount++; - writeOffset += 9; - } - } - - triangleFrame.polygonCount = polygonCount; - triangleFrame.solidTriangles = !hasTexture; - return triangleFrame; - }; - - const controller: GltfAnimationController = { clips, sample }; - controller[POLY_ANIMATION_TRIANGLE_FRAME_SOURCE] = sampleTriangleFrame; - controller[GLTF_ANIMATION_RUNTIME_INFO] = { - withPolygonFilter(indices) { - const masks = sourceMasksFromPolygonFilter(indices); - return masks ? createController(masks) : undefined; - }, - }; - return controller; - }; - - return createController(); -} +import type { ParseResult } from "./types"; +import { + buildAnimationController, + filterGltfAnimationController, + seedCollapsedRawTrisFromAnimation, +} from "./gltf/animation"; +import { + decodeUtf8, + isQuantizedPositionComponentType, + parseGlbContainer, + readAccessor, + readAccessorTupleArray, + resolveBuffers, + validateGltfAsset, +} from "./gltf/binary"; +import { + buildMaterialTextureMap, + colorFromMaterial, + extractImageUrls, + gltfAlphaMode, + makeDispose, +} from "./gltf/materials"; +import { + IDENTITY4, + isDegenerateProjectedTriangle, + mulMat4, + nodeLocalMatrix, +} from "./gltf/transforms"; +import { + GLB_MAGIC, + MESHOPT_COMPRESSION_EXTENSIONS, + PRIMITIVE_MODE_NAMES, + type AccessorArray, + type AnimatedPolygonSourceRef, + type AnimatedPrimitiveSource, + type GltfDoc, + type GltfMesh, + type GltfParseOptions, + type GltfPrimitive, + type Mat4, + type RawTri, +} from "./gltf/types"; + +export type { GltfParseOptions } from "./gltf/types"; +export { filterGltfAnimationController }; export function parseGltf(input: ArrayBuffer | Uint8Array, options?: GltfParseOptions): ParseResult { const targetSize = options?.targetSize ?? 60; @@ -1419,592 +94,476 @@ export function parseGltf(input: ArrayBuffer | Uint8Array, options?: GltfParseOp const buffers = resolveBuffers(doc, glbBin, options?.resolveBuffer); const { urls: imageUrls, objectUrls } = extractImageUrls(doc, buffers, options?.baseUrl); - const matTexMap = buildMaterialTextureMap(doc, imageUrls); - const warnings: string[] = []; - const warningKeys = new Set(); - const requiredExtensions = new Set(doc.extensionsRequired ?? []); - const usesMeshQuantization = - requiredExtensions.has("KHR_mesh_quantization") || - (doc.extensionsUsed ?? []).includes("KHR_mesh_quantization"); - - function pushWarningOnce(key: string, warning: string): void { - if (warningKeys.has(key)) return; - warningKeys.add(key); - warnings.push(warning); - } - - function accessorUsesBufferViewExtension(accessorIdx: number | undefined, extensionName: string): boolean { - if (accessorIdx === undefined) return false; - const acc = doc.accessors?.[accessorIdx]; - if (!acc) return false; - const bufferViewHasExtension = (bufferViewIdx: number): boolean => - doc.bufferViews?.[bufferViewIdx]?.extensions?.[extensionName] !== undefined; - if (acc.bufferView !== undefined && bufferViewHasExtension(acc.bufferView)) return true; - if (acc.sparse) { - if (bufferViewHasExtension(acc.sparse.indices.bufferView)) return true; - if (bufferViewHasExtension(acc.sparse.values.bufferView)) return true; - } - return false; - } - - function primitiveUsesRequiredMeshopt(prim: GltfPrimitive): string | undefined { - for (const extensionName of MESHOPT_COMPRESSION_EXTENSIONS) { - if (!requiredExtensions.has(extensionName)) continue; - if (prim.extensions?.[extensionName]) return extensionName; - if (accessorUsesBufferViewExtension(prim.indices, extensionName)) return extensionName; - if (Object.values(prim.attributes ?? {}).some((accessorIdx) => - accessorUsesBufferViewExtension(accessorIdx, extensionName) - )) { - return extensionName; + const dispose = makeDispose(objectUrls); + try { + const matTexMap = buildMaterialTextureMap(doc, imageUrls); + const warnings: string[] = []; + const warningKeys = new Set(); + const requiredExtensions = new Set(doc.extensionsRequired ?? []); + const usesMeshQuantization = + requiredExtensions.has("KHR_mesh_quantization") || + (doc.extensionsUsed ?? []).includes("KHR_mesh_quantization"); + + function pushWarningOnce(key: string, warning: string): void { + if (warningKeys.has(key)) return; + warningKeys.add(key); + warnings.push(warning); + } + + function accessorUsesBufferViewExtension(accessorIdx: number | undefined, extensionName: string): boolean { + if (accessorIdx === undefined) return false; + const acc = doc.accessors?.[accessorIdx]; + if (!acc) return false; + const bufferViewHasExtension = (bufferViewIdx: number): boolean => + doc.bufferViews?.[bufferViewIdx]?.extensions?.[extensionName] !== undefined; + if (acc.bufferView !== undefined && bufferViewHasExtension(acc.bufferView)) return true; + if (acc.sparse) { + if (bufferViewHasExtension(acc.sparse.indices.bufferView)) return true; + if (bufferViewHasExtension(acc.sparse.values.bufferView)) return true; + } + return false; + } + + function primitiveUsesRequiredMeshopt(prim: GltfPrimitive): string | undefined { + for (const extensionName of MESHOPT_COMPRESSION_EXTENSIONS) { + if (!requiredExtensions.has(extensionName)) continue; + if (prim.extensions?.[extensionName]) return extensionName; + if (accessorUsesBufferViewExtension(prim.indices, extensionName)) return extensionName; + if (Object.values(prim.attributes ?? {}).some((accessorIdx) => + accessorUsesBufferViewExtension(accessorIdx, extensionName) + )) { + return extensionName; + } } + return undefined; } - return undefined; - } - function canUsePositionAccessor(accessorIdx: number, array: AccessorArray): boolean { - if (array instanceof Float32Array) return true; - const acc = doc.accessors?.[accessorIdx]; - return ( - usesMeshQuantization && - acc?.type === "VEC3" && - isQuantizedPositionComponentType(acc.componentType) - ); - } - - function morphWeightsFor(mesh: GltfMesh, meshNode: number | null): number[] { - const nodeWeights = meshNode !== null ? doc.nodes?.[meshNode]?.weights : undefined; - return nodeWeights ?? mesh.weights ?? []; - } - - function buildMorphPositionOffsets( - mesh: GltfMesh, - meshIdx: number, - prim: GltfPrimitive, - meshNode: number | null, - vertCount: number, - ): Vec3[] | undefined { - const targets = prim.targets; - if (!targets || targets.length === 0) return undefined; - const weights = morphWeightsFor(mesh, meshNode); - if (!weights.some((weight) => Number.isFinite(weight) && weight !== 0)) return undefined; + function canUsePositionAccessor(accessorIdx: number, array: AccessorArray): boolean { + if (array instanceof Float32Array) return true; + const acc = doc.accessors?.[accessorIdx]; + return ( + usesMeshQuantization && + acc?.type === "VEC3" && + isQuantizedPositionComponentType(acc.componentType) + ); + } - const offsets: Vec3[] = Array.from({ length: vertCount }, () => [0, 0, 0]); - let touched = false; - for (let targetIndex = 0; targetIndex < targets.length; targetIndex++) { - const weight = weights[targetIndex] ?? 0; - if (!Number.isFinite(weight) || weight === 0) continue; - const positionAccessor = targets[targetIndex]?.POSITION; - if (positionAccessor === undefined) continue; - const { array, count, componentCount } = readAccessor(doc, buffers, positionAccessor); - if (count !== vertCount || componentCount < 3) { - pushWarningOnce( - `morph-position-count:${meshIdx}:${targetIndex}`, - `Mesh ${mesh.name ?? meshIdx}: skipped morph target ${targetIndex} POSITION with mismatched count`, - ); - continue; - } - if (!canUsePositionAccessor(positionAccessor, array)) { - pushWarningOnce( - `morph-position-type:${meshIdx}:${targetIndex}`, - `Mesh ${mesh.name ?? meshIdx}: skipped morph target ${targetIndex} POSITION with unsupported accessor type`, - ); - continue; - } - touched = true; - for (let i = 0; i < vertCount; i++) { - const base = i * componentCount; - const offset = offsets[i]!; - offset[0] += Number(array[base]) * weight; - offset[1] += Number(array[base + 1]) * weight; - offset[2] += Number(array[base + 2]) * weight; + function morphWeightsFor(mesh: GltfMesh, meshNode: number | null): number[] { + const nodeWeights = meshNode !== null ? doc.nodes?.[meshNode]?.weights : undefined; + return nodeWeights ?? mesh.weights ?? []; + } + + function buildMorphPositionOffsets( + mesh: GltfMesh, + meshIdx: number, + prim: GltfPrimitive, + meshNode: number | null, + vertCount: number, + ): Vec3[] | undefined { + const targets = prim.targets; + if (!targets || targets.length === 0) return undefined; + const weights = morphWeightsFor(mesh, meshNode); + if (!weights.some((weight) => Number.isFinite(weight) && weight !== 0)) return undefined; + + const offsets: Vec3[] = Array.from({ length: vertCount }, () => [0, 0, 0]); + let touched = false; + for (let targetIndex = 0; targetIndex < targets.length; targetIndex++) { + const weight = weights[targetIndex] ?? 0; + if (!Number.isFinite(weight) || weight === 0) continue; + const positionAccessor = targets[targetIndex]?.POSITION; + if (positionAccessor === undefined) continue; + const { array, count, componentCount } = readAccessor(doc, buffers, positionAccessor); + if (count !== vertCount || componentCount < 3) { + pushWarningOnce( + `morph-position-count:${meshIdx}:${targetIndex}`, + `Mesh ${mesh.name ?? meshIdx}: skipped morph target ${targetIndex} POSITION with mismatched count`, + ); + continue; + } + if (!canUsePositionAccessor(positionAccessor, array)) { + pushWarningOnce( + `morph-position-type:${meshIdx}:${targetIndex}`, + `Mesh ${mesh.name ?? meshIdx}: skipped morph target ${targetIndex} POSITION with unsupported accessor type`, + ); + continue; + } + touched = true; + for (let i = 0; i < vertCount; i++) { + const base = i * componentCount; + const offset = offsets[i]!; + offset[0] += Number(array[base]) * weight; + offset[1] += Number(array[base + 1]) * weight; + offset[2] += Number(array[base + 2]) * weight; + } } - } - return touched ? offsets : undefined; - } + return touched ? offsets : undefined; + } - interface RawTri { - v0: Vec3; - v1: Vec3; - v2: Vec3; - color: string; - texture?: string; - textureWrap?: PolyTextureWrap; - textureAlphaMode?: PolyTextureAlphaMode; - doubleSided?: boolean; - uvs?: Vec2[]; - simplifySourceVertexKeys?: string[]; - source?: AnimatedPrimitiveSource; - sourceIndex?: number; - sourceTriangleIndex?: number; - } - const rawTris: RawTri[] = []; - const animatedSources: AnimatedPrimitiveSource[] = []; - const animatedPolygonRefs: Array = []; - const meshNames: string[] = (doc.meshes ?? []).map((m, i) => m.name ?? `mesh_${i}`); - const materialNames: string[] = (doc.materials ?? []).map((m, i) => m.name ?? `material_${i}`); + const rawTris: RawTri[] = []; + const animatedSources: AnimatedPrimitiveSource[] = []; + const animatedPolygonRefs: Array = []; + const meshNames: string[] = (doc.meshes ?? []).map((m, i) => m.name ?? `mesh_${i}`); + const materialNames: string[] = (doc.materials ?? []).map((m, i) => m.name ?? `material_${i}`); - function triangulatePrimitiveIndices(indices: number[], mode: number): number[] { - if (mode === 4) return indices; - const out: number[] = []; - if (mode === 5) { - for (let i = 0; i + 2 < indices.length; i++) { - out.push(indices[i], indices[i + 1 + (i % 2)], indices[i + 2 - (i % 2)]); - } - } else if (mode === 6) { - for (let i = 0; i + 2 < indices.length; i++) { - out.push(indices[i + 1], indices[i + 2], indices[0]); + function triangulatePrimitiveIndices(indices: number[], mode: number): number[] { + if (mode === 4) return indices; + const out: number[] = []; + if (mode === 5) { + for (let i = 0; i + 2 < indices.length; i++) { + out.push(indices[i], indices[i + 1 + (i % 2)], indices[i + 2 - (i % 2)]); + } + } else if (mode === 6) { + for (let i = 0; i + 2 < indices.length; i++) { + out.push(indices[i + 1], indices[i + 2], indices[0]); + } } + return out; } - return out; - } - function makeDoubleSidedTriangleIndices(indices: number[]): number[] { - const out: number[] = []; - for (let i = 0; i + 2 < indices.length; i += 3) { - const i0 = indices[i]; - const i1 = indices[i + 1]; - const i2 = indices[i + 2]; - out.push(i0, i1, i2, i0, i2, i1); + function makeDoubleSidedTriangleIndices(indices: number[]): number[] { + const out: number[] = []; + for (let i = 0; i + 2 < indices.length; i += 3) { + const i0 = indices[i]; + const i1 = indices[i + 1]; + const i2 = indices[i + 2]; + out.push(i0, i1, i2, i0, i2, i1); + } + return out; } - return out; - } - function emitMesh(meshIdx: number, world: Mat4, meshNode: number | null): void { - const mesh = doc.meshes?.[meshIdx]; - if (!mesh) return; - if (!Array.isArray(mesh.primitives)) { - pushWarningOnce( - `malformed-primitives:${meshIdx}`, - `Mesh ${mesh.name ?? meshIdx}: skipped mesh with non-array primitives`, - ); - return; - } - for (let primitiveIndex = 0; primitiveIndex < mesh.primitives.length; primitiveIndex += 1) { - const prim = mesh.primitives[primitiveIndex]; - if (!prim) continue; - const mode = prim.mode ?? 4; - if (mode !== 4 && mode !== 5 && mode !== 6) { - const modeName = PRIMITIVE_MODE_NAMES[mode] ?? `mode ${mode}`; + function emitMesh(meshIdx: number, world: Mat4, meshNode: number | null): void { + const mesh = doc.meshes?.[meshIdx]; + if (!mesh) return; + if (!Array.isArray(mesh.primitives)) { pushWarningOnce( - `unsupported-mode:${mode}`, - `Skipped primitives with unsupported mode ${mode} (${modeName})`, + `malformed-primitives:${meshIdx}`, + `Mesh ${mesh.name ?? meshIdx}: skipped mesh with non-array primitives`, ); - continue; - } - if (prim.extensions?.KHR_draco_mesh_compression && requiredExtensions.has("KHR_draco_mesh_compression")) { - pushWarningOnce( - "KHR_draco_mesh_compression", - "Skipped primitives with unsupported required extension KHR_draco_mesh_compression", - ); - continue; - } - const meshoptExtension = primitiveUsesRequiredMeshopt(prim); - if (meshoptExtension) { - pushWarningOnce( - meshoptExtension, - `Skipped primitives with unsupported required extension ${meshoptExtension}`, - ); - continue; - } - if (prim.attributes.POSITION === undefined) { - pushWarningOnce( - `missing-position:${meshIdx}`, - `Mesh ${mesh.name ?? meshIdx}: skipped primitive without POSITION attribute`, - ); - continue; + return; } + for (let primitiveIndex = 0; primitiveIndex < mesh.primitives.length; primitiveIndex += 1) { + const prim = mesh.primitives[primitiveIndex]; + if (!prim) continue; + const mode = prim.mode ?? 4; + if (mode !== 4 && mode !== 5 && mode !== 6) { + const modeName = PRIMITIVE_MODE_NAMES[mode] ?? `mode ${mode}`; + pushWarningOnce( + `unsupported-mode:${mode}`, + `Skipped primitives with unsupported mode ${mode} (${modeName})`, + ); + continue; + } + if (prim.extensions?.KHR_draco_mesh_compression && requiredExtensions.has("KHR_draco_mesh_compression")) { + pushWarningOnce( + "KHR_draco_mesh_compression", + "Skipped primitives with unsupported required extension KHR_draco_mesh_compression", + ); + continue; + } + const meshoptExtension = primitiveUsesRequiredMeshopt(prim); + if (meshoptExtension) { + pushWarningOnce( + meshoptExtension, + `Skipped primitives with unsupported required extension ${meshoptExtension}`, + ); + continue; + } + if (prim.attributes.POSITION === undefined) { + pushWarningOnce( + `missing-position:${meshIdx}`, + `Mesh ${mesh.name ?? meshIdx}: skipped primitive without POSITION attribute`, + ); + continue; + } - const material = prim.material !== undefined ? doc.materials?.[prim.material] : undefined; - const materialAlphaMode = gltfAlphaMode(material?.alphaMode); - const matName = material?.name; - const matOverride = matName ? materialOverrides[matName] : undefined; - const color = matOverride ?? colorFromMaterial( - material, - defaultColor, - materialAlphaMode, - ); - const doubleSided = material?.doubleSided === true; - const materialTextureInfo = prim.material !== undefined ? matTexMap.get(prim.material) : undefined; - const texture = matName && materialTextureOverrides[matName] - ? materialTextureOverrides[matName] - : prim.material !== undefined - ? materialTextureInfo?.url + const material = prim.material !== undefined ? doc.materials?.[prim.material] : undefined; + const materialAlphaMode = gltfAlphaMode(material?.alphaMode); + const matName = material?.name; + const matOverride = matName ? materialOverrides[matName] : undefined; + const color = matOverride ?? colorFromMaterial( + material, + defaultColor, + materialAlphaMode, + ); + const doubleSided = material?.doubleSided === true; + const materialTextureInfo = prim.material !== undefined ? matTexMap.get(prim.material) : undefined; + const texture = matName && materialTextureOverrides[matName] + ? materialTextureOverrides[matName] + : prim.material !== undefined + ? materialTextureInfo?.url + : undefined; + const textureWrap = texture && prim.material !== undefined + ? materialTextureInfo?.wrap : undefined; - const textureWrap = texture && prim.material !== undefined - ? materialTextureInfo?.wrap - : undefined; - const textureAlphaMode = texture - ? materialTextureInfo?.alphaMode ?? materialAlphaMode - : undefined; - const textureTexCoord = texture ? materialTextureInfo?.texCoord ?? 0 : 0; + const textureAlphaMode = texture + ? materialTextureInfo?.alphaMode ?? materialAlphaMode + : undefined; + const textureTexCoord = texture ? materialTextureInfo?.texCoord ?? 0 : 0; + + const positionAccessor = prim.attributes.POSITION; + const { + array: posArr, + count: vertCount, + componentCount: positionComponentCount, + } = readAccessor(doc, buffers, positionAccessor); + if (!canUsePositionAccessor(positionAccessor, posArr)) continue; + const morphPositionOffsets = buildMorphPositionOffsets(mesh, meshIdx, prim, meshNode, vertCount); + const localPositions: Vec3[] = []; + const positions: Vec3[] = []; + for (let i = 0; i < vertCount; i++) { + const base = i * positionComponentCount; + const morphOffset = morphPositionOffsets?.[i]; + const local: Vec3 = [ + Number(posArr[base]) + (morphOffset?.[0] ?? 0), + Number(posArr[base + 1]) + (morphOffset?.[1] ?? 0), + Number(posArr[base + 2]) + (morphOffset?.[2] ?? 0), + ]; + localPositions.push(local); + positions.push(transformPoint(world, local)); + } - const positionAccessor = prim.attributes.POSITION; - const { - array: posArr, - count: vertCount, - componentCount: positionComponentCount, - } = readAccessor(doc, buffers, positionAccessor); - if (!canUsePositionAccessor(positionAccessor, posArr)) continue; - const morphPositionOffsets = buildMorphPositionOffsets(mesh, meshIdx, prim, meshNode, vertCount); - const localPositions: Vec3[] = []; - const positions: Vec3[] = []; - for (let i = 0; i < vertCount; i++) { - const base = i * positionComponentCount; - const morphOffset = morphPositionOffsets?.[i]; - const local: Vec3 = [ - Number(posArr[base]) + (morphOffset?.[0] ?? 0), - Number(posArr[base + 1]) + (morphOffset?.[1] ?? 0), - Number(posArr[base + 2]) + (morphOffset?.[2] ?? 0), - ]; - localPositions.push(local); - positions.push(transformPoint(world, local)); - } + let uvs: Vec2[] | null = null; + const uvAccIdx = prim.attributes[`TEXCOORD_${textureTexCoord}`]; + if (texture && uvAccIdx !== undefined) { + const { array: uvArr, count: uvCount } = readAccessor(doc, buffers, uvAccIdx); + uvs = []; + let scale = 1; + if (uvArr instanceof Uint8Array) scale = 1 / 255; + else if (uvArr instanceof Uint16Array) scale = 1 / 65535; + for (let i = 0; i < uvCount; i++) { + const u = uvArr[i * 2] * scale; + const v = uvArr[i * 2 + 1] * scale; + uvs.push([u, 1 - v]); + } + } - let uvs: Vec2[] | null = null; - const uvAccIdx = prim.attributes[`TEXCOORD_${textureTexCoord}`]; - if (texture && uvAccIdx !== undefined) { - const { array: uvArr, count: uvCount } = readAccessor(doc, buffers, uvAccIdx); - uvs = []; - let scale = 1; - if (uvArr instanceof Uint8Array) scale = 1 / 255; - else if (uvArr instanceof Uint16Array) scale = 1 / 65535; - for (let i = 0; i < uvCount; i++) { - const u = uvArr[i * 2] * scale; - const v = uvArr[i * 2 + 1] * scale; - uvs.push([u, 1 - v]); + let indices: number[]; + if (prim.indices !== undefined) { + const { array: idxArr, count: idxCount } = readAccessor(doc, buffers, prim.indices); + indices = []; + for (let i = 0; i < idxCount; i++) indices.push(Number(idxArr[i])); + } else { + indices = positions.map((_, i) => i); + } + indices = triangulatePrimitiveIndices(indices, mode); + if (doubleSided) indices = makeDoubleSidedTriangleIndices(indices); + + let animatedSource: AnimatedPrimitiveSource | undefined; + if ((doc.animations?.length ?? 0) > 0) { + const joints = readAccessorTupleArray(doc, buffers, prim.attributes.JOINTS_0, 4, vertCount); + const weights = readAccessorTupleArray(doc, buffers, prim.attributes.WEIGHTS_0, 4, vertCount); + animatedSource = { + sourceIndex: animatedSources.length, + meshNode, + meshBindWorld: world, + skinIndex: meshNode !== null ? doc.nodes?.[meshNode]?.skin : undefined, + positions: localPositions, + indices, + triangleMask: [], + color, + texture, + textureWrap, + textureAlphaMode, + doubleSided, + uvs: uvs ?? undefined, + joints, + weights, + }; + animatedSources.push(animatedSource); } - } - let indices: number[]; - if (prim.indices !== undefined) { - const { array: idxArr, count: idxCount } = readAccessor(doc, buffers, prim.indices); - indices = []; - for (let i = 0; i < idxCount; i++) indices.push(Number(idxArr[i])); - } else { - indices = positions.map((_, i) => i); + for (let i = 0; i + 2 < indices.length; i += 3) { + const i0 = indices[i]!; + const i1 = indices[i + 1]!; + const i2 = indices[i + 2]!; + const sourceTriangleIndex = animatedSource ? animatedSource.triangleMask.length : undefined; + if (animatedSource) animatedSource.triangleMask.push(false); + const v0 = positions[i0]; + const v1 = positions[i1]; + const v2 = positions[i2]; + if (!v0 || !v1 || !v2) continue; + let triUvs: Vec2[] | undefined; + if (uvs && texture) { + const u0 = uvs[i0], u1 = uvs[i1], u2 = uvs[i2]; + if (u0 && u1 && u2) triUvs = [u0, u1, u2]; + } + const keyPrefix = `${meshIdx}:${primitiveIndex}:${meshNode ?? "root"}`; + rawTris.push({ + v0, + v1, + v2, + color, + texture, + textureWrap, + textureAlphaMode, + doubleSided, + uvs: triUvs, + simplifySourceVertexKeys: [ + `${keyPrefix}:${i0}`, + `${keyPrefix}:${i1}`, + `${keyPrefix}:${i2}`, + ], + source: animatedSource, + sourceIndex: animatedSource?.sourceIndex, + sourceTriangleIndex, + }); + } } - indices = triangulatePrimitiveIndices(indices, mode); - if (doubleSided) indices = makeDoubleSidedTriangleIndices(indices); + } - let animatedSource: AnimatedPrimitiveSource | undefined; - if ((doc.animations?.length ?? 0) > 0) { - const joints = readAccessorTupleArray(doc, buffers, prim.attributes.JOINTS_0, 4, vertCount); - const weights = readAccessorTupleArray(doc, buffers, prim.attributes.WEIGHTS_0, 4, vertCount); - animatedSource = { - sourceIndex: animatedSources.length, - meshNode, - meshBindWorld: world, - skinIndex: meshNode !== null ? doc.nodes?.[meshNode]?.skin : undefined, - positions: localPositions, - indices, - triangleMask: [], - color, - texture, - textureWrap, - textureAlphaMode, - doubleSided, - uvs: uvs ?? undefined, - joints, - weights, - }; - animatedSources.push(animatedSource); + function walkNode(nodeIdx: number, parentWorld: Mat4, ancestors: Set): void { + if (ancestors.has(nodeIdx)) { + pushWarningOnce( + `recursive-node:${nodeIdx}`, + `Skipped recursive node reference ${nodeIdx} in glTF scene graph`, + ); + return; } - - for (let i = 0; i + 2 < indices.length; i += 3) { - const i0 = indices[i]!; - const i1 = indices[i + 1]!; - const i2 = indices[i + 2]!; - const sourceTriangleIndex = animatedSource ? animatedSource.triangleMask.length : undefined; - if (animatedSource) animatedSource.triangleMask.push(false); - const v0 = positions[i0]; - const v1 = positions[i1]; - const v2 = positions[i2]; - if (!v0 || !v1 || !v2) continue; - let triUvs: Vec2[] | undefined; - if (uvs && texture) { - const u0 = uvs[i0], u1 = uvs[i1], u2 = uvs[i2]; - if (u0 && u1 && u2) triUvs = [u0, u1, u2]; - } - const keyPrefix = `${meshIdx}:${primitiveIndex}:${meshNode ?? "root"}`; - rawTris.push({ - v0, - v1, - v2, - color, - texture, - textureWrap, - textureAlphaMode, - doubleSided, - uvs: triUvs, - simplifySourceVertexKeys: [ - `${keyPrefix}:${i0}`, - `${keyPrefix}:${i1}`, - `${keyPrefix}:${i2}`, - ], - source: animatedSource, - sourceIndex: animatedSource?.sourceIndex, - sourceTriangleIndex, - }); + const node = doc.nodes?.[nodeIdx]; + if (!node) return; + const world = mulMat4(parentWorld, nodeLocalMatrix(node)); + if (typeof node.mesh === "number") emitMesh(node.mesh, world, nodeIdx); + ancestors.add(nodeIdx); + for (const child of node.children ?? []) walkNode(child, world, ancestors); + ancestors.delete(nodeIdx); + } + + const sceneIdx = doc.scene ?? 0; + const sceneRoots = doc.scenes?.[sceneIdx]?.nodes; + if (sceneRoots && sceneRoots.length > 0) { + for (const r of sceneRoots) walkNode(r, IDENTITY4, new Set()); + } else { + if ((doc.meshes?.length ?? 0) === 0) { + pushWarningOnce("no-gltf-meshes", "No glTF meshes found"); } + for (let i = 0; i < (doc.meshes?.length ?? 0); i++) emitMesh(i, IDENTITY4, null); } - } + seedCollapsedRawTrisFromAnimation(doc, buffers, rawTris); - function walkNode(nodeIdx: number, parentWorld: Mat4, ancestors: Set): void { - if (ancestors.has(nodeIdx)) { - pushWarningOnce( - `recursive-node:${nodeIdx}`, - `Skipped recursive node reference ${nodeIdx} in glTF scene graph`, - ); - return; + if (rawTris.length === 0) { + return { + polygons: [], + objectUrls, + dispose, + warnings, + metadata: { + triangleCount: 0, + meshes: meshNames, + materials: materialNames, + sourceBytes, + }, + }; } - const node = doc.nodes?.[nodeIdx]; - if (!node) return; - const world = mulMat4(parentWorld, nodeLocalMatrix(node)); - if (typeof node.mesh === "number") emitMesh(node.mesh, world, nodeIdx); - ancestors.add(nodeIdx); - for (const child of node.children ?? []) walkNode(child, world, ancestors); - ancestors.delete(nodeIdx); - } - function seedTimesForClip(clip: RuntimeAnimationClip): number[] { - const times = new Set(); - const duration = clip.info.duration; - for (const channel of clip.channels) { - for (const time of channel.sampler.input) { - if (!Number.isFinite(time) || time <= 0) continue; - if (duration > 0 && time >= duration) continue; - times.add(time); + let minX = Infinity, minY = Infinity, minZ = Infinity; + let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity; + for (const t of rawTris) { + for (const v of [t.v0, t.v1, t.v2]) { + if (v[0] < minX) minX = v[0]; if (v[0] > maxX) maxX = v[0]; + if (v[1] < minY) minY = v[1]; if (v[1] > maxY) maxY = v[1]; + if (v[2] < minZ) minZ = v[2]; if (v[2] > maxZ) maxZ = v[2]; } } - if (duration > 0) { - times.add(duration * 0.25); - times.add(duration * 0.5); - times.add(duration * 0.75); - } - return Array.from(times).sort((a, b) => a - b).slice(0, 128); - } - - function animatedRawTriFrame( - tri: RawTri, - worldMatrices: Mat4[], - ): { v0: Vec3; v1: Vec3; v2: Vec3 } | undefined { - const source = tri.source; - if (!source || tri.sourceTriangleIndex === undefined || source.skinIndex !== undefined) return undefined; - const offset = tri.sourceTriangleIndex * 3; - const i0 = source.indices[offset]; - const i1 = source.indices[offset + 1]; - const i2 = source.indices[offset + 2]; - const p0 = i0 !== undefined ? source.positions[i0] : undefined; - const p1 = i1 !== undefined ? source.positions[i1] : undefined; - const p2 = i2 !== undefined ? source.positions[i2] : undefined; - if (!p0 || !p1 || !p2) return undefined; - const meshWorld = source.meshNode !== null - ? (worldMatrices[source.meshNode] ?? source.meshBindWorld) - : source.meshBindWorld; - return { - v0: transformPoint(meshWorld, p0), - v1: transformPoint(meshWorld, p1), - v2: transformPoint(meshWorld, p2), - }; - } - - function sameWorldVertex(a: Vec3, b: Vec3): boolean { - return a[0] === b[0] && a[1] === b[1] && a[2] === b[2]; - } - - function isDegenerateRawTriFrame(frame: { v0: Vec3; v1: Vec3; v2: Vec3 }): boolean { - return ( - sameWorldVertex(frame.v0, frame.v1) || - sameWorldVertex(frame.v0, frame.v2) || - sameWorldVertex(frame.v1, frame.v2) - ); - } - - function hasNonDegenerateRawTri(): boolean { - return rawTris.some((tri) => !isDegenerateRawTriFrame(tri)); - } - - function seedCollapsedRawTrisFromAnimation(): void { - if (rawTris.length === 0 || (doc.animations?.length ?? 0) === 0 || hasNonDegenerateRawTri()) return; - const runtimeClips = buildRuntimeAnimationClips(doc, buffers); - if (runtimeClips.length === 0) return; - const basePoses = (doc.nodes ?? []).map((node) => poseFromNode(node)); - const seededFrames: Array<{ v0: Vec3; v1: Vec3; v2: Vec3 } | undefined> = - new Array(rawTris.length); - - for (const clip of runtimeClips) { - for (const time of seedTimesForClip(clip)) { - const worldMatrices = sampleRuntimeClipWorldMatrices(doc, basePoses, clip, time); - for (let i = 0; i < rawTris.length; i++) { - if (seededFrames[i]) continue; - const frame = animatedRawTriFrame(rawTris[i]!, worldMatrices); - if (frame && !isDegenerateRawTriFrame(frame)) seededFrames[i] = frame; + const maxDim = Math.max(maxX - minX, maxY - minY, maxZ - minZ); + const scale = maxDim > 0 ? targetSize / maxDim : 1; + + // Offset to subtract from each source vertex. `center: "min"` (default) + // → bbox-min sits at local (0,0,0); geometry in +X+Y+Z. `center: true` + // → bbox-center at origin so wrapper rotation pivots at the centroid + // (three.js-style rotate-in-place). + const centerMode = options?.center; + const useCenter = centerMode === true || centerMode === "center"; + const ox = useCenter ? (minX + maxX) * 0.5 : minX; + const oy = useCenter ? (minY + maxY) * 0.5 : minY; + const oz = useCenter ? (minZ + maxZ) * 0.5 : minZ; + + const round = (n: number) => Math.round(n * 1000) / 1000; + const upAxis = options?.upAxis ?? "y"; + const project: (v: Vec3) => Vec3 = upAxis === "z" + ? ([x, y, z]) => [ + round((x - ox) * scale), + round((y - oy) * scale), + round((z - oz) * scale), + ] + : ([x, y, z]) => [ + round((z - oz) * scale), + round((x - ox) * scale), + round((y - oy) * scale), + ]; + const projectFrameVertex = upAxis === "z" + ? (v: Vec3, out: Float64Array, offset: number): void => { + out[offset] = round((v[0] - ox) * scale); + out[offset + 1] = round((v[1] - oy) * scale); + out[offset + 2] = round((v[2] - oz) * scale); } + : (v: Vec3, out: Float64Array, offset: number): void => { + out[offset] = round((v[2] - oz) * scale); + out[offset + 1] = round((v[0] - ox) * scale); + out[offset + 2] = round((v[1] - oy) * scale); + }; + const polygons: Polygon[] = []; + let projectedDegenerateCount = 0; + for (const t of rawTris) { + const v0 = project(t.v0); + const v1 = project(t.v1); + const v2 = project(t.v2); + const degenerate = isDegenerateProjectedTriangle(v0, v1, v2); + if (t.source && t.sourceTriangleIndex !== undefined) { + t.source.triangleMask[t.sourceTriangleIndex] = !degenerate; } + if (degenerate) { + projectedDegenerateCount++; + continue; + } + const p: Polygon = { + vertices: [v0, v1, v2], + color: t.color, + }; + if (t.texture) p.texture = t.texture; + if (t.texture && t.textureWrap) p.textureWrap = t.textureWrap; + if (t.texture && t.textureAlphaMode) p.textureAlphaMode = t.textureAlphaMode; + if (t.doubleSided) p.doubleSided = true; + if (t.uvs) p.uvs = t.uvs; + if (t.simplifySourceVertexKeys) p.simplifySourceVertexKeys = t.simplifySourceVertexKeys; + polygons.push(p); + animatedPolygonRefs.push( + t.sourceIndex !== undefined && t.sourceTriangleIndex !== undefined + ? { sourceIndex: t.sourceIndex, triangleIndex: t.sourceTriangleIndex } + : undefined, + ); } - - if (!seededFrames.some(Boolean)) return; - for (let i = 0; i < rawTris.length; i++) { - const frame = seededFrames[i]; - if (!frame) continue; - rawTris[i]!.v0 = frame.v0; - rawTris[i]!.v1 = frame.v1; - rawTris[i]!.v2 = frame.v2; - } - } - - const sceneIdx = doc.scene ?? 0; - const sceneRoots = doc.scenes?.[sceneIdx]?.nodes; - if (sceneRoots && sceneRoots.length > 0) { - for (const r of sceneRoots) walkNode(r, IDENTITY4, new Set()); - } else { - if ((doc.meshes?.length ?? 0) === 0) { - pushWarningOnce("no-gltf-meshes", "No glTF meshes found"); + if (polygons.length === 0 && projectedDegenerateCount > 0) { + pushWarningOnce( + "all-projected-triangles-degenerate", + "No non-degenerate glTF triangles remained after normalization", + ); } - for (let i = 0; i < (doc.meshes?.length ?? 0); i++) emitMesh(i, IDENTITY4, null); - } - seedCollapsedRawTrisFromAnimation(); - - const dispose = makeDispose(objectUrls); + const animation = buildAnimationController( + doc, + buffers, + animatedSources, + animatedPolygonRefs, + project, + projectFrameVertex, + ); - if (rawTris.length === 0) { return { - polygons: [], + polygons, + animation, objectUrls, dispose, warnings, metadata: { - triangleCount: 0, + triangleCount: polygons.length, meshes: meshNames, materials: materialNames, + animations: animation?.clips, sourceBytes, }, }; + } catch (err) { + dispose(); + throw err; } - - let minX = Infinity, minY = Infinity, minZ = Infinity; - let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity; - for (const t of rawTris) { - for (const v of [t.v0, t.v1, t.v2]) { - if (v[0] < minX) minX = v[0]; if (v[0] > maxX) maxX = v[0]; - if (v[1] < minY) minY = v[1]; if (v[1] > maxY) maxY = v[1]; - if (v[2] < minZ) minZ = v[2]; if (v[2] > maxZ) maxZ = v[2]; - } - } - const maxDim = Math.max(maxX - minX, maxY - minY, maxZ - minZ); - const scale = maxDim > 0 ? targetSize / maxDim : 1; - - // Offset to subtract from each source vertex. `center: "min"` (default) - // → bbox-min sits at local (0,0,0); geometry in +X+Y+Z. `center: true` - // → bbox-center at origin so wrapper rotation pivots at the centroid - // (three.js-style rotate-in-place). - const centerMode = options?.center; - const useCenter = centerMode === true || centerMode === "center"; - const ox = useCenter ? (minX + maxX) * 0.5 : minX; - const oy = useCenter ? (minY + maxY) * 0.5 : minY; - const oz = useCenter ? (minZ + maxZ) * 0.5 : minZ; - - const round = (n: number) => Math.round(n * 1000) / 1000; - const upAxis = options?.upAxis ?? "y"; - const project: (v: Vec3) => Vec3 = upAxis === "z" - ? ([x, y, z]) => [ - round((x - ox) * scale), - round((y - oy) * scale), - round((z - oz) * scale), - ] - : ([x, y, z]) => [ - round((z - oz) * scale), - round((x - ox) * scale), - round((y - oy) * scale), - ]; - const projectFrameVertex = upAxis === "z" - ? (v: Vec3, out: Float64Array, offset: number): void => { - out[offset] = round((v[0] - ox) * scale); - out[offset + 1] = round((v[1] - oy) * scale); - out[offset + 2] = round((v[2] - oz) * scale); - } - : (v: Vec3, out: Float64Array, offset: number): void => { - out[offset] = round((v[2] - oz) * scale); - out[offset + 1] = round((v[0] - ox) * scale); - out[offset + 2] = round((v[1] - oy) * scale); - }; - const polygons: Polygon[] = []; - let projectedDegenerateCount = 0; - for (const t of rawTris) { - const v0 = project(t.v0); - const v1 = project(t.v1); - const v2 = project(t.v2); - const degenerate = isDegenerateProjectedTriangle(v0, v1, v2); - if (t.source && t.sourceTriangleIndex !== undefined) { - t.source.triangleMask[t.sourceTriangleIndex] = !degenerate; - } - if (degenerate) { - projectedDegenerateCount++; - continue; - } - const p: Polygon = { - vertices: [v0, v1, v2], - color: t.color, - }; - if (t.texture) p.texture = t.texture; - if (t.texture && t.textureWrap) p.textureWrap = t.textureWrap; - if (t.texture && t.textureAlphaMode) p.textureAlphaMode = t.textureAlphaMode; - if (t.doubleSided) p.doubleSided = true; - if (t.uvs) p.uvs = t.uvs; - if (t.simplifySourceVertexKeys) p.simplifySourceVertexKeys = t.simplifySourceVertexKeys; - polygons.push(p); - animatedPolygonRefs.push( - t.sourceIndex !== undefined && t.sourceTriangleIndex !== undefined - ? { sourceIndex: t.sourceIndex, triangleIndex: t.sourceTriangleIndex } - : undefined, - ); - } - if (polygons.length === 0 && projectedDegenerateCount > 0) { - pushWarningOnce( - "all-projected-triangles-degenerate", - "No non-degenerate glTF triangles remained after normalization", - ); - } - const animation = buildAnimationController( - doc, - buffers, - animatedSources, - animatedPolygonRefs, - project, - projectFrameVertex, - ); - - return { - polygons, - animation, - objectUrls, - dispose, - warnings, - metadata: { - triangleCount: polygons.length, - meshes: meshNames, - materials: materialNames, - animations: animation?.clips, - sourceBytes, - }, - }; -} - -/** - * Build an idempotent disposer that revokes each minted blob URL exactly - * once. Subsequent calls are no-ops, so component unmount paths can call - * `dispose()` defensively without worrying about double-revoke errors. - */ -function makeDispose(objectUrls: string[]): () => void { - let disposed = false; - return () => { - if (disposed) return; - disposed = true; - const URL = (globalThis as unknown as { URL?: { revokeObjectURL?: (url: string) => void } }).URL; - if (!URL?.revokeObjectURL) return; - for (const url of objectUrls) { - try { URL.revokeObjectURL(url); } catch { /* swallow — best effort */ } - } - }; } diff --git a/packages/core/src/shadow/computeReceiverShadows.ts b/packages/core/src/shadow/computeReceiverShadows.ts index e716ae919..4e61a97dd 100644 --- a/packages/core/src/shadow/computeReceiverShadows.ts +++ b/packages/core/src/shadow/computeReceiverShadows.ts @@ -12,42 +12,47 @@ * re-runs the prepare* helpers only when their bust keys change. The * compute step is pure data-in/data-out so it's safe to call every frame. */ -import { BASE_TILE } from "../camera/camera"; -import { normalFacesCamera, type CameraCullRotation } from "../cull/cameraBackfaceCulling"; -import { shadePolygon } from "../atlas/paintDefaults"; -import { safePlanSeamBleedAmount } from "../atlas/edgeRepair"; -import { offsetConvexPolygonPointsByEdgeAmounts } from "../atlas/solidTriangle"; -import { parseHexColor } from "../color/color"; -import { rotateVec3InWrapperCssFrame } from "../math/rotation"; -import { clipPolygonToConvex2D } from "./clipping"; -import { ensureCcw2D } from "./projection"; +import type { CameraCullRotation } from "../cull/cameraBackfaceCulling"; +import { meshScaleVec3 } from "./receiverFaceGroups"; import { - expandConvexHullOutward, - groupReceiverFaceGroups, - meshScaleVec3, - RECEIVER_EDGE_PERP_EPS, - RECEIVER_OUTLINE_EXPAND, - spatialEdge, - spatialEdgeBoundsOverlap, - spatialEdgesShareLine, - worldCssForMesh, - worldPositionToCss, - type SpatialEdge, -} from "./receiverFaceGroups"; -import { - buildEdgeOwners as buildEdgeOwnersHelper, classifyFacing, extractSilhouetteLoops, silhouetteReliable, - type EdgeOwners, } from "./silhouette"; +import type { Vec3 } from "../types"; +import { mergeReceiverShadowPasses } from "./receiver/merge"; +import { computePlaneShadowSpec, type PlaneProjectionContext } from "./receiver/projection"; +import { computePlaneShading, type PlaneShadingContext } from "./receiver/shading"; import type { - PolyAmbientLight, - PolyDirectionalLight, - Polygon, - Vec2, - Vec3, -} from "../types"; + ComputeReceiverShadowFacesInput, + MergedReceiverShadowInput, + MergedShadowFace, + PlaneShading, + ReceiverShadowFaceSpec, +} from "./receiver/types"; + +export { + POLY_DEFAULT_SHADOW_LIFT, + SHADOW_CLIP_SEAM_BLEED, + type CasterPolyItem, + type ComputeReceiverShadowFacesInput, + type MergedReceiverShadowInput, + type MergedShadowFace, + type MergedShadowLayer, + type ReceiverCasterInput, + type ReceiverFacePlane, + type ReceiverShadowFaceSpec, + type ReceiverShadowPath, + type ReceiverShadowSignatureLights, +} from "./receiver/types"; + +export { + buildSharedEdgeMap, + prepareCasterEdgeOwners, + prepareCasterPolyItems, + prepareReceiverFacePlanes, + receiverShadowCameraSignature, +} from "./receiver/preparation"; /** Minimum item count required to attempt per-caster-mesh silhouette * extraction. For smaller meshes (crates, simple primitives) the @@ -55,850 +60,6 @@ import type { * loops. See `bench/notes/SHADOW_PERF_LOG.md` H9. */ const SILHOUETTE_MIN_POLYS = 40; -/** - * Outward overscan (CSS px on the receiver plane — UV units) applied to a - * member polygon's clip outline along its SHARED and CREASE edges only, before - * shadow geometry is clipped against it. Exactly-abutting clipped subpaths - * don't sum to full coverage under SVG antialiasing, so member seams and - * creases showed a hairline light strip — the same artifact class the atlas - * seam bleed solves for solid leaves. Edges with no neighbouring surface get - * zero expansion so the shadow never leaks past the face-group boundary. - * - * Fixed constant: the scene `seamBleed` option does not flow into the - * shadow pipeline (`shadow` options carry only color/opacity/maxExtend), - * and threading it through all three renderers is out of scope here. - */ -export const SHADOW_CLIP_SEAM_BLEED = 0.75; - -/** - * How much wider than `RECEIVER_OUTLINE_EXPAND` the shadow pre-clip has to be - * so it never caps the per-edge member bleed. The pre-clip runs BEFORE the - * per-member clips, so at the stored 0.5 px outline a crease sitting on the - * group hull (91% of the castle's) kept only 0.5 px of its granted 0.75 px. - * Applied ONLY where a crease edge was actually bled, because the stored outline also - * sizes the face plane's matrix and box — widening that unconditionally moves - * emitted geometry on multi-light and textured receivers, which get no crease - * bleed at all. The group hull is not the surface boundary (the member clips - * are, and they still bound every edge), so widening the clip copy cannot push - * shadow past a member outline. - */ -const CLIP_OUTLINE_EXTRA = Math.max(0, SHADOW_CLIP_SEAM_BLEED - RECEIVER_OUTLINE_EXPAND); - -/** - * Per-receiver cached face geometry. One record per coplanar face group: - * plane (O, n, u, v), outline polygon (Sutherland-Hodgman clip), bbox in - * (u, v) for SVG sizing, and the pre-stringified matrix3d transform that - * places an SVG on that face plane. - * - * All of this is invariant under light/caster changes. Per light tick the - * caller just re-runs the per-tri SH and builds the path `d` — never - * recompute groups or basis. Cache invalidated when the receiver's polygon - * count or position changes. - */ -export interface ReceiverFacePlane { - O: Vec3; - n: Vec3; - u: Vec3; - v: Vec3; - outlineUv: Array<[number, number]>; - memberPolysUv: Array>; - /** Parallel to `memberPolysUv`: each member's unsnapped world-space vertices - * (see `ReceiverPlaneGroup.memberPolysWorld`). Crease matching reads these - * rather than lifting (u, v) back to 3D, which would snap non-planar - * members onto their group plane and hide real creases. - * - * Optional so a hand-built plane still type-checks: without it a face gets - * no crease detection and no pre-blend (its members' shading cannot be - * verified), which is the safe degradation, not a silent approximation. */ - memberPolysWorld?: Vec3[][]; - memberPolyIndices: number[]; - /** Parallel to `memberPolysUv`: CCW edge indices shared with another member - * of the same group (see `ReceiverPlaneGroup.memberSharedEdges`). Drives - * the member-clip seam bleed. Optional — absent means no seam bleed. */ - memberSharedEdges?: Array | undefined>; - /** Parallel to `memberPolysUv`: CCW edge index → the INDICES (into the same - * `ReceiverFacePlane[]`) of the neighbouring face planes across a CREASE — - * a neighbouring surface belonging to a DIFFERENT, non-coplanar face group. - * Those two groups emit separate SVGs, so their antialiased clip edges abut - * at the crease without summing to full coverage. Unioned with - * `memberSharedEdges` at clip-expansion time so one pass bleeds both - * classes. Filled by `prepareReceiverFacePlanes` after the occlusion cull; - * edges already in `memberSharedEdges` are skipped (already bled). - * - * Plane INDICES are kept — not just the edge index, and not just the - * neighbour's normal — because bleeding across a crease is only safe when - * the neighbour on the far side actually paints an abutting, compatible - * shadow layer in this same pass. Answering that needs the neighbour's - * identity (its facing, its emission, its resolved fill), which a bare - * normal cannot supply. Indices are valid only for the array the planes - * were prepared as: callers pass `prepareReceiverFacePlanes`' result - * through unfiltered and unreordered. - * - * Optional, and filled in place by `prepareReceiverFacePlanes`; absent - * means no crease bleed. */ - memberCreaseEdges?: Array | undefined>; - /** Every plane index this plane marks a crease edge toward, unioned across - * members. Lets the bleed test ask "does the neighbour bleed BACK at me?" - * in O(1) — a one-sided bleed would paint an opaque pre-blend over a - * neighbour still painting at alpha, which double-darkens the overlap - * depending on SVG paint order. Filled alongside `memberCreaseEdges`. */ - creaseNeighbourPlanes?: ReadonlySet; - minU: number; - minV: number; - width: number; - height: number; - matrixCss: string; - faceIndex: number; - /** World-frame lift (already × BASE_TILE) along +n. Re-applied per-frame - * when building a tight shadow SVG matrix so the SVG hovers over the face. */ - lift: number; -} - -/** - * Per-caster cached per-polygon data: world-space vertices + 3D AABB - * corners + caster-polygon plane normal/offset. Invariant under light - * direction; depends only on the caster mesh's geometry and position. - */ -export interface CasterPolyItem { - wv: Vec3[]; - bboxCorners: Vec3[]; - planeN: Vec3 | null; - planeOffset: number; - polygonIndex: number; -} - -/** A caster mesh's prepared items paired with a stable identifier the caller - * can use for per-path attribution. */ -export interface ReceiverCasterInput { - /** Caller-defined identifier (e.g. mesh ref, mesh shadow id). Echoed back - * on each emitted path so the renderer can map a subpath to its source - * caster mesh. */ - id: T; - items: CasterPolyItem[]; - /** Self-shadow edge adjacency. When this caster is the same mesh as the - * receiver, the renderer pre-computes a map polygonIndex → - * set-of-other-polygonIndex that share at least one edge (within - * EDGE_MATCH_EPS). The shadow algorithm skips projecting `polygonIndex` - * onto any receiver face whose member set intersects the shared-edge - * set — those projections are sliver shadows along seams (smooth-shaded - * GLB meshes, subdivided spheres) that the user never wants to see. */ - selfShadowEdgeMap?: ReadonlyMap>; - /** Per-mesh edge ownership map for silhouette extraction. Cached by the - * caller (WeakMap) and shared across receivers within a frame. - * When present AND the caster is NOT the receiver AND items.length ≥ - * SILHOUETTE_MIN_POLYS, the shadow algorithm projects per-mesh - * silhouette loops instead of every front-facing triangle — collapses - * the N-triangle path to 1 outline per caster per receiver. See H9 in - * `bench/notes/SHADOW_PERF_LOG.md`. */ - edgeOwners?: ReadonlyMap; - /** Total polygon count on the source caster mesh (NOT the filtered - * `items` count). Needed by silhouette extraction so the `facing` - * array is sized correctly even when atlas-plan / dedup filters drop - * some polygons from `items`. */ - casterPolygonCount?: number; - /** Parametric-shadow override: a precomputed world-frame silhouette loop set - * (see `computeParametricShadowSilhouette`). When present it is projected - * directly — skipping per-poly and silhouette extraction — so a cheap, - * low-resolution outline casts onto every receiver via the normal pipeline. */ - overrideSilhouette?: Vec3[][]; - /** Per-point-light parametric override (indexed by the point light's index in - * `allPointLights`). A point pass uses this RADIAL silhouette instead of the - * directional `overrideSilhouette`; an undefined entry → exact point path. */ - overridePointSilhouettes?: Array; -} - -/** - * Build a polygon-adjacency map: polygonIndex → set of polygonIndex that - * share at least one edge (vertex pair, orientation-independent). Used by - * the receiver-shadow algorithm to cull sliver shadows along mesh seams. - * - * Edge match tolerance is small enough to dedupe vertex coordinates that - * went through `optimizeMeshPolygons` snap-to-plane but not so loose it - * connects geometrically distinct polygons. - */ -export function buildSharedEdgeMap( - polygons: readonly Polygon[], -): Map> { - const EDGE_MATCH_PRECISION = 1e-4; - const quant = (n: number): string => Math.round(n / EDGE_MATCH_PRECISION).toString(36); - const vertKey = (v: Vec3): string => `${quant(v[0])},${quant(v[1])},${quant(v[2])}`; - // Edge key: sorted vertex-pair string so orientation doesn't matter. - const edgeKey = (a: Vec3, b: Vec3): string => { - const ka = vertKey(a); - const kb = vertKey(b); - return ka < kb ? `${ka}|${kb}` : `${kb}|${ka}`; - }; - // edgeKey → polygon indices touching that edge - const edgeOwners = new Map(); - for (let i = 0; i < polygons.length; i++) { - const poly = polygons[i]; - if (!poly || poly.vertices.length < 2) continue; - const verts = poly.vertices; - for (let j = 0; j < verts.length; j++) { - const a = verts[j]!; - const b = verts[(j + 1) % verts.length]!; - const k = edgeKey(a, b); - let owners = edgeOwners.get(k); - if (!owners) { - owners = []; - edgeOwners.set(k, owners); - } - owners.push(i); - } - } - const out = new Map>(); - for (const owners of edgeOwners.values()) { - if (owners.length < 2) continue; - for (const a of owners) { - for (const b of owners) { - if (a === b) continue; - let set = out.get(a); - if (!set) { - set = new Set(); - out.set(a, set); - } - set.add(b); - } - } - } - return out; -} - -/** One contributing caster's shadow subpath on a single receiver face. */ -export interface ReceiverShadowPath { - /** Caster id echoed from the input. */ - casterId: T; - /** Path data string: `M…L…Z` subpaths in face-local (u, v) coordinates - * pre-translated so the SVG's `viewBox` is `0 0 width height`. */ - d: string; - /** Source polygon indices on the caster mesh in subpath order (one per - * M…L…Z block). Used for DevTools attribution. */ - casterPolygonIndices: number[]; -} - -/** Per-receiver-face shadow spec. Renderer mounts one SVG per spec. */ -export interface ReceiverShadowFaceSpec { - /** Index into the prepared `ReceiverFacePlane[]` list. Stable across - * frames; used as the `data-poly-shadow-receiver-face` attr. */ - faceIndex: number; - /** Receiver polygon indices that make up this coplanar group. */ - memberPolyIndices: number[]; - /** matrix3d(...) transform that places the SVG on the face plane. */ - matrixCss: string; - width: number; - height: number; - /** Fill (and stroke) color resolved per-face: textured receivers get the - * user's `shadow.color`; solid receivers get their own ambient-only - * shadePolygon for byte-exact Three.js parity. */ - fill: string; - /** Per-face opacity (already accounts for textured-darken Lambert ratio - * if applicable). */ - opacity: number; - paths: Array>; - /** Full-lit face color C (all lights), for the multi-light merge: callers - * multiply C by each pass's `fill/C` factor so overlaps composite to the - * both-blocked color. Empty string for textured receivers (per-pixel base, - * multiply can't be uniform — those fall back to cumulative-alpha). */ - fullLitFill: string; - /** Every clipped caster polygon for this pass in absolute face-(u,v) space - * (NOT offset by the tight bbox). The multi-light merge re-bases these to a - * shared per-face bbox so all lights' shadows live in one SVG. */ - facePolysUv: Array>; - /** True when EVERY member polygon of this group paints exactly - * `fullLitFill`, AND the pre-blend of `fill` at `opacity` over it is - * representable — so a single-pass shadow may be emitted as that - * PRE-BLENDED color at alpha 1 instead of the shadowed color at `opacity` - * (identical pixel, but idempotent under overlap). - * - * All three conditions are required: - * - solid receiver (a textured one has no uniform lit base); - * - every member paints `fullLitFill` — a group is formed by plane + - * adjacency, not material, and admits member normals up to - * `RECEIVER_NORMAL_TOL` apart, so neither one base color nor one Lambert - * term can be assumed. Checked per member against its OWN normal and - * centroid, i.e. exactly what the renderer bakes into the leaf; - * - `blendShadowOverLitBase` can actually represent the result. A - * translucent receiver shades to `rgba(...)`, which it cannot — and - * emitting the alpha form under expanded clips would double-darken. */ - preblendEligible: boolean; - /** True when at least one member clip of this face was expanded across a - * CREASE edge into a neighbouring face group's SVG. Only these faces need - * the opaque pre-blend (that overlap is what alpha paint would - * double-darken); every other face keeps the alpha form, whose off-surface - * `shadow.lift` parallax at grazing angles is far less visible. */ - creaseBled: boolean; -} - -/** - * Build silhouette `edgeOwners` for a caster mesh in world-CSS frame. - * Used by the silhouette path inside `computeReceiverShadowFaces` (H9). - * Polygons are transformed through the same world-CSS pipeline as - * `prepareCasterPolyItems` (worldCssForMesh + optional rotation around - * the CSS-pivot) so the silhouette loop vertices land in the same world - * frame as the receiver face plane and the light direction. - * - * Caller caches by (mesh, polygon-list-identity + position + scale + - * rotation) — invalidates only when the caster's geometry or transform - * actually changes. Light direction is NOT a bust key (silhouette - * adjacency is per-mesh, facing is per-frame). - */ -function transformCasterVertices( - vertices: readonly Vec3[], - position: Vec3, - worldCss: (vert: Vec3, pos: Vec3) => Vec3, - rotation: Vec3 | null | undefined, - cssPivot: Vec3 | null, -): Vec3[] { - const wv = vertices.map((vert) => worldCss(vert, position)); - if (!cssPivot || !rotation) return wv; - return wv.map((w) => { - const local: Vec3 = [w[0] - cssPivot[0], w[1] - cssPivot[1], w[2] - cssPivot[2]]; - const r = rotateVec3InWrapperCssFrame(local, rotation); - return [r[0] + cssPivot[0], r[1] + cssPivot[1], r[2] + cssPivot[2]]; - }); -} - -export function prepareCasterEdgeOwners( - polygons: readonly Polygon[], - position: Vec3, - scale: number | Vec3 | undefined | null, - rotation?: Vec3 | null, -): ReadonlyMap { - const worldCss = worldCssForMesh(scale); - const hasRotation = !!rotation && (rotation[0] !== 0 || rotation[1] !== 0 || rotation[2] !== 0); - const cssPivot = hasRotation ? worldPositionToCss(position) : null; - // Lightweight stub list — buildEdgeOwners only reads `.vertices`. - const worldPolys: Polygon[] = polygons.map((p) => { - if (!p) return { vertices: [], color: "" }; - return { vertices: transformCasterVertices(p.vertices, position, worldCss, rotation, cssPivot), color: "" }; - }); - return buildEdgeOwnersHelper(worldPolys); -} - -/** - * Build CasterPolyItem[] for a caster mesh. Pure: same inputs → same output. - * The caller memoizes by mesh ref + bust key. `includePolygonIndex(idx)` - * decides which polygons participate (e.g. dedup drop + atlas-plan filter - * in vanilla; just dedup drop in React/Vue without an atlas-plan concept). - */ -export function prepareCasterPolyItems( - polygons: readonly Polygon[], - position: Vec3, - scale: number | Vec3 | undefined | null, - includePolygonIndex: (polygonIndex: number) => boolean, - rotation?: Vec3 | null, -): CasterPolyItem[] { - const out: CasterPolyItem[] = []; - const worldCss = worldCssForMesh(scale); - // Mesh rotation lives on the wrapper as a CSS rotate around the wrapper - // local origin. To put caster vertices into the SAME world-space the - // wrapper composites into, we apply the wrapper's CSS rotation matrix - // around the wrapper's CSS-space origin (which is `cssPos`). Without - // this, shadows stay attached to the un-rotated mesh while the visible - // mesh tips/swings. - const hasRotation = !!rotation && (rotation[0] !== 0 || rotation[1] !== 0 || rotation[2] !== 0); - const cssPivot = hasRotation ? worldPositionToCss(position) : null; - for (let i = 0; i < polygons.length; i++) { - if (!includePolygonIndex(i)) continue; - const polygon = polygons[i]; - if (!polygon) continue; - const wv = transformCasterVertices(polygon.vertices, position, worldCss, rotation, cssPivot); - let minX = Infinity, minY = Infinity, minZ = Infinity; - let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity; - for (const w of wv) { - if (w[0] < minX) minX = w[0]; if (w[0] > maxX) maxX = w[0]; - if (w[1] < minY) minY = w[1]; if (w[1] > maxY) maxY = w[1]; - if (w[2] < minZ) minZ = w[2]; if (w[2] > maxZ) maxZ = w[2]; - } - const bboxCorners: Vec3[] = [ - [minX, minY, minZ], [maxX, minY, minZ], - [minX, maxY, minZ], [maxX, maxY, minZ], - [minX, minY, maxZ], [maxX, minY, maxZ], - [minX, maxY, maxZ], [maxX, maxY, maxZ], - ]; - let planeN: Vec3 | null = null; - let planeOffset = 0; - if (wv.length >= 3) { - const O = wv[0]!, w1 = wv[1]!, w2 = wv[2]!; - const e1: Vec3 = [w1[0] - O[0], w1[1] - O[1], w1[2] - O[2]]; - const e2: Vec3 = [w2[0] - O[0], w2[1] - O[1], w2[2] - O[2]]; - const nx = e2[1] * e1[2] - e2[2] * e1[1]; - const ny = e2[2] * e1[0] - e2[0] * e1[2]; - const nz = e2[0] * e1[1] - e2[1] * e1[0]; - const nLen = Math.hypot(nx, ny, nz); - if (nLen > 1e-9) { - planeN = [nx / nLen, ny / nLen, nz / nLen]; - planeOffset = planeN[0] * O[0] + planeN[1] * O[1] + planeN[2] * O[2]; - } - } - out.push({ wv, bboxCorners, planeN, planeOffset, polygonIndex: i }); - } - return out; -} - -/** - * Default clearance between a receiver face and the shadow painted on it, in - * world units. - * - * Single source of truth on purpose: this default was previously written out at - * seven call sites across the three renderers, and two of them drifted to - * `0.001` — small enough that the receiver painted over its own shadow, so - * `castShadow` + `receiveShadow` emitted paths that darkened nothing. - * - * Note this is a WORLD-unit value while the depth conflict it must win is - * resolved in device pixels, so it still fails below roughly `zoom: 1`. That - * limitation is documented for callers; fixing it needs projection-aware - * clearance. - */ -export const POLY_DEFAULT_SHADOW_LIFT = 0.05; - -/** - * Build ReceiverFacePlane[] for a receiver mesh. Pure: groups coplanar - * polygons, computes (u,v) basis + outline, applies interior occlusion cull - * (drops face planes hidden behind a parallel face plane within wall- - * thickness range). - * - * `shadowLift` is the world-unit lift applied along each face normal so the - * shadow SVG composites above the surface without z-fighting (matches the - * ground-shadow `shadow.lift` option). - */ -export function prepareReceiverFacePlanes( - polygons: readonly Polygon[], - position: Vec3, - scale: number | Vec3 | undefined | null, - dedupDrop: ReadonlySet, - shadowLift: number, - rotation?: Vec3 | null, -): ReceiverFacePlane[] { - const baseWorldCss = worldCssForMesh(scale); - // Same as the caster path: rotation lives on the wrapper as a CSS - // rotate around its local origin (CSS-pivot = `worldPositionToCss(pos)`). - // Wrap the per-vertex worldCss so the receiver face planes match where - // the rotated mesh actually composites — otherwise the shadow projects - // onto the un-rotated face plane and detaches from the visible surface. - const hasRotation = !!rotation && (rotation[0] !== 0 || rotation[1] !== 0 || rotation[2] !== 0); - const cssPivot = hasRotation ? worldPositionToCss(position) : null; - const worldCss: (vert: Vec3, pos: Vec3) => Vec3 = (hasRotation && cssPivot && rotation) - ? (vert, pos) => { - const w = baseWorldCss(vert, pos); - const local: Vec3 = [w[0] - cssPivot[0], w[1] - cssPivot[1], w[2] - cssPivot[2]]; - const r = rotateVec3InWrapperCssFrame(local, rotation); - return [r[0] + cssPivot[0], r[1] + cssPivot[1], r[2] + cssPivot[2]]; - } - : baseWorldCss; - const surfaces = groupReceiverFaceGroups(polygons, position, worldCss, dedupDrop); - let planes: ReceiverFacePlane[] = surfaces.map((group, faceIndex): ReceiverFacePlane => { - const { - O, n, u, v, outlineUv, - memberPolysUv, memberPolysWorld, memberPolyIndices, memberSharedEdges, - } = group; - let minU = Infinity, minV = Infinity, maxU = -Infinity, maxV = -Infinity; - for (const pt of outlineUv) { - if (pt[0] < minU) minU = pt[0]; - if (pt[1] < minV) minV = pt[1]; - if (pt[0] > maxU) maxU = pt[0]; - if (pt[1] > maxV) maxV = pt[1]; - } - const width = maxU - minU; - const height = maxV - minV; - const lift = shadowLift * BASE_TILE; - const Ox = O[0] + minU * u[0] + minV * v[0] + lift * n[0]; - const Oy = O[1] + minU * u[1] + minV * v[1] + lift * n[1]; - const Oz = O[2] + minU * u[2] + minV * v[2] + lift * n[2]; - const m = [ - u[0], u[1], u[2], 0, - v[0], v[1], v[2], 0, - n[0], n[1], n[2], 0, - Ox, Oy, Oz, 1, - ]; - const matrixCss = `matrix3d(${m.map((x) => x.toFixed(4)).join(",")})`; - return { - O, n, u, v, outlineUv, - memberPolysUv, memberPolysWorld, memberPolyIndices, memberSharedEdges, - memberCreaseEdges: memberPolysUv.map(() => undefined), - minU, minV, width, height, matrixCss, faceIndex, lift, - }; - }); - - // Interior occlusion cull. Drop face planes hidden behind a parallel - // plane along the outward normal (interior wall layers inside imported - // building meshes). Without z-buffer occlusion the interior wall's shadow - // would paint where the user can't see it. - const OCCL_NORMAL_TOL = 0.015; - const OCCL_OFFSET_TOL = 0.5; - // Wall thickness is typically 1-10 CSS px; beyond that the planes are - // separated by air, not nested geometry. - const OCCL_MAX_GAP = 20; - const occluded = new Set(); - for (let i = 0; i < planes.length; i++) { - if (occluded.has(i)) continue; - const pi = planes[i]!; - const offsetI = pi.n[0] * pi.O[0] + pi.n[1] * pi.O[1] + pi.n[2] * pi.O[2]; - const iMinU = pi.minU, iMinV = pi.minV; - const iMaxU = pi.minU + pi.width, iMaxV = pi.minV + pi.height; - for (let j = 0; j < planes.length; j++) { - if (j === i || occluded.has(j)) continue; - const pj = planes[j]!; - const dotN = pi.n[0] * pj.n[0] + pi.n[1] * pj.n[1] + pi.n[2] * pj.n[2]; - if (dotN < 1 - OCCL_NORMAL_TOL) continue; - const offsetJ = pi.n[0] * pj.O[0] + pi.n[1] * pj.O[1] + pi.n[2] * pj.O[2]; - if (offsetJ <= offsetI + OCCL_OFFSET_TOL) continue; - if (offsetJ - offsetI > OCCL_MAX_GAP) continue; - let jMinU = Infinity, jMinV = Infinity, jMaxU = -Infinity, jMaxV = -Infinity; - for (const pt of pj.outlineUv) { - const wx = pj.O[0] + pt[0] * pj.u[0] + pt[1] * pj.v[0]; - const wy = pj.O[1] + pt[0] * pj.u[1] + pt[1] * pj.v[1]; - const wz = pj.O[2] + pt[0] * pj.u[2] + pt[1] * pj.v[2]; - const dx = wx - pi.O[0], dy = wy - pi.O[1], dz = wz - pi.O[2]; - const iu = dx * pi.u[0] + dy * pi.u[1] + dz * pi.u[2]; - const iv = dx * pi.v[0] + dy * pi.v[1] + dz * pi.v[2]; - if (iu < jMinU) jMinU = iu; - if (iu > jMaxU) jMaxU = iu; - if (iv < jMinV) jMinV = iv; - if (iv > jMaxV) jMaxV = iv; - } - if (jMinU <= iMinU && jMaxU >= iMaxU && jMinV <= iMinV && jMaxV >= iMaxV) { - // Don't cull when j is much LARGER than i — small surface feature - // (door frame, recess) sitting inside a broader wall. - const iArea = Math.max(0, iMaxU - iMinU) * Math.max(0, iMaxV - iMinV); - const jArea = Math.max(0, jMaxU - jMinU) * Math.max(0, jMaxV - jMinV); - const OCCL_AREA_RATIO = 2.0; - if (jArea > iArea * OCCL_AREA_RATIO) continue; - occluded.add(i); - break; - } - } - } - planes = planes.filter((_, i) => !occluded.has(i)); - fillCrossGroupCreaseEdges(planes); - return planes; -} - -/** - * Fill each plane's `memberCreaseEdges`: member edges whose neighbouring - * surface belongs to a DIFFERENT face plane. On imported architecture (the - * castle) this is the dominant receiver-edge class — merlon face vs merlon top - * vs wall — and each group's shadow SVG stops exactly at the crease with an - * antialiased edge, so two abutting layers leave a pale hairline. - * - * Matching runs on `memberPolysWorld` — the members' TRUE world vertices — not - * on the (u, v) outlines lifted back to 3D. That lift is exact only for members - * that are perfectly coplanar with their group plane, and imported architecture - * is routinely not: the castle has quads with vertices ~0.3 CSS px off their - * own plane. Projecting drops that offset, so each of two groups snaps the SAME - * shared vertex to a different point, moving an exactly-shared crease edge - * further apart than `RECEIVER_EDGE_PERP_EPS` (0.25) allows — and the crease - * silently vanished, leaving the pale hairline it exists to close. - * - * Two passes mirroring `detectMemberSharedEdges`: an exact quantized - * endpoint-pair hash, then a collinear-overlap pass over a uniform spatial - * hash for T-junctions where a crease neighbour covers only part of the edge. - * Edges already in `memberSharedEdges` stay in the candidate pool AND record - * their crease neighbours like any other edge. Doing so cannot change their own - * clip expansion — an edge gets one bleed amount whether it is shared, crease, - * or both — but the mark is also what flips the face to its opaque pre-blend - * (`creaseBled`), and that is required for soundness: when a wall's bottom edge - * lands on a seam interior to a floor group, the wall's opaque bleed overlaps a - * floor still painting at alpha unless the floor is marked too, and the - * composite then depends on SVG paint order. It is also the direction - * `qualifiesCrease` condition 4 reads, so suppressing the mark made BOTH sides - * refuse to bleed and the hairline came back. The 2D `planarEdgesShareLine` - * predicate cannot be reused here - * because crease neighbours are by definition not coplanar — - * `spatialEdgesShareLine` is its world-space sibling with the same tolerances. - * - * Runs AFTER the occlusion cull so hidden interior planes cannot mark a - * visible plane's edge as a crease. - */ -function fillCrossGroupCreaseEdges(planes: ReceiverFacePlane[]): void { - if (planes.length < 2) return; - type Ref = SpatialEdge & { plane: number; member: number; edge: number; pre: boolean }; - const refs: Ref[] = []; - for (let pi = 0; pi < planes.length; pi++) { - const plane = planes[pi]!; - const memberWorld = plane.memberPolysWorld; - if (!memberWorld) continue; - for (let mi = 0; mi < memberWorld.length; mi++) { - const world = memberWorld[mi]!; - if (world.length < 3) continue; - const shared = plane.memberSharedEdges?.[mi]; - for (let e = 0; e < world.length; e++) { - const built = spatialEdge(world[e]!, world[(e + 1) % world.length]!); - // `pre` = already bled as a within-group seam. It still records crease - // neighbours (see the header); `pre` only means the collinear pass need - // not spend a query initiating from it, since its bleed amount is - // already decided and the other side of any T-junction queries it. - if (built) refs.push({ ...built, plane: pi, member: mi, edge: e, pre: !!shared?.has(e) }); - } - } - } - if (refs.length < 2) return; - - const marked: Array | undefined>[] = planes.map((p) => - p.memberPolysUv.map(() => undefined), - ); - const neighbourPlanes: Array> = planes.map(() => new Set()); - const mark = (r: Ref, neighbourPlane: number): void => { - const perPlane = marked[r.plane]!; - let map = perPlane[r.member]; - if (!map) { map = new Map(); perPlane[r.member] = map; } - neighbourPlanes[r.plane]!.add(neighbourPlane); - const existing = map.get(r.edge); - if (!existing) { map.set(r.edge, [neighbourPlane]); return; } - if (!existing.includes(neighbourPlane)) existing.push(neighbourPlane); - }; - const isMarked = (r: Ref): boolean => - r.pre || !!marked[r.plane]![r.member]?.has(r.edge); - - const QUANT = 1000; - const ptKey = (x: number, y: number, z: number): string => - `${Math.round(x * QUANT)},${Math.round(y * QUANT)},${Math.round(z * QUANT)}`; - const owners = new Map(); - for (const r of refs) { - const ka = ptKey(r.ax, r.ay, r.az); - const kb = ptKey(r.bx, r.by, r.bz); - const key = ka < kb ? `${ka}|${kb}` : `${kb}|${ka}`; - let list = owners.get(key); - if (!list) { list = []; owners.set(key, list); } - list.push(r); - } - for (const list of owners.values()) { - if (list.length < 2) continue; - let crossPlane = false; - for (let i = 1; i < list.length; i++) { - if (list[i]!.plane !== list[0]!.plane) { crossPlane = true; break; } - } - if (!crossPlane) continue; - for (const r of list) { - for (const other of list) { - if (other.plane !== r.plane) mark(r, other.plane); - } - } - } - - // Collinear-overlap pass for crease T-JUNCTIONS: a member edge lying along - // part of a neighbouring surface's longer edge, which the exact endpoint-pair - // hash above cannot see. Creases are LOCAL in world space, so candidates come - // from a uniform spatial hash rather than a linear sweep — on the coliseum a - // minX sweep still visited 2.1M pairs (94% of edges are already matched by - // the exact pass, so almost every visit was wasted), which dominated the - // whole preparation. - // - // Cell hash collisions merely widen a bucket; the geometric predicate still - // decides, so they cost time and never correctness. Edges whose padded AABB - // spans more cells than CELL_CAP go in `oversized` and are tested against - // everything, which keeps a few long edges from exploding the grid. - const EPS = RECEIVER_EDGE_PERP_EPS; - let lenSum = 0; - for (const r of refs) lenSum += r.len; - const cell = Math.max(2 * EPS, lenSum / refs.length); - const CELL_CAP = 32; - const cellKey = (ix: number, iy: number, iz: number): number => - (Math.imul(ix, 73856093) ^ Math.imul(iy, 19349663) ^ Math.imul(iz, 83492791)) | 0; - const grid = new Map(); - const oversized: number[] = []; - const cellRange = (r: Ref) => ({ - x0: Math.floor((r.minX - EPS) / cell), x1: Math.floor((r.maxX + EPS) / cell), - y0: Math.floor((r.minY - EPS) / cell), y1: Math.floor((r.maxY + EPS) / cell), - z0: Math.floor((r.minZ - EPS) / cell), z1: Math.floor((r.maxZ + EPS) / cell), - }); - for (let i = 0; i < refs.length; i++) { - const c = cellRange(refs[i]!); - const span = (c.x1 - c.x0 + 1) * (c.y1 - c.y0 + 1) * (c.z1 - c.z0 + 1); - if (span > CELL_CAP) { oversized.push(i); continue; } - for (let ix = c.x0; ix <= c.x1; ix++) { - for (let iy = c.y0; iy <= c.y1; iy++) { - for (let iz = c.z0; iz <= c.z1; iz++) { - const k = cellKey(ix, iy, iz); - let bucket = grid.get(k); - if (!bucket) { bucket = []; grid.set(k, bucket); } - bucket.push(i); - } - } - } - } - // Stamp so a pair sharing several cells is only evaluated once. - const stamp = new Int32Array(refs.length).fill(-1); - const test = (i: number, j: number): void => { - const A = refs[i]!, B = refs[j]!; - if (A.plane === B.plane) return; - if (isMarked(A) && isMarked(B)) return; - if (!spatialEdgeBoundsOverlap(A, B)) return; - if (!spatialEdgesShareLine(A, B)) return; - mark(A, B.plane); - mark(B, A.plane); - }; - // Only edges the exact pass left UNMATCHED need querying: a pair whose two - // edges are both already marked is skipped by `test`, and every pair with an - // unmatched member is reached from that member's own query. On the coliseum - // that is ~600 queries instead of ~10600. - for (let i = 0; i < refs.length; i++) { - if (isMarked(refs[i]!)) continue; - const c = cellRange(refs[i]!); - const span = (c.x1 - c.x0 + 1) * (c.y1 - c.y0 + 1) * (c.z1 - c.z0 + 1); - if (span > CELL_CAP) continue; - for (let ix = c.x0; ix <= c.x1; ix++) { - for (let iy = c.y0; iy <= c.y1; iy++) { - for (let iz = c.z0; iz <= c.z1; iz++) { - const bucket = grid.get(cellKey(ix, iy, iz)); - if (!bucket) continue; - for (const j of bucket) { - if (j === i || stamp[j] === i) continue; - stamp[j] = i; - test(i, j); - } - } - } - } - } - for (const i of oversized) { - for (let j = 0; j < refs.length; j++) { - if (j === i) continue; - test(i, j); - } - } - - for (let pi = 0; pi < planes.length; pi++) { - planes[pi]!.memberCreaseEdges = marked[pi]!; - planes[pi]!.creaseNeighbourPlanes = neighbourPlanes[pi]!; - } -} - -/** The pass lights a camera signature is computed against. Omitting it makes - * the signature conservative (every plane contributes a bit). */ -export interface ReceiverShadowSignatureLights { - /** Directional to-source vector in CSS frame; omitted/null when the - * directional pass does not run. */ - lightDir?: Vec3 | null; - /** CSS-frame positions of the shadow-casting point lights. */ - pointLightPositions?: ReadonlyArray; -} - -/** Mirrors the per-plane `L·n` gate the passes themselves apply (point lights - * use the to-source direction at the face origin, exactly as `dirAt(O)` does), - * so a plane is dropped from the signature only when every pass would reject - * it anyway. */ -function planeReceivesAnyLight( - plane: ReceiverFacePlane, - lights: ReceiverShadowSignatureLights, -): boolean { - const n = plane.n; - const dir = lights.lightDir; - if (dir) { - const len = Math.hypot(dir[0], dir[1], dir[2]) || 1; - if ((dir[0] * n[0] + dir[1] * n[1] + dir[2] * n[2]) / len > 1e-6) return true; - } - for (const p of lights.pointLightPositions ?? []) { - const O = plane.O; - const dx = p[0] - O[0], dy = p[1] - O[1], dz = p[2] - O[2]; - const len = Math.hypot(dx, dy, dz) || 1; - if ((dx * n[0] + dy * n[1] + dz * n[2]) / len > 1e-6) return true; - } - return false; -} - -/** - * Compact signature of every CAMERA-dependent decision in a receiver's shadow - * output. Two camera orientations with the same signature produce byte- - * identical shadow SVGs for that receiver; a different signature means the - * camera has crossed a facing boundary and the shadows must be re-emitted. - * - * The camera enters the pipeline at exactly one predicate — is this face plane - * turned toward the camera — read twice: once to decide whether the face paints - * at all, and once per crease to decide whether the neighbour on the far side - * is drawn there (`qualifiesCrease` condition 1). Both reduce to the same - * per-plane boolean, so the whole camera dependence is the bit vector of - * `normalFacesCamera` over the receiver's planes. Packing it base-32 keeps the - * key short enough to compare as a string on every camera frame; the count of - * CONTRIBUTING planes prefixes the packed bits because the final group is - * zero-padded to five, so without it an all-back-facing 2-plane receiver and an - * all-back-facing 5-plane one both read "0" and a plane-set change between them - * would be missed. - * - * Mesh rotation is deliberately NOT folded in — the plane normals are already - * in world frame, so `normalFacesCamera` must not re-apply it. That makes the - * signature meaningless against planes built for a different mesh rotation, so - * the CALLER must rebuild its planes (and re-emit) whenever the mesh transform - * changes, before comparing keys. Mirrors the per-mesh voxel DOM cull's - * `cameraCullVisibleSignature` — recompute on boundary crossings, not per frame. - */ -export function receiverShadowCameraSignature( - planes: readonly ReceiverFacePlane[], - cameraRot: CameraCullRotation, - lights?: ReceiverShadowSignatureLights, -): string { - const cameraOnlyRot: CameraCullRotation = { rotX: cameraRot.rotX, rotY: cameraRot.rotY }; - let out = ""; - let acc = 0; - let bits = 0; - let contributing = 0; - for (const plane of planes) { - // A plane no light can reach fails the `L·n` test in every pass, so it - // emits nothing and cannot qualify as a crease neighbour at ANY camera - // angle. Its facing bit could never change the output, and including it - // would invent boundary crossings that re-emit the scene for nothing. - if (lights && !planeReceivesAnyLight(plane, lights)) continue; - acc = (acc << 1) | (normalFacesCamera(plane.n, cameraOnlyRot) ? 1 : 0); - bits += 1; - contributing += 1; - if (bits === 5) { - out += acc.toString(32); - acc = 0; - bits = 0; - } - } - if (bits > 0) out += (acc << (5 - bits)).toString(32); - return `${contributing.toString(32)}:${out}`; -} - -/** Input for `computeReceiverShadowFaces`. */ -export interface ComputeReceiverShadowFacesInput { - /** Precomputed face planes from `prepareReceiverFacePlanes`. */ - receiverPlanes: ReceiverFacePlane[]; - /** Receiver's polygon list, used to look up per-face fill color. */ - receiverPolygons: readonly Polygon[]; - /** Whether the receiver mesh has any textured polygons. Drives the - * textured-darken opacity calc vs solid-replace fill color. */ - receiverHasTexture: boolean; - /** Per-caster items + caller id, in caller-defined order. */ - casters: ReceiverCasterInput[]; - /** Light direction in CSS frame, pointing TOWARD the light (to-source). - * For a point light this is a representative direction (used only for the - * textured-receiver opacity ratio); per-vertex directions come from - * `lightPos`. */ - lightDir: Vec3; - /** When set, the light is a point light at this CSS-frame position. The - * shadow projection becomes radial (per-vertex direction from the light) - * and the silhouette fast path is disabled (facing is per-polygon). */ - lightPos?: Vec3; - /** Every point light in the scene (CSS-frame absolute positions), used to - * compute the SHADED shadow color — a shadow shows the receiver lit by all - * lights EXCEPT the blocked one, so a spot shadowed from one colored light - * still shows the others' color (Three.js parity). Includes non-shadow- - * casting lights, since they still illuminate the shadowed region. */ - allPointLights?: ReadonlyArray<{ position: Vec3; color?: string; intensity?: number }>; - /** For a point-light pass, the index into `allPointLights` of the light - * being shadowed (excluded from the remaining-light fill). Undefined for - * the directional pass (which instead excludes the directional light). */ - thisPointIndex?: number; - /** Camera cull rotation (rotX/rotY + receiver mesh rotation) so back- - * facing receiver faces can be skipped. */ - cameraRot: CameraCullRotation; - /** Ambient light (used for solid-receiver shadow tint via shadePolygon). */ - ambientLight?: PolyAmbientLight; - /** Directional light (used for textured-darken opacity calc). */ - directionalLight?: PolyDirectionalLight; - /** Scene shadow options. */ - shadow?: { color?: string; opacity?: number; maxExtend?: number }; - /** Also bleed member clip outlines along CREASE edges (neighbour in a - * different, non-coplanar face group). Cross-group bleed makes shadow - * regions OVERLAP between two SVGs, which only composites correctly when - * the caller paints the pre-blended color opaque (see - * `computeMergedReceiverShadows`) — so it is opt-in and additionally gated - * per face on `preblendEligible`. */ - creaseBleed?: boolean; -} - /** * The pure per-frame algorithm. Returns one ReceiverShadowFaceSpec for each * visible receiver face that catches at least one caster's shadow. Skips @@ -1065,43 +226,6 @@ export function computeReceiverShadowFaces( return extractSilhouetteLoops(edgeOwners, facing); }); - // 3D half-space clip: keep the portion of `loop` where planeDist > eps. - // Sutherland-Hodgman style — used to clip silhouette loops that dip - // below the receiver plane before projection. Returns `[]` if the loop - // ends up fully below. - const clipLoopAbovePlane = ( - loop: ReadonlyArray, - O: Vec3, n: Vec3, eps: number, - ): Vec3[] => { - if (loop.length < 3) return []; - const out: Vec3[] = []; - const dist = (p: Vec3) => - (p[0] - O[0]) * n[0] + (p[1] - O[1]) * n[1] + (p[2] - O[2]) * n[2]; - const cross = (a: Vec3, b: Vec3, da: number, db: number): Vec3 => { - const s = (da - eps) / (da - db); - return [ - a[0] + s * (b[0] - a[0]), - a[1] + s * (b[1] - a[1]), - a[2] + s * (b[2] - a[2]), - ]; - }; - for (let i = 0; i < loop.length; i++) { - const curr = loop[i]!; - const prev = loop[(i + loop.length - 1) % loop.length]!; - const dCurr = dist(curr); - const dPrev = dist(prev); - const inCurr = dCurr > eps; - const inPrev = dPrev > eps; - if (inCurr) { - if (!inPrev) out.push(cross(prev, curr, dPrev, dCurr)); - out.push(curr); - } else if (inPrev) { - out.push(cross(prev, curr, dPrev, dCurr)); - } - } - return out; - }; - // The face-plane normals `group.n` are already in world frame (the // worldCss wrap in prepareReceiverFacePlanes applies the mesh rotation // before the plane is built). Pass a camera-only rotation to @@ -1119,641 +243,19 @@ export function computeReceiverShadowFaces( // answerable for B before A's clips are built. Everything here is O(members) // arithmetic — no projection, no clipping — so computing it for planes that // later emit nothing is cheap. - interface PlaneShading { - /** Face is turned toward this pass's light (can receive it at all). */ - lit: boolean; - /** Face is turned toward the camera. SVGs don't honor CSS - * backface-visibility reliably, so a back-of-camera face must not paint. */ - camFacing: boolean; - effOp: number; - fillColor: string; - fullLitFill: string; - preblendEligible: boolean; - /** The opaque colour this face paints when it bleeds a crease, or null when - * the pre-blend is ineligible or unrepresentable. Two faces may only bleed - * into each other when these are equal — overlap of two DIFFERENT opaque - * colours is not idempotent, it just paints one over the other. */ - preblendPaint: string | null; - } - const UNLIT_SHADING: PlaneShading = { - lit: false, camFacing: false, effOp: 0, fillColor: "", - fullLitFill: "", preblendEligible: false, preblendPaint: null, - }; - - const shadingForPlane = (group: ReceiverFacePlane): PlaneShading => { - const { O, n, u, v, outlineUv } = group; - // Back-facing receiver face → can't receive light → no shadow. For point - // lights the representative direction is the to-source vector at the - // face origin. - const faceDir = dirAt(O); - const Ldotn = faceDir[0] * n[0] + faceDir[1] * n[1] + faceDir[2] * n[2]; - if (Ldotn <= 1e-6) return UNLIT_SHADING; - if (!normalFacesCamera(n, cameraOnlyRot)) return UNLIT_SHADING; - - // Per-face light scalars for the SHADED shadow color. `dirDot` is the - // directional Lambert term (always vs the directional vector, not the - // pass's faceDir). Point dots use the to-source direction from the face - // CENTROID — matching the baked surface shading (per-polygon centroid), so - // the shadow's full-lit base color equals the painted receiver and the SVG - // leaves no visible base-color box. (Projection still uses per-vertex - // radial directions; only the flat per-face color uses the centroid.) - const dirDot = Math.max(0, Lx * n[0] + Ly * n[1] + Lz * n[2]); - let cMeanU = 0, cMeanV = 0; - for (const pt of outlineUv) { cMeanU += pt[0]; cMeanV += pt[1]; } - const cInv = outlineUv.length > 0 ? 1 / outlineUv.length : 0; - cMeanU *= cInv; cMeanV *= cInv; - const cen: Vec3 = [ - O[0] + cMeanU * u[0] + cMeanV * v[0], - O[1] + cMeanU * u[1] + cMeanV * v[1], - O[2] + cMeanU * u[2] + cMeanV * v[2], - ]; - const pointDots: number[] = []; - let pointTotalScale = 0; - if (allPointLights) { - for (let k = 0; k < allPointLights.length; k++) { - const pl = allPointLights[k]!; - const dx = pl.position[0] - cen[0]; - const dy = pl.position[1] - cen[1]; - const dz = pl.position[2] - cen[2]; - const len = Math.hypot(dx, dy, dz) || 1; - const dot = Math.max(0, (dx / len) * n[0] + (dy / len) * n[1] + (dz / len) * n[2]); - pointDots[k] = dot; - pointTotalScale += (pl.intensity ?? 1) * dot; - } - } - - // Intensity removed by THIS pass (the blocked light) and the scene total. - const thisScale = isDirPass - ? dirIntensity * dirDot - : (allPointLights?.[thisPointIndex ?? -1]?.intensity ?? 1) * (pointDots[thisPointIndex ?? -1] ?? 0); - const totalScale = dirIntensity * dirDot + pointTotalScale + Math.max(0, ambIntensity); - - // Per-group opacity for textured receivers. The shadow leaves the receiver - // lit by everything EXCEPT this pass's light: shadow_linear = - // lit_linear × remaining/total. A black overlay at sRGB opacity o gives - // lit_srgb × (1 − o), so o = 1 − (remaining/total)^(1/2.4). For a lone - // directional light remaining = ambient, matching the previous formula. - let effOp = opacity; - if (receiverHasTexture) { - if (totalScale > 0) { - const remainingRatio = Math.max(0, (totalScale - thisScale) / totalScale); - effOp = opacity * (1 - Math.pow(remainingRatio, 1 / 2.4)); - } else { - effOp = 0; - } - } - - // Per-face shadow tint. Each receiver face uses ITS OWN polygon color - // (one material per coplanar group). The fill is the receiver lit by - // every light EXCEPT this pass's blocked light — so a region shadowed - // from one colored light still shows the others' color. A lone - // directional light → remaining = ambient only (unchanged from before). - const groupPolyIdx = group.memberPolyIndices[0] ?? 0; - const groupColor = receiverPolygons[groupPolyIdx]?.color ?? "#cccccc"; - const remDirScale = isDirPass ? 0 : dirIntensity * dirDot; - const remPointContribs: { color: string; scale: number }[] = []; - if (allPointLights) { - for (let k = 0; k < allPointLights.length; k++) { - if (isPoint && k === thisPointIndex) continue; - const dot = pointDots[k] ?? 0; - if (dot <= 0) continue; - const pl = allPointLights[k]!; - remPointContribs.push({ color: pl.color ?? "#ffffff", scale: (pl.intensity ?? 1) * dot }); - } - } - const fillColor = receiverHasTexture - ? userShadowColor - : shadePolygon(groupColor, remDirScale, dirColor, ambColor, ambIntensity, remPointContribs); - - // Full-lit face color C (every light) for the multi-light merge — callers - // multiply C by each pass's `fill/C` so overlapping shadows composite to - // the both-blocked color. Empty for textured (per-pixel base). - const fullPointContribs: { color: string; scale: number }[] = []; - if (allPointLights) { - for (let k = 0; k < allPointLights.length; k++) { - const dot = pointDots[k] ?? 0; - if (dot <= 0) continue; - const pl = allPointLights[k]!; - fullPointContribs.push({ color: pl.color ?? "#ffffff", scale: (pl.intensity ?? 1) * dot }); - } - } - const fullLitFill = receiverHasTexture - ? "" - : shadePolygon(groupColor, dirIntensity * dirDot, dirColor, ambColor, ambIntensity, fullPointContribs); - - // A face group is formed by plane + adjacency, never by material and never - // by exact normal: `fullLitFill` uses member[0]'s color and the GROUP - // plane's Lambert term, while each leaf is baked from its OWN normal (and, - // under point lights, its own centroid). The opaque pre-blend is a pixel - // identity only where those agree for every member, so that is checked - // directly rather than assumed — and the pre-blend must additionally be - // representable at all. - const preblend = receiverHasTexture ? null : blendShadowOverLitBase(fullLitFill, fillColor, effOp); - const preblendEligible = !receiverHasTexture - && groupMembersShareLitColor( - group, receiverPolygons, fullLitFill, - [Lx, Ly, Lz], dirIntensity, dirColor, ambColor, ambIntensity, allPointLights, - ) - && preblend !== null; - return { - lit: true, - camFacing: true, - effOp, - fillColor, - fullLitFill, - preblendEligible, - preblendPaint: preblendEligible ? preblend : null, - }; + const shadingCtx: PlaneShadingContext = { + dirAt, cameraOnlyRot, Lx, Ly, Lz, isDirPass, isPoint, + allPointLights, thisPointIndex, dirIntensity, dirColor, + ambColor, ambIntensity, opacity, receiverHasTexture, + receiverPolygons, userShadowColor, }; + const shadingByPlane: PlaneShading[] = receiverPlanes.map((group) => + computePlaneShading(group, shadingCtx), + ); - const shadingByPlane: PlaneShading[] = receiverPlanes.map(shadingForPlane); - - /** - * One receiver face's spec, or null when the face paints nothing. - * - * `allowedCreaseNeighbours` is the set of neighbouring PLANE INDICES this - * face may bleed its member clips into; null disables crease bleed entirely. - * The caller resolves it (see the two-phase driver below) because it depends - * on whether those neighbours emit a layer in this same pass. - */ - const computePlaneSpec = ( - group: ReceiverFacePlane, - planeIdx: number, - allowedCreaseNeighbours: ReadonlySet | null, - ): ReceiverShadowFaceSpec | null => { - const shading = shadingByPlane[planeIdx]!; - if (!shading.lit || !shading.camFacing) return null; - const { effOp, fillColor, fullLitFill, preblendEligible } = shading; - const { O, n, u, v, outlineUv, minU, minV, width, height } = group; - // Denominator of the directional projection (to-source · face normal), - // known positive here because `shading.lit` already passed. - const faceDir = dirAt(O); - const Ldotn = faceDir[0] * n[0] + faceDir[1] * n[1] + faceDir[2] * n[2]; - - const planeDist = (w: Vec3): number => - (w[0] - O[0]) * n[0] + (w[1] - O[1]) * n[1] + (w[2] - O[2]) * n[2]; - const planeCross = (a: Vec3, b: Vec3, da: number, db: number): Vec3 => { - const s = da / (da - db); - return [a[0] + s * (b[0] - a[0]), a[1] + s * (b[1] - a[1]), a[2] + s * (b[2] - a[2])]; - }; - const projectOntoPlane = (w: Vec3): [number, number] => { - const VmOx = w[0] - O[0]; - const VmOy = w[1] - O[1]; - const VmOz = w[2] - O[2]; - // Directional: constant to-source L, denom = Ldotn. Point: per-vertex - // to-source direction, denom = d·n. Clamp denom to a small positive so - // a grazing point-light vertex projects far (then gets reach/outline - // clipped) instead of dividing by ~0. - const d = isPoint ? dirAt(w) : ([Lx, Ly, Lz] as Vec3); - const denomRaw = isPoint ? d[0] * n[0] + d[1] * n[1] + d[2] * n[2] : Ldotn; - const denom = denomRaw > 1e-3 ? denomRaw : 1e-3; - const t = (VmOx * n[0] + VmOy * n[1] + VmOz * n[2]) / denom; - const Px = w[0] - t * d[0]; - const Py = w[1] - t * d[1]; - const Pz = w[2] - t * d[2]; - const dx = Px - O[0]; - const dy = Py - O[1]; - const dz = Pz - O[2]; - return [dx * u[0] + dy * u[1] + dz * u[2], dx * v[0] + dy * v[1] + dz * v[2]]; - }; - - type PerCasterClip = { - id: T; - verts: Array>; - subPolygonIndices: number[]; - }; - const clippedByCaster = new Map(); - let totalClipped = 0; - - // Per-plane shadow-reach rect: union of all casters' perpendicular - // footprints on this receiver face in (u,v), expanded by maxExtend. - // Mirrors groundShadow.ts's `clipBounds = fp ± maxExtend` semantic so - // `shadow.maxExtend` caps shadow reach uniformly across the ground - // path and the receiver-mesh path. - let footMinU = Infinity, footMinV = Infinity; - let footMaxU = -Infinity, footMaxV = -Infinity; - for (const casterEntry of casters) { - for (const item of casterEntry.items) { - for (const w of item.wv) { - const dx = w[0] - O[0]; - const dy = w[1] - O[1]; - const dz = w[2] - O[2]; - const cu = dx * u[0] + dy * u[1] + dz * u[2]; - const cv = dx * v[0] + dy * v[1] + dz * v[2]; - if (cu < footMinU) footMinU = cu; - if (cu > footMaxU) footMaxU = cu; - if (cv < footMinV) footMinV = cv; - if (cv > footMaxV) footMaxV = cv; - } - } - } - const reachRect: Array<[number, number]> = Number.isFinite(footMinU) ? [ - [footMinU - maxExtend, footMinV - maxExtend], - [footMaxU + maxExtend, footMinV - maxExtend], - [footMaxU + maxExtend, footMaxV + maxExtend], - [footMinU - maxExtend, footMaxV + maxExtend], - ] : []; - const SELF_SHADOW_EPS = 0.05; - const receiverPlaneOffset = n[0] * O[0] + n[1] * O[1] + n[2] * O[2]; - const COPLANAR_NORMAL_TOL = 0.0025; - const COPLANAR_OFFSET_TOL = 5.0; - // Seam cull fires only when the caster face is within ~20° of coplanar - // with the receiver face (|n·n| > cos 20°). Edge-neighbours on a smooth - // mesh sit a few degrees apart (culled as sub-pixel slivers); a faceted - // occluder across a hard edge is far more angled (kept as a real shadow). - const SEAM_COPLANAR_TOL = 0.94; - // Member clip polygons with seam bleed: each member's CCW outline is - // expanded outward by SHADOW_CLIP_SEAM_BLEED along the edges it SHARES - // with another member of this group (non-shared edges stay put), so the - // clipped shadow subpaths of abutting members overlap across the seam - // instead of leaving a hairline light strip under SVG antialiasing. - // Overlapping pieces land in the same nonzero compound path, so they - // cannot double-darken. `safePlanSeamBleedAmount` fits each edge's - // amount to the polygon (tiny/degenerate members fall back to 0), and - // `offsetConvexPolygonPointsByEdgeAmounts` returns the input unchanged - // for non-convex/degenerate outlines — the unexpanded member is the - // fallback in every failure mode. - // - // CREASE edges (neighbour in a different, non-coplanar group) are unioned - // into the same expansion when `applyCreaseBleed` holds. Those two groups - // are separate SVGs, so their expanded clips OVERLAP rather than landing in - // one nonzero path — safe only because the caller then paints the - // pre-blended color opaque (idempotent under overlap). - // - // Which crease edges may bleed is decided by the caller, per neighbouring - // PLANE, and handed down as `allowedCreaseNeighbours` — see - // `qualifiesCrease` for the three conditions a neighbour must meet - // (camera-facing, emits an abutting layer in this pass, paints the same - // resolved colour). - const applyCreaseBleed = allowedCreaseNeighbours !== null; - const creaseBleedsIntoNeighbour = (neighbours: number[] | undefined): boolean => { - if (!neighbours || !allowedCreaseNeighbours) return false; - for (const b of neighbours) if (allowedCreaseNeighbours.has(b)) return true; - return false; - }; - let anyCreaseBled = false; - const memberClipsUv: Array> = group.memberPolysUv.map( - (memberPoly, mi) => { - const ccw = ensureCcw2D(memberPoly); - const shared = group.memberSharedEdges?.[mi]; - const crease = applyCreaseBleed ? group.memberCreaseEdges?.[mi] : undefined; - const sharedCount = shared?.size ?? 0; - const creaseCount = crease?.size ?? 0; - if ((sharedCount === 0 && creaseCount === 0) || ccw.length < 3) return ccw; - const flat: number[] = []; - for (const p of ccw) flat.push(p[0], p[1]); - let bledCrease = false; - const amounts = ccw.map((_, e) => { - const isCrease = creaseBleedsIntoNeighbour(crease?.get(e)); - if (!shared?.has(e) && !isCrease) return 0; - const amount = safePlanSeamBleedAmount(flat, e, SHADOW_CLIP_SEAM_BLEED); - if (amount > 0 && isCrease) bledCrease = true; - return amount; - }); - let any = false; - for (const a of amounts) if (a > 0) { any = true; break; } - if (!any) return ccw; - const expanded = offsetConvexPolygonPointsByEdgeAmounts(flat, amounts); - if (expanded === flat || expanded.length !== flat.length) return ccw; - if (bledCrease) anyCreaseBled = true; - const out2: Array<[number, number]> = []; - for (let i = 0; i < expanded.length; i += 2) { - out2.push([expanded[i]!, expanded[i + 1]!]); - } - return out2; - }, - ); - // Widen the PRE-CLIP copy of the group hull so it cannot cap a bled member - // edge (see CLIP_OUTLINE_EXTRA). Only where a crease edge was actually - // bled: everywhere else the stored outline must be used verbatim or - // multi-light and textured receivers would shift. Within-group shared edges - // are interior to the hull and never need it. The stored `outlineUv` — and - // therefore the face plane's box and matrix — is never touched either way. - const clipOutlineUv = anyCreaseBled && CLIP_OUTLINE_EXTRA > 0 - ? expandConvexHullOutward(outlineUv, CLIP_OUTLINE_EXTRA) - : outlineUv; - const clipPad = clipOutlineUv === outlineUv ? 0 : CLIP_OUTLINE_EXTRA; - // Projection prefilter bounds. Padded with the clip widening so a caster - // whose footprint only reaches into the bled margin is not rejected here. - const fMinU = minU - clipPad, fMinV = minV - clipPad; - const fMaxU = group.minU + width + clipPad; - const fMaxV = group.minV + height + clipPad; - for (let casterIdx = 0; casterIdx < casters.length; casterIdx++) { - const casterEntry = casters[casterIdx]!; - const sharedEdgeMap = casterEntry.selfShadowEdgeMap; - - // Silhouette path: when the caster qualified for silhouette - // extraction, project each closed loop onto this receiver face - // instead of fan-triangulating every front-facing polygon. One - // sub-path per loop replaces O(items) sub-paths. - const silhouette = silhouetteByCaster[casterIdx]; - if (silhouette !== null) { - // Empty loop set means "light fully behind mesh" → no shadow on - // this receiver from this caster. - if (silhouette.length === 0) continue; - // Parametric (override) loops carry coverage holes (courtyards, the - // coliseum arena) as opposite-wound loops. Preserving that relative - // winding lets them subtract under the path's nonzero fill. The - // (u,v) basis may flip handedness, so pick one global orientation from - // the largest loop (→ outer CCW) and apply it uniformly. The exact - // silhouette path keeps per-loop `ensureCcw2D` (no holes there). - const isOverride = !!casterEntry.overrideSilhouette; - let overrideFlip = false; - if (isOverride) { - let bestAbs = 0; - for (const loop of silhouette) { - if (loop.length < 3) continue; - const ab = clipLoopAbovePlane(loop, O, n, SELF_SHADOW_EPS); - if (ab.length < 3) continue; - const pr = ab.map(projectOntoPlane); - let area = 0; - for (let i = 0; i < pr.length; i++) { - const p = pr[i]!, q = pr[(i + 1) % pr.length]!; - area += p[0] * q[1] - q[0] * p[1]; - } - if (Math.abs(area) > bestAbs) { bestAbs = Math.abs(area); overrideFlip = area < 0; } - } - } - for (const loop of silhouette) { - if (loop.length < 3) continue; - // 3D clip against the receiver plane half-space first — silhouette - // vertices that sit BELOW the receiver project to the wrong side - // of the (u,v) basis and produce inverted shadows. - const above3D = clipLoopAbovePlane(loop, O, n, SELF_SHADOW_EPS); - if (above3D.length < 3) continue; - const projected = above3D.map(projectOntoPlane); - const subjectCcw = isOverride - ? (overrideFlip ? [...projected].reverse() : projected) - : ensureCcw2D(projected); - const reachClipped = reachRect.length === 4 - ? clipPolygonToConvex2D(subjectCcw, reachRect) - : subjectCcw; - if (reachClipped.length < 3) continue; - const clip = clipPolygonToConvex2D(reachClipped, clipOutlineUv); - if (clip.length < 3) continue; - let bucket: { id: T; verts: Vec2[][]; subPolygonIndices: number[] } | undefined; - for (const memberClipPoly of memberClipsUv) { - const memberClip = clipPolygonToConvex2D(clip, memberClipPoly); - if (memberClip.length < 3) continue; - if (!bucket) { - bucket = clippedByCaster.get(casterEntry.id); - if (!bucket) { - bucket = { id: casterEntry.id, verts: [], subPolygonIndices: [] }; - clippedByCaster.set(casterEntry.id, bucket); - } - } - bucket.verts.push(memberClip); - // Silhouette path has no source-polygon attribution; use -1 - // so DevTools tooling can tell it apart from per-poly indices. - bucket.subPolygonIndices.push(-1); - totalClipped++; - } - } - continue; - } - - for (const item of casterEntry.items) { - // Seam-shadow cull: if this caster polygon shares an edge with ANY - // of the receiver face's member polygons, skip — projecting a - // shared-edge poly always produces a thin sliver along the seam, - // independent of plane angle. Without this cull, smooth-shaded - // GLB meshes (apple, sphere, teapot) get a dark spiderweb of - // shadow streaks at every vertex. - if (sharedEdgeMap) { - const adj = sharedEdgeMap.get(item.polygonIndex); - if (adj) { - let sharesEdge = false; - for (const memberIdx of group.memberPolyIndices) { - if (adj.has(memberIdx)) { sharesEdge = true; break; } - } - // Seam-shadow cull, but ONLY when the caster is near-COPLANAR with - // the receiver face. That's the smooth-shaded-mesh case the cull is - // for: edge-neighbour faces a few degrees apart project sub-pixel - // slivers (the apple/sphere/teapot "spiderweb"). A caster at a real - // angle to the receiver across a shared edge — a wing over a - // fuselage, a wall meeting a floor — casts a genuine self-shadow and - // must be kept (culling it left big holes on faceted meshes). - if (sharesEdge) { - const cn = item.planeN; - const coplanar = !cn || - Math.abs(cn[0] * n[0] + cn[1] * n[1] + cn[2] * n[2]) > SEAM_COPLANAR_TOL; - if (coplanar) continue; - } - } - } - // Light back-face cull: a caster polygon whose normal points AWAY - // from the light cannot cast shadow on anything beyond what the - // matching front-facing polygons (across the same closed mesh - // silhouette) already cover. For convex closed meshes the projected - // shadow is unchanged; for concave closed meshes the union under - // fill-rule=nonzero collapses to the same silhouette. For open - // one-sided meshes lit from behind the shadow disappears — this - // is the "single-sided material" semantic that most pipelines - // default to. Use a small epsilon so polygons exactly edge-on - // (grazing the light) still cast — they're the silhouette edge - // of a closed mesh. - if (item.planeN && !doubleSidedByCaster[casterIdx]) { - let lx = Lx, ly = Ly, lz = Lz; - if (isPoint) { - // To-source direction from the caster polygon's centroid. - let cx = 0, cy = 0, cz = 0; - for (const w of item.wv) { cx += w[0]; cy += w[1]; cz += w[2]; } - const inv = item.wv.length > 0 ? 1 / item.wv.length : 0; - const d = dirAt([cx * inv, cy * inv, cz * inv]); - lx = d[0]; ly = d[1]; lz = d[2]; - } - const cnDotL = item.planeN[0] * lx + item.planeN[1] * ly + item.planeN[2] * lz; - if (cnDotL > -1e-6) continue; - } - // Coplanar caster skip. - if (item.planeN) { - const cn = item.planeN; - const dot = cn[0] * n[0] + cn[1] * n[1] + cn[2] * n[2]; - if (Math.abs(dot) > 1 - COPLANAR_NORMAL_TOL) { - const sign = dot > 0 ? 1 : -1; - if (Math.abs(item.planeOffset - sign * receiverPlaneOffset) < COPLANAR_OFFSET_TOL) { - continue; - } - } - } - // 8-projection bbox prefilter, also confirms ≥ 1 corner ABOVE plane. - const corners = item.bboxCorners; - let anyAbove = false; - let pMinU = Infinity, pMinV = Infinity, pMaxU = -Infinity, pMaxV = -Infinity; - for (let ci = 0; ci < 8; ci++) { - const c = corners[ci]!; - if (planeDist(c) > SELF_SHADOW_EPS) anyAbove = true; - const pr = projectOntoPlane(c); - if (pr[0] < pMinU) pMinU = pr[0]; - if (pr[0] > pMaxU) pMaxU = pr[0]; - if (pr[1] < pMinV) pMinV = pr[1]; - if (pr[1] > pMaxV) pMaxV = pr[1]; - } - if (!anyAbove) continue; - if (pMaxU < fMinU || pMinU > fMaxU || pMaxV < fMinV || pMinV > fMaxV) continue; - const wv = item.wv; - // Fan-triangulate. - for (let triIdx = 1; triIdx < wv.length - 1; triIdx++) { - const tA = wv[0]!, tB = wv[triIdx]!, tC = wv[triIdx + 1]!; - const dA = planeDist(tA), dB = planeDist(tB), dC = planeDist(tC); - const above: Vec3[] = []; - const cycle: Array<[Vec3, number]> = [[tA, dA], [tB, dB], [tC, dC]]; - for (let k = 0; k < 3; k++) { - const [p, dp] = cycle[k]!; - const [q, dq] = cycle[(k + 1) % 3]!; - const pAbove = dp > SELF_SHADOW_EPS; - const qAbove = dq > SELF_SHADOW_EPS; - if (pAbove) above.push(p); - if (pAbove !== qAbove) above.push(planeCross(p, q, dp, dq)); - } - if (above.length < 3) continue; - const projected = above.map(projectOntoPlane); - const subjectCcw = ensureCcw2D(projected); - // Shadow-reach clip: cap how far the projected shadow can stretch - // beyond the caster mesh's perpendicular footprint on this face, - // before the (potentially expensive) outline + member clips. - const reachClipped = reachRect.length === 4 - ? clipPolygonToConvex2D(subjectCcw, reachRect) - : subjectCcw; - if (reachClipped.length < 3) continue; - const clip = clipPolygonToConvex2D(reachClipped, clipOutlineUv); - if (clip.length < 3) continue; - // Clip the projected shadow against each MEMBER polygon of the - // receiver face group, not just the group's outer outline. The - // outline can span concave regions / holes / disconnected - // coplanar islands where the mesh has no actual surface; - // clipping against the union of members keeps shadow pixels - // strictly over real mesh polygons. - // - // Self-shadow sliver cull is applied PER MEMBER-CLIP (not on the - // outline-clip): smooth-shaded GLBs produce many near-coplanar - // adjacent polys whose individual member-clips come out as long - // thin sub-pixel-adjacent streaks the user reads as visual - // noise. Earlier the cull ran on the outline-clip and would - // drop legitimate thin shadows landing on a thin-but-real - // member polygon (e.g. flight-system poly 38, a long diagonal - // slab receiving a thin shadow from the outer ring). Moving the - // cull onto each member-clip lets real thin shadows through - // while still discarding tiny-area / extreme-aspect noise. - let bucket: { id: T; verts: Vec2[][]; subPolygonIndices: number[] } | undefined; - for (const memberClipPoly of memberClipsUv) { - const memberClip = clipPolygonToConvex2D(clip, memberClipPoly); - if (memberClip.length < 3) continue; - if (sharedEdgeMap) { - let twiceArea = 0; - let minClipX = Infinity, maxClipX = -Infinity; - let minClipY = Infinity, maxClipY = -Infinity; - for (let pi = 0; pi < memberClip.length; pi++) { - const p1 = memberClip[pi]!; - const p2 = memberClip[(pi + 1) % memberClip.length]!; - twiceArea += p1[0] * p2[1] - p2[0] * p1[1]; - if (p1[0] < minClipX) minClipX = p1[0]; - if (p1[0] > maxClipX) maxClipX = p1[0]; - if (p1[1] < minClipY) minClipY = p1[1]; - if (p1[1] > maxClipY) maxClipY = p1[1]; - } - const clipArea = Math.abs(twiceArea) * 0.5; - // Pure tiny-area noise → drop. Aspect-only filter is gone: - // legitimate thin shadows (poly 38) trip it; member-clip is - // the geometric guard against bridging-region false positives. - if (clipArea < 5) continue; - } - if (!bucket) { - bucket = clippedByCaster.get(casterEntry.id); - if (!bucket) { - bucket = { id: casterEntry.id, verts: [], subPolygonIndices: [] }; - clippedByCaster.set(casterEntry.id, bucket); - } - } - bucket.verts.push(memberClip); - bucket.subPolygonIndices.push(item.polygonIndex); - totalClipped++; - } - } - } - } - - if (totalClipped === 0 || !(width > 0) || !(height > 0)) return null; - - // Tight shadow-content bbox in (u, v). The receiver face outline can be - // huge (e.g. a 17500×17500 CSS-px floor at world units × BASE_TILE), but - // the actual shadow content typically covers a fraction of that area. - // Sizing the SVG to the receiver outline made Chrome's compositor drop - // the entire layer past certain perspective angles (the projected - // trapezoid grew unboundedly when one corner approached the horizon). - // Clipping the SVG to the shadow's tight bbox keeps the layer small - // enough that compositor heuristics keep painting it at every camera - // orientation. The on-screen geometry is unchanged: matrix3d is rebased - // to the tight bbox and path coordinates are emitted relative to it. - let shMinU = Infinity, shMinV = Infinity, shMaxU = -Infinity, shMaxV = -Infinity; - for (const entry of clippedByCaster.values()) { - for (const verts of entry.verts) { - for (const pt of verts) { - if (pt[0] < shMinU) shMinU = pt[0]; - if (pt[0] > shMaxU) shMaxU = pt[0]; - if (pt[1] < shMinV) shMinV = pt[1]; - if (pt[1] > shMaxV) shMaxV = pt[1]; - } - } - } - // Round outward to whole pixels so the SVG covers the path with one px - // of slack on each side (matches the path's `.toFixed(1)` precision). - shMinU = Math.floor(shMinU - 1); - shMinV = Math.floor(shMinV - 1); - shMaxU = Math.ceil(shMaxU + 1); - shMaxV = Math.ceil(shMaxV + 1); - // Clamp the tight bbox to the face outline so we never extend the SVG - // past the receiver surface (would let a stray pixel render off-face). - if (shMinU < minU - clipPad) shMinU = minU - clipPad; - if (shMinV < minV - clipPad) shMinV = minV - clipPad; - if (shMaxU > minU + width + clipPad) shMaxU = minU + width + clipPad; - if (shMaxV > minV + height + clipPad) shMaxV = minV + height + clipPad; - const tightW = shMaxU - shMinU; - const tightH = shMaxV - shMinV; - if (!(tightW > 0) || !(tightH > 0)) return null; - - // matrix3d for the tight SVG: O + shMinU*u + shMinV*v + lift*n - const liftN = group.lift; - const tx = O[0] + shMinU * u[0] + shMinV * v[0] + liftN * n[0]; - const ty = O[1] + shMinU * u[1] + shMinV * v[1] + liftN * n[1]; - const tz = O[2] + shMinU * u[2] + shMinV * v[2] + liftN * n[2]; - const tm = [ - u[0], u[1], u[2], 0, - v[0], v[1], v[2], 0, - n[0], n[1], n[2], 0, - tx, ty, tz, 1, - ]; - const tightMatrixCss = `matrix3d(${tm.map((x) => x.toFixed(4)).join(",")})`; - - const paths: Array> = []; - const facePolysUv: Array> = []; - for (const entry of clippedByCaster.values()) { - let d = ""; - for (const verts of entry.verts) { - d += `M${(verts[0]![0] - shMinU).toFixed(1)},${(verts[0]![1] - shMinV).toFixed(1)}`; - for (let j = 1; j < verts.length; j++) { - d += `L${(verts[j]![0] - shMinU).toFixed(1)},${(verts[j]![1] - shMinV).toFixed(1)}`; - } - d += "Z"; - facePolysUv.push(verts.map((p) => [p[0], p[1]] as [number, number])); - } - paths.push({ casterId: entry.id, d, casterPolygonIndices: entry.subPolygonIndices }); - } - - return { - faceIndex: group.faceIndex, - memberPolyIndices: group.memberPolyIndices, - matrixCss: tightMatrixCss, - width: tightW, - height: tightH, - fill: fillColor, - opacity: effOp, - paths, - fullLitFill, - facePolysUv, - preblendEligible, - creaseBled: anyCreaseBled, - }; + const projectionCtx: PlaneProjectionContext = { + casters, silhouetteByCaster, doubleSidedByCaster, + isPoint, Lx, Ly, Lz, dirAt, maxExtend, }; // ── Two-phase crease resolution ───────────────────────────────────────── @@ -1768,7 +270,9 @@ export function computeReceiverShadowFaces( // neighbours are non-coplanar, so their Lambert terms and therefore their // resolved colours differ) phase 2 does no work at all. const specs: Array | null> = - receiverPlanes.map((group, i) => computePlaneSpec(group, i, null)); + receiverPlanes.map((group, i) => + computePlaneShadowSpec(group, shadingByPlane[i]!, null, projectionCtx), + ); if (creaseBleed === true) { /** @@ -1817,7 +321,7 @@ export function computeReceiverShadowFaces( if (qualifiesCrease(a, b)) allowed.add(b); } if (allowed.size === 0) continue; - const bled = computePlaneSpec(group, a, allowed); + const bled = computePlaneShadowSpec(group, shadingByPlane[a]!, allowed, projectionCtx); if (bled) specs[a] = bled; } } @@ -1826,216 +330,6 @@ export function computeReceiverShadowFaces( return out; } -// ── Multi-light per-face merge ────────────────────────────────────────────── -// All renderers share this so a receiver FACE's lights merge into ONE SVG: -// overlapping shadows then composite correctly (single light → one path with -// the remaining-light color; multi-light solid → a full-lit base + one -// `mix-blend-mode: multiply` layer per light, so the both-blocked overlap -// becomes base·∏factor). Pure data in → DOM-ready descriptors out; each -// renderer only emits the / nodes. - -/** One path inside a merged face SVG. */ -export interface MergedShadowLayer { - /** Path data (`M…L…Z`, already offset to the SVG's tight bbox). */ - d: string; - /** Fill color (remaining-light color for a single layer, multiply factor for - * a merged solid layer, dark shadow color for textured). */ - fill: string; - /** Apply `mix-blend-mode: multiply` (merged solid layers only). */ - multiply: boolean; - /** Per-path opacity (1 for merged solid layers, which carry strength on the - * SVG; the pass's own opacity otherwise). */ - opacity: number; -} - -/** One receiver FACE's merged shadow, ready to mount as a single SVG. */ -export interface MergedShadowFace { - faceIndex: number; - memberPolyIndices: number[]; - matrixCss: string; - width: number; - height: number; - /** SVG-level opacity (shadow strength for merged solid faces, else 1). */ - svgOpacity: number; - /** Full-lit base path (merged solid faces only); null otherwise. */ - baseFill: string | null; - baseD: string | null; - layers: MergedShadowLayer[]; -} - -/** Inputs for `computeMergedReceiverShadows` — the full light set for one - * receiver, plus its prepared face planes and casters. */ -export interface MergedReceiverShadowInput { - receiverPlanes: ReceiverFacePlane[]; - receiverPolygons: readonly Polygon[]; - receiverHasTexture: boolean; - casters: ReceiverCasterInput[]; - /** Directional light vector in CSS frame (to-source). */ - lightDir: Vec3; - /** Run the directional pass (caller gates on a real, nonzero-intensity - * directional light). */ - runDirectional: boolean; - /** One pass per shadow-casting point light: CSS position + index into - * `allPointLights`. Empty in dynamic mode (point lights are baked-only). */ - pointPasses: ReadonlyArray<{ lightPos: Vec3; index: number }>; - /** All point lights (CSS positions) for the shaded shadow color; empty in - * dynamic mode. */ - allPointLights?: ReadonlyArray<{ position: Vec3; color?: string; intensity?: number }>; - cameraRot: CameraCullRotation; - ambientLight?: PolyAmbientLight; - directionalLight?: PolyDirectionalLight; - shadow?: { color?: string; opacity?: number; maxExtend?: number }; -} - -/** Per-channel multiply factor `remaining / full` (both sRGB hex) as `rgb(...)`. - * Painting the base = `full` then this with `mix-blend-mode: multiply` - * reproduces `remaining`; overlapping factors multiply to the both-removed - * color. */ -function shadowMultiplyFactor(remaining: string, full: string): string { - const a = parseHexColor(remaining)?.rgb ?? [0, 0, 0]; - const b = parseHexColor(full)?.rgb ?? [255, 255, 255]; - const f = (i: number): number => { - const c = b[i] ?? 0; - if (c <= 0) return 255; - return Math.max(0, Math.min(255, Math.round((a[i]! / c) * 255))); - }; - return `rgb(${f(0)},${f(1)},${f(2)})`; -} - -/** - * `blend(litFaceColor, shadowedColor, opacity)` in sRGB — the exact pixel an - * SVG path of `fill` at `opacity` produces over a receiver painted `base`. - * - * Emitting THIS opaque is pixel-identical to the alpha version, edges - * included: at antialiased coverage `c` the alpha version gives - * `base·(1 − o·c) + fill·o·c`, and painting the pre-blend at coverage `c` - * gives `base·(1 − c) + (base·(1 − o) + fill·o)·c` — the same expression. - * What changes is OVERLAP: two overlapping opaque paints of one color are that - * color, where two overlapping alpha paints darken twice. That idempotence is - * what lets a face's clip bleed across a crease into its neighbour's SVG. - * - * Returns `null` when either color is not a plain hex (a translucent receiver - * makes `shadePolygon` return `rgba(...)`, whose alpha the blend cannot - * represent) — the caller then keeps the alpha form. - */ -function blendShadowOverLitBase(base: string, fill: string, opacity: number): string | null { - const b = parseHexColor(base); - const f = parseHexColor(fill); - if (!b || !f || b.alpha !== 1 || f.alpha !== 1) return null; - const o = Math.max(0, Math.min(1, opacity)); - const mix = (i: number): number => { - const bc = b.rgb[i] ?? 0; - const fc = f.rgb[i] ?? 0; - return Math.max(0, Math.min(255, Math.round(bc + (fc - bc) * o))); - }; - return `rgb(${mix(0)},${mix(1)},${mix(2)})`; -} - -/** A stored member polygon's own surface normal, in the same world-CSS frame - * and with the same fan accumulation the face plane was built with. The - * stored world list may have been reversed to make the (u, v) copy CCW, so - * the result is oriented onto the group normal's hemisphere — grouping - * already guarantees every member sits within `RECEIVER_NORMAL_TOL` of it, - * which makes that orientation unambiguous. Null for a degenerate member. */ -function memberWorldNormal(ws: readonly Vec3[], groupN: Vec3): Vec3 | null { - if (ws.length < 3) return null; - const O = ws[0]!; - let nx = 0, ny = 0, nz = 0; - for (let k = 1; k + 1 < ws.length; k++) { - const a = ws[k]!, b = ws[k + 1]!; - const e1x = a[0] - O[0], e1y = a[1] - O[1], e1z = a[2] - O[2]; - const e2x = b[0] - O[0], e2y = b[1] - O[1], e2z = b[2] - O[2]; - nx += e2y * e1z - e2z * e1y; - ny += e2z * e1x - e2x * e1z; - nz += e2x * e1y - e2y * e1x; - } - const len = Math.hypot(nx, ny, nz); - if (len < 1e-9) return null; - const s = (nx * groupN[0] + ny * groupN[1] + nz * groupN[2]) >= 0 ? 1 / len : -1 / len; - return [nx * s, ny * s, nz * s]; -} - -/** - * True when EVERY member of a face group paints exactly `fullLitFill`. - * - * `fullLitFill` is one color per GROUP: member[0]'s base color shaded with the - * group plane's normal (and, for point lights, the group hull centroid). The - * renderer bakes each leaf from its OWN normal and centroid, and a group is - * formed by plane + adjacency — not by material, and not by exact normal - * (`RECEIVER_NORMAL_TOL` admits ~2.5°). So this reproduces the renderer's - * per-leaf shading and compares, instead of assuming. - * - * The pre-blend replaces `leaf·(1−o) + fill·o` with `fullLit·(1−o) + fill·o` - * painted opaque; the residual is `(leaf − fullLit)·(1−o)`. Requiring exact - * equality makes it zero for every member, at every opacity — which is what - * "pixel-identical" has to mean before a face's clip may bleed into a - * neighbouring SVG. - */ -function groupMembersShareLitColor( - group: ReceiverFacePlane, - receiverPolygons: readonly Polygon[], - fullLitFill: string, - L: Vec3, - dirIntensity: number, - dirColor: string, - ambColor: string, - ambIntensity: number, - allPointLights: ReadonlyArray<{ position: Vec3; color?: string; intensity?: number }> | undefined, -): boolean { - if (fullLitFill === "") return false; - const members = group.memberPolysWorld; - if (!members || members.length === 0) return false; - const hasPoints = !!allPointLights && allPointLights.length > 0; - const litCache = new Map(); - for (let mi = 0; mi < members.length; mi++) { - const ws = members[mi]!; - const color = receiverPolygons[group.memberPolyIndices[mi] ?? -1]?.color ?? "#cccccc"; - const nm = memberWorldNormal(ws, group.n); - if (!nm) return false; - const dot = Math.max(0, L[0] * nm[0] + L[1] * nm[1] + L[2] * nm[2]); - const contribs: { color: string; scale: number }[] = []; - if (hasPoints) { - let cx = 0, cy = 0, cz = 0; - for (const w of ws) { cx += w[0]; cy += w[1]; cz += w[2]; } - const inv = 1 / ws.length; - cx *= inv; cy *= inv; cz *= inv; - for (const pl of allPointLights!) { - const dx = pl.position[0] - cx, dy = pl.position[1] - cy, dz = pl.position[2] - cz; - const len = Math.hypot(dx, dy, dz) || 1; - const d = Math.max(0, (dx / len) * nm[0] + (dy / len) * nm[1] + (dz / len) * nm[2]); - if (d <= 0) continue; - contribs.push({ color: pl.color ?? "#ffffff", scale: (pl.intensity ?? 1) * d }); - } - } - const key = `${color}|${dot.toFixed(6)}|${contribs.map((c) => `${c.color}:${c.scale.toFixed(6)}`).join(",")}`; - let lit = litCache.get(key); - if (lit === undefined) { - lit = shadePolygon(color, dirIntensity * dot, dirColor, ambColor, ambIntensity, contribs); - litCache.set(key, lit); - } - if (lit !== fullLitFill) return false; - } - return true; -} - -/** Build an `M…L…Z` path from face-(u,v) polygons offset to (minU, minV). */ -function polysToPathD( - polys: ReadonlyArray>, - minU: number, - minV: number, -): string { - let d = ""; - for (const poly of polys) { - if (poly.length < 3) continue; - d += `M${(poly[0]![0] - minU).toFixed(1)},${(poly[0]![1] - minV).toFixed(1)}`; - for (let j = 1; j < poly.length; j++) { - d += `L${(poly[j]![0] - minU).toFixed(1)},${(poly[j]![1] - minV).toFixed(1)}`; - } - d += "Z"; - } - return d; -} - /** * Run every light pass for one receiver and merge each face's passes into a * single SVG descriptor. Shared by all three renderers so multi-light shadow @@ -2044,142 +338,7 @@ function polysToPathD( export function computeMergedReceiverShadows( input: MergedReceiverShadowInput, ): MergedShadowFace[] { - const { - receiverPlanes, receiverPolygons, receiverHasTexture, casters, - lightDir, runDirectional, pointPasses, allPointLights, - cameraRot, ambientLight, directionalLight, shadow, - } = input; - const shadowOpacity = shadow?.opacity ?? 0.25; - - const planeByFace = new Map(); - for (const pl of receiverPlanes) planeByFace.set(pl.faceIndex, pl); - - type Layer = { polys: Array>; fill: string; opacity: number }; - type FaceAgg = { - memberPolyIndices: number[]; - base: string; - solid: boolean; - preblendEligible: boolean; - creaseBled: boolean; - layers: Layer[]; - }; - const perFace = new Map(); - - // Crease bleed is only safe where the opaque pre-blend applies, and the - // pre-blend only applies to a SINGLE-pass solid face. With more than one - // light pass a face may aggregate two layers and take the base + multiply - // path, whose layers do NOT compose across separate SVGs and are not - // idempotent — so multi-light receivers keep today's geometry and behavior - // exactly. Gating on the pass count (rather than per-face layer count) is - // required because the clips are built during the passes, before the - // per-face layer count is known. - const creaseBleed = !receiverHasTexture && (runDirectional ? 1 : 0) + pointPasses.length === 1; - - const runPass = (lightPos: Vec3 | undefined, thisPointIndex: number | undefined): void => { - const specs = computeReceiverShadowFaces({ - receiverPlanes, receiverPolygons, receiverHasTexture, casters, - lightDir, lightPos, allPointLights, thisPointIndex, - cameraRot, ambientLight, directionalLight, shadow, creaseBleed, - }); - for (const spec of specs) { - if (spec.facePolysUv.length === 0) continue; - const solid = spec.fullLitFill !== ""; - let agg = perFace.get(spec.faceIndex); - if (!agg) { - agg = { - memberPolyIndices: spec.memberPolyIndices, - base: spec.fullLitFill, - solid, - preblendEligible: spec.preblendEligible, - creaseBled: false, - layers: [], - }; - perFace.set(spec.faceIndex, agg); - } - if (spec.creaseBled) agg.creaseBled = true; - agg.layers.push({ polys: spec.facePolysUv, fill: spec.fill, opacity: spec.opacity }); - } - }; - if (runDirectional) runPass(undefined, undefined); - for (const p of pointPasses) runPass(p.lightPos, p.index); - - const out: MergedShadowFace[] = []; - for (const [faceIndex, agg] of perFace) { - const plane = planeByFace.get(faceIndex); - if (!plane || agg.layers.length === 0) continue; - let minU = Infinity, minV = Infinity, maxU = -Infinity, maxV = -Infinity; - for (const layer of agg.layers) for (const poly of layer.polys) for (const pt of poly) { - if (pt[0] < minU) minU = pt[0]; - if (pt[0] > maxU) maxU = pt[0]; - if (pt[1] < minV) minV = pt[1]; - if (pt[1] > maxV) maxV = pt[1]; - } - if (!Number.isFinite(minU)) continue; - minU = Math.floor(minU - 1); minV = Math.floor(minV - 1); - maxU = Math.ceil(maxU + 1); maxV = Math.ceil(maxV + 1); - const width = maxU - minU, height = maxV - minV; - if (!(width > 0) || !(height > 0)) continue; - - const { O, u, v, n, lift } = plane; - const tx = O[0] + minU * u[0] + minV * v[0] + lift * n[0]; - const ty = O[1] + minU * u[1] + minV * v[1] + lift * n[1]; - const tz = O[2] + minU * u[2] + minV * v[2] + lift * n[2]; - const m = [u[0], u[1], u[2], 0, v[0], v[1], v[2], 0, n[0], n[1], n[2], 0, tx, ty, tz, 1]; - const matrixCss = `matrix3d(${m.map((x) => x.toFixed(4)).join(",")})`; - - // Merge (base + multiply) only when a SOLID face has ≥2 lights; otherwise - // one path per pass at its own alpha (single light, or textured). - const merged = agg.solid && agg.layers.length > 1; - let baseFill: string | null = null; - let baseD: string | null = null; - const layers: MergedShadowLayer[] = []; - if (merged) { - baseFill = agg.base; - baseD = ""; - for (const layer of agg.layers) baseD += polysToPathD(layer.polys, minU, minV); - for (const layer of agg.layers) { - layers.push({ - d: polysToPathD(layer.polys, minU, minV), - fill: shadowMultiplyFactor(layer.fill, agg.base), - multiply: true, - opacity: 1, - }); - } - } else { - // Single-pass SOLID face whose clip actually bled across a crease: emit - // the pre-blended color opaque so the overlap with the neighbouring - // face's SVG is idempotent (see blendShadowOverLitBase). Every other - // face keeps the shadow color at its own alpha — the opaque form is - // pixel-identical ON the surface but far more visible OFF it, where - // `shadow.lift` parallax hangs the card past the silhouette at grazing - // angles (measured ~4× the deviation from backdrop at opacity 0.25), so - // it is paid only where it buys the seam fix. Textured receivers have a - // per-pixel base — no lit color to blend against — and never pre-blend. - for (const layer of agg.layers) { - const preblend = agg.solid && agg.preblendEligible && agg.creaseBled && agg.layers.length === 1 - ? blendShadowOverLitBase(agg.base, layer.fill, layer.opacity) - : null; - layers.push({ - d: polysToPathD(layer.polys, minU, minV), - fill: preblend ?? layer.fill, - multiply: false, - opacity: preblend ? 1 : layer.opacity, - }); - } - } - out.push({ - faceIndex, - memberPolyIndices: agg.memberPolyIndices, - matrixCss, - width, - height, - svgOpacity: merged ? shadowOpacity : 1, - baseFill, - baseD, - layers, - }); - } - return out; + return mergeReceiverShadowPasses(input, computeReceiverShadowFaces); } /** Re-export caster scale helper for caller convenience. */ diff --git a/packages/core/src/shadow/receiver/merge.ts b/packages/core/src/shadow/receiver/merge.ts new file mode 100644 index 000000000..88c8cc215 --- /dev/null +++ b/packages/core/src/shadow/receiver/merge.ts @@ -0,0 +1,179 @@ +/** + * Multi-light per-face shadow merge: aggregates every light pass for one + * receiver into one SVG descriptor per face (single-pass remaining-light or + * opaque crease-bled pre-blend, or multi-light solid base + multiply layers). + */ +import type { Vec3 } from "../../types"; +import { blendShadowOverLitBase, shadowMultiplyFactor } from "./shading"; +import type { + ComputeReceiverShadowFacesInput, + MergedReceiverShadowInput, + MergedShadowFace, + MergedShadowLayer, + ReceiverFacePlane, + ReceiverShadowFaceSpec, +} from "./types"; + +/** Build an `M…L…Z` path from face-(u,v) polygons offset to (minU, minV). */ +function polysToPathD( + polys: ReadonlyArray>, + minU: number, + minV: number, +): string { + let d = ""; + for (const poly of polys) { + if (poly.length < 3) continue; + d += `M${(poly[0]![0] - minU).toFixed(1)},${(poly[0]![1] - minV).toFixed(1)}`; + for (let j = 1; j < poly.length; j++) { + d += `L${(poly[j]![0] - minU).toFixed(1)},${(poly[j]![1] - minV).toFixed(1)}`; + } + d += "Z"; + } + return d; +} + +/** + * Run every light pass for one receiver via `computeFaces` and merge each + * face's passes into a single SVG descriptor. + */ +export function mergeReceiverShadowPasses( + input: MergedReceiverShadowInput, + computeFaces: (passInput: ComputeReceiverShadowFacesInput) => ReceiverShadowFaceSpec[], +): MergedShadowFace[] { + const { + receiverPlanes, receiverPolygons, receiverHasTexture, casters, + lightDir, runDirectional, pointPasses, allPointLights, + cameraRot, ambientLight, directionalLight, shadow, + } = input; + const shadowOpacity = shadow?.opacity ?? 0.25; + + const planeByFace = new Map(); + for (const pl of receiverPlanes) planeByFace.set(pl.faceIndex, pl); + + type Layer = { polys: Array>; fill: string; opacity: number }; + type FaceAgg = { + memberPolyIndices: number[]; + base: string; + solid: boolean; + preblendEligible: boolean; + creaseBled: boolean; + layers: Layer[]; + }; + const perFace = new Map(); + + // Crease bleed is only safe where the opaque pre-blend applies, and the + // pre-blend only applies to a SINGLE-pass solid face. With more than one + // light pass a face may aggregate two layers and take the base + multiply + // path, whose layers do NOT compose across separate SVGs and are not + // idempotent — so multi-light receivers keep today's geometry and behavior + // exactly. Gating on the pass count (rather than per-face layer count) is + // required because the clips are built during the passes, before the + // per-face layer count is known. + const creaseBleed = !receiverHasTexture && (runDirectional ? 1 : 0) + pointPasses.length === 1; + + const runPass = (lightPos: Vec3 | undefined, thisPointIndex: number | undefined): void => { + const specs = computeFaces({ + receiverPlanes, receiverPolygons, receiverHasTexture, casters, + lightDir, lightPos, allPointLights, thisPointIndex, + cameraRot, ambientLight, directionalLight, shadow, creaseBleed, + }); + for (const spec of specs) { + if (spec.facePolysUv.length === 0) continue; + const solid = spec.fullLitFill !== ""; + let agg = perFace.get(spec.faceIndex); + if (!agg) { + agg = { + memberPolyIndices: spec.memberPolyIndices, + base: spec.fullLitFill, + solid, + preblendEligible: spec.preblendEligible, + creaseBled: false, + layers: [], + }; + perFace.set(spec.faceIndex, agg); + } + if (spec.creaseBled) agg.creaseBled = true; + agg.layers.push({ polys: spec.facePolysUv, fill: spec.fill, opacity: spec.opacity }); + } + }; + if (runDirectional) runPass(undefined, undefined); + for (const p of pointPasses) runPass(p.lightPos, p.index); + + const out: MergedShadowFace[] = []; + for (const [faceIndex, agg] of perFace) { + const plane = planeByFace.get(faceIndex); + if (!plane || agg.layers.length === 0) continue; + let minU = Infinity, minV = Infinity, maxU = -Infinity, maxV = -Infinity; + for (const layer of agg.layers) for (const poly of layer.polys) for (const pt of poly) { + if (pt[0] < minU) minU = pt[0]; + if (pt[0] > maxU) maxU = pt[0]; + if (pt[1] < minV) minV = pt[1]; + if (pt[1] > maxV) maxV = pt[1]; + } + if (!Number.isFinite(minU)) continue; + minU = Math.floor(minU - 1); minV = Math.floor(minV - 1); + maxU = Math.ceil(maxU + 1); maxV = Math.ceil(maxV + 1); + const width = maxU - minU, height = maxV - minV; + if (!(width > 0) || !(height > 0)) continue; + + const { O, u, v, n, lift } = plane; + const tx = O[0] + minU * u[0] + minV * v[0] + lift * n[0]; + const ty = O[1] + minU * u[1] + minV * v[1] + lift * n[1]; + const tz = O[2] + minU * u[2] + minV * v[2] + lift * n[2]; + const m = [u[0], u[1], u[2], 0, v[0], v[1], v[2], 0, n[0], n[1], n[2], 0, tx, ty, tz, 1]; + const matrixCss = `matrix3d(${m.map((x) => x.toFixed(4)).join(",")})`; + + // Merge (base + multiply) only when a SOLID face has ≥2 lights; otherwise + // one path per pass at its own alpha (single light, or textured). + const merged = agg.solid && agg.layers.length > 1; + let baseFill: string | null = null; + let baseD: string | null = null; + const layers: MergedShadowLayer[] = []; + if (merged) { + baseFill = agg.base; + baseD = ""; + for (const layer of agg.layers) baseD += polysToPathD(layer.polys, minU, minV); + for (const layer of agg.layers) { + layers.push({ + d: polysToPathD(layer.polys, minU, minV), + fill: shadowMultiplyFactor(layer.fill, agg.base), + multiply: true, + opacity: 1, + }); + } + } else { + // Single-pass SOLID face whose clip actually bled across a crease: emit + // the pre-blended color opaque so the overlap with the neighbouring + // face's SVG is idempotent (see blendShadowOverLitBase). Every other + // face keeps the shadow color at its own alpha — the opaque form is + // pixel-identical ON the surface but far more visible OFF it, where + // `shadow.lift` parallax hangs the card past the silhouette at grazing + // angles (measured ~4× the deviation from backdrop at opacity 0.25), so + // it is paid only where it buys the seam fix. Textured receivers have a + // per-pixel base — no lit color to blend against — and never pre-blend. + for (const layer of agg.layers) { + const preblend = agg.solid && agg.preblendEligible && agg.creaseBled && agg.layers.length === 1 + ? blendShadowOverLitBase(agg.base, layer.fill, layer.opacity) + : null; + layers.push({ + d: polysToPathD(layer.polys, minU, minV), + fill: preblend ?? layer.fill, + multiply: false, + opacity: preblend ? 1 : layer.opacity, + }); + } + } + out.push({ + faceIndex, + memberPolyIndices: agg.memberPolyIndices, + matrixCss, + width, + height, + svgOpacity: merged ? shadowOpacity : 1, + baseFill, + baseD, + layers, + }); + } + return out; +} diff --git a/packages/core/src/shadow/receiver/preparation.ts b/packages/core/src/shadow/receiver/preparation.ts new file mode 100644 index 000000000..891c7b97e --- /dev/null +++ b/packages/core/src/shadow/receiver/preparation.ts @@ -0,0 +1,582 @@ +/** + * Geometry preparation helpers for receiver shadows: shared-edge maps, caster + * world-frame items & silhouette edge owners, receiver face planes (with + * interior occlusion cull and cross-group crease detection), and camera-facing + * signatures. + */ +import { BASE_TILE } from "../../camera/camera"; +import { normalFacesCamera, type CameraCullRotation } from "../../cull/cameraBackfaceCulling"; +import { rotateVec3InWrapperCssFrame } from "../../math/rotation"; +import { + groupReceiverFaceGroups, + RECEIVER_EDGE_PERP_EPS, + spatialEdge, + spatialEdgeBoundsOverlap, + spatialEdgesShareLine, + worldCssForMesh, + worldPositionToCss, + type SpatialEdge, +} from "../receiverFaceGroups"; +import { + buildEdgeOwners as buildEdgeOwnersHelper, + type EdgeOwners, +} from "../silhouette"; +import type { Polygon, Vec3 } from "../../types"; +import type { + CasterPolyItem, + ReceiverFacePlane, + ReceiverShadowSignatureLights, +} from "./types"; + +/** + * Build a polygon-adjacency map: polygonIndex → set of polygonIndex that + * share at least one edge (vertex pair, orientation-independent). Used by + * the receiver-shadow algorithm to cull sliver shadows along mesh seams. + * + * Edge match tolerance is small enough to dedupe vertex coordinates that + * went through `optimizeMeshPolygons` snap-to-plane but not so loose it + * connects geometrically distinct polygons. + */ +export function buildSharedEdgeMap( + polygons: readonly Polygon[], +): Map> { + const EDGE_MATCH_PRECISION = 1e-4; + const quant = (n: number): string => Math.round(n / EDGE_MATCH_PRECISION).toString(36); + const vertKey = (v: Vec3): string => `${quant(v[0])},${quant(v[1])},${quant(v[2])}`; + // Edge key: sorted vertex-pair string so orientation doesn't matter. + const edgeKey = (a: Vec3, b: Vec3): string => { + const ka = vertKey(a); + const kb = vertKey(b); + return ka < kb ? `${ka}|${kb}` : `${kb}|${ka}`; + }; + // edgeKey → polygon indices touching that edge + const edgeOwners = new Map(); + for (let i = 0; i < polygons.length; i++) { + const poly = polygons[i]; + if (!poly || poly.vertices.length < 2) continue; + const verts = poly.vertices; + for (let j = 0; j < verts.length; j++) { + const a = verts[j]!; + const b = verts[(j + 1) % verts.length]!; + const k = edgeKey(a, b); + let owners = edgeOwners.get(k); + if (!owners) { + owners = []; + edgeOwners.set(k, owners); + } + owners.push(i); + } + } + const out = new Map>(); + for (const owners of edgeOwners.values()) { + if (owners.length < 2) continue; + for (const a of owners) { + for (const b of owners) { + if (a === b) continue; + let set = out.get(a); + if (!set) { + set = new Set(); + out.set(a, set); + } + set.add(b); + } + } + } + return out; +} + +/** + * Build silhouette `edgeOwners` for a caster mesh in world-CSS frame. + * Used by the silhouette path inside `computeReceiverShadowFaces` (H9). + * Polygons are transformed through the same world-CSS pipeline as + * `prepareCasterPolyItems` (worldCssForMesh + optional rotation around + * the CSS-pivot) so the silhouette loop vertices land in the same world + * frame as the receiver face plane and the light direction. + * + * Caller caches by (mesh, polygon-list-identity + position + scale + + * rotation) — invalidates only when the caster's geometry or transform + * actually changes. Light direction is NOT a bust key (silhouette + * adjacency is per-mesh, facing is per-frame). + */ +function transformCasterVertices( + vertices: readonly Vec3[], + position: Vec3, + worldCss: (vert: Vec3, pos: Vec3) => Vec3, + rotation: Vec3 | null | undefined, + cssPivot: Vec3 | null, +): Vec3[] { + const wv = vertices.map((vert) => worldCss(vert, position)); + if (!cssPivot || !rotation) return wv; + return wv.map((w) => { + const local: Vec3 = [w[0] - cssPivot[0], w[1] - cssPivot[1], w[2] - cssPivot[2]]; + const r = rotateVec3InWrapperCssFrame(local, rotation); + return [r[0] + cssPivot[0], r[1] + cssPivot[1], r[2] + cssPivot[2]]; + }); +} + +export function prepareCasterEdgeOwners( + polygons: readonly Polygon[], + position: Vec3, + scale: number | Vec3 | undefined | null, + rotation?: Vec3 | null, +): ReadonlyMap { + const worldCss = worldCssForMesh(scale); + const hasRotation = !!rotation && (rotation[0] !== 0 || rotation[1] !== 0 || rotation[2] !== 0); + const cssPivot = hasRotation ? worldPositionToCss(position) : null; + // Lightweight stub list — buildEdgeOwners only reads `.vertices`. + const worldPolys: Polygon[] = polygons.map((p) => { + if (!p) return { vertices: [], color: "" }; + return { vertices: transformCasterVertices(p.vertices, position, worldCss, rotation, cssPivot), color: "" }; + }); + return buildEdgeOwnersHelper(worldPolys); +} + +/** + * Build CasterPolyItem[] for a caster mesh. Pure: same inputs → same output. + * The caller memoizes by mesh ref + bust key. `includePolygonIndex(idx)` + * decides which polygons participate (e.g. dedup drop + atlas-plan filter + * in vanilla; just dedup drop in React/Vue without an atlas-plan concept). + */ +export function prepareCasterPolyItems( + polygons: readonly Polygon[], + position: Vec3, + scale: number | Vec3 | undefined | null, + includePolygonIndex: (polygonIndex: number) => boolean, + rotation?: Vec3 | null, +): CasterPolyItem[] { + const out: CasterPolyItem[] = []; + const worldCss = worldCssForMesh(scale); + // Mesh rotation lives on the wrapper as a CSS rotate around the wrapper + // local origin. To put caster vertices into the SAME world-space the + // wrapper composites into, we apply the wrapper's CSS rotation matrix + // around the wrapper's CSS-space origin (which is `cssPos`). Without + // this, shadows stay attached to the un-rotated mesh while the visible + // mesh tips/swings. + const hasRotation = !!rotation && (rotation[0] !== 0 || rotation[1] !== 0 || rotation[2] !== 0); + const cssPivot = hasRotation ? worldPositionToCss(position) : null; + for (let i = 0; i < polygons.length; i++) { + if (!includePolygonIndex(i)) continue; + const polygon = polygons[i]; + if (!polygon) continue; + const wv = transformCasterVertices(polygon.vertices, position, worldCss, rotation, cssPivot); + let minX = Infinity, minY = Infinity, minZ = Infinity; + let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity; + for (const w of wv) { + if (w[0] < minX) minX = w[0]; if (w[0] > maxX) maxX = w[0]; + if (w[1] < minY) minY = w[1]; if (w[1] > maxY) maxY = w[1]; + if (w[2] < minZ) minZ = w[2]; if (w[2] > maxZ) maxZ = w[2]; + } + const bboxCorners: Vec3[] = [ + [minX, minY, minZ], [maxX, minY, minZ], + [minX, maxY, minZ], [maxX, maxY, minZ], + [minX, minY, maxZ], [maxX, minY, maxZ], + [minX, maxY, maxZ], [maxX, maxY, maxZ], + ]; + let planeN: Vec3 | null = null; + let planeOffset = 0; + if (wv.length >= 3) { + const O = wv[0]!, w1 = wv[1]!, w2 = wv[2]!; + const e1: Vec3 = [w1[0] - O[0], w1[1] - O[1], w1[2] - O[2]]; + const e2: Vec3 = [w2[0] - O[0], w2[1] - O[1], w2[2] - O[2]]; + const nx = e2[1] * e1[2] - e2[2] * e1[1]; + const ny = e2[2] * e1[0] - e2[0] * e1[2]; + const nz = e2[0] * e1[1] - e2[1] * e1[0]; + const nLen = Math.hypot(nx, ny, nz); + if (nLen > 1e-9) { + planeN = [nx / nLen, ny / nLen, nz / nLen]; + planeOffset = planeN[0] * O[0] + planeN[1] * O[1] + planeN[2] * O[2]; + } + } + out.push({ wv, bboxCorners, planeN, planeOffset, polygonIndex: i }); + } + return out; +} + +/** + * Build ReceiverFacePlane[] for a receiver mesh. Pure: groups coplanar + * polygons, computes (u,v) basis + outline, applies interior occlusion cull + * (drops face planes hidden behind a parallel face plane within wall- + * thickness range). + * + * `shadowLift` is the world-unit lift applied along each face normal so the + * shadow SVG composites above the surface without z-fighting (matches the + * ground-shadow `shadow.lift` option). + */ +export function prepareReceiverFacePlanes( + polygons: readonly Polygon[], + position: Vec3, + scale: number | Vec3 | undefined | null, + dedupDrop: ReadonlySet, + shadowLift: number, + rotation?: Vec3 | null, +): ReceiverFacePlane[] { + const baseWorldCss = worldCssForMesh(scale); + // Same as the caster path: rotation lives on the wrapper as a CSS + // rotate around its local origin (CSS-pivot = `worldPositionToCss(pos)`). + // Wrap the per-vertex worldCss so the receiver face planes match where + // the rotated mesh actually composites — otherwise the shadow projects + // onto the un-rotated face plane and detaches from the visible surface. + const hasRotation = !!rotation && (rotation[0] !== 0 || rotation[1] !== 0 || rotation[2] !== 0); + const cssPivot = hasRotation ? worldPositionToCss(position) : null; + const worldCss: (vert: Vec3, pos: Vec3) => Vec3 = (hasRotation && cssPivot && rotation) + ? (vert, pos) => { + const w = baseWorldCss(vert, pos); + const local: Vec3 = [w[0] - cssPivot[0], w[1] - cssPivot[1], w[2] - cssPivot[2]]; + const r = rotateVec3InWrapperCssFrame(local, rotation); + return [r[0] + cssPivot[0], r[1] + cssPivot[1], r[2] + cssPivot[2]]; + } + : baseWorldCss; + const surfaces = groupReceiverFaceGroups(polygons, position, worldCss, dedupDrop); + let planes: ReceiverFacePlane[] = surfaces.map((group, faceIndex): ReceiverFacePlane => { + const { + O, n, u, v, outlineUv, + memberPolysUv, memberPolysWorld, memberPolyIndices, memberSharedEdges, + } = group; + let minU = Infinity, minV = Infinity, maxU = -Infinity, maxV = -Infinity; + for (const pt of outlineUv) { + if (pt[0] < minU) minU = pt[0]; + if (pt[1] < minV) minV = pt[1]; + if (pt[0] > maxU) maxU = pt[0]; + if (pt[1] > maxV) maxV = pt[1]; + } + const width = maxU - minU; + const height = maxV - minV; + const lift = shadowLift * BASE_TILE; + const Ox = O[0] + minU * u[0] + minV * v[0] + lift * n[0]; + const Oy = O[1] + minU * u[1] + minV * v[1] + lift * n[1]; + const Oz = O[2] + minU * u[2] + minV * v[2] + lift * n[2]; + const m = [ + u[0], u[1], u[2], 0, + v[0], v[1], v[2], 0, + n[0], n[1], n[2], 0, + Ox, Oy, Oz, 1, + ]; + const matrixCss = `matrix3d(${m.map((x) => x.toFixed(4)).join(",")})`; + return { + O, n, u, v, outlineUv, + memberPolysUv, memberPolysWorld, memberPolyIndices, memberSharedEdges, + memberCreaseEdges: memberPolysUv.map(() => undefined), + minU, minV, width, height, matrixCss, faceIndex, lift, + }; + }); + + // Interior occlusion cull. Drop face planes hidden behind a parallel + // plane along the outward normal (interior wall layers inside imported + // building meshes). Without z-buffer occlusion the interior wall's shadow + // would paint where the user can't see it. + const OCCL_NORMAL_TOL = 0.015; + const OCCL_OFFSET_TOL = 0.5; + // Wall thickness is typically 1-10 CSS px; beyond that the planes are + // separated by air, not nested geometry. + const OCCL_MAX_GAP = 20; + const occluded = new Set(); + for (let i = 0; i < planes.length; i++) { + if (occluded.has(i)) continue; + const pi = planes[i]!; + const offsetI = pi.n[0] * pi.O[0] + pi.n[1] * pi.O[1] + pi.n[2] * pi.O[2]; + const iMinU = pi.minU, iMinV = pi.minV; + const iMaxU = pi.minU + pi.width, iMaxV = pi.minV + pi.height; + for (let j = 0; j < planes.length; j++) { + if (j === i || occluded.has(j)) continue; + const pj = planes[j]!; + const dotN = pi.n[0] * pj.n[0] + pi.n[1] * pj.n[1] + pi.n[2] * pj.n[2]; + if (dotN < 1 - OCCL_NORMAL_TOL) continue; + const offsetJ = pi.n[0] * pj.O[0] + pi.n[1] * pj.O[1] + pi.n[2] * pj.O[2]; + if (offsetJ <= offsetI + OCCL_OFFSET_TOL) continue; + if (offsetJ - offsetI > OCCL_MAX_GAP) continue; + let jMinU = Infinity, jMinV = Infinity, jMaxU = -Infinity, jMaxV = -Infinity; + for (const pt of pj.outlineUv) { + const wx = pj.O[0] + pt[0] * pj.u[0] + pt[1] * pj.v[0]; + const wy = pj.O[1] + pt[0] * pj.u[1] + pt[1] * pj.v[1]; + const wz = pj.O[2] + pt[0] * pj.u[2] + pt[1] * pj.v[2]; + const dx = wx - pi.O[0], dy = wy - pi.O[1], dz = wz - pi.O[2]; + const iu = dx * pi.u[0] + dy * pi.u[1] + dz * pi.u[2]; + const iv = dx * pi.v[0] + dy * pi.v[1] + dz * pi.v[2]; + if (iu < jMinU) jMinU = iu; + if (iu > jMaxU) jMaxU = iu; + if (iv < jMinV) jMinV = iv; + if (iv > jMaxV) jMaxV = iv; + } + if (jMinU <= iMinU && jMaxU >= iMaxU && jMinV <= iMinV && jMaxV >= iMaxV) { + // Don't cull when j is much LARGER than i — small surface feature + // (door frame, recess) sitting inside a broader wall. + const iArea = Math.max(0, iMaxU - iMinU) * Math.max(0, iMaxV - iMinV); + const jArea = Math.max(0, jMaxU - jMinU) * Math.max(0, jMaxV - jMinV); + const OCCL_AREA_RATIO = 2.0; + if (jArea > iArea * OCCL_AREA_RATIO) continue; + occluded.add(i); + break; + } + } + } + planes = planes.filter((_, i) => !occluded.has(i)); + fillCrossGroupCreaseEdges(planes); + return planes; +} + +/** + * Fill each plane's `memberCreaseEdges`: member edges whose neighbouring + * surface belongs to a DIFFERENT face plane. On imported architecture (the + * castle) this is the dominant receiver-edge class — merlon face vs merlon top + * vs wall — and each group's shadow SVG stops exactly at the crease with an + * antialiased edge, so two abutting layers leave a pale hairline. + * + * Matching runs on `memberPolysWorld` — the members' TRUE world vertices — not + * on the (u, v) outlines lifted back to 3D. That lift is exact only for members + * that are perfectly coplanar with their group plane, and imported architecture + * is routinely not: the castle has quads with vertices ~0.3 CSS px off their + * own plane. Projecting drops that offset, so each of two groups snaps the SAME + * shared vertex to a different point, moving an exactly-shared crease edge + * further apart than `RECEIVER_EDGE_PERP_EPS` (0.25) allows — and the crease + * silently vanished, leaving the pale hairline it exists to close. + * + * Two passes mirroring `detectMemberSharedEdges`: an exact quantized + * endpoint-pair hash, then a collinear-overlap pass over a uniform spatial + * hash for T-junctions where a crease neighbour covers only part of the edge. + * Edges already in `memberSharedEdges` stay in the candidate pool AND record + * their crease neighbours like any other edge. Doing so cannot change their own + * clip expansion — an edge gets one bleed amount whether it is shared, crease, + * or both — but the mark is also what flips the face to its opaque pre-blend + * (`creaseBled`), and that is required for soundness: when a wall's bottom edge + * lands on a seam interior to a floor group, the wall's opaque bleed overlaps a + * floor still painting at alpha unless the floor is marked too, and the + * composite then depends on SVG paint order. It is also the direction + * `qualifiesCrease` condition 4 reads, so suppressing the mark made BOTH sides + * refuse to bleed and the hairline came back. The 2D `planarEdgesShareLine` + * predicate cannot be reused here + * because crease neighbours are by definition not coplanar — + * `spatialEdgesShareLine` is its world-space sibling with the same tolerances. + * + * Runs AFTER the occlusion cull so hidden interior planes cannot mark a + * visible plane's edge as a crease. + */ +function fillCrossGroupCreaseEdges(planes: ReceiverFacePlane[]): void { + if (planes.length < 2) return; + type Ref = SpatialEdge & { plane: number; member: number; edge: number; pre: boolean }; + const refs: Ref[] = []; + for (let pi = 0; pi < planes.length; pi++) { + const plane = planes[pi]!; + const memberWorld = plane.memberPolysWorld; + if (!memberWorld) continue; + for (let mi = 0; mi < memberWorld.length; mi++) { + const world = memberWorld[mi]!; + if (world.length < 3) continue; + const shared = plane.memberSharedEdges?.[mi]; + for (let e = 0; e < world.length; e++) { + const built = spatialEdge(world[e]!, world[(e + 1) % world.length]!); + // `pre` = already bled as a within-group seam. It still records crease + // neighbours (see the header); `pre` only means the collinear pass need + // not spend a query initiating from it, since its bleed amount is + // already decided and the other side of any T-junction queries it. + if (built) refs.push({ ...built, plane: pi, member: mi, edge: e, pre: !!shared?.has(e) }); + } + } + } + if (refs.length < 2) return; + + const marked: Array | undefined>[] = planes.map((p) => + p.memberPolysUv.map(() => undefined), + ); + const neighbourPlanes: Array> = planes.map(() => new Set()); + const mark = (r: Ref, neighbourPlane: number): void => { + const perPlane = marked[r.plane]!; + let map = perPlane[r.member]; + if (!map) { map = new Map(); perPlane[r.member] = map; } + neighbourPlanes[r.plane]!.add(neighbourPlane); + const existing = map.get(r.edge); + if (!existing) { map.set(r.edge, [neighbourPlane]); return; } + if (!existing.includes(neighbourPlane)) existing.push(neighbourPlane); + }; + const isMarked = (r: Ref): boolean => + r.pre || !!marked[r.plane]![r.member]?.has(r.edge); + + const QUANT = 1000; + const ptKey = (x: number, y: number, z: number): string => + `${Math.round(x * QUANT)},${Math.round(y * QUANT)},${Math.round(z * QUANT)}`; + const owners = new Map(); + for (const r of refs) { + const ka = ptKey(r.ax, r.ay, r.az); + const kb = ptKey(r.bx, r.by, r.bz); + const key = ka < kb ? `${ka}|${kb}` : `${kb}|${ka}`; + let list = owners.get(key); + if (!list) { list = []; owners.set(key, list); } + list.push(r); + } + for (const list of owners.values()) { + if (list.length < 2) continue; + let crossPlane = false; + for (let i = 1; i < list.length; i++) { + if (list[i]!.plane !== list[0]!.plane) { crossPlane = true; break; } + } + if (!crossPlane) continue; + for (const r of list) { + for (const other of list) { + if (other.plane !== r.plane) mark(r, other.plane); + } + } + } + + // Collinear-overlap pass for crease T-JUNCTIONS: a member edge lying along + // part of a neighbouring surface's longer edge, which the exact endpoint-pair + // hash above cannot see. Creases are LOCAL in world space, so candidates come + // from a uniform spatial hash rather than a linear sweep — on the coliseum a + // minX sweep still visited 2.1M pairs (94% of edges are already matched by + // the exact pass, so almost every visit was wasted), which dominated the + // whole preparation. + // + // Cell hash collisions merely widen a bucket; the geometric predicate still + // decides, so they cost time and never correctness. Edges whose padded AABB + // spans more cells than CELL_CAP go in `oversized` and are tested against + // everything, which keeps a few long edges from exploding the grid. + const EPS = RECEIVER_EDGE_PERP_EPS; + let lenSum = 0; + for (const r of refs) lenSum += r.len; + const cell = Math.max(2 * EPS, lenSum / refs.length); + const CELL_CAP = 32; + const cellKey = (ix: number, iy: number, iz: number): number => + (Math.imul(ix, 73856093) ^ Math.imul(iy, 19349663) ^ Math.imul(iz, 83492791)) | 0; + const grid = new Map(); + const oversized: number[] = []; + const cellRange = (r: Ref) => ({ + x0: Math.floor((r.minX - EPS) / cell), x1: Math.floor((r.maxX + EPS) / cell), + y0: Math.floor((r.minY - EPS) / cell), y1: Math.floor((r.maxY + EPS) / cell), + z0: Math.floor((r.minZ - EPS) / cell), z1: Math.floor((r.maxZ + EPS) / cell), + }); + for (let i = 0; i < refs.length; i++) { + const c = cellRange(refs[i]!); + const span = (c.x1 - c.x0 + 1) * (c.y1 - c.y0 + 1) * (c.z1 - c.z0 + 1); + if (span > CELL_CAP) { oversized.push(i); continue; } + for (let ix = c.x0; ix <= c.x1; ix++) { + for (let iy = c.y0; iy <= c.y1; iy++) { + for (let iz = c.z0; iz <= c.z1; iz++) { + const k = cellKey(ix, iy, iz); + let bucket = grid.get(k); + if (!bucket) { bucket = []; grid.set(k, bucket); } + bucket.push(i); + } + } + } + } + // Stamp so a pair sharing several cells is only evaluated once. + const stamp = new Int32Array(refs.length).fill(-1); + const test = (i: number, j: number): void => { + const A = refs[i]!, B = refs[j]!; + if (A.plane === B.plane) return; + if (isMarked(A) && isMarked(B)) return; + if (!spatialEdgeBoundsOverlap(A, B)) return; + if (!spatialEdgesShareLine(A, B)) return; + mark(A, B.plane); + mark(B, A.plane); + }; + // Only edges the exact pass left UNMATCHED need querying: a pair whose two + // edges are both already marked is skipped by `test`, and every pair with an + // unmatched member is reached from that member's own query. On the coliseum + // that is ~600 queries instead of ~10600. + for (let i = 0; i < refs.length; i++) { + if (isMarked(refs[i]!)) continue; + const c = cellRange(refs[i]!); + const span = (c.x1 - c.x0 + 1) * (c.y1 - c.y0 + 1) * (c.z1 - c.z0 + 1); + if (span > CELL_CAP) continue; + for (let ix = c.x0; ix <= c.x1; ix++) { + for (let iy = c.y0; iy <= c.y1; iy++) { + for (let iz = c.z0; iz <= c.z1; iz++) { + const bucket = grid.get(cellKey(ix, iy, iz)); + if (!bucket) continue; + for (const j of bucket) { + if (j === i || stamp[j] === i) continue; + stamp[j] = i; + test(i, j); + } + } + } + } + } + for (const i of oversized) { + for (let j = 0; j < refs.length; j++) { + if (j === i) continue; + test(i, j); + } + } + + for (let pi = 0; pi < planes.length; pi++) { + planes[pi]!.memberCreaseEdges = marked[pi]!; + planes[pi]!.creaseNeighbourPlanes = neighbourPlanes[pi]!; + } +} + +/** Mirrors the per-plane `L·n` gate the passes themselves apply (point lights + * use the to-source direction at the face origin, exactly as `dirAt(O)` does), + * so a plane is dropped from the signature only when every pass would reject + * it anyway. */ +function planeReceivesAnyLight( + plane: ReceiverFacePlane, + lights: ReceiverShadowSignatureLights, +): boolean { + const n = plane.n; + const dir = lights.lightDir; + if (dir) { + const len = Math.hypot(dir[0], dir[1], dir[2]) || 1; + if ((dir[0] * n[0] + dir[1] * n[1] + dir[2] * n[2]) / len > 1e-6) return true; + } + for (const p of lights.pointLightPositions ?? []) { + const O = plane.O; + const dx = p[0] - O[0], dy = p[1] - O[1], dz = p[2] - O[2]; + const len = Math.hypot(dx, dy, dz) || 1; + if ((dx * n[0] + dy * n[1] + dz * n[2]) / len > 1e-6) return true; + } + return false; +} + +/** + * Compact signature of every CAMERA-dependent decision in a receiver's shadow + * output. Two camera orientations with the same signature produce byte- + * identical shadow SVGs for that receiver; a different signature means the + * camera has crossed a facing boundary and the shadows must be re-emitted. + * + * The camera enters the pipeline at exactly one predicate — is this face plane + * turned toward the camera — read twice: once to decide whether the face paints + * at all, and once per crease to decide whether the neighbour on the far side + * is drawn there (`qualifiesCrease` condition 1). Both reduce to the same + * per-plane boolean, so the whole camera dependence is the bit vector of + * `normalFacesCamera` over the receiver's planes. Packing it base-32 keeps the + * key short enough to compare as a string on every camera frame; the count of + * CONTRIBUTING planes prefixes the packed bits because the final group is + * zero-padded to five, so without it an all-back-facing 2-plane receiver and an + * all-back-facing 5-plane one both read "0" and a plane-set change between them + * would be missed. + * + * Mesh rotation is deliberately NOT folded in — the plane normals are already + * in world frame, so `normalFacesCamera` must not re-apply it. That makes the + * signature meaningless against planes built for a different mesh rotation, so + * the CALLER must rebuild its planes (and re-emit) whenever the mesh transform + * changes, before comparing keys. Mirrors the per-mesh voxel DOM cull's + * `cameraCullVisibleSignature` — recompute on boundary crossings, not per frame. + */ +export function receiverShadowCameraSignature( + planes: readonly ReceiverFacePlane[], + cameraRot: CameraCullRotation, + lights?: ReceiverShadowSignatureLights, +): string { + const cameraOnlyRot: CameraCullRotation = { rotX: cameraRot.rotX, rotY: cameraRot.rotY }; + let out = ""; + let acc = 0; + let bits = 0; + let contributing = 0; + for (const plane of planes) { + // A plane no light can reach fails the `L·n` test in every pass, so it + // emits nothing and cannot qualify as a crease neighbour at ANY camera + // angle. Its facing bit could never change the output, and including it + // would invent boundary crossings that re-emit the scene for nothing. + if (lights && !planeReceivesAnyLight(plane, lights)) continue; + acc = (acc << 1) | (normalFacesCamera(plane.n, cameraOnlyRot) ? 1 : 0); + bits += 1; + contributing += 1; + if (bits === 5) { + out += acc.toString(32); + acc = 0; + bits = 0; + } + } + if (bits > 0) out += (acc << (5 - bits)).toString(32); + return `${contributing.toString(32)}:${out}`; +} diff --git a/packages/core/src/shadow/receiver/projection.ts b/packages/core/src/shadow/receiver/projection.ts new file mode 100644 index 000000000..28aaa11b0 --- /dev/null +++ b/packages/core/src/shadow/receiver/projection.ts @@ -0,0 +1,573 @@ +/** + * Single-plane shadow projection, clipping (3D half-space, reach rect, outline, + * seam/crease-bled member polygons), and tight SVG spec emission. + */ +import { safePlanSeamBleedAmount } from "../../atlas/edgeRepair"; +import { offsetConvexPolygonPointsByEdgeAmounts } from "../../atlas/solidTriangle"; +import { clipPolygonToConvex2D } from "../clipping"; +import { ensureCcw2D } from "../projection"; +import { expandConvexHullOutward, RECEIVER_OUTLINE_EXPAND } from "../receiverFaceGroups"; +import type { Vec2, Vec3 } from "../../types"; +import { + SHADOW_CLIP_SEAM_BLEED, + type PlaneShading, + type ReceiverCasterInput, + type ReceiverFacePlane, + type ReceiverShadowFaceSpec, + type ReceiverShadowPath, +} from "./types"; + +/** + * How much wider than `RECEIVER_OUTLINE_EXPAND` the shadow pre-clip has to be + * so it never caps the per-edge member bleed. The pre-clip runs BEFORE the + * per-member clips, so at the stored 0.5 px outline a crease sitting on the + * group hull (91% of the castle's) kept only 0.5 px of its granted 0.75 px. + * Applied ONLY where a crease edge was actually bled, because the stored outline also + * sizes the face plane's matrix and box — widening that unconditionally moves + * emitted geometry on multi-light and textured receivers, which get no crease + * bleed at all. The group hull is not the surface boundary (the member clips + * are, and they still bound every edge), so widening the clip copy cannot push + * shadow past a member outline. + */ +const CLIP_OUTLINE_EXTRA = Math.max(0, SHADOW_CLIP_SEAM_BLEED - RECEIVER_OUTLINE_EXPAND); + +// 3D half-space clip: keep the portion of `loop` where planeDist > eps. +// Sutherland-Hodgman style — used to clip silhouette loops that dip +// below the receiver plane before projection. Returns `[]` if the loop +// ends up fully below. +function clipLoopAbovePlane( + loop: ReadonlyArray, + O: Vec3, n: Vec3, eps: number, +): Vec3[] { + if (loop.length < 3) return []; + const out: Vec3[] = []; + const dist = (p: Vec3) => + (p[0] - O[0]) * n[0] + (p[1] - O[1]) * n[1] + (p[2] - O[2]) * n[2]; + const cross = (a: Vec3, b: Vec3, da: number, db: number): Vec3 => { + const s = (da - eps) / (da - db); + return [ + a[0] + s * (b[0] - a[0]), + a[1] + s * (b[1] - a[1]), + a[2] + s * (b[2] - a[2]), + ]; + }; + for (let i = 0; i < loop.length; i++) { + const curr = loop[i]!; + const prev = loop[(i + loop.length - 1) % loop.length]!; + const dCurr = dist(curr); + const dPrev = dist(prev); + const inCurr = dCurr > eps; + const inPrev = dPrev > eps; + if (inCurr) { + if (!inPrev) out.push(cross(prev, curr, dPrev, dCurr)); + out.push(curr); + } else if (inPrev) { + out.push(cross(prev, curr, dPrev, dCurr)); + } + } + return out; +} + +export interface PlaneProjectionContext { + casters: ReceiverCasterInput[]; + silhouetteByCaster: ReadonlyArray; + doubleSidedByCaster: readonly boolean[]; + isPoint: boolean; + Lx: number; + Ly: number; + Lz: number; + dirAt: (p: Vec3) => Vec3; + maxExtend: number; +} + +/** + * One receiver face's spec, or null when the face paints nothing. + * + * `allowedCreaseNeighbours` is the set of neighbouring PLANE INDICES this + * face may bleed its member clips into; null disables crease bleed entirely. + * The caller resolves it (see the two-phase driver) because it depends + * on whether those neighbours emit a layer in this same pass. + */ +export function computePlaneShadowSpec( + group: ReceiverFacePlane, + shading: PlaneShading, + allowedCreaseNeighbours: ReadonlySet | null, + ctx: PlaneProjectionContext, +): ReceiverShadowFaceSpec | null { + if (!shading.lit || !shading.camFacing) return null; + const { + casters, silhouetteByCaster, doubleSidedByCaster, + isPoint, Lx, Ly, Lz, dirAt, maxExtend, + } = ctx; + const { effOp, fillColor, fullLitFill, preblendEligible } = shading; + const { O, n, u, v, outlineUv, minU, minV, width, height } = group; + // Denominator of the directional projection (to-source · face normal), + // known positive here because `shading.lit` already passed. + const faceDir = dirAt(O); + const Ldotn = faceDir[0] * n[0] + faceDir[1] * n[1] + faceDir[2] * n[2]; + + const planeDist = (w: Vec3): number => + (w[0] - O[0]) * n[0] + (w[1] - O[1]) * n[1] + (w[2] - O[2]) * n[2]; + const planeCross = (a: Vec3, b: Vec3, da: number, db: number): Vec3 => { + const s = da / (da - db); + return [a[0] + s * (b[0] - a[0]), a[1] + s * (b[1] - a[1]), a[2] + s * (b[2] - a[2])]; + }; + const projectOntoPlane = (w: Vec3): [number, number] => { + const VmOx = w[0] - O[0]; + const VmOy = w[1] - O[1]; + const VmOz = w[2] - O[2]; + // Directional: constant to-source L, denom = Ldotn. Point: per-vertex + // to-source direction, denom = d·n. Clamp denom to a small positive so + // a grazing point-light vertex projects far (then gets reach/outline + // clipped) instead of dividing by ~0. + const d = isPoint ? dirAt(w) : ([Lx, Ly, Lz] as Vec3); + const denomRaw = isPoint ? d[0] * n[0] + d[1] * n[1] + d[2] * n[2] : Ldotn; + const denom = denomRaw > 1e-3 ? denomRaw : 1e-3; + const t = (VmOx * n[0] + VmOy * n[1] + VmOz * n[2]) / denom; + const Px = w[0] - t * d[0]; + const Py = w[1] - t * d[1]; + const Pz = w[2] - t * d[2]; + const dx = Px - O[0]; + const dy = Py - O[1]; + const dz = Pz - O[2]; + return [dx * u[0] + dy * u[1] + dz * u[2], dx * v[0] + dy * v[1] + dz * v[2]]; + }; + + type PerCasterClip = { + id: T; + verts: Array>; + subPolygonIndices: number[]; + }; + const clippedByCaster = new Map(); + let totalClipped = 0; + + // Per-plane shadow-reach rect: union of all casters' perpendicular + // footprints on this receiver face in (u,v), expanded by maxExtend. + // Mirrors groundShadow.ts's `clipBounds = fp ± maxExtend` semantic so + // `shadow.maxExtend` caps shadow reach uniformly across the ground + // path and the receiver-mesh path. + let footMinU = Infinity, footMinV = Infinity; + let footMaxU = -Infinity, footMaxV = -Infinity; + for (const casterEntry of casters) { + for (const item of casterEntry.items) { + for (const w of item.wv) { + const dx = w[0] - O[0]; + const dy = w[1] - O[1]; + const dz = w[2] - O[2]; + const cu = dx * u[0] + dy * u[1] + dz * u[2]; + const cv = dx * v[0] + dy * v[1] + dz * v[2]; + if (cu < footMinU) footMinU = cu; + if (cu > footMaxU) footMaxU = cu; + if (cv < footMinV) footMinV = cv; + if (cv > footMaxV) footMaxV = cv; + } + } + } + const reachRect: Array<[number, number]> = Number.isFinite(footMinU) ? [ + [footMinU - maxExtend, footMinV - maxExtend], + [footMaxU + maxExtend, footMinV - maxExtend], + [footMaxU + maxExtend, footMaxV + maxExtend], + [footMinU - maxExtend, footMaxV + maxExtend], + ] : []; + const SELF_SHADOW_EPS = 0.05; + const receiverPlaneOffset = n[0] * O[0] + n[1] * O[1] + n[2] * O[2]; + const COPLANAR_NORMAL_TOL = 0.0025; + const COPLANAR_OFFSET_TOL = 5.0; + // Seam cull fires only when the caster face is within ~20° of coplanar + // with the receiver face (|n·n| > cos 20°). Edge-neighbours on a smooth + // mesh sit a few degrees apart (culled as sub-pixel slivers); a faceted + // occluder across a hard edge is far more angled (kept as a real shadow). + const SEAM_COPLANAR_TOL = 0.94; + // Member clip polygons with seam bleed: each member's CCW outline is + // expanded outward by SHADOW_CLIP_SEAM_BLEED along the edges it SHARES + // with another member of this group (non-shared edges stay put), so the + // clipped shadow subpaths of abutting members overlap across the seam + // instead of leaving a hairline light strip under SVG antialiasing. + // Overlapping pieces land in the same nonzero compound path, so they + // cannot double-darken. `safePlanSeamBleedAmount` fits each edge's + // amount to the polygon (tiny/degenerate members fall back to 0), and + // `offsetConvexPolygonPointsByEdgeAmounts` returns the input unchanged + // for non-convex/degenerate outlines — the unexpanded member is the + // fallback in every failure mode. + // + // CREASE edges (neighbour in a different, non-coplanar group) are unioned + // into the same expansion when `applyCreaseBleed` holds. Those two groups + // are separate SVGs, so their expanded clips OVERLAP rather than landing in + // one nonzero path — safe only because the caller then paints the + // pre-blended color opaque (idempotent under overlap). + // + // Which crease edges may bleed is decided by the caller, per neighbouring + // PLANE, and handed down as `allowedCreaseNeighbours` — see + // `qualifiesCrease` for the three conditions a neighbour must meet + // (camera-facing, emits an abutting layer in this pass, paints the same + // resolved colour). + const applyCreaseBleed = allowedCreaseNeighbours !== null; + const creaseBleedsIntoNeighbour = (neighbours: number[] | undefined): boolean => { + if (!neighbours || !allowedCreaseNeighbours) return false; + for (const b of neighbours) if (allowedCreaseNeighbours.has(b)) return true; + return false; + }; + let anyCreaseBled = false; + const memberClipsUv: Array> = group.memberPolysUv.map( + (memberPoly, mi) => { + const ccw = ensureCcw2D(memberPoly); + const shared = group.memberSharedEdges?.[mi]; + const crease = applyCreaseBleed ? group.memberCreaseEdges?.[mi] : undefined; + const sharedCount = shared?.size ?? 0; + const creaseCount = crease?.size ?? 0; + if ((sharedCount === 0 && creaseCount === 0) || ccw.length < 3) return ccw; + const flat: number[] = []; + for (const p of ccw) flat.push(p[0], p[1]); + let bledCrease = false; + const amounts = ccw.map((_, e) => { + const isCrease = creaseBleedsIntoNeighbour(crease?.get(e)); + if (!shared?.has(e) && !isCrease) return 0; + const amount = safePlanSeamBleedAmount(flat, e, SHADOW_CLIP_SEAM_BLEED); + if (amount > 0 && isCrease) bledCrease = true; + return amount; + }); + let any = false; + for (const a of amounts) if (a > 0) { any = true; break; } + if (!any) return ccw; + const expanded = offsetConvexPolygonPointsByEdgeAmounts(flat, amounts); + if (expanded === flat || expanded.length !== flat.length) return ccw; + if (bledCrease) anyCreaseBled = true; + const out2: Array<[number, number]> = []; + for (let i = 0; i < expanded.length; i += 2) { + out2.push([expanded[i]!, expanded[i + 1]!]); + } + return out2; + }, + ); + // Widen the PRE-CLIP copy of the group hull so it cannot cap a bled member + // edge (see CLIP_OUTLINE_EXTRA). Only where a crease edge was actually + // bled: everywhere else the stored outline must be used verbatim or + // multi-light and textured receivers would shift. Within-group shared edges + // are interior to the hull and never need it. The stored `outlineUv` — and + // therefore the face plane's box and matrix — is never touched either way. + const clipOutlineUv = anyCreaseBled && CLIP_OUTLINE_EXTRA > 0 + ? expandConvexHullOutward(outlineUv, CLIP_OUTLINE_EXTRA) + : outlineUv; + const clipPad = clipOutlineUv === outlineUv ? 0 : CLIP_OUTLINE_EXTRA; + // Projection prefilter bounds. Padded with the clip widening so a caster + // whose footprint only reaches into the bled margin is not rejected here. + const fMinU = minU - clipPad, fMinV = minV - clipPad; + const fMaxU = group.minU + width + clipPad; + const fMaxV = group.minV + height + clipPad; + for (let casterIdx = 0; casterIdx < casters.length; casterIdx++) { + const casterEntry = casters[casterIdx]!; + const sharedEdgeMap = casterEntry.selfShadowEdgeMap; + + // Silhouette path: when the caster qualified for silhouette + // extraction, project each closed loop onto this receiver face + // instead of fan-triangulating every front-facing polygon. One + // sub-path per loop replaces O(items) sub-paths. + const silhouette = silhouetteByCaster[casterIdx]; + if (silhouette !== null) { + // Empty loop set means "light fully behind mesh" → no shadow on + // this receiver from this caster. + if (silhouette.length === 0) continue; + // Parametric (override) loops carry coverage holes (courtyards, the + // coliseum arena) as opposite-wound loops. Preserving that relative + // winding lets them subtract under the path's nonzero fill. The + // (u,v) basis may flip handedness, so pick one global orientation from + // the largest loop (→ outer CCW) and apply it uniformly. The exact + // silhouette path keeps per-loop `ensureCcw2D` (no holes there). + const isOverride = !!casterEntry.overrideSilhouette; + let overrideFlip = false; + if (isOverride) { + let bestAbs = 0; + for (const loop of silhouette) { + if (loop.length < 3) continue; + const ab = clipLoopAbovePlane(loop, O, n, SELF_SHADOW_EPS); + if (ab.length < 3) continue; + const pr = ab.map(projectOntoPlane); + let area = 0; + for (let i = 0; i < pr.length; i++) { + const p = pr[i]!, q = pr[(i + 1) % pr.length]!; + area += p[0] * q[1] - q[0] * p[1]; + } + if (Math.abs(area) > bestAbs) { bestAbs = Math.abs(area); overrideFlip = area < 0; } + } + } + for (const loop of silhouette) { + if (loop.length < 3) continue; + // 3D clip against the receiver plane half-space first — silhouette + // vertices that sit BELOW the receiver project to the wrong side + // of the (u,v) basis and produce inverted shadows. + const above3D = clipLoopAbovePlane(loop, O, n, SELF_SHADOW_EPS); + if (above3D.length < 3) continue; + const projected = above3D.map(projectOntoPlane); + const subjectCcw = isOverride + ? (overrideFlip ? [...projected].reverse() : projected) + : ensureCcw2D(projected); + const reachClipped = reachRect.length === 4 + ? clipPolygonToConvex2D(subjectCcw, reachRect) + : subjectCcw; + if (reachClipped.length < 3) continue; + const clip = clipPolygonToConvex2D(reachClipped, clipOutlineUv); + if (clip.length < 3) continue; + let bucket: { id: T; verts: Vec2[][]; subPolygonIndices: number[] } | undefined; + for (const memberClipPoly of memberClipsUv) { + const memberClip = clipPolygonToConvex2D(clip, memberClipPoly); + if (memberClip.length < 3) continue; + if (!bucket) { + bucket = clippedByCaster.get(casterEntry.id); + if (!bucket) { + bucket = { id: casterEntry.id, verts: [], subPolygonIndices: [] }; + clippedByCaster.set(casterEntry.id, bucket); + } + } + bucket.verts.push(memberClip); + // Silhouette path has no source-polygon attribution; use -1 + // so DevTools tooling can tell it apart from per-poly indices. + bucket.subPolygonIndices.push(-1); + totalClipped++; + } + } + continue; + } + + for (const item of casterEntry.items) { + // Seam-shadow cull: if this caster polygon shares an edge with ANY + // of the receiver face's member polygons, skip — projecting a + // shared-edge poly always produces a thin sliver along the seam, + // independent of plane angle. Without this cull, smooth-shaded + // GLB meshes (apple, sphere, teapot) get a dark spiderweb of + // shadow streaks at every vertex. + if (sharedEdgeMap) { + const adj = sharedEdgeMap.get(item.polygonIndex); + if (adj) { + let sharesEdge = false; + for (const memberIdx of group.memberPolyIndices) { + if (adj.has(memberIdx)) { sharesEdge = true; break; } + } + // Seam-shadow cull, but ONLY when the caster is near-COPLANAR with + // the receiver face. That's the smooth-shaded-mesh case the cull is + // for: edge-neighbour faces a few degrees apart project sub-pixel + // slivers (the apple/sphere/teapot "spiderweb"). A caster at a real + // angle to the receiver across a shared edge — a wing over a + // fuselage, a wall meeting a floor — casts a genuine self-shadow and + // must be kept (culling it left big holes on faceted meshes). + if (sharesEdge) { + const cn = item.planeN; + const coplanar = !cn || + Math.abs(cn[0] * n[0] + cn[1] * n[1] + cn[2] * n[2]) > SEAM_COPLANAR_TOL; + if (coplanar) continue; + } + } + } + // Light back-face cull: a caster polygon whose normal points AWAY + // from the light cannot cast shadow on anything beyond what the + // matching front-facing polygons (across the same closed mesh + // silhouette) already cover. For convex closed meshes the projected + // shadow is unchanged; for concave closed meshes the union under + // fill-rule=nonzero collapses to the same silhouette. For open + // one-sided meshes lit from behind the shadow disappears — this + // is the "single-sided material" semantic that most pipelines + // default to. Use a small epsilon so polygons exactly edge-on + // (grazing the light) still cast — they're the silhouette edge + // of a closed mesh. + if (item.planeN && !doubleSidedByCaster[casterIdx]) { + let lx = Lx, ly = Ly, lz = Lz; + if (isPoint) { + // To-source direction from the caster polygon's centroid. + let cx = 0, cy = 0, cz = 0; + for (const w of item.wv) { cx += w[0]; cy += w[1]; cz += w[2]; } + const inv = item.wv.length > 0 ? 1 / item.wv.length : 0; + const d = dirAt([cx * inv, cy * inv, cz * inv]); + lx = d[0]; ly = d[1]; lz = d[2]; + } + const cnDotL = item.planeN[0] * lx + item.planeN[1] * ly + item.planeN[2] * lz; + if (cnDotL > -1e-6) continue; + } + // Coplanar caster skip. + if (item.planeN) { + const cn = item.planeN; + const dot = cn[0] * n[0] + cn[1] * n[1] + cn[2] * n[2]; + if (Math.abs(dot) > 1 - COPLANAR_NORMAL_TOL) { + const sign = dot > 0 ? 1 : -1; + if (Math.abs(item.planeOffset - sign * receiverPlaneOffset) < COPLANAR_OFFSET_TOL) { + continue; + } + } + } + // 8-projection bbox prefilter, also confirms ≥ 1 corner ABOVE plane. + const corners = item.bboxCorners; + let anyAbove = false; + let pMinU = Infinity, pMinV = Infinity, pMaxU = -Infinity, pMaxV = -Infinity; + for (let ci = 0; ci < 8; ci++) { + const c = corners[ci]!; + if (planeDist(c) > SELF_SHADOW_EPS) anyAbove = true; + const pr = projectOntoPlane(c); + if (pr[0] < pMinU) pMinU = pr[0]; + if (pr[0] > pMaxU) pMaxU = pr[0]; + if (pr[1] < pMinV) pMinV = pr[1]; + if (pr[1] > pMaxV) pMaxV = pr[1]; + } + if (!anyAbove) continue; + if (pMaxU < fMinU || pMinU > fMaxU || pMaxV < fMinV || pMinV > fMaxV) continue; + const wv = item.wv; + // Fan-triangulate. + for (let triIdx = 1; triIdx < wv.length - 1; triIdx++) { + const tA = wv[0]!, tB = wv[triIdx]!, tC = wv[triIdx + 1]!; + const dA = planeDist(tA), dB = planeDist(tB), dC = planeDist(tC); + const above: Vec3[] = []; + const cycle: Array<[Vec3, number]> = [[tA, dA], [tB, dB], [tC, dC]]; + for (let k = 0; k < 3; k++) { + const [p, dp] = cycle[k]!; + const [q, dq] = cycle[(k + 1) % 3]!; + const pAbove = dp > SELF_SHADOW_EPS; + const qAbove = dq > SELF_SHADOW_EPS; + if (pAbove) above.push(p); + if (pAbove !== qAbove) above.push(planeCross(p, q, dp, dq)); + } + if (above.length < 3) continue; + const projected = above.map(projectOntoPlane); + const subjectCcw = ensureCcw2D(projected); + // Shadow-reach clip: cap how far the projected shadow can stretch + // beyond the caster mesh's perpendicular footprint on this face, + // before the (potentially expensive) outline + member clips. + const reachClipped = reachRect.length === 4 + ? clipPolygonToConvex2D(subjectCcw, reachRect) + : subjectCcw; + if (reachClipped.length < 3) continue; + const clip = clipPolygonToConvex2D(reachClipped, clipOutlineUv); + if (clip.length < 3) continue; + // Clip the projected shadow against each MEMBER polygon of the + // receiver face group, not just the group's outer outline. The + // outline can span concave regions / holes / disconnected + // coplanar islands where the mesh has no actual surface; + // clipping against the union of members keeps shadow pixels + // strictly over real mesh polygons. + // + // Self-shadow sliver cull is applied PER MEMBER-CLIP (not on the + // outline-clip): smooth-shaded GLBs produce many near-coplanar + // adjacent polys whose individual member-clips come out as long + // thin sub-pixel-adjacent streaks the user reads as visual + // noise. Earlier the cull ran on the outline-clip and would + // drop legitimate thin shadows landing on a thin-but-real + // member polygon (e.g. flight-system poly 38, a long diagonal + // slab receiving a thin shadow from the outer ring). Moving the + // cull onto each member-clip lets real thin shadows through + // while still discarding tiny-area / extreme-aspect noise. + let bucket: { id: T; verts: Vec2[][]; subPolygonIndices: number[] } | undefined; + for (const memberClipPoly of memberClipsUv) { + const memberClip = clipPolygonToConvex2D(clip, memberClipPoly); + if (memberClip.length < 3) continue; + if (sharedEdgeMap) { + let twiceArea = 0; + let minClipX = Infinity, maxClipX = -Infinity; + let minClipY = Infinity, maxClipY = -Infinity; + for (let pi = 0; pi < memberClip.length; pi++) { + const p1 = memberClip[pi]!; + const p2 = memberClip[(pi + 1) % memberClip.length]!; + twiceArea += p1[0] * p2[1] - p2[0] * p1[1]; + if (p1[0] < minClipX) minClipX = p1[0]; + if (p1[0] > maxClipX) maxClipX = p1[0]; + if (p1[1] < minClipY) minClipY = p1[1]; + if (p1[1] > maxClipY) maxClipY = p1[1]; + } + const clipArea = Math.abs(twiceArea) * 0.5; + // Pure tiny-area noise → drop. Aspect-only filter is gone: + // legitimate thin shadows (poly 38) trip it; member-clip is + // the geometric guard against bridging-region false positives. + if (clipArea < 5) continue; + } + if (!bucket) { + bucket = clippedByCaster.get(casterEntry.id); + if (!bucket) { + bucket = { id: casterEntry.id, verts: [], subPolygonIndices: [] }; + clippedByCaster.set(casterEntry.id, bucket); + } + } + bucket.verts.push(memberClip); + bucket.subPolygonIndices.push(item.polygonIndex); + totalClipped++; + } + } + } + } + + if (totalClipped === 0 || !(width > 0) || !(height > 0)) return null; + + // Tight shadow-content bbox in (u, v). The receiver face outline can be + // huge (e.g. a 17500×17500 CSS-px floor at world units × BASE_TILE), but + // the actual shadow content typically covers a fraction of that area. + // Sizing the SVG to the receiver outline made Chrome's compositor drop + // the entire layer past certain perspective angles (the projected + // trapezoid grew unboundedly when one corner approached the horizon). + // Clipping the SVG to the shadow's tight bbox keeps the layer small + // enough that compositor heuristics keep painting it at every camera + // orientation. The on-screen geometry is unchanged: matrix3d is rebased + // to the tight bbox and path coordinates are emitted relative to it. + let shMinU = Infinity, shMinV = Infinity, shMaxU = -Infinity, shMaxV = -Infinity; + for (const entry of clippedByCaster.values()) { + for (const verts of entry.verts) { + for (const pt of verts) { + if (pt[0] < shMinU) shMinU = pt[0]; + if (pt[0] > shMaxU) shMaxU = pt[0]; + if (pt[1] < shMinV) shMinV = pt[1]; + if (pt[1] > shMaxV) shMaxV = pt[1]; + } + } + } + // Round outward to whole pixels so the SVG covers the path with one px + // of slack on each side (matches the path's `.toFixed(1)` precision). + shMinU = Math.floor(shMinU - 1); + shMinV = Math.floor(shMinV - 1); + shMaxU = Math.ceil(shMaxU + 1); + shMaxV = Math.ceil(shMaxV + 1); + // Clamp the tight bbox to the face outline so we never extend the SVG + // past the receiver surface (would let a stray pixel render off-face). + if (shMinU < minU - clipPad) shMinU = minU - clipPad; + if (shMinV < minV - clipPad) shMinV = minV - clipPad; + if (shMaxU > minU + width + clipPad) shMaxU = minU + width + clipPad; + if (shMaxV > minV + height + clipPad) shMaxV = minV + height + clipPad; + const tightW = shMaxU - shMinU; + const tightH = shMaxV - shMinV; + if (!(tightW > 0) || !(tightH > 0)) return null; + + // matrix3d for the tight SVG: O + shMinU*u + shMinV*v + lift*n + const liftN = group.lift; + const tx = O[0] + shMinU * u[0] + shMinV * v[0] + liftN * n[0]; + const ty = O[1] + shMinU * u[1] + shMinV * v[1] + liftN * n[1]; + const tz = O[2] + shMinU * u[2] + shMinV * v[2] + liftN * n[2]; + const tm = [ + u[0], u[1], u[2], 0, + v[0], v[1], v[2], 0, + n[0], n[1], n[2], 0, + tx, ty, tz, 1, + ]; + const tightMatrixCss = `matrix3d(${tm.map((x) => x.toFixed(4)).join(",")})`; + + const paths: Array> = []; + const facePolysUv: Array> = []; + for (const entry of clippedByCaster.values()) { + let d = ""; + for (const verts of entry.verts) { + d += `M${(verts[0]![0] - shMinU).toFixed(1)},${(verts[0]![1] - shMinV).toFixed(1)}`; + for (let j = 1; j < verts.length; j++) { + d += `L${(verts[j]![0] - shMinU).toFixed(1)},${(verts[j]![1] - shMinV).toFixed(1)}`; + } + d += "Z"; + facePolysUv.push(verts.map((p) => [p[0], p[1]] as [number, number])); + } + paths.push({ casterId: entry.id, d, casterPolygonIndices: entry.subPolygonIndices }); + } + + return { + faceIndex: group.faceIndex, + memberPolyIndices: group.memberPolyIndices, + matrixCss: tightMatrixCss, + width: tightW, + height: tightH, + fill: fillColor, + opacity: effOp, + paths, + fullLitFill, + facePolysUv, + preblendEligible, + creaseBled: anyCreaseBled, + }; +} diff --git a/packages/core/src/shadow/receiver/shading.ts b/packages/core/src/shadow/receiver/shading.ts new file mode 100644 index 000000000..e8bd96927 --- /dev/null +++ b/packages/core/src/shadow/receiver/shading.ts @@ -0,0 +1,306 @@ +/** + * Per-plane shadow shading, pre-blend eligibility, and sRGB color blending + * helpers shared by the single-pass shadow projector and the multi-light + * merger. + */ +import { shadePolygon } from "../../atlas/paintDefaults"; +import { parseHexColor } from "../../color/color"; +import { normalFacesCamera, type CameraCullRotation } from "../../cull/cameraBackfaceCulling"; +import type { Polygon, Vec3 } from "../../types"; +import type { PlaneShading, ReceiverFacePlane } from "./types"; + +export const UNLIT_SHADING: PlaneShading = { + lit: false, camFacing: false, effOp: 0, fillColor: "", + fullLitFill: "", preblendEligible: false, preblendPaint: null, +}; + +/** Per-channel multiply factor `remaining / full` (both sRGB hex) as `rgb(...)`. + * Painting the base = `full` then this with `mix-blend-mode: multiply` + * reproduces `remaining`; overlapping factors multiply to the both-removed + * color. */ +export function shadowMultiplyFactor(remaining: string, full: string): string { + const a = parseHexColor(remaining)?.rgb ?? [0, 0, 0]; + const b = parseHexColor(full)?.rgb ?? [255, 255, 255]; + const f = (i: number): number => { + const c = b[i] ?? 0; + if (c <= 0) return 255; + return Math.max(0, Math.min(255, Math.round((a[i]! / c) * 255))); + }; + return `rgb(${f(0)},${f(1)},${f(2)})`; +} + +/** + * `blend(litFaceColor, shadowedColor, opacity)` in sRGB — the exact pixel an + * SVG path of `fill` at `opacity` produces over a receiver painted `base`. + * + * Emitting THIS opaque is pixel-identical to the alpha version, edges + * included: at antialiased coverage `c` the alpha version gives + * `base·(1 − o·c) + fill·o·c`, and painting the pre-blend at coverage `c` + * gives `base·(1 − c) + (base·(1 − o) + fill·o)·c` — the same expression. + * What changes is OVERLAP: two overlapping opaque paints of one color are that + * color, where two overlapping alpha paints darken twice. That idempotence is + * what lets a face's clip bleed across a crease into its neighbour's SVG. + * + * Returns `null` when either color is not a plain hex (a translucent receiver + * makes `shadePolygon` return `rgba(...)`, whose alpha the blend cannot + * represent) — the caller then keeps the alpha form. + */ +export function blendShadowOverLitBase(base: string, fill: string, opacity: number): string | null { + const b = parseHexColor(base); + const f = parseHexColor(fill); + if (!b || !f || b.alpha !== 1 || f.alpha !== 1) return null; + const o = Math.max(0, Math.min(1, opacity)); + const mix = (i: number): number => { + const bc = b.rgb[i] ?? 0; + const fc = f.rgb[i] ?? 0; + return Math.max(0, Math.min(255, Math.round(bc + (fc - bc) * o))); + }; + return `rgb(${mix(0)},${mix(1)},${mix(2)})`; +} + +/** A stored member polygon's own surface normal, in the same world-CSS frame + * and with the same fan accumulation the face plane was built with. The + * stored world list may have been reversed to make the (u, v) copy CCW, so + * the result is oriented onto the group normal's hemisphere — grouping + * already guarantees every member sits within `RECEIVER_NORMAL_TOL` of it, + * which makes that orientation unambiguous. Null for a degenerate member. */ +function memberWorldNormal(ws: readonly Vec3[], groupN: Vec3): Vec3 | null { + if (ws.length < 3) return null; + const O = ws[0]!; + let nx = 0, ny = 0, nz = 0; + for (let k = 1; k + 1 < ws.length; k++) { + const a = ws[k]!, b = ws[k + 1]!; + const e1x = a[0] - O[0], e1y = a[1] - O[1], e1z = a[2] - O[2]; + const e2x = b[0] - O[0], e2y = b[1] - O[1], e2z = b[2] - O[2]; + nx += e2y * e1z - e2z * e1y; + ny += e2z * e1x - e2x * e1z; + nz += e2x * e1y - e2y * e1x; + } + const len = Math.hypot(nx, ny, nz); + if (len < 1e-9) return null; + const s = (nx * groupN[0] + ny * groupN[1] + nz * groupN[2]) >= 0 ? 1 / len : -1 / len; + return [nx * s, ny * s, nz * s]; +} + +/** + * True when EVERY member of a face group paints exactly `fullLitFill`. + * + * `fullLitFill` is one color per GROUP: member[0]'s base color shaded with the + * group plane's normal (and, for point lights, the group hull centroid). The + * renderer bakes each leaf from its OWN normal and centroid, and a group is + * formed by plane + adjacency — not by material, and not by exact normal + * (`RECEIVER_NORMAL_TOL` admits ~2.5°). So this reproduces the renderer's + * per-leaf shading and compares, instead of assuming. + * + * The pre-blend replaces `leaf·(1−o) + fill·o` with `fullLit·(1−o) + fill·o` + * painted opaque; the residual is `(leaf − fullLit)·(1−o)`. Requiring exact + * equality makes it zero for every member, at every opacity — which is what + * "pixel-identical" has to mean before a face's clip may bleed into a + * neighbouring SVG. + */ +function groupMembersShareLitColor( + group: ReceiverFacePlane, + receiverPolygons: readonly Polygon[], + fullLitFill: string, + L: Vec3, + dirIntensity: number, + dirColor: string, + ambColor: string, + ambIntensity: number, + allPointLights: ReadonlyArray<{ position: Vec3; color?: string; intensity?: number }> | undefined, +): boolean { + if (fullLitFill === "") return false; + const members = group.memberPolysWorld; + if (!members || members.length === 0) return false; + const hasPoints = !!allPointLights && allPointLights.length > 0; + const litCache = new Map(); + for (let mi = 0; mi < members.length; mi++) { + const ws = members[mi]!; + const color = receiverPolygons[group.memberPolyIndices[mi] ?? -1]?.color ?? "#cccccc"; + const nm = memberWorldNormal(ws, group.n); + if (!nm) return false; + const dot = Math.max(0, L[0] * nm[0] + L[1] * nm[1] + L[2] * nm[2]); + const contribs: { color: string; scale: number }[] = []; + if (hasPoints) { + let cx = 0, cy = 0, cz = 0; + for (const w of ws) { cx += w[0]; cy += w[1]; cz += w[2]; } + const inv = 1 / ws.length; + cx *= inv; cy *= inv; cz *= inv; + for (const pl of allPointLights!) { + const dx = pl.position[0] - cx, dy = pl.position[1] - cy, dz = pl.position[2] - cz; + const len = Math.hypot(dx, dy, dz) || 1; + const d = Math.max(0, (dx / len) * nm[0] + (dy / len) * nm[1] + (dz / len) * nm[2]); + if (d <= 0) continue; + contribs.push({ color: pl.color ?? "#ffffff", scale: (pl.intensity ?? 1) * d }); + } + } + const key = `${color}|${dot.toFixed(6)}|${contribs.map((c) => `${c.color}:${c.scale.toFixed(6)}`).join(",")}`; + let lit = litCache.get(key); + if (lit === undefined) { + lit = shadePolygon(color, dirIntensity * dot, dirColor, ambColor, ambIntensity, contribs); + litCache.set(key, lit); + } + if (lit !== fullLitFill) return false; + } + return true; +} + +export interface PlaneShadingContext { + dirAt: (p: Vec3) => Vec3; + cameraOnlyRot: CameraCullRotation; + Lx: number; + Ly: number; + Lz: number; + isDirPass: boolean; + isPoint: boolean; + allPointLights: ReadonlyArray<{ position: Vec3; color?: string; intensity?: number }> | undefined; + thisPointIndex: number | undefined; + dirIntensity: number; + dirColor: string; + ambColor: string; + ambIntensity: number; + opacity: number; + receiverHasTexture: boolean; + receiverPolygons: readonly Polygon[]; + userShadowColor: string; +} + +/** + * Resolve per-plane shading facts up front (facing, opacity, shadow fill, + * full-lit fill, and pre-blend eligibility) so crease-bleed decisions can + * inspect neighbouring planes before clips are built. + */ +export function computePlaneShading( + group: ReceiverFacePlane, + ctx: PlaneShadingContext, +): PlaneShading { + const { + dirAt, cameraOnlyRot, Lx, Ly, Lz, isDirPass, isPoint, + allPointLights, thisPointIndex, dirIntensity, dirColor, + ambColor, ambIntensity, opacity, receiverHasTexture, + receiverPolygons, userShadowColor, + } = ctx; + const { O, n, u, v, outlineUv } = group; + // Back-facing receiver face → can't receive light → no shadow. For point + // lights the representative direction is the to-source vector at the + // face origin. + const faceDir = dirAt(O); + const Ldotn = faceDir[0] * n[0] + faceDir[1] * n[1] + faceDir[2] * n[2]; + if (Ldotn <= 1e-6) return UNLIT_SHADING; + if (!normalFacesCamera(n, cameraOnlyRot)) return UNLIT_SHADING; + + // Per-face light scalars for the SHADED shadow color. `dirDot` is the + // directional Lambert term (always vs the directional vector, not the + // pass's faceDir). Point dots use the to-source direction from the face + // CENTROID — matching the baked surface shading (per-polygon centroid), so + // the shadow's full-lit base color equals the painted receiver and the SVG + // leaves no visible base-color box. (Projection still uses per-vertex + // radial directions; only the flat per-face color uses the centroid.) + const dirDot = Math.max(0, Lx * n[0] + Ly * n[1] + Lz * n[2]); + let cMeanU = 0, cMeanV = 0; + for (const pt of outlineUv) { cMeanU += pt[0]; cMeanV += pt[1]; } + const cInv = outlineUv.length > 0 ? 1 / outlineUv.length : 0; + cMeanU *= cInv; cMeanV *= cInv; + const cen: Vec3 = [ + O[0] + cMeanU * u[0] + cMeanV * v[0], + O[1] + cMeanU * u[1] + cMeanV * v[1], + O[2] + cMeanU * u[2] + cMeanV * v[2], + ]; + const pointDots: number[] = []; + let pointTotalScale = 0; + if (allPointLights) { + for (let k = 0; k < allPointLights.length; k++) { + const pl = allPointLights[k]!; + const dx = pl.position[0] - cen[0]; + const dy = pl.position[1] - cen[1]; + const dz = pl.position[2] - cen[2]; + const len = Math.hypot(dx, dy, dz) || 1; + const dot = Math.max(0, (dx / len) * n[0] + (dy / len) * n[1] + (dz / len) * n[2]); + pointDots[k] = dot; + pointTotalScale += (pl.intensity ?? 1) * dot; + } + } + + // Intensity removed by THIS pass (the blocked light) and the scene total. + const thisScale = isDirPass + ? dirIntensity * dirDot + : (allPointLights?.[thisPointIndex ?? -1]?.intensity ?? 1) * (pointDots[thisPointIndex ?? -1] ?? 0); + const totalScale = dirIntensity * dirDot + pointTotalScale + Math.max(0, ambIntensity); + + // Per-group opacity for textured receivers. The shadow leaves the receiver + // lit by everything EXCEPT this pass's light: shadow_linear = + // lit_linear × remaining/total. A black overlay at sRGB opacity o gives + // lit_srgb × (1 − o), so o = 1 − (remaining/total)^(1/2.4). For a lone + // directional light remaining = ambient, matching the previous formula. + let effOp = opacity; + if (receiverHasTexture) { + if (totalScale > 0) { + const remainingRatio = Math.max(0, (totalScale - thisScale) / totalScale); + effOp = opacity * (1 - Math.pow(remainingRatio, 1 / 2.4)); + } else { + effOp = 0; + } + } + + // Per-face shadow tint. Each receiver face uses ITS OWN polygon color + // (one material per coplanar group). The fill is the receiver lit by + // every light EXCEPT this pass's blocked light — so a region shadowed + // from one colored light still shows the others' color. A lone + // directional light → remaining = ambient only (unchanged from before). + const groupPolyIdx = group.memberPolyIndices[0] ?? 0; + const groupColor = receiverPolygons[groupPolyIdx]?.color ?? "#cccccc"; + const remDirScale = isDirPass ? 0 : dirIntensity * dirDot; + const remPointContribs: { color: string; scale: number }[] = []; + if (allPointLights) { + for (let k = 0; k < allPointLights.length; k++) { + if (isPoint && k === thisPointIndex) continue; + const dot = pointDots[k] ?? 0; + if (dot <= 0) continue; + const pl = allPointLights[k]!; + remPointContribs.push({ color: pl.color ?? "#ffffff", scale: (pl.intensity ?? 1) * dot }); + } + } + const fillColor = receiverHasTexture + ? userShadowColor + : shadePolygon(groupColor, remDirScale, dirColor, ambColor, ambIntensity, remPointContribs); + + // Full-lit face color C (every light) for the multi-light merge — callers + // multiply C by each pass's `fill/C` so overlapping shadows composite to + // the both-blocked color. Empty for textured (per-pixel base). + const fullPointContribs: { color: string; scale: number }[] = []; + if (allPointLights) { + for (let k = 0; k < allPointLights.length; k++) { + const dot = pointDots[k] ?? 0; + if (dot <= 0) continue; + const pl = allPointLights[k]!; + fullPointContribs.push({ color: pl.color ?? "#ffffff", scale: (pl.intensity ?? 1) * dot }); + } + } + const fullLitFill = receiverHasTexture + ? "" + : shadePolygon(groupColor, dirIntensity * dirDot, dirColor, ambColor, ambIntensity, fullPointContribs); + + // A face group is formed by plane + adjacency, never by material and never + // by exact normal: `fullLitFill` uses member[0]'s color and the GROUP + // plane's Lambert term, while each leaf is baked from its OWN normal (and, + // under point lights, its own centroid). The opaque pre-blend is a pixel + // identity only where those agree for every member, so that is checked + // directly rather than assumed — and the pre-blend must additionally be + // representable at all. + const preblend = receiverHasTexture ? null : blendShadowOverLitBase(fullLitFill, fillColor, effOp); + const preblendEligible = !receiverHasTexture + && groupMembersShareLitColor( + group, receiverPolygons, fullLitFill, + [Lx, Ly, Lz], dirIntensity, dirColor, ambColor, ambIntensity, allPointLights, + ) + && preblend !== null; + return { + lit: true, + camFacing: true, + effOp, + fillColor, + fullLitFill, + preblendEligible, + preblendPaint: preblendEligible ? preblend : null, + }; +} diff --git a/packages/core/src/shadow/receiver/types.ts b/packages/core/src/shadow/receiver/types.ts new file mode 100644 index 000000000..0e02f5e9d --- /dev/null +++ b/packages/core/src/shadow/receiver/types.ts @@ -0,0 +1,359 @@ +/** + * Shared types and constants for the receiver-shadow pipeline. + */ +import type { CameraCullRotation } from "../../cull/cameraBackfaceCulling"; +import type { EdgeOwners } from "../silhouette"; +import type { + PolyAmbientLight, + PolyDirectionalLight, + Polygon, + Vec3, +} from "../../types"; + +/** + * Outward overscan (CSS px on the receiver plane — UV units) applied to a + * member polygon's clip outline along its SHARED and CREASE edges only, before + * shadow geometry is clipped against it. Exactly-abutting clipped subpaths + * don't sum to full coverage under SVG antialiasing, so member seams and + * creases showed a hairline light strip — the same artifact class the atlas + * seam bleed solves for solid leaves. Edges with no neighbouring surface get + * zero expansion so the shadow never leaks past the face-group boundary. + * + * Fixed constant: the scene `seamBleed` option does not flow into the + * shadow pipeline (`shadow` options carry only color/opacity/maxExtend), + * and threading it through all three renderers is out of scope here. + */ +export const SHADOW_CLIP_SEAM_BLEED = 0.75; + +/** + * Default clearance between a receiver face and the shadow painted on it, in + * world units. + * + * Single source of truth on purpose: this default was previously written out at + * seven call sites across the three renderers, and two of them drifted to + * `0.001` — small enough that the receiver painted over its own shadow, so + * `castShadow` + `receiveShadow` emitted paths that darkened nothing. + * + * Note this is a WORLD-unit value while the depth conflict it must win is + * resolved in device pixels, so it still fails below roughly `zoom: 1`. That + * limitation is documented for callers; fixing it needs projection-aware + * clearance. + */ +export const POLY_DEFAULT_SHADOW_LIFT = 0.05; + +/** + * Per-receiver cached face geometry. One record per coplanar face group: + * plane (O, n, u, v), outline polygon (Sutherland-Hodgman clip), bbox in + * (u, v) for SVG sizing, and the pre-stringified matrix3d transform that + * places an SVG on that face plane. + * + * All of this is invariant under light/caster changes. Per light tick the + * caller just re-runs the per-tri SH and builds the path `d` — never + * recompute groups or basis. Cache invalidated when the receiver's polygon + * count or position changes. + */ +export interface ReceiverFacePlane { + O: Vec3; + n: Vec3; + u: Vec3; + v: Vec3; + outlineUv: Array<[number, number]>; + memberPolysUv: Array>; + /** Parallel to `memberPolysUv`: each member's unsnapped world-space vertices + * (see `ReceiverPlaneGroup.memberPolysWorld`). Crease matching reads these + * rather than lifting (u, v) back to 3D, which would snap non-planar + * members onto their group plane and hide real creases. + * + * Optional so a hand-built plane still type-checks: without it a face gets + * no crease detection and no pre-blend (its members' shading cannot be + * verified), which is the safe degradation, not a silent approximation. */ + memberPolysWorld?: Vec3[][]; + memberPolyIndices: number[]; + /** Parallel to `memberPolysUv`: CCW edge indices shared with another member + * of the same group (see `ReceiverPlaneGroup.memberSharedEdges`). Drives + * the member-clip seam bleed. Optional — absent means no seam bleed. */ + memberSharedEdges?: Array | undefined>; + /** Parallel to `memberPolysUv`: CCW edge index → the INDICES (into the same + * `ReceiverFacePlane[]`) of the neighbouring face planes across a CREASE — + * a neighbouring surface belonging to a DIFFERENT, non-coplanar face group. + * Those two groups emit separate SVGs, so their antialiased clip edges abut + * at the crease without summing to full coverage. Unioned with + * `memberSharedEdges` at clip-expansion time so one pass bleeds both + * classes. Filled by `prepareReceiverFacePlanes` after the occlusion cull; + * edges already in `memberSharedEdges` are skipped (already bled). + * + * Plane INDICES are kept — not just the edge index, and not just the + * neighbour's normal — because bleeding across a crease is only safe when + * the neighbour on the far side actually paints an abutting, compatible + * shadow layer in this same pass. Answering that needs the neighbour's + * identity (its facing, its emission, its resolved fill), which a bare + * normal cannot supply. Indices are valid only for the array the planes + * were prepared as: callers pass `prepareReceiverFacePlanes`' result + * through unfiltered and unreordered. + * + * Optional, and filled in place by `prepareReceiverFacePlanes`; absent + * means no crease bleed. */ + memberCreaseEdges?: Array | undefined>; + /** Every plane index this plane marks a crease edge toward, unioned across + * members. Lets the bleed test ask "does the neighbour bleed BACK at me?" + * in O(1) — a one-sided bleed would paint an opaque pre-blend over a + * neighbour still painting at alpha, which double-darkens the overlap + * depending on SVG paint order. Filled alongside `memberCreaseEdges`. */ + creaseNeighbourPlanes?: ReadonlySet; + minU: number; + minV: number; + width: number; + height: number; + matrixCss: string; + faceIndex: number; + /** World-frame lift (already × BASE_TILE) along +n. Re-applied per-frame + * when building a tight shadow SVG matrix so the SVG hovers over the face. */ + lift: number; +} + +/** + * Per-caster cached per-polygon data: world-space vertices + 3D AABB + * corners + caster-polygon plane normal/offset. Invariant under light + * direction; depends only on the caster mesh's geometry and position. + */ +export interface CasterPolyItem { + wv: Vec3[]; + bboxCorners: Vec3[]; + planeN: Vec3 | null; + planeOffset: number; + polygonIndex: number; +} + +/** A caster mesh's prepared items paired with a stable identifier the caller + * can use for per-path attribution. */ +export interface ReceiverCasterInput { + /** Caller-defined identifier (e.g. mesh ref, mesh shadow id). Echoed back + * on each emitted path so the renderer can map a subpath to its source + * caster mesh. */ + id: T; + items: CasterPolyItem[]; + /** Self-shadow edge adjacency. When this caster is the same mesh as the + * receiver, the renderer pre-computes a map polygonIndex → + * set-of-other-polygonIndex that share at least one edge (within + * EDGE_MATCH_EPS). The shadow algorithm skips projecting `polygonIndex` + * onto any receiver face whose member set intersects the shared-edge + * set — those projections are sliver shadows along seams (smooth-shaded + * GLB meshes, subdivided spheres) that the user never wants to see. */ + selfShadowEdgeMap?: ReadonlyMap>; + /** Per-mesh edge ownership map for silhouette extraction. Cached by the + * caller (WeakMap) and shared across receivers within a frame. + * When present AND the caster is NOT the receiver AND items.length ≥ + * SILHOUETTE_MIN_POLYS, the shadow algorithm projects per-mesh + * silhouette loops instead of every front-facing triangle — collapses + * the N-triangle path to 1 outline per caster per receiver. See H9 in + * `bench/notes/SHADOW_PERF_LOG.md`. */ + edgeOwners?: ReadonlyMap; + /** Total polygon count on the source caster mesh (NOT the filtered + * `items` count). Needed by silhouette extraction so the `facing` + * array is sized correctly even when atlas-plan / dedup filters drop + * some polygons from `items`. */ + casterPolygonCount?: number; + /** Parametric-shadow override: a precomputed world-frame silhouette loop set + * (see `computeParametricShadowSilhouette`). When present it is projected + * directly — skipping per-poly and silhouette extraction — so a cheap, + * low-resolution outline casts onto every receiver via the normal pipeline. */ + overrideSilhouette?: Vec3[][]; + /** Per-point-light parametric override (indexed by the point light's index in + * `allPointLights`). A point pass uses this RADIAL silhouette instead of the + * directional `overrideSilhouette`; an undefined entry → exact point path. */ + overridePointSilhouettes?: Array; +} + +/** One contributing caster's shadow subpath on a single receiver face. */ +export interface ReceiverShadowPath { + /** Caster id echoed from the input. */ + casterId: T; + /** Path data string: `M…L…Z` subpaths in face-local (u, v) coordinates + * pre-translated so the SVG's `viewBox` is `0 0 width height`. */ + d: string; + /** Source polygon indices on the caster mesh in subpath order (one per + * M…L…Z block). Used for DevTools attribution. */ + casterPolygonIndices: number[]; +} + +/** Per-receiver-face shadow spec. Renderer mounts one SVG per spec. */ +export interface ReceiverShadowFaceSpec { + /** Index into the prepared `ReceiverFacePlane[]` list. Stable across + * frames; used as the `data-poly-shadow-receiver-face` attr. */ + faceIndex: number; + /** Receiver polygon indices that make up this coplanar group. */ + memberPolyIndices: number[]; + /** matrix3d(...) transform that places the SVG on the face plane. */ + matrixCss: string; + width: number; + height: number; + /** Fill (and stroke) color resolved per-face: textured receivers get the + * user's `shadow.color`; solid receivers get their own ambient-only + * shadePolygon for byte-exact Three.js parity. */ + fill: string; + /** Per-face opacity (already accounts for textured-darken Lambert ratio + * if applicable). */ + opacity: number; + paths: Array>; + /** Full-lit face color C (all lights), for the multi-light merge: callers + * multiply C by each pass's `fill/C` factor so overlaps composite to the + * both-blocked color. Empty string for textured receivers (per-pixel base, + * multiply can't be uniform — those fall back to cumulative-alpha). */ + fullLitFill: string; + /** Every clipped caster polygon for this pass in absolute face-(u,v) space + * (NOT offset by the tight bbox). The multi-light merge re-bases these to a + * shared per-face bbox so all lights' shadows live in one SVG. */ + facePolysUv: Array>; + /** True when EVERY member polygon of this group paints exactly + * `fullLitFill`, AND the pre-blend of `fill` at `opacity` over it is + * representable — so a single-pass shadow may be emitted as that + * PRE-BLENDED color at alpha 1 instead of the shadowed color at `opacity` + * (identical pixel, but idempotent under overlap). + * + * All three conditions are required: + * - solid receiver (a textured one has no uniform lit base); + * - every member paints `fullLitFill` — a group is formed by plane + + * adjacency, not material, and admits member normals up to + * `RECEIVER_NORMAL_TOL` apart, so neither one base color nor one Lambert + * term can be assumed. Checked per member against its OWN normal and + * centroid, i.e. exactly what the renderer bakes into the leaf; + * - `blendShadowOverLitBase` can actually represent the result. A + * translucent receiver shades to `rgba(...)`, which it cannot — and + * emitting the alpha form under expanded clips would double-darken. */ + preblendEligible: boolean; + /** True when at least one member clip of this face was expanded across a + * CREASE edge into a neighbouring face group's SVG. Only these faces need + * the opaque pre-blend (that overlap is what alpha paint would + * double-darken); every other face keeps the alpha form, whose off-surface + * `shadow.lift` parallax at grazing angles is far less visible. */ + creaseBled: boolean; +} + +/** The pass lights a camera signature is computed against. Omitting it makes + * the signature conservative (every plane contributes a bit). */ +export interface ReceiverShadowSignatureLights { + /** Directional to-source vector in CSS frame; omitted/null when the + * directional pass does not run. */ + lightDir?: Vec3 | null; + /** CSS-frame positions of the shadow-casting point lights. */ + pointLightPositions?: ReadonlyArray; +} + +/** Input for `computeReceiverShadowFaces`. */ +export interface ComputeReceiverShadowFacesInput { + /** Precomputed face planes from `prepareReceiverFacePlanes`. */ + receiverPlanes: ReceiverFacePlane[]; + /** Receiver's polygon list, used to look up per-face fill color. */ + receiverPolygons: readonly Polygon[]; + /** Whether the receiver mesh has any textured polygons. Drives the + * textured-darken opacity calc vs solid-replace fill color. */ + receiverHasTexture: boolean; + /** Per-caster items + caller id, in caller-defined order. */ + casters: ReceiverCasterInput[]; + /** Light direction in CSS frame, pointing TOWARD the light (to-source). + * For a point light this is a representative direction (used only for the + * textured-receiver opacity ratio); per-vertex directions come from + * `lightPos`. */ + lightDir: Vec3; + /** When set, the light is a point light at this CSS-frame position. The + * shadow projection becomes radial (per-vertex direction from the light) + * and the silhouette fast path is disabled (facing is per-polygon). */ + lightPos?: Vec3; + /** Every point light in the scene (CSS-frame absolute positions), used to + * compute the SHADED shadow color — a shadow shows the receiver lit by all + * lights EXCEPT the blocked one, so a spot shadowed from one colored light + * still shows the others' color (Three.js parity). Includes non-shadow- + * casting lights, since they still illuminate the shadowed region. */ + allPointLights?: ReadonlyArray<{ position: Vec3; color?: string; intensity?: number }>; + /** For a point-light pass, the index into `allPointLights` of the light + * being shadowed (excluded from the remaining-light fill). Undefined for + * the directional pass (which instead excludes the directional light). */ + thisPointIndex?: number; + /** Camera cull rotation (rotX/rotY + receiver mesh rotation) so back- + * facing receiver faces can be skipped. */ + cameraRot: CameraCullRotation; + /** Ambient light (used for solid-receiver shadow tint via shadePolygon). */ + ambientLight?: PolyAmbientLight; + /** Directional light (used for textured-darken opacity calc). */ + directionalLight?: PolyDirectionalLight; + /** Scene shadow options. */ + shadow?: { color?: string; opacity?: number; maxExtend?: number }; + /** Also bleed member clip outlines along CREASE edges (neighbour in a + * different, non-coplanar face group). Cross-group bleed makes shadow + * regions OVERLAP between two SVGs, which only composites correctly when + * the caller paints the pre-blended color opaque (see + * `computeMergedReceiverShadows`) — so it is opt-in and additionally gated + * per face on `preblendEligible`. */ + creaseBleed?: boolean; +} + +/** One path inside a merged face SVG. */ +export interface MergedShadowLayer { + /** Path data (`M…L…Z`, already offset to the SVG's tight bbox). */ + d: string; + /** Fill color (remaining-light color for a single layer, multiply factor for + * a merged solid layer, dark shadow color for textured). */ + fill: string; + /** Apply `mix-blend-mode: multiply` (merged solid layers only). */ + multiply: boolean; + /** Per-path opacity (1 for merged solid layers, which carry strength on the + * SVG; the pass's own opacity otherwise). */ + opacity: number; +} + +/** One receiver FACE's merged shadow, ready to mount as a single SVG. */ +export interface MergedShadowFace { + faceIndex: number; + memberPolyIndices: number[]; + matrixCss: string; + width: number; + height: number; + /** SVG-level opacity (shadow strength for merged solid faces, else 1). */ + svgOpacity: number; + /** Full-lit base path (merged solid faces only); null otherwise. */ + baseFill: string | null; + baseD: string | null; + layers: MergedShadowLayer[]; +} + +/** Inputs for `computeMergedReceiverShadows` — the full light set for one + * receiver, plus its prepared face planes and casters. */ +export interface MergedReceiverShadowInput { + receiverPlanes: ReceiverFacePlane[]; + receiverPolygons: readonly Polygon[]; + receiverHasTexture: boolean; + casters: ReceiverCasterInput[]; + /** Directional light vector in CSS frame (to-source). */ + lightDir: Vec3; + /** Run the directional pass (caller gates on a real, nonzero-intensity + * directional light). */ + runDirectional: boolean; + /** One pass per shadow-casting point light: CSS position + index into + * `allPointLights`. Empty in dynamic mode (point lights are baked-only). */ + pointPasses: ReadonlyArray<{ lightPos: Vec3; index: number }>; + /** All point lights (CSS positions) for the shaded shadow color; empty in + * dynamic mode. */ + allPointLights?: ReadonlyArray<{ position: Vec3; color?: string; intensity?: number }>; + cameraRot: CameraCullRotation; + ambientLight?: PolyAmbientLight; + directionalLight?: PolyDirectionalLight; + shadow?: { color?: string; opacity?: number; maxExtend?: number }; +} + +/** Internal per-plane shading facts resolved before projection. */ +export interface PlaneShading { + /** Face is turned toward this pass's light (can receive it at all). */ + lit: boolean; + /** Face is turned toward the camera. SVGs don't honor CSS + * backface-visibility reliably, so a back-of-camera face must not paint. */ + camFacing: boolean; + effOp: number; + fillColor: string; + fullLitFill: string; + preblendEligible: boolean; + /** The opaque colour this face paints when it bleeds a crease, or null when + * the pre-blend is ineligible or unrepresentable. Two faces may only bleed + * into each other when these are equal — overlap of two DIFFERENT opaque + * colours is not idempotent, it just paints one over the other. */ + preblendPaint: string | null; +} diff --git a/packages/polycss/package.json b/packages/polycss/package.json index 84b637216..d2fe3ba36 100644 --- a/packages/polycss/package.json +++ b/packages/polycss/package.json @@ -31,6 +31,10 @@ "types": "./dist/runtime.d.ts", "import": "./dist/runtime.js" }, + "./internal": { + "types": "./dist/internal.d.ts", + "import": "./dist/internal.js" + }, "./elements": { "types": "./dist/elements.d.ts", "import": "./dist/elements.js" @@ -43,6 +47,7 @@ "typesVersions": { "*": { "runtime": ["dist/runtime.d.ts"], + "internal": ["dist/internal.d.ts"], "three": ["dist/three.d.ts"], "elements": ["dist/elements.d.ts"] } diff --git a/packages/polycss/src/api/controls/common.ts b/packages/polycss/src/api/controls/common.ts index 9a08b0191..371bd9e23 100644 --- a/packages/polycss/src/api/controls/common.ts +++ b/packages/polycss/src/api/controls/common.ts @@ -260,41 +260,50 @@ export function makeAnimLoop( } { let animFrameId: number | null = null; let animLastTime = 0; - - const animTick = (now: number): void => { - if (animFrameId === null || isStopped()) return; - const opts = getOpts(); - if (!opts.animate) { - animFrameId = null; - return; - } - if (!isAnimPaused()) { - const dt = Math.min(ANIM_DT_CLAMP_MS, animLastTime ? now - animLastTime : ANIM_FRAME_MS); - animLastTime = now; - const delta = opts.animate.speed * (dt / ANIM_FRAME_MS); - const cameraState = scene.camera.state; - if (opts.animate.axis === "x") { - const next = (((cameraState.rotX ?? 65) + delta) % 360 + 360) % 360; - scene.camera.update({ rotX: next }); - } else { - const next = (((cameraState.rotY ?? 45) + delta) % 360 + 360) % 360; - scene.camera.update({ rotY: next }); - } - scene.applyCamera(); - emitChange(snapshot); - } else { - animLastTime = now; - } - animFrameId = win.requestAnimationFrame(animTick); - }; + let loopGen = 0; const start = (): void => { if (animFrameId !== null || !getOpts().animate || isStopped()) return; animLastTime = 0; + const gen = ++loopGen; + const animTick = (now: number): void => { + if (gen !== loopGen || animFrameId === null || isStopped()) { + if (gen === loopGen) animFrameId = null; + return; + } + const opts = getOpts(); + if (!opts.animate) { + animFrameId = null; + return; + } + if (!isAnimPaused()) { + const dt = Math.min(ANIM_DT_CLAMP_MS, animLastTime ? now - animLastTime : ANIM_FRAME_MS); + animLastTime = now; + const delta = opts.animate.speed * (dt / ANIM_FRAME_MS); + const cameraState = scene.camera.state; + if (opts.animate.axis === "x") { + const next = (((cameraState.rotX ?? 65) + delta) % 360 + 360) % 360; + scene.camera.update({ rotX: next }); + } else { + const next = (((cameraState.rotY ?? 45) + delta) % 360 + 360) % 360; + scene.camera.update({ rotY: next }); + } + scene.applyCamera(); + emitChange(snapshot); + } else { + animLastTime = now; + } + if (gen !== loopGen || animFrameId === null || isStopped() || !getOpts().animate) { + if (gen === loopGen) animFrameId = null; + return; + } + animFrameId = win.requestAnimationFrame(animTick); + }; animFrameId = win.requestAnimationFrame(animTick); }; const stop = (): void => { + loopGen++; if (animFrameId === null) return; win.cancelAnimationFrame(animFrameId); animFrameId = null; diff --git a/packages/polycss/src/api/controls/gizmoEngine.ts b/packages/polycss/src/api/controls/gizmoEngine.ts index b307a62b3..9cd4a3f65 100644 --- a/packages/polycss/src/api/controls/gizmoEngine.ts +++ b/packages/polycss/src/api/controls/gizmoEngine.ts @@ -133,7 +133,7 @@ export interface AxisDragParams { * Project pointer screen-px deltas onto the screen projection of an axis * vector via a temporary probe element. */ -export function startAxisDrag(opts: AxisDragParams): boolean { +export function startAxisDrag(opts: AxisDragParams): (() => void) | null { const { cssAxis, sign, @@ -152,29 +152,42 @@ export function startAxisDrag(opts: AxisDragParams): boolean { axisVec[cssAxis] = sign; const screen = probeScreenAxis(wrapper, axisVec, shaftLengthCss); const screenAxisLenSq = screen.x * screen.x + screen.y * screen.y; - if (screenAxisLenSq < SCREEN_AXIS_DEAD_ZONE_SQ) return false; + if (screenAxisLenSq < SCREEN_AXIS_DEAD_ZONE_SQ) return null; onMouseDown?.(); onDraggingChanged?.(true); + let active = true; + const removeListeners = (): void => { + window.removeEventListener("pointermove", handleMove); + window.removeEventListener("pointerup", handleUp); + window.removeEventListener("pointercancel", handleUp); + }; const handleMove = (ev: PointerEvent): void => { + if (!active) return; const dx = ev.clientX - startClientX; const dy = ev.clientY - startClientY; const t = snap(solveAxisDragDelta(dx, dy, screen.x, screen.y), translationSnap); onAxisDelta(t, axisVec); }; const handleUp = (): void => { - window.removeEventListener("pointermove", handleMove); - window.removeEventListener("pointerup", handleUp); - window.removeEventListener("pointercancel", handleUp); + if (!active) return; + active = false; + removeListeners(); swallowNextClick(); onMouseUp?.(); onDraggingChanged?.(false); }; + const cancel = (): void => { + if (!active) return; + active = false; + removeListeners(); + onDraggingChanged?.(false); + }; window.addEventListener("pointermove", handleMove); window.addEventListener("pointerup", handleUp); window.addEventListener("pointercancel", handleUp); - return true; + return cancel; } export interface PlaneDragParams { @@ -195,7 +208,7 @@ export interface PlaneDragParams { * Project pointer screen-px deltas onto a 2D basis (screen projections of two * axes) and solve the 2x2 system for planar motion. */ -export function startPlaneDrag(opts: PlaneDragParams): boolean { +export function startPlaneDrag(opts: PlaneDragParams): (() => void) | null { const { axisA, axisB, @@ -217,12 +230,19 @@ export function startPlaneDrag(opts: PlaneDragParams): boolean { const pA = probeScreenAxis(wrapper, axisAVec, probeDistanceCss); const pB = probeScreenAxis(wrapper, axisBVec, probeDistanceCss); const det = screenPlaneDet(pA, pB); - if (Math.abs(det) < SCREEN_AXIS_DEAD_ZONE_SQ) return false; + if (Math.abs(det) < SCREEN_AXIS_DEAD_ZONE_SQ) return null; onMouseDown?.(); onDraggingChanged?.(true); + let active = true; + const removeListeners = (): void => { + window.removeEventListener("pointermove", handleMove); + window.removeEventListener("pointerup", handleUp); + window.removeEventListener("pointercancel", handleUp); + }; const handleMove = (ev: PointerEvent): void => { + if (!active) return; const dx = ev.clientX - startClientX; const dy = ev.clientY - startClientY; const solved = solvePlaneDragDeltas(dx, dy, pA, pB, det); @@ -231,17 +251,23 @@ export function startPlaneDrag(opts: PlaneDragParams): boolean { onPlaneDelta(tA, tB, axisAVec, axisBVec); }; const handleUp = (): void => { - window.removeEventListener("pointermove", handleMove); - window.removeEventListener("pointerup", handleUp); - window.removeEventListener("pointercancel", handleUp); + if (!active) return; + active = false; + removeListeners(); swallowNextClick(); onMouseUp?.(); onDraggingChanged?.(false); }; + const cancel = (): void => { + if (!active) return; + active = false; + removeListeners(); + onDraggingChanged?.(false); + }; window.addEventListener("pointermove", handleMove); window.addEventListener("pointerup", handleUp); window.addEventListener("pointercancel", handleUp); - return true; + return cancel; } export interface RingDragParams { @@ -260,7 +286,7 @@ export interface RingDragParams { * Track pointer angle around the gizmo center, accumulate unwrapped radians, * and report degrees of rotation. */ -export function startRingDrag(opts: RingDragParams): void { +export function startRingDrag(opts: RingDragParams): () => void { const { wrapper, startClientX, @@ -283,7 +309,14 @@ export function startRingDrag(opts: RingDragParams): void { onMouseDown?.(); onDraggingChanged?.(true); + let active = true; + const removeListeners = (): void => { + window.removeEventListener("pointermove", handleMove); + window.removeEventListener("pointerup", handleUp); + window.removeEventListener("pointercancel", handleUp); + }; const handleMove = (ev: PointerEvent): void => { + if (!active) return; const a = Math.atan2(ev.clientY - centerY, ev.clientX - centerX); cumulative += unwrapAngleDelta(a, lastAngle); lastAngle = a; @@ -291,17 +324,24 @@ export function startRingDrag(opts: RingDragParams): void { onAngleDelta(degrees); }; const handleUp = (): void => { - window.removeEventListener("pointermove", handleMove); - window.removeEventListener("pointerup", handleUp); - window.removeEventListener("pointercancel", handleUp); + if (!active) return; + active = false; + removeListeners(); swallowNextClick(); onMouseUp?.(); onDraggingChanged?.(false); onComplete?.(); }; + const cancel = (): void => { + if (!active) return; + active = false; + removeListeners(); + onDraggingChanged?.(false); + }; window.addEventListener("pointermove", handleMove); window.addEventListener("pointerup", handleUp); window.addEventListener("pointercancel", handleUp); + return cancel; } // ── Shared geometry builders ────────────────────────────────────────────── @@ -551,12 +591,12 @@ export function startDeclarativeArrowDrag< startClientX: number, startClientY: number, getState: () => DeclarativeGizmoDragState, -): boolean { +): (() => void) | null { const initial = getState(); const target = initial.target; - if (!target || !initial.enabled) return false; + if (!target || !initial.enabled) return null; const startPos = (target.getPosition() ?? [0, 0, 0]) as Vec3; - const started = startAxisDrag({ + return startAxisDrag({ cssAxis: spec.cssAxis, sign: spec.sign, shaftLengthCss: initial.shaftLengthCss, @@ -582,7 +622,6 @@ export function startDeclarativeArrowDrag< live.onDraggingChanged?.(d); }, }); - return started; } export function startDeclarativePlaneDrag< @@ -593,10 +632,10 @@ export function startDeclarativePlaneDrag< startClientX: number, startClientY: number, getState: () => DeclarativeGizmoDragState, -): boolean { +): (() => void) | null { const initial = getState(); const target = initial.target; - if (!target || !initial.enabled) return false; + if (!target || !initial.enabled) return null; const startPos = (target.getPosition() ?? [0, 0, 0]) as Vec3; return startPlaneDrag({ axisA: spec.axisA, @@ -634,15 +673,15 @@ export function startDeclarativeRingDrag< startClientX: number, startClientY: number, getState: () => DeclarativeGizmoDragState, -): void { +): (() => void) | null { const initial = getState(); const target = initial.target; - if (!target || !initial.enabled) return; + if (!target || !initial.enabled) return null; const startRotation = (target.getRotation() ?? [0, 0, 0]) as Vec3; const qStart = quatFromEulerXYZ(startRotation); const axisVec: Vec3 = [0, 0, 0]; axisVec[spec.cssAxis] = 1; - startRingDrag({ + return startRingDrag({ wrapper, startClientX, startClientY, @@ -680,6 +719,11 @@ export function attachDeclarativeGizmoFallback< cameraEl: HTMLElement, getState: () => DeclarativeGizmoDragState, ): () => void { + let activeDragCancel: (() => void) | null = null; + const setActiveDrag = (cancel: (() => void) | null): void => { + activeDragCancel?.(); + activeDragCancel = cancel; + }; const onPointerDown = (event: PointerEvent): void => { const state = getState(); if (!state.target || !state.enabled) return; @@ -702,7 +746,9 @@ export function attachDeclarativeGizmoFallback< if (!wrapper) return; event.preventDefault(); event.stopPropagation(); - startDeclarativePlaneDrag(spec, wrapper, event.clientX, event.clientY, getState); + setActiveDrag( + startDeclarativePlaneDrag(spec, wrapper, event.clientX, event.clientY, getState), + ); return; } for (const spec of ARROW_SPECS) { @@ -718,7 +764,9 @@ export function attachDeclarativeGizmoFallback< if (!wrapper) return; event.preventDefault(); event.stopPropagation(); - startDeclarativeArrowDrag(spec, wrapper, event.clientX, event.clientY, getState); + setActiveDrag( + startDeclarativeArrowDrag(spec, wrapper, event.clientX, event.clientY, getState), + ); return; } return; @@ -737,11 +785,17 @@ export function attachDeclarativeGizmoFallback< if (!wrapper) return; event.preventDefault(); event.stopPropagation(); - startDeclarativeRingDrag(spec, wrapper, event.clientX, event.clientY, getState); + setActiveDrag( + startDeclarativeRingDrag(spec, wrapper, event.clientX, event.clientY, getState), + ); return; } }; cameraEl.addEventListener("pointerdown", onPointerDown); - return () => cameraEl.removeEventListener("pointerdown", onPointerDown); + return () => { + cameraEl.removeEventListener("pointerdown", onPointerDown); + activeDragCancel?.(); + activeDragCancel = null; + }; } diff --git a/packages/polycss/src/api/createPolyFirstPersonControls.test.ts b/packages/polycss/src/api/createPolyFirstPersonControls.test.ts index e50d04c20..05628f842 100644 --- a/packages/polycss/src/api/createPolyFirstPersonControls.test.ts +++ b/packages/polycss/src/api/createPolyFirstPersonControls.test.ts @@ -465,5 +465,32 @@ describe("createPolyFirstPersonControls", () => { controls.update({ eyeHeight: 3 }); expect((scene.camera.state.target ?? [0, 0, 0])[2]).toBeCloseTo(3, 3); }); + + it("pause() inside a change listener does not reschedule rAF", () => { + controls = createPolyFirstPersonControls(scene, { moveSpeed: 10 }); + controls.addEventListener("change", () => { + controls?.pause(); + }); + pressKey("KeyW"); + tickFrame(16); + expect(rafQueue.length).toBe(0); + releaseKey("KeyW"); + }); + + it("pause() resets isLocked() when pointer-locked", () => { + controls = createPolyFirstPersonControls(scene); + Object.defineProperty(document, "pointerLockElement", { + configurable: true, + get: () => host, + }); + document.dispatchEvent(new Event("pointerlockchange")); + expect(controls.isLocked()).toBe(true); + controls.pause(); + expect(controls.isLocked()).toBe(false); + Object.defineProperty(document, "pointerLockElement", { + configurable: true, + get: () => null, + }); + }); }); }); diff --git a/packages/polycss/src/api/createPolyFirstPersonControls.ts b/packages/polycss/src/api/createPolyFirstPersonControls.ts index 3e5e4376a..5c43741f0 100644 --- a/packages/polycss/src/api/createPolyFirstPersonControls.ts +++ b/packages/polycss/src/api/createPolyFirstPersonControls.ts @@ -248,50 +248,59 @@ export function createPolyFirstPersonControls( // ── RAF tick ────────────────────────────────────────────────────────────── let rafId: number | null = null; let lastTime = 0; + let loopGen = 0; const ANIM_DT_CLAMP = 0.05; // 50 ms - const tick = (now: number): void => { - if (rafId === null || stopped) return; - const dt = Math.min(ANIM_DT_CLAMP, lastTime ? (now - lastTime) / 1000 : 0.0167); - lastTime = now; - - if (opts.enabled) { - const cameraState = scene.camera.state; - const res = stepFirstPersonPhysics( - { origin: cameraOrigin, verticalVel, jumpOffset }, - keysHeld, - cameraState.rotY ?? 0, - dt, - opts, - ); - cameraOrigin[0] = res.origin[0]; - cameraOrigin[1] = res.origin[1]; - cameraOrigin[2] = res.origin[2]; - verticalVel = res.verticalVel; - jumpOffset = res.jumpOffset; - - if (res.dirty) { - // Re-derive target from the new origin so PolyCSS's perspective viewer - // tracks the camera. Without this, walking forward would move - // `cameraOrigin` but target would stay put, and the visible center - // would drift behind us. - const target = deriveTarget(); - scene.camera.update({ target }); - scene.applyCamera(); - emitChange(snapshot); - } - } - - rafId = win.requestAnimationFrame(tick); - }; - function startLoop(): void { if (rafId !== null || stopped) return; lastTime = 0; + const gen = ++loopGen; + const tick = (now: number): void => { + if (gen !== loopGen || rafId === null || stopped) { + if (gen === loopGen) rafId = null; + return; + } + const dt = Math.min(ANIM_DT_CLAMP, lastTime ? (now - lastTime) / 1000 : 0.0167); + lastTime = now; + + if (opts.enabled) { + const cameraState = scene.camera.state; + const res = stepFirstPersonPhysics( + { origin: cameraOrigin, verticalVel, jumpOffset }, + keysHeld, + cameraState.rotY ?? 0, + dt, + opts, + ); + cameraOrigin[0] = res.origin[0]; + cameraOrigin[1] = res.origin[1]; + cameraOrigin[2] = res.origin[2]; + verticalVel = res.verticalVel; + jumpOffset = res.jumpOffset; + + if (res.dirty) { + // Re-derive target from the new origin so PolyCSS's perspective viewer + // tracks the camera. Without this, walking forward would move + // `cameraOrigin` but target would stay put, and the visible center + // would drift behind us. + const target = deriveTarget(); + scene.camera.update({ target }); + scene.applyCamera(); + emitChange(snapshot); + } + } + + if (gen !== loopGen || rafId === null || stopped) { + if (gen === loopGen) rafId = null; + return; + } + rafId = win.requestAnimationFrame(tick); + }; rafId = win.requestAnimationFrame(tick); } function stopLoop(): void { + loopGen++; if (rafId === null) return; win.cancelAnimationFrame(rafId); rafId = null; @@ -352,6 +361,7 @@ export function createPolyFirstPersonControls( } keysHeld.clear(); if (pointerLocked) { + pointerLocked = false; try { doc.exitPointerLock(); } catch { /* ignore */ } } clearFpvHostPerspective(); diff --git a/packages/polycss/src/api/createPolyOrbitControls.test.ts b/packages/polycss/src/api/createPolyOrbitControls.test.ts index 8967e9d57..269d8556b 100644 --- a/packages/polycss/src/api/createPolyOrbitControls.test.ts +++ b/packages/polycss/src/api/createPolyOrbitControls.test.ts @@ -230,6 +230,32 @@ describe("createPolyOrbitControls", () => { expect(rafQueue.length).toBe(0); expect(host.style.cursor).toBe(""); }); + + it("pause() inside a change listener during animate does not reschedule rAF", () => { + controls = createPolyOrbitControls(scene, { animate: { speed: 1 } }); + controls.addEventListener("change", () => { + controls?.pause(); + }); + tickFrame(16.67); + expect(rafQueue.length).toBe(0); + controls.resume(); + expect(rafQueue.length).toBe(1); + }); + + it("re-entrant pause()+resume() inside a change listener keeps exactly one rAF loop", () => { + controls = createPolyOrbitControls(scene, { animate: { speed: 1 } }); + let bounced = false; + controls.addEventListener("change", () => { + if (bounced) return; + bounced = true; + controls?.pause(); + controls?.resume(); + }); + tickFrame(16.67); + expect(rafQueue.length).toBe(1); + tickFrame(16.67); + expect(rafQueue.length).toBe(1); + }); }); // ── Event subscription ─────────────────────────────────────────────────── diff --git a/packages/polycss/src/api/createPolyScene.test.ts b/packages/polycss/src/api/createPolyScene.test.ts index 9f580b594..3a737b1ed 100644 --- a/packages/polycss/src/api/createPolyScene.test.ts +++ b/packages/polycss/src/api/createPolyScene.test.ts @@ -2730,4 +2730,31 @@ describe("scene.add — meshResolution option", () => { expect(handle).toBeTruthy(); expect(host.querySelectorAll("i,b,s,u").length).toBeGreaterThan(0); }); + + it("superseded setPolygonsChunked does not wipe a newer synchronous setPolygons()", async () => { + scene = makeScene(host); + const handle = scene.add(makeParseResult([triangle()])); + const many: Polygon[] = Array.from({ length: 120 }, (_, i) => ({ + vertices: [ + [i, 0, 0], + [i + 1, 0, 0], + [i, 1, 0], + ], + color: "#ff0000", + })); + const chunked = (handle as unknown as { setPolygonsChunked(p: Polygon[]): Promise }).setPolygonsChunked(many); + handle.setPolygons([ + triangle("#ff0000"), + { + vertices: [ + [5, 0, 0], + [6, 0, 0], + [5, 1, 0], + ], + color: "#00ff00", + }, + ]); + await chunked; + expect(handle.element.querySelectorAll("i,b,s,u").length).toBe(2); + }); }); diff --git a/packages/polycss/src/api/createTransformControls.test.ts b/packages/polycss/src/api/createTransformControls.test.ts index cdff1d3dc..a2e72c778 100644 --- a/packages/polycss/src/api/createTransformControls.test.ts +++ b/packages/polycss/src/api/createTransformControls.test.ts @@ -495,4 +495,28 @@ describe("createTransformControls", () => { expect(rebakeSpy).not.toHaveBeenCalled(); }); }); + + it("destroy() mid-drag cancels window pointer listeners and stops mutating target", () => { + withFakeLayout(2, () => { + const onObjectChange = vi.fn(); + const onDraggingChanged = vi.fn(); + const mesh = scene.add(parseResult(), { id: "target", position: [0, 0, 0] }); + tc = createTransformControls(scene, { onObjectChange, onDraggingChanged }); + tc.attach(mesh); + + triggerPointerDownOnGizmoEl(host, ".polycss-transform-arrow--x", 0, 0); + expect(onDraggingChanged).toHaveBeenCalledWith(true); + + tc.destroy(); + tc = null; + + expect(onDraggingChanged).toHaveBeenLastCalledWith(false); + onObjectChange.mockClear(); + + window.dispatchEvent(new PointerEvent("pointermove", { clientX: 50, clientY: 0, pointerId: 1 })); + window.dispatchEvent(new PointerEvent("pointerup", { clientX: 50, clientY: 0, pointerId: 1 })); + expect(onObjectChange).not.toHaveBeenCalled(); + expect(mesh.transform.position).toEqual([0, 0, 0]); + }); + }); }); diff --git a/packages/polycss/src/api/createTransformControls.ts b/packages/polycss/src/api/createTransformControls.ts index 64ac1795c..7799772f6 100644 --- a/packages/polycss/src/api/createTransformControls.ts +++ b/packages/polycss/src/api/createTransformControls.ts @@ -205,7 +205,18 @@ export function createTransformControls( })); } + let activeDragCancel: (() => void) | null = null; + + function cancelActiveDrag(): void { + const cancel = activeDragCancel; + activeDragCancel = null; + cancel?.(); + dragStartPosition = null; + dragStartRotation = null; + } + function teardownGizmos(): void { + cancelActiveDrag(); for (const { handle } of gizmos.values()) handle.remove(); gizmos.clear(); hoveredKey = null; @@ -299,10 +310,11 @@ export function createTransformControls( if (!gm || !pointInMeshElement(gm.handle.element, event.clientX, event.clientY)) continue; event.preventDefault(); event.stopPropagation(); + cancelActiveDrag(); draggingKey = spec.key; rebuildGizmoColors(); dragStartPosition = (target.transform.position ?? [0, 0, 0]).slice() as Vec3; - const started = startPlaneDrag({ + const cancel = startPlaneDrag({ axisA: spec.axisA, axisB: spec.axisB, probeDistanceCss: gizmoLengthForMesh(target.polygons) * size, @@ -323,6 +335,7 @@ export function createTransformControls( onMouseUp: opts.onMouseUp, onDraggingChanged: (d) => { if (!d) { + activeDragCancel = null; draggingKey = null; dragStartPosition = null; rebuildGizmoColors(); @@ -330,10 +343,12 @@ export function createTransformControls( opts.onDraggingChanged?.(d); }, }); - if (!started) { + if (!cancel) { draggingKey = null; dragStartPosition = null; rebuildGizmoColors(); + } else { + activeDragCancel = cancel; } return; } @@ -344,10 +359,11 @@ export function createTransformControls( if (!gm || !pointInMeshElement(gm.handle.element, event.clientX, event.clientY)) continue; event.preventDefault(); event.stopPropagation(); + cancelActiveDrag(); draggingKey = spec.key; rebuildGizmoColors(); dragStartPosition = (target.transform.position ?? [0, 0, 0]).slice() as Vec3; - const started = startAxisDrag({ + const cancel = startAxisDrag({ cssAxis: spec.cssAxis, sign: spec.sign, shaftLengthCss: gizmoLengthForMesh(target.polygons) * size, @@ -367,6 +383,7 @@ export function createTransformControls( onMouseUp: opts.onMouseUp, onDraggingChanged: (d) => { if (!d) { + activeDragCancel = null; draggingKey = null; dragStartPosition = null; rebuildGizmoColors(); @@ -374,10 +391,12 @@ export function createTransformControls( opts.onDraggingChanged?.(d); }, }); - if (!started) { + if (!cancel) { draggingKey = null; dragStartPosition = null; rebuildGizmoColors(); + } else { + activeDragCancel = cancel; } return; } @@ -390,6 +409,7 @@ export function createTransformControls( if (!gm || !pointInMeshElement(gm.handle.element, event.clientX, event.clientY)) continue; event.preventDefault(); event.stopPropagation(); + cancelActiveDrag(); draggingKey = spec.key; rebuildGizmoColors(); dragStartRotation = (target.transform.rotation ?? [0, 0, 0]).slice() as Vec3; @@ -398,7 +418,7 @@ export function createTransformControls( const axisVec: Vec3 = [0, 0, 0]; axisVec[worldAxis] = 1; const qStart = quatFromEulerXYZ(dragStartRotation); - startRingDrag({ + activeDragCancel = startRingDrag({ wrapper: gm.handle.element, startClientX: event.clientX, startClientY: event.clientY, @@ -430,6 +450,7 @@ export function createTransformControls( onMouseUp: opts.onMouseUp, onDraggingChanged: (d) => { if (!d) { + activeDragCancel = null; draggingKey = null; dragStartRotation = null; dragStartPosition = null; @@ -486,6 +507,7 @@ export function createTransformControls( function destroy(): void { scene.host.removeEventListener("pointerdown", onPointerDown, { capture: true }); scene.host.removeEventListener("pointermove", onPointerMove); + target = null; teardownGizmos(); } diff --git a/packages/polycss/src/api/runtimeSeams.test.ts b/packages/polycss/src/api/runtimeSeams.test.ts index b63e75c23..7f1d59ac1 100644 --- a/packages/polycss/src/api/runtimeSeams.test.ts +++ b/packages/polycss/src/api/runtimeSeams.test.ts @@ -637,5 +637,9 @@ describe("@layoutit/polycss/runtime subpath hygiene", () => { expect("PolySceneElement" in runtimeExports).toBe(false); expect("exportPolySceneSnapshot" in runtimeExports).toBe(false); expect("createPolyBox" in runtimeExports).toBe(false); + expect("createSelectionController" in runtimeExports).toBe(false); + expect("attachDeclarativeGizmoFallback" in runtimeExports).toBe(false); + expect("setInlineStyleProperty" in runtimeExports).toBe(false); + expect(typeof runtimeExports.pointInMeshElement).toBe("function"); }); }); diff --git a/packages/polycss/src/api/scene/meshEntry.ts b/packages/polycss/src/api/scene/meshEntry.ts index fc4186809..d34277d46 100644 --- a/packages/polycss/src/api/scene/meshEntry.ts +++ b/packages/polycss/src/api/scene/meshEntry.ts @@ -500,7 +500,9 @@ export function addSceneMeshEntry( const shouldCancel = () => entry.disposed || version !== polygonUpdateVersion; const completed = await renderSceneEntryChunked(ctx, entry, shouldCancel); if (!completed) { - clearRendered(ctx, entry); + // Only wipe DOM if the mesh was disposed; if superseded by a newer + // setPolygons/setPolygonsChunked call, that call already owns the DOM. + if (entry.disposed) clearRendered(ctx, entry); return; } if (shouldRecomputeAutoCenter) recomputeAutoCenter(); @@ -576,6 +578,8 @@ export function addSceneMeshEntry( try { parseResult.dispose(); } catch { /* ignore */ } meshes.delete(entry); meshByElement.delete(wrapper); + clearReceiverShadowCache(ctx, entry); + clearCasterItemsCache(ctx, entry); recomputeAutoCenter(); const prevGround = ctx.shadowSvgState.currentGroundCssZ; recomputeShadowGround(ctx); diff --git a/packages/polycss/src/api/scene/rebake.ts b/packages/polycss/src/api/scene/rebake.ts index 5b176817e..d1020708d 100644 --- a/packages/polycss/src/api/scene/rebake.ts +++ b/packages/polycss/src/api/scene/rebake.ts @@ -155,7 +155,7 @@ export function rebakeRenderEntryInPlace( renderOptions as Parameters[1], ); const apply = (): void => { - if (entry.disposed) { + if (entry.disposed || !ctx.meshes.has(entry)) { newAtlas.dispose(); finish(); return; @@ -213,7 +213,7 @@ export function rebakeRenderEntryInPlace( .then(decodeAtlasUrls) .then(apply, () => { newAtlas.dispose(); - if (!entry.disposed) renderEntry(entry, lightDirectionOverride); + if (!entry.disposed && ctx.meshes.has(entry)) renderEntry(entry, lightDirectionOverride); finish(); }); } else { diff --git a/packages/polycss/src/elements/PolyFirstPersonControlsElement.ts b/packages/polycss/src/elements/PolyFirstPersonControlsElement.ts index 2e8f0a2d5..5dd6418bc 100644 --- a/packages/polycss/src/elements/PolyFirstPersonControlsElement.ts +++ b/packages/polycss/src/elements/PolyFirstPersonControlsElement.ts @@ -62,6 +62,7 @@ export class PolyFirstPersonControlsElement extends ELEMENT_BASE { } private _controls: PolyFirstPersonControlsHandle | null = null; + private _pendingReadyCleanup: (() => void) | null = null; private _readOptions(): PolyFirstPersonControlsOptions { const opts: PolyFirstPersonControlsOptions = {}; @@ -110,17 +111,26 @@ export class PolyFirstPersonControlsElement extends ELEMENT_BASE { return null; } + private _clearPendingReady(): void { + this._pendingReadyCleanup?.(); + this._pendingReadyCleanup = null; + } + private _attach(): void { if (this._controls) return; + this._clearPendingReady(); const sceneEl = this._findScene(); const handle = sceneEl?.getScene(); if (!handle) { if (sceneEl) { const onReady = (): void => { - sceneEl.removeEventListener("polycss:scene-ready", onReady); + this._clearPendingReady(); + if (!this.isConnected) return; this._attach(); }; sceneEl.addEventListener("polycss:scene-ready", onReady); + this._pendingReadyCleanup = () => + sceneEl.removeEventListener("polycss:scene-ready", onReady); } return; } @@ -132,6 +142,7 @@ export class PolyFirstPersonControlsElement extends ELEMENT_BASE { } disconnectedCallback(): void { + this._clearPendingReady(); if (this._controls) { this._controls.destroy(); this._controls = null; diff --git a/packages/polycss/src/elements/PolyOrbitControlsElement.test.ts b/packages/polycss/src/elements/PolyOrbitControlsElement.test.ts index 29cac0e04..a5987f518 100644 --- a/packages/polycss/src/elements/PolyOrbitControlsElement.test.ts +++ b/packages/polycss/src/elements/PolyOrbitControlsElement.test.ts @@ -188,4 +188,24 @@ describe("PolyOrbitControlsElement", () => { expect(rafQueue.length).toBe(0); expect(sceneEl.style.cursor).toBe(""); }); + + it("disconnecting before polycss:scene-ready removes pending ready listener", () => { + const sceneEl = document.createElement("poly-scene") as PolySceneElement; + host.appendChild(sceneEl); + const getSceneSpy = vi.spyOn(sceneEl, "getScene").mockReturnValue(null); + const removeSpy = vi.spyOn(sceneEl, "removeEventListener"); + const controlsEl = document.createElement("poly-orbit-controls") as PolyOrbitControlsElement; + controlsEl.setAttribute("animate-speed", "1"); + + // Connect while scene handle is not ready yet, then disconnect before scene-ready fires. + sceneEl.appendChild(controlsEl); + sceneEl.removeChild(controlsEl); + + expect(removeSpy).toHaveBeenCalledWith("polycss:scene-ready", expect.any(Function)); + + getSceneSpy.mockRestore(); + sceneEl.dispatchEvent(new CustomEvent("polycss:scene-ready")); + expect(rafQueue.length).toBe(0); + expect(controlsEl.getControls()).toBeNull(); + }); }); diff --git a/packages/polycss/src/elements/PolyPointerControlsElement.ts b/packages/polycss/src/elements/PolyPointerControlsElement.ts index c8ebba2b5..873ea65ad 100644 --- a/packages/polycss/src/elements/PolyPointerControlsElement.ts +++ b/packages/polycss/src/elements/PolyPointerControlsElement.ts @@ -32,6 +32,7 @@ export abstract class PolyPointerControlsElement extends ELEMENT_BASE { } private _controls: PolyControlsHandle | null = null; + private _pendingReadyCleanup: (() => void) | null = null; protected abstract _createControls( scene: PolySceneHandle, @@ -88,17 +89,26 @@ export abstract class PolyPointerControlsElement extends ELEMENT_BASE { return null; } + private _clearPendingReady(): void { + this._pendingReadyCleanup?.(); + this._pendingReadyCleanup = null; + } + private _attach(): void { if (this._controls) return; + this._clearPendingReady(); const sceneEl = this._findScene(); const handle = sceneEl?.getScene(); if (!handle) { if (sceneEl) { const onReady = (): void => { - sceneEl.removeEventListener("polycss:scene-ready", onReady); + this._clearPendingReady(); + if (!this.isConnected) return; this._attach(); }; sceneEl.addEventListener("polycss:scene-ready", onReady); + this._pendingReadyCleanup = () => + sceneEl.removeEventListener("polycss:scene-ready", onReady); } return; } @@ -110,6 +120,7 @@ export abstract class PolyPointerControlsElement extends ELEMENT_BASE { } disconnectedCallback(): void { + this._clearPendingReady(); if (this._controls) { this._controls.destroy(); this._controls = null; diff --git a/packages/polycss/src/elements/PolySelectElement.ts b/packages/polycss/src/elements/PolySelectElement.ts index 01597bc10..c14fb7782 100644 --- a/packages/polycss/src/elements/PolySelectElement.ts +++ b/packages/polycss/src/elements/PolySelectElement.ts @@ -33,6 +33,7 @@ export class PolySelectElement extends ELEMENT_BASE { } private _selection: PolySelectionHandle | null = null; + private _pendingReadyCleanup: (() => void) | null = null; private _findScene(): PolySceneElement | null { let node: Node | null = this.parentNode; @@ -58,17 +59,26 @@ export class PolySelectElement extends ELEMENT_BASE { }; } + private _clearPendingReady(): void { + this._pendingReadyCleanup?.(); + this._pendingReadyCleanup = null; + } + private _attach(): void { if (this._selection) return; + this._clearPendingReady(); const sceneEl = this._findScene(); const handle = sceneEl?.getScene(); if (!handle) { if (sceneEl) { const onReady = (): void => { - sceneEl.removeEventListener("polycss:scene-ready", onReady); + this._clearPendingReady(); + if (!this.isConnected) return; this._attach(); }; sceneEl.addEventListener("polycss:scene-ready", onReady); + this._pendingReadyCleanup = () => + sceneEl.removeEventListener("polycss:scene-ready", onReady); } return; } @@ -80,6 +90,7 @@ export class PolySelectElement extends ELEMENT_BASE { } disconnectedCallback(): void { + this._clearPendingReady(); if (this._selection) { this._selection.destroy(); this._selection = null; @@ -97,6 +108,6 @@ export class PolySelectElement extends ELEMENT_BASE { this._selection.destroy(); this._selection = null; } - this._attach(); + if (this.isConnected) this._attach(); } } diff --git a/packages/polycss/src/elements/PolyTransformControlsElement.ts b/packages/polycss/src/elements/PolyTransformControlsElement.ts index cf1f2201d..ebd4c95da 100644 --- a/packages/polycss/src/elements/PolyTransformControlsElement.ts +++ b/packages/polycss/src/elements/PolyTransformControlsElement.ts @@ -46,6 +46,7 @@ export class PolyTransformControlsElement extends ELEMENT_BASE { } private _tc: PolyTransformControlsHandle | null = null; + private _pendingReadyCleanup: (() => void) | null = null; private _findScene(): PolySceneElement | null { let node: Node | null = this.parentNode; @@ -92,17 +93,26 @@ export class PolyTransformControlsElement extends ELEMENT_BASE { return opts; } + private _clearPendingReady(): void { + this._pendingReadyCleanup?.(); + this._pendingReadyCleanup = null; + } + private _attach(): void { if (this._tc) return; + this._clearPendingReady(); const sceneEl = this._findScene(); const handle = sceneEl?.getScene(); if (!handle) { if (sceneEl) { const onReady = (): void => { - sceneEl.removeEventListener("polycss:scene-ready", onReady); + this._clearPendingReady(); + if (!this.isConnected) return; this._attach(); }; sceneEl.addEventListener("polycss:scene-ready", onReady); + this._pendingReadyCleanup = () => + sceneEl.removeEventListener("polycss:scene-ready", onReady); } return; } @@ -120,6 +130,7 @@ export class PolyTransformControlsElement extends ELEMENT_BASE { } disconnectedCallback(): void { + this._clearPendingReady(); if (this._tc) { this._tc.destroy(); this._tc = null; @@ -132,7 +143,7 @@ export class PolyTransformControlsElement extends ELEMENT_BASE { newValue: string | null, ): void { if (oldValue === newValue) return; - if (!this._tc) return; + if (!this.isConnected || !this._tc) return; if (name === "mode") { const mode = parseMode(newValue); if (mode) this._tc.setMode(mode); diff --git a/packages/polycss/src/index.ts b/packages/polycss/src/index.ts index a3c266b4d..1425295fb 100644 --- a/packages/polycss/src/index.ts +++ b/packages/polycss/src/index.ts @@ -12,6 +12,8 @@ // ── Imperative scene API ────────────────────────────────────────── export { createPolyScene } from "./api/createPolyScene"; +export { pointInMeshElement } from "./api/meshHitTest"; +export type { GizmoMode } from "./api/controls/gizmoEngine"; export type { PolyCameraControlTarget, PolySceneElements, diff --git a/packages/polycss/src/internal.ts b/packages/polycss/src/internal.ts new file mode 100644 index 000000000..0b69527ae --- /dev/null +++ b/packages/polycss/src/internal.ts @@ -0,0 +1,57 @@ +/** + * @layoutit/polycss/internal — internal adapter plumbing for lockstep framework + * packages (`@layoutit/polycss-react`, `@layoutit/polycss-vue`). + * + * Not part of the semver-stable public API surface; React and Vue pin an exact + * lockstep `@layoutit/polycss` version (`workspace:*`). + */ + +export { createSelectionController } from "./api/controls/selectionEngine"; + +export { + RING_MASK_INNER_RATIO, + RING_MASK_OUTER_RATIO, + attachDeclarativeGizmoFallback, + buildTransformGizmoEntries, + computeGizmoWrapperPositionCss, + startDeclarativeArrowDrag, + startDeclarativePlaneDrag, + startDeclarativeRingDrag, +} from "./api/controls/gizmoEngine"; +export type { + DeclarativeGizmoDragState, + GizmoArrowSpec, + GizmoPlaneSpec, + GizmoRingSpec, + TransformGizmoCache, +} from "./api/controls/gizmoEngine"; + +export { + buildPolyPointerEvent, + createMeshElementRegistry, +} from "./api/meshHitTest"; + +export { + adaptFallbackCamera, + applyCameraTransformDirect, + bindCameraStoreSync, + createLiveRuntimeCamera, + observeViewportHeight, + writeCameraSnapshotAttrs, +} from "./api/cameraSnapshotAttrs"; + +export { + clearOwnedDomNodes, + renderStandaloneMeshIntoWrapper, + restoreVoxelMeshClass, +} from "./api/standaloneMesh"; + +export { + buildDirectMaterialLeafDescriptor, + buildFallbackLeafDescriptor, + buildPolyWrapperTransform, + isAxisAlignedRectUVs, + readElementDataAttrs, + readElementStyleRecord, + syncLeafBorderShapeStyle, +} from "./render/polyLeafDescriptor"; diff --git a/packages/polycss/src/render/atlas/rasterise.ts b/packages/polycss/src/render/atlas/rasterise.ts index 295e45fde..08b912d3c 100644 --- a/packages/polycss/src/render/atlas/rasterise.ts +++ b/packages/polycss/src/render/atlas/rasterise.ts @@ -618,9 +618,19 @@ export async function buildAtlasPages( isCancelled: () => boolean, ): Promise { const built: TextureAtlasPage[] = []; - for (const page of pages) { - if (isCancelled()) break; - built.push(await buildAtlasPage(page, textureLighting, doc, atlasScale)); + try { + for (const page of pages) { + if (isCancelled()) break; + built.push(await buildAtlasPage(page, textureLighting, doc, atlasScale)); + } + return built; + } catch (err) { + for (const page of built) { + const url = page.url; + if (url && url.startsWith("blob:") && typeof URL !== "undefined" && typeof URL.revokeObjectURL === "function") { + try { URL.revokeObjectURL(url); } catch { /* ignore */ } + } + } + throw err; } - return built; } diff --git a/packages/polycss/src/runtime.ts b/packages/polycss/src/runtime.ts index 7642ab77c..e94ed3a16 100644 --- a/packages/polycss/src/runtime.ts +++ b/packages/polycss/src/runtime.ts @@ -1,11 +1,10 @@ /** * @layoutit/polycss/runtime — side-effect-free DOM rendering runtime. * - * Exposes the imperative scene, camera, controls, selection, transform gizmo, - * atlas/voxel renderers, diagnostics, and base stylesheet injector WITHOUT - * custom-element classes, standalone snapshot export, or primitive shape - * factories. Intended for framework adapters (`@layoutit/polycss-react`, - * `@layoutit/polycss-vue`) and lean imperative bundles. + * Exposes the public imperative scene, camera, controls, selection, transform + * gizmo, atlas/voxel renderers, diagnostics, and base stylesheet injector + * WITHOUT custom-element classes, standalone snapshot export, or primitive + * shape factories. Framework adapter plumbing lives in `@layoutit/polycss/internal`. */ // ── Imperative scene API ────────────────────────────────────────── @@ -68,105 +67,14 @@ export type { export { createSelect } from "./api/createSelect"; export type { PolySelectOptions, PolySelectionHandle } from "./api/createSelect"; -export { createSelectionController } from "./api/controls/selectionEngine"; -export type { - SelectionController, - SelectionControllerOptions, -} from "./api/controls/selectionEngine"; - export { createTransformControls } from "./api/createTransformControls"; export type { PolyTransformControlsHandle, PolyTransformControlsObjectChangeEvent, PolyTransformControlsOptions, } from "./api/createTransformControls"; - -export { - RING_MASK_INNER_RATIO, - RING_MASK_OUTER_RATIO, - attachDeclarativeGizmoFallback, - buildArrowGizmoPolygons, - buildPlaneGizmoPolygons, - buildRingGizmoPolygons, - buildTransformGizmoEntries, - computeGizmoWrapperPositionCss, - gizmoAlphaForKey, - isArrowSpecVisible, - isPlaneSpecVisible, - isRingSpecVisible, - startAxisDrag, - startDeclarativeArrowDrag, - startDeclarativePlaneDrag, - startDeclarativeRingDrag, - startPlaneDrag, - startRingDrag, - swallowNextClick, -} from "./api/controls/gizmoEngine"; -export type { - AxisDragParams, - BuildTransformGizmoEntriesOptions, - DeclarativeGizmoCallbacks, - DeclarativeGizmoDragState, - DeclarativeGizmoObjectChangeEvent, - DeclarativeGizmoTarget, - GizmoArrowSpec, - GizmoMode, - GizmoPlaneSpec, - GizmoPolygonEntry, - GizmoRingSpec, - GizmoVisibility, - PlaneDragParams, - RingDragParams, - TransformGizmoCache, - TransformGizmoEntries, -} from "./api/controls/gizmoEngine"; - -export { - buildPolyPointerEvent, - createMeshElementRegistry, - pointInMeshElement, -} from "./api/meshHitTest"; -export type { - MeshElementRegistry, - SynthesizedPolyPointerEvent, -} from "./api/meshHitTest"; - -export { - adaptFallbackCamera, - applyCameraTransformDirect, - bindCameraStoreSync, - createLiveRuntimeCamera, - observeViewportHeight, - writeCameraSnapshotAttrs, -} from "./api/cameraSnapshotAttrs"; -export type { - CameraSyncStoreLike, - LiveRuntimeCameraOptions, - WriteCameraSnapshotAttrsOptions, -} from "./api/cameraSnapshotAttrs"; - -export { - clearOwnedDomNodes, - renderStandaloneMeshIntoWrapper, - restoreVoxelMeshClass, -} from "./api/standaloneMesh"; -export type { StandaloneMeshMountResult } from "./api/standaloneMesh"; - -export { - buildDirectMaterialLeafDescriptor, - buildFallbackLeafDescriptor, - buildPolyWrapperTransform, - cssPropToCamel, - isAxisAlignedRectUVs, - readElementDataAttrs, - readElementStyleRecord, - syncLeafBorderShapeStyle, -} from "./render/polyLeafDescriptor"; -export type { - DirectMaterialLeafDescriptor, - FallbackLeafDescriptor, - PolyUvRect, -} from "./render/polyLeafDescriptor"; +export type { GizmoMode } from "./api/controls/gizmoEngine"; +export { pointInMeshElement } from "./api/meshHitTest"; // ── Low-level atlas & voxel renderers ───────────────────────────── export { @@ -236,12 +144,5 @@ export type { PolyTextureRenderStats, } from "./render/renderStats"; -/** - * @internal Adapter-plumbing exports below are consumed by the lockstep - * `@layoutit/polycss-react` and `@layoutit/polycss-vue` packages and are not - * part of the public semver-stable imperative API surface. - */ -export { setInlineStyleProperty } from "./render/atlas/paintDefaults"; - // ── Style injection ─────────────────────────────────────────────── export { injectPolyBaseStyles } from "./styles/styles"; diff --git a/packages/polycss/tsup.config.ts b/packages/polycss/tsup.config.ts index ac58f6466..8bdca826a 100644 --- a/packages/polycss/tsup.config.ts +++ b/packages/polycss/tsup.config.ts @@ -4,6 +4,7 @@ export default createLibraryConfig({ entry: { index: "src/index.ts", runtime: "src/runtime.ts", + internal: "src/internal.ts", elements: "src/elements/index.ts", three: "src/three.ts", }, diff --git a/packages/react/package.json b/packages/react/package.json index 86f37e084..4ee33b6b0 100644 --- a/packages/react/package.json +++ b/packages/react/package.json @@ -47,7 +47,7 @@ "access": "public" }, "dependencies": { - "@layoutit/polycss": "workspace:^", + "@layoutit/polycss": "workspace:*", "@layoutit/polycss-core": "workspace:^" }, "peerDependencies": { diff --git a/packages/react/src/animation/usePolyAnimation.ts b/packages/react/src/animation/usePolyAnimation.ts index d01b50f83..ac8a0a090 100644 --- a/packages/react/src/animation/usePolyAnimation.ts +++ b/packages/react/src/animation/usePolyAnimation.ts @@ -95,8 +95,10 @@ export function usePolyAnimation( let rafId: number; let lastTime: number | null = null; + let cancelled = false; function tick(now: number) { + if (cancelled) return; if (lastTime === null) { lastTime = now; rafId = requestAnimationFrame(tick); @@ -105,11 +107,13 @@ export function usePolyAnimation( const dt = (now - lastTime) / 1000; lastTime = now; mixerRef.current?.update(dt); + if (cancelled) return; rafId = requestAnimationFrame(tick); } rafId = requestAnimationFrame(tick); return () => { + cancelled = true; cancelAnimationFrame(rafId); lastTime = null; }; diff --git a/packages/react/src/camera/useCamera.ts b/packages/react/src/camera/useCamera.ts index 044f2d558..a744ea8c5 100644 --- a/packages/react/src/camera/useCamera.ts +++ b/packages/react/src/camera/useCamera.ts @@ -5,9 +5,11 @@ import { bindCameraStoreSync, createLiveRuntimeCamera, writeCameraSnapshotAttrs, - type PolyOrthographicCameraHandle, - type PolyPerspectiveCameraHandle, - type PolySceneHandle, +} from "@layoutit/polycss/internal"; +import type { + PolyOrthographicCameraHandle, + PolyPerspectiveCameraHandle, + PolySceneHandle, } from "@layoutit/polycss/runtime"; import { createSceneStore, type SceneStore } from "../store/sceneStore"; diff --git a/packages/react/src/controls/TransformControls.tsx b/packages/react/src/controls/TransformControls.tsx index 88dfc38bf..8625efcc9 100644 --- a/packages/react/src/controls/TransformControls.tsx +++ b/packages/react/src/controls/TransformControls.tsx @@ -12,6 +12,7 @@ import { type RefObject, } from "react"; import { DEFAULT_CAMERA_STATE, type Vec3 } from "@layoutit/polycss-core"; +import type { GizmoMode } from "@layoutit/polycss/runtime"; import { RING_MASK_INNER_RATIO, RING_MASK_OUTER_RATIO, @@ -23,11 +24,10 @@ import { startDeclarativeRingDrag, type DeclarativeGizmoDragState, type GizmoArrowSpec, - type GizmoMode, type GizmoPlaneSpec, type GizmoRingSpec, type TransformGizmoCache, -} from "@layoutit/polycss/runtime"; +} from "@layoutit/polycss/internal"; import { PolyMesh } from "../scene/PolyMesh"; import type { PolyMeshHandle, PolyPointerEvent } from "../scene/events"; import { PolyCameraContext } from "../camera/context"; @@ -125,6 +125,7 @@ export function PolyTransformControls({ const [hoveredKey, setHoveredKey] = useState(null); const [draggingKey, setDraggingKey] = useState(null); const gizmoCacheRef = useRef(new Map()); + const activeDragCancelRef = useRef<(() => void) | null>(null); const dragStateRef = useRef>({ target: null, @@ -140,13 +141,26 @@ export function PolyTransformControls({ useEffect(() => { const cameraEl = cameraElRef?.current; - if (!cameraEl) return; - return attachDeclarativeGizmoFallback(cameraEl, () => dragStateRef.current); + const detachFallback = cameraEl + ? attachDeclarativeGizmoFallback(cameraEl, () => dragStateRef.current) + : undefined; + return () => { + detachFallback?.(); + activeDragCancelRef.current?.(); + activeDragCancelRef.current = null; + }; }, [cameraElRef]); const target = resolveObject(object); const polygons = target ? target.getPolygons() : []; + useEffect(() => { + if (!target || !enabled) { + activeDragCancelRef.current?.(); + activeDragCancelRef.current = null; + } + }, [target, enabled]); + const entries = useMemo( () => target @@ -202,7 +216,7 @@ export function PolyTransformControls({ const startFromMeshEvent = ( e: PolyPointerEvent, - run: (wrapper: HTMLElement) => void, + run: (wrapper: HTMLElement) => (() => void) | null, ): void => { if (!dragStateRef.current.enabled) return; e.stopPropagation(); @@ -210,43 +224,44 @@ export function PolyTransformControls({ "[data-poly-transform-controls]", ) as HTMLElement | null; if (!wrapper) return; - run(wrapper); + activeDragCancelRef.current?.(); + activeDragCancelRef.current = run(wrapper); }; const getDragState = () => dragStateRef.current; const handleArrowDown = (spec: GizmoArrowSpec) => (e: PolyPointerEvent) => - startFromMeshEvent(e, (wrapper) => { + startFromMeshEvent(e, (wrapper) => startDeclarativeArrowDrag( spec, wrapper, e.nativeEvent.clientX, e.nativeEvent.clientY, getDragState, - ); - }); + ), + ); const handlePlaneDown = (spec: GizmoPlaneSpec) => (e: PolyPointerEvent) => - startFromMeshEvent(e, (wrapper) => { + startFromMeshEvent(e, (wrapper) => startDeclarativePlaneDrag( spec, wrapper, e.nativeEvent.clientX, e.nativeEvent.clientY, getDragState, - ); - }); + ), + ); const handleRingDown = (spec: GizmoRingSpec) => (e: PolyPointerEvent) => - startFromMeshEvent(e, (wrapper) => { + startFromMeshEvent(e, (wrapper) => startDeclarativeRingDrag( spec, wrapper, e.nativeEvent.clientX, e.nativeEvent.clientY, getDragState, - ); - }); + ), + ); const hoverHandlers = (key: string) => ({ onPointerOver: () => setHoveredKey(key), diff --git a/packages/react/src/scene/PolyMesh.tsx b/packages/react/src/scene/PolyMesh.tsx index b6ef90115..1ac1feeb5 100644 --- a/packages/react/src/scene/PolyMesh.tsx +++ b/packages/react/src/scene/PolyMesh.tsx @@ -32,9 +32,11 @@ import { clearOwnedDomNodes, renderStandaloneMeshIntoWrapper, restoreVoxelMeshClass, - type PolyMeshHandle as RuntimeMeshHandle, - type PolySceneHandle, - type TextureQuality, +} from "@layoutit/polycss/internal"; +import type { + PolyMeshHandle as RuntimeMeshHandle, + PolySceneHandle, + TextureQuality, } from "@layoutit/polycss/runtime"; import type { TransformProps } from "../shapes/types"; import type { UseMeshOptions } from "./useMesh"; diff --git a/packages/react/src/scene/PolyScene.tsx b/packages/react/src/scene/PolyScene.tsx index 0b5ce1eb9..e6027b3b4 100644 --- a/packages/react/src/scene/PolyScene.tsx +++ b/packages/react/src/scene/PolyScene.tsx @@ -14,8 +14,8 @@ import type { PolyTextureProjection, } from "@layoutit/polycss-core"; import { DEFAULT_SEAM_BLEED } from "@layoutit/polycss-core"; +import { adaptFallbackCamera } from "@layoutit/polycss/internal"; import { - adaptFallbackCamera, createPolyScene, injectPolyBaseStyles, type PolyMeshHandle as RuntimeMeshHandle, diff --git a/packages/react/src/scene/events.ts b/packages/react/src/scene/events.ts index b5320c1eb..b951e17e9 100644 --- a/packages/react/src/scene/events.ts +++ b/packages/react/src/scene/events.ts @@ -1,9 +1,10 @@ /** * Pointer event API for . Delegates DOM element registry and - * bounding-rect hit-testing to `@layoutit/polycss/runtime`. + * bounding-rect hit-testing to `@layoutit/polycss`. */ import type { Polygon, Vec3 } from "@layoutit/polycss-core"; -import { createMeshElementRegistry, pointInMeshElement } from "@layoutit/polycss/runtime"; +import { pointInMeshElement } from "@layoutit/polycss/runtime"; +import { createMeshElementRegistry } from "@layoutit/polycss/internal"; /** * Imperative handle exposed by ``. Read-only view of the diff --git a/packages/react/src/scene/mesh/useMeshEvents.ts b/packages/react/src/scene/mesh/useMeshEvents.ts index e2a1e0aea..1f2d0a9d5 100644 --- a/packages/react/src/scene/mesh/useMeshEvents.ts +++ b/packages/react/src/scene/mesh/useMeshEvents.ts @@ -8,7 +8,7 @@ import type { MouseEvent as ReactMouseEvent, WheelEvent as ReactWheelEvent, } from "react"; -import { buildPolyPointerEvent } from "@layoutit/polycss/runtime"; +import { buildPolyPointerEvent } from "@layoutit/polycss/internal"; import type { PolyCameraContextValue } from "../../camera/context"; import { findPolyMeshHandle, diff --git a/packages/react/src/select/Select.tsx b/packages/react/src/select/Select.tsx index 32dce98ab..14fa65196 100644 --- a/packages/react/src/select/Select.tsx +++ b/packages/react/src/select/Select.tsx @@ -11,7 +11,7 @@ import { useState, } from "react"; import type { CSSProperties, MouseEvent as ReactMouseEvent, ReactNode } from "react"; -import { createSelectionController } from "@layoutit/polycss/runtime"; +import { createSelectionController } from "@layoutit/polycss/internal"; import { findPolyMeshHandle, findMeshUnderPoint as findMeshUnderPointShared, diff --git a/packages/react/src/shapes/Poly.test.tsx b/packages/react/src/shapes/Poly.test.tsx index b646a743d..19bf27187 100644 --- a/packages/react/src/shapes/Poly.test.tsx +++ b/packages/react/src/shapes/Poly.test.tsx @@ -45,9 +45,12 @@ const OFFAXIS_TRIANGLE_VERTS: [number, number, number][] = [ [0, 1, 1], ]; +const mountedRoots: Array> = []; + function renderPoly(props: Partial & { vertices: [number, number, number][] }): HTMLElement { const container = document.createElement("div"); const root = createRoot(container); + mountedRoots.push(root); act(() => root.render( React.createElement(Poly, { @@ -60,6 +63,13 @@ function renderPoly(props: Partial & { vertices: [number, number, num return container; } +afterEach(() => { + while (mountedRoots.length > 0) { + const root = mountedRoots.pop()!; + act(() => root.unmount()); + } +}); + function getPoly(container: HTMLElement): HTMLElement { const poly = container.querySelector("i,b,s,u") as HTMLElement | null; expect(poly).toBeTruthy(); @@ -514,4 +524,32 @@ describe("Poly — DOM passthrough", () => { }); expect(getPoly(container).classList.contains("my-custom-class")).toBe(true); }); + + it("unmounts cleanly in StrictMode without leaking solid fallback atlas leaves", () => { + vi.stubGlobal("CSS", { + supports: vi.fn(() => false), + }); + const container = document.createElement("div"); + const root = createRoot(container); + try { + act(() => + root.render( + React.createElement( + React.StrictMode, + null, + React.createElement(Poly, { + context: DEFAULT_CONTEXT, + color: "#cccccc", + vertices: IRREGULAR_SOLID_VERTS, + } as PolyProps), + ), + ), + ); + expect(getPoly(container).tagName.toLowerCase()).toBe("s"); + act(() => root.unmount()); + expect(container.querySelector("i,b,s,u")).toBeNull(); + } finally { + vi.unstubAllGlobals(); + } + }); }); diff --git a/packages/react/src/shapes/Poly.tsx b/packages/react/src/shapes/Poly.tsx index 09ce04869..2446b8400 100644 --- a/packages/react/src/shapes/Poly.tsx +++ b/packages/react/src/shapes/Poly.tsx @@ -7,12 +7,14 @@ import { buildDirectMaterialLeafDescriptor, buildFallbackLeafDescriptor, buildPolyWrapperTransform, - computeTextureAtlasPlanPublic, isAxisAlignedRectUVs, readElementDataAttrs, readElementStyleRecord, - renderPolygonsWithTextureAtlas, syncLeafBorderShapeStyle, +} from "@layoutit/polycss/internal"; +import { + computeTextureAtlasPlanPublic, + renderPolygonsWithTextureAtlas, type RenderTextureAtlasResult, } from "@layoutit/polycss/runtime"; import type { PolyProps } from "./types"; @@ -120,50 +122,19 @@ function PolyInner({ ); const isTextured = Boolean(effectiveTexture || textureImageSource); - const hasDom = typeof document !== "undefined"; - - // Solid polygons are synchronous with zero blob URLs; textured polygons - // manage async canvas/blob atlases in a layout effect for StrictMode safety. - const solidRenderedResult = useMemo(() => { - if (materialUvRect || isTextured || !hasDom) return null; - return renderPolygonsWithTextureAtlas([polygon], { - tileSize, - layerElevation, - directionalLight: - textureLighting === "dynamic" - ? undefined - : worldDirectionalLightToCss(context?.directionalLight), - textureLighting, - textureQuality, - textureLeafSizing, - textureImageRendering, - textureBackend, - textureProjection, - }); - }, [ - materialUvRect, - isTextured, - hasDom, - polygon, - tileSize, - layerElevation, - context?.directionalLight, - textureLighting, - textureQuality, - textureLeafSizing, - textureImageRendering, - textureBackend, - textureProjection, - ]); - const [texturedState, setTexturedState] = useState<{ + const [renderedState, setRenderedState] = useState<{ result: RenderTextureAtlasResult; tick: number; } | null>(null); + // Manage all runtime-rendered leaves (solid and textured) inside a layout + // effect so StrictMode remounts and atlas-fallback solid polygons (`` on + // non-`border-shape` / WebKit browsers) always revoke blob URLs and observe + // `pagesReady`. useIsomorphicLayoutEffect(() => { - if (materialUvRect || !isTextured || typeof document === "undefined") { - setTexturedState(null); + if (materialUvRect || typeof document === "undefined") { + setRenderedState(null); return; } let alive = true; @@ -181,16 +152,20 @@ function PolyInner({ textureBackend, textureProjection, }); - setTexturedState({ result: next, tick: 0 }); - const leaf = next.rendered[0]?.element; - if (leaf && leaf.tagName.toLowerCase() === "s") { - next.pagesReady?.then(() => { - if (alive) { - setTexturedState((prev) => - prev && prev.result === next ? { result: next, tick: prev.tick + 1 } : prev, - ); - } - }); + setRenderedState({ result: next, tick: 0 }); + const entry = next.rendered[0]; + if (entry?.kind === "atlas") { + const initialStyle = entry.element.getAttribute("style") ?? ""; + next.pagesReady?.then( + () => { + if (alive && (entry.element.getAttribute("style") ?? "") !== initialStyle) { + setRenderedState((prev) => + prev && prev.result === next ? { result: next, tick: prev.tick + 1 } : prev, + ); + } + }, + () => {}, + ); } return () => { alive = false; @@ -198,7 +173,6 @@ function PolyInner({ }; }, [ materialUvRect, - isTextured, polygon, tileSize, layerElevation, @@ -211,7 +185,7 @@ function PolyInner({ textureProjection, ]); - const renderedResult = isTextured ? texturedState?.result ?? null : solidRenderedResult; + const renderedResult = renderedState?.result ?? null; // Pure-JS fallback plan for Node SSR and pre-effect textured initial frame. const fallbackPlan = useMemo( diff --git a/packages/react/src/three/PolyThreeOrthographicCamera.tsx b/packages/react/src/three/PolyThreeOrthographicCamera.tsx index a8138b5c1..cff7d044d 100644 --- a/packages/react/src/three/PolyThreeOrthographicCamera.tsx +++ b/packages/react/src/three/PolyThreeOrthographicCamera.tsx @@ -5,7 +5,7 @@ import { applyThreeOrthographicCameraProps as applyCameraProps, } from "@layoutit/polycss-core/three"; import type { Vector3Tuple } from "@layoutit/polycss-core/three"; -import { observeViewportHeight } from "@layoutit/polycss/runtime"; +import { observeViewportHeight } from "@layoutit/polycss/internal"; import { PolyCameraContext } from "../camera/context"; import { usePolyCamera } from "../camera/useCamera"; diff --git a/packages/react/src/three/PolyThreePerspectiveCamera.tsx b/packages/react/src/three/PolyThreePerspectiveCamera.tsx index 0ddde66e5..829da5727 100644 --- a/packages/react/src/three/PolyThreePerspectiveCamera.tsx +++ b/packages/react/src/three/PolyThreePerspectiveCamera.tsx @@ -5,7 +5,7 @@ import { applyThreePerspectiveCameraProps as applyCameraProps, } from "@layoutit/polycss-core/three"; import type { Vector3Tuple } from "@layoutit/polycss-core/three"; -import { observeViewportHeight } from "@layoutit/polycss/runtime"; +import { observeViewportHeight } from "@layoutit/polycss/internal"; import { PolyCameraContext } from "../camera/context"; import { usePolyCamera } from "../camera/useCamera"; diff --git a/packages/react/tsup.config.ts b/packages/react/tsup.config.ts index f69f36d79..f909eaf60 100644 --- a/packages/react/tsup.config.ts +++ b/packages/react/tsup.config.ts @@ -10,6 +10,7 @@ export default createLibraryConfig({ "react-dom", "@layoutit/polycss", "@layoutit/polycss/runtime", + "@layoutit/polycss/internal", "@layoutit/polycss-core", "@layoutit/polycss-core/three", ], diff --git a/packages/vue/package.json b/packages/vue/package.json index 9b44fb222..253837eea 100644 --- a/packages/vue/package.json +++ b/packages/vue/package.json @@ -47,7 +47,7 @@ "access": "public" }, "dependencies": { - "@layoutit/polycss": "workspace:^", + "@layoutit/polycss": "workspace:*", "@layoutit/polycss-core": "workspace:^" }, "peerDependencies": { diff --git a/packages/vue/src/animation/usePolyAnimation.ts b/packages/vue/src/animation/usePolyAnimation.ts index fda059c1d..6af61acb5 100644 --- a/packages/vue/src/animation/usePolyAnimation.ts +++ b/packages/vue/src/animation/usePolyAnimation.ts @@ -77,7 +77,10 @@ export function usePolyAnimation( return r ?? internalRef.value; } + let _loopGen = 0; + function stopRaf(): void { + _loopGen++; if (_rafId !== null) { cancelAnimationFrame(_rafId); _rafId = null; @@ -97,7 +100,12 @@ export function usePolyAnimation( function startLoop(): void { if (_rafId !== null) return; + const gen = ++_loopGen; function tick(now: number): void { + if (gen !== _loopGen || _rafId === null || !_mixer) { + if (gen === _loopGen) _rafId = null; + return; + } if (_lastTime === null) { _lastTime = now; _rafId = requestAnimationFrame(tick); @@ -105,7 +113,11 @@ export function usePolyAnimation( } const dt = (now - _lastTime) / 1000; _lastTime = now; - _mixer?.update(dt); + _mixer.update(dt); + if (gen !== _loopGen || _rafId === null || !_mixer) { + if (gen === _loopGen) _rafId = null; + return; + } _rafId = requestAnimationFrame(tick); } _rafId = requestAnimationFrame(tick); diff --git a/packages/vue/src/camera/useCamera.ts b/packages/vue/src/camera/useCamera.ts index 6f75c2ee3..fed0c0561 100644 --- a/packages/vue/src/camera/useCamera.ts +++ b/packages/vue/src/camera/useCamera.ts @@ -1,15 +1,17 @@ import { onScopeDispose, ref, shallowRef, watch } from "vue"; import type { Ref, ShallowRef } from "vue"; import type { CameraState, CameraHandle, PolyCameraProjection, Vec3 } from "@layoutit/polycss-core"; +import type { + PolyOrthographicCameraHandle, + PolyPerspectiveCameraHandle, + PolySceneHandle, +} from "@layoutit/polycss/runtime"; import { applyCameraTransformDirect, bindCameraStoreSync, createLiveRuntimeCamera, writeCameraSnapshotAttrs, - type PolyOrthographicCameraHandle, - type PolyPerspectiveCameraHandle, - type PolySceneHandle, -} from "@layoutit/polycss/runtime"; +} from "@layoutit/polycss/internal"; import { createSceneStore, type SceneStore } from "../store"; export interface UseCameraOptions { diff --git a/packages/vue/src/controls/PolyTransformControls.ts b/packages/vue/src/controls/PolyTransformControls.ts index f47ef1d42..f9f9cc623 100644 --- a/packages/vue/src/controls/PolyTransformControls.ts +++ b/packages/vue/src/controls/PolyTransformControls.ts @@ -1,6 +1,6 @@ /** * `` (Vue) — thin Vue wrapper over - * `@layoutit/polycss/runtime`'s shared gizmo drag, geometry, and fallback + * `@layoutit/polycss/internal`'s shared gizmo drag, geometry, and fallback * hit-test engine. */ import { @@ -11,11 +11,13 @@ import { onMounted, ref, computed, + watch, type ComputedRef, type PropType, type Ref, } from "vue"; import type { Vec3 } from "@layoutit/polycss-core"; +import type { GizmoMode } from "@layoutit/polycss/runtime"; import { RING_MASK_INNER_RATIO, RING_MASK_OUTER_RATIO, @@ -27,11 +29,10 @@ import { startDeclarativeRingDrag, type DeclarativeGizmoDragState, type GizmoArrowSpec, - type GizmoMode, type GizmoPlaneSpec, type GizmoRingSpec, type TransformGizmoCache, -} from "@layoutit/polycss/runtime"; +} from "@layoutit/polycss/internal"; import { PolyMesh } from "../scene/PolyMesh"; import type { PolyMeshHandle, PolyPointerEvent } from "../scene/events"; import { PolyCameraContextKey } from "../camera"; @@ -169,14 +170,25 @@ export const PolyTransformControls = defineComponent({ } }); + let activeDragCancel: (() => void) | null = null; + + watch([target, () => props.enabled], ([nextTarget, nextEnabled]) => { + if (!nextTarget || !nextEnabled) { + activeDragCancel?.(); + activeDragCancel = null; + } + }); + onBeforeUnmount(() => { unsubscribeCamera?.(); detachFallback?.(); + activeDragCancel?.(); + activeDragCancel = null; }); function startFromMeshEvent( e: PolyPointerEvent, - run: (wrapper: HTMLElement) => void, + run: (wrapper: HTMLElement) => (() => void) | null, ): void { if (!props.enabled || !target.value) return; e.stopPropagation(); @@ -184,46 +196,47 @@ export const PolyTransformControls = defineComponent({ "[data-poly-transform-controls]", ) as HTMLElement | null; if (!wrapper) return; - run(wrapper); + activeDragCancel?.(); + activeDragCancel = run(wrapper); } function makeArrowPointerDown(spec: GizmoArrowSpec) { return (e: PolyPointerEvent) => - startFromMeshEvent(e, (wrapper) => { + startFromMeshEvent(e, (wrapper) => startDeclarativeArrowDrag( spec, wrapper, e.nativeEvent.clientX, e.nativeEvent.clientY, getDragState, - ); - }); + ), + ); } function makePlanePointerDown(spec: GizmoPlaneSpec) { return (e: PolyPointerEvent) => - startFromMeshEvent(e, (wrapper) => { + startFromMeshEvent(e, (wrapper) => startDeclarativePlaneDrag( spec, wrapper, e.nativeEvent.clientX, e.nativeEvent.clientY, getDragState, - ); - }); + ), + ); } function makeRingPointerDown(spec: GizmoRingSpec) { return (e: PolyPointerEvent) => - startFromMeshEvent(e, (wrapper) => { + startFromMeshEvent(e, (wrapper) => startDeclarativeRingDrag( spec, wrapper, e.nativeEvent.clientX, e.nativeEvent.clientY, getDragState, - ); - }); + ), + ); } function makeHoverHandlers(key: string) { diff --git a/packages/vue/src/scene/PolyMesh.ts b/packages/vue/src/scene/PolyMesh.ts index 22dde3b47..a119b773a 100644 --- a/packages/vue/src/scene/PolyMesh.ts +++ b/packages/vue/src/scene/PolyMesh.ts @@ -25,13 +25,15 @@ import type { Vec3, } from "@layoutit/polycss-core"; import { buildPolyMeshTransform } from "@layoutit/polycss-core"; +import type { + PolyMeshHandle as RuntimeMeshHandle, + TextureQuality, +} from "@layoutit/polycss/runtime"; import { clearOwnedDomNodes, renderStandaloneMeshIntoWrapper, restoreVoxelMeshClass, - type PolyMeshHandle as RuntimeMeshHandle, - type TextureQuality, -} from "@layoutit/polycss/runtime"; +} from "@layoutit/polycss/internal"; import type { UseMeshOptions } from "./useMesh"; import { useSceneContextValue } from "./sceneContext"; import { PolyCameraContextKey } from "../camera"; diff --git a/packages/vue/src/scene/PolyScene.ts b/packages/vue/src/scene/PolyScene.ts index d79581022..6ed09ff6d 100644 --- a/packages/vue/src/scene/PolyScene.ts +++ b/packages/vue/src/scene/PolyScene.ts @@ -30,7 +30,6 @@ import type { } from "@layoutit/polycss-core"; import { DEFAULT_SEAM_BLEED } from "@layoutit/polycss-core"; import { - adaptFallbackCamera, createPolyScene, injectPolyBaseStyles, type PolyMeshHandle as RuntimeMeshHandle, @@ -38,6 +37,7 @@ import { type PolyShadowOptions, type TextureQuality, } from "@layoutit/polycss/runtime"; +import { adaptFallbackCamera } from "@layoutit/polycss/internal"; import { PolyCameraContextKey } from "../camera"; import { PolySceneContextKey } from "./sceneContext"; diff --git a/packages/vue/src/scene/events.ts b/packages/vue/src/scene/events.ts index e6db808df..a8f1868ef 100644 --- a/packages/vue/src/scene/events.ts +++ b/packages/vue/src/scene/events.ts @@ -1,9 +1,10 @@ /** * Pointer event API for `` (Vue). Delegates DOM element registry and - * bounding-rect hit-testing to `@layoutit/polycss/runtime`. + * bounding-rect hit-testing to `@layoutit/polycss`. */ import type { Polygon, Vec3 } from "@layoutit/polycss-core"; -import { createMeshElementRegistry, pointInMeshElement } from "@layoutit/polycss/runtime"; +import { pointInMeshElement } from "@layoutit/polycss/runtime"; +import { createMeshElementRegistry } from "@layoutit/polycss/internal"; /** Imperative handle exposed by `` via Vue's `defineExpose`. */ export interface PolyMeshHandle { diff --git a/packages/vue/src/scene/mesh/useMeshEvents.ts b/packages/vue/src/scene/mesh/useMeshEvents.ts index 69da723e3..5114670f4 100644 --- a/packages/vue/src/scene/mesh/useMeshEvents.ts +++ b/packages/vue/src/scene/mesh/useMeshEvents.ts @@ -1,8 +1,8 @@ /** - * useMeshEvents — pointer-event synthesis over `@layoutit/polycss/runtime`'s + * useMeshEvents — pointer-event synthesis over `@layoutit/polycss/internal`'s * `buildPolyPointerEvent` and wrapper DOM handler wiring for Vue ``. */ -import { buildPolyPointerEvent } from "@layoutit/polycss/runtime"; +import { buildPolyPointerEvent } from "@layoutit/polycss/internal"; import type { PolyCameraContextValue } from "../../camera/context"; import { findPolyMeshHandle, diff --git a/packages/vue/src/select/PolySelect.ts b/packages/vue/src/select/PolySelect.ts index 9fa2dd81d..9d3b620a8 100644 --- a/packages/vue/src/select/PolySelect.ts +++ b/packages/vue/src/select/PolySelect.ts @@ -1,5 +1,5 @@ /** - * `` (Vue) — thin Vue wrapper over `@layoutit/polycss/runtime`'s + * `` (Vue) — thin Vue wrapper over `@layoutit/polycss/internal`'s * shared `createSelectionController`. */ import { @@ -16,7 +16,7 @@ import { type InjectionKey, type PropType, } from "vue"; -import { createSelectionController } from "@layoutit/polycss/runtime"; +import { createSelectionController } from "@layoutit/polycss/internal"; import { findPolyMeshHandle, findMeshUnderPoint as findMeshUnderPointShared, diff --git a/packages/vue/src/shapes/Poly.ts b/packages/vue/src/shapes/Poly.ts index ed8706348..df0d8e4a3 100644 --- a/packages/vue/src/shapes/Poly.ts +++ b/packages/vue/src/shapes/Poly.ts @@ -27,20 +27,22 @@ import type { Vec3, } from "@layoutit/polycss-core"; import { worldDirectionalLightToCss } from "@layoutit/polycss-core"; +import { + computeTextureAtlasPlanPublic, + renderPolygonsWithTextureAtlas, + type RenderTextureAtlasResult, + type TextureAtlasPlan, + type TextureQuality, +} from "@layoutit/polycss/runtime"; import { buildDirectMaterialLeafDescriptor, buildFallbackLeafDescriptor, buildPolyWrapperTransform, - computeTextureAtlasPlanPublic, isAxisAlignedRectUVs, readElementDataAttrs, readElementStyleRecord, - renderPolygonsWithTextureAtlas, syncLeafBorderShapeStyle, - type RenderTextureAtlasResult, - type TextureAtlasPlan, - type TextureQuality, -} from "@layoutit/polycss/runtime"; +} from "@layoutit/polycss/internal"; export interface PolyContext { tileSize?: number; @@ -170,11 +172,14 @@ export const Poly = defineComponent({ (next, prev) => { if (prev && prev !== next) prev.dispose(); currentResult = next; - const leaf = next?.rendered[0]?.element; - if (leaf && leaf.tagName.toLowerCase() === "s") { - next?.pagesReady?.then(() => { - if (currentResult === next) atlasTick.value += 1; - }); + const entry = next?.rendered[0]; + if (entry?.kind === "atlas") { + next?.pagesReady?.then( + () => { + if (currentResult === next) atlasTick.value += 1; + }, + () => {}, + ); } }, { immediate: true }, diff --git a/packages/vue/src/three/PolyThreeOrthographicCamera.ts b/packages/vue/src/three/PolyThreeOrthographicCamera.ts index d0b5408c9..9eb15f484 100644 --- a/packages/vue/src/three/PolyThreeOrthographicCamera.ts +++ b/packages/vue/src/three/PolyThreeOrthographicCamera.ts @@ -5,7 +5,7 @@ import { applyThreeOrthographicCameraProps as applyCameraProps, } from "@layoutit/polycss-core/three"; import type { Vector3Tuple } from "@layoutit/polycss-core/three"; -import { observeViewportHeight } from "@layoutit/polycss/runtime"; +import { observeViewportHeight } from "@layoutit/polycss/internal"; import { usePolyCamera } from "../camera/useCamera"; import { PolyCameraContextKey } from "../camera/context"; diff --git a/packages/vue/src/three/PolyThreePerspectiveCamera.ts b/packages/vue/src/three/PolyThreePerspectiveCamera.ts index e1633fb50..5925293d5 100644 --- a/packages/vue/src/three/PolyThreePerspectiveCamera.ts +++ b/packages/vue/src/three/PolyThreePerspectiveCamera.ts @@ -5,7 +5,7 @@ import { applyThreePerspectiveCameraProps as applyCameraProps, } from "@layoutit/polycss-core/three"; import type { Vector3Tuple } from "@layoutit/polycss-core/three"; -import { observeViewportHeight } from "@layoutit/polycss/runtime"; +import { observeViewportHeight } from "@layoutit/polycss/internal"; import { usePolyCamera } from "../camera/useCamera"; import { PolyCameraContextKey } from "../camera/context"; diff --git a/packages/vue/tsup.config.ts b/packages/vue/tsup.config.ts index cf9e8cdf0..f3ecf183b 100644 --- a/packages/vue/tsup.config.ts +++ b/packages/vue/tsup.config.ts @@ -10,6 +10,7 @@ export default createLibraryConfig({ "vue", "@layoutit/polycss", "@layoutit/polycss/runtime", + "@layoutit/polycss/internal", "@layoutit/polycss-core", "@layoutit/polycss-core/three", ], diff --git a/packages/workspace-aliases.mjs b/packages/workspace-aliases.mjs index c929213ee..e04f1b0e2 100644 --- a/packages/workspace-aliases.mjs +++ b/packages/workspace-aliases.mjs @@ -24,6 +24,7 @@ export const WORKSPACE_SOURCE_ENTRIES = Object.freeze({ "@layoutit/polycss-core/three": "core/src/three/index.ts", "@layoutit/polycss-core": "core/src/index.ts", "@layoutit/polycss/runtime": "polycss/src/runtime.ts", + "@layoutit/polycss/internal": "polycss/src/internal.ts", "@layoutit/polycss/elements": "polycss/src/elements/index.ts", "@layoutit/polycss/three": "polycss/src/three.ts", "@layoutit/polycss": "polycss/src/index.ts", diff --git a/website/src/components/BuilderWorkbench/components/BuilderScene.tsx b/website/src/components/BuilderWorkbench/components/BuilderScene.tsx index f238aee1a..28ea5cd05 100644 --- a/website/src/components/BuilderWorkbench/components/BuilderScene.tsx +++ b/website/src/components/BuilderWorkbench/components/BuilderScene.tsx @@ -13,7 +13,6 @@ import { PolyTransformControls, useCameraContext, } from "@layoutit/polycss-react"; -import { swallowNextClick } from "@layoutit/polycss/runtime"; import type { PolyAmbientLight, PolyDirectionalLight, @@ -24,6 +23,15 @@ import type { Vec3, } from "@layoutit/polycss-react"; import { useEffect, useMemo, useRef, type RefObject } from "react"; + +function swallowNextClick(): void { + const swallow = (e: Event): void => { + e.stopPropagation(); + e.stopImmediatePropagation(); + }; + window.addEventListener("click", swallow, { capture: true, once: true }); + setTimeout(() => window.removeEventListener("click", swallow, true), 0); +} import { meshResolutionShowsMesh, type SceneOptionsState } from "../../types"; import { FPV_PERSPECTIVE } from "../../fpv"; import { BUILDER_GROUND_SPAN, BUILDER_MAX_CAMERA_ROT_X } from "../defaults"; diff --git a/website/src/components/BuilderWorkbench/geometry/ghost.ts b/website/src/components/BuilderWorkbench/geometry/ghost.ts index 9c5dae47f..966c8f95c 100644 --- a/website/src/components/BuilderWorkbench/geometry/ghost.ts +++ b/website/src/components/BuilderWorkbench/geometry/ghost.ts @@ -1,19 +1,8 @@ /** - * Ghost bounding-box helpers for placement mode. + * Solid cuboid wireframe helper for selected-shape highlighting in `/builder`. * - * Builds the 6 face quads of the bbox cuboid directly in WORLD coords — - * the caller passes the world XY center + half-extents + height, and the - * faces come out positioned exactly where they should appear. The - * resulting PolyMesh is rendered with NO `position` / `scale` props — - * same pattern as PolyTransformControls' planar handles (which we know - * render correctly in all three planes). - * - * Earlier attempts passed polygons in model-local coords and let - * PolyMesh's `scale` + `position` transform place them. That kept - * collapsing the box to the floor — most likely because the scale+ - * position-around-bbox-center wrapping interacts with PolyCSS's - * basis chooser in a way I can't easily debug. Direct world coords - * sidestep all of that. + * Builds the 12 edge sticks of the bbox directly in WORLD coordinates so the + * resulting `` needs no `position` / `scale` wrapper transform. */ import type { Polygon } from "@layoutit/polycss-react"; @@ -36,35 +25,19 @@ export interface GhostWorldRect { hy: number; /** Total height of the bbox in WORLD units. Bottom sits at baseZ. */ height: number; - /** Base elevation in world units. Wireframe spans `baseZ` → - * `baseZ + height`. 0 for the flat floor. Used to lift the ghost - * onto an elevated terrain cell. Default 0. */ + /** Base elevation in world units. Default 0. */ baseZ?: number; } /** Solid cyan wireframe edge color. Never set CSS `opacity` on the ghost * wrapper because it would flatten the 3D context. */ -export const GHOST_COLOR = "#00d9ff"; +const GHOST_COLOR = "#00d9ff"; -/** Edge half-thickness in world units. ~0.06 world units ≈ 3 CSS px at - * BASE_TILE=50 — readable as a wireframe dot at typical zoom. */ +/** Edge half-thickness in world units (~3 CSS px at BASE_TILE=50). */ const EDGE_HALF = 0.06; -/** Approx length of a single dot in world units. */ -const DOT_LENGTH = 0.5; -/** Approx gap between consecutive dots. */ -const GAP_LENGTH = 0.5; - -export interface WireframeStyle { - edgeHalf?: number; - dotLength?: number; - gapLength?: number; -} - -/** Build the 6 axis-aligned face quads of an arbitrary cuboid using - * axisBox's vertex labelling + CCW-from-outside winding. Each face's - * surface normal points OUTWARD so PolyCSS's basis chooser keeps the - * matrix3d determinant positive (negative determinants flatten). */ +/** Build the 6 axis-aligned face quads of a cuboid with CCW-from-outside + * winding so every face's matrix3d determinant stays positive. */ function cuboidFaces( x0: number, x1: number, y0: number, y1: number, @@ -89,84 +62,8 @@ function cuboidFaces( ]; } -/** Compute the (start, end) pairs of dots along a 1D edge of `length` - * world units. Dot count adapts to length so dot SIZE stays uniform - * across edges of different lengths — short edges get fewer dots. - * Dots always include both endpoints (so corners of the bbox always - * have visible markers). */ -function dotSpans(length: number, dotLength: number = DOT_LENGTH, gapLength: number = GAP_LENGTH): Array<[number, number]> { - const pattern = dotLength + gapLength; - const count = Math.max(2, Math.round(length / pattern)); - // Distribute evenly: the centres of `count` dots sit at fractions - // i/(count-1) of the edge for i=0..count-1. - const halfDot = dotLength / 2; - const spans: Array<[number, number]> = []; - for (let i = 0; i < count; i++) { - const centre = (i / (count - 1)) * length; - const a = Math.max(0, centre - halfDot); - const b = Math.min(length, centre + halfDot); - spans.push([a, b]); - } - return spans; -} - -/** Build a dotted 12-edge wireframe of the bbox. Each edge becomes a - * run of short cuboid "dots" instead of one continuous stick, so the - * outline reads as a dashed bbox at the placement cursor. Closed - * cuboids (not flat slabs) so each dot stays 3D regardless of the - * camera angle, with axisBox winding for stable rendering. */ -export function buildGhostWireframePolygons( - rect: GhostWorldRect, - color: string = GHOST_COLOR, - style: WireframeStyle = {}, -): Polygon[] { - const { worldX, worldY, hx, hy, height } = rect; - const x0 = worldX - hx; - const x1 = worldX + hx; - const y0 = worldY - hy; - const y1 = worldY + hy; - const z0 = rect.baseZ ?? 0; - const z1 = z0 + height; - const t = style.edgeHalf ?? EDGE_HALF; - const dotLength = style.dotLength ?? DOT_LENGTH; - const gapLength = style.gapLength ?? GAP_LENGTH; - - const polys: Polygon[] = []; - - // 4 X-direction edges — dot spans run along X. - const xSpans = dotSpans(x1 - x0, dotLength, gapLength); - for (const y of [y0, y1]) { - for (const z of [z0, z1]) { - for (const [a, b] of xSpans) { - polys.push(...cuboidFaces(x0 + a, x0 + b, y - t, y + t, z - t, z + t, color)); - } - } - } - // 4 Y-direction edges — dot spans run along Y. - const ySpans = dotSpans(y1 - y0, dotLength, gapLength); - for (const x of [x0, x1]) { - for (const z of [z0, z1]) { - for (const [a, b] of ySpans) { - polys.push(...cuboidFaces(x - t, x + t, y0 + a, y0 + b, z - t, z + t, color)); - } - } - } - // 4 Z-direction edges — dot spans run along Z. - const zSpans = dotSpans(z1 - z0, dotLength, gapLength); - for (const x of [x0, x1]) { - for (const y of [y0, y1]) { - for (const [a, b] of zSpans) { - polys.push(...cuboidFaces(x - t, x + t, y - t, y + t, z0 + a, z0 + b, color)); - } - } - } - - return polys; -} - -/** Build one continuous cuboid stick for each bbox edge. This is used - * for selected-shape highlighting, where a solid cage is easier to see - * than the dotted placement preview. */ +/** Build one continuous cuboid stick for each bbox edge for selected-shape + * highlighting. */ export function buildSolidWireframePolygons( rect: GhostWorldRect, color: string = GHOST_COLOR, @@ -200,116 +97,3 @@ export function buildSolidWireframePolygons( return polys; } - -/** - * Rotate every vertex of every polygon around `pivot` so that the - * resulting world-coord polygons, once rendered through `cssPoints`' - * world→CSS axis swap, look identical to a `PolyMesh` with - * `rotation = [rotXDeg, rotYDeg, 0]`. PolyMesh's CSS transform is - * `rotateX(α) rotateY(β)` (rotateY applied to vectors first), so we - * mirror that ordering here. - * - * Because `cssPoints` swaps world-X and world-Y axes, CSS rotateX - * (which preserves CSS-X) corresponds to a world-frame rotation that - * preserves world-Y, and CSS rotateY (preserves CSS-Y) corresponds to - * a world rotation that preserves world-X — that's why the world math - * below preserves the "opposite" axis to what the CSS name suggests. - */ -export function rotatePolygonsAroundPivot( - polygons: Polygon[], - pivot: [number, number, number], - rotXDeg: number, - rotYDeg: number, -): Polygon[] { - if (rotXDeg === 0 && rotYDeg === 0) return polygons; - const rx = (rotXDeg * Math.PI) / 180; - const ry = (rotYDeg * Math.PI) / 180; - const cx = Math.cos(rx); - const sx = Math.sin(rx); - const cy = Math.cos(ry); - const sy = Math.sin(ry); - - const rotateVertex = (v: [number, number, number]): [number, number, number] => { - let x = v[0] - pivot[0]; - let y = v[1] - pivot[1]; - let z = v[2] - pivot[2]; - // CSS rotateY first (applied to vectors first). In world coords: - // preserves x, transforms (y, z). - const y1 = y * cy + z * sy; - const z1 = -y * sy + z * cy; - y = y1; z = z1; - // CSS rotateX next. In world coords: preserves y, transforms (x, z). - const x2 = x * cx - z * sx; - const z2 = x * sx + z * cx; - x = x2; z = z2; - return [x + pivot[0], y + pivot[1], z + pivot[2]]; - }; - - return polygons.map((p) => ({ - ...p, - vertices: p.vertices.map(rotateVertex), - })); -} - -/** - * Build the 6 faces of a bounding box positioned at (worldX, worldY) - * on the floor with the given half-extents and height. Vertex order - * mirrors `axisBox` in core/helpers/axesPolygons.ts — the same helper - * `` uses to render its thin cuboids in 3D. Each face's - * winding is CCW from the OUTWARD-facing side so the surface normal - * points outward and PolyCSS's basis chooser keeps the matrix3d - * determinant positive (negative determinants get treated as - * back-facing and silently flatten). - * - * All vertices are in WORLD coords; caller passes the list to a - * `` with no `position` or `scale` prop. - */ -export function buildGhostBoxPolygons(rect: GhostWorldRect, color: string = GHOST_COLOR): Polygon[] { - const { worldX, worldY, hx, hy, height } = rect; - const x0 = worldX - hx; - const x1 = worldX + hx; - const y0 = worldY - hy; - const y1 = worldY + hy; - const z0 = 0; - const z1 = height; - - // 8 corners in axisBox naming convention: c0-c3 ring around the bottom - // CCW from +Z, c4-c7 directly above them. - const c0: [number, number, number] = [x0, y0, z0]; - const c1: [number, number, number] = [x1, y0, z0]; - const c2: [number, number, number] = [x1, y1, z0]; - const c3: [number, number, number] = [x0, y1, z0]; - const c4: [number, number, number] = [x0, y0, z1]; - const c5: [number, number, number] = [x1, y0, z1]; - const c6: [number, number, number] = [x1, y1, z1]; - const c7: [number, number, number] = [x0, y1, z1]; - - return [ - { vertices: [c0, c1, c2, c3], color }, // bottom (XY at z0) — normal -Z - { vertices: [c4, c5, c6, c7], color }, // top (XY at z1) — normal +Z - { vertices: [c0, c1, c5, c4], color }, // front (XZ at y0) — normal -Y - { vertices: [c1, c2, c6, c5], color }, // right (YZ at x1) — normal +X - { vertices: [c2, c3, c7, c6], color }, // back (XZ at y1) — normal +Y - { vertices: [c3, c0, c4, c7], color }, // left (YZ at x0) — normal -X - ]; -} - -/** Compute a `GhostWorldRect` for placing a model at (worldX, worldY) - * given its model-local bbox and the auto-fit scale. `baseZ` lifts - * the wireframe off the floor for placements on elevated terrain. */ -export function ghostRectFromBbox( - bbox: Bbox, - worldX: number, - worldY: number, - fitScale: number, - baseZ: number = 0, -): GhostWorldRect { - return { - worldX, - worldY, - hx: ((bbox.maxX - bbox.minX) * fitScale) / 2, - hy: ((bbox.maxY - bbox.minY) * fitScale) / 2, - height: (bbox.maxZ - bbox.minZ) * fitScale, - baseZ, - }; -} diff --git a/website/src/components/BuilderWorkbench/geometry/terrain.ts b/website/src/components/BuilderWorkbench/geometry/terrain.ts index 417c735dc..7726e6bda 100644 --- a/website/src/components/BuilderWorkbench/geometry/terrain.ts +++ b/website/src/components/BuilderWorkbench/geometry/terrain.ts @@ -21,16 +21,10 @@ * floor — the warp emerges from sharing vertex heights. */ -import type { Polygon } from "@layoutit/polycss-react"; - /** Sparse heightmap: vertex (i, j) → elevation in world units. */ export type TerrainVertices = Map; export const vertexKey = (i: number, j: number): string => `${i},${j}`; -export function parseVertexKey(key: string): [number, number] { - const [i, j] = key.split(",").map(Number); - return [i, j]; -} /** Project a world XY to the nearest VERTEX index. Used for tools — * clicks snap to the closest grid intersection. */ @@ -43,68 +37,11 @@ export function worldToCell(worldX: number, worldY: number, cellSize: number): [ return [Math.floor(worldX / cellSize), Math.floor(worldY / cellSize)]; } -/** Build the polygons for every cell that has at least one elevated - * corner. Each such cell renders as a single tilted quad spanning - * (i, j) → (i+1, j+1) with the actual corner heights. */ -export interface TerrainRenderOptions { - vertices: TerrainVertices; - cellSize: number; - color?: string; -} - -export function buildTerrainPolygons(opts: TerrainRenderOptions): Polygon[] { - const color = opts.color ?? "#12343c"; - const polys: Polygon[] = []; - - // Walk the set of CELLS that have at least one non-zero corner. A - // vertex is shared by up to 4 cells (its NW, NE, SE, SW), so for - // each non-zero vertex we mark all 4 touching cells dirty. - const dirtyCells = new Set(); - for (const key of opts.vertices.keys()) { - const [i, j] = parseVertexKey(key); - dirtyCells.add(vertexKey(i - 1, j - 1)); - dirtyCells.add(vertexKey(i, j - 1)); - dirtyCells.add(vertexKey(i - 1, j)); - dirtyCells.add(vertexKey(i, j)); - } - - const getZ = (i: number, j: number): number => opts.vertices.get(vertexKey(i, j)) ?? 0; - - for (const cellKey of dirtyCells) { - const [ci, cj] = parseVertexKey(cellKey); - const x0 = ci * opts.cellSize; - const x1 = (ci + 1) * opts.cellSize; - const y0 = cj * opts.cellSize; - const y1 = (cj + 1) * opts.cellSize; - const z00 = getZ(ci, cj); - const z10 = getZ(ci + 1, cj); - const z11 = getZ(ci + 1, cj + 1); - const z01 = getZ(ci, cj + 1); - const p00: [number, number, number] = [x0, y0, z00]; - const p10: [number, number, number] = [x1, y0, z10]; - const p11: [number, number, number] = [x1, y1, z11]; - const p01: [number, number, number] = [x0, y1, z01]; - // Split each cell into 2 triangles along the (p00 → p11) diagonal. - // A non-planar quad would be auto-snapped by PolyCSS (see AGENTS.md - // "Coplanarity is a hard requirement at render time…") which opens - // visible seams with neighbouring cells; triangles are inherently - // planar so the warped surface stays gap-free. CCW from +Z on both - // tris so the surface normal points up. - polys.push({ vertices: [p00, p10, p11], color }); - polys.push({ vertices: [p00, p11, p01], color }); - } - - return polys; -} - /** Sample the heightmap at a continuous world (x, y) and return both * the surface elevation z AND the slope gradients dz/dx, dz/dy at * that point. The interpolation matches the rendered triangulation - * (cells are split along the (p00 → p11) diagonal, see - * `buildTerrainPolygons`) so a placement queried via this function - * lands exactly on the visible surface. Both gradients are constant - * within each triangle, so a placement on a slope reads the same - * tilt anywhere inside that triangle. */ + * (cells split along the (p00 → p11) diagonal) so a placement queried + * via this function lands on the visible surface. */ export interface TerrainSample { z: number; slopeX: number; diff --git a/website/src/components/BuilderWorkbench/scenes.ts b/website/src/components/BuilderWorkbench/scenes.ts deleted file mode 100644 index 33174ee68..000000000 --- a/website/src/components/BuilderWorkbench/scenes.ts +++ /dev/null @@ -1,114 +0,0 @@ -/** - * Builder scene presets — composite layouts that load multiple model - * presets at once with prebuilt relative positions/rotations/scales. - * - * Scene items reference model presets by FILE (relative to - * `website/public/gallery/glb/`) and the matching preset ID is derived - * via `presetIdFromFile`. This keeps the scene definitions - * human-readable AND impossible to desync from the preset list — the - * filename is the single source of truth. - * - * Positions are in WORLD units (post `fitScale` normalization, models - * are ~NORMALIZED_MAX_DIM = 8 units wide). X is right, Y is depth (back), - * Z snaps to floor via `placeMeshOnFloor`. Rotation is in degrees (Euler - * XYZ). Scale is a multiplier on the auto-fit scale; 1 keeps the - * normalized size, 1.5 makes it 50 % larger, etc. - */ - -import type { SceneOptionsState } from "../types"; -import { presetIdFromFile } from "../GalleryWorkbench/presets/presetBuilders"; - -export interface ScenePresetItem { - presetId: string; - /** Desired world position (X, Y, Z). Z is usually 0 (floor); the - * builder's `placeMeshOnFloor` adds vertical correction so the - * visible bottom of the mesh lands on the ground plane. */ - position: [number, number, number]; - /** Euler XYZ in degrees. Defaults to [0, 0, 0]. */ - rotation?: [number, number, number]; - /** Multiplier on the auto-fit scale. Defaults to 1. */ - scale?: number; -} - -export interface ScenePreset { - id: string; - label: string; - category: string; - items: ScenePresetItem[]; - /** Patch applied to `sceneOptions` when the scene loads. Lets a - * scene declare "I want the ground plane visible" or similar without - * the user having to flip the toggle in the dock. Applied via - * `updateScene` in `handleAddScene` before the items are placed. */ - defaultSceneOptions?: Partial; -} - -/** Scene IDs are prefixed so BuilderWorkbench's click handler can route - * them to `handleAddScene` instead of `handleAddPreset`. */ -export const SCENE_PRESET_ID_PREFIX = "scene-"; - -/** Preset ID for a GLB file under `public/gallery/glb/`. */ -const glb = (file: string): string => presetIdFromFile("glb", file); - -/** Single city block — buildings arranged around a small empty plot, - * all facing outward toward the surrounding streets. Roughly 3×3 - * building footprints (~25×25 world units) so it sits comfortably - * inside the default render distance of 40. */ -export const CITY_BLOCK: ScenePreset = { - id: `${SCENE_PRESET_ID_PREFIX}city-block`, - label: "City Block", - category: "Scenes", - items: [ - // Back row (north edge of the block) — taller anchors facing outward - { presetId: glb("city/Skyscraper.glb"), position: [0, 10, 0], rotation: [0, 0, 180] }, - { presetId: glb("city/Large Building.glb"), position: [-10, 10, 0], rotation: [0, 0, 180] }, - { presetId: glb("city/Skyscraper.glb"), position: [10, 10, 0], rotation: [0, 0, 180] }, - - // Side rows — small/low buildings facing east and west - { presetId: glb("city/Small Building.glb"), position: [-10, 0, 0], rotation: [0, 0, 90] }, - { presetId: glb("city/Small Building.glb"), position: [10, 0, 0], rotation: [0, 0, -90] }, - - // Front row (south edge) — mid-height buildings facing the camera default - { presetId: glb("city/Large Building.glb"), position: [-10, -10, 0] }, - { presetId: glb("city/Small Building.glb"), position: [0, -10, 0] }, - { presetId: glb("city/Large Building.glb"), position: [10, -10, 0] }, - ], -}; - -/** Roads + trees on a big ground plane — no buildings. A north/south - * road and an east/west road cross at the origin; trees + a few props - * are scattered on the surrounding "lawn". The scene asks for - * `showGround: true` via defaultSceneOptions so the ground plane - * (200 world units in builder) sits underneath the road tiles. */ -export const CITY_STREET: ScenePreset = { - id: `${SCENE_PRESET_ID_PREFIX}city-street`, - label: "City Roads", - category: "Scenes", - defaultSceneOptions: { - showGround: true, - }, - items: [ - // North–south road tiles through the origin - { presetId: glb("urban/Road Bits.glb"), position: [0, -24, 0] }, - { presetId: glb("urban/Road Bits.glb"), position: [0, -16, 0] }, - { presetId: glb("urban/Road Bits.glb"), position: [0, -8, 0] }, - { presetId: glb("urban/Road Bits.glb"), position: [0, 0, 0] }, - { presetId: glb("urban/Road Bits.glb"), position: [0, 8, 0] }, - { presetId: glb("urban/Road Bits.glb"), position: [0, 16, 0] }, - { presetId: glb("urban/Road Bits.glb"), position: [0, 24, 0] }, - - // East–west road tiles (rotated 90 around Z) crossing at origin - { presetId: glb("urban/Road Bits.glb"), position: [-24, 0, 0], rotation: [0, 0, 90] }, - { presetId: glb("urban/Road Bits.glb"), position: [-16, 0, 0], rotation: [0, 0, 90] }, - { presetId: glb("urban/Road Bits.glb"), position: [-8, 0, 0], rotation: [0, 0, 90] }, - { presetId: glb("urban/Road Bits.glb"), position: [8, 0, 0], rotation: [0, 0, 90] }, - { presetId: glb("urban/Road Bits.glb"), position: [16, 0, 0], rotation: [0, 0, 90] }, - { presetId: glb("urban/Road Bits.glb"), position: [24, 0, 0], rotation: [0, 0, 90] }, - - // A couple of cars on the road just for life - { presetId: glb("urban/Car.glb"), position: [0, -12, 0] }, - { presetId: glb("urban/Police Car.glb"), position: [0, 12, 0], rotation: [0, 0, 180] }, - { presetId: glb("urban/SUV.glb"), position: [-12, 0, 0], rotation: [0, 0, 90] }, - ], -}; - -export const SCENE_PRESETS: ScenePreset[] = [CITY_STREET, CITY_BLOCK]; diff --git a/website/src/components/GalleryWorkbench/GalleryWorkbench.tsx b/website/src/components/GalleryWorkbench/GalleryWorkbench.tsx index a91a91141..eaf263927 100644 --- a/website/src/components/GalleryWorkbench/GalleryWorkbench.tsx +++ b/website/src/components/GalleryWorkbench/GalleryWorkbench.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import type { PolyMeshHandle as ReactPolyMeshHandle, Polygon, @@ -7,8 +7,7 @@ import type { import type { PolyMeshHandle as VanillaPolyMeshHandle, } from "@layoutit/polycss"; -import { exportPolySceneSnapshot, normalizeSolidColorKey as inspectorColorKey, optimizeAnimatedMeshPolygons, parsePureColor } from "@layoutit/polycss"; -import { screenToWorldOnSphere } from "@layoutit/polycss-core"; +import { exportPolySceneSnapshot, normalizeSolidColorKey as inspectorColorKey, optimizeAnimatedMeshPolygons } from "@layoutit/polycss"; import type { InspectorColorGroup, InspectorMesh } from "../Inspector"; import { VanillaScene, type VanillaSceneTransientHandle } from "../VanillaScene"; import { ReactScene } from "../ReactScene"; @@ -25,6 +24,7 @@ import { import { ModelsSidebar } from "../ModelsSidebar"; import { DropOverlay } from "../DropOverlay"; import { StatsOverlay } from "../StatsOverlay"; +import { openCodePen } from "../helpers/codePen"; import { activeMeshResolution, POLYCSS_DEFAULT_PERSPECTIVE, @@ -43,20 +43,29 @@ import { GALLERY_BUCKET_ORDER, galleryBucketForPreset, galleryBucketRank, - stripParenthesizedText, } from "./presets"; import { EMPTY_METRICS, measureDom, } from "./helpers/domMetrics"; import { - applyDebugMatrixPrecision, - applyDebugBorderShapePrecision, - applyDebugTriangleBrushPrecision, - applyDebugSolidColorHex, - applyDebugInlineStyleOrder, - applyDebugInlineStyleMinify, -} from "./helpers/debugPrecision"; + ALL_PRESET_IDS, + PRESET_PICKER_ITEMS, + applyGalleryDebugDom, + compareInspectorColors, + parserDefaultsFor, + parserStateFor, + polygonHasTextureData, + polygonHasTexturePaint, + presetPickerItem, + randomPreset, + resolveInitialPreset, + responsiveShadowMaxExtend, + responsiveShadowPreviewMaxExtend, + sceneDefaultsFor, + sceneDefaultsForPresetId, + withSolidMaterials, +} from "./helpers/galleryDefaults"; import { defaultZoomForModel } from "./helpers/smartDefaults"; import { directionalFromOptions, ambientFromOptions } from "./helpers/lighting"; import { @@ -65,7 +74,6 @@ import { firstSelectableAnimationValue, hasAnimationValue, } from "./helpers/animationClips"; -import { responsiveZoomScaleForViewport } from "./helpers/responsivePresentation"; import { useDroppedFiles, usePresetLoader, @@ -76,631 +84,14 @@ import { setRoutePresetId, setRouteSceneOptions, clearRouteSceneOptions, - routeInitialPresetId, routeInitialSceneOptions, routeHasSceneOptions, } from "./hooks"; +import { useLightRotationDrag, useResponsiveViewportZoomScale } from "./hooks/useLightRotationDrag"; import { useFpvHost } from "../fpv"; -import type { ObjParseOptions, GltfParseOptions, VoxParseOptions, StlParseOptions } from "@layoutit/polycss"; type MobileGalleryPanel = "models" | "controls" | null; -function presetPickerItem(preset: PresetModel, local = false) { - const label = local ? `Dropped: ${stripParenthesizedText(preset.label)}` : stripParenthesizedText(preset.label); - const category = galleryBucketForPreset(preset); - return { - id: preset.id, - label, - category, - searchText: [ - label, - preset.label, - category, - preset.category, - preset.kind, - preset.attribution?.creator, - preset.attribution?.license, - ].filter(Boolean).join(" ").toLowerCase(), - }; -} - -const PRESET_PICKER_ITEMS = PRESETS.map((preset) => presetPickerItem(preset)); -const ALL_PRESET_IDS = PRESETS.map((p) => p.id); - -const DEFAULT_SCENE: SceneOptionsState = { - renderer: "vanilla", - animationPaused: false, - animationTimeScale: 1, - autoCenter: true, - interactive: true, - animate: false, - showAxes: false, - selection: false, - hoverEffects: false, - showLight: false, - zoom: PRESETS[0].zoom ?? 0.35, - rotX: PRESETS[0].rotX ?? 65, - rotY: PRESETS[0].rotY ?? 45, - perspective: undefined, - lightAzimuth: 40, - lightElevation: 45, - lightIntensity: 4.5, - lightColor: "#ffffff", - ambientIntensity: 0.55, - ambientColor: "#ffffff", - textureLighting: "baked", - textureQuality: "auto", - solidMaterials: false, - matrixPrecision: "exact", - borderShapePrecision: "exact", - meshResolution: "lossy", - interiorFill: false, - outlinePolygons: false, - dragMode: "orbit", - target: [0, 0, 0], - disableStrategies: [], - castShadow: false, - selfShadow: false, - shadowMaxExtend: 2000, - shadowParametric: true, - shadowDefinition: 35, - shadowStyle: "vector", - shadowFollowAnimation: true, - shadowOpacity: 0.25, - showGround: false, - groundColor: "#7d848e", - fpvLook: true, - fpvMove: true, - fpvJump: true, - fpvCrouch: true, - fpvMoveSpeed: 30, - fpvJumpVelocity: 25, - fpvGravity: 60, - fpvEyeHeight: 6, - fpvCrouchHeight: 3, - fpvLookSensitivity: 0.15, - fpvInvertY: false, - fpvRenderDistance: 40, - snapToGrid: true, - gridResolution: 5, - gridTone: "gray", -}; - -const DEFAULT_PARSER: ParserOptionsState = { - targetSize: 60, - defaultColor: "#8b95a1", -}; - -const LIGHT_HELPER_TILE = 50; -const LIGHT_HELPER_SELECTOR = ".dn-light-helper"; -const RESPONSIVE_SHADOW_EXTEND_BASE = 3200; -const RESPONSIVE_SHADOW_EXTEND_MIN = 2000; -const RESPONSIVE_SHADOW_PREVIEW_EXTEND_BASE = 1800; -const RESPONSIVE_SHADOW_PREVIEW_EXTEND_MIN = 800; - -function responsiveCappedShadowMaxExtend( - value: number, - viewportScale: number, - base: number, - min: number, -): number { - if (viewportScale >= 0.995) return value; - const cap = Math.max( - min, - Math.round(base * viewportScale), - ); - return Math.min(value, cap); -} - -function responsiveShadowMaxExtend(value: number, viewportScale: number): number { - return responsiveCappedShadowMaxExtend( - value, - viewportScale, - RESPONSIVE_SHADOW_EXTEND_BASE, - RESPONSIVE_SHADOW_EXTEND_MIN, - ); -} - -function responsiveShadowPreviewMaxExtend(value: number, viewportScale: number): number { - return responsiveCappedShadowMaxExtend( - value, - viewportScale, - RESPONSIVE_SHADOW_PREVIEW_EXTEND_BASE, - RESPONSIVE_SHADOW_PREVIEW_EXTEND_MIN, - ); -} - -function initialResponsiveZoomScale(): number { - if (typeof window === "undefined") return 1; - return responsiveZoomScaleForViewport(window.innerWidth, window.innerHeight); -} - -function useResponsiveViewportZoomScale( - viewportRef: RefObject, -): number { - const [scale, setScale] = useState(initialResponsiveZoomScale); - - useEffect(() => { - const viewport = viewportRef.current; - if (!viewport) return; - - const updateScale = (width: number, height: number): void => { - const next = responsiveZoomScaleForViewport(width, height); - setScale((current) => Math.abs(current - next) < 0.005 ? current : next); - }; - const readScale = (): void => { - const rect = viewport.getBoundingClientRect(); - updateScale(rect.width, rect.height); - }; - - readScale(); - window.addEventListener("resize", readScale); - - let observer: ResizeObserver | null = null; - if (typeof ResizeObserver !== "undefined") { - observer = new ResizeObserver((entries) => { - const rect = entries[0]?.contentRect; - if (rect) updateScale(rect.width, rect.height); - else readScale(); - }); - observer.observe(viewport); - } - - return () => { - window.removeEventListener("resize", readScale); - observer?.disconnect(); - }; - }, [viewportRef]); - - return scale; -} - -interface ScreenPoint { - x: number; - y: number; -} - -function wrapDegrees(value: number): number { - return ((value % 360) + 360) % 360; -} - -function clampLightElevation(value: number): number { - return Math.max(0, Math.min(90, value)); -} - -function lightDirectionFromAngles(azimuth: number, elevation: number): ReactVec3 { - const az = (azimuth * Math.PI) / 180; - const el = (elevation * Math.PI) / 180; - const cosEl = Math.cos(el); - return [ - cosEl * Math.sin(az), - cosEl * Math.cos(az), - Math.sin(el), - ]; -} - -function projectLightDirectionToScreen( - direction: ReactVec3, - sceneOptions: SceneOptionsState, - radiusCss: number, -): ReactVec3 { - const [dx, dy, dz] = direction; - const x = dx * radiusCss; - const y = dy * radiusCss; - const z = dz * radiusCss; - const rotY = (sceneOptions.rotY * Math.PI) / 180; - const rotX = (sceneOptions.rotX * Math.PI) / 180; - const cosY = Math.cos(rotY); - const sinY = Math.sin(rotY); - const cosX = Math.cos(rotX); - const sinX = Math.sin(rotX); - const x1 = x * cosY - y * sinY; - const y1 = x * sinY + y * cosY; - const y2 = y1 * cosX - z * sinX; - const z2 = y1 * sinX + z * cosX; - return [x1 * sceneOptions.zoom, y2 * sceneOptions.zoom, z2 * sceneOptions.zoom]; -} - -function lightAnglesFromScreenOffset( - offset: ScreenPoint, - sceneOptions: SceneOptionsState, - radiusCss: number, -): { lightAzimuth: number; lightElevation: number } { - const zoomedRadius = Math.max(1, radiusCss * Math.max(0.001, sceneOptions.zoom)); - let qx = offset.x / zoomedRadius; - let qy = offset.y / zoomedRadius; - const len = Math.hypot(qx, qy); - if (len > 1) { - qx /= len; - qy /= len; - } - - const currentDirection = lightDirectionFromAngles( - sceneOptions.lightAzimuth, - sceneOptions.lightElevation, - ); - const currentProjected = projectLightDirectionToScreen(currentDirection, sceneOptions, 1); - const qzSign = currentProjected[2] >= 0 ? 1 : -1; - const qz = qzSign * Math.sqrt(Math.max(0, 1 - qx * qx - qy * qy)); - - const rotY = (sceneOptions.rotY * Math.PI) / 180; - const rotX = (sceneOptions.rotX * Math.PI) / 180; - const cosY = Math.cos(rotY); - const sinY = Math.sin(rotY); - const cosX = Math.cos(rotX); - const sinX = Math.sin(rotX); - - const x1 = qx; - const y1 = qy * cosX + qz * sinX; - const z = -qy * sinX + qz * cosX; - const dx = x1 * cosY + y1 * sinY; - const dy = -x1 * sinY + y1 * cosY; - const dz = Math.max(-1, Math.min(1, z)); - return { - lightAzimuth: wrapDegrees((Math.atan2(dx, dy) * 180) / Math.PI), - lightElevation: clampLightElevation((Math.asin(dz) * 180) / Math.PI), - }; -} - -function elementScreenCenter(element: HTMLElement): ScreenPoint { - const leaves = Array.from(element.querySelectorAll("b,i,s,u")); - const rects = (leaves.length > 0 ? leaves : [element]) - .map((el) => el.getBoundingClientRect()) - .filter((rect) => rect.width > 0 || rect.height > 0); - if (rects.length === 0) { - const rect = element.getBoundingClientRect(); - return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }; - } - const minX = Math.min(...rects.map((rect) => rect.left)); - const maxX = Math.max(...rects.map((rect) => rect.right)); - const minY = Math.min(...rects.map((rect) => rect.top)); - const maxY = Math.max(...rects.map((rect) => rect.bottom)); - return { x: (minX + maxX) / 2, y: (minY + maxY) / 2 }; -} - -function applyGalleryDebugDom(root: HTMLElement, options: SceneOptionsState): void { - applyDebugMatrixPrecision(root, options.matrixPrecision); - applyDebugBorderShapePrecision(root, options.borderShapePrecision); - applyDebugTriangleBrushPrecision(root); - applyDebugSolidColorHex(root); - applyDebugInlineStyleOrder(root); - applyDebugInlineStyleMinify(root); -} - -function useLightRotationDrag( - viewportRef: RefObject, - sceneOptions: SceneOptionsState, - helperScale: number, - helperTarget: [number, number, number], - gizmoDragging: boolean, - onCommitScene: (partial: Partial) => void, - canPreviewSceneOptions: (options: SceneOptionsState) => boolean, - onPreviewSceneOptions: (options: SceneOptionsState) => void, -): void { - const sceneOptionsRef = useRef(sceneOptions); - const helperScaleRef = useRef(helperScale); - const helperTargetRef = useRef(helperTarget); - const gizmoDraggingRef = useRef(gizmoDragging); - const onCommitSceneRef = useRef(onCommitScene); - const canPreviewSceneOptionsRef = useRef(canPreviewSceneOptions); - const onPreviewSceneOptionsRef = useRef(onPreviewSceneOptions); - sceneOptionsRef.current = sceneOptions; - helperScaleRef.current = helperScale; - helperTargetRef.current = helperTarget; - gizmoDraggingRef.current = gizmoDragging; - onCommitSceneRef.current = onCommitScene; - canPreviewSceneOptionsRef.current = canPreviewSceneOptions; - onPreviewSceneOptionsRef.current = onPreviewSceneOptions; - - useEffect(() => { - const viewport = viewportRef.current; - if (!viewport) return; - - let activePointerId: number | null = null; - let sphereRadius = 1; // world units - let previewRaf = 0; - let dragOptions: SceneOptionsState | null = null; - let pendingPreviewOptions: SceneOptionsState | null = null; - let pendingCommit: Pick | null = null; - - const flushPreview = (): void => { - previewRaf = 0; - const options = pendingPreviewOptions; - pendingPreviewOptions = null; - if (options) onPreviewSceneOptionsRef.current(options); - }; - - const schedulePreview = (options: SceneOptionsState): void => { - pendingPreviewOptions = options; - if (!previewRaf) previewRaf = requestAnimationFrame(flushPreview); - }; - - const cancelPreview = (): void => { - if (previewRaf) cancelAnimationFrame(previewRaf); - previewRaf = 0; - pendingPreviewOptions = null; - }; - - const helperDragEnabled = (): boolean => { - const options = sceneOptionsRef.current; - return options.interactive && options.showLight && !gizmoDraggingRef.current; - }; - - /** - * Pixel-perfect drag via inverse projection from screen → 3D world point - * on the helper sphere (radius = helperScale × 0.7 around helperTarget). - * Mirrors the bench's three-parity drag handler exactly. The post-parity - * vanilla camera treats `zoom` as px-per-world-unit, so the legacy - * unitless `sceneOptions.zoom` is scaled by `LIGHT_HELPER_TILE` here to - * match what the renderer is actually using. - */ - const computeAnglesFromCursor = ( - options: SceneOptionsState, - clientX: number, - clientY: number, - ): { lightAzimuth: number; lightElevation: number } | null => { - const rect = viewport.getBoundingClientRect(); - // Scene autoCenter adds the bbox center (= helperTarget) to the - // configured `target` before computing the scene-root translate, so the - // effective look-at point seen by the renderer is target + helperTarget. - // screenToWorldOnSphere needs that same effective target to inverse- - // project the cursor consistently with what's actually on screen. - const ht = helperTargetRef.current; - const t = options.target as ReactVec3; - const camArg = { - rotX: options.rotX, - rotY: options.rotY, - // sceneOptions.zoom is the post-parity px-per-world-unit value the - // post-parity camera receives directly (after VanillaScene's - // LEGACY_ZOOM_COMPAT multiplier, which translates the workbench - // slider's unitless value into px/u). We use the same multiplied - // value here so the inverse-projection matches the actual rendered - // scale. - zoom: options.zoom * LIGHT_HELPER_TILE, - target: [t[0] + ht[0], t[1] + ht[1], t[2] + ht[2]] as ReactVec3, - }; - const hit = screenToWorldOnSphere({ - camera: camArg as unknown as Parameters[0]["camera"], - tileSize: LIGHT_HELPER_TILE, - viewportCenterX: rect.left + rect.width / 2, - viewportCenterY: rect.top + rect.height / 2, - mouseX: clientX, - mouseY: clientY, - sphereCenter: helperTargetRef.current, - sphereRadius, - }); - if (!hit) return null; - const target = helperTargetRef.current; - const ox = hit[0] - target[0]; - const oy = hit[1] - target[1]; - const oz = hit[2] - target[2]; - const len = Math.hypot(ox, oy, oz) || 1; - const nx = ox / len, ny = oy / len, nz = oz / len; - // direction-from-angles convention (lightDirectionFromAngles above): - // dir = [cos(el)*sin(az), cos(el)*cos(az), sin(el)] - // So azimuth from XY-plane bearing, elevation from Z. - return { - lightAzimuth: wrapDegrees((Math.atan2(nx, ny) * 180) / Math.PI), - lightElevation: clampLightElevation((Math.asin(Math.max(-1, Math.min(1, nz))) * 180) / Math.PI), - }; - }; - - const stopDrag = (event: PointerEvent): void => { - if (activePointerId !== event.pointerId) return; - const commit = pendingCommit; - if (pendingPreviewOptions) { - if (previewRaf) cancelAnimationFrame(previewRaf); - flushPreview(); - } - if (commit) onCommitSceneRef.current(commit); - activePointerId = null; - dragOptions = null; - pendingCommit = null; - cancelPreview(); - viewport.classList.remove("is-light-rotating"); - try { viewport.releasePointerCapture(event.pointerId); } catch { /* ignore */ } - }; - - const onPointerDown = (event: PointerEvent): void => { - if (activePointerId !== null) return; - if (event.isPrimary === false) return; - if (event.button !== 0) return; - const target = event.target instanceof Element ? event.target : null; - if (target?.closest("[data-poly-transform-controls]")) return; - const helper = target?.closest(LIGHT_HELPER_SELECTOR) ?? null; - if (!helper || !helperDragEnabled()) return; - event.preventDefault(); - event.stopPropagation(); - activePointerId = event.pointerId; - dragOptions = sceneOptionsRef.current; - pendingCommit = null; - // World-unit sphere radius — matches the helper's - // `helperScale × 0.7` distance used by ReactScene/VanillaScene when - // they place the helper octahedron. - sphereRadius = Math.max(0.001, helperScaleRef.current * 0.7); - viewport.classList.add("is-light-rotating"); - try { viewport.setPointerCapture(event.pointerId); } catch { /* ignore */ } - }; - - const onPointerMove = (event: PointerEvent): void => { - if (activePointerId !== event.pointerId) return; - if (!helperDragEnabled()) { - stopDrag(event); - return; - } - event.preventDefault(); - const baseOptions = dragOptions ?? sceneOptionsRef.current; - const nextAngles = computeAnglesFromCursor(baseOptions, event.clientX, event.clientY); - if (!nextAngles) return; - if (!canPreviewSceneOptionsRef.current(baseOptions)) { - onCommitSceneRef.current(nextAngles); - dragOptions = { ...baseOptions, ...nextAngles }; - pendingCommit = null; - return; - } - const nextOptions = { ...baseOptions, ...nextAngles }; - dragOptions = nextOptions; - pendingCommit = nextAngles; - schedulePreview(nextOptions); - }; - - viewport.addEventListener("pointerdown", onPointerDown, { capture: true }); - viewport.addEventListener("pointermove", onPointerMove); - viewport.addEventListener("pointerup", stopDrag); - viewport.addEventListener("pointercancel", stopDrag); - return () => { - viewport.removeEventListener("pointerdown", onPointerDown, { capture: true }); - viewport.removeEventListener("pointermove", onPointerMove); - viewport.removeEventListener("pointerup", stopDrag); - viewport.removeEventListener("pointercancel", stopDrag); - viewport.classList.remove("is-light-rotating"); - cancelPreview(); - }; - }, [viewportRef]); -} - -function parserDefaultsFor(model: PresetModel): Partial { - const options = model.options as (ObjParseOptions & GltfParseOptions & VoxParseOptions & StlParseOptions) | undefined; - return { - ...(typeof options?.targetSize === "number" ? { targetSize: options.targetSize } : {}), - ...(typeof options?.defaultColor === "string" ? { defaultColor: options.defaultColor } : {}), - }; -} - -function randomPreset(): PresetModel { - return PRESETS[Math.floor(Math.random() * PRESETS.length)] ?? PRESETS[0]; -} - -function sceneDefaultsFor(model: PresetModel): SceneOptionsState { - return { - ...DEFAULT_SCENE, - zoom: model.zoom ?? DEFAULT_SCENE.zoom, - rotX: model.rotX ?? DEFAULT_SCENE.rotX, - rotY: model.rotY ?? DEFAULT_SCENE.rotY, - }; -} - -function sceneDefaultsForPresetId(id: string): SceneOptionsState { - return sceneDefaultsFor(PRESETS.find((preset) => preset.id === id) ?? PRESETS[0]); -} - -function parserStateFor(model: PresetModel): ParserOptionsState { - return { - ...DEFAULT_PARSER, - ...parserDefaultsFor(model), - }; -} - -function withSolidMaterials(polygons: Polygon[], fallbackColor: string): Polygon[] { - return polygons.map((polygon) => { - if (!polygonHasTextureData(polygon)) { - return polygon; - } - return { - ...polygon, - texture: undefined, - material: undefined, - uvs: undefined, - textureTriangles: undefined, - color: polygon.color ?? fallbackColor, - }; - }); -} - -function polygonHasTextureData(polygon: Polygon): boolean { - return Boolean( - polygonHasTexturePaint(polygon) || - polygon.uvs?.length - ); -} - -function polygonHasTexturePaint(polygon: Polygon): boolean { - return Boolean(polygon.texture || polygon.material?.texture || polygon.textureTriangles?.length); -} - -interface InspectorColorSortKey { - bucket: number; - hue: number; - saturation: number; - value: number; - label: string; -} - -function inspectorColorSortKey(color: string): InspectorColorSortKey { - const parsed = parsePureColor(color); - if (!parsed) return { bucket: 2, hue: 0, saturation: 0, value: 0, label: color }; - const [r, g, b] = parsed.rgb.map((channel) => Math.max(0, Math.min(255, channel)) / 255); - const max = Math.max(r, g, b); - const min = Math.min(r, g, b); - const delta = max - min; - const saturation = max === 0 ? 0 : delta / max; - let hue = 0; - if (delta !== 0) { - if (max === r) hue = 60 * (((g - b) / delta) % 6); - else if (max === g) hue = 60 * ((b - r) / delta + 2); - else hue = 60 * ((r - g) / delta + 4); - } - if (hue < 0) hue += 360; - const neutral = saturation < 0.08; - return { - bucket: neutral ? 0 : 1, - hue: neutral ? 0 : hue, - saturation: neutral ? 0 : saturation, - value: max, - label: color, - }; -} - -function compareInspectorColors(a: string, b: string): number { - const ak = inspectorColorSortKey(a); - const bk = inspectorColorSortKey(b); - return ( - ak.bucket - bk.bucket || - ak.hue - bk.hue || - bk.saturation - ak.saturation || - ak.value - bk.value || - ak.label.localeCompare(bk.label) - ); -} - -function resolveInitialPreset(): PresetModel { - const id = routeInitialPresetId(ALL_PRESET_IDS); - return (id ? PRESETS.find((p) => p.id === id) : null) ?? randomPreset(); -} - -function codePenPayload(snapshotHtml: string, title: string): string { - const parsed = new DOMParser().parseFromString(snapshotHtml, "text/html"); - const css = Array.from(parsed.querySelectorAll("style")) - .map((style) => style.textContent ?? "") - .filter(Boolean) - .join("\n\n"); - const html = parsed.body.innerHTML.trim() || snapshotHtml; - return JSON.stringify({ - title, - html, - css, - editors: "100", - layout: "left", - }); -} - -function openCodePen(html: string, title: string, target: string): void { - const form = document.createElement("form"); - const input = document.createElement("input"); - form.action = "https://codepen.io/pen/define"; - form.method = "POST"; - form.target = target; - form.setAttribute("rel", "noopener noreferrer"); - form.style.display = "none"; - input.type = "hidden"; - input.name = "data"; - input.value = codePenPayload(html, title); - form.appendChild(input); - document.body.appendChild(form); - form.submit(); - form.remove(); -} - export default function GalleryWorkbench() { const [initialPreset] = useState(resolveInitialPreset); const [initialRouteSceneOptions] = useState(routeInitialSceneOptions); diff --git a/website/src/components/GalleryWorkbench/helpers/debugPrecision.ts b/website/src/components/GalleryWorkbench/helpers/debugPrecision.ts index ffee63093..440f7b3a3 100644 --- a/website/src/components/GalleryWorkbench/helpers/debugPrecision.ts +++ b/website/src/components/GalleryWorkbench/helpers/debugPrecision.ts @@ -1,8 +1,18 @@ import { parsePureColor } from "@layoutit/polycss-react"; -import { setInlineStyleProperty } from "@layoutit/polycss/runtime"; import type { MatrixPrecision, BorderShapePrecision } from "../types"; import { getInlineStyleDeclaration } from "./cssValues"; +function setInlineStyleProperty(el: HTMLElement, property: string, value: string): void { + const current = el.getAttribute("style") ?? ""; + const declaration = `${property}:${value}`; + const escaped = property.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const pattern = new RegExp(`(^|;)\\s*${escaped}\\s*:[^;]*`, "i"); + const next = pattern.test(current) + ? current.replace(pattern, (_match, prefix: string) => `${prefix}${declaration}`) + : `${current}${current.trim() && !current.trim().endsWith(";") ? ";" : ""}${declaration}`; + if (next !== current) el.setAttribute("style", next); +} + export function roundMatrix3dValue(value: string, decimals: number): string { return value.replace(/matrix3d\(([^)]+)\)/g, (_match, body: string) => { const rounded = body.split(",").map((raw) => { diff --git a/website/src/components/GalleryWorkbench/helpers/galleryDefaults.ts b/website/src/components/GalleryWorkbench/helpers/galleryDefaults.ts new file mode 100644 index 000000000..3531703fa --- /dev/null +++ b/website/src/components/GalleryWorkbench/helpers/galleryDefaults.ts @@ -0,0 +1,252 @@ +import type { Polygon } from "@layoutit/polycss-react"; +import { parsePureColor } from "@layoutit/polycss"; +import type { ObjParseOptions, GltfParseOptions, VoxParseOptions, StlParseOptions } from "@layoutit/polycss"; +import type { SceneOptionsState } from "../../types"; +import type { PresetModel, ParserOptionsState } from "../types"; +import { + PRESETS, + galleryBucketForPreset, + stripParenthesizedText, +} from "../presets"; +import { + applyDebugMatrixPrecision, + applyDebugBorderShapePrecision, + applyDebugTriangleBrushPrecision, + applyDebugSolidColorHex, + applyDebugInlineStyleOrder, + applyDebugInlineStyleMinify, +} from "./debugPrecision"; +import { routeInitialPresetId } from "../hooks"; + +export function presetPickerItem(preset: PresetModel, local = false) { + const label = local ? `Dropped: ${stripParenthesizedText(preset.label)}` : stripParenthesizedText(preset.label); + const category = galleryBucketForPreset(preset); + return { + id: preset.id, + label, + category, + searchText: [ + label, + preset.label, + category, + preset.category, + preset.kind, + preset.attribution?.creator, + preset.attribution?.license, + ].filter(Boolean).join(" ").toLowerCase(), + }; +} + +export const PRESET_PICKER_ITEMS = PRESETS.map((preset) => presetPickerItem(preset)); +export const ALL_PRESET_IDS = PRESETS.map((p) => p.id); + +export const DEFAULT_SCENE: SceneOptionsState = { + renderer: "vanilla", + animationPaused: false, + animationTimeScale: 1, + autoCenter: true, + interactive: true, + animate: false, + showAxes: false, + selection: false, + hoverEffects: false, + showLight: false, + zoom: PRESETS[0].zoom ?? 0.35, + rotX: PRESETS[0].rotX ?? 65, + rotY: PRESETS[0].rotY ?? 45, + perspective: undefined, + lightAzimuth: 40, + lightElevation: 45, + lightIntensity: 4.5, + lightColor: "#ffffff", + ambientIntensity: 0.55, + ambientColor: "#ffffff", + textureLighting: "baked", + textureQuality: "auto", + solidMaterials: false, + matrixPrecision: "exact", + borderShapePrecision: "exact", + meshResolution: "lossy", + interiorFill: false, + outlinePolygons: false, + dragMode: "orbit", + target: [0, 0, 0], + disableStrategies: [], + castShadow: false, + selfShadow: false, + shadowMaxExtend: 2000, + shadowParametric: true, + shadowDefinition: 35, + shadowStyle: "vector", + shadowFollowAnimation: true, + shadowOpacity: 0.25, + showGround: false, + groundColor: "#7d848e", + fpvLook: true, + fpvMove: true, + fpvJump: true, + fpvCrouch: true, + fpvMoveSpeed: 30, + fpvJumpVelocity: 25, + fpvGravity: 60, + fpvEyeHeight: 6, + fpvCrouchHeight: 3, + fpvLookSensitivity: 0.15, + fpvInvertY: false, + fpvRenderDistance: 40, + snapToGrid: true, + gridResolution: 5, + gridTone: "gray", +}; + +const DEFAULT_PARSER: ParserOptionsState = { + targetSize: 60, + defaultColor: "#8b95a1", +}; + +const RESPONSIVE_SHADOW_EXTEND_BASE = 3200; +const RESPONSIVE_SHADOW_EXTEND_MIN = 2000; +const RESPONSIVE_SHADOW_PREVIEW_EXTEND_BASE = 1800; +const RESPONSIVE_SHADOW_PREVIEW_EXTEND_MIN = 800; + +function responsiveCappedShadowMaxExtend( + value: number, + viewportScale: number, + base: number, + min: number, +): number { + if (viewportScale >= 0.995) return value; + const cap = Math.max(min, Math.round(base * viewportScale)); + return Math.min(value, cap); +} + +export function responsiveShadowMaxExtend(value: number, viewportScale: number): number { + return responsiveCappedShadowMaxExtend( + value, + viewportScale, + RESPONSIVE_SHADOW_EXTEND_BASE, + RESPONSIVE_SHADOW_EXTEND_MIN, + ); +} + +export function responsiveShadowPreviewMaxExtend(value: number, viewportScale: number): number { + return responsiveCappedShadowMaxExtend( + value, + viewportScale, + RESPONSIVE_SHADOW_PREVIEW_EXTEND_BASE, + RESPONSIVE_SHADOW_PREVIEW_EXTEND_MIN, + ); +} + +export function applyGalleryDebugDom(root: HTMLElement, options: SceneOptionsState): void { + applyDebugMatrixPrecision(root, options.matrixPrecision); + applyDebugBorderShapePrecision(root, options.borderShapePrecision); + applyDebugTriangleBrushPrecision(root); + applyDebugSolidColorHex(root); + applyDebugInlineStyleOrder(root); + applyDebugInlineStyleMinify(root); +} + +export function parserDefaultsFor(model: PresetModel): Partial { + const options = model.options as (ObjParseOptions & GltfParseOptions & VoxParseOptions & StlParseOptions) | undefined; + return { + ...(typeof options?.targetSize === "number" ? { targetSize: options.targetSize } : {}), + ...(typeof options?.defaultColor === "string" ? { defaultColor: options.defaultColor } : {}), + }; +} + +export function randomPreset(): PresetModel { + return PRESETS[Math.floor(Math.random() * PRESETS.length)] ?? PRESETS[0]; +} + +export function sceneDefaultsFor(model: PresetModel): SceneOptionsState { + return { + ...DEFAULT_SCENE, + zoom: model.zoom ?? DEFAULT_SCENE.zoom, + rotX: model.rotX ?? DEFAULT_SCENE.rotX, + rotY: model.rotY ?? DEFAULT_SCENE.rotY, + }; +} + +export function sceneDefaultsForPresetId(id: string): SceneOptionsState { + return sceneDefaultsFor(PRESETS.find((preset) => preset.id === id) ?? PRESETS[0]); +} + +export function parserStateFor(model: PresetModel): ParserOptionsState { + return { + ...DEFAULT_PARSER, + ...parserDefaultsFor(model), + }; +} + +export function resolveInitialPreset(): PresetModel { + const id = routeInitialPresetId(ALL_PRESET_IDS); + return (id ? PRESETS.find((p) => p.id === id) : null) ?? randomPreset(); +} + +export function polygonHasTexturePaint(polygon: Polygon): boolean { + return Boolean(polygon.texture || polygon.material?.texture || polygon.textureTriangles?.length); +} + +export function polygonHasTextureData(polygon: Polygon): boolean { + return Boolean(polygonHasTexturePaint(polygon) || polygon.uvs?.length); +} + +export function withSolidMaterials(polygons: Polygon[], fallbackColor: string): Polygon[] { + return polygons.map((polygon) => { + if (!polygonHasTextureData(polygon)) return polygon; + return { + ...polygon, + texture: undefined, + material: undefined, + uvs: undefined, + textureTriangles: undefined, + color: polygon.color ?? fallbackColor, + }; + }); +} + +interface InspectorColorSortKey { + bucket: number; + hue: number; + saturation: number; + value: number; + label: string; +} + +function inspectorColorSortKey(color: string): InspectorColorSortKey { + const parsed = parsePureColor(color); + if (!parsed) return { bucket: 2, hue: 0, saturation: 0, value: 0, label: color }; + const [r, g, b] = parsed.rgb.map((channel) => Math.max(0, Math.min(255, channel)) / 255); + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + const delta = max - min; + const saturation = max === 0 ? 0 : delta / max; + let hue = 0; + if (delta !== 0) { + if (max === r) hue = 60 * (((g - b) / delta) % 6); + else if (max === g) hue = 60 * ((b - r) / delta + 2); + else hue = 60 * ((r - g) / delta + 4); + } + if (hue < 0) hue += 360; + const neutral = saturation < 0.08; + return { + bucket: neutral ? 0 : 1, + hue: neutral ? 0 : hue, + saturation: neutral ? 0 : saturation, + value: max, + label: color, + }; +} + +export function compareInspectorColors(a: string, b: string): number { + const ak = inspectorColorSortKey(a); + const bk = inspectorColorSortKey(b); + return ( + ak.bucket - bk.bucket || + ak.hue - bk.hue || + bk.saturation - ak.saturation || + ak.value - bk.value || + ak.label.localeCompare(bk.label) + ); +} diff --git a/website/src/components/GalleryWorkbench/hooks/useLightRotationDrag.ts b/website/src/components/GalleryWorkbench/hooks/useLightRotationDrag.ts new file mode 100644 index 000000000..0894b311f --- /dev/null +++ b/website/src/components/GalleryWorkbench/hooks/useLightRotationDrag.ts @@ -0,0 +1,228 @@ +import { useEffect, useRef, useState, type RefObject } from "react"; +import type { Vec3 as ReactVec3 } from "@layoutit/polycss-react"; +import { screenToWorldOnSphere } from "@layoutit/polycss-core"; +import type { SceneOptionsState } from "../../types"; +import { responsiveZoomScaleForViewport } from "../helpers/responsivePresentation"; + +const LIGHT_HELPER_TILE = 50; +const LIGHT_HELPER_SELECTOR = ".dn-light-helper"; + +function initialResponsiveZoomScale(): number { + if (typeof window === "undefined") return 1; + return responsiveZoomScaleForViewport(window.innerWidth, window.innerHeight); +} + +export function useResponsiveViewportZoomScale( + viewportRef: RefObject, +): number { + const [scale, setScale] = useState(initialResponsiveZoomScale); + + useEffect(() => { + const viewport = viewportRef.current; + if (!viewport) return; + + const updateScale = (width: number, height: number): void => { + const next = responsiveZoomScaleForViewport(width, height); + setScale((current) => Math.abs(current - next) < 0.005 ? current : next); + }; + const readScale = (): void => { + const rect = viewport.getBoundingClientRect(); + updateScale(rect.width, rect.height); + }; + + readScale(); + window.addEventListener("resize", readScale); + + let observer: ResizeObserver | null = null; + if (typeof ResizeObserver !== "undefined") { + observer = new ResizeObserver((entries) => { + const rect = entries[0]?.contentRect; + if (rect) updateScale(rect.width, rect.height); + else readScale(); + }); + observer.observe(viewport); + } + + return () => { + window.removeEventListener("resize", readScale); + observer?.disconnect(); + }; + }, [viewportRef]); + + return scale; +} + +function wrapDegrees(value: number): number { + return ((value % 360) + 360) % 360; +} + +function clampLightElevation(value: number): number { + return Math.max(0, Math.min(90, value)); +} + +export function useLightRotationDrag( + viewportRef: RefObject, + sceneOptions: SceneOptionsState, + helperScale: number, + helperTarget: [number, number, number], + gizmoDragging: boolean, + onCommitScene: (partial: Partial) => void, + canPreviewSceneOptions: (options: SceneOptionsState) => boolean, + onPreviewSceneOptions: (options: SceneOptionsState) => void, +): void { + const sceneOptionsRef = useRef(sceneOptions); + const helperScaleRef = useRef(helperScale); + const helperTargetRef = useRef(helperTarget); + const gizmoDraggingRef = useRef(gizmoDragging); + const onCommitSceneRef = useRef(onCommitScene); + const canPreviewSceneOptionsRef = useRef(canPreviewSceneOptions); + const onPreviewSceneOptionsRef = useRef(onPreviewSceneOptions); + sceneOptionsRef.current = sceneOptions; + helperScaleRef.current = helperScale; + helperTargetRef.current = helperTarget; + gizmoDraggingRef.current = gizmoDragging; + onCommitSceneRef.current = onCommitScene; + canPreviewSceneOptionsRef.current = canPreviewSceneOptions; + onPreviewSceneOptionsRef.current = onPreviewSceneOptions; + + useEffect(() => { + const viewport = viewportRef.current; + if (!viewport) return; + + let activePointerId: number | null = null; + let sphereRadius = 1; + let previewRaf = 0; + let dragOptions: SceneOptionsState | null = null; + let pendingPreviewOptions: SceneOptionsState | null = null; + let pendingCommit: Pick | null = null; + + const flushPreview = (): void => { + previewRaf = 0; + const options = pendingPreviewOptions; + pendingPreviewOptions = null; + if (options) onPreviewSceneOptionsRef.current(options); + }; + + const schedulePreview = (options: SceneOptionsState): void => { + pendingPreviewOptions = options; + if (!previewRaf) previewRaf = requestAnimationFrame(flushPreview); + }; + + const cancelPreview = (): void => { + if (previewRaf) cancelAnimationFrame(previewRaf); + previewRaf = 0; + pendingPreviewOptions = null; + }; + + const helperDragEnabled = (): boolean => { + const options = sceneOptionsRef.current; + return options.interactive && options.showLight && !gizmoDraggingRef.current; + }; + + const computeAnglesFromCursor = ( + options: SceneOptionsState, + clientX: number, + clientY: number, + ): { lightAzimuth: number; lightElevation: number } | null => { + const rect = viewport.getBoundingClientRect(); + const ht = helperTargetRef.current; + const t = options.target as ReactVec3; + const camArg = { + rotX: options.rotX, + rotY: options.rotY, + zoom: options.zoom * LIGHT_HELPER_TILE, + target: [t[0] + ht[0], t[1] + ht[1], t[2] + ht[2]] as ReactVec3, + }; + const hit = screenToWorldOnSphere({ + camera: camArg as unknown as Parameters[0]["camera"], + tileSize: LIGHT_HELPER_TILE, + viewportCenterX: rect.left + rect.width / 2, + viewportCenterY: rect.top + rect.height / 2, + mouseX: clientX, + mouseY: clientY, + sphereCenter: helperTargetRef.current, + sphereRadius, + }); + if (!hit) return null; + const target = helperTargetRef.current; + const ox = hit[0] - target[0]; + const oy = hit[1] - target[1]; + const oz = hit[2] - target[2]; + const len = Math.hypot(ox, oy, oz) || 1; + const nx = ox / len, ny = oy / len, nz = oz / len; + return { + lightAzimuth: wrapDegrees((Math.atan2(nx, ny) * 180) / Math.PI), + lightElevation: clampLightElevation((Math.asin(Math.max(-1, Math.min(1, nz))) * 180) / Math.PI), + }; + }; + + const stopDrag = (event: PointerEvent): void => { + if (activePointerId !== event.pointerId) return; + const commit = pendingCommit; + if (pendingPreviewOptions) { + if (previewRaf) cancelAnimationFrame(previewRaf); + flushPreview(); + } + if (commit) onCommitSceneRef.current(commit); + activePointerId = null; + dragOptions = null; + pendingCommit = null; + cancelPreview(); + viewport.classList.remove("is-light-rotating"); + try { viewport.releasePointerCapture(event.pointerId); } catch { /* ignore */ } + }; + + const onPointerDown = (event: PointerEvent): void => { + if (activePointerId !== null) return; + if (event.isPrimary === false) return; + if (event.button !== 0) return; + const target = event.target instanceof Element ? event.target : null; + if (target?.closest("[data-poly-transform-controls]")) return; + const helper = target?.closest(LIGHT_HELPER_SELECTOR) ?? null; + if (!helper || !helperDragEnabled()) return; + event.preventDefault(); + event.stopPropagation(); + activePointerId = event.pointerId; + dragOptions = sceneOptionsRef.current; + pendingCommit = null; + sphereRadius = Math.max(0.001, helperScaleRef.current * 0.7); + viewport.classList.add("is-light-rotating"); + try { viewport.setPointerCapture(event.pointerId); } catch { /* ignore */ } + }; + + const onPointerMove = (event: PointerEvent): void => { + if (activePointerId !== event.pointerId) return; + if (!helperDragEnabled()) { + stopDrag(event); + return; + } + event.preventDefault(); + const baseOptions = dragOptions ?? sceneOptionsRef.current; + const nextAngles = computeAnglesFromCursor(baseOptions, event.clientX, event.clientY); + if (!nextAngles) return; + if (!canPreviewSceneOptionsRef.current(baseOptions)) { + onCommitSceneRef.current(nextAngles); + dragOptions = { ...baseOptions, ...nextAngles }; + pendingCommit = null; + return; + } + const nextOptions = { ...baseOptions, ...nextAngles }; + dragOptions = nextOptions; + pendingCommit = nextAngles; + schedulePreview(nextOptions); + }; + + viewport.addEventListener("pointerdown", onPointerDown, { capture: true }); + viewport.addEventListener("pointermove", onPointerMove); + viewport.addEventListener("pointerup", stopDrag); + viewport.addEventListener("pointercancel", stopDrag); + return () => { + viewport.removeEventListener("pointerdown", onPointerDown, { capture: true }); + viewport.removeEventListener("pointermove", onPointerMove); + viewport.removeEventListener("pointerup", stopDrag); + viewport.removeEventListener("pointercancel", stopDrag); + viewport.classList.remove("is-light-rotating"); + cancelPreview(); + }; + }, [viewportRef]); +} diff --git a/website/src/components/VanillaScene/VanillaScene.tsx b/website/src/components/VanillaScene/VanillaScene.tsx index 8ce55e179..c95cdc8f5 100644 --- a/website/src/components/VanillaScene/VanillaScene.tsx +++ b/website/src/components/VanillaScene/VanillaScene.tsx @@ -1,7 +1,6 @@ import { useCallback, useEffect, useRef } from "react"; -import type { ParseAnimationController, PolyAmbientLight, PolyDirectionalLight, Polygon, Vec3 as ReactVec3 } from "@layoutit/polycss-react"; +import type { Polygon, Vec3 as ReactVec3 } from "@layoutit/polycss-react"; import { - axesHelperPolygons, createPolyFirstPersonControls, createPolyOrbitControls, createPolyMapControls, @@ -10,7 +9,6 @@ import { createPolyScene, createSelect, createTransformControls, - octahedronPolygons, } from "@layoutit/polycss"; import type { PolyControlsHandle, @@ -29,270 +27,20 @@ import type { import { meshResolutionShowsMesh, type GizmoMode, type SceneOptionsState } from "../types"; import { FPV_PERSPECTIVE } from "../fpv"; import { ambientFromOptions, directionalFromOptions } from "../GalleryWorkbench/helpers/lighting"; - -export type { GizmoMode, SceneOptionsState }; - -// Light helper world units → CSS pixels conversion (matches the helper -// components in @layoutit/polycss-react and @layoutit/polycss-vue). -const LIGHT_HELPER_TILE = 50; -// Keep the visible ground just below the model floor; coplanar ground/car -// faces z-fight during repaint-heavy light drags. -const GROUND_Z_OFFSET = -0.04; -// Ground ALBEDO, not ground paint. The engine bakes this through the same -// `shadePolygon` Lambert as every other polygon, and derives the ground's -// receiver-shadow fill from it, so the lit floor and its shadow share one -// base. The value is picked so the baked result lands at the gallery's -// established floor tone (~88 luma under the reference lighting) — the old -// code got that tone by overpainting the leaf with `!important`, which left -// the shadow blended from the un-overpainted base and made the shadow ~1.7x -// too deep AND impossible to turn off at strength 0. -const GALLERY_GROUND_COLOR = "#7d848e"; -const GALLERY_GROUND_RADIUS_MULTIPLIER = 2.5; -const GALLERY_GROUND_MODEL_RADIUS_MULTIPLIER = 1.75; -const GALLERY_GROUND_MIN_RADIUS = 40; -// Lift the shadow above the ground plane (which sits at GROUND_Z_OFFSET -// below the model floor). The library's `shadow.lift` is now interpreted -// as "world-unit displacement ALONG the receiver face's normal" — for -// the floor that's +Z, so a positive value puts the shadow visibly above -// the ground. (Earlier this constant ALSO added GROUND_Z_OFFSET because -// the old non-receiver cast-shadow path treated `lift` as an absolute -// z relative to caster.minZ, where negative was correct. Once the floor -// became a receiver, that negative result placed the shadow BELOW the -// ground and got occluded by it.) -const GALLERY_SHADOW_LIFT = 0.01; -const ANIMATION_STABLE_TRIANGLE_COLOR_POLICY = "cadence"; -// Deforming low-poly triangles can swing face normals sharply; keep the -// mounted baked color pinned and animate transforms only. -const ANIMATION_STABLE_TRIANGLE_COLOR_FREEZE_FRAMES = 0; -const ANIMATION_TRANSFORM_CACHE_FRAMES = 60; - -// Transitional compat: the polycss vanilla camera was updated to interpret -// `zoom` as "px per world unit" (Three.js convention) rather than a raw CSS -// scale factor. The shared workbench presets / sceneOptions still carry -// CSS-scale-tuned values that ALSO drive the React renderer (which keeps the -// old semantic until the parity refactor is mirrored there). Multiply by 50 -// going into the vanilla camera and divide on the way back out so both -// renderers can keep reading from the same `sceneOptions.zoom` field. -// Remove once @layoutit/polycss-react has been mirrored. -const LEGACY_ZOOM_COMPAT = 50; - -interface StableTriangleTransformFrameItem { - transform: string; - visibility: string; -} - -interface StableTriangleTransformCache { - frames: Array; - leaves: HTMLElement[] | null; - leafCount: number; - filled: number; - disabled: boolean; - canRefreshColor: boolean; - lastAppliedFrameIndex: number; -} - -function createStableTriangleTransformCache(): StableTriangleTransformCache { - return { - frames: Array.from({ length: ANIMATION_TRANSFORM_CACHE_FRAMES }), - leaves: null, - leafCount: 0, - filled: 0, - disabled: false, - canRefreshColor: false, - lastAppliedFrameIndex: -1, - }; -} - -function resetStableTriangleTransformCache(cache: StableTriangleTransformCache): void { - cache.frames.fill(undefined); - cache.leaves = null; - cache.leafCount = 0; - cache.filled = 0; - cache.canRefreshColor = false; - cache.lastAppliedFrameIndex = -1; -} - -function directStableAnimationLeaves(handle: VanillaPolyMeshHandle): HTMLElement[] { - return Array.from(handle.element.querySelectorAll(":scope > u,:scope > s")); -} - -function captureStableTriangleTransformFrame( - handle: VanillaPolyMeshHandle, - cache: StableTriangleTransformCache, - frameIndex: number, -): void { - if (cache.disabled) return; - const leaves = directStableAnimationLeaves(handle); - const expectedCount = handle.polygons.length; - if ( - expectedCount <= 0 || - leaves.length !== expectedCount - ) { - cache.disabled = true; - resetStableTriangleTransformCache(cache); - return; - } - const canRefreshColor = leaves.every((leaf) => leaf.tagName === "U"); - if ( - cache.leafCount !== 0 && - (leaves.length !== cache.leafCount || cache.canRefreshColor !== canRefreshColor) - ) { - resetStableTriangleTransformCache(cache); - } - cache.leaves = leaves; - cache.leafCount = leaves.length; - cache.canRefreshColor = canRefreshColor; - if (!cache.frames[frameIndex]) cache.filled += 1; - cache.frames[frameIndex] = leaves.map((leaf) => ({ - transform: leaf.style.transform || "none", - visibility: leaf.style.visibility === "hidden" ? "hidden" : "", - })); - cache.lastAppliedFrameIndex = frameIndex; -} - -function applyStableTriangleTransformFrame( - handle: VanillaPolyMeshHandle, - cache: StableTriangleTransformCache, - frameIndex: number, -): boolean { - if (cache.disabled) return false; - const frame = cache.frames[frameIndex]; - if (!frame) return false; - if ( - cache.lastAppliedFrameIndex === frameIndex && - cache.leaves && - cache.leafCount === frame.length - ) { - return true; - } - const leaves = cache.leaves ?? directStableAnimationLeaves(handle); - if (leaves.length !== frame.length) { - resetStableTriangleTransformCache(cache); - return false; - } - const previousFrame = cache.lastAppliedFrameIndex >= 0 - ? cache.frames[cache.lastAppliedFrameIndex] - : undefined; - cache.leaves = leaves; - cache.leafCount = leaves.length; - for (let i = 0; i < leaves.length; i += 1) { - const leaf = leaves[i]; - const next = frame[i]; - const previous = previousFrame?.[i]; - if (previous?.transform !== next.transform) { - leaf.style.transform = next.transform; - } - if (previous?.visibility !== next.visibility) { - leaf.style.visibility = next.visibility; - } - } - cache.lastAppliedFrameIndex = frameIndex; - return true; -} - -function animationCacheFrameIndex( - timeSeconds: number, - durationSeconds: number, -): number { - const duration = Math.max(0.001, durationSeconds); - const localTime = ((timeSeconds % duration) + duration) % duration; - return Math.floor( - (localTime / duration) * ANIMATION_TRANSFORM_CACHE_FRAMES, - ) % ANIMATION_TRANSFORM_CACHE_FRAMES; -} - -function lightHelperPosition( - light: PolyDirectionalLight, - target: Vec3, - distance: number, -): Vec3 { - // Post-parity: createPolyScene treats `position` as WORLD UNITS and - // applies the world→CSS axis swap + ×BASE_TILE conversion internally. - // Pre-parity, this helper used to ×LIGHT_HELPER_TILE + swap manually, - // which after the parity refactor pushed the helper thousands of CSS - // pixels off-screen because the renderer multiplied a second time. - const [dx, dy, dz] = light.direction; - const len = Math.hypot(dx, dy, dz) || 1; - return [ - target[0] + (dx / len) * distance, - target[1] + (dy / len) * distance, - target[2] + (dz / len) * distance, - ]; -} - -function bakedLightingSignature( - directionalLight: PolyDirectionalLight, - ambientLight: PolyAmbientLight, -): string { - return [ - directionalLight.direction.map((value) => value.toFixed(4)).join(","), - directionalLight.color ?? "", - directionalLight.intensity ?? "", - ambientLight.color ?? "", - ambientLight.intensity ?? "", - ].join("|"); -} - -export interface VanillaSceneTransientHandle { - applySceneOptions(options: SceneOptionsState): void; - applyLightOptions(options: SceneOptionsState, preview?: { shadow?: boolean }): void; -} - -type BakedSolidLightingPreviewSceneHandle = PolySceneHandle & { - previewBakedSolidLighting?: (next: { - directionalLight?: PolyDirectionalLight; - ambientLight?: PolyAmbientLight; - skipShadows?: boolean; - }) => boolean; - commitBakedSolidLighting?: () => boolean; -}; - -export interface VanillaSceneProps { - polygons: Polygon[]; - interiorShellPolygons: Polygon[]; - parseResult?: ParseResult; - options: SceneOptionsState; - directionalLight: PolyDirectionalLight; - ambientLight: PolyAmbientLight; - showAxes: boolean; - showLight: boolean; - showGround: boolean; - helperScale: number; - helperTarget: Vec3; - mergePolygonsForMesh: boolean; - stableDomForMesh: boolean; - animationKey?: string; - animationDurationSeconds?: number; - animationFrameFactory?: (timeSeconds: number) => Polygon[]; - onBuild?: (ms: number) => void; - onCameraChange?: (camera: { rotX: number; rotY: number; zoom: number; target?: ReactVec3 }) => void; - enableSelection?: boolean; - meshId?: string; - onSelectionChange?: (selectedIds: string[]) => void; - gizmoMode?: GizmoMode; - enableHover?: boolean; - onHoverChange?: (id: string | null) => void; - onMeshHandleChange?: (handle: VanillaPolyMeshHandle | null) => void; - onTransientHandleChange?: (handle: VanillaSceneTransientHandle | null) => void; - onSceneDomChange?: () => void; -} - -function fpvOptionsFromSceneOptions(options: SceneOptionsState) { - return { - enabled: options.interactive, - lookEnabled: options.fpvLook, - moveEnabled: options.fpvMove, - jumpEnabled: options.fpvJump, - crouchEnabled: options.fpvCrouch, - moveSpeed: options.fpvMoveSpeed, - jumpVelocity: options.fpvJumpVelocity, - gravity: options.fpvGravity, - eyeHeight: options.fpvEyeHeight, - crouchHeight: options.fpvCrouchHeight, - lookSensitivity: options.fpvLookSensitivity, - invertY: options.fpvInvertY, - }; -} +import { + GALLERY_SHADOW_LIFT, + LEGACY_ZOOM_COMPAT, + bakedLightingSignature, + fpvOptionsFromSceneOptions, + lightHelperPosition, + type BakedSolidLightingPreviewSceneHandle, + type VanillaSceneProps, + type VanillaSceneTransientHandle, +} from "./sceneHelpers"; +import { useVanillaAnimationLoop } from "./stableAnimationCache"; +import { useVanillaHelperMeshes } from "./useVanillaSceneHelpers"; + +export type { GizmoMode, SceneOptionsState, VanillaSceneProps, VanillaSceneTransientHandle }; export function VanillaScene({ polygons, @@ -339,8 +87,6 @@ export function VanillaScene({ onBuildRef.current = onBuild; const onCameraChangeRef = useRef(onCameraChange); onCameraChangeRef.current = onCameraChange; - // Debounce handle for syncing FPV position to options/URL once movement - // settles (FPV emits per-frame; we only want the resting spot). const fpvSettleTimerRef = useRef(0); const onSelectionChangeRef = useRef(onSelectionChange); onSelectionChangeRef.current = onSelectionChange; @@ -402,17 +148,6 @@ export function VanillaScene({ ...(previewShadow ? { shadow: nextShadow } : {}), }); } else { - // Baked mode: push the new light direction to the scene so shadow - // SVGs re-emit live during drag, AND install the CSS-cascade light - // preview on solid leaves so they tint live too — matches the - // pre-#9e4763f gallery feel where lights update interactively - // while the user drags the gizmo. The atlas pixels themselves stay - // at the last baked color; the CSS-cascade preview multiplies them - // by the live light vars. On commit the atlas re-bakes via - // commitBakedSolidLighting → rebakeRenderEntryInPlace and the - // preview vars are dropped — there may be a tiny snap if the - // approximate CSS calc Lambert disagrees with the CPU bake, but - // the live-feedback during drag is what the user expects. if (previewShadow) { scene.setOptions({ directionalLight: nextDirectionalLight, shadow: nextShadow }); } else { @@ -449,7 +184,15 @@ export function VanillaScene({ directionalLight: nextDirectionalLight, ambientLight: ambientFromOptions(nextOptions), textureLighting: nextOptions.textureLighting, - shadow: { maxExtend: nextOptions.shadowMaxExtend, lift: GALLERY_SHADOW_LIFT, parametric: nextOptions.shadowParametric, definition: nextOptions.shadowDefinition, style: nextOptions.shadowStyle, followAnimation: nextOptions.shadowFollowAnimation, opacity: nextOptions.shadowOpacity }, + shadow: { + maxExtend: nextOptions.shadowMaxExtend, + lift: GALLERY_SHADOW_LIFT, + parametric: nextOptions.shadowParametric, + definition: nextOptions.shadowDefinition, + style: nextOptions.shadowStyle, + followAnimation: nextOptions.shadowFollowAnimation, + opacity: nextOptions.shadowOpacity, + }, }); lightHandleRef.current?.setTransform({ position: lightHelperPosition( @@ -468,15 +211,7 @@ export function VanillaScene({ return () => onTransientHandleChangeRef.current?.(null); }, [applyTransientLightOptions, applyTransientSceneOptions]); - // Split structural options (require destroying the scene) from incremental - // lighting/camera options. Baked light changes commit solid colors in place; - // rebuilding the whole mesh on mouseup causes visible polygon flicker. - const stableDirectionalForRebuild = null; - const stableAmbientForRebuild = null; - - // Effect 1 — heavy: create the scene + add the current polygons once. - // Polygon replacement is handled by Effect 1.5 so animation frames do not - // tear down controls/helpers. + // Effect 1 — create the scene + add the initial polygons once. useEffect(() => { const host = hostRef.current; if (!host) return; @@ -502,7 +237,15 @@ export function VanillaScene({ autoCenter: options.autoCenter, textureQuality: options.textureQuality, strategies: { disable: options.disableStrategies }, - shadow: { maxExtend: options.shadowMaxExtend, lift: GALLERY_SHADOW_LIFT, parametric: options.shadowParametric, definition: options.shadowDefinition, style: options.shadowStyle, followAnimation: options.shadowFollowAnimation, opacity: options.shadowOpacity }, + shadow: { + maxExtend: options.shadowMaxExtend, + lift: GALLERY_SHADOW_LIFT, + parametric: options.shadowParametric, + definition: options.shadowDefinition, + style: options.shadowStyle, + followAnimation: options.shadowFollowAnimation, + opacity: options.shadowOpacity, + }, }; const scene = createPolyScene(host, sceneOptions); sceneRef.current = scene; @@ -515,17 +258,8 @@ export function VanillaScene({ receiveShadow: options.selfShadow, } as PolyMeshTransform; const modelParseResult: ParseResult = parseResult - ? { - ...parseResult, - polygons, - dispose: () => { }, - } - : { - polygons, - objectUrls: [], - warnings: [], - dispose: () => { }, - }; + ? { ...parseResult, polygons, dispose: () => { } } + : { polygons, objectUrls: [], warnings: [], dispose: () => { } }; meshHandleRef.current = scene.add(modelParseResult, meshTransform); mountedModelRef.current = { handle: meshHandleRef.current, @@ -538,8 +272,6 @@ export function VanillaScene({ onMeshHandleChangeRef.current?.(meshHandleRef.current); notifySceneDomChange(); return () => { - // Tear controls down BEFORE destroying the scene — otherwise the - // controls' rAF tick could fire one more time against a stale handle. onMeshHandleChangeRef.current?.(null); controlsRef.current?.destroy(); controlsRef.current = null; @@ -558,8 +290,6 @@ export function VanillaScene({ options.textureQuality, options.textureLighting, options.perspective, - stableDirectionalForRebuild, - stableAmbientForRebuild, stableDomForMesh, parseResult, notifySceneDomChange, @@ -569,11 +299,7 @@ export function VanillaScene({ meshHandleRef.current?.element.classList.toggle("is-mesh-hidden", !meshResolutionShowsMesh(options.meshResolution)); }, [options.meshResolution]); - // Effect 1.5 — replace geometry on the existing mesh. This is the path - // used by animated GLB playback; seam bleed is already baked into the - // polygon list before the mesh reaches this renderer. The interior shell - // is a separate non-shadow mesh mounted inside the model wrapper so it - // inherits the same mesh transform without changing auto-centering. + // Effect 1.5 — replace geometry on the existing mesh + interior shell. useEffect(() => { const handle = meshHandleRef.current; const scene = sceneRef.current; @@ -642,23 +368,15 @@ export function VanillaScene({ notifySceneDomChange, ]); - // Effect 1.6 — live-toggle castShadow / selfShadow (receiveShadow on the - // mesh) without rebuilding the scene. + // Effect 1.6 — live-toggle castShadow / selfShadow without rebuilding scene. useEffect(() => { - const handle = meshHandleRef.current; - if (!handle) return; - handle.setTransform({ castShadow: options.castShadow }); + meshHandleRef.current?.setTransform({ castShadow: options.castShadow }); }, [options.castShadow]); useEffect(() => { - const handle = meshHandleRef.current; - if (!handle) return; - handle.setTransform({ receiveShadow: options.selfShadow }); + meshHandleRef.current?.setTransform({ receiveShadow: options.selfShadow }); }, [options.selfShadow]); - // Selection + transform-controls layer. Selection toggle controls - // both — when on, clicking the mesh selects it (and attaches the - // gizmo); clicking again deselects (and detaches). The gizmo's - // mode follows `gizmoMode` (translate / rotate). + // Selection + transform-controls layer. useEffect(() => { if (!enableSelection) { selectionRef.current?.destroy(); @@ -671,15 +389,11 @@ export function VanillaScene({ } const scene = sceneRef.current; if (!scene) return; - const tc = createTransformControls(scene, { - mode: gizmoMode ?? "translate", - }); + const tc = createTransformControls(scene, { mode: gizmoMode ?? "translate" }); transformControlsRef.current = tc; const select = createSelect(scene, { clearOnMiss: false, onChange: (meshes) => { - // Drive the gizmo from selection: attach to the first selected - // mesh, or detach when nothing is selected. tc.attach(meshes[0] ?? null); onSelectionChangeRef.current?.(meshes.map((m) => m.id ?? "")); }, @@ -695,31 +409,20 @@ export function VanillaScene({ }; }, [ enableSelection, - // Same deps as the scene-init effect so the selection rebinds to - // the new PolySceneHandle whenever the scene tears down + rebuilds. options.autoCenter, options.textureQuality, options.textureLighting, options.perspective, - stableDirectionalForRebuild, - stableAmbientForRebuild, stableDomForMesh, parseResult, notifySceneDomChange, ]); - // Forward gizmo mode changes to the live PolyTransformControls handle. useEffect(() => { transformControlsRef.current?.setMode(gizmoMode ?? "translate"); }, [gizmoMode]); - // Hover layer for vanilla — pointerenter / pointerleave on the mesh - // wrapper. DOM enter/leave semantics fire only when the pointer - // actually crosses the wrapper boundary (not on every internal - // polygon-to-polygon transition), so the hover state stays stable - // across the chicken's many `` polygons. Adds the `is-hovered` - // class so the same `.polycss-mesh.is-hovered i { filter: brightness }` - // rule the React path uses kicks in here too. + // Hover layer useEffect(() => { const mesh = meshHandleRef.current; if (!mesh || !enableHover) { @@ -743,169 +446,31 @@ export function VanillaScene({ }; }, [ enableHover, - // Same deps as the scene-init effect so the hover listener - // reattaches to the new mesh wrapper after a scene rebuild. options.autoCenter, options.textureQuality, options.textureLighting, options.perspective, - stableDirectionalForRebuild, - stableAmbientForRebuild, stableDomForMesh, parseResult, ]); - useEffect(() => { - if (!animationFrameFactory || !animationKey) return; - let raf = 0; - let last = performance.now(); - let elapsedSeconds = 0; - let sampledSeconds: number | null = null; - let animationFrameCount = 0; - let lastAnimatedPolygonCount = 0; - const transformCache = - stableDomForMesh && - options.textureLighting === "baked" && - // Follow-animation shadows need fresh polygons via setPolygons every - // frame; the transform cache skips setPolygons on cache hits (leaving - // entry.polygons stale), so disable it while shadows track the pose. - !options.shadowFollowAnimation && - typeof animationDurationSeconds === "number" && - animationDurationSeconds > 0 - ? createStableTriangleTransformCache() - : null; - - const tick = (now: number) => { - const deltaSeconds = Math.max(0, (now - last) / 1000); - last = now; - if (!animationPausedRef.current) { - elapsedSeconds += deltaSeconds * animationTimeScaleRef.current; - } - const handle = meshHandleRef.current; - if (handle && sampledSeconds !== elapsedSeconds) { - sampledSeconds = elapsedSeconds; - animationFrameCount += 1; - const debugTarget = window as unknown as { - __polycssGalleryAnimationSamples?: Array<{ - t: number; - sampleMs: number; - setPolygonsMs: number; - polygons: number; - transformCacheHit?: boolean; - transformCacheFilled?: number; - transformCacheMs?: number; - }>; - __polycssStableTriangleDebug?: "transform-only" | "plan-only"; - }; - const stableTriangleDebug = debugTarget.__polycssStableTriangleDebug; - const setPolygonsOptions = { - merge: false, - stableDom: true, - recomputeAutoCenter: false, - ...(stableTriangleDebug === "transform-only" || stableTriangleDebug === "plan-only" - ? { stableTriangleDebug } - : {}), - stableTriangleColorPolicy: ANIMATION_STABLE_TRIANGLE_COLOR_POLICY, - stableTriangleColorFreezeFrames: ANIMATION_STABLE_TRIANGLE_COLOR_FREEZE_FRAMES, - } satisfies Parameters[1] & { - stableTriangleDebug?: "transform-only" | "plan-only"; - stableTriangleUpdateMode?: "full" | "transform-only" | "color-only"; - stableTriangleColorPolicy: "cadence" | "adaptive"; - stableTriangleColorFreezeFrames: number; - }; - const canUseTransformCache = - transformCache && - !transformCache.disabled && - !stableTriangleDebug && - animationDurationSeconds !== undefined; - const frameIndex = canUseTransformCache - ? animationCacheFrameIndex(elapsedSeconds, animationDurationSeconds) - : -1; - const shouldRefreshColor = - canUseTransformCache && - transformCache.canRefreshColor && - ANIMATION_STABLE_TRIANGLE_COLOR_FREEZE_FRAMES > 0 && - animationFrameCount % ANIMATION_STABLE_TRIANGLE_COLOR_FREEZE_FRAMES === 0; - const samples = debugTarget.__polycssGalleryAnimationSamples; - let sampleMs = 0; - let setPolygonsMs = 0; - let transformCacheMs = 0; - let transformCacheHit = false; - if (canUseTransformCache) { - const cacheStart = samples ? performance.now() : 0; - transformCacheHit = applyStableTriangleTransformFrame( - handle, - transformCache, - frameIndex, - ); - transformCacheMs = samples ? performance.now() - cacheStart : 0; - } - if (transformCacheHit && shouldRefreshColor) { - const sampleStart = samples ? performance.now() : 0; - const animatedPolygons = animationFrameFactory(elapsedSeconds); - sampleMs = samples ? performance.now() - sampleStart : 0; - lastAnimatedPolygonCount = animatedPolygons.length; - const setStart = samples ? performance.now() : 0; - handle.setPolygons(animatedPolygons, { - ...setPolygonsOptions, - stableTriangleUpdateMode: "color-only", - }); - setPolygonsMs = samples ? performance.now() - setStart : 0; - } else if (!transformCacheHit) { - const sampleStart = samples ? performance.now() : 0; - const animatedPolygons = animationFrameFactory(elapsedSeconds); - sampleMs = samples ? performance.now() - sampleStart : 0; - lastAnimatedPolygonCount = animatedPolygons.length; - const setStart = samples ? performance.now() : 0; - handle.setPolygons(animatedPolygons, setPolygonsOptions); - setPolygonsMs = samples ? performance.now() - setStart : 0; - if (canUseTransformCache) { - captureStableTriangleTransformFrame(handle, transformCache, frameIndex); - } - } - if (samples) { - samples.push({ - t: now, - sampleMs, - setPolygonsMs, - polygons: lastAnimatedPolygonCount, - transformCacheHit, - transformCacheFilled: transformCache?.filled, - transformCacheMs, - }); - if (samples.length > 1800) samples.splice(0, samples.length - 1800); - } - } - raf = requestAnimationFrame(tick); - }; - - raf = requestAnimationFrame(tick); - return () => cancelAnimationFrame(raf); - }, [ + useVanillaAnimationLoop({ + meshHandleRef, + animationPausedRef, + animationTimeScaleRef, animationKey, - animationFrameFactory, animationDurationSeconds, - options.textureLighting, - options.shadowFollowAnimation, + animationFrameFactory, + textureLighting: options.textureLighting, + shadowFollowAnimation: options.shadowFollowAnimation, stableDomForMesh, - ]); + }); - // Effect 2a — camera-only updates. Runs every drag tick. Pushes the new - // camera state and re-applies the scene transform. Does NOT call - // scene.setOptions — camera changes don't change lighting/shadow, and - // calling setOptions({shadow:...}) here would trigger a full receiver- - // shadow rebuild every drag tick, causing visible mid-frame flicker - // ("shadows disappear when rotating") in real Chrome. + // Camera-only updates useEffect(() => { const scene = sceneRef.current; const camera = cameraRef.current; - if (!scene || !camera) return; - // FPV is authoritative over the live camera. We DO sync FPV's position back - // to options (debounced, so the scene URL captures where you walked), but - // re-applying that camera here would fight FPV's own per-frame writes — its - // target is a derived look-ahead point, not the stored eye. Skip; the - // initial pose still restores via scene creation (Effect 1) on load. - if (options.dragMode === "fpv") return; + if (!scene || !camera || options.dragMode === "fpv") return; camera.update({ rotX: options.rotX, rotY: options.rotY, @@ -915,10 +480,7 @@ export function VanillaScene({ scene.applyCamera(); }, [options.rotX, options.rotY, options.zoom, options.target, options.dragMode]); - // Effect 2b — lighting + shadow updates. Runs only when the light, shadow, - // textureLighting, or ground color actually change (sliders, not camera). - // setOptions triggers the receiver-shadow rebuild via emitSceneShadows(); - // keep it off the camera-tick path. + // Lighting + shadow updates useEffect(() => { const scene = sceneRef.current; if (!scene) return; @@ -926,7 +488,15 @@ export function VanillaScene({ directionalLight, ambientLight, textureLighting: options.textureLighting, - shadow: { maxExtend: options.shadowMaxExtend, lift: GALLERY_SHADOW_LIFT, parametric: options.shadowParametric, definition: options.shadowDefinition, style: options.shadowStyle, followAnimation: options.shadowFollowAnimation, opacity: options.shadowOpacity }, + shadow: { + maxExtend: options.shadowMaxExtend, + lift: GALLERY_SHADOW_LIFT, + parametric: options.shadowParametric, + definition: options.shadowDefinition, + style: options.shadowStyle, + followAnimation: options.shadowFollowAnimation, + opacity: options.shadowOpacity, + }, }); const nextLightingSignature = bakedLightingSignature(directionalLight, ambientLight); if ( @@ -951,23 +521,15 @@ export function VanillaScene({ ambientLight, ]); - // Effect 2b — render strategy controls. Kept separate from Effect 2 because - // these options trigger a full mesh re-render in - // createPolyScene; folding it into the camera/lighting effect would - // re-render on every rotation/zoom tick. + // Render strategy controls useEffect(() => { const scene = sceneRef.current; if (!scene) return; - scene.setOptions({ - strategies: { disable: options.disableStrategies }, - }); + scene.setOptions({ strategies: { disable: options.disableStrategies } }); notifySceneDomChange(); }, [options.disableStrategies, notifySceneDomChange]); - // Effect 2.5 — vanilla controls. The React renderer wires interactive + - // animate through ; the vanilla path uses createPolyOrbitControls. - // The handle is created lazily once the scene is ready and we're on the - // vanilla renderer; subsequent prop changes flow through controls.update(). + // Vanilla controls (orbit / map / first-person) useEffect(() => { if (options.renderer !== "vanilla") { controlsRef.current?.destroy(); @@ -979,14 +541,6 @@ export function VanillaScene({ const buildControls = (): PolyControlsHandle | PolyFirstPersonControlsHandle => { if (options.dragMode === "fpv") { const fpv = createPolyFirstPersonControls(scene, fpvOptionsFromSceneOptions(options)); - // FPV is authoritative over the camera while engaged — don't echo its - // per-frame writes back into React state; that round-trip fights the - // rAF tick and jitters mouselook/walk. But once movement SETTLES - // (~900ms idle) we sync the resting pose to options so the scene URL - // captures where you walked. We store the EYE position (getOrigin) as - // `target`: on reload FPV re-seeds its origin from camera.target, so - // the eye lands back at that spot. The camera-apply effect skips fpv - // mode, so this write never fights the live controls. fpv.addEventListener("change", () => { if (fpvSettleTimerRef.current) window.clearTimeout(fpvSettleTimerRef.current); fpvSettleTimerRef.current = window.setTimeout(() => { @@ -1011,7 +565,6 @@ export function VanillaScene({ : false as const, }); controls.addEventListener("end", ((e: { camera: { rotX: number; rotY: number; zoom: number; target?: ReactVec3 } }) => { - // Convert back to legacy CSS-scale zoom on the way out — see LEGACY_ZOOM_COMPAT. onCameraChangeRef.current?.({ ...e.camera, zoom: e.camera.zoom / LEGACY_ZOOM_COMPAT }); }) as any); return controls; @@ -1020,9 +573,6 @@ export function VanillaScene({ if (fpvSettleTimerRef.current) { window.clearTimeout(fpvSettleTimerRef.current); fpvSettleTimerRef.current = 0; } controlsRef.current = buildControls(); return () => { - // Effect re-runs when deps change — destroy only on full unmount, - // which is signaled by the scene Effect 1 cleanup destroying scene. - // Until then, the next effect run will reuse + update controlsRef. if (fpvSettleTimerRef.current) { window.clearTimeout(fpvSettleTimerRef.current); fpvSettleTimerRef.current = 0; } }; }, [ @@ -1035,15 +585,11 @@ export function VanillaScene({ options.textureQuality, options.textureLighting, options.perspective, - stableDirectionalForRebuild, - stableAmbientForRebuild, stableDomForMesh, parseResult, ]); - // Effect 2.6 — live-update FPV options (booleans + numerics) without - // destroying the controls. Keeps the pointer-lock + camera target intact - // while sliders are dragged. + // Live-update FPV options without destroying controls useEffect(() => { if (options.dragMode !== "fpv") return; const handle = controlsRef.current as PolyFirstPersonControlsHandle | null; @@ -1065,210 +611,23 @@ export function VanillaScene({ options.fpvInvertY, ]); - // Effect 3 — axes helper. Add/remove based on toggle; rebuild when scale - // changes (different bar lengths bake into different polygons). - useEffect(() => { - const scene = sceneRef.current; - if (!scene) return; - if (!showAxes) { - if (axesHandleRef.current) { - axesHandleRef.current.dispose(); - axesHandleRef.current = null; - notifySceneDomChange(); - } - return; - } - axesHandleRef.current = scene.add( - { - polygons: axesHelperPolygons({ size: helperScale * 0.6 }), - objectUrls: [], - warnings: [], - dispose: () => { }, - }, - { excludeFromAutoCenter: true }, - ); - notifySceneDomChange(); - return () => { - axesHandleRef.current?.dispose(); - axesHandleRef.current = null; - notifySceneDomChange(); - }; - }, [ + useVanillaHelperMeshes({ + sceneRef, + axesHandleRef, + lightHandleRef, + groundHandleRef, showAxes, - helperScale, - polygons, - options.autoCenter, - options.textureQuality, - options.textureLighting, - options.perspective, - stableDirectionalForRebuild, - stableAmbientForRebuild, - parseResult, - notifySceneDomChange, - ]); - - // Effect 3.5 — ground receiver. A flat quad in the XY plane (Z is "up" - // in PolyCSS's world convention — the red-green plane in the axes helper - // is the floor) at the model's min-Z. Size from both footprint and full - // model scale so tall/narrow assets still get a usable floor. Gives shadows - // something to land on. excludeFromAutoCenter so toggling it doesn't shift - // the camera pivot; castShadow:false because the floor doesn't shadow itself. - useEffect(() => { - const scene = sceneRef.current; - if (!scene) return; - if (!showGround || polygons.length === 0) { - if (groundHandleRef.current) { - groundHandleRef.current.dispose(); - groundHandleRef.current = null; - notifySceneDomChange(); - } - return; - } - let minX = Infinity, minY = Infinity, minZ = Infinity; - let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity; - for (const p of polygons) { - for (const v of p.vertices) { - if (v[0] < minX) minX = v[0]; if (v[0] > maxX) maxX = v[0]; - if (v[1] < minY) minY = v[1]; if (v[1] > maxY) maxY = v[1]; - if (v[2] < minZ) minZ = v[2]; if (v[2] > maxZ) maxZ = v[2]; - } - } - if (!Number.isFinite(minZ)) { - if (groundHandleRef.current) { - groundHandleRef.current.dispose(); - groundHandleRef.current = null; - notifySceneDomChange(); - } - return; - } - const footprintSpan = Math.max(maxX - minX, maxY - minY, 1); - const modelSpan = Math.max(footprintSpan, maxZ - minZ, 1); - const pad = Math.max( - footprintSpan * GALLERY_GROUND_RADIUS_MULTIPLIER, - modelSpan * GALLERY_GROUND_MODEL_RADIUS_MULTIPLIER, - GALLERY_GROUND_MIN_RADIUS, - ); - const cx = (minX + maxX) / 2; - const cy = (minY + maxY) / 2; - const z = minZ + GROUND_Z_OFFSET; - const groundPoly: Polygon = { - vertices: [ - [cx - pad, cy - pad, z], - [cx + pad, cy - pad, z], - [cx + pad, cy + pad, z], - [cx - pad, cy + pad, z], - ], - color: options.groundColor || GALLERY_GROUND_COLOR, - }; - groundHandleRef.current = scene.add( - { - polygons: [groundPoly], - objectUrls: [], - warnings: [], - dispose: () => { }, - }, - // Floor MUST be a receiver — Three.js parity: no receiver, no - // shadow. PolyCSS dropped the legacy virtual-ground fallback so - // a `castShadow:true` mesh casts no shadow unless an explicit - // receiver mesh exists to catch it. The gallery floor is that - // receiver. Until the receiver-shadow path is hardened for - // perspective cameras, large tilts may visually under-render the - // shadow; that's a known follow-up (huge intrinsic receiver SVG - // vs ancestor `overflow:hidden`). - { excludeFromAutoCenter: true, castShadow: false, receiveShadow: true }, - ); - groundHandleRef.current.element.classList.add("dn-gallery-ground"); - notifySceneDomChange(); - return () => { - groundHandleRef.current?.dispose(); - groundHandleRef.current = null; - notifySceneDomChange(); - }; - }, [ showGround, - polygons, - options.autoCenter, - options.textureQuality, - options.textureLighting, - options.groundColor, - options.perspective, - stableDirectionalForRebuild, - stableAmbientForRebuild, - parseResult, - notifySceneDomChange, - ]); - - // Effect 4 — light helper. Octahedron at LOCAL origin so polygons stay - // stable across light moves; the light direction only updates the - // mesh wrapper transform. - useEffect(() => { - const scene = sceneRef.current; - if (!scene) return; - if (!showLight) { - if (lightHandleRef.current) { - lightHandleRef.current.dispose(); - lightHandleRef.current = null; - notifySceneDomChange(); - } - return; - } - const swatch = directionalLight.color ?? "#ffd54a"; - const handle = scene.add( - { - polygons: octahedronPolygons({ center: [0, 0, 0], size: helperScale * 0.05, color: swatch }), - objectUrls: [], - warnings: [], - dispose: () => { }, - }, - { - position: lightHelperPosition( - directionalLight, - helperTarget, - helperScale * 0.7, - ), - excludeFromAutoCenter: true, - }, - ); - handle.element.classList.add("dn-light-helper"); - lightHandleRef.current = handle; - notifySceneDomChange(); - return () => { - lightHandleRef.current?.dispose(); - lightHandleRef.current = null; - notifySceneDomChange(); - }; - // directionalLight.color triggers a remount because the swatch is - // baked into polygon data; direction is handled by Effect 5 below. - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [ showLight, helperScale, - directionalLight.color, + helperTarget, + directionalLight, polygons, - options.autoCenter, - options.textureQuality, - options.textureLighting, - options.perspective, - stableDirectionalForRebuild, - stableAmbientForRebuild, + options, + stableDomForMesh, parseResult, notifySceneDomChange, - ]); - - // Effect 5 — slide the light helper to the new orbit position whenever - // direction or target/distance change. Only updates the wrapper - // transform, no atlas work. - useEffect(() => { - const handle = lightHandleRef.current; - if (!handle) return; - handle.setTransform({ - position: lightHelperPosition( - directionalLight, - helperTarget, - helperScale * 0.7, - ), - }); - }, [directionalLight, helperTarget, helperScale]); + }); return
; } diff --git a/website/src/components/VanillaScene/index.ts b/website/src/components/VanillaScene/index.ts index 27578e035..a7939f75f 100644 --- a/website/src/components/VanillaScene/index.ts +++ b/website/src/components/VanillaScene/index.ts @@ -1,2 +1,2 @@ export { VanillaScene } from "./VanillaScene"; -export type { VanillaSceneProps } from "./VanillaScene"; +export type { VanillaSceneProps, VanillaSceneTransientHandle } from "./VanillaScene"; diff --git a/website/src/components/VanillaScene/sceneHelpers.ts b/website/src/components/VanillaScene/sceneHelpers.ts new file mode 100644 index 000000000..3ef39c0fa --- /dev/null +++ b/website/src/components/VanillaScene/sceneHelpers.ts @@ -0,0 +1,148 @@ +import type { + PolyAmbientLight, + PolyDirectionalLight, + Polygon, + Vec3 as ReactVec3, +} from "@layoutit/polycss-react"; +import type { + ParseResult, + PolyMeshHandle as VanillaPolyMeshHandle, + PolySceneHandle, + Vec3, +} from "@layoutit/polycss"; +import type { GizmoMode, SceneOptionsState } from "../types"; + +// Keep the visible ground just below the model floor so coplanar faces don't z-fight. +const GROUND_Z_OFFSET = -0.04; +const GALLERY_GROUND_COLOR = "#7d848e"; +const GALLERY_GROUND_RADIUS_MULTIPLIER = 2.5; +const GALLERY_GROUND_MODEL_RADIUS_MULTIPLIER = 1.75; +const GALLERY_GROUND_MIN_RADIUS = 40; + +export const GALLERY_SHADOW_LIFT = 0.01; +// Transitional compat: vanilla camera zoom is px-per-world-unit while shared +// workbench sceneOptions still carry unitless CSS-scale values. +export const LEGACY_ZOOM_COMPAT = 50; + +export interface VanillaSceneTransientHandle { + applySceneOptions(options: SceneOptionsState): void; + applyLightOptions(options: SceneOptionsState, preview?: { shadow?: boolean }): void; +} + +export type BakedSolidLightingPreviewSceneHandle = PolySceneHandle & { + previewBakedSolidLighting?: (next: { + directionalLight?: PolyDirectionalLight; + ambientLight?: PolyAmbientLight; + skipShadows?: boolean; + }) => boolean; + commitBakedSolidLighting?: () => boolean; +}; + +export interface VanillaSceneProps { + polygons: Polygon[]; + interiorShellPolygons: Polygon[]; + parseResult?: ParseResult; + options: SceneOptionsState; + directionalLight: PolyDirectionalLight; + ambientLight: PolyAmbientLight; + showAxes: boolean; + showLight: boolean; + showGround: boolean; + helperScale: number; + helperTarget: Vec3; + mergePolygonsForMesh: boolean; + stableDomForMesh: boolean; + animationKey?: string; + animationDurationSeconds?: number; + animationFrameFactory?: (timeSeconds: number) => Polygon[]; + onBuild?: (ms: number) => void; + onCameraChange?: (camera: { rotX: number; rotY: number; zoom: number; target?: ReactVec3 }) => void; + enableSelection?: boolean; + meshId?: string; + onSelectionChange?: (selectedIds: string[]) => void; + gizmoMode?: GizmoMode; + enableHover?: boolean; + onHoverChange?: (id: string | null) => void; + onMeshHandleChange?: (handle: VanillaPolyMeshHandle | null) => void; + onTransientHandleChange?: (handle: VanillaSceneTransientHandle | null) => void; + onSceneDomChange?: () => void; +} + +export function lightHelperPosition( + light: PolyDirectionalLight, + target: Vec3, + distance: number, +): Vec3 { + const [dx, dy, dz] = light.direction; + const len = Math.hypot(dx, dy, dz) || 1; + return [ + target[0] + (dx / len) * distance, + target[1] + (dy / len) * distance, + target[2] + (dz / len) * distance, + ]; +} + +export function bakedLightingSignature( + directionalLight: PolyDirectionalLight, + ambientLight: PolyAmbientLight, +): string { + return [ + directionalLight.direction.map((value) => value.toFixed(4)).join(","), + directionalLight.color ?? "", + directionalLight.intensity ?? "", + ambientLight.color ?? "", + ambientLight.intensity ?? "", + ].join("|"); +} + +export function fpvOptionsFromSceneOptions(options: SceneOptionsState) { + return { + enabled: options.interactive, + lookEnabled: options.fpvLook, + moveEnabled: options.fpvMove, + jumpEnabled: options.fpvJump, + crouchEnabled: options.fpvCrouch, + moveSpeed: options.fpvMoveSpeed, + jumpVelocity: options.fpvJumpVelocity, + gravity: options.fpvGravity, + eyeHeight: options.fpvEyeHeight, + crouchHeight: options.fpvCrouchHeight, + lookSensitivity: options.fpvLookSensitivity, + invertY: options.fpvInvertY, + }; +} + +export function buildGroundPolygon( + polygons: Polygon[], + groundColor?: string, +): Polygon | null { + let minX = Infinity, minY = Infinity, minZ = Infinity; + let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity; + for (const p of polygons) { + for (const v of p.vertices) { + if (v[0] < minX) minX = v[0]; if (v[0] > maxX) maxX = v[0]; + if (v[1] < minY) minY = v[1]; if (v[1] > maxY) maxY = v[1]; + if (v[2] < minZ) minZ = v[2]; if (v[2] > maxZ) maxZ = v[2]; + } + } + if (!Number.isFinite(minZ)) return null; + const footprintSpan = Math.max(maxX - minX, maxY - minY, 1); + const modelSpan = Math.max(footprintSpan, maxZ - minZ, 1); + const pad = Math.max( + footprintSpan * GALLERY_GROUND_RADIUS_MULTIPLIER, + modelSpan * GALLERY_GROUND_MODEL_RADIUS_MULTIPLIER, + GALLERY_GROUND_MIN_RADIUS, + ); + const cx = (minX + maxX) / 2; + const cy = (minY + maxY) / 2; + const z = minZ + GROUND_Z_OFFSET; + return { + vertices: [ + [cx - pad, cy - pad, z], + [cx + pad, cy - pad, z], + [cx + pad, cy + pad, z], + [cx - pad, cy + pad, z], + ], + color: groundColor || GALLERY_GROUND_COLOR, + }; +} diff --git a/website/src/components/VanillaScene/stableAnimationCache.ts b/website/src/components/VanillaScene/stableAnimationCache.ts new file mode 100644 index 000000000..c7f1a436f --- /dev/null +++ b/website/src/components/VanillaScene/stableAnimationCache.ts @@ -0,0 +1,286 @@ +import { useEffect, type RefObject } from "react"; +import type { Polygon } from "@layoutit/polycss-react"; +import type { PolyMeshHandle as VanillaPolyMeshHandle } from "@layoutit/polycss"; + +const ANIMATION_STABLE_TRIANGLE_COLOR_POLICY = "cadence"; +const ANIMATION_STABLE_TRIANGLE_COLOR_FREEZE_FRAMES = 0; +const ANIMATION_TRANSFORM_CACHE_FRAMES = 60; + +interface StableTriangleTransformFrameItem { + transform: string; + visibility: string; +} + +interface StableTriangleTransformCache { + frames: Array; + leaves: HTMLElement[] | null; + leafCount: number; + filled: number; + disabled: boolean; + canRefreshColor: boolean; + lastAppliedFrameIndex: number; +} + +function createStableTriangleTransformCache(): StableTriangleTransformCache { + return { + frames: Array.from({ length: ANIMATION_TRANSFORM_CACHE_FRAMES }), + leaves: null, + leafCount: 0, + filled: 0, + disabled: false, + canRefreshColor: false, + lastAppliedFrameIndex: -1, + }; +} + +function resetStableTriangleTransformCache(cache: StableTriangleTransformCache): void { + cache.frames.fill(undefined); + cache.leaves = null; + cache.leafCount = 0; + cache.filled = 0; + cache.canRefreshColor = false; + cache.lastAppliedFrameIndex = -1; +} + +function directStableAnimationLeaves(handle: VanillaPolyMeshHandle): HTMLElement[] { + return Array.from(handle.element.querySelectorAll(":scope > u,:scope > s")); +} + +function captureStableTriangleTransformFrame( + handle: VanillaPolyMeshHandle, + cache: StableTriangleTransformCache, + frameIndex: number, +): void { + if (cache.disabled) return; + const leaves = directStableAnimationLeaves(handle); + const expectedCount = handle.polygons.length; + if (expectedCount <= 0 || leaves.length !== expectedCount) { + cache.disabled = true; + resetStableTriangleTransformCache(cache); + return; + } + const canRefreshColor = leaves.every((leaf) => leaf.tagName === "U"); + if ( + cache.leafCount !== 0 && + (leaves.length !== cache.leafCount || cache.canRefreshColor !== canRefreshColor) + ) { + resetStableTriangleTransformCache(cache); + } + cache.leaves = leaves; + cache.leafCount = leaves.length; + cache.canRefreshColor = canRefreshColor; + if (!cache.frames[frameIndex]) cache.filled += 1; + cache.frames[frameIndex] = leaves.map((leaf) => ({ + transform: leaf.style.transform || "none", + visibility: leaf.style.visibility === "hidden" ? "hidden" : "", + })); + cache.lastAppliedFrameIndex = frameIndex; +} + +function applyStableTriangleTransformFrame( + handle: VanillaPolyMeshHandle, + cache: StableTriangleTransformCache, + frameIndex: number, +): boolean { + if (cache.disabled) return false; + const frame = cache.frames[frameIndex]; + if (!frame) return false; + if ( + cache.lastAppliedFrameIndex === frameIndex && + cache.leaves && + cache.leafCount === frame.length + ) { + return true; + } + const leaves = cache.leaves ?? directStableAnimationLeaves(handle); + if (leaves.length !== frame.length) { + resetStableTriangleTransformCache(cache); + return false; + } + const previousFrame = cache.lastAppliedFrameIndex >= 0 + ? cache.frames[cache.lastAppliedFrameIndex] + : undefined; + cache.leaves = leaves; + cache.leafCount = leaves.length; + for (let i = 0; i < leaves.length; i += 1) { + const leaf = leaves[i]; + const next = frame[i]; + const previous = previousFrame?.[i]; + if (previous?.transform !== next.transform) { + leaf.style.transform = next.transform; + } + if (previous?.visibility !== next.visibility) { + leaf.style.visibility = next.visibility; + } + } + cache.lastAppliedFrameIndex = frameIndex; + return true; +} + +function animationCacheFrameIndex( + timeSeconds: number, + durationSeconds: number, +): number { + const duration = Math.max(0.001, durationSeconds); + const localTime = ((timeSeconds % duration) + duration) % duration; + return Math.floor( + (localTime / duration) * ANIMATION_TRANSFORM_CACHE_FRAMES, + ) % ANIMATION_TRANSFORM_CACHE_FRAMES; +} + +export function useVanillaAnimationLoop({ + meshHandleRef, + animationPausedRef, + animationTimeScaleRef, + animationKey, + animationDurationSeconds, + animationFrameFactory, + textureLighting, + shadowFollowAnimation, + stableDomForMesh, +}: { + meshHandleRef: RefObject; + animationPausedRef: RefObject; + animationTimeScaleRef: RefObject; + animationKey?: string; + animationDurationSeconds?: number; + animationFrameFactory?: (timeSeconds: number) => Polygon[]; + textureLighting: "baked" | "dynamic"; + shadowFollowAnimation: boolean; + stableDomForMesh: boolean; +}): void { + useEffect(() => { + if (!animationFrameFactory || !animationKey) return; + let raf = 0; + let last = performance.now(); + let elapsedSeconds = 0; + let sampledSeconds: number | null = null; + let animationFrameCount = 0; + let lastAnimatedPolygonCount = 0; + const transformCache = + stableDomForMesh && + textureLighting === "baked" && + !shadowFollowAnimation && + typeof animationDurationSeconds === "number" && + animationDurationSeconds > 0 + ? createStableTriangleTransformCache() + : null; + + const tick = (now: number) => { + const deltaSeconds = Math.max(0, (now - last) / 1000); + last = now; + if (!animationPausedRef.current) { + elapsedSeconds += deltaSeconds * animationTimeScaleRef.current; + } + const handle = meshHandleRef.current; + if (handle && sampledSeconds !== elapsedSeconds) { + sampledSeconds = elapsedSeconds; + animationFrameCount += 1; + const debugTarget = window as unknown as { + __polycssGalleryAnimationSamples?: Array<{ + t: number; + sampleMs: number; + setPolygonsMs: number; + polygons: number; + transformCacheHit?: boolean; + transformCacheFilled?: number; + transformCacheMs?: number; + }>; + __polycssStableTriangleDebug?: "transform-only" | "plan-only"; + }; + const stableTriangleDebug = debugTarget.__polycssStableTriangleDebug; + const setPolygonsOptions = { + merge: false, + stableDom: true, + recomputeAutoCenter: false, + ...(stableTriangleDebug === "transform-only" || stableTriangleDebug === "plan-only" + ? { stableTriangleDebug } + : {}), + stableTriangleColorPolicy: ANIMATION_STABLE_TRIANGLE_COLOR_POLICY, + stableTriangleColorFreezeFrames: ANIMATION_STABLE_TRIANGLE_COLOR_FREEZE_FRAMES, + } satisfies Parameters[1] & { + stableTriangleDebug?: "transform-only" | "plan-only"; + stableTriangleUpdateMode?: "full" | "transform-only" | "color-only"; + stableTriangleColorPolicy: "cadence" | "adaptive"; + stableTriangleColorFreezeFrames: number; + }; + const canUseTransformCache = + transformCache && + !transformCache.disabled && + !stableTriangleDebug && + animationDurationSeconds !== undefined; + const frameIndex = canUseTransformCache + ? animationCacheFrameIndex(elapsedSeconds, animationDurationSeconds) + : -1; + const shouldRefreshColor = + canUseTransformCache && + transformCache.canRefreshColor && + ANIMATION_STABLE_TRIANGLE_COLOR_FREEZE_FRAMES > 0 && + animationFrameCount % ANIMATION_STABLE_TRIANGLE_COLOR_FREEZE_FRAMES === 0; + const samples = debugTarget.__polycssGalleryAnimationSamples; + let sampleMs = 0; + let setPolygonsMs = 0; + let transformCacheMs = 0; + let transformCacheHit = false; + if (canUseTransformCache) { + const cacheStart = samples ? performance.now() : 0; + transformCacheHit = applyStableTriangleTransformFrame( + handle, + transformCache, + frameIndex, + ); + transformCacheMs = samples ? performance.now() - cacheStart : 0; + } + if (transformCacheHit && shouldRefreshColor) { + const sampleStart = samples ? performance.now() : 0; + const animatedPolygons = animationFrameFactory(elapsedSeconds); + sampleMs = samples ? performance.now() - sampleStart : 0; + lastAnimatedPolygonCount = animatedPolygons.length; + const setStart = samples ? performance.now() : 0; + handle.setPolygons(animatedPolygons, { + ...setPolygonsOptions, + stableTriangleUpdateMode: "color-only", + } as Parameters[1]); + setPolygonsMs = samples ? performance.now() - setStart : 0; + } else if (!transformCacheHit) { + const sampleStart = samples ? performance.now() : 0; + const animatedPolygons = animationFrameFactory(elapsedSeconds); + sampleMs = samples ? performance.now() - sampleStart : 0; + lastAnimatedPolygonCount = animatedPolygons.length; + const setStart = samples ? performance.now() : 0; + handle.setPolygons(animatedPolygons, setPolygonsOptions); + setPolygonsMs = samples ? performance.now() - setStart : 0; + if (canUseTransformCache) { + captureStableTriangleTransformFrame(handle, transformCache, frameIndex); + } + } + if (samples) { + samples.push({ + t: now, + sampleMs, + setPolygonsMs, + polygons: lastAnimatedPolygonCount, + transformCacheHit, + transformCacheFilled: transformCache?.filled, + transformCacheMs, + }); + if (samples.length > 1800) samples.splice(0, samples.length - 1800); + } + } + raf = requestAnimationFrame(tick); + }; + + raf = requestAnimationFrame(tick); + return () => cancelAnimationFrame(raf); + }, [ + meshHandleRef, + animationPausedRef, + animationTimeScaleRef, + animationKey, + animationFrameFactory, + animationDurationSeconds, + textureLighting, + shadowFollowAnimation, + stableDomForMesh, + ]); +} diff --git a/website/src/components/VanillaScene/useVanillaSceneHelpers.ts b/website/src/components/VanillaScene/useVanillaSceneHelpers.ts new file mode 100644 index 000000000..945c8156a --- /dev/null +++ b/website/src/components/VanillaScene/useVanillaSceneHelpers.ts @@ -0,0 +1,199 @@ +import { useEffect, type MutableRefObject } from "react"; +import type { PolyDirectionalLight, Polygon } from "@layoutit/polycss-react"; +import { + axesHelperPolygons, + octahedronPolygons, + type ParseResult, + type PolyMeshHandle as VanillaPolyMeshHandle, + type PolySceneHandle, + type Vec3, +} from "@layoutit/polycss"; +import type { SceneOptionsState } from "../types"; +import { buildGroundPolygon, lightHelperPosition } from "./sceneHelpers"; + +export function useVanillaHelperMeshes({ + sceneRef, + axesHandleRef, + lightHandleRef, + groundHandleRef, + showAxes, + showGround, + showLight, + helperScale, + helperTarget, + directionalLight, + polygons, + options, + stableDomForMesh, + parseResult, + notifySceneDomChange, +}: { + sceneRef: MutableRefObject; + axesHandleRef: MutableRefObject; + lightHandleRef: MutableRefObject; + groundHandleRef: MutableRefObject; + showAxes: boolean; + showGround: boolean; + showLight: boolean; + helperScale: number; + helperTarget: Vec3; + directionalLight: PolyDirectionalLight; + polygons: Polygon[]; + options: SceneOptionsState; + stableDomForMesh: boolean; + parseResult?: ParseResult; + notifySceneDomChange: () => void; +}): void { + // Axes helper + useEffect(() => { + const scene = sceneRef.current; + if (!scene) return; + if (!showAxes) { + if (axesHandleRef.current) { + axesHandleRef.current.dispose(); + axesHandleRef.current = null; + notifySceneDomChange(); + } + return; + } + axesHandleRef.current = scene.add( + { + polygons: axesHelperPolygons({ size: helperScale * 0.6 }), + objectUrls: [], + warnings: [], + dispose: () => { }, + }, + { excludeFromAutoCenter: true }, + ); + notifySceneDomChange(); + return () => { + axesHandleRef.current?.dispose(); + axesHandleRef.current = null; + notifySceneDomChange(); + }; + }, [ + sceneRef, + axesHandleRef, + showAxes, + helperScale, + polygons, + options.autoCenter, + options.textureQuality, + options.textureLighting, + options.perspective, + stableDomForMesh, + parseResult, + notifySceneDomChange, + ]); + + // Ground receiver mesh + useEffect(() => { + const scene = sceneRef.current; + if (!scene) return; + if (!showGround || polygons.length === 0) { + if (groundHandleRef.current) { + groundHandleRef.current.dispose(); + groundHandleRef.current = null; + notifySceneDomChange(); + } + return; + } + const groundPoly = buildGroundPolygon(polygons, options.groundColor); + if (!groundPoly) { + if (groundHandleRef.current) { + groundHandleRef.current.dispose(); + groundHandleRef.current = null; + notifySceneDomChange(); + } + return; + } + groundHandleRef.current = scene.add( + { + polygons: [groundPoly], + objectUrls: [], + warnings: [], + dispose: () => { }, + }, + { excludeFromAutoCenter: true, castShadow: false, receiveShadow: true }, + ); + groundHandleRef.current.element.classList.add("dn-gallery-ground"); + notifySceneDomChange(); + return () => { + groundHandleRef.current?.dispose(); + groundHandleRef.current = null; + notifySceneDomChange(); + }; + }, [ + sceneRef, + groundHandleRef, + showGround, + polygons, + options.autoCenter, + options.textureQuality, + options.textureLighting, + options.groundColor, + options.perspective, + stableDomForMesh, + parseResult, + notifySceneDomChange, + ]); + + // Light helper octahedron + useEffect(() => { + const scene = sceneRef.current; + if (!scene) return; + if (!showLight) { + if (lightHandleRef.current) { + lightHandleRef.current.dispose(); + lightHandleRef.current = null; + notifySceneDomChange(); + } + return; + } + const swatch = directionalLight.color ?? "#ffd54a"; + const handle = scene.add( + { + polygons: octahedronPolygons({ center: [0, 0, 0], size: helperScale * 0.05, color: swatch }), + objectUrls: [], + warnings: [], + dispose: () => { }, + }, + { + position: lightHelperPosition(directionalLight, helperTarget, helperScale * 0.7), + excludeFromAutoCenter: true, + }, + ); + handle.element.classList.add("dn-light-helper"); + lightHandleRef.current = handle; + notifySceneDomChange(); + return () => { + lightHandleRef.current?.dispose(); + lightHandleRef.current = null; + notifySceneDomChange(); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [ + sceneRef, + lightHandleRef, + showLight, + helperScale, + directionalLight.color, + polygons, + options.autoCenter, + options.textureQuality, + options.textureLighting, + options.perspective, + stableDomForMesh, + parseResult, + notifySceneDomChange, + ]); + + // Slide the light helper without rebuilding its atlas. + useEffect(() => { + const handle = lightHandleRef.current; + if (!handle) return; + handle.setTransform({ + position: lightHelperPosition(directionalLight, helperTarget, helperScale * 0.7), + }); + }, [lightHandleRef, directionalLight, helperTarget, helperScale]); +} diff --git a/website/src/components/WordArtWorkbench/WordArtPanels.tsx b/website/src/components/WordArtWorkbench/WordArtPanels.tsx new file mode 100644 index 000000000..6556ea633 --- /dev/null +++ b/website/src/components/WordArtWorkbench/WordArtPanels.tsx @@ -0,0 +1,423 @@ +import { useEffect, useMemo, useRef, useState } from "react"; +import GUI from "lil-gui"; +import type { FontEntry } from "@layoutit/polycss-fonts"; +import { bezierToCss, parseBezier, TEXTURES, texUrl, type Bezier4 } from "./wordArtPresets"; + +export interface GuiValues { + layered: boolean; + profileMode: string; warp: string; bend: number; + depth: number; letterSpacing: number; lineHeight: number; scaleX: number; scaleY: number; + curveSegments: number; simplify: number; profileSegments: number; offset: number; + perspective: boolean; zoom: number; spin: boolean; + light: number; ambient: number; az: number; el: number; lightColor: string; +} + +/** One coordinate of a cubic Bézier P0..P3 at parameter t. */ +function cubicAt(p0: number, p1: number, p2: number, p3: number, t: number): number { + const m = 1 - t; + return m * m * m * p0 + 3 * m * m * t * p1 + 3 * m * t * t * p2 + t * t * t * p3; +} + +/** + * Mount a draggable cubic-bezier editor (the CSS easing curve) into `parent`. + * P0=(0,0) and P3=(1,1) are fixed; the two control handles drive `setB`. + * Returns a `redraw()` to resync the SVG when the value changes elsewhere. + */ +function mountBezierEditor(parent: HTMLElement, getB: () => Bezier4, setB: (b: Bezier4) => void): () => void { + const NS = "http://www.w3.org/2000/svg"; + const W = 220, H = 150, pad = 16; + const X = (x: number) => pad + x * (W - 2 * pad); + const Y = (y: number) => (H - pad) - y * (H - 2 * pad); + const el = (n: string, a: Record) => { + const e = document.createElementNS(NS, n); + for (const k in a) e.setAttribute(k, a[k]); + return e; + }; + const svg = el("svg", { viewBox: `0 0 ${W} ${H}`, class: "wa-bez" }); + const frame = el("rect", { x: `${X(0)}`, y: `${Y(1)}`, width: `${W - 2 * pad}`, height: `${H - 2 * pad}`, class: "wa-bez__frame" }); + const diag = el("line", { x1: `${X(0)}`, y1: `${Y(0)}`, x2: `${X(1)}`, y2: `${Y(1)}`, class: "wa-bez__diag" }); + const l1 = el("line", { class: "wa-bez__leg" }); + const l2 = el("line", { class: "wa-bez__leg" }); + const curve = el("path", { class: "wa-bez__curve" }); + const h1 = el("circle", { r: "5", class: "wa-bez__h" }); + const h2 = el("circle", { r: "5", class: "wa-bez__h" }); + svg.append(frame, diag, l1, l2, curve, h1, h2); + parent.appendChild(svg); + + let drawB: Bezier4 = getB(); + let active = 0; + let timer = 0; + const commit = (now: boolean) => { + clearTimeout(timer); + if (now) setB(drawB); + else timer = window.setTimeout(() => setB(drawB), 130); + }; + const render = () => { + const [x1, y1, x2, y2] = drawB; + let d = `M ${X(0)} ${Y(0)}`; + for (let i = 1; i <= 24; i++) { + const t = i / 24; + d += ` L ${X(cubicAt(0, x1, x2, 1, t))} ${Y(cubicAt(0, y1, y2, 1, t))}`; + } + curve.setAttribute("d", d); + l1.setAttribute("x1", `${X(0)}`); l1.setAttribute("y1", `${Y(0)}`); l1.setAttribute("x2", `${X(x1)}`); l1.setAttribute("y2", `${Y(y1)}`); + l2.setAttribute("x1", `${X(1)}`); l2.setAttribute("y1", `${Y(1)}`); l2.setAttribute("x2", `${X(x2)}`); l2.setAttribute("y2", `${Y(y2)}`); + h1.setAttribute("cx", `${X(x1)}`); h1.setAttribute("cy", `${Y(y1)}`); + h2.setAttribute("cx", `${X(x2)}`); h2.setAttribute("cy", `${Y(y2)}`); + }; + + const toData = (ev: PointerEvent): [number, number] => { + const r = svg.getBoundingClientRect(); + const x = (((ev.clientX - r.left) / r.width) * W - pad) / (W - 2 * pad); + const y = ((H - pad) - ((ev.clientY - r.top) / r.height) * H) / (H - 2 * pad); + return [Math.min(1, Math.max(0, x)), Math.min(1, Math.max(0, y))]; + }; + const move = (ev: PointerEvent) => { + if (!active) return; + const [x, y] = toData(ev); + drawB = [...drawB] as Bezier4; + if (active === 1) { drawB[0] = x; drawB[1] = y; } else { drawB[2] = x; drawB[3] = y; } + render(); + commit(false); + }; + const start = (handle: number, e: PointerEvent, target: SVGElement) => { + active = handle; + drawB = [...getB()] as Bezier4; + target.setPointerCapture(e.pointerId); + }; + h1.addEventListener("pointerdown", (e) => start(1, e as PointerEvent, h1 as SVGElement)); + h2.addEventListener("pointerdown", (e) => start(2, e as PointerEvent, h2 as SVGElement)); + svg.addEventListener("pointermove", move as EventListener); + svg.addEventListener("pointerup", () => { if (active) { active = 0; commit(true); } }); + render(); + return () => { if (!active) drawB = getB(); render(); }; +} + +/** Right-hand lil-gui control panel themed to match `/gallery`. */ +export function GuiPanel({ + id, + className = "", + values, + set, + onPreviewAxis, + bezier, + onBezier, +}: { + id?: string; + className?: string; + values: GuiValues; + set: (k: keyof GuiValues, v: number | string | boolean) => void; + onPreviewAxis: (axis: "sx" | "sy" | "sz", ratio: number) => void; + bezier: Bezier4; + onBezier: (b: Bezier4) => void; +}) { + const hostRef = useRef(null); + const valuesRef = useRef(values); + valuesRef.current = values; + const onPreviewAxisRef = useRef(onPreviewAxis); + onPreviewAxisRef.current = onPreviewAxis; + const previewDragRef = useRef(false); + const cfgRef = useRef({ ...values }); + const ctrlRef = useRef>>({}); + const bezierRef = useRef(bezier); + const onBezierRef = useRef(onBezier); + const bezUiRef = useRef<{ wrap: HTMLElement; input: HTMLInputElement; redraw: () => void } | null>(null); + + useEffect(() => { + const cfg = cfgRef.current; + const c = ctrlRef.current; + const gui = new GUI({ container: hostRef.current!, title: "Settings", width: 300 }); + const on = (k: keyof GuiValues) => (v: number | string | boolean) => set(k, v); + + const previewAxis = (k: keyof GuiValues, axis: "sx" | "sy" | "sz") => (v: number | string | boolean) => { + previewDragRef.current = true; + const base = (valuesRef.current[k] as number) || 1; + onPreviewAxisRef.current(axis, ((v as number) / base) || 1); + }; + const bake = (k: keyof GuiValues) => (v: number | string | boolean) => { + previewDragRef.current = false; + set(k, v); + }; + + const shape = gui.addFolder("Shape"); + c.profileMode = shape.add(cfg, "profileMode", { + "Flat (slab)": "flat", + "Bevel": "bevel", + "Round in": "round", + "Round out": "roundup", + "Custom curve": "custom", + }).name("Profile").onChange(on("profileMode")); + + c.bezierText = shape.add({ _: "" }, "_").name("Curve"); + { + const widget = c.bezierText.domElement.querySelector(".widget"); + const wrap = document.createElement("div"); + wrap.className = "wa-bezwrap"; + const input = document.createElement("input"); + if (widget) { + widget.replaceChildren(); + input.type = "text"; + input.className = "wa-input wa-bezinput"; + input.spellcheck = false; + input.addEventListener("change", () => { + const parsed = parseBezier(input.value); + if (parsed) onBezierRef.current(parsed); + }); + widget.appendChild(input); + } + shape.domElement.querySelector(".children")?.appendChild(wrap); + const redraw = mountBezierEditor(wrap, () => bezierRef.current, (b) => onBezierRef.current(b)); + bezUiRef.current = { wrap, input, redraw }; + } + + c.warp = shape.add(cfg, "warp", { + None: "none", "Arch up": "arch", "Arch down": "archDown", "Arc (circle)": "arc", + Wave: "wave", Bulge: "bulge", "Cone (taper)": "cone", "Slant up": "slantUp", "Slant down": "slantDown", + }).name("Warp").onChange(on("warp")); + c.bend = shape.add(cfg, "bend", 0, 1, 0.02).name("Bend").onFinishChange(on("bend")); + + const layout = gui.addFolder("Layout"); + c.depth = layout.add(cfg, "depth", 2, 80, 1).name("Depth").onChange(previewAxis("depth", "sz")).onFinishChange(bake("depth")); + c.letterSpacing = layout.add(cfg, "letterSpacing", -20, 60, 1).name("Letter spacing").onFinishChange(on("letterSpacing")); + c.lineHeight = layout.add(cfg, "lineHeight", 0.8, 2.5, 0.05).name("Line height").onFinishChange(on("lineHeight")); + c.scaleX = layout.add(cfg, "scaleX", 40, 200, 1).name("Scale X").onChange(on("scaleX")); + c.scaleY = layout.add(cfg, "scaleY", 40, 200, 1).name("Scale Y").onChange(on("scaleY")); + c.curveSegments = layout.add(cfg, "curveSegments", 1, 12, 1).name("Curve segments").onFinishChange(on("curveSegments")); + c.simplify = layout.add(cfg, "simplify", 0, 8, 0.5).name("Simplify").onFinishChange(on("simplify")); + c.profileSegments = layout.add(cfg, "profileSegments", 2, 10, 1).name("Edge segments").onFinishChange(on("profileSegments")); + c.offset = layout.add(cfg, "offset", 0, 32, 1).name("Layer offset").onFinishChange(on("offset")); + c.layered = layout.add(cfg, "layered").name("Flat layers").onChange(on("layered")); + + const cam = gui.addFolder("Camera"); + c.perspective = cam.add(cfg, "perspective").name("Perspective").onChange(on("perspective")); + c.zoom = cam.add(cfg, "zoom", 0.1, 6, 0.05).name("Zoom").onChange(on("zoom")); + c.spin = cam.add(cfg, "spin").name("Auto-spin").onChange(on("spin")); + + const lighting = gui.addFolder("Lighting"); + c.light = lighting.add(cfg, "light", 0, 2, 0.05).name("Light").onChange(on("light")); + c.ambient = lighting.add(cfg, "ambient", 0, 1, 0.05).name("Ambient").onChange(on("ambient")); + c.az = lighting.add(cfg, "az", -90, 90, 1).name("Angle").onChange(on("az")); + c.el = lighting.add(cfg, "el", 0, 90, 1).name("Elev.").onChange(on("el")); + c.lightColor = lighting.addColor(cfg, "lightColor").name("Light color").onChange(on("lightColor")); + + return () => gui.destroy(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + useEffect(() => { + if (!previewDragRef.current) { + Object.assign(cfgRef.current, values); + for (const ctrl of Object.values(ctrlRef.current)) ctrl?.updateDisplay(); + } + bezierRef.current = bezier; + onBezierRef.current = onBezier; + const isCustom = values.profileMode.startsWith("custom"); + ctrlRef.current.bend?.[values.warp !== "none" ? "show" : "hide"](); + ctrlRef.current.profileSegments?.[(values.profileMode.startsWith("round") || isCustom) ? "show" : "hide"](); + ctrlRef.current.bezierText?.[isCustom ? "show" : "hide"](); + if (bezUiRef.current) { + bezUiRef.current.wrap.style.display = isCustom ? "" : "none"; + bezUiRef.current.redraw(); + if (document.activeElement !== bezUiRef.current.input) bezUiRef.current.input.value = bezierToCss(bezier); + } + }); + + return
; +} + +export interface LeftValues { + weight: number; italic: boolean; underline: boolean; strike: boolean; + textCase: string; align: string; color: string; sideColor: string; backColor: string; + fillType: string; gradA: string; gradB: string; gradAngle: number; image: string; + faceTex: string; sideFill: string; sideTex: string; backFill: string; backTex: string; + outlineOn: boolean; outlineColor: string; outlineWidth: number; +} + +/** lil-gui typography + color panel for the left card. */ +export function LeftGuiPanel({ values, set }: { values: LeftValues; set: (k: keyof LeftValues, v: number | string | boolean) => void }) { + const hostRef = useRef(null); + const cfgRef = useRef({ ...values }); + const ctrlRef = useRef>>({}); + const segRef = useRef void>>({}); + const texRef = useRef void>>({}); + const texWrapRef = useRef>({}); + + useEffect(() => { + const cfg = cfgRef.current; + const c = ctrlRef.current; + const gui = new GUI({ container: hostRef.current!, title: "", width: 300 }); + const on = (k: keyof LeftValues) => (v: number | string | boolean) => set(k, v); + + const segmented = (folder: GUI, name: string, key: keyof LeftValues, options: [string, string, string][]) => { + const ctrl = folder.add({ _: "" }, "_").name(name); + const widget = ctrl.domElement.querySelector(".widget"); + if (!widget) return; + widget.replaceChildren(); + widget.classList.add("wa-seg"); + const btns: Record = {}; + for (const [value, label, title] of options) { + const btn = document.createElement("button"); + btn.type = "button"; + btn.textContent = label; + btn.title = title; + btn.addEventListener("click", () => set(key, value)); + widget.appendChild(btn); + btns[value] = btn; + } + segRef.current[key] = (v: string) => { + for (const k in btns) btns[k].classList.toggle("is-on", k === v); + }; + }; + + const type = gui.addFolder("Type"); + c.weight = type.add(cfg, "weight", [100, 200, 300, 400, 500, 600, 700, 800, 900]).name("Weight").onChange(on("weight")); + c.italic = type.add(cfg, "italic").name("Italic").onChange(on("italic")); + c.underline = type.add(cfg, "underline").name("Underline").onChange(on("underline")); + c.strike = type.add(cfg, "strike").name("Strikethrough").onChange(on("strike")); + segmented(type, "Case", "textCase", [["as-typed", "Aa", "As typed"], ["upper", "AB", "UPPERCASE"], ["lower", "ab", "lowercase"], ["title", "Ab", "Title Case"]]); + segmented(type, "Align", "align", [["left", "L", "Left"], ["center", "C", "Center"], ["right", "R", "Right"]]); + + const col = gui.addFolder("Color"); + const colChildren = col.domElement.querySelector(".children"); + + const texGrid = (key: keyof LeftValues) => { + const wrap = document.createElement("div"); + wrap.className = "wa-texrow"; + const grid = document.createElement("div"); + grid.className = "wa-texgrid"; + wrap.append(grid); + const swatches: Record = {}; + for (const t of TEXTURES) { + const sw = document.createElement("button"); + sw.type = "button"; + sw.className = "wa-texgrid__sw"; + sw.title = t.label; + sw.style.backgroundImage = `url(${texUrl(t.id)})`; + sw.addEventListener("click", () => set(key, t.id)); + grid.appendChild(sw); + swatches[t.id] = sw; + } + colChildren?.appendChild(wrap); + texRef.current[key] = (v: string) => { + for (const id in swatches) swatches[id].classList.toggle("is-on", id === v); + }; + texWrapRef.current[key] = wrap; + }; + + c.fillType = col.add(cfg, "fillType", { Solid: "solid", Gradient: "gradient", Rainbow: "rainbow", Texture: "texture", Image: "image" }).name("Front").onChange(on("fillType")); + c.color = col.addColor(cfg, "color").name("Color").onChange(on("color")); + c.gradA = col.addColor(cfg, "gradA").name("Color A").onChange(on("gradA")); + c.gradB = col.addColor(cfg, "gradB").name("Color B").onChange(on("gradB")); + c.gradAngle = col.add(cfg, "gradAngle", 0, 360, 5).name("Angle").onChange(on("gradAngle")); + c.image = col.add({ _: "" }, "_").name("Image"); + { + const widget = c.image.domElement.querySelector(".widget"); + if (widget) { + widget.replaceChildren(); + const btn = document.createElement("button"); + btn.type = "button"; + btn.className = "wa-imgbtn"; + btn.textContent = "Choose image…"; + const input = document.createElement("input"); + input.type = "file"; + input.accept = "image/*"; + input.style.display = "none"; + btn.addEventListener("click", () => input.click()); + input.addEventListener("change", () => { + const file = input.files?.[0]; + if (!file) return; + const reader = new FileReader(); + reader.onload = () => set("image", String(reader.result)); + reader.readAsDataURL(file); + }); + widget.append(btn, input); + } + } + texGrid("faceTex"); + + c.sideFill = col.add(cfg, "sideFill", { Solid: "solid", Texture: "texture", None: "none" }).name("Sides").onChange(on("sideFill")); + c.sideColor = col.addColor(cfg, "sideColor").name("Color").onChange(on("sideColor")); + texGrid("sideTex"); + + c.backFill = col.add(cfg, "backFill", { Solid: "solid", Texture: "texture", None: "none" }).name("Back").onChange(on("backFill")); + c.backColor = col.addColor(cfg, "backColor").name("Color").onChange(on("backColor")); + texGrid("backTex"); + + c.outlineOn = col.add(cfg, "outlineOn").name("Outline").onChange(on("outlineOn")); + c.outlineColor = col.addColor(cfg, "outlineColor").name("Outline color").onChange(on("outlineColor")); + c.outlineWidth = col.add(cfg, "outlineWidth", 0.5, 12, 0.5).name("Outline width").onChange(on("outlineWidth")); + + return () => gui.destroy(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + useEffect(() => { + Object.assign(cfgRef.current, values); + for (const ctrl of Object.values(ctrlRef.current)) ctrl?.updateDisplay(); + segRef.current.textCase?.(values.textCase); + segRef.current.align?.(values.align); + const grad = values.fillType === "gradient"; + ctrlRef.current.color?.[values.fillType === "solid" ? "show" : "hide"](); + ctrlRef.current.gradA?.[grad ? "show" : "hide"](); + ctrlRef.current.gradB?.[grad ? "show" : "hide"](); + ctrlRef.current.gradAngle?.[grad || values.fillType === "rainbow" ? "show" : "hide"](); + ctrlRef.current.image?.[values.fillType === "image" ? "show" : "hide"](); + texWrapRef.current.faceTex?.style.setProperty("display", values.fillType === "texture" ? "" : "none"); + ctrlRef.current.sideColor?.[values.sideFill === "solid" ? "show" : "hide"](); + texWrapRef.current.sideTex?.style.setProperty("display", values.sideFill === "texture" ? "" : "none"); + ctrlRef.current.backColor?.[values.backFill === "solid" ? "show" : "hide"](); + texWrapRef.current.backTex?.style.setProperty("display", values.backFill === "texture" ? "" : "none"); + ctrlRef.current.outlineColor?.[values.outlineOn ? "show" : "hide"](); + ctrlRef.current.outlineWidth?.[values.outlineOn ? "show" : "hide"](); + texRef.current.faceTex?.(values.faceTex); + texRef.current.sideTex?.(values.sideTex); + texRef.current.backTex?.(values.backTex); + }); + + return
; +} + +/** Searchable font dropdown — filters the catalog as you type. */ +export function FontPicker({ catalog, value, onPick }: { catalog: FontEntry[]; value: string; onPick: (family: string) => void }) { + const [open, setOpen] = useState(false); + const [query, setQuery] = useState(value); + const wrapRef = useRef(null); + useEffect(() => { setQuery(value); }, [value]); + const results = useMemo(() => { + const q = query.trim().toLowerCase(); + return (q ? catalog.filter((f) => f.family.toLowerCase().includes(q)) : catalog).slice(0, 80); + }, [query, catalog]); + useEffect(() => { + const h = (e: PointerEvent) => { + if (wrapRef.current && !wrapRef.current.contains(e.target as Node)) setOpen(false); + }; + document.addEventListener("pointerdown", h); + return () => document.removeEventListener("pointerdown", h); + }, []); + return ( +
+ setOpen(true)} + onChange={(e) => { setQuery(e.target.value); setOpen(true); }} + /> + {open && results.length > 0 && ( +
    + {results.map((f) => ( +
  • { onPick(f.family); setQuery(f.family); setOpen(false); }} + > + {f.family} +
  • + ))} +
+ )} +
+ ); +} diff --git a/website/src/components/WordArtWorkbench/WordArtStage.tsx b/website/src/components/WordArtWorkbench/WordArtStage.tsx new file mode 100644 index 000000000..cd12a231a --- /dev/null +++ b/website/src/components/WordArtWorkbench/WordArtStage.tsx @@ -0,0 +1,148 @@ +import { useEffect, useLayoutEffect, useRef, useState } from "react"; +import { + BASE_TILE, + PolyMesh, + PolyOrthographicCamera, + PolyPerspectiveCamera, + PolyScene, +} from "@layoutit/polycss-react"; +import type { Polygon, Vec3 } from "@layoutit/polycss-react"; +import { fitZoom } from "./wordArtPresets"; + +export interface StageProps { + polygons: Polygon[]; + preview: { sx: number; sy: number; sz: number }; + onFrameReady: () => void; + scaleXFrac: number; + scaleYFrac: number; + zoomScale: number; + setZoomScale: (updater: (prev: number) => number) => void; + perspective: boolean; + lightDir: Vec3; + lightIntensity: number; + lightColor: string; + ambient: number; + spin: boolean; + status: string; +} + +/** + * Isolated render surface. Rotation lives in refs and is written straight to + * the DOM — no React state per frame, so spinning/dragging stays at full FPS. + */ +export function Stage({ + polygons, + preview, + onFrameReady, + scaleXFrac, + scaleYFrac, + zoomScale, + setZoomScale, + perspective, + lightDir, + lightIntensity, + lightColor, + ambient, + spin, + status, +}: StageProps) { + const stageRef = useRef(null); + const wrapRef = useRef(null); + const [stage, setStage] = useState({ w: 900, h: 600 }); + const spinRef = useRef(0); + const tiltRef = useRef(8); + const draggingRef = useRef(false); + const lastPtr = useRef({ x: 0, y: 0 }); + + const previewRef = useRef(preview); + previewRef.current = preview; + const scaleRef = useRef({ x: scaleXFrac, y: scaleYFrac }); + scaleRef.current = { x: scaleXFrac, y: scaleYFrac }; + const applyRotation = () => { + const el = wrapRef.current; + const p = previewRef.current; + const s = scaleRef.current; + if (el) el.style.transform = `rotateX(${tiltRef.current}deg) rotateY(${spinRef.current}deg) scale3d(${s.x}, ${s.y}, ${p.sz})`; + }; + useLayoutEffect(applyRotation); + + useEffect(() => { + const el = stageRef.current; + if (!el) return; + const ro = new ResizeObserver(() => setStage({ w: el.clientWidth, h: el.clientHeight })); + ro.observe(el); + setStage({ w: el.clientWidth, h: el.clientHeight }); + return () => ro.disconnect(); + }, []); + + useEffect(() => { + if (!spin) return; + let raf = 0; + let last = performance.now(); + const tick = (now: number) => { + const dt = (now - last) / 1000; + last = now; + if (!draggingRef.current) { + spinRef.current = (spinRef.current - dt * 32) % 360; + applyRotation(); + } + raf = requestAnimationFrame(tick); + }; + raf = requestAnimationFrame(tick); + return () => cancelAnimationFrame(raf); + }, [spin]); + + const onPointerDown = (e: React.PointerEvent) => { + draggingRef.current = true; + lastPtr.current = { x: e.clientX, y: e.clientY }; + e.currentTarget.setPointerCapture(e.pointerId); + }; + const onPointerMove = (e: React.PointerEvent) => { + if (!draggingRef.current) return; + const dx = e.clientX - lastPtr.current.x; + const dy = e.clientY - lastPtr.current.y; + lastPtr.current = { x: e.clientX, y: e.clientY }; + spinRef.current += dx * 0.4; + tiltRef.current = Math.max(-85, Math.min(85, tiltRef.current - dy * 0.4)); + applyRotation(); + }; + const onPointerUp = (e: React.PointerEvent) => { + draggingRef.current = false; + e.currentTarget.releasePointerCapture(e.pointerId); + }; + const onWheel = (e: React.WheelEvent) => { + const factor = Math.pow(0.95, e.deltaY * 0.012); + setZoomScale((z) => Math.max(0.1, Math.min(6, z * factor))); + }; + + const zoom = fitZoom(polygons, stage.w, stage.h, scaleXFrac, scaleYFrac) * zoomScale * BASE_TILE; + const Cam = perspective ? PolyPerspectiveCamera : PolyOrthographicCamera; + + return ( +
+ + +
+ +
+
+
+
+ {polygons.length.toLocaleString()} polygons{status ? ` · ${status}` : ""} +
+
+ ); +} diff --git a/website/src/components/WordArtWorkbench/WordArtWorkbench.tsx b/website/src/components/WordArtWorkbench/WordArtWorkbench.tsx index e8c2913bc..b96153fec 100644 --- a/website/src/components/WordArtWorkbench/WordArtWorkbench.tsx +++ b/website/src/components/WordArtWorkbench/WordArtWorkbench.tsx @@ -1,16 +1,8 @@ -import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; -import { - BASE_TILE, - PolyMesh, - PolyOrthographicCamera, - PolyPerspectiveCamera, - PolyScene, -} from "@layoutit/polycss-react"; -import type { Vec3 } from "@layoutit/polycss-react"; -import type { Polygon } from "@layoutit/polycss-react"; +import { useEffect, useMemo, useState } from "react"; +import type { Polygon, Vec3 } from "@layoutit/polycss-react"; import { exportPolySceneSnapshot } from "@layoutit/polycss"; -import GUI from "lil-gui"; import { StatsOverlay } from "../StatsOverlay"; +import { openCodePen } from "../helpers/codePen"; import { composeText, listGoogleFonts, @@ -27,161 +19,21 @@ import { type Profile, type WarpShape, } from "@layoutit/polycss-fonts"; +import { + PRESETS, + applyCase, + readable, + texUrl, + type Align, + type Bezier4, + type FaceFill, + type FillType, + type Preset, +} from "./wordArtPresets"; +import { Stage } from "./WordArtStage"; +import { FontPicker, GuiPanel, LeftGuiPanel, type GuiValues, type LeftValues } from "./WordArtPanels"; import "./wordart.css"; -type Align = "left" | "center" | "right"; -type FillType = "solid" | "gradient" | "rainbow" | "texture" | "image"; -type FaceFill = "solid" | "texture" | "none"; -type Bezier4 = [number, number, number, number]; - -// Named CSS easings → cubic-bezier control points, for the custom edge profile. -const CSS_EASINGS: Record = { - linear: [0, 0, 1, 1], - ease: [0.25, 0.1, 0.25, 1], - "ease-in": [0.42, 0, 1, 1], - "ease-out": [0, 0, 0.58, 1], - "ease-in-out": [0.42, 0, 0.58, 1], -}; - -/** Parse a CSS easing string (`cubic-bezier(...)` or a keyword) to 4 controls. */ -function parseBezier(input: string): Bezier4 | null { - const s = input.trim().toLowerCase(); - if (CSS_EASINGS[s]) return CSS_EASINGS[s]; - const m = /cubic-bezier\(\s*([\d.+-]+)[ ,]+([\d.+-]+)[ ,]+([\d.+-]+)[ ,]+([\d.+-]+)\s*\)/.exec(s); - if (!m) return null; - const p = [m[1], m[2], m[3], m[4]].map(Number) as Bezier4; - return p.every((n) => !Number.isNaN(n)) ? p : null; -} -const bezierToCss = (b: Bezier4) => `cubic-bezier(${b.map((n) => +n.toFixed(2)).join(", ")})`; - -// Bundled voxel-style block textures (Layoutit voxels set), served locally from -// public/textures/wordart so the atlas canvas stays same-origin (no CORS taint). -const TEXTURES: { id: string; label: string }[] = [ - { id: "dirt", label: "Dirt" }, { id: "dirt2", label: "Dirt 2" }, { id: "grass3", label: "Grass" }, - { id: "brick", label: "Brick" }, { id: "brick2", label: "Brick 2" }, { id: "wood", label: "Wood" }, - { id: "wood3", label: "Plank" }, { id: "rock", label: "Rock" }, { id: "rock3", label: "Rock 2" }, - { id: "ice", label: "Ice" }, { id: "ice3", label: "Ice 2" }, { id: "glass", label: "Glass" }, - { id: "sand", label: "Sand" }, { id: "cacti", label: "Cactus" }, { id: "mine", label: "Ore" }, { id: "mine4", label: "Ore 2" }, -]; -const texUrl = (id: string) => (id ? `/textures/wordart/${id}.svg` : ""); - -interface Preset { - label: string; - profile: ExtrudeProfile; - depth: number; - color: string; - sideColor: string; - /** Back-face color (layered look when different + offset > 0). */ - backColor?: string; - /** Diagonal back offset for the layered block (down-right). */ - offset?: number; - warp?: { shape: WarpShape; amount: number }; - /** Face fill (defaults to solid `color`). */ - fill?: FillType; - gradA?: string; - gradB?: string; - gradAngle?: number; - /** Block-texture ids for the front / sides / back faces. */ - faceTex?: string; - sideTex?: string; - backTex?: string; - outline?: { color: string; width: number }; - /** Flat two-layer drop shadow (no extrusion walls). */ - layered?: boolean; - /** CSS background for the preset tile thumbnail (defaults to `color`). */ - thumb?: string; -} - -// Left-rail style presets — each is a full "look": extrusion, layered front/back, -// and/or a baked-in WordArt warp (like the builder's shape tiles). -const PRESETS: Preset[] = [ - { label: "Gold Gradient", profile: "bevel", depth: 26, color: "#ffd23f", sideColor: "#7c4a12", - fill: "gradient", gradA: "#ffe14d", gradB: "#ff7a1a", gradAngle: 270, thumb: "linear-gradient(#ffe14d,#ff7a1a)" }, - { label: "Grape Pop", profile: "flat", depth: 5, color: "#b14be0", sideColor: "#7a8cff", backColor: "#8aa0ff", offset: 14, layered: true, - fill: "gradient", gradA: "#c45cf0", gradB: "#7a1fb8", gradAngle: 270, thumb: "linear-gradient(#c45cf0,#7a1fb8)" }, - { label: "Chrome", profile: "bevel", depth: 22, color: "#d7dde4", sideColor: "#3a2222", - fill: "gradient", gradA: "#f4f8ff", gradB: "#9a4b4b", gradAngle: 270, thumb: "linear-gradient(#f4f8ff 45%,#9a4b4b)" }, - { label: "Rainbow", profile: "flat", depth: 10, color: "#ff5e3a", sideColor: "#7a2a55", - fill: "rainbow", gradAngle: 0, thumb: "linear-gradient(90deg,#ff3b30,#ffcc00,#34c759,#007aff,#af52de)" }, - { label: "Sky Outline", profile: "flat", depth: 8, color: "#7ec8ff", sideColor: "#2b50b0", - outline: { color: "#1838b8", width: 3 }, thumb: "#7ec8ff" }, - { label: "Grass Block", profile: "flat", depth: 18, color: "#6ab04c", sideColor: "#6b4a2b", - fill: "texture", faceTex: "grass3", sideTex: "dirt", thumb: "url(/textures/wordart/grass3.svg) center/cover" }, - { label: "Brick Wall", profile: "bevel", depth: 22, color: "#a8432a", sideColor: "#7a2f1d", - fill: "texture", faceTex: "brick", sideTex: "brick2", thumb: "url(/textures/wordart/brick.svg) center/cover" }, - { label: "Stone", profile: "flat", depth: 20, color: "#8d8d8d", sideColor: "#5a5a5a", - fill: "texture", faceTex: "rock", sideTex: "rock3", thumb: "url(/textures/wordart/rock.svg) center/cover" }, - { label: "Ice", profile: "bevel", depth: 18, color: "#b9e6ff", sideColor: "#6aa9cc", - fill: "texture", faceTex: "ice", sideTex: "ice3", thumb: "url(/textures/wordart/ice.svg) center/cover" }, - { label: "Gold Bevel", profile: "bevel", depth: 26, color: "#d4a82a", sideColor: "#7c5e16" }, - { label: "Retro Block", profile: "flat", depth: 6, color: "#ff4d6d", sideColor: "#3a0ca3", backColor: "#3a0ca3", offset: 16, layered: true, thumb: "#ff4d6d" }, - { label: "Arch Gold", profile: "bevel", depth: 22, color: "#e9b949", sideColor: "#8a5a12", warp: { shape: "arch", amount: 0.6 } }, - { label: "Wave Mint", profile: "round", depth: 24, color: "#7cffb2", sideColor: "#2f8f5e", warp: { shape: "wave", amount: 0.55 } }, - { label: "Ink Shadow", profile: "flat", depth: 4, color: "#e8edf2", sideColor: "#2b313b", backColor: "#2b313b", offset: 12, layered: true, thumb: "#e8edf2" }, -]; - -function applyCase(text: string, mode: "as-typed" | "upper" | "lower" | "title"): string { - if (mode === "upper") return text.toUpperCase(); - if (mode === "lower") return text.toLowerCase(); - if (mode === "title") return text.replace(/\b\p{L}/gu, (c) => c.toUpperCase()); - return text; -} - -function readable(hex: string): string { - const m = /^#?([0-9a-f]{6})$/i.exec(hex); - if (!m) return "#000"; - const n = parseInt(m[1], 16); - const lum = 0.299 * ((n >> 16) & 255) + 0.587 * ((n >> 8) & 255) + 0.114 * (n & 255); - return lum > 150 ? "#0b0f18" : "#ffffff"; -} - -function fitZoom(polygons: Polygon[], stageW: number, stageH: number, scaleX = 1, scaleY = 1): number { - if (!polygons.length) return 0.06; - let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity, minZ = Infinity, maxZ = -Infinity; - for (const p of polygons) { - for (const v of p.vertices) { - if (v[0] < minX) minX = v[0]; if (v[0] > maxX) maxX = v[0]; - if (v[1] < minY) minY = v[1]; if (v[1] > maxY) maxY = v[1]; - if (v[2] < minZ) minZ = v[2]; if (v[2] > maxZ) maxZ = v[2]; - } - } - // Flat text: Y = width (screen-right), X = height (screen-down), Z = depth. - // As the mesh turntables, width swings into depth, so fit the larger of the - // two. Scale X/Y are applied as a CSS transform on the mesh (not baked), so - // multiply the base bounds by them here to frame the *scaled* word — the - // camera then compensates the wrapper scale, keeping the word framed and the - // texture ~base resolution. - const horizontal = Math.max((maxY - minY) * scaleX, maxZ - minZ); - const vertical = (maxX - minX) * scaleY; - const fitW = (stageW * 0.7) / (Math.max(horizontal, 1) * BASE_TILE); - const fitH = (stageH * 0.68) / (Math.max(vertical, 1) * BASE_TILE); - return Math.max(0.01, Math.min(0.2, Math.min(fitW, fitH))); -} - -function codePenPayload(snapshotHtml: string, title: string): string { - const parsed = new DOMParser().parseFromString(snapshotHtml, "text/html"); - const css = Array.from(parsed.querySelectorAll("style")).map((s) => s.textContent ?? "").filter(Boolean).join("\n\n"); - const html = parsed.body.innerHTML.trim() || snapshotHtml; - return JSON.stringify({ title, html, css, editors: "100", layout: "left" }); -} - -function openCodePen(html: string, title: string): void { - const form = document.createElement("form"); - form.action = "https://codepen.io/pen/define"; - form.method = "POST"; - form.target = "_blank"; - form.setAttribute("rel", "noopener noreferrer"); - form.style.display = "none"; - const input = document.createElement("input"); - input.type = "hidden"; - input.name = "data"; - input.value = codePenPayload(html, title); - form.appendChild(input); - document.body.appendChild(form); - form.submit(); - form.remove(); -} - // All controls persist to the URL query string so any look is a shareable link. const URL_SEARCH = typeof window !== "undefined" ? new URLSearchParams(window.location.search) : new URLSearchParams(); const qs = (k: string, d: string) => URL_SEARCH.get(k) ?? d; @@ -223,7 +75,6 @@ export function WordArtWorkbench() { const [warpShape, setWarpShape] = useState(() => qs("warp", "none") as WarpShape); const [warpAmount, setWarpAmount] = useState(() => qn("bend", 0.5)); const [spin, setSpin] = useState(() => qb("spin", true)); - // Face fill (solid / gradient / rainbow / image), outline, flat-layer shadow. const [fillType, setFillType] = useState(() => qs("fill", "solid") as FillType); const [gradA, setGradA] = useState(() => qs("ga", "#ffd23f")); const [gradB, setGradB] = useState(() => qs("gb", "#ff5e3a")); @@ -238,7 +89,6 @@ export function WordArtWorkbench() { const [outlineColor, setOutlineColor] = useState(() => qs("olc", "#1a1a2e")); const [outlineWidth, setOutlineWidth] = useState(() => qn("olw", 3)); const [layered, setLayered] = useState(() => qb("layer", false)); - // Camera + lighting (gallery-style) const [perspective, setPerspective] = useState(() => qb("persp", true)); const [zoomScale, setZoomScale] = useState(() => qn("zoom", 1)); const [lightIntensity, setLightIntensity] = useState(() => qn("li", 0.95)); @@ -248,7 +98,6 @@ export function WordArtWorkbench() { const [lightEl, setLightEl] = useState(() => qn("lel", 45)); const [activePreset, setActivePreset] = useState(null); const [exporting, setExporting] = useState(false); - // Mobile: only one floating panel is open at a time, toggled by the bottom tabs. const [mobilePanel, setMobilePanel] = useState<"style" | "controls" | null>(null); const handleCodePen = async () => { @@ -273,8 +122,6 @@ export function WordArtWorkbench() { return () => window.removeEventListener("keydown", onKey); }, [mobilePanel]); - // Default bundled font + Google catalog. If the URL named a font, select it - // once the catalog is in. useEffect(() => { loadFont("/fonts/default.ttf").then(setFont).catch((e) => setStatus(String(e))); listGoogleFonts() @@ -289,7 +136,6 @@ export function WordArtWorkbench() { .catch(() => {}); }, []); - // Persist every control to the URL (non-defaults only, for short links). useEffect(() => { const p = new URLSearchParams(); const ss = (k: string, v: string, d: string) => { if (v !== d) p.set(k, v); }; @@ -344,7 +190,6 @@ export function WordArtWorkbench() { window.history.replaceState(null, "", `${window.location.pathname}${search ? `?${search}` : ""}${window.location.hash}`); }, [text, entry, weight, italic, textCase, scaleX, scaleY, profile, depth, letterSpacing, lineHeight, align, underline, strike, color, sideColor, backColor, offset, curveSegments, simplify, profileSegments, warpShape, warpAmount, spin, perspective, zoomScale, lightIntensity, ambient, lightColor, lightAz, lightEl, roundConvex, bezier, fillType, gradA, gradB, gradAngle, faceTex, sideFill, sideTex, backFill, backTex, outlineOn, outlineColor, outlineWidth, layered]); - // Load the picked Google font whenever family / weight / style changes. useEffect(() => { if (!entry) return; let alive = true; @@ -362,8 +207,6 @@ export function WordArtWorkbench() { }; }, [entry, weight, italic]); - // Resolve each face's UI fill into a pure `Face` (gradients/rainbow → data URL - // via resolveFace; solid/texture pass through). One key so the memo is stable. const TILE = 52; const frontKey = `${fillType}:${gradA}:${gradB}:${gradAngle}:${faceTex}:${color}:${fillImage.slice(0, 40)}`; const front = useMemo(() => { @@ -379,13 +222,11 @@ export function WordArtWorkbench() { const polygons = useMemo(() => { if (!font) return []; - // "None" → no separate material for that face (it's covered by the nearest - // active face), but the geometry still renders — no hole. const sides: Face | false = sideFill === "texture" ? resolveFace({ kind: "texture", color: sideColor, url: texUrl(sideTex), tile: TILE }) : sideFill === "solid" ? { color: sideColor } : false; - let back: BackFace | false = + const back: BackFace | false = backFill === "texture" ? resolveFace({ kind: "texture", color: backColor, url: texUrl(backTex), tile: TILE }) : backFill === "solid" ? { color: backColor } : false; @@ -398,10 +239,8 @@ export function WordArtWorkbench() { return composeText(font, applyCase(text, textCase), { size: 100, - depth: layered ? 0 : depth, // "Flat layers" = no edges (depth 0) + depth: layered ? 0 : depth, profile: profileObj, - // Scale X/Y are NOT baked here — they're a live CSS transform on the mesh - // wrapper (so they stretch the whole block uniformly and need no recompute). letterSpacing, lineHeight, align, @@ -415,14 +254,8 @@ export function WordArtWorkbench() { }); }, [font, text, textCase, depth, profile, roundConvex, bezier, letterSpacing, lineHeight, align, underline, strike, sideColor, backColor, offset, curveSegments, simplify, profileSegments, warpShape, warpAmount, front, fillType, backFill, backTex, sideFill, sideTex, outlineOn, outlineColor, outlineWidth, layered]); - // Live "dynamic-mode" preview for the affine sliders (scale X/Y, depth): while - // dragging, we don't recompute geometry — we set a CSS scale3d on the mesh - // wrapper (one var per axis, like dynamic lighting) and bake the real geometry - // only on release. {1,1,1} = identity (nothing previewing). const [preview, setPreview] = useState<{ sx: number; sy: number; sz: number }>({ sx: 1, sy: 1, sz: 1 }); - // Directional light direction from azimuth (left/right) + elevation (height), - // always biased toward the front so the face stays lit. const lightDir = useMemo(() => { const a = (lightAz * Math.PI) / 180; const e = (lightEl * Math.PI) / 180; @@ -495,8 +328,6 @@ export function WordArtWorkbench() { } }; - // The Profile dropdown encodes edge shape only — colors now come from the - // axial face stops, so there's no coverage to bundle in. const profileMode = profile === "flat" ? "flat" : profile === "custom" ? "custom" : profile === "round" ? (roundConvex ? "roundup" : "round") @@ -633,582 +464,3 @@ export function WordArtWorkbench() {
); } - -interface StageProps { - polygons: Polygon[]; - preview: { sx: number; sy: number; sz: number }; - onFrameReady: () => void; - scaleXFrac: number; - scaleYFrac: number; - zoomScale: number; - setZoomScale: (updater: (prev: number) => number) => void; - perspective: boolean; - lightDir: Vec3; - lightIntensity: number; - lightColor: string; - ambient: number; - spin: boolean; - status: string; -} - -/** - * Isolated render surface. The auto-spin updates state every frame — keeping it - * in this small component means only the camera/scene/mesh re-render per frame, - * not the parent's controls + 2000-option font datalist (which tanked FPS). - */ -function Stage({ polygons, preview, onFrameReady, scaleXFrac, scaleYFrac, zoomScale, setZoomScale, perspective, lightDir, lightIntensity, lightColor, ambient, spin, status }: StageProps) { - const stageRef = useRef(null); - const wrapRef = useRef(null); - const [stage, setStage] = useState({ w: 900, h: 600 }); - // Rotation lives in refs and is written straight to the DOM — no React state, - // so spinning/dragging never re-renders React (keeps it at full frame rate). - const spinRef = useRef(0); - const tiltRef = useRef(8); - const draggingRef = useRef(false); - const lastPtr = useRef({ x: 0, y: 0 }); - - // The wrapper transform is set imperatively (the spin raf rewrites it every - // frame), so the live scale preview has to be folded in here rather than via - // React style — otherwise applyRotation would clobber it. scale3d is - // innermost (applied to the geometry) then rotate/tilt. - const previewRef = useRef(preview); - previewRef.current = preview; - // Live scale read from a ref so the spin raf's captured applyRotation still - // sees the latest value (otherwise scaling while spinning would be clobbered). - const scaleRef = useRef({ x: scaleXFrac, y: scaleYFrac }); - scaleRef.current = { x: scaleXFrac, y: scaleYFrac }; - const applyRotation = () => { - const el = wrapRef.current; - const p = previewRef.current; - const s = scaleRef.current; - // Scale X/Y are live CSS; depth uses the preview sz. - if (el) el.style.transform = `rotateX(${tiltRef.current}deg) rotateY(${spinRef.current}deg) scale3d(${s.x}, ${s.y}, ${p.sz})`; - }; - useLayoutEffect(applyRotation); // re-assert after any re-render (preview / new geometry) - - useEffect(() => { - const el = stageRef.current; - if (!el) return; - const ro = new ResizeObserver(() => setStage({ w: el.clientWidth, h: el.clientHeight })); - ro.observe(el); - setStage({ w: el.clientWidth, h: el.clientHeight }); - return () => ro.disconnect(); - }, []); - - // Camera stays dead-on front; the wrapper spins/tilts in 3D (grab-an-object feel). - useEffect(() => { - if (!spin) return; - let raf = 0; - let last = performance.now(); - const tick = (now: number) => { - const dt = (now - last) / 1000; - last = now; - if (!draggingRef.current) { - spinRef.current = (spinRef.current - dt * 32) % 360; - applyRotation(); - } - raf = requestAnimationFrame(tick); - }; - raf = requestAnimationFrame(tick); - return () => cancelAnimationFrame(raf); - }, [spin]); - - const onPointerDown = (e: React.PointerEvent) => { - draggingRef.current = true; - lastPtr.current = { x: e.clientX, y: e.clientY }; - e.currentTarget.setPointerCapture(e.pointerId); - }; - const onPointerMove = (e: React.PointerEvent) => { - if (!draggingRef.current) return; - const dx = e.clientX - lastPtr.current.x; - const dy = e.clientY - lastPtr.current.y; - lastPtr.current = { x: e.clientX, y: e.clientY }; - spinRef.current += dx * 0.4; - tiltRef.current = Math.max(-85, Math.min(85, tiltRef.current - dy * 0.4)); - applyRotation(); - }; - const onPointerUp = (e: React.PointerEvent) => { - draggingRef.current = false; - e.currentTarget.releasePointerCapture(e.pointerId); - }; - // Wheel drives the same zoomScale the sidebar slider does (so they agree and - // share one min/max), instead of the orbit-control's separate camera zoom. - const onWheel = (e: React.WheelEvent) => { - const factor = Math.pow(0.95, e.deltaY * 0.012); - setZoomScale((z) => Math.max(0.1, Math.min(6, z * factor))); - }; - - // Post-parity camera `zoom` is px-per-world-unit; the renderer divides - // by BASE_TILE for the scene-root CSS scale. `fitZoom` + `zoomScale` - // both produce the legacy unitless CSS-scale value (range 0.01–0.2 * - // 0.1–6 = roughly 0.001–1.2), so multiply by BASE_TILE to land back at - // the same on-screen scale. Same shape as gallery's LEGACY_ZOOM_COMPAT - // and the builder's recently-fixed zoom path. - const zoom = fitZoom(polygons, stage.w, stage.h, scaleXFrac, scaleYFrac) * zoomScale * BASE_TILE; - const Cam = perspective ? PolyPerspectiveCamera : PolyOrthographicCamera; - - return ( -
- - -
- -
-
-
-
- {polygons.length.toLocaleString()} polygons{status ? ` · ${status}` : ""} -
-
- ); -} - -interface GuiValues { - layered: boolean; - profileMode: string; warp: string; bend: number; - depth: number; letterSpacing: number; lineHeight: number; scaleX: number; scaleY: number; - curveSegments: number; simplify: number; profileSegments: number; offset: number; - perspective: boolean; zoom: number; spin: boolean; - light: number; ambient: number; az: number; el: number; lightColor: string; -} - -/** One coordinate of a cubic Bézier P0..P3 at parameter t. */ -function cubicAt(p0: number, p1: number, p2: number, p3: number, t: number): number { - const m = 1 - t; - return m * m * m * p0 + 3 * m * m * t * p1 + 3 * m * t * t * p2 + t * t * t * p3; -} - -/** - * Mount a draggable cubic-bezier editor (the CSS easing curve) into `parent`. - * P0=(0,0) and P3=(1,1) are fixed; the two control handles drive `setB`. - * Returns a `redraw()` to resync the SVG when the value changes elsewhere. - */ -function mountBezierEditor(parent: HTMLElement, getB: () => Bezier4, setB: (b: Bezier4) => void): () => void { - const NS = "http://www.w3.org/2000/svg"; - const W = 220, H = 150, pad = 16; - const X = (x: number) => pad + x * (W - 2 * pad); - const Y = (y: number) => (H - pad) - y * (H - 2 * pad); - const el = (n: string, a: Record) => { - const e = document.createElementNS(NS, n); - for (const k in a) e.setAttribute(k, a[k]); - return e; - }; - const svg = el("svg", { viewBox: `0 0 ${W} ${H}`, class: "wa-bez" }); - const frame = el("rect", { x: `${X(0)}`, y: `${Y(1)}`, width: `${W - 2 * pad}`, height: `${H - 2 * pad}`, class: "wa-bez__frame" }); - const diag = el("line", { x1: `${X(0)}`, y1: `${Y(0)}`, x2: `${X(1)}`, y2: `${Y(1)}`, class: "wa-bez__diag" }); - const l1 = el("line", { class: "wa-bez__leg" }); - const l2 = el("line", { class: "wa-bez__leg" }); - const curve = el("path", { class: "wa-bez__curve" }); - const h1 = el("circle", { r: "5", class: "wa-bez__h" }); - const h2 = el("circle", { r: "5", class: "wa-bez__h" }); - svg.append(frame, diag, l1, l2, curve, h1, h2); - parent.appendChild(svg); - - // `drawB` is the editor's live value; the SVG follows it every move (cheap), - // but the mesh re-extrude (`setB`) is debounced so dragging stays smooth. - let drawB: Bezier4 = getB(); - let active = 0; - let timer = 0; - const commit = (now: boolean) => { - clearTimeout(timer); - if (now) setB(drawB); - else timer = window.setTimeout(() => setB(drawB), 130); - }; - const render = () => { - const [x1, y1, x2, y2] = drawB; - let d = `M ${X(0)} ${Y(0)}`; - for (let i = 1; i <= 24; i++) { - const t = i / 24; - d += ` L ${X(cubicAt(0, x1, x2, 1, t))} ${Y(cubicAt(0, y1, y2, 1, t))}`; - } - curve.setAttribute("d", d); - l1.setAttribute("x1", `${X(0)}`); l1.setAttribute("y1", `${Y(0)}`); l1.setAttribute("x2", `${X(x1)}`); l1.setAttribute("y2", `${Y(y1)}`); - l2.setAttribute("x1", `${X(1)}`); l2.setAttribute("y1", `${Y(1)}`); l2.setAttribute("x2", `${X(x2)}`); l2.setAttribute("y2", `${Y(y2)}`); - h1.setAttribute("cx", `${X(x1)}`); h1.setAttribute("cy", `${Y(y1)}`); - h2.setAttribute("cx", `${X(x2)}`); h2.setAttribute("cy", `${Y(y2)}`); - }; - - const toData = (ev: PointerEvent): [number, number] => { - const r = svg.getBoundingClientRect(); - const x = (((ev.clientX - r.left) / r.width) * W - pad) / (W - 2 * pad); - const y = ((H - pad) - ((ev.clientY - r.top) / r.height) * H) / (H - 2 * pad); - return [Math.min(1, Math.max(0, x)), Math.min(1, Math.max(0, y))]; - }; - const move = (ev: PointerEvent) => { - if (!active) return; - const [x, y] = toData(ev); - drawB = [...drawB] as Bezier4; - if (active === 1) { drawB[0] = x; drawB[1] = y; } else { drawB[2] = x; drawB[3] = y; } - render(); - commit(false); - }; - const start = (handle: number, e: PointerEvent, target: SVGElement) => { - active = handle; - drawB = [...getB()] as Bezier4; - target.setPointerCapture(e.pointerId); - }; - h1.addEventListener("pointerdown", (e) => start(1, e as PointerEvent, h1 as SVGElement)); - h2.addEventListener("pointerdown", (e) => start(2, e as PointerEvent, h2 as SVGElement)); - svg.addEventListener("pointermove", move as EventListener); - svg.addEventListener("pointerup", () => { if (active) { active = 0; commit(true); } }); - render(); - // External redraw (state changed elsewhere) — adopt it only when not dragging. - return () => { if (!active) drawB = getB(); render(); }; -} - -/** - * Right-hand control panel built with the SAME library the /gallery uses - * (lil-gui), themed with the gallery's exact CSS variables — so the controls - * are identical, not a CSS approximation. lil-gui is imperative, so we mount it - * once and bridge its onChange → React, and React state → updateDisplay(). - */ -function GuiPanel({ id, className = "", values, set, onPreviewAxis, bezier, onBezier }: { id?: string; className?: string; values: GuiValues; set: (k: keyof GuiValues, v: number | string | boolean) => void; onPreviewAxis: (axis: "sx" | "sy" | "sz", ratio: number) => void; bezier: Bezier4; onBezier: (b: Bezier4) => void }) { - const hostRef = useRef(null); - // Current committed values, read inside the (mount-once) GUI callbacks so the - // live-preview ratio is taken against the value at drag start. - const valuesRef = useRef(values); - valuesRef.current = values; - const onPreviewAxisRef = useRef(onPreviewAxis); - onPreviewAxisRef.current = onPreviewAxis; - // True while an affine slider is mid-drag (preview mode). The values→GUI - // write-back below is skipped then, so it can't reset the control the user is - // dragging back to the (not-yet-committed) value. - const previewDragRef = useRef(false); - const cfgRef = useRef({ ...values }); - const ctrlRef = useRef>>({}); - const bezierRef = useRef(bezier); - const onBezierRef = useRef(onBezier); - const bezUiRef = useRef<{ wrap: HTMLElement; input: HTMLInputElement; redraw: () => void } | null>(null); - - useEffect(() => { - const cfg = cfgRef.current; - const c = ctrlRef.current; - const gui = new GUI({ container: hostRef.current!, title: "Settings", width: 300 }); - const on = (k: keyof GuiValues) => (v: number | string | boolean) => set(k, v); - - // Tier-1 "dynamic mode": while dragging an affine slider, only set a CSS - // scale3d ratio on the wrapper (no geometry recompute). On release we commit - // the real value but DON'T reset the preview here — the mesh holds the old - // frame until the new atlas is decoded (atomicAtlas) and fires onFrameReady, - // which resets the preview so the swap is seamless (no backward flash). - const previewAxis = (k: keyof GuiValues, axis: "sx" | "sy" | "sz") => (v: number | string | boolean) => { - previewDragRef.current = true; - const base = (valuesRef.current[k] as number) || 1; - onPreviewAxisRef.current(axis, ((v as number) / base) || 1); - }; - const bake = (k: keyof GuiValues) => (v: number | string | boolean) => { - previewDragRef.current = false; - set(k, v); - }; - - const shape = gui.addFolder("Shape"); - c.profileMode = shape.add(cfg, "profileMode", { - "Flat (slab)": "flat", - "Bevel": "bevel", - "Round in": "round", - "Round out": "roundup", - "Custom curve": "custom", - }).name("Profile").onChange(on("profileMode")); - - // Custom-profile curve: a CSS cubic-bezier() text field + a draggable editor - // (shown only for the Custom profile). Both drive the `bezier` prop. - c.bezierText = shape.add({ _: "" }, "_").name("Curve"); - { - const widget = c.bezierText.domElement.querySelector(".widget"); - const wrap = document.createElement("div"); - wrap.className = "wa-bezwrap"; - let input = document.createElement("input"); - if (widget) { - widget.replaceChildren(); - input.type = "text"; - input.className = "wa-input wa-bezinput"; - input.spellcheck = false; - input.addEventListener("change", () => { - const parsed = parseBezier(input.value); - if (parsed) onBezierRef.current(parsed); - }); - widget.appendChild(input); - } - shape.domElement.querySelector(".children")?.appendChild(wrap); - const redraw = mountBezierEditor(wrap, () => bezierRef.current, (b) => onBezierRef.current(b)); - bezUiRef.current = { wrap, input, redraw }; - } - - c.warp = shape.add(cfg, "warp", { None: "none", "Arch up": "arch", "Arch down": "archDown", "Arc (circle)": "arc", Wave: "wave", Bulge: "bulge", "Cone (taper)": "cone", "Slant up": "slantUp", "Slant down": "slantDown" }).name("Warp").onChange(on("warp")); - // Tier-3 (changes poly count / non-linear): no live recompute — bake on release. - c.bend = shape.add(cfg, "bend", 0, 1, 0.02).name("Bend").onFinishChange(on("bend")); - - const layout = gui.addFolder("Layout"); - // Tier-1 (affine): live CSS scale preview while dragging, bake on release. - c.depth = layout.add(cfg, "depth", 2, 80, 1).name("Depth").onChange(previewAxis("depth", "sz")).onFinishChange(bake("depth")); - c.letterSpacing = layout.add(cfg, "letterSpacing", -20, 60, 1).name("Letter spacing").onFinishChange(on("letterSpacing")); - c.lineHeight = layout.add(cfg, "lineHeight", 0.8, 2.5, 0.05).name("Line height").onFinishChange(on("lineHeight")); - // Scale X/Y just update state → a live CSS wrapper transform (no recompute). - c.scaleX = layout.add(cfg, "scaleX", 40, 200, 1).name("Scale X").onChange(on("scaleX")); - c.scaleY = layout.add(cfg, "scaleY", 40, 200, 1).name("Scale Y").onChange(on("scaleY")); - c.curveSegments = layout.add(cfg, "curveSegments", 1, 12, 1).name("Curve segments").onFinishChange(on("curveSegments")); - c.simplify = layout.add(cfg, "simplify", 0, 8, 0.5).name("Simplify").onFinishChange(on("simplify")); - c.profileSegments = layout.add(cfg, "profileSegments", 2, 10, 1).name("Edge segments").onFinishChange(on("profileSegments")); - c.offset = layout.add(cfg, "offset", 0, 32, 1).name("Layer offset").onFinishChange(on("offset")); - c.layered = layout.add(cfg, "layered").name("Flat layers").onChange(on("layered")); - - const cam = gui.addFolder("Camera"); - c.perspective = cam.add(cfg, "perspective").name("Perspective").onChange(on("perspective")); - c.zoom = cam.add(cfg, "zoom", 0.1, 6, 0.05).name("Zoom").onChange(on("zoom")); - c.spin = cam.add(cfg, "spin").name("Auto-spin").onChange(on("spin")); - - const lighting = gui.addFolder("Lighting"); - c.light = lighting.add(cfg, "light", 0, 2, 0.05).name("Light").onChange(on("light")); - c.ambient = lighting.add(cfg, "ambient", 0, 1, 0.05).name("Ambient").onChange(on("ambient")); - c.az = lighting.add(cfg, "az", -90, 90, 1).name("Angle").onChange(on("az")); - c.el = lighting.add(cfg, "el", 0, 90, 1).name("Elev.").onChange(on("el")); - c.lightColor = lighting.addColor(cfg, "lightColor").name("Light color").onChange(on("lightColor")); - - return () => gui.destroy(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - - // Push React state back into the GUI display + toggle conditional controllers. - useEffect(() => { - // Skip the write-back mid preview-drag so it can't reset the dragged control. - if (!previewDragRef.current) { - Object.assign(cfgRef.current, values); - for (const ctrl of Object.values(ctrlRef.current)) ctrl?.updateDisplay(); - } - bezierRef.current = bezier; - onBezierRef.current = onBezier; - const isCustom = values.profileMode.startsWith("custom"); - ctrlRef.current.bend?.[values.warp !== "none" ? "show" : "hide"](); - ctrlRef.current.profileSegments?.[(values.profileMode.startsWith("round") || isCustom) ? "show" : "hide"](); - ctrlRef.current.bezierText?.[isCustom ? "show" : "hide"](); - if (bezUiRef.current) { - bezUiRef.current.wrap.style.display = isCustom ? "" : "none"; - bezUiRef.current.redraw(); - if (document.activeElement !== bezUiRef.current.input) bezUiRef.current.input.value = bezierToCss(bezier); - } - }); - - return
; -} - -interface LeftValues { - weight: number; italic: boolean; underline: boolean; strike: boolean; - textCase: string; align: string; color: string; sideColor: string; backColor: string; - fillType: string; gradA: string; gradB: string; gradAngle: number; image: string; - faceTex: string; sideFill: string; sideTex: string; backFill: string; backTex: string; - outlineOn: boolean; outlineColor: string; outlineWidth: number; -} - -/** lil-gui typography + color panel for the left card (blends in, borderless). */ -function LeftGuiPanel({ values, set }: { values: LeftValues; set: (k: keyof LeftValues, v: number | string | boolean) => void }) { - const hostRef = useRef(null); - const cfgRef = useRef({ ...values }); - const ctrlRef = useRef>>({}); - const segRef = useRef void>>({}); - const texRef = useRef void>>({}); - const texWrapRef = useRef>({}); - - useEffect(() => { - const cfg = cfgRef.current; - const c = ctrlRef.current; - const gui = new GUI({ container: hostRef.current!, title: "", width: 300 }); - const on = (k: keyof LeftValues) => (v: number | string | boolean) => set(k, v); - - // Inject a segmented button-group into a lil-gui row's widget (lil-gui has - // no native one — the gallery injects custom widgets the same way). - const segmented = (folder: GUI, name: string, key: keyof LeftValues, options: [string, string, string][]) => { - const ctrl = folder.add({ _: "" }, "_").name(name); - const widget = ctrl.domElement.querySelector(".widget"); - if (!widget) return; - widget.replaceChildren(); - widget.classList.add("wa-seg"); - const btns: Record = {}; - for (const [value, label, title] of options) { - const btn = document.createElement("button"); - btn.type = "button"; - btn.textContent = label; - btn.title = title; - btn.addEventListener("click", () => set(key, value)); - widget.appendChild(btn); - btns[value] = btn; - } - segRef.current[key] = (v: string) => { - for (const k in btns) btns[k].classList.toggle("is-on", k === v); - }; - }; - - const type = gui.addFolder("Type"); - c.weight = type.add(cfg, "weight", [100, 200, 300, 400, 500, 600, 700, 800, 900]).name("Weight").onChange(on("weight")); - c.italic = type.add(cfg, "italic").name("Italic").onChange(on("italic")); - c.underline = type.add(cfg, "underline").name("Underline").onChange(on("underline")); - c.strike = type.add(cfg, "strike").name("Strikethrough").onChange(on("strike")); - segmented(type, "Case", "textCase", [["as-typed", "Aa", "As typed"], ["upper", "AB", "UPPERCASE"], ["lower", "ab", "lowercase"], ["title", "Ab", "Title Case"]]); - segmented(type, "Align", "align", [["left", "L", "Left"], ["center", "C", "Center"], ["right", "R", "Right"]]); - - // Each face (front / sides / back) has its own fill-type selector that - // generates the matching input below it. - const col = gui.addFolder("Color"); - const colChildren = col.domElement.querySelector(".children"); - - // A grid of bundled block-texture swatches injected into the folder - // (lil-gui has no image picker). Shown only when that face is in Texture mode. - const texGrid = (key: keyof LeftValues) => { - const wrap = document.createElement("div"); - wrap.className = "wa-texrow"; - const grid = document.createElement("div"); - grid.className = "wa-texgrid"; - wrap.append(grid); - const swatches: Record = {}; - for (const t of TEXTURES) { - const sw = document.createElement("button"); - sw.type = "button"; - sw.className = "wa-texgrid__sw"; - sw.title = t.label; - sw.style.backgroundImage = `url(${texUrl(t.id)})`; - sw.addEventListener("click", () => set(key, t.id)); - grid.appendChild(sw); - swatches[t.id] = sw; - } - colChildren?.appendChild(wrap); - texRef.current[key] = (v: string) => { - for (const id in swatches) swatches[id].classList.toggle("is-on", id === v); - }; - texWrapRef.current[key] = wrap; - }; - - // Front — the full fill set. - c.fillType = col.add(cfg, "fillType", { Solid: "solid", Gradient: "gradient", Rainbow: "rainbow", Texture: "texture", Image: "image" }).name("Front").onChange(on("fillType")); - c.color = col.addColor(cfg, "color").name("Color").onChange(on("color")); - c.gradA = col.addColor(cfg, "gradA").name("Color A").onChange(on("gradA")); - c.gradB = col.addColor(cfg, "gradB").name("Color B").onChange(on("gradB")); - c.gradAngle = col.add(cfg, "gradAngle", 0, 360, 5).name("Angle").onChange(on("gradAngle")); - // lil-gui has no file input — inject a "Choose image" button that reads the - // picked file as a data URL (the renderer uses it as a background-image). - c.image = col.add({ _: "" }, "_").name("Image"); - { - const widget = c.image.domElement.querySelector(".widget"); - if (widget) { - widget.replaceChildren(); - const btn = document.createElement("button"); - btn.type = "button"; - btn.className = "wa-imgbtn"; - btn.textContent = "Choose image…"; - const input = document.createElement("input"); - input.type = "file"; - input.accept = "image/*"; - input.style.display = "none"; - btn.addEventListener("click", () => input.click()); - input.addEventListener("change", () => { - const file = input.files?.[0]; - if (!file) return; - const reader = new FileReader(); - reader.onload = () => set("image", String(reader.result)); - reader.readAsDataURL(file); - }); - widget.append(btn, input); - } - } - texGrid("faceTex"); - - // Sides — solid color or block texture. - c.sideFill = col.add(cfg, "sideFill", { Solid: "solid", Texture: "texture", None: "none" }).name("Sides").onChange(on("sideFill")); - c.sideColor = col.addColor(cfg, "sideColor").name("Color").onChange(on("sideColor")); - texGrid("sideTex"); - - // Back — solid color or block texture. - c.backFill = col.add(cfg, "backFill", { Solid: "solid", Texture: "texture", None: "none" }).name("Back").onChange(on("backFill")); - c.backColor = col.addColor(cfg, "backColor").name("Color").onChange(on("backColor")); - texGrid("backTex"); - - c.outlineOn = col.add(cfg, "outlineOn").name("Outline").onChange(on("outlineOn")); - c.outlineColor = col.addColor(cfg, "outlineColor").name("Outline color").onChange(on("outlineColor")); - c.outlineWidth = col.add(cfg, "outlineWidth", 0.5, 12, 0.5).name("Outline width").onChange(on("outlineWidth")); - - return () => gui.destroy(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - - useEffect(() => { - Object.assign(cfgRef.current, values); - for (const ctrl of Object.values(ctrlRef.current)) ctrl?.updateDisplay(); - segRef.current.textCase?.(values.textCase); - segRef.current.align?.(values.align); - // Show only the input that matches each face's selected fill mode. - const grad = values.fillType === "gradient"; - ctrlRef.current.color?.[values.fillType === "solid" ? "show" : "hide"](); - ctrlRef.current.gradA?.[grad ? "show" : "hide"](); - ctrlRef.current.gradB?.[grad ? "show" : "hide"](); - ctrlRef.current.gradAngle?.[grad || values.fillType === "rainbow" ? "show" : "hide"](); - ctrlRef.current.image?.[values.fillType === "image" ? "show" : "hide"](); - texWrapRef.current.faceTex?.style.setProperty("display", values.fillType === "texture" ? "" : "none"); - ctrlRef.current.sideColor?.[values.sideFill === "solid" ? "show" : "hide"](); - texWrapRef.current.sideTex?.style.setProperty("display", values.sideFill === "texture" ? "" : "none"); - ctrlRef.current.backColor?.[values.backFill === "solid" ? "show" : "hide"](); - texWrapRef.current.backTex?.style.setProperty("display", values.backFill === "texture" ? "" : "none"); - ctrlRef.current.outlineColor?.[values.outlineOn ? "show" : "hide"](); - ctrlRef.current.outlineWidth?.[values.outlineOn ? "show" : "hide"](); - texRef.current.faceTex?.(values.faceTex); - texRef.current.sideTex?.(values.sideTex); - texRef.current.backTex?.(values.backTex); - }); - - return
; -} - -/** Searchable font dropdown — filters the catalog as you type, styled list. */ -function FontPicker({ catalog, value, onPick }: { catalog: FontEntry[]; value: string; onPick: (family: string) => void }) { - const [open, setOpen] = useState(false); - const [query, setQuery] = useState(value); - const wrapRef = useRef(null); - useEffect(() => { setQuery(value); }, [value]); - const results = useMemo(() => { - const q = query.trim().toLowerCase(); - return (q ? catalog.filter((f) => f.family.toLowerCase().includes(q)) : catalog).slice(0, 80); - }, [query, catalog]); - useEffect(() => { - const h = (e: PointerEvent) => { - if (wrapRef.current && !wrapRef.current.contains(e.target as Node)) setOpen(false); - }; - document.addEventListener("pointerdown", h); - return () => document.removeEventListener("pointerdown", h); - }, []); - return ( -
- setOpen(true)} - onChange={(e) => { setQuery(e.target.value); setOpen(true); }} - /> - {open && results.length > 0 && ( -
    - {results.map((f) => ( -
  • { onPick(f.family); setQuery(f.family); setOpen(false); }} - > - {f.family} -
  • - ))} -
- )} -
- ); -} \ No newline at end of file diff --git a/website/src/components/WordArtWorkbench/wordArtPresets.ts b/website/src/components/WordArtWorkbench/wordArtPresets.ts new file mode 100644 index 000000000..af6dbce17 --- /dev/null +++ b/website/src/components/WordArtWorkbench/wordArtPresets.ts @@ -0,0 +1,132 @@ +import { BASE_TILE } from "@layoutit/polycss-react"; +import type { Polygon } from "@layoutit/polycss-react"; +import type { ExtrudeProfile, WarpShape } from "@layoutit/polycss-fonts"; + +export type Align = "left" | "center" | "right"; +export type FillType = "solid" | "gradient" | "rainbow" | "texture" | "image"; +export type FaceFill = "solid" | "texture" | "none"; +export type Bezier4 = [number, number, number, number]; + +// Named CSS easings → cubic-bezier control points, for the custom edge profile. +const CSS_EASINGS: Record = { + linear: [0, 0, 1, 1], + ease: [0.25, 0.1, 0.25, 1], + "ease-in": [0.42, 0, 1, 1], + "ease-out": [0, 0, 0.58, 1], + "ease-in-out": [0.42, 0, 0.58, 1], +}; + +/** Parse a CSS easing string (`cubic-bezier(...)` or a keyword) to 4 controls. */ +export function parseBezier(input: string): Bezier4 | null { + const s = input.trim().toLowerCase(); + if (CSS_EASINGS[s]) return CSS_EASINGS[s]; + const m = /cubic-bezier\(\s*([\d.+-]+)[ ,]+([\d.+-]+)[ ,]+([\d.+-]+)[ ,]+([\d.+-]+)\s*\)/.exec(s); + if (!m) return null; + const p = [m[1], m[2], m[3], m[4]].map(Number) as Bezier4; + return p.every((n) => !Number.isNaN(n)) ? p : null; +} + +export const bezierToCss = (b: Bezier4) => `cubic-bezier(${b.map((n) => +n.toFixed(2)).join(", ")})`; + +// Bundled voxel-style block textures (Layoutit voxels set), served locally from +// public/textures/wordart so the atlas canvas stays same-origin (no CORS taint). +export const TEXTURES: { id: string; label: string }[] = [ + { id: "dirt", label: "Dirt" }, { id: "dirt2", label: "Dirt 2" }, { id: "grass3", label: "Grass" }, + { id: "brick", label: "Brick" }, { id: "brick2", label: "Brick 2" }, { id: "wood", label: "Wood" }, + { id: "wood3", label: "Plank" }, { id: "rock", label: "Rock" }, { id: "rock3", label: "Rock 2" }, + { id: "ice", label: "Ice" }, { id: "ice3", label: "Ice 2" }, { id: "glass", label: "Glass" }, + { id: "sand", label: "Sand" }, { id: "cacti", label: "Cactus" }, { id: "mine", label: "Ore" }, { id: "mine4", label: "Ore 2" }, +]; + +export const texUrl = (id: string) => (id ? `/textures/wordart/${id}.svg` : ""); + +export interface Preset { + label: string; + profile: ExtrudeProfile; + depth: number; + color: string; + sideColor: string; + /** Back-face color (layered look when different + offset > 0). */ + backColor?: string; + /** Diagonal back offset for the layered block (down-right). */ + offset?: number; + warp?: { shape: WarpShape; amount: number }; + /** Face fill (defaults to solid `color`). */ + fill?: FillType; + gradA?: string; + gradB?: string; + gradAngle?: number; + /** Block-texture ids for the front / sides / back faces. */ + faceTex?: string; + sideTex?: string; + backTex?: string; + outline?: { color: string; width: number }; + /** Flat two-layer drop shadow (no extrusion walls). */ + layered?: boolean; + /** CSS background for the preset tile thumbnail (defaults to `color`). */ + thumb?: string; +} + +// Left-rail style presets — each is a full "look": extrusion, layered front/back, +// and/or a baked-in WordArt warp (like the builder's shape tiles). +export const PRESETS: Preset[] = [ + { label: "Gold Gradient", profile: "bevel", depth: 26, color: "#ffd23f", sideColor: "#7c4a12", + fill: "gradient", gradA: "#ffe14d", gradB: "#ff7a1a", gradAngle: 270, thumb: "linear-gradient(#ffe14d,#ff7a1a)" }, + { label: "Grape Pop", profile: "flat", depth: 5, color: "#b14be0", sideColor: "#7a8cff", backColor: "#8aa0ff", offset: 14, layered: true, + fill: "gradient", gradA: "#c45cf0", gradB: "#7a1fb8", gradAngle: 270, thumb: "linear-gradient(#c45cf0,#7a1fb8)" }, + { label: "Chrome", profile: "bevel", depth: 22, color: "#d7dde4", sideColor: "#3a2222", + fill: "gradient", gradA: "#f4f8ff", gradB: "#9a4b4b", gradAngle: 270, thumb: "linear-gradient(#f4f8ff 45%,#9a4b4b)" }, + { label: "Rainbow", profile: "flat", depth: 10, color: "#ff5e3a", sideColor: "#7a2a55", + fill: "rainbow", gradAngle: 0, thumb: "linear-gradient(90deg,#ff3b30,#ffcc00,#34c759,#007aff,#af52de)" }, + { label: "Sky Outline", profile: "flat", depth: 8, color: "#7ec8ff", sideColor: "#2b50b0", + outline: { color: "#1838b8", width: 3 }, thumb: "#7ec8ff" }, + { label: "Grass Block", profile: "flat", depth: 18, color: "#6ab04c", sideColor: "#6b4a2b", + fill: "texture", faceTex: "grass3", sideTex: "dirt", thumb: "url(/textures/wordart/grass3.svg) center/cover" }, + { label: "Brick Wall", profile: "bevel", depth: 22, color: "#a8432a", sideColor: "#7a2f1d", + fill: "texture", faceTex: "brick", sideTex: "brick2", thumb: "url(/textures/wordart/brick.svg) center/cover" }, + { label: "Stone", profile: "flat", depth: 20, color: "#8d8d8d", sideColor: "#5a5a5a", + fill: "texture", faceTex: "rock", sideTex: "rock3", thumb: "url(/textures/wordart/rock.svg) center/cover" }, + { label: "Ice", profile: "bevel", depth: 18, color: "#b9e6ff", sideColor: "#6aa9cc", + fill: "texture", faceTex: "ice", sideTex: "ice3", thumb: "url(/textures/wordart/ice.svg) center/cover" }, + { label: "Gold Bevel", profile: "bevel", depth: 26, color: "#d4a82a", sideColor: "#7c5e16" }, + { label: "Retro Block", profile: "flat", depth: 6, color: "#ff4d6d", sideColor: "#3a0ca3", backColor: "#3a0ca3", offset: 16, layered: true, thumb: "#ff4d6d" }, + { label: "Arch Gold", profile: "bevel", depth: 22, color: "#e9b949", sideColor: "#8a5a12", warp: { shape: "arch", amount: 0.6 } }, + { label: "Wave Mint", profile: "round", depth: 24, color: "#7cffb2", sideColor: "#2f8f5e", warp: { shape: "wave", amount: 0.55 } }, + { label: "Ink Shadow", profile: "flat", depth: 4, color: "#e8edf2", sideColor: "#2b313b", backColor: "#2b313b", offset: 12, layered: true, thumb: "#e8edf2" }, +]; + +export function applyCase(text: string, mode: "as-typed" | "upper" | "lower" | "title"): string { + if (mode === "upper") return text.toUpperCase(); + if (mode === "lower") return text.toLowerCase(); + if (mode === "title") return text.replace(/\b\p{L}/gu, (c) => c.toUpperCase()); + return text; +} + +export function readable(hex: string): string { + const m = /^#?([0-9a-f]{6})$/i.exec(hex); + if (!m) return "#000"; + const n = parseInt(m[1], 16); + const lum = 0.299 * ((n >> 16) & 255) + 0.587 * ((n >> 8) & 255) + 0.114 * (n & 255); + return lum > 150 ? "#0b0f18" : "#ffffff"; +} + +export function fitZoom(polygons: Polygon[], stageW: number, stageH: number, scaleX = 1, scaleY = 1): number { + if (!polygons.length) return 0.06; + let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity, minZ = Infinity, maxZ = -Infinity; + for (const p of polygons) { + for (const v of p.vertices) { + if (v[0] < minX) minX = v[0]; if (v[0] > maxX) maxX = v[0]; + if (v[1] < minY) minY = v[1]; if (v[1] > maxY) maxY = v[1]; + if (v[2] < minZ) minZ = v[2]; if (v[2] > maxZ) maxZ = v[2]; + } + } + // Flat text: Y = width (screen-right), X = height (screen-down), Z = depth. + // As the mesh turntables, width swings into depth, so fit the larger of the + // two. Scale X/Y are applied as a CSS transform on the mesh (not baked), so + // multiply the base bounds by them here to frame the *scaled* word. + const horizontal = Math.max((maxY - minY) * scaleX, maxZ - minZ); + const vertical = (maxX - minX) * scaleY; + const fitW = (stageW * 0.7) / (Math.max(horizontal, 1) * BASE_TILE); + const fitH = (stageH * 0.68) / (Math.max(vertical, 1) * BASE_TILE); + return Math.max(0.01, Math.min(0.2, Math.min(fitW, fitH))); +} diff --git a/website/src/components/helpers/codePen.ts b/website/src/components/helpers/codePen.ts new file mode 100644 index 000000000..6fbe18cf1 --- /dev/null +++ b/website/src/components/helpers/codePen.ts @@ -0,0 +1,32 @@ +function codePenPayload(snapshotHtml: string, title: string): string { + const parsed = new DOMParser().parseFromString(snapshotHtml, "text/html"); + const css = Array.from(parsed.querySelectorAll("style")) + .map((styleEl) => styleEl.textContent ?? "") + .filter(Boolean) + .join("\n\n"); + const html = parsed.body.innerHTML.trim() || snapshotHtml; + return JSON.stringify({ + title, + html, + css, + editors: "100", + layout: "left", + }); +} + +export function openCodePen(html: string, title: string, target = "_blank"): void { + const form = document.createElement("form"); + form.action = "https://codepen.io/pen/define"; + form.method = "POST"; + form.target = target; + form.setAttribute("rel", "noopener noreferrer"); + form.style.display = "none"; + const input = document.createElement("input"); + input.type = "hidden"; + input.name = "data"; + input.value = codePenPayload(html, title); + form.appendChild(input); + document.body.appendChild(form); + form.submit(); + form.remove(); +} diff --git a/website/tsconfig.json b/website/tsconfig.json index 32fac8eab..2f56374dc 100644 --- a/website/tsconfig.json +++ b/website/tsconfig.json @@ -6,6 +6,7 @@ "@layoutit/polycss-core/three": ["packages/core/src/three/index.ts"], "@layoutit/polycss-core": ["packages/core/src/index.ts"], "@layoutit/polycss/runtime": ["packages/polycss/src/runtime.ts"], + "@layoutit/polycss/internal": ["packages/polycss/src/internal.ts"], "@layoutit/polycss/elements": ["packages/polycss/src/elements/index.ts"], "@layoutit/polycss/three": ["packages/polycss/src/three.ts"], "@layoutit/polycss": ["packages/polycss/src/index.ts"],