diff --git a/.github/architecture/repo-map.md b/.github/architecture/repo-map.md index a1369ff63..f68c594d9 100644 --- a/.github/architecture/repo-map.md +++ b/.github/architecture/repo-map.md @@ -1,20 +1,20 @@ # PolyCSS Repository Map -Tracked production code scanned across `packages/*/src`, `bench/`, and `website/src`: **421 files**, **101,578 lines**. Regenerate with `pnpm map`; verified in CI by `pnpm check:map`. +Tracked production code scanned across `packages/*/src`, `bench/`, and `website/src`: **435 files**, **98,545 lines**. Regenerate with `pnpm map`; verified in CI by `pnpm check:map`. ## 1. Packages & Entry Points | Package | Visibility | Exports | Workspace deps | Src files | Src lines | Test files | |---|---|---|---|---:|---:|---:| -| `packages/core` (`@layoutit/polycss-core`) | npm | `., ./three` | — | 75 | 27,024 | 58 | +| `packages/core` (`@layoutit/polycss-core`) | npm | `., ./three` | — | 78 | 26,885 | 58 | | `packages/domformat` (`@layoutit/polycss-domformat`) | private | `., ./browser` | — | 36 | 13,165 | 0 | -| `packages/fonts` (`@layoutit/polycss-fonts`) | npm | `.` | `@layoutit/polycss-core` | 7 | 1,661 | 4 | -| `packages/morph` (`@layoutit/polycss-morph`) | npm | `., ./prepare` | `@layoutit/polycss`, `@layoutit/polycss-core` | 49 | 7,633 | 14 | -| `packages/polycss` (`@layoutit/polycss`) | npm | `., ./runtime, ./elements, ./three` | `@layoutit/polycss-core` | 62 | 16,582 | 40 | -| `packages/react` (`@layoutit/polycss-react`) | npm | `., ./three` | `@layoutit/polycss`, `@layoutit/polycss-core` | 44 | 6,398 | 31 | +| `packages/fonts` (`@layoutit/polycss-fonts`) | npm | `.` | `@layoutit/polycss-core` | 7 | 1,656 | 4 | +| `packages/morph` (`@layoutit/polycss-morph`) | npm | `., ./prepare` | `@layoutit/polycss`, `@layoutit/polycss-core` | 49 | 7,629 | 14 | +| `packages/polycss` (`@layoutit/polycss`) | npm | `., ./runtime, ./elements, ./three` | `@layoutit/polycss-core` | 72 | 16,820 | 41 | +| `packages/react` (`@layoutit/polycss-react`) | npm | `., ./three` | `@layoutit/polycss`, `@layoutit/polycss-core` | 44 | 4,653 | 31 | | `packages/skills` (`@layoutit/polycss-skills`) | npm | `.` | — | 1 | 415 | 1 | -| `packages/vue` (`@layoutit/polycss-vue`) | npm | `., ./three` | `@layoutit/polycss`, `@layoutit/polycss-core` | 42 | 5,560 | 29 | +| `packages/vue` (`@layoutit/polycss-vue`) | npm | `., ./three` | `@layoutit/polycss`, `@layoutit/polycss-core` | 42 | 4,402 | 29 | ## 2. Canonical Workspace Source Aliases @@ -44,35 +44,35 @@ Single source of truth: [`packages/workspace-aliases.mjs`](../../packages/worksp | Fan-in | Lines | File | |---:|---:|---| -| 108 | 642 | `packages/core/src/index.ts` | -| 65 | 248 | `packages/core/src/types.ts` | +| 113 | 644 | `packages/core/src/index.ts` | +| 67 | 248 | `packages/core/src/types.ts` | +| 39 | 247 | `packages/polycss/src/runtime.ts` | | 32 | 301 | `packages/react/src/index.ts` | -| 31 | 119 | `website/src/components/types.ts` | -| 24 | 147 | `packages/polycss/src/runtime.ts` | +| 30 | 119 | `website/src/components/types.ts` | | 18 | 218 | `packages/polycss/src/index.ts` | | 18 | 88 | `website/src/components/GalleryWorkbench/types.ts` | -| 13 | 283 | `packages/polycss/src/elements/PolySceneElement.ts` | -| 13 | 45 | `packages/polycss/src/render/textureAtlas.ts` | -| 13 | 41 | `packages/react/src/camera/context.ts` | -| 12 | 1,396 | `packages/polycss/src/api/createPolyScene.ts` | -| 11 | 101 | `packages/core/src/atlas/constants.ts` | +| 17 | 385 | `packages/polycss/src/api/createPolyScene.ts` | +| 16 | 45 | `packages/polycss/src/render/textureAtlas.ts` | +| 13 | 121 | `packages/polycss/src/api/scene/internalTypes.ts` | +| 13 | 476 | `packages/polycss/src/api/scene/types.ts` | +| 12 | 49 | `packages/core/src/math/vec3.ts` | ### Largest production source files | Lines | File | |---:|---| | 3,578 | `packages/domformat/src/schema.ts` | -| 2,746 | `packages/core/src/merge/optimizePolygons.ts` | -| 2,185 | `packages/core/src/shadow/computeReceiverShadows.ts` | -| 2,017 | `packages/core/src/parser/parseGltf.ts` | +| 2,705 | `packages/core/src/merge/optimizePolygons.ts` | +| 2,186 | `packages/core/src/shadow/computeReceiverShadows.ts` | +| 2,010 | `packages/core/src/parser/parseGltf.ts` | | 1,935 | `packages/domformat/src/state/polycss.ts` | -| 1,592 | `packages/core/src/merge/seamRepair.ts` | -| 1,527 | `website/src/components/GalleryWorkbench/GalleryWorkbench.tsx` | -| 1,396 | `packages/polycss/src/api/createPolyScene.ts` | -| 1,283 | `website/src/components/VanillaScene/VanillaScene.tsx` | -| 1,227 | `packages/react/src/controls/TransformControls.tsx` | +| 1,548 | `packages/core/src/merge/seamRepair.ts` | +| 1,519 | `website/src/components/GalleryWorkbench/GalleryWorkbench.tsx` | +| 1,274 | `website/src/components/VanillaScene/VanillaScene.tsx` | | 1,214 | `website/src/components/WordArtWorkbench/WordArtWorkbench.tsx` | -| 1,198 | `bench/visual-gate.mjs` | +| 1,192 | `bench/visual-gate.mjs` | +| 1,178 | `packages/domformat/src/browser.ts` | +| 1,139 | `website/src/components/GalleryWorkbench/presets/presetFiles.ts` | ## 4. Core Render & Control Pipelines diff --git a/.github/scripts/check-packs.mjs b/.github/scripts/check-packs.mjs index 5533ce798..c5256a549 100644 --- a/.github/scripts/check-packs.mjs +++ b/.github/scripts/check-packs.mjs @@ -14,7 +14,7 @@ * Usage: * node .github/scripts/check-packs.mjs */ -import { execFile } from "node:child_process"; +import { execFile, execFileSync } from "node:child_process"; import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; @@ -110,6 +110,93 @@ export function validateTarballInventory(pkgName, packedManifest, tarEntries) { return errors; } +export function extractNamedImportsFromDist(jsSource, targetSpecifier) { + const escaped = targetSpecifier.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const re = new RegExp(`import\\s*\\{([^}]*)\\}\\s*from\\s*["']${escaped}["']`, "g"); + const names = new Set(); + for (const match of jsSource.matchAll(re)) { + for (const part of match[1].split(",")) { + const cleaned = part.trim(); + if (!cleaned) continue; + const imported = cleaned.split(/\s+as\s+/)[0].trim(); + if (imported) names.add(imported); + } + } + return [...names].sort(); +} + +export function collectBarrelValueExports(barrelSource) { + const names = new Set(); + const stripped = barrelSource + .replace(/\/\*[\s\S]*?\*\//g, "") + .replace(/\/\/[^\n]*/g, ""); + for (const match of stripped.matchAll(/export\s+(?!type\b)\{([^}]*)\}/g)) { + for (const part of match[1].split(",")) { + const cleaned = part.trim(); + if (!cleaned || /^type\s+/.test(cleaned)) continue; + const pieces = cleaned.split(/\s+as\s+/); + const exported = (pieces[1] ?? pieces[0]).trim(); + if (exported) names.add(exported); + } + } + for (const match of stripped.matchAll(/export\s+(?:async\s+)?(?:function|const|let|var|class)\s+([A-Za-z_$][\w$]*)/g)) { + names.add(match[1]); + } + return names; +} + +function readGitFile(root, ref, relPath) { + try { + return execFileSync("git", ["show", `${ref}:${relPath}`], { + cwd: root, + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + }); + } catch { + return null; + } +} + +export function validateMorphRegistryCompat({ root = repoRoot } = {}) { + const morphManifestPath = join(root, "packages", "morph", "package.json"); + const coreManifestPath = join(root, "packages", "core", "package.json"); + const morphDistDir = join(root, "packages", "morph", "dist"); + if (!existsSync(morphManifestPath) || !existsSync(coreManifestPath) || !existsSync(morphDistDir)) { + return []; + } + const coreVersion = JSON.parse(readFileSync(coreManifestPath, "utf8")).version; + const candidateRefs = [`v${coreVersion}`, "origin/main", "main"]; + let baseRef = null; + for (const ref of candidateRefs) { + const baseCorePkgRaw = readGitFile(root, ref, "packages/core/package.json"); + if (!baseCorePkgRaw) continue; + const baseCoreVersion = JSON.parse(baseCorePkgRaw).version; + if (baseCoreVersion === coreVersion) { + baseRef = ref; + break; + } + } + if (!baseRef) return []; + + const baseCoreIndex = readGitFile(root, baseRef, "packages/core/src/index.ts"); + if (!baseCoreIndex) return []; + const publishedCoreExports = collectBarrelValueExports(baseCoreIndex); + + const errors = []; + const distJsFiles = readdirSync(morphDistDir).filter((f) => f.endsWith(".js")).sort(); + for (const file of distJsFiles) { + const src = readFileSync(join(morphDistDir, file), "utf8"); + const imported = extractNamedImportsFromDist(src, "@layoutit/polycss-core"); + const missing = imported.filter((name) => !publishedCoreExports.has(name)); + if (missing.length > 0) { + errors.push( + `@layoutit/polycss-morph: dist/${file} imports @layoutit/polycss-core symbol(s) missing from ${baseRef} (${coreVersion}): ${missing.join(", ")} (will fail morph test:package:registry in CI)`, + ); + } + } + return errors; +} + export async function checkAllPublishablePacks({ root = repoRoot } = {}) { const packagesRoot = resolve(root, "packages"); const pkgDirs = readdirSync(packagesRoot, { withFileTypes: true }) @@ -158,6 +245,7 @@ export async function checkAllPublishablePacks({ root = repoRoot } = {}) { ); for (const item of checked) allErrors.push(...item.errors); + allErrors.push(...validateMorphRegistryCompat({ root })); return { ok: allErrors.length === 0, checked: checked.map(({ errors: _e, ...rest }) => rest), diff --git a/.github/scripts/check-packs.test.mjs b/.github/scripts/check-packs.test.mjs index 9c6a7bf05..895da79d9 100644 --- a/.github/scripts/check-packs.test.mjs +++ b/.github/scripts/check-packs.test.mjs @@ -1,6 +1,11 @@ import test from "node:test"; import assert from "node:assert/strict"; -import { collectDeclaredEntryPaths, validateTarballInventory } from "./check-packs.mjs"; +import { + collectBarrelValueExports, + collectDeclaredEntryPaths, + extractNamedImportsFromDist, + validateTarballInventory, +} from "./check-packs.mjs"; test("collectDeclaredEntryPaths collects main, module, types, bin, exports, and typesVersions", () => { const entries = collectDeclaredEntryPaths({ @@ -74,3 +79,25 @@ test("validateTarballInventory catches missing entries, missing README, unresolv assert.ok(errors.some((e) => e.includes("unresolved workspace specifier"))); assert.ok(errors.some((e) => e.includes("test file leaked"))); }); + +test("extractNamedImportsFromDist and collectBarrelValueExports catch new core imports missing from published barrel", () => { + const distJs = 'import{crossVec as a,transformPointMat4 as b}from"@layoutit/polycss-core";'; + const imported = extractNamedImportsFromDist(distJs, "@layoutit/polycss-core"); + assert.deepEqual(imported, ["crossVec", "transformPointMat4"]); + + const baseBarrel = ` + export type { Vec3 } from "./types"; + export { crossVec, type Foo, bar as baz } from "./math"; + export const BASE_TILE = 50; + `; + const exported = collectBarrelValueExports(baseBarrel); + assert.equal(exported.has("crossVec"), true); + assert.equal(exported.has("baz"), true); + assert.equal(exported.has("BASE_TILE"), true); + assert.equal(exported.has("Foo"), false); + assert.equal(exported.has("transformPointMat4"), false); + assert.deepEqual( + imported.filter((name) => !exported.has(name)), + ["transformPointMat4"], + ); +}); diff --git a/AGENTS.md b/AGENTS.md index 22e598eac..24c2bcf8f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -54,7 +54,7 @@ Public API is **mirrored** across React and Vue. Explicit `*/three` subpaths (`@ - `pnpm check:mirrors --require-base` — identical react↔vue files, 12 mirror sets covering all of `packages/{react,vue}/src`, per-pair & cross-lane-group diff parity against base ref, and fail-closed tamper-evident waivers (`.github/mirror-waivers.json`). Note: touch parity ≠ semantic parity. - `pnpm check:exports` — React↔Vue root and `./three` barrel value/type export parity (block, direct, and namespace exports; fails closed on bare `export *`). - `pnpm check:ir` — zero-browser cross-renderer DOM/CSS IR conformance across compiled `polycss`, `react`, and `vue` `dist/index.js` in `happy-dom` (real lighting/normal/albedo vars, baked paint, transforms, shadows, and `*/three`). - - `pnpm check:packs` — read-only parallel `pnpm pack` verification for all 7 publishable packages (all declared entries + `typesVersions` + `README.md`, zero `workspace:` leaks, zero test files). + - `pnpm check:packs` — read-only parallel `pnpm pack` verification for all 7 publishable packages (all declared entries + `typesVersions` + `README.md`, zero `workspace:` leaks, zero test files, plus zero-network `morph` registry-dependency export compatibility against the published `core` version). - `pnpm check:readmes` and `pnpm check:skill` — shared README blocks and website skill sync. ## Backward compatibility & iterating on the system @@ -86,6 +86,7 @@ Public API is **mirrored** across React and Vue. Explicit `*/three` subpaths (`@ - `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. +- **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/bench/gate/cases.mjs b/bench/gate/cases.mjs index 2975e8383..4ec309a19 100644 --- a/bench/gate/cases.mjs +++ b/bench/gate/cases.mjs @@ -1,6 +1,9 @@ /** * Declarative visual-gate test matrices and frame-locked iframe driver HTML. */ +import { dirFromAzEl } from "../math.mjs"; + +export { dirFromAzEl }; export const DRIVER_HTML = ` @@ -28,13 +31,6 @@ export const DRIVER_HTML = ` `; -export function dirFromAzEl(azDeg, elDeg) { - const az = (azDeg * Math.PI) / 180; - const el = (elDeg * Math.PI) / 180; - const cosEl = Math.cos(el); - return [cosEl * Math.sin(az), cosEl * Math.cos(az), Math.sin(el)]; -} - export function lerpHexColor(t) { // Smooth cycle across white -> pure red -> pure green -> pure blue -> white const stops = [ @@ -429,17 +425,7 @@ export const VIDEO_ORACLE_CASES = [ bakedPage: "perf-react.html", dynQuery: "mesh=chicken&mode=dynamic&motion=none&az=40&el=35&nohud=1", bakedBaseQuery: "mesh=chicken&mode=baked&motion=none&az=40&el=35&nohud=1", - frame(k, n) { - const t = k / n; - const rx = 25 * Math.sin(t * Math.PI * 2); - const ry = t * 360; - const rz = 20 * Math.cos(t * Math.PI * 2); - return { - tag: `r=[${rx.toFixed(0)},${ry.toFixed(0)},${rz.toFixed(0)}]`, - msgs: [{ kind: "set-object", rotation: [rx, ry, rz] }], - bakedExtra: `orx=${rx.toFixed(3)}&ory=${ry.toFixed(3)}&orz=${rz.toFixed(3)}`, - }; - }, + frame: chickenTumbleFrame, }, { id: "video-oracle-chicken-tumble-vue", @@ -448,16 +434,18 @@ export const VIDEO_ORACLE_CASES = [ bakedPage: "perf-vue.html", dynQuery: "mesh=chicken&mode=dynamic&motion=none&az=40&el=35&nohud=1", bakedBaseQuery: "mesh=chicken&mode=baked&motion=none&az=40&el=35&nohud=1", - frame(k, n) { - const t = k / n; - const rx = 25 * Math.sin(t * Math.PI * 2); - const ry = t * 360; - const rz = 20 * Math.cos(t * Math.PI * 2); - return { - tag: `r=[${rx.toFixed(0)},${ry.toFixed(0)},${rz.toFixed(0)}]`, - msgs: [{ kind: "set-object", rotation: [rx, ry, rz] }], - bakedExtra: `orx=${rx.toFixed(3)}&ory=${ry.toFixed(3)}&orz=${rz.toFixed(3)}`, - }; - }, + frame: chickenTumbleFrame, }, ]; + +function chickenTumbleFrame(k, n) { + const t = k / n; + const rx = 25 * Math.sin(t * Math.PI * 2); + const ry = t * 360; + const rz = 20 * Math.cos(t * Math.PI * 2); + return { + tag: `r=[${rx.toFixed(0)},${ry.toFixed(0)},${rz.toFixed(0)}]`, + msgs: [{ kind: "set-object", rotation: [rx, ry, rz] }], + bakedExtra: `orx=${rx.toFixed(3)}&ory=${ry.toFixed(3)}&orz=${rz.toFixed(3)}`, + }; +} diff --git a/bench/math.mjs b/bench/math.mjs new file mode 100644 index 000000000..0c6c0bac0 --- /dev/null +++ b/bench/math.mjs @@ -0,0 +1,19 @@ +/** + * Zero-dependency math & statistics helpers shared between Node bench/gate + * scripts and browser bench pages. + */ +export function dirFromAzEl(azDeg, elDeg) { + const az = (azDeg * Math.PI) / 180; + const el = (elDeg * Math.PI) / 180; + const cosEl = Math.cos(el); + return [cosEl * Math.sin(az), cosEl * Math.cos(az), Math.sin(el)]; +} + +export function quantile(sorted, q) { + if (sorted.length === 0) return 0; + const i = (sorted.length - 1) * q; + const lo = Math.floor(i); + const hi = Math.ceil(i); + if (lo === hi) return sorted[lo]; + return sorted[lo] + (sorted[hi] - sorted[lo]) * (i - lo); +} diff --git a/bench/perf-bench.mjs b/bench/perf-bench.mjs index b523c4665..e12d5b27f 100644 --- a/bench/perf-bench.mjs +++ b/bench/perf-bench.mjs @@ -20,6 +20,7 @@ import { fileURLToPath } from "node:url"; import { chromiumArgsWithGpuDefault } from "./chromium-defaults.mjs"; import { findCachedExecutable, launchBrowser } from "./browser-discovery.mjs"; import { startStaticServer } from "./http-server.mjs"; +import { quantile } from "./math.mjs"; const __dirname = dirname(fileURLToPath(import.meta.url)); const repoRoot = resolve(__dirname, ".."); @@ -101,15 +102,6 @@ function startServer() { } // ── stats helpers ────────────────────────────────────────────────────── -function quantile(sorted, q) { - if (sorted.length === 0) return 0; - const i = (sorted.length - 1) * q; - const lo = Math.floor(i); - const hi = Math.ceil(i); - if (lo === hi) return sorted[lo]; - return sorted[lo] + (sorted[hi] - sorted[lo]) * (i - lo); -} - function summarizeFrameTimes(dts, rawCount) { const sample_count_raw = rawCount ?? dts.length; if (dts.length === 0) return { fps_p50: 0, fps_p95: 0, frame_time_p50_ms: 0, frame_time_p95_ms: 0, frame_time_p99_ms: 0, sample_count: 0, sample_count_raw, sample_count_filtered: sample_count_raw, is_bimodal: false }; diff --git a/bench/perf-gate.mjs b/bench/perf-gate.mjs index a77bfa0c8..64bb449f1 100644 --- a/bench/perf-gate.mjs +++ b/bench/perf-gate.mjs @@ -39,6 +39,7 @@ import { dirname, resolve } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { startStaticServer } from "./http-server.mjs"; import { findCachedExecutable, launchBrowser } from "./browser-discovery.mjs"; +import { quantile } from "./math.mjs"; const __dirname = dirname(fileURLToPath(import.meta.url)); const repoRoot = resolve(__dirname, ".."); @@ -202,15 +203,6 @@ export function parsePerfCliArgs(argv) { return cfg; } -function quantile(sorted, q) { - if (sorted.length === 0) return 0; - const i = (sorted.length - 1) * q; - const lo = Math.floor(i); - const hi = Math.ceil(i); - if (lo === hi) return sorted[lo]; - return sorted[lo] + (sorted[hi] - sorted[lo]) * (i - lo); -} - export function summarizeFrameTimes(dts, rawCount = dts.length) { if (dts.length === 0) { return { diff --git a/bench/perf-shared.mjs b/bench/perf-shared.mjs index 704e4d63a..99c1a468b 100644 --- a/bench/perf-shared.mjs +++ b/bench/perf-shared.mjs @@ -14,6 +14,7 @@ * update; this module just provides the measurement surface. */ import { BASE_TILE, collectPolyRenderStats } from "./.generated/polycss-render-stats.js"; +export { dirFromAzEl } from "./math.mjs"; // These presets were authored against the old bench scene-scale control. // Runtime camera zoom is now px per world unit, so convert at the fixture @@ -302,13 +303,6 @@ export function buildFloorPolygons(halfSize = 80) { }]; } -export function dirFromAzEl(azDeg, elDeg) { - const az = (azDeg * Math.PI) / 180; - const el = (elDeg * Math.PI) / 180; - const cosEl = Math.cos(el); - return [cosEl * Math.sin(az), cosEl * Math.cos(az), Math.sin(el)]; -} - /** * Parity-quad postMessage protocol — used when `?sync=1` is set on a perf * page. Each perf-*.html implements the per-renderer `apply*` callbacks via diff --git a/bench/renderer-ir-conformance.test.mjs b/bench/renderer-ir-conformance.test.mjs index 979771989..842f30dc9 100644 --- a/bench/renderer-ir-conformance.test.mjs +++ b/bench/renderer-ir-conformance.test.mjs @@ -584,3 +584,8 @@ test("IR conformance: */three Y-up camera + mesh transform produces identical le assert.deepEqual(irR.leafSigs, irV.leafSigs); assert.deepEqual(irU.leafSigs, irV.leafSigs); }); + +test("dist/index.js retains every @layoutit/polycss-core re-export under chunk splitting", () => { + const missing = Object.keys(core).filter((name) => !(name in vanilla)); + assert.deepEqual(missing, [], `Missing @layoutit/polycss-core re-exports in dist/index.js: ${missing.join(", ")}`); +}); diff --git a/bench/visual-gate.mjs b/bench/visual-gate.mjs index d53c215c4..dc6c7c43d 100644 --- a/bench/visual-gate.mjs +++ b/bench/visual-gate.mjs @@ -612,7 +612,15 @@ async function launchEngine(engine, cfg) { }); } -export async function runVisualGate(cfg) { +export function attachPageErrorListeners(page, sink) { + if (!page) return; + page.on("pageerror", (err) => sink.push(`pageerror: ${err?.message ?? err}`)); + page.on("console", (msg) => { + if (msg.type() === "error") sink.push(`console.error: ${msg.text()}`); + }); +} + +async function runVisualGate(cfg) { const modePlan = resolveModeSuites(cfg.mode); const { runStrict, runOracle, runParity, runVideo, runVideoOracle, isVideoMode } = modePlan; @@ -871,15 +879,8 @@ export async function runVisualGate(cfg) { const candPage = isWebKit ? null : await ctx.newPage(); const pmOpts = pixelmatchOpts(engine, "video", cfg); const videoErrors = []; - const attachErrs = (p) => { - if (!p) return; - p.on("pageerror", (err) => videoErrors.push(`pageerror: ${err?.message ?? err}`)); - p.on("console", (msg) => { - if (msg.type() === "error") videoErrors.push(`console.error: ${msg.text()}`); - }); - }; - attachErrs(basePage); - attachErrs(candPage); + attachPageErrorListeners(basePage, videoErrors); + attachPageErrorListeners(candPage, videoErrors); try { for (const c of VIDEO_STRICT_CASES) { if (c.engines && !c.engines.includes(engine)) continue; @@ -994,15 +995,8 @@ export async function runVisualGate(cfg) { const pmOpts = pixelmatchOpts(engine, "video-oracle", cfg); const oraclePort = cfg.oracleFromCand ? candSrv.port : baseSrv.port; const videoErrors = []; - const attachErrs = (p) => { - if (!p) return; - p.on("pageerror", (err) => videoErrors.push(`pageerror: ${err?.message ?? err}`)); - p.on("console", (msg) => { - if (msg.type() === "error") videoErrors.push(`console.error: ${msg.text()}`); - }); - }; - attachErrs(basePage); - attachErrs(candPage); + attachPageErrorListeners(basePage, videoErrors); + attachPageErrorListeners(candPage, videoErrors); try { for (const c of VIDEO_ORACLE_CASES) { if (c.engines && !c.engines.includes(engine)) continue; diff --git a/packages/core/src/atlas/plan.ts b/packages/core/src/atlas/plan.ts index 17d8516d1..12a29c298 100644 --- a/packages/core/src/atlas/plan.ts +++ b/packages/core/src/atlas/plan.ts @@ -5,6 +5,8 @@ import type { Vec2, Vec3, } from "../types"; +import { crossVec } from "../math/vec3"; +export { crossVec }; import { DEFAULT_TILE, DEFAULT_LIGHT_DIR, @@ -188,14 +190,6 @@ export function dotVec(a: Vec3, b: Vec3): number { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } -export function crossVec(a: Vec3, b: Vec3): Vec3 { - return [ - a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0], - ]; -} - export function isBasisOptimizable(polygon: Polygon): boolean { return !polygon.texture; } diff --git a/packages/core/src/atlas/solidTriangle.ts b/packages/core/src/atlas/solidTriangle.ts index 3e90ac691..31ad379dc 100644 --- a/packages/core/src/atlas/solidTriangle.ts +++ b/packages/core/src/atlas/solidTriangle.ts @@ -52,7 +52,7 @@ export function isConvexPolygonPoints(points: Array<[number, number]>): boolean return true; } -export function signedArea2D(points: Array<[number, number]>): number { +export function signedArea2D(points: ReadonlyArray): number { let area = 0; for (let i = 0; i < points.length; i++) { const a = points[i]; diff --git a/packages/core/src/color/color.ts b/packages/core/src/color/color.ts index cf1c13987..62bfdb545 100644 --- a/packages/core/src/color/color.ts +++ b/packages/core/src/color/color.ts @@ -58,3 +58,55 @@ export function formatColor(color: ParsedColor): string { ? `rgba(${r}, ${g}, ${b}, ${color.alpha})` : `rgb(${r}, ${g}, ${b})`; } + +export interface HsvColor { + hue: number; + saturation: number; + value: number; +} + +export function colorDistance( + a: { rgb: readonly [number, number, number] }, + b: { rgb: readonly [number, number, number] }, +): number { + return Math.hypot( + a.rgb[0] - b.rgb[0], + a.rgb[1] - b.rgb[1], + a.rgb[2] - b.rgb[2], + ); +} + +export function hsvFromColor(color: { rgb: readonly [number, number, number] }): HsvColor { + const r = color.rgb[0] / 255; + const g = color.rgb[1] / 255; + const b = color.rgb[2] / 255; + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + const delta = max - min; + let hue = 0; + if (delta !== 0) { + if (max === r) hue = 60 * (((g - b) / delta) % 6); + else if (max === g) hue = 60 * ((b - r) / delta + 2); + else hue = 60 * ((r - g) / delta + 4); + } + if (hue < 0) hue += 360; + return { + hue, + saturation: max === 0 ? 0 : delta / max, + value: max, + }; +} + +export function hueDistance(a: number, b: number): number { + const delta = Math.abs(a - b) % 360; + return delta > 180 ? 360 - delta : delta; +} + +/** Normalize an opaque pure CSS color to `#rrggbb`, falling back to trimmed lowercase. */ +export function normalizeSolidColorKey(color: string): string { + const parsed = parsePureColor(color); + if (!parsed || parsed.alpha < 1) return color.trim().toLowerCase(); + return `#${parsed.rgb + .map((channel) => Math.max(0, Math.min(255, Math.round(channel))).toString(16).padStart(2, "0")) + .join("")}`; +} diff --git a/packages/core/src/cull/bvh.ts b/packages/core/src/cull/bvh.ts new file mode 100644 index 000000000..6402cf787 --- /dev/null +++ b/packages/core/src/cull/bvh.ts @@ -0,0 +1,416 @@ +/** + * Shared flat-array SAH BVH and Möller–Trumbore ray-triangle intersection. + * + * Used by `cullInteriorPolygons` and `computeLightVisibility` for fast any-hit + * ray occlusion queries. + */ + +export const BVH_PARALLEL_EPS = 1e-9; +export const BVH_MIN_HIT_T = 1e-3; + +const BVH_STRIDE = 9; +const BVH_LEAF_SIZE = 6; +const DEFAULT_SAH_BUCKETS = 8; + +export interface BvhPolyMeta { + /** Flat triangle data: [ax,ay,az, bx,by,bz, cx,cy,cz, ...] per triangle */ + triFlat: Float64Array; + /** Bounding sphere center + radius² */ + bcx: number; + bcy: number; + bcz: number; + br2: number; + /** Axis-aligned bounding box */ + minX: number; + minY: number; + minZ: number; + maxX: number; + maxY: number; + maxZ: number; +} + +export interface BVH { + data: Float64Array; + nodeCount: number; + polyIndices: Int32Array; + meta: Array; +} + +/** + * Möller–Trumbore ray-triangle intersection (flat array variant). + * Returns true if the ray hits the triangle at t > BVH_MIN_HIT_T. + */ +export function rayTriFlat( + ox: number, + oy: number, + oz: number, + dx: number, + dy: number, + dz: number, + tf: Float64Array, + base: number, +): boolean { + const ax = tf[base]!; + const ay = tf[base + 1]!; + const az = tf[base + 2]!; + const e1x = tf[base + 3]! - ax; + const e1y = tf[base + 4]! - ay; + const e1z = tf[base + 5]! - az; + const e2x = tf[base + 6]! - ax; + const e2y = tf[base + 7]! - ay; + const e2z = tf[base + 8]! - az; + const hx = dy * e2z - dz * e2y; + const hy = dz * e2x - dx * e2z; + const hz = dx * e2y - dy * e2x; + const det = e1x * hx + e1y * hy + e1z * hz; + if (det > -BVH_PARALLEL_EPS && det < BVH_PARALLEL_EPS) return false; + const invDet = 1 / det; + const sx = ox - ax; + const sy = oy - ay; + const sz = oz - az; + const u = invDet * (sx * hx + sy * hy + sz * hz); + if (u < 0 || u > 1) return false; + const qx = sy * e1z - sz * e1y; + const qy = sz * e1x - sx * e1z; + const qz = sx * e1y - sy * e1x; + const v = invDet * (dx * qx + dy * qy + dz * qz); + if (v < 0 || u + v > 1) return false; + return invDet * (e2x * qx + e2y * qy + e2z * qz) > BVH_MIN_HIT_T; +} + +/** + * Test if ray hits any triangle in polygon `q`, using a bounding-sphere + * pre-reject before triangle testing. + */ +export function rayHitsPolygon( + ox: number, + oy: number, + oz: number, + dx: number, + dy: number, + dz: number, + q: BvhPolyMeta, +): boolean { + const vx = q.bcx - ox; + const vy = q.bcy - oy; + const vz = q.bcz - oz; + const proj = vx * dx + vy * dy + vz * dz; + const perpX = vx - proj * dx; + const perpY = vy - proj * dy; + const perpZ = vz - proj * dz; + if (perpX * perpX + perpY * perpY + perpZ * perpZ > q.br2) return false; + const tf = q.triFlat; + const n = tf.length; + for (let b = 0; b < n; b += 9) { + if (rayTriFlat(ox, oy, oz, dx, dy, dz, tf, b)) return true; + } + return false; +} + +/** Half-surface-area of an AABB (factor 2 cancels in SAH ratios). */ +function aabbSA( + minX: number, + minY: number, + minZ: number, + maxX: number, + maxY: number, + maxZ: number, +): number { + const dx = maxX - minX; + const dy = maxY - minY; + const dz = maxZ - minZ; + return dx * dy + dy * dz + dz * dx; +} + +/** + * Build a flat-array SAH-bucketed binary BVH over polygon metadata. + * Node layout (9 Float64 values per node): + * [0..5] AABB: minX minY minZ maxX maxY maxZ + * [6] isLeaf: 1 = leaf, 0 = internal + * [7,8] internal: leftIdx, rightIdx; leaf: start, end into polyIndices + */ +export function buildBVH( + meta: Array, + sahBuckets = DEFAULT_SAH_BUCKETS, +): BVH { + const valid: number[] = []; + for (let i = 0; i < meta.length; i++) { + if (meta[i]) valid.push(i); + } + const n = valid.length; + const polyIndices = new Int32Array(n); + for (let i = 0; i < n; i++) polyIndices[i] = valid[i]!; + + const centX = new Float64Array(n); + const centY = new Float64Array(n); + const centZ = new Float64Array(n); + for (let i = 0; i < n; i++) { + const m = meta[polyIndices[i]!]!; + centX[i] = (m.minX + m.maxX) * 0.5; + centY[i] = (m.minY + m.maxY) * 0.5; + centZ[i] = (m.minZ + m.maxZ) * 0.5; + } + + const maxNodes = 2 * Math.max(1, n) + 1; + const data = new Float64Array(maxNodes * BVH_STRIDE); + let nodeCount = 0; + + const bMinX = new Float64Array(sahBuckets); + const bMinY = new Float64Array(sahBuckets); + const bMinZ = new Float64Array(sahBuckets); + const bMaxX = new Float64Array(sahBuckets); + const bMaxY = new Float64Array(sahBuckets); + const bMaxZ = new Float64Array(sahBuckets); + const bCnt = new Int32Array(sahBuckets); + const lSA = new Float64Array(sahBuckets - 1); + const lCnt = new Int32Array(sahBuckets - 1); + const rSA = new Float64Array(sahBuckets - 1); + const rCnt = new Int32Array(sahBuckets - 1); + + function buildNode(start: number, end: number): number { + const ni = nodeCount++; + const base = ni * BVH_STRIDE; + const count = end - start; + + let minX = Infinity; + let minY = Infinity; + let minZ = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + let maxZ = -Infinity; + for (let i = start; i < end; i++) { + const m = meta[polyIndices[i]!]!; + if (m.minX < minX) minX = m.minX; + if (m.maxX > maxX) maxX = m.maxX; + if (m.minY < minY) minY = m.minY; + if (m.maxY > maxY) maxY = m.maxY; + if (m.minZ < minZ) minZ = m.minZ; + if (m.maxZ > maxZ) maxZ = m.maxZ; + } + data[base] = minX; + data[base + 1] = minY; + data[base + 2] = minZ; + data[base + 3] = maxX; + data[base + 4] = maxY; + data[base + 5] = maxZ; + + if (count <= BVH_LEAF_SIZE) { + data[base + 6] = 1; + data[base + 7] = start; + data[base + 8] = end; + return ni; + } + + let cxMin = Infinity; + let cyMin = Infinity; + let czMin = Infinity; + let cxMax = -Infinity; + let cyMax = -Infinity; + let czMax = -Infinity; + for (let i = start; i < end; i++) { + if (centX[i]! < cxMin) cxMin = centX[i]!; + if (centX[i]! > cxMax) cxMax = centX[i]!; + if (centY[i]! < cyMin) cyMin = centY[i]!; + if (centY[i]! > cyMax) cyMax = centY[i]!; + if (centZ[i]! < czMin) czMin = centZ[i]!; + if (centZ[i]! > czMax) czMax = centZ[i]!; + } + const extX = cxMax - cxMin; + const extY = cyMax - cyMin; + const extZ = czMax - czMin; + + if (extX === 0 && extY === 0 && extZ === 0) { + data[base + 6] = 1; + data[base + 7] = start; + data[base + 8] = end; + return ni; + } + + const nodeSA = aabbSA(minX, minY, minZ, maxX, maxY, maxZ); + const invSA = nodeSA > 0 ? 1 / nodeSA : 0; + let bestCost = count + 1; + let bestAxis = 0; + let bestSplitVal = 0; + + for (let axis = 0; axis < 3; axis++) { + const cMin = axis === 0 ? cxMin : axis === 1 ? cyMin : czMin; + const ext = axis === 0 ? extX : axis === 1 ? extY : extZ; + if (ext === 0) continue; + const centArr = axis === 0 ? centX : axis === 1 ? centY : centZ; + const scale = sahBuckets / ext; + + bMinX.fill(Infinity); + bMinY.fill(Infinity); + bMinZ.fill(Infinity); + bMaxX.fill(-Infinity); + bMaxY.fill(-Infinity); + bMaxZ.fill(-Infinity); + bCnt.fill(0); + + for (let i = start; i < end; i++) { + let b = ((centArr[i]! - cMin) * scale) | 0; + if (b >= sahBuckets) b = sahBuckets - 1; + const m = meta[polyIndices[i]!]!; + if (m.minX < bMinX[b]!) bMinX[b] = m.minX; + if (m.maxX > bMaxX[b]!) bMaxX[b] = m.maxX; + if (m.minY < bMinY[b]!) bMinY[b] = m.minY; + if (m.maxY > bMaxY[b]!) bMaxY[b] = m.maxY; + if (m.minZ < bMinZ[b]!) bMinZ[b] = m.minZ; + if (m.maxZ > bMaxZ[b]!) bMaxZ[b] = m.maxZ; + bCnt[b]!++; + } + + let lx0 = Infinity; + let ly0 = Infinity; + let lz0 = Infinity; + let lx1 = -Infinity; + let ly1 = -Infinity; + let lz1 = -Infinity; + let lc = 0; + for (let k = 0; k < sahBuckets - 1; k++) { + if (bMinX[k]! < lx0) lx0 = bMinX[k]!; + if (bMaxX[k]! > lx1) lx1 = bMaxX[k]!; + if (bMinY[k]! < ly0) ly0 = bMinY[k]!; + if (bMaxY[k]! > ly1) ly1 = bMaxY[k]!; + if (bMinZ[k]! < lz0) lz0 = bMinZ[k]!; + if (bMaxZ[k]! > lz1) lz1 = bMaxZ[k]!; + lc += bCnt[k]!; + lSA[k] = aabbSA(lx0, ly0, lz0, lx1, ly1, lz1); + lCnt[k] = lc; + } + + let rx0 = Infinity; + let ry0 = Infinity; + let rz0 = Infinity; + let rx1 = -Infinity; + let ry1 = -Infinity; + let rz1 = -Infinity; + let rc = 0; + for (let k = sahBuckets - 2; k >= 0; k--) { + const kb = k + 1; + if (bMinX[kb]! < rx0) rx0 = bMinX[kb]!; + if (bMaxX[kb]! > rx1) rx1 = bMaxX[kb]!; + if (bMinY[kb]! < ry0) ry0 = bMinY[kb]!; + if (bMaxY[kb]! > ry1) ry1 = bMaxY[kb]!; + if (bMinZ[kb]! < rz0) rz0 = bMinZ[kb]!; + if (bMaxZ[kb]! > rz1) rz1 = bMaxZ[kb]!; + rc += bCnt[kb]!; + rSA[k] = aabbSA(rx0, ry0, rz0, rx1, ry1, rz1); + rCnt[k] = rc; + } + + for (let k = 0; k < sahBuckets - 1; k++) { + if (lCnt[k] === 0 || rCnt[k] === 0) continue; + const cost = 0.125 + (lSA[k]! * lCnt[k]! + rSA[k]! * rCnt[k]!) * invSA; + if (cost < bestCost) { + bestCost = cost; + bestAxis = axis; + bestSplitVal = cMin + (k + 1) / scale; + } + } + } + + const centArr2 = bestAxis === 0 ? centX : bestAxis === 1 ? centY : centZ; + let lo = start; + let hi = end - 1; + while (lo <= hi) { + if (centArr2[lo]! < bestSplitVal) { + lo++; + } else { + const tmp = polyIndices[lo]!; + polyIndices[lo] = polyIndices[hi]!; + polyIndices[hi] = tmp; + const t0 = centX[lo]!; + centX[lo] = centX[hi]!; + centX[hi] = t0; + const t1 = centY[lo]!; + centY[lo] = centY[hi]!; + centY[hi] = t1; + const t2 = centZ[lo]!; + centZ[lo] = centZ[hi]!; + centZ[hi] = t2; + hi--; + } + } + let mid = lo; + if (mid === start || mid === end) mid = (start + end) >> 1; + + data[base + 6] = 0; + const left = buildNode(start, mid); + const right = buildNode(mid, end); + data[ni * BVH_STRIDE + 7] = left; + data[ni * BVH_STRIDE + 8] = right; + + return ni; + } + + if (n > 0) buildNode(0, n); + return { data, nodeCount, polyIndices, meta }; +} + +/** + * Any-hit ray traversal over the BVH. Returns true immediately on first hit. + */ +export function rayHitsAnyInBVH( + ox: number, + oy: number, + oz: number, + dx: number, + dy: number, + dz: number, + selfIdx: number, + bvh: BVH, + stack: Int32Array, +): boolean { + if (bvh.nodeCount === 0) return false; + const { data, polyIndices, meta } = bvh; + + const invDx = dx !== 0 ? 1 / dx : dx >= 0 ? Infinity : -Infinity; + const invDy = dy !== 0 ? 1 / dy : dy >= 0 ? Infinity : -Infinity; + const invDz = dz !== 0 ? 1 / dz : dz >= 0 ? Infinity : -Infinity; + + let top = 0; + stack[top++] = 0; + + while (top > 0) { + const ni = stack[--top]!; + const base = ni * BVH_STRIDE; + + const tx1 = (data[base]! - ox) * invDx; + const tx2 = (data[base + 3]! - ox) * invDx; + let tMin = tx1 < tx2 ? tx1 : tx2; + let tMax = tx1 < tx2 ? tx2 : tx1; + + const ty1 = (data[base + 1]! - oy) * invDy; + const ty2 = (data[base + 4]! - oy) * invDy; + const tyMin = ty1 < ty2 ? ty1 : ty2; + const tyMax = ty1 < ty2 ? ty2 : ty1; + if (tMin > tyMax || tyMin > tMax) continue; + if (tyMin > tMin) tMin = tyMin; + if (tyMax < tMax) tMax = tyMax; + + const tz1 = (data[base + 2]! - oz) * invDz; + const tz2 = (data[base + 5]! - oz) * invDz; + const tzMin = tz1 < tz2 ? tz1 : tz2; + const tzMax = tz1 < tz2 ? tz2 : tz1; + if (tMin > tzMax || tzMin > tMax) continue; + if (tzMax < tMax) tMax = tzMax; + + if (tMax < BVH_MIN_HIT_T) continue; + + if (data[base + 6] === 1) { + const start = data[base + 7]! | 0; + const end = data[base + 8]! | 0; + for (let k = start; k < end; k++) { + const j = polyIndices[k]!; + if (j === selfIdx) continue; + const q = meta[j]; + if (q && rayHitsPolygon(ox, oy, oz, dx, dy, dz, q)) return true; + } + } else { + stack[top++] = data[base + 7]! | 0; + stack[top++] = data[base + 8]! | 0; + } + } + return false; +} diff --git a/packages/core/src/cull/cullInteriorPolygons.ts b/packages/core/src/cull/cullInteriorPolygons.ts index 9267e3392..f34523320 100644 --- a/packages/core/src/cull/cullInteriorPolygons.ts +++ b/packages/core/src/cull/cullInteriorPolygons.ts @@ -19,11 +19,15 @@ * a truly hidden poly) are safe; false positives would be a visual bug. */ import type { Polygon, Vec3 } from "../types"; +import { + BVH_PARALLEL_EPS as PARALLEL_EPS, + buildBVH, + rayHitsAnyInBVH, + rayHitsPolygon, +} from "./bvh"; const DEFAULT_HEMISPHERE_SAMPLES = 8; const RAY_ORIGIN_OFFSET = 1e-3; -const MIN_HIT_T = 1e-3; -const PARALLEL_EPS = 1e-9; const OPEN_TOPOLOGY_MIN_POLYGONS = 100; const OPEN_TOPOLOGY_MIN_BOUNDARY_EDGES = 128; const OPEN_TOPOLOGY_BOUNDARY_RATIO = 0.2; @@ -146,322 +150,6 @@ function precompute(p: Polygon): PolyMeta | null { }; } -/** - * Möller–Trumbore ray-triangle intersection (flat array variant). - * Returns true if the ray hits the triangle at t > MIN_HIT_T. - */ -function rayTriFlat( - ox: number, oy: number, oz: number, - dx: number, dy: number, dz: number, - tf: Float64Array, base: number, -): boolean { - const ax = tf[base], ay = tf[base + 1], az = tf[base + 2]; - const e1x = tf[base + 3] - ax, e1y = tf[base + 4] - ay, e1z = tf[base + 5] - az; - const e2x = tf[base + 6] - ax, e2y = tf[base + 7] - ay, e2z = tf[base + 8] - az; - const hx = dy * e2z - dz * e2y; - const hy = dz * e2x - dx * e2z; - const hz = dx * e2y - dy * e2x; - const det = e1x * hx + e1y * hy + e1z * hz; - if (det > -PARALLEL_EPS && det < PARALLEL_EPS) return false; - const invDet = 1 / det; - const sx = ox - ax, sy = oy - ay, sz = oz - az; - const u = invDet * (sx * hx + sy * hy + sz * hz); - if (u < 0 || u > 1) return false; - const qx = sy * e1z - sz * e1y; - const qy = sz * e1x - sx * e1z; - const qz = sx * e1y - sy * e1x; - const v = invDet * (dx * qx + dy * qy + dz * qz); - if (v < 0 || u + v > 1) return false; - return invDet * (e2x * qx + e2y * qy + e2z * qz) > MIN_HIT_T; -} - -/** - * Test if ray hits any triangle in polygon q. - * Bounding-sphere pre-reject for non-BVH callers; BVH has already done AABB culling. - */ -function rayHitsPolygon( - ox: number, oy: number, oz: number, - dx: number, dy: number, dz: number, - q: PolyMeta, -): boolean { - // Bounding-sphere reject (keeps leaf testing fast for non-hitting rays). - const vx = q.bcx - ox, vy = q.bcy - oy, vz = q.bcz - oz; - const proj = vx * dx + vy * dy + vz * dz; - const perpX = vx - proj * dx; - const perpY = vy - proj * dy; - const perpZ = vz - proj * dz; - if (perpX * perpX + perpY * perpY + perpZ * perpZ > q.br2) return false; - const tf = q.triFlat; - const n = tf.length; - for (let b = 0; b < n; b += 9) { - if (rayTriFlat(ox, oy, oz, dx, dy, dz, tf, b)) return true; - } - return false; -} - -// ─── Flat-array SAH BVH ────────────────────────────────────────────────────── -// Node layout (BVH_STRIDE Float64 values per node): -// [0..5] AABB: minX minY minZ maxX maxY maxZ -// [6] isLeaf: 1 = leaf, 0 = internal -// Internal: [7] leftIdx [8] rightIdx -// Leaf: [7] start [8] end (into polyIndices) - -const BVH_STRIDE = 9; -const BVH_LEAF_SIZE = 6; -const SAH_BUCKETS = 8; - -interface BVH { - data: Float64Array; - nodeCount: number; - polyIndices: Int32Array; - meta: Array; -} - -/** Half-surface-area of an AABB (factor 2 cancels in SAH ratios). */ -function aabbSA(minX: number, minY: number, minZ: number, maxX: number, maxY: number, maxZ: number): number { - const dx = maxX - minX, dy = maxY - minY, dz = maxZ - minZ; - return dx * dy + dy * dz + dz * dx; -} - -function buildBVH(meta: Array): BVH { - const valid: number[] = []; - for (let i = 0; i < meta.length; i++) { if (meta[i]) valid.push(i); } - const n = valid.length; - const polyIndices = new Int32Array(n); - for (let i = 0; i < n; i++) polyIndices[i] = valid[i]; - - // Precompute centroid per reordered index slot. - const centX = new Float64Array(n); - const centY = new Float64Array(n); - const centZ = new Float64Array(n); - for (let i = 0; i < n; i++) { - const m = meta[polyIndices[i]]!; - centX[i] = (m.minX + m.maxX) * 0.5; - centY[i] = (m.minY + m.maxY) * 0.5; - centZ[i] = (m.minZ + m.maxZ) * 0.5; - } - - // Worst case: 2*N nodes for a balanced tree; +1 for safety. - const maxNodes = 2 * Math.max(1, n) + 1; - const data = new Float64Array(maxNodes * BVH_STRIDE); - let nodeCount = 0; - - // Reusable bucket arrays to avoid alloc in the hot build loop. - const bMinX = new Float64Array(SAH_BUCKETS); - const bMinY = new Float64Array(SAH_BUCKETS); - const bMinZ = new Float64Array(SAH_BUCKETS); - const bMaxX = new Float64Array(SAH_BUCKETS); - const bMaxY = new Float64Array(SAH_BUCKETS); - const bMaxZ = new Float64Array(SAH_BUCKETS); - const bCnt = new Int32Array(SAH_BUCKETS); - const lSA = new Float64Array(SAH_BUCKETS - 1); - const lCnt = new Int32Array(SAH_BUCKETS - 1); - const rSA = new Float64Array(SAH_BUCKETS - 1); - const rCnt = new Int32Array(SAH_BUCKETS - 1); - - function buildNode(start: number, end: number): number { - const ni = nodeCount++; - const base = ni * BVH_STRIDE; - const count = end - start; - - // Compute AABB for this range and write to node. - let minX = Infinity, minY = Infinity, minZ = Infinity; - let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity; - for (let i = start; i < end; i++) { - const m = meta[polyIndices[i]]!; - if (m.minX < minX) minX = m.minX; if (m.maxX > maxX) maxX = m.maxX; - if (m.minY < minY) minY = m.minY; if (m.maxY > maxY) maxY = m.maxY; - if (m.minZ < minZ) minZ = m.minZ; if (m.maxZ > maxZ) maxZ = m.maxZ; - } - data[base] = minX; data[base + 1] = minY; data[base + 2] = minZ; - data[base + 3] = maxX; data[base + 4] = maxY; data[base + 5] = maxZ; - - if (count <= BVH_LEAF_SIZE) { - data[base + 6] = 1; data[base + 7] = start; data[base + 8] = end; - return ni; - } - - // Centroid AABB for SAH axis selection. - let cxMin = Infinity, cyMin = Infinity, czMin = Infinity; - let cxMax = -Infinity, cyMax = -Infinity, czMax = -Infinity; - for (let i = start; i < end; i++) { - if (centX[i] < cxMin) cxMin = centX[i]; if (centX[i] > cxMax) cxMax = centX[i]; - if (centY[i] < cyMin) cyMin = centY[i]; if (centY[i] > cyMax) cyMax = centY[i]; - if (centZ[i] < czMin) czMin = centZ[i]; if (centZ[i] > czMax) czMax = centZ[i]; - } - const extX = cxMax - cxMin, extY = cyMax - cyMin, extZ = czMax - czMin; - - if (extX === 0 && extY === 0 && extZ === 0) { - data[base + 6] = 1; data[base + 7] = start; data[base + 8] = end; - return ni; - } - - const nodeSA = aabbSA(minX, minY, minZ, maxX, maxY, maxZ); - const invSA = nodeSA > 0 ? 1 / nodeSA : 0; - let bestCost = count + 1; - let bestAxis = 0, bestSplitVal = 0; - - // Evaluate SAH on all three axes. - for (let axis = 0; axis < 3; axis++) { - const cMin = axis === 0 ? cxMin : (axis === 1 ? cyMin : czMin); - const ext = axis === 0 ? extX : (axis === 1 ? extY : extZ); - if (ext === 0) continue; - const centArr = axis === 0 ? centX : (axis === 1 ? centY : centZ); - const scale = SAH_BUCKETS / ext; - - bMinX.fill(Infinity); bMinY.fill(Infinity); bMinZ.fill(Infinity); - bMaxX.fill(-Infinity); bMaxY.fill(-Infinity); bMaxZ.fill(-Infinity); - bCnt.fill(0); - - for (let i = start; i < end; i++) { - let b = (centArr[i] - cMin) * scale | 0; - if (b >= SAH_BUCKETS) b = SAH_BUCKETS - 1; - const m = meta[polyIndices[i]]!; - if (m.minX < bMinX[b]) bMinX[b] = m.minX; if (m.maxX > bMaxX[b]) bMaxX[b] = m.maxX; - if (m.minY < bMinY[b]) bMinY[b] = m.minY; if (m.maxY > bMaxY[b]) bMaxY[b] = m.maxY; - if (m.minZ < bMinZ[b]) bMinZ[b] = m.minZ; if (m.maxZ > bMaxZ[b]) bMaxZ[b] = m.maxZ; - bCnt[b]++; - } - - // Left sweep. - let lx0 = Infinity, ly0 = Infinity, lz0 = Infinity; - let lx1 = -Infinity, ly1 = -Infinity, lz1 = -Infinity; - let lc = 0; - for (let k = 0; k < SAH_BUCKETS - 1; k++) { - if (bMinX[k] < lx0) lx0 = bMinX[k]; if (bMaxX[k] > lx1) lx1 = bMaxX[k]; - if (bMinY[k] < ly0) ly0 = bMinY[k]; if (bMaxY[k] > ly1) ly1 = bMaxY[k]; - if (bMinZ[k] < lz0) lz0 = bMinZ[k]; if (bMaxZ[k] > lz1) lz1 = bMaxZ[k]; - lc += bCnt[k]; - lSA[k] = aabbSA(lx0, ly0, lz0, lx1, ly1, lz1); - lCnt[k] = lc; - } - // Right sweep. - let rx0 = Infinity, ry0 = Infinity, rz0 = Infinity; - let rx1 = -Infinity, ry1 = -Infinity, rz1 = -Infinity; - let rc = 0; - for (let k = SAH_BUCKETS - 2; k >= 0; k--) { - const kb = k + 1; - if (bMinX[kb] < rx0) rx0 = bMinX[kb]; if (bMaxX[kb] > rx1) rx1 = bMaxX[kb]; - if (bMinY[kb] < ry0) ry0 = bMinY[kb]; if (bMaxY[kb] > ry1) ry1 = bMaxY[kb]; - if (bMinZ[kb] < rz0) rz0 = bMinZ[kb]; if (bMaxZ[kb] > rz1) rz1 = bMaxZ[kb]; - rc += bCnt[kb]; - rSA[k] = aabbSA(rx0, ry0, rz0, rx1, ry1, rz1); - rCnt[k] = rc; - } - - for (let k = 0; k < SAH_BUCKETS - 1; k++) { - if (lCnt[k] === 0 || rCnt[k] === 0) continue; - const cost = 0.125 + (lSA[k] * lCnt[k] + rSA[k] * rCnt[k]) * invSA; - if (cost < bestCost) { - bestCost = cost; - bestAxis = axis; - bestSplitVal = cMin + (k + 1) / scale; - } - } - } - - // Partition around bestSplitVal on bestAxis. - const centArr2 = bestAxis === 0 ? centX : (bestAxis === 1 ? centY : centZ); - let lo = start, hi = end - 1; - while (lo <= hi) { - if (centArr2[lo] < bestSplitVal) { - lo++; - } else { - // Swap polyIndices and centroids. - const tmp = polyIndices[lo]; polyIndices[lo] = polyIndices[hi]; polyIndices[hi] = tmp; - const t0 = centX[lo]; centX[lo] = centX[hi]; centX[hi] = t0; - const t1 = centY[lo]; centY[lo] = centY[hi]; centY[hi] = t1; - const t2 = centZ[lo]; centZ[lo] = centZ[hi]; centZ[hi] = t2; - hi--; - } - } - let mid = lo; - if (mid === start || mid === end) mid = (start + end) >> 1; - - // Internal node: recurse. Must write children after recursion since - // nodeCount advances during recursion. - data[base + 6] = 0; - const left = buildNode(start, mid); - const right = buildNode(mid, end); - // Re-compute base since nodeCount changed (data buffer is fixed-size). - data[ni * BVH_STRIDE + 7] = left; - data[ni * BVH_STRIDE + 8] = right; - - return ni; - } - - if (n > 0) buildNode(0, n); - - return { data, nodeCount, polyIndices, meta }; -} - -/** - * Any-hit ray traversal over the BVH. Returns true immediately on first hit - * (perfect for occlusion queries). Uses an explicit stack for speed. - */ -function rayHitsAnyInBVH( - ox: number, oy: number, oz: number, - dx: number, dy: number, dz: number, - selfIdx: number, - bvh: BVH, - stack: Int32Array, -): boolean { - if (bvh.nodeCount === 0) return false; - const { data, polyIndices, meta } = bvh; - - const invDx = dx !== 0 ? 1 / dx : (dx >= 0 ? Infinity : -Infinity); - const invDy = dy !== 0 ? 1 / dy : (dy >= 0 ? Infinity : -Infinity); - const invDz = dz !== 0 ? 1 / dz : (dz >= 0 ? Infinity : -Infinity); - - let top = 0; - stack[top++] = 0; - - while (top > 0) { - const ni = stack[--top]; - const base = ni * BVH_STRIDE; - - // AABB slab test. - const tx1 = (data[base] - ox) * invDx; - const tx2 = (data[base + 3] - ox) * invDx; - let tMin = tx1 < tx2 ? tx1 : tx2; - let tMax = tx1 < tx2 ? tx2 : tx1; - - const ty1 = (data[base + 1] - oy) * invDy; - const ty2 = (data[base + 4] - oy) * invDy; - const tyMin = ty1 < ty2 ? ty1 : ty2; - const tyMax = ty1 < ty2 ? ty2 : ty1; - if (tMin > tyMax || tyMin > tMax) continue; - if (tyMin > tMin) tMin = tyMin; - if (tyMax < tMax) tMax = tyMax; - - const tz1 = (data[base + 2] - oz) * invDz; - const tz2 = (data[base + 5] - oz) * invDz; - const tzMin = tz1 < tz2 ? tz1 : tz2; - const tzMax = tz1 < tz2 ? tz2 : tz1; - if (tMin > tzMax || tzMin > tMax) continue; - if (tzMax < tMax) tMax = tzMax; - - if (tMax < MIN_HIT_T) continue; // AABB entirely behind origin - - if (data[base + 6] === 1) { - // Leaf node. - const start = data[base + 7] | 0; - const end = data[base + 8] | 0; - for (let k = start; k < end; k++) { - const j = polyIndices[k]; - if (j === selfIdx) continue; - const q = meta[j]; - if (q && rayHitsPolygon(ox, oy, oz, dx, dy, dz, q)) return true; - } - } else { - // Push both children; order doesn't matter for any-hit. - stack[top++] = data[base + 7] | 0; - stack[top++] = data[base + 8] | 0; - } - } - return false; -} - /** * Precompute K Fibonacci-spiral hemisphere samples as a flat Float64Array. * Layout: [lx0, ly0, lz0, lx1, ly1, lz1, ...] diff --git a/packages/core/src/cull/lightVisibility.ts b/packages/core/src/cull/lightVisibility.ts index fcd82c83a..958a38f42 100644 --- a/packages/core/src/cull/lightVisibility.ts +++ b/packages/core/src/cull/lightVisibility.ts @@ -14,10 +14,14 @@ * (mesh geometry version, lightDir hash) and only recompute on change. */ import type { Polygon, Vec3 } from "../types"; +import { + BVH_PARALLEL_EPS as PARALLEL_EPS, + buildBVH, + rayHitsAnyInBVH, +} from "./bvh"; -const PARALLEL_EPS = 1e-9; -const MIN_HIT_T = 1e-3; const RAY_ORIGIN_OFFSET = 1e-3; +const LIGHT_VISIBILITY_SAH_BUCKETS = 12; interface PolyMeta { triFlat: Float64Array; @@ -71,262 +75,6 @@ function precompute(p: Polygon): PolyMeta | null { }; } -function rayTriFlat( - ox: number, oy: number, oz: number, - dx: number, dy: number, dz: number, - tf: Float64Array, base: number, -): boolean { - const ax = tf[base], ay = tf[base + 1], az = tf[base + 2]; - const e1x = tf[base + 3] - ax, e1y = tf[base + 4] - ay, e1z = tf[base + 5] - az; - const e2x = tf[base + 6] - ax, e2y = tf[base + 7] - ay, e2z = tf[base + 8] - az; - const hx = dy * e2z - dz * e2y; - const hy = dz * e2x - dx * e2z; - const hz = dx * e2y - dy * e2x; - const det = e1x * hx + e1y * hy + e1z * hz; - if (det > -PARALLEL_EPS && det < PARALLEL_EPS) return false; - const invDet = 1 / det; - const sx = ox - ax, sy = oy - ay, sz = oz - az; - const u = invDet * (sx * hx + sy * hy + sz * hz); - if (u < 0 || u > 1) return false; - const qx = sy * e1z - sz * e1y; - const qy = sz * e1x - sx * e1z; - const qz = sx * e1y - sy * e1x; - const v = invDet * (dx * qx + dy * qy + dz * qz); - if (v < 0 || u + v > 1) return false; - return invDet * (e2x * qx + e2y * qy + e2z * qz) > MIN_HIT_T; -} - -function rayHitsPolygon( - ox: number, oy: number, oz: number, - dx: number, dy: number, dz: number, - q: PolyMeta, -): boolean { - const vx = q.bcx - ox, vy = q.bcy - oy, vz = q.bcz - oz; - const proj = vx * dx + vy * dy + vz * dz; - const perpX = vx - proj * dx; - const perpY = vy - proj * dy; - const perpZ = vz - proj * dz; - if (perpX * perpX + perpY * perpY + perpZ * perpZ > q.br2) return false; - const tf = q.triFlat; - const n = tf.length; - for (let b = 0; b < n; b += 9) { - if (rayTriFlat(ox, oy, oz, dx, dy, dz, tf, b)) return true; - } - return false; -} - -// Flat-array SAH BVH (mirrors cullInteriorPolygons). Node layout: -// [0..5] AABB minX minY minZ maxX maxY maxZ -// [6] isLeaf (1/0) -// [7,8] leaf: start,end into polyIndices; internal: left,right -const BVH_STRIDE = 9; -const BVH_LEAF_SIZE = 6; -const SAH_BUCKETS = 12; - -interface BVH { - data: Float64Array; - nodeCount: number; - polyIndices: Int32Array; - meta: Array; -} - -function aabbSA(minX: number, minY: number, minZ: number, maxX: number, maxY: number, maxZ: number): number { - const dx = maxX - minX, dy = maxY - minY, dz = maxZ - minZ; - return dx * dy + dy * dz + dz * dx; -} - -function buildBVH(meta: Array): BVH { - const valid: number[] = []; - for (let i = 0; i < meta.length; i++) { if (meta[i]) valid.push(i); } - const n = valid.length; - const polyIndices = new Int32Array(n); - for (let i = 0; i < n; i++) polyIndices[i] = valid[i]; - const centX = new Float64Array(n); - const centY = new Float64Array(n); - const centZ = new Float64Array(n); - for (let i = 0; i < n; i++) { - const m = meta[polyIndices[i]]!; - centX[i] = (m.minX + m.maxX) * 0.5; - centY[i] = (m.minY + m.maxY) * 0.5; - centZ[i] = (m.minZ + m.maxZ) * 0.5; - } - const maxNodes = 2 * Math.max(1, n) + 1; - const data = new Float64Array(maxNodes * BVH_STRIDE); - let nodeCount = 0; - const bMinX = new Float64Array(SAH_BUCKETS); - const bMinY = new Float64Array(SAH_BUCKETS); - const bMinZ = new Float64Array(SAH_BUCKETS); - const bMaxX = new Float64Array(SAH_BUCKETS); - const bMaxY = new Float64Array(SAH_BUCKETS); - const bMaxZ = new Float64Array(SAH_BUCKETS); - const bCnt = new Int32Array(SAH_BUCKETS); - const lSA = new Float64Array(SAH_BUCKETS - 1); - const lCnt = new Int32Array(SAH_BUCKETS - 1); - const rSA = new Float64Array(SAH_BUCKETS - 1); - const rCnt = new Int32Array(SAH_BUCKETS - 1); - function buildNode(start: number, end: number): number { - const ni = nodeCount++; - const base = ni * BVH_STRIDE; - const count = end - start; - let minX = Infinity, minY = Infinity, minZ = Infinity; - let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity; - for (let i = start; i < end; i++) { - const m = meta[polyIndices[i]]!; - if (m.minX < minX) minX = m.minX; if (m.maxX > maxX) maxX = m.maxX; - if (m.minY < minY) minY = m.minY; if (m.maxY > maxY) maxY = m.maxY; - if (m.minZ < minZ) minZ = m.minZ; if (m.maxZ > maxZ) maxZ = m.maxZ; - } - data[base] = minX; data[base + 1] = minY; data[base + 2] = minZ; - data[base + 3] = maxX; data[base + 4] = maxY; data[base + 5] = maxZ; - if (count <= BVH_LEAF_SIZE) { - data[base + 6] = 1; data[base + 7] = start; data[base + 8] = end; - return ni; - } - let cxMin = Infinity, cyMin = Infinity, czMin = Infinity; - let cxMax = -Infinity, cyMax = -Infinity, czMax = -Infinity; - for (let i = start; i < end; i++) { - if (centX[i] < cxMin) cxMin = centX[i]; if (centX[i] > cxMax) cxMax = centX[i]; - if (centY[i] < cyMin) cyMin = centY[i]; if (centY[i] > cyMax) cyMax = centY[i]; - if (centZ[i] < czMin) czMin = centZ[i]; if (centZ[i] > czMax) czMax = centZ[i]; - } - const extX = cxMax - cxMin, extY = cyMax - cyMin, extZ = czMax - czMin; - if (extX === 0 && extY === 0 && extZ === 0) { - data[base + 6] = 1; data[base + 7] = start; data[base + 8] = end; - return ni; - } - const nodeSA = aabbSA(minX, minY, minZ, maxX, maxY, maxZ); - const invSA = nodeSA > 0 ? 1 / nodeSA : 0; - let bestCost = count + 1; - let bestAxis = 0, bestSplitVal = 0; - for (let axis = 0; axis < 3; axis++) { - const cMin = axis === 0 ? cxMin : (axis === 1 ? cyMin : czMin); - const ext = axis === 0 ? extX : (axis === 1 ? extY : extZ); - if (ext === 0) continue; - const centArr = axis === 0 ? centX : (axis === 1 ? centY : centZ); - const scale = SAH_BUCKETS / ext; - bMinX.fill(Infinity); bMinY.fill(Infinity); bMinZ.fill(Infinity); - bMaxX.fill(-Infinity); bMaxY.fill(-Infinity); bMaxZ.fill(-Infinity); - bCnt.fill(0); - for (let i = start; i < end; i++) { - let b = (centArr[i] - cMin) * scale | 0; - if (b >= SAH_BUCKETS) b = SAH_BUCKETS - 1; - const m = meta[polyIndices[i]]!; - if (m.minX < bMinX[b]) bMinX[b] = m.minX; if (m.maxX > bMaxX[b]) bMaxX[b] = m.maxX; - if (m.minY < bMinY[b]) bMinY[b] = m.minY; if (m.maxY > bMaxY[b]) bMaxY[b] = m.maxY; - if (m.minZ < bMinZ[b]) bMinZ[b] = m.minZ; if (m.maxZ > bMaxZ[b]) bMaxZ[b] = m.maxZ; - bCnt[b]++; - } - let lx0 = Infinity, ly0 = Infinity, lz0 = Infinity; - let lx1 = -Infinity, ly1 = -Infinity, lz1 = -Infinity; - let lc = 0; - for (let k = 0; k < SAH_BUCKETS - 1; k++) { - if (bMinX[k] < lx0) lx0 = bMinX[k]; if (bMaxX[k] > lx1) lx1 = bMaxX[k]; - if (bMinY[k] < ly0) ly0 = bMinY[k]; if (bMaxY[k] > ly1) ly1 = bMaxY[k]; - if (bMinZ[k] < lz0) lz0 = bMinZ[k]; if (bMaxZ[k] > lz1) lz1 = bMaxZ[k]; - lc += bCnt[k]; - lSA[k] = aabbSA(lx0, ly0, lz0, lx1, ly1, lz1); - lCnt[k] = lc; - } - let rx0 = Infinity, ry0 = Infinity, rz0 = Infinity; - let rx1 = -Infinity, ry1 = -Infinity, rz1 = -Infinity; - let rc = 0; - for (let k = SAH_BUCKETS - 2; k >= 0; k--) { - const kb = k + 1; - if (bMinX[kb] < rx0) rx0 = bMinX[kb]; if (bMaxX[kb] > rx1) rx1 = bMaxX[kb]; - if (bMinY[kb] < ry0) ry0 = bMinY[kb]; if (bMaxY[kb] > ry1) ry1 = bMaxY[kb]; - if (bMinZ[kb] < rz0) rz0 = bMinZ[kb]; if (bMaxZ[kb] > rz1) rz1 = bMaxZ[kb]; - rc += bCnt[kb]; - rSA[k] = aabbSA(rx0, ry0, rz0, rx1, ry1, rz1); - rCnt[k] = rc; - } - for (let k = 0; k < SAH_BUCKETS - 1; k++) { - if (lCnt[k] === 0 || rCnt[k] === 0) continue; - const cost = 0.125 + (lSA[k] * lCnt[k] + rSA[k] * rCnt[k]) * invSA; - if (cost < bestCost) { - bestCost = cost; - bestAxis = axis; - bestSplitVal = cMin + (k + 1) / scale; - } - } - } - const centArr2 = bestAxis === 0 ? centX : (bestAxis === 1 ? centY : centZ); - let lo = start, hi = end - 1; - while (lo <= hi) { - if (centArr2[lo] < bestSplitVal) { - lo++; - } else { - const tmp = polyIndices[lo]; polyIndices[lo] = polyIndices[hi]; polyIndices[hi] = tmp; - const t0 = centX[lo]; centX[lo] = centX[hi]; centX[hi] = t0; - const t1 = centY[lo]; centY[lo] = centY[hi]; centY[hi] = t1; - const t2 = centZ[lo]; centZ[lo] = centZ[hi]; centZ[hi] = t2; - hi--; - } - } - let mid = lo; - if (mid === start || mid === end) mid = (start + end) >> 1; - data[base + 6] = 0; - const left = buildNode(start, mid); - const right = buildNode(mid, end); - data[ni * BVH_STRIDE + 7] = left; - data[ni * BVH_STRIDE + 8] = right; - return ni; - } - if (n > 0) buildNode(0, n); - return { data, nodeCount, polyIndices, meta }; -} - -function rayHitsAnyInBVH( - ox: number, oy: number, oz: number, - dx: number, dy: number, dz: number, - selfIdx: number, - bvh: BVH, - stack: Int32Array, -): boolean { - if (bvh.nodeCount === 0) return false; - const { data, polyIndices, meta } = bvh; - const invDx = dx !== 0 ? 1 / dx : (dx >= 0 ? Infinity : -Infinity); - const invDy = dy !== 0 ? 1 / dy : (dy >= 0 ? Infinity : -Infinity); - const invDz = dz !== 0 ? 1 / dz : (dz >= 0 ? Infinity : -Infinity); - let top = 0; - stack[top++] = 0; - while (top > 0) { - const ni = stack[--top]; - const base = ni * BVH_STRIDE; - const tx1 = (data[base] - ox) * invDx; - const tx2 = (data[base + 3] - ox) * invDx; - let tMin = tx1 < tx2 ? tx1 : tx2; - let tMax = tx1 < tx2 ? tx2 : tx1; - const ty1 = (data[base + 1] - oy) * invDy; - const ty2 = (data[base + 4] - oy) * invDy; - const tyMin = ty1 < ty2 ? ty1 : ty2; - const tyMax = ty1 < ty2 ? ty2 : ty1; - if (tMin > tyMax || tyMin > tMax) continue; - if (tyMin > tMin) tMin = tyMin; - if (tyMax < tMax) tMax = tyMax; - const tz1 = (data[base + 2] - oz) * invDz; - const tz2 = (data[base + 5] - oz) * invDz; - const tzMin = tz1 < tz2 ? tz1 : tz2; - const tzMax = tz1 < tz2 ? tz2 : tz1; - if (tMin > tzMax || tzMin > tMax) continue; - if (tzMax < tMax) tMax = tzMax; - if (tMax < MIN_HIT_T) continue; - if (data[base + 6] === 1) { - const start = data[base + 7] | 0; - const end = data[base + 8] | 0; - for (let k = start; k < end; k++) { - const j = polyIndices[k]; - if (j === selfIdx) continue; - const q = meta[j]; - if (q && rayHitsPolygon(ox, oy, oz, dx, dy, dz, q)) return true; - } - } else { - stack[top++] = data[base + 7] | 0; - stack[top++] = data[base + 8] | 0; - } - } - return false; -} - /** * Returns a Set of polygon indices that are OCCLUDED from the light * (a ray from the polygon's centroid in the +lightDir direction hits @@ -358,7 +106,7 @@ export function computeLightVisibility( if (skipIndices && skipIndices.size > 0) { for (const i of skipIndices) meta[i] = null; } - const bvh = buildBVH(meta); + const bvh = buildBVH(meta, LIGHT_VISIBILITY_SAH_BUCKETS); const stack = new Int32Array(Math.max(64, bvh.nodeCount)); for (let i = 0; i < polygons.length; i++) { const p = meta[i]; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 5122a4991..88bb5b917 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -33,6 +33,7 @@ export { buildSceneContext, computeSceneBbox, normalizePolygons, + recenterPolygons, } from "./scene/context"; export type { SceneContext, @@ -101,6 +102,7 @@ export { parseRgbColor, clampChannel, formatColor, + normalizeSolidColorKey, } from "./color/color"; // ── Mesh post-processing ────────────────────────────────────────── @@ -293,7 +295,7 @@ export { worldPositionToPolyCss, } from "./shadow/receiverFaceGroups"; export type { ReceiverPlaneGroup } from "./shadow/receiverFaceGroups"; -export { buildPolyMeshTransform } from "./transform/meshTransform"; +export { buildPolyIframeTransform, buildPolyMeshTransform } from "./transform/meshTransform"; export type { PolyMeshTransformInput } from "./transform/meshTransform"; export { buildPolySceneTransform } from "./transform/sceneTransform"; export type { PolySceneTransformInput } from "./transform/sceneTransform"; diff --git a/packages/core/src/math/vec3.ts b/packages/core/src/math/vec3.ts new file mode 100644 index 000000000..14d7e499d --- /dev/null +++ b/packages/core/src/math/vec3.ts @@ -0,0 +1,49 @@ +import type { Vec3 } from "../types"; + +export interface BoxBounds3D { + minX: number; + minY: number; + minZ: number; + maxX: number; + maxY: number; + maxZ: number; +} + +export function crossVec( + a: readonly [number, number, number], + b: readonly [number, number, number], +): Vec3 { + return [ + a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0], + ]; +} + +/** Unit vector; falls back to +Z for a zero-length input. */ +export function unitVec3(v: readonly [number, number, number]): Vec3 { + const len = Math.hypot(v[0], v[1], v[2]); + if (len < 1e-9) return [0, 0, 1]; + return [v[0] / len, v[1] / len, v[2] / len]; +} + +/** Transform a 3D point by a column-major 4x4 matrix. */ +export function transformPointMat4( + matrix: readonly number[], + point: readonly [number, number, number], +): Vec3 { + return [ + matrix[0]! * point[0] + matrix[4]! * point[1] + matrix[8]! * point[2] + matrix[12]!, + matrix[1]! * point[0] + matrix[5]! * point[1] + matrix[9]! * point[2] + matrix[13]!, + matrix[2]! * point[0] + matrix[6]! * point[1] + matrix[10]! * point[2] + matrix[14]!, + ]; +} + +export function boundsOverlap3D(a: BoxBounds3D, b: BoxBounds3D, tolerance: number): boolean { + return a.minX <= b.maxX + tolerance && + b.minX <= a.maxX + tolerance && + a.minY <= b.maxY + tolerance && + b.minY <= a.maxY + tolerance && + a.minZ <= b.maxZ + tolerance && + b.minZ <= a.maxZ + tolerance; +} diff --git a/packages/core/src/merge/coverPlanarPolygons.ts b/packages/core/src/merge/coverPlanarPolygons.ts index 358a7311d..228c529e7 100644 --- a/packages/core/src/merge/coverPlanarPolygons.ts +++ b/packages/core/src/merge/coverPlanarPolygons.ts @@ -1,3 +1,4 @@ +import { crossVec as cross } from "../math/vec3"; import type { Polygon, Vec2, Vec3 } from "../types"; import { mergePolygons } from "./mergePolygons"; @@ -65,11 +66,6 @@ const sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; const add = (a: Vec3, b: Vec3): Vec3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]]; const scale = (v: Vec3, n: number): Vec3 => [v[0] * n, v[1] * n, v[2] * n]; const dot = (a: Vec3, b: Vec3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; -const cross = (a: Vec3, b: Vec3): Vec3 => [ - a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0], -]; const length = (v: Vec3): number => Math.hypot(v[0], v[1], v[2]); function normalize(v: Vec3): Vec3 | null { diff --git a/packages/core/src/merge/dedupeOverlappingPolygons.ts b/packages/core/src/merge/dedupeOverlappingPolygons.ts index 10ef773d5..a914cdae8 100644 --- a/packages/core/src/merge/dedupeOverlappingPolygons.ts +++ b/packages/core/src/merge/dedupeOverlappingPolygons.ts @@ -36,6 +36,7 @@ * dedup logic never executes again. */ +import { crossVec as cross } from "../math/vec3"; import type { Polygon, Vec2, Vec3 } from "../types"; /** Tunable thresholds. Default values are conservative — only catch @@ -94,11 +95,6 @@ interface PolyMeta { } const sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; -const cross = (a: Vec3, b: Vec3): Vec3 => [ - a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0], -]; const dot = (a: Vec3, b: Vec3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; const norm = (a: Vec3): number => Math.hypot(a[0], a[1], a[2]); diff --git a/packages/core/src/merge/mergePolygons.ts b/packages/core/src/merge/mergePolygons.ts index 7796ec856..f64be0780 100644 --- a/packages/core/src/merge/mergePolygons.ts +++ b/packages/core/src/merge/mergePolygons.ts @@ -25,6 +25,8 @@ */ import type { Polygon, PolyTextureAlphaMode, PolyTextureWrap, TextureTriangle, Vec2, Vec3 } from "../types"; +import { crossVec as cross } from "../math/vec3"; +import { cloneTextureTriangles, fanTextureTriangles } from "./textureTriangles"; const EPS_NORMAL = 1e-3; // dot product tolerance for "same plane" const EPS_DISTANCE = 0.05; // signed-distance tolerance (in scene-space units) @@ -70,11 +72,6 @@ interface EdgeOwners { } const sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; -const cross = (a: Vec3, b: Vec3): Vec3 => [ - a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0], -]; const dot = (a: Vec3, b: Vec3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; const norm = (a: Vec3): number => Math.hypot(a[0], a[1], a[2]); const eqVec = (a: Vec3, b: Vec3): boolean => @@ -253,13 +250,6 @@ function mergeIsPlanar(vertices: Vec3[], epsilon: number): boolean { return true; } -function cloneTextureTriangles(triangles: TextureTriangle[]): TextureTriangle[] { - return triangles.map((triangle) => ({ - vertices: triangle.vertices.map((vertex) => [...vertex] as Vec3) as [Vec3, Vec3, Vec3], - uvs: triangle.uvs.map((uv) => [...uv] as Vec2) as [Vec2, Vec2, Vec2], - })); -} - function cloneImageSource(source: Polygon["textureImageSource"]): Polygon["textureImageSource"] { if (!source) return undefined; return { @@ -292,25 +282,6 @@ function sameTextureAlphaMode( return (a ?? "") === (b ?? ""); } -function fanTextureTriangles(vertices: Vec3[], uvs: Vec2[]): TextureTriangle[] { - const triangles: TextureTriangle[] = []; - for (let i = 1; i < vertices.length - 1; i++) { - triangles.push({ - vertices: [ - [...vertices[0]] as Vec3, - [...vertices[i]] as Vec3, - [...vertices[i + 1]] as Vec3, - ], - uvs: [ - [...uvs[0]] as Vec2, - [...uvs[i]] as Vec2, - [...uvs[i + 1]] as Vec2, - ], - }); - } - return triangles; -} - function rotateToNonCollinearStart(vertices: Vec3[], uvs?: Vec2[]): { vertices: Vec3[]; uvs?: Vec2[] } { for (let i = 0; i < vertices.length; i++) { const a = vertices[i]; diff --git a/packages/core/src/merge/optimizePolygons.ts b/packages/core/src/merge/optimizePolygons.ts index c5cf0637e..2a1fb191f 100644 --- a/packages/core/src/merge/optimizePolygons.ts +++ b/packages/core/src/merge/optimizePolygons.ts @@ -1,4 +1,5 @@ import { cullInteriorPolygons } from "../cull/cullInteriorPolygons"; +import { boundsOverlap3D as topologySegmentBoundsOverlap, crossVec } from "../math/vec3"; import { findOverlappingPolygonDuplicates } from "./dedupeOverlappingPolygons"; import type { MeshResolution, Polygon, TextureTriangle, Vec2, Vec3 } from "../types"; import { coverPlanarPolygons, type CoverPlanarPolygonsOptions } from "./coverPlanarPolygons"; @@ -8,6 +9,7 @@ import { simplifyTriangleMeshPolygons, type SimplifyTriangleMeshPolygonsOptions, } from "./simplifyTriangleMesh"; +import { cloneTextureTriangles, fanTextureTriangles } from "./textureTriangles"; const NORMALIZE_MAX_ANGLE_DEG = 3; const NORMALIZE_MAX_PLANE_DISPLACEMENT = 0.03; @@ -1254,15 +1256,6 @@ function segmentOverlap( return offset <= tolerance ? { overlapLength, offset } : null; } -function topologySegmentBoundsOverlap(a: TopologySegment, b: TopologySegment, tolerance: number): boolean { - return a.minX <= b.maxX + tolerance && - b.minX <= a.maxX + tolerance && - a.minY <= b.maxY + tolerance && - b.minY <= a.maxY + tolerance && - a.minZ <= b.maxZ + tolerance && - b.minZ <= a.maxZ + tolerance; -} - function aggressiveLossyMinRenderCostGain(sourcePolygonCount: number): number { return Math.max( AGGRESSIVE_LOSSY_MIN_RENDER_COST_GAIN, @@ -2157,32 +2150,6 @@ function textureTrianglesForPolygons(polygons: Polygon[]): TextureTriangle[] | u return triangles.length > 0 ? triangles : undefined; } -function fanTextureTriangles(vertices: Vec3[], uvs: Vec2[]): TextureTriangle[] { - const triangles: TextureTriangle[] = []; - for (let i = 1; i < vertices.length - 1; i++) { - triangles.push({ - vertices: [ - [...vertices[0]] as Vec3, - [...vertices[i]] as Vec3, - [...vertices[i + 1]] as Vec3, - ], - uvs: [ - [...uvs[0]] as Vec2, - [...uvs[i]] as Vec2, - [...uvs[i + 1]] as Vec2, - ], - }); - } - return triangles; -} - -function cloneTextureTriangles(triangles: TextureTriangle[]): TextureTriangle[] { - return triangles.map((triangle) => ({ - vertices: triangle.vertices.map((vertex) => [...vertex] as Vec3) as [Vec3, Vec3, Vec3], - uvs: triangle.uvs.map((uv) => [...uv] as Vec2) as [Vec2, Vec2, Vec2], - })); -} - function mapTextureTriangleVertices( triangles: TextureTriangle[] | undefined, mapVertex: (vertex: Vec3) => Vec3, @@ -2710,14 +2677,6 @@ function subVec(a: Vec3, b: Vec3): Vec3 { return [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; } -function crossVec(a: Vec3, b: Vec3): Vec3 { - return [ - a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0], - ]; -} - function dotVec(a: Vec3, b: Vec3): number { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } diff --git a/packages/core/src/merge/seamRepair.ts b/packages/core/src/merge/seamRepair.ts index a552df7c1..f8d78d34a 100644 --- a/packages/core/src/merge/seamRepair.ts +++ b/packages/core/src/merge/seamRepair.ts @@ -1,3 +1,6 @@ +import { signedArea2D as signedArea } from "../atlas/solidTriangle"; +import { rotateVec3 as rotateCssVec3 } from "../math/rotation"; +import { boundsOverlap3D as edgeBoundsCouldOverlap, crossVec as cross } from "../math/vec3"; import type { Polygon, Vec3 } from "../types"; import type { SeamFacetSplitCandidateReason as SplitReason, SeamFacetSplitOptions as SplitOptions, SeamFacetSplitReport as SplitReport, SeamOverlapCandidate as OverlapCandidate, SeamOverlapCandidateKind as OverlapKind, SeamOverlapDiagnostics as OverlapDiagnostics, SeamOverlapOptions as OverlapOptions } from "./seamRepairTypes"; export type * from "./seamRepairTypes"; @@ -120,34 +123,6 @@ function dot(a: Vec3, b: Vec3) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } -function rotateCssVec3(v: Vec3, rxDeg: number, ryDeg: number, rzDeg: number): Vec3 { - const dx = (rxDeg * Math.PI) / 180; - const dy = (ryDeg * Math.PI) / 180; - const dz = (rzDeg * Math.PI) / 180; - let [x, y, z] = v; - if (dz !== 0) { - const c = Math.cos(dz), s = Math.sin(dz); - [x, y] = [x * c - y * s, x * s + y * c]; - } - if (dy !== 0) { - const c = Math.cos(dy), s = Math.sin(dy); - [x, z] = [x * c + z * s, -x * s + z * c]; - } - if (dx !== 0) { - const c = Math.cos(dx), s = Math.sin(dx); - [y, z] = [y * c - z * s, y * s + z * c]; - } - return [x, y, z]; -} - -function cross(a: Vec3, b: Vec3): Vec3 { - return [ - a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0], - ]; -} - function surfaceNormal(points: Vec3[]): Vec3 | null { if (points.length < 3) return null; const origin = points[0]; @@ -197,16 +172,6 @@ function localBasis(points: Vec3[]): Basis | null { return Math.abs(area) > EPS ? { origin, normal, xAxis, yAxis, local, area } : null; } -function signedArea(points: Vec2[]) { - let area = 0; - for (let i = 0; i < points.length; i += 1) { - const a = points[i]; - const b = points[(i + 1) % points.length]; - area += a[0] * b[1] - a[1] * b[0]; - } - return area / 2; -} - function isWeaklyConvex(points: Vec2[]) { if (points.length < 3) return false; let sign = 0; @@ -614,15 +579,6 @@ function buildNearSeamEdgeAmounts( } } -function edgeBoundsCouldOverlap(a: Edge, b: Edge, maxGap: number) { - return a.minX <= b.maxX + maxGap && - b.minX <= a.maxX + maxGap && - a.minY <= b.maxY + maxGap && - b.minY <= a.maxY + maxGap && - a.minZ <= b.maxZ + maxGap && - b.minZ <= a.maxZ + maxGap; -} - function cellCoords(point: Vec3, cellSize: number): [number, number, number] { return [ Math.floor(point[0] / cellSize), diff --git a/packages/core/src/merge/simplifyTriangleMesh.ts b/packages/core/src/merge/simplifyTriangleMesh.ts index ae4ab3111..3df56952f 100644 --- a/packages/core/src/merge/simplifyTriangleMesh.ts +++ b/packages/core/src/merge/simplifyTriangleMesh.ts @@ -1,3 +1,4 @@ +import { crossVec } from "../math/vec3"; import type { Polygon, Vec3 } from "../types"; export interface SimplifyTriangleMeshPolygonsOptions { @@ -160,13 +161,6 @@ function dotVec(a: Vec3, b: Vec3): number { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } -function crossVec(a: Vec3, b: Vec3): Vec3 { - return [ - a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0], - ]; -} function lengthVec(a: Vec3): number { return Math.hypot(a[0], a[1], a[2]); diff --git a/packages/core/src/merge/textureTriangles.ts b/packages/core/src/merge/textureTriangles.ts new file mode 100644 index 000000000..1d6a102d9 --- /dev/null +++ b/packages/core/src/merge/textureTriangles.ts @@ -0,0 +1,27 @@ +import type { TextureTriangle, Vec2, Vec3 } from "../types"; + +export function cloneTextureTriangles(triangles: TextureTriangle[]): TextureTriangle[] { + return triangles.map((triangle) => ({ + vertices: triangle.vertices.map((vertex) => [...vertex] as Vec3) as [Vec3, Vec3, Vec3], + uvs: triangle.uvs.map((uv) => [...uv] as Vec2) as [Vec2, Vec2, Vec2], + })); +} + +export function fanTextureTriangles(vertices: Vec3[], uvs: Vec2[]): TextureTriangle[] { + const triangles: TextureTriangle[] = []; + for (let i = 1; i < vertices.length - 1; i++) { + triangles.push({ + vertices: [ + [...vertices[0]!] as Vec3, + [...vertices[i]!] as Vec3, + [...vertices[i + 1]!] as Vec3, + ], + uvs: [ + [...uvs[0]!] as Vec2, + [...uvs[i]!] as Vec2, + [...uvs[i + 1]!] as Vec2, + ], + }); + } + return triangles; +} diff --git a/packages/core/src/parser/optimizeMeshParseResult.ts b/packages/core/src/parser/optimizeMeshParseResult.ts index 91c0832a1..1852023ba 100644 --- a/packages/core/src/parser/optimizeMeshParseResult.ts +++ b/packages/core/src/parser/optimizeMeshParseResult.ts @@ -1,4 +1,10 @@ -import { parsePureColor } from "../color/color"; +import { + colorDistance, + hsvFromColor, + hueDistance, + normalizeSolidColorKey as colorKey, + parsePureColor, +} from "../color/color"; import { optimizeParseMeshPolygons } from "../merge/optimizePolygons"; import type { SimplifyTriangleMeshPolygonsOptions } from "../merge/simplifyTriangleMesh"; import type { MeshResolution, Polygon } from "../types"; @@ -9,12 +15,6 @@ interface RgbColor { alpha: number; } -interface HsvColor { - hue: number; - saturation: number; - value: number; -} - export interface OptimizeMeshParseResultOptions { /** Render-cost optimization intent. Defaults to "lossy". */ meshResolution?: MeshResolution; @@ -46,14 +46,6 @@ function hasTexturePaint(polygon: Polygon): boolean { ); } -function colorKey(color: string): string { - const parsed = parsePureColor(color); - if (!parsed || parsed.alpha < 1) return color.trim().toLowerCase(); - return `#${parsed.rgb - .map((channel) => Math.max(0, Math.min(255, Math.round(channel))).toString(16).padStart(2, "0")) - .join("")}`; -} - function parseRgbColor(color: string): RgbColor | null { const parsed = parsePureColor(color); if (!parsed) return null; @@ -67,40 +59,6 @@ function parseRgbColor(color: string): RgbColor | null { }; } -function colorDistance(a: RgbColor, b: RgbColor): number { - return Math.hypot( - a.rgb[0] - b.rgb[0], - a.rgb[1] - b.rgb[1], - a.rgb[2] - b.rgb[2], - ); -} - -function hsvFromColor(color: RgbColor): HsvColor { - const r = color.rgb[0] / 255; - const g = color.rgb[1] / 255; - const b = color.rgb[2] / 255; - const max = Math.max(r, g, b); - const min = Math.min(r, g, b); - const delta = max - min; - let hue = 0; - if (delta !== 0) { - if (max === r) hue = 60 * (((g - b) / delta) % 6); - else if (max === g) hue = 60 * ((b - r) / delta + 2); - else hue = 60 * ((r - g) / delta + 4); - } - if (hue < 0) hue += 360; - return { - hue, - saturation: max === 0 ? 0 : delta / max, - value: max, - }; -} - -function hueDistance(a: number, b: number): number { - const delta = Math.abs(a - b) % 360; - return delta > 180 ? 360 - delta : delta; -} - function compatibleColors(a: RgbColor, b: RgbColor): boolean { if (a.alpha < 1 || b.alpha < 1) return false; const ah = hsvFromColor(a); diff --git a/packages/core/src/parser/parseGltf.ts b/packages/core/src/parser/parseGltf.ts index 4f1cc39ab..415bd6b6b 100644 --- a/packages/core/src/parser/parseGltf.ts +++ b/packages/core/src/parser/parseGltf.ts @@ -30,6 +30,7 @@ import type { Vec2, Vec3, } from "../types"; +import { transformPointMat4 as transformPoint } from "../math/vec3"; import type { ParseAnimationController, ParseAnimationClip, ParseResult } from "./types"; export interface GltfParseOptions { @@ -687,14 +688,6 @@ function mulMat4Into(out: Mat4, a: Mat4, b: Mat4): Mat4 { return out; } -function transformPoint(m: Mat4, p: Vec3): Vec3 { - return [ - m[0] * p[0] + m[4] * p[1] + m[8] * p[2] + m[12], - m[1] * p[0] + m[5] * p[1] + m[9] * p[2] + m[13], - m[2] * p[0] + m[6] * p[1] + m[10] * p[2] + m[14], - ]; -} - function trsToMat4(t?: number[], r?: number[], s?: number[]): Mat4 { const tx = t?.[0] ?? 0, ty = t?.[1] ?? 0, tz = t?.[2] ?? 0; const qx = r?.[0] ?? 0, qy = r?.[1] ?? 0, qz = r?.[2] ?? 0, qw = r?.[3] ?? 1; diff --git a/packages/core/src/parser/parseStl.ts b/packages/core/src/parser/parseStl.ts index 68b69171a..898376e90 100644 --- a/packages/core/src/parser/parseStl.ts +++ b/packages/core/src/parser/parseStl.ts @@ -11,6 +11,7 @@ * consistent supplied-normal signal are oriented to those normals before * polygons are emitted. */ +import { crossVec as cross } from "../math/vec3"; import type { Polygon, Vec3 } from "../types"; import type { ParseResult, ParseStlColor, ParseStlSolid } from "./types"; @@ -380,13 +381,6 @@ function sub(a: Vec3, b: Vec3): Vec3 { return [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; } -function cross(a: Vec3, b: Vec3): Vec3 { - return [ - a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0], - ]; -} function dot(a: Vec3, b: Vec3): number { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; diff --git a/packages/core/src/parser/parseVox.ts b/packages/core/src/parser/parseVox.ts index c2a782881..a50fd46f5 100644 --- a/packages/core/src/parser/parseVox.ts +++ b/packages/core/src/parser/parseVox.ts @@ -30,6 +30,7 @@ */ import type { Polygon, Vec3 } from "../types"; import { BASE_TILE } from "../camera/camera"; +import { colorDistance, hsvFromColor, hueDistance } from "../color/color"; import type { ParseResult, PolyVoxelSource } from "./types"; export interface VoxParseOptions { @@ -159,40 +160,6 @@ function parseResolvedVoxColor(color: string): ResolvedVoxColor | null { }; } -function colorDistance(a: ResolvedVoxColor, b: ResolvedVoxColor): number { - return Math.hypot( - a.rgb[0] - b.rgb[0], - a.rgb[1] - b.rgb[1], - a.rgb[2] - b.rgb[2], - ); -} - -function hsvFromColor(color: ResolvedVoxColor): HsvColor { - const r = color.rgb[0] / 255; - const g = color.rgb[1] / 255; - const b = color.rgb[2] / 255; - const max = Math.max(r, g, b); - const min = Math.min(r, g, b); - const delta = max - min; - let hue = 0; - if (delta !== 0) { - if (max === r) hue = 60 * (((g - b) / delta) % 6); - else if (max === g) hue = 60 * ((b - r) / delta + 2); - else hue = 60 * ((r - g) / delta + 4); - } - if (hue < 0) hue += 360; - return { - hue, - saturation: max === 0 ? 0 : delta / max, - value: max, - }; -} - -function hueDistance(a: number, b: number): number { - const delta = Math.abs(a - b) % 360; - return delta > 180 ? 360 - delta : delta; -} - function canMergeVoxColors(a: ResolvedVoxColor, b: ResolvedVoxColor): boolean { if (a.alpha < 1 || b.alpha < 1) return false; const ah = hsvFromColor(a); diff --git a/packages/core/src/scene/context.ts b/packages/core/src/scene/context.ts index 6655a2ffb..29a75eed7 100644 --- a/packages/core/src/scene/context.ts +++ b/packages/core/src/scene/context.ts @@ -111,6 +111,32 @@ export function buildSceneContext(args: SceneContextBuildArgs): SceneContextBuil }; } +/** + * Re-center polygons around their bounding-box midpoint in mesh-local space, + * shifting both polygon vertices and any `textureTriangles` vertices. + */ +export function recenterPolygons(polygons: Polygon[]): Polygon[] { + if (polygons.length === 0) return polygons; + const bbox = computeSceneBbox(polygons); + const cx = (bbox.min[0] + bbox.max[0]) / 2; + const cy = (bbox.min[1] + bbox.max[1]) / 2; + const cz = (bbox.min[2] + bbox.max[2]) / 2; + if (cx === 0 && cy === 0 && cz === 0) return polygons; + const shift = (v: Vec3): Vec3 => [v[0] - cx, v[1] - cy, v[2] - cz]; + return polygons.map((p) => ({ + ...p, + vertices: p.vertices.map(shift), + ...(p.textureTriangles?.length + ? { + textureTriangles: p.textureTriangles.map((triangle) => ({ + ...triangle, + vertices: triangle.vertices.map(shift) as [Vec3, Vec3, Vec3], + })), + } + : null), + })); +} + /** * Re-export `normalizePolygons` for callers that import scene/context as * the canonical scene-pipeline entry point. diff --git a/packages/core/src/scene/normalize.ts b/packages/core/src/scene/normalize.ts index a67be0182..bc17f0163 100644 --- a/packages/core/src/scene/normalize.ts +++ b/packages/core/src/scene/normalize.ts @@ -8,6 +8,7 @@ * Pure: no DOM, no I/O, deterministic. Bbox is NOT computed here — that's * derived on demand by `buildSceneContext` / consumers. */ +import { crossVec as cross } from "../math/vec3"; import type { Polygon, Vec2, Vec3 } from "../types"; import { parseColor } from "../color/lighting"; @@ -19,11 +20,6 @@ export interface NormalizeResult { const DEFAULT_COLOR = "#cccccc"; const sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; -const cross = (a: Vec3, b: Vec3): Vec3 => [ - a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0], -]; const dot = (a: Vec3, b: Vec3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; const len = (a: Vec3): number => Math.hypot(a[0], a[1], a[2]); diff --git a/packages/core/src/shadow/computeReceiverShadows.ts b/packages/core/src/shadow/computeReceiverShadows.ts index 352ae4cd8..e716ae919 100644 --- a/packages/core/src/shadow/computeReceiverShadows.ts +++ b/packages/core/src/shadow/computeReceiverShadows.ts @@ -342,6 +342,22 @@ export interface ReceiverShadowFaceSpec { * actually changes. Light direction is NOT a bust key (silhouette * adjacency is per-mesh, facing is per-frame). */ +function transformCasterVertices( + vertices: readonly Vec3[], + position: Vec3, + worldCss: (vert: Vec3, pos: Vec3) => Vec3, + rotation: Vec3 | null | undefined, + cssPivot: Vec3 | null, +): Vec3[] { + const wv = vertices.map((vert) => worldCss(vert, position)); + if (!cssPivot || !rotation) return wv; + return wv.map((w) => { + const local: Vec3 = [w[0] - cssPivot[0], w[1] - cssPivot[1], w[2] - cssPivot[2]]; + const r = rotateVec3InWrapperCssFrame(local, rotation); + return [r[0] + cssPivot[0], r[1] + cssPivot[1], r[2] + cssPivot[2]]; + }); +} + export function prepareCasterEdgeOwners( polygons: readonly Polygon[], position: Vec3, @@ -354,15 +370,7 @@ export function prepareCasterEdgeOwners( // Lightweight stub list — buildEdgeOwners only reads `.vertices`. const worldPolys: Polygon[] = polygons.map((p) => { if (!p) return { vertices: [], color: "" }; - let wv = p.vertices.map((vert) => worldCss(vert, position)); - if (hasRotation && cssPivot && rotation) { - wv = wv.map((w) => { - const local: Vec3 = [w[0] - cssPivot[0], w[1] - cssPivot[1], w[2] - cssPivot[2]]; - const r = rotateVec3InWrapperCssFrame(local, rotation); - return [r[0] + cssPivot[0], r[1] + cssPivot[1], r[2] + cssPivot[2]]; - }); - } - return { vertices: wv, color: "" }; + return { vertices: transformCasterVertices(p.vertices, position, worldCss, rotation, cssPivot), color: "" }; }); return buildEdgeOwnersHelper(worldPolys); } @@ -394,14 +402,7 @@ export function prepareCasterPolyItems( if (!includePolygonIndex(i)) continue; const polygon = polygons[i]; if (!polygon) continue; - let wv = polygon.vertices.map((vert) => worldCss(vert, position)); - if (hasRotation && cssPivot && rotation) { - wv = wv.map((w) => { - const local: Vec3 = [w[0] - cssPivot[0], w[1] - cssPivot[1], w[2] - cssPivot[2]]; - const r = rotateVec3InWrapperCssFrame(local, rotation); - return [r[0] + cssPivot[0], r[1] + cssPivot[1], r[2] + cssPivot[2]]; - }); - } + const wv = transformCasterVertices(polygon.vertices, position, worldCss, rotation, cssPivot); let minX = Infinity, minY = Infinity, minZ = Infinity; let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity; for (const w of wv) { diff --git a/packages/core/src/shadow/coverageSilhouette.ts b/packages/core/src/shadow/coverageSilhouette.ts index 7721a48ea..16a15aad1 100644 --- a/packages/core/src/shadow/coverageSilhouette.ts +++ b/packages/core/src/shadow/coverageSilhouette.ts @@ -21,14 +21,9 @@ // `definition` drives the mask resolution: low → blobby, high → the real // concave outline (towers, gaps, courtyards). Robust on any mesh — no manifold // or polygon-boolean requirement. +import { unitVec3 as unit } from "../math/vec3"; import type { Vec3 } from "../types"; -function unit(v: Vec3): Vec3 { - const len = Math.hypot(v[0], v[1], v[2]); - if (len < 1e-9) return [0, 0, 1]; - return [v[0] / len, v[1] / len, v[2] / len]; -} - // Marching-squares segment table: case (c0|c1<<1|c2<<2|c3<<3) → flat list of // edge pairs. Edges: 0=bottom, 1=right, 2=top, 3=left. const MS: number[][] = [ diff --git a/packages/core/src/shadow/parametricSilhouette.ts b/packages/core/src/shadow/parametricSilhouette.ts index 8595fc4be..21a4d21b9 100644 --- a/packages/core/src/shadow/parametricSilhouette.ts +++ b/packages/core/src/shadow/parametricSilhouette.ts @@ -12,15 +12,9 @@ // converges to the caster's exact convex outline. Concave detail beyond the // convex hull is intentionally not represented (that's the "approximate but // light" trade — a future definition tier could add it). +import { unitVec3 as unit } from "../math/vec3"; import type { Vec3 } from "../types"; -/** Unit vector; falls back to +Z for a zero input. */ -function unit(v: Vec3): Vec3 { - const len = Math.hypot(v[0], v[1], v[2]); - if (len < 1e-9) return [0, 0, 1]; - return [v[0] / len, v[1] / len, v[2] / len]; -} - /** 2D convex hull (Andrew's monotone chain) returning INDICES into `pts`, CCW. */ function convexHullIndices(pts: ReadonlyArray): number[] { const n = pts.length; diff --git a/packages/core/src/three/index.ts b/packages/core/src/three/index.ts index 99cedcf3c..01de884c9 100644 --- a/packages/core/src/three/index.ts +++ b/packages/core/src/three/index.ts @@ -382,6 +382,62 @@ function perspectiveFromFov(fov: number, viewportHeight: number, zoom = 1): numb return (viewportHeight * zoom) / (2 * Math.tan((fov * DEG) / 2)); } +export interface ThreeOrthographicCameraPropPatch { + left?: number; + right?: number; + top?: number; + bottom?: number; + near?: number; + far?: number; + zoom?: number; + position?: Vector3Tuple; + lookAt?: Vector3Tuple; + up?: Vector3Tuple; +} + +export function applyThreeOrthographicCameraProps( + camera: OrthographicCamera, + props: ThreeOrthographicCameraPropPatch, +): OrthographicCamera { + if (props.left !== undefined) camera.left = props.left; + if (props.right !== undefined) camera.right = props.right; + if (props.top !== undefined) camera.top = props.top; + if (props.bottom !== undefined) camera.bottom = props.bottom; + if (props.near !== undefined) camera.near = props.near; + if (props.far !== undefined) camera.far = props.far; + if (props.zoom !== undefined) camera.zoom = props.zoom; + if (props.position !== undefined) camera.position.set(props.position[0], props.position[1], props.position[2]); + if (props.up !== undefined) camera.up.set(props.up[0], props.up[1], props.up[2]); + if (props.lookAt !== undefined) camera.lookAt(props.lookAt[0], props.lookAt[1], props.lookAt[2]); + return camera; +} + +export interface ThreePerspectiveCameraPropPatch { + fov?: number; + aspect?: number; + near?: number; + far?: number; + zoom?: number; + position?: Vector3Tuple; + lookAt?: Vector3Tuple; + up?: Vector3Tuple; +} + +export function applyThreePerspectiveCameraProps( + camera: PerspectiveCamera, + props: ThreePerspectiveCameraPropPatch, +): PerspectiveCamera { + if (props.fov !== undefined) camera.fov = props.fov; + if (props.aspect !== undefined) camera.aspect = props.aspect; + if (props.near !== undefined) camera.near = props.near; + if (props.far !== undefined) camera.far = props.far; + if (props.zoom !== undefined) camera.zoom = props.zoom; + if (props.position !== undefined) camera.position.set(props.position[0], props.position[1], props.position[2]); + if (props.up !== undefined) camera.up.set(props.up[0], props.up[1], props.up[2]); + if (props.lookAt !== undefined) camera.lookAt(props.lookAt[0], props.lookAt[1], props.lookAt[2]); + return camera; +} + function asVector3(v: Vector3 | Vector3Tuple): Vector3 { return v instanceof Vector3 ? v.clone() : new Vector3(v[0], v[1], v[2]); } diff --git a/packages/core/src/transform/meshTransform.ts b/packages/core/src/transform/meshTransform.ts index 584bd1afa..bbf66550c 100644 --- a/packages/core/src/transform/meshTransform.ts +++ b/packages/core/src/transform/meshTransform.ts @@ -35,3 +35,36 @@ export function buildPolyMeshTransform( } return parts.length > 0 ? parts.join(" ") : undefined; } + +/** + * Build the wrapper transform string for `` / ``. + * Applies world→CSS position swap, conjugated rotation, scale, and a trailing + * `translate(-cssWidth/2, -cssHeight/2)` so transforms pivot at the iframe center. + */ +export function buildPolyIframeTransform( + position: Vec3 | undefined, + rotation: Vec3 | undefined, + scale: number | Vec3 | undefined, + cssWidth: number, + cssHeight: number, +): string { + const sx = typeof scale === "number" ? scale : (scale?.[0] ?? 1); + const sy = typeof scale === "number" ? scale : (scale?.[1] ?? 1); + const sz = typeof scale === "number" ? scale : (scale?.[2] ?? 1); + const hasScale = sx !== 1 || sy !== 1 || sz !== 1; + const hasRotation = !!rotation && (!!rotation[0] || !!rotation[1] || !!rotation[2]); + const cssPos = position ? worldPositionToCss(position) : ([0, 0, 0] as Vec3); + + const parts: string[] = []; + parts.push(`translate3d(${cssPos[0]}px, ${cssPos[1]}px, ${cssPos[2]}px)`); + if (hasRotation) { + if (rotation![0]) parts.push(`rotateY(${-rotation![0]}deg)`); + if (rotation![1]) parts.push(`rotateX(${-rotation![1]}deg)`); + if (rotation![2]) parts.push(`rotateZ(${-rotation![2]}deg)`); + } + if (hasScale) { + parts.push(`scale3d(${sx}, ${sy}, ${sz})`); + } + parts.push(`translate(${-cssWidth / 2}px, ${-cssHeight / 2}px)`); + return parts.join(" "); +} diff --git a/packages/fonts/src/extrude.ts b/packages/fonts/src/extrude.ts index f2bbee445..571af6d87 100644 --- a/packages/fonts/src/extrude.ts +++ b/packages/fonts/src/extrude.ts @@ -637,11 +637,6 @@ export function groupShapes(contours: Contour[]): Shape[] { return shapes; } -/** Axis-aligned rectangle as a single shape (for underline / strike bars). */ -export function rectShape(x0: number, y0: number, x1: number, y1: number): Shape { - return { outer: [[x0, y0], [x1, y0], [x1, y1], [x0, y1]], holes: [] }; -} - /** Multiply a hex color toward black by `f` (0..1). */ export function shade(hex: string, f: number): string { const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim()); diff --git a/packages/morph/src/contracts/validation.ts b/packages/morph/src/contracts/validation.ts index 25bec9815..5c594dcd3 100644 --- a/packages/morph/src/contracts/validation.ts +++ b/packages/morph/src/contracts/validation.ts @@ -70,22 +70,31 @@ function fail(code: string, path: string, message: string): never { throw new PolyMorphContractError(code, path, message); } -function record( +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)) { - fail("invalid-type", path, "expected an object"); + 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])) { - fail("invalid-keys", path, `expected exactly ${expected.join(", ")}`); + 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; diff --git a/packages/morph/src/package/validation.ts b/packages/morph/src/package/validation.ts index 1dbb83434..fa49cdbea 100644 --- a/packages/morph/src/package/validation.ts +++ b/packages/morph/src/package/validation.ts @@ -5,6 +5,7 @@ import { isPolyMorphResourcePath, type PolyMorphProfile, } from "../contracts/index.js"; +import { assertExactRecord } from "../contracts/validation.js"; import { PolyMorphPackageError } from "./error.js"; import type { PolyMorphCatalog, @@ -34,15 +35,7 @@ function fail(code: string, path: string, message: string): never { } function record(value: unknown, path: string, keys: readonly string[]): Record { - if (!value || typeof value !== "object" || Array.isArray(value)) { - fail("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])) { - fail("invalid-keys", path, `expected exactly ${expected.join(", ")}`); - } - return value as Record; + return assertExactRecord(value, path, keys, fail); } function array(value: unknown, path: string): readonly unknown[] { diff --git a/packages/morph/src/prepare/compile.ts b/packages/morph/src/prepare/compile.ts index c27aec302..7eb2ecf63 100644 --- a/packages/morph/src/prepare/compile.ts +++ b/packages/morph/src/prepare/compile.ts @@ -1,5 +1,6 @@ import { computeSolidTrianglePlanFromCssPoints, + crossVec as cross, SOLID_TRIANGLE_CANONICAL_SIZE, type Polygon, } from "@layoutit/polycss-core"; @@ -132,13 +133,6 @@ function subtract(left: PolyMorphVec3, right: PolyMorphVec3): PolyMorphVec3 { ]; } -function cross(left: PolyMorphVec3, right: PolyMorphVec3): PolyMorphVec3 { - return [ - left[1] * right[2] - left[2] * right[1], - left[2] * right[0] - left[0] * right[2], - left[0] * right[1] - left[1] * right[0], - ]; -} function normalise(value: readonly number[], path: string): PolyMorphVec3 { const length = Math.hypot(...value); diff --git a/packages/polycss/src/api/cameraSnapshotAttrs.ts b/packages/polycss/src/api/cameraSnapshotAttrs.ts new file mode 100644 index 000000000..3275f2e52 --- /dev/null +++ b/packages/polycss/src/api/cameraSnapshotAttrs.ts @@ -0,0 +1,227 @@ +/** + * Shared camera DOM snapshot-attribute writer and framework camera-store sync. + * + * Used by: + * - `createPolyScene` (`@layoutit/polycss`) + * - `usePolyCamera` (`@layoutit/polycss-react` & `@layoutit/polycss-vue`) + */ +import { + buildPolyCameraSceneTransform, + capturePolyCameraSnapshot, + type CameraHandle, + type CameraState, + type PolyCameraProjection, + type PolyCameraSnapshot, + type PolyCameraSnapshotOptions, + type PolyCameraSnapshotSource, + type Vec3, +} from "@layoutit/polycss-core"; +import { + createPolyOrthographicCamera, + createPolyPerspectiveCamera, + type PolyOrthographicCameraHandle, + type PolyPerspectiveCameraHandle, +} from "./createPolyCamera"; +import type { PolySceneHandle } from "./createPolyScene"; + +export interface WriteCameraSnapshotAttrsOptions extends PolyCameraSnapshotOptions { + /** Also write `el.style.perspective = snapshot.appliedPerspectiveStyle`. */ + applyPerspective?: boolean; +} + +/** + * Write canonical `data-polycss-camera-*` dataset attributes (and optionally + * CSS `perspective`) onto a `.polycss-camera` element. + */ +export function writeCameraSnapshotAttrs( + el: HTMLElement | null, + camera: PolyCameraSnapshotSource, + options?: WriteCameraSnapshotAttrsOptions, +): PolyCameraSnapshot | null { + if (!el) return null; + const snapshot = capturePolyCameraSnapshot(camera, options); + if (options?.applyPerspective) { + el.style.perspective = snapshot.appliedPerspectiveStyle; + } + el.dataset.polycssCameraProjection = snapshot.projection; + el.dataset.polycssCameraPerspective = snapshot.perspectiveStyle; + el.dataset.polycssCameraAppliedPerspective = snapshot.appliedPerspectiveStyle; + el.dataset.polycssCameraZoom = String(snapshot.state.zoom); + el.dataset.polycssCameraDistance = String(snapshot.state.distance); + el.dataset.polycssCameraRotX = String(snapshot.state.rotX); + el.dataset.polycssCameraRotY = String(snapshot.state.rotY); + el.dataset.polycssCameraTarget = snapshot.state.target.join(","); + return snapshot; +} + +export interface LiveRuntimeCameraOptions { + zoom?: number; + target?: Vec3; + rotX?: number; + rotY?: number; + distance?: number; + initialProjection?: PolyCameraProjection; + initialPerspectiveStyle?: string; + getProjection: () => PolyCameraProjection; + getPerspectiveStyle: () => string; +} + +/** + * Create a runtime camera handle whose `type` and `perspectiveStyle` getters + * reflect live framework props so `createPolyScene.applyCamera()` stays in sync. + */ +export function createLiveRuntimeCamera( + options: LiveRuntimeCameraOptions, +): PolyPerspectiveCameraHandle | PolyOrthographicCameraHandle { + const baseOpts = { + zoom: options.zoom, + target: options.target, + rotX: options.rotX, + rotY: options.rotY, + distance: options.distance, + }; + const inner = + options.initialProjection === "perspective" + ? createPolyPerspectiveCamera({ + ...baseOpts, + perspective: parseFloat(options.initialPerspectiveStyle ?? "32000px") || 32000, + }) + : createPolyOrthographicCamera(baseOpts); + + return { + get state() { + return inner.state; + }, + update(next: Partial) { + inner.update(next); + }, + getStyle(input) { + return inner.getStyle(input); + }, + subscribe(listener) { + return inner.subscribe(listener); + }, + get type() { + return options.getProjection() as "perspective" & "orthographic"; + }, + get perspectiveStyle() { + return options.getPerspectiveStyle() as string & "none"; + }, + } as PolyPerspectiveCameraHandle | PolyOrthographicCameraHandle; +} + +export interface CameraSyncStoreLike { + getState(): { cameraState: CameraState }; + subscribe(listener: () => void): () => void; + updateCameraFromRef(camera: CameraHandle): void; +} + +/** + * Bind bidirectional synchronization between a runtime camera handle and a + * framework reactive scene store without feedback loops. + */ +export function bindCameraStoreSync( + handle: PolyPerspectiveCameraHandle | PolyOrthographicCameraHandle, + store: CameraSyncStoreLike, + getRuntimeScene: () => PolySceneHandle | null, +): () => void { + let syncing = false; + const unsubHandle = handle.subscribe(() => { + if (syncing) return; + syncing = true; + try { + store.updateCameraFromRef(handle); + } finally { + syncing = false; + } + }); + const unsubStore = store.subscribe(() => { + if (syncing) return; + const next = store.getState().cameraState; + const cur = handle.state; + const changed = + next.rotX !== cur.rotX || + next.rotY !== cur.rotY || + next.zoom !== cur.zoom || + next.distance !== cur.distance || + next.target[0] !== cur.target[0] || + next.target[1] !== cur.target[1] || + next.target[2] !== cur.target[2]; + if (!changed) return; + syncing = true; + try { + handle.update(next); + getRuntimeScene()?.applyCamera(); + } finally { + syncing = false; + } + }); + return () => { + unsubHandle(); + unsubStore(); + }; +} + +export function applyCameraTransformDirect(opts: { + runtimeScene: PolySceneHandle | null; + sceneEl: HTMLElement | null; + cameraEl: HTMLElement | null; + handle: CameraHandle; + autoCenterOffset: Vec3; + projection: PolyCameraProjection | undefined; + perspectiveStyle: string | undefined; +}): void { + if (opts.runtimeScene) { + opts.runtimeScene.applyCamera(); + writeCameraSnapshotAttrs(opts.cameraEl, opts.handle, { + projection: opts.projection, + perspectiveStyle: opts.perspectiveStyle, + }); + return; + } + if (opts.sceneEl) { + opts.sceneEl.style.transform = buildPolyCameraSceneTransform(opts.handle.state, { + autoCenterOffset: opts.autoCenterOffset, + }); + } + writeCameraSnapshotAttrs(opts.cameraEl, opts.handle, { + projection: opts.projection, + perspectiveStyle: opts.perspectiveStyle, + }); +} + +/** + * Wrap a plain `CameraHandle` as a minimal orthographic runtime camera handle + * when a scene mounts without an explicit runtime camera provider. + */ +export function adaptFallbackCamera( + camera: CameraHandle, +): PolyPerspectiveCameraHandle | PolyOrthographicCameraHandle { + return { + get state() { return camera.state; }, + update(next) { camera.update(next); }, + getStyle(input) { return camera.getStyle(input); }, + subscribe() { return () => {}; }, + type: "orthographic", + perspectiveStyle: "none", + }; +} + +/** + * Measure an element's height immediately and re-emit on `ResizeObserver` + * updates; returns a cleanup callback. + */ +export function observeViewportHeight( + el: HTMLElement, + onHeight: (height: number) => void, + fallback = 420, +): () => void { + const measure = () => { + onHeight(el.getBoundingClientRect().height || el.clientHeight || fallback); + }; + measure(); + if (typeof ResizeObserver === "undefined") return () => {}; + const observer = new ResizeObserver(measure); + observer.observe(el); + return () => observer.disconnect(); +} diff --git a/packages/polycss/src/api/controls/gizmoEngine.ts b/packages/polycss/src/api/controls/gizmoEngine.ts new file mode 100644 index 000000000..b307a62b3 --- /dev/null +++ b/packages/polycss/src/api/controls/gizmoEngine.ts @@ -0,0 +1,747 @@ +/** + * Shared transform-controls drag, geometry, and fallback hit-test engine. + * + * Used by: + * - `createTransformControls` (`@layoutit/polycss`) + * - `` (`@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 { 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): boolean { + 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 false; + + onMouseDown?.(); + onDraggingChanged?.(true); + + const handleMove = (ev: PointerEvent): void => { + const dx = ev.clientX - startClientX; + const dy = ev.clientY - startClientY; + const t = snap(solveAxisDragDelta(dx, dy, screen.x, screen.y), translationSnap); + onAxisDelta(t, axisVec); + }; + const handleUp = (): void => { + window.removeEventListener("pointermove", handleMove); + window.removeEventListener("pointerup", handleUp); + window.removeEventListener("pointercancel", handleUp); + swallowNextClick(); + onMouseUp?.(); + onDraggingChanged?.(false); + }; + window.addEventListener("pointermove", handleMove); + window.addEventListener("pointerup", handleUp); + window.addEventListener("pointercancel", handleUp); + return true; +} + +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): boolean { + 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 false; + + onMouseDown?.(); + onDraggingChanged?.(true); + + const handleMove = (ev: PointerEvent): void => { + 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 => { + window.removeEventListener("pointermove", handleMove); + window.removeEventListener("pointerup", handleUp); + window.removeEventListener("pointercancel", handleUp); + swallowNextClick(); + onMouseUp?.(); + onDraggingChanged?.(false); + }; + window.addEventListener("pointermove", handleMove); + window.addEventListener("pointerup", handleUp); + window.addEventListener("pointercancel", handleUp); + return true; +} + +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); + + const handleMove = (ev: PointerEvent): void => { + 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 => { + window.removeEventListener("pointermove", handleMove); + window.removeEventListener("pointerup", handleUp); + window.removeEventListener("pointercancel", handleUp); + swallowNextClick(); + onMouseUp?.(); + onDraggingChanged?.(false); + onComplete?.(); + }; + window.addEventListener("pointermove", handleMove); + window.addEventListener("pointerup", handleUp); + window.addEventListener("pointercancel", handleUp); +} + +// ── 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, +): 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: [] }; + } + + 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, +): boolean { + const initial = getState(); + const target = initial.target; + if (!target || !initial.enabled) return false; + const startPos = (target.getPosition() ?? [0, 0, 0]) as Vec3; + const started = 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); + }, + }); + return started; +} + +export function startDeclarativePlaneDrag< + TTarget extends DeclarativeGizmoTarget, +>( + spec: GizmoPlaneSpec, + wrapper: HTMLElement, + startClientX: number, + startClientY: number, + getState: () => DeclarativeGizmoDragState, +): boolean { + const initial = getState(); + const target = initial.target; + if (!target || !initial.enabled) return false; + 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 { + const initial = getState(); + const target = initial.target; + if (!target || !initial.enabled) return; + const startRotation = (target.getRotation() ?? [0, 0, 0]) as Vec3; + const qStart = quatFromEulerXYZ(startRotation); + const axisVec: Vec3 = [0, 0, 0]; + axisVec[spec.cssAxis] = 1; + 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(); + }, + }); +} + +/** + * Attach a camera-level `pointerdown` JS bounding-rect fallback listener for + * declarative `` wrappers (React & Vue). Handles clicks + * that fall through native polygon hit-testing (e.g. `border-shape` clipping + * or upstream `pointer-events: none`), while skipping clicks that already hit + * a `.polycss-transform-gizmo` element. + */ +export function attachDeclarativeGizmoFallback< + TTarget extends DeclarativeGizmoTarget, +>( + cameraEl: HTMLElement, + getState: () => DeclarativeGizmoDragState, +): () => void { + const onPointerDown = (event: PointerEvent): void => { + const state = getState(); + if (!state.target || !state.enabled) return; + const targetEl = event.target as Element | null; + if (targetEl?.closest(".polycss-transform-gizmo")) return; + const doc = cameraEl.ownerDocument ?? document; + + 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(); + 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(); + startDeclarativeArrowDrag(spec, wrapper, event.clientX, event.clientY, getState); + 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(); + startDeclarativeRingDrag(spec, wrapper, event.clientX, event.clientY, getState); + return; + } + }; + + cameraEl.addEventListener("pointerdown", onPointerDown); + return () => cameraEl.removeEventListener("pointerdown", onPointerDown); +} diff --git a/packages/polycss/src/api/controls/pointerControlsCore.ts b/packages/polycss/src/api/controls/pointerControlsCore.ts new file mode 100644 index 000000000..b4c315e11 --- /dev/null +++ b/packages/polycss/src/api/controls/pointerControlsCore.ts @@ -0,0 +1,306 @@ +/** + * Shared pointer/wheel camera controls engine powering both + * `createPolyOrbitControls` and `createPolyMapControls`. + */ +import { applyOrbit, applyPan } from "@layoutit/polycss-core"; +import type { PolyCameraControlTarget } from "../scene/types"; +import { + BASE_DEFAULTS, + resolveOptions, + makeListenerRegistry, + makeCameraSnapshot, + makeWheelHandler, + makeAnimLoop, + type PolyControlsBaseOptions, + type PolyControlsEvent, + type PolyControlsHandle, + type PolyControlsListener, + type ResolvedOptions, +} from "./common"; + +export type PointerControlsMode = "orbit" | "map"; + +export function createPointerControls( + scene: PolyCameraControlTarget, + mode: PointerControlsMode, + options: PolyControlsBaseOptions = {}, +): PolyControlsHandle { + let opts: ResolvedOptions = resolveOptions(BASE_DEFAULTS, options); + const host = scene.host; + const win = host.ownerDocument?.defaultView ?? globalThis; + + let activePointerId: number | null = null; + let pointer = { x: 0, y: 0 }; + let rightDragActive = false; + let rightPointer = { x: 0, y: 0 }; + let dragStylesApplied = false; + let animPaused = false; + let stopped = false; + + const registry = makeListenerRegistry(); + const snapshot = makeCameraSnapshot(scene); + const { + changeListeners, + startListeners, + endListeners, + listenerArray, + emitChange, + emitInteraction, + } = registry; + + const animLoop = makeAnimLoop( + win as typeof globalThis, + scene, + () => opts, + () => stopped, + () => animPaused, + snapshot, + emitChange, + ); + + function syncDragStyles(): void { + if (!stopped && opts.drag) { + host.style.cursor = activePointerId !== null ? "grabbing" : "grab"; + host.style.touchAction = "none"; + host.style.userSelect = "none"; + dragStylesApplied = true; + } else if (dragStylesApplied) { + host.style.cursor = ""; + host.style.touchAction = ""; + host.style.userSelect = ""; + dragStylesApplied = false; + } + } + + function applyPanDelta(dx: number, dy: number): void { + const cameraState = scene.camera.state; + const { targetD0, targetD1 } = applyPan( + dx, + dy, + cameraState.zoom ?? 1, + cameraState.rotX ?? 65, + cameraState.rotY ?? 45, + ); + const t = cameraState.target ?? [0, 0, 0]; + scene.camera.update({ target: [t[0] + targetD0, t[1] + targetD1, t[2]] }); + } + + function applyOrbitDelta(dx: number, dy: number, clampGroundTilt: boolean): void { + const cameraState = scene.camera.state; + const next = applyOrbit( + dx, + dy, + cameraState.rotX ?? 65, + cameraState.rotY ?? 45, + opts.invert, + ); + // In orbit mode clamp rotX to [0, 89] so the floor's +Z normal never flips + // away from the camera and vanishes with its cast shadows. + const rotX = clampGroundTilt ? Math.max(0, Math.min(89, next.rotX)) : next.rotX; + scene.camera.update({ rotX, rotY: next.rotY }); + } + + const onPointerDown = (e: PointerEvent): void => { + if (!opts.drag || stopped) return; + if (e.button === 2) return; + if (activePointerId !== null) return; + if (e.isPrimary === false) return; + e.preventDefault(); + activePointerId = e.pointerId; + pointer = { x: e.clientX, y: e.clientY }; + host.style.cursor = "grabbing"; + dragStylesApplied = true; + try { + (e.target as Element).setPointerCapture(e.pointerId); + } catch { + /* ignore */ + } + if (opts.animate && opts.animate.pauseOnInteraction) { + animPaused = true; + } + emitInteraction("start", snapshot); + }; + + const onPointerMove = (e: PointerEvent): void => { + if (activePointerId === null || e.pointerId !== activePointerId) return; + if (!opts.drag || stopped) return; + e.preventDefault(); + const dx = e.clientX - pointer.x; + const dy = e.clientY - pointer.y; + pointer = { x: e.clientX, y: e.clientY }; + + const shouldPan = mode === "orbit" ? e.shiftKey : !e.shiftKey; + if (shouldPan) { + applyPanDelta(dx, dy); + } else { + applyOrbitDelta(dx, dy, mode === "orbit"); + } + scene.applyCamera(); + emitChange(snapshot); + }; + + const onPointerUp = (e: PointerEvent): void => { + if (activePointerId !== e.pointerId) return; + activePointerId = null; + syncDragStyles(); + try { + (e.target as Element).releasePointerCapture(e.pointerId); + } catch { + /* ignore */ + } + if (opts.animate && opts.animate.pauseOnInteraction) { + animPaused = false; + } + emitInteraction("end", snapshot); + }; + + const onContextMenu = (e: Event): void => { + if (!opts.drag || stopped) return; + e.preventDefault(); + }; + + const onMouseDown = (e: MouseEvent): void => { + if (!opts.drag || stopped) return; + if (e.button !== 2) return; + rightDragActive = true; + rightPointer = { x: e.clientX, y: e.clientY }; + if (opts.animate && opts.animate.pauseOnInteraction) { + animPaused = true; + } + emitInteraction("start", snapshot); + }; + + const onMouseMove = (e: MouseEvent): void => { + if (!rightDragActive || !opts.drag || stopped) return; + const dx = e.clientX - rightPointer.x; + const dy = e.clientY - rightPointer.y; + rightPointer = { x: e.clientX, y: e.clientY }; + if (mode === "orbit") { + applyPanDelta(dx, dy); + } else { + applyOrbitDelta(dx, dy, false); + } + scene.applyCamera(); + emitChange(snapshot); + }; + + const onMouseUp = (e: MouseEvent): void => { + if (e.button !== 2) return; + if (rightDragActive) { + rightDragActive = false; + if (opts.animate && opts.animate.pauseOnInteraction) { + animPaused = false; + } + emitInteraction("end", snapshot); + } + }; + + const wheelHandler = makeWheelHandler( + scene, + () => opts, + () => stopped, + snapshot, + emitChange, + emitInteraction, + ); + + function attach(): void { + host.addEventListener("pointerdown", onPointerDown); + host.addEventListener("pointermove", onPointerMove); + host.addEventListener("pointerup", onPointerUp); + host.addEventListener("pointercancel", onPointerUp); + host.addEventListener("wheel", wheelHandler.onWheel, { passive: false }); + host.addEventListener("contextmenu", onContextMenu); + host.addEventListener("mousedown", onMouseDown); + host.addEventListener("mousemove", onMouseMove); + host.addEventListener("mouseup", onMouseUp); + syncDragStyles(); + } + + function detach(): void { + host.removeEventListener("pointerdown", onPointerDown); + host.removeEventListener("pointermove", onPointerMove); + host.removeEventListener("pointerup", onPointerUp); + host.removeEventListener("pointercancel", onPointerUp); + host.removeEventListener("wheel", wheelHandler.onWheel); + host.removeEventListener("contextmenu", onContextMenu); + host.removeEventListener("mousedown", onMouseDown); + host.removeEventListener("mousemove", onMouseMove); + host.removeEventListener("mouseup", onMouseUp); + if (dragStylesApplied) { + host.style.cursor = ""; + host.style.touchAction = ""; + host.style.userSelect = ""; + dragStylesApplied = false; + } + wheelHandler.teardown(); + } + + attach(); + animLoop.start(); + + function update(partial: PolyControlsBaseOptions): void { + const wasAnimating = !!opts.animate; + opts = resolveOptions(opts, partial); + if (!stopped && activePointerId === null) { + syncDragStyles(); + } + const isAnimating = !!opts.animate; + if (wasAnimating && !isAnimating) { + animLoop.stop(); + } else if (!wasAnimating && isAnimating) { + animLoop.start(); + } + } + + function resume(): void { + if (!stopped) return; + stopped = false; + attach(); + animLoop.start(); + } + + function pause(): void { + if (stopped) return; + stopped = true; + detach(); + animLoop.stop(); + activePointerId = null; + rightDragActive = false; + animPaused = false; + wheelHandler.teardown(); + } + + function destroy(): void { + pause(); + changeListeners.length = 0; + startListeners.length = 0; + endListeners.length = 0; + } + + function addEventListener( + type: T, + listener: PolyControlsListener>, + ): void { + const arr = listenerArray(type); + if (!arr.includes(listener as PolyControlsListener)) arr.push(listener as PolyControlsListener); + } + + function removeEventListener( + type: T, + listener: PolyControlsListener>, + ): void { + const arr = listenerArray(type); + const idx = arr.indexOf(listener as PolyControlsListener); + if (idx >= 0) arr.splice(idx, 1); + } + + function hasEventListener( + type: T, + listener: PolyControlsListener>, + ): boolean { + return listenerArray(type).includes(listener as PolyControlsListener); + } + + return { update, resume, pause, destroy, addEventListener, removeEventListener, hasEventListener }; +} diff --git a/packages/polycss/src/api/controls/selectionEngine.ts b/packages/polycss/src/api/controls/selectionEngine.ts new file mode 100644 index 000000000..c9d06a648 --- /dev/null +++ b/packages/polycss/src/api/controls/selectionEngine.ts @@ -0,0 +1,128 @@ +/** + * Shared mesh selection state and click-delegation controller. + * + * Used by: + * - `createSelect` (`@layoutit/polycss`) + * - `` (`@layoutit/polycss-react`) + * - `` (`@layoutit/polycss-vue`) + */ + +export interface SelectionControllerOptions { + /** Whether multi-selection (shift/meta/ctrl + click, `add`) is enabled. */ + getMultiple: () => boolean; + /** Whether clicking background clears selection. Default true. */ + getClearOnMiss: () => boolean; + /** Optional filter applied to every selection update. */ + getFilter: () => ((meshes: TMesh[]) => TMesh[]) | undefined; + /** Resolve a clicked DOM target or viewport coordinate to a mesh handle. */ + resolveTarget: (target: Element | null, clientX: number, clientY: number) => TMesh | null; + /** Optional predicate to ignore clicks (e.g. transform gizmo elements). */ + shouldIgnoreTarget?: (target: Element | null) => boolean; + /** Called whenever selection is committed. */ + onChange: (meshes: TMesh[]) => void; + /** Called when a click resolves to no mesh. */ + onPointerMissed?: (event: MouseEvent) => void; + /** When true, `clear()` is a no-op if selection is already empty. Default false. */ + skipEmptyClear?: boolean; +} + +export interface SelectionController { + readonly selected: TMesh[]; + set(next: TMesh[]): void; + add(mesh: TMesh): void; + remove(mesh: TMesh): void; + toggle(mesh: TMesh): void; + clear(): void; + has(mesh: TMesh): boolean; + handleClick(event: MouseEvent): void; + attach(el: HTMLElement): () => void; +} + +export function createSelectionController( + options: SelectionControllerOptions, +): SelectionController { + let selected: TMesh[] = []; + + function commit(next: TMesh[]): void { + const filter = options.getFilter(); + const filtered = filter ? filter(next) : next; + selected = filtered; + options.onChange(filtered); + } + + function set(next: TMesh[]): void { + commit(next); + } + + function add(mesh: TMesh): void { + if (options.getMultiple()) { + if (selected.includes(mesh)) return; + commit([...selected, mesh]); + } else { + commit([mesh]); + } + } + + function remove(mesh: TMesh): void { + if (!selected.includes(mesh)) return; + commit(selected.filter((item) => item !== mesh)); + } + + function toggle(mesh: TMesh): void { + if (selected.includes(mesh)) { + commit(selected.filter((item) => item !== mesh)); + } else if (options.getMultiple()) { + commit([...selected, mesh]); + } else { + commit([mesh]); + } + } + + function clear(): void { + if (options.skipEmptyClear && selected.length === 0) return; + commit([]); + } + + function has(mesh: TMesh): boolean { + return selected.includes(mesh); + } + + function handleClick(event: MouseEvent): void { + const target = event.target as Element | null; + if (options.shouldIgnoreTarget?.(target)) return; + const handle = options.resolveTarget(target, event.clientX, event.clientY); + if (!handle) { + options.onPointerMissed?.(event); + if (options.getClearOnMiss()) clear(); + return; + } + const additive = + options.getMultiple() && (event.shiftKey || event.metaKey || event.ctrlKey); + if (additive) { + toggle(handle); + } else if (selected.length === 1 && selected[0] === handle) { + clear(); + } else { + set([handle]); + } + } + + function attach(el: HTMLElement): () => void { + el.addEventListener("click", handleClick); + return () => el.removeEventListener("click", handleClick); + } + + return { + get selected() { + return selected; + }, + set, + add, + remove, + toggle, + clear, + has, + handleClick, + attach, + }; +} diff --git a/packages/polycss/src/api/createPolyMapControls.ts b/packages/polycss/src/api/createPolyMapControls.ts index 34ff984ec..b51a70ab5 100644 --- a/packages/polycss/src/api/createPolyMapControls.ts +++ b/packages/polycss/src/api/createPolyMapControls.ts @@ -1,29 +1,12 @@ /** * createPolyMapControls — map/pan-mode camera input for a PolyScene. * - * Left-drag pans the target (slippy-map semantics — terrain follows pointer). - * Right-drag or Shift+left-drag orbits. Wheel zooms or dollies. - * Mirrors Three.js MapControls semantics. - * - * For orbit-only semantics (left-drag orbits) use `createPolyOrbitControls` - * instead. + * Left-drag pans (slippy-map semantics), Shift+left-drag or right-drag orbits, + * wheel zooms or dollies. Mirrors Three.js MapControls semantics. */ - -import { applyOrbit, applyPan } from "@layoutit/polycss-core"; import type { PolyCameraControlTarget } from "./scene/types"; -import { - BASE_DEFAULTS, - resolveOptions, - makeListenerRegistry, - makeCameraSnapshot, - makeWheelHandler, - makeAnimLoop, - type PolyControlsBaseOptions, - type PolyControlsHandle, - type PolyControlsEvent, - type PolyControlsListener, - type ResolvedOptions, -} from "./controls/common"; +import type { PolyControlsBaseOptions, PolyControlsHandle } from "./controls/common"; +import { createPointerControls } from "./controls/pointerControlsCore"; export type { PolyControlsAnimateOptions, @@ -42,249 +25,5 @@ export function createPolyMapControls( scene: PolyCameraControlTarget, options: PolyMapControlsOptions = {}, ): PolyMapControlsHandle { - let opts: ResolvedOptions = resolveOptions(BASE_DEFAULTS, options); - const host = scene.host; - const win = host.ownerDocument?.defaultView ?? globalThis; - - let activePointerId: number | null = null; - let pointer = { x: 0, y: 0 }; - let dragStylesApplied = false; - let animPaused = false; - let stopped = false; - - // Right-drag state for orbit via right button - let rightDragActive = false; - let rightPointer = { x: 0, y: 0 }; - - const registry = makeListenerRegistry(); - const snapshot = makeCameraSnapshot(scene); - const { changeListeners, startListeners, endListeners, listenerArray, emitChange, emitInteraction } = registry; - - const animLoop = makeAnimLoop( - win as typeof globalThis, - scene, - () => opts, - () => stopped, - () => animPaused, - snapshot, - emitChange, - ); - - function syncDragStyles(): void { - if (!stopped && opts.drag) { - host.style.cursor = activePointerId !== null ? "grabbing" : "grab"; - host.style.touchAction = "none"; - host.style.userSelect = "none"; - dragStylesApplied = true; - } else if (dragStylesApplied) { - host.style.cursor = ""; - host.style.touchAction = ""; - host.style.userSelect = ""; - dragStylesApplied = false; - } - } - - // ── Left-drag: pan ──────────────────────────────────────────────────────── - const onPointerDown = (e: PointerEvent): void => { - if (!opts.drag || stopped) return; - if (e.button === 2) return; - if (activePointerId !== null) return; - if (e.isPrimary === false) return; - e.preventDefault(); - activePointerId = e.pointerId; - pointer = { x: e.clientX, y: e.clientY }; - host.style.cursor = "grabbing"; - dragStylesApplied = true; - try { (e.target as Element).setPointerCapture(e.pointerId); } catch { /* ignore */ } - if (opts.animate && opts.animate.pauseOnInteraction) { - animPaused = true; - } - emitInteraction("start", snapshot); - }; - - const onPointerMove = (e: PointerEvent): void => { - if (activePointerId === null || e.pointerId !== activePointerId) return; - if (!opts.drag || stopped) return; - e.preventDefault(); - const dx = e.clientX - pointer.x; - const dy = e.clientY - pointer.y; - pointer = { x: e.clientX, y: e.clientY }; - const cameraState = scene.camera.state; - - if (e.shiftKey) { - // Shift+left-drag orbits - const next = applyOrbit(dx, dy, cameraState.rotX ?? 65, cameraState.rotY ?? 45, opts.invert); - scene.camera.update({ rotX: next.rotX, rotY: next.rotY }); - } else { - // Left-drag pans (slippy-map semantics) - const { targetD0, targetD1 } = applyPan( - dx, - dy, - cameraState.zoom ?? 1, - cameraState.rotX ?? 65, - cameraState.rotY ?? 45, - ); - const t = cameraState.target ?? [0, 0, 0]; - scene.camera.update({ target: [t[0] + targetD0, t[1] + targetD1, t[2]] }); - } - scene.applyCamera(); - emitChange(snapshot); - }; - - const onPointerUp = (e: PointerEvent): void => { - if (activePointerId !== e.pointerId) return; - activePointerId = null; - syncDragStyles(); - try { (e.target as Element).releasePointerCapture(e.pointerId); } catch { /* ignore */ } - if (opts.animate && opts.animate.pauseOnInteraction) { - animPaused = false; - } - emitInteraction("end", snapshot); - }; - - // ── Right-drag: orbit ──────────────────────────────────────────────────── - const onContextMenu = (e: Event): void => { - if (!opts.drag || stopped) return; - e.preventDefault(); - }; - - const onMouseDown = (e: MouseEvent): void => { - if (!opts.drag || stopped) return; - if (e.button !== 2) return; - rightDragActive = true; - rightPointer = { x: e.clientX, y: e.clientY }; - if (opts.animate && opts.animate.pauseOnInteraction) { - animPaused = true; - } - emitInteraction("start", snapshot); - }; - - const onMouseMove = (e: MouseEvent): void => { - if (!rightDragActive || !opts.drag) return; - const dx = e.clientX - rightPointer.x; - const dy = e.clientY - rightPointer.y; - rightPointer = { x: e.clientX, y: e.clientY }; - const cameraState = scene.camera.state; - const next = applyOrbit(dx, dy, cameraState.rotX ?? 65, cameraState.rotY ?? 45, opts.invert); - scene.camera.update({ rotX: next.rotX, rotY: next.rotY }); - scene.applyCamera(); - emitChange(snapshot); - }; - - const onMouseUp = (e: MouseEvent): void => { - if (e.button !== 2) return; - if (rightDragActive) { - rightDragActive = false; - emitInteraction("end", snapshot); - } - }; - - const wheelHandler = makeWheelHandler( - scene, - () => opts, - () => stopped, - snapshot, - emitChange, - emitInteraction, - ); - - function attach(): void { - host.addEventListener("pointerdown", onPointerDown); - host.addEventListener("pointermove", onPointerMove); - host.addEventListener("pointerup", onPointerUp); - host.addEventListener("pointercancel", onPointerUp); - host.addEventListener("wheel", wheelHandler.onWheel, { passive: false }); - host.addEventListener("contextmenu", onContextMenu); - host.addEventListener("mousedown", onMouseDown); - host.addEventListener("mousemove", onMouseMove); - host.addEventListener("mouseup", onMouseUp); - syncDragStyles(); - } - - function detach(): void { - host.removeEventListener("pointerdown", onPointerDown); - host.removeEventListener("pointermove", onPointerMove); - host.removeEventListener("pointerup", onPointerUp); - host.removeEventListener("pointercancel", onPointerUp); - host.removeEventListener("wheel", wheelHandler.onWheel); - host.removeEventListener("contextmenu", onContextMenu); - host.removeEventListener("mousedown", onMouseDown); - host.removeEventListener("mousemove", onMouseMove); - host.removeEventListener("mouseup", onMouseUp); - if (dragStylesApplied) { - host.style.cursor = ""; - host.style.touchAction = ""; - host.style.userSelect = ""; - dragStylesApplied = false; - } - wheelHandler.teardown(); - } - - attach(); - animLoop.start(); - - function update(partial: PolyMapControlsOptions): void { - const wasAnimating = !!opts.animate; - opts = resolveOptions(opts, partial); - if (!stopped && activePointerId === null) { - syncDragStyles(); - } - const isAnimating = !!opts.animate; - if (wasAnimating && !isAnimating) { - animLoop.stop(); - } else if (!wasAnimating && isAnimating) { - animLoop.start(); - } - } - - function resume(): void { - if (!stopped) return; - stopped = false; - attach(); - animLoop.start(); - } - - function pause(): void { - if (stopped) return; - stopped = true; - detach(); - animLoop.stop(); - activePointerId = null; - animPaused = false; - rightDragActive = false; - wheelHandler.teardown(); - } - - function destroy(): void { - pause(); - changeListeners.length = 0; - startListeners.length = 0; - endListeners.length = 0; - } - - function addEventListener( - type: T, - listener: PolyControlsListener>, - ): void { - const arr = listenerArray(type); - if (!arr.includes(listener as PolyControlsListener)) arr.push(listener as PolyControlsListener); - } - - function removeEventListener( - type: T, - listener: PolyControlsListener>, - ): void { - const arr = listenerArray(type); - const idx = arr.indexOf(listener as PolyControlsListener); - if (idx >= 0) arr.splice(idx, 1); - } - - function hasEventListener( - type: T, - listener: PolyControlsListener>, - ): boolean { - return listenerArray(type).includes(listener as PolyControlsListener); - } - - return { update, resume, pause, destroy, addEventListener, removeEventListener, hasEventListener }; + return createPointerControls(scene, "map", options); } diff --git a/packages/polycss/src/api/createPolyOrbitControls.ts b/packages/polycss/src/api/createPolyOrbitControls.ts index 1a1b49f73..d959d155c 100644 --- a/packages/polycss/src/api/createPolyOrbitControls.ts +++ b/packages/polycss/src/api/createPolyOrbitControls.ts @@ -1,28 +1,12 @@ /** * createPolyOrbitControls — orbit-mode camera input for a PolyScene. * - * Left-drag rotates rotX / rotY around the target (orbit). Wheel zooms or - * dollies. Mirrors Three.js OrbitControls semantics. - * - * For map/pan semantics (left-drag pans, right-drag orbits) use - * `createPolyMapControls` instead. + * Left-drag orbits, Shift+left-drag or right-drag pans, wheel zooms or dollies. + * Mirrors Three.js OrbitControls semantics. */ - -import { applyOrbit, applyPan } from "@layoutit/polycss-core"; import type { PolyCameraControlTarget } from "./scene/types"; -import { - BASE_DEFAULTS, - resolveOptions, - makeListenerRegistry, - makeCameraSnapshot, - makeWheelHandler, - makeAnimLoop, - type PolyControlsBaseOptions, - type PolyControlsHandle, - type PolyControlsEvent, - type PolyControlsListener, - type ResolvedOptions, -} from "./controls/common"; +import type { PolyControlsBaseOptions, PolyControlsHandle } from "./controls/common"; +import { createPointerControls } from "./controls/pointerControlsCore"; export type { PolyControlsAnimateOptions, @@ -41,265 +25,5 @@ export function createPolyOrbitControls( scene: PolyCameraControlTarget, options: PolyOrbitControlsOptions = {}, ): PolyOrbitControlsHandle { - let opts: ResolvedOptions = resolveOptions(BASE_DEFAULTS, options); - const host = scene.host; - const win = host.ownerDocument?.defaultView ?? globalThis; - - let activePointerId: number | null = null; - let pointer = { x: 0, y: 0 }; - let rightDragActive = false; - let rightPointer = { x: 0, y: 0 }; - let dragStylesApplied = false; - let animPaused = false; - let stopped = false; - - const registry = makeListenerRegistry(); - const snapshot = makeCameraSnapshot(scene); - const { changeListeners, startListeners, endListeners, listenerArray, emitChange, emitInteraction } = registry; - - const animLoop = makeAnimLoop( - win as typeof globalThis, - scene, - () => opts, - () => stopped, - () => animPaused, - snapshot, - emitChange, - ); - - function syncDragStyles(): void { - if (!stopped && opts.drag) { - host.style.cursor = activePointerId !== null ? "grabbing" : "grab"; - host.style.touchAction = "none"; - host.style.userSelect = "none"; - dragStylesApplied = true; - } else if (dragStylesApplied) { - host.style.cursor = ""; - host.style.touchAction = ""; - host.style.userSelect = ""; - dragStylesApplied = false; - } - } - - // ── Pointer drag (orbit) ───────────────────────────────────────────────── - const onPointerDown = (e: PointerEvent): void => { - if (!opts.drag || stopped) return; - if (e.button === 2) return; - if (activePointerId !== null) return; - if (e.isPrimary === false) return; - e.preventDefault(); - activePointerId = e.pointerId; - pointer = { x: e.clientX, y: e.clientY }; - host.style.cursor = "grabbing"; - dragStylesApplied = true; - try { (e.target as Element).setPointerCapture(e.pointerId); } catch { /* ignore */ } - if (opts.animate && opts.animate.pauseOnInteraction) { - animPaused = true; - } - emitInteraction("start", snapshot); - }; - - const onPointerMove = (e: PointerEvent): void => { - if (activePointerId === null || e.pointerId !== activePointerId) return; - if (!opts.drag || stopped) return; - e.preventDefault(); - const dx = e.clientX - pointer.x; - const dy = e.clientY - pointer.y; - pointer = { x: e.clientX, y: e.clientY }; - const cameraState = scene.camera.state; - if (e.shiftKey) { - // Shift+left-drag pans (slippy-map semantics) - const { targetD0, targetD1 } = applyPan( - dx, - dy, - cameraState.zoom ?? 1, - cameraState.rotX ?? 65, - cameraState.rotY ?? 45, - ); - const t = cameraState.target ?? [0, 0, 0]; - scene.camera.update({ target: [t[0] + targetD0, t[1] + targetD1, t[2]] }); - } else { - // Left-drag orbits. - // rotX is clamped to [0, 89]: at 0 the camera is looking straight - // down at the scene (floor's +Z normal faces the camera); rotating - // PAST 90 flips the floor's normal away from camera, so its - // `backface-visibility: hidden` leaf vanishes and any cast shadow - // ON the floor vanishes with it. The old upper bound of 100 let a - // user drag the camera into that back-facing region (visible in the - // gallery as "the ground disappears when I rotate up"); stop at 89 - // so the floor stays visible at the steepest practical tilt. - const next = applyOrbit(dx, dy, cameraState.rotX ?? 65, cameraState.rotY ?? 45, opts.invert); - scene.camera.update({ rotX: Math.max(0, Math.min(89, next.rotX)), rotY: next.rotY }); - } - scene.applyCamera(); - emitChange(snapshot); - }; - - const onPointerUp = (e: PointerEvent): void => { - if (activePointerId !== e.pointerId) return; - activePointerId = null; - syncDragStyles(); - try { (e.target as Element).releasePointerCapture(e.pointerId); } catch { /* ignore */ } - if (opts.animate && opts.animate.pauseOnInteraction) { - animPaused = false; - // Reset lastTime to avoid a catch-up jump equal to drag duration. - } - emitInteraction("end", snapshot); - }; - - // ── Right-drag: pan ────────────────────────────────────────────────────── - const onContextMenu = (e: Event): void => { - if (!opts.drag || stopped) return; - e.preventDefault(); - }; - - const onMouseDown = (e: MouseEvent): void => { - if (!opts.drag || stopped) return; - if (e.button !== 2) return; - rightDragActive = true; - rightPointer = { x: e.clientX, y: e.clientY }; - if (opts.animate && opts.animate.pauseOnInteraction) { - animPaused = true; - } - emitInteraction("start", snapshot); - }; - - const onMouseMove = (e: MouseEvent): void => { - if (!rightDragActive || !opts.drag || stopped) return; - const dx = e.clientX - rightPointer.x; - const dy = e.clientY - rightPointer.y; - rightPointer = { x: e.clientX, y: e.clientY }; - const cameraState = scene.camera.state; - const { targetD0, targetD1 } = applyPan( - dx, - dy, - cameraState.zoom ?? 1, - cameraState.rotX ?? 65, - cameraState.rotY ?? 45, - ); - const t = cameraState.target ?? [0, 0, 0]; - scene.camera.update({ target: [t[0] + targetD0, t[1] + targetD1, t[2]] }); - scene.applyCamera(); - emitChange(snapshot); - }; - - const onMouseUp = (e: MouseEvent): void => { - if (e.button !== 2) return; - if (rightDragActive) { - rightDragActive = false; - if (opts.animate && opts.animate.pauseOnInteraction) { - animPaused = false; - } - emitInteraction("end", snapshot); - } - }; - - const wheelHandler = makeWheelHandler( - scene, - () => opts, - () => stopped, - snapshot, - emitChange, - emitInteraction, - ); - - function attach(): void { - host.addEventListener("pointerdown", onPointerDown); - host.addEventListener("pointermove", onPointerMove); - host.addEventListener("pointerup", onPointerUp); - host.addEventListener("pointercancel", onPointerUp); - host.addEventListener("wheel", wheelHandler.onWheel, { passive: false }); - host.addEventListener("contextmenu", onContextMenu); - host.addEventListener("mousedown", onMouseDown); - host.addEventListener("mousemove", onMouseMove); - host.addEventListener("mouseup", onMouseUp); - syncDragStyles(); - } - - function detach(): void { - host.removeEventListener("pointerdown", onPointerDown); - host.removeEventListener("pointermove", onPointerMove); - host.removeEventListener("pointerup", onPointerUp); - host.removeEventListener("pointercancel", onPointerUp); - host.removeEventListener("wheel", wheelHandler.onWheel); - host.removeEventListener("contextmenu", onContextMenu); - host.removeEventListener("mousedown", onMouseDown); - host.removeEventListener("mousemove", onMouseMove); - host.removeEventListener("mouseup", onMouseUp); - if (dragStylesApplied) { - host.style.cursor = ""; - host.style.touchAction = ""; - host.style.userSelect = ""; - dragStylesApplied = false; - } - wheelHandler.teardown(); - } - - attach(); - animLoop.start(); - - function update(partial: PolyOrbitControlsOptions): void { - const wasAnimating = !!opts.animate; - opts = resolveOptions(opts, partial); - if (!stopped && activePointerId === null) { - syncDragStyles(); - } - const isAnimating = !!opts.animate; - if (wasAnimating && !isAnimating) { - animLoop.stop(); - } else if (!wasAnimating && isAnimating) { - animLoop.start(); - } - } - - function resume(): void { - if (!stopped) return; - stopped = false; - attach(); - animLoop.start(); - } - - function pause(): void { - if (stopped) return; - stopped = true; - detach(); - animLoop.stop(); - activePointerId = null; - rightDragActive = false; - animPaused = false; - wheelHandler.teardown(); - } - - function destroy(): void { - pause(); - changeListeners.length = 0; - startListeners.length = 0; - endListeners.length = 0; - } - - function addEventListener( - type: T, - listener: PolyControlsListener>, - ): void { - const arr = listenerArray(type); - if (!arr.includes(listener as PolyControlsListener)) arr.push(listener as PolyControlsListener); - } - - function removeEventListener( - type: T, - listener: PolyControlsListener>, - ): void { - const arr = listenerArray(type); - const idx = arr.indexOf(listener as PolyControlsListener); - if (idx >= 0) arr.splice(idx, 1); - } - - function hasEventListener( - type: T, - listener: PolyControlsListener>, - ): boolean { - return listenerArray(type).includes(listener as PolyControlsListener); - } - - return { update, resume, pause, destroy, addEventListener, removeEventListener, hasEventListener }; + return createPointerControls(scene, "orbit", options); } diff --git a/packages/polycss/src/api/createPolyScene.ts b/packages/polycss/src/api/createPolyScene.ts index 5b4f01da2..ac4a2c041 100644 --- a/packages/polycss/src/api/createPolyScene.ts +++ b/packages/polycss/src/api/createPolyScene.ts @@ -5,134 +5,48 @@ * Takes a host element + scene options and returns a `PolySceneHandle` whose * `add(parseResult, transform?)` mounts a mesh under the scene root and returns * a removable `PolyMeshHandle`. - * - * Implementation: - * - Inserts a `
` into the host. - * - Each `add(...)` creates a `
` with the mesh - * transform; mounts every valid polygon using the cheapest supported - * render-strategy leaf. - * - `destroy()` removes the scene element and disposes every mesh - * (which in turn disposes generated atlas blob URLs). - * - * The scene element is a 0×0 anchor at world (0,0,0) — pinned via - * top:50%/left:50% so it sits at the visible center of the host. This - * matches React/Vue's PolyScene anchor pattern. Polygons render around - * the anchor via their own matrix3d translations. */ import type { ParseResult, Polygon, - Vec3, PolyPointLight, + Vec3, } from "@layoutit/polycss-core"; -import type { - PolyPerspectiveCameraHandle, - PolyOrthographicCameraHandle, -} from "./createPolyCamera"; -import { - DEFAULT_SEAM_BLEED, - computeSceneBbox, - computeLightVisibility, - capturePolyCameraSnapshot, - inverseRotateVec3, - optimizeMeshPolygons, - -} from "@layoutit/polycss-core"; -import { - getSolidPaintDefaults, - renderPolygonsWithTextureAtlas, - renderPolygonsWithTextureAtlasAsync, - renderPolygonsWithStableTriangles, - updateStableTriangleFrame, - updatePolygonsWithStableTopology, - type SolidPaintDefaults, -} from "../render/textureAtlas"; -import { - createPolyVoxelRenderer, - type PolyVoxelRenderer, -} from "../render/voxelRenderer"; +import { DEFAULT_SEAM_BLEED, computeSceneBbox } from "@layoutit/polycss-core"; +import { writeCameraSnapshotAttrs } from "./cameraSnapshotAttrs"; import { injectPolyBaseStyles } from "../styles/styles"; -import { - DEFAULT_TILE, - applyCssZoomCompensation, - buildMeshTransform, - buildSceneTransformFromCamera, - effectiveCssZoom, - worldDirectionalLightToCss, -} from "./scene/transforms"; -import { - shadowOptsEqual, - strategiesEqual, - vec3Equal, -} from "./scene/equality"; -import { - applyDynamicLightVars, - applySolidPaintVars, -} from "./scene/lightingVars"; -import type { - MeshEntry, -} from "./scene/internalTypes"; -import { createSceneContext } from "./scene/sceneContext"; -import type { SceneContext } from "./scene/sceneContext"; -import { - TEXTURES_READY, - clearRendered, - setRendered, -} from "./scene/mountLifecycle"; -import { - cameraCullRotation, - canDomCullCamera, - recomputeCameraCullGroups, - syncCameraCullSignature, -} from "./scene/cameraCull"; -import { - syncMountedRendered, - syncMountedRenderedChunked, - syncMountedRenderedForCameraChange, -} from "./scene/mountSync"; -import { - canRenderVoxelDirect, - collectAtlasUrlsFromRendered, - decodeAtlasUrls, - effectiveTextureLighting, - renderEntryAtomic, - requestRebakeAtlas, - resolveMeshRenderOptions, -} from "./scene/rebake"; import { applyMeshLightVarOverride, clearBakedSolidLightingPreview, commitBakedSolidLighting, previewBakedSolidLighting, } from "./scene/bakedLighting"; -import { tryUpdatePolygonLeafOnly } from "./scene/polygonPatch"; -import { disposeReceiverShadowMounts } from "./scene/receiverShadow"; +import { shadowOptsEqual, strategiesEqual, vec3Equal } from "./scene/equality"; +import type { MeshEntry } from "./scene/internalTypes"; +import { applyDynamicLightVars } from "./scene/lightingVars"; +import { addSceneMeshEntry } from "./scene/meshEntry"; +import { syncMountedRenderedForCameraChange } from "./scene/mountSync"; +import { effectiveTextureLighting } from "./scene/rebake"; +import { renderSceneEntry } from "./scene/renderEntry"; +import { createSceneContext, type SceneContext } from "./scene/sceneContext"; +import { clearAllSceneShadows } from "./scene/shadowCache"; import { - clearAllSceneShadows, - clearCasterItemsCache as clearCasterItemsCacheImpl, - clearReceiverShadowCache as clearReceiverShadowCacheImpl, -} from "./scene/shadowCache"; -import { - cachedOverlappingPolygonDuplicates, emitSceneShadows, - emitShadowLeaves, invalidateShadowLightCache, - maybeEmitAnimationShadow, recomputeShadowGround, syncShadowsForCameraChange, } from "./scene/shadowOrchestrator"; +import { + applyCssZoomCompensation, + buildSceneTransformFromCamera, + effectiveCssZoom, +} from "./scene/transforms"; import type { - InternalPolyMeshHandle, - InternalSetPolygonsOptions, - PolyAnimationTriangleFrame, - PolyCameraControlTarget, PolyMeshHandle, PolyMeshTransform, - PolySceneElements, PolySceneHandle, PolySceneOptions, } from "./scene/types"; -import { POLY_ANIMATION_TRIANGLE_FRAME_TARGET } from "./scene/types"; export type { PolyCameraControlTarget, @@ -144,28 +58,6 @@ export type { PolyShadowOptions, } from "./scene/types"; -function recenterPolygons(polygons: Polygon[]): Polygon[] { - if (polygons.length === 0) return polygons; - const bbox = computeSceneBbox(polygons); - const cx = (bbox.min[0] + bbox.max[0]) / 2; - const cy = (bbox.min[1] + bbox.max[1]) / 2; - const cz = (bbox.min[2] + bbox.max[2]) / 2; - if (cx === 0 && cy === 0 && cz === 0) return polygons; - const shift = (v: Vec3): Vec3 => [v[0] - cx, v[1] - cy, v[2] - cz]; - return polygons.map((p) => ({ - ...p, - vertices: p.vertices.map(shift), - ...(p.textureTriangles?.length - ? { - textureTriangles: p.textureTriangles.map((tri) => ({ - ...tri, - vertices: [shift(tri.vertices[0]), shift(tri.vertices[1]), shift(tri.vertices[2])] as [Vec3, Vec3, Vec3], - })), - } - : {}), - })); -} - function normalizeSceneOptions>>(options: T): T { if (!Object.prototype.hasOwnProperty.call(options, "seamBleed") || options.seamBleed !== undefined) { return options; @@ -173,7 +65,6 @@ function normalizeSceneOptions = normalizeSceneOptions({ @@ -214,35 +99,21 @@ export function createPolyScene( }); const layoutScale = effectiveCssZoom(host); - // Bbox-center of all live meshes (helpers opt out), or explicit polygons - // when `autoCenterSource === "explicit"`. Folded into the scene transform - // alongside `target` so the camera orbits the model's visible center without - // shifting the mesh DOM. let autoCenterOffset: Vec3 = [0, 0, 0]; let explicitCenterPolygons: readonly Polygon[] | null = null; const doc = host.ownerDocument ?? document; - // Camera wrapper: carries the CSS `perspective` so it foreshortens the - // scene's direct 3D children correctly. When `options.elements` is passed, - // adopt caller-owned elements without creating duplicate wrappers. const cameraEl = options.elements ? options.elements.cameraEl : doc.createElement("div"); cameraEl.classList.add("polycss-camera"); - applyCameraStyle(cameraEl, currentOptions); + applyCameraStyle(cameraEl); if (!adoptedElements) host.appendChild(cameraEl); const sceneEl = options.elements ? options.elements.sceneEl : doc.createElement("div"); sceneEl.classList.add("polycss-scene"); if (!adoptedElements) sceneEl.setAttribute("aria-hidden", "true"); - // 0×0 anchor at the host's visible center. Polygons render around it. applySceneStyle(sceneEl, currentOptions); - if (!adoptedElements) cameraEl.appendChild(sceneEl); - // Bundle every mutable scene-state field into a SceneContext. Extracted - // scene/* helpers take this object as their first arg instead of capturing - // a 30-symbol closure. `meshes`, `shadowSvgState`, the cache maps, etc. - // are aliased below so the rest of the closure body uses the same names - // it always did; the alias and the ctx field reference the same object. const ctx: SceneContext = createSceneContext({ host, doc, @@ -253,49 +124,12 @@ export function createPolyScene( options: currentOptions, }); const meshes = ctx.meshes; - // Element → MeshEntry index. Outside the SceneContext because it's a - // pure-DOM lookup that the extracted shadow helpers never need; only - // findMeshByElement and click-target resolution use it. const meshByElement = new WeakMap(); - // Cache-management closures over the SceneContext. The actual maps live - // on `ctx` and are read/written by the extracted shadow emitters. - const clearReceiverShadowCache = (entry?: MeshEntry) => - clearReceiverShadowCacheImpl(ctx, entry); - const clearCasterItemsCache = (entry?: MeshEntry) => - clearCasterItemsCacheImpl(ctx, entry); - - // Apply CSS perspective on the camera wrapper, not the scene element. - // CSS `perspective` only foreshortens direct children's 3D transforms, so - // the wrapper must be the perspective context for .polycss-scene to work - // correctly — matching React/Vue's PolyPerspectiveCamera wrapper shape. - function applyCameraStyle(el: HTMLElement, _opts: Omit): void { - const snapshot = capturePolyCameraSnapshot(camera); - el.style.perspective = snapshot.appliedPerspectiveStyle; - el.dataset.polycssCameraProjection = snapshot.projection; - el.dataset.polycssCameraPerspective = snapshot.perspectiveStyle; - el.dataset.polycssCameraAppliedPerspective = snapshot.appliedPerspectiveStyle; - el.dataset.polycssCameraZoom = String(snapshot.state.zoom); - el.dataset.polycssCameraDistance = String(snapshot.state.distance); - el.dataset.polycssCameraRotX = String(snapshot.state.rotX); - el.dataset.polycssCameraRotY = String(snapshot.state.rotY); - el.dataset.polycssCameraTarget = snapshot.state.target.join(","); + function applyCameraStyle(el: HTMLElement): void { + writeCameraSnapshotAttrs(el, camera, { applyPerspective: true }); } - // Dynamic lighting cascade vars: PolyScene writes the directional + ambient - // light setup to these custom properties on the scene root. Each polygon's - // bakes its own normal directly into an inline calc() that reads these - // vars to resolve the Lambert dot product and per-channel tint. Sliding - // the light only writes these scene-root vars — no JS, no atlas redraw. - // - // Additionally emits --clx/--cly/--clz: the directional light expressed in - // CSS coordinate space (world-Y→CSS-X, world-X→CSS-Y, world-Z→CSS-Z). These - // are used by the shadow projection matrix (--shadow-proj) which must operate - // on matrix3d positions that live in CSS space — not world space. The Lambert - // dot product can use world-space normals because both normals and light sit - // in the same frame there; the shadow projection works against 3D positions - // that have already been through the axis swap, so it needs the light in - // that same swapped frame. function applySceneStyle(el: HTMLElement, opts: Omit): void { applyCssZoomCompensation(el, layoutScale); el.style.transform = buildSceneTransformFromCamera(camera, autoCenterOffset, layoutScale); @@ -306,223 +140,11 @@ export function createPolyScene( el.style.transform = buildSceneTransformFromCamera(camera, autoCenterOffset, layoutScale); } - // Per-light raytrace cache. Returns the set of polygon indices the - // directional light cannot reach (occluded by another polygon of the - // same mesh). Used by baked atlas planning to force directScale=0 on - // those polys so they render ambient-only — matches what a shadow-map - // depth-test would do, without running per-frame. - // - // The mesh's bakedRotation already lives in the (lightDir) passed by - // rebakeAtlas (light is inverse-rotated to mesh-local frame), so the - // raytrace can run directly against entry.polygons. - function occludedPolyIndicesForEntry( - entry: MeshEntry, - lightDir: Vec3 | undefined, - ): ReadonlySet | undefined { - if (!lightDir) return undefined; - if (!entry.polygons || entry.polygons.length < 2) return undefined; - const lLen = Math.hypot(lightDir[0], lightDir[1], lightDir[2]); - if (!Number.isFinite(lLen) || lLen <= 0) return undefined; - const lx = lightDir[0] / lLen, ly = lightDir[1] / lLen, lz = lightDir[2] / lLen; - // Quantize so jittery slider input doesn't bust the cache every frame. - const k = (v: number) => Math.round(v * 1000) / 1000; - const lightDirKey = `${k(lx)},${k(ly)},${k(lz)}`; - const cached = entry.lightOcclusionCache; - if (cached && cached.polygons === entry.polygons && cached.lightDirKey === lightDirKey) { - return cached.occluded; - } - // Reuse the dedup drop-set across light-direction changes — it's a - // pure geometric property of the polygon set, not of the light. This - // matters because dedup is O(n²) and the raytrace itself is BVH-fast. - // Tight thresholds vs the shadow-rendering dedup (distanceTolerance: - // 0.5, overlapFraction: 0.95): only drop near-coincident back-to-back - // wall pairs (~0.05-0.1 mesh units apart — the OBJ double-face quirk - // that caused the cottage false-positive). With distanceTolerance: 0.5 - // the bench castle drops 104/681 polys including legitimate occluded - // walls (polygon 111). Tightening to 0.12 + overlapFraction 0.98 - // captures the cottage case and leaves merlon/tower geometry intact. - const dedupDropped = cachedOverlappingPolygonDuplicates(entry.polygons, { - normalTolerance: 0.1, - distanceTolerance: 0.12, - overlapFraction: 0.98, - preserveDoubleSidedBackfaces: false, - }); - const occluded = computeLightVisibility(entry.polygons, [lx, ly, lz], dedupDropped); - entry.lightOcclusionCache = { - polygons: entry.polygons, - lightDirKey, - occluded, - dedupDropped, - }; - return occluded; - } - function renderEntry(entry: MeshEntry, lightDirectionOverride?: Vec3): void { - clearRendered(ctx, entry); - const baseDirLight = currentOptions.directionalLight; - // lightDirectionOverride and baseDirLight.direction are both in user - // world frame; convert to renderer CSS frame for the lambert dot product. - const userDirLight: typeof baseDirLight = lightDirectionOverride - ? { ...baseDirLight, direction: lightDirectionOverride } - : baseDirLight; - const directionalLight = worldDirectionalLightToCss(userDirLight); - // Per-light raytrace occlusion (task #121). Re-enabled — the cottage - // false-positive (back-to-back inner/outer wall pairs ~0.05-0.1 mesh - // units apart self-occluding the outer face) is dropped via the - // dedup-before-raytrace path inside occludedPolyIndicesForEntry. We - // pass `findOverlappingPolygonDuplicates`'s drop-set as `skipIndices` - // to `computeLightVisibility`, which removes those polys from both - // the source loop AND the BVH candidate set. - // - // Frame: pass the USER-WORLD light direction, not the CSS-frame one. - // `computeLightVisibility` raytraces against polygon vertices in - // their original frame (vertex arrays as the parser produced them), - // so the light direction must match that frame. Passing the CSS- - // converted direction here mismatches axes (X↔Y swap) and silently - // gives wrong occlusion results — matches the regression from - // task #126. - // Per-light occlusion raytrace (task #121) used to mark polygons in - // ray-traced shadow with `directScale=0` so they baked at ambient-only. - // Three.js doesn't bake shadow into the diffuse atlas — it uses a real - // shadow map at render time, so a "in shadow" polygon's diffuse stays - // at full Lambert(n·L) and the shadow darkens it later. Matching that - // contract avoids the gallery's "first render looks dim, brightens - // after I move a light" symptom (the commit-on-light bake never knew - // about the occluded set and so always produced the bright look — - // which is the correct one). The occluded set is still computed by - // the dynamic path for per-leaf SH-1 visibility (task #128). - const lightOccludedPolyIndices: ReadonlySet | undefined = undefined; - void occludedPolyIndicesForEntry; // keep helper exported for dynamic path - if (canRenderVoxelDirect(ctx, entry)) { - const renderer = createPolyVoxelRenderer({ - doc, - wrapper: entry.wrapper, - polygons: entry.parseResult.polygons, - directionalLight, - ambientLight: currentOptions.ambientLight, - }); - if (renderer) { - entry.voxelRenderer = renderer; - renderer.render(cameraCullRotation(ctx, entry)); - entry.cameraCullSignature = "voxel-direct"; - entry.textureReadyPromise = TEXTURES_READY; - if (entry.atomicAtlas && entry.onFrameReady) entry.onFrameReady(); - return; - } - } - - const resolvedRenderOptions = resolveMeshRenderOptions(ctx, entry, lightDirectionOverride); - const entryLighting = resolvedRenderOptions.textureLighting; - const renderOptions = { - ...resolvedRenderOptions, - lightOccludedPolyIndices, - }; - let stableAtlas: ReturnType = null; - if (entry.stableDom) { - const solidPaintDefaults = getSolidPaintDefaults(entry.polygons, renderOptions); - stableAtlas = renderPolygonsWithStableTriangles(entry.polygons, { - ...renderOptions, - solidPaintDefaults, - }); - if (stableAtlas) { - applySolidPaintVars(entry.wrapper, solidPaintDefaults); - } else { - // Polygons are not eligible for stable-triangle updates (e.g. quads - // or textured faces); clear stableDom so Lambert bucketing and - // in-place rebaking stay enabled. - entry.stableDom = false; - } - } - const atlas = stableAtlas ?? renderPolygonsWithTextureAtlas(entry.polygons, { - ...renderOptions, - computeSolidPaintDefaults: true, - skipDynamicNormalVars: entryLighting === "dynamic", - } as typeof renderOptions & { computeSolidPaintDefaults: true }); - if (!stableAtlas) { - applySolidPaintVars( - entry.wrapper, - (atlas as { solidPaintDefaults?: SolidPaintDefaults }).solidPaintDefaults ?? {}, - ); - } - setRendered(entry, atlas.rendered, atlas.dispose, atlas.pagesReady); - entry.skipBucketNormalCleanupOnce = - entryLighting === "dynamic" && !entry.stableDom; - recomputeCameraCullGroups(entry); - syncMountedRendered(ctx, entry); - emitShadowLeaves(ctx, entry); - if (entry.atomicAtlas && entry.onFrameReady) { - const version = entry.atomicSwapVersion; - const ready = (atlas as { pagesReady?: Promise }).pagesReady; - if (ready && typeof ready.then === "function") { - ready - .then(() => { - if (entry.disposed || version !== entry.atomicSwapVersion) return; - return decodeAtlasUrls(collectAtlasUrlsFromRendered(atlas.rendered)); - }) - .then(() => { - if (!entry.disposed && version === entry.atomicSwapVersion) entry.onFrameReady?.(); - }, () => { - if (!entry.disposed && version === entry.atomicSwapVersion) entry.onFrameReady?.(); - }); - } else { - entry.onFrameReady(); - } - } - } - - async function renderEntryChunked( - entry: MeshEntry, - shouldCancel: () => boolean, - ): Promise { - clearRendered(ctx, entry); - const resolvedRenderOptions = resolveMeshRenderOptions(ctx, entry); - const entryLighting = resolvedRenderOptions.textureLighting; - const renderOptions = { - ...resolvedRenderOptions, - // Per-light raytrace occlusion (task #121) disabled — see renderEntry. - lightOccludedPolyIndices: undefined as ReadonlySet | undefined, - }; - const atlas = entry.stableDom - ? renderPolygonsWithStableTriangles(entry.polygons, renderOptions) - : null; - if (atlas) { - const solidPaintDefaults = getSolidPaintDefaults(entry.polygons, renderOptions); - applySolidPaintVars(entry.wrapper, solidPaintDefaults); - setRendered(entry, atlas.rendered, atlas.dispose, atlas.pagesReady); - recomputeCameraCullGroups(entry); - syncMountedRendered(ctx, entry); - emitShadowLeaves(ctx, entry); - return !shouldCancel(); - } - - const asyncAtlas = await renderPolygonsWithTextureAtlasAsync( - entry.polygons, - { - ...renderOptions, - skipDynamicNormalVars: entryLighting === "dynamic", - } as typeof renderOptions & { skipDynamicNormalVars: boolean }, - shouldCancel, - ); - if (shouldCancel()) { - asyncAtlas.dispose(); - return false; - } - applySolidPaintVars(entry.wrapper, asyncAtlas.solidPaintDefaults); - setRendered(entry, asyncAtlas.rendered, asyncAtlas.dispose, asyncAtlas.pagesReady); - entry.skipBucketNormalCleanupOnce = - entryLighting === "dynamic" && !entry.stableDom; - recomputeCameraCullGroups(entry); - const mounted = await syncMountedRenderedChunked(ctx, entry, shouldCancel); - if (mounted) emitShadowLeaves(ctx, entry); - return mounted; + renderSceneEntry(ctx, entry, lightDirectionOverride); } function recomputeAutoCenter(): void { - // Three.js–style: instead of moving the meshes (via a wrapper translate), - // store the bbox center as a camera-target offset. `buildSceneTransform` - // folds it into the scene's rotation pivot, so the visible center stays - // at the viewport without adding a DOM wrapper or shifting polygon - // coordinates. const prev = autoCenterOffset; let next: Vec3 = [0, 0, 0]; if (currentOptions.autoCenter) { @@ -552,612 +174,10 @@ export function createPolyScene( currentOptions.onAutoCenterOffsetChange?.(next); } - function add(parseResult: ParseResult, transformIn: PolyMeshTransform = {}): PolyMeshHandle { - const mountDoc = sceneEl.ownerDocument ?? document; - const adoptedWrapper = !!transformIn.wrapper; - const isSceneRootWrapper = transformIn.wrapper === sceneEl; - const wrapper = transformIn.wrapper ?? mountDoc.createElement("div"); - if (adoptedWrapper) { - if (!isSceneRootWrapper) wrapper.classList.add("polycss-mesh"); - } else { - wrapper.className = "polycss-mesh"; - } - const autoMeshId = `polycss-mesh-${ctx.meshAutoCounter.next++}`; - if (!isSceneRootWrapper) { - if (transformIn.id) wrapper.setAttribute("data-poly-mesh-id", transformIn.id); - wrapper.setAttribute("data-poly-mesh-index", autoMeshId); - } - - let transform: PolyMeshTransform = { ...transformIn }; - let mergeOnUpdate = transformIn.merge !== false; - let stableDomOnUpdate = !!transformIn.stableDom; - let autoCenterOnUpdate = !!transformIn.autoCenter; - let polygonUpdateVersion = 0; - const css = buildMeshTransform(transform); - if (!isSceneRootWrapper && css) wrapper.style.transform = css; - - const preparePolygons = (polygons: Polygon[], merge: boolean): Polygon[] => { - const centered = autoCenterOnUpdate ? recenterPolygons(polygons) : polygons; - if (parseResult.voxelSource) return centered; - if (merge) return optimizeMeshPolygons(centered, { meshResolution: transform.meshResolution }); - if (stableDomOnUpdate) return centered; - if (transform.excludeFromAutoCenter) return centered; - return centered; - }; - const sourcePolygons = preparePolygons(parseResult.polygons, mergeOnUpdate); - - // Three.js parity: wrapper rotation, scale and translate all pivot at - // the wrapper's local (0,0,0). Parser places geometry either with - // bbox-min at origin (default) or centered (parser `{ center: true }`); - // callers wanting "rotate in place around centroid" use the centered - // variant. `bboxCenterCssCache` still tracks the geometry bbox center - // because the shadow cache keys on it (receiverShadow.ts) — same data, - // but it no longer drives transform-origin. - let bboxCenterCssCache: Vec3 | null = null; - function reapplyWrapperTransform(): void { - if (isSceneRootWrapper) return; - const css = buildMeshTransform(transform); - wrapper.style.transform = css ?? ""; - } - function applyTransformOrigin(polygons: Polygon[]): void { - if (polygons.length === 0) { - bboxCenterCssCache = null; - if (entryRef) entryRef.bboxCenterCss = null; - reapplyWrapperTransform(); - return; - } - let minX = Infinity, minY = Infinity, minZ = Infinity; - let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity; - for (const poly of polygons) { - for (const v of poly.vertices) { - if (v[0] < minX) minX = v[0]; - if (v[0] > maxX) maxX = v[0]; - if (v[1] < minY) minY = v[1]; - if (v[1] > maxY) maxY = v[1]; - if (v[2] < minZ) minZ = v[2]; - if (v[2] > maxZ) maxZ = v[2]; - } - } - if (!Number.isFinite(minX)) { - bboxCenterCssCache = null; - if (entryRef) entryRef.bboxCenterCss = null; - reapplyWrapperTransform(); - return; - } - // World→CSS axis remap (matches polygonGeometry / autoCenter). - const cssX = ((minY + maxY) / 2) * DEFAULT_TILE; - const cssY = ((minX + maxX) / 2) * DEFAULT_TILE; - const cssZ = ((minZ + maxZ) / 2) * DEFAULT_TILE; - bboxCenterCssCache = [cssX, cssY, cssZ]; - if (entryRef) entryRef.bboxCenterCss = bboxCenterCssCache; - reapplyWrapperTransform(); - } - let entryRef: MeshEntry | null = null; - applyTransformOrigin(sourcePolygons); - - if (!adoptedWrapper) sceneEl.appendChild(wrapper); - - const entry: MeshEntry = { - handle: undefined as unknown as PolyMeshHandle, - wrapper, - adoptedWrapper, - ownedNodes: new Set(), - parseResult, - rendered: [], - renderedByPolygonIndex: [], - shadowRendered: [], - polygons: sourcePolygons, - voxelSource: parseResult.voxelSource, - disposed: false, - stableDom: stableDomOnUpdate, - autoCenter: autoCenterOnUpdate, - atomicAtlas: !!transformIn.atomicAtlas, - onFrameReady: transformIn.onFrameReady, - atomicSwapVersion: 0, - renderOverrides: { - textureLighting: transformIn.textureLighting, - textureQuality: transformIn.textureQuality, - textureLeafSizing: transformIn.textureLeafSizing, - textureImageRendering: transformIn.textureImageRendering, - textureBackend: transformIn.textureBackend, - textureProjection: transformIn.textureProjection, - seamBleed: transformIn.seamBleed, - }, - hasBuckets: false, - skipBucketNormalCleanupOnce: false, - excludeFromAutoCenter: !!transformIn.excludeFromAutoCenter, - castShadow: !!transformIn.castShadow, - bboxCenterCss: bboxCenterCssCache, - receiveShadow: !!transformIn.receiveShadow, - shadowDefinition: transformIn.shadowDefinition, - cameraCullGroups: [], - cameraCullSignature: "", - lightOverrideSignature: "clear", - stableTriangleColorFrame: 0, - solidLightingPreviewPrepared: false, - solidLightingPreviewActive: false, - bakedRotation: (transformIn.rotation ? [...transformIn.rotation] : [0, 0, 0]) as Vec3, - autoMeshId, - rebakeInFlight: false, - rebakeQueued: false, - rebakeQueuedLightDir: undefined, - textureReadyPromise: TEXTURES_READY, - }; - - let currentTriangleFrame: PolyAnimationTriangleFrame | null = null; - let currentTriangleFrameVersion = 0; - let materializedTriangleFrameVersion = -1; - let materializedTriangleFramePolygons: Polygon[] | null = null; - - function clearCurrentTriangleFrame(): void { - currentTriangleFrame = null; - materializedTriangleFramePolygons = null; - materializedTriangleFrameVersion = -1; - } - - function currentPolygons(): Polygon[] { - const frame = currentTriangleFrame; - if (!frame || frame.polygonCount !== entry.polygons.length) return entry.polygons; - if ( - materializedTriangleFramePolygons && - materializedTriangleFrameVersion === currentTriangleFrameVersion - ) { - return materializedTriangleFramePolygons; - } - const values = frame.vertices; - const out: Polygon[] = new Array(frame.polygonCount); - for (let polygonIndex = 0; polygonIndex < frame.polygonCount; polygonIndex++) { - const base = entry.polygons[polygonIndex]!; - const offset = polygonIndex * 9; - out[polygonIndex] = { - ...base, - color: frame.colors?.[polygonIndex] ?? base.color, - vertices: [ - [values[offset]!, values[offset + 1]!, values[offset + 2]!] as Vec3, - [values[offset + 3]!, values[offset + 4]!, values[offset + 5]!] as Vec3, - [values[offset + 6]!, values[offset + 7]!, values[offset + 8]!] as Vec3, - ], - }; - } - materializedTriangleFramePolygons = out; - materializedTriangleFrameVersion = currentTriangleFrameVersion; - return out; - } - - function applyStableTopologyUpdate( - options: InternalSetPolygonsOptions | undefined, - shouldRecomputeAutoCenter: boolean, - ): boolean { - const colorOnlyStableTriangleUpdate = - options?.stableTriangleUpdateMode === "color-only"; - entry.stableTriangleColorFrame++; - const shouldSkipTransformOrigin = - entry.stableDom && !shouldRecomputeAutoCenter; - if (!shouldSkipTransformOrigin) applyTransformOrigin(entry.polygons); - if (entry.stableDom && !entry.hasBuckets) { - const renderOptions = resolveMeshRenderOptions(ctx, entry); - const allStableTriangles = - entry.rendered.length === entry.polygons.length && - entry.rendered.every((item) => item.kind === "triangle"); - const optimizeStableTopology = - entry.stableDom && !shouldRecomputeAutoCenter; - const solidPaintDefaults = allStableTriangles || optimizeStableTopology - ? {} - : getSolidPaintDefaults(entry.polygons, renderOptions); - if (!allStableTriangles) applySolidPaintVars(entry.wrapper, solidPaintDefaults); - const stableTopologyOptions = { - ...renderOptions, - solidPaintDefaults, - optimizeStableTriangleStyle: true, - stableTriangleDebug: options?.stableTriangleDebug, - stableTriangleUpdateMode: options?.stableTriangleUpdateMode, - stableTriangleColorPolicy: options?.stableTriangleColorPolicy, - stableTriangleColorSteps: options?.stableTriangleColorSteps, - stableTriangleColorFreezeFrames: options?.stableTriangleColorFreezeFrames, - stableTriangleColorBudget: options?.stableTriangleColorBudget, - stableTriangleColorMaxAge: options?.stableTriangleColorMaxAge, - stableTriangleColorMaxStep: options?.stableTriangleColorMaxStep, - stableTriangleMatrixDecimals: options?.stableTriangleMatrixDecimals, - stableTriangleColorFrame: entry.stableTriangleColorFrame, - } as Parameters[2] & { - optimizeStableTriangleStyle: boolean; - stableTriangleDebug?: "transform-only" | "plan-only"; - stableTriangleUpdateMode?: "full" | "transform-only" | "color-only"; - stableTriangleColorPolicy?: "cadence" | "adaptive"; - stableTriangleColorSteps?: number; - stableTriangleColorFreezeFrames?: number; - stableTriangleColorBudget?: number; - stableTriangleColorMaxAge?: number; - stableTriangleColorMaxStep?: number; - stableTriangleMatrixDecimals?: number; - stableTriangleColorFrame?: number; - }; - if ( - updatePolygonsWithStableTopology( - entry.rendered, - entry.polygons, - stableTopologyOptions, - ) - ) { - if (!colorOnlyStableTriangleUpdate) { - recomputeCameraCullGroups(entry); - syncMountedRenderedForCameraChange(ctx, entry, true); - if (shouldRecomputeAutoCenter) recomputeAutoCenter(); - } - return true; - } - } - if (shouldSkipTransformOrigin) applyTransformOrigin(entry.polygons); - return false; - } - - const handle: InternalPolyMeshHandle = { - get polygons() { return currentPolygons(); }, - set polygons(polygons: Polygon[]) { - clearCurrentTriangleFrame(); - entry.polygons = polygons; - }, - element: wrapper, - get id() { return transform.id; }, - get transform() { return transform; }, - remove() { - polygonUpdateVersion++; - entry.atomicSwapVersion++; - if (!entry.adoptedWrapper && wrapper.parentNode) wrapper.parentNode.removeChild(wrapper); - // Removing from DOM doesn't auto-dispose generated atlas/blob URLs. - clearRendered(ctx, entry); - meshes.delete(entry); - meshByElement.delete(wrapper); - clearReceiverShadowCache(entry); - clearCasterItemsCache(entry); - recomputeAutoCenter(); - recomputeShadowGround(ctx); - }, - setPolygons(polygons: Polygon[], options?: InternalSetPolygonsOptions) { - polygonUpdateVersion++; - mergeOnUpdate = options?.merge ?? mergeOnUpdate; - stableDomOnUpdate = options?.stableDom ?? stableDomOnUpdate; - entry.stableDom = stableDomOnUpdate; - entry.voxelSource = undefined; - entry.polygons = preparePolygons(polygons, mergeOnUpdate); - clearCasterItemsCache(entry); - clearReceiverShadowCache(entry); - clearCurrentTriangleFrame(); - handle.polygons = entry.polygons; - const shouldRecomputeAutoCenter = options?.recomputeAutoCenter ?? true; - // Animated shadows: re-project (throttled) from the freshly-deformed - // polygons so the shadow tracks the pose. entry.polygons is already the - // current frame's geometry here; the caster-item cache was just cleared. - maybeEmitAnimationShadow(ctx, entry); - if (applyStableTopologyUpdate(options, shouldRecomputeAutoCenter)) return; - if (entry.atomicAtlas && (entry.rendered.length > 0 || entry.voxelRenderer)) { - renderEntryAtomic(ctx, entry); - } else { - renderEntry(entry); - } - if (shouldRecomputeAutoCenter) recomputeAutoCenter(); - }, - [POLY_ANIMATION_TRIANGLE_FRAME_TARGET]( - frame: PolyAnimationTriangleFrame, - options?: InternalSetPolygonsOptions, - ) { - const nextMergeOnUpdate = options?.merge ?? mergeOnUpdate; - const nextStableDomOnUpdate = options?.stableDom ?? stableDomOnUpdate; - if ( - !frame.solidTriangles || - !nextStableDomOnUpdate || - nextMergeOnUpdate || - transformIn.meshResolution !== undefined || - entry.hasBuckets || - frame.polygonCount !== entry.polygons.length || - frame.vertices.length < frame.polygonCount * 9 || - entry.rendered.length !== frame.polygonCount - ) { - return false; - } - for (let i = 0; i < entry.rendered.length; i++) { - const rendered = entry.rendered[i]; - const polygon = entry.polygons[i]; - if ( - rendered?.kind !== "triangle" || - rendered.polygonIndex !== i || - !polygon || - polygon.vertices.length !== 3 || - polygon.texture || - polygon.material?.texture - ) { - return false; - } - } - - const shouldRecomputeAutoCenter = options?.recomputeAutoCenter ?? true; - if (!shouldRecomputeAutoCenter) { - const colorFrame = entry.stableTriangleColorFrame + 1; - const stableTopologyOptions = { - ...resolveMeshRenderOptions(ctx, entry), - solidPaintDefaults: {}, - optimizeStableTriangleStyle: true, - stableTriangleDebug: options?.stableTriangleDebug, - stableTriangleUpdateMode: options?.stableTriangleUpdateMode, - stableTriangleColorPolicy: options?.stableTriangleColorPolicy, - stableTriangleColorSteps: options?.stableTriangleColorSteps, - // Triangle-frame animation updates transforms directly; pin baked - // color unless an internal caller opts into color refresh. - stableTriangleColorFreezeFrames: options?.stableTriangleColorFreezeFrames ?? 0, - stableTriangleColorBudget: options?.stableTriangleColorBudget, - stableTriangleColorMaxAge: options?.stableTriangleColorMaxAge, - stableTriangleColorMaxStep: options?.stableTriangleColorMaxStep, - stableTriangleMatrixDecimals: options?.stableTriangleMatrixDecimals, - stableTriangleColorFrame: colorFrame, - } as Parameters[3] & { - optimizeStableTriangleStyle: boolean; - stableTriangleDebug?: "transform-only" | "plan-only"; - stableTriangleUpdateMode?: "full" | "transform-only" | "color-only"; - stableTriangleColorPolicy?: "cadence" | "adaptive"; - stableTriangleColorSteps?: number; - stableTriangleColorFreezeFrames?: number; - stableTriangleColorBudget?: number; - stableTriangleColorMaxAge?: number; - stableTriangleColorMaxStep?: number; - stableTriangleMatrixDecimals?: number; - stableTriangleColorFrame?: number; - }; - if ( - updateStableTriangleFrame( - entry.rendered, - entry.polygons, - frame, - stableTopologyOptions, - ) - ) { - polygonUpdateVersion++; - mergeOnUpdate = nextMergeOnUpdate; - stableDomOnUpdate = nextStableDomOnUpdate; - entry.stableDom = stableDomOnUpdate; - entry.voxelSource = undefined; - entry.stableTriangleColorFrame = colorFrame; - currentTriangleFrame = frame; - currentTriangleFrameVersion++; - materializedTriangleFramePolygons = null; - materializedTriangleFrameVersion = -1; - if (canDomCullCamera(entry)) { - recomputeCameraCullGroups(entry); - syncMountedRenderedForCameraChange(ctx, entry, true); - } else { - syncCameraCullSignature(ctx, entry); - } - return true; - } - } - - polygonUpdateVersion++; - mergeOnUpdate = nextMergeOnUpdate; - stableDomOnUpdate = nextStableDomOnUpdate; - entry.stableDom = stableDomOnUpdate; - entry.voxelSource = undefined; - - const values = frame.vertices; - for (let polygonIndex = 0; polygonIndex < frame.polygonCount; polygonIndex++) { - const polygon = entry.polygons[polygonIndex]!; - const color = frame.colors?.[polygonIndex]; - if (color) polygon.color = color; - const vertices = polygon.vertices; - const offset = polygonIndex * 9; - vertices[0]![0] = values[offset]!; - vertices[0]![1] = values[offset + 1]!; - vertices[0]![2] = values[offset + 2]!; - vertices[1]![0] = values[offset + 3]!; - vertices[1]![1] = values[offset + 4]!; - vertices[1]![2] = values[offset + 5]!; - vertices[2]![0] = values[offset + 6]!; - vertices[2]![1] = values[offset + 7]!; - vertices[2]![2] = values[offset + 8]!; - } - clearCurrentTriangleFrame(); - handle.polygons = entry.polygons; - return applyStableTopologyUpdate( - options, - shouldRecomputeAutoCenter, - ); - }, - updatePolygon(target: Polygon | number, partial: Partial) { - let idx = typeof target === "number" - ? target - : entry.polygons.indexOf(target); - if (idx < 0 && typeof target !== "number" && currentTriangleFrame) { - idx = currentPolygons().indexOf(target); - } - if (idx < 0 || idx >= entry.polygons.length) return; - clearCurrentTriangleFrame(); - entry.voxelSource = undefined; - // Shadow caches derive from polygon geometry, but their bust keys - // (polygon count + transform + bbox center, or polygon-array - // identity) all survive an in-place vertex edit. Mirror setPolygons: - // clear the caster/receiver caches explicitly and give the array a - // fresh identity so the identity-keyed caches (overlap dedup, - // shared-edge map, light occlusion) bust too. Color/data-only edits - // skip this — those caches are pure geometry. - if ("vertices" in partial && (entry.castShadow || entry.receiveShadow)) { - entry.polygons = entry.polygons.slice(); - clearCasterItemsCache(entry); - clearReceiverShadowCache(entry); - } - Object.assign(entry.polygons[idx], partial); - const partialKeys = Object.keys(partial); - if (tryUpdatePolygonLeafOnly(ctx, entry, idx, partialKeys)) { - return; - } - renderEntry(entry); - }, - async setPolygonsChunked(polygons: Polygon[], options?: { - merge?: boolean; - stableDom?: boolean; - recomputeAutoCenter?: boolean; - }) { - const version = ++polygonUpdateVersion; - mergeOnUpdate = options?.merge ?? mergeOnUpdate; - stableDomOnUpdate = options?.stableDom ?? stableDomOnUpdate; - entry.stableDom = stableDomOnUpdate; - entry.voxelSource = undefined; - entry.polygons = preparePolygons(polygons, mergeOnUpdate); - clearCurrentTriangleFrame(); - handle.polygons = entry.polygons; - applyTransformOrigin(entry.polygons); - const shouldRecomputeAutoCenter = options?.recomputeAutoCenter ?? true; - const shouldCancel = () => entry.disposed || version !== polygonUpdateVersion; - const completed = await renderEntryChunked(entry, shouldCancel); - if (!completed) { - clearRendered(ctx, entry); - return; - } - if (shouldRecomputeAutoCenter) recomputeAutoCenter(); - }, - setTransform(t: Partial) { - const hasOwn = (key: string): boolean => Object.prototype.hasOwnProperty.call(t, key); - const prevCastShadow = entry.castShadow; - const prevReceiveShadow = entry.receiveShadow; - const prevShadowDef = entry.shadowDefinition; - const prevExclude = entry.excludeFromAutoCenter; - if (hasOwn("castShadow")) entry.castShadow = !!t.castShadow; - if (hasOwn("receiveShadow")) entry.receiveShadow = !!t.receiveShadow; - if (hasOwn("shadowDefinition")) entry.shadowDefinition = t.shadowDefinition; - if (hasOwn("excludeFromAutoCenter")) entry.excludeFromAutoCenter = !!t.excludeFromAutoCenter; - if (hasOwn("autoCenter")) { - autoCenterOnUpdate = !!t.autoCenter; - entry.autoCenter = autoCenterOnUpdate; - } - if (hasOwn("atomicAtlas")) entry.atomicAtlas = !!t.atomicAtlas; - if (hasOwn("onFrameReady")) entry.onFrameReady = t.onFrameReady; - let renderOverrideChanged = false; - const overrideKeys = [ - "textureLighting", - "textureQuality", - "textureLeafSizing", - "textureImageRendering", - "textureBackend", - "textureProjection", - "seamBleed", - ] as const; - for (const key of overrideKeys) { - if (Object.prototype.hasOwnProperty.call(t, key) && entry.renderOverrides[key] !== t[key]) { - (entry.renderOverrides as Record)[key] = t[key]; - renderOverrideChanged = true; - } - } - transform = { ...transform, ...t }; - if (!isSceneRootWrapper) { - const css2 = buildMeshTransform(transform); - wrapper.style.transform = css2 ?? ""; - } - applyMeshLightVarOverride(ctx, entry, transform.rotation); - if (renderOverrideChanged) { - if (entry.atomicAtlas && (entry.rendered.length > 0 || entry.voxelRenderer)) { - renderEntryAtomic(ctx, entry); - } else { - renderEntry(entry); - } - } - if (t.rotation !== undefined) syncMountedRenderedForCameraChange(ctx, entry, true); - if (entry.excludeFromAutoCenter !== prevExclude) recomputeAutoCenter(); - if (entry.castShadow !== prevCastShadow) { - // Voxel-eligible meshes use the direct-matrix fast path only when - // castShadow is false (canRenderVoxelDirect). Toggling castShadow - // flips that eligibility — if it changes, the mesh has to switch - // renderer (direct-voxel ↔ polygon), so re-render the whole entry. - // Otherwise emitShadowLeaves runs on the wrong leaf set (the - // voxel-direct path has no polygon leaves to project from), and - // shadows silently fail to emit. - if (entry.voxelSource) renderEntry(entry); - emitShadowLeaves(ctx, entry); - recomputeShadowGround(ctx); - } - // Receiver toggled: rebuild the scene-level shadow set so this - // mesh's faces are added (or removed) as receivers. When flipping - // OFF, the per-frame emitter for THIS mesh would never run again - // (emitSceneShadows skips meshes with !receiveShadow), so its - // previously-mounted receiver SVGs would linger in the DOM. Tear - // them down explicitly before the rebuild. - if (entry.receiveShadow !== prevReceiveShadow) { - if (!entry.receiveShadow) disposeReceiverShadowMounts(entry); - invalidateShadowLightCache(ctx); - emitSceneShadows(ctx); - } - // Position / rotation / scale change: shadow geometry depends on - // world-space coords AND the mesh's wrapper scale (which pivots from - // the bbox center). Rotation belongs here too — it moves every caster - // vertex and every receiver face plane, and the camera-visibility - // short-circuit in emitSceneShadows reads the CACHED planes, so - // skipping the re-emit leaves that gate comparing rotated camera state - // against identity-pose normals (stale SVGs across a later orbit). - // Non-shadow helpers (e.g. the light helper) must not overwrite - // transient preview shadows with the committed light, so the gate is - // on castShadow || receiveShadow. - if ((t.position !== undefined || t.rotation !== undefined || t.scale !== undefined) - && (entry.castShadow || entry.receiveShadow)) { - recomputeShadowGround(ctx); - invalidateShadowLightCache(ctx); - emitSceneShadows(ctx); - } - // Per-mesh shadow definition changed: re-emit at the new detail. - if (entry.shadowDefinition !== prevShadowDef && (entry.castShadow || entry.receiveShadow)) { - invalidateShadowLightCache(ctx); - emitSceneShadows(ctx); - } - }, - dispose() { - if (entry.disposed) return; - entry.disposed = true; - polygonUpdateVersion++; - entry.atomicSwapVersion++; - if (!entry.adoptedWrapper && wrapper.parentNode) wrapper.parentNode.removeChild(wrapper); - clearRendered(ctx, entry); - try { parseResult.dispose(); } catch { /* ignore */ } - meshes.delete(entry); - meshByElement.delete(wrapper); - recomputeAutoCenter(); - const prevGround = ctx.shadowSvgState.currentGroundCssZ; - recomputeShadowGround(ctx); - if ((entry.castShadow || entry.receiveShadow) && ctx.shadowSvgState.currentGroundCssZ === prevGround) { - invalidateShadowLightCache(ctx); - emitSceneShadows(ctx); - } - }, - rebakeAtlas() { - // Advance the baked rotation to match the current live rotation. - // The atlas baker will use this to inverse-rotate the world light - // into the mesh's local frame so Lambert shading stays correct. - entry.bakedRotation = (transform.rotation ? [...transform.rotation] : [0, 0, 0]) as Vec3; - // Compute the local-frame light direction by inverse-rotating the - // world-space directional light through the baked rotation. When no - // directional light is configured, pass `undefined` so baked leaves - // settle to ambient-only shading instead of synthesizing a default sun. - const worldDir = currentOptions.directionalLight?.direction; - const localLightDir = worldDir - ? inverseRotateVec3(worldDir as Vec3, entry.bakedRotation) - : undefined; - // Serialised in-place swap: only one rebake runs at a time and - // intermediate slider ticks just update the queued target. Avoids - // both blank-flash AND the out-of-order bitmap swaps that look - // like flicker when many rebakes finish at slightly different - // moments. - requestRebakeAtlas(ctx, entry, renderEntry, localLightDir); - }, - whenTexturesReady() { return entry.textureReadyPromise; }, - getPosition() { return transform.position; }, - getRotation() { return transform.rotation; }, - getScale() { return transform.scale; }, - getPolygons() { return handle.polygons; }, - }; + const meshDeps = { meshByElement, recomputeAutoCenter }; - entry.handle = handle; - entryRef = entry; - if (!isSceneRootWrapper) meshByElement.set(wrapper, entry); - meshes.add(entry); - renderEntry(entry); - applyMeshLightVarOverride(ctx, entry, transform.rotation); - recomputeAutoCenter(); - recomputeShadowGround(ctx); - return handle; + function add(parseResult: ParseResult, transformIn: PolyMeshTransform = {}): PolyMeshHandle { + return addSceneMeshEntry(ctx, meshDeps, parseResult, transformIn); } function setOptions(partial: Partial>): void { @@ -1182,21 +202,14 @@ export function createPolyScene( const prevPointLights = currentOptions.pointLights; const normalizedPartial = normalizeSceneOptions(partial); currentOptions = { ...currentOptions, ...normalizedPartial }; - // Keep the SceneContext's options ref pointing to the latest snapshot so - // extracted scene/* helpers see the new value on their next read. ctx.options.current = currentOptions; applySceneStyle(sceneEl, currentOptions); const nextAutoCenter = !!currentOptions.autoCenter; - // Re-evaluate per-mesh light overrides when lighting settings change — - // textureLighting or directionalLight may have changed. + for (const entry of meshes) { applyMeshLightVarOverride(ctx, entry, entry.handle.transform.rotation); } - // `strategies` controls which leaf tags the renderer emits. A change - // means we have to re-render every mesh against the new constraint. - // Skip the re-render when the value didn't actually change so callers - // that pass the same strategies on every tick (bundled with camera - // updates) don't blow up the atlas every frame. + const strategiesChanged = hasOwn("strategies") && !strategiesEqual(currentOptions.strategies, prevStrategies); const seamBleedChanged = hasOwn("seamBleed") && @@ -1211,14 +224,11 @@ export function createPolyScene( normalizedPartial.textureBackend !== prevTextureBackend; const textureProjectionChanged = hasOwn("textureProjection") && normalizedPartial.textureProjection !== prevTextureProjection; - // Point lights are baked per-face into the atlas/solid colors, so any - // change (added/removed/moved/recolored) requires a re-bake of every - // mesh. Compare a compact signature so passing the same array each tick - // (e.g. bundled with camera updates) doesn't re-bake needlessly. const pointLightSig = (pls: PolyPointLight[] | undefined): string => (pls ?? []).map((p) => `${p.position.join(",")}|${p.color ?? ""}|${p.intensity ?? 1}|${p.castShadow ? 1 : 0}`).join(";"); const pointLightsChanged = hasOwn("pointLights") && pointLightSig(currentOptions.pointLights) !== pointLightSig(prevPointLights); + const fullRenderTriggered = strategiesChanged || seamBleedChanged || @@ -1234,6 +244,7 @@ export function createPolyScene( if (prevAutoCenter !== nextAutoCenter || prevAutoCenterSource !== currentOptions.autoCenterSource) { recomputeAutoCenter(); } + const textureLightingChanged = hasOwn("textureLighting") && prevTextureLighting !== currentOptions.textureLighting; const nextDirLight = currentOptions.directionalLight; @@ -1253,13 +264,14 @@ export function createPolyScene( clearTimeout(ctx.animationShadowTrailingTimer); ctx.animationShadowTrailingTimer = null; } - const shadowAppearanceChanged = hasOwn("shadow") - && !shadowOptsEqual( + const shadowAppearanceChanged = hasOwn("shadow") && + !shadowOptsEqual( prevShadow ? { ...prevShadow, followAnimation: false } : undefined, nextShadow ? { ...nextShadow, followAnimation: false } : undefined, ); const shadowReemitNeeded = directionalChanged || shadowAppearanceChanged || pointLightsChanged || (ambientChanged && currentOptions.bakedLightPolicy === "auto"); + if ( !textureLightingChanged && currentOptions.bakedLightPolicy === "auto" && @@ -1273,17 +285,6 @@ export function createPolyScene( } } if (textureLightingChanged) { - // Every mesh needs a full re-render to swap baked/dynamic leaf - // emission. Baked leaves carry inline `color: rgb(...)`; dynamic - // leaves carry inline `--pnx/y/z` and rely on a wrapper-level - // `--psr/g/b` (set via applySolidPaintVars) for the CSS calc(). - // Without re-rendering, switching baked→dynamic leaves stale inline - // `color` on most leaves (looks fine) but any leaf that gets even - // a partial restyle (e.g. plan recomputation downstream) loses its - // inline color and falls through to the CSS calc reading the - // @property defaults — rendering WHITE polygons on the model. - // Skip when texture-affecting option changes already triggered a - // re-render above. if (!fullRenderTriggered) { for (const entry of meshes) renderEntry(entry); } @@ -1291,15 +292,10 @@ export function createPolyScene( invalidateShadowLightCache(ctx); emitSceneShadows(ctx); } else if (shadowReemitNeeded) { - // The emit short-circuit key only discriminates by light DIRECTION, so a - // direction change self-busts, but shadow-appearance and directional - // intensity/color changes must bust the cache explicitly or - // emitSceneShadows would no-op. if (shadowAppearanceChanged || directionalChanged) invalidateShadowLightCache(ctx); - // A light-DIRECTION or point-light move is "motion" → eligible for the - // progressive drag-definition pass. Shadow-appearance edits (opacity, - // definition, dragDefinition) render at full definition immediately. - emitSceneShadows(ctx, undefined, { progressive: (directionalChanged || pointLightsChanged) && !shadowAppearanceChanged }); + emitSceneShadows(ctx, undefined, { + progressive: (directionalChanged || pointLightsChanged) && !shadowAppearanceChanged, + }); } if (shadowAppearanceChanged && currentOptions.shadow?.lift !== prevShadow?.lift) { recomputeShadowGround(ctx); @@ -1311,12 +307,9 @@ export function createPolyScene( } function applyCamera(): void { - applyCameraStyle(cameraEl, currentOptions); + applyCameraStyle(cameraEl); applySceneCameraTransform(sceneEl); for (const entry of meshes) syncMountedRenderedForCameraChange(ctx, entry); - // Receiver shadows are camera-dependent (face culling + crease bleed), so - // they must not ride an orbit frozen. Signature-gated: this costs one - // per-plane facing sweep unless the camera crossed a visibility boundary. syncShadowsForCameraChange(ctx); } @@ -1360,15 +353,11 @@ export function createPolyScene( clearTimeout(ctx.animationShadowTrailingTimer); ctx.animationShadowTrailingTimer = null; } - // Dispose all meshes (revokes blob URLs) before removing the scene. - // Snapshot first since dispose() mutates the set. const snapshot = Array.from(meshes); for (const m of snapshot) { try { m.handle.dispose(); } catch { /* ignore */ } } clearAllSceneShadows(ctx); - // Remove the camera wrapper only when we created it (adopted elements are - // owned by the caller, e.g. React/Vue / ). if (!adoptedElements && cameraEl.parentNode) cameraEl.parentNode.removeChild(cameraEl); } diff --git a/packages/polycss/src/api/createSelect.ts b/packages/polycss/src/api/createSelect.ts index 5ea87cde9..ada2a31fb 100644 --- a/packages/polycss/src/api/createSelect.ts +++ b/packages/polycss/src/api/createSelect.ts @@ -1,33 +1,21 @@ /** * createSelect — additive selection layer for vanilla PolyCSS scenes. - * Mirrors the React `. - clear(); - } else { - set([handle]); - } - }; - scene.host.addEventListener("click", onClick); + const detach = controller.attach(scene.host); function destroy(): void { - scene.host.removeEventListener("click", onClick); + detach(); subscribers.clear(); } return { - get selected() { return selected; }, - set, - add, - remove, - toggle, - clear, - has, + get selected() { + return controller.selected; + }, + set: controller.set, + add: controller.add, + remove: controller.remove, + toggle: controller.toggle, + clear: controller.clear, + has: controller.has, destroy, }; } diff --git a/packages/polycss/src/api/createTransformControls.ts b/packages/polycss/src/api/createTransformControls.ts index 92836a777..64ac1795c 100644 --- a/packages/polycss/src/api/createTransformControls.ts +++ b/packages/polycss/src/api/createTransformControls.ts @@ -1,77 +1,49 @@ /** - * createTransformControls — vanilla equivalent of ``. - * Builds the same six-arrow translate gizmo / three-ring rotate gizmo - * around an attached mesh and emits `objectChange` events as the user - * drags. Mirrors the React API surface (mode, size, snap, draggingChanged - * event) and uses the same shared geometry helpers in `@layoutit/polycss-core` - * (`arrowPolygons`, `ringQuadPolygons`). - * - * Usage: - * const tc = createTransformControls(scene, { - * mode: "translate", - * // Events are constructor options — the handle has no `on(...)`. - * onObjectChange: ({ position, rotation }) => { - * // Apply to your own state if you need to keep it in sync; the - * // gizmo already calls target.setTransform internally. - * }, - * }); - * tc.attach(meshHandle); - * tc.setMode("rotate"); - * tc.detach(); - * tc.destroy(); + * createTransformControls — vanilla equivalent of ``. + * Builds the six-arrow + three-plane translate gizmo or three-ring rotate gizmo + * around an attached mesh and emits `objectChange` events as the user drags. + * Shares drag math and geometry builders with React/Vue via `gizmoEngine.ts`. */ 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_HALF_THICKNESS_RATIO, - RING_RADIUS_RATIO, RING_SPECS, SCENE_TILE_SIZE, - SCREEN_AXIS_DEAD_ZONE_SQ, - SHAFT_HALF_THICKNESS_RATIO, WORLD_AXIS_FOR_CSS, - arrowPolygons, eulerXYZFromQuat, gizmoLengthForMesh, - isAxisBackFacing, - planePolygons, quatFromAxisAngle, quatFromEulerXYZ, quatMultiply, - ringQuadPolygons, rotateVec3, - screenPlaneDet, - snap, - solveAxisDragDelta, - solvePlaneDragDeltas, - unwrapAngleDelta, - withAlpha, } from "@layoutit/polycss-core"; import type { Polygon, Vec3 } from "@layoutit/polycss-core"; import type { PolyMeshHandle, PolySceneHandle } from "./createPolyScene"; import { pointInMeshElement } from "./meshHitTest"; +import { + RING_MASK_INNER_RATIO, + RING_MASK_OUTER_RATIO, + buildArrowGizmoPolygons, + buildPlaneGizmoPolygons, + buildRingGizmoPolygons, + gizmoAlphaForKey, + isArrowSpecVisible, + isPlaneSpecVisible, + isRingSpecVisible, + startAxisDrag, + startPlaneDrag, + startRingDrag, + type GizmoMode, +} from "./controls/gizmoEngine"; -type Mode = "translate" | "rotate"; - -/** Compute the bbox center of a mesh's polygons in WORLD units, world-axis - * order (`+X right, +Y forward, +Z up`). Added to `target.transform.position` - * (also world units, world-axis) to place the gizmo at the mesh's visible - * centroid. PolyMesh's buildMeshTransform applies the world→CSS axis swap + - * ×BASE_TILE on the resulting position, so consumers stay in world units. - * Collapses to (0,0,0) when the mesh is already centered (e.g. when - * PolyMesh autoCenter or `loadMesh(..., { center: true })` was used). */ function bboxCenterWorld(polygons: Polygon[]): Vec3 { if (polygons.length === 0) return [0, 0, 0]; - let minX = Infinity, minY = Infinity, minZ = Infinity; - let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity; + let minX = Infinity; + let minY = Infinity; + let minZ = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + let maxZ = -Infinity; for (const poly of polygons) { for (const v of poly.vertices) { if (v[0] < minX) minX = v[0]; @@ -83,11 +55,7 @@ function bboxCenterWorld(polygons: Polygon[]): Vec3 { } } if (!Number.isFinite(minX)) return [0, 0, 0]; - return [ - (minX + maxX) / 2, - (minY + maxY) / 2, - (minZ + maxZ) / 2, - ]; + return [(minX + maxX) / 2, (minY + maxY) / 2, (minZ + maxZ) / 2]; } export interface PolyTransformControlsObjectChangeEvent { @@ -98,7 +66,7 @@ export interface PolyTransformControlsObjectChangeEvent { export interface PolyTransformControlsOptions { /** Drag mode. "translate" → axial arrows, "rotate" → axial rings. */ - mode?: Mode; + mode?: GizmoMode; /** Multiplier on gizmo size (shaft length / ring radius). Default 1. */ size?: number; /** Snap step (CSS pixels) for translate-mode. */ @@ -119,9 +87,7 @@ export interface PolyTransformControlsOptions { applyTransform?: boolean; /** Fires for any transform change. Argument-less, mirrors three.js. */ onChange?: () => void; - /** Fires with the new transform during drag. The gizmo also calls - * `target.setTransform` internally; this callback lets parent code - * mirror the change into its own state. */ + /** Fires with the new transform during drag. */ onObjectChange?: (event: PolyTransformControlsObjectChangeEvent) => void; /** Fires once on drag start. */ onMouseDown?: () => void; @@ -132,396 +98,80 @@ export interface PolyTransformControlsOptions { } export interface PolyTransformControlsHandle { - /** Bind to a mesh — gizmo follows the mesh's transform. Pass `null` - * to detach. Calling `attach` again with a new target swaps the - * binding without rebuilding the gizmo geometry. */ + /** Bind to a mesh — gizmo follows the mesh's transform. Pass `null` to detach. */ attach(mesh: PolyMeshHandle | null): void; /** Equivalent to `attach(null)`. */ detach(): void; - /** Switch between translate and rotate. Tears down the old gizmo - * and rebuilds the new one. */ - setMode(mode: Mode): void; - /** Re-read the target's transform and reposition the gizmo. Call - * after mutating `target.setTransform` externally if you want the - * gizmo to follow. */ + /** Switch between translate and rotate. */ + setMode(mode: GizmoMode): void; + /** Re-read the target's transform and reposition the gizmo. */ update(): void; - /** Update options (size, snaps, visibility, callbacks, applyTransform) - * in place without tearing down the controller. Rebuilds gizmo geometry - * only when mode, size, or axis visibility changed. */ + /** Update options in place without tearing down the controller. */ setOptions(partial: Partial): void; /** Remove all listeners + gizmo meshes from the scene. Idempotent. */ destroy(): void; } -interface DragOptions { - cssAxis: 0 | 1 | 2; - sign: 1 | -1; - shaftLengthCss: number; - wrapper: HTMLElement; - target: PolyMeshHandle; - 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. Matches React's - * `startAxisDrag`. */ -function startAxisDrag(opts: DragOptions): void { - const { - cssAxis, - sign, - shaftLengthCss, - wrapper, - target: _target, - startClientX, - startClientY, - translationSnap, - onAxisDelta, - onMouseDown, - onMouseUp, - onDraggingChanged, - } = opts; - - const probeDistance = shaftLengthCss; - const axisVec: Vec3 = [0, 0, 0]; - axisVec[cssAxis] = sign; - 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] * probeDistance}px, ${axisVec[1] * probeDistance}px, ${axisVec[2] * probeDistance}px)`; - wrapper.appendChild(probe); - const wRect = wrapper.getBoundingClientRect(); - const pRect = probe.getBoundingClientRect(); - wrapper.removeChild(probe); - const screenAxisX = (pRect.left - wRect.left) / probeDistance; - const screenAxisY = (pRect.top - wRect.top) / probeDistance; - const screenAxisLenSq = screenAxisX * screenAxisX + screenAxisY * screenAxisY; - if (screenAxisLenSq < SCREEN_AXIS_DEAD_ZONE_SQ) return; - - onMouseDown?.(); - onDraggingChanged?.(true); - - const handleMove = (ev: PointerEvent): void => { - const dx = ev.clientX - startClientX; - const dy = ev.clientY - startClientY; - let t = solveAxisDragDelta(dx, dy, screenAxisX, screenAxisY); - t = snap(t, translationSnap); - onAxisDelta(t, axisVec); - }; - const handleUp = (): void => { - window.removeEventListener("pointermove", handleMove); - window.removeEventListener("pointerup", handleUp); - window.removeEventListener("pointercancel", handleUp); - // Swallow the click that follows pointerup so a release-over-mesh - // doesn't toggle selection in createSelect. - const swallow = (e: Event): void => { - e.stopPropagation(); - e.stopImmediatePropagation(); - }; - window.addEventListener("click", swallow, { capture: true, once: true }); - setTimeout(() => window.removeEventListener("click", swallow, true), 0); - onMouseUp?.(); - onDraggingChanged?.(false); - }; - window.addEventListener("pointermove", handleMove); - window.addEventListener("pointerup", handleUp); - window.addEventListener("pointercancel", handleUp); -} - -interface PlaneDragOptions { - axisA: 0 | 1 | 2; - axisB: 0 | 1 | 2; - probeDistanceCss: number; - wrapper: HTMLElement; - target: PolyMeshHandle; - 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 world axes) and solve a 2x2 system for the planar motion. Mirror of - * the single-axis projection in `startAxisDrag`, extended to two axes. */ -function startPlaneDrag(opts: PlaneDragOptions): void { - const { - axisA, - axisB, - probeDistanceCss, - wrapper, - startClientX, - startClientY, - translationSnap, - onPlaneDelta, - onMouseDown, - onMouseUp, - onDraggingChanged, - } = opts; - - // Probe both in-plane axes to measure their screen projections. Same - // technique as startAxisDrag: place a 0×0 element at `axis * dist`, read - // its bounding rect against the wrapper's, divide by `dist` to get the - // unit screen vector for that world axis. - const axisAVec: Vec3 = [0, 0, 0]; axisAVec[axisA] = 1; - const axisBVec: Vec3 = [0, 0, 0]; axisBVec[axisB] = 1; - function probe(axisVec: Vec3): { x: number; y: number } { - const el = wrapper.ownerDocument!.createElement("div"); - el.style.position = "absolute"; - el.style.left = "0"; - el.style.top = "0"; - el.style.width = "0"; - el.style.height = "0"; - el.style.transform = `translate3d(${axisVec[0] * probeDistanceCss}px, ${axisVec[1] * probeDistanceCss}px, ${axisVec[2] * probeDistanceCss}px)`; - wrapper.appendChild(el); - const wR = wrapper.getBoundingClientRect(); - const pR = el.getBoundingClientRect(); - wrapper.removeChild(el); - return { - x: (pR.left - wR.left) / probeDistanceCss, - y: (pR.top - wR.top) / probeDistanceCss, - }; - } - const pA = probe(axisAVec); - const pB = probe(axisBVec); - const det = screenPlaneDet(pA, pB); - if (Math.abs(det) < SCREEN_AXIS_DEAD_ZONE_SQ) return; // plane edge-on to camera - - onMouseDown?.(); - onDraggingChanged?.(true); - - const handleMove = (ev: PointerEvent): void => { - 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 => { - window.removeEventListener("pointermove", handleMove); - window.removeEventListener("pointerup", handleUp); - window.removeEventListener("pointercancel", handleUp); - const swallow = (e: Event): void => { - e.stopPropagation(); - e.stopImmediatePropagation(); - }; - window.addEventListener("click", swallow, { capture: true, once: true }); - setTimeout(() => window.removeEventListener("click", swallow, true), 0); - onMouseUp?.(); - onDraggingChanged?.(false); - }; - window.addEventListener("pointermove", handleMove); - window.addEventListener("pointerup", handleUp); - window.addEventListener("pointercancel", handleUp); -} - -interface RingDragOptions { - cssAxis: 0 | 1 | 2; - wrapper: HTMLElement; - target: PolyMeshHandle; - startClientX: number; - startClientY: number; - rotationSnap: number | null; - onAngleDelta(degrees: number): void; - onMouseDown?: () => void; - onMouseUp?: () => void; - onDraggingChanged?: (dragging: boolean) => void; -} - -/** Track pointer angle around the gizmo center, accumulate the - * unwrapped delta, and feed it back as degrees of rotation. Matches - * React's `startRingDrag`. */ -function startRingDrag(opts: RingDragOptions): void { - const { - cssAxis: _cssAxis, - wrapper, - target: _target, - startClientX, - startClientY, - rotationSnap, - onAngleDelta, - onMouseDown, - onMouseUp, - onDraggingChanged, - } = 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); - - const handleMove = (ev: PointerEvent): void => { - const a = Math.atan2(ev.clientY - centerY, ev.clientX - centerX); - cumulative += unwrapAngleDelta(a, lastAngle); - lastAngle = a; - let degrees = (cumulative * 180) / Math.PI; - degrees = snap(degrees, rotationSnap); - onAngleDelta(degrees); - }; - const handleUp = (): void => { - window.removeEventListener("pointermove", handleMove); - window.removeEventListener("pointerup", handleUp); - window.removeEventListener("pointercancel", handleUp); - const swallow = (e: Event): void => { - e.stopPropagation(); - e.stopImmediatePropagation(); - }; - window.addEventListener("click", swallow, { capture: true, once: true }); - setTimeout(() => window.removeEventListener("click", swallow, true), 0); - onMouseUp?.(); - onDraggingChanged?.(false); - }; - window.addEventListener("pointermove", handleMove); - window.addEventListener("pointerup", handleUp); - window.addEventListener("pointercancel", handleUp); -} +type GizmoSpec = + | { kind: "arrow"; key: string; cssAxis: 0 | 1 | 2; sign: 1 | -1; color: string } + | { kind: "ring"; key: string; cssAxis: 0 | 1 | 2; color: string } + | { kind: "plane"; key: string; perpAxis: 0 | 1 | 2; axisA: 0 | 1 | 2; axisB: 0 | 1 | 2; color: string }; export function createTransformControls( scene: PolySceneHandle, options: PolyTransformControlsOptions = {}, ): PolyTransformControlsHandle { let target: PolyMeshHandle | null = null; - let mode: Mode = options.mode ?? "translate"; + let mode: GizmoMode = options.mode ?? "translate"; let size = options.size ?? 1; const opts: PolyTransformControlsOptions = { ...options }; - // No standalone wrapper element. The earlier draft appended a - // wrapper to `scene.host`, but that lives OUTSIDE the camera- - // transformed scene root (`.polycss-camera` carries the scale + - // rotateX/rotateY), so the gizmo polygons rendered in screen space - // and ignored the camera. Going through `scene.add` for each gizmo - // mesh puts it inside the centerWrapper (camera-space), which is - // exactly the same coordinate frame the user mesh lives in. Each - // gizmo mesh is positioned at `target.transform.position` via - // setTransform — that's the gizmo origin. - - // Per-key tracking. Each gizmo arrow / ring / plane is a polycss - // PolyMeshHandle added to the scene, then re-parented under our wrapper. - type GizmoSpec = - | { kind: "arrow"; key: string; cssAxis: 0 | 1 | 2; sign: 1 | -1; color: string } - | { kind: "ring"; key: string; cssAxis: 0 | 1 | 2; color: string } - | { kind: "plane"; key: string; perpAxis: 0 | 1 | 2; axisA: 0 | 1 | 2; axisB: 0 | 1 | 2; color: string }; type GizmoMesh = { handle: PolyMeshHandle; spec: GizmoSpec }; const gizmos = new Map(); let hoveredKey: string | null = null; let draggingKey: string | null = null; - // Offset added to `target.transform.position` to place the gizmo at - // the mesh's visible center under scene-level autoCenter. Cached on - // attach because it depends only on the target's polygon bbox. let centerOffset: Vec3 = [0, 0, 0]; + let dragStartPosition: Vec3 | null = null; + let dragStartRotation: Vec3 | null = null; function gizmoPosition(): Vec3 { if (!target) return [0, 0, 0]; const t = target.transform.position ?? ([0, 0, 0] as Vec3); const r = target.transform.rotation ?? ([0, 0, 0] as Vec3); - const s = typeof target.transform.scale === "number" - ? target.transform.scale - : (target.transform.scale?.[0] ?? 1); - // Visible mesh center under the post-parity wrapper transform - // `T · R · S · p`: at p = bboxCenter (mesh-local), visible center - // = T + scale * R(rotation) * bboxCenter. Apply current rotation so - // the gizmo follows the mesh while it spins — without this, the - // rotation handler's pivot compensation slides position around to - // keep the visible center fixed and the gizmo (placed at - // position + centerOffset) drifts off-axis. + const s = + typeof target.transform.scale === "number" + ? target.transform.scale + : (target.transform.scale?.[0] ?? 1); const rc = rotateVec3(centerOffset, r[0], r[1], r[2]); return [t[0] + s * rc[0], t[1] + s * rc[1], t[2] + s * rc[2]]; } function alphaFor(key: string): number { - if (draggingKey === key) return ALPHA_DRAGGING; - if (hoveredKey === key) return ALPHA_HOVER; - return ALPHA_IDLE; - } - - function rebuildGizmoColors(): void { - // Re-emit each arrow/ring's polygons with the updated alpha. Cheap - // — geometry hasn't changed, just the per-polygon color string. - for (const [key, gm] of gizmos) { - const polys = buildPolygonsFor(gm.spec, alphaFor(key)); - gm.handle.setPolygons(polys, { recomputeAutoCenter: false }); - } + return gizmoAlphaForKey(key, hoveredKey, draggingKey); } function buildPolygonsFor(spec: GizmoSpec, alpha: number): Polygon[] { - const baseLength = gizmoLengthForMesh(target?.polygons ?? []); - const shaftLengthCss = baseLength * size; + const shaftLengthCss = gizmoLengthForMesh(target?.polygons ?? []) * size; const lengthWorld = shaftLengthCss / SCENE_TILE_SIZE; - const color = withAlpha(spec.color, alpha); + const cameraState = scene.camera.state; + const rotX = cameraState.rotX ?? 65; + const rotY = cameraState.rotY ?? 45; + if (spec.kind === "arrow") { - // Strip the shaft for back-facing arrows so the visible-only-from- - // outside silhouette stays clean. Both halves of a pair otherwise - // share the same shaft volume at the gizmo origin. - const cameraState = scene.camera.state; - const backFacing = isAxisBackFacing( - spec.cssAxis, - spec.sign, - cameraState.rotX ?? 65, - cameraState.rotY ?? 45, - ); - 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, - shaft: !backFacing, - }); + return buildArrowGizmoPolygons(spec, lengthWorld, alpha, rotX, rotY); } if (spec.kind === "plane") { - // Place the quad in the camera-facing octant: for each in-plane axis, - // flip the offset sign if the +axis is back-facing. planePolygons - // works in WORLD axes (a = (perp+1)%3, b = (perp+2)%3); since - // WORLD_AXIS_FOR_CSS is involutive, the CSS axis we test for back- - // facing is just WORLD_AXIS_FOR_CSS[worldA / worldB]. - const cameraState = scene.camera.state; - const rotX = cameraState.rotX ?? 65; - const rotY = cameraState.rotY ?? 45; - 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, + return buildPlaneGizmoPolygons(spec, lengthWorld, alpha, rotX, rotY); + } + return buildRingGizmoPolygons(spec, shaftLengthCss, alpha); + } + + function rebuildGizmoColors(): void { + for (const [key, gm] of gizmos) { + gm.handle.setPolygons(buildPolygonsFor(gm.spec, alphaFor(key)), { + recomputeAutoCenter: false, }); } - // ring — single square quad masked to a donut via CSS (see - // .polycss-transform-ring rule in styles.ts). One DOM node per ring - // instead of N segment quads. Quad outer radius is sized by - // RING_QUAD_OUTER_RATIO so the hit footprint stays generous even when - // the visible band (driven by RING_HALF_THICKNESS_RATIO) is thin. - 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, - }); } function classPrefixFor(spec: GizmoSpec): string { @@ -530,63 +180,44 @@ export function createTransformControls( return "polycss-transform-ring"; } - /** Resolve the active spec list for the current mode. Translate mode mixes - * the 6 axis arrows with the 3 planar handles; rotate mode just rings. */ function activeSpecs(): GizmoSpec[] { if (mode === "translate") { - const arrows: GizmoSpec[] = ARROW_SPECS.map((a) => ({ - kind: "arrow", - key: a.key, - cssAxis: a.cssAxis, - sign: a.sign, - color: a.color, - })); - const planes: GizmoSpec[] = PLANE_SPECS.map((p) => ({ - kind: "plane", - key: p.key, - perpAxis: p.perpAxis, - axisA: p.axisA, - axisB: p.axisB, - color: p.color, - })); + const arrows: GizmoSpec[] = ARROW_SPECS.filter((a) => isArrowSpecVisible(a, opts)).map( + (a) => ({ kind: "arrow", key: a.key, cssAxis: a.cssAxis, sign: a.sign, color: a.color }), + ); + const planes: GizmoSpec[] = PLANE_SPECS.filter((p) => isPlaneSpecVisible(p, opts)).map( + (p) => ({ + kind: "plane", + key: p.key, + perpAxis: p.perpAxis, + axisA: p.axisA, + axisB: p.axisB, + color: p.color, + }), + ); return [...arrows, ...planes]; } - if (mode === "rotate") { - return RING_SPECS.map((r) => ({ kind: "ring", key: r.key, cssAxis: r.cssAxis, color: r.color })); - } - return []; + return RING_SPECS.filter((r) => isRingSpecVisible(r, opts)).map((r) => ({ + kind: "ring", + key: r.key, + cssAxis: r.cssAxis, + color: r.color, + })); + } + + function teardownGizmos(): void { + for (const { handle } of gizmos.values()) handle.remove(); + gizmos.clear(); + hoveredKey = null; + draggingKey = null; } function buildGizmos(): void { teardownGizmos(); if (!target) return; - const showByKey = { - x: opts.showX !== false, - y: opts.showY !== false, - z: opts.showZ !== false, - }; - function specVisible(spec: GizmoSpec): boolean { - if (spec.kind === "arrow") { - const userAxis = spec.key.replace("-", "")[0] as "x" | "y" | "z"; - return showByKey[userAxis]; - } - if (spec.kind === "ring") { - return showByKey[spec.key as "x" | "y" | "z"]; - } - // Plane handles need BOTH in-plane axes visible. - const aName = (["x", "y", "z"] as const)[spec.axisA]; - const bName = (["x", "y", "z"] as const)[spec.axisB]; - return showByKey[aName] && showByKey[bName]; - } const targetPos = gizmoPosition(); for (const spec of activeSpecs()) { - if (!specVisible(spec)) continue; const polys = buildPolygonsFor(spec, alphaFor(spec.key)); - // Each gizmo mesh is added directly to the scene at the target's - // position. scene.add appends to centerWrapper (the camera- - // transformed scene root), so the arrow inherits the scene's - // perspective + rotateX/rotateY/scale automatically — no - // separate wrapper needed. const handle = scene.add( { polygons: polys, objectUrls: [], warnings: [], dispose: () => {} }, { @@ -603,28 +234,13 @@ export function createTransformControls( `${classPrefix}--${spec.key}`, ); if (spec.kind === "ring") { - // Two CSS vars consumed by the .polycss-transform-ring mask: where - // the visible band STARTS and ENDS, both as a fraction of the quad - // edge (50%). The quad's outer radius is RING_QUAD_OUTER_RATIO · - // mid-radius, so we normalize the visible inner/outer edges - // (mid ± halfThickness) against the quad outer to get the mask - // positions inside the quad. - const innerRatio = (1 - RING_HALF_THICKNESS_RATIO) / RING_QUAD_OUTER_RATIO; - const outerRatio = (1 + RING_HALF_THICKNESS_RATIO) / RING_QUAD_OUTER_RATIO; - handle.element.style.setProperty("--ring-inner-ratio", `${innerRatio}`); - handle.element.style.setProperty("--ring-outer-ratio", `${outerRatio}`); + handle.element.style.setProperty("--ring-inner-ratio", `${RING_MASK_INNER_RATIO}`); + handle.element.style.setProperty("--ring-outer-ratio", `${RING_MASK_OUTER_RATIO}`); } gizmos.set(spec.key, { handle, spec }); } } - function teardownGizmos(): void { - for (const { handle } of gizmos.values()) handle.remove(); - gizmos.clear(); - hoveredKey = null; - draggingKey = null; - } - function syncGizmoPositions(): void { if (!target) return; const pos = gizmoPosition(); @@ -653,7 +269,7 @@ export function createTransformControls( attach(null); } - function setMode(m: Mode): void { + function setMode(m: GizmoMode): void { if (m === mode) return; mode = m; if (target) { @@ -662,92 +278,46 @@ export function createTransformControls( } } - function applyAxisDelta(spec: { cssAxis: 0 | 1 | 2 }, t: number, axisVec: Vec3): void { + function commitTransform(next: { position?: Vec3; rotation?: Vec3 }): void { if (!target) return; - // Snapshot at drag start lives in the closure passed to - // startAxisDrag — but applyAxisDelta is called per move with the - // raw cumulative `t`, so we need to anchor each application to - // the drag-start position, not the live (already-mutated) one. - // The dragStartPosition snapshot is captured in the pointerdown - // handler below. - if (!dragStartPosition) return; - // Translate the drag from CSS-pixel CSS-axis space (where the screen - // probe was measured) to world-unit world-axis space (where - // `transform.position` lives post-parity). t is CSS px along the - // visible arrow direction; divide by SCENE_TILE_SIZE for world units. - // axisVec encodes the ±sign at index cssAxis; the corresponding - // world axis is WORLD_AXIS_FOR_CSS[cssAxis]. - const sign = axisVec[spec.cssAxis]; - const worldAxis = WORLD_AXIS_FOR_CSS[spec.cssAxis]; - const worldStep = (t * sign) / SCENE_TILE_SIZE; - const next = dragStartPosition.slice() as Vec3; - next[worldAxis] = dragStartPosition[worldAxis] + worldStep; if (opts.applyTransform !== false) { - target.setTransform({ position: next }); + target.setTransform(next); syncGizmoPositions(); } - opts.onObjectChange?.({ object: target, position: next }); + opts.onObjectChange?.({ object: target, ...next }); opts.onChange?.(); } - let dragStartPosition: Vec3 | null = null; - - // Track the start-of-drag rotation snapshot so accumulated deltas - // are anchored to the rotation at pointerdown rather than the live - // (already-mutated) rotation each move. - let dragStartRotation: Vec3 | null = null; - // Pointerdown listener on the host. Same JS bbox hit-test the React - // version uses — reliable regardless of CSS pointer-events / border- - // shape clipping issues. const onPointerDown = (event: PointerEvent): void => { if (!target || opts.enabled === false) return; - const showByKey = { - x: opts.showX !== false, - y: opts.showY !== false, - z: opts.showZ !== false, - }; + if (mode === "translate") { - // Plane handles are hit-tested FIRST so they win when overlapping with - // the arrow shafts at the corner. + // Plane handles hit-tested first so they win at overlapping corners. for (const spec of PLANE_SPECS) { - const aName = (["x", "y", "z"] as const)[spec.axisA]; - const bName = (["x", "y", "z"] as const)[spec.axisB]; - if (!showByKey[aName] || !showByKey[bName]) continue; + if (!isPlaneSpecVisible(spec, opts)) continue; const gm = gizmos.get(spec.key); - if (!gm) continue; - if (!pointInMeshElement(gm.handle.element, event.clientX, event.clientY)) continue; + if (!gm || !pointInMeshElement(gm.handle.element, event.clientX, event.clientY)) continue; event.preventDefault(); event.stopPropagation(); draggingKey = spec.key; rebuildGizmoColors(); dragStartPosition = (target.transform.position ?? [0, 0, 0]).slice() as Vec3; - startPlaneDrag({ + const started = startPlaneDrag({ axisA: spec.axisA, axisB: spec.axisB, probeDistanceCss: gizmoLengthForMesh(target.polygons) * size, wrapper: gm.handle.element, - target, startClientX: event.clientX, startClientY: event.clientY, translationSnap: opts.translationSnap ?? null, onPlaneDelta: (tA, tB, aVec, bVec) => { - if (!target || !dragStartPosition) return; - // Same CSS→world translation as applyAxisDelta. aVec/bVec - // encode the ±sign at index axisA/axisB (CSS-axis order); - // the world axes to translate along are WORLD_AXIS_FOR_CSS. - const signA = aVec[spec.axisA]; - const signB = bVec[spec.axisB]; + if (!dragStartPosition) return; const worldAxisA = WORLD_AXIS_FOR_CSS[spec.axisA]; const worldAxisB = WORLD_AXIS_FOR_CSS[spec.axisB]; const next = dragStartPosition.slice() as Vec3; - next[worldAxisA] += (tA * signA) / SCENE_TILE_SIZE; - next[worldAxisB] += (tB * signB) / SCENE_TILE_SIZE; - if (opts.applyTransform !== false) { - target.setTransform({ position: next }); - syncGizmoPositions(); - } - opts.onObjectChange?.({ object: target, position: next }); - opts.onChange?.(); + next[worldAxisA] += (tA * aVec[spec.axisA]) / SCENE_TILE_SIZE; + next[worldAxisB] += (tB * bVec[spec.axisB]) / SCENE_TILE_SIZE; + commitTransform({ position: next }); }, onMouseDown: opts.onMouseDown, onMouseUp: opts.onMouseUp, @@ -760,37 +330,39 @@ export function createTransformControls( opts.onDraggingChanged?.(d); }, }); + if (!started) { + draggingKey = null; + dragStartPosition = null; + rebuildGizmoColors(); + } return; } + for (const spec of ARROW_SPECS) { - const userAxis = spec.key.replace("-", "")[0] as "x" | "y" | "z"; - if (!showByKey[userAxis]) continue; + if (!isArrowSpecVisible(spec, opts)) continue; const gm = gizmos.get(spec.key); - if (!gm) continue; - if (!pointInMeshElement(gm.handle.element, event.clientX, event.clientY)) continue; + if (!gm || !pointInMeshElement(gm.handle.element, event.clientX, event.clientY)) continue; event.preventDefault(); event.stopPropagation(); draggingKey = spec.key; rebuildGizmoColors(); - // Snapshot the position at drag start so each pointermove - // applies its cumulative `t` against the same anchor instead - // of compounding off the live (already-mutated) position. dragStartPosition = (target.transform.position ?? [0, 0, 0]).slice() as Vec3; - startAxisDrag({ + const started = startAxisDrag({ cssAxis: spec.cssAxis, sign: spec.sign, shaftLengthCss: gizmoLengthForMesh(target.polygons) * size, - // Use the arrow's own mesh wrapper as the probe target — - // it's positioned at target.position and lives in the same - // camera-transformed scene root as the polygons we're - // dragging, so probe-vs-wrapper bbox math gives px-per- - // scene-px directly. wrapper: gm.handle.element, - target, startClientX: event.clientX, startClientY: event.clientY, translationSnap: opts.translationSnap ?? null, - onAxisDelta: (t, axisVec) => applyAxisDelta(spec, t, axisVec), + onAxisDelta: (t, axisVec) => { + if (!dragStartPosition) return; + const worldAxis = WORLD_AXIS_FOR_CSS[spec.cssAxis]; + const next = dragStartPosition.slice() as Vec3; + next[worldAxis] = + dragStartPosition[worldAxis] + (t * axisVec[spec.cssAxis]) / SCENE_TILE_SIZE; + commitTransform({ position: next }); + }, onMouseDown: opts.onMouseDown, onMouseUp: opts.onMouseUp, onDraggingChanged: (d) => { @@ -802,115 +374,79 @@ export function createTransformControls( opts.onDraggingChanged?.(d); }, }); + if (!started) { + draggingKey = null; + dragStartPosition = null; + rebuildGizmoColors(); + } return; } - } else if (mode === "rotate") { - for (const spec of RING_SPECS) { - if (!showByKey[spec.key as "x" | "y" | "z"]) continue; - const gm = gizmos.get(spec.key); - if (!gm) continue; - // Plain bbox-containment hit-test. The donut mask is decoration; the - // entire ring quad bbox is clickable so the rings are easy to land on. - if (!pointInMeshElement(gm.handle.element, event.clientX, event.clientY)) continue; - event.preventDefault(); - event.stopPropagation(); - draggingKey = spec.key; - rebuildGizmoColors(); - dragStartRotation = (target.transform.rotation ?? [0, 0, 0]).slice() as Vec3; - // Snapshot the position too so the per-tick pivot compensation - // anchors to the drag-start state (otherwise compounding rounding - // drift across moves slowly slides the mesh off-pivot). - dragStartPosition = (target.transform.position ?? [0, 0, 0]).slice() as Vec3; - startRingDrag({ - cssAxis: spec.cssAxis, - wrapper: gm.handle.element, - target, - startClientX: event.clientX, - startClientY: event.clientY, - rotationSnap: opts.rotationSnap ?? null, - onAngleDelta: (degrees) => { - if (!target || !dragStartRotation || !dragStartPosition) return; - // Each ring rotates the mesh around the WORLD axis the ring - // visually wraps. Ring quads are built with axis = - // WORLD_AXIS_FOR_CSS[cssAxis] (see `buildPolygonsFor`), so the - // rotation axis here must match — otherwise the mesh spins - // around a different axis than the ring the user grabbed. - const worldAxis = WORLD_AXIS_FOR_CSS[spec.cssAxis]; - const axisVec: Vec3 = [0, 0, 0]; - axisVec[worldAxis] = 1; - // Negate the screen-derived angle: `startRingDrag` returns a - // CCW-in-screen-space delta, but the world↔CSS axis swap is a - // reflection (det -1) so the same screen direction maps to a - // CW world rotation around the ring's axis. Flip once globally - // rather than per-axis empirically. - const deltaRad = (-degrees * Math.PI) / 180; - const qStart = quatFromEulerXYZ(dragStartRotation); - const qDelta = quatFromAxisAngle(axisVec, deltaRad); - const nextRot = eulerXYZFromQuat(quatMultiply(qDelta, qStart)); - // Pivot the mesh around its visible bbox center, not its - // local origin. Post-parity `` pivots at - // (0,0,0) by design — for callers that haven't pre-centered - // their geometry (most loaders default to `{ center: "min" }`), - // raw rotation would swing the mesh around its bbox-min corner. - // We compensate by re-translating so the world-space point - // `position + scale * R * bboxCenter` stays put across the drag. - const scaleVal = typeof target.transform.scale === "number" + return; + } + + for (const spec of RING_SPECS) { + if (!isRingSpecVisible(spec, opts)) continue; + const gm = gizmos.get(spec.key); + if (!gm || !pointInMeshElement(gm.handle.element, event.clientX, event.clientY)) continue; + event.preventDefault(); + event.stopPropagation(); + draggingKey = spec.key; + rebuildGizmoColors(); + dragStartRotation = (target.transform.rotation ?? [0, 0, 0]).slice() as Vec3; + dragStartPosition = (target.transform.position ?? [0, 0, 0]).slice() as Vec3; + const worldAxis = WORLD_AXIS_FOR_CSS[spec.cssAxis]; + const axisVec: Vec3 = [0, 0, 0]; + axisVec[worldAxis] = 1; + const qStart = quatFromEulerXYZ(dragStartRotation); + startRingDrag({ + wrapper: gm.handle.element, + startClientX: event.clientX, + startClientY: event.clientY, + rotationSnap: opts.rotationSnap ?? null, + onAngleDelta: (degrees) => { + if (!target || !dragStartRotation || !dragStartPosition) return; + // Negate screen-derived angle: world↔CSS axis swap is a reflection (det -1). + const qDelta = quatFromAxisAngle(axisVec, (-degrees * Math.PI) / 180); + const nextRot = eulerXYZFromQuat(quatMultiply(qDelta, qStart)); + const scaleVal = + typeof target.transform.scale === "number" ? target.transform.scale : (target.transform.scale?.[0] ?? 1); - const startC = rotateVec3( - centerOffset, - dragStartRotation[0], - dragStartRotation[1], - dragStartRotation[2], - ); - const nextC = rotateVec3(centerOffset, nextRot[0], nextRot[1], nextRot[2]); - const nextPos: Vec3 = [ - dragStartPosition[0] + scaleVal * (startC[0] - nextC[0]), - dragStartPosition[1] + scaleVal * (startC[1] - nextC[1]), - dragStartPosition[2] + scaleVal * (startC[2] - nextC[2]), - ]; + const startC = rotateVec3( + centerOffset, + dragStartRotation[0], + dragStartRotation[1], + dragStartRotation[2], + ); + const nextC = rotateVec3(centerOffset, nextRot[0], nextRot[1], nextRot[2]); + const nextPos: Vec3 = [ + dragStartPosition[0] + scaleVal * (startC[0] - nextC[0]), + dragStartPosition[1] + scaleVal * (startC[1] - nextC[1]), + dragStartPosition[2] + scaleVal * (startC[2] - nextC[2]), + ]; + commitTransform({ rotation: nextRot, position: nextPos }); + }, + onMouseDown: opts.onMouseDown, + onMouseUp: opts.onMouseUp, + onDraggingChanged: (d) => { + if (!d) { + draggingKey = null; + dragStartRotation = null; + dragStartPosition = null; + rebuildGizmoColors(); if (opts.applyTransform !== false) { - target.setTransform({ rotation: nextRot, position: nextPos }); - syncGizmoPositions(); + target?.rebakeAtlas(); } - opts.onObjectChange?.({ object: target, rotation: nextRot, position: nextPos }); - opts.onChange?.(); - }, - onMouseDown: opts.onMouseDown, - onMouseUp: opts.onMouseUp, - onDraggingChanged: (d) => { - if (!d) { - draggingKey = null; - dragStartRotation = null; - dragStartPosition = null; - rebuildGizmoColors(); - // Rebake the atlas now that the rotation is committed. The - // mesh wrapper's CSS rotation has already been applied via - // setTransform; rebakeAtlas() inverse-rotates the world light - // into the mesh's new local frame and re-rasterizes the atlas - // so baked Lambert shading is correct for the new orientation. - if (opts.applyTransform !== false) { - target?.rebakeAtlas(); - } - } - opts.onDraggingChanged?.(d); - }, - }); - return; - } + } + opts.onDraggingChanged?.(d); + }, + }); + return; } }; - // Capture-phase so we fire BEFORE createPolyOrbitControls' bubble-phase - // pointerdown listener on the same host element. If the click hits - // a gizmo arrow / ring we call stopPropagation, which prevents - // the orbit/map controls from starting a camera-rotate gesture in parallel. - // If the click misses every gizmo, we don't stop — PolyControls - // gets the event during its bubble phase and rotates as usual. + // Capture-phase so gizmo hits beat bubble-phase orbit/map controls on the host. scene.host.addEventListener("pointerdown", onPointerDown, { capture: true }); - // Hover tracking — listen at the host and figure out which gizmo - // mesh (if any) is under the cursor. Cheaper than per-element - // listeners and works regardless of pointer-events quirks. const onPointerMove = (event: MouseEvent): void => { if (!target || draggingKey || opts.enabled === false) return; let next: string | null = null; diff --git a/packages/polycss/src/api/meshHitTest.ts b/packages/polycss/src/api/meshHitTest.ts index 7656658a6..ac916990b 100644 --- a/packages/polycss/src/api/meshHitTest.ts +++ b/packages/polycss/src/api/meshHitTest.ts @@ -33,3 +33,126 @@ export function findMeshUnderPoint( } return null; } + +export interface MeshElementRegistry { + registerMeshElement(el: HTMLElement, handle: THandle): void; + unregisterMeshElement(el: HTMLElement): void; + findPolyMeshHandle(el: Element | null): THandle | null; + findMeshUnderPoint( + clientX: number, + clientY: number, + filter?: (meshEl: HTMLElement) => boolean, + ): THandle | null; +} + +/** + * Create a WeakMap-backed DOM-element → mesh-handle registry with ancestor + * lookup and JS bounding-rect hit-test fallback. Shared by React and Vue. + */ +export function createMeshElementRegistry(): MeshElementRegistry { + const registry = new WeakMap(); + + function registerMeshElement(el: HTMLElement, handle: THandle): void { + registry.set(el, handle); + } + + function unregisterMeshElement(el: HTMLElement): void { + registry.delete(el); + } + + function findPolyMeshHandle(el: Element | null): THandle | null { + let cur: Element | null = el; + while (cur) { + if (cur instanceof HTMLElement) { + const h = registry.get(cur); + if (h) return h; + } + cur = cur.parentElement; + } + return null; + } + + function findRegisteredMeshUnderPoint( + clientX: number, + clientY: number, + filter?: (meshEl: HTMLElement) => boolean, + ): THandle | null { + if (typeof document === "undefined") return null; + const meshEls = Array.from( + document.querySelectorAll(".polycss-mesh"), + ) as HTMLElement[]; + for (const meshEl of meshEls) { + if (filter && !filter(meshEl)) continue; + const handle = findPolyMeshHandle(meshEl); + if (!handle) continue; + if (pointInMeshElement(meshEl, clientX, clientY)) return handle; + } + return null; + } + + return { + registerMeshElement, + unregisterMeshElement, + findPolyMeshHandle, + findMeshUnderPoint: findRegisteredMeshUnderPoint, + }; +} + +export interface SynthesizedPolyPointerEvent { + object: THandle; + eventObject: THandle; + intersections: Array<{ object: THandle }>; + pointer: { x: number; y: number }; + delta: number; + nativeEvent: E; + stopPropagation(): void; +} + +/** + * Build a r3f-shaped pointer/mouse/wheel event payload from native DOM inputs, + * using `document.elementsFromPoint`, camera viewport NDC, and pointerdown delta. + */ +export function buildPolyPointerEvent(opts: { + handle: THandle; + nativeEvent: E; + clientX: number; + clientY: number; + cameraEl: HTMLElement | null | undefined; + pointerDownAt: { x: number; y: number } | null; + resolveHandle: (el: Element | null) => THandle | null; +}): SynthesizedPolyPointerEvent { + const { handle, nativeEvent, clientX, clientY, cameraEl, pointerDownAt, resolveHandle } = opts; + const intersections: Array<{ object: THandle }> = []; + if (typeof document !== "undefined" && typeof document.elementsFromPoint === "function") { + const stacked = document.elementsFromPoint(clientX, clientY); + const seen = new Set(); + for (const el of stacked) { + const h = resolveHandle(el); + if (h && !seen.has(h)) { + seen.add(h); + intersections.push({ object: h }); + } + } + } + let nx = 0; + let ny = 0; + if (cameraEl) { + const r = cameraEl.getBoundingClientRect(); + if (r.width > 0 && r.height > 0) { + nx = ((clientX - r.left) / r.width) * 2 - 1; + ny = -(((clientY - r.top) / r.height) * 2 - 1); + } + } + const delta = pointerDownAt + ? Math.hypot(clientX - pointerDownAt.x, clientY - pointerDownAt.y) + : 0; + return { + object: intersections[0]?.object ?? handle, + eventObject: handle, + intersections, + pointer: { x: nx, y: ny }, + delta, + nativeEvent, + stopPropagation: () => nativeEvent.stopPropagation(), + }; +} diff --git a/packages/polycss/src/api/runtimeHelpers.test.ts b/packages/polycss/src/api/runtimeHelpers.test.ts new file mode 100644 index 000000000..4bffe9953 --- /dev/null +++ b/packages/polycss/src/api/runtimeHelpers.test.ts @@ -0,0 +1,567 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { CameraState, Polygon, Vec3 } from "@layoutit/polycss-core"; +import { + RING_MASK_INNER_RATIO, + RING_MASK_OUTER_RATIO, + attachDeclarativeGizmoFallback, + buildTransformGizmoEntries, + computeGizmoWrapperPositionCss, + startDeclarativeArrowDrag, + startDeclarativePlaneDrag, + startDeclarativeRingDrag, + type DeclarativeGizmoDragState, + type DeclarativeGizmoTarget, + type TransformGizmoCache, +} from "./controls/gizmoEngine"; +import { createSelectionController } from "./controls/selectionEngine"; +import { + applyCameraTransformDirect, + bindCameraStoreSync, + createLiveRuntimeCamera, + writeCameraSnapshotAttrs, +} from "./cameraSnapshotAttrs"; +import { + buildPolyPointerEvent, + createMeshElementRegistry, +} from "./meshHitTest"; +import { + clearOwnedDomNodes, + renderStandaloneMeshIntoWrapper, + restoreVoxelMeshClass, +} from "./standaloneMesh"; +import { + buildDirectMaterialLeafDescriptor, + buildFallbackLeafDescriptor, + buildPolyWrapperTransform, + cssPropToCamel, + isAxisAlignedRectUVs, + readElementDataAttrs, + readElementStyleRecord, + syncLeafBorderShapeStyle, +} from "../render/polyLeafDescriptor"; +import { computeTextureAtlasPlanPublic } from "../render/textureAtlas"; + +const QUAD: Polygon = { + vertices: [ + [0, 0, 0], + [1, 0, 0], + [1, 1, 0], + [0, 1, 0], + ], + color: "#ff0000", + uvs: [ + [0, 0], + [1, 0], + [1, 1], + [0, 1], + ], + data: { face: "top" }, + doubleSided: true, +}; + +afterEach(() => { + document.body.innerHTML = ""; + vi.restoreAllMocks(); +}); + +function withFakeLayout(cameraScale: number, fn: () => void): void { + const TRANSFORM_RE = /translate3d\(\s*(-?[\d.]+)px,\s*(-?[\d.]+)px,\s*(-?[\d.]+)px\s*\)/; + const orig = Element.prototype.getBoundingClientRect; + Element.prototype.getBoundingClientRect = function fakeRect(this: Element): DOMRect { + let x = 0; + let y = 0; + let cur: Element | null = this; + while (cur && cur instanceof HTMLElement) { + const t = cur.style.transform; + if (t) { + const m = TRANSFORM_RE.exec(t); + if (m) { + x += parseFloat(m[1]!) * cameraScale; + y += parseFloat(m[2]!) * cameraScale; + } + } + cur = cur.parentElement; + } + const w = this instanceof HTMLElement ? parseFloat(this.style.width || "0") || 0 : 0; + const h = this instanceof HTMLElement ? parseFloat(this.style.height || "0") || 0 : 0; + return { + left: x, + top: y, + right: x + w, + bottom: y + h, + width: w, + height: h, + x, + y, + toJSON() { + return this; + }, + } as DOMRect; + }; + try { + fn(); + } finally { + Element.prototype.getBoundingClientRect = orig; + } +} + +describe("polyLeafDescriptor", () => { + it("detects axis-aligned rect UVs and rejects non-rect UVs", () => { + expect( + isAxisAlignedRectUVs([ + [0, 0], + [0.5, 0], + [0.5, 1], + [0, 1], + ]), + ).toEqual({ u0: 0, u1: 0.5, v0: 0, v1: 1 }); + expect(isAxisAlignedRectUVs([[0, 0], [1, 0], [0, 1]])).toBeNull(); + expect( + isAxisAlignedRectUVs([ + [0, 0], + [0.5, 0], + [1, 1], + [0, 1], + ]), + ).toBeNull(); + }); + + it("converts CSS property names and reflects inline style & data attributes", () => { + expect(cssPropToCamel("--custom-var")).toBe("--custom-var"); + expect(cssPropToCamel("-webkit-mask-image")).toBe("WebkitMaskImage"); + expect(cssPropToCamel("background-color")).toBe("backgroundColor"); + + const el = document.createElement("i"); + el.style.backgroundColor = "red"; + el.style.setProperty("--shade", "0.5"); + el.setAttribute("data-poly-index", "3"); + el.setAttribute("id", "ignored"); + + expect(readElementStyleRecord(el, { camelCase: true })).toMatchObject({ + backgroundColor: "red", + "--shade": "0.5", + }); + expect(readElementStyleRecord(el)).toMatchObject({ + "background-color": "red", + "--shade": "0.5", + }); + expect(readElementDataAttrs(el)).toEqual({ "data-poly-index": "3" }); + }); + + it("builds direct-material and SSR fallback descriptors plus wrapper transforms", () => { + const plan = computeTextureAtlasPlanPublic(QUAD, 0, { tileSize: 50, layerElevation: 50 })!; + expect(plan).not.toBeNull(); + + const direct = buildDirectMaterialLeafDescriptor({ + plan, + material: { texture: "/sprite.png" }, + uvRect: { u0: 0, u1: 0.5, v0: 0, v1: 0.5 }, + className: " custom ", + pointerEvents: "none", + imageRendering: "pixelated", + }); + expect(direct.className).toBe("custom"); + expect(direct.style.backgroundImage).toBe("url(/sprite.png)"); + expect(direct.style.imageRendering).toBe("pixelated"); + expect(direct.style.pointerEvents).toBe("none"); + expect(direct.dataAttrs["data-face"]).toBe("top"); + expect(direct.dataAttrs["data-polycss-double-sided"]).toBe("true"); + + const solidFallback = buildFallbackLeafDescriptor({ + plan, + polygon: QUAD, + isTextured: false, + className: "ssr-leaf", + pointerEvents: "none", + }); + expect(solidFallback.tag).toBe("b"); + expect(solidFallback.style.backgroundColor).toBe(plan.shadedColor); + expect(solidFallback.style.pointerEvents).toBe("none"); + + const texFallback = buildFallbackLeafDescriptor({ + plan, + polygon: QUAD, + isTextured: true, + }); + expect(texFallback.tag).toBe("s"); + expect(texFallback.style.backgroundColor).toBeUndefined(); + + expect(buildPolyWrapperTransform({})).toBeUndefined(); + expect( + buildPolyWrapperTransform({ + position: [1, 2, 3], + scale: 2, + rotation: [10, 20, 30], + }), + ).toBe("translate3d(1px, 2px, 3px) scale3d(2, 2, 2) rotateX(10deg) rotateY(20deg) rotateZ(30deg)"); + expect(buildPolyWrapperTransform({ scale: [1, 2, 3] })).toBe("scale3d(1, 2, 3)"); + + const leaf = document.createElement("i"); + syncLeafBorderShapeStyle(leaf, "polygon(0 0, 100% 0, 0 100%)", "color: red;", "none", { + opacity: "0.5", + }); + expect(leaf.style.pointerEvents).toBe("none"); + expect(leaf.style.opacity).toBe("0.5"); + }); +}); + +describe("cameraSnapshotAttrs & camera store sync", () => { + it("creates a live runtime camera, writes snapshot attrs, and syncs store bidirectionally", () => { + let projection: "orthographic" | "perspective" = "perspective"; + let perspectiveStyle = "24000px"; + const cam = createLiveRuntimeCamera({ + zoom: 1.5, + rotX: 45, + rotY: 30, + initialProjection: projection, + initialPerspectiveStyle: perspectiveStyle, + getProjection: () => projection, + getPerspectiveStyle: () => perspectiveStyle, + }); + expect(cam.type).toBe("perspective"); + expect(cam.perspectiveStyle).toBe("24000px"); + + const cameraEl = document.createElement("div"); + const sceneEl = document.createElement("div"); + writeCameraSnapshotAttrs(cameraEl, cam, { applyPerspective: true }); + expect(cameraEl.dataset.polycssCameraProjection).toBe("perspective"); + expect(cameraEl.style.perspective).toBe("24000px"); + + const listeners = new Set<() => void>(); + let state: { cameraState: CameraState } = { cameraState: { ...cam.state } }; + const store = { + getState: () => state, + subscribe: (fn: () => void) => { + listeners.add(fn); + return () => listeners.delete(fn); + }, + updateCameraFromRef: vi.fn((c: { state: CameraState }) => { + state = { cameraState: { ...c.state } }; + }), + }; + const applyCamera = vi.fn(); + const unbind = bindCameraStoreSync(cam, store, () => ({ applyCamera }) as never); + + cam.update({ zoom: 2 }); + expect(store.updateCameraFromRef).toHaveBeenCalledTimes(1); + + state = { cameraState: { ...cam.state, rotY: 90 } }; + for (const fn of listeners) fn(); + expect(cam.state.rotY).toBe(90); + expect(applyCamera).toHaveBeenCalledTimes(1); + + applyCameraTransformDirect({ + runtimeScene: null, + sceneEl, + cameraEl, + handle: cam, + autoCenterOffset: [0, 0, 0], + projection, + perspectiveStyle, + }); + expect(sceneEl.style.transform).toContain("rotate(90deg)"); + + applyCameraTransformDirect({ + runtimeScene: { applyCamera } as never, + sceneEl, + cameraEl, + handle: cam, + autoCenterOffset: [0, 0, 0], + projection, + perspectiveStyle, + }); + expect(applyCamera).toHaveBeenCalledTimes(2); + unbind(); + }); +}); + +describe("meshHitTest registry, pointer events, and standaloneMesh", () => { + it("registers meshes, resolves hit-test fallback, and builds pointer events", () => { + type FakeHandle = { id: string; element: HTMLElement }; + const reg = createMeshElementRegistry(); + const meshEl = document.createElement("div"); + meshEl.className = "polycss-mesh"; + const leaf = document.createElement("b"); + leaf.getBoundingClientRect = () => + ({ left: 10, top: 10, right: 60, bottom: 60, width: 50, height: 50, x: 10, y: 10, toJSON() { return this; } }) as DOMRect; + meshEl.appendChild(leaf); + document.body.appendChild(meshEl); + + const handle: FakeHandle = { id: "m1", element: meshEl }; + reg.registerMeshElement(meshEl, handle); + expect(reg.findPolyMeshHandle(leaf)).toBe(handle); + expect(reg.findMeshUnderPoint(25, 25)).toBe(handle); + expect(reg.findMeshUnderPoint(25, 25, () => false)).toBeNull(); + + const camEl = document.createElement("div"); + camEl.getBoundingClientRect = () => + ({ left: 0, top: 0, right: 200, bottom: 100, width: 200, height: 100, x: 0, y: 0, toJSON() { return this; } }) as DOMRect; + const nativeEv = new MouseEvent("click"); + const spyStop = vi.spyOn(nativeEv, "stopPropagation"); + const polyEv = buildPolyPointerEvent({ + handle, + nativeEvent: nativeEv, + clientX: 100, + clientY: 50, + cameraEl: camEl, + pointerDownAt: { x: 97, y: 46 }, + resolveHandle: reg.findPolyMeshHandle, + }); + expect(polyEv.pointer.x).toBeCloseTo(0); + expect(polyEv.pointer.y).toBeCloseTo(0); + expect(polyEv.delta).toBe(5); + polyEv.stopPropagation(); + expect(spyStop).toHaveBeenCalledOnce(); + + reg.unregisterMeshElement(meshEl); + expect(reg.findPolyMeshHandle(leaf)).toBeNull(); + }); + + it("mounts standalone mesh leaves preserving static children and restores voxel class", () => { + const wrapper = document.createElement("div"); + const staticChild = document.createElement("span"); + wrapper.appendChild(staticChild); + const owned = new Set(); + + const mounted = renderStandaloneMeshIntoWrapper(wrapper, owned, [QUAD], { + doc: document, + textureLighting: "baked", + }); + expect(owned.size).toBe(1); + expect(wrapper.lastChild).toBe(staticChild); + mounted.dispose(); + expect(owned.size).toBe(0); + expect(wrapper.children.length).toBe(1); + + const empty = renderStandaloneMeshIntoWrapper(wrapper, owned, [], { + doc: document, + textureLighting: "baked", + }); + empty.dispose(); + clearOwnedDomNodes(owned); + + const voxelFace = document.createElement("div"); + voxelFace.className = "polycss-voxel-face"; + wrapper.appendChild(voxelFace); + restoreVoxelMeshClass(wrapper); + expect(wrapper.classList.contains("polycss-voxel-mesh")).toBe(true); + }); +}); + +describe("gizmoEngine declarative helpers & selectionEngine", () => { + it("builds translate/rotate entries, runs declarative drags, and handles camera fallback", () => { + expect(RING_MASK_INNER_RATIO).toBeLessThan(RING_MASK_OUTER_RATIO); + const tEntries = buildTransformGizmoEntries({ + mode: "translate", + polygons: [QUAD], + size: 1, + showX: true, + showY: true, + showZ: false, + rotX: 60, + rotY: 45, + hoveredKey: "x", + draggingKey: null, + }); + expect(tEntries.arrows.length).toBe(4); + expect(tEntries.planes.length).toBe(1); + + const rEntries = buildTransformGizmoEntries({ + mode: "rotate", + polygons: [QUAD], + size: 1, + showX: true, + showY: false, + showZ: true, + rotX: 60, + rotY: 45, + hoveredKey: null, + draggingKey: "x", + }); + expect(rEntries.rings.length).toBe(2); + expect(computeGizmoWrapperPositionCss([1, 2, 3], [QUAD])).toEqual([125, 75, 150]); + + const onObjectChange = vi.fn(); + const rebakeAtlas = vi.fn(); + const target: DeclarativeGizmoTarget = { + getPosition: () => [10, 20, 30] as Vec3, + getRotation: () => [0, 0, 0] as Vec3, + rebakeAtlas, + }; + const wrapper = document.createElement("div"); + wrapper.setAttribute("data-poly-transform-controls", ""); + const cameraEl = document.createElement("div"); + const planeEl = document.createElement("div"); + planeEl.className = "polycss-transform-gizmo polycss-transform-plane polycss-transform-plane--xy"; + const planeLeaf = document.createElement("b"); + planeLeaf.getBoundingClientRect = () => + ({ left: 0, top: 0, right: 50, bottom: 50, width: 50, height: 50, x: 0, y: 0, toJSON() { return this; } }) as DOMRect; + planeEl.appendChild(planeLeaf); + wrapper.appendChild(planeEl); + cameraEl.appendChild(wrapper); + document.body.appendChild(cameraEl); + + const state: DeclarativeGizmoDragState = { + target, + mode: "translate", + shaftLengthCss: 100, + enabled: true, + showX: true, + showY: true, + showZ: true, + translationSnap: null, + rotationSnap: null, + onObjectChange, + }; + + withFakeLayout(2, () => { + startDeclarativeArrowDrag(tEntries.arrows[0]!.spec, wrapper, 0, 0, () => state); + window.dispatchEvent(new PointerEvent("pointermove", { clientX: 10, clientY: 0 })); + window.dispatchEvent(new PointerEvent("pointerup")); + expect(onObjectChange).toHaveBeenCalledWith({ object: target, position: [15, 20, 30] }); + + startDeclarativePlaneDrag(tEntries.planes[0]!.spec, wrapper, 0, 0, () => state); + window.dispatchEvent(new PointerEvent("pointermove", { clientX: 8, clientY: 6 })); + window.dispatchEvent(new PointerEvent("pointerup")); + expect(onObjectChange).toHaveBeenLastCalledWith({ object: target, position: [14, 23, 30] }); + + startDeclarativeRingDrag(rEntries.rings[0]!.spec, wrapper, 100, 0, () => ({ + ...state, + mode: "rotate", + })); + window.dispatchEvent(new PointerEvent("pointermove", { clientX: 0, clientY: 100 })); + window.dispatchEvent(new PointerEvent("pointerup")); + expect(rebakeAtlas).toHaveBeenCalledOnce(); + }); + + const detach = attachDeclarativeGizmoFallback(cameraEl, () => state); + withFakeLayout(2, () => { + cameraEl.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, clientX: 25, clientY: 25 })); + window.dispatchEvent(new PointerEvent("pointerup")); + }); + detach(); + }); + + it("caches per-handle gizmo polygons across intra-quadrant camera ticks and single-handle hover", () => { + const cache: TransformGizmoCache = new Map(); + const t1 = buildTransformGizmoEntries({ + mode: "translate", + polygons: [QUAD], + size: 1, + showX: true, + showY: true, + showZ: true, + rotX: 60, + rotY: 40, + hoveredKey: null, + draggingKey: null, + cache, + }); + const t2 = buildTransformGizmoEntries({ + mode: "translate", + polygons: [QUAD], + size: 1, + showX: true, + showY: true, + showZ: true, + rotX: 62, + rotY: 42, + hoveredKey: null, + draggingKey: null, + cache, + }); + expect(t2.arrows.map((a) => a.polygons)).toEqual(t1.arrows.map((a) => a.polygons)); + for (let i = 0; i < t1.arrows.length; i++) { + expect(t2.arrows[i]!.polygons).toBe(t1.arrows[i]!.polygons); + } + for (let i = 0; i < t1.planes.length; i++) { + expect(t2.planes[i]!.polygons).toBe(t1.planes[i]!.polygons); + } + + const tHover = buildTransformGizmoEntries({ + mode: "translate", + polygons: [QUAD], + size: 1, + showX: true, + showY: true, + showZ: true, + rotX: 62, + rotY: 42, + hoveredKey: t1.arrows[0]!.spec.key, + draggingKey: null, + cache, + }); + expect(tHover.arrows[0]!.polygons).not.toBe(t2.arrows[0]!.polygons); + for (let i = 1; i < t2.arrows.length; i++) { + expect(tHover.arrows[i]!.polygons).toBe(t2.arrows[i]!.polygons); + } + + const r1 = buildTransformGizmoEntries({ + mode: "rotate", + polygons: [QUAD], + size: 1, + showX: true, + showY: true, + showZ: true, + rotX: 10, + rotY: 20, + hoveredKey: null, + draggingKey: null, + cache, + }); + const r2 = buildTransformGizmoEntries({ + mode: "rotate", + polygons: [QUAD], + size: 1, + showX: true, + showY: true, + showZ: true, + rotX: 85, + rotY: 210, + hoveredKey: null, + draggingKey: null, + cache, + }); + for (let i = 0; i < r1.rings.length; i++) { + expect(r2.rings[i]!.polygons).toBe(r1.rings[i]!.polygons); + } + }); + + it("manages selection add/remove/toggle/clear and click delegation", () => { + const onChange = vi.fn(); + const onMiss = vi.fn(); + const ctrl = createSelectionController({ + getMultiple: () => true, + getClearOnMiss: () => true, + getFilter: () => undefined, + resolveTarget: (el) => el?.getAttribute("data-id") ?? null, + onChange, + onPointerMissed: onMiss, + }); + ctrl.add("a"); + ctrl.add("a"); + expect(onChange).toHaveBeenCalledTimes(1); + ctrl.add("b"); + expect(onChange).toHaveBeenCalledTimes(2); + expect(ctrl.has("a")).toBe(true); + ctrl.remove("missing"); + ctrl.remove("a"); + ctrl.toggle("b"); + ctrl.toggle("c"); + ctrl.clear(); + expect(ctrl.selected).toEqual([]); + + const host = document.createElement("div"); + const item = document.createElement("div"); + item.setAttribute("data-id", "x"); + host.appendChild(item); + const detach = ctrl.attach(host); + item.dispatchEvent(new MouseEvent("click", { bubbles: true })); + expect(ctrl.selected).toEqual(["x"]); + item.dispatchEvent(new MouseEvent("click", { bubbles: true })); + expect(ctrl.selected).toEqual([]); + host.dispatchEvent(new MouseEvent("click", { bubbles: true })); + expect(onMiss).toHaveBeenCalledOnce(); + detach(); + }); +}); diff --git a/packages/polycss/src/api/scene/meshEntry.ts b/packages/polycss/src/api/scene/meshEntry.ts new file mode 100644 index 000000000..fc4186809 --- /dev/null +++ b/packages/polycss/src/api/scene/meshEntry.ts @@ -0,0 +1,611 @@ +/** + * Mesh entry creation and `PolyMeshHandle` implementation for `createPolyScene`. + */ +import type { ParseResult, Polygon, Vec3 } from "@layoutit/polycss-core"; +import { + inverseRotateVec3, + optimizeMeshPolygons, + recenterPolygons, +} from "@layoutit/polycss-core"; +import { + getSolidPaintDefaults, + updatePolygonsWithStableTopology, + updateStableTriangleFrame, + type SolidPaintDefaults, +} from "../../render/textureAtlas"; +import { applyMeshLightVarOverride } from "./bakedLighting"; +import { + canDomCullCamera, + recomputeCameraCullGroups, + syncCameraCullSignature, +} from "./cameraCull"; +import type { MeshEntry } from "./internalTypes"; +import { applySolidPaintVars } from "./lightingVars"; +import { TEXTURES_READY, clearRendered } from "./mountLifecycle"; +import { syncMountedRenderedForCameraChange } from "./mountSync"; +import { tryUpdatePolygonLeafOnly } from "./polygonPatch"; +import { renderEntryAtomic, requestRebakeAtlas, resolveMeshRenderOptions } from "./rebake"; +import { disposeReceiverShadowMounts } from "./receiverShadow"; +import { renderSceneEntry, renderSceneEntryChunked } from "./renderEntry"; +import type { SceneContext } from "./sceneContext"; +import { clearCasterItemsCache, clearReceiverShadowCache } from "./shadowCache"; +import { + emitSceneShadows, + emitShadowLeaves, + invalidateShadowLightCache, + maybeEmitAnimationShadow, + recomputeShadowGround, +} from "./shadowOrchestrator"; +import { DEFAULT_TILE, buildMeshTransform } from "./transforms"; +import type { + InternalPolyMeshHandle, + InternalSetPolygonsOptions, + PolyAnimationTriangleFrame, + PolyMeshHandle, + PolyMeshTransform, +} from "./types"; +import { POLY_ANIMATION_TRIANGLE_FRAME_TARGET } from "./types"; + +export interface AddSceneMeshDeps { + meshByElement: WeakMap; + recomputeAutoCenter: () => void; +} + +const RENDER_OVERRIDE_KEYS = [ + "textureLighting", + "textureQuality", + "textureLeafSizing", + "textureImageRendering", + "textureBackend", + "textureProjection", + "seamBleed", +] as const; + +function buildStableTopologyOptions( + ctx: SceneContext, + entry: MeshEntry, + options: InternalSetPolygonsOptions | undefined, + solidPaintDefaults: SolidPaintDefaults, + colorFrame: number, + defaultFreezeFrames?: number, +) { + return { + ...resolveMeshRenderOptions(ctx, entry), + solidPaintDefaults, + optimizeStableTriangleStyle: true, + stableTriangleDebug: options?.stableTriangleDebug, + stableTriangleUpdateMode: options?.stableTriangleUpdateMode, + stableTriangleColorPolicy: options?.stableTriangleColorPolicy, + stableTriangleColorSteps: options?.stableTriangleColorSteps, + stableTriangleColorFreezeFrames: options?.stableTriangleColorFreezeFrames ?? defaultFreezeFrames, + stableTriangleColorBudget: options?.stableTriangleColorBudget, + stableTriangleColorMaxAge: options?.stableTriangleColorMaxAge, + stableTriangleColorMaxStep: options?.stableTriangleColorMaxStep, + stableTriangleMatrixDecimals: options?.stableTriangleMatrixDecimals, + stableTriangleColorFrame: colorFrame, + } as Parameters[2] & + Parameters[3] & { + optimizeStableTriangleStyle: boolean; + stableTriangleDebug?: "transform-only" | "plan-only"; + stableTriangleUpdateMode?: "full" | "transform-only" | "color-only"; + stableTriangleColorPolicy?: "cadence" | "adaptive"; + stableTriangleColorSteps?: number; + stableTriangleColorFreezeFrames?: number; + stableTriangleColorBudget?: number; + stableTriangleColorMaxAge?: number; + stableTriangleColorMaxStep?: number; + stableTriangleMatrixDecimals?: number; + stableTriangleColorFrame?: number; + }; +} + +export function addSceneMeshEntry( + ctx: SceneContext, + deps: AddSceneMeshDeps, + parseResult: ParseResult, + transformIn: PolyMeshTransform = {}, +): PolyMeshHandle { + const { sceneEl, meshes } = ctx; + const { meshByElement, recomputeAutoCenter } = deps; + const renderEntry = (entry: MeshEntry, lightDirectionOverride?: Vec3) => + renderSceneEntry(ctx, entry, lightDirectionOverride); + + const mountDoc = sceneEl.ownerDocument ?? document; + const adoptedWrapper = !!transformIn.wrapper; + const isSceneRootWrapper = transformIn.wrapper === sceneEl; + const wrapper = transformIn.wrapper ?? mountDoc.createElement("div"); + if (adoptedWrapper) { + if (!isSceneRootWrapper) wrapper.classList.add("polycss-mesh"); + } else { + wrapper.className = "polycss-mesh"; + } + const autoMeshId = `polycss-mesh-${ctx.meshAutoCounter.next++}`; + if (!isSceneRootWrapper) { + if (transformIn.id) wrapper.setAttribute("data-poly-mesh-id", transformIn.id); + wrapper.setAttribute("data-poly-mesh-index", autoMeshId); + } + + let transform: PolyMeshTransform = { ...transformIn }; + let mergeOnUpdate = transformIn.merge !== false; + let stableDomOnUpdate = !!transformIn.stableDom; + let autoCenterOnUpdate = !!transformIn.autoCenter; + let polygonUpdateVersion = 0; + const css = buildMeshTransform(transform); + if (!isSceneRootWrapper && css) wrapper.style.transform = css; + + const preparePolygons = (polygons: Polygon[], merge: boolean): Polygon[] => { + const centered = autoCenterOnUpdate ? recenterPolygons(polygons) : polygons; + if (parseResult.voxelSource) return centered; + if (merge) return optimizeMeshPolygons(centered, { meshResolution: transform.meshResolution }); + return centered; + }; + const sourcePolygons = preparePolygons(parseResult.polygons, mergeOnUpdate); + + let bboxCenterCssCache: Vec3 | null = null; + let entryRef: MeshEntry | null = null; + + function reapplyWrapperTransform(): void { + if (isSceneRootWrapper) return; + const nextCss = buildMeshTransform(transform); + wrapper.style.transform = nextCss ?? ""; + } + + function applyTransformOrigin(polygons: Polygon[]): void { + if (polygons.length === 0) { + bboxCenterCssCache = null; + if (entryRef) entryRef.bboxCenterCss = null; + reapplyWrapperTransform(); + return; + } + let minX = Infinity, minY = Infinity, minZ = Infinity; + let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity; + for (const poly of polygons) { + for (const v of poly.vertices) { + if (v[0] < minX) minX = v[0]; + if (v[0] > maxX) maxX = v[0]; + if (v[1] < minY) minY = v[1]; + if (v[1] > maxY) maxY = v[1]; + if (v[2] < minZ) minZ = v[2]; + if (v[2] > maxZ) maxZ = v[2]; + } + } + if (!Number.isFinite(minX)) { + bboxCenterCssCache = null; + if (entryRef) entryRef.bboxCenterCss = null; + reapplyWrapperTransform(); + return; + } + // World→CSS axis remap (matches polygonGeometry / autoCenter). + const cssX = ((minY + maxY) / 2) * DEFAULT_TILE; + const cssY = ((minX + maxX) / 2) * DEFAULT_TILE; + const cssZ = ((minZ + maxZ) / 2) * DEFAULT_TILE; + bboxCenterCssCache = [cssX, cssY, cssZ]; + if (entryRef) entryRef.bboxCenterCss = bboxCenterCssCache; + reapplyWrapperTransform(); + } + + applyTransformOrigin(sourcePolygons); + + if (!adoptedWrapper) sceneEl.appendChild(wrapper); + + const entry: MeshEntry = { + handle: undefined as unknown as PolyMeshHandle, + wrapper, + adoptedWrapper, + ownedNodes: new Set(), + parseResult, + rendered: [], + renderedByPolygonIndex: [], + shadowRendered: [], + polygons: sourcePolygons, + voxelSource: parseResult.voxelSource, + disposed: false, + stableDom: stableDomOnUpdate, + autoCenter: autoCenterOnUpdate, + atomicAtlas: !!transformIn.atomicAtlas, + onFrameReady: transformIn.onFrameReady, + atomicSwapVersion: 0, + renderOverrides: { + textureLighting: transformIn.textureLighting, + textureQuality: transformIn.textureQuality, + textureLeafSizing: transformIn.textureLeafSizing, + textureImageRendering: transformIn.textureImageRendering, + textureBackend: transformIn.textureBackend, + textureProjection: transformIn.textureProjection, + seamBleed: transformIn.seamBleed, + }, + hasBuckets: false, + skipBucketNormalCleanupOnce: false, + excludeFromAutoCenter: !!transformIn.excludeFromAutoCenter, + castShadow: !!transformIn.castShadow, + bboxCenterCss: bboxCenterCssCache, + receiveShadow: !!transformIn.receiveShadow, + shadowDefinition: transformIn.shadowDefinition, + cameraCullGroups: [], + cameraCullSignature: "", + lightOverrideSignature: "clear", + stableTriangleColorFrame: 0, + solidLightingPreviewPrepared: false, + solidLightingPreviewActive: false, + bakedRotation: (transformIn.rotation ? [...transformIn.rotation] : [0, 0, 0]) as Vec3, + autoMeshId, + rebakeInFlight: false, + rebakeQueued: false, + rebakeQueuedLightDir: undefined, + textureReadyPromise: TEXTURES_READY, + }; + + let currentTriangleFrame: PolyAnimationTriangleFrame | null = null; + let currentTriangleFrameVersion = 0; + let materializedTriangleFrameVersion = -1; + let materializedTriangleFramePolygons: Polygon[] | null = null; + + function clearCurrentTriangleFrame(): void { + currentTriangleFrame = null; + materializedTriangleFramePolygons = null; + materializedTriangleFrameVersion = -1; + } + + function currentPolygons(): Polygon[] { + const frame = currentTriangleFrame; + if (!frame || frame.polygonCount !== entry.polygons.length) return entry.polygons; + if ( + materializedTriangleFramePolygons && + materializedTriangleFrameVersion === currentTriangleFrameVersion + ) { + return materializedTriangleFramePolygons; + } + const values = frame.vertices; + const out: Polygon[] = new Array(frame.polygonCount); + for (let polygonIndex = 0; polygonIndex < frame.polygonCount; polygonIndex++) { + const base = entry.polygons[polygonIndex]!; + const offset = polygonIndex * 9; + out[polygonIndex] = { + ...base, + color: frame.colors?.[polygonIndex] ?? base.color, + vertices: [ + [values[offset]!, values[offset + 1]!, values[offset + 2]!] as Vec3, + [values[offset + 3]!, values[offset + 4]!, values[offset + 5]!] as Vec3, + [values[offset + 6]!, values[offset + 7]!, values[offset + 8]!] as Vec3, + ], + }; + } + materializedTriangleFramePolygons = out; + materializedTriangleFrameVersion = currentTriangleFrameVersion; + return out; + } + + function applyStableTopologyUpdate( + options: InternalSetPolygonsOptions | undefined, + shouldRecomputeAutoCenter: boolean, + ): boolean { + const colorOnlyStableTriangleUpdate = options?.stableTriangleUpdateMode === "color-only"; + entry.stableTriangleColorFrame++; + const shouldSkipTransformOrigin = entry.stableDom && !shouldRecomputeAutoCenter; + if (!shouldSkipTransformOrigin) applyTransformOrigin(entry.polygons); + if (entry.stableDom && !entry.hasBuckets) { + const renderOptions = resolveMeshRenderOptions(ctx, entry); + const allStableTriangles = + entry.rendered.length === entry.polygons.length && + entry.rendered.every((item) => item.kind === "triangle"); + const optimizeStableTopology = entry.stableDom && !shouldRecomputeAutoCenter; + const solidPaintDefaults = allStableTriangles || optimizeStableTopology + ? {} + : getSolidPaintDefaults(entry.polygons, renderOptions); + if (!allStableTriangles) applySolidPaintVars(entry.wrapper, solidPaintDefaults); + const stableTopologyOptions = buildStableTopologyOptions( + ctx, + entry, + options, + solidPaintDefaults, + entry.stableTriangleColorFrame, + ); + if ( + updatePolygonsWithStableTopology( + entry.rendered, + entry.polygons, + stableTopologyOptions, + ) + ) { + if (!colorOnlyStableTriangleUpdate) { + recomputeCameraCullGroups(entry); + syncMountedRenderedForCameraChange(ctx, entry, true); + if (shouldRecomputeAutoCenter) recomputeAutoCenter(); + } + return true; + } + } + if (shouldSkipTransformOrigin) applyTransformOrigin(entry.polygons); + return false; + } + + const handle: InternalPolyMeshHandle = { + get polygons() { return currentPolygons(); }, + set polygons(polygons: Polygon[]) { + clearCurrentTriangleFrame(); + entry.polygons = polygons; + }, + element: wrapper, + get id() { return transform.id; }, + get transform() { return transform; }, + remove() { + polygonUpdateVersion++; + entry.atomicSwapVersion++; + if (!entry.adoptedWrapper && wrapper.parentNode) wrapper.parentNode.removeChild(wrapper); + clearRendered(ctx, entry); + meshes.delete(entry); + meshByElement.delete(wrapper); + clearReceiverShadowCache(ctx, entry); + clearCasterItemsCache(ctx, entry); + recomputeAutoCenter(); + recomputeShadowGround(ctx); + }, + setPolygons(polygons: Polygon[], options?: InternalSetPolygonsOptions) { + polygonUpdateVersion++; + mergeOnUpdate = options?.merge ?? mergeOnUpdate; + stableDomOnUpdate = options?.stableDom ?? stableDomOnUpdate; + entry.stableDom = stableDomOnUpdate; + entry.voxelSource = undefined; + entry.polygons = preparePolygons(polygons, mergeOnUpdate); + clearCasterItemsCache(ctx, entry); + clearReceiverShadowCache(ctx, entry); + clearCurrentTriangleFrame(); + handle.polygons = entry.polygons; + const shouldRecomputeAutoCenter = options?.recomputeAutoCenter ?? true; + maybeEmitAnimationShadow(ctx, entry); + if (applyStableTopologyUpdate(options, shouldRecomputeAutoCenter)) return; + if (entry.atomicAtlas && (entry.rendered.length > 0 || entry.voxelRenderer)) { + renderEntryAtomic(ctx, entry); + } else { + renderEntry(entry); + } + if (shouldRecomputeAutoCenter) recomputeAutoCenter(); + }, + [POLY_ANIMATION_TRIANGLE_FRAME_TARGET]( + frame: PolyAnimationTriangleFrame, + options?: InternalSetPolygonsOptions, + ) { + const nextMergeOnUpdate = options?.merge ?? mergeOnUpdate; + const nextStableDomOnUpdate = options?.stableDom ?? stableDomOnUpdate; + if ( + !frame.solidTriangles || + !nextStableDomOnUpdate || + nextMergeOnUpdate || + transformIn.meshResolution !== undefined || + entry.hasBuckets || + frame.polygonCount !== entry.polygons.length || + frame.vertices.length < frame.polygonCount * 9 || + entry.rendered.length !== frame.polygonCount + ) { + return false; + } + for (let i = 0; i < entry.rendered.length; i++) { + const rendered = entry.rendered[i]; + const polygon = entry.polygons[i]; + if ( + rendered?.kind !== "triangle" || + rendered.polygonIndex !== i || + !polygon || + polygon.vertices.length !== 3 || + polygon.texture || + polygon.material?.texture + ) { + return false; + } + } + + const shouldRecomputeAutoCenter = options?.recomputeAutoCenter ?? true; + if (!shouldRecomputeAutoCenter) { + const colorFrame = entry.stableTriangleColorFrame + 1; + // Triangle-frame animation updates transforms directly; pin baked + // color unless an internal caller opts into color refresh. + const stableTopologyOptions = buildStableTopologyOptions( + ctx, + entry, + options, + {}, + colorFrame, + 0, + ); + if ( + updateStableTriangleFrame( + entry.rendered, + entry.polygons, + frame, + stableTopologyOptions, + ) + ) { + polygonUpdateVersion++; + mergeOnUpdate = nextMergeOnUpdate; + stableDomOnUpdate = nextStableDomOnUpdate; + entry.stableDom = stableDomOnUpdate; + entry.voxelSource = undefined; + entry.stableTriangleColorFrame = colorFrame; + currentTriangleFrame = frame; + currentTriangleFrameVersion++; + materializedTriangleFramePolygons = null; + materializedTriangleFrameVersion = -1; + if (canDomCullCamera(entry)) { + recomputeCameraCullGroups(entry); + syncMountedRenderedForCameraChange(ctx, entry, true); + } else { + syncCameraCullSignature(ctx, entry); + } + return true; + } + } + + polygonUpdateVersion++; + mergeOnUpdate = nextMergeOnUpdate; + stableDomOnUpdate = nextStableDomOnUpdate; + entry.stableDom = stableDomOnUpdate; + entry.voxelSource = undefined; + + const values = frame.vertices; + for (let polygonIndex = 0; polygonIndex < frame.polygonCount; polygonIndex++) { + const polygon = entry.polygons[polygonIndex]!; + const color = frame.colors?.[polygonIndex]; + if (color) polygon.color = color; + const vertices = polygon.vertices; + const offset = polygonIndex * 9; + vertices[0]![0] = values[offset]!; + vertices[0]![1] = values[offset + 1]!; + vertices[0]![2] = values[offset + 2]!; + vertices[1]![0] = values[offset + 3]!; + vertices[1]![1] = values[offset + 4]!; + vertices[1]![2] = values[offset + 5]!; + vertices[2]![0] = values[offset + 6]!; + vertices[2]![1] = values[offset + 7]!; + vertices[2]![2] = values[offset + 8]!; + } + clearCurrentTriangleFrame(); + handle.polygons = entry.polygons; + return applyStableTopologyUpdate(options, shouldRecomputeAutoCenter); + }, + updatePolygon(target: Polygon | number, partial: Partial) { + let idx = typeof target === "number" ? target : entry.polygons.indexOf(target); + if (idx < 0 && typeof target !== "number" && currentTriangleFrame) { + idx = currentPolygons().indexOf(target); + } + if (idx < 0 || idx >= entry.polygons.length) return; + clearCurrentTriangleFrame(); + entry.voxelSource = undefined; + if ("vertices" in partial && (entry.castShadow || entry.receiveShadow)) { + entry.polygons = entry.polygons.slice(); + clearCasterItemsCache(ctx, entry); + clearReceiverShadowCache(ctx, entry); + } + Object.assign(entry.polygons[idx], partial); + const partialKeys = Object.keys(partial); + if (tryUpdatePolygonLeafOnly(ctx, entry, idx, partialKeys)) { + return; + } + renderEntry(entry); + }, + async setPolygonsChunked(polygons: Polygon[], options?: { + merge?: boolean; + stableDom?: boolean; + recomputeAutoCenter?: boolean; + }) { + const version = ++polygonUpdateVersion; + mergeOnUpdate = options?.merge ?? mergeOnUpdate; + stableDomOnUpdate = options?.stableDom ?? stableDomOnUpdate; + entry.stableDom = stableDomOnUpdate; + entry.voxelSource = undefined; + entry.polygons = preparePolygons(polygons, mergeOnUpdate); + clearCurrentTriangleFrame(); + handle.polygons = entry.polygons; + applyTransformOrigin(entry.polygons); + const shouldRecomputeAutoCenter = options?.recomputeAutoCenter ?? true; + const shouldCancel = () => entry.disposed || version !== polygonUpdateVersion; + const completed = await renderSceneEntryChunked(ctx, entry, shouldCancel); + if (!completed) { + clearRendered(ctx, entry); + return; + } + if (shouldRecomputeAutoCenter) recomputeAutoCenter(); + }, + setTransform(t: Partial) { + const hasOwn = (key: string): boolean => Object.prototype.hasOwnProperty.call(t, key); + const prevCastShadow = entry.castShadow; + const prevReceiveShadow = entry.receiveShadow; + const prevShadowDef = entry.shadowDefinition; + const prevExclude = entry.excludeFromAutoCenter; + if (hasOwn("castShadow")) entry.castShadow = !!t.castShadow; + if (hasOwn("receiveShadow")) entry.receiveShadow = !!t.receiveShadow; + if (hasOwn("shadowDefinition")) entry.shadowDefinition = t.shadowDefinition; + if (hasOwn("excludeFromAutoCenter")) entry.excludeFromAutoCenter = !!t.excludeFromAutoCenter; + if (hasOwn("autoCenter")) { + autoCenterOnUpdate = !!t.autoCenter; + entry.autoCenter = autoCenterOnUpdate; + } + if (hasOwn("atomicAtlas")) entry.atomicAtlas = !!t.atomicAtlas; + if (hasOwn("onFrameReady")) entry.onFrameReady = t.onFrameReady; + let renderOverrideChanged = false; + for (const key of RENDER_OVERRIDE_KEYS) { + if (Object.prototype.hasOwnProperty.call(t, key) && entry.renderOverrides[key] !== t[key]) { + (entry.renderOverrides as Record)[key] = t[key]; + renderOverrideChanged = true; + } + } + transform = { ...transform, ...t }; + if (!isSceneRootWrapper) { + const css2 = buildMeshTransform(transform); + wrapper.style.transform = css2 ?? ""; + } + applyMeshLightVarOverride(ctx, entry, transform.rotation); + if (renderOverrideChanged) { + if (entry.atomicAtlas && (entry.rendered.length > 0 || entry.voxelRenderer)) { + renderEntryAtomic(ctx, entry); + } else { + renderEntry(entry); + } + } + if (t.rotation !== undefined) syncMountedRenderedForCameraChange(ctx, entry, true); + if (entry.excludeFromAutoCenter !== prevExclude) recomputeAutoCenter(); + if (entry.castShadow !== prevCastShadow) { + if (entry.voxelSource) renderEntry(entry); + emitShadowLeaves(ctx, entry); + recomputeShadowGround(ctx); + } + if (entry.receiveShadow !== prevReceiveShadow) { + if (!entry.receiveShadow) disposeReceiverShadowMounts(entry); + invalidateShadowLightCache(ctx); + emitSceneShadows(ctx); + } + if ( + (t.position !== undefined || t.rotation !== undefined || t.scale !== undefined) && + (entry.castShadow || entry.receiveShadow) + ) { + recomputeShadowGround(ctx); + invalidateShadowLightCache(ctx); + emitSceneShadows(ctx); + } + if (entry.shadowDefinition !== prevShadowDef && (entry.castShadow || entry.receiveShadow)) { + invalidateShadowLightCache(ctx); + emitSceneShadows(ctx); + } + }, + dispose() { + if (entry.disposed) return; + entry.disposed = true; + polygonUpdateVersion++; + entry.atomicSwapVersion++; + if (!entry.adoptedWrapper && wrapper.parentNode) wrapper.parentNode.removeChild(wrapper); + clearRendered(ctx, entry); + try { parseResult.dispose(); } catch { /* ignore */ } + meshes.delete(entry); + meshByElement.delete(wrapper); + recomputeAutoCenter(); + const prevGround = ctx.shadowSvgState.currentGroundCssZ; + recomputeShadowGround(ctx); + if ((entry.castShadow || entry.receiveShadow) && ctx.shadowSvgState.currentGroundCssZ === prevGround) { + invalidateShadowLightCache(ctx); + emitSceneShadows(ctx); + } + }, + rebakeAtlas() { + entry.bakedRotation = (transform.rotation ? [...transform.rotation] : [0, 0, 0]) as Vec3; + const worldDir = ctx.options.current.directionalLight?.direction; + const localLightDir = worldDir + ? inverseRotateVec3(worldDir as Vec3, entry.bakedRotation) + : undefined; + requestRebakeAtlas(ctx, entry, renderEntry, localLightDir); + }, + whenTexturesReady() { return entry.textureReadyPromise; }, + getPosition() { return transform.position; }, + getRotation() { return transform.rotation; }, + getScale() { return transform.scale; }, + getPolygons() { return handle.polygons; }, + }; + + entry.handle = handle; + entryRef = entry; + if (!isSceneRootWrapper) meshByElement.set(wrapper, entry); + meshes.add(entry); + renderEntry(entry); + applyMeshLightVarOverride(ctx, entry, transform.rotation); + recomputeAutoCenter(); + recomputeShadowGround(ctx); + return handle; +} diff --git a/packages/polycss/src/api/scene/renderEntry.ts b/packages/polycss/src/api/scene/renderEntry.ts new file mode 100644 index 000000000..83eccf61b --- /dev/null +++ b/packages/polycss/src/api/scene/renderEntry.ts @@ -0,0 +1,164 @@ +/** + * Per-mesh rendering entry points (synchronous and chunked-async) for + * `createPolyScene`. Operates purely on `SceneContext` + `MeshEntry`. + */ +import type { Vec3 } from "@layoutit/polycss-core"; +import { + getSolidPaintDefaults, + renderPolygonsWithStableTriangles, + renderPolygonsWithTextureAtlas, + renderPolygonsWithTextureAtlasAsync, + type SolidPaintDefaults, +} from "../../render/textureAtlas"; +import { createPolyVoxelRenderer } from "../../render/voxelRenderer"; +import { cameraCullRotation, recomputeCameraCullGroups } from "./cameraCull"; +import type { MeshEntry } from "./internalTypes"; +import { applySolidPaintVars } from "./lightingVars"; +import { TEXTURES_READY, clearRendered, setRendered } from "./mountLifecycle"; +import { syncMountedRendered, syncMountedRenderedChunked } from "./mountSync"; +import { + canRenderVoxelDirect, + collectAtlasUrlsFromRendered, + decodeAtlasUrls, + resolveMeshRenderOptions, +} from "./rebake"; +import type { SceneContext } from "./sceneContext"; +import { emitShadowLeaves } from "./shadowOrchestrator"; +import { worldDirectionalLightToCss } from "./transforms"; + +export function renderSceneEntry( + ctx: SceneContext, + entry: MeshEntry, + lightDirectionOverride?: Vec3, +): void { + clearRendered(ctx, entry); + const currentOptions = ctx.options.current; + const baseDirLight = currentOptions.directionalLight; + const userDirLight: typeof baseDirLight = lightDirectionOverride + ? { ...baseDirLight, direction: lightDirectionOverride } + : baseDirLight; + const directionalLight = worldDirectionalLightToCss(userDirLight); + if (canRenderVoxelDirect(ctx, entry)) { + const renderer = createPolyVoxelRenderer({ + doc: ctx.doc, + wrapper: entry.wrapper, + polygons: entry.parseResult.polygons, + directionalLight, + ambientLight: currentOptions.ambientLight, + }); + if (renderer) { + entry.voxelRenderer = renderer; + renderer.render(cameraCullRotation(ctx, entry)); + entry.cameraCullSignature = "voxel-direct"; + entry.textureReadyPromise = TEXTURES_READY; + if (entry.atomicAtlas && entry.onFrameReady) entry.onFrameReady(); + return; + } + } + + const resolvedRenderOptions = resolveMeshRenderOptions(ctx, entry, lightDirectionOverride); + const entryLighting = resolvedRenderOptions.textureLighting; + const renderOptions = { + ...resolvedRenderOptions, + lightOccludedPolyIndices: undefined as ReadonlySet | undefined, + }; + let stableAtlas: ReturnType = null; + if (entry.stableDom) { + const solidPaintDefaults = getSolidPaintDefaults(entry.polygons, renderOptions); + stableAtlas = renderPolygonsWithStableTriangles(entry.polygons, { + ...renderOptions, + solidPaintDefaults, + }); + if (stableAtlas) { + applySolidPaintVars(entry.wrapper, solidPaintDefaults); + } else { + // Polygons are not eligible for stable-triangle updates (e.g. quads + // or textured faces); clear stableDom so Lambert bucketing and + // in-place rebaking stay enabled. + entry.stableDom = false; + } + } + const atlas = stableAtlas ?? renderPolygonsWithTextureAtlas(entry.polygons, { + ...renderOptions, + computeSolidPaintDefaults: true, + skipDynamicNormalVars: entryLighting === "dynamic", + } as typeof renderOptions & { computeSolidPaintDefaults: true }); + if (!stableAtlas) { + applySolidPaintVars( + entry.wrapper, + (atlas as { solidPaintDefaults?: SolidPaintDefaults }).solidPaintDefaults ?? {}, + ); + } + setRendered(entry, atlas.rendered, atlas.dispose, atlas.pagesReady); + entry.skipBucketNormalCleanupOnce = entryLighting === "dynamic" && !entry.stableDom; + recomputeCameraCullGroups(entry); + syncMountedRendered(ctx, entry); + emitShadowLeaves(ctx, entry); + if (entry.atomicAtlas && entry.onFrameReady) { + const version = entry.atomicSwapVersion; + const ready = (atlas as { pagesReady?: Promise }).pagesReady; + if (ready && typeof ready.then === "function") { + ready + .then(() => { + if (entry.disposed || version !== entry.atomicSwapVersion) return; + return decodeAtlasUrls(collectAtlasUrlsFromRendered(atlas.rendered)); + }) + .then( + () => { + if (!entry.disposed && version === entry.atomicSwapVersion) entry.onFrameReady?.(); + }, + () => { + if (!entry.disposed && version === entry.atomicSwapVersion) entry.onFrameReady?.(); + }, + ); + } else { + entry.onFrameReady(); + } + } +} + +export async function renderSceneEntryChunked( + ctx: SceneContext, + entry: MeshEntry, + shouldCancel: () => boolean, +): Promise { + clearRendered(ctx, entry); + const resolvedRenderOptions = resolveMeshRenderOptions(ctx, entry); + const entryLighting = resolvedRenderOptions.textureLighting; + const renderOptions = { + ...resolvedRenderOptions, + lightOccludedPolyIndices: undefined as ReadonlySet | undefined, + }; + const atlas = entry.stableDom + ? renderPolygonsWithStableTriangles(entry.polygons, renderOptions) + : null; + if (atlas) { + const solidPaintDefaults = getSolidPaintDefaults(entry.polygons, renderOptions); + applySolidPaintVars(entry.wrapper, solidPaintDefaults); + setRendered(entry, atlas.rendered, atlas.dispose, atlas.pagesReady); + recomputeCameraCullGroups(entry); + syncMountedRendered(ctx, entry); + emitShadowLeaves(ctx, entry); + return !shouldCancel(); + } + + const asyncAtlas = await renderPolygonsWithTextureAtlasAsync( + entry.polygons, + { + ...renderOptions, + skipDynamicNormalVars: entryLighting === "dynamic", + } as typeof renderOptions & { skipDynamicNormalVars: boolean }, + shouldCancel, + ); + if (shouldCancel()) { + asyncAtlas.dispose(); + return false; + } + applySolidPaintVars(entry.wrapper, asyncAtlas.solidPaintDefaults); + setRendered(entry, asyncAtlas.rendered, asyncAtlas.dispose, asyncAtlas.pagesReady); + entry.skipBucketNormalCleanupOnce = entryLighting === "dynamic" && !entry.stableDom; + recomputeCameraCullGroups(entry); + const mounted = await syncMountedRenderedChunked(ctx, entry, shouldCancel); + if (mounted) emitShadowLeaves(ctx, entry); + return mounted; +} diff --git a/packages/polycss/src/api/standaloneMesh.ts b/packages/polycss/src/api/standaloneMesh.ts new file mode 100644 index 000000000..6abbec000 --- /dev/null +++ b/packages/polycss/src/api/standaloneMesh.ts @@ -0,0 +1,68 @@ +/** + * Shared standalone `` DOM helpers for React and Vue adapters. + */ +import type { Polygon } from "@layoutit/polycss-core"; +import { + renderPolygonsWithTextureAtlas, + type RenderTextureAtlasOptions, +} from "../render/textureAtlas"; + +const RESOLVED_PROMISE = Promise.resolve(); + +/** + * Re-apply `.polycss-voxel-mesh` on an adopted direct-voxel wrapper after + * React/Vue reconciles its `className`/`class` attribute. + */ +export function restoreVoxelMeshClass(el: HTMLElement | null): void { + if (!el) return; + for (let i = 0; i < el.children.length; i += 1) { + if (el.children[i]?.classList.contains("polycss-voxel-face")) { + el.classList.add("polycss-voxel-mesh"); + break; + } + } +} + +export function clearOwnedDomNodes(owned: Set): void { + for (const node of owned) { + node.parentNode?.removeChild(node); + } + owned.clear(); +} + +export interface StandaloneMeshMountResult { + dispose: () => void; + ready: Promise; +} + +/** + * Render polygons directly into a standalone `` wrapper element + * (when mounted outside a ``), preserving any non-owned static + * framework children at the end of the wrapper. + */ +export function renderStandaloneMeshIntoWrapper( + el: HTMLElement, + owned: Set, + polygons: Polygon[], + options: RenderTextureAtlasOptions, +): StandaloneMeshMountResult { + clearOwnedDomNodes(owned); + if (polygons.length === 0) { + return { dispose: () => {}, ready: RESOLVED_PROMISE }; + } + const result = renderPolygonsWithTextureAtlas(polygons, options); + const firstStatic = Array.from(el.childNodes).find((n) => !owned.has(n)) ?? null; + const frag = (el.ownerDocument ?? document).createDocumentFragment(); + for (const item of result.rendered) { + owned.add(item.element); + frag.appendChild(item.element); + } + el.insertBefore(frag, firstStatic); + return { + dispose: () => { + result.dispose(); + clearOwnedDomNodes(owned); + }, + ready: result.pagesReady ?? RESOLVED_PROMISE, + }; +} diff --git a/packages/polycss/src/elements/PolyDirectionalLightHelperElement.ts b/packages/polycss/src/elements/PolyDirectionalLightHelperElement.ts index da3ba26ac..442a480ba 100644 --- a/packages/polycss/src/elements/PolyDirectionalLightHelperElement.ts +++ b/packages/polycss/src/elements/PolyDirectionalLightHelperElement.ts @@ -14,6 +14,7 @@ import { octahedronPolygons } from "@layoutit/polycss-core"; import type { ParseResult, Vec3 } from "@layoutit/polycss-core"; import type { PolyMeshHandle } from "../api/createPolyScene"; import type { PolySceneElement } from "./PolySceneElement"; +import { parseVec3 } from "./parseAttr"; const ELEMENT_BASE: typeof HTMLElement = typeof HTMLElement !== "undefined" @@ -36,15 +37,6 @@ function findScene(el: HTMLElement): PolySceneElement | null { return (el.closest("poly-scene") as unknown as PolySceneElement | null) ?? null; } -function parseVec3(value: string | null): Vec3 | undefined { - if (!value) return undefined; - const parts = value.split(",").map((p) => parseFloat(p.trim())); - if (parts.length !== 3 || parts.some((p) => !Number.isFinite(p))) { - return undefined; - } - return [parts[0], parts[1], parts[2]]; -} - function parseNumber(value: string | null, fallback: number): number { if (value == null) return fallback; const n = parseFloat(value); diff --git a/packages/polycss/src/elements/PolyIframeElement.test.ts b/packages/polycss/src/elements/PolyIframeElement.test.ts index 503c24885..27f4d77c2 100644 --- a/packages/polycss/src/elements/PolyIframeElement.test.ts +++ b/packages/polycss/src/elements/PolyIframeElement.test.ts @@ -5,8 +5,8 @@ * disconnect. */ import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest"; -import { BASE_TILE } from "@layoutit/polycss-core"; -import { PolyIframeElement, buildIframeTransform } from "./PolyIframeElement"; +import { BASE_TILE, buildPolyIframeTransform as buildIframeTransform } from "@layoutit/polycss-core"; +import { PolyIframeElement } from "./PolyIframeElement"; import { PolySceneElement } from "./PolySceneElement"; beforeAll(() => { diff --git a/packages/polycss/src/elements/PolyIframeElement.ts b/packages/polycss/src/elements/PolyIframeElement.ts index 64d332c18..7b3609950 100644 --- a/packages/polycss/src/elements/PolyIframeElement.ts +++ b/packages/polycss/src/elements/PolyIframeElement.ts @@ -20,9 +20,10 @@ * wrapper div + iframe inside the scene's `.polycss-scene` element so * the CSS camera transform applies. On disconnect: removes the wrapper. */ -import { BASE_TILE } from "@layoutit/polycss-core"; +import { BASE_TILE, buildPolyIframeTransform } from "@layoutit/polycss-core"; import type { Vec3 } from "@layoutit/polycss-core"; import type { PolySceneElement } from "./PolySceneElement"; +import { parseVec3 } from "./parseAttr"; const ELEMENT_BASE: typeof HTMLElement = typeof HTMLElement !== "undefined" @@ -43,13 +44,6 @@ const OBSERVED_ATTRS = [ "title", ] as const; -function parseVec3(value: string | null): Vec3 | undefined { - if (!value) return undefined; - const parts = value.split(",").map((p) => parseFloat(p.trim())); - if (parts.length !== 3 || parts.some((p) => !Number.isFinite(p))) return undefined; - return [parts[0], parts[1], parts[2]]; -} - function parseScale(value: string | null): number | Vec3 | undefined { if (!value) return undefined; if (!value.includes(",")) { @@ -75,50 +69,6 @@ function findSceneRoot(el: HTMLElement): HTMLElement | null { return sceneCustomEl.querySelector(".polycss-scene") as HTMLElement | null; } -/** - * Build the wrapper transform string. Mirrors `buildMeshTransform` in - * `packages/polycss/src/api/scene/transforms.ts` exactly — world→CSS axis - * swap on position, rotation conjugation (`rotateY(-rx) rotateX(-ry) - * rotateZ(-rz)` because the swap reflects axes, det=-1), scale at the - * end. The trailing `translate(-w/2, -h/2)` is the only addition: it - * centers the iframe content at the wrapper's local origin (otherwise the - * iframe would extend from (0,0) to (w,h) and rotation would pivot at the - * iframe's corner). - */ -export function buildIframeTransform( - position: Vec3 | undefined, - rotation: Vec3 | undefined, - scale: number | Vec3 | undefined, - cssWidth: number, - cssHeight: number, -): string { - const sx = typeof scale === "number" ? scale : (scale?.[0] ?? 1); - const sy = typeof scale === "number" ? scale : (scale?.[1] ?? 1); - const sz = typeof scale === "number" ? scale : (scale?.[2] ?? 1); - const hasScale = sx !== 1 || sy !== 1 || sz !== 1; - const hasRotation = !!rotation && (!!rotation[0] || !!rotation[1] || !!rotation[2]); - const cssX = (position?.[1] ?? 0) * BASE_TILE; - const cssY = (position?.[0] ?? 0) * BASE_TILE; - const cssZ = (position?.[2] ?? 0) * BASE_TILE; - - const parts: string[] = []; - parts.push(`translate3d(${cssX}px, ${cssY}px, ${cssZ}px)`); - if (hasRotation) { - if (rotation![0]) parts.push(`rotateY(${-rotation![0]}deg)`); - if (rotation![1]) parts.push(`rotateX(${-rotation![1]}deg)`); - if (rotation![2]) parts.push(`rotateZ(${-rotation![2]}deg)`); - } - if (hasScale) { - parts.push(`scale3d(${sx}, ${sy}, ${sz})`); - } - // 2D translate at the end: rotation/scale operate on the centered - // iframe, then the centering offset is applied. Order matters — placing - // this before rotation would rotate the offset itself and the iframe - // would orbit instead of spinning in place. - parts.push(`translate(${-cssWidth / 2}px, ${-cssHeight / 2}px)`); - return parts.join(" "); -} - export class PolyIframeElement extends ELEMENT_BASE { static get observedAttributes(): string[] { return [...OBSERVED_ATTRS]; @@ -210,7 +160,7 @@ export class PolyIframeElement extends ELEMENT_BASE { const position = parseVec3(this.getAttribute("position")); const rotation = parseVec3(this.getAttribute("rotation")); const scale = parseScale(this.getAttribute("scale")); - this._wrapper.style.transform = buildIframeTransform(position, rotation, scale, cssW, cssH); + this._wrapper.style.transform = buildPolyIframeTransform(position, rotation, scale, cssW, cssH); } private _teardown(): void { diff --git a/packages/polycss/src/elements/PolyMapControlsElement.ts b/packages/polycss/src/elements/PolyMapControlsElement.ts index 6c127f1ef..be79d6fd0 100644 --- a/packages/polycss/src/elements/PolyMapControlsElement.ts +++ b/packages/polycss/src/elements/PolyMapControlsElement.ts @@ -1,141 +1,19 @@ /** * — declarative wrapper around `createPolyMapControls`. - * - * Behavior element: no rendered output. Sits inside and walks - * up via parent nodes to attach itself to the parent scene. - * Left-drag pans target (slippy-map semantics); right-drag or Shift+left - * orbits. The full options surface is exposed via kebab-case attributes: - * - * */ -import { PolySceneElement } from "./PolySceneElement"; +import type { PolySceneHandle } from "../api/createPolyScene"; import { createPolyMapControls, type PolyMapControlsHandle, type PolyMapControlsOptions, } from "../api/createPolyMapControls"; -import { parseNumber, parseBoolAttr, parseInvert, parseAxis } from "./parseAttr"; - -const ELEMENT_BASE: typeof HTMLElement = - typeof HTMLElement !== "undefined" - ? HTMLElement - : (class {} as unknown as typeof HTMLElement); - -const OBSERVED_ATTRS = [ - "drag", - "wheel", - "dolly", - "min-distance", - "max-distance", - "invert", - "zoom-min", - "zoom-max", - "animate-speed", - "animate-axis", - "animate-pause-on-interaction", -] as const; - - -export class PolyMapControlsElement extends ELEMENT_BASE { - static get observedAttributes(): string[] { - return [...OBSERVED_ATTRS]; - } - - private _controls: PolyMapControlsHandle | null = null; - - private _readAnimate(): PolyMapControlsOptions["animate"] | undefined { - const speed = parseNumber(this.getAttribute("animate-speed")); - const axis = parseAxis(this.getAttribute("animate-axis")); - const pauseAttr = this.getAttribute("animate-pause-on-interaction"); - const hasAny = - this.hasAttribute("animate-speed") || - this.hasAttribute("animate-axis") || - this.hasAttribute("animate-pause-on-interaction"); - if (!hasAny) return undefined; - return { - ...(speed !== undefined ? { speed } : {}), - ...(axis !== undefined ? { axis } : {}), - ...(pauseAttr !== null ? { pauseOnInteraction: parseBoolAttr(pauseAttr) } : {}), - }; - } - - private _readOptions(): PolyMapControlsOptions { - const opts: PolyMapControlsOptions = {}; - const drag = parseBoolAttr(this.getAttribute("drag")); - if (drag !== undefined) opts.drag = drag; - const wheel = parseBoolAttr(this.getAttribute("wheel")); - if (wheel !== undefined) opts.wheel = wheel; - if (this.hasAttribute("dolly")) opts.dolly = true; - const minDistance = parseNumber(this.getAttribute("min-distance")); - if (minDistance !== undefined) opts.minDistance = minDistance; - const maxDistance = parseNumber(this.getAttribute("max-distance")); - if (maxDistance !== undefined) opts.maxDistance = maxDistance; - const invert = parseInvert(this.getAttribute("invert")); - if (invert !== undefined) opts.invert = invert; - const zoomMin = parseNumber(this.getAttribute("zoom-min")); - const zoomMax = parseNumber(this.getAttribute("zoom-max")); - if (zoomMin !== undefined) opts.minZoom = zoomMin; - if (zoomMax !== undefined) opts.maxZoom = zoomMax; - opts.animate = this._readAnimate() ?? false; - return opts; - } - - private _findScene(): PolySceneElement | null { - let node: Node | null = this.parentNode; - while (node) { - if (node instanceof PolySceneElement) return node; - node = node.parentNode; - } - return null; - } - - private _attach(): void { - if (this._controls) return; - const sceneEl = this._findScene(); - const handle = sceneEl?.getScene(); - if (!handle) { - if (sceneEl) { - const onReady = (): void => { - sceneEl.removeEventListener("polycss:scene-ready", onReady); - this._attach(); - }; - sceneEl.addEventListener("polycss:scene-ready", onReady); - } - return; - } - this._controls = createPolyMapControls(handle, this._readOptions()); - } - - connectedCallback(): void { - this._attach(); - } - - disconnectedCallback(): void { - if (this._controls) { - this._controls.destroy(); - this._controls = null; - } - } - - attributeChangedCallback( - _name: string, - oldValue: string | null, - newValue: string | null, - ): void { - if (oldValue === newValue) return; - if (!this._controls) return; - this._controls.update(this._readOptions()); +import { PolyPointerControlsElement } from "./PolyPointerControlsElement"; + +export class PolyMapControlsElement extends PolyPointerControlsElement { + protected _createControls( + scene: PolySceneHandle, + options: PolyMapControlsOptions, + ): PolyMapControlsHandle { + return createPolyMapControls(scene, options); } } diff --git a/packages/polycss/src/elements/PolyMeshElement.ts b/packages/polycss/src/elements/PolyMeshElement.ts index b75491250..b8b081c84 100644 --- a/packages/polycss/src/elements/PolyMeshElement.ts +++ b/packages/polycss/src/elements/PolyMeshElement.ts @@ -10,10 +10,11 @@ * `auto-center` is currently honored by recentering vertices in-place before * registering; this matches `` semantics. */ -import type { MeshResolution, ObjParseOptions, ParseResult, Polygon, Vec3 } from "@layoutit/polycss-core"; -import { computeSceneBbox, loadMesh } from "@layoutit/polycss-core"; +import type { MeshResolution, ObjParseOptions, ParseResult, Vec3 } from "@layoutit/polycss-core"; +import { loadMesh, recenterPolygons as recenter } from "@layoutit/polycss-core"; import type { PolyMeshHandle } from "../api/createPolyScene"; import type { PolySceneElement } from "./PolySceneElement"; +import { parseVec3 } from "./parseAttr"; const ELEMENT_BASE: typeof HTMLElement = typeof HTMLElement !== "undefined" @@ -37,15 +38,6 @@ const OBSERVED_ATTRS = [ "exclude-objects", ] as const; -function parseVec3(value: string | null): Vec3 | undefined { - if (!value) return undefined; - const parts = value.split(",").map((p) => parseFloat(p.trim())); - if (parts.length !== 3 || parts.some((p) => !Number.isFinite(p))) { - return undefined; - } - return [parts[0], parts[1], parts[2]]; -} - function parseScale(value: string | null): number | Vec3 | undefined { if (!value) return undefined; if (!value.includes(",")) { @@ -85,28 +77,6 @@ function findScene(el: HTMLElement): PolySceneElement | null { return found ?? null; } -function recenter(polygons: Polygon[]): Polygon[] { - if (polygons.length === 0) return polygons; - const bbox = computeSceneBbox(polygons); - const cx = (bbox.min[0] + bbox.max[0]) / 2; - const cy = (bbox.min[1] + bbox.max[1]) / 2; - const cz = (bbox.min[2] + bbox.max[2]) / 2; - if (cx === 0 && cy === 0 && cz === 0) return polygons; - const shift = (v: Vec3): Vec3 => [v[0] - cx, v[1] - cy, v[2] - cz]; - return polygons.map((p) => ({ - ...p, - vertices: p.vertices.map(shift), - ...(p.textureTriangles?.length - ? { - textureTriangles: p.textureTriangles.map((triangle) => ({ - ...triangle, - vertices: triangle.vertices.map(shift) as [Vec3, Vec3, Vec3], - })), - } - : null), - })); -} - export class PolyMeshElement extends ELEMENT_BASE { static get observedAttributes(): string[] { return [...OBSERVED_ATTRS]; diff --git a/packages/polycss/src/elements/PolyOrbitControlsElement.ts b/packages/polycss/src/elements/PolyOrbitControlsElement.ts index 99183eaed..9b773d191 100644 --- a/packages/polycss/src/elements/PolyOrbitControlsElement.ts +++ b/packages/polycss/src/elements/PolyOrbitControlsElement.ts @@ -1,149 +1,19 @@ /** * — declarative wrapper around `createPolyOrbitControls`. - * - * Behavior element: no rendered output. Sits inside and walks - * up via parent nodes to attach itself to the parent scene. - * The full options surface from createPolyOrbitControls is exposed via - * kebab-case attributes: - * - * */ -import { PolySceneElement } from "./PolySceneElement"; +import type { PolySceneHandle } from "../api/createPolyScene"; import { createPolyOrbitControls, type PolyOrbitControlsHandle, type PolyOrbitControlsOptions, } from "../api/createPolyOrbitControls"; -import { parseNumber, parseBoolAttr, parseInvert, parseAxis } from "./parseAttr"; - -const ELEMENT_BASE: typeof HTMLElement = - typeof HTMLElement !== "undefined" - ? HTMLElement - : (class {} as unknown as typeof HTMLElement); - -const OBSERVED_ATTRS = [ - "drag", - "wheel", - "dolly", - "min-distance", - "max-distance", - "invert", - "zoom-min", - "zoom-max", - "animate-speed", - "animate-axis", - "animate-pause-on-interaction", -] as const; - - -export class PolyOrbitControlsElement extends ELEMENT_BASE { - static get observedAttributes(): string[] { - return [...OBSERVED_ATTRS]; - } - - private _controls: PolyOrbitControlsHandle | null = null; - - /** Returns the wrapped PolyOrbitControlsHandle once the element has - * connected to its `` ancestor. Lets external callers attach - * `change` listeners (or call `update()` / `pause()`) the same way they - * would on a vanilla `createPolyOrbitControls(scene, ...)` handle. */ - getControls(): PolyOrbitControlsHandle | null { - return this._controls; - } - - private _readAnimate(): PolyOrbitControlsOptions["animate"] | undefined { - const speed = parseNumber(this.getAttribute("animate-speed")); - const axis = parseAxis(this.getAttribute("animate-axis")); - const pauseAttr = this.getAttribute("animate-pause-on-interaction"); - const hasAny = - this.hasAttribute("animate-speed") || - this.hasAttribute("animate-axis") || - this.hasAttribute("animate-pause-on-interaction"); - if (!hasAny) return undefined; - return { - ...(speed !== undefined ? { speed } : {}), - ...(axis !== undefined ? { axis } : {}), - ...(pauseAttr !== null ? { pauseOnInteraction: parseBoolAttr(pauseAttr) } : {}), - }; - } - - private _readOptions(): PolyOrbitControlsOptions { - const opts: PolyOrbitControlsOptions = {}; - const drag = parseBoolAttr(this.getAttribute("drag")); - if (drag !== undefined) opts.drag = drag; - const wheel = parseBoolAttr(this.getAttribute("wheel")); - if (wheel !== undefined) opts.wheel = wheel; - if (this.hasAttribute("dolly")) opts.dolly = true; - const minDistance = parseNumber(this.getAttribute("min-distance")); - if (minDistance !== undefined) opts.minDistance = minDistance; - const maxDistance = parseNumber(this.getAttribute("max-distance")); - if (maxDistance !== undefined) opts.maxDistance = maxDistance; - const invert = parseInvert(this.getAttribute("invert")); - if (invert !== undefined) opts.invert = invert; - const zoomMin = parseNumber(this.getAttribute("zoom-min")); - const zoomMax = parseNumber(this.getAttribute("zoom-max")); - if (zoomMin !== undefined) opts.minZoom = zoomMin; - if (zoomMax !== undefined) opts.maxZoom = zoomMax; - opts.animate = this._readAnimate() ?? false; - return opts; - } - - private _findScene(): PolySceneElement | null { - let node: Node | null = this.parentNode; - while (node) { - if (node instanceof PolySceneElement) return node; - node = node.parentNode; - } - return null; - } - - private _attach(): void { - if (this._controls) return; - const sceneEl = this._findScene(); - const handle = sceneEl?.getScene(); - if (!handle) { - if (sceneEl) { - const onReady = (): void => { - sceneEl.removeEventListener("polycss:scene-ready", onReady); - this._attach(); - }; - sceneEl.addEventListener("polycss:scene-ready", onReady); - } - return; - } - this._controls = createPolyOrbitControls(handle, this._readOptions()); - } - - connectedCallback(): void { - this._attach(); - } - - disconnectedCallback(): void { - if (this._controls) { - this._controls.destroy(); - this._controls = null; - } - } - - attributeChangedCallback( - _name: string, - oldValue: string | null, - newValue: string | null, - ): void { - if (oldValue === newValue) return; - if (!this._controls) return; - this._controls.update(this._readOptions()); +import { PolyPointerControlsElement } from "./PolyPointerControlsElement"; + +export class PolyOrbitControlsElement extends PolyPointerControlsElement { + protected _createControls( + scene: PolySceneHandle, + options: PolyOrbitControlsOptions, + ): PolyOrbitControlsHandle { + return createPolyOrbitControls(scene, options); } } diff --git a/packages/polycss/src/elements/PolyOrthographicCameraElement.ts b/packages/polycss/src/elements/PolyOrthographicCameraElement.ts index 9d90e82d3..3c9c8daf5 100644 --- a/packages/polycss/src/elements/PolyOrthographicCameraElement.ts +++ b/packages/polycss/src/elements/PolyOrthographicCameraElement.ts @@ -15,6 +15,7 @@ import { createPolyOrthographicCamera, type PolyOrthographicCameraHandle, } from "../api/createPolyCamera"; +import { mountCameraWrapper, teardownCameraWrapper } from "./cameraWrapper"; import { parseNumber, parseVec3 } from "./parseAttr"; const ELEMENT_BASE: typeof HTMLElement = @@ -58,24 +59,12 @@ export class PolyOrthographicCameraElement extends ELEMENT_BASE { if (this._camera) return; const opts = this._readOptions(); this._camera = createPolyOrthographicCamera(opts); - this._wrapper = this.ownerDocument!.createElement("div"); - this._wrapper.className = "polycss-camera"; - this._wrapper.style.perspective = this._camera.perspectiveStyle; - while (this.firstChild) { - this._wrapper.appendChild(this.firstChild); - } - this.appendChild(this._wrapper); - this.dispatchEvent(new CustomEvent("polycss:camera-ready", { bubbles: false })); + this._wrapper = mountCameraWrapper(this, this._camera.perspectiveStyle); } private _teardown(): void { - if (this._wrapper) { - while (this._wrapper.firstChild) { - this.insertBefore(this._wrapper.firstChild, this._wrapper); - } - if (this._wrapper.parentNode) this._wrapper.parentNode.removeChild(this._wrapper); - this._wrapper = null; - } + teardownCameraWrapper(this, this._wrapper); + this._wrapper = null; this._camera = null; } diff --git a/packages/polycss/src/elements/PolyPerspectiveCameraElement.ts b/packages/polycss/src/elements/PolyPerspectiveCameraElement.ts index 647c9a882..5af375ef0 100644 --- a/packages/polycss/src/elements/PolyPerspectiveCameraElement.ts +++ b/packages/polycss/src/elements/PolyPerspectiveCameraElement.ts @@ -18,6 +18,7 @@ import { createPolyPerspectiveCamera, type PolyPerspectiveCameraHandle, } from "../api/createPolyCamera"; +import { mountCameraWrapper, teardownCameraWrapper } from "./cameraWrapper"; import { parseNumber, parseVec3 } from "./parseAttr"; const ELEMENT_BASE: typeof HTMLElement = @@ -63,26 +64,12 @@ export class PolyPerspectiveCameraElement extends ELEMENT_BASE { if (this._camera) return; const opts = this._readOptions(); this._camera = createPolyPerspectiveCamera(opts); - this._wrapper = this.ownerDocument!.createElement("div"); - this._wrapper.className = "polycss-camera"; - this._wrapper.style.perspective = this._camera.perspectiveStyle; - // Move existing children into the wrapper - while (this.firstChild) { - this._wrapper.appendChild(this.firstChild); - } - this.appendChild(this._wrapper); - this.dispatchEvent(new CustomEvent("polycss:camera-ready", { bubbles: false })); + this._wrapper = mountCameraWrapper(this, this._camera.perspectiveStyle); } private _teardown(): void { - // Move children back out of the wrapper - if (this._wrapper) { - while (this._wrapper.firstChild) { - this.insertBefore(this._wrapper.firstChild, this._wrapper); - } - if (this._wrapper.parentNode) this._wrapper.parentNode.removeChild(this._wrapper); - this._wrapper = null; - } + teardownCameraWrapper(this, this._wrapper); + this._wrapper = null; this._camera = null; } diff --git a/packages/polycss/src/elements/PolyPointerControlsElement.ts b/packages/polycss/src/elements/PolyPointerControlsElement.ts new file mode 100644 index 000000000..c8ebba2b5 --- /dev/null +++ b/packages/polycss/src/elements/PolyPointerControlsElement.ts @@ -0,0 +1,128 @@ +/** + * Shared base custom element for `` and + * ``. + */ +import { PolySceneElement } from "./PolySceneElement"; +import type { PolySceneHandle } from "../api/createPolyScene"; +import type { PolyControlsBaseOptions, PolyControlsHandle } from "../api/controls/common"; +import { parseNumber, parseBoolAttr, parseInvert, parseAxis } from "./parseAttr"; + +const ELEMENT_BASE: typeof HTMLElement = + typeof HTMLElement !== "undefined" + ? HTMLElement + : (class {} as unknown as typeof HTMLElement); + +const OBSERVED_ATTRS = [ + "drag", + "wheel", + "dolly", + "min-distance", + "max-distance", + "invert", + "zoom-min", + "zoom-max", + "animate-speed", + "animate-axis", + "animate-pause-on-interaction", +] as const; + +export abstract class PolyPointerControlsElement extends ELEMENT_BASE { + static get observedAttributes(): string[] { + return [...OBSERVED_ATTRS]; + } + + private _controls: PolyControlsHandle | null = null; + + protected abstract _createControls( + scene: PolySceneHandle, + options: PolyControlsBaseOptions, + ): PolyControlsHandle; + + getControls(): PolyControlsHandle | null { + return this._controls; + } + + private _readAnimate(): PolyControlsBaseOptions["animate"] | undefined { + const speed = parseNumber(this.getAttribute("animate-speed")); + const axis = parseAxis(this.getAttribute("animate-axis")); + const pauseAttr = this.getAttribute("animate-pause-on-interaction"); + const hasAny = + this.hasAttribute("animate-speed") || + this.hasAttribute("animate-axis") || + this.hasAttribute("animate-pause-on-interaction"); + if (!hasAny) return undefined; + return { + ...(speed !== undefined ? { speed } : {}), + ...(axis !== undefined ? { axis } : {}), + ...(pauseAttr !== null ? { pauseOnInteraction: parseBoolAttr(pauseAttr) } : {}), + }; + } + + private _readOptions(): PolyControlsBaseOptions { + const opts: PolyControlsBaseOptions = {}; + const drag = parseBoolAttr(this.getAttribute("drag")); + if (drag !== undefined) opts.drag = drag; + const wheel = parseBoolAttr(this.getAttribute("wheel")); + if (wheel !== undefined) opts.wheel = wheel; + if (this.hasAttribute("dolly")) opts.dolly = true; + const minDistance = parseNumber(this.getAttribute("min-distance")); + if (minDistance !== undefined) opts.minDistance = minDistance; + const maxDistance = parseNumber(this.getAttribute("max-distance")); + if (maxDistance !== undefined) opts.maxDistance = maxDistance; + const invert = parseInvert(this.getAttribute("invert")); + if (invert !== undefined) opts.invert = invert; + const zoomMin = parseNumber(this.getAttribute("zoom-min")); + const zoomMax = parseNumber(this.getAttribute("zoom-max")); + if (zoomMin !== undefined) opts.minZoom = zoomMin; + if (zoomMax !== undefined) opts.maxZoom = zoomMax; + opts.animate = this._readAnimate() ?? false; + return opts; + } + + private _findScene(): PolySceneElement | null { + let node: Node | null = this.parentNode; + while (node) { + if (node instanceof PolySceneElement) return node; + node = node.parentNode; + } + return null; + } + + private _attach(): void { + if (this._controls) return; + const sceneEl = this._findScene(); + const handle = sceneEl?.getScene(); + if (!handle) { + if (sceneEl) { + const onReady = (): void => { + sceneEl.removeEventListener("polycss:scene-ready", onReady); + this._attach(); + }; + sceneEl.addEventListener("polycss:scene-ready", onReady); + } + return; + } + this._controls = this._createControls(handle, this._readOptions()); + } + + connectedCallback(): void { + this._attach(); + } + + disconnectedCallback(): void { + if (this._controls) { + this._controls.destroy(); + this._controls = null; + } + } + + attributeChangedCallback( + _name: string, + oldValue: string | null, + newValue: string | null, + ): void { + if (oldValue === newValue) return; + if (!this._controls) return; + this._controls.update(this._readOptions()); + } +} diff --git a/packages/polycss/src/elements/PolyPolygonElement.ts b/packages/polycss/src/elements/PolyPolygonElement.ts index 5a9b85e47..05ad1f73d 100644 --- a/packages/polycss/src/elements/PolyPolygonElement.ts +++ b/packages/polycss/src/elements/PolyPolygonElement.ts @@ -11,6 +11,7 @@ import type { ParseResult, Polygon, Vec2, Vec3 } from "@layoutit/polycss-core"; import type { PolyMeshHandle } from "../api/createPolyScene"; import type { PolySceneElement } from "./PolySceneElement"; +import { parseVec3 } from "./parseAttr"; const ELEMENT_BASE: typeof HTMLElement = typeof HTMLElement !== "undefined" @@ -36,15 +37,6 @@ function parseJsonOrNull(value: string | null): T | null { } } -function parseVec3(value: string | null): Vec3 | undefined { - if (!value) return undefined; - const parts = value.split(",").map((p) => parseFloat(p.trim())); - if (parts.length !== 3 || parts.some((p) => !Number.isFinite(p))) { - return undefined; - } - return [parts[0], parts[1], parts[2]]; -} - function parseScale(value: string | null): number | Vec3 | undefined { if (!value) return undefined; if (!value.includes(",")) { diff --git a/packages/polycss/src/elements/PolySceneElement.ts b/packages/polycss/src/elements/PolySceneElement.ts index c09eeaf1d..21412732d 100644 --- a/packages/polycss/src/elements/PolySceneElement.ts +++ b/packages/polycss/src/elements/PolySceneElement.ts @@ -37,6 +37,7 @@ import { type PolyOrthographicCameraHandle, type PolyPerspectiveCameraHandle, } from "../api/createPolyCamera"; +import { parseNumber, parseVec3 } from "./parseAttr"; const ELEMENT_BASE: typeof HTMLElement = typeof HTMLElement !== "undefined" @@ -64,26 +65,11 @@ const OBSERVED_ATTRS = [ "auto-center", ] as const; -function parseNumber(value: string | null): number | undefined { - if (value == null) return undefined; - const n = parseFloat(value); - return Number.isFinite(n) ? n : undefined; -} - function parsePerspective(value: string | null): number | false | undefined { if (value === "false") return false; return parseNumber(value); } -function parseVec3(value: string | null): Vec3 | undefined { - if (!value) return undefined; - const parts = value.split(",").map((p) => parseFloat(p.trim())); - if (parts.length !== 3 || parts.some((p) => !Number.isFinite(p))) { - return undefined; - } - return [parts[0], parts[1], parts[2]]; -} - function parseTextureLighting(value: string | null): PolyTextureLightingMode | undefined { if (value === "baked" || value === "dynamic") return value; return undefined; diff --git a/packages/polycss/src/elements/PolyShapeElements.ts b/packages/polycss/src/elements/PolyShapeElements.ts index e23245ba8..62bc7dcb1 100644 --- a/packages/polycss/src/elements/PolyShapeElements.ts +++ b/packages/polycss/src/elements/PolyShapeElements.ts @@ -23,10 +23,11 @@ import { cylinderPolygons, conePolygons, torusPolygons, - computeSceneBbox, + recenterPolygons as recenter, } from "@layoutit/polycss-core"; import type { PolyMeshHandle, PolySceneHandle } from "../api/createPolyScene"; import type { PolySceneElement } from "./PolySceneElement"; +import { parseVec3 } from "./parseAttr"; const ELEMENT_BASE: typeof HTMLElement = typeof HTMLElement !== "undefined" @@ -52,22 +53,7 @@ function strAttr(el: HTMLElement, name: string, fallback?: string): string | und } function parseVec3Attr(el: HTMLElement, name: string): Vec3 | undefined { - const raw = el.getAttribute(name); - if (!raw) return undefined; - const parts = raw.split(",").map((s) => parseFloat(s.trim())); - if (parts.length !== 3 || parts.some((p) => !Number.isFinite(p))) return undefined; - return [parts[0], parts[1], parts[2]]; -} - -function recenter(polygons: Polygon[]): Polygon[] { - if (polygons.length === 0) return polygons; - const bbox = computeSceneBbox(polygons); - const cx = (bbox.min[0] + bbox.max[0]) / 2; - const cy = (bbox.min[1] + bbox.max[1]) / 2; - const cz = (bbox.min[2] + bbox.max[2]) / 2; - if (cx === 0 && cy === 0 && cz === 0) return polygons; - const shift = (v: Vec3): Vec3 => [v[0] - cx, v[1] - cy, v[2] - cz]; - return polygons.map((p) => ({ ...p, vertices: p.vertices.map(shift) })); + return parseVec3(el.getAttribute(name)); } /** diff --git a/packages/polycss/src/elements/cameraWrapper.ts b/packages/polycss/src/elements/cameraWrapper.ts new file mode 100644 index 000000000..a37eb9318 --- /dev/null +++ b/packages/polycss/src/elements/cameraWrapper.ts @@ -0,0 +1,29 @@ +/** + * Shared `.polycss-camera` wrapper DOM mount/teardown helpers for custom + * camera elements (``, ``). + */ +export function mountCameraWrapper( + host: HTMLElement, + perspectiveStyle: string, +): HTMLDivElement { + const wrapper = host.ownerDocument!.createElement("div"); + wrapper.className = "polycss-camera"; + wrapper.style.perspective = perspectiveStyle; + while (host.firstChild) { + wrapper.appendChild(host.firstChild); + } + host.appendChild(wrapper); + host.dispatchEvent(new CustomEvent("polycss:camera-ready", { bubbles: false })); + return wrapper; +} + +export function teardownCameraWrapper( + host: HTMLElement, + wrapper: HTMLElement | null, +): void { + if (!wrapper) return; + while (wrapper.firstChild) { + host.insertBefore(wrapper.firstChild, wrapper); + } + if (wrapper.parentNode) wrapper.parentNode.removeChild(wrapper); +} diff --git a/packages/polycss/src/render/atlas/stableTriangle.ts b/packages/polycss/src/render/atlas/stableTriangle.ts index be106012c..99ba541d6 100644 --- a/packages/polycss/src/render/atlas/stableTriangle.ts +++ b/packages/polycss/src/render/atlas/stableTriangle.ts @@ -412,114 +412,6 @@ export function updateStableTriangleElementsStreaming( return true; } -export function captureStableTriangleTransformFrame( - rendered: RenderedPoly[], - polygons: Polygon[], - frame: SolidTriangleFrame, - options: RenderTextureAtlasOptions = {}, -): boolean { - const textureLighting = options.textureLighting ?? "baked"; - const internalOptions = options as InternalRenderTextureAtlasOptions; - const optimizeTriangleStyle = - internalOptions.optimizeStableTriangleStyle === true && - textureLighting === "baked"; - if (!optimizeTriangleStyle) return false; - if (internalOptions.stableTriangleColorPolicy === "adaptive") return false; - if (rendered.length !== frame.polygonCount || polygons.length !== frame.polygonCount) return false; - if (frame.vertices.length < frame.polygonCount * 9) return false; - - const stableTriangleDebug = internalOptions.stableTriangleDebug; - const stableTriangleUpdateMode = internalOptions.stableTriangleUpdateMode ?? - (stableTriangleDebug === "plan-only" || stableTriangleDebug === "transform-only" - ? stableTriangleDebug - : "full"); - if (stableTriangleUpdateMode === "color-only") return false; - - const matrixDecimals = stableTriangleMatrixDecimals(internalOptions.stableTriangleMatrixDecimals); - const colorState = stableTriangleColorState(internalOptions); - const tile = options.tileSize ?? DEFAULT_TILE; - const elev = options.layerElevation ?? tile; - const doc = options.doc ?? (typeof document !== "undefined" ? document : null); - const solidTrianglePrimitive = doc - ? resolveSolidTrianglePrimitive(doc, options.strategies) ?? "border" - : "border"; - - for (let i = 0; i < rendered.length; i++) { - const item = rendered[i]; - const polygon = polygons[i]; - if ( - item.kind !== "triangle" || - item.polygonIndex !== i || - !polygon || - polygon.vertices.length !== 3 || - polygon.texture || - polygon.material?.texture - ) { - return false; - } - } - - const values = frame.vertices; - const seamBleedEdges = buildStableTriangleSeamEdges(polygons, options); - for (let i = 0; i < rendered.length; i++) { - const element = rendered[i].element as SolidTriangleElement; - const polygon = polygons[i]!; - const offset = i * 9; - const p0x = values[offset + 1]! * tile; - const p0y = values[offset]! * tile; - const p0z = values[offset + 2]! * elev; - const p1x = values[offset + 4]! * tile; - const p1y = values[offset + 3]! * tile; - const p1z = values[offset + 5]! * elev; - const p2x = values[offset + 7]! * tile; - const p2y = values[offset + 6]! * tile; - const p2z = values[offset + 8]! * elev; - const plan = computeSolidTrianglePlanFromCssPoints( - polygon, - i, - stableTriangleSeamOptions(i, seamBleedEdges, options), - { - basis: element.__polycssSolidTriangleBasis, - matrixDecimals, - primitive: solidTrianglePrimitive, - color: frame.colors?.[i], - includeColor: stableTriangleUpdateMode !== "plan-only" && - stableTriangleUpdateMode !== "transform-only" && - shouldComputeStableTriangleColor( - element, - i, - optimizeTriangleStyle, - stableTriangleDebug, - internalOptions.stableTriangleColorPolicy, - colorState, - ), - }, - p0x, - p0y, - p0z, - p1x, - p1y, - p1z, - p2x, - p2y, - p2z, - ); - if (!plan) { - hideSolidTriangleElement(element); - continue; - } - if (stableTriangleUpdateMode === "plan-only") { - continue; - } else if (stableTriangleUpdateMode === "transform-only") { - applySolidTriangleElementTransformOnly(element, plan); - } else { - applySolidTriangleElementFast(element, plan, colorState); - } - } - - return true; -} - export function renderPolygonsWithStableTriangles( polygons: Polygon[], options: RenderTextureAtlasOptions = {}, diff --git a/packages/polycss/src/render/polyLeafDescriptor.ts b/packages/polycss/src/render/polyLeafDescriptor.ts new file mode 100644 index 000000000..afda0b4a6 --- /dev/null +++ b/packages/polycss/src/render/polyLeafDescriptor.ts @@ -0,0 +1,212 @@ +/** + * Shared standalone `` leaf-descriptor helpers. + * + * Used by `@layoutit/polycss-react` (`Poly.tsx`) and `@layoutit/polycss-vue` + * (`Poly.ts`) so direct-texture UV positioning, SSR fallback style assembly, + * wrapper transforms, and DOM leaf style/data-attr reflection live in one place. + */ +import type { + PolyMaterial, + PolyTextureImageRendering, + Polygon, + Vec2, + Vec3, +} from "@layoutit/polycss-core"; +import { formatCssLength } from "@layoutit/polycss-core"; +import type { TextureAtlasPlan } from "./textureAtlas"; + +const DIRECT_TEXTURE_CSS_DECIMALS = 4; + +export interface PolyUvRect { + u0: number; + u1: number; + v0: number; + v1: number; +} + +export function isAxisAlignedRectUVs(uvs: Vec2[]): PolyUvRect | null { + if (uvs.length !== 4) return null; + const us = [...new Set(uvs.map((uv) => uv[0]))].sort((a, b) => a - b); + const vs = [...new Set(uvs.map((uv) => uv[1]))].sort((a, b) => a - b); + if (us.length !== 2 || vs.length !== 2) return null; + const corners = new Set([ + `${us[0]},${vs[0]}`, + `${us[0]},${vs[1]}`, + `${us[1]},${vs[0]}`, + `${us[1]},${vs[1]}`, + ]); + for (const uv of uvs) { + if (!corners.has(`${uv[0]},${uv[1]}`)) return null; + } + return { u0: us[0]!, u1: us[1]!, v0: vs[0]!, v1: vs[1]! }; +} + +export function cssPropToCamel(prop: string): string { + if (prop.startsWith("--")) return prop; + if (prop.startsWith("-webkit-")) { + return "Webkit" + prop.slice(7).replace(/-([a-z])/g, (_, c: string) => c.toUpperCase()); + } + return prop.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase()); +} + +export function readElementStyleRecord( + el: HTMLElement, + options?: { camelCase?: boolean }, +): Record { + const camelCase = options?.camelCase ?? false; + const out: Record = {}; + const style = el.style; + for (let i = 0; i < style.length; i += 1) { + const prop = style[i]!; + const val = style.getPropertyValue(prop); + if (val) out[camelCase ? cssPropToCamel(prop) : prop] = val; + } + return out; +} + +export function readElementDataAttrs(el: HTMLElement): Record { + const out: Record = {}; + for (const attr of Array.from(el.attributes)) { + if (attr.name.startsWith("data-")) { + out[attr.name] = attr.value; + } + } + return out; +} + +export interface DirectMaterialLeafDescriptor { + className: string | undefined; + style: Record; + dataAttrs: Record; +} + +export function buildDirectMaterialLeafDescriptor(opts: { + plan: TextureAtlasPlan; + material: PolyMaterial; + uvRect: PolyUvRect; + className?: string; + pointerEvents?: "auto" | "none"; + imageRendering?: PolyTextureImageRendering; +}): DirectMaterialLeafDescriptor { + const { plan, material, uvRect, className, pointerEvents = "auto", imageRendering } = opts; + const { u0, u1, v0, v1 } = uvRect; + const du = u1 - u0; + const dv = v1 - v0; + const sourceW = 1 / du; + const sourceH = 1 / dv; + const vMax = Math.max(v0, v1); + const offsetX = u0 / du; + const offsetY = (1 - vMax) / dv; + + const style: Record = { + transform: `matrix3d(${plan.canonicalMatrix})`, + backgroundImage: `url(${material.texture})`, + backgroundSize: `${formatCssLength(sourceW, DIRECT_TEXTURE_CSS_DECIMALS)} ${formatCssLength(sourceH, DIRECT_TEXTURE_CSS_DECIMALS)}`, + backgroundPosition: `${formatCssLength(-offsetX, DIRECT_TEXTURE_CSS_DECIMALS)} ${formatCssLength(-offsetY, DIRECT_TEXTURE_CSS_DECIMALS)}`, + backgroundRepeat: "no-repeat", + imageRendering: imageRendering === "pixelated" ? "pixelated" : undefined, + pointerEvents: pointerEvents === "none" ? "none" : undefined, + }; + + const polygonDataAttrs = plan.polygon.data + ? Object.fromEntries( + Object.entries(plan.polygon.data).map(([k, v]) => [`data-${k}`, String(v)]), + ) + : {}; + + const dataAttrs: Record = { + "data-poly-index": String(plan.index), + "data-polycss-leaf": "polygon", + "data-polycss-texture-backend": "image", + "data-polycss-texture-ready": "true", + "data-polycss-texture-image-rendering": imageRendering ?? "auto", + "data-polycss-texture-projection": "affine", + "data-polycss-texture-lighting": "source", + "data-polycss-double-sided": plan.polygon.doubleSided ? "true" : undefined, + ...polygonDataAttrs, + }; + + return { + className: className?.trim() || undefined, + style, + dataAttrs, + }; +} + +export interface FallbackLeafDescriptor { + tag: "b" | "s"; + className: string | undefined; + style: Record; + dataAttrs: Record; +} + +export function buildFallbackLeafDescriptor(opts: { + plan: TextureAtlasPlan; + polygon: Polygon; + isTextured: boolean; + className?: string; + pointerEvents?: "auto" | "none"; +}): FallbackLeafDescriptor { + const { plan, polygon, isTextured, className, pointerEvents } = opts; + const tag = !isTextured && polygon.vertices.length === 4 ? "b" : "s"; + const style: Record = { + transform: `matrix3d(${plan.canonicalMatrix})`, + ...(!isTextured ? { backgroundColor: plan.shadedColor } : {}), + pointerEvents: pointerEvents === "none" ? "none" : undefined, + }; + const dataAttrs: Record = { + "data-poly-index": "0", + "data-polycss-leaf": "polygon", + "data-polycss-double-sided": polygon.doubleSided ? "true" : undefined, + }; + return { + tag, + className: className?.trim() || undefined, + style, + dataAttrs, + }; +} + +export function buildPolyWrapperTransform(opts: { + position?: Vec3; + scale?: number | Vec3; + rotation?: Vec3; +}): string | undefined { + const { position, scale, rotation } = opts; + const parts: string[] = []; + if (position) { + parts.push(`translate3d(${position[0]}px, ${position[1]}px, ${position[2]}px)`); + } + if (scale !== undefined) { + if (typeof scale === "number") { + if (scale !== 1) parts.push(`scale3d(${scale}, ${scale}, ${scale})`); + } else { + parts.push(`scale3d(${scale[0]}, ${scale[1]}, ${scale[2]})`); + } + } + if (rotation) { + if (rotation[0]) parts.push(`rotateX(${rotation[0]}deg)`); + if (rotation[1]) parts.push(`rotateY(${rotation[1]}deg)`); + if (rotation[2]) parts.push(`rotateZ(${rotation[2]}deg)`); + } + return parts.length > 0 ? parts.join(" ") : undefined; +} + +/** + * Re-apply raw engine cssText when a leaf uses CSS `border-shape`, which + * frameworks and happy-dom can strip during style object syncing. + */ +export function syncLeafBorderShapeStyle( + el: HTMLElement | null, + rawBorderShape: string, + rawLeafCssText: string, + pointerEvents?: "auto" | "none", + userStyle?: Record, +): void { + if (!el || !rawBorderShape) return; + el.setAttribute("style", rawLeafCssText); + if (pointerEvents === "none") el.style.pointerEvents = "none"; + if (userStyle && typeof userStyle === "object") { + Object.assign(el.style, userStyle); + } +} diff --git a/packages/polycss/src/render/voxelRenderer.ts b/packages/polycss/src/render/voxelRenderer.ts index 49f3f2924..13e2e1035 100644 --- a/packages/polycss/src/render/voxelRenderer.ts +++ b/packages/polycss/src/render/voxelRenderer.ts @@ -13,6 +13,7 @@ import { parsePureColor, PROJECTIVE_QUAD_BLEED, resolveProjectiveQuadGuards, + rgbToHex, rotateVec3, rotateVec3InWrapperCssFrame, shadePolygon, @@ -368,12 +369,6 @@ function canonicalBrushColor(input: string | undefined): string { return rgbToHex(rgb); } -function rgbToHex({ r, g, b }: RGB): string { - const f = (n: number) => - Math.round(Math.max(0, Math.min(255, n))).toString(16).padStart(2, "0"); - return `#${f(r)}${f(g)}${f(b)}`; -} - function clampChannel(value: number): number { return Math.round(Math.max(0, Math.min(255, value))); } diff --git a/packages/polycss/src/runtime.ts b/packages/polycss/src/runtime.ts index 929c3653f..7642ab77c 100644 --- a/packages/polycss/src/runtime.ts +++ b/packages/polycss/src/runtime.ts @@ -68,6 +68,12 @@ export type { export { createSelect } from "./api/createSelect"; export type { PolySelectOptions, PolySelectionHandle } from "./api/createSelect"; +export { createSelectionController } from "./api/controls/selectionEngine"; +export type { + SelectionController, + SelectionControllerOptions, +} from "./api/controls/selectionEngine"; + export { createTransformControls } from "./api/createTransformControls"; export type { PolyTransformControlsHandle, @@ -75,6 +81,93 @@ export type { PolyTransformControlsOptions, } from "./api/createTransformControls"; +export { + RING_MASK_INNER_RATIO, + RING_MASK_OUTER_RATIO, + attachDeclarativeGizmoFallback, + buildArrowGizmoPolygons, + buildPlaneGizmoPolygons, + buildRingGizmoPolygons, + buildTransformGizmoEntries, + computeGizmoWrapperPositionCss, + gizmoAlphaForKey, + isArrowSpecVisible, + isPlaneSpecVisible, + isRingSpecVisible, + startAxisDrag, + startDeclarativeArrowDrag, + startDeclarativePlaneDrag, + startDeclarativeRingDrag, + startPlaneDrag, + startRingDrag, + swallowNextClick, +} from "./api/controls/gizmoEngine"; +export type { + AxisDragParams, + BuildTransformGizmoEntriesOptions, + DeclarativeGizmoCallbacks, + DeclarativeGizmoDragState, + DeclarativeGizmoObjectChangeEvent, + DeclarativeGizmoTarget, + GizmoArrowSpec, + GizmoMode, + GizmoPlaneSpec, + GizmoPolygonEntry, + GizmoRingSpec, + GizmoVisibility, + PlaneDragParams, + RingDragParams, + TransformGizmoCache, + TransformGizmoEntries, +} from "./api/controls/gizmoEngine"; + +export { + buildPolyPointerEvent, + createMeshElementRegistry, + pointInMeshElement, +} from "./api/meshHitTest"; +export type { + MeshElementRegistry, + SynthesizedPolyPointerEvent, +} from "./api/meshHitTest"; + +export { + adaptFallbackCamera, + applyCameraTransformDirect, + bindCameraStoreSync, + createLiveRuntimeCamera, + observeViewportHeight, + writeCameraSnapshotAttrs, +} from "./api/cameraSnapshotAttrs"; +export type { + CameraSyncStoreLike, + LiveRuntimeCameraOptions, + WriteCameraSnapshotAttrsOptions, +} from "./api/cameraSnapshotAttrs"; + +export { + clearOwnedDomNodes, + renderStandaloneMeshIntoWrapper, + restoreVoxelMeshClass, +} from "./api/standaloneMesh"; +export type { StandaloneMeshMountResult } from "./api/standaloneMesh"; + +export { + buildDirectMaterialLeafDescriptor, + buildFallbackLeafDescriptor, + buildPolyWrapperTransform, + cssPropToCamel, + isAxisAlignedRectUVs, + readElementDataAttrs, + readElementStyleRecord, + syncLeafBorderShapeStyle, +} from "./render/polyLeafDescriptor"; +export type { + DirectMaterialLeafDescriptor, + FallbackLeafDescriptor, + PolyUvRect, +} from "./render/polyLeafDescriptor"; + // ── Low-level atlas & voxel renderers ───────────────────────────── export { buildAtlasPages, @@ -143,5 +236,12 @@ export type { PolyTextureRenderStats, } from "./render/renderStats"; +/** + * @internal Adapter-plumbing exports below are consumed by the lockstep + * `@layoutit/polycss-react` and `@layoutit/polycss-vue` packages and are not + * part of the public semver-stable imperative API surface. + */ +export { setInlineStyleProperty } from "./render/atlas/paintDefaults"; + // ── Style injection ─────────────────────────────────────────────── export { injectPolyBaseStyles } from "./styles/styles"; diff --git a/packages/polycss/src/three.ts b/packages/polycss/src/three.ts index bf098f501..57bf3ad7d 100644 --- a/packages/polycss/src/three.ts +++ b/packages/polycss/src/three.ts @@ -13,13 +13,13 @@ import type { import { createPolyOrthographicCamera, createPolyPerspectiveCamera, - createPolyScene, -} from "./index"; +} from "./api/createPolyCamera"; +import { createPolyScene } from "./api/createPolyScene"; import type { PolyMeshTransform, PolySceneHandle, PolySceneOptions, -} from "./index"; +} from "./api/createPolyScene"; export { AmbientLight, diff --git a/packages/polycss/tsup.config.ts b/packages/polycss/tsup.config.ts index 9a0ba1a91..ac58f6466 100644 --- a/packages/polycss/tsup.config.ts +++ b/packages/polycss/tsup.config.ts @@ -7,9 +7,7 @@ export default createLibraryConfig({ elements: "src/elements/index.ts", three: "src/three.ts", }, - // esbuild drops `export * from "@layoutit/polycss-core"` when splitting: true - // with an external package, stripping all core re-exports from dist/index.js. - splitting: false, + splitting: true, tsconfig: "tsconfig.build.json", external: ["@layoutit/polycss-core", "@layoutit/polycss-core/three"], }); diff --git a/packages/react/src/camera/useCamera.ts b/packages/react/src/camera/useCamera.ts index d06e66172..044f2d558 100644 --- a/packages/react/src/camera/useCamera.ts +++ b/packages/react/src/camera/useCamera.ts @@ -1,12 +1,10 @@ import { useRef, useCallback, useEffect, useMemo } from "react"; -import { - buildPolyCameraSceneTransform, - capturePolyCameraSnapshot, -} from "@layoutit/polycss-core"; import type { CameraState, CameraHandle, PolyCameraProjection, Vec3 } from "@layoutit/polycss-core"; import { - createPolyOrthographicCamera, - createPolyPerspectiveCamera, + applyCameraTransformDirect, + bindCameraStoreSync, + createLiveRuntimeCamera, + writeCameraSnapshotAttrs, type PolyOrthographicCameraHandle, type PolyPerspectiveCameraHandle, type PolySceneHandle, @@ -35,24 +33,6 @@ export interface UseCameraResult { applyTransformDirect: () => void; } -function writeCameraSnapshotAttrs( - el: HTMLElement | null, - camera: CameraHandle, - projection: PolyCameraProjection | undefined, - perspectiveStyle: string | undefined, -): void { - if (!el) return; - const snapshot = capturePolyCameraSnapshot(camera, { projection, perspectiveStyle }); - el.dataset.polycssCameraProjection = snapshot.projection; - el.dataset.polycssCameraPerspective = snapshot.perspectiveStyle; - el.dataset.polycssCameraAppliedPerspective = snapshot.appliedPerspectiveStyle; - el.dataset.polycssCameraZoom = String(snapshot.state.zoom); - el.dataset.polycssCameraDistance = String(snapshot.state.distance); - el.dataset.polycssCameraRotX = String(snapshot.state.rotX); - el.dataset.polycssCameraRotY = String(snapshot.state.rotY); - el.dataset.polycssCameraTarget = snapshot.state.target.join(","); -} - export function usePolyCamera(options: UseCameraOptions): UseCameraResult { const projectionRef = useRef(options.projection ?? "orthographic"); projectionRef.current = options.projection ?? "orthographic"; @@ -64,116 +44,42 @@ export function usePolyCamera(options: UseCameraOptions): UseCameraResult { const handleRef = useRef(null); if (!handleRef.current) { - const baseOpts = { + handleRef.current = createLiveRuntimeCamera({ zoom: options.zoom, target: options.target, rotX: options.rotX, rotY: options.rotY, distance: options.distance, - }; - const inner = - options.projection === "perspective" - ? createPolyPerspectiveCamera({ - ...baseOpts, - perspective: parseFloat(perspectiveStyleRef.current) || 32000, - }) - : createPolyOrthographicCamera(baseOpts); - // Wrap with live projection/perspectiveStyle getters so prop updates to - // `perspective` flow into createPolyScene's `applyCamera()`. - handleRef.current = { - get state() { return inner.state; }, - update(next: Partial) { inner.update(next); }, - getStyle(input) { return inner.getStyle(input); }, - subscribe(listener) { return inner.subscribe(listener); }, - get type() { return projectionRef.current as "perspective" & "orthographic"; }, - get perspectiveStyle() { return perspectiveStyleRef.current as string & "none"; }, - } as PolyPerspectiveCameraHandle | PolyOrthographicCameraHandle; + initialProjection: options.projection, + initialPerspectiveStyle: perspectiveStyleRef.current, + getProjection: () => projectionRef.current, + getPerspectiveStyle: () => perspectiveStyleRef.current, + }); } const sceneElRef = useRef(null); const cameraElRef = useRef(null); const runtimeSceneRef = useRef(null); - const store = useMemo( - () => createSceneStore(handleRef.current!.state), - [], - ); + const store = useMemo(() => createSceneStore(handleRef.current!.state), []); - // Sync camera handle mutations (from runtime controls or direct handle.update) - // back into the reactive store, AND sync direct store.setState({ cameraState }) - // mutations back into the camera handle + runtime scene (for receiver shadow - // camera-boundary crossings and external store drivers). - useEffect(() => { - const handle = handleRef.current!; - let syncing = false; - const unsubHandle = handle.subscribe(() => { - if (syncing) return; - syncing = true; - try { - store.updateCameraFromRef(handle); - } finally { - syncing = false; - } - }); - const unsubStore = store.subscribe(() => { - if (syncing) return; - const next = store.getState().cameraState; - const cur = handle.state; - const changed = - next.rotX !== cur.rotX || - next.rotY !== cur.rotY || - next.zoom !== cur.zoom || - next.distance !== cur.distance || - next.target[0] !== cur.target[0] || - next.target[1] !== cur.target[1] || - next.target[2] !== cur.target[2]; - if (!changed) return; - syncing = true; - try { - handle.update(next); - runtimeSceneRef.current?.applyCamera(); - } finally { - syncing = false; - } - }); - return () => { - unsubHandle(); - unsubStore(); - }; - }, [store]); + useEffect( + () => bindCameraStoreSync(handleRef.current!, store, () => runtimeSceneRef.current), + [store], + ); - // Apply camera transform directly to scene element (bypasses React). - // Delegates to the mounted runtime scene when present so voxel culling and - // receiver-shadow camera crossings stay in sync; falls back to direct DOM - // transform for standalone camera tests without a . const applyTransformDirect = useCallback(() => { - const handle = handleRef.current!; - const runtimeScene = runtimeSceneRef.current; - if (runtimeScene) { - runtimeScene.applyCamera(); - writeCameraSnapshotAttrs( - cameraElRef.current, - handle, - projectionRef.current, - perspectiveStyleRef.current, - ); - return; - } - const el = sceneElRef.current; - if (el) { - el.style.transform = buildPolyCameraSceneTransform(handle.state, { - autoCenterOffset: store.getState().autoCenterOffset, - }); - } - writeCameraSnapshotAttrs( - cameraElRef.current, - handle, - projectionRef.current, - perspectiveStyleRef.current, - ); + applyCameraTransformDirect({ + runtimeScene: runtimeSceneRef.current, + sceneEl: sceneElRef.current, + cameraEl: cameraElRef.current, + handle: handleRef.current!, + autoCenterOffset: store.getState().autoCenterOffset, + projection: projectionRef.current, + perspectiveStyle: perspectiveStyleRef.current, + }); }, [store]); - // Sync prop changes to camera handle useEffect(() => { const handle = handleRef.current!; const next: Partial = {}; @@ -188,12 +94,10 @@ export function usePolyCamera(options: UseCameraOptions): UseCameraResult { store.updateCameraFromRef(handle); store.notifyAll(); } else { - writeCameraSnapshotAttrs( - cameraElRef.current, - handle, - projectionRef.current, - perspectiveStyleRef.current, - ); + writeCameraSnapshotAttrs(cameraElRef.current, handle, { + projection: projectionRef.current, + perspectiveStyle: perspectiveStyleRef.current, + }); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [ diff --git a/packages/react/src/controls/PolyMapControls.tsx b/packages/react/src/controls/PolyMapControls.tsx index 5a27b312d..b1f9a0a10 100644 --- a/packages/react/src/controls/PolyMapControls.tsx +++ b/packages/react/src/controls/PolyMapControls.tsx @@ -2,90 +2,16 @@ * — thin React wrapper over `createPolyMapControls` * from `@layoutit/polycss/runtime`. */ -import { useEffect, useRef } from "react"; +import { createPolyMapControls } from "@layoutit/polycss/runtime"; import { - createPolyMapControls, - type PolyCameraControlTarget, - type PolyMapControlsHandle, -} from "@layoutit/polycss/runtime"; -import { useCameraContext } from "../camera/context"; -import type { SharedControlsProps, PolyControlsCamera } from "./sharedControls"; + usePointerControls, + type SharedControlsProps, + type PolyControlsCamera, +} from "./sharedControls"; export type { PolyControlsCamera as PolyMapControlsCamera }; export interface PolyMapControlsProps extends SharedControlsProps {} -export function PolyMapControls({ - drag = true, - wheel = true, - dolly = false, - invert = false, - minZoom = 0.1, - maxZoom = 10, - minDistance = 0, - maxDistance = Infinity, - animate = false, - onChange, - onInteractionStart, - onInteractionEnd, -}: PolyMapControlsProps): null { - const { store, cameraRef, runtimeCameraRef, cameraElRef, applyTransformDirect } = useCameraContext(); - const controlsRef = useRef(null); - - const onChangeRef = useRef(onChange); - const onStartRef = useRef(onInteractionStart); - const onEndRef = useRef(onInteractionEnd); - onChangeRef.current = onChange; - onStartRef.current = onInteractionStart; - onEndRef.current = onInteractionEnd; - - useEffect(() => { - const el = cameraElRef.current; - if (!el) return; - const target: PolyCameraControlTarget = { - host: el, - cameraEl: el, - camera: (runtimeCameraRef?.current ?? cameraRef.current) as PolyCameraControlTarget["camera"], - applyCamera: () => { - applyTransformDirect(); - store.updateCameraFromRef(cameraRef.current); - }, - }; - const controls = createPolyMapControls(target, { - drag, - wheel, - dolly, - invert, - minZoom, - maxZoom, - minDistance, - maxDistance, - animate, - }); - controls.addEventListener("change", (ev) => onChangeRef.current?.(ev.camera)); - controls.addEventListener("start", (ev) => onStartRef.current?.(ev.camera)); - controls.addEventListener("end", (ev) => onEndRef.current?.(ev.camera)); - controlsRef.current = controls; - return () => { - controlsRef.current = null; - controls.destroy(); - }; - // Lifecycle bound to camera context; option updates flow through controls.update(). - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [cameraElRef, cameraRef, runtimeCameraRef, applyTransformDirect, store]); - - useEffect(() => { - controlsRef.current?.update({ - drag, - wheel, - dolly, - invert, - minZoom, - maxZoom, - minDistance, - maxDistance, - animate, - }); - }, [drag, wheel, dolly, invert, minZoom, maxZoom, minDistance, maxDistance, animate]); - - return null; +export function PolyMapControls(props: PolyMapControlsProps): null { + return usePointerControls(createPolyMapControls, props); } diff --git a/packages/react/src/controls/PolyOrbitControls.tsx b/packages/react/src/controls/PolyOrbitControls.tsx index cf0852ba6..226d611c6 100644 --- a/packages/react/src/controls/PolyOrbitControls.tsx +++ b/packages/react/src/controls/PolyOrbitControls.tsx @@ -2,90 +2,16 @@ * — thin React wrapper over `createPolyOrbitControls` * from `@layoutit/polycss/runtime`. */ -import { useEffect, useRef } from "react"; +import { createPolyOrbitControls } from "@layoutit/polycss/runtime"; import { - createPolyOrbitControls, - type PolyCameraControlTarget, - type PolyOrbitControlsHandle, -} from "@layoutit/polycss/runtime"; -import { useCameraContext } from "../camera/context"; -import type { SharedControlsProps, PolyControlsCamera } from "./sharedControls"; + usePointerControls, + type SharedControlsProps, + type PolyControlsCamera, +} from "./sharedControls"; export type { PolyControlsCamera as PolyOrbitControlsCamera }; export interface PolyOrbitControlsProps extends SharedControlsProps {} -export function PolyOrbitControls({ - drag = true, - wheel = true, - dolly = false, - invert = false, - minZoom = 0.1, - maxZoom = 10, - minDistance = 0, - maxDistance = Infinity, - animate = false, - onChange, - onInteractionStart, - onInteractionEnd, -}: PolyOrbitControlsProps): null { - const { store, cameraRef, runtimeCameraRef, cameraElRef, applyTransformDirect } = useCameraContext(); - const controlsRef = useRef(null); - - const onChangeRef = useRef(onChange); - const onStartRef = useRef(onInteractionStart); - const onEndRef = useRef(onInteractionEnd); - onChangeRef.current = onChange; - onStartRef.current = onInteractionStart; - onEndRef.current = onInteractionEnd; - - useEffect(() => { - const el = cameraElRef.current; - if (!el) return; - const target: PolyCameraControlTarget = { - host: el, - cameraEl: el, - camera: (runtimeCameraRef?.current ?? cameraRef.current) as PolyCameraControlTarget["camera"], - applyCamera: () => { - applyTransformDirect(); - store.updateCameraFromRef(cameraRef.current); - }, - }; - const controls = createPolyOrbitControls(target, { - drag, - wheel, - dolly, - invert, - minZoom, - maxZoom, - minDistance, - maxDistance, - animate, - }); - controls.addEventListener("change", (ev) => onChangeRef.current?.(ev.camera)); - controls.addEventListener("start", (ev) => onStartRef.current?.(ev.camera)); - controls.addEventListener("end", (ev) => onEndRef.current?.(ev.camera)); - controlsRef.current = controls; - return () => { - controlsRef.current = null; - controls.destroy(); - }; - // Lifecycle bound to camera context; option updates flow through controls.update(). - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [cameraElRef, cameraRef, runtimeCameraRef, applyTransformDirect, store]); - - useEffect(() => { - controlsRef.current?.update({ - drag, - wheel, - dolly, - invert, - minZoom, - maxZoom, - minDistance, - maxDistance, - animate, - }); - }, [drag, wheel, dolly, invert, minZoom, maxZoom, minDistance, maxDistance, animate]); - - return null; +export function PolyOrbitControls(props: PolyOrbitControlsProps): null { + return usePointerControls(createPolyOrbitControls, props); } diff --git a/packages/react/src/controls/TransformControls.test.tsx b/packages/react/src/controls/TransformControls.test.tsx index f61045a3e..df2c4ffc1 100644 --- a/packages/react/src/controls/TransformControls.test.tsx +++ b/packages/react/src/controls/TransformControls.test.tsx @@ -624,4 +624,51 @@ describe("", () => { }); }); + it("causes 0 gizmo DOM childList mutations across intra-quadrant camera orbit updates", () => { + const container = document.createElement("div"); + document.body.appendChild(container); + const root = createRoot(container); + const meshRef = createRef(); + + const renderWithCamera = (mode: "translate" | "rotate", rotX: number, rotY: number) => { + act(() => + root.render( + + + + + + , + ), + ); + }; + + renderWithCamera("translate", 60, 40); + const wrapper = container.querySelector("[data-poly-transform-controls]") as HTMLElement; + expect(wrapper).not.toBeNull(); + let mutations = 0; + const observer = new MutationObserver((records) => { + mutations += records.length; + }); + observer.observe(wrapper, { childList: true, subtree: true }); + + for (let step = 1; step <= 5; step++) { + renderWithCamera("translate", 60 + step, 40 + step); + } + mutations += observer.takeRecords().length; + expect(mutations).toBe(0); + + observer.disconnect(); + renderWithCamera("rotate", 20, 30); + mutations = 0; + observer.observe(wrapper, { childList: true, subtree: true }); + for (let step = 1; step <= 5; step++) { + renderWithCamera("rotate", 20 + step * 5, 30 + step * 5); + } + mutations += observer.takeRecords().length; + expect(mutations).toBe(0); + observer.disconnect(); + act(() => root.unmount()); + }); + }); diff --git a/packages/react/src/controls/TransformControls.tsx b/packages/react/src/controls/TransformControls.tsx index dffe26832..88dfc38bf 100644 --- a/packages/react/src/controls/TransformControls.tsx +++ b/packages/react/src/controls/TransformControls.tsx @@ -1,31 +1,8 @@ /** - * — drag gizmo for translating a `` along - * the six world-axis directions (±X, ±Y, ±Z). Mirrors three.js's - * TransformControls API (`mode`, `space`, `size`, `showX/Y/Z`, - * `translationSnap`, events `onChange` / `onObjectChange` / `onMouseDown` - * / `onMouseUp` / `onDraggingChanged`). - * - * Geometry: each arrow is a polycss `` whose vertices come - * from `arrowPolygons` (a thin axis-aligned cuboid shaft + a 4-sided - * pyramid head). This matches how `` is built — same - * 3D primitives, so the gizmo's lit appearance composes naturally with - * the rest of the scene. - * - * Drag math: project pointer screen-pixel delta onto the screen - * projection of the world axis. Screen-axis is snapshotted at - * pointerdown via a probe element placed `axis × beamLength` from the - * gizmo origin, then normalized — `getBoundingClientRect()` deltas give - * px-per-scene-px automatically (handles camera tilt + zoom). - * - * `position` / drag deltas live in scene-CSS pixels, matching `` (which is `translate3d(x px, y px, z px)`). Polygon - * vertices live in WORLD units; we convert via `SCENE_TILE_SIZE` (the - * default `tileSize` PolyScene applies to atlas geometry). - * - * `space="local"` is accepted in the type but only "world" is implemented. + * — thin React wrapper over `@layoutit/polycss/runtime`'s + * shared gizmo drag, geometry, and fallback hit-test engine. */ import { - useCallback, useContext, useEffect, useMemo, @@ -34,53 +11,29 @@ import { type CSSProperties, type RefObject, } from "react"; +import { DEFAULT_CAMERA_STATE, type Vec3 } from "@layoutit/polycss-core"; 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, - DEFAULT_CAMERA_STATE, - eulerXYZFromQuat, - gizmoCenterForMesh, - gizmoLengthForMesh, - isAxisBackFacing, - planePolygons, - quatFromAxisAngle, - quatFromEulerXYZ, - quatMultiply, - ringQuadPolygons, - screenPlaneDet, - snap, - solveAxisDragDelta, - solvePlaneDragDeltas, - unwrapAngleDelta, - userAxisLetterOf, - withAlpha, - type Polygon, - type Vec3, -} from "@layoutit/polycss-core"; + RING_MASK_INNER_RATIO, + RING_MASK_OUTER_RATIO, + attachDeclarativeGizmoFallback, + buildTransformGizmoEntries, + computeGizmoWrapperPositionCss, + startDeclarativeArrowDrag, + startDeclarativePlaneDrag, + startDeclarativeRingDrag, + type DeclarativeGizmoDragState, + type GizmoArrowSpec, + type GizmoMode, + type GizmoPlaneSpec, + type GizmoRingSpec, + type TransformGizmoCache, +} from "@layoutit/polycss/runtime"; import { PolyMesh } from "../scene/PolyMesh"; -import { pointInMeshElement, type PolyMeshHandle, type PolyPointerEvent } from "../scene/events"; +import type { PolyMeshHandle, PolyPointerEvent } from "../scene/events"; import { PolyCameraContext } from "../camera/context"; import { createSceneStore, useStoreSelector } from "../store/sceneStore"; -// Stable no-op store used as a hook-rule-compliant fallback when -// PolyTransformControls is rendered outside a PolyCamera. We always pass a -// store to useStoreSelector; this one never changes, so it never re-renders. +// Stable no-op store used as a hook-rule-compliant fallback outside . const FALLBACK_CAMERA_STORE = createSceneStore(DEFAULT_CAMERA_STATE); /** Optional ref-or-direct binding to a target mesh. */ @@ -94,24 +47,20 @@ export interface PolyTransformControlsObjectChangeEvent { object: PolyMeshHandle; /** The new position. Only emitted when `mode` is "translate". */ position?: Vec3; - /** The new Euler rotation (degrees, X/Y/Z). Only emitted when - * `mode` is "rotate". */ + /** The new Euler rotation (degrees, X/Y/Z). Only emitted when `mode` is "rotate". */ rotation?: Vec3; } export interface PolyTransformControlsProps { - /** Mesh to attach to. Pass a ref returned from `useRef()` - * or a handle directly. `null` hides the gizmo. */ + /** Mesh to attach to. Pass a ref or handle directly. `null` hides the gizmo. */ object: PolyTransformControlsObject; - /** Drag mode. "translate" → axial arrows, "rotate" → axial rings. */ - mode?: "translate" | "rotate"; + /** Drag mode. "translate" → axial arrows + planes, "rotate" → axial rings. */ + mode?: GizmoMode; /** Axis basis. Only "world" is implemented in v1. */ space?: "world" | "local"; /** Multiplier on gizmo size (shaft length / ring radius). Default 1. */ size?: number; - /** Show / hide axis gizmo PAIRS. Default true. In translate mode this - * hides both the +/- arrows for that axis; in rotate mode this hides - * the corresponding ring. */ + /** Show / hide axis gizmo PAIRS. Default true. */ showX?: boolean; showY?: boolean; showZ?: boolean; @@ -123,16 +72,13 @@ export interface PolyTransformControlsProps { enabled?: boolean; /** Fires for any transform change. Argument-less, mirrors three.js. */ onChange?: () => void; - /** Fires with the new transform during drag. Use this to update - * position state — controlled flow, parent owns state. */ + /** Fires with the new transform during drag. */ onObjectChange?: (event: PolyTransformControlsObjectChangeEvent) => void; /** Fires once on drag start. */ onMouseDown?: () => void; /** Fires once on drag end. */ onMouseUp?: () => void; - /** Fires with `true` on drag start, `false` on drag end. Mirrors - * three.js's `'dragging-changed'` event (kebab-case preserved here - * via the boolean payload, since react prop naming is camelCase). */ + /** Fires with `true` on drag start, `false` on drag end. */ onDraggingChanged?: (dragging: boolean) => void; } @@ -142,312 +88,6 @@ function resolveObject(o: PolyTransformControlsObject): PolyMeshHandle | null { return o as PolyMeshHandle; } -interface DragOptions { - /** CSS axis index this arrow drives (0=x, 1=y, 2=z). The probe is - * placed along this CSS direction; pointer-px deltas project onto - * it; the resulting `t` updates `position[cssAxis]`. */ - cssAxis: 0 | 1 | 2; - sign: 1 | -1; - shaftLengthCss: number; - wrapper: HTMLElement; - target: PolyMeshHandle; - startClientX: number; - startClientY: number; - translationSnap: number | null; - onChange?: () => void; - onObjectChange?: (event: PolyTransformControlsObjectChangeEvent) => void; - onMouseDown?: () => void; - onMouseUp?: () => void; - onDraggingChanged?: (dragging: boolean) => void; -} - -/** Project the screen-space delta of a CSS-axis vector via a probe - * placed `axis × shaftLengthCss` from the gizmo wrapper origin, then - * run a pointermove/up loop translating pointer-px deltas into - * scene-px along the axis. Shared by the per-arrow - * PolyMesh.onPointerDown handler AND the cameraEl JS hit-test - * fallback so both paths produce identical drag behavior. */ -function startAxisDrag(opts: DragOptions): void { - const { - cssAxis, - sign, - shaftLengthCss, - wrapper, - target, - startClientX, - startClientY, - translationSnap, - onChange, - onObjectChange, - onMouseDown, - onMouseUp, - onDraggingChanged, - } = opts; - - const probeDistance = shaftLengthCss; - const axisVec: Vec3 = [0, 0, 0]; - axisVec[cssAxis] = sign; - const probe = document.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] * probeDistance}px, ${axisVec[1] * probeDistance}px, ${axisVec[2] * probeDistance}px)`; - wrapper.appendChild(probe); - const wRect = wrapper.getBoundingClientRect(); - const pRect = probe.getBoundingClientRect(); - wrapper.removeChild(probe); - const screenAxisX = (pRect.left - wRect.left) / probeDistance; - const screenAxisY = (pRect.top - wRect.top) / probeDistance; - const screenAxisLenSq = screenAxisX * screenAxisX + screenAxisY * screenAxisY; - if (screenAxisLenSq < SCREEN_AXIS_DEAD_ZONE_SQ) return; - - const startPos = target.getPosition() ?? ([0, 0, 0] as Vec3); - - onMouseDown?.(); - onDraggingChanged?.(true); - - const handleMove = (ev: PointerEvent): void => { - const dx = ev.clientX - startClientX; - const dy = ev.clientY - startClientY; - let t = solveAxisDragDelta(dx, dy, screenAxisX, screenAxisY); - t = snap(t, translationSnap); - const newPos: Vec3 = [ - startPos[0] + t * axisVec[0], - startPos[1] + t * axisVec[1], - startPos[2] + t * axisVec[2], - ]; - onObjectChange?.({ object: target, position: newPos }); - onChange?.(); - }; - const handleUp = (): void => { - window.removeEventListener("pointermove", handleMove); - window.removeEventListener("pointerup", handleUp); - window.removeEventListener("pointercancel", handleUp); - // Defang the synthesized `click` that follows pointerup. Without - // this, releasing a gizmo drag over the chicken's polygons fires - // Select's click listener and (since the chicken is already - // selected) immediately toggles it off. Capture-phase one-shot - // listener stops the click before it bubbles to cameraEl. The - // setTimeout(0) cleanup handles the case where the browser - // didn't synthesize a click (large pointer movement) — the - // listener would otherwise stay armed and eat the next real click. - const swallow = (e: Event): void => { - e.stopPropagation(); - e.stopImmediatePropagation(); - }; - window.addEventListener("click", swallow, { capture: true, once: true }); - setTimeout(() => window.removeEventListener("click", swallow, true), 0); - onMouseUp?.(); - onDraggingChanged?.(false); - }; - window.addEventListener("pointermove", handleMove); - window.addEventListener("pointerup", handleUp); - window.addEventListener("pointercancel", handleUp); -} - -interface PlaneDragOptions { - axisA: 0 | 1 | 2; - axisB: 0 | 1 | 2; - /** Distance (CSS px) the probe is offset along each in-plane axis. Uses - * the same scale as the arrow's shaftLengthCss so screen projection is - * proportional to one axis-unit of mesh translation. */ - probeDistanceCss: number; - wrapper: HTMLElement; - target: PolyMeshHandle; - startClientX: number; - startClientY: number; - translationSnap: number | null; - onChange?: () => void; - onObjectChange?: (event: PolyTransformControlsObjectChangeEvent) => void; - onMouseDown?: () => void; - onMouseUp?: () => void; - onDraggingChanged?: (dragging: boolean) => void; -} - -/** Project pointer screen-px deltas onto the screen projections of TWO - * world axes (the plane's basis), solve a 2x2 system, and update the - * mesh position along both axes. Same probe trick as `startAxisDrag`, - * extended to two basis vectors. */ -function startPlaneDrag(opts: PlaneDragOptions): void { - const { - axisA, - axisB, - probeDistanceCss, - wrapper, - target, - startClientX, - startClientY, - translationSnap, - onChange, - onObjectChange, - onMouseDown, - onMouseUp, - onDraggingChanged, - } = opts; - - const axisAVec: Vec3 = [0, 0, 0]; axisAVec[axisA] = 1; - const axisBVec: Vec3 = [0, 0, 0]; axisBVec[axisB] = 1; - function probe(axisVec: Vec3): { x: number; y: number } { - const el = wrapper.ownerDocument!.createElement("div"); - el.style.position = "absolute"; - el.style.left = "0"; - el.style.top = "0"; - el.style.width = "0"; - el.style.height = "0"; - el.style.transform = `translate3d(${axisVec[0] * probeDistanceCss}px, ${axisVec[1] * probeDistanceCss}px, ${axisVec[2] * probeDistanceCss}px)`; - wrapper.appendChild(el); - const wR = wrapper.getBoundingClientRect(); - const pR = el.getBoundingClientRect(); - wrapper.removeChild(el); - return { - x: (pR.left - wR.left) / probeDistanceCss, - y: (pR.top - wR.top) / probeDistanceCss, - }; - } - const pA = probe(axisAVec); - const pB = probe(axisBVec); - const det = screenPlaneDet(pA, pB); - if (Math.abs(det) < SCREEN_AXIS_DEAD_ZONE_SQ) return; - - const startPos = target.getPosition() ?? ([0, 0, 0] as Vec3); - onMouseDown?.(); - onDraggingChanged?.(true); - - const handleMove = (ev: PointerEvent): void => { - const dx = ev.clientX - startClientX; - const dy = ev.clientY - startClientY; - let { tA, tB } = solvePlaneDragDeltas(dx, dy, pA, pB, det); - if (translationSnap !== null) { - tA = Math.round(tA / translationSnap) * translationSnap; - tB = Math.round(tB / translationSnap) * translationSnap; - } - 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], - ]; - onObjectChange?.({ object: target, position: next }); - onChange?.(); - }; - const handleUp = (): void => { - window.removeEventListener("pointermove", handleMove); - window.removeEventListener("pointerup", handleUp); - window.removeEventListener("pointercancel", handleUp); - const swallow = (e: Event): void => { - e.stopPropagation(); - e.stopImmediatePropagation(); - }; - window.addEventListener("click", swallow, { capture: true, once: true }); - setTimeout(() => window.removeEventListener("click", swallow, true), 0); - onMouseUp?.(); - onDraggingChanged?.(false); - }; - window.addEventListener("pointermove", handleMove); - window.addEventListener("pointerup", handleUp); - window.addEventListener("pointercancel", handleUp); -} - -interface RingDragOptions { - /** CSS axis the ring rotates around (0=x, 1=y, 2=z). Maps directly - * to PolyMesh's `rotation[cssAxis]` slot (rotateX/rotateY/rotateZ). */ - cssAxis: 0 | 1 | 2; - wrapper: HTMLElement; - target: PolyMeshHandle; - startClientX: number; - startClientY: number; - rotationSnap: number | null; - onChange?: () => void; - onObjectChange?: (event: PolyTransformControlsObjectChangeEvent) => void; - onMouseDown?: () => void; - onMouseUp?: () => void; - onDraggingChanged?: (dragging: boolean) => void; -} - -/** Rotation drag: track the pointer's screen-space angle around the - * gizmo wrapper's screen center, accumulate the unwrapped delta - * across moves, and apply it as degrees-of-rotation around the ring's - * CSS axis. Coarser than three.js's true ray-onto-rotation-plane - * projection (which would reproject through the camera per move) but - * reads naturally for the intuitive case of dragging a ring face-on, - * and degenerates predictably when the ring is edge-on (rotation - * speed scales with the apparent ring size). */ -function startRingDrag(opts: RingDragOptions): void { - const { - cssAxis, - wrapper, - target, - startClientX, - startClientY, - rotationSnap, - onChange, - onObjectChange, - onMouseDown, - onMouseUp, - onDraggingChanged, - } = opts; - - const wRect = wrapper.getBoundingClientRect(); - // Wrapper is a 0×0 anchor at the gizmo origin — its bounding rect - // collapses to a single point in screen space, which is exactly the - // ring's center (we want angle relative to the rotation pivot). - const centerX = wRect.left; - const centerY = wRect.top; - - let lastAngle = Math.atan2(startClientY - centerY, startClientX - centerX); - let cumulative = 0; // accumulated radians since drag start - const startRotation = (target.getRotation() ?? [0, 0, 0]) as Vec3; - - onMouseDown?.(); - onDraggingChanged?.(true); - - // World-frame quaternion compose. The gizmo's rings stay at fixed world - // axes (the wrapper isn't rotated with the mesh), so the user clicks a - // ring expecting rotation around the WORLD axis they see. We pre-multiply: - // Qnew = Qdelta · Qstart - // → rotation applies in the WORLD frame, then the prior orientation. Each - // ring drag composes cumulatively on top of the mesh's current orientation - // without resetting it — which Euler-add couldn't do for repeated axes. - const qStart = quatFromEulerXYZ(startRotation); - const handleMove = (ev: PointerEvent): void => { - const a = Math.atan2(ev.clientY - centerY, ev.clientX - centerX); - // Unwrap so a drag that crosses the ±π boundary doesn't jump by 2π. - cumulative += unwrapAngleDelta(a, lastAngle); - lastAngle = a; - let degrees = (cumulative * 180) / Math.PI; - degrees = snap(degrees, rotationSnap); - const axisVec: Vec3 = [0, 0, 0]; - axisVec[cssAxis] = 1; - const qDelta = quatFromAxisAngle(axisVec, (degrees * Math.PI) / 180); - const newRotation = eulerXYZFromQuat(quatMultiply(qDelta, qStart)); - onObjectChange?.({ object: target, rotation: newRotation }); - onChange?.(); - }; - const handleUp = (): void => { - window.removeEventListener("pointermove", handleMove); - window.removeEventListener("pointerup", handleUp); - window.removeEventListener("pointercancel", handleUp); - // Same click-swallow trick as the translate drag — release-over- - // chicken would otherwise toggle selection off mid-rotation. - const swallow = (e: Event): void => { - e.stopPropagation(); - e.stopImmediatePropagation(); - }; - window.addEventListener("click", swallow, { capture: true, once: true }); - setTimeout(() => window.removeEventListener("click", swallow, true), 0); - onMouseUp?.(); - onDraggingChanged?.(false); - // Rebake the atlas with the new rotation baked in. Must come after the - // callbacks above so consumers have already committed the final rotation - // to state before the atlas snapshot runs. - target.rebakeAtlas(); - }; - window.addEventListener("pointermove", handleMove); - window.addEventListener("pointerup", handleUp); - window.addEventListener("pointercancel", handleUp); -} - export function PolyTransformControls({ object, mode = "translate", @@ -465,241 +105,76 @@ export function PolyTransformControls({ onMouseUp, onDraggingChanged, }: PolyTransformControlsProps) { - // Refs don't trigger React re-renders. When `object` is a RefObject - // whose `.current` lands AFTER first render (the common case — the - // target mounts in the same pass and only sets the ref - // after our first render), we need a single follow-up render to - // pick it up. useEffect with `object` in the deps array handles - // both first-mount and ref-identity changes cleanly. + // Refs don't trigger React re-renders; pick up `.current` after mount commit. const [, forceRender] = useState(0); useEffect(() => { forceRender((n) => n + 1); }, [object]); - // Camera rotation, reactively. Used to compute which translate arrows are - // pointing AWAY from the viewer so we can render them as head-only. The - // store subscription means the gizmo geometry re-evaluates whenever the - // user orbits the camera — no stale back/front state. - const cameraCtxForRot = useContext(PolyCameraContext); - // Two primitive selectors — returning an object literal each call would - // make useSyncExternalStore see a "changed" snapshot every render and - // trigger an infinite re-render loop. + const cameraCtx = useContext(PolyCameraContext); + const cameraElRef = cameraCtx?.cameraElRef; const rotX = useStoreSelector( - cameraCtxForRot?.store ?? FALLBACK_CAMERA_STORE, + cameraCtx?.store ?? FALLBACK_CAMERA_STORE, (s) => s.cameraState.rotX, ); const rotY = useStoreSelector( - cameraCtxForRot?.store ?? FALLBACK_CAMERA_STORE, + cameraCtx?.store ?? FALLBACK_CAMERA_STORE, (s) => s.cameraState.rotY, ); - // Per-arrow hover + dragging state. Lifted here so both the React - // PolyMesh.onPointerDown handler and the cameraEl JS hit-test - // fallback can keep them in sync. Each render re-evaluates which - // arrow is hot, and TranslateArrow paints its polygons at the - // matching alpha (idle / hover / drag). const [hoveredKey, setHoveredKey] = useState(null); const [draggingKey, setDraggingKey] = useState(null); + const gizmoCacheRef = useRef(new Map()); - // Pin everything the cameraEl fallback listener needs. The listener - // is attached once per cameraEl identity and reads through the refs, - // so prop changes don't re-bind window listeners during a drag. - const cameraCtx = useContext(PolyCameraContext); - const cameraElRef = cameraCtx?.cameraElRef; - const dragRef = useRef<{ - target: PolyMeshHandle | null; - mode: "translate" | "rotate"; - shaftLengthCss: number; - enabled: boolean; - show: { x: boolean; y: boolean; z: boolean }; - translationSnap: number | null; - rotationSnap: number | null; - onChange?: () => void; - onObjectChange?: (event: PolyTransformControlsObjectChangeEvent) => void; - onMouseDown?: () => void; - onMouseUp?: () => void; - onDraggingChanged?: (dragging: boolean) => void; - }>({ + const dragStateRef = useRef>({ target: null, - mode: "translate", + mode, shaftLengthCss: 0, - enabled: true, - show: { x: true, y: true, z: true }, - translationSnap: null, - rotationSnap: null, + enabled, + showX, + showY, + showZ, + translationSnap, + rotationSnap, }); - // cameraEl JS hit-test fallback. Native polygon hit-testing handles - // the common case (PolyMesh.onPointerDown fires when an arrow's - // `` is clicked), but if something upstream forces - // `pointer-events: none` on polycss elements, OR `border-shape` - // clipping suppresses the click on the visible-but-transparent - // corners of an arrow rect, the click falls through to cameraEl. - // This bubble-phase listener catches those misses, walks the six - // arrow elements testing each polygon's bounding rect against the - // click point, and dispatches the same `startAxisDrag`. - // - // Skips events whose target is already inside an arrow PolyMesh — - // those will trigger the per-arrow handler shortly via React - // synthetic dispatch; falling through here would double-fire. useEffect(() => { const cameraEl = cameraElRef?.current; if (!cameraEl) return; - const onPointerDown = (event: PointerEvent): void => { - const state = dragRef.current; - if (!state.target || !state.enabled) return; - const targetEl = event.target as Element | null; - // Don't double-fire when the click already hit one of our gizmo - // PolyMeshes — React's per-arrow/per-ring synthetic handler will - // pick it up. The shared `polycss-transform-gizmo` class is set - // on both translate arrows and rotate rings. - if (targetEl?.closest(".polycss-transform-gizmo")) return; - if (state.mode === "translate") { - // Plane handles hit-tested FIRST so they win over arrow shafts at - // overlapping corners. - for (const spec of PLANE_SPECS) { - const aL = (["x", "y", "z"] as const)[spec.axisA]; - const bL = (["x", "y", "z"] as const)[spec.axisB]; - if (!state.show[aL] || !state.show[bL]) continue; - const planeEl = document.querySelector( - `.polycss-transform-plane--${spec.key}`, - ) as HTMLElement | null; - if (!planeEl) continue; - if (!pointInMeshElement(planeEl, event.clientX, event.clientY)) continue; - event.preventDefault(); - event.stopPropagation(); - const wrapper = planeEl.closest( - "[data-poly-transform-controls]", - ) as HTMLElement | null; - if (!wrapper) return; - setDraggingKey(spec.key); - startPlaneDrag({ - axisA: spec.axisA, - axisB: spec.axisB, - probeDistanceCss: state.shaftLengthCss, - wrapper, - target: state.target, - startClientX: event.clientX, - startClientY: event.clientY, - translationSnap: state.translationSnap, - onChange: state.onChange, - onObjectChange: state.onObjectChange, - onMouseDown: state.onMouseDown, - onMouseUp: state.onMouseUp, - onDraggingChanged: (d) => { - if (!d) setDraggingKey(null); - state.onDraggingChanged?.(d); - }, - }); - return; - } - for (const spec of ARROW_SPECS) { - if (!state.show[userAxisLetterOf(spec.key)]) continue; - const arrowEl = document.querySelector( - `.polycss-transform-arrow--${spec.key}`, - ) as HTMLElement | null; - if (!arrowEl) continue; - if (!pointInMeshElement(arrowEl, event.clientX, event.clientY)) continue; - event.preventDefault(); - event.stopPropagation(); - const wrapper = arrowEl.closest( - "[data-poly-transform-controls]", - ) as HTMLElement | null; - if (!wrapper) return; - setDraggingKey(spec.key); - startAxisDrag({ - cssAxis: spec.cssAxis, - sign: spec.sign, - shaftLengthCss: state.shaftLengthCss, - wrapper, - target: state.target, - startClientX: event.clientX, - startClientY: event.clientY, - translationSnap: state.translationSnap, - onChange: state.onChange, - onObjectChange: state.onObjectChange, - onMouseDown: state.onMouseDown, - onMouseUp: state.onMouseUp, - onDraggingChanged: (d) => { - if (!d) setDraggingKey(null); - state.onDraggingChanged?.(d); - }, - }); - return; - } - } else if (state.mode === "rotate") { - for (const spec of RING_SPECS) { - if (!state.show[spec.key as "x" | "y" | "z"]) continue; - const ringEl = document.querySelector( - `.polycss-transform-ring--${spec.key}`, - ) as HTMLElement | null; - if (!ringEl) continue; - // Regular bbox-containment hit. The visible donut mask is only - // decoration — the WHOLE ring quad bbox is clickable so the rings - // are easy to land on. Clicks inside the inner hole also trigger - // rotation; selecting the wrapped mesh is done via clicks outside - // any ring's bbox (or via the Scene panel). - if (!pointInMeshElement(ringEl, event.clientX, event.clientY)) continue; - event.preventDefault(); - event.stopPropagation(); - const wrapper = ringEl.closest( - "[data-poly-transform-controls]", - ) as HTMLElement | null; - if (!wrapper) return; - setDraggingKey(spec.key); - startRingDrag({ - cssAxis: spec.cssAxis, - wrapper, - target: state.target, - startClientX: event.clientX, - startClientY: event.clientY, - rotationSnap: state.rotationSnap, - onChange: state.onChange, - onObjectChange: state.onObjectChange, - onMouseDown: state.onMouseDown, - onMouseUp: state.onMouseUp, - onDraggingChanged: (d) => { - if (!d) setDraggingKey(null); - state.onDraggingChanged?.(d); - }, - }); - return; - } - } - }; - cameraEl.addEventListener("pointerdown", onPointerDown); - return () => cameraEl.removeEventListener("pointerdown", onPointerDown); + return attachDeclarativeGizmoFallback(cameraEl, () => dragStateRef.current); }, [cameraElRef]); const target = resolveObject(object); - if (!target) return null; - - const position = target.getPosition() ?? ([0, 0, 0] as Vec3); - const polygons = target.getPolygons(); - const bboxCenter = gizmoCenterForMesh(polygons); - // Post-parity: `position` is world units in world-axis order. The gizmo - // wrapper lives in scene-CSS pixel space, so apply the world→CSS axis - // swap + ×BASE_TILE before adding the (already CSS-pixel) bbox center. - // bboxCenter accounts for meshes whose vertices aren't centered at 0; - // when PolyMesh autoCenter is set, bboxCenter is (0,0,0) and this is a - // pure axis-swap. - const cssPosX = position[1] * SCENE_TILE_SIZE; - const cssPosY = position[0] * SCENE_TILE_SIZE; - const cssPosZ = position[2] * SCENE_TILE_SIZE; - const wrapperPos: Vec3 = [ - cssPosX + bboxCenter[0], - cssPosY + bboxCenter[1], - cssPosZ + bboxCenter[2], - ]; - const baseLength = gizmoLengthForMesh(polygons); - const shaftLengthCss = baseLength * size; + const polygons = target ? target.getPolygons() : []; + + const entries = useMemo( + () => + target + ? buildTransformGizmoEntries({ + mode, + polygons, + size, + showX, + showY, + showZ, + rotX, + rotY, + hoveredKey, + draggingKey, + cache: gizmoCacheRef.current, + }) + : null, + [target, mode, polygons, size, showX, showY, showZ, rotX, rotY, hoveredKey, draggingKey], + ); - dragRef.current = { + dragStateRef.current = { target, mode, - shaftLengthCss, + shaftLengthCss: entries?.shaftLengthCss ?? 0, enabled, - show: { x: showX, y: showY, z: showZ }, + showX, + showY, + showZ, translationSnap, rotationSnap, onChange, @@ -707,521 +182,116 @@ export function PolyTransformControls({ onMouseDown, onMouseUp, onDraggingChanged, + onDraggingKeyChange: setDraggingKey, }; - // Gizmo stays at world-axis orientation (NOT rotated with the mesh). This - // keeps the arrows in fixed screen positions so panning + repeated drags - // stay predictable. The MATH still composes rotations correctly — see - // `startRingDrag` for the world-frame quaternion compose. + if (!target || !entries) return null; + + const wrapperPos = computeGizmoWrapperPositionCss(target.getPosition(), polygons); const wrapperStyle: CSSProperties = { transform: `translate3d(${wrapperPos[0]}px, ${wrapperPos[1]}px, ${wrapperPos[2]}px)`, position: "absolute", transformStyle: "preserve-3d", - // No `pointer-events: none` here — that property is inherited, so - // setting it on the wrapper would cascade to every arrow polygon - // and disable native hit-testing on the gizmo entirely. The - // wrapper is a 0×0 anchor so it has no surface to be hit on its - // own; descendants opt in via the default `auto`. zIndex: 1000, }; - return ( -
- {mode === "translate" && ARROW_SPECS.map((spec) => { - const show = { x: showX, y: showY, z: showZ }[userAxisLetterOf(spec.key)]; - if (!show) return null; - const hovered = hoveredKey === spec.key; - const dragging = draggingKey === spec.key; - const alpha = dragging ? ALPHA_DRAGGING : hovered ? ALPHA_HOVER : ALPHA_IDLE; - const backFacing = isAxisBackFacing(spec.cssAxis, spec.sign, rotX, rotY); - return ( - setHoveredKey(h ? spec.key : (cur) => (cur === spec.key ? null : cur))} - onDraggingStart={() => setDraggingKey(spec.key)} - onDraggingStop={() => setDraggingKey((cur) => (cur === spec.key ? null : cur))} - /> - ); - })} - {mode === "translate" && PLANE_SPECS.map((spec) => { - const aLetter = (["x", "y", "z"] as const)[spec.axisA]; - const bLetter = (["x", "y", "z"] as const)[spec.axisB]; - const show = ({ x: showX, y: showY, z: showZ }[aLetter]) - && ({ x: showX, y: showY, z: showZ }[bLetter]); - if (!show) return null; - const hovered = hoveredKey === spec.key; - const dragging = draggingKey === spec.key; - const alpha = dragging ? ALPHA_DRAGGING : hovered ? ALPHA_HOVER : ALPHA_IDLE; - return ( - setHoveredKey(h ? spec.key : (cur) => (cur === spec.key ? null : cur))} - onDraggingStart={() => setDraggingKey(spec.key)} - onDraggingStop={() => setDraggingKey((cur) => (cur === spec.key ? null : cur))} - /> - ); - })} - {mode === "rotate" && RING_SPECS.map((spec) => { - const show = { x: showX, y: showY, z: showZ }[spec.key as "x" | "y" | "z"]; - if (!show) return null; - const hovered = hoveredKey === spec.key; - const dragging = draggingKey === spec.key; - const alpha = dragging ? ALPHA_DRAGGING : hovered ? ALPHA_HOVER : ALPHA_IDLE; - return ( - setHoveredKey(h ? spec.key : (cur) => (cur === spec.key ? null : cur))} - onDraggingStart={() => setDraggingKey(spec.key)} - onDraggingStop={() => setDraggingKey((cur) => (cur === spec.key ? null : cur))} - /> - ); - })} -
- ); -} - -interface TranslateArrowProps { - cssAxis: 0 | 1 | 2; - sign: 1 | -1; - axisKey: string; - color: string; - shaftLengthCss: number; - /** Emit the shaft cuboid. Caller sets false when this arrow is on the - * camera-facing-away side of an axis pair, leaving just the head. */ - includeShaft: boolean; - target: PolyMeshHandle; - enabled: boolean; - translationSnap: number | null; - onChange?: () => void; - onObjectChange?: (event: PolyTransformControlsObjectChangeEvent) => void; - onMouseDown?: () => void; - onMouseUp?: () => void; - onDraggingChanged?: (dragging: boolean) => void; - /** Local hover-state notifications, lifted to the parent so it can - * mark the right arrow as hovered without per-arrow render plumbing. */ - onHoverChange?: (hovered: boolean) => void; - onDraggingStart?: () => void; - onDraggingStop?: () => void; -} + const ringStyle: CSSProperties = { + ["--ring-inner-ratio" as string]: RING_MASK_INNER_RATIO, + ["--ring-outer-ratio" as string]: RING_MASK_OUTER_RATIO, + }; -function TranslateArrow({ - cssAxis, - sign, - axisKey, - color, - shaftLengthCss, - includeShaft, - target, - enabled, - translationSnap, - onChange, - onObjectChange, - onMouseDown, - onMouseUp, - onDraggingChanged, - onHoverChange, - onDraggingStart, - onDraggingStop, -}: TranslateArrowProps) { - // Pin callback refs so the pointerdown handler always reads fresh - // closures without re-binding window listeners. - const cbRef = useRef({ - onChange, - onObjectChange, - onMouseDown, - onMouseUp, - onDraggingChanged, - onDraggingStart, - onDraggingStop, - enabled, - translationSnap, - }); - cbRef.current = { - onChange, - onObjectChange, - onMouseDown, - onMouseUp, - onDraggingChanged, - onDraggingStart, - onDraggingStop, - enabled, - translationSnap, + const startFromMeshEvent = ( + e: PolyPointerEvent, + run: (wrapper: HTMLElement) => void, + ): void => { + if (!dragStateRef.current.enabled) return; + e.stopPropagation(); + const wrapper = e.eventObject.element?.closest( + "[data-poly-transform-controls]", + ) as HTMLElement | null; + if (!wrapper) return; + run(wrapper); }; - // Build the polygon geometry. Vertex coords are in WORLD units; the - // scene multiplies by tileSize when rendering, so the arrow ends up - // `shaftLengthCss` scene-CSS pixels long. Convert from CSS axis to - // world axis here — the rest of the component (probe, drag math) - // operates in CSS coords. - const polygons = useMemo(() => { - const lengthWorld = shaftLengthCss / SCENE_TILE_SIZE; - return arrowPolygons({ - axis: WORLD_AXIS_FOR_CSS[cssAxis], - sign, - shaftLength: lengthWorld, - shaftHalfThickness: lengthWorld * SHAFT_HALF_THICKNESS_RATIO, - headLength: lengthWorld * HEAD_LENGTH_RATIO, - headHalfThickness: lengthWorld * HEAD_HALF_THICKNESS_RATIO, - color, - shaft: includeShaft, - }); - }, [cssAxis, sign, color, shaftLengthCss, includeShaft]); + const getDragState = () => dragStateRef.current; - const onPointerDown = useCallback( - (e: PolyPointerEvent): void => { - if (!cbRef.current.enabled) return; - // Stop propagation BOTH on the polycss event (React tree) AND on - // the underlying native event — the latter prevents PolyControls' - // camera-drag bubble listener on .polycss-camera from starting a - // rotation in parallel with our axis drag, and also signals the - // gizmo's own cameraEl fallback listener (in TransformControls) - // not to redundantly start a second drag. - e.stopPropagation(); - const meshEl = e.eventObject.element; - const wrapper = meshEl?.closest("[data-poly-transform-controls]") as HTMLElement | null; - if (!wrapper) return; - cbRef.current.onDraggingStart?.(); - startAxisDrag({ - cssAxis, - sign, - shaftLengthCss, + const handleArrowDown = (spec: GizmoArrowSpec) => (e: PolyPointerEvent) => + startFromMeshEvent(e, (wrapper) => { + startDeclarativeArrowDrag( + spec, wrapper, - target, - startClientX: e.nativeEvent.clientX, - startClientY: e.nativeEvent.clientY, - translationSnap: cbRef.current.translationSnap, - onChange: cbRef.current.onChange, - onObjectChange: cbRef.current.onObjectChange, - onMouseDown: cbRef.current.onMouseDown, - onMouseUp: cbRef.current.onMouseUp, - onDraggingChanged: (d) => { - if (!d) cbRef.current.onDraggingStop?.(); - cbRef.current.onDraggingChanged?.(d); - }, - }); - }, - [cssAxis, sign, target, shaftLengthCss], - ); - - // Render the arrow as a directly under - // .polycss-transform-controls — no intermediate wrapper. An extra - //
between PolyScene and PolyMesh flattens the 3D context (the - // intermediate generates its own group and composites its children - // as a flat bitmap before drawing into the scene's 3D space), so the - // cuboid shaft + pyramid head end up as a single 2D strip even - // though every polygon has a real matrix3d transform. Hanging axis - // identification on the PolyMesh wrapper via className keeps the - // 3D chain unbroken while still giving us a queryable marker. - return ( - onHoverChange?.(true)} - onPointerOut={() => onHoverChange?.(false)} - className={`polycss-transform-gizmo polycss-transform-arrow polycss-transform-arrow--${axisKey}`} - // Force baked rendering: in dynamic mode every color change - // (hover / drag) re-builds the texture atlas asynchronously, - // and the polygon ``'s background-image briefly resolves to - // null mid-rebuild — visually the arrow disappears for a frame. - // Baked mode renders solid polygons via inline `color` / currentColor - // (TextureBorderShapePoly path) which updates synchronously - // with no atlas hop, giving instant hover/drag feedback. - textureLighting="baked" - /> - ); -} - -interface TranslatePlaneProps { - axisA: 0 | 1 | 2; - axisB: 0 | 1 | 2; - perpAxis: 0 | 1 | 2; - planeKey: "xy" | "xz" | "yz"; - color: string; - shaftLengthCss: number; - /** Scene rotation (degrees) used to pick the camera-facing octant for - * the plane handle. */ - rotX: number; - rotY: number; - target: PolyMeshHandle; - enabled: boolean; - translationSnap: number | null; - onChange?: () => void; - onObjectChange?: (event: PolyTransformControlsObjectChangeEvent) => void; - onMouseDown?: () => void; - onMouseUp?: () => void; - onDraggingChanged?: (dragging: boolean) => void; - onHoverChange?: (hovered: boolean) => void; - onDraggingStart?: () => void; - onDraggingStop?: () => void; -} - -function TranslatePlane({ - axisA, - axisB, - perpAxis, - planeKey, - color, - shaftLengthCss, - rotX, - rotY, - target, - enabled, - translationSnap, - onChange, - onObjectChange, - onMouseDown, - onMouseUp, - onDraggingChanged, - onHoverChange, - onDraggingStart, - onDraggingStop, -}: TranslatePlaneProps) { - const cbRef = useRef({ - onChange, onObjectChange, onMouseDown, onMouseUp, - onDraggingChanged, onDraggingStart, onDraggingStop, enabled, translationSnap, - }); - cbRef.current = { - onChange, onObjectChange, onMouseDown, onMouseUp, - onDraggingChanged, onDraggingStart, onDraggingStop, enabled, translationSnap, - }; - - const polygons = useMemo(() => { - const lengthWorld = shaftLengthCss / SCENE_TILE_SIZE; - // Place the quad in the camera-facing octant: for each in-plane axis, - // flip the offset if its CSS +direction is back-facing the viewer. - // planePolygons uses WORLD axes (a/b derived from perp); WORLD_AXIS_FOR_CSS - // is involutive so the CSS axis we test is WORLD_AXIS_FOR_CSS[worldA]. - const worldPerp = WORLD_AXIS_FOR_CSS[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, + e.nativeEvent.clientX, + e.nativeEvent.clientY, + getDragState, + ); }); - }, [perpAxis, color, shaftLengthCss, rotX, rotY]); - const onPointerDown = useCallback( - (e: PolyPointerEvent): void => { - if (!cbRef.current.enabled) return; - e.stopPropagation(); - const meshEl = e.eventObject.element; - const wrapper = meshEl?.closest("[data-poly-transform-controls]") as HTMLElement | null; - if (!wrapper) return; - cbRef.current.onDraggingStart?.(); - startPlaneDrag({ - axisA, - axisB, - probeDistanceCss: shaftLengthCss, + const handlePlaneDown = (spec: GizmoPlaneSpec) => (e: PolyPointerEvent) => + startFromMeshEvent(e, (wrapper) => { + startDeclarativePlaneDrag( + spec, wrapper, - target, - startClientX: e.nativeEvent.clientX, - startClientY: e.nativeEvent.clientY, - translationSnap: cbRef.current.translationSnap, - onChange: cbRef.current.onChange, - onObjectChange: cbRef.current.onObjectChange, - onMouseDown: cbRef.current.onMouseDown, - onMouseUp: cbRef.current.onMouseUp, - onDraggingChanged: (d) => { - if (!d) cbRef.current.onDraggingStop?.(); - cbRef.current.onDraggingChanged?.(d); - }, - }); - }, - [axisA, axisB, target, shaftLengthCss], - ); - - return ( - onHoverChange?.(true)} - onPointerOut={() => onHoverChange?.(false)} - className={`polycss-transform-gizmo polycss-transform-plane polycss-transform-plane--${planeKey}`} - textureLighting="baked" - /> - ); -} - -interface RotateRingProps { - cssAxis: 0 | 1 | 2; - axisKey: string; - color: string; - radiusCss: number; - target: PolyMeshHandle; - enabled: boolean; - rotationSnap: number | null; - onChange?: () => void; - onObjectChange?: (event: PolyTransformControlsObjectChangeEvent) => void; - onMouseDown?: () => void; - onMouseUp?: () => void; - onDraggingChanged?: (dragging: boolean) => void; - onHoverChange?: (hovered: boolean) => void; - onDraggingStart?: () => void; - onDraggingStop?: () => void; -} - -function RotateRing({ - cssAxis, - axisKey, - color, - radiusCss, - target, - enabled, - rotationSnap, - onChange, - onObjectChange, - onMouseDown, - onMouseUp, - onDraggingChanged, - onHoverChange, - onDraggingStart, - onDraggingStop, -}: RotateRingProps) { - const cbRef = useRef({ - onChange, - onObjectChange, - onMouseDown, - onMouseUp, - onDraggingChanged, - onDraggingStart, - onDraggingStop, - enabled, - rotationSnap, - }); - cbRef.current = { - onChange, - onObjectChange, - onMouseDown, - onMouseUp, - onDraggingChanged, - onDraggingStart, - onDraggingStop, - enabled, - rotationSnap, - }; - - // Single square quad covering the ring's outer bounding box; CSS mask - // (`mask: radial-gradient(...)`) clips it to the donut shape. The mask - // reads `--ring-inner-ratio` so the donut's inner cutout scales with our - // chosen RING_HALF_THICKNESS_RATIO without hardcoding it in CSS. One DOM - // node per ring instead of `segments` segment quads. - const polygons = useMemo(() => { - const radiusWorld = radiusCss / SCENE_TILE_SIZE; - const outerWorld = radiusWorld * RING_QUAD_OUTER_RATIO; - return ringQuadPolygons({ - axis: WORLD_AXIS_FOR_CSS[cssAxis], - outerRadius: outerWorld, - color, + e.nativeEvent.clientX, + e.nativeEvent.clientY, + getDragState, + ); }); - }, [cssAxis, color, radiusCss]); - // Visible band start/end as fractions of the quad edge. The quad covers - // ±RING_QUAD_OUTER_RATIO · mid-radius; the visible ring is mid ± - // halfThickness. Normalize against the quad outer to get mask positions. - const ringInnerRatio = (1 - RING_HALF_THICKNESS_RATIO) / RING_QUAD_OUTER_RATIO; - const ringOuterRatio = (1 + RING_HALF_THICKNESS_RATIO) / RING_QUAD_OUTER_RATIO; - const onPointerDown = useCallback( - (e: PolyPointerEvent): void => { - if (!cbRef.current.enabled) return; - // No donut hit-test — let any click on the ring's quad bbox start - // the drag. The whole bbox is the click target so the rings are - // easy to land on; the visible donut mask is decoration only. - e.stopPropagation(); - const meshEl = e.eventObject.element; - const wrapper = meshEl?.closest("[data-poly-transform-controls]") as HTMLElement | null; - if (!wrapper) return; - cbRef.current.onDraggingStart?.(); - startRingDrag({ - cssAxis, + const handleRingDown = (spec: GizmoRingSpec) => (e: PolyPointerEvent) => + startFromMeshEvent(e, (wrapper) => { + startDeclarativeRingDrag( + spec, wrapper, - target, - startClientX: e.nativeEvent.clientX, - startClientY: e.nativeEvent.clientY, - rotationSnap: cbRef.current.rotationSnap, - onChange: cbRef.current.onChange, - onObjectChange: cbRef.current.onObjectChange, - onMouseDown: cbRef.current.onMouseDown, - onMouseUp: cbRef.current.onMouseUp, - onDraggingChanged: (d) => { - if (!d) cbRef.current.onDraggingStop?.(); - cbRef.current.onDraggingChanged?.(d); - }, - }); - }, - [cssAxis, target], - ); + e.nativeEvent.clientX, + e.nativeEvent.clientY, + getDragState, + ); + }); + + const hoverHandlers = (key: string) => ({ + onPointerOver: () => setHoveredKey(key), + onPointerOut: () => setHoveredKey((cur) => (cur === key ? null : cur)), + }); return ( - onHoverChange?.(true)} - onPointerOut={() => onHoverChange?.(false)} - className={`polycss-transform-gizmo polycss-transform-ring polycss-transform-ring--${axisKey}`} - // CSS variable consumed by the .polycss-transform-ring radial-gradient - // mask in styles.ts. Carries the donut's inner/outer radius ratio. - style={{ - ["--ring-inner-ratio" as string]: ringInnerRatio, - ["--ring-outer-ratio" as string]: ringOuterRatio, - }} - // Same baked-mode reasoning as the translate arrows: avoid the - // dynamic-mode atlas-rebuild flash on hover/drag color changes. - textureLighting="baked" - /> +
+ {entries.arrows.map(({ spec, polygons: arrowPolys }) => ( + + ))} + {entries.planes.map(({ spec, polygons: planePolys }) => ( + + ))} + {entries.rings.map(({ spec, polygons: ringPolys }) => ( + + ))} +
); } diff --git a/packages/react/src/controls/sharedControls.ts b/packages/react/src/controls/sharedControls.ts index f6a90f3ef..432ca5930 100644 --- a/packages/react/src/controls/sharedControls.ts +++ b/packages/react/src/controls/sharedControls.ts @@ -1,10 +1,17 @@ /** - * Shared prop types for PolyOrbitControls and PolyMapControls. + * Shared prop types and hook for PolyOrbitControls and PolyMapControls. */ +import { useEffect, useRef } from "react"; import type { PolyControlsAnimateOptions, PolyControlsCamera, } from "@layoutit/polycss-core"; +import type { + PolyCameraControlTarget, + PolyControlsBaseOptions, + PolyControlsHandle, +} from "@layoutit/polycss/runtime"; +import { useCameraContext } from "../camera/context"; export type { PolyControlsAnimateOptions, PolyControlsCamera } from "@layoutit/polycss-core"; @@ -32,3 +39,82 @@ export interface SharedControlsProps { onInteractionStart?: (camera: PolyControlsCamera) => void; onInteractionEnd?: (camera: PolyControlsCamera) => void; } + +export function usePointerControls( + factory: (target: PolyCameraControlTarget, options: PolyControlsBaseOptions) => PolyControlsHandle, + { + drag = true, + wheel = true, + dolly = false, + invert = false, + minZoom = 0.1, + maxZoom = 10, + minDistance = 0, + maxDistance = Infinity, + animate = false, + onChange, + onInteractionStart, + onInteractionEnd, + }: SharedControlsProps, +): null { + const { store, cameraRef, runtimeCameraRef, cameraElRef, applyTransformDirect } = useCameraContext(); + const controlsRef = useRef(null); + + const onChangeRef = useRef(onChange); + const onStartRef = useRef(onInteractionStart); + const onEndRef = useRef(onInteractionEnd); + onChangeRef.current = onChange; + onStartRef.current = onInteractionStart; + onEndRef.current = onInteractionEnd; + + useEffect(() => { + const el = cameraElRef.current; + if (!el) return; + const target: PolyCameraControlTarget = { + host: el, + cameraEl: el, + camera: (runtimeCameraRef?.current ?? cameraRef.current) as PolyCameraControlTarget["camera"], + applyCamera: () => { + applyTransformDirect(); + store.updateCameraFromRef(cameraRef.current); + }, + }; + const controls = factory(target, { + drag, + wheel, + dolly, + invert, + minZoom, + maxZoom, + minDistance, + maxDistance, + animate, + }); + controls.addEventListener("change", (ev) => onChangeRef.current?.(ev.camera)); + controls.addEventListener("start", (ev) => onStartRef.current?.(ev.camera)); + controls.addEventListener("end", (ev) => onEndRef.current?.(ev.camera)); + controlsRef.current = controls; + return () => { + controlsRef.current = null; + controls.destroy(); + }; + // Lifecycle bound to camera context; option updates flow through controls.update(). + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [factory, cameraElRef, cameraRef, runtimeCameraRef, applyTransformDirect, store]); + + useEffect(() => { + controlsRef.current?.update({ + drag, + wheel, + dolly, + invert, + minZoom, + maxZoom, + minDistance, + maxDistance, + animate, + }); + }, [drag, wheel, dolly, invert, minZoom, maxZoom, minDistance, maxDistance, animate]); + + return null; +} diff --git a/packages/react/src/scene/PolyIframe.tsx b/packages/react/src/scene/PolyIframe.tsx index 8d420365b..b77268f53 100644 --- a/packages/react/src/scene/PolyIframe.tsx +++ b/packages/react/src/scene/PolyIframe.tsx @@ -16,7 +16,7 @@ * whose vertices straddle the origin. */ import type { CSSProperties, IframeHTMLAttributes } from "react"; -import { BASE_TILE, type Vec3 } from "@layoutit/polycss-core"; +import { BASE_TILE, buildPolyIframeTransform, type Vec3 } from "@layoutit/polycss-core"; export interface PolyIframeProps { /** Iframe URL — forwarded to the underlying