diff --git a/.github/actions/setup-workspace/action.yml b/.github/actions/setup-workspace/action.yml index fe4c1a28..b823a60e 100644 --- a/.github/actions/setup-workspace/action.yml +++ b/.github/actions/setup-workspace/action.yml @@ -10,12 +10,10 @@ runs: using: composite steps: - name: Set up pnpm - uses: pnpm/action-setup@a7487c7e89a18df4991f7f222e4898a00d66ddda - with: - version: 10.32.1 + uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 - name: Set up Node - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 + uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7.2.0 with: node-version: 22 cache: pnpm diff --git a/.github/architecture/repo-map.md b/.github/architecture/repo-map.md index 27b471d4..0da0195e 100644 --- a/.github/architecture/repo-map.md +++ b/.github/architecture/repo-map.md @@ -1,7 +1,7 @@ # PolyCSS Repository Map -Tracked production code scanned across `packages/*/src`, `bench/`, and `website/src`: **488 files**, **98,910 lines**. Regenerate with `pnpm map`; verified in CI by `pnpm check:map`. +Tracked production code scanned across `packages/*/src`, `bench/`, and `website/src`: **512 files**, **99,750 lines**. Regenerate with `pnpm map`; verified in CI by `pnpm check:map`. ## 1. Packages & Entry Points @@ -10,8 +10,8 @@ Tracked production code scanned across `packages/*/src`, `bench/`, and `website/ | `packages/core` (`@layoutit/polycss-core`) | npm | `., ./three` | — | 104 | 27,402 | 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, ./internal, ./elements, ./three` | `@layoutit/polycss-core` | 91 | 17,154 | 41 | +| `packages/morph` (`@layoutit/polycss-morph`) | npm | `., ./prepare` | `@layoutit/polycss`, `@layoutit/polycss-core` | 54 | 7,826 | 14 | +| `packages/polycss` (`@layoutit/polycss`) | npm | `., ./runtime, ./internal, ./elements, ./three` | `@layoutit/polycss-core` | 95 | 17,300 | 42 | | `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,437 | 29 | @@ -37,7 +37,7 @@ Single source of truth: [`packages/workspace-aliases.mjs`](../../packages/worksp | `@layoutit/polycss-morph/prepare` | `packages/morph/src/prepare.ts` | | `@layoutit/polycss-morph` | `packages/morph/src/index.ts` | -**Consumers (12):** `bench/build.mjs`, `packages/fonts/vitest.config.ts`, `packages/morph/vitest.config.ts`, `packages/polycss/vitest.config.ts`, `packages/react/vitest.config.ts`, `packages/vitest.base.mjs`, `packages/vue/vitest.config.ts`, `website/astro.config.mjs`, `website/scripts/generate-builder-shape-thumbnails.mjs`, `website/scripts/generate-gallery-domformat.mjs`, `website/scripts/prove-gallery-domformat.mjs`, `website/tsconfig.json` +**Consumers (13):** `bench/build.mjs`, `packages/fonts/vitest.config.ts`, `packages/morph/vitest.config.ts`, `packages/polycss/vitest.config.ts`, `packages/react/vitest.config.ts`, `packages/vitest.base.mjs`, `packages/vue/vitest.config.ts`, `website/astro.config.mjs`, `website/scripts/generate-builder-shape-thumbnails.mjs`, `website/scripts/generate-gallery-domformat.mjs`, `website/scripts/prove-gallery-domformat.mjs`, `website/scripts/run-unit-tests.mjs`, `website/tsconfig.json` ## 3. Top Import Hubs (`fanIn`) & Largest Source Files @@ -45,14 +45,14 @@ Single source of truth: [`packages/workspace-aliases.mjs`](../../packages/worksp | Fan-in | Lines | File | |---:|---:|---| -| 123 | 528 | `packages/core/src/index.ts` | +| 127 | 528 | `packages/core/src/index.ts` | | 92 | 248 | `packages/core/src/types.ts` | -| 38 | 301 | `packages/react/src/index.ts` | -| 33 | 119 | `website/src/components/types.ts` | +| 46 | 301 | `packages/react/src/index.ts` | +| 44 | 119 | `website/src/components/types.ts` | | 29 | 148 | `packages/polycss/src/runtime.ts` | -| 22 | 220 | `packages/polycss/src/index.ts` | +| 25 | 220 | `packages/polycss/src/index.ts` | +| 23 | 88 | `website/src/components/GalleryWorkbench/types.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 | 366 | `packages/core/src/atlas/types.ts` | @@ -68,12 +68,12 @@ Single source of truth: [`packages/workspace-aliases.mjs`](../../packages/worksp | 1,178 | `packages/domformat/src/browser.ts` | | 1,139 | `website/src/components/GalleryWorkbench/presets/presetFiles.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` | -| 827 | `website/src/components/BuilderWorkbench/components/BuilderScene.tsx` | -| 825 | `website/src/components/GalleryWorkbench/hooks/useRouteSync.ts` | -| 801 | `packages/polycss/src/api/controls/gizmoEngine.ts` | +| 771 | `packages/core/src/merge/coverPlanarPolygons.ts` | +| 757 | `packages/core/src/parser/parseStl.ts` | +| 728 | `packages/core/src/parser/parseVox.ts` | +| 718 | `bench/perf-gate.mjs` | +| 711 | `packages/domformat/src/state/paged-state.ts` | ## 4. Core Render & Control Pipelines diff --git a/.github/scripts/check-boundaries.mjs b/.github/scripts/check-boundaries.mjs index 02373e25..1686210c 100644 --- a/.github/scripts/check-boundaries.mjs +++ b/.github/scripts/check-boundaries.mjs @@ -639,7 +639,7 @@ function checkPackageDir(root, pkg, dir, rules, violations) { } function checkDeepImportsOutsidePackages(root, violations) { - const scanRoots = ["website/src", "website/scripts", "bench", "examples"] + const scanRoots = ["website/src", "website/scripts", "website/tests", "bench", "examples"] .map((dir) => resolve(root, dir)) .filter((dir) => { try { diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 656b56ad..b065f5d0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,7 +18,7 @@ jobs: timeout-minutes: 15 steps: - name: Check out - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: # check:mirrors needs history to merge-base against the PR's base ref; # it runs with --require-base, so a shallow clone fails the job. @@ -58,14 +58,17 @@ jobs: - name: Certify Gallery domformat corpus run: pnpm --filter @layoutit/polycss-website test:domformat-tools && pnpm --filter @layoutit/polycss-website verify:domformat + - name: Run website unit tests + run: pnpm test:website + - name: Build website run: pnpm build:website - name: Build bench bundles run: pnpm bench:build - - name: Build examples - run: pnpm --filter './examples/*' -r build + - name: Typecheck and build examples + run: pnpm typecheck:examples && pnpm --filter './examples/*' -r build visual-gate: if: github.event_name == 'pull_request' @@ -74,7 +77,7 @@ jobs: timeout-minutes: 20 steps: - name: Check out - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 @@ -111,7 +114,7 @@ jobs: - name: Upload failing visual-gate report and triptychs if: failure() && steps.changes.outputs.run == 'true' - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: visual-gate-failures path: bench/results/ci-gate @@ -123,7 +126,7 @@ jobs: timeout-minutes: 20 steps: - name: Check out - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 @@ -158,7 +161,7 @@ jobs: - name: Upload failing perf-gate report if: failure() && steps.changes.outputs.run == 'true' - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: perf-gate-failures path: bench/results/ci-perf-gate @@ -170,7 +173,7 @@ jobs: timeout-minutes: 15 steps: - name: Check out - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 @@ -207,7 +210,7 @@ jobs: - name: Upload failing lifecycle-gate report if: failure() && steps.changes.outputs.run == 'true' - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: lifecycle-gate-failures path: bench/results/ci-lifecycle-gate @@ -219,7 +222,7 @@ jobs: timeout-minutes: 45 steps: - name: Check out - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 @@ -269,7 +272,7 @@ jobs: timeout-minutes: 30 steps: - name: Check out - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 diff --git a/.github/workflows/deploy-website.yml b/.github/workflows/deploy-website.yml index 1bd569a5..9c223b06 100644 --- a/.github/workflows/deploy-website.yml +++ b/.github/workflows/deploy-website.yml @@ -30,7 +30,7 @@ jobs: url: ${{ steps.deployment.outputs.page_url }} steps: - name: Check out - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Setup workspace uses: ./.github/actions/setup-workspace @@ -42,15 +42,15 @@ jobs: run: pnpm build:website - name: Configure GitHub Pages - uses: actions/configure-pages@983d7736d9b0ae728b81ab479565c72886d7745b + uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d # v6.0.0 with: enablement: true - name: Upload GitHub Pages artifact - uses: actions/upload-pages-artifact@7b1f4a764d45c48632c6b24a0339c27f5614fb0b + uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0 with: path: website/dist - name: Deploy to GitHub Pages id: deployment - uses: actions/deploy-pages@d6db90164ac5ed86f2b6aed7e0febac5b3c0c03e + uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1 diff --git a/.github/workflows/publish-packages.yml b/.github/workflows/publish-packages.yml index 920e2262..f5f5501c 100644 --- a/.github/workflows/publish-packages.yml +++ b/.github/workflows/publish-packages.yml @@ -35,15 +35,13 @@ jobs: runs-on: ubuntu-latest steps: - name: Check out - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 token: ${{ secrets.GITHUB_TOKEN }} - name: Setup workspace uses: ./.github/actions/setup-workspace - with: - registry-url: "https://registry.npmjs.org" - name: Run repo guards run: pnpm check:guards @@ -71,7 +69,11 @@ jobs: run: pnpm --filter @layoutit/polycss-morph test:package - name: Publish to npm - run: pnpm --filter "./packages/*" --filter "!@layoutit/polycss-domformat" -r publish --access public --no-git-checks + run: | + NPMRC="$(mktemp)" + trap 'rm -f "$NPMRC"' EXIT + printf 'registry=https://registry.npmjs.org/\n//registry.npmjs.org/:_authToken=%s\n' "$NODE_AUTH_TOKEN" > "$NPMRC" + NPM_CONFIG_USERCONFIG="$NPMRC" pnpm --filter "./packages/*" --filter "!@layoutit/polycss-domformat" -r publish --access public --no-git-checks env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} diff --git a/AGENTS.md b/AGENTS.md index 0c9bdf30..18cd7a51 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -74,7 +74,7 @@ Public API is **mirrored** across React and Vue. Explicit `*/three` subpaths (`@ ## Tests, visual gates & build -- **One-command local preflight:** `pnpm verify` runs `check:guards`, `test`, `build:packages`, `typecheck`, `check:ir`, `check:packs`, `bench:build`, and `examples/*` builds. `pnpm test:coverage` enforces coverage thresholds across all 8 workspace packages. +- **One-command local preflight:** `pnpm verify` runs `check:guards`, `test`, `test:website`, `build:packages`, `typecheck`, `typecheck:website`, `typecheck:examples`, `check:ir`, `check:packs`, `bench:build`, and `examples/*` builds. `pnpm test:coverage` enforces coverage thresholds across all 8 workspace packages. - **`pnpm test && pnpm build` is mandatory** before opening a PR (Vitest does not catch `tsup`/DTS declaration errors). Never delete or weaken tests to pass a refactor. - **Renderer changes require fail-closed `pixelmatch` static + 360° video triptych gates** via `bench/visual-gate.mjs` (`pixelmatch` + `pngjs` in Node): - `pnpm bench:gate:parity` — HEAD internal equivalence (4-way renderer parity across vanilla/html/react/vue, strategy parity vs `all-s`, dynamic vs baked, shadows, translucent faces, plus fail-closed `renderStats` tag-shift checks) with zero static PNG baselines. @@ -85,7 +85,7 @@ Public API is **mirrored** across React and Vue. Explicit `*/three` subpaths (`@ - `pnpm bench:gate:perf -- --base-ref ` — fail-closed A/B perf gate (`bench/perf-gate.mjs`): enforces active motion, 0 per-frame descendant DOM mutations, exact leaf counts, no non-bucket DOM/style/``/layout regressions, and paired p50/p95/JS-per-frame/bimodal budgets on Chromium. - `pnpm bench:gate:lifecycle` — fail-closed Node SSR + Chromium lifecycle gate (`bench/lifecycle-gate.mjs`): verifies pure Node SSR (zero DOM globals), React `` remounts and textured `` blob URLs, `setOptions` / 3× rebake / `undefined` clears, real `.vox` class updates, stable-topology overrides, dynamic shadow emits, Vue async `src` single-mount, and controls interaction. - Shared browser and `ffmpeg` discovery lives in `bench/browser-discovery.mjs`. Gate fail-closed invariants are unit-tested in `bench/{visual,perf,lifecycle}-gate.test.mjs` (`pnpm test:scripts`). -- **CI (`.github/workflows/ci.yml`)** runs `test-and-build` (`check:guards`, unified `test:coverage`, `build:packages`, `typecheck`, `check:packs`, `check:ir`, website/bench/examples), path-filtered PR `visual-gate` (Chromium + Firefox), `perf-gate` (paired A/B on Chromium), `lifecycle-gate` (Node SSR + Chromium), and `certify-domformat-browser` / `certify-gallery-domformat-corpus` (path-filtered on PRs, unconditional on `push: main`). `.github/workflows/publish-packages.yml` runs `check:guards`, `test`, `build:packages`, `typecheck`, `check:ir`, `check:packs`, and `morph test:package` before publishing. +- **CI (`.github/workflows/ci.yml`)** runs `test-and-build` (`check:guards`, unified `test:coverage`, `build:packages`, `typecheck`, `check:packs`, `check:ir`, `test:website`, website/bench/examples typecheck & builds), path-filtered PR `visual-gate` (Chromium + Firefox), `perf-gate` (paired A/B on Chromium), `lifecycle-gate` (Node SSR + Chromium), and `certify-domformat-browser` / `certify-gallery-domformat-corpus` (path-filtered on PRs, unconditional on `push: main`). `.github/workflows/publish-packages.yml` runs `check:guards`, `test`, `build:packages`, `typecheck`, `check:ir`, `check:packs`, and `morph test:package` before publishing. - **Pre-push & dead-code hygiene:** Check `.github/workflows/ci.yml` path filters before editing peripheral packages (`packages/domformat` triggers the 45-minute `certify-domformat-browser` job; `packages/morph` is tested against npm-published `@layoutit/polycss-core` by `test:package:registry`). Always grep the entire repo including `.agents/` (e.g., `.agents/skills/chrome-trace/scripts/`) before deleting any export. ## Style / process diff --git a/examples/html/package.json b/examples/html/package.json index bb53c0b1..34dbc4a4 100644 --- a/examples/html/package.json +++ b/examples/html/package.json @@ -6,6 +6,7 @@ "scripts": { "dev": "vite", "build": "vite build", + "typecheck": "tsc --noEmit", "preview": "vite preview" }, "dependencies": { diff --git a/examples/react/package.json b/examples/react/package.json index 2aeaa183..ee54114f 100644 --- a/examples/react/package.json +++ b/examples/react/package.json @@ -6,6 +6,7 @@ "scripts": { "dev": "vite", "build": "vite build", + "typecheck": "tsc --noEmit", "preview": "vite preview" }, "dependencies": { diff --git a/examples/vanilla/package.json b/examples/vanilla/package.json index 5a582e5b..32d34d4d 100644 --- a/examples/vanilla/package.json +++ b/examples/vanilla/package.json @@ -6,6 +6,7 @@ "scripts": { "dev": "vite", "build": "vite build", + "typecheck": "tsc --noEmit", "preview": "vite preview" }, "dependencies": { diff --git a/examples/vue/package.json b/examples/vue/package.json index 869a09f5..23fae5de 100644 --- a/examples/vue/package.json +++ b/examples/vue/package.json @@ -6,6 +6,7 @@ "scripts": { "dev": "vite", "build": "vite build", + "typecheck": "tsc --noEmit", "preview": "vite preview" }, "dependencies": { diff --git a/package.json b/package.json index a76c64e1..57ff9a8b 100644 --- a/package.json +++ b/package.json @@ -37,9 +37,11 @@ "check:ir": "node --test bench/renderer-ir-conformance.test.mjs", "typecheck": "pnpm --filter './packages/*' -r --if-present typecheck", "typecheck:website": "pnpm --filter @layoutit/polycss-website typecheck", + "typecheck:examples": "pnpm --filter './examples/*' -r typecheck", + "test:website": "pnpm --filter @layoutit/polycss-website test:unit", "test:scripts": "node --test .github/scripts/*.test.mjs bench/visual-gate.test.mjs bench/perf-gate.test.mjs bench/lifecycle-gate.test.mjs", "check:guards": "pnpm test:scripts && pnpm check:readmes && pnpm check:skill && pnpm check:map && pnpm check:boundaries && pnpm check:mirrors --require-base && pnpm check:exports", - "verify": "pnpm check:guards && pnpm test && pnpm build:packages && pnpm typecheck && pnpm typecheck:website && pnpm check:ir && pnpm check:packs && pnpm bench:build && pnpm --filter './examples/*' -r build", + "verify": "pnpm check:guards && pnpm test && pnpm test:website && pnpm build:packages && pnpm typecheck && pnpm typecheck:website && pnpm typecheck:examples && pnpm check:ir && pnpm check:packs && pnpm bench:build && pnpm --filter './examples/*' -r build", "publish:all": "pnpm sync:readmes && pnpm --filter './packages/*' --filter '!@layoutit/polycss-domformat' -r publish --access public", "dev:website": "pnpm --filter @layoutit/polycss-website dev", "gallery:domformat": "pnpm --filter @layoutit/polycss-website generate:domformat", diff --git a/packages/morph/src/contracts/validation.test.ts b/packages/morph/src/contracts/validation.test.ts index c5f66965..0e005020 100644 --- a/packages/morph/src/contracts/validation.test.ts +++ b/packages/morph/src/contracts/validation.test.ts @@ -294,7 +294,16 @@ describe("validatePolyMorphModel", () => { }); it("keeps internal leaf tags out of the public contracts", () => { - const publicFiles = ["types.ts", "validation.ts", "index.ts"].map((name) => + const publicFiles = [ + "types.ts", + "validation.ts", + "index.ts", + "validation/primitives.ts", + "validation/metadata.ts", + "validation/deformation.ts", + "validation/motion.ts", + "validation/render.ts", + ].map((name) => readFileSync(fileURLToPath(new URL(name, import.meta.url)), "utf8").toLowerCase()); for (const source of publicFiles) { expect(source).not.toMatch(/<(?:b|i|s|u)>/); diff --git a/packages/morph/src/contracts/validation.ts b/packages/morph/src/contracts/validation.ts index 5c594dcd..ffe63533 100644 --- a/packages/morph/src/contracts/validation.ts +++ b/packages/morph/src/contracts/validation.ts @@ -1,585 +1,40 @@ +import { POLY_MORPH_MODEL_SCHEMA, type PolyMorphModel } from "./types.js"; +import { validateDeformation } from "./validation/deformation.js"; import { - POLY_MORPH_MODEL_SCHEMA, - type PolyMorphAnimationChannel, - type PolyMorphAnimationTarget, - type PolyMorphAtlasSlice, - type PolyMorphCapability, - type PolyMorphControl, - type PolyMorphDeformation, - type PolyMorphJoint, - type PolyMorphMat4, - type PolyMorphModel, - type PolyMorphPlayback, - type PolyMorphProfile, - type PolyMorphProvenanceSource, - type PolyMorphRenderFallback, - type PolyMorphRenderLeaf, - type PolyMorphRenderStrategy, - type PolyMorphTopology, - type PolyMorphVec3, -} from "./types.js"; - -const ID = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/; -const PATH_SEGMENT = /^[a-z0-9][a-z0-9._-]*$/; -const REVISION = /^\d+\.\d+\.\d+$/; -const SHA256 = /^[a-f0-9]{64}$/; -const PROFILES = new Set([ - "joint-skin", - "morph-regions", - "prepared-playback", - "static-prepared", -]); -const CAPABILITIES = new Set([ - "animation", - "joint-skinning", - "morph-targets", - "prepared-playback", - "retained-render", - "semantic-controls", - "sparse-updates", - "springs", -]); -const STRATEGIES = new Set([ - "atlas-slice", - "direct-image", - "solid-quad", - "solid-triangle", -]); -const ANIMATION_TARGETS = new Set([ - "control-value", - "joint-rotation", - "joint-scale", - "joint-translation", - "morph-weight", - "shape-matrix", -]); - -export class PolyMorphContractError extends TypeError { - readonly code: string; - readonly path: string; - - constructor(code: string, path: string, message: string) { - super(`${path}: ${message}`); - this.name = "PolyMorphContractError"; - this.code = code; - this.path = path; - } -} - -function fail(code: string, path: string, message: string): never { - throw new PolyMorphContractError(code, path, message); -} - -export function assertExactRecord( - value: unknown, - path: string, - keys: readonly string[], - onFail: (code: string, path: string, message: string) => never, -): Record { - if (!value || typeof value !== "object" || Array.isArray(value)) { - onFail("invalid-type", path, "expected an object"); - } - const actual = Object.keys(value).sort(); - const expected = [...keys].sort(); - if (actual.length !== expected.length || actual.some((key, index) => key !== expected[index])) { - onFail("invalid-keys", path, `expected exactly ${expected.join(", ")}`); - } - return value as Record; -} - -function record( - value: unknown, - path: string, - keys: readonly string[], -): Record { - return assertExactRecord(value, path, keys, fail); -} - -function array(value: unknown, path: string): readonly unknown[] { - if (!Array.isArray(value)) fail("invalid-type", path, "expected an array"); - return value; -} - -function string(value: unknown, path: string): string { - if (typeof value !== "string" || value.length === 0) { - fail("invalid-string", path, "expected a non-empty string"); - } - return value; -} - -function number(value: unknown, path: string): number { - if (typeof value !== "number" || !Number.isFinite(value)) { - fail("invalid-number", path, "expected a finite number"); - } - return value; -} - -function integer(value: unknown, path: string, minimum = 0): number { - const result = number(value, path); - if (!Number.isSafeInteger(result) || result < minimum) { - fail("invalid-integer", path, `expected an integer >= ${minimum}`); - } - return result; -} - -function boolean(value: unknown, path: string): boolean { - if (typeof value !== "boolean") fail("invalid-boolean", path, "expected a boolean"); - return value; -} - -function id(value: unknown, path: string): string { - const result = string(value, path); - if (!ID.test(result)) fail("invalid-id", path, "expected a normalized kebab-case id"); - return result; -} - -function uniqueIds(values: readonly string[], path: string): void { - const seen = new Set(); - for (const value of values) { - if (seen.has(value)) fail("duplicate-id", path, `duplicate id ${value}`); - seen.add(value); - } -} - -function vec3(value: unknown, path: string): PolyMorphVec3 { - const values = array(value, path); - if (values.length !== 3) fail("invalid-vector", path, "expected three components"); - return values.map((part, index) => number(part, `${path}[${index}]`)) as unknown as PolyMorphVec3; -} - -function mat4(value: unknown, path: string): PolyMorphMat4 { - const values = array(value, path); - if (values.length !== 16) fail("invalid-matrix", path, "expected sixteen components"); - return values.map((part, index) => number(part, `${path}[${index}]`)) as unknown as PolyMorphMat4; -} - -function normalizedPath(value: unknown, path: string): string { - const result = string(value, path); - if ( - result.split("/").some((part) => !PATH_SEGMENT.test(part)) - ) { - fail( - "invalid-path", - path, - "expected lowercase URL-safe package path segments", - ); - } - return result; -} - -function indexInRange(value: unknown, path: string, length: number): number { - const result = integer(value, path); - if (result >= length) fail("out-of-range", path, `expected an index below ${length}`); - return result; -} - -function validateTopology(value: unknown, path: string): PolyMorphTopology { - const input = record(value, path, ["normals", "polygons", "vertices"]); - const vertices = array(input.vertices, `${path}.vertices`).map((entry, index) => - vec3(entry, `${path}.vertices[${index}]`)); - const normals = array(input.normals, `${path}.normals`).map((entry, index) => - vec3(entry, `${path}.normals[${index}]`)); - if (vertices.length === 0) fail("missing-topology", `${path}.vertices`, "expected at least one vertex"); - if (normals.length === 0) fail("missing-topology", `${path}.normals`, "expected at least one normal"); - const polygons = array(input.polygons, `${path}.polygons`).map((entry, index) => { - const itemPath = `${path}.polygons[${index}]`; - const polygon = record(entry, itemPath, ["id", "normalIndices", "vertexIndices"]); - const vertexIndices = array(polygon.vertexIndices, `${itemPath}.vertexIndices`).map((part, partIndex) => - indexInRange(part, `${itemPath}.vertexIndices[${partIndex}]`, vertices.length)); - const normalIndices = array(polygon.normalIndices, `${itemPath}.normalIndices`).map((part, partIndex) => - indexInRange(part, `${itemPath}.normalIndices[${partIndex}]`, normals.length)); - if (vertexIndices.length < 3) fail("invalid-polygon", itemPath, "expected at least three vertices"); - if (normalIndices.length !== vertexIndices.length) { - fail("invalid-polygon", itemPath, "normal and vertex index counts must match"); - } - if (new Set(vertexIndices).size !== vertexIndices.length) { - fail("invalid-polygon", itemPath, "vertex indices must be unique"); - } - return { - id: id(polygon.id, `${itemPath}.id`), - vertexIndices, - normalIndices, - }; - }); - if (polygons.length === 0) fail("missing-topology", `${path}.polygons`, "expected at least one polygon"); - uniqueIds(polygons.map((polygon) => polygon.id), `${path}.polygons`); - return { vertices, normals, polygons }; -} - -function validateRenderLeaf( - value: unknown, - path: string, - references: { - readonly polygonIds: ReadonlySet; - readonly shapeIds: ReadonlySet; - readonly materialIds: ReadonlySet; - }, -): PolyMorphRenderLeaf { - const input = record(value, path, [ - "atlas", - "fallback", - "height", - "id", - "materialId", - "matrix", - "polygonId", - "shapeId", - "strategy", - "width", - ]); - const strategy = string(input.strategy, `${path}.strategy`) as PolyMorphRenderStrategy; - if (!STRATEGIES.has(strategy)) fail("invalid-strategy", `${path}.strategy`, "unknown render strategy"); - const polygonId = id(input.polygonId, `${path}.polygonId`); - const shapeId = id(input.shapeId, `${path}.shapeId`); - const materialId = id(input.materialId, `${path}.materialId`); - if (!references.polygonIds.has(polygonId)) fail("unknown-reference", `${path}.polygonId`, polygonId); - if (!references.shapeIds.has(shapeId)) fail("unknown-reference", `${path}.shapeId`, shapeId); - if (!references.materialIds.has(materialId)) fail("unknown-reference", `${path}.materialId`, materialId); - const width = number(input.width, `${path}.width`); - const height = number(input.height, `${path}.height`); - if (width <= 0 || height <= 0) fail("invalid-size", path, "leaf dimensions must be positive"); - const needsAtlas = strategy === "atlas-slice" || strategy === "direct-image"; - const atlas = input.atlas === null - ? null - : validateAtlasSlice(input.atlas, `${path}.atlas`); - if (needsAtlas !== (atlas !== null)) { - fail("invalid-strategy", `${path}.atlas`, needsAtlas - ? "image strategies require an atlas/source slice" - : "solid strategies cannot declare an atlas/source slice"); - } - const fallback = input.fallback === null - ? null - : validateRenderFallback(input.fallback, `${path}.fallback`); - if (fallback !== null && strategy !== "solid-triangle") { - fail( - "invalid-strategy", - `${path}.fallback`, - "only solid-triangle leaves may declare a prepared fallback", - ); - } - return { - id: id(input.id, `${path}.id`), - polygonId, - shapeId, - materialId, - strategy, - width, - height, - matrix: mat4(input.matrix, `${path}.matrix`), - atlas, - fallback, - }; -} - -function validateRenderFallback( - value: unknown, - path: string, -): PolyMorphRenderFallback { - const input = record(value, path, [ - "atlas", - "height", - "matrixFromLeaf", - "width", - ]); - const width = integer(input.width, `${path}.width`, 1); - const height = integer(input.height, `${path}.height`, 1); - const atlas = validateAtlasSlice(input.atlas, `${path}.atlas`); - if (atlas.width !== width || atlas.height !== height) { - fail( - "invalid-size", - path, - "fallback dimensions must match its per-polygon atlas slice", - ); - } - return { - width, - height, - matrixFromLeaf: mat4(input.matrixFromLeaf, `${path}.matrixFromLeaf`), - atlas, - }; -} - -function validateAtlasSlice( - value: unknown, - path: string, -): PolyMorphAtlasSlice { - const input = record(value, path, [ - "height", - "pageHeight", - "pageWidth", - "resourcePath", - "width", - "x", - "y", - ]); - const atlas = { - resourcePath: normalizedPath(input.resourcePath, `${path}.resourcePath`), - x: integer(input.x, `${path}.x`), - y: integer(input.y, `${path}.y`), - width: integer(input.width, `${path}.width`, 1), - height: integer(input.height, `${path}.height`, 1), - pageWidth: integer(input.pageWidth, `${path}.pageWidth`, 1), - pageHeight: integer(input.pageHeight, `${path}.pageHeight`, 1), - }; - if (atlas.x + atlas.width > atlas.pageWidth || atlas.y + atlas.height > atlas.pageHeight) { - fail("out-of-range", path, "slice must fit inside its page"); - } - return atlas; -} - -function validateDeformation( - value: unknown, - path: string, - topology: PolyMorphTopology, -): PolyMorphDeformation { - if (!value || typeof value !== "object" || Array.isArray(value)) { - fail("invalid-type", path, "expected a deformation object"); - } - const kind = string((value as Record).kind, `${path}.kind`); - if (kind === "none") { - record(value, path, ["kind"]); - return { kind }; - } - if (kind === "morph-regions") { - const input = record(value, path, ["kind", "targets"]); - const targets = array(input.targets, `${path}.targets`).map((entry, targetIndex) => { - const targetPath = `${path}.targets[${targetIndex}]`; - const target = record(entry, targetPath, ["deltas", "id"]); - const deltas = array(target.deltas, `${targetPath}.deltas`).map((deltaEntry, deltaIndex) => { - const deltaPath = `${targetPath}.deltas[${deltaIndex}]`; - const delta = record(deltaEntry, deltaPath, ["normal", "position", "vertexIndex"]); - const position = delta.position === null ? null : vec3(delta.position, `${deltaPath}.position`); - const normal = delta.normal === null ? null : vec3(delta.normal, `${deltaPath}.normal`); - if (position === null && normal === null) { - fail("empty-delta", deltaPath, "expected a position or normal delta"); - } - return { - vertexIndex: indexInRange(delta.vertexIndex, `${deltaPath}.vertexIndex`, topology.vertices.length), - position, - normal, - }; - }); - if (deltas.length === 0) fail("missing-deltas", `${targetPath}.deltas`, "expected at least one delta"); - const indices = deltas.map((delta) => String(delta.vertexIndex)); - uniqueIds(indices, `${targetPath}.deltas`); - return { id: id(target.id, `${targetPath}.id`), deltas }; - }); - if (targets.length === 0) fail("missing-targets", `${path}.targets`, "expected at least one target"); - uniqueIds(targets.map((target) => target.id), `${path}.targets`); - return { kind, targets }; - } - if (kind === "joint-skin") { - const input = record(value, path, ["joints", "kind", "vertices"]); - const joints = array(input.joints, `${path}.joints`).map((entry, jointIndex) => { - const jointPath = `${path}.joints[${jointIndex}]`; - const joint = record(entry, jointPath, ["id", "inverseBindMatrix", "parentId", "restMatrix"]); - return { - id: id(joint.id, `${jointPath}.id`), - parentId: joint.parentId === null ? null : id(joint.parentId, `${jointPath}.parentId`), - restMatrix: mat4(joint.restMatrix, `${jointPath}.restMatrix`), - inverseBindMatrix: mat4(joint.inverseBindMatrix, `${jointPath}.inverseBindMatrix`), - }; - }); - if (joints.length === 0) fail("missing-joints", `${path}.joints`, "expected at least one joint"); - uniqueIds(joints.map((joint) => joint.id), `${path}.joints`); - validateJointHierarchy(joints, `${path}.joints`); - const jointIds = new Set(joints.map((joint) => joint.id)); - const vertices = array(input.vertices, `${path}.vertices`).map((entry, vertexIndex) => { - const vertexPath = `${path}.vertices[${vertexIndex}]`; - const vertex = record(entry, vertexPath, ["influences", "vertexIndex"]); - const resolvedIndex = indexInRange(vertex.vertexIndex, `${vertexPath}.vertexIndex`, topology.vertices.length); - const influences = array(vertex.influences, `${vertexPath}.influences`).map((entryInfluence, influenceIndex) => { - const influencePath = `${vertexPath}.influences[${influenceIndex}]`; - const influence = record(entryInfluence, influencePath, ["jointId", "weight"]); - const jointId = id(influence.jointId, `${influencePath}.jointId`); - if (!jointIds.has(jointId)) fail("unknown-reference", `${influencePath}.jointId`, jointId); - const weight = number(influence.weight, `${influencePath}.weight`); - if (weight <= 0 || weight > 1) fail("invalid-weight", `${influencePath}.weight`, "expected 0 < weight <= 1"); - return { jointId, weight }; - }); - if (influences.length === 0) fail("missing-influences", `${vertexPath}.influences`, "expected at least one influence"); - uniqueIds(influences.map((influence) => influence.jointId), `${vertexPath}.influences`); - const total = influences.reduce((sum, influence) => sum + influence.weight, 0); - if (Math.abs(total - 1) > 1e-6) fail("invalid-weight", `${vertexPath}.influences`, "weights must sum to 1"); - return { vertexIndex: resolvedIndex, influences }; - }); - if (vertices.length !== topology.vertices.length) { - fail("missing-skin-vertex", `${path}.vertices`, "every topology vertex must have one skin record"); - } - const skinIndices = vertices.map((vertex) => String(vertex.vertexIndex)); - uniqueIds(skinIndices, `${path}.vertices`); - return { kind, joints, vertices }; - } - fail("invalid-deformation", `${path}.kind`, `unknown deformation kind ${kind}`); -} - -function validateJointHierarchy(joints: readonly PolyMorphJoint[], path: string): void { - const byId = new Map(joints.map((joint) => [joint.id, joint])); - const roots = joints.filter((joint) => joint.parentId === null); - if (roots.length !== 1) fail("invalid-hierarchy", path, "expected exactly one root joint"); - for (const joint of joints) { - if (joint.parentId !== null && !byId.has(joint.parentId)) { - fail("unknown-reference", path, `joint ${joint.id} references ${joint.parentId}`); - } - const seen = new Set(); - let ancestor: PolyMorphJoint | undefined = joint; - while (ancestor) { - if (seen.has(ancestor.id)) fail("invalid-hierarchy", path, `cycle at joint ${ancestor.id}`); - seen.add(ancestor.id); - ancestor = ancestor.parentId === null ? undefined : byId.get(ancestor.parentId); - } - } -} - -function channelArity(target: PolyMorphAnimationTarget): number { - if (target === "control-value" || target === "morph-weight") return 1; - if (target === "joint-rotation") return 4; - if (target === "shape-matrix") return 16; - return 3; -} - -function validateAnimationChannel( - value: unknown, - path: string, - references: { - readonly controlIds: ReadonlySet; - readonly jointIds: ReadonlySet; - readonly shapeIds: ReadonlySet; - readonly targetIds: ReadonlySet; - }, - durationMs: number, -): PolyMorphAnimationChannel { - const input = record(value, path, ["interpolation", "target", "targetId", "timesMs", "values"]); - const target = string(input.target, `${path}.target`) as PolyMorphAnimationTarget; - if (!ANIMATION_TARGETS.has(target)) fail("invalid-animation-target", `${path}.target`, target); - const targetId = id(input.targetId, `${path}.targetId`); - const referenceSet = target === "control-value" - ? references.controlIds - : target === "morph-weight" - ? references.targetIds - : target === "shape-matrix" - ? references.shapeIds - : references.jointIds; - if (!referenceSet.has(targetId)) fail("unknown-reference", `${path}.targetId`, targetId); - const interpolation = string(input.interpolation, `${path}.interpolation`); - if (interpolation !== "linear" && interpolation !== "step") { - fail("invalid-interpolation", `${path}.interpolation`, interpolation); - } - if (target === "shape-matrix" && interpolation !== "step") { - fail( - "invalid-interpolation", - `${path}.interpolation`, - "shape matrices require step interpolation", - ); - } - const timesMs = array(input.timesMs, `${path}.timesMs`).map((entry, index) => - number(entry, `${path}.timesMs[${index}]`)); - const values = array(input.values, `${path}.values`).map((entry, valueIndex) => { - const parts = array(entry, `${path}.values[${valueIndex}]`); - const arity = channelArity(target); - if (parts.length !== arity) { - fail("invalid-animation-value", `${path}.values[${valueIndex}]`, `expected ${arity} components`); - } - const result = parts.map((part, partIndex) => - number(part, `${path}.values[${valueIndex}][${partIndex}]`)); - if (target === "joint-rotation" && Math.hypot(...result) <= 1e-12) { - fail( - "invalid-animation-value", - `${path}.values[${valueIndex}]`, - "quaternion must be non-zero", - ); - } - return result; - }); - if (timesMs.length === 0 || timesMs.length !== values.length) { - fail("invalid-animation-samples", path, "times and values must have the same non-zero length"); - } - if (timesMs[0] !== 0 || timesMs.some((time, index) => - time < 0 || time > durationMs || (index > 0 && time <= timesMs[index - 1]!))) { - fail("invalid-animation-time", `${path}.timesMs`, "times must start at zero and increase within the clip"); - } - return { - target, - targetId, - interpolation, - timesMs, - values, - }; -} - -function validatePlayback( - value: unknown, - path: string, - leafIds: ReadonlySet, - shapeIds: ReadonlySet, -): PolyMorphPlayback { - const input = record(value, path, ["durationMs", "frames", "loop"]); - const durationMs = number(input.durationMs, `${path}.durationMs`); - if (durationMs <= 0) fail("invalid-duration", `${path}.durationMs`, "expected a positive duration"); - const frames = array(input.frames, `${path}.frames`).map((entry, frameIndex) => { - const framePath = `${path}.frames[${frameIndex}]`; - const frame = record(entry, framePath, ["leaves", "modelMatrix", "shapes", "timeMs"]); - const timeMs = number(frame.timeMs, `${framePath}.timeMs`); - const shapes = array(frame.shapes, `${framePath}.shapes`).map((shapeEntry, shapeIndex) => { - const shapePath = `${framePath}.shapes[${shapeIndex}]`; - const shape = record(shapeEntry, shapePath, ["matrix", "shapeId"]); - const shapeId = id(shape.shapeId, `${shapePath}.shapeId`); - if (!shapeIds.has(shapeId)) fail("unknown-reference", `${shapePath}.shapeId`, shapeId); - return { shapeId, matrix: mat4(shape.matrix, `${shapePath}.matrix`) }; - }); - uniqueIds(shapes.map((shape) => shape.shapeId), `${framePath}.shapes`); - const leaves = array(frame.leaves, `${framePath}.leaves`).map((leafEntry, leafIndex) => { - const leafPath = `${framePath}.leaves[${leafIndex}]`; - const leaf = record(leafEntry, leafPath, ["atlasRow", "leafId", "matrix", "opacity", "visible"]); - const leafId = id(leaf.leafId, `${leafPath}.leafId`); - if (!leafIds.has(leafId)) fail("unknown-reference", `${leafPath}.leafId`, leafId); - const opacity = leaf.opacity === null ? null : number(leaf.opacity, `${leafPath}.opacity`); - if (opacity !== null && (opacity < 0 || opacity > 1)) { - fail("out-of-range", `${leafPath}.opacity`, "expected 0 <= opacity <= 1"); - } - return { - leafId, - matrix: leaf.matrix === null ? null : mat4(leaf.matrix, `${leafPath}.matrix`), - visible: leaf.visible === null ? null : boolean(leaf.visible, `${leafPath}.visible`), - opacity, - atlasRow: leaf.atlasRow === null ? null : integer(leaf.atlasRow, `${leafPath}.atlasRow`), - }; - }); - uniqueIds(leaves.map((leaf) => leaf.leafId), `${framePath}.leaves`); - return { - timeMs, - modelMatrix: frame.modelMatrix === null ? null : mat4(frame.modelMatrix, `${framePath}.modelMatrix`), - shapes, - leaves, - }; - }); - if (frames.length === 0) fail("missing-frames", `${path}.frames`, "expected at least one frame"); - if (frames[0]!.timeMs !== 0 || frames.some((frame, index) => - frame.timeMs < 0 - || frame.timeMs > durationMs - || (index > 0 && frame.timeMs <= frames[index - 1]!.timeMs))) { - fail("invalid-frame-time", `${path}.frames`, "frames must start at zero and increase within the timeline"); - } - return { durationMs, loop: boolean(input.loop, `${path}.loop`), frames }; -} - -function requiredCapabilities( - profile: PolyMorphProfile, - model: { - readonly controls: readonly unknown[]; - readonly springs: readonly unknown[]; - readonly animations: readonly unknown[]; - }, -): readonly PolyMorphCapability[] { - const required: PolyMorphCapability[] = ["retained-render"]; - if (profile === "morph-regions") required.push("morph-targets", "sparse-updates"); - if (profile === "joint-skin") required.push("joint-skinning", "sparse-updates"); - if (profile === "prepared-playback") required.push("prepared-playback", "sparse-updates"); - if (model.controls.length > 0) required.push("semantic-controls"); - if (model.springs.length > 0) required.push("springs"); - if (model.animations.length > 0) required.push("animation"); - return required; -} + validateBudgetLimits, + validateBudgets, + validateCapabilities, + validateIdentity, + validateProfile, + validateProvenance, + validateRequiredCapabilities, +} from "./validation/metadata.js"; +import { + validateAnimations, + validateControls, + validatePlayback, + validateSprings, +} from "./validation/motion.js"; +import { + assertExactRecord, + fail, + isPolyMorphId, + isPolyMorphResourcePath, + PolyMorphContractError, + record, +} from "./validation/primitives.js"; +import { + validateMaterials, + validateRenderPlan, + validateTopology, +} from "./validation/render.js"; + +export { + assertExactRecord, + isPolyMorphId, + isPolyMorphResourcePath, + PolyMorphContractError, +}; export function validatePolyMorphModel(value: unknown): PolyMorphModel { const path = "$"; @@ -602,94 +57,13 @@ export function validatePolyMorphModel(value: unknown): PolyMorphModel { if (input.schema !== POLY_MORPH_MODEL_SCHEMA) { fail("invalid-schema", "$.schema", `expected ${POLY_MORPH_MODEL_SCHEMA}`); } - const identityInput = record(input.identity, "$.identity", ["id", "name", "revision"]); - const identity = { - id: id(identityInput.id, "$.identity.id"), - name: string(identityInput.name, "$.identity.name"), - revision: string(identityInput.revision, "$.identity.revision"), - }; - if (!REVISION.test(identity.revision)) { - fail("invalid-revision", "$.identity.revision", "expected x.y.z"); - } - const profile = string(input.profile, "$.profile") as PolyMorphProfile; - if (!PROFILES.has(profile)) fail("invalid-profile", "$.profile", profile); - const capabilities = array(input.capabilities, "$.capabilities").map((entry, index) => { - const capability = string(entry, `$.capabilities[${index}]`) as PolyMorphCapability; - if (!CAPABILITIES.has(capability)) { - fail("invalid-capability", `$.capabilities[${index}]`, capability); - } - return capability; - }); - uniqueIds(capabilities, "$.capabilities"); - if (capabilities.some((capability, index) => index > 0 && capability <= capabilities[index - 1]!)) { - fail("non-canonical-order", "$.capabilities", "capabilities must be sorted"); - } - const budgetInput = record(input.budgets, "$.budgets", [ - "maxBytes", - "maxFrames", - "maxJoints", - "maxLeaves", - "maxPolygons", - "maxResources", - "maxVertices", - ]); - const budgets = { - maxVertices: integer(budgetInput.maxVertices, "$.budgets.maxVertices"), - maxPolygons: integer(budgetInput.maxPolygons, "$.budgets.maxPolygons"), - maxLeaves: integer(budgetInput.maxLeaves, "$.budgets.maxLeaves"), - maxFrames: integer(budgetInput.maxFrames, "$.budgets.maxFrames"), - maxJoints: integer(budgetInput.maxJoints, "$.budgets.maxJoints"), - maxResources: integer(budgetInput.maxResources, "$.budgets.maxResources"), - maxBytes: integer(budgetInput.maxBytes, "$.budgets.maxBytes"), - }; + const identity = validateIdentity(input.identity, "$.identity"); + const profile = validateProfile(input.profile, "$.profile"); + const capabilities = validateCapabilities(input.capabilities, "$.capabilities"); + const budgets = validateBudgets(input.budgets, "$.budgets"); const topology = validateTopology(input.topology, "$.topology"); - const materials = array(input.materials, "$.materials").map((entry, materialIndex) => { - const materialPath = `$.materials[${materialIndex}]`; - const material = record(entry, materialPath, ["color", "id"]); - const colorParts = array(material.color, `${materialPath}.color`); - if (colorParts.length !== 4) fail("invalid-color", `${materialPath}.color`, "expected four components"); - const color = colorParts.map((part, partIndex) => { - const component = number(part, `${materialPath}.color[${partIndex}]`); - if (component < 0 || component > 1) { - fail("out-of-range", `${materialPath}.color[${partIndex}]`, "expected 0 <= component <= 1"); - } - return component; - }) as [number, number, number, number]; - return { id: id(material.id, `${materialPath}.id`), color }; - }); - if (materials.length === 0) fail("missing-materials", "$.materials", "expected at least one material"); - uniqueIds(materials.map((material) => material.id), "$.materials"); - const renderInput = record(input.render, "$.render", [ - "leaves", - "modelMatrix", - "shapes", - ]); - const shapes = array(renderInput.shapes, "$.render.shapes").map((entry, shapeIndex) => { - const shapePath = `$.render.shapes[${shapeIndex}]`; - const shape = record(entry, shapePath, ["id", "matrix"]); - return { - id: id(shape.id, `${shapePath}.id`), - matrix: mat4(shape.matrix, `${shapePath}.matrix`), - }; - }); - if (shapes.length === 0) fail("missing-shapes", "$.render.shapes", "expected at least one shape"); - uniqueIds(shapes.map((shape) => shape.id), "$.render.shapes"); - const leaves = array(renderInput.leaves, "$.render.leaves").map((entry, leafIndex) => - validateRenderLeaf(entry, `$.render.leaves[${leafIndex}]`, { - polygonIds: new Set(topology.polygons.map((polygon) => polygon.id)), - shapeIds: new Set(shapes.map((shape) => shape.id)), - materialIds: new Set(materials.map((material) => material.id)), - })); - uniqueIds(leaves.map((leaf) => leaf.id), "$.render.leaves"); - uniqueIds(leaves.map((leaf) => leaf.polygonId), "$.render.leaves[*].polygonId"); - if (leaves.length !== topology.polygons.length) { - fail("unstable-topology", "$.render.leaves", "every polygon must bind exactly one retained leaf"); - } - const render = { - modelMatrix: mat4(renderInput.modelMatrix, "$.render.modelMatrix"), - shapes, - leaves, - }; + const materials = validateMaterials(input.materials, "$.materials"); + const render = validateRenderPlan(input.render, "$.render", { topology, materials }); const deformation = validateDeformation(input.deformation, "$.deformation", topology); if ( (profile === "static-prepared" || profile === "prepared-playback") @@ -704,155 +78,36 @@ export function validatePolyMorphModel(value: unknown): PolyMorphModel { const jointIds = new Set(deformation.kind === "joint-skin" ? deformation.joints.map((joint) => joint.id) : []); - const controls = array(input.controls, "$.controls").map((entry, controlIndex): PolyMorphControl => { - const controlPath = `$.controls[${controlIndex}]`; - const control = record(entry, controlPath, [ - "anchor", - "axis", - "id", - "initial", - "maximum", - "minimum", - "radius", - "targets", - ]); - const minimum = number(control.minimum, `${controlPath}.minimum`); - const maximum = number(control.maximum, `${controlPath}.maximum`); - const initial = number(control.initial, `${controlPath}.initial`); - if (minimum > maximum || initial < minimum || initial > maximum) { - fail("invalid-control-bounds", controlPath, "expected minimum <= initial <= maximum"); - } - const anchor = vec3(control.anchor, `${controlPath}.anchor`); - const axis = vec3(control.axis, `${controlPath}.axis`); - const axisLength = Math.hypot(...axis); - if (axisLength < 1e-9) fail("invalid-control-axis", `${controlPath}.axis`, "axis must be non-zero"); - const radius = number(control.radius, `${controlPath}.radius`); - if (radius <= 0) fail("invalid-control-radius", `${controlPath}.radius`, "radius must be positive"); - const targets = array(control.targets, `${controlPath}.targets`).map((entryTarget, targetIndex) => { - const targetPath = `${controlPath}.targets[${targetIndex}]`; - const target = record(entryTarget, targetPath, ["scale", "targetId"]); - const targetId = id(target.targetId, `${targetPath}.targetId`); - if (!targetIds.has(targetId)) fail("unknown-reference", `${targetPath}.targetId`, targetId); - return { targetId, scale: number(target.scale, `${targetPath}.scale`) }; - }); - uniqueIds(targets.map((target) => target.targetId), `${controlPath}.targets`); - return { - id: id(control.id, `${controlPath}.id`), - anchor, - axis, - radius, - minimum, - maximum, - initial, - targets, - }; - }); - uniqueIds(controls.map((control) => control.id), "$.controls"); + const controls = validateControls(input.controls, "$.controls", targetIds); const controlIds = new Set(controls.map((control) => control.id)); - const springs = array(input.springs, "$.springs").map((entry, springIndex) => { - const springPath = `$.springs[${springIndex}]`; - const spring = record(entry, springPath, ["controlId", "damping", "id", "stiffness"]); - const controlId = id(spring.controlId, `${springPath}.controlId`); - if (!controlIds.has(controlId)) fail("unknown-reference", `${springPath}.controlId`, controlId); - const stiffness = number(spring.stiffness, `${springPath}.stiffness`); - const damping = number(spring.damping, `${springPath}.damping`); - if (stiffness <= 0 || damping < 0) { - fail("invalid-spring", springPath, "expected stiffness > 0 and damping >= 0"); - } - return { id: id(spring.id, `${springPath}.id`), controlId, stiffness, damping }; - }); - uniqueIds(springs.map((spring) => spring.id), "$.springs"); - const shapeIds = new Set(shapes.map((shape) => shape.id)); - const animations = array(input.animations, "$.animations").map((entry, clipIndex) => { - const clipPath = `$.animations[${clipIndex}]`; - const clip = record(entry, clipPath, ["channels", "durationMs", "id", "loop"]); - const durationMs = number(clip.durationMs, `${clipPath}.durationMs`); - if (durationMs <= 0) fail("invalid-duration", `${clipPath}.durationMs`, "expected a positive duration"); - const channels = array(clip.channels, `${clipPath}.channels`).map((channel, channelIndex) => - validateAnimationChannel(channel, `${clipPath}.channels[${channelIndex}]`, { - controlIds, - jointIds, - shapeIds, - targetIds, - }, durationMs)); - if (channels.length === 0) fail("missing-channels", `${clipPath}.channels`, "expected at least one channel"); - const channelKeys = channels.map((channel) => `${channel.target}:${channel.targetId}`); - uniqueIds(channelKeys, `${clipPath}.channels`); - return { - id: id(clip.id, `${clipPath}.id`), - durationMs, - loop: boolean(clip.loop, `${clipPath}.loop`), - channels, - }; + const springs = validateSprings(input.springs, "$.springs", controlIds); + const shapeIds = new Set(render.shapes.map((shape) => shape.id)); + const animations = validateAnimations(input.animations, "$.animations", { + controlIds, + jointIds, + shapeIds, + targetIds, }); - uniqueIds(animations.map((clip) => clip.id), "$.animations"); const playback = input.playback === null ? null : validatePlayback( input.playback, "$.playback", - new Set(leaves.map((leaf) => leaf.id)), + new Set(render.leaves.map((leaf) => leaf.id)), shapeIds, ); if ((profile === "prepared-playback") !== (playback !== null)) { fail("profile-mismatch", "$.playback", "playback is required only by the prepared-playback profile"); } - const provenanceInput = record(input.provenance, "$.provenance", [ - "generator", - "generatorVersion", - "sources", - ]); - const sources = array(provenanceInput.sources, "$.provenance.sources").map((entry, sourceIndex) => { - const sourcePath = `$.provenance.sources[${sourceIndex}]`; - const source = record(entry, sourcePath, ["id", "kind", "license", "sha256", "uri"]); - const kind = string(source.kind, `${sourcePath}.kind`) as PolyMorphProvenanceSource["kind"]; - if (kind !== "authored" && kind !== "generated" && kind !== "open-data") { - fail("invalid-source-kind", `${sourcePath}.kind`, kind); - } - const uri = string(source.uri, `${sourcePath}.uri`); - if (uri.startsWith("/") || uri.startsWith("file:") || uri.includes("\\")) { - fail("invalid-source-uri", `${sourcePath}.uri`, "local filesystem paths are forbidden"); - } - const sha256 = source.sha256 === null ? null : string(source.sha256, `${sourcePath}.sha256`); - if (sha256 !== null && !SHA256.test(sha256)) { - fail("invalid-hash", `${sourcePath}.sha256`, "expected lowercase SHA-256"); - } - return { - id: id(source.id, `${sourcePath}.id`), - kind, - uri, - sha256, - license: string(source.license, `${sourcePath}.license`), - }; - }); - if (sources.length === 0) fail("missing-provenance", "$.provenance.sources", "expected at least one source"); - uniqueIds(sources.map((source) => source.id), "$.provenance.sources"); - const provenance = { - generator: id(provenanceInput.generator, "$.provenance.generator"), - generatorVersion: string(provenanceInput.generatorVersion, "$.provenance.generatorVersion"), - sources, - }; - if (!REVISION.test(provenance.generatorVersion)) { - fail("invalid-revision", "$.provenance.generatorVersion", "expected x.y.z"); - } - const required = requiredCapabilities(profile, { controls, springs, animations }); - for (const capability of required) { - if (!capabilities.includes(capability)) { - fail("missing-capability", "$.capabilities", `profile requires ${capability}`); - } - } - const jointCount = deformation.kind === "joint-skin" ? deformation.joints.length : 0; - const frameCount = playback?.frames.length ?? 0; - const actualBudgets = [ - ["maxVertices", topology.vertices.length, budgets.maxVertices], - ["maxPolygons", topology.polygons.length, budgets.maxPolygons], - ["maxLeaves", leaves.length, budgets.maxLeaves], - ["maxFrames", frameCount, budgets.maxFrames], - ["maxJoints", jointCount, budgets.maxJoints], - ] as const; - for (const [key, actual, maximum] of actualBudgets) { - if (actual > maximum) fail("budget-exceeded", `$.budgets.${key}`, `${actual} exceeds ${maximum}`); - } + const provenance = validateProvenance(input.provenance, "$.provenance"); + validateRequiredCapabilities(profile, capabilities, { controls, springs, animations }, "$.capabilities"); + validateBudgetLimits(budgets, { + vertices: topology.vertices.length, + polygons: topology.polygons.length, + leaves: render.leaves.length, + frames: playback?.frames.length ?? 0, + joints: deformation.kind === "joint-skin" ? deformation.joints.length : 0, + }, "$.budgets"); return { schema: POLY_MORPH_MODEL_SCHEMA, identity, @@ -870,16 +125,3 @@ export function validatePolyMorphModel(value: unknown): PolyMorphModel { provenance, }; } - -export function isPolyMorphId(value: string): boolean { - return ID.test(value); -} - -export function isPolyMorphResourcePath(value: string): boolean { - try { - normalizedPath(value, "$"); - return true; - } catch { - return false; - } -} diff --git a/packages/morph/src/contracts/validation/deformation.ts b/packages/morph/src/contracts/validation/deformation.ts new file mode 100644 index 00000000..5d292495 --- /dev/null +++ b/packages/morph/src/contracts/validation/deformation.ts @@ -0,0 +1,121 @@ +import type { + PolyMorphDeformation, + PolyMorphJoint, + PolyMorphTopology, +} from "../types.js"; +import { + array, + fail, + id, + indexInRange, + mat4, + number, + record, + string, + uniqueIds, + vec3, +} from "./primitives.js"; + +function validateJointHierarchy(joints: readonly PolyMorphJoint[], path: string): void { + const byId = new Map(joints.map((joint) => [joint.id, joint])); + const roots = joints.filter((joint) => joint.parentId === null); + if (roots.length !== 1) fail("invalid-hierarchy", path, "expected exactly one root joint"); + for (const joint of joints) { + if (joint.parentId !== null && !byId.has(joint.parentId)) { + fail("unknown-reference", path, `joint ${joint.id} references ${joint.parentId}`); + } + const seen = new Set(); + let ancestor: PolyMorphJoint | undefined = joint; + while (ancestor) { + if (seen.has(ancestor.id)) fail("invalid-hierarchy", path, `cycle at joint ${ancestor.id}`); + seen.add(ancestor.id); + ancestor = ancestor.parentId === null ? undefined : byId.get(ancestor.parentId); + } + } +} + +export function validateDeformation( + value: unknown, + path: string, + topology: PolyMorphTopology, +): PolyMorphDeformation { + if (!value || typeof value !== "object" || Array.isArray(value)) { + fail("invalid-type", path, "expected a deformation object"); + } + const kind = string((value as Record).kind, `${path}.kind`); + if (kind === "none") { + record(value, path, ["kind"]); + return { kind }; + } + if (kind === "morph-regions") { + const input = record(value, path, ["kind", "targets"]); + const targets = array(input.targets, `${path}.targets`).map((entry, targetIndex) => { + const targetPath = `${path}.targets[${targetIndex}]`; + const target = record(entry, targetPath, ["deltas", "id"]); + const deltas = array(target.deltas, `${targetPath}.deltas`).map((deltaEntry, deltaIndex) => { + const deltaPath = `${targetPath}.deltas[${deltaIndex}]`; + const delta = record(deltaEntry, deltaPath, ["normal", "position", "vertexIndex"]); + const position = delta.position === null ? null : vec3(delta.position, `${deltaPath}.position`); + const normal = delta.normal === null ? null : vec3(delta.normal, `${deltaPath}.normal`); + if (position === null && normal === null) { + fail("empty-delta", deltaPath, "expected a position or normal delta"); + } + return { + vertexIndex: indexInRange(delta.vertexIndex, `${deltaPath}.vertexIndex`, topology.vertices.length), + position, + normal, + }; + }); + if (deltas.length === 0) fail("missing-deltas", `${targetPath}.deltas`, "expected at least one delta"); + const indices = deltas.map((delta) => String(delta.vertexIndex)); + uniqueIds(indices, `${targetPath}.deltas`); + return { id: id(target.id, `${targetPath}.id`), deltas }; + }); + if (targets.length === 0) fail("missing-targets", `${path}.targets`, "expected at least one target"); + uniqueIds(targets.map((target) => target.id), `${path}.targets`); + return { kind, targets }; + } + if (kind === "joint-skin") { + const input = record(value, path, ["joints", "kind", "vertices"]); + const joints = array(input.joints, `${path}.joints`).map((entry, jointIndex) => { + const jointPath = `${path}.joints[${jointIndex}]`; + const joint = record(entry, jointPath, ["id", "inverseBindMatrix", "parentId", "restMatrix"]); + return { + id: id(joint.id, `${jointPath}.id`), + parentId: joint.parentId === null ? null : id(joint.parentId, `${jointPath}.parentId`), + restMatrix: mat4(joint.restMatrix, `${jointPath}.restMatrix`), + inverseBindMatrix: mat4(joint.inverseBindMatrix, `${jointPath}.inverseBindMatrix`), + }; + }); + if (joints.length === 0) fail("missing-joints", `${path}.joints`, "expected at least one joint"); + uniqueIds(joints.map((joint) => joint.id), `${path}.joints`); + validateJointHierarchy(joints, `${path}.joints`); + const jointIds = new Set(joints.map((joint) => joint.id)); + const vertices = array(input.vertices, `${path}.vertices`).map((entry, vertexIndex) => { + const vertexPath = `${path}.vertices[${vertexIndex}]`; + const vertex = record(entry, vertexPath, ["influences", "vertexIndex"]); + const resolvedIndex = indexInRange(vertex.vertexIndex, `${vertexPath}.vertexIndex`, topology.vertices.length); + const influences = array(vertex.influences, `${vertexPath}.influences`).map((entryInfluence, influenceIndex) => { + const influencePath = `${vertexPath}.influences[${influenceIndex}]`; + const influence = record(entryInfluence, influencePath, ["jointId", "weight"]); + const jointId = id(influence.jointId, `${influencePath}.jointId`); + if (!jointIds.has(jointId)) fail("unknown-reference", `${influencePath}.jointId`, jointId); + const weight = number(influence.weight, `${influencePath}.weight`); + if (weight <= 0 || weight > 1) fail("invalid-weight", `${influencePath}.weight`, "expected 0 < weight <= 1"); + return { jointId, weight }; + }); + if (influences.length === 0) fail("missing-influences", `${vertexPath}.influences`, "expected at least one influence"); + uniqueIds(influences.map((influence) => influence.jointId), `${vertexPath}.influences`); + const total = influences.reduce((sum, influence) => sum + influence.weight, 0); + if (Math.abs(total - 1) > 1e-6) fail("invalid-weight", `${vertexPath}.influences`, "weights must sum to 1"); + return { vertexIndex: resolvedIndex, influences }; + }); + if (vertices.length !== topology.vertices.length) { + fail("missing-skin-vertex", `${path}.vertices`, "every topology vertex must have one skin record"); + } + const skinIndices = vertices.map((vertex) => String(vertex.vertexIndex)); + uniqueIds(skinIndices, `${path}.vertices`); + return { kind, joints, vertices }; + } + fail("invalid-deformation", `${path}.kind`, `unknown deformation kind ${kind}`); +} diff --git a/packages/morph/src/contracts/validation/metadata.ts b/packages/morph/src/contracts/validation/metadata.ts new file mode 100644 index 00000000..a835bd33 --- /dev/null +++ b/packages/morph/src/contracts/validation/metadata.ts @@ -0,0 +1,186 @@ +import type { + PolyMorphBudgets, + PolyMorphCapability, + PolyMorphModelIdentity, + PolyMorphProfile, + PolyMorphProvenance, + PolyMorphProvenanceSource, +} from "../types.js"; +import { array, fail, id, integer, record, string, uniqueIds } from "./primitives.js"; + +const REVISION = /^\d+\.\d+\.\d+$/; +const SHA256 = /^[a-f0-9]{64}$/; + +const PROFILES = new Set([ + "joint-skin", + "morph-regions", + "prepared-playback", + "static-prepared", +]); + +const CAPABILITIES = new Set([ + "animation", + "joint-skinning", + "morph-targets", + "prepared-playback", + "retained-render", + "semantic-controls", + "sparse-updates", + "springs", +]); + +export function validateIdentity(value: unknown, path: string): PolyMorphModelIdentity { + const identityInput = record(value, path, ["id", "name", "revision"]); + const identity = { + id: id(identityInput.id, `${path}.id`), + name: string(identityInput.name, `${path}.name`), + revision: string(identityInput.revision, `${path}.revision`), + }; + if (!REVISION.test(identity.revision)) { + fail("invalid-revision", `${path}.revision`, "expected x.y.z"); + } + return identity; +} + +export function validateProfile(value: unknown, path: string): PolyMorphProfile { + const profile = string(value, path) as PolyMorphProfile; + if (!PROFILES.has(profile)) fail("invalid-profile", path, profile); + return profile; +} + +export function validateCapabilities(value: unknown, path: string): readonly PolyMorphCapability[] { + const capabilities = array(value, path).map((entry, index) => { + const capability = string(entry, `${path}[${index}]`) as PolyMorphCapability; + if (!CAPABILITIES.has(capability)) { + fail("invalid-capability", `${path}[${index}]`, capability); + } + return capability; + }); + uniqueIds(capabilities, path); + if (capabilities.some((capability, index) => index > 0 && capability <= capabilities[index - 1]!)) { + fail("non-canonical-order", path, "capabilities must be sorted"); + } + return capabilities; +} + +export function validateBudgets(value: unknown, path: string): PolyMorphBudgets { + const budgetInput = record(value, path, [ + "maxBytes", + "maxFrames", + "maxJoints", + "maxLeaves", + "maxPolygons", + "maxResources", + "maxVertices", + ]); + return { + maxVertices: integer(budgetInput.maxVertices, `${path}.maxVertices`), + maxPolygons: integer(budgetInput.maxPolygons, `${path}.maxPolygons`), + maxLeaves: integer(budgetInput.maxLeaves, `${path}.maxLeaves`), + maxFrames: integer(budgetInput.maxFrames, `${path}.maxFrames`), + maxJoints: integer(budgetInput.maxJoints, `${path}.maxJoints`), + maxResources: integer(budgetInput.maxResources, `${path}.maxResources`), + maxBytes: integer(budgetInput.maxBytes, `${path}.maxBytes`), + }; +} + +export function validateProvenance(value: unknown, path: string): PolyMorphProvenance { + const provenanceInput = record(value, path, [ + "generator", + "generatorVersion", + "sources", + ]); + const sources = array(provenanceInput.sources, `${path}.sources`).map((entry, sourceIndex) => { + const sourcePath = `${path}.sources[${sourceIndex}]`; + const source = record(entry, sourcePath, ["id", "kind", "license", "sha256", "uri"]); + const kind = string(source.kind, `${sourcePath}.kind`) as PolyMorphProvenanceSource["kind"]; + if (kind !== "authored" && kind !== "generated" && kind !== "open-data") { + fail("invalid-source-kind", `${sourcePath}.kind`, kind); + } + const uri = string(source.uri, `${sourcePath}.uri`); + if (uri.startsWith("/") || uri.startsWith("file:") || uri.includes("\\")) { + fail("invalid-source-uri", `${sourcePath}.uri`, "local filesystem paths are forbidden"); + } + const sha256 = source.sha256 === null ? null : string(source.sha256, `${sourcePath}.sha256`); + if (sha256 !== null && !SHA256.test(sha256)) { + fail("invalid-hash", `${sourcePath}.sha256`, "expected lowercase SHA-256"); + } + return { + id: id(source.id, `${sourcePath}.id`), + kind, + uri, + sha256, + license: string(source.license, `${sourcePath}.license`), + }; + }); + if (sources.length === 0) fail("missing-provenance", `${path}.sources`, "expected at least one source"); + uniqueIds(sources.map((source) => source.id), `${path}.sources`); + const provenance = { + generator: id(provenanceInput.generator, `${path}.generator`), + generatorVersion: string(provenanceInput.generatorVersion, `${path}.generatorVersion`), + sources, + }; + if (!REVISION.test(provenance.generatorVersion)) { + fail("invalid-revision", `${path}.generatorVersion`, "expected x.y.z"); + } + return provenance; +} + +function requiredCapabilities( + profile: PolyMorphProfile, + model: { + readonly controls: readonly unknown[]; + readonly springs: readonly unknown[]; + readonly animations: readonly unknown[]; + }, +): readonly PolyMorphCapability[] { + const required: PolyMorphCapability[] = ["retained-render"]; + if (profile === "morph-regions") required.push("morph-targets", "sparse-updates"); + if (profile === "joint-skin") required.push("joint-skinning", "sparse-updates"); + if (profile === "prepared-playback") required.push("prepared-playback", "sparse-updates"); + if (model.controls.length > 0) required.push("semantic-controls"); + if (model.springs.length > 0) required.push("springs"); + if (model.animations.length > 0) required.push("animation"); + return required; +} + +export function validateRequiredCapabilities( + profile: PolyMorphProfile, + capabilities: readonly PolyMorphCapability[], + model: { + readonly controls: readonly unknown[]; + readonly springs: readonly unknown[]; + readonly animations: readonly unknown[]; + }, + path: string, +): void { + const required = requiredCapabilities(profile, model); + for (const capability of required) { + if (!capabilities.includes(capability)) { + fail("missing-capability", path, `profile requires ${capability}`); + } + } +} + +export function validateBudgetLimits( + budgets: PolyMorphBudgets, + counts: { + readonly vertices: number; + readonly polygons: number; + readonly leaves: number; + readonly frames: number; + readonly joints: number; + }, + path: string, +): void { + const actualBudgets = [ + ["maxVertices", counts.vertices, budgets.maxVertices], + ["maxPolygons", counts.polygons, budgets.maxPolygons], + ["maxLeaves", counts.leaves, budgets.maxLeaves], + ["maxFrames", counts.frames, budgets.maxFrames], + ["maxJoints", counts.joints, budgets.maxJoints], + ] as const; + for (const [key, actual, maximum] of actualBudgets) { + if (actual > maximum) fail("budget-exceeded", `${path}.${key}`, `${actual} exceeds ${maximum}`); + } +} diff --git a/packages/morph/src/contracts/validation/motion.ts b/packages/morph/src/contracts/validation/motion.ts new file mode 100644 index 00000000..a22fdb1c --- /dev/null +++ b/packages/morph/src/contracts/validation/motion.ts @@ -0,0 +1,266 @@ +import type { + PolyMorphAnimationChannel, + PolyMorphAnimationClip, + PolyMorphAnimationTarget, + PolyMorphControl, + PolyMorphPlayback, + PolyMorphSpring, +} from "../types.js"; +import { + array, + boolean, + fail, + id, + integer, + mat4, + number, + record, + string, + uniqueIds, + vec3, +} from "./primitives.js"; + +const ANIMATION_TARGETS = new Set([ + "control-value", + "joint-rotation", + "joint-scale", + "joint-translation", + "morph-weight", + "shape-matrix", +]); + +export function validateControls( + value: unknown, + path: string, + targetIds: ReadonlySet, +): readonly PolyMorphControl[] { + const controls = array(value, path).map((entry, controlIndex): PolyMorphControl => { + const controlPath = `${path}[${controlIndex}]`; + const control = record(entry, controlPath, [ + "anchor", + "axis", + "id", + "initial", + "maximum", + "minimum", + "radius", + "targets", + ]); + const minimum = number(control.minimum, `${controlPath}.minimum`); + const maximum = number(control.maximum, `${controlPath}.maximum`); + const initial = number(control.initial, `${controlPath}.initial`); + if (minimum > maximum || initial < minimum || initial > maximum) { + fail("invalid-control-bounds", controlPath, "expected minimum <= initial <= maximum"); + } + const anchor = vec3(control.anchor, `${controlPath}.anchor`); + const axis = vec3(control.axis, `${controlPath}.axis`); + const axisLength = Math.hypot(...axis); + if (axisLength < 1e-9) fail("invalid-control-axis", `${controlPath}.axis`, "axis must be non-zero"); + const radius = number(control.radius, `${controlPath}.radius`); + if (radius <= 0) fail("invalid-control-radius", `${controlPath}.radius`, "radius must be positive"); + const targets = array(control.targets, `${controlPath}.targets`).map((entryTarget, targetIndex) => { + const targetPath = `${controlPath}.targets[${targetIndex}]`; + const target = record(entryTarget, targetPath, ["scale", "targetId"]); + const targetId = id(target.targetId, `${targetPath}.targetId`); + if (!targetIds.has(targetId)) fail("unknown-reference", `${targetPath}.targetId`, targetId); + return { targetId, scale: number(target.scale, `${targetPath}.scale`) }; + }); + uniqueIds(targets.map((target) => target.targetId), `${controlPath}.targets`); + return { + id: id(control.id, `${controlPath}.id`), + anchor, + axis, + radius, + minimum, + maximum, + initial, + targets, + }; + }); + uniqueIds(controls.map((control) => control.id), path); + return controls; +} + +export function validateSprings( + value: unknown, + path: string, + controlIds: ReadonlySet, +): readonly PolyMorphSpring[] { + const springs = array(value, path).map((entry, springIndex) => { + const springPath = `${path}[${springIndex}]`; + const spring = record(entry, springPath, ["controlId", "damping", "id", "stiffness"]); + const controlId = id(spring.controlId, `${springPath}.controlId`); + if (!controlIds.has(controlId)) fail("unknown-reference", `${springPath}.controlId`, controlId); + const stiffness = number(spring.stiffness, `${springPath}.stiffness`); + const damping = number(spring.damping, `${springPath}.damping`); + if (stiffness <= 0 || damping < 0) { + fail("invalid-spring", springPath, "expected stiffness > 0 and damping >= 0"); + } + return { id: id(spring.id, `${springPath}.id`), controlId, stiffness, damping }; + }); + uniqueIds(springs.map((spring) => spring.id), path); + return springs; +} + +function channelArity(target: PolyMorphAnimationTarget): number { + if (target === "control-value" || target === "morph-weight") return 1; + if (target === "joint-rotation") return 4; + if (target === "shape-matrix") return 16; + return 3; +} + +function validateAnimationChannel( + value: unknown, + path: string, + references: { + readonly controlIds: ReadonlySet; + readonly jointIds: ReadonlySet; + readonly shapeIds: ReadonlySet; + readonly targetIds: ReadonlySet; + }, + durationMs: number, +): PolyMorphAnimationChannel { + const input = record(value, path, ["interpolation", "target", "targetId", "timesMs", "values"]); + const target = string(input.target, `${path}.target`) as PolyMorphAnimationTarget; + if (!ANIMATION_TARGETS.has(target)) fail("invalid-animation-target", `${path}.target`, target); + const targetId = id(input.targetId, `${path}.targetId`); + const referenceSet = target === "control-value" + ? references.controlIds + : target === "morph-weight" + ? references.targetIds + : target === "shape-matrix" + ? references.shapeIds + : references.jointIds; + if (!referenceSet.has(targetId)) fail("unknown-reference", `${path}.targetId`, targetId); + const interpolation = string(input.interpolation, `${path}.interpolation`); + if (interpolation !== "linear" && interpolation !== "step") { + fail("invalid-interpolation", `${path}.interpolation`, interpolation); + } + if (target === "shape-matrix" && interpolation !== "step") { + fail( + "invalid-interpolation", + `${path}.interpolation`, + "shape matrices require step interpolation", + ); + } + const timesMs = array(input.timesMs, `${path}.timesMs`).map((entry, index) => + number(entry, `${path}.timesMs[${index}]`)); + const values = array(input.values, `${path}.values`).map((entry, valueIndex) => { + const parts = array(entry, `${path}.values[${valueIndex}]`); + const arity = channelArity(target); + if (parts.length !== arity) { + fail("invalid-animation-value", `${path}.values[${valueIndex}]`, `expected ${arity} components`); + } + const result = parts.map((part, partIndex) => + number(part, `${path}.values[${valueIndex}][${partIndex}]`)); + if (target === "joint-rotation" && Math.hypot(...result) <= 1e-12) { + fail( + "invalid-animation-value", + `${path}.values[${valueIndex}]`, + "quaternion must be non-zero", + ); + } + return result; + }); + if (timesMs.length === 0 || timesMs.length !== values.length) { + fail("invalid-animation-samples", path, "times and values must have the same non-zero length"); + } + if (timesMs[0] !== 0 || timesMs.some((time, index) => + time < 0 || time > durationMs || (index > 0 && time <= timesMs[index - 1]!))) { + fail("invalid-animation-time", `${path}.timesMs`, "times must start at zero and increase within the clip"); + } + return { + target, + targetId, + interpolation, + timesMs, + values, + }; +} + +export function validateAnimations( + value: unknown, + path: string, + references: { + readonly controlIds: ReadonlySet; + readonly jointIds: ReadonlySet; + readonly shapeIds: ReadonlySet; + readonly targetIds: ReadonlySet; + }, +): readonly PolyMorphAnimationClip[] { + const animations = array(value, path).map((entry, clipIndex) => { + const clipPath = `${path}[${clipIndex}]`; + const clip = record(entry, clipPath, ["channels", "durationMs", "id", "loop"]); + const durationMs = number(clip.durationMs, `${clipPath}.durationMs`); + if (durationMs <= 0) fail("invalid-duration", `${clipPath}.durationMs`, "expected a positive duration"); + const channels = array(clip.channels, `${clipPath}.channels`).map((channel, channelIndex) => + validateAnimationChannel(channel, `${clipPath}.channels[${channelIndex}]`, references, durationMs)); + if (channels.length === 0) fail("missing-channels", `${clipPath}.channels`, "expected at least one channel"); + const channelKeys = channels.map((channel) => `${channel.target}:${channel.targetId}`); + uniqueIds(channelKeys, `${clipPath}.channels`); + return { + id: id(clip.id, `${clipPath}.id`), + durationMs, + loop: boolean(clip.loop, `${clipPath}.loop`), + channels, + }; + }); + uniqueIds(animations.map((clip) => clip.id), path); + return animations; +} + +export function validatePlayback( + value: unknown, + path: string, + leafIds: ReadonlySet, + shapeIds: ReadonlySet, +): PolyMorphPlayback { + const input = record(value, path, ["durationMs", "frames", "loop"]); + const durationMs = number(input.durationMs, `${path}.durationMs`); + if (durationMs <= 0) fail("invalid-duration", `${path}.durationMs`, "expected a positive duration"); + const frames = array(input.frames, `${path}.frames`).map((entry, frameIndex) => { + const framePath = `${path}.frames[${frameIndex}]`; + const frame = record(entry, framePath, ["leaves", "modelMatrix", "shapes", "timeMs"]); + const timeMs = number(frame.timeMs, `${framePath}.timeMs`); + const shapes = array(frame.shapes, `${framePath}.shapes`).map((shapeEntry, shapeIndex) => { + const shapePath = `${framePath}.shapes[${shapeIndex}]`; + const shape = record(shapeEntry, shapePath, ["matrix", "shapeId"]); + const shapeId = id(shape.shapeId, `${shapePath}.shapeId`); + if (!shapeIds.has(shapeId)) fail("unknown-reference", `${shapePath}.shapeId`, shapeId); + return { shapeId, matrix: mat4(shape.matrix, `${shapePath}.matrix`) }; + }); + uniqueIds(shapes.map((shape) => shape.shapeId), `${framePath}.shapes`); + const leaves = array(frame.leaves, `${framePath}.leaves`).map((leafEntry, leafIndex) => { + const leafPath = `${framePath}.leaves[${leafIndex}]`; + const leaf = record(leafEntry, leafPath, ["atlasRow", "leafId", "matrix", "opacity", "visible"]); + const leafId = id(leaf.leafId, `${leafPath}.leafId`); + if (!leafIds.has(leafId)) fail("unknown-reference", `${leafPath}.leafId`, leafId); + const opacity = leaf.opacity === null ? null : number(leaf.opacity, `${leafPath}.opacity`); + if (opacity !== null && (opacity < 0 || opacity > 1)) { + fail("out-of-range", `${leafPath}.opacity`, "expected 0 <= opacity <= 1"); + } + return { + leafId, + matrix: leaf.matrix === null ? null : mat4(leaf.matrix, `${leafPath}.matrix`), + visible: leaf.visible === null ? null : boolean(leaf.visible, `${leafPath}.visible`), + opacity, + atlasRow: leaf.atlasRow === null ? null : integer(leaf.atlasRow, `${leafPath}.atlasRow`), + }; + }); + uniqueIds(leaves.map((leaf) => leaf.leafId), `${framePath}.leaves`); + return { + timeMs, + modelMatrix: frame.modelMatrix === null ? null : mat4(frame.modelMatrix, `${framePath}.modelMatrix`), + shapes, + leaves, + }; + }); + if (frames.length === 0) fail("missing-frames", `${path}.frames`, "expected at least one frame"); + if (frames[0]!.timeMs !== 0 || frames.some((frame, index) => + frame.timeMs < 0 + || frame.timeMs > durationMs + || (index > 0 && frame.timeMs <= frames[index - 1]!.timeMs))) { + fail("invalid-frame-time", `${path}.frames`, "frames must start at zero and increase within the timeline"); + } + return { durationMs, loop: boolean(input.loop, `${path}.loop`), frames }; +} diff --git a/packages/morph/src/contracts/validation/primitives.ts b/packages/morph/src/contracts/validation/primitives.ts new file mode 100644 index 00000000..0eeb5061 --- /dev/null +++ b/packages/morph/src/contracts/validation/primitives.ts @@ -0,0 +1,134 @@ +import type { PolyMorphMat4, PolyMorphVec3 } from "../types.js"; + +const ID = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/; +const PATH_SEGMENT = /^[a-z0-9][a-z0-9._-]*$/; + +export class PolyMorphContractError extends TypeError { + readonly code: string; + readonly path: string; + + constructor(code: string, path: string, message: string) { + super(`${path}: ${message}`); + this.name = "PolyMorphContractError"; + this.code = code; + this.path = path; + } +} + +export function fail(code: string, path: string, message: string): never { + throw new PolyMorphContractError(code, path, message); +} + +export function assertExactRecord( + value: unknown, + path: string, + keys: readonly string[], + onFail: (code: string, path: string, message: string) => never, +): Record { + if (!value || typeof value !== "object" || Array.isArray(value)) { + onFail("invalid-type", path, "expected an object"); + } + const actual = Object.keys(value).sort(); + const expected = [...keys].sort(); + if (actual.length !== expected.length || actual.some((key, index) => key !== expected[index])) { + onFail("invalid-keys", path, `expected exactly ${expected.join(", ")}`); + } + return value as Record; +} + +export function record( + value: unknown, + path: string, + keys: readonly string[], +): Record { + return assertExactRecord(value, path, keys, fail); +} + +export function array(value: unknown, path: string): readonly unknown[] { + if (!Array.isArray(value)) fail("invalid-type", path, "expected an array"); + return value; +} + +export function string(value: unknown, path: string): string { + if (typeof value !== "string" || value.length === 0) { + fail("invalid-string", path, "expected a non-empty string"); + } + return value; +} + +export function number(value: unknown, path: string): number { + if (typeof value !== "number" || !Number.isFinite(value)) { + fail("invalid-number", path, "expected a finite number"); + } + return value; +} + +export function integer(value: unknown, path: string, minimum = 0): number { + const result = number(value, path); + if (!Number.isSafeInteger(result) || result < minimum) { + fail("invalid-integer", path, `expected an integer >= ${minimum}`); + } + return result; +} + +export function boolean(value: unknown, path: string): boolean { + if (typeof value !== "boolean") fail("invalid-boolean", path, "expected a boolean"); + return value; +} + +export function id(value: unknown, path: string): string { + const result = string(value, path); + if (!ID.test(result)) fail("invalid-id", path, "expected a normalized kebab-case id"); + return result; +} + +export function uniqueIds(values: readonly string[], path: string): void { + const seen = new Set(); + for (const value of values) { + if (seen.has(value)) fail("duplicate-id", path, `duplicate id ${value}`); + seen.add(value); + } +} + +export function vec3(value: unknown, path: string): PolyMorphVec3 { + const values = array(value, path); + if (values.length !== 3) fail("invalid-vector", path, "expected three components"); + return values.map((part, index) => number(part, `${path}[${index}]`)) as unknown as PolyMorphVec3; +} + +export function mat4(value: unknown, path: string): PolyMorphMat4 { + const values = array(value, path); + if (values.length !== 16) fail("invalid-matrix", path, "expected sixteen components"); + return values.map((part, index) => number(part, `${path}[${index}]`)) as unknown as PolyMorphMat4; +} + +export function normalizedPath(value: unknown, path: string): string { + const result = string(value, path); + if (result.split("/").some((part) => !PATH_SEGMENT.test(part))) { + fail( + "invalid-path", + path, + "expected lowercase URL-safe package path segments", + ); + } + return result; +} + +export function indexInRange(value: unknown, path: string, length: number): number { + const result = integer(value, path); + if (result >= length) fail("out-of-range", path, `expected an index below ${length}`); + return result; +} + +export function isPolyMorphId(value: string): boolean { + return ID.test(value); +} + +export function isPolyMorphResourcePath(value: string): boolean { + try { + normalizedPath(value, "$"); + return true; + } catch { + return false; + } +} diff --git a/packages/morph/src/contracts/validation/render.ts b/packages/morph/src/contracts/validation/render.ts new file mode 100644 index 00000000..47a8a375 --- /dev/null +++ b/packages/morph/src/contracts/validation/render.ts @@ -0,0 +1,248 @@ +import type { + PolyMorphAtlasSlice, + PolyMorphMaterial, + PolyMorphRenderFallback, + PolyMorphRenderLeaf, + PolyMorphRenderPlan, + PolyMorphRenderStrategy, + PolyMorphTopology, +} from "../types.js"; +import { + array, + fail, + id, + indexInRange, + integer, + mat4, + normalizedPath, + number, + record, + string, + uniqueIds, + vec3, +} from "./primitives.js"; + +const STRATEGIES = new Set([ + "atlas-slice", + "direct-image", + "solid-quad", + "solid-triangle", +]); + +export function validateTopology(value: unknown, path: string): PolyMorphTopology { + const input = record(value, path, ["normals", "polygons", "vertices"]); + const vertices = array(input.vertices, `${path}.vertices`).map((entry, index) => + vec3(entry, `${path}.vertices[${index}]`)); + const normals = array(input.normals, `${path}.normals`).map((entry, index) => + vec3(entry, `${path}.normals[${index}]`)); + if (vertices.length === 0) fail("missing-topology", `${path}.vertices`, "expected at least one vertex"); + if (normals.length === 0) fail("missing-topology", `${path}.normals`, "expected at least one normal"); + const polygons = array(input.polygons, `${path}.polygons`).map((entry, index) => { + const itemPath = `${path}.polygons[${index}]`; + const polygon = record(entry, itemPath, ["id", "normalIndices", "vertexIndices"]); + const vertexIndices = array(polygon.vertexIndices, `${itemPath}.vertexIndices`).map((part, partIndex) => + indexInRange(part, `${itemPath}.vertexIndices[${partIndex}]`, vertices.length)); + const normalIndices = array(polygon.normalIndices, `${itemPath}.normalIndices`).map((part, partIndex) => + indexInRange(part, `${itemPath}.normalIndices[${partIndex}]`, normals.length)); + if (vertexIndices.length < 3) fail("invalid-polygon", itemPath, "expected at least three vertices"); + if (normalIndices.length !== vertexIndices.length) { + fail("invalid-polygon", itemPath, "normal and vertex index counts must match"); + } + if (new Set(vertexIndices).size !== vertexIndices.length) { + fail("invalid-polygon", itemPath, "vertex indices must be unique"); + } + return { + id: id(polygon.id, `${itemPath}.id`), + vertexIndices, + normalIndices, + }; + }); + if (polygons.length === 0) fail("missing-topology", `${path}.polygons`, "expected at least one polygon"); + uniqueIds(polygons.map((polygon) => polygon.id), `${path}.polygons`); + return { vertices, normals, polygons }; +} + +export function validateMaterials(value: unknown, path: string): readonly PolyMorphMaterial[] { + const materials = array(value, path).map((entry, materialIndex) => { + const materialPath = `${path}[${materialIndex}]`; + const material = record(entry, materialPath, ["color", "id"]); + const colorParts = array(material.color, `${materialPath}.color`); + if (colorParts.length !== 4) fail("invalid-color", `${materialPath}.color`, "expected four components"); + const color = colorParts.map((part, partIndex) => { + const component = number(part, `${materialPath}.color[${partIndex}]`); + if (component < 0 || component > 1) { + fail("out-of-range", `${materialPath}.color[${partIndex}]`, "expected 0 <= component <= 1"); + } + return component; + }) as [number, number, number, number]; + return { id: id(material.id, `${materialPath}.id`), color }; + }); + if (materials.length === 0) fail("missing-materials", path, "expected at least one material"); + uniqueIds(materials.map((material) => material.id), path); + return materials; +} + +function validateAtlasSlice( + value: unknown, + path: string, +): PolyMorphAtlasSlice { + const input = record(value, path, [ + "height", + "pageHeight", + "pageWidth", + "resourcePath", + "width", + "x", + "y", + ]); + const atlas = { + resourcePath: normalizedPath(input.resourcePath, `${path}.resourcePath`), + x: integer(input.x, `${path}.x`), + y: integer(input.y, `${path}.y`), + width: integer(input.width, `${path}.width`, 1), + height: integer(input.height, `${path}.height`, 1), + pageWidth: integer(input.pageWidth, `${path}.pageWidth`, 1), + pageHeight: integer(input.pageHeight, `${path}.pageHeight`, 1), + }; + if (atlas.x + atlas.width > atlas.pageWidth || atlas.y + atlas.height > atlas.pageHeight) { + fail("out-of-range", path, "slice must fit inside its page"); + } + return atlas; +} + +function validateRenderFallback( + value: unknown, + path: string, +): PolyMorphRenderFallback { + const input = record(value, path, [ + "atlas", + "height", + "matrixFromLeaf", + "width", + ]); + const width = integer(input.width, `${path}.width`, 1); + const height = integer(input.height, `${path}.height`, 1); + const atlas = validateAtlasSlice(input.atlas, `${path}.atlas`); + if (atlas.width !== width || atlas.height !== height) { + fail( + "invalid-size", + path, + "fallback dimensions must match its per-polygon atlas slice", + ); + } + return { + width, + height, + matrixFromLeaf: mat4(input.matrixFromLeaf, `${path}.matrixFromLeaf`), + atlas, + }; +} + +function validateRenderLeaf( + value: unknown, + path: string, + references: { + readonly polygonIds: ReadonlySet; + readonly shapeIds: ReadonlySet; + readonly materialIds: ReadonlySet; + }, +): PolyMorphRenderLeaf { + const input = record(value, path, [ + "atlas", + "fallback", + "height", + "id", + "materialId", + "matrix", + "polygonId", + "shapeId", + "strategy", + "width", + ]); + const strategy = string(input.strategy, `${path}.strategy`) as PolyMorphRenderStrategy; + if (!STRATEGIES.has(strategy)) fail("invalid-strategy", `${path}.strategy`, "unknown render strategy"); + const polygonId = id(input.polygonId, `${path}.polygonId`); + const shapeId = id(input.shapeId, `${path}.shapeId`); + const materialId = id(input.materialId, `${path}.materialId`); + if (!references.polygonIds.has(polygonId)) fail("unknown-reference", `${path}.polygonId`, polygonId); + if (!references.shapeIds.has(shapeId)) fail("unknown-reference", `${path}.shapeId`, shapeId); + if (!references.materialIds.has(materialId)) fail("unknown-reference", `${path}.materialId`, materialId); + const width = number(input.width, `${path}.width`); + const height = number(input.height, `${path}.height`); + if (width <= 0 || height <= 0) fail("invalid-size", path, "leaf dimensions must be positive"); + const needsAtlas = strategy === "atlas-slice" || strategy === "direct-image"; + const atlas = input.atlas === null + ? null + : validateAtlasSlice(input.atlas, `${path}.atlas`); + if (needsAtlas !== (atlas !== null)) { + fail("invalid-strategy", `${path}.atlas`, needsAtlas + ? "image strategies require an atlas/source slice" + : "solid strategies cannot declare an atlas/source slice"); + } + const fallback = input.fallback === null + ? null + : validateRenderFallback(input.fallback, `${path}.fallback`); + if (fallback !== null && strategy !== "solid-triangle") { + fail( + "invalid-strategy", + `${path}.fallback`, + "only solid-triangle leaves may declare a prepared fallback", + ); + } + return { + id: id(input.id, `${path}.id`), + polygonId, + shapeId, + materialId, + strategy, + width, + height, + matrix: mat4(input.matrix, `${path}.matrix`), + atlas, + fallback, + }; +} + +export function validateRenderPlan( + value: unknown, + path: string, + references: { + readonly topology: PolyMorphTopology; + readonly materials: readonly PolyMorphMaterial[]; + }, +): PolyMorphRenderPlan { + const renderInput = record(value, path, [ + "leaves", + "modelMatrix", + "shapes", + ]); + const shapes = array(renderInput.shapes, `${path}.shapes`).map((entry, shapeIndex) => { + const shapePath = `${path}.shapes[${shapeIndex}]`; + const shape = record(entry, shapePath, ["id", "matrix"]); + return { + id: id(shape.id, `${shapePath}.id`), + matrix: mat4(shape.matrix, `${shapePath}.matrix`), + }; + }); + if (shapes.length === 0) fail("missing-shapes", `${path}.shapes`, "expected at least one shape"); + uniqueIds(shapes.map((shape) => shape.id), `${path}.shapes`); + const polygonIds = new Set(references.topology.polygons.map((polygon) => polygon.id)); + const shapeIds = new Set(shapes.map((shape) => shape.id)); + const materialIds = new Set(references.materials.map((material) => material.id)); + const leaves = array(renderInput.leaves, `${path}.leaves`).map((entry, leafIndex) => + validateRenderLeaf(entry, `${path}.leaves[${leafIndex}]`, { + polygonIds, + shapeIds, + materialIds, + })); + uniqueIds(leaves.map((leaf) => leaf.id), `${path}.leaves`); + uniqueIds(leaves.map((leaf) => leaf.polygonId), `${path}.leaves[*].polygonId`); + if (leaves.length !== references.topology.polygons.length) { + fail("unstable-topology", `${path}.leaves`, "every polygon must bind exactly one retained leaf"); + } + return { + modelMatrix: mat4(renderInput.modelMatrix, `${path}.modelMatrix`), + shapes, + leaves, + }; +} diff --git a/packages/polycss/src/api/controls/gizmo/declarativeDrag.ts b/packages/polycss/src/api/controls/gizmo/declarativeDrag.ts new file mode 100644 index 00000000..1340c5ff --- /dev/null +++ b/packages/polycss/src/api/controls/gizmo/declarativeDrag.ts @@ -0,0 +1,138 @@ +import { + eulerXYZFromQuat, + quatFromAxisAngle, + quatFromEulerXYZ, + quatMultiply, +} from "@layoutit/polycss-core"; +import type { Vec3 } from "@layoutit/polycss-core"; +import { startAxisDrag, startPlaneDrag, startRingDrag } from "./pointerDrag"; +import type { + DeclarativeGizmoDragState, + DeclarativeGizmoTarget, + GizmoArrowSpec, + GizmoPlaneSpec, + GizmoRingSpec, +} from "./types"; + +export function startDeclarativeArrowDrag< + TTarget extends DeclarativeGizmoTarget, +>( + spec: GizmoArrowSpec, + wrapper: HTMLElement, + startClientX: number, + startClientY: number, + getState: () => DeclarativeGizmoDragState, +): (() => void) | null { + const initial = getState(); + const target = initial.target; + if (!target || !initial.enabled) return null; + const startPos = (target.getPosition() ?? [0, 0, 0]) as Vec3; + return startAxisDrag({ + cssAxis: spec.cssAxis, + sign: spec.sign, + shaftLengthCss: initial.shaftLengthCss, + wrapper, + startClientX, + startClientY, + translationSnap: initial.translationSnap, + onAxisDelta: (t, axisVec) => { + const next: Vec3 = [ + startPos[0] + t * axisVec[0], + startPos[1] + t * axisVec[1], + startPos[2] + t * axisVec[2], + ]; + const live = getState(); + live.onObjectChange?.({ object: target, position: next }); + live.onChange?.(); + }, + onMouseDown: () => getState().onMouseDown?.(), + onMouseUp: () => getState().onMouseUp?.(), + onDraggingChanged: (d) => { + const live = getState(); + live.onDraggingKeyChange?.(d ? spec.key : null); + live.onDraggingChanged?.(d); + }, + }); +} + +export function startDeclarativePlaneDrag< + TTarget extends DeclarativeGizmoTarget, +>( + spec: GizmoPlaneSpec, + wrapper: HTMLElement, + startClientX: number, + startClientY: number, + getState: () => DeclarativeGizmoDragState, +): (() => void) | null { + const initial = getState(); + const target = initial.target; + if (!target || !initial.enabled) return null; + const startPos = (target.getPosition() ?? [0, 0, 0]) as Vec3; + return startPlaneDrag({ + axisA: spec.axisA, + axisB: spec.axisB, + probeDistanceCss: initial.shaftLengthCss, + wrapper, + startClientX, + startClientY, + translationSnap: initial.translationSnap, + onPlaneDelta: (tA, tB, axisAVec, axisBVec) => { + const next: Vec3 = [ + startPos[0] + tA * axisAVec[0] + tB * axisBVec[0], + startPos[1] + tA * axisAVec[1] + tB * axisBVec[1], + startPos[2] + tA * axisAVec[2] + tB * axisBVec[2], + ]; + const live = getState(); + live.onObjectChange?.({ object: target, position: next }); + live.onChange?.(); + }, + onMouseDown: () => getState().onMouseDown?.(), + onMouseUp: () => getState().onMouseUp?.(), + onDraggingChanged: (d) => { + const live = getState(); + live.onDraggingKeyChange?.(d ? spec.key : null); + live.onDraggingChanged?.(d); + }, + }); +} + +export function startDeclarativeRingDrag< + TTarget extends DeclarativeGizmoTarget, +>( + spec: GizmoRingSpec, + wrapper: HTMLElement, + startClientX: number, + startClientY: number, + getState: () => DeclarativeGizmoDragState, +): (() => void) | null { + const initial = getState(); + const target = initial.target; + 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; + return startRingDrag({ + wrapper, + startClientX, + startClientY, + rotationSnap: initial.rotationSnap, + onAngleDelta: (degrees) => { + const qDelta = quatFromAxisAngle(axisVec, (degrees * Math.PI) / 180); + const nextRotation = eulerXYZFromQuat(quatMultiply(qDelta, qStart)); + const live = getState(); + live.onObjectChange?.({ object: target, rotation: nextRotation }); + live.onChange?.(); + }, + onMouseDown: () => getState().onMouseDown?.(), + onMouseUp: () => getState().onMouseUp?.(), + onDraggingChanged: (d) => { + const live = getState(); + live.onDraggingKeyChange?.(d ? spec.key : null); + live.onDraggingChanged?.(d); + }, + onComplete: () => { + target.rebakeAtlas(); + }, + }); +} diff --git a/packages/polycss/src/api/controls/gizmo/geometry.ts b/packages/polycss/src/api/controls/gizmo/geometry.ts new file mode 100644 index 00000000..980f3dcb --- /dev/null +++ b/packages/polycss/src/api/controls/gizmo/geometry.ts @@ -0,0 +1,280 @@ +import { + ALPHA_DRAGGING, + ALPHA_HOVER, + ALPHA_IDLE, + ARROW_SPECS, + HEAD_HALF_THICKNESS_RATIO, + HEAD_LENGTH_RATIO, + PLANE_HALF_SIZE_RATIO, + PLANE_OFFSET_RATIO, + PLANE_SPECS, + RING_QUAD_OUTER_RATIO, + RING_RADIUS_RATIO, + RING_SPECS, + SCENE_TILE_SIZE, + SHAFT_HALF_THICKNESS_RATIO, + WORLD_AXIS_FOR_CSS, + arrowPolygons, + gizmoCenterForMesh, + gizmoLengthForMesh, + isAxisBackFacing, + planePolygons, + ringQuadPolygons, + userAxisLetterOf, + withAlpha, +} from "@layoutit/polycss-core"; +import type { Polygon, Vec3 } from "@layoutit/polycss-core"; +import type { + GizmoArrowSpec, + GizmoMode, + GizmoPlaneSpec, + GizmoRingSpec, + GizmoVisibility, + TransformGizmoCache, + TransformGizmoEntries, +} from "./types"; + +export function gizmoAlphaForKey( + key: string, + hoveredKey: string | null, + draggingKey: string | null, +): number { + if (draggingKey === key) return ALPHA_DRAGGING; + if (hoveredKey === key) return ALPHA_HOVER; + return ALPHA_IDLE; +} + +export function buildArrowGizmoPolygons( + spec: { cssAxis: 0 | 1 | 2; sign: 1 | -1; color: string }, + lengthWorld: number, + alpha: number, + rotX: number, + rotY: number, +): Polygon[] { + const backFacing = isAxisBackFacing(spec.cssAxis, spec.sign, rotX, rotY); + return arrowPolygons({ + axis: WORLD_AXIS_FOR_CSS[spec.cssAxis], + sign: spec.sign, + shaftLength: lengthWorld, + shaftHalfThickness: lengthWorld * SHAFT_HALF_THICKNESS_RATIO, + headLength: lengthWorld * HEAD_LENGTH_RATIO, + headHalfThickness: lengthWorld * HEAD_HALF_THICKNESS_RATIO, + color: withAlpha(spec.color, alpha), + shaft: !backFacing, + }); +} + +export function buildPlaneGizmoPolygons( + spec: { perpAxis: 0 | 1 | 2; color: string }, + lengthWorld: number, + alpha: number, + rotX: number, + rotY: number, +): Polygon[] { + const worldPerp = WORLD_AXIS_FOR_CSS[spec.perpAxis]; + const worldA = ((worldPerp + 1) % 3) as 0 | 1 | 2; + const worldB = ((worldPerp + 2) % 3) as 0 | 1 | 2; + const cssAForOffset = WORLD_AXIS_FOR_CSS[worldA]; + const cssBForOffset = WORLD_AXIS_FOR_CSS[worldB]; + const signA = isAxisBackFacing(cssAForOffset, 1, rotX, rotY) ? -1 : 1; + const signB = isAxisBackFacing(cssBForOffset, 1, rotX, rotY) ? -1 : 1; + const mag = lengthWorld * PLANE_OFFSET_RATIO; + return planePolygons({ + axis: worldPerp, + size: lengthWorld * PLANE_HALF_SIZE_RATIO, + offset: [signA * mag, signB * mag], + color: withAlpha(spec.color, alpha), + }); +} + +export function buildRingGizmoPolygons( + spec: { cssAxis: 0 | 1 | 2; color: string }, + shaftLengthCss: number, + alpha: number, +): Polygon[] { + const radiusWorld = (shaftLengthCss * RING_RADIUS_RATIO) / SCENE_TILE_SIZE; + const outerWorld = radiusWorld * RING_QUAD_OUTER_RATIO; + return ringQuadPolygons({ + axis: WORLD_AXIS_FOR_CSS[spec.cssAxis], + outerRadius: outerWorld, + color: withAlpha(spec.color, alpha), + }); +} + +export function isArrowSpecVisible( + spec: GizmoArrowSpec, + vis: GizmoVisibility, +): boolean { + const show = { + x: vis.showX !== false, + y: vis.showY !== false, + z: vis.showZ !== false, + }; + return show[userAxisLetterOf(spec.key)]; +} + +export function isPlaneSpecVisible( + spec: GizmoPlaneSpec, + vis: GizmoVisibility, +): boolean { + const show = { + x: vis.showX !== false, + y: vis.showY !== false, + z: vis.showZ !== false, + }; + const axes = ["x", "y", "z"] as const; + return show[axes[spec.axisA]] && show[axes[spec.axisB]]; +} + +export function isRingSpecVisible( + spec: GizmoRingSpec, + vis: GizmoVisibility, +): boolean { + const show = { + x: vis.showX !== false, + y: vis.showY !== false, + z: vis.showZ !== false, + }; + return show[spec.key as "x" | "y" | "z"]; +} + +export interface BuildTransformGizmoEntriesOptions extends GizmoVisibility { + mode: GizmoMode; + polygons: Polygon[]; + size: number; + rotX: number; + rotY: number; + hoveredKey: string | null; + draggingKey: string | null; + /** Optional per-instance handle cache so unchanged handles keep stable Polygon[] identity across camera ticks. */ + cache?: TransformGizmoCache; +} + +function cachedHandlePolygons( + cache: TransformGizmoCache | undefined, + cacheKey: string, + sig: string, + build: () => Polygon[], +): Polygon[] { + const hit = cache?.get(cacheKey); + if (hit && hit.sig === sig) return hit.polygons; + const polygons = build(); + cache?.set(cacheKey, { sig, polygons }); + return polygons; +} + +export function buildTransformGizmoEntries( + opts: BuildTransformGizmoEntriesOptions, +): TransformGizmoEntries { + const shaftLengthCss = gizmoLengthForMesh(opts.polygons) * opts.size; + const lengthWorld = shaftLengthCss / SCENE_TILE_SIZE; + + if (opts.mode === "translate") { + const arrows = ARROW_SPECS.filter((spec) => + isArrowSpecVisible(spec, opts), + ).map((spec) => { + const alpha = gizmoAlphaForKey( + spec.key, + opts.hoveredKey, + opts.draggingKey, + ); + const backFacing = isAxisBackFacing( + spec.cssAxis, + spec.sign, + opts.rotX, + opts.rotY, + ); + const sig = `${lengthWorld}|${alpha}|${backFacing ? 1 : 0}`; + return { + spec, + polygons: cachedHandlePolygons(opts.cache, `arrow:${spec.key}`, sig, () => + buildArrowGizmoPolygons( + spec, + lengthWorld, + alpha, + opts.rotX, + opts.rotY, + ), + ), + }; + }); + const planes = PLANE_SPECS.filter((spec) => + isPlaneSpecVisible(spec, opts), + ).map((spec) => { + const alpha = gizmoAlphaForKey( + spec.key, + opts.hoveredKey, + opts.draggingKey, + ); + const worldPerp = WORLD_AXIS_FOR_CSS[spec.perpAxis]; + const worldA = ((worldPerp + 1) % 3) as 0 | 1 | 2; + const worldB = ((worldPerp + 2) % 3) as 0 | 1 | 2; + const signA = isAxisBackFacing( + WORLD_AXIS_FOR_CSS[worldA], + 1, + opts.rotX, + opts.rotY, + ) + ? -1 + : 1; + const signB = isAxisBackFacing( + WORLD_AXIS_FOR_CSS[worldB], + 1, + opts.rotX, + opts.rotY, + ) + ? -1 + : 1; + const sig = `${lengthWorld}|${alpha}|${signA}|${signB}`; + return { + spec, + polygons: cachedHandlePolygons(opts.cache, `plane:${spec.key}`, sig, () => + buildPlaneGizmoPolygons( + spec, + lengthWorld, + alpha, + opts.rotX, + opts.rotY, + ), + ), + }; + }); + return { shaftLengthCss, arrows, planes, rings: [] }; + } + + const rings = RING_SPECS.filter((spec) => isRingSpecVisible(spec, opts)).map( + (spec) => { + const alpha = gizmoAlphaForKey( + spec.key, + opts.hoveredKey, + opts.draggingKey, + ); + const sig = `${shaftLengthCss}|${alpha}`; + return { + spec, + polygons: cachedHandlePolygons(opts.cache, `ring:${spec.key}`, sig, () => + buildRingGizmoPolygons(spec, shaftLengthCss, alpha), + ), + }; + }, + ); + return { shaftLengthCss, arrows: [], planes: [], rings }; +} + +/** + * Compute the gizmo wrapper's CSS-pixel `translate3d` position from a target's + * world-unit `position` and mesh polygons (applying the world→CSS axis swap + + * `SCENE_TILE_SIZE` scale + mesh bbox center). + */ +export function computeGizmoWrapperPositionCss( + position: Vec3 | undefined, + polygons: Polygon[], +): Vec3 { + const pos = position ?? ([0, 0, 0] as Vec3); + const bboxCenter = gizmoCenterForMesh(polygons); + return [ + pos[1] * SCENE_TILE_SIZE + bboxCenter[0], + pos[0] * SCENE_TILE_SIZE + bboxCenter[1], + pos[2] * SCENE_TILE_SIZE + bboxCenter[2], + ]; +} diff --git a/packages/polycss/src/api/controls/gizmo/pointerDrag.ts b/packages/polycss/src/api/controls/gizmo/pointerDrag.ts new file mode 100644 index 00000000..7b1a7f43 --- /dev/null +++ b/packages/polycss/src/api/controls/gizmo/pointerDrag.ts @@ -0,0 +1,251 @@ +import { + SCREEN_AXIS_DEAD_ZONE_SQ, + screenPlaneDet, + snap, + solveAxisDragDelta, + solvePlaneDragDeltas, + unwrapAngleDelta, +} from "@layoutit/polycss-core"; +import type { Vec3 } from "@layoutit/polycss-core"; + +/** + * Swallow the synthesized `click` that immediately follows a gizmo drag's + * `pointerup`, so releasing a drag over a selected mesh does not toggle + * selection off in `` / `createSelect`. + */ +export 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); +} + +function probeScreenAxis( + wrapper: HTMLElement, + axisVec: Vec3, + probeDistanceCss: number, +): { x: number; y: number } { + const probe = wrapper.ownerDocument!.createElement("div"); + probe.style.position = "absolute"; + probe.style.left = "0"; + probe.style.top = "0"; + probe.style.width = "0"; + probe.style.height = "0"; + probe.style.transform = `translate3d(${axisVec[0] * probeDistanceCss}px, ${axisVec[1] * probeDistanceCss}px, ${axisVec[2] * probeDistanceCss}px)`; + wrapper.appendChild(probe); + const wRect = wrapper.getBoundingClientRect(); + const pRect = probe.getBoundingClientRect(); + wrapper.removeChild(probe); + return { + x: (pRect.left - wRect.left) / probeDistanceCss, + y: (pRect.top - wRect.top) / probeDistanceCss, + }; +} + +interface PointerDragSessionHooks { + onMove: (ev: PointerEvent) => void; + onMouseDown?: () => void; + onMouseUp?: () => void; + onDraggingChanged?: (dragging: boolean) => void; + onComplete?: () => void; +} + +function bindPointerDragSession(hooks: PointerDragSessionHooks): () => void { + hooks.onMouseDown?.(); + hooks.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; + hooks.onMove(ev); + }; + const handleUp = (): void => { + if (!active) return; + active = false; + removeListeners(); + swallowNextClick(); + hooks.onMouseUp?.(); + hooks.onDraggingChanged?.(false); + hooks.onComplete?.(); + }; + const cancel = (): void => { + if (!active) return; + active = false; + removeListeners(); + hooks.onDraggingChanged?.(false); + }; + window.addEventListener("pointermove", handleMove); + window.addEventListener("pointerup", handleUp); + window.addEventListener("pointercancel", handleUp); + return cancel; +} + +export interface AxisDragParams { + cssAxis: 0 | 1 | 2; + sign: 1 | -1; + shaftLengthCss: number; + wrapper: HTMLElement; + startClientX: number; + startClientY: number; + translationSnap: number | null; + onAxisDelta(t: number, axisVec: Vec3): void; + onMouseDown?: () => void; + onMouseUp?: () => void; + onDraggingChanged?: (dragging: boolean) => void; +} + +/** + * Project pointer screen-px deltas onto the screen projection of an axis + * vector via a temporary probe element. + */ +export function startAxisDrag(opts: AxisDragParams): (() => void) | null { + const { + cssAxis, + sign, + shaftLengthCss, + wrapper, + startClientX, + startClientY, + translationSnap, + onAxisDelta, + onMouseDown, + onMouseUp, + onDraggingChanged, + } = opts; + + const axisVec: Vec3 = [0, 0, 0]; + 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 null; + + return bindPointerDragSession({ + onMove: (ev) => { + const dx = ev.clientX - startClientX; + const dy = ev.clientY - startClientY; + const t = snap( + solveAxisDragDelta(dx, dy, screen.x, screen.y), + translationSnap, + ); + onAxisDelta(t, axisVec); + }, + onMouseDown, + onMouseUp, + onDraggingChanged, + }); +} + +export interface PlaneDragParams { + axisA: 0 | 1 | 2; + axisB: 0 | 1 | 2; + probeDistanceCss: number; + wrapper: HTMLElement; + startClientX: number; + startClientY: number; + translationSnap: number | null; + onPlaneDelta(tA: number, tB: number, axisAVec: Vec3, axisBVec: Vec3): void; + onMouseDown?: () => void; + onMouseUp?: () => void; + onDraggingChanged?: (dragging: boolean) => void; +} + +/** + * 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): (() => void) | null { + const { + axisA, + axisB, + probeDistanceCss, + wrapper, + startClientX, + startClientY, + translationSnap, + onPlaneDelta, + onMouseDown, + onMouseUp, + onDraggingChanged, + } = opts; + + const axisAVec: Vec3 = [0, 0, 0]; + axisAVec[axisA] = 1; + const axisBVec: Vec3 = [0, 0, 0]; + axisBVec[axisB] = 1; + 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 null; + + return bindPointerDragSession({ + onMove: (ev) => { + const dx = ev.clientX - startClientX; + const dy = ev.clientY - startClientY; + const solved = solvePlaneDragDeltas(dx, dy, pA, pB, det); + const tA = snap(solved.tA, translationSnap); + const tB = snap(solved.tB, translationSnap); + onPlaneDelta(tA, tB, axisAVec, axisBVec); + }, + onMouseDown, + onMouseUp, + onDraggingChanged, + }); +} + +export interface RingDragParams { + wrapper: HTMLElement; + startClientX: number; + startClientY: number; + rotationSnap: number | null; + onAngleDelta(degrees: number): void; + onMouseDown?: () => void; + onMouseUp?: () => void; + onDraggingChanged?: (dragging: boolean) => void; + onComplete?: () => void; +} + +/** + * Track pointer angle around the gizmo center, accumulate unwrapped radians, + * and report degrees of rotation. + */ +export function startRingDrag(opts: RingDragParams): () => void { + const { + wrapper, + startClientX, + startClientY, + rotationSnap, + onAngleDelta, + onMouseDown, + onMouseUp, + onDraggingChanged, + onComplete, + } = opts; + + const wRect = wrapper.getBoundingClientRect(); + const centerX = wRect.left; + const centerY = wRect.top; + + let lastAngle = Math.atan2(startClientY - centerY, startClientX - centerX); + let cumulative = 0; + + return bindPointerDragSession({ + onMove: (ev) => { + const a = Math.atan2(ev.clientY - centerY, ev.clientX - centerX); + cumulative += unwrapAngleDelta(a, lastAngle); + lastAngle = a; + const degrees = snap((cumulative * 180) / Math.PI, rotationSnap); + onAngleDelta(degrees); + }, + onMouseDown, + onMouseUp, + onDraggingChanged, + onComplete, + }); +} diff --git a/packages/polycss/src/api/controls/gizmo/types.ts b/packages/polycss/src/api/controls/gizmo/types.ts new file mode 100644 index 00000000..500d3dac --- /dev/null +++ b/packages/polycss/src/api/controls/gizmo/types.ts @@ -0,0 +1,84 @@ +import { + ARROW_SPECS, + PLANE_SPECS, + RING_HALF_THICKNESS_RATIO, + RING_QUAD_OUTER_RATIO, + RING_SPECS, +} from "@layoutit/polycss-core"; +import type { Polygon, Vec3 } from "@layoutit/polycss-core"; + +export type GizmoMode = "translate" | "rotate"; + +export type GizmoArrowSpec = (typeof ARROW_SPECS)[number]; +export type GizmoPlaneSpec = (typeof PLANE_SPECS)[number]; +export type GizmoRingSpec = (typeof RING_SPECS)[number]; + +export interface GizmoVisibility { + showX?: boolean; + showY?: boolean; + showZ?: boolean; +} + +export interface GizmoPolygonEntry { + spec: TSpec; + polygons: Polygon[]; +} + +export interface TransformGizmoEntries { + shaftLengthCss: number; + arrows: GizmoPolygonEntry[]; + planes: GizmoPolygonEntry[]; + rings: GizmoPolygonEntry[]; +} + +export type TransformGizmoCache = Map< + string, + { sig: string; polygons: Polygon[] } +>; + +/** + * Visible band start/end as fractions of the ring quad edge. The quad covers + * `±RING_QUAD_OUTER_RATIO · mid-radius`; the visible band is + * `mid ± halfThickness`. Consumed by `.polycss-transform-ring`'s CSS mask. + */ +export const RING_MASK_INNER_RATIO = + (1 - RING_HALF_THICKNESS_RATIO) / RING_QUAD_OUTER_RATIO; +export const RING_MASK_OUTER_RATIO = + (1 + RING_HALF_THICKNESS_RATIO) / RING_QUAD_OUTER_RATIO; + +export interface DeclarativeGizmoTarget { + getPosition(): Vec3 | undefined; + getRotation(): Vec3 | undefined; + rebakeAtlas(): void; +} + +export interface DeclarativeGizmoObjectChangeEvent< + TTarget extends DeclarativeGizmoTarget, +> { + object: TTarget; + position?: Vec3; + rotation?: Vec3; +} + +export interface DeclarativeGizmoCallbacks< + TTarget extends DeclarativeGizmoTarget, +> { + onChange?: () => void; + onObjectChange?: (event: DeclarativeGizmoObjectChangeEvent) => void; + onMouseDown?: () => void; + onMouseUp?: () => void; + onDraggingChanged?: (dragging: boolean) => void; +} + +export interface DeclarativeGizmoDragState< + TTarget extends DeclarativeGizmoTarget, +> extends DeclarativeGizmoCallbacks, + GizmoVisibility { + target: TTarget | null; + mode: GizmoMode; + shaftLengthCss: number; + enabled: boolean; + translationSnap: number | null; + rotationSnap: number | null; + onDraggingKeyChange?: (key: string | null) => void; +} diff --git a/packages/polycss/src/api/controls/gizmoEngine.ts b/packages/polycss/src/api/controls/gizmoEngine.ts index 9cd4a3f6..57df5b5f 100644 --- a/packages/polycss/src/api/controls/gizmoEngine.ts +++ b/packages/polycss/src/api/controls/gizmoEngine.ts @@ -6,704 +6,99 @@ * - `` (`@layoutit/polycss-react`) * - `` (`@layoutit/polycss-vue`) */ -import { - ALPHA_DRAGGING, - ALPHA_HOVER, - ALPHA_IDLE, - ARROW_SPECS, - HEAD_HALF_THICKNESS_RATIO, - HEAD_LENGTH_RATIO, - PLANE_HALF_SIZE_RATIO, - PLANE_OFFSET_RATIO, - PLANE_SPECS, - RING_HALF_THICKNESS_RATIO, - RING_QUAD_OUTER_RATIO, - RING_RADIUS_RATIO, - RING_SPECS, - SCENE_TILE_SIZE, - SCREEN_AXIS_DEAD_ZONE_SQ, - SHAFT_HALF_THICKNESS_RATIO, - WORLD_AXIS_FOR_CSS, - arrowPolygons, - eulerXYZFromQuat, - gizmoCenterForMesh, - gizmoLengthForMesh, - isAxisBackFacing, - planePolygons, - quatFromAxisAngle, - quatFromEulerXYZ, - quatMultiply, - ringQuadPolygons, - screenPlaneDet, - snap, - solveAxisDragDelta, - solvePlaneDragDeltas, - unwrapAngleDelta, - userAxisLetterOf, - withAlpha, -} from "@layoutit/polycss-core"; -import type { Polygon, Vec3 } from "@layoutit/polycss-core"; +import { ARROW_SPECS, PLANE_SPECS, RING_SPECS } from "@layoutit/polycss-core"; import { pointInMeshElement } from "../meshHitTest"; - -export type GizmoMode = "translate" | "rotate"; - -export type GizmoArrowSpec = (typeof ARROW_SPECS)[number]; -export type GizmoPlaneSpec = (typeof PLANE_SPECS)[number]; -export type GizmoRingSpec = (typeof RING_SPECS)[number]; - -export interface GizmoVisibility { - showX?: boolean; - showY?: boolean; - showZ?: boolean; -} - -export interface GizmoPolygonEntry { - spec: TSpec; - polygons: Polygon[]; -} - -export interface TransformGizmoEntries { - shaftLengthCss: number; - arrows: GizmoPolygonEntry[]; - planes: GizmoPolygonEntry[]; - rings: GizmoPolygonEntry[]; -} - -/** - * Visible band start/end as fractions of the ring quad edge. The quad covers - * `±RING_QUAD_OUTER_RATIO · mid-radius`; the visible band is - * `mid ± halfThickness`. Consumed by `.polycss-transform-ring`'s CSS mask. - */ -export const RING_MASK_INNER_RATIO = - (1 - RING_HALF_THICKNESS_RATIO) / RING_QUAD_OUTER_RATIO; -export const RING_MASK_OUTER_RATIO = - (1 + RING_HALF_THICKNESS_RATIO) / RING_QUAD_OUTER_RATIO; - -/** - * Swallow the synthesized `click` that immediately follows a gizmo drag's - * `pointerup`, so releasing a drag over a selected mesh does not toggle - * selection off in `` / `createSelect`. - */ -export 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); -} - -function probeScreenAxis( - wrapper: HTMLElement, - axisVec: Vec3, - probeDistanceCss: number, -): { x: number; y: number } { - const probe = wrapper.ownerDocument!.createElement("div"); - probe.style.position = "absolute"; - probe.style.left = "0"; - probe.style.top = "0"; - probe.style.width = "0"; - probe.style.height = "0"; - probe.style.transform = `translate3d(${axisVec[0] * probeDistanceCss}px, ${axisVec[1] * probeDistanceCss}px, ${axisVec[2] * probeDistanceCss}px)`; - wrapper.appendChild(probe); - const wRect = wrapper.getBoundingClientRect(); - const pRect = probe.getBoundingClientRect(); - wrapper.removeChild(probe); - return { - x: (pRect.left - wRect.left) / probeDistanceCss, - y: (pRect.top - wRect.top) / probeDistanceCss, - }; -} - -export interface AxisDragParams { - cssAxis: 0 | 1 | 2; - sign: 1 | -1; - shaftLengthCss: number; - wrapper: HTMLElement; - startClientX: number; - startClientY: number; - translationSnap: number | null; - onAxisDelta(t: number, axisVec: Vec3): void; - onMouseDown?: () => void; - onMouseUp?: () => void; - onDraggingChanged?: (dragging: boolean) => void; -} - -/** - * Project pointer screen-px deltas onto the screen projection of an axis - * vector via a temporary probe element. - */ -export function startAxisDrag(opts: AxisDragParams): (() => void) | null { - const { - cssAxis, - sign, - shaftLengthCss, - wrapper, - startClientX, - startClientY, - translationSnap, - onAxisDelta, - onMouseDown, - onMouseUp, - onDraggingChanged, - } = opts; - - const axisVec: Vec3 = [0, 0, 0]; - 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 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 => { - 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 cancel; -} - -export interface PlaneDragParams { - axisA: 0 | 1 | 2; - axisB: 0 | 1 | 2; - probeDistanceCss: number; - wrapper: HTMLElement; - startClientX: number; - startClientY: number; - translationSnap: number | null; - onPlaneDelta(tA: number, tB: number, axisAVec: Vec3, axisBVec: Vec3): void; - onMouseDown?: () => void; - onMouseUp?: () => void; - onDraggingChanged?: (dragging: boolean) => void; -} - -/** - * 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): (() => void) | null { - const { - axisA, - axisB, - probeDistanceCss, - wrapper, - startClientX, - startClientY, - translationSnap, - onPlaneDelta, - onMouseDown, - onMouseUp, - onDraggingChanged, - } = opts; - - const axisAVec: Vec3 = [0, 0, 0]; - axisAVec[axisA] = 1; - const axisBVec: Vec3 = [0, 0, 0]; - axisBVec[axisB] = 1; - 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 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); - const tA = snap(solved.tA, translationSnap); - const tB = snap(solved.tB, translationSnap); - onPlaneDelta(tA, tB, axisAVec, axisBVec); - }; - const handleUp = (): void => { - 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 cancel; -} - -export interface RingDragParams { - wrapper: HTMLElement; - startClientX: number; - startClientY: number; - rotationSnap: number | null; - onAngleDelta(degrees: number): void; - onMouseDown?: () => void; - onMouseUp?: () => void; - onDraggingChanged?: (dragging: boolean) => void; - onComplete?: () => void; -} - -/** - * Track pointer angle around the gizmo center, accumulate unwrapped radians, - * and report degrees of rotation. - */ -export function startRingDrag(opts: RingDragParams): () => void { - const { - wrapper, - startClientX, - startClientY, - rotationSnap, - onAngleDelta, - onMouseDown, - onMouseUp, - onDraggingChanged, - onComplete, - } = opts; - - const wRect = wrapper.getBoundingClientRect(); - const centerX = wRect.left; - const centerY = wRect.top; - - let lastAngle = Math.atan2(startClientY - centerY, startClientX - centerX); - let cumulative = 0; - - 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; - const degrees = snap((cumulative * 180) / Math.PI, rotationSnap); - onAngleDelta(degrees); - }; - const handleUp = (): void => { - 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 ────────────────────────────────────────────── - -export function gizmoAlphaForKey( - key: string, - hoveredKey: string | null, - draggingKey: string | null, -): number { - if (draggingKey === key) return ALPHA_DRAGGING; - if (hoveredKey === key) return ALPHA_HOVER; - return ALPHA_IDLE; -} - -export function buildArrowGizmoPolygons( - spec: { cssAxis: 0 | 1 | 2; sign: 1 | -1; color: string }, - lengthWorld: number, - alpha: number, - rotX: number, - rotY: number, -): Polygon[] { - const backFacing = isAxisBackFacing(spec.cssAxis, spec.sign, rotX, rotY); - return arrowPolygons({ - axis: WORLD_AXIS_FOR_CSS[spec.cssAxis], - sign: spec.sign, - shaftLength: lengthWorld, - shaftHalfThickness: lengthWorld * SHAFT_HALF_THICKNESS_RATIO, - headLength: lengthWorld * HEAD_LENGTH_RATIO, - headHalfThickness: lengthWorld * HEAD_HALF_THICKNESS_RATIO, - color: withAlpha(spec.color, alpha), - shaft: !backFacing, - }); -} - -export function buildPlaneGizmoPolygons( - spec: { perpAxis: 0 | 1 | 2; color: string }, - lengthWorld: number, - alpha: number, - rotX: number, - rotY: number, -): Polygon[] { - const worldPerp = WORLD_AXIS_FOR_CSS[spec.perpAxis]; - const worldA = ((worldPerp + 1) % 3) as 0 | 1 | 2; - const worldB = ((worldPerp + 2) % 3) as 0 | 1 | 2; - const cssAForOffset = WORLD_AXIS_FOR_CSS[worldA]; - const cssBForOffset = WORLD_AXIS_FOR_CSS[worldB]; - const signA = isAxisBackFacing(cssAForOffset, 1, rotX, rotY) ? -1 : 1; - const signB = isAxisBackFacing(cssBForOffset, 1, rotX, rotY) ? -1 : 1; - const mag = lengthWorld * PLANE_OFFSET_RATIO; - return planePolygons({ - axis: worldPerp, - size: lengthWorld * PLANE_HALF_SIZE_RATIO, - offset: [signA * mag, signB * mag], - color: withAlpha(spec.color, alpha), - }); -} - -export function buildRingGizmoPolygons( - spec: { cssAxis: 0 | 1 | 2; color: string }, - shaftLengthCss: number, - alpha: number, -): Polygon[] { - const radiusWorld = (shaftLengthCss * RING_RADIUS_RATIO) / SCENE_TILE_SIZE; - const outerWorld = radiusWorld * RING_QUAD_OUTER_RATIO; - return ringQuadPolygons({ - axis: WORLD_AXIS_FOR_CSS[spec.cssAxis], - outerRadius: outerWorld, - color: withAlpha(spec.color, alpha), - }); -} - -export function isArrowSpecVisible( - spec: GizmoArrowSpec, - vis: GizmoVisibility, -): boolean { - const show = { - x: vis.showX !== false, - y: vis.showY !== false, - z: vis.showZ !== false, - }; - return show[userAxisLetterOf(spec.key)]; -} - -export function isPlaneSpecVisible( - spec: GizmoPlaneSpec, - vis: GizmoVisibility, -): boolean { - const show = { - x: vis.showX !== false, - y: vis.showY !== false, - z: vis.showZ !== false, - }; - const axes = ["x", "y", "z"] as const; - return show[axes[spec.axisA]] && show[axes[spec.axisB]]; -} - -export function isRingSpecVisible( - spec: GizmoRingSpec, - vis: GizmoVisibility, +import { + startDeclarativeArrowDrag, + startDeclarativePlaneDrag, + startDeclarativeRingDrag, +} from "./gizmo/declarativeDrag"; +import { + isArrowSpecVisible, + isPlaneSpecVisible, + isRingSpecVisible, +} from "./gizmo/geometry"; +import type { + DeclarativeGizmoDragState, + DeclarativeGizmoTarget, +} from "./gizmo/types"; + +export { + RING_MASK_INNER_RATIO, + RING_MASK_OUTER_RATIO, +} from "./gizmo/types"; +export type { + DeclarativeGizmoCallbacks, + DeclarativeGizmoDragState, + DeclarativeGizmoObjectChangeEvent, + DeclarativeGizmoTarget, + GizmoArrowSpec, + GizmoMode, + GizmoPlaneSpec, + GizmoPolygonEntry, + GizmoRingSpec, + GizmoVisibility, + TransformGizmoCache, + TransformGizmoEntries, +} from "./gizmo/types"; + +export { + startAxisDrag, + startPlaneDrag, + startRingDrag, + swallowNextClick, +} from "./gizmo/pointerDrag"; +export type { + AxisDragParams, + PlaneDragParams, + RingDragParams, +} from "./gizmo/pointerDrag"; + +export { + buildArrowGizmoPolygons, + buildPlaneGizmoPolygons, + buildRingGizmoPolygons, + buildTransformGizmoEntries, + computeGizmoWrapperPositionCss, + gizmoAlphaForKey, + isArrowSpecVisible, + isPlaneSpecVisible, + isRingSpecVisible, +} from "./gizmo/geometry"; +export type { BuildTransformGizmoEntriesOptions } from "./gizmo/geometry"; + +export { + startDeclarativeArrowDrag, + startDeclarativePlaneDrag, + startDeclarativeRingDrag, +} from "./gizmo/declarativeDrag"; + +function hitTestFallbackHandle( + doc: Document, + event: PointerEvent, + specs: readonly TSpec[], + selectorPrefix: string, + isVisible: (spec: TSpec) => boolean, + startDrag: (spec: TSpec, wrapper: HTMLElement) => (() => void) | null, + setActiveDrag: (cancel: (() => void) | null) => void, ): boolean { - const show = { - x: vis.showX !== false, - y: vis.showY !== false, - z: vis.showZ !== false, - }; - return show[spec.key as "x" | "y" | "z"]; -} - -export type TransformGizmoCache = Map; - -export interface BuildTransformGizmoEntriesOptions extends GizmoVisibility { - mode: GizmoMode; - polygons: Polygon[]; - size: number; - rotX: number; - rotY: number; - hoveredKey: string | null; - draggingKey: string | null; - /** Optional per-instance handle cache so unchanged handles keep stable Polygon[] identity across camera ticks. */ - cache?: TransformGizmoCache; -} - -function cachedHandlePolygons( - cache: TransformGizmoCache | undefined, - cacheKey: string, - sig: string, - build: () => Polygon[], -): Polygon[] { - const hit = cache?.get(cacheKey); - if (hit && hit.sig === sig) return hit.polygons; - const polygons = build(); - cache?.set(cacheKey, { sig, polygons }); - return polygons; -} - -export function buildTransformGizmoEntries( - opts: BuildTransformGizmoEntriesOptions, -): TransformGizmoEntries { - const shaftLengthCss = gizmoLengthForMesh(opts.polygons) * opts.size; - const lengthWorld = shaftLengthCss / SCENE_TILE_SIZE; - - if (opts.mode === "translate") { - const arrows = ARROW_SPECS.filter((spec) => isArrowSpecVisible(spec, opts)).map((spec) => { - const alpha = gizmoAlphaForKey(spec.key, opts.hoveredKey, opts.draggingKey); - const backFacing = isAxisBackFacing(spec.cssAxis, spec.sign, opts.rotX, opts.rotY); - const sig = `${lengthWorld}|${alpha}|${backFacing ? 1 : 0}`; - return { - spec, - polygons: cachedHandlePolygons(opts.cache, `arrow:${spec.key}`, sig, () => - buildArrowGizmoPolygons(spec, lengthWorld, alpha, opts.rotX, opts.rotY), - ), - }; - }); - const planes = PLANE_SPECS.filter((spec) => isPlaneSpecVisible(spec, opts)).map((spec) => { - const alpha = gizmoAlphaForKey(spec.key, opts.hoveredKey, opts.draggingKey); - const worldPerp = WORLD_AXIS_FOR_CSS[spec.perpAxis]; - const worldA = ((worldPerp + 1) % 3) as 0 | 1 | 2; - const worldB = ((worldPerp + 2) % 3) as 0 | 1 | 2; - const signA = isAxisBackFacing(WORLD_AXIS_FOR_CSS[worldA], 1, opts.rotX, opts.rotY) ? -1 : 1; - const signB = isAxisBackFacing(WORLD_AXIS_FOR_CSS[worldB], 1, opts.rotX, opts.rotY) ? -1 : 1; - const sig = `${lengthWorld}|${alpha}|${signA}|${signB}`; - return { - spec, - polygons: cachedHandlePolygons(opts.cache, `plane:${spec.key}`, sig, () => - buildPlaneGizmoPolygons(spec, lengthWorld, alpha, opts.rotX, opts.rotY), - ), - }; - }); - return { shaftLengthCss, arrows, planes, rings: [] }; + for (const spec of specs) { + if (!isVisible(spec)) continue; + const handleEl = doc.querySelector( + `${selectorPrefix}${spec.key}`, + ) as HTMLElement | null; + if (!handleEl) continue; + if (!pointInMeshElement(handleEl, event.clientX, event.clientY)) continue; + const wrapper = handleEl.closest( + "[data-poly-transform-controls]", + ) as HTMLElement | null; + if (!wrapper) return true; + event.preventDefault(); + event.stopPropagation(); + setActiveDrag(startDrag(spec, wrapper)); + return true; } - - const rings = RING_SPECS.filter((spec) => isRingSpecVisible(spec, opts)).map((spec) => { - const alpha = gizmoAlphaForKey(spec.key, opts.hoveredKey, opts.draggingKey); - const sig = `${shaftLengthCss}|${alpha}`; - return { - spec, - polygons: cachedHandlePolygons(opts.cache, `ring:${spec.key}`, sig, () => - buildRingGizmoPolygons(spec, shaftLengthCss, alpha), - ), - }; - }); - return { shaftLengthCss, arrows: [], planes: [], rings }; -} - -/** - * Compute the gizmo wrapper's CSS-pixel `translate3d` position from a target's - * world-unit `position` and mesh polygons (applying the world→CSS axis swap + - * `SCENE_TILE_SIZE` scale + mesh bbox center). - */ -export function computeGizmoWrapperPositionCss( - position: Vec3 | undefined, - polygons: Polygon[], -): Vec3 { - const pos = position ?? ([0, 0, 0] as Vec3); - const bboxCenter = gizmoCenterForMesh(polygons); - return [ - pos[1] * SCENE_TILE_SIZE + bboxCenter[0], - pos[0] * SCENE_TILE_SIZE + bboxCenter[1], - pos[2] * SCENE_TILE_SIZE + bboxCenter[2], - ]; -} - -// ── Declarative React/Vue gizmo drag & fallback controller ──────────────── - -export interface DeclarativeGizmoTarget { - getPosition(): Vec3 | undefined; - getRotation(): Vec3 | undefined; - rebakeAtlas(): void; -} - -export interface DeclarativeGizmoObjectChangeEvent< - TTarget extends DeclarativeGizmoTarget, -> { - object: TTarget; - position?: Vec3; - rotation?: Vec3; -} - -export interface DeclarativeGizmoCallbacks< - TTarget extends DeclarativeGizmoTarget, -> { - onChange?: () => void; - onObjectChange?: (event: DeclarativeGizmoObjectChangeEvent) => void; - onMouseDown?: () => void; - onMouseUp?: () => void; - onDraggingChanged?: (dragging: boolean) => void; -} - -export interface DeclarativeGizmoDragState< - TTarget extends DeclarativeGizmoTarget, -> extends DeclarativeGizmoCallbacks, - GizmoVisibility { - target: TTarget | null; - mode: GizmoMode; - shaftLengthCss: number; - enabled: boolean; - translationSnap: number | null; - rotationSnap: number | null; - onDraggingKeyChange?: (key: string | null) => void; -} - -export function startDeclarativeArrowDrag< - TTarget extends DeclarativeGizmoTarget, ->( - spec: GizmoArrowSpec, - wrapper: HTMLElement, - startClientX: number, - startClientY: number, - getState: () => DeclarativeGizmoDragState, -): (() => void) | null { - const initial = getState(); - const target = initial.target; - if (!target || !initial.enabled) return null; - const startPos = (target.getPosition() ?? [0, 0, 0]) as Vec3; - return startAxisDrag({ - cssAxis: spec.cssAxis, - sign: spec.sign, - shaftLengthCss: initial.shaftLengthCss, - wrapper, - startClientX, - startClientY, - translationSnap: initial.translationSnap, - onAxisDelta: (t, axisVec) => { - const next: Vec3 = [ - startPos[0] + t * axisVec[0], - startPos[1] + t * axisVec[1], - startPos[2] + t * axisVec[2], - ]; - const live = getState(); - live.onObjectChange?.({ object: target, position: next }); - live.onChange?.(); - }, - onMouseDown: () => getState().onMouseDown?.(), - onMouseUp: () => getState().onMouseUp?.(), - onDraggingChanged: (d) => { - const live = getState(); - live.onDraggingKeyChange?.(d ? spec.key : null); - live.onDraggingChanged?.(d); - }, - }); -} - -export function startDeclarativePlaneDrag< - TTarget extends DeclarativeGizmoTarget, ->( - spec: GizmoPlaneSpec, - wrapper: HTMLElement, - startClientX: number, - startClientY: number, - getState: () => DeclarativeGizmoDragState, -): (() => void) | null { - const initial = getState(); - const target = initial.target; - if (!target || !initial.enabled) return null; - const startPos = (target.getPosition() ?? [0, 0, 0]) as Vec3; - return startPlaneDrag({ - axisA: spec.axisA, - axisB: spec.axisB, - probeDistanceCss: initial.shaftLengthCss, - wrapper, - startClientX, - startClientY, - translationSnap: initial.translationSnap, - onPlaneDelta: (tA, tB, axisAVec, axisBVec) => { - const next: Vec3 = [ - startPos[0] + tA * axisAVec[0] + tB * axisBVec[0], - startPos[1] + tA * axisAVec[1] + tB * axisBVec[1], - startPos[2] + tA * axisAVec[2] + tB * axisBVec[2], - ]; - const live = getState(); - live.onObjectChange?.({ object: target, position: next }); - live.onChange?.(); - }, - onMouseDown: () => getState().onMouseDown?.(), - onMouseUp: () => getState().onMouseUp?.(), - onDraggingChanged: (d) => { - const live = getState(); - live.onDraggingKeyChange?.(d ? spec.key : null); - live.onDraggingChanged?.(d); - }, - }); -} - -export function startDeclarativeRingDrag< - TTarget extends DeclarativeGizmoTarget, ->( - spec: GizmoRingSpec, - wrapper: HTMLElement, - startClientX: number, - startClientY: number, - getState: () => DeclarativeGizmoDragState, -): (() => void) | null { - const initial = getState(); - const target = initial.target; - 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; - return startRingDrag({ - wrapper, - startClientX, - startClientY, - rotationSnap: initial.rotationSnap, - onAngleDelta: (degrees) => { - const qDelta = quatFromAxisAngle(axisVec, (degrees * Math.PI) / 180); - const nextRotation = eulerXYZFromQuat(quatMultiply(qDelta, qStart)); - const live = getState(); - live.onObjectChange?.({ object: target, rotation: nextRotation }); - live.onChange?.(); - }, - onMouseDown: () => getState().onMouseDown?.(), - onMouseUp: () => getState().onMouseUp?.(), - onDraggingChanged: (d) => { - const live = getState(); - live.onDraggingKeyChange?.(d ? spec.key : null); - live.onDraggingChanged?.(d); - }, - onComplete: () => { - target.rebakeAtlas(); - }, - }); + return false; } /** @@ -733,63 +128,61 @@ export function attachDeclarativeGizmoFallback< if (state.mode === "translate") { // Plane handles are hit-tested first so they win at overlapping corners. - for (const spec of PLANE_SPECS) { - if (!isPlaneSpecVisible(spec, state)) continue; - const planeEl = doc.querySelector( - `.polycss-transform-plane--${spec.key}`, - ) as HTMLElement | null; - if (!planeEl) continue; - if (!pointInMeshElement(planeEl, event.clientX, event.clientY)) continue; - const wrapper = planeEl.closest( - "[data-poly-transform-controls]", - ) as HTMLElement | null; - if (!wrapper) return; - event.preventDefault(); - event.stopPropagation(); - setActiveDrag( - startDeclarativePlaneDrag(spec, wrapper, event.clientX, event.clientY, getState), - ); - return; - } - for (const spec of ARROW_SPECS) { - if (!isArrowSpecVisible(spec, state)) continue; - const arrowEl = doc.querySelector( - `.polycss-transform-arrow--${spec.key}`, - ) as HTMLElement | null; - if (!arrowEl) continue; - if (!pointInMeshElement(arrowEl, event.clientX, event.clientY)) continue; - const wrapper = arrowEl.closest( - "[data-poly-transform-controls]", - ) as HTMLElement | null; - if (!wrapper) return; - event.preventDefault(); - event.stopPropagation(); - setActiveDrag( - startDeclarativeArrowDrag(spec, wrapper, event.clientX, event.clientY, getState), - ); + if ( + hitTestFallbackHandle( + doc, + event, + PLANE_SPECS, + ".polycss-transform-plane--", + (spec) => isPlaneSpecVisible(spec, state), + (spec, wrapper) => + startDeclarativePlaneDrag( + spec, + wrapper, + event.clientX, + event.clientY, + getState, + ), + setActiveDrag, + ) + ) { return; } - return; - } - - for (const spec of RING_SPECS) { - if (!isRingSpecVisible(spec, state)) continue; - const ringEl = doc.querySelector( - `.polycss-transform-ring--${spec.key}`, - ) as HTMLElement | null; - if (!ringEl) continue; - if (!pointInMeshElement(ringEl, event.clientX, event.clientY)) continue; - const wrapper = ringEl.closest( - "[data-poly-transform-controls]", - ) as HTMLElement | null; - if (!wrapper) return; - event.preventDefault(); - event.stopPropagation(); - setActiveDrag( - startDeclarativeRingDrag(spec, wrapper, event.clientX, event.clientY, getState), + hitTestFallbackHandle( + doc, + event, + ARROW_SPECS, + ".polycss-transform-arrow--", + (spec) => isArrowSpecVisible(spec, state), + (spec, wrapper) => + startDeclarativeArrowDrag( + spec, + wrapper, + event.clientX, + event.clientY, + getState, + ), + setActiveDrag, ); return; } + + hitTestFallbackHandle( + doc, + event, + RING_SPECS, + ".polycss-transform-ring--", + (spec) => isRingSpecVisible(spec, state), + (spec, wrapper) => + startDeclarativeRingDrag( + spec, + wrapper, + event.clientX, + event.clientY, + getState, + ), + setActiveDrag, + ); }; cameraEl.addEventListener("pointerdown", onPointerDown); diff --git a/packages/polycss/src/render/atlas/render/stableTopologyUpdate.test.ts b/packages/polycss/src/render/atlas/render/stableTopologyUpdate.test.ts new file mode 100644 index 00000000..975436c6 --- /dev/null +++ b/packages/polycss/src/render/atlas/render/stableTopologyUpdate.test.ts @@ -0,0 +1,218 @@ +import { describe, expect, it } from "vitest"; +import type { Polygon, SolidTriangleFrame } from "@layoutit/polycss-core"; +import type { InternalRenderTextureAtlasOptions } from "../types"; +import { + renderPolygonsWithTextureAtlas, + updatePolygonsWithStableTopology, + updateStableTriangleFrame, +} from "../renderPolygons"; + +function makeTri(dx = 0, color = "#e05a2b"): Polygon { + return { + vertices: [ + [dx, 0, 0], + [dx + 2, 0, 0], + [dx, 2, 0], + ], + color, + }; +} + +function makeQuad(dx = 0, color = "#3b82f6"): Polygon { + return { + vertices: [ + [dx, 0, 0], + [dx + 2, 0, 0], + [dx + 2, 2, 0], + [dx, 2, 0], + ], + color, + }; +} + +describe("updatePolygonsWithStableTopology & updateStableTriangleFrame", () => { + it("rejects mismatched lengths, index drift, and color-only mode on non-triangles", () => { + const polys = [makeQuad(0)]; + const atlas = renderPolygonsWithTextureAtlas(polys, { textureLighting: "baked" }); + try { + expect(updatePolygonsWithStableTopology(atlas.rendered, [])).toBe(false); + expect( + updatePolygonsWithStableTopology( + [{ ...atlas.rendered[0]!, polygonIndex: 2 }], + polys, + ), + ).toBe(false); + const colorOnlyOpts: InternalRenderTextureAtlasOptions = { + textureLighting: "baked", + optimizeStableTriangleStyle: true, + stableTriangleUpdateMode: "color-only", + }; + expect(updatePolygonsWithStableTopology(atlas.rendered, polys, colorOnlyOpts)).toBe(false); + } finally { + atlas.dispose(); + } + }); + + it("updates mixed solid quads and triangles in place without replacing DOM elements", () => { + const initial = [makeQuad(0, "#3b82f6"), makeTri(3, "#e05a2b")]; + const atlas = renderPolygonsWithTextureAtlas(initial, { textureLighting: "baked" }); + const [quadEl, triEl] = atlas.rendered.map((item) => item.element); + const beforeTriTransform = triEl!.style.transform; + try { + const next = [makeQuad(1, "#22c55e"), makeTri(4, "#f59e0b")]; + expect(updatePolygonsWithStableTopology(atlas.rendered, next, { textureLighting: "baked" })).toBe(true); + expect(atlas.rendered[0]!.element).toBe(quadEl); + expect(atlas.rendered[1]!.element).toBe(triEl); + expect(triEl!.style.transform).not.toBe(beforeTriTransform); + expect(triEl!.style.visibility).not.toBe("hidden"); + + // Degenerate triangle hides cleanly rather than forcing full rebuild. + const degenerate: Polygon = { + vertices: [[0, 0, 0], [0, 0, 0], [0, 0, 0]], + color: "#f59e0b", + }; + expect( + updatePolygonsWithStableTopology(atlas.rendered, [next[0]!, degenerate], { textureLighting: "baked" }), + ).toBe(true); + expect(triEl!.style.visibility).toBe("hidden"); + } finally { + atlas.dispose(); + } + }); + + it("exercises optimizeStableTriangleStyle modes (plan-only, transform-only, color-only, adaptive)", () => { + const polys = [makeTri(0, "#cc4422"), makeTri(3, "#2288cc")]; + const atlas = renderPolygonsWithTextureAtlas(polys, { textureLighting: "baked" }); + const triEl = atlas.rendered[0]!.element; + try { + const moved = [makeTri(1, "#22cc66"), makeTri(4, "#3399dd")]; + const beforeStyle = triEl.getAttribute("style"); + + const planOnlyOpts: InternalRenderTextureAtlasOptions = { + textureLighting: "baked", + optimizeStableTriangleStyle: true, + stableTriangleDebug: "plan-only", + }; + expect(updatePolygonsWithStableTopology(atlas.rendered, moved, planOnlyOpts)).toBe(true); + expect(triEl.getAttribute("style")).toBe(beforeStyle); + + const transformOnlyOpts: InternalRenderTextureAtlasOptions = { + textureLighting: "baked", + optimizeStableTriangleStyle: true, + stableTriangleUpdateMode: "transform-only", + }; + const beforeTransform = triEl.style.transform; + const beforeColor = triEl.style.color || triEl.style.borderBottomColor || triEl.style.backgroundColor; + expect(updatePolygonsWithStableTopology(atlas.rendered, moved, transformOnlyOpts)).toBe(true); + expect(triEl.style.transform).not.toBe(beforeTransform); + expect(triEl.style.color || triEl.style.borderBottomColor || triEl.style.backgroundColor).toBe(beforeColor); + + const colorOnlyOpts: InternalRenderTextureAtlasOptions = { + textureLighting: "baked", + optimizeStableTriangleStyle: true, + stableTriangleUpdateMode: "color-only", + stableTriangleColorPolicy: "adaptive", + }; + const transformAfterMove = triEl.style.transform; + expect(updatePolygonsWithStableTopology(atlas.rendered, moved, colorOnlyOpts)).toBe(true); + expect(triEl.style.transform).toBe(transformAfterMove); + expect(triEl.style.color || triEl.style.borderBottomColor || triEl.style.backgroundColor).not.toBe(beforeColor); + + const adaptiveFullOpts: InternalRenderTextureAtlasOptions = { + textureLighting: "baked", + optimizeStableTriangleStyle: true, + stableTriangleColorPolicy: "adaptive", + }; + expect(updatePolygonsWithStableTopology(atlas.rendered, [makeTri(2, "#aa22ee"), makeTri(5, "#3399dd")], adaptiveFullOpts)).toBe(true); + expect(triEl.style.transform).not.toBe(transformAfterMove); + } finally { + atlas.dispose(); + } + }); + + it("updates triangles via updateStableTriangleFrame and rejects invalid frames/modes", () => { + const polys = [makeTri(0, "#cc4422"), makeTri(3, "#2288cc")]; + const atlas = renderPolygonsWithTextureAtlas(polys, { textureLighting: "baked" }); + const triEl = atlas.rendered[0]!.element; + const frame: SolidTriangleFrame = { + polygonCount: 2, + vertices: new Float64Array([ + 1, 0, 0, 3, 0, 0, 1, 2, 0, + 4, 0, 0, 6, 0, 0, 4, 2, 0, + ]), + }; + try { + expect(updateStableTriangleFrame(atlas.rendered, polys, frame, { textureLighting: "baked" })).toBe(false); + const dynamicOpts: InternalRenderTextureAtlasOptions = { + textureLighting: "dynamic", + optimizeStableTriangleStyle: true, + }; + expect(updateStableTriangleFrame(atlas.rendered, polys, frame, dynamicOpts)).toBe(false); + const adaptiveOpts: InternalRenderTextureAtlasOptions = { + textureLighting: "baked", + optimizeStableTriangleStyle: true, + stableTriangleColorPolicy: "adaptive", + }; + expect(updateStableTriangleFrame(atlas.rendered, polys, frame, adaptiveOpts)).toBe(false); + const colorOnlyOpts: InternalRenderTextureAtlasOptions = { + textureLighting: "baked", + optimizeStableTriangleStyle: true, + stableTriangleUpdateMode: "color-only", + }; + expect(updateStableTriangleFrame(atlas.rendered, polys, frame, colorOnlyOpts)).toBe(false); + const fullOpts: InternalRenderTextureAtlasOptions = { + textureLighting: "baked", + optimizeStableTriangleStyle: true, + }; + expect( + updateStableTriangleFrame( + atlas.rendered, + polys, + { polygonCount: 2, vertices: new Float64Array(9) }, + fullOpts, + ), + ).toBe(false); + + const styleBeforePlanOnly = triEl.getAttribute("style"); + const planOnlyOpts: InternalRenderTextureAtlasOptions = { + textureLighting: "baked", + optimizeStableTriangleStyle: true, + stableTriangleDebug: "plan-only", + }; + expect(updateStableTriangleFrame(atlas.rendered, polys, frame, planOnlyOpts)).toBe(true); + expect(triEl.getAttribute("style")).toBe(styleBeforePlanOnly); + + const transformBefore = triEl.style.transform; + const transformOnlyOpts: InternalRenderTextureAtlasOptions = { + textureLighting: "baked", + optimizeStableTriangleStyle: true, + stableTriangleUpdateMode: "transform-only", + }; + expect(updateStableTriangleFrame(atlas.rendered, polys, frame, transformOnlyOpts)).toBe(true); + expect(triEl.style.transform).not.toBe(transformBefore); + + const movedFrame: SolidTriangleFrame = { + polygonCount: 2, + vertices: new Float64Array([ + 2, 0, 0, 4, 0, 0, 2, 2, 0, + 5, 0, 0, 7, 0, 0, 5, 2, 0, + ]), + }; + const transformBeforeFull = triEl.style.transform; + expect(updateStableTriangleFrame(atlas.rendered, polys, movedFrame, fullOpts)).toBe(true); + expect(triEl.style.transform).not.toBe(transformBeforeFull); + + const degenerateFrame: SolidTriangleFrame = { + polygonCount: 2, + vertices: new Float64Array([ + 0, 0, 0, 0, 0, 0, 0, 0, 0, + 4, 0, 0, 6, 0, 0, 4, 2, 0, + ]), + }; + expect(updateStableTriangleFrame(atlas.rendered, polys, degenerateFrame, fullOpts)).toBe(true); + expect(triEl.style.visibility).toBe("hidden"); + } finally { + atlas.dispose(); + } + }); +}); diff --git a/website/package.json b/website/package.json index 64f1d481..c2435d1e 100644 --- a/website/package.json +++ b/website/package.json @@ -7,7 +7,7 @@ "license": "MIT", "scripts": { "dev": "astro dev", - "build": "astro build && node scripts/generate-llms-txt.mjs", + "build": "ASTRO_TELEMETRY_DISABLED=1 astro build && node scripts/generate-llms-txt.mjs", "typecheck": "ASTRO_TELEMETRY_DISABLED=1 astro sync && tsc --noEmit", "generate:domformat": "node scripts/generate-gallery-domformat.mjs", "prove:domformat": "node scripts/prove-gallery-domformat.mjs", @@ -15,6 +15,7 @@ "verify:domformat:fresh": "node scripts/verify-gallery-domformat.mjs --fresh", "generate:shape-thumbnails": "node scripts/generate-builder-shape-thumbnails.mjs", "test:domformat-tools": "node --test scripts/gallery-domformat-canonical.test.mjs", + "test:unit": "node scripts/run-unit-tests.mjs", "preview": "astro preview" }, "dependencies": { diff --git a/website/scripts/run-unit-tests.mjs b/website/scripts/run-unit-tests.mjs new file mode 100644 index 00000000..a598cc94 --- /dev/null +++ b/website/scripts/run-unit-tests.mjs @@ -0,0 +1,55 @@ +#!/usr/bin/env node +/** + * Bundle and run TypeScript unit tests under `website/tests/*.test.ts` + * using the workspace's `esbuild` + `node --test` (zero extra deps). + */ +import { execFileSync } from "node:child_process"; +import { mkdtempSync, readdirSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { build } from "esbuild"; +import { createWorkspaceSourceAliases } from "../../packages/workspace-aliases.mjs"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const websiteRoot = resolve(__dirname, ".."); +const testsDir = join(websiteRoot, "tests"); + +function collectTestFiles(dir, out = []) { + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const full = join(dir, entry.name); + if (entry.isDirectory()) collectTestFiles(full, out); + else if (entry.name.endsWith(".test.ts")) out.push(full); + } + return out; +} + +const entryPoints = collectTestFiles(testsDir).sort(); + +if (entryPoints.length === 0) { + console.error("[website:test:unit] No *.test.ts files found under website/tests/"); + process.exit(1); +} + +const outDir = mkdtempSync(join(tmpdir(), "polycss-website-unit-")); +try { + await build({ + entryPoints, + outdir: outDir, + bundle: true, + format: "esm", + platform: "node", + target: "node22", + outExtension: { ".js": ".mjs" }, + alias: createWorkspaceSourceAliases(), + external: ["node:*"], + logLevel: "warning", + }); + const built = readdirSync(outDir) + .filter((name) => name.endsWith(".mjs")) + .sort() + .map((name) => join(outDir, name)); + execFileSync(process.execPath, ["--test", ...built], { stdio: "inherit" }); +} finally { + rmSync(outDir, { recursive: true, force: true }); +} diff --git a/website/src/components/BuilderWorkbench/components/BuilderScene.tsx b/website/src/components/BuilderWorkbench/components/BuilderScene.tsx index 28ea5cd0..53d8ab0d 100644 --- a/website/src/components/BuilderWorkbench/components/BuilderScene.tsx +++ b/website/src/components/BuilderWorkbench/components/BuilderScene.tsx @@ -11,7 +11,6 @@ import { PolyScene, PolySelect, PolyTransformControls, - useCameraContext, } from "@layoutit/polycss-react"; import type { PolyAmbientLight, @@ -22,37 +21,18 @@ import type { Polygon, 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 { useMemo, type RefObject } from "react"; import { meshResolutionShowsMesh, type SceneOptionsState } from "../../types"; import { FPV_PERSPECTIVE } from "../../fpv"; import { BUILDER_GROUND_SPAN, BUILDER_MAX_CAMERA_ROT_X } from "../defaults"; import { buildSolidWireframePolygons } from "../geometry/ghost"; import { meshBbox } from "../geometry/meshBbox"; -import { projectScreenToWorldGround } from "../geometry/screenToWorld"; -import { snapWorldToCellCenter } from "../geometry/snap"; import type { BuilderPlacementTarget, BuilderToolMode, PlacedItem } from "../types"; import { BuilderCameraDragControls } from "./BuilderCameraDragControls"; - -const GROUND_FILL_COLORS = { - gray: "#f5f3ea", - dark: "#05070b", -} as const; - -// The Dock's camera slider feeds a unitless 0.05–2.5 zoom value (legacy -// CSS-scale semantics shared with the gallery). Post-parity the camera -// expects px-per-world-unit, so we multiply the slider value by BASE_TILE -// (50) before handing it to the camera, and divide it back before pushing -// updates into sceneOptions. Same shape as gallery's LEGACY_ZOOM_COMPAT. -const LEGACY_ZOOM_COMPAT = 50; +import { BuilderSelectedMeshInteractionControls } from "./scene/BuilderSelectedMeshInteractionControls"; +import { BuilderViewportToolControls } from "./scene/BuilderViewportToolControls"; +import { GROUND_FILL_COLORS, LEGACY_ZOOM_COMPAT } from "./scene/constants"; +import { placementSurfaceForItem, type PlacementSurface } from "./scene/placementSurface"; export interface BuilderSceneProps { sceneOptions: SceneOptionsState; @@ -82,516 +62,6 @@ export interface BuilderSceneProps { selected: PlacedItem | null; } -// Post-parity `` is `T·R·S` pivoting at the local origin, -// so visible(v) = T + S·v (no rotation here — XY surfaces are axis-aligned). -// `position[2]` is the world-Z translate, so the visible bottom of a vertex -// at v.z = minZ sits at `position[2] + scale * minZ`. -function selectedSurfaceWorldZ(item: PlacedItem): number { - if (!item.rawPolygons) return item.elevation ?? 0; - const bbox = meshBbox(item.rawPolygons); - const scale = Math.max(item.fitScale * item.scale, 0.0001); - return item.position[2] + scale * bbox.minZ; -} - -function itemTopSurfaceWorldZ(item: PlacedItem & { rawPolygons: Polygon[] }, polygons: Polygon[]): number { - const bbox = meshBbox(polygons); - const scale = Math.max(item.fitScale * item.scale, 0.0001); - return item.position[2] + scale * bbox.maxZ; -} - -function itemBaseSurfaceWorldZ(item: PlacedItem & { rawPolygons: Polygon[] }, polygons: Polygon[]): number { - const bbox = meshBbox(polygons); - const scale = Math.max(item.fitScale * item.scale, 0.0001); - return item.position[2] + scale * bbox.minZ; -} - -interface PlacementSurface { - baseWorldZ: number; - surfaceWorldZ: number; - minWorldX: number; - maxWorldX: number; - minWorldY: number; - maxWorldY: number; -} - -type PaintLeafFace = "top" | "side" | "other"; - -function transformNormalZ(transform: string): number | null { - const matrix3d = transform.match(/^matrix3d\((.+)\)$/); - if (matrix3d) { - const values = matrix3d[1].split(",").map((value) => Number(value.trim())); - if (values.length !== 16 || values.some((value) => !Number.isFinite(value))) return null; - const nx = values[8]; - const ny = values[9]; - const nz = values[10]; - const len = Math.hypot(nx, ny, nz); - return len > 0 ? nz / len : null; - } - - const matrix = transform.match(/^matrix\((.+)\)$/); - if (matrix) return 1; - return null; -} - -function paintLeafFace(target: EventTarget | null): PaintLeafFace { - const el = target as Element | null; - const leaf = el?.closest("b,i,s,u") as HTMLElement | null; - if (!leaf || !leaf.closest(".builder-placed")) return "other"; - const normalZ = transformNormalZ(getComputedStyle(leaf).transform); - if (normalZ === null) return "other"; - if (normalZ > 0.5) return "top"; - if (Math.abs(normalZ) < 0.25) return "side"; - return "other"; -} - -function placementSurfaceForItem(item: PlacedItem & { rawPolygons: Polygon[] }, polygons: Polygon[]): PlacementSurface { - const bbox = meshBbox(polygons); - const scale = Math.max(item.fitScale * item.scale, 0.0001); - const rz = ((item.rotation[2] ?? 0) * Math.PI) / 180; - const cos = Math.cos(rz); - const sin = Math.sin(rz); - let minWorldX = Infinity; - let maxWorldX = -Infinity; - let minWorldY = Infinity; - let maxWorldY = -Infinity; - for (const [x, y] of [ - [bbox.minX, bbox.minY], - [bbox.maxX, bbox.minY], - [bbox.maxX, bbox.maxY], - [bbox.minX, bbox.maxY], - ] as const) { - const dx = (x - bbox.midX) * scale; - const dy = (y - bbox.midY) * scale; - const worldX = item.worldX + dx * cos - dy * sin; - const worldY = item.worldY + dx * sin + dy * cos; - minWorldX = Math.min(minWorldX, worldX); - maxWorldX = Math.max(maxWorldX, worldX); - minWorldY = Math.min(minWorldY, worldY); - maxWorldY = Math.max(maxWorldY, worldY); - } - return { - baseWorldZ: itemBaseSurfaceWorldZ(item, polygons), - surfaceWorldZ: itemTopSurfaceWorldZ(item, polygons), - minWorldX, - maxWorldX, - minWorldY, - maxWorldY, - }; -} - -function zArrowDirectionFromTarget(target: Element | null): 1 | -1 | null { - const arrow = target?.closest(".polycss-transform-arrow--z, .polycss-transform-arrow---z"); - if (!arrow) return null; - return arrow.classList.contains("polycss-transform-arrow---z") ? -1 : 1; -} - -function zArrowDirectionFromPoint(clientX: number, clientY: number): 1 | -1 | null { - for (const [selector, direction] of [ - [".polycss-transform-arrow--z", 1], - [".polycss-transform-arrow---z", -1], - ] as const) { - const arrow = document.querySelector(selector); - if (!arrow) continue; - const leaves = arrow.querySelectorAll("b,i,s,u,q,svg"); - for (const leaf of leaves) { - const rect = leaf.getBoundingClientRect(); - if (rect.width <= 1 || rect.height <= 1) continue; - if ( - clientX >= rect.left && - clientX <= rect.right && - clientY >= rect.top && - clientY <= rect.bottom - ) { - return direction; - } - } - } - return null; -} - -interface BuilderSelectedMeshInteractionControlsProps { - selected: PlacedItem | null; - sceneOptions: SceneOptionsState; - enabled: boolean; - onSelectedMeshDrag: (id: string, worldX: number, worldY: number) => void; - onDraggingChanged: (dragging: boolean) => void; - onStepSelectedElevation: (direction: 1 | -1) => void; -} - -function BuilderSelectedMeshInteractionControls({ - selected, - sceneOptions, - enabled, - onSelectedMeshDrag, - onDraggingChanged, - onStepSelectedElevation, -}: BuilderSelectedMeshInteractionControlsProps): null { - const { store, cameraElRef } = useCameraContext(); - const stateRef = useRef({ - selected, - sceneOptions, - enabled, - onSelectedMeshDrag, - onDraggingChanged, - onStepSelectedElevation, - }); - stateRef.current = { - selected, - sceneOptions, - enabled, - onSelectedMeshDrag, - onDraggingChanged, - onStepSelectedElevation, - }; - const dragRef = useRef<{ - id: string; - pointerId: number; - planeWorldZ: number; - offsetX: number; - offsetY: number; - startX: number; - startY: number; - } | null>(null); - - useEffect(() => { - const cameraEl = cameraElRef.current; - if (!cameraEl) return; - - const armClickSwallow = swallowNextClick; - - const projectAt = (clientX: number, clientY: number, planeWorldZ: number): [number, number] | null => { - const opts = stateRef.current.sceneOptions; - return projectScreenToWorldGround({ - clientX, - clientY, - cameraEl, - sceneOptions: { ...opts, zoom: opts.zoom * LEGACY_ZOOM_COMPAT }, - autoCenterOffset: store.getState().autoCenterOffset, - planeWorldZ, - }); - }; - - const armZClickSwallow = (pointerId: number): void => { - const onUp = (event: PointerEvent): void => { - if (event.pointerId !== pointerId) return; - window.removeEventListener("pointerup", onUp, true); - window.removeEventListener("pointercancel", onUp, true); - armClickSwallow(); - }; - window.addEventListener("pointerup", onUp, true); - window.addEventListener("pointercancel", onUp, true); - }; - - const onPointerDown = (event: PointerEvent): void => { - if (!stateRef.current.enabled) return; - if (event.button !== 0 || event.isPrimary === false) return; - const target = event.target as Element | null; - - const zDirection = zArrowDirectionFromTarget(target) ?? zArrowDirectionFromPoint(event.clientX, event.clientY); - if (zDirection) { - event.preventDefault(); - event.stopPropagation(); - event.stopImmediatePropagation(); - stateRef.current.onStepSelectedElevation(zDirection); - armZClickSwallow(event.pointerId); - return; - } - - if (target?.closest(".polycss-transform-gizmo")) return; - const current = stateRef.current.selected; - if (!current) return; - const meshEl = target?.closest(".builder-placed.is-selected") as HTMLElement | null; - if (!meshEl || meshEl.dataset.polyMeshId !== current.id) return; - - const planeWorldZ = selectedSurfaceWorldZ(current); - const hit = projectAt(event.clientX, event.clientY, planeWorldZ); - if (!hit) return; - - event.preventDefault(); - event.stopPropagation(); - event.stopImmediatePropagation(); - dragRef.current = { - id: current.id, - pointerId: event.pointerId, - planeWorldZ, - offsetX: current.worldX - hit[0], - offsetY: current.worldY - hit[1], - startX: event.clientX, - startY: event.clientY, - }; - cameraEl.style.cursor = "grabbing"; - stateRef.current.onDraggingChanged(true); - }; - - const onPointerMove = (event: PointerEvent): void => { - const drag = dragRef.current; - if (!drag || event.pointerId !== drag.pointerId) return; - const hit = projectAt(event.clientX, event.clientY, drag.planeWorldZ); - if (!hit) return; - event.preventDefault(); - event.stopPropagation(); - event.stopImmediatePropagation(); - stateRef.current.onSelectedMeshDrag(drag.id, hit[0] + drag.offsetX, hit[1] + drag.offsetY); - }; - - const onPointerDone = (event: PointerEvent): void => { - const drag = dragRef.current; - if (!drag || event.pointerId !== drag.pointerId) return; - dragRef.current = null; - event.preventDefault(); - event.stopPropagation(); - event.stopImmediatePropagation(); - cameraEl.style.cursor = stateRef.current.sceneOptions.interactive ? "grab" : ""; - stateRef.current.onDraggingChanged(false); - armClickSwallow(); - }; - - cameraEl.addEventListener("pointerdown", onPointerDown, true); - window.addEventListener("pointermove", onPointerMove, true); - window.addEventListener("pointerup", onPointerDone, true); - window.addEventListener("pointercancel", onPointerDone, true); - - return () => { - cameraEl.removeEventListener("pointerdown", onPointerDown, true); - window.removeEventListener("pointermove", onPointerMove, true); - window.removeEventListener("pointerup", onPointerDone, true); - window.removeEventListener("pointercancel", onPointerDone, true); - if (dragRef.current) { - dragRef.current = null; - stateRef.current.onDraggingChanged(false); - } - }; - }, [cameraElRef, store]); - - return null; -} - -interface BuilderViewportToolControlsProps { - tool: BuilderToolMode; - sceneOptions: SceneOptionsState; - placementSurfaceById: Map; - onAddShapeAt: (target: BuilderPlacementTarget) => void; - onRemoveItem: (id: string) => void; - onDraggingChanged: (dragging: boolean) => void; -} - -function BuilderViewportToolControls({ - tool, - sceneOptions, - placementSurfaceById, - onAddShapeAt, - onRemoveItem, - onDraggingChanged, -}: BuilderViewportToolControlsProps): null { - const { store, cameraElRef } = useCameraContext(); - const stateRef = useRef({ - tool, - sceneOptions, - placementSurfaceById, - onAddShapeAt, - onRemoveItem, - onDraggingChanged, - }); - stateRef.current = { - tool, - sceneOptions, - placementSurfaceById, - onAddShapeAt, - onRemoveItem, - onDraggingChanged, - }; - const downRef = useRef<{ x: number; y: number; target: EventTarget | null } | null>(null); - - useEffect(() => { - const cameraEl = cameraElRef.current; - if (!cameraEl) return; - - const isUiOverlay = (target: EventTarget | null): boolean => { - const el = target as HTMLElement | null; - if (!el?.closest) return false; - return Boolean(el.closest(".builder-tool-ribbon, .shape-picker, .builder-camera-mode, .dn-floating-controls")); - }; - - const snapHit = (hit: [number, number]): [number, number] => { - const { sceneOptions: options } = stateRef.current; - if (!options.snapToGrid || options.gridResolution <= 0) return hit; - return snapWorldToCellCenter(hit[0], hit[1], options.gridResolution); - }; - - const projectAt = (clientX: number, clientY: number, planeWorldZ = 0): [number, number] | null => { - const state = stateRef.current; - const opts = state.sceneOptions; - const hit = projectScreenToWorldGround({ - clientX, - clientY, - cameraEl, - sceneOptions: { ...opts, zoom: opts.zoom * LEGACY_ZOOM_COMPAT }, - autoCenterOffset: store.getState().autoCenterOffset, - planeWorldZ, - }); - return hit; - }; - - const surfaceForTarget = (target: EventTarget | null): PlacementSurface | null => { - const el = target as Element | null; - const meshEl = el?.closest(".builder-placed") as HTMLElement | null; - const id = meshEl?.dataset.polyMeshId; - if (!id) return null; - return stateRef.current.placementSurfaceById.get(id) ?? null; - }; - - const clampToSurface = (hit: [number, number], surface: PlacementSurface): [number, number] => { - const { sceneOptions: options } = stateRef.current; - if (!options.snapToGrid || options.gridResolution <= 0) { - return [ - Math.min(surface.maxWorldX, Math.max(surface.minWorldX, hit[0])), - Math.min(surface.maxWorldY, Math.max(surface.minWorldY, hit[1])), - ]; - } - - const step = options.gridResolution; - const minCenterX = surface.minWorldX + step / 2; - const maxCenterX = surface.maxWorldX - step / 2; - const minCenterY = surface.minWorldY + step / 2; - const maxCenterY = surface.maxWorldY - step / 2; - const centerX = (surface.minWorldX + surface.maxWorldX) / 2; - const centerY = (surface.minWorldY + surface.maxWorldY) / 2; - return [ - minCenterX <= maxCenterX - ? Math.min(maxCenterX, Math.max(minCenterX, hit[0])) - : centerX, - minCenterY <= maxCenterY - ? Math.min(maxCenterY, Math.max(minCenterY, hit[1])) - : centerY, - ]; - }; - - const highestSurfaceAt = (worldX: number, worldY: number, fallback: PlacementSurface): number => { - const epsilon = Math.max(0.001, stateRef.current.sceneOptions.gridResolution * 0.01); - let top = fallback.surfaceWorldZ; - for (const surface of stateRef.current.placementSurfaceById.values()) { - if ( - worldX >= surface.minWorldX - epsilon && - worldX <= surface.maxWorldX + epsilon && - worldY >= surface.minWorldY - epsilon && - worldY <= surface.maxWorldY + epsilon - ) { - top = Math.max(top, surface.surfaceWorldZ); - } - } - return top; - }; - - const sidePlacementTarget = (hit: [number, number], surface: PlacementSurface): [number, number] => { - const { sceneOptions: options } = stateRef.current; - const step = options.gridResolution > 0 - ? options.gridResolution - : Math.max(surface.maxWorldX - surface.minWorldX, surface.maxWorldY - surface.minWorldY, 1); - const centerX = (surface.minWorldX + surface.maxWorldX) / 2; - const centerY = (surface.minWorldY + surface.maxWorldY) / 2; - const snapped = options.snapToGrid && options.gridResolution > 0 - ? snapWorldToCellCenter(hit[0], hit[1], step) - : hit; - const minCenterX = surface.minWorldX + step / 2; - const maxCenterX = surface.maxWorldX - step / 2; - const minCenterY = surface.minWorldY + step / 2; - const maxCenterY = surface.maxWorldY - step / 2; - const clampX = (value: number): number => - minCenterX <= maxCenterX - ? Math.min(maxCenterX, Math.max(minCenterX, value)) - : centerX; - const clampY = (value: number): number => - minCenterY <= maxCenterY - ? Math.min(maxCenterY, Math.max(minCenterY, value)) - : centerY; - const sides = [ - { axis: "x" as const, sign: -1 as const, distance: Math.abs(hit[0] - surface.minWorldX) }, - { axis: "x" as const, sign: 1 as const, distance: Math.abs(hit[0] - surface.maxWorldX) }, - { axis: "y" as const, sign: -1 as const, distance: Math.abs(hit[1] - surface.minWorldY) }, - { axis: "y" as const, sign: 1 as const, distance: Math.abs(hit[1] - surface.maxWorldY) }, - ].sort((a, b) => a.distance - b.distance); - const side = sides[0]; - if (side.axis === "x") { - return [ - side.sign < 0 ? surface.minWorldX - step / 2 : surface.maxWorldX + step / 2, - clampY(snapped[1]), - ]; - } - return [ - clampX(snapped[0]), - side.sign < 0 ? surface.minWorldY - step / 2 : surface.maxWorldY + step / 2, - ]; - }; - - const onPointerDown = (event: PointerEvent): void => { - if (stateRef.current.tool === "move") return; - if (event.button !== 0 || event.isPrimary === false) return; - if (isUiOverlay(event.target)) return; - downRef.current = { x: event.clientX, y: event.clientY, target: event.target }; - }; - - const onClick = (event: MouseEvent): void => { - const state = stateRef.current; - if (state.tool === "move") return; - if (isUiOverlay(event.target)) return; - const down = downRef.current; - downRef.current = null; - if (down && Math.hypot(event.clientX - down.x, event.clientY - down.y) > 8) return; - - if (state.tool === "remove") { - const el = event.target as Element | null; - const meshEl = el?.closest(".builder-placed") as HTMLElement | null; - const id = meshEl?.dataset.polyMeshId; - if (!id) return; - event.preventDefault(); - event.stopPropagation(); - event.stopImmediatePropagation(); - state.onRemoveItem(id); - return; - } - - const face = paintLeafFace(event.target); - const surface = face !== "other" ? surfaceForTarget(event.target) : null; - let hit: [number, number] | null = null; - let surfaceWorldZ: number | null = null; - if (surface && face === "top") { - const projected = projectAt(event.clientX, event.clientY, surface.surfaceWorldZ); - if (!projected) return; - hit = clampToSurface(snapHit(projected), surface); - surfaceWorldZ = highestSurfaceAt(hit[0], hit[1], surface); - } else if (surface && face === "side") { - const projected = projectAt(event.clientX, event.clientY, surface.baseWorldZ); - if (!projected) return; - hit = sidePlacementTarget(projected, surface); - surfaceWorldZ = surface.baseWorldZ; - } else { - const projected = projectAt(event.clientX, event.clientY); - if (!projected) return; - hit = snapHit(projected); - } - event.preventDefault(); - event.stopPropagation(); - event.stopImmediatePropagation(); - state.onAddShapeAt({ - worldX: hit[0], - worldY: hit[1], - ...(surfaceWorldZ !== null ? { surfaceWorldZ } : null), - }); - }; - - cameraEl.addEventListener("pointerdown", onPointerDown, true); - cameraEl.addEventListener("click", onClick, true); - return () => { - cameraEl.removeEventListener("pointerdown", onPointerDown, true); - cameraEl.removeEventListener("click", onClick, true); - downRef.current = null; - stateRef.current.onDraggingChanged(false); - }; - }, [cameraElRef, store]); - - return null; -} - export function BuilderScene({ sceneOptions, updateScene, diff --git a/website/src/components/BuilderWorkbench/components/scene/BuilderSelectedMeshInteractionControls.tsx b/website/src/components/BuilderWorkbench/components/scene/BuilderSelectedMeshInteractionControls.tsx new file mode 100644 index 00000000..6b14b018 --- /dev/null +++ b/website/src/components/BuilderWorkbench/components/scene/BuilderSelectedMeshInteractionControls.tsx @@ -0,0 +1,203 @@ +import { useCameraContext } from "@layoutit/polycss-react"; +import { useEffect, useRef } from "react"; +import type { SceneOptionsState } from "../../../types"; +import { projectScreenToWorldGround } from "../../geometry/screenToWorld"; +import type { PlacedItem } from "../../types"; +import { LEGACY_ZOOM_COMPAT } from "./constants"; +import { selectedSurfaceWorldZ } from "./placementSurface"; + +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); +} + +function zArrowDirectionFromTarget(target: Element | null): 1 | -1 | null { + const arrow = target?.closest(".polycss-transform-arrow--z, .polycss-transform-arrow---z"); + if (!arrow) return null; + return arrow.classList.contains("polycss-transform-arrow---z") ? -1 : 1; +} + +function zArrowDirectionFromPoint(clientX: number, clientY: number): 1 | -1 | null { + for (const [selector, direction] of [ + [".polycss-transform-arrow--z", 1], + [".polycss-transform-arrow---z", -1], + ] as const) { + const arrow = document.querySelector(selector); + if (!arrow) continue; + const leaves = arrow.querySelectorAll("b,i,s,u,q,svg"); + for (const leaf of leaves) { + const rect = leaf.getBoundingClientRect(); + if (rect.width <= 1 || rect.height <= 1) continue; + if ( + clientX >= rect.left && + clientX <= rect.right && + clientY >= rect.top && + clientY <= rect.bottom + ) { + return direction; + } + } + } + return null; +} + +export interface BuilderSelectedMeshInteractionControlsProps { + selected: PlacedItem | null; + sceneOptions: SceneOptionsState; + enabled: boolean; + onSelectedMeshDrag: (id: string, worldX: number, worldY: number) => void; + onDraggingChanged: (dragging: boolean) => void; + onStepSelectedElevation: (direction: 1 | -1) => void; +} + +export function BuilderSelectedMeshInteractionControls({ + selected, + sceneOptions, + enabled, + onSelectedMeshDrag, + onDraggingChanged, + onStepSelectedElevation, +}: BuilderSelectedMeshInteractionControlsProps): null { + const { store, cameraElRef } = useCameraContext(); + const stateRef = useRef({ + selected, + sceneOptions, + enabled, + onSelectedMeshDrag, + onDraggingChanged, + onStepSelectedElevation, + }); + stateRef.current = { + selected, + sceneOptions, + enabled, + onSelectedMeshDrag, + onDraggingChanged, + onStepSelectedElevation, + }; + const dragRef = useRef<{ + id: string; + pointerId: number; + planeWorldZ: number; + offsetX: number; + offsetY: number; + startX: number; + startY: number; + } | null>(null); + + useEffect(() => { + const cameraEl = cameraElRef.current; + if (!cameraEl) return; + + const armClickSwallow = swallowNextClick; + + const projectAt = (clientX: number, clientY: number, planeWorldZ: number): [number, number] | null => { + const opts = stateRef.current.sceneOptions; + return projectScreenToWorldGround({ + clientX, + clientY, + cameraEl, + sceneOptions: { ...opts, zoom: opts.zoom * LEGACY_ZOOM_COMPAT }, + autoCenterOffset: store.getState().autoCenterOffset, + planeWorldZ, + }); + }; + + const armZClickSwallow = (pointerId: number): void => { + const onUp = (event: PointerEvent): void => { + if (event.pointerId !== pointerId) return; + window.removeEventListener("pointerup", onUp, true); + window.removeEventListener("pointercancel", onUp, true); + armClickSwallow(); + }; + window.addEventListener("pointerup", onUp, true); + window.addEventListener("pointercancel", onUp, true); + }; + + const onPointerDown = (event: PointerEvent): void => { + if (!stateRef.current.enabled) return; + if (event.button !== 0 || event.isPrimary === false) return; + const target = event.target as Element | null; + + const zDirection = zArrowDirectionFromTarget(target) ?? zArrowDirectionFromPoint(event.clientX, event.clientY); + if (zDirection) { + event.preventDefault(); + event.stopPropagation(); + event.stopImmediatePropagation(); + stateRef.current.onStepSelectedElevation(zDirection); + armZClickSwallow(event.pointerId); + return; + } + + if (target?.closest(".polycss-transform-gizmo")) return; + const current = stateRef.current.selected; + if (!current) return; + const meshEl = target?.closest(".builder-placed.is-selected") as HTMLElement | null; + if (!meshEl || meshEl.dataset.polyMeshId !== current.id) return; + + const planeWorldZ = selectedSurfaceWorldZ(current); + const hit = projectAt(event.clientX, event.clientY, planeWorldZ); + if (!hit) return; + + event.preventDefault(); + event.stopPropagation(); + event.stopImmediatePropagation(); + dragRef.current = { + id: current.id, + pointerId: event.pointerId, + planeWorldZ, + offsetX: current.worldX - hit[0], + offsetY: current.worldY - hit[1], + startX: event.clientX, + startY: event.clientY, + }; + cameraEl.style.cursor = "grabbing"; + stateRef.current.onDraggingChanged(true); + }; + + const onPointerMove = (event: PointerEvent): void => { + const drag = dragRef.current; + if (!drag || event.pointerId !== drag.pointerId) return; + const hit = projectAt(event.clientX, event.clientY, drag.planeWorldZ); + if (!hit) return; + event.preventDefault(); + event.stopPropagation(); + event.stopImmediatePropagation(); + stateRef.current.onSelectedMeshDrag(drag.id, hit[0] + drag.offsetX, hit[1] + drag.offsetY); + }; + + const onPointerDone = (event: PointerEvent): void => { + const drag = dragRef.current; + if (!drag || event.pointerId !== drag.pointerId) return; + dragRef.current = null; + event.preventDefault(); + event.stopPropagation(); + event.stopImmediatePropagation(); + cameraEl.style.cursor = stateRef.current.sceneOptions.interactive ? "grab" : ""; + stateRef.current.onDraggingChanged(false); + armClickSwallow(); + }; + + cameraEl.addEventListener("pointerdown", onPointerDown, true); + window.addEventListener("pointermove", onPointerMove, true); + window.addEventListener("pointerup", onPointerDone, true); + window.addEventListener("pointercancel", onPointerDone, true); + + return () => { + cameraEl.removeEventListener("pointerdown", onPointerDown, true); + window.removeEventListener("pointermove", onPointerMove, true); + window.removeEventListener("pointerup", onPointerDone, true); + window.removeEventListener("pointercancel", onPointerDone, true); + if (dragRef.current) { + dragRef.current = null; + stateRef.current.onDraggingChanged(false); + } + }; + }, [cameraElRef, store]); + + return null; +} diff --git a/website/src/components/BuilderWorkbench/components/scene/BuilderViewportToolControls.tsx b/website/src/components/BuilderWorkbench/components/scene/BuilderViewportToolControls.tsx new file mode 100644 index 00000000..a7443152 --- /dev/null +++ b/website/src/components/BuilderWorkbench/components/scene/BuilderViewportToolControls.tsx @@ -0,0 +1,155 @@ +import { useCameraContext } from "@layoutit/polycss-react"; +import { useEffect, useRef } from "react"; +import type { SceneOptionsState } from "../../../types"; +import { projectScreenToWorldGround } from "../../geometry/screenToWorld"; +import type { BuilderPlacementTarget, BuilderToolMode } from "../../types"; +import { LEGACY_ZOOM_COMPAT } from "./constants"; +import { + clampHitToSurface, + computeSidePlacementTarget, + highestSurfaceWorldZAt, + paintLeafFace, + snapPlacementHit, + type PlacementSurface, +} from "./placementSurface"; + +function isUiOverlay(target: EventTarget | null): boolean { + const el = target as HTMLElement | null; + if (!el?.closest) return false; + return Boolean(el.closest(".builder-tool-ribbon, .shape-picker, .builder-camera-mode, .dn-floating-controls")); +} + +export interface BuilderViewportToolControlsProps { + tool: BuilderToolMode; + sceneOptions: SceneOptionsState; + placementSurfaceById: Map; + onAddShapeAt: (target: BuilderPlacementTarget) => void; + onRemoveItem: (id: string) => void; + onDraggingChanged: (dragging: boolean) => void; +} + +export function BuilderViewportToolControls({ + tool, + sceneOptions, + placementSurfaceById, + onAddShapeAt, + onRemoveItem, + onDraggingChanged, +}: BuilderViewportToolControlsProps): null { + const { store, cameraElRef } = useCameraContext(); + const stateRef = useRef({ + tool, + sceneOptions, + placementSurfaceById, + onAddShapeAt, + onRemoveItem, + onDraggingChanged, + }); + stateRef.current = { + tool, + sceneOptions, + placementSurfaceById, + onAddShapeAt, + onRemoveItem, + onDraggingChanged, + }; + const downRef = useRef<{ x: number; y: number; target: EventTarget | null } | null>(null); + + useEffect(() => { + const cameraEl = cameraElRef.current; + if (!cameraEl) return; + + const projectAt = (clientX: number, clientY: number, planeWorldZ = 0): [number, number] | null => { + const opts = stateRef.current.sceneOptions; + return projectScreenToWorldGround({ + clientX, + clientY, + cameraEl, + sceneOptions: { ...opts, zoom: opts.zoom * LEGACY_ZOOM_COMPAT }, + autoCenterOffset: store.getState().autoCenterOffset, + planeWorldZ, + }); + }; + + const surfaceForTarget = (target: EventTarget | null): PlacementSurface | null => { + const el = target as Element | null; + const meshEl = el?.closest(".builder-placed") as HTMLElement | null; + const id = meshEl?.dataset.polyMeshId; + if (!id) return null; + return stateRef.current.placementSurfaceById.get(id) ?? null; + }; + + const onPointerDown = (event: PointerEvent): void => { + if (stateRef.current.tool === "move") return; + if (event.button !== 0 || event.isPrimary === false) return; + if (isUiOverlay(event.target)) return; + downRef.current = { x: event.clientX, y: event.clientY, target: event.target }; + }; + + const onClick = (event: MouseEvent): void => { + const state = stateRef.current; + if (state.tool === "move") return; + if (isUiOverlay(event.target)) return; + const down = downRef.current; + downRef.current = null; + if (down && Math.hypot(event.clientX - down.x, event.clientY - down.y) > 8) return; + + if (state.tool === "remove") { + const el = event.target as Element | null; + const meshEl = el?.closest(".builder-placed") as HTMLElement | null; + const id = meshEl?.dataset.polyMeshId; + if (!id) return; + event.preventDefault(); + event.stopPropagation(); + event.stopImmediatePropagation(); + state.onRemoveItem(id); + return; + } + + const face = paintLeafFace(event.target); + const surface = face !== "other" ? surfaceForTarget(event.target) : null; + let hit: [number, number] | null = null; + let surfaceWorldZ: number | null = null; + if (surface && face === "top") { + const projected = projectAt(event.clientX, event.clientY, surface.surfaceWorldZ); + if (!projected) return; + hit = clampHitToSurface(snapPlacementHit(projected, state.sceneOptions), surface, state.sceneOptions); + surfaceWorldZ = highestSurfaceWorldZAt( + hit[0], + hit[1], + surface, + state.placementSurfaceById, + state.sceneOptions.gridResolution, + ); + } else if (surface && face === "side") { + const projected = projectAt(event.clientX, event.clientY, surface.baseWorldZ); + if (!projected) return; + hit = computeSidePlacementTarget(projected, surface, state.sceneOptions); + surfaceWorldZ = surface.baseWorldZ; + } else { + const projected = projectAt(event.clientX, event.clientY); + if (!projected) return; + hit = snapPlacementHit(projected, state.sceneOptions); + } + event.preventDefault(); + event.stopPropagation(); + event.stopImmediatePropagation(); + state.onAddShapeAt({ + worldX: hit[0], + worldY: hit[1], + ...(surfaceWorldZ !== null ? { surfaceWorldZ } : null), + }); + }; + + cameraEl.addEventListener("pointerdown", onPointerDown, true); + cameraEl.addEventListener("click", onClick, true); + return () => { + cameraEl.removeEventListener("pointerdown", onPointerDown, true); + cameraEl.removeEventListener("click", onClick, true); + downRef.current = null; + stateRef.current.onDraggingChanged(false); + }; + }, [cameraElRef, store]); + + return null; +} diff --git a/website/src/components/BuilderWorkbench/components/scene/constants.ts b/website/src/components/BuilderWorkbench/components/scene/constants.ts new file mode 100644 index 00000000..f9eccfc4 --- /dev/null +++ b/website/src/components/BuilderWorkbench/components/scene/constants.ts @@ -0,0 +1,11 @@ +export const GROUND_FILL_COLORS = { + gray: "#f5f3ea", + dark: "#05070b", +} as const; + +// The Dock's camera slider feeds a unitless 0.05–2.5 zoom value (legacy +// CSS-scale semantics shared with the gallery). Post-parity the camera +// expects px-per-world-unit, so we multiply the slider value by BASE_TILE +// (50) before handing it to the camera, and divide it back before pushing +// updates into sceneOptions. Same shape as gallery's LEGACY_ZOOM_COMPAT. +export const LEGACY_ZOOM_COMPAT = 50; diff --git a/website/src/components/BuilderWorkbench/components/scene/placementSurface.ts b/website/src/components/BuilderWorkbench/components/scene/placementSurface.ts new file mode 100644 index 00000000..3253b644 --- /dev/null +++ b/website/src/components/BuilderWorkbench/components/scene/placementSurface.ts @@ -0,0 +1,208 @@ +import type { Polygon } from "@layoutit/polycss-react"; +import type { SceneOptionsState } from "../../../types"; +import { meshBbox } from "../../geometry/meshBbox"; +import { snapWorldToCellCenter } from "../../geometry/snap"; +import type { PlacedItem } from "../../types"; + +export interface PlacementSurface { + baseWorldZ: number; + surfaceWorldZ: number; + minWorldX: number; + maxWorldX: number; + minWorldY: number; + maxWorldY: number; +} + +export type PaintLeafFace = "top" | "side" | "other"; + +// Post-parity `` is `T·R·S` pivoting at the local origin, +// so visible(v) = T + S·v (no rotation here — XY surfaces are axis-aligned). +// `position[2]` is the world-Z translate, so the visible bottom of a vertex +// at v.z = minZ sits at `position[2] + scale * minZ`. +export function selectedSurfaceWorldZ(item: PlacedItem): number { + if (!item.rawPolygons) return item.elevation ?? 0; + const bbox = meshBbox(item.rawPolygons); + const scale = Math.max(item.fitScale * item.scale, 0.0001); + return item.position[2] + scale * bbox.minZ; +} + +function itemTopSurfaceWorldZ(item: PlacedItem & { rawPolygons: Polygon[] }, polygons: Polygon[]): number { + const bbox = meshBbox(polygons); + const scale = Math.max(item.fitScale * item.scale, 0.0001); + return item.position[2] + scale * bbox.maxZ; +} + +function itemBaseSurfaceWorldZ(item: PlacedItem & { rawPolygons: Polygon[] }, polygons: Polygon[]): number { + const bbox = meshBbox(polygons); + const scale = Math.max(item.fitScale * item.scale, 0.0001); + return item.position[2] + scale * bbox.minZ; +} + +function transformNormalZ(transform: string): number | null { + const matrix3d = transform.match(/^matrix3d\((.+)\)$/); + if (matrix3d) { + const values = matrix3d[1].split(",").map((value) => Number(value.trim())); + if (values.length !== 16 || values.some((value) => !Number.isFinite(value))) return null; + const nx = values[8]; + const ny = values[9]; + const nz = values[10]; + const len = Math.hypot(nx, ny, nz); + return len > 0 ? nz / len : null; + } + + const matrix = transform.match(/^matrix\((.+)\)$/); + if (matrix) return 1; + return null; +} + +export function paintLeafFace(target: EventTarget | null): PaintLeafFace { + const el = target as Element | null; + const leaf = el?.closest("b,i,s,u") as HTMLElement | null; + if (!leaf || !leaf.closest(".builder-placed")) return "other"; + const normalZ = transformNormalZ(getComputedStyle(leaf).transform); + if (normalZ === null) return "other"; + if (normalZ > 0.5) return "top"; + if (Math.abs(normalZ) < 0.25) return "side"; + return "other"; +} + +export function placementSurfaceForItem( + item: PlacedItem & { rawPolygons: Polygon[] }, + polygons: Polygon[], +): PlacementSurface { + const bbox = meshBbox(polygons); + const scale = Math.max(item.fitScale * item.scale, 0.0001); + const rz = ((item.rotation[2] ?? 0) * Math.PI) / 180; + const cos = Math.cos(rz); + const sin = Math.sin(rz); + let minWorldX = Infinity; + let maxWorldX = -Infinity; + let minWorldY = Infinity; + let maxWorldY = -Infinity; + for (const [x, y] of [ + [bbox.minX, bbox.minY], + [bbox.maxX, bbox.minY], + [bbox.maxX, bbox.maxY], + [bbox.minX, bbox.maxY], + ] as const) { + const dx = (x - bbox.midX) * scale; + const dy = (y - bbox.midY) * scale; + const worldX = item.worldX + dx * cos - dy * sin; + const worldY = item.worldY + dx * sin + dy * cos; + minWorldX = Math.min(minWorldX, worldX); + maxWorldX = Math.max(maxWorldX, worldX); + minWorldY = Math.min(minWorldY, worldY); + maxWorldY = Math.max(maxWorldY, worldY); + } + return { + baseWorldZ: itemBaseSurfaceWorldZ(item, polygons), + surfaceWorldZ: itemTopSurfaceWorldZ(item, polygons), + minWorldX, + maxWorldX, + minWorldY, + maxWorldY, + }; +} + +export function snapPlacementHit( + hit: [number, number], + options: Pick, +): [number, number] { + if (!options.snapToGrid || options.gridResolution <= 0) return hit; + return snapWorldToCellCenter(hit[0], hit[1], options.gridResolution); +} + +export function clampHitToSurface( + hit: [number, number], + surface: PlacementSurface, + options: Pick, +): [number, number] { + if (!options.snapToGrid || options.gridResolution <= 0) { + return [ + Math.min(surface.maxWorldX, Math.max(surface.minWorldX, hit[0])), + Math.min(surface.maxWorldY, Math.max(surface.minWorldY, hit[1])), + ]; + } + + const step = options.gridResolution; + const minCenterX = surface.minWorldX + step / 2; + const maxCenterX = surface.maxWorldX - step / 2; + const minCenterY = surface.minWorldY + step / 2; + const maxCenterY = surface.maxWorldY - step / 2; + const centerX = (surface.minWorldX + surface.maxWorldX) / 2; + const centerY = (surface.minWorldY + surface.maxWorldY) / 2; + return [ + minCenterX <= maxCenterX + ? Math.min(maxCenterX, Math.max(minCenterX, hit[0])) + : centerX, + minCenterY <= maxCenterY + ? Math.min(maxCenterY, Math.max(minCenterY, hit[1])) + : centerY, + ]; +} + +export function highestSurfaceWorldZAt( + worldX: number, + worldY: number, + fallback: PlacementSurface, + placementSurfaceById: ReadonlyMap, + gridResolution: number, +): number { + const epsilon = Math.max(0.001, gridResolution * 0.01); + let top = fallback.surfaceWorldZ; + for (const surface of placementSurfaceById.values()) { + if ( + worldX >= surface.minWorldX - epsilon && + worldX <= surface.maxWorldX + epsilon && + worldY >= surface.minWorldY - epsilon && + worldY <= surface.maxWorldY + epsilon + ) { + top = Math.max(top, surface.surfaceWorldZ); + } + } + return top; +} + +export function computeSidePlacementTarget( + hit: [number, number], + surface: PlacementSurface, + options: Pick, +): [number, number] { + const step = options.gridResolution > 0 + ? options.gridResolution + : Math.max(surface.maxWorldX - surface.minWorldX, surface.maxWorldY - surface.minWorldY, 1); + const centerX = (surface.minWorldX + surface.maxWorldX) / 2; + const centerY = (surface.minWorldY + surface.maxWorldY) / 2; + const snapped = options.snapToGrid && options.gridResolution > 0 + ? snapWorldToCellCenter(hit[0], hit[1], step) + : hit; + const minCenterX = surface.minWorldX + step / 2; + const maxCenterX = surface.maxWorldX - step / 2; + const minCenterY = surface.minWorldY + step / 2; + const maxCenterY = surface.maxWorldY - step / 2; + const clampX = (value: number): number => + minCenterX <= maxCenterX + ? Math.min(maxCenterX, Math.max(minCenterX, value)) + : centerX; + const clampY = (value: number): number => + minCenterY <= maxCenterY + ? Math.min(maxCenterY, Math.max(minCenterY, value)) + : centerY; + const sides = [ + { axis: "x" as const, sign: -1 as const, distance: Math.abs(hit[0] - surface.minWorldX) }, + { axis: "x" as const, sign: 1 as const, distance: Math.abs(hit[0] - surface.maxWorldX) }, + { axis: "y" as const, sign: -1 as const, distance: Math.abs(hit[1] - surface.minWorldY) }, + { axis: "y" as const, sign: 1 as const, distance: Math.abs(hit[1] - surface.maxWorldY) }, + ].sort((a, b) => a.distance - b.distance); + const side = sides[0]; + if (side.axis === "x") { + return [ + side.sign < 0 ? surface.minWorldX - step / 2 : surface.maxWorldX + step / 2, + clampY(snapped[1]), + ]; + } + return [ + clampX(snapped[0]), + side.sign < 0 ? surface.minWorldY - step / 2 : surface.maxWorldY + step / 2, + ]; +} diff --git a/website/src/components/GalleryWorkbench/GalleryWorkbench.tsx b/website/src/components/GalleryWorkbench/GalleryWorkbench.tsx index eaf26392..b9cd28d6 100644 --- a/website/src/components/GalleryWorkbench/GalleryWorkbench.tsx +++ b/website/src/components/GalleryWorkbench/GalleryWorkbench.tsx @@ -1,96 +1,39 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from "react"; -import type { - PolyMeshHandle as ReactPolyMeshHandle, - Polygon, - Vec3 as ReactVec3, -} from "@layoutit/polycss-react"; -import type { - PolyMeshHandle as VanillaPolyMeshHandle, -} from "@layoutit/polycss"; -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"; -import { - Dock, - DockModel, - DockRendering, - DockAnimation, - DockInteraction, - DockCamera, - DockLighting, - DockMaterials, -} from "../Dock"; +import { useCallback, useEffect, useRef, useState } from "react"; import { ModelsSidebar } from "../ModelsSidebar"; -import { DropOverlay } from "../DropOverlay"; import { StatsOverlay } from "../StatsOverlay"; -import { openCodePen } from "../helpers/codePen"; -import { - activeMeshResolution, - POLYCSS_DEFAULT_PERSPECTIVE, - type GizmoMode, - type SceneOptionsState, - type DomMetrics, -} from "../types"; +import { activeMeshResolution, type SceneOptionsState } from "../types"; import "./gallery-workbench.css"; -import type { - PresetModel, - LoadedModel, - ParserOptionsState, -} from "./types"; -import { - PRESETS, - GALLERY_BUCKET_ORDER, - galleryBucketForPreset, - galleryBucketRank, -} from "./presets"; -import { - EMPTY_METRICS, - measureDom, -} from "./helpers/domMetrics"; +import type { LoadedModel, ParserOptionsState, PresetModel } from "./types"; import { 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 { - dedupeAnimationClips, - displayAnimationName, - firstSelectableAnimationValue, - hasAnimationValue, -} from "./helpers/animationClips"; +import { firstSelectableAnimationValue, hasAnimationValue } from "./helpers/animationClips"; import { useDroppedFiles, usePresetLoader, - useScenePolygons, - useAnimationFrames, useRouteSync, - useGuiCameraSync, setRoutePresetId, setRouteSceneOptions, clearRouteSceneOptions, routeInitialSceneOptions, routeHasSceneOptions, } from "./hooks"; -import { useLightRotationDrag, useResponsiveViewportZoomScale } from "./hooks/useLightRotationDrag"; +import { useLightRotationDrag } from "./hooks/useLightRotationDrag"; import { useFpvHost } from "../fpv"; - -type MobileGalleryPanel = "models" | "controls" | null; +import { useModelPicker } from "./components/useModelPicker"; +import { useMeshInteraction } from "./components/useMeshInteraction"; +import { useViewportController } from "./components/useViewportController"; +import { useGalleryRenderPipeline } from "./components/useGalleryRenderPipeline"; +import { useMaterialInspector } from "./components/useMaterialInspector"; +import { GalleryViewport } from "./components/GalleryViewport"; +import { GalleryDock } from "./components/GalleryDock"; +import { GalleryMobileTabs, type MobileGalleryPanel } from "./components/GalleryMobileTabs"; export default function GalleryWorkbench() { const [initialPreset] = useState(resolveInitialPreset); @@ -106,70 +49,15 @@ export default function GalleryWorkbench() { const [loadError, setLoadError] = useState(null); const [loading, setLoading] = useState(false); const [selectedAnimation, setSelectedAnimation] = useState(""); - const [metrics, setMetrics] = useState(EMPTY_METRICS); - const [modelSearch, setModelSearch] = useState(""); - const [openModelCategory, setOpenModelCategory] = useState(null); const [mobilePanel, setMobilePanel] = useState(null); - const [codePenState, setCodePenState] = useState<"idle" | "exporting">("idle"); - const [codePenError, setCodePenError] = useState(null); - const viewportRef = useRef(null); const autoZoomPresetRef = useRef(initialRouteHasSceneOptions ? initialPreset.id : null); const autoAmbientPresetRef = useRef(initialRouteHasSceneOptions ? initialPreset.id : null); const autoKeyPresetRef = useRef(initialRouteHasSceneOptions ? initialPreset.id : null); const loadedModelKeyRef = useRef(null); - - // Selection + drag state for the React renderer's wrapper. - // Lives at this level so a model swap can reset both — the gizmo - // shouldn't follow a stale handle, and a freshly loaded mesh should - // sit at its authored origin. - const meshRef = useRef(null); - const [meshPosition, setMeshPosition] = useState([0, 0, 0]); - const [meshRotation, setMeshRotation] = useState([0, 0, 0]); - const [gizmoMode, setGizmoMode] = useState("translate"); - const [selectedMeshes, setSelectedMeshes] = useState([]); - // Mirror of PolyTransformControls' drag state — three.js convention is to - // disable OrbitControls while a transform gizmo is being dragged so - // the camera doesn't co-rotate. Same idea here: gate PolyOrbitControls' - // drag/wheel on this flag. - const [gizmoDragging, setGizmoDragging] = useState(false); - // Hover state for the mesh — wired the r3f / three.js way via - // onPointerOver / onPointerOut on . Demonstrates the - // mesh-event API (events.ts → InteractionProps) — same shape as - // r3f, no raycasting needed because PolyCSS uses DOM events. - const [hoveredMeshId, setHoveredMeshId] = useState(null); - // Mesh handle for the currently rendered model (vanilla path only). The - // Inspector folder uses this to push color-group edits back into the - // scene via setPolygons. Set by VanillaScene's onMeshHandleChange. - const activeMeshHandleRef = useRef(null); - const transientSceneHandleRef = useRef(null); - const [materialEditVersion, setMaterialEditVersion] = useState(0); - // Vanilla selection state — kept separate from React's - // `selectedMeshes` because vanilla MeshHandles aren't comparable to - // React PolyMeshHandles. Stored as IDs since that's what both paths - // can agree on for the toolbar display. - const [, setVanillaSelectedIds] = useState([]); - const sceneOptionsRef = useRef(sceneOptions); - sceneOptionsRef.current = sceneOptions; - const domRefreshRafRef = useRef(0); const sceneRouteTouchedRef = useRef(false); const [sceneRouteRevision, setSceneRouteRevision] = useState(0); - const requestGalleryDomRefresh = useCallback(() => { - if (domRefreshRafRef.current) return; - domRefreshRafRef.current = requestAnimationFrame(() => { - domRefreshRafRef.current = 0; - const root = viewportRef.current; - if (!root) return; - applyGalleryDebugDom(root, sceneOptionsRef.current); - setMetrics(measureDom(root)); - }); - }, []); - - useEffect(() => { - return () => { - if (domRefreshRafRef.current) cancelAnimationFrame(domRefreshRafRef.current); - }; - }, []); + const interaction = useMeshInteraction(loaded?.label); const markSceneRouteDirty = useCallback(() => { sceneRouteTouchedRef.current = true; @@ -180,40 +68,13 @@ export default function GalleryWorkbench() { markSceneRouteDirty(); setSceneOptions((current) => ({ ...current, ...partial })); }, [markSceneRouteDirty]); - const responsiveZoomScale = useResponsiveViewportZoomScale(viewportRef); - const canPreviewSceneOptions = useCallback( - (options: SceneOptionsState) => - options.renderer === "vanilla" && transientSceneHandleRef.current !== null, - [], - ); - const previewSceneOptions = useCallback((options: SceneOptionsState) => { - const previewShadow = responsiveZoomScale >= 0.995 || options.textureLighting === "dynamic"; - transientSceneHandleRef.current?.applyLightOptions({ - ...options, - shadowMaxExtend: responsiveShadowPreviewMaxExtend(options.shadowMaxExtend, responsiveZoomScale), - }, { shadow: previewShadow }); - }, [responsiveZoomScale]); - const { handleCameraChange } = useGuiCameraSync({ setSceneOptions }); - const renderSceneOptions = useMemo(() => { - const shadowMaxExtend = responsiveShadowMaxExtend(sceneOptions.shadowMaxExtend, responsiveZoomScale); - if (responsiveZoomScale === 1 && shadowMaxExtend === sceneOptions.shadowMaxExtend) return sceneOptions; - return { - ...sceneOptions, - zoom: sceneOptions.zoom * responsiveZoomScale, - shadowMaxExtend, - }; - }, [sceneOptions, responsiveZoomScale]); - const handleRenderCameraChange = useCallback( - (camera: { rotX: number; rotY: number; zoom: number; target?: ReactVec3 }) => { - markSceneRouteDirty(); - handleCameraChange({ - ...camera, - zoom: camera.zoom / Math.max(responsiveZoomScale, 0.001), - }); - }, - [handleCameraChange, markSceneRouteDirty, responsiveZoomScale], - ); + const viewport = useViewportController({ + sceneOptions, + setSceneOptions, + transientSceneHandleRef: interaction.transientSceneHandleRef, + markSceneRouteDirty, + }); const dropped = useDroppedFiles({ onDroppedSource: (source) => { @@ -238,17 +99,17 @@ export default function GalleryWorkbench() { onDropError: (message) => setLoadError(message), }); - const availablePresets = useMemo( - () => dropped.droppedSource ? [dropped.droppedSource.preset, ...PRESETS] : PRESETS, - [dropped.droppedSource], - ); - const pickerItems = useMemo( - () => dropped.droppedSource ? [presetPickerItem(dropped.droppedSource.preset, true), ...PRESET_PICKER_ITEMS] : PRESET_PICKER_ITEMS, - [dropped.droppedSource], - ); - const selectedPreset = availablePresets.find((preset) => preset.id === presetId) ?? PRESETS[0]; - const selectedDroppedSource = dropped.droppedSource?.id === selectedPreset.id ? dropped.droppedSource : null; - const selectedSceneDefaults = useMemo(() => sceneDefaultsFor(selectedPreset), [selectedPreset]); + const modelPicker = useModelPicker({ + presetId, + droppedSource: dropped.droppedSource, + }); + const { + availablePresets, + selectedPreset, + selectedDroppedSource, + selectedSceneDefaults, + } = modelPicker; + const loadMeshResolution = activeMeshResolution(sceneOptions.meshResolution); const handleLoaded = useCallback((model: LoadedModel) => { const modelKey = selectedPreset.id; @@ -262,61 +123,6 @@ export default function GalleryWorkbench() { return first; }); }, [selectedPreset.id]); - const selectedPresetPickerCategory = - pickerItems.find((preset) => preset.id === selectedPreset.id)?.category ?? - galleryBucketForPreset(selectedPreset); - const trimmedModelSearch = modelSearch.trim().toLowerCase(); - const filteredPresetItems = useMemo(() => { - if (!trimmedModelSearch) return pickerItems; - return pickerItems.filter((preset) => - preset.searchText.includes(trimmedModelSearch), - ); - }, [pickerItems, trimmedModelSearch]); - const modelCategories = useMemo(() => { - const buckets = new Map(); - if (!trimmedModelSearch) { - for (const category of GALLERY_BUCKET_ORDER) { - buckets.set(category, { id: category, label: category, models: [] as typeof PRESET_PICKER_ITEMS }); - } - } - for (const preset of filteredPresetItems) { - const category = preset.category || "Other"; - if (!buckets.has(category)) { - buckets.set(category, { id: category, label: category, models: [] as typeof PRESET_PICKER_ITEMS }); - } - buckets.get(category)!.models.push(preset); - } - const orderedCategories = Array.from(buckets.values()).sort((a, b) => - galleryBucketRank(a.id) - galleryBucketRank(b.id) - ); - for (const category of orderedCategories) { - category.models.sort((a, b) => a.label.localeCompare(b.label)); - } - return orderedCategories; - }, [filteredPresetItems, trimmedModelSearch]); - const defaultCategoryId = modelCategories.find((category) => category.models.length > 0)?.id ?? modelCategories[0]?.id; - const isCategoryOpen = useCallback( - (categoryId: string): boolean => { - if (trimmedModelSearch) return true; - if (openModelCategory !== null) return categoryId === openModelCategory; - return categoryId === selectedPresetPickerCategory || categoryId === defaultCategoryId; - }, - [trimmedModelSearch, openModelCategory, selectedPresetPickerCategory, defaultCategoryId], - ); - const handleToggleCategory = useCallback((categoryId: string) => { - setOpenModelCategory((prev) => (prev === categoryId ? null : categoryId)); - }, []); - const modelTreeId = useMemo(() => { - const slug = (value: string) => value.toLowerCase().replace(/[^a-z0-9]+/gi, "-").replace(/(^-|-$)/g, ""); - return modelCategories.map((category) => `debug-model-cat-${slug(category.id) || "category"}`); - }, [modelCategories]); - - useEffect(() => { - if (trimmedModelSearch) { - return; - } - setOpenModelCategory((prev) => (prev === selectedPresetPickerCategory ? prev : selectedPresetPickerCategory)); - }, [trimmedModelSearch, selectedPresetPickerCategory]); usePresetLoader({ selectedPreset, @@ -347,117 +153,32 @@ export default function GalleryWorkbench() { autoKeyPresetRef, }); - // Drop selection + reset gizmo position when the model changes. The - // PolyMesh wrapper persists across model swaps, so without this the - // user would inherit the previous model's drag offset. - useEffect(() => { - setSelectedMeshes([]); - setVanillaSelectedIds([]); - setMeshPosition([0, 0, 0]); - setMeshRotation([0, 0, 0]); - }, [loaded?.label]); - - const directionalLight = useMemo( - () => directionalFromOptions(sceneOptions), - [ - sceneOptions.lightAzimuth, - sceneOptions.lightElevation, - sceneOptions.lightColor, - sceneOptions.lightIntensity, - ], - ); - const ambientLight = useMemo( - () => ambientFromOptions(sceneOptions), - [sceneOptions.ambientColor, sceneOptions.ambientIntensity], - ); - const textureQuality = sceneOptions.textureQuality; - - const animationClips = loaded?.animation?.clips ?? []; - const selectableAnimationClips = useMemo( - () => dedupeAnimationClips(animationClips), - [animationClips], - ); - const activeAnimation = useMemo( - () => animationClips.find((clip) => String(clip.index) === selectedAnimation) ?? null, - [animationClips, selectedAnimation], - ); - const hasActiveAnimation = activeAnimation !== null; - const effectiveMeshResolution = activeMeshResolution(sceneOptions.meshResolution); - const renderLoaded = useMemo(() => { - if (!loaded || !activeAnimation || effectiveMeshResolution !== "lossy") return loaded; - const optimized = optimizeAnimatedMeshPolygons(loaded.parseResult, { - meshResolution: effectiveMeshResolution, - }); - if (optimized === loaded.parseResult) return loaded; - return { - ...loaded, - parseResult: optimized, - rawPolygons: optimized.polygons, - polygons: optimized.polygons, - animation: optimized.animation, - }; - }, [loaded, activeAnimation, effectiveMeshResolution]); - - const animation = useAnimationFrames({ - loaded: renderLoaded, - activeAnimation, - renderer: sceneOptions.renderer, - animationPaused: sceneOptions.animationPaused, - animationTimeScale: sceneOptions.animationTimeScale, - reactMeshRef: meshRef, + const pipeline = useGalleryRenderPipeline({ + loaded, + selectedAnimation, + sceneOptions, + defaultColor: parserOptions.defaultColor, + metricsSprites: viewport.metrics.sprites, + meshRef: interaction.meshRef, }); - const { - modelPolygons, - interiorShellPolygons, - scenePolygons, - helperScale, - helperTarget, - } = useScenePolygons({ - loaded: renderLoaded, - hasActiveAnimation, - meshResolution: sceneOptions.meshResolution, - renderer: sceneOptions.renderer, - reactAnimatedPolygons: animation.reactAnimatedPolygons, - interiorFill: sceneOptions.interiorFill, - }); useLightRotationDrag( - viewportRef, - renderSceneOptions, - helperScale, - helperTarget, - gizmoDragging, + viewport.viewportRef, + viewport.renderSceneOptions, + pipeline.helperScale, + pipeline.helperTarget, + interaction.gizmoDragging, updateScene, - canPreviewSceneOptions, - previewSceneOptions, - ); - const renderModelPolygons = useMemo( - () => sceneOptions.solidMaterials - ? withSolidMaterials(modelPolygons, parserOptions.defaultColor) - : modelPolygons, - [modelPolygons, sceneOptions.solidMaterials, parserOptions.defaultColor], - ); - const hasSpriteLeaves = useMemo( - () => metrics.sprites > 0 || scenePolygons.some(polygonHasTextureData), - [metrics.sprites, scenePolygons], + viewport.canPreviewSceneOptions, + viewport.previewSceneOptions, ); - const vanillaAnimationFrameFactory = useMemo(() => { - if (!animation.vanillaAnimationFrameFactory) return undefined; - if (!sceneOptions.solidMaterials) return animation.vanillaAnimationFrameFactory; - return (timeSeconds: number) => - withSolidMaterials(animation.vanillaAnimationFrameFactory!(timeSeconds), parserOptions.defaultColor); - }, [ - animation.vanillaAnimationFrameFactory, - sceneOptions.solidMaterials, - parserOptions.defaultColor, - ]); useFpvHost({ dragMode: sceneOptions.dragMode, autoCenter: sceneOptions.autoCenter, perspective: sceneOptions.perspective, rotY: sceneOptions.rotY, - scenePolygons, + scenePolygons: pipeline.scenePolygons, updateScene, }); @@ -470,7 +191,7 @@ export default function GalleryWorkbench() { setPresetId(id); if (loadedModelKeyRef.current !== id) loadedModelKeyRef.current = null; setSelectedAnimation(""); - animation.setReactAnimatedPolygons(null); + pipeline.setReactAnimatedPolygons(null); if (!next) return; if (options.updateRoute) { if (dropped.droppedSource?.id === next.id) setRoutePresetId(null); @@ -485,7 +206,7 @@ export default function GalleryWorkbench() { rotX: next.rotX ?? current.rotX, rotY: next.rotY ?? current.rotY, })); - }, [availablePresets, dropped.droppedSource, animation.setReactAnimatedPolygons, markSceneRouteDirty]); + }, [availablePresets, dropped.droppedSource, pipeline.setReactAnimatedPolygons, markSceneRouteDirty]); const handleRandomPreset = useCallback(() => { const next = randomPreset(); @@ -498,37 +219,6 @@ export default function GalleryWorkbench() { setMobilePanel(null); }, [resetToPreset]); - const handleOpenCodePen = useCallback(async () => { - const viewport = viewportRef.current; - if (!viewport || codePenState === "exporting") return; - setCodePenState("exporting"); - setCodePenError(null); - try { - const html = await exportPolySceneSnapshot(viewport); - openCodePen( - html, - `PolyCSS Gallery - ${loaded?.label ?? selectedPreset.label}`, - "_blank", - ); - } catch (error) { - const message = error instanceof Error - ? error.message - : "Could not create a CodePen snapshot."; - setCodePenError(message); - } finally { - setCodePenState("idle"); - } - }, [codePenState, loaded?.label, selectedPreset.label]); - - useEffect(() => { - if (!mobilePanel) return; - const handleKeyDown = (event: KeyboardEvent) => { - if (event.key === "Escape") setMobilePanel(null); - }; - window.addEventListener("keydown", handleKeyDown); - return () => window.removeEventListener("keydown", handleKeyDown); - }, [mobilePanel]); - useRouteSync({ presetId, presetIds: ALL_PRESET_IDS, @@ -556,114 +246,12 @@ export default function GalleryWorkbench() { selectedSceneDefaults, ]); - useEffect(() => { - requestGalleryDomRefresh(); - }, [ - requestGalleryDomRefresh, - sceneOptions.matrixPrecision, - sceneOptions.borderShapePrecision, - ]); - - const rendererDebugKey = useMemo( - () => [ - sceneOptions.renderer, - sceneOptions.matrixPrecision, - sceneOptions.borderShapePrecision, - sceneOptions.textureLighting, - sceneOptions.textureQuality, - sceneOptions.solidMaterials ? "solid-materials" : "authored-materials", - sceneOptions.meshResolution, - sceneOptions.interiorFill ? "interior-fill" : "no-interior-fill", - sceneOptions.autoCenter, - sceneOptions.perspective === false ? "none" : sceneOptions.perspective, - loaded?.label ?? "none", - ].join(":"), - [ - sceneOptions.renderer, - sceneOptions.matrixPrecision, - sceneOptions.borderShapePrecision, - sceneOptions.textureLighting, - sceneOptions.textureQuality, - sceneOptions.solidMaterials, - sceneOptions.meshResolution, - sceneOptions.interiorFill, - sceneOptions.autoCenter, - sceneOptions.perspective, - loaded?.label, - ], - ); - - const animationOptions = useMemo(() => { - const options: Record = { None: "" }; - for (const clip of selectableAnimationClips) { - options[`${displayAnimationName(clip.name)} (${clip.duration.toFixed(2)}s)`] = String(clip.index); - } - return options; - }, [selectableAnimationClips]); - const perspectiveMode = sceneOptions.perspective === false ? "orthographic" : "perspective"; - const perspectivePx = typeof sceneOptions.perspective === "number" - ? sceneOptions.perspective - : POLYCSS_DEFAULT_PERSPECTIVE; - - // Materials data — grouped by mesh, then by canonical polygon color. - const inspectorMeshes = useMemo(() => { - if (renderModelPolygons.length === 0) return []; - const colorGroups = new Map(); - const textured: Polygon[] = []; - for (const p of renderModelPolygons) { - if (polygonHasTexturePaint(p)) { - textured.push(p); - continue; - } - if (!p.color) continue; - const key = inspectorColorKey(p.color); - let arr = colorGroups.get(key); - if (!arr) { - arr = []; - colorGroups.set(key, arr); - } - arr.push(p); - } - if (colorGroups.size === 0 && textured.length === 0) return []; - const sortedColors = [...colorGroups.entries()] - .sort((a, b) => compareInspectorColors(a[0], b[0]) || b[1].length - a[1].length) - .map(([color, polys]) => ({ - color, - count: polys.length, - editable: true, - polygons: polys, - })); - const groups: InspectorColorGroup[] = sortedColors; - if (textured.length > 0) { - groups.push({ - color: "textured", - count: textured.length, - editable: false, - polygons: textured, - }); - } - const label = loaded?.label ?? "model"; - return [{ id: label, label, groups }]; - }, [renderModelPolygons, loaded?.label, materialEditVersion]); - - const handleInspectorColorChange = useCallback( - ( - _mesh: InspectorMesh, - group: InspectorColorGroup, - next: string, - ) => { - for (const p of group.polygons) p.color = next; - const handle = activeMeshHandleRef.current; - // Pass the *source* polygons (pre-merge) — the renderer holds a - // merged copy that doesn't see in-place edits. setPolygons without - // an explicit merge flag reuses the mesh's current merge setting - // (true for static models, false during animation playback). - if (handle) handle.setPolygons(renderModelPolygons); - requestGalleryDomRefresh(); - setMaterialEditVersion((version) => version + 1); - }, - [renderModelPolygons, requestGalleryDomRefresh], - ); + const { inspectorMeshes, handleInspectorColorChange } = useMaterialInspector({ + renderModelPolygons: pipeline.renderModelPolygons, + loadedLabel: loaded?.label, + activeMeshHandleRef: interaction.activeMeshHandleRef, + requestGalleryDomRefresh: viewport.requestGalleryDomRefresh, + }); return ( ); } diff --git a/website/src/components/GalleryWorkbench/components/GalleryDock.tsx b/website/src/components/GalleryWorkbench/components/GalleryDock.tsx new file mode 100644 index 00000000..b5354f78 --- /dev/null +++ b/website/src/components/GalleryWorkbench/components/GalleryDock.tsx @@ -0,0 +1,173 @@ +import { useMemo } from "react"; +import type { Polygon } from "@layoutit/polycss-react"; +import type { InspectorColorGroup, InspectorMesh } from "../../Inspector"; +import { + Dock, + DockModel, + DockRendering, + DockAnimation, + DockInteraction, + DockCamera, + DockLighting, + DockMaterials, +} from "../../Dock"; +import { + POLYCSS_DEFAULT_PERSPECTIVE, + type DomMetrics, + type GizmoMode, + type SceneOptionsState, +} from "../../types"; +import type { LoadedModel, PresetModel } from "../types"; +import { defaultZoomForModel } from "../helpers/smartDefaults"; +import { displayAnimationName } from "../helpers/animationClips"; + +export interface GalleryDockProps { + className?: string; + loading: boolean; + metrics: DomMetrics; + sceneOptions: SceneOptionsState; + inspectorMeshes: InspectorMesh[]; + onInspectorColorChange: (mesh: InspectorMesh, group: InspectorColorGroup, next: string) => void; + hasActiveAnimation: boolean; + hasSpriteLeaves: boolean; + selectedAnimation: string; + selectableAnimationClips: ReadonlyArray<{ index: number; name: string; duration: number }>; + onAnimationChange: (value: string) => void; + onResetAnimatedPolygons: () => void; + onSelectAnimationClear: () => void; + gizmoMode: GizmoMode; + onGizmoModeChange: (mode: GizmoMode) => void; + loaded: LoadedModel | null; + selectedPreset: PresetModel; + onUpdateScene: (partial: Partial) => void; +} + +export function GalleryDock({ + className, + loading, + metrics, + sceneOptions, + inspectorMeshes, + onInspectorColorChange, + hasActiveAnimation, + hasSpriteLeaves, + selectedAnimation, + selectableAnimationClips, + onAnimationChange, + onResetAnimatedPolygons, + onSelectAnimationClear, + gizmoMode, + onGizmoModeChange, + loaded, + selectedPreset, + onUpdateScene, +}: GalleryDockProps) { + const animationOptions = useMemo(() => { + const options: Record = { None: "" }; + for (const clip of selectableAnimationClips) { + options[`${displayAnimationName(clip.name)} (${clip.duration.toFixed(2)}s)`] = String(clip.index); + } + return options; + }, [selectableAnimationClips]); + + const perspectiveMode = sceneOptions.perspective === false ? "orthographic" : "perspective"; + const perspectivePx = typeof sceneOptions.perspective === "number" + ? sceneOptions.perspective + : POLYCSS_DEFAULT_PERSPECTIVE; + + return ( + + + + + + + defaultZoomForModel(preset as PresetModel, polys as Polygon[])} + onUpdateScene={onUpdateScene} + /> + + + ); +} diff --git a/website/src/components/GalleryWorkbench/components/GalleryMobileTabs.tsx b/website/src/components/GalleryWorkbench/components/GalleryMobileTabs.tsx new file mode 100644 index 00000000..7a158f85 --- /dev/null +++ b/website/src/components/GalleryWorkbench/components/GalleryMobileTabs.tsx @@ -0,0 +1,55 @@ +import { useEffect, type Dispatch, type SetStateAction } from "react"; + +export type MobileGalleryPanel = "models" | "controls" | null; + +export interface GalleryMobileTabsProps { + mobilePanel: MobileGalleryPanel; + onMobilePanelChange: Dispatch>; + onRandomPreset: () => void; +} + +export function GalleryMobileTabs({ + mobilePanel, + onMobilePanelChange, + onRandomPreset, +}: GalleryMobileTabsProps) { + useEffect(() => { + if (!mobilePanel) return; + const handleKeyDown = (event: KeyboardEvent) => { + if (event.key === "Escape") onMobilePanelChange(null); + }; + window.addEventListener("keydown", handleKeyDown); + return () => window.removeEventListener("keydown", handleKeyDown); + }, [mobilePanel, onMobilePanelChange]); + + return ( + + ); +} diff --git a/website/src/components/GalleryWorkbench/components/GalleryViewport.tsx b/website/src/components/GalleryWorkbench/components/GalleryViewport.tsx new file mode 100644 index 00000000..49cddfe7 --- /dev/null +++ b/website/src/components/GalleryWorkbench/components/GalleryViewport.tsx @@ -0,0 +1,180 @@ +import { useCallback, useState, type RefObject } from "react"; +import type { + PolyAmbientLight, + PolyDirectionalLight, + Polygon, + Vec3 as ReactVec3, +} from "@layoutit/polycss-react"; +import { exportPolySceneSnapshot, type TextureQuality } from "@layoutit/polycss"; +import { VanillaScene } from "../../VanillaScene"; +import { ReactScene } from "../../ReactScene"; +import { DropOverlay } from "../../DropOverlay"; +import { openCodePen } from "../../helpers/codePen"; +import type { SceneOptionsState } from "../../types"; +import type { LoadedModel } from "../types"; +import type { GalleryMeshInteraction } from "./useMeshInteraction"; + +export interface GalleryViewportProps { + viewportRef: RefObject; + sceneOptions: SceneOptionsState; + renderSceneOptions: SceneOptionsState; + rendererDebugKey: string; + renderModelPolygons: Polygon[]; + interiorShellPolygons: Polygon[]; + renderLoaded: LoadedModel | null; + loaded: LoadedModel | null; + selectedPresetLabel: string; + directionalLight: PolyDirectionalLight; + ambientLight: PolyAmbientLight; + textureQuality: TextureQuality; + helperScale: number; + helperTarget: ReactVec3; + hasActiveAnimation: boolean; + activeAnimation: { index: number; name: string; duration: number } | null; + selectedAnimation: string; + vanillaAnimationFrameFactory: ((timeSeconds: number) => Polygon[]) | undefined; + onSceneDomChange: () => void; + onCameraChange: (camera: { rotX: number; rotY: number; zoom: number; target?: ReactVec3 }) => void; + interaction: GalleryMeshInteraction; + loadError: string | null; + dropActive: boolean; +} + +export function GalleryViewport({ + viewportRef, + sceneOptions, + renderSceneOptions, + rendererDebugKey, + renderModelPolygons, + interiorShellPolygons, + renderLoaded, + loaded, + selectedPresetLabel, + directionalLight, + ambientLight, + textureQuality, + helperScale, + helperTarget, + hasActiveAnimation, + activeAnimation, + selectedAnimation, + vanillaAnimationFrameFactory, + onSceneDomChange, + onCameraChange, + interaction, + loadError, + dropActive, +}: GalleryViewportProps) { + const [codePenState, setCodePenState] = useState<"idle" | "exporting">("idle"); + const [codePenError, setCodePenError] = useState(null); + + const handleOpenCodePen = useCallback(async () => { + const viewport = viewportRef.current; + if (!viewport || codePenState === "exporting") return; + setCodePenState("exporting"); + setCodePenError(null); + try { + const html = await exportPolySceneSnapshot(viewport); + openCodePen( + html, + `PolyCSS Gallery - ${loaded?.label ?? selectedPresetLabel}`, + "_blank", + ); + } catch (error) { + const message = error instanceof Error + ? error.message + : "Could not create a CodePen snapshot."; + setCodePenError(message); + } finally { + setCodePenState("idle"); + } + }, [codePenState, loaded?.label, selectedPresetLabel, viewportRef]); + + return ( +
+
+ {sceneOptions.renderer === "vanilla" ? ( + { interaction.activeMeshHandleRef.current = h; }} + onTransientHandleChange={(h) => { interaction.transientSceneHandleRef.current = h; }} + /> + ) : ( + + )} + {loadError ? ( +
+ Import skipped + {loadError} +
+ ) : null} +
+ + {codePenError ? ( +
{codePenError}
+ ) : null} +
+
+ +
+ ); +} diff --git a/website/src/components/GalleryWorkbench/components/useGalleryRenderPipeline.ts b/website/src/components/GalleryWorkbench/components/useGalleryRenderPipeline.ts new file mode 100644 index 00000000..05412575 --- /dev/null +++ b/website/src/components/GalleryWorkbench/components/useGalleryRenderPipeline.ts @@ -0,0 +1,160 @@ +import { useMemo, type RefObject } from "react"; +import type { PolyMeshHandle as ReactPolyMeshHandle } from "@layoutit/polycss-react"; +import { optimizeAnimatedMeshPolygons } from "@layoutit/polycss"; +import { activeMeshResolution, type SceneOptionsState } from "../../types"; +import type { LoadedModel } from "../types"; +import { polygonHasTextureData, withSolidMaterials } from "../helpers/galleryDefaults"; +import { ambientFromOptions, directionalFromOptions } from "../helpers/lighting"; +import { dedupeAnimationClips } from "../helpers/animationClips"; +import { useAnimationFrames, useScenePolygons } from "../hooks"; + +export interface UseGalleryRenderPipelineOptions { + loaded: LoadedModel | null; + selectedAnimation: string; + sceneOptions: SceneOptionsState; + defaultColor: string; + metricsSprites: number; + meshRef: RefObject; +} + +export function useGalleryRenderPipeline({ + loaded, + selectedAnimation, + sceneOptions, + defaultColor, + metricsSprites, + meshRef, +}: UseGalleryRenderPipelineOptions) { + const directionalLight = useMemo( + () => directionalFromOptions(sceneOptions), + [ + sceneOptions.lightAzimuth, + sceneOptions.lightElevation, + sceneOptions.lightColor, + sceneOptions.lightIntensity, + ], + ); + const ambientLight = useMemo( + () => ambientFromOptions(sceneOptions), + [sceneOptions.ambientColor, sceneOptions.ambientIntensity], + ); + + const animationClips = loaded?.animation?.clips ?? []; + const selectableAnimationClips = useMemo( + () => dedupeAnimationClips(animationClips), + [animationClips], + ); + const activeAnimation = useMemo( + () => animationClips.find((clip) => String(clip.index) === selectedAnimation) ?? null, + [animationClips, selectedAnimation], + ); + const hasActiveAnimation = activeAnimation !== null; + const effectiveMeshResolution = activeMeshResolution(sceneOptions.meshResolution); + + const renderLoaded = useMemo(() => { + if (!loaded || !activeAnimation || effectiveMeshResolution !== "lossy") return loaded; + const optimized = optimizeAnimatedMeshPolygons(loaded.parseResult, { + meshResolution: effectiveMeshResolution, + }); + if (optimized === loaded.parseResult) return loaded; + return { + ...loaded, + parseResult: optimized, + rawPolygons: optimized.polygons, + polygons: optimized.polygons, + animation: optimized.animation, + }; + }, [loaded, activeAnimation, effectiveMeshResolution]); + + const animation = useAnimationFrames({ + loaded: renderLoaded, + activeAnimation, + renderer: sceneOptions.renderer, + animationPaused: sceneOptions.animationPaused, + animationTimeScale: sceneOptions.animationTimeScale, + reactMeshRef: meshRef, + }); + + const { + modelPolygons, + interiorShellPolygons, + scenePolygons, + helperScale, + helperTarget, + } = useScenePolygons({ + loaded: renderLoaded, + hasActiveAnimation, + meshResolution: sceneOptions.meshResolution, + renderer: sceneOptions.renderer, + reactAnimatedPolygons: animation.reactAnimatedPolygons, + interiorFill: sceneOptions.interiorFill, + }); + + const renderModelPolygons = useMemo( + () => sceneOptions.solidMaterials + ? withSolidMaterials(modelPolygons, defaultColor) + : modelPolygons, + [modelPolygons, sceneOptions.solidMaterials, defaultColor], + ); + const hasSpriteLeaves = useMemo( + () => metricsSprites > 0 || scenePolygons.some(polygonHasTextureData), + [metricsSprites, scenePolygons], + ); + const vanillaAnimationFrameFactory = useMemo(() => { + if (!animation.vanillaAnimationFrameFactory) return undefined; + if (!sceneOptions.solidMaterials) return animation.vanillaAnimationFrameFactory; + return (timeSeconds: number) => + withSolidMaterials(animation.vanillaAnimationFrameFactory!(timeSeconds), defaultColor); + }, [ + animation.vanillaAnimationFrameFactory, + sceneOptions.solidMaterials, + defaultColor, + ]); + + const rendererDebugKey = useMemo( + () => [ + sceneOptions.renderer, + sceneOptions.matrixPrecision, + sceneOptions.borderShapePrecision, + sceneOptions.textureLighting, + sceneOptions.textureQuality, + sceneOptions.solidMaterials ? "solid-materials" : "authored-materials", + sceneOptions.meshResolution, + sceneOptions.interiorFill ? "interior-fill" : "no-interior-fill", + sceneOptions.autoCenter, + sceneOptions.perspective === false ? "none" : sceneOptions.perspective, + loaded?.label ?? "none", + ].join(":"), + [ + sceneOptions.renderer, + sceneOptions.matrixPrecision, + sceneOptions.borderShapePrecision, + sceneOptions.textureLighting, + sceneOptions.textureQuality, + sceneOptions.solidMaterials, + sceneOptions.meshResolution, + sceneOptions.interiorFill, + sceneOptions.autoCenter, + sceneOptions.perspective, + loaded?.label, + ], + ); + + return { + directionalLight, + ambientLight, + selectableAnimationClips, + activeAnimation, + hasActiveAnimation, + renderLoaded, + setReactAnimatedPolygons: animation.setReactAnimatedPolygons, + renderModelPolygons, + interiorShellPolygons, + scenePolygons, + helperScale, + helperTarget, + hasSpriteLeaves, + vanillaAnimationFrameFactory, + rendererDebugKey, + }; +} diff --git a/website/src/components/GalleryWorkbench/components/useMaterialInspector.ts b/website/src/components/GalleryWorkbench/components/useMaterialInspector.ts new file mode 100644 index 00000000..20a09de9 --- /dev/null +++ b/website/src/components/GalleryWorkbench/components/useMaterialInspector.ts @@ -0,0 +1,89 @@ +import { useCallback, useMemo, useState, type RefObject } from "react"; +import type { Polygon } from "@layoutit/polycss-react"; +import { + normalizeSolidColorKey as inspectorColorKey, + type PolyMeshHandle as VanillaPolyMeshHandle, +} from "@layoutit/polycss"; +import type { InspectorColorGroup, InspectorMesh } from "../../Inspector"; +import { compareInspectorColors, polygonHasTexturePaint } from "../helpers/galleryDefaults"; + +export interface UseMaterialInspectorOptions { + renderModelPolygons: Polygon[]; + loadedLabel: string | undefined; + activeMeshHandleRef: RefObject; + requestGalleryDomRefresh: () => void; +} + +export function useMaterialInspector({ + renderModelPolygons, + loadedLabel, + activeMeshHandleRef, + requestGalleryDomRefresh, +}: UseMaterialInspectorOptions) { + const [materialEditVersion, setMaterialEditVersion] = useState(0); + + // Materials data — grouped by mesh, then by canonical polygon color. + const inspectorMeshes = useMemo(() => { + if (renderModelPolygons.length === 0) return []; + const colorGroups = new Map(); + const textured: Polygon[] = []; + for (const p of renderModelPolygons) { + if (polygonHasTexturePaint(p)) { + textured.push(p); + continue; + } + if (!p.color) continue; + const key = inspectorColorKey(p.color); + let arr = colorGroups.get(key); + if (!arr) { + arr = []; + colorGroups.set(key, arr); + } + arr.push(p); + } + if (colorGroups.size === 0 && textured.length === 0) return []; + const sortedColors = [...colorGroups.entries()] + .sort((a, b) => compareInspectorColors(a[0], b[0]) || b[1].length - a[1].length) + .map(([color, polys]) => ({ + color, + count: polys.length, + editable: true, + polygons: polys, + })); + const groups: InspectorColorGroup[] = sortedColors; + if (textured.length > 0) { + groups.push({ + color: "textured", + count: textured.length, + editable: false, + polygons: textured, + }); + } + const label = loadedLabel ?? "model"; + return [{ id: label, label, groups }]; + }, [renderModelPolygons, loadedLabel, materialEditVersion]); + + const handleInspectorColorChange = useCallback( + ( + _mesh: InspectorMesh, + group: InspectorColorGroup, + next: string, + ) => { + for (const p of group.polygons) p.color = next; + const handle = activeMeshHandleRef.current; + // Pass the *source* polygons (pre-merge) — the renderer holds a + // merged copy that doesn't see in-place edits. setPolygons without + // an explicit merge flag reuses the mesh's current merge setting + // (true for static models, false during animation playback). + if (handle) handle.setPolygons(renderModelPolygons); + requestGalleryDomRefresh(); + setMaterialEditVersion((version) => version + 1); + }, + [activeMeshHandleRef, renderModelPolygons, requestGalleryDomRefresh], + ); + + return { + inspectorMeshes, + handleInspectorColorChange, + }; +} diff --git a/website/src/components/GalleryWorkbench/components/useMeshInteraction.ts b/website/src/components/GalleryWorkbench/components/useMeshInteraction.ts new file mode 100644 index 00000000..40b79cf0 --- /dev/null +++ b/website/src/components/GalleryWorkbench/components/useMeshInteraction.ts @@ -0,0 +1,71 @@ +import { useEffect, useRef, useState } from "react"; +import type { + PolyMeshHandle as ReactPolyMeshHandle, + Vec3 as ReactVec3, +} from "@layoutit/polycss-react"; +import type { PolyMeshHandle as VanillaPolyMeshHandle } from "@layoutit/polycss"; +import type { VanillaSceneTransientHandle } from "../../VanillaScene"; +import type { GizmoMode } from "../../types"; + +export function useMeshInteraction(loadedLabel: string | undefined) { + // Selection + drag state for the React renderer's wrapper. + // Lives at this level so a model swap can reset both — the gizmo + // shouldn't follow a stale handle, and a freshly loaded mesh should + // sit at its authored origin. + const meshRef = useRef(null); + const [meshPosition, setMeshPosition] = useState([0, 0, 0]); + const [meshRotation, setMeshRotation] = useState([0, 0, 0]); + const [gizmoMode, setGizmoMode] = useState("translate"); + const [selectedMeshes, setSelectedMeshes] = useState([]); + // Mirror of PolyTransformControls' drag state — three.js convention is to + // disable OrbitControls while a transform gizmo is being dragged so + // the camera doesn't co-rotate. Same idea here: gate PolyOrbitControls' + // drag/wheel on this flag. + const [gizmoDragging, setGizmoDragging] = useState(false); + // Hover state for the mesh — wired the r3f / three.js way via + // onPointerOver / onPointerOut on . Demonstrates the + // mesh-event API (events.ts → InteractionProps) — same shape as + // r3f, no raycasting needed because PolyCSS uses DOM events. + const [hoveredMeshId, setHoveredMeshId] = useState(null); + // Mesh handle for the currently rendered model (vanilla path only). The + // Inspector folder uses this to push color-group edits back into the + // scene via setPolygons. Set by VanillaScene's onMeshHandleChange. + const activeMeshHandleRef = useRef(null); + const transientSceneHandleRef = useRef(null); + // Vanilla selection state — kept separate from React's + // `selectedMeshes` because vanilla MeshHandles aren't comparable to + // React PolyMeshHandles. Stored as IDs since that's what both paths + // can agree on for the toolbar display. + const [, setVanillaSelectedIds] = useState([]); + + // Drop selection + reset gizmo position when the model changes. The + // PolyMesh wrapper persists across model swaps, so without this the + // user would inherit the previous model's drag offset. + useEffect(() => { + setSelectedMeshes([]); + setVanillaSelectedIds([]); + setMeshPosition([0, 0, 0]); + setMeshRotation([0, 0, 0]); + }, [loadedLabel]); + + return { + meshRef, + meshPosition, + setMeshPosition, + meshRotation, + setMeshRotation, + gizmoMode, + setGizmoMode, + selectedMeshes, + setSelectedMeshes, + gizmoDragging, + setGizmoDragging, + hoveredMeshId, + setHoveredMeshId, + activeMeshHandleRef, + transientSceneHandleRef, + setVanillaSelectedIds, + }; +} + +export type GalleryMeshInteraction = ReturnType; diff --git a/website/src/components/GalleryWorkbench/components/useModelPicker.ts b/website/src/components/GalleryWorkbench/components/useModelPicker.ts new file mode 100644 index 00000000..e0b4953a --- /dev/null +++ b/website/src/components/GalleryWorkbench/components/useModelPicker.ts @@ -0,0 +1,109 @@ +import { useCallback, useEffect, useMemo, useState } from "react"; +import type { DroppedModelSource, PresetModel } from "../types"; +import { + PRESETS, + GALLERY_BUCKET_ORDER, + galleryBucketForPreset, + galleryBucketRank, +} from "../presets"; +import { + PRESET_PICKER_ITEMS, + presetPickerItem, + sceneDefaultsFor, +} from "../helpers/galleryDefaults"; + +export interface UseModelPickerOptions { + presetId: string; + droppedSource: DroppedModelSource | null; +} + +export function useModelPicker({ presetId, droppedSource }: UseModelPickerOptions) { + const [modelSearch, setModelSearch] = useState(""); + const [openModelCategory, setOpenModelCategory] = useState(null); + + const availablePresets = useMemo( + () => droppedSource ? [droppedSource.preset, ...PRESETS] : PRESETS, + [droppedSource], + ); + const pickerItems = useMemo( + () => droppedSource ? [presetPickerItem(droppedSource.preset, true), ...PRESET_PICKER_ITEMS] : PRESET_PICKER_ITEMS, + [droppedSource], + ); + const selectedPreset = availablePresets.find((preset) => preset.id === presetId) ?? PRESETS[0]; + const selectedDroppedSource = droppedSource?.id === selectedPreset.id ? droppedSource : null; + const selectedSceneDefaults = useMemo(() => sceneDefaultsFor(selectedPreset), [selectedPreset]); + const selectedPresetPickerCategory = + pickerItems.find((preset) => preset.id === selectedPreset.id)?.category ?? + galleryBucketForPreset(selectedPreset); + + const trimmedModelSearch = modelSearch.trim().toLowerCase(); + const filteredPresetItems = useMemo(() => { + if (!trimmedModelSearch) return pickerItems; + return pickerItems.filter((preset) => + preset.searchText.includes(trimmedModelSearch), + ); + }, [pickerItems, trimmedModelSearch]); + + const modelCategories = useMemo(() => { + const buckets = new Map(); + if (!trimmedModelSearch) { + for (const category of GALLERY_BUCKET_ORDER) { + buckets.set(category, { id: category, label: category, models: [] as typeof PRESET_PICKER_ITEMS }); + } + } + for (const preset of filteredPresetItems) { + const category = preset.category || "Other"; + if (!buckets.has(category)) { + buckets.set(category, { id: category, label: category, models: [] as typeof PRESET_PICKER_ITEMS }); + } + buckets.get(category)!.models.push(preset); + } + const orderedCategories = Array.from(buckets.values()).sort((a, b) => + galleryBucketRank(a.id) - galleryBucketRank(b.id) + ); + for (const category of orderedCategories) { + category.models.sort((a, b) => a.label.localeCompare(b.label)); + } + return orderedCategories; + }, [filteredPresetItems, trimmedModelSearch]); + + const defaultCategoryId = modelCategories.find((category) => category.models.length > 0)?.id ?? modelCategories[0]?.id; + + const isCategoryOpen = useCallback( + (categoryId: string): boolean => { + if (trimmedModelSearch) return true; + if (openModelCategory !== null) return categoryId === openModelCategory; + return categoryId === selectedPresetPickerCategory || categoryId === defaultCategoryId; + }, + [trimmedModelSearch, openModelCategory, selectedPresetPickerCategory, defaultCategoryId], + ); + + const handleToggleCategory = useCallback((categoryId: string) => { + setOpenModelCategory((prev) => (prev === categoryId ? null : categoryId)); + }, []); + + const modelTreeId = useMemo(() => { + const slug = (value: string) => value.toLowerCase().replace(/[^a-z0-9]+/gi, "-").replace(/(^-|-$)/g, ""); + return modelCategories.map((category) => `debug-model-cat-${slug(category.id) || "category"}`); + }, [modelCategories]); + + useEffect(() => { + if (trimmedModelSearch) { + return; + } + setOpenModelCategory((prev) => (prev === selectedPresetPickerCategory ? prev : selectedPresetPickerCategory)); + }, [trimmedModelSearch, selectedPresetPickerCategory]); + + return { + modelSearch, + setModelSearch, + availablePresets, + selectedPreset, + selectedDroppedSource, + selectedSceneDefaults, + modelCategories, + isCategoryOpen, + handleToggleCategory, + modelTreeId, + }; +} diff --git a/website/src/components/GalleryWorkbench/components/useViewportController.ts b/website/src/components/GalleryWorkbench/components/useViewportController.ts new file mode 100644 index 00000000..c956d136 --- /dev/null +++ b/website/src/components/GalleryWorkbench/components/useViewportController.ts @@ -0,0 +1,112 @@ +import { + useCallback, + useEffect, + useMemo, + useRef, + useState, + type Dispatch, + type RefObject, + type SetStateAction, +} from "react"; +import type { Vec3 as ReactVec3 } from "@layoutit/polycss-react"; +import type { VanillaSceneTransientHandle } from "../../VanillaScene"; +import type { DomMetrics, SceneOptionsState } from "../../types"; +import { EMPTY_METRICS, measureDom } from "../helpers/domMetrics"; +import { + applyGalleryDebugDom, + responsiveShadowMaxExtend, + responsiveShadowPreviewMaxExtend, +} from "../helpers/galleryDefaults"; +import { useGuiCameraSync } from "../hooks"; +import { useResponsiveViewportZoomScale } from "../hooks/useLightRotationDrag"; + +export interface UseViewportControllerOptions { + sceneOptions: SceneOptionsState; + setSceneOptions: Dispatch>; + transientSceneHandleRef: RefObject; + markSceneRouteDirty: () => void; +} + +export function useViewportController({ + sceneOptions, + setSceneOptions, + transientSceneHandleRef, + markSceneRouteDirty, +}: UseViewportControllerOptions) { + const viewportRef = useRef(null); + const [metrics, setMetrics] = useState(EMPTY_METRICS); + const sceneOptionsRef = useRef(sceneOptions); + sceneOptionsRef.current = sceneOptions; + const domRefreshRafRef = useRef(0); + + const requestGalleryDomRefresh = useCallback(() => { + if (domRefreshRafRef.current) return; + domRefreshRafRef.current = requestAnimationFrame(() => { + domRefreshRafRef.current = 0; + const root = viewportRef.current; + if (!root) return; + applyGalleryDebugDom(root, sceneOptionsRef.current); + setMetrics(measureDom(root)); + }); + }, []); + + useEffect(() => { + return () => { + if (domRefreshRafRef.current) cancelAnimationFrame(domRefreshRafRef.current); + }; + }, []); + + useEffect(() => { + requestGalleryDomRefresh(); + }, [ + requestGalleryDomRefresh, + sceneOptions.matrixPrecision, + sceneOptions.borderShapePrecision, + ]); + + const responsiveZoomScale = useResponsiveViewportZoomScale(viewportRef); + const canPreviewSceneOptions = useCallback( + (options: SceneOptionsState) => + options.renderer === "vanilla" && transientSceneHandleRef.current !== null, + [transientSceneHandleRef], + ); + const previewSceneOptions = useCallback((options: SceneOptionsState) => { + const previewShadow = responsiveZoomScale >= 0.995 || options.textureLighting === "dynamic"; + transientSceneHandleRef.current?.applyLightOptions({ + ...options, + shadowMaxExtend: responsiveShadowPreviewMaxExtend(options.shadowMaxExtend, responsiveZoomScale), + }, { shadow: previewShadow }); + }, [responsiveZoomScale, transientSceneHandleRef]); + + const { handleCameraChange } = useGuiCameraSync({ setSceneOptions }); + const renderSceneOptions = useMemo(() => { + const shadowMaxExtend = responsiveShadowMaxExtend(sceneOptions.shadowMaxExtend, responsiveZoomScale); + if (responsiveZoomScale === 1 && shadowMaxExtend === sceneOptions.shadowMaxExtend) return sceneOptions; + return { + ...sceneOptions, + zoom: sceneOptions.zoom * responsiveZoomScale, + shadowMaxExtend, + }; + }, [sceneOptions, responsiveZoomScale]); + + const handleRenderCameraChange = useCallback( + (camera: { rotX: number; rotY: number; zoom: number; target?: ReactVec3 }) => { + markSceneRouteDirty(); + handleCameraChange({ + ...camera, + zoom: camera.zoom / Math.max(responsiveZoomScale, 0.001), + }); + }, + [handleCameraChange, markSceneRouteDirty, responsiveZoomScale], + ); + + return { + viewportRef, + metrics, + requestGalleryDomRefresh, + canPreviewSceneOptions, + previewSceneOptions, + renderSceneOptions, + handleRenderCameraChange, + }; +} diff --git a/website/src/components/GalleryWorkbench/helpers/routeCodec.ts b/website/src/components/GalleryWorkbench/helpers/routeCodec.ts new file mode 100644 index 00000000..e371151a --- /dev/null +++ b/website/src/components/GalleryWorkbench/helpers/routeCodec.ts @@ -0,0 +1,260 @@ +import type { SceneOptionsState } from "../../types"; +import { + BOOLEAN_OPTIONS, + COMPACT_KEY_BY_OPTION, + COMPACT_OPTION_BY_KEY, + COMPACT_SCENE_VERSION, + DOTTED_COMPACT_OPTION_BY_KEY, + RETIRED_PACKED_KEY_WIDTHS, + isColorOption, + type SceneTarget, + type SerializedGalleryScene, + type SerializedGallerySceneOptionKey, + type SerializedGallerySceneOptions, +} from "./routeCodecTypes"; +import { + decodeCompactColor, + decodeCompactNumber, + decodeEnum, + decodeJson, + encodeCompactColor, + encodeEnum, + encodePackedNumber, + isVec3, + readPackedNumber, + sceneOptionsFromPayload, + sceneOptionsPayload, + strategiesFromMask, + strategiesMask, +} from "./routeCodecValues"; + +export type { + SceneTarget, + SerializedGalleryScene, + SerializedGallerySceneOptionKey, + SerializedGallerySceneOptions, +} from "./routeCodecTypes"; +export { sceneOptionsFromPayload, sceneOptionsPayload } from "./routeCodecValues"; + +export function hashStringToUint32(value: string): number { + let hash = 2166136261; + for (let i = 0; i < value.length; i += 1) { + hash ^= value.charCodeAt(i); + hash = Math.imul(hash, 16777619); + } + return hash >>> 0; +} + +export function routeIdForPresetId(presetId: string): string { + return String(hashStringToUint32(presetId)); +} + +export function resolveRoutePresetId(routeValue: string, presetIds: string[]): string { + const value = typeof routeValue === "string" ? routeValue.trim() : ""; + if (!value) return ""; + + if (/^\d+$/.test(value)) { + const found = presetIds.find((id) => routeIdForPresetId(id) === value); + if (found) return found; + } + + return presetIds.find((id) => id === value) ?? ""; +} + +function encodeCompactValue( + key: SerializedGallerySceneOptionKey, + value: SerializedGallerySceneOptions[SerializedGallerySceneOptionKey], +): string | undefined { + if (key === "p") return value === false ? "n" : typeof value === "number" ? encodePackedNumber(value) : undefined; + if (typeof value === "boolean") return value ? "" : "0"; + if (typeof value === "number") return encodePackedNumber(value); + if (key === "t" && isVec3(value)) return value.map(encodePackedNumber).join(""); + if (isColorOption(key)) return typeof value === "string" ? encodeCompactColor(value) : undefined; + if (key === "ds") return typeof value === "string" ? strategiesMask(value) : undefined; + if (key === "r" && (value === "react" || value === "vanilla")) return encodeEnum(value, { react: "r", vanilla: "v" }); + if (key === "tl" && (value === "baked" || value === "dynamic")) return encodeEnum(value, { baked: "b", dynamic: "d" }); + if (key === "tq") { + if (value === "auto") return "a"; + return typeof value === "number" ? encodePackedNumber(value) : undefined; + } + if (key === "mp" || key === "bp") return value === "exact" ? "e" : typeof value === "string" ? value : undefined; + if (key === "mr" && (value === "lossless" || value === "lossy" || value === "disabled")) { + return encodeEnum(value, { lossless: "x", lossy: "y", disabled: "d" }); + } + if (key === "drag" && (value === "orbit" || value === "pan" || value === "fpv")) { + return encodeEnum(value, { orbit: "o", pan: "p", fpv: "f" }); + } + if (key === "sst" && (value === "vector" || value === "pixel")) { + return encodeEnum(value, { vector: "v", pixel: "p" }); + } + return typeof value === "string" ? value : undefined; +} + +export function encodeCompactScene(payload: SerializedGallerySceneOptions): string { + const tokens: string[] = []; + for (const [rawKey, rawValue] of Object.entries(payload)) { + const key = rawKey as SerializedGallerySceneOptionKey; + const compactKey = COMPACT_KEY_BY_OPTION[key]; + const value = encodeCompactValue(key, rawValue as SerializedGallerySceneOptions[SerializedGallerySceneOptionKey]); + if (!compactKey || value === undefined) continue; + tokens.push(`${compactKey}${value}`); + } + return `${COMPACT_SCENE_VERSION}${tokens.join("")}`; +} + +export function encodeRouteSceneOptions( + sceneOptions: SceneOptionsState, + sceneDefaults: SceneOptionsState, +): string | null { + const payload = sceneOptionsPayload(sceneOptions, sceneDefaults); + return payload ? encodeCompactScene(payload) : null; +} + +function decodeDottedCompactValue( + key: SerializedGallerySceneOptionKey, + value: string, +): SerializedGallerySceneOptions[SerializedGallerySceneOptionKey] | undefined { + if (BOOLEAN_OPTIONS.has(key)) return value === "" || value === "1" ? true : value === "0" ? false : undefined; + if (key === "p") return value === "n" ? false : decodeCompactNumber(value); + if (key === "t") { + const values = value.split("_").map(decodeCompactNumber); + return values.length === 3 && values.every((entry) => entry !== undefined) + ? values as SceneTarget + : undefined; + } + if (isColorOption(key)) return /^[0-9a-f]{6}$/i.test(value) ? `#${value.toLowerCase()}` : undefined; + if (key === "ds") return strategiesFromMask(value) ?? (value === "-" ? "" : value); + if (key === "r") return decodeEnum(value, { react: "r", vanilla: "v" }); + if (key === "tl") return decodeEnum(value, { baked: "b", dynamic: "d" }); + if (key === "tq") return value === "a" ? "auto" : decodeCompactNumber(value); + if (key === "mp" || key === "bp") return value === "e" ? "exact" : value; + if (key === "mr") return decodeEnum(value, { lossless: "x", lossy: "y", disabled: "d" }); + if (key === "drag") return decodeEnum(value, { orbit: "o", pan: "p", fpv: "f" }); + if (key === "sst") return decodeEnum(value, { vector: "v", pixel: "p" }); + return decodeCompactNumber(value) ?? value; +} + +export function decodeDottedCompactRouteSceneOptions(routeValue: string): Partial | null { + const tokens = routeValue.split("."); + if (tokens[0] !== COMPACT_SCENE_VERSION || tokens.length < 2) return null; + const payload: SerializedGallerySceneOptions = {}; + for (const token of tokens.slice(1)) { + const compactKey = Object.keys(DOTTED_COMPACT_OPTION_BY_KEY) + .sort((a, b) => b.length - a.length) + .find((key) => token.startsWith(key)); + if (!compactKey) continue; + const optionKey = DOTTED_COMPACT_OPTION_BY_KEY[compactKey]; + const encodedValue = token.slice(compactKey.length); + if (!optionKey) continue; + const decodedValue = decodeDottedCompactValue(optionKey, encodedValue); + if (decodedValue !== undefined) { + (payload as Record)[optionKey] = decodedValue; + } + } + return Object.keys(payload).length > 0 ? sceneOptionsFromPayload(payload) : null; +} + +function readPackedValue( + key: SerializedGallerySceneOptionKey, + routeValue: string, + index: number, +): { value: SerializedGallerySceneOptions[SerializedGallerySceneOptionKey]; next: number } | undefined { + if (BOOLEAN_OPTIONS.has(key)) { + return routeValue[index] === "0" + ? { value: false, next: index + 1 } + : { value: true, next: index }; + } + if (key === "p") { + if (routeValue[index] === "n") return { value: false, next: index + 1 }; + return readPackedNumber(routeValue, index); + } + if (key === "t") { + const x = readPackedNumber(routeValue, index); + if (!x) return undefined; + const y = readPackedNumber(routeValue, x.next); + if (!y) return undefined; + const z = readPackedNumber(routeValue, y.next); + return z ? { value: [x.value, y.value, z.value], next: z.next } : undefined; + } + if (isColorOption(key)) { + const color = decodeCompactColor(routeValue.slice(index, index + 5)); + return color ? { value: color, next: index + 5 } : undefined; + } + if (key === "ds") { + const strategies = strategiesFromMask(routeValue[index] ?? ""); + return strategies === undefined ? undefined : { value: strategies, next: index + 1 }; + } + if (key === "r") { + const value = decodeEnum(routeValue[index] ?? "", { react: "r", vanilla: "v" }); + return value ? { value, next: index + 1 } : undefined; + } + if (key === "tl") { + const value = decodeEnum(routeValue[index] ?? "", { baked: "b", dynamic: "d" }); + return value ? { value, next: index + 1 } : undefined; + } + if (key === "tq") { + if (routeValue[index] === "a") return { value: "auto", next: index + 1 }; + return readPackedNumber(routeValue, index); + } + if (key === "mp" || key === "bp") { + const value = routeValue[index]; + return value ? { value: value === "e" ? "exact" : value, next: index + 1 } : undefined; + } + if (key === "mr") { + const value = decodeEnum(routeValue[index] ?? "", { lossless: "x", lossy: "y", disabled: "d" }); + return value ? { value, next: index + 1 } : undefined; + } + if (key === "drag") { + const value = decodeEnum(routeValue[index] ?? "", { orbit: "o", pan: "p", fpv: "f" }); + return value ? { value, next: index + 1 } : undefined; + } + if (key === "sst") { + const value = decodeEnum(routeValue[index] ?? "", { vector: "v", pixel: "p" }); + return value ? { value, next: index + 1 } : undefined; + } + return readPackedNumber(routeValue, index); +} + +export function decodePackedCompactRouteSceneOptions(routeValue: string): Partial | null { + if (!routeValue.startsWith(COMPACT_SCENE_VERSION) || routeValue.startsWith(`${COMPACT_SCENE_VERSION}.`)) return null; + const payload: SerializedGallerySceneOptions = {}; + let index = COMPACT_SCENE_VERSION.length; + while (index < routeValue.length) { + const compactKey = routeValue[index]; + const optionKey = COMPACT_OPTION_BY_KEY[compactKey]; + index += 1; + if (!optionKey) { + // The packed form is a positional stream, so a retired key cannot just + // be skipped — its payload has to be consumed too or every option after + // it decodes against the wrong offset and the whole scene is dropped. + const retiredWidth = RETIRED_PACKED_KEY_WIDTHS[compactKey]; + if (retiredWidth === undefined) return null; + index += retiredWidth; + continue; + } + const decoded = readPackedValue(optionKey, routeValue, index); + if (!decoded) return null; + (payload as Record)[optionKey] = decoded.value; + index = decoded.next; + } + return Object.keys(payload).length > 0 ? sceneOptionsFromPayload(payload) : null; +} + +export function decodeLegacyRouteSceneOptions(routeValue: string): Partial | null { + try { + const decoded = decodeJson(routeValue); + if (!decoded || typeof decoded !== "object") return null; + const scene = decoded as Partial; + if (scene.v !== 1 || !scene.o || typeof scene.o !== "object") return null; + return sceneOptionsFromPayload(scene.o); + } catch { + return null; + } +} + +export function decodeRouteSceneOptions(routeValue: string): Partial | null { + if (!routeValue) return null; + return decodePackedCompactRouteSceneOptions(routeValue) ?? + decodeDottedCompactRouteSceneOptions(routeValue) ?? + decodeLegacyRouteSceneOptions(routeValue); +} diff --git a/website/src/components/GalleryWorkbench/helpers/routeCodecTypes.ts b/website/src/components/GalleryWorkbench/helpers/routeCodecTypes.ts new file mode 100644 index 00000000..71c24e85 --- /dev/null +++ b/website/src/components/GalleryWorkbench/helpers/routeCodecTypes.ts @@ -0,0 +1,160 @@ +import type { SceneOptionsState } from "../../types"; + +export type SceneTarget = SceneOptionsState["target"]; +export type SerializedGallerySceneOptionKey = keyof SerializedGallerySceneOptions; + +export interface SerializedGallerySceneOptions { + r?: SceneOptionsState["renderer"]; + ap?: boolean; + ats?: number; + c?: boolean; + i?: boolean; + ar?: boolean; + axes?: boolean; + sel?: boolean; + hov?: boolean; + helper?: boolean; + z?: number; + rx?: number; + ry?: number; + p?: number | false; + az?: number; + el?: number; + key?: number; + kc?: string; + amb?: number; + amc?: string; + tl?: SceneOptionsState["textureLighting"]; + tq?: SceneOptionsState["textureQuality"]; + solid?: boolean; + mp?: SceneOptionsState["matrixPrecision"]; + bp?: SceneOptionsState["borderShapePrecision"]; + mr?: SceneOptionsState["meshResolution"]; + fill?: boolean; + outline?: boolean; + drag?: SceneOptionsState["dragMode"]; + t?: SceneTarget; + ds?: string; + shadow?: boolean; + self?: boolean; + reach?: number; + sp?: boolean; + sd?: number; + sst?: SceneOptionsState["shadowStyle"]; + sfa?: boolean; + so?: number; + ground?: boolean; + gc?: string; + fl?: boolean; + fm?: boolean; + fj?: boolean; + fc?: boolean; + fms?: number; + fjv?: number; + fg?: number; + feh?: number; + fch?: number; + fls?: number; + fiy?: boolean; + frd?: number; +} + +export interface SerializedGalleryScene { + v: 1; + o?: SerializedGallerySceneOptions; +} + +export const STRATEGY_ORDER = ["b", "i", "u"] as const; +export const COMPACT_SCENE_VERSION = "2"; +export const COMPACT_NUMBER_SCALE = 10000; + +export const COMPACT_KEY_BY_OPTION: Record = { + r: "r", + ap: "P", + ats: "A", + c: "c", + i: "i", + ar: "n", + axes: "x", + sel: "s", + hov: "h", + helper: "l", + z: "z", + rx: "X", + ry: "Y", + p: "p", + az: "a", + el: "e", + key: "k", + kc: "K", + amb: "m", + amc: "M", + tl: "T", + tq: "q", + solid: "o", + mp: "u", + bp: "v", + mr: "w", + fill: "f", + outline: "O", + drag: "d", + t: "t", + ds: "b", + shadow: "S", + self: "Z", + reach: "E", + sp: "D", + sd: "F", + sst: "H", + sfa: "I", + so: "N", + ground: "g", + gc: "G", + fl: "L", + fm: "V", + fj: "J", + fc: "C", + fms: "1", + fjv: "2", + fg: "3", + feh: "4", + fch: "5", + fls: "6", + fiy: "7", + frd: "8", +}; + +export const COMPACT_OPTION_BY_KEY = Object.fromEntries( + Object.entries(COMPACT_KEY_BY_OPTION).map(([key, compact]) => [compact, key]), +) as Record; + +export const DOTTED_COMPACT_OPTION_BY_KEY: Record = { + ...COMPACT_OPTION_BY_KEY, + ms: "fms", + jv: "fjv", + fg: "fg", + eh: "feh", + ch: "fch", + ls: "fls", + iy: "fiy", + rd: "frd", +}; + +export const COLOR_OPTIONS = new Set(["kc", "amc", "gc"]); + +/** Packed-stream keys that no longer map to an option but still appear in + * saved scene URLs. Value = payload character count to skip. `Q` was the + * shadow-color control (a 5-char packed color), removed because + * `shadow.color` is a no-op on the gallery's solid receivers. */ +export const RETIRED_PACKED_KEY_WIDTHS: Record = { Q: 5 }; + +export function isColorOption(key: SerializedGallerySceneOptionKey): boolean { + return COLOR_OPTIONS.has(key); +} + +export const BOOLEAN_OPTIONS = new Set([ + "ap", "c", "i", "ar", "axes", "sel", "hov", "helper", + "solid", "fill", "outline", "shadow", "ground", + "fl", "fm", "fj", "fc", "fiy", + "self", "sp", "sfa", +]); diff --git a/website/src/components/GalleryWorkbench/helpers/routeCodecValues.ts b/website/src/components/GalleryWorkbench/helpers/routeCodecValues.ts new file mode 100644 index 00000000..8ab28ceb --- /dev/null +++ b/website/src/components/GalleryWorkbench/helpers/routeCodecValues.ts @@ -0,0 +1,338 @@ +import type { SceneOptionsState } from "../../types"; +import { + COMPACT_NUMBER_SCALE, + STRATEGY_ORDER, + type SceneTarget, + type SerializedGallerySceneOptions, +} from "./routeCodecTypes"; + +export function round(value: number): number { + return Number(value.toFixed(4)); +} + +export function roundVec3(value: SceneTarget): SceneTarget { + return [round(value[0]), round(value[1]), round(value[2])]; +} + +function sameNumber(a: number, b: number): boolean { + return round(a) === round(b); +} + +function sameVec3(a: SceneTarget, b: SceneTarget): boolean { + return sameNumber(a[0], b[0]) && sameNumber(a[1], b[1]) && sameNumber(a[2], b[2]); +} + +function samePerspective( + a: SceneOptionsState["perspective"], + b: SceneOptionsState["perspective"], +): boolean { + if (a === false || b === false) return a === b; + if (typeof a === "number" || typeof b === "number") { + return typeof a === "number" && typeof b === "number" && sameNumber(a, b); + } + return a === b; +} + +function sameTextureQuality( + a: SceneOptionsState["textureQuality"], + b: SceneOptionsState["textureQuality"], +): boolean { + if (typeof a === "number" || typeof b === "number") { + return typeof a === "number" && typeof b === "number" && sameNumber(a, b); + } + return a === b; +} + +function addBoolean( + out: SerializedGallerySceneOptions, + key: K, + value: boolean, + defaultValue: boolean, +): void { + if (value !== defaultValue) out[key] = value as SerializedGallerySceneOptions[K]; +} + +function addNumber( + out: SerializedGallerySceneOptions, + key: K, + value: number, + defaultValue: number, +): void { + if (!sameNumber(value, defaultValue)) out[key] = round(value) as SerializedGallerySceneOptions[K]; +} + +function addString< + K extends keyof SerializedGallerySceneOptions, + T extends string & NonNullable, +>( + out: SerializedGallerySceneOptions, + key: K, + value: T, + defaultValue: T, +): void { + if (value !== defaultValue) out[key] = value as SerializedGallerySceneOptions[K]; +} + +function strategiesPayload(strategies: SceneOptionsState["disableStrategies"]): string { + return STRATEGY_ORDER.filter((strategy) => strategies.includes(strategy)).join(""); +} + +export function sceneOptionsPayload( + options: SceneOptionsState, + defaults: SceneOptionsState, +): SerializedGallerySceneOptions | undefined { + const out: SerializedGallerySceneOptions = {}; + addString(out, "r", options.renderer, defaults.renderer); + addBoolean(out, "ap", options.animationPaused, defaults.animationPaused); + addNumber(out, "ats", options.animationTimeScale, defaults.animationTimeScale); + addBoolean(out, "c", options.autoCenter, defaults.autoCenter); + addBoolean(out, "i", options.interactive, defaults.interactive); + addBoolean(out, "ar", options.animate, defaults.animate); + addBoolean(out, "axes", options.showAxes, defaults.showAxes); + addBoolean(out, "sel", options.selection, defaults.selection); + addBoolean(out, "hov", options.hoverEffects, defaults.hoverEffects); + addBoolean(out, "helper", options.showLight, defaults.showLight); + addNumber(out, "z", options.zoom, defaults.zoom); + addNumber(out, "rx", options.rotX, defaults.rotX); + addNumber(out, "ry", options.rotY, defaults.rotY); + if (!samePerspective(options.perspective, defaults.perspective)) { + if (options.perspective === false) out.p = false; + else if (typeof options.perspective === "number") out.p = round(options.perspective); + } + addNumber(out, "az", options.lightAzimuth, defaults.lightAzimuth); + addNumber(out, "el", options.lightElevation, defaults.lightElevation); + addNumber(out, "key", options.lightIntensity, defaults.lightIntensity); + addString(out, "kc", options.lightColor, defaults.lightColor); + addNumber(out, "amb", options.ambientIntensity, defaults.ambientIntensity); + addString(out, "amc", options.ambientColor, defaults.ambientColor); + addString(out, "tl", options.textureLighting, defaults.textureLighting); + if (!sameTextureQuality(options.textureQuality, defaults.textureQuality)) { + out.tq = typeof options.textureQuality === "number" ? round(options.textureQuality) : options.textureQuality; + } + addBoolean(out, "solid", options.solidMaterials, defaults.solidMaterials); + addString(out, "mp", options.matrixPrecision, defaults.matrixPrecision); + addString(out, "bp", options.borderShapePrecision, defaults.borderShapePrecision); + addString(out, "mr", options.meshResolution, defaults.meshResolution); + addBoolean(out, "fill", options.interiorFill, defaults.interiorFill); + addBoolean(out, "outline", options.outlinePolygons, defaults.outlinePolygons); + addString(out, "drag", options.dragMode, defaults.dragMode); + if (!sameVec3(options.target, defaults.target)) out.t = roundVec3(options.target); + const currentStrategies = strategiesPayload(options.disableStrategies); + if (currentStrategies !== strategiesPayload(defaults.disableStrategies)) out.ds = currentStrategies; + addBoolean(out, "shadow", options.castShadow, defaults.castShadow); + addBoolean(out, "self", options.selfShadow, defaults.selfShadow); + addNumber(out, "reach", options.shadowMaxExtend, defaults.shadowMaxExtend); + addBoolean(out, "sp", options.shadowParametric, defaults.shadowParametric); + addNumber(out, "sd", options.shadowDefinition, defaults.shadowDefinition); + addString(out, "sst", options.shadowStyle, defaults.shadowStyle); + addBoolean(out, "sfa", options.shadowFollowAnimation, defaults.shadowFollowAnimation); + addNumber(out, "so", options.shadowOpacity, defaults.shadowOpacity); + addBoolean(out, "ground", options.showGround, defaults.showGround); + addString(out, "gc", options.groundColor, defaults.groundColor); + addBoolean(out, "fl", options.fpvLook, defaults.fpvLook); + addBoolean(out, "fm", options.fpvMove, defaults.fpvMove); + addBoolean(out, "fj", options.fpvJump, defaults.fpvJump); + addBoolean(out, "fc", options.fpvCrouch, defaults.fpvCrouch); + addNumber(out, "fms", options.fpvMoveSpeed, defaults.fpvMoveSpeed); + addNumber(out, "fjv", options.fpvJumpVelocity, defaults.fpvJumpVelocity); + addNumber(out, "fg", options.fpvGravity, defaults.fpvGravity); + addNumber(out, "feh", options.fpvEyeHeight, defaults.fpvEyeHeight); + addNumber(out, "fch", options.fpvCrouchHeight, defaults.fpvCrouchHeight); + addNumber(out, "fls", options.fpvLookSensitivity, defaults.fpvLookSensitivity); + addBoolean(out, "fiy", options.fpvInvertY, defaults.fpvInvertY); + addNumber(out, "frd", options.fpvRenderDistance, defaults.fpvRenderDistance); + return Object.keys(out).length > 0 ? out : undefined; +} + +export function encodeCompactNumber(value: number): string { + return Math.round(round(value) * COMPACT_NUMBER_SCALE).toString(36); +} + +export function decodeCompactNumber(value: string): number | undefined { + if (!/^-?[0-9a-z]+$/i.test(value)) return undefined; + const sign = value.startsWith("-") ? -1 : 1; + const digits = sign === -1 ? value.slice(1) : value; + const parsed = Number.parseInt(digits, 36); + if (!Number.isFinite(parsed)) return undefined; + return round((sign * parsed) / COMPACT_NUMBER_SCALE); +} + +export function encodePackedNumber(value: number): string { + const encoded = encodeCompactNumber(value); + return `${encoded.length.toString(36)}${encoded}`; +} + +export function encodeCompactColor(value: string): string | undefined { + const hex = value.replace(/^#/, "").toLowerCase(); + if (!/^[0-9a-f]{6}$/.test(hex)) return undefined; + return Number.parseInt(hex, 16).toString(36).padStart(5, "0"); +} + +export function decodeCompactColor(value: string): string | undefined { + if (!/^[0-9a-z]{5}$/i.test(value)) return undefined; + const parsed = Number.parseInt(value, 36); + if (!Number.isFinite(parsed) || parsed < 0 || parsed > 0xffffff) return undefined; + return `#${parsed.toString(16).padStart(6, "0")}`; +} + +export function readPackedNumber(value: string, index: number): { value: number; next: number } | undefined { + const length = Number.parseInt(value[index] ?? "", 36); + if (!Number.isFinite(length) || length <= 0) return undefined; + const start = index + 1; + const end = start + length; + if (end > value.length) return undefined; + const decoded = decodeCompactNumber(value.slice(start, end)); + return decoded === undefined ? undefined : { value: decoded, next: end }; +} + +export function encodeEnum(value: T, values: Record): string { + return values[value]; +} + +export function decodeEnum(value: string, values: Record): T | undefined { + for (const [decoded, encoded] of Object.entries(values)) { + if (encoded === value) return decoded as T; + } + return undefined; +} + +export function strategiesMask(strategies: string): string { + let mask = 0; + if (strategies.includes("b")) mask |= 1; + if (strategies.includes("i")) mask |= 2; + if (strategies.includes("u")) mask |= 4; + return mask.toString(36); +} + +export function strategiesFromMask(value: string): string | undefined { + if (!/^[0-7]$/.test(value)) return undefined; + const mask = Number.parseInt(value, 36); + return STRATEGY_ORDER.filter((strategy, index) => (mask & (1 << index)) !== 0).join(""); +} + +function base64UrlToBytes(value: string): Uint8Array { + const padded = value.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(value.length / 4) * 4, "="); + const binary = atob(padded); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i); + return bytes; +} + +export function decodeJson(value: string): unknown { + return JSON.parse(new TextDecoder().decode(base64UrlToBytes(value))); +} + +function isFiniteNumber(value: unknown): value is number { + return typeof value === "number" && Number.isFinite(value); +} + +function isBoolean(value: unknown): value is boolean { + return typeof value === "boolean"; +} + +function isRenderer(value: unknown): value is SceneOptionsState["renderer"] { + return value === "react" || value === "vanilla"; +} + +function isHexColor(value: unknown): value is string { + return typeof value === "string" && /^#[0-9a-fA-F]{6}$/.test(value); +} + +function isTextureLighting(value: unknown): value is SceneOptionsState["textureLighting"] { + return value === "baked" || value === "dynamic"; +} + +function isTextureQuality(value: unknown): value is SceneOptionsState["textureQuality"] { + return value === "auto" || (isFiniteNumber(value) && value >= 0.1 && value <= 1); +} + +function isMatrixPrecision(value: unknown): value is SceneOptionsState["matrixPrecision"] { + return value === "exact" || value === "2" || value === "3" || value === "4" || value === "5" || value === "6"; +} + +function isBorderShapePrecision(value: unknown): value is SceneOptionsState["borderShapePrecision"] { + return isMatrixPrecision(value); +} + +function isMeshResolution(value: unknown): value is SceneOptionsState["meshResolution"] { + return value === "lossless" || value === "lossy" || value === "disabled"; +} + +function isDragMode(value: unknown): value is SceneOptionsState["dragMode"] { + return value === "orbit" || value === "pan" || value === "fpv"; +} + +function isShadowStyle(value: unknown): value is SceneOptionsState["shadowStyle"] { + return value === "vector" || value === "pixel"; +} + +export function isVec3(value: unknown): value is SceneTarget { + return Array.isArray(value) && + value.length === 3 && + value.every((entry) => typeof entry === "number" && Number.isFinite(entry)); +} + +function routeStrategies(value: unknown): SceneOptionsState["disableStrategies"] | undefined { + if (typeof value !== "string") return undefined; + const strategies = STRATEGY_ORDER.filter((strategy) => value.includes(strategy)); + return strategies.length > 0 ? [...strategies] : []; +} + +export function sceneOptionsFromPayload(o: SerializedGallerySceneOptions): Partial { + const disableStrategies = routeStrategies(o.ds); + return { + ...(isRenderer(o.r) ? { renderer: o.r } : null), + ...(isBoolean(o.ap) ? { animationPaused: o.ap } : null), + ...(isFiniteNumber(o.ats) ? { animationTimeScale: o.ats } : null), + ...(isBoolean(o.c) ? { autoCenter: o.c } : null), + ...(isBoolean(o.i) ? { interactive: o.i } : null), + ...(isBoolean(o.ar) ? { animate: o.ar } : null), + ...(isBoolean(o.axes) ? { showAxes: o.axes } : null), + ...(isBoolean(o.sel) ? { selection: o.sel } : null), + ...(isBoolean(o.hov) ? { hoverEffects: o.hov } : null), + ...(isBoolean(o.helper) ? { showLight: o.helper } : null), + ...(isFiniteNumber(o.z) ? { zoom: o.z } : null), + ...(isFiniteNumber(o.rx) ? { rotX: o.rx } : null), + ...(isFiniteNumber(o.ry) ? { rotY: o.ry } : null), + ...((o.p === false || isFiniteNumber(o.p)) ? { perspective: o.p } : null), + ...(isFiniteNumber(o.az) ? { lightAzimuth: o.az } : null), + ...(isFiniteNumber(o.el) ? { lightElevation: o.el } : null), + ...(isFiniteNumber(o.key) ? { lightIntensity: o.key } : null), + ...(isHexColor(o.kc) ? { lightColor: o.kc.toLowerCase() } : null), + ...(isFiniteNumber(o.amb) ? { ambientIntensity: o.amb } : null), + ...(isHexColor(o.amc) ? { ambientColor: o.amc.toLowerCase() } : null), + ...(isTextureLighting(o.tl) ? { textureLighting: o.tl } : null), + ...(isTextureQuality(o.tq) ? { textureQuality: o.tq } : null), + ...(isBoolean(o.solid) ? { solidMaterials: o.solid } : null), + ...(isMatrixPrecision(o.mp) ? { matrixPrecision: o.mp } : null), + ...(isBorderShapePrecision(o.bp) ? { borderShapePrecision: o.bp } : null), + ...(isMeshResolution(o.mr) ? { meshResolution: o.mr } : null), + ...(isBoolean(o.fill) ? { interiorFill: o.fill } : null), + ...(isBoolean(o.outline) ? { outlinePolygons: o.outline } : null), + ...(isDragMode(o.drag) ? { dragMode: o.drag } : null), + ...(isVec3(o.t) ? { target: roundVec3(o.t) } : null), + ...(disableStrategies ? { disableStrategies } : null), + ...(isBoolean(o.shadow) ? { castShadow: o.shadow } : null), + ...(isBoolean(o.self) ? { selfShadow: o.self } : null), + ...(isFiniteNumber(o.reach) ? { shadowMaxExtend: o.reach } : null), + ...(isBoolean(o.sp) ? { shadowParametric: o.sp } : null), + ...(isFiniteNumber(o.sd) ? { shadowDefinition: o.sd } : null), + ...(isShadowStyle(o.sst) ? { shadowStyle: o.sst } : null), + ...(isBoolean(o.sfa) ? { shadowFollowAnimation: o.sfa } : null), + ...(isFiniteNumber(o.so) ? { shadowOpacity: o.so } : null), + ...(isBoolean(o.ground) ? { showGround: o.ground } : null), + ...(isHexColor(o.gc) ? { groundColor: o.gc.toLowerCase() } : null), + ...(isBoolean(o.fl) ? { fpvLook: o.fl } : null), + ...(isBoolean(o.fm) ? { fpvMove: o.fm } : null), + ...(isBoolean(o.fj) ? { fpvJump: o.fj } : null), + ...(isBoolean(o.fc) ? { fpvCrouch: o.fc } : null), + ...(isFiniteNumber(o.fms) ? { fpvMoveSpeed: o.fms } : null), + ...(isFiniteNumber(o.fjv) ? { fpvJumpVelocity: o.fjv } : null), + ...(isFiniteNumber(o.fg) ? { fpvGravity: o.fg } : null), + ...(isFiniteNumber(o.feh) ? { fpvEyeHeight: o.feh } : null), + ...(isFiniteNumber(o.fch) ? { fpvCrouchHeight: o.fch } : null), + ...(isFiniteNumber(o.fls) ? { fpvLookSensitivity: o.fls } : null), + ...(isBoolean(o.fiy) ? { fpvInvertY: o.fiy } : null), + ...(isFiniteNumber(o.frd) ? { fpvRenderDistance: o.frd } : null), + }; +} diff --git a/website/src/components/GalleryWorkbench/hooks/useRouteSync.ts b/website/src/components/GalleryWorkbench/hooks/useRouteSync.ts index 180968aa..a731a3ab 100644 --- a/website/src/components/GalleryWorkbench/hooks/useRouteSync.ts +++ b/website/src/components/GalleryWorkbench/hooks/useRouteSync.ts @@ -1,164 +1,15 @@ import { useEffect, type Dispatch, type SetStateAction } from "react"; import type { SceneOptionsState } from "../../types"; +import { + decodeRouteSceneOptions, + encodeRouteSceneOptions, + resolveRoutePresetId, + routeIdForPresetId, +} from "../helpers/routeCodec"; const MODEL_PARAM = "model"; const SCENE_PARAM = "scene"; -type SceneTarget = SceneOptionsState["target"]; -type SerializedGallerySceneOptionKey = keyof SerializedGallerySceneOptions; - -interface SerializedGallerySceneOptions { - r?: SceneOptionsState["renderer"]; - ap?: boolean; - ats?: number; - c?: boolean; - i?: boolean; - ar?: boolean; - axes?: boolean; - sel?: boolean; - hov?: boolean; - helper?: boolean; - z?: number; - rx?: number; - ry?: number; - p?: number | false; - az?: number; - el?: number; - key?: number; - kc?: string; - amb?: number; - amc?: string; - tl?: SceneOptionsState["textureLighting"]; - tq?: SceneOptionsState["textureQuality"]; - solid?: boolean; - mp?: SceneOptionsState["matrixPrecision"]; - bp?: SceneOptionsState["borderShapePrecision"]; - mr?: SceneOptionsState["meshResolution"]; - fill?: boolean; - outline?: boolean; - drag?: SceneOptionsState["dragMode"]; - t?: SceneTarget; - ds?: string; - shadow?: boolean; - self?: boolean; - reach?: number; - sp?: boolean; - sd?: number; - sst?: SceneOptionsState["shadowStyle"]; - sfa?: boolean; - so?: number; - ground?: boolean; - gc?: string; - fl?: boolean; - fm?: boolean; - fj?: boolean; - fc?: boolean; - fms?: number; - fjv?: number; - fg?: number; - feh?: number; - fch?: number; - fls?: number; - fiy?: boolean; - frd?: number; -} - -interface SerializedGalleryScene { - v: 1; - o?: SerializedGallerySceneOptions; -} - -const STRATEGY_ORDER = ["b", "i", "u"] as const; -const COMPACT_SCENE_VERSION = "2"; -const COMPACT_NUMBER_SCALE = 10000; -const COMPACT_KEY_BY_OPTION: Record = { - r: "r", - ap: "P", - ats: "A", - c: "c", - i: "i", - ar: "n", - axes: "x", - sel: "s", - hov: "h", - helper: "l", - z: "z", - rx: "X", - ry: "Y", - p: "p", - az: "a", - el: "e", - key: "k", - kc: "K", - amb: "m", - amc: "M", - tl: "T", - tq: "q", - solid: "o", - mp: "u", - bp: "v", - mr: "w", - fill: "f", - outline: "O", - drag: "d", - t: "t", - ds: "b", - shadow: "S", - self: "Z", - reach: "E", - sp: "D", - sd: "F", - sst: "H", - sfa: "I", - so: "N", - ground: "g", - gc: "G", - fl: "L", - fm: "V", - fj: "J", - fc: "C", - fms: "1", - fjv: "2", - fg: "3", - feh: "4", - fch: "5", - fls: "6", - fiy: "7", - frd: "8", -}; -const COMPACT_OPTION_BY_KEY = Object.fromEntries( - Object.entries(COMPACT_KEY_BY_OPTION).map(([key, compact]) => [compact, key]), -) as Record; -const DOTTED_COMPACT_OPTION_BY_KEY: Record = { - ...COMPACT_OPTION_BY_KEY, - ms: "fms", - jv: "fjv", - fg: "fg", - eh: "feh", - ch: "fch", - ls: "fls", - iy: "fiy", - rd: "frd", -}; -const COLOR_OPTIONS = new Set(["kc", "amc", "gc"]); - -/** Packed-stream keys that no longer map to an option but still appear in - * saved scene URLs. Value = payload character count to skip. `Q` was the - * shadow-color control (a 5-char packed color), removed because - * `shadow.color` is a no-op on the gallery's solid receivers. */ -const RETIRED_PACKED_KEY_WIDTHS: Record = { Q: 5 }; - -function isColorOption(key: SerializedGallerySceneOptionKey): boolean { - return COLOR_OPTIONS.has(key); -} - -const BOOLEAN_OPTIONS = new Set([ - "ap", "c", "i", "ar", "axes", "sel", "hov", "helper", - "solid", "fill", "outline", "shadow", "ground", - "fl", "fm", "fj", "fc", "fiy", - "self", "sp", "sfa", -]); - function getRoutePresetValue(): string { if (typeof window === "undefined") return ""; const params = new URLSearchParams(window.location.search); @@ -171,534 +22,6 @@ function getRouteSceneValue(): string { return params.get(SCENE_PARAM) || ""; } -function hashStringToUint32(value: string): number { - let hash = 2166136261; - for (let i = 0; i < value.length; i += 1) { - hash ^= value.charCodeAt(i); - hash = Math.imul(hash, 16777619); - } - return hash >>> 0; -} - -function routeIdForPresetId(presetId: string): string { - return String(hashStringToUint32(presetId)); -} - -function round(value: number): number { - return Number(value.toFixed(4)); -} - -function roundVec3(value: SceneTarget): SceneTarget { - return [round(value[0]), round(value[1]), round(value[2])]; -} - -function sameNumber(a: number, b: number): boolean { - return round(a) === round(b); -} - -function sameVec3(a: SceneTarget, b: SceneTarget): boolean { - return sameNumber(a[0], b[0]) && sameNumber(a[1], b[1]) && sameNumber(a[2], b[2]); -} - -function samePerspective( - a: SceneOptionsState["perspective"], - b: SceneOptionsState["perspective"], -): boolean { - if (a === false || b === false) return a === b; - if (typeof a === "number" || typeof b === "number") { - return typeof a === "number" && typeof b === "number" && sameNumber(a, b); - } - return a === b; -} - -function sameTextureQuality( - a: SceneOptionsState["textureQuality"], - b: SceneOptionsState["textureQuality"], -): boolean { - if (typeof a === "number" || typeof b === "number") { - return typeof a === "number" && typeof b === "number" && sameNumber(a, b); - } - return a === b; -} - -function addBoolean( - out: SerializedGallerySceneOptions, - key: K, - value: boolean, - defaultValue: boolean, -): void { - if (value !== defaultValue) out[key] = value as SerializedGallerySceneOptions[K]; -} - -function addNumber( - out: SerializedGallerySceneOptions, - key: K, - value: number, - defaultValue: number, -): void { - if (!sameNumber(value, defaultValue)) out[key] = round(value) as SerializedGallerySceneOptions[K]; -} - -function addString< - K extends keyof SerializedGallerySceneOptions, - T extends string & NonNullable, ->( - out: SerializedGallerySceneOptions, - key: K, - value: T, - defaultValue: T, -): void { - if (value !== defaultValue) out[key] = value as SerializedGallerySceneOptions[K]; -} - -function strategiesPayload(strategies: SceneOptionsState["disableStrategies"]): string { - return STRATEGY_ORDER.filter((strategy) => strategies.includes(strategy)).join(""); -} - -function sceneOptionsPayload( - options: SceneOptionsState, - defaults: SceneOptionsState, -): SerializedGallerySceneOptions | undefined { - const out: SerializedGallerySceneOptions = {}; - addString(out, "r", options.renderer, defaults.renderer); - addBoolean(out, "ap", options.animationPaused, defaults.animationPaused); - addNumber(out, "ats", options.animationTimeScale, defaults.animationTimeScale); - addBoolean(out, "c", options.autoCenter, defaults.autoCenter); - addBoolean(out, "i", options.interactive, defaults.interactive); - addBoolean(out, "ar", options.animate, defaults.animate); - addBoolean(out, "axes", options.showAxes, defaults.showAxes); - addBoolean(out, "sel", options.selection, defaults.selection); - addBoolean(out, "hov", options.hoverEffects, defaults.hoverEffects); - addBoolean(out, "helper", options.showLight, defaults.showLight); - addNumber(out, "z", options.zoom, defaults.zoom); - addNumber(out, "rx", options.rotX, defaults.rotX); - addNumber(out, "ry", options.rotY, defaults.rotY); - if (!samePerspective(options.perspective, defaults.perspective)) { - if (options.perspective === false) out.p = false; - else if (typeof options.perspective === "number") out.p = round(options.perspective); - } - addNumber(out, "az", options.lightAzimuth, defaults.lightAzimuth); - addNumber(out, "el", options.lightElevation, defaults.lightElevation); - addNumber(out, "key", options.lightIntensity, defaults.lightIntensity); - addString(out, "kc", options.lightColor, defaults.lightColor); - addNumber(out, "amb", options.ambientIntensity, defaults.ambientIntensity); - addString(out, "amc", options.ambientColor, defaults.ambientColor); - addString(out, "tl", options.textureLighting, defaults.textureLighting); - if (!sameTextureQuality(options.textureQuality, defaults.textureQuality)) { - out.tq = typeof options.textureQuality === "number" ? round(options.textureQuality) : options.textureQuality; - } - addBoolean(out, "solid", options.solidMaterials, defaults.solidMaterials); - addString(out, "mp", options.matrixPrecision, defaults.matrixPrecision); - addString(out, "bp", options.borderShapePrecision, defaults.borderShapePrecision); - addString(out, "mr", options.meshResolution, defaults.meshResolution); - addBoolean(out, "fill", options.interiorFill, defaults.interiorFill); - addBoolean(out, "outline", options.outlinePolygons, defaults.outlinePolygons); - addString(out, "drag", options.dragMode, defaults.dragMode); - if (!sameVec3(options.target, defaults.target)) out.t = roundVec3(options.target); - const currentStrategies = strategiesPayload(options.disableStrategies); - if (currentStrategies !== strategiesPayload(defaults.disableStrategies)) out.ds = currentStrategies; - addBoolean(out, "shadow", options.castShadow, defaults.castShadow); - addBoolean(out, "self", options.selfShadow, defaults.selfShadow); - addNumber(out, "reach", options.shadowMaxExtend, defaults.shadowMaxExtend); - addBoolean(out, "sp", options.shadowParametric, defaults.shadowParametric); - addNumber(out, "sd", options.shadowDefinition, defaults.shadowDefinition); - addString(out, "sst", options.shadowStyle, defaults.shadowStyle); - addBoolean(out, "sfa", options.shadowFollowAnimation, defaults.shadowFollowAnimation); - addNumber(out, "so", options.shadowOpacity, defaults.shadowOpacity); - addBoolean(out, "ground", options.showGround, defaults.showGround); - addString(out, "gc", options.groundColor, defaults.groundColor); - addBoolean(out, "fl", options.fpvLook, defaults.fpvLook); - addBoolean(out, "fm", options.fpvMove, defaults.fpvMove); - addBoolean(out, "fj", options.fpvJump, defaults.fpvJump); - addBoolean(out, "fc", options.fpvCrouch, defaults.fpvCrouch); - addNumber(out, "fms", options.fpvMoveSpeed, defaults.fpvMoveSpeed); - addNumber(out, "fjv", options.fpvJumpVelocity, defaults.fpvJumpVelocity); - addNumber(out, "fg", options.fpvGravity, defaults.fpvGravity); - addNumber(out, "feh", options.fpvEyeHeight, defaults.fpvEyeHeight); - addNumber(out, "fch", options.fpvCrouchHeight, defaults.fpvCrouchHeight); - addNumber(out, "fls", options.fpvLookSensitivity, defaults.fpvLookSensitivity); - addBoolean(out, "fiy", options.fpvInvertY, defaults.fpvInvertY); - addNumber(out, "frd", options.fpvRenderDistance, defaults.fpvRenderDistance); - return Object.keys(out).length > 0 ? out : undefined; -} - -function encodeCompactNumber(value: number): string { - return Math.round(round(value) * COMPACT_NUMBER_SCALE).toString(36); -} - -function decodeCompactNumber(value: string): number | undefined { - if (!/^-?[0-9a-z]+$/i.test(value)) return undefined; - const sign = value.startsWith("-") ? -1 : 1; - const digits = sign === -1 ? value.slice(1) : value; - const parsed = Number.parseInt(digits, 36); - if (!Number.isFinite(parsed)) return undefined; - return round((sign * parsed) / COMPACT_NUMBER_SCALE); -} - -function encodePackedNumber(value: number): string { - const encoded = encodeCompactNumber(value); - return `${encoded.length.toString(36)}${encoded}`; -} - -function encodeCompactColor(value: string): string | undefined { - const hex = value.replace(/^#/, "").toLowerCase(); - if (!/^[0-9a-f]{6}$/.test(hex)) return undefined; - return Number.parseInt(hex, 16).toString(36).padStart(5, "0"); -} - -function decodeCompactColor(value: string): string | undefined { - if (!/^[0-9a-z]{5}$/i.test(value)) return undefined; - const parsed = Number.parseInt(value, 36); - if (!Number.isFinite(parsed) || parsed < 0 || parsed > 0xffffff) return undefined; - return `#${parsed.toString(16).padStart(6, "0")}`; -} - -function readPackedNumber(value: string, index: number): { value: number; next: number } | undefined { - const length = Number.parseInt(value[index] ?? "", 36); - if (!Number.isFinite(length) || length <= 0) return undefined; - const start = index + 1; - const end = start + length; - if (end > value.length) return undefined; - const decoded = decodeCompactNumber(value.slice(start, end)); - return decoded === undefined ? undefined : { value: decoded, next: end }; -} - -function encodeEnum(value: T, values: Record): string { - return values[value]; -} - -function decodeEnum(value: string, values: Record): T | undefined { - for (const [decoded, encoded] of Object.entries(values)) { - if (encoded === value) return decoded as T; - } - return undefined; -} - -function strategiesMask(strategies: string): string { - let mask = 0; - if (strategies.includes("b")) mask |= 1; - if (strategies.includes("i")) mask |= 2; - if (strategies.includes("u")) mask |= 4; - return mask.toString(36); -} - -function strategiesFromMask(value: string): string | undefined { - if (!/^[0-7]$/.test(value)) return undefined; - const mask = Number.parseInt(value, 36); - return STRATEGY_ORDER.filter((strategy, index) => (mask & (1 << index)) !== 0).join(""); -} - -function encodeCompactValue(key: SerializedGallerySceneOptionKey, value: SerializedGallerySceneOptions[SerializedGallerySceneOptionKey]): string | undefined { - if (key === "p") return value === false ? "n" : typeof value === "number" ? encodePackedNumber(value) : undefined; - if (typeof value === "boolean") return value ? "" : "0"; - if (typeof value === "number") return encodePackedNumber(value); - if (key === "t" && isVec3(value)) return value.map(encodePackedNumber).join(""); - if (isColorOption(key)) return typeof value === "string" ? encodeCompactColor(value) : undefined; - if (key === "ds") return typeof value === "string" ? strategiesMask(value) : undefined; - if (key === "r" && (value === "react" || value === "vanilla")) return encodeEnum(value, { react: "r", vanilla: "v" }); - if (key === "tl" && (value === "baked" || value === "dynamic")) return encodeEnum(value, { baked: "b", dynamic: "d" }); - if (key === "tq") { - if (value === "auto") return "a"; - return typeof value === "number" ? encodePackedNumber(value) : undefined; - } - if (key === "mp" || key === "bp") return value === "exact" ? "e" : typeof value === "string" ? value : undefined; - if (key === "mr" && (value === "lossless" || value === "lossy" || value === "disabled")) { - return encodeEnum(value, { lossless: "x", lossy: "y", disabled: "d" }); - } - if (key === "drag" && (value === "orbit" || value === "pan" || value === "fpv")) { - return encodeEnum(value, { orbit: "o", pan: "p", fpv: "f" }); - } - if (key === "sst" && (value === "vector" || value === "pixel")) { - return encodeEnum(value, { vector: "v", pixel: "p" }); - } - return typeof value === "string" ? value : undefined; -} - -function encodeCompactScene(payload: SerializedGallerySceneOptions): string { - const tokens: string[] = []; - for (const [rawKey, rawValue] of Object.entries(payload)) { - const key = rawKey as SerializedGallerySceneOptionKey; - const compactKey = COMPACT_KEY_BY_OPTION[key]; - const value = encodeCompactValue(key, rawValue as SerializedGallerySceneOptions[SerializedGallerySceneOptionKey]); - if (!compactKey || value === undefined) continue; - tokens.push(`${compactKey}${value}`); - } - return `${COMPACT_SCENE_VERSION}${tokens.join("")}`; -} - -function base64UrlToBytes(value: string): Uint8Array { - const padded = value.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(value.length / 4) * 4, "="); - const binary = atob(padded); - const bytes = new Uint8Array(binary.length); - for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i); - return bytes; -} - -function decodeJson(value: string): unknown { - return JSON.parse(new TextDecoder().decode(base64UrlToBytes(value))); -} - -function isFiniteNumber(value: unknown): value is number { - return typeof value === "number" && Number.isFinite(value); -} - -function isBoolean(value: unknown): value is boolean { - return typeof value === "boolean"; -} - -function isRenderer(value: unknown): value is SceneOptionsState["renderer"] { - return value === "react" || value === "vanilla"; -} - -function isHexColor(value: unknown): value is string { - return typeof value === "string" && /^#[0-9a-fA-F]{6}$/.test(value); -} - -function isTextureLighting(value: unknown): value is SceneOptionsState["textureLighting"] { - return value === "baked" || value === "dynamic"; -} - -function isTextureQuality(value: unknown): value is SceneOptionsState["textureQuality"] { - return value === "auto" || (isFiniteNumber(value) && value >= 0.1 && value <= 1); -} - -function isMatrixPrecision(value: unknown): value is SceneOptionsState["matrixPrecision"] { - return value === "exact" || value === "2" || value === "3" || value === "4" || value === "5" || value === "6"; -} - -function isBorderShapePrecision(value: unknown): value is SceneOptionsState["borderShapePrecision"] { - return isMatrixPrecision(value); -} - -function isMeshResolution(value: unknown): value is SceneOptionsState["meshResolution"] { - return value === "lossless" || value === "lossy" || value === "disabled"; -} - -function isDragMode(value: unknown): value is SceneOptionsState["dragMode"] { - return value === "orbit" || value === "pan" || value === "fpv"; -} - -function isShadowStyle(value: unknown): value is SceneOptionsState["shadowStyle"] { - return value === "vector" || value === "pixel"; -} - -function isVec3(value: unknown): value is SceneTarget { - return Array.isArray(value) && - value.length === 3 && - value.every((entry) => typeof entry === "number" && Number.isFinite(entry)); -} - -function routeStrategies(value: unknown): SceneOptionsState["disableStrategies"] | undefined { - if (typeof value !== "string") return undefined; - const strategies = STRATEGY_ORDER.filter((strategy) => value.includes(strategy)); - return strategies.length > 0 ? [...strategies] : []; -} - -function sceneOptionsFromPayload(o: SerializedGallerySceneOptions): Partial { - const disableStrategies = routeStrategies(o.ds); - return { - ...(isRenderer(o.r) ? { renderer: o.r } : null), - ...(isBoolean(o.ap) ? { animationPaused: o.ap } : null), - ...(isFiniteNumber(o.ats) ? { animationTimeScale: o.ats } : null), - ...(isBoolean(o.c) ? { autoCenter: o.c } : null), - ...(isBoolean(o.i) ? { interactive: o.i } : null), - ...(isBoolean(o.ar) ? { animate: o.ar } : null), - ...(isBoolean(o.axes) ? { showAxes: o.axes } : null), - ...(isBoolean(o.sel) ? { selection: o.sel } : null), - ...(isBoolean(o.hov) ? { hoverEffects: o.hov } : null), - ...(isBoolean(o.helper) ? { showLight: o.helper } : null), - ...(isFiniteNumber(o.z) ? { zoom: o.z } : null), - ...(isFiniteNumber(o.rx) ? { rotX: o.rx } : null), - ...(isFiniteNumber(o.ry) ? { rotY: o.ry } : null), - ...((o.p === false || isFiniteNumber(o.p)) ? { perspective: o.p } : null), - ...(isFiniteNumber(o.az) ? { lightAzimuth: o.az } : null), - ...(isFiniteNumber(o.el) ? { lightElevation: o.el } : null), - ...(isFiniteNumber(o.key) ? { lightIntensity: o.key } : null), - ...(isHexColor(o.kc) ? { lightColor: o.kc.toLowerCase() } : null), - ...(isFiniteNumber(o.amb) ? { ambientIntensity: o.amb } : null), - ...(isHexColor(o.amc) ? { ambientColor: o.amc.toLowerCase() } : null), - ...(isTextureLighting(o.tl) ? { textureLighting: o.tl } : null), - ...(isTextureQuality(o.tq) ? { textureQuality: o.tq } : null), - ...(isBoolean(o.solid) ? { solidMaterials: o.solid } : null), - ...(isMatrixPrecision(o.mp) ? { matrixPrecision: o.mp } : null), - ...(isBorderShapePrecision(o.bp) ? { borderShapePrecision: o.bp } : null), - ...(isMeshResolution(o.mr) ? { meshResolution: o.mr } : null), - ...(isBoolean(o.fill) ? { interiorFill: o.fill } : null), - ...(isBoolean(o.outline) ? { outlinePolygons: o.outline } : null), - ...(isDragMode(o.drag) ? { dragMode: o.drag } : null), - ...(isVec3(o.t) ? { target: roundVec3(o.t) } : null), - ...(disableStrategies ? { disableStrategies } : null), - ...(isBoolean(o.shadow) ? { castShadow: o.shadow } : null), - ...(isBoolean(o.self) ? { selfShadow: o.self } : null), - ...(isFiniteNumber(o.reach) ? { shadowMaxExtend: o.reach } : null), - ...(isBoolean(o.sp) ? { shadowParametric: o.sp } : null), - ...(isFiniteNumber(o.sd) ? { shadowDefinition: o.sd } : null), - ...(isShadowStyle(o.sst) ? { shadowStyle: o.sst } : null), - ...(isBoolean(o.sfa) ? { shadowFollowAnimation: o.sfa } : null), - ...(isFiniteNumber(o.so) ? { shadowOpacity: o.so } : null), - ...(isBoolean(o.ground) ? { showGround: o.ground } : null), - ...(isHexColor(o.gc) ? { groundColor: o.gc.toLowerCase() } : null), - ...(isBoolean(o.fl) ? { fpvLook: o.fl } : null), - ...(isBoolean(o.fm) ? { fpvMove: o.fm } : null), - ...(isBoolean(o.fj) ? { fpvJump: o.fj } : null), - ...(isBoolean(o.fc) ? { fpvCrouch: o.fc } : null), - ...(isFiniteNumber(o.fms) ? { fpvMoveSpeed: o.fms } : null), - ...(isFiniteNumber(o.fjv) ? { fpvJumpVelocity: o.fjv } : null), - ...(isFiniteNumber(o.fg) ? { fpvGravity: o.fg } : null), - ...(isFiniteNumber(o.feh) ? { fpvEyeHeight: o.feh } : null), - ...(isFiniteNumber(o.fch) ? { fpvCrouchHeight: o.fch } : null), - ...(isFiniteNumber(o.fls) ? { fpvLookSensitivity: o.fls } : null), - ...(isBoolean(o.fiy) ? { fpvInvertY: o.fiy } : null), - ...(isFiniteNumber(o.frd) ? { fpvRenderDistance: o.frd } : null), - }; -} - -function decodeDottedCompactValue(key: SerializedGallerySceneOptionKey, value: string): SerializedGallerySceneOptions[SerializedGallerySceneOptionKey] | undefined { - if (BOOLEAN_OPTIONS.has(key)) return value === "" || value === "1" ? true : value === "0" ? false : undefined; - if (key === "p") return value === "n" ? false : decodeCompactNumber(value); - if (key === "t") { - const values = value.split("_").map(decodeCompactNumber); - return values.length === 3 && values.every((entry) => entry !== undefined) - ? values as SceneTarget - : undefined; - } - if (isColorOption(key)) return /^[0-9a-f]{6}$/i.test(value) ? `#${value.toLowerCase()}` : undefined; - if (key === "ds") return strategiesFromMask(value) ?? (value === "-" ? "" : value); - if (key === "r") return decodeEnum(value, { react: "r", vanilla: "v" }); - if (key === "tl") return decodeEnum(value, { baked: "b", dynamic: "d" }); - if (key === "tq") return value === "a" ? "auto" : decodeCompactNumber(value); - if (key === "mp" || key === "bp") return value === "e" ? "exact" : value; - if (key === "mr") return decodeEnum(value, { lossless: "x", lossy: "y", disabled: "d" }); - if (key === "drag") return decodeEnum(value, { orbit: "o", pan: "p", fpv: "f" }); - if (key === "sst") return decodeEnum(value, { vector: "v", pixel: "p" }); - return decodeCompactNumber(value) ?? value; -} - -function decodeDottedCompactRouteSceneOptions(routeValue: string): Partial | null { - const tokens = routeValue.split("."); - if (tokens[0] !== COMPACT_SCENE_VERSION || tokens.length < 2) return null; - const payload: SerializedGallerySceneOptions = {}; - for (const token of tokens.slice(1)) { - const compactKey = Object.keys(DOTTED_COMPACT_OPTION_BY_KEY) - .sort((a, b) => b.length - a.length) - .find((key) => token.startsWith(key)); - if (!compactKey) continue; - const optionKey = DOTTED_COMPACT_OPTION_BY_KEY[compactKey]; - const encodedValue = token.slice(compactKey.length); - if (!optionKey) continue; - const decodedValue = decodeDottedCompactValue(optionKey, encodedValue); - if (decodedValue !== undefined) { - (payload as Record)[optionKey] = decodedValue; - } - } - return Object.keys(payload).length > 0 ? sceneOptionsFromPayload(payload) : null; -} - -function readPackedValue( - key: SerializedGallerySceneOptionKey, - routeValue: string, - index: number, -): { value: SerializedGallerySceneOptions[SerializedGallerySceneOptionKey]; next: number } | undefined { - if (BOOLEAN_OPTIONS.has(key)) { - return routeValue[index] === "0" - ? { value: false, next: index + 1 } - : { value: true, next: index }; - } - if (key === "p") { - if (routeValue[index] === "n") return { value: false, next: index + 1 }; - return readPackedNumber(routeValue, index); - } - if (key === "t") { - const x = readPackedNumber(routeValue, index); - if (!x) return undefined; - const y = readPackedNumber(routeValue, x.next); - if (!y) return undefined; - const z = readPackedNumber(routeValue, y.next); - return z ? { value: [x.value, y.value, z.value], next: z.next } : undefined; - } - if (isColorOption(key)) { - const color = decodeCompactColor(routeValue.slice(index, index + 5)); - return color ? { value: color, next: index + 5 } : undefined; - } - if (key === "ds") { - const strategies = strategiesFromMask(routeValue[index] ?? ""); - return strategies === undefined ? undefined : { value: strategies, next: index + 1 }; - } - if (key === "r") { - const value = decodeEnum(routeValue[index] ?? "", { react: "r", vanilla: "v" }); - return value ? { value, next: index + 1 } : undefined; - } - if (key === "tl") { - const value = decodeEnum(routeValue[index] ?? "", { baked: "b", dynamic: "d" }); - return value ? { value, next: index + 1 } : undefined; - } - if (key === "tq") { - if (routeValue[index] === "a") return { value: "auto", next: index + 1 }; - return readPackedNumber(routeValue, index); - } - if (key === "mp" || key === "bp") { - const value = routeValue[index]; - return value ? { value: value === "e" ? "exact" : value, next: index + 1 } : undefined; - } - if (key === "mr") { - const value = decodeEnum(routeValue[index] ?? "", { lossless: "x", lossy: "y", disabled: "d" }); - return value ? { value, next: index + 1 } : undefined; - } - if (key === "drag") { - const value = decodeEnum(routeValue[index] ?? "", { orbit: "o", pan: "p", fpv: "f" }); - return value ? { value, next: index + 1 } : undefined; - } - if (key === "sst") { - const value = decodeEnum(routeValue[index] ?? "", { vector: "v", pixel: "p" }); - return value ? { value, next: index + 1 } : undefined; - } - return readPackedNumber(routeValue, index); -} - -function decodePackedCompactRouteSceneOptions(routeValue: string): Partial | null { - if (!routeValue.startsWith(COMPACT_SCENE_VERSION) || routeValue.startsWith(`${COMPACT_SCENE_VERSION}.`)) return null; - const payload: SerializedGallerySceneOptions = {}; - let index = COMPACT_SCENE_VERSION.length; - while (index < routeValue.length) { - const compactKey = routeValue[index]; - const optionKey = COMPACT_OPTION_BY_KEY[compactKey]; - index += 1; - if (!optionKey) { - // The packed form is a positional stream, so a retired key cannot just - // be skipped — its payload has to be consumed too or every option after - // it decodes against the wrong offset and the whole scene is dropped. - const retiredWidth = RETIRED_PACKED_KEY_WIDTHS[compactKey]; - if (retiredWidth === undefined) return null; - index += retiredWidth; - continue; - } - const decoded = readPackedValue(optionKey, routeValue, index); - if (!decoded) return null; - (payload as Record)[optionKey] = decoded.value; - index = decoded.next; - } - return Object.keys(payload).length > 0 ? sceneOptionsFromPayload(payload) : null; -} - -function decodeLegacyRouteSceneOptions(routeValue: string): Partial | null { - try { - const decoded = decodeJson(routeValue); - if (!decoded || typeof decoded !== "object") return null; - const scene = decoded as Partial; - if (scene.v !== 1 || !scene.o || typeof scene.o !== "object") return null; - return sceneOptionsFromPayload(scene.o); - } catch { - return null; - } -} - -function decodeRouteSceneOptions(routeValue: string): Partial | null { - if (!routeValue) return null; - return decodePackedCompactRouteSceneOptions(routeValue) ?? - decodeDottedCompactRouteSceneOptions(routeValue) ?? - decodeLegacyRouteSceneOptions(routeValue); -} - function writeRouteParams(params: URLSearchParams): void { if (typeof window === "undefined") return; const newSearch = params.toString(); @@ -708,18 +31,6 @@ function writeRouteParams(params: URLSearchParams): void { } } -function resolveRoutePresetId(routeValue: string, presetIds: string[]): string { - const value = typeof routeValue === "string" ? routeValue.trim() : ""; - if (!value) return ""; - - if (/^\d+$/.test(value)) { - const found = presetIds.find((id) => routeIdForPresetId(id) === value); - if (found) return found; - } - - return presetIds.find((id) => id === value) ?? ""; -} - export function setRoutePresetId(presetId: string | null): void { if (typeof window === "undefined") return; const next = presetId ? routeIdForPresetId(presetId) : ""; @@ -751,11 +62,11 @@ export function setRouteSceneOptions({ presetId: string | null; }): void { if (typeof window === "undefined") return; - const payload = sceneOptionsPayload(sceneOptions, sceneDefaults); + const encodedScene = encodeRouteSceneOptions(sceneOptions, sceneDefaults); const params = new URLSearchParams(window.location.search); if (presetId) params.set(MODEL_PARAM, routeIdForPresetId(presetId)); else params.delete(MODEL_PARAM); - if (payload) params.set(SCENE_PARAM, encodeCompactScene(payload)); + if (encodedScene) params.set(SCENE_PARAM, encodedScene); else params.delete(SCENE_PARAM); writeRouteParams(params); } diff --git a/website/src/components/VanillaScene/VanillaScene.tsx b/website/src/components/VanillaScene/VanillaScene.tsx index c95cdc8f..d9072720 100644 --- a/website/src/components/VanillaScene/VanillaScene.tsx +++ b/website/src/components/VanillaScene/VanillaScene.tsx @@ -564,9 +564,9 @@ export function VanillaScene({ ? { speed: 0.3, axis: "y" as const, pauseOnInteraction: true } : false as const, }); - controls.addEventListener("end", ((e: { camera: { rotX: number; rotY: number; zoom: number; target?: ReactVec3 } }) => { + controls.addEventListener("end", (e) => { onCameraChangeRef.current?.({ ...e.camera, zoom: e.camera.zoom / LEGACY_ZOOM_COMPAT }); - }) as any); + }); return controls; }; if (controlsRef.current) controlsRef.current.destroy(); diff --git a/website/tests/builderTerrain.test.ts b/website/tests/builderTerrain.test.ts new file mode 100644 index 00000000..67ba1a73 --- /dev/null +++ b/website/tests/builderTerrain.test.ts @@ -0,0 +1,45 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { + sampleTerrain, + rotationForSlope, + vertexKey, + worldToCell, + worldToVertex, + type TerrainVertices, +} from "../src/components/BuilderWorkbench/geometry/terrain"; + +test("worldToVertex and worldToCell map positive and negative coordinates cleanly", () => { + assert.deepEqual(worldToVertex(14, -6, 10), [1, -1]); + assert.deepEqual(worldToCell(14, -6, 10), [1, -1]); + assert.deepEqual(worldToCell(0, 0, 10), [0, 0]); +}); + +test("sampleTerrain returns flat zero height and zero slope on empty map", () => { + const vertices: TerrainVertices = new Map(); + assert.deepEqual(sampleTerrain(vertices, 10, 5, 5), { z: 0, slopeX: 0, slopeY: 0 }); +}); + +test("sampleTerrain is continuous across the (p00 -> p11) diagonal and matches raised corners", () => { + const vertices: TerrainVertices = new Map([[vertexKey(1, 1), 10]]); + // Corners: (0,0)=0, (1,0)=0, (1,1)=10, (0,1)=0 + const center = sampleTerrain(vertices, 10, 5, 5); + const justBelowDiag = sampleTerrain(vertices, 10, 5.001, 5); + const justAboveDiag = sampleTerrain(vertices, 10, 5, 5.001); + + assert.equal(center.z, 5); + assert.ok(Math.abs(justBelowDiag.z - center.z) < 0.01); + assert.ok(Math.abs(justAboveDiag.z - center.z) < 0.01); + // Best-fit cell average plane slopes: ((0 + 10) - (0 + 0)) / 20 = 0.5 + assert.equal(center.slopeX, 0.5); + assert.equal(center.slopeY, 0.5); +}); + +test("rotationForSlope converts slopes into expected Euler degrees", () => { + const flat = rotationForSlope(0, 0); + assert.deepEqual(flat.map((v) => v + 0), [0, 0, 0]); + const [rotX, rotY, rotZ] = rotationForSlope(1, 1); + assert.ok(Math.abs(rotX - 45) < 1e-6); + assert.ok(Math.abs(rotY + 45) < 1e-6); + assert.equal(rotZ, 0); +}); diff --git a/website/tests/routeCodec.test.ts b/website/tests/routeCodec.test.ts new file mode 100644 index 00000000..9982f892 --- /dev/null +++ b/website/tests/routeCodec.test.ts @@ -0,0 +1,121 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { DEFAULT_SCENE } from "../src/components/GalleryWorkbench/helpers/galleryDefaults"; +import { + decodeDottedCompactRouteSceneOptions, + decodeLegacyRouteSceneOptions, + decodePackedCompactRouteSceneOptions, + decodeRouteSceneOptions, + encodeRouteSceneOptions, + hashStringToUint32, + resolveRoutePresetId, + routeIdForPresetId, +} from "../src/components/GalleryWorkbench/helpers/routeCodec"; +import type { SceneOptionsState } from "../src/components/types"; + +test("encodeRouteSceneOptions returns null when options match defaults", () => { + assert.equal(encodeRouteSceneOptions(DEFAULT_SCENE, DEFAULT_SCENE), null); +}); + +test("packed compact round-trips perspective:false (orthographic) as pn and numeric perspective", () => { + const ortho: SceneOptionsState = { ...DEFAULT_SCENE, perspective: false }; + const encodedOrtho = encodeRouteSceneOptions(ortho, DEFAULT_SCENE); + assert.equal(encodedOrtho, "2pn"); + assert.deepEqual(decodeRouteSceneOptions(encodedOrtho!), { perspective: false }); + + const persp: SceneOptionsState = { ...DEFAULT_SCENE, perspective: 1200 }; + const encodedPersp = encodeRouteSceneOptions(persp, DEFAULT_SCENE); + assert.ok(encodedPersp && encodedPersp.startsWith("2p")); + assert.deepEqual(decodeRouteSceneOptions(encodedPersp!), { perspective: 1200 }); +}); + +test("packed compact round-trips mixed booleans, numbers, enums, colors, strategies, and vec3 target", () => { + const custom: SceneOptionsState = { + ...DEFAULT_SCENE, + renderer: "react", + perspective: false, + selfShadow: true, + castShadow: true, + zoom: 1.75, + rotX: 42.5, + rotY: 135, + lightColor: "#ff8800", + groundColor: "#112233", + textureLighting: "dynamic", + textureQuality: 0.5, + matrixPrecision: "4", + meshResolution: "lossless", + dragMode: "fpv", + shadowStyle: "pixel", + disableStrategies: ["b", "u"], + target: [12.5, -4, 3.25], + }; + + const encoded = encodeRouteSceneOptions(custom, DEFAULT_SCENE); + assert.ok(encoded && encoded.startsWith("2")); + const decoded = decodeRouteSceneOptions(encoded!); + assert.deepEqual(decoded, { + renderer: "react", + perspective: false, + selfShadow: true, + castShadow: true, + zoom: 1.75, + rotX: 42.5, + rotY: 135, + lightColor: "#ff8800", + groundColor: "#112233", + textureLighting: "dynamic", + textureQuality: 0.5, + matrixPrecision: "4", + meshResolution: "lossless", + dragMode: "fpv", + shadowStyle: "pixel", + disableStrategies: ["b", "u"], + target: [12.5, -4, 3.25], + }); +}); + +test("packed decoder skips retired 5-char color key Q cleanly", () => { + assert.deepEqual(decodePackedCompactRouteSceneOptions("2Q00000pnZ"), { + perspective: false, + selfShadow: true, + }); +}); + +test("dotted compact and legacy v1 base64url JSON decoders stay backward-compatible", () => { + assert.deepEqual(decodeDottedCompactRouteSceneOptions("2.pn.Z.G112233.b5"), { + perspective: false, + selfShadow: true, + groundColor: "#112233", + disableStrategies: ["b", "u"], + }); + + const legacyPayload = Buffer.from( + JSON.stringify({ v: 1, o: { p: false, self: true, z: 2.5, r: "vanilla" } }), + "utf8", + ).toString("base64url"); + assert.deepEqual(decodeLegacyRouteSceneOptions(legacyPayload), { + perspective: false, + selfShadow: true, + zoom: 2.5, + renderer: "vanilla", + }); +}); + +test("decoders return null on corrupt, empty, or wrong-version payloads", () => { + assert.equal(decodeRouteSceneOptions(""), null); + assert.equal(decodeRouteSceneOptions("2"), null); + assert.equal(decodeRouteSceneOptions("2p0"), null); + assert.equal(decodeRouteSceneOptions("not-valid-base64!!!"), null); + assert.equal(decodeDottedCompactRouteSceneOptions("1.pn"), null); +}); + +test("preset ID hashing and resolution handles numeric hash, literal id, and missing ids", () => { + const presets = ["chicken", "saucer", "glb-poly-pizza-cow"]; + const hashed = routeIdForPresetId("chicken"); + assert.equal(hashed, String(hashStringToUint32("chicken"))); + assert.equal(resolveRoutePresetId(hashed, presets), "chicken"); + assert.equal(resolveRoutePresetId("saucer", presets), "saucer"); + assert.equal(resolveRoutePresetId("nonexistent", presets), ""); + assert.equal(resolveRoutePresetId(" ", presets), ""); +}); diff --git a/website/tsconfig.json b/website/tsconfig.json index 2f56374d..9735fb77 100644 --- a/website/tsconfig.json +++ b/website/tsconfig.json @@ -21,5 +21,5 @@ } }, "include": [".astro/types.d.ts", "**/*"], - "exclude": ["dist"] + "exclude": ["dist", "tests"] }