diff --git a/.github/architecture/repo-map.md b/.github/architecture/repo-map.md index 798a6aad1..27b471d42 100644 --- a/.github/architecture/repo-map.md +++ b/.github/architecture/repo-map.md @@ -1,17 +1,17 @@ # PolyCSS Repository Map -Tracked production code scanned across `packages/*/src`, `bench/`, and `website/src`: **465 files**, **98,571 lines**. Regenerate with `pnpm map`; verified in CI by `pnpm check:map`. +Tracked production code scanned across `packages/*/src`, `bench/`, and `website/src`: **488 files**, **98,910 lines**. Regenerate with `pnpm map`; verified in CI by `pnpm check:map`. ## 1. Packages & Entry Points | Package | Visibility | Exports | Workspace deps | Src files | Src lines | Test files | |---|---|---|---|---:|---:|---:| -| `packages/core` (`@layoutit/polycss-core`) | npm | `., ./three` | — | 99 | 27,290 | 58 | +| `packages/core` (`@layoutit/polycss-core`) | npm | `., ./three` | — | 104 | 27,402 | 58 | | `packages/domformat` (`@layoutit/polycss-domformat`) | private | `., ./browser` | — | 36 | 13,165 | 0 | | `packages/fonts` (`@layoutit/polycss-fonts`) | npm | `.` | `@layoutit/polycss-core` | 7 | 1,656 | 4 | | `packages/morph` (`@layoutit/polycss-morph`) | npm | `., ./prepare` | `@layoutit/polycss`, `@layoutit/polycss-core` | 49 | 7,629 | 14 | -| `packages/polycss` (`@layoutit/polycss`) | npm | `., ./runtime, ./internal, ./elements, ./three` | `@layoutit/polycss-core` | 73 | 16,933 | 41 | +| `packages/polycss` (`@layoutit/polycss`) | npm | `., ./runtime, ./internal, ./elements, ./three` | `@layoutit/polycss-core` | 91 | 17,154 | 41 | | `packages/react` (`@layoutit/polycss-react`) | npm | `., ./three` | `@layoutit/polycss`, `@layoutit/polycss-core` | 44 | 4,651 | 31 | | `packages/skills` (`@layoutit/polycss-skills`) | npm | `.` | — | 1 | 415 | 1 | | `packages/vue` (`@layoutit/polycss-vue`) | npm | `., ./three` | `@layoutit/polycss`, `@layoutit/polycss-core` | 42 | 4,437 | 29 | @@ -45,8 +45,8 @@ Single source of truth: [`packages/workspace-aliases.mjs`](../../packages/worksp | Fan-in | Lines | File | |---:|---:|---| -| 113 | 528 | `packages/core/src/index.ts` | -| 87 | 248 | `packages/core/src/types.ts` | +| 123 | 528 | `packages/core/src/index.ts` | +| 92 | 248 | `packages/core/src/types.ts` | | 38 | 301 | `packages/react/src/index.ts` | | 33 | 119 | `website/src/components/types.ts` | | 29 | 148 | `packages/polycss/src/runtime.ts` | @@ -55,8 +55,8 @@ Single source of truth: [`packages/workspace-aliases.mjs`](../../packages/worksp | 19 | 88 | `website/src/components/GalleryWorkbench/types.ts` | | 17 | 49 | `packages/core/src/math/vec3.ts` | | 17 | 385 | `packages/polycss/src/api/createPolyScene.ts` | +| 16 | 366 | `packages/core/src/atlas/types.ts` | | 16 | 45 | `packages/polycss/src/render/textureAtlas.ts` | -| 13 | 121 | `packages/polycss/src/api/scene/internalTypes.ts` | ### Largest production source files @@ -67,13 +67,13 @@ Single source of truth: [`packages/workspace-aliases.mjs`](../../packages/worksp | 1,192 | `bench/visual-gate.mjs` | | 1,178 | `packages/domformat/src/browser.ts` | | 1,139 | `website/src/components/GalleryWorkbench/presets/presetFiles.ts` | -| 968 | `packages/polycss/src/snapshot/exportPolySceneSnapshot.ts` | -| 963 | `packages/core/src/atlas/plan.ts` | | 912 | `bench/entries/lifecycle.tsx` | | 910 | `website/src/components/GalleryWorkbench/GalleryWorkbench.tsx` | | 885 | `packages/morph/src/contracts/validation.ts` | | 860 | `packages/domformat/src/state/interaction.ts` | -| 840 | `packages/polycss/src/render/atlas/renderPolygons.ts` | +| 827 | `website/src/components/BuilderWorkbench/components/BuilderScene.tsx` | +| 825 | `website/src/components/GalleryWorkbench/hooks/useRouteSync.ts` | +| 801 | `packages/polycss/src/api/controls/gizmoEngine.ts` | ## 4. Core Render & Control Pipelines diff --git a/.github/scripts/check-doc-imports.test.mjs b/.github/scripts/check-doc-imports.test.mjs new file mode 100644 index 000000000..f8f3a50a3 --- /dev/null +++ b/.github/scripts/check-doc-imports.test.mjs @@ -0,0 +1,290 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { WORKSPACE_SOURCE_ENTRIES } from "../../packages/workspace-aliases.mjs"; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const repoRoot = path.resolve(__dirname, "..", ".."); +const packagesRoot = path.join(repoRoot, "packages"); + +const PRIVATE_SUBPATHS = new Set(["@layoutit/polycss/internal"]); + +function stripCommentsPreserveStrings(source) { + let out = ""; + let i = 0; + while (i < source.length) { + const ch = source[i]; + const next = source[i + 1]; + if (ch === "\"" || ch === "'" || ch === "`") { + const quote = ch; + out += ch; + i += 1; + while (i < source.length) { + if (source[i] === "\\" && i + 1 < source.length) { + out += source[i] + source[i + 1]; + i += 2; + continue; + } + out += source[i]; + if (source[i] === quote) { + i += 1; + break; + } + i += 1; + } + continue; + } + if (ch === "/" && next === "/") { + i += 2; + while (i < source.length && source[i] !== "\n") i += 1; + continue; + } + if (ch === "/" && next === "*") { + i += 2; + while (i < source.length && !(source[i] === "*" && source[i + 1] === "/")) i += 1; + i += 2; + continue; + } + out += ch; + i += 1; + } + return out; +} + +function resolveTsFile(baseFile, specifier) { + if (specifier.startsWith("@layoutit/")) { + const rel = WORKSPACE_SOURCE_ENTRIES[specifier]; + return rel ? path.join(packagesRoot, rel) : null; + } + const base = path.resolve(path.dirname(baseFile), specifier.replace(/\.js$/, "")); + for (const candidate of [ + `${base}.ts`, + `${base}.tsx`, + path.join(base, "index.ts"), + path.join(base, "index.tsx"), + ]) { + if (fs.existsSync(candidate)) return candidate; + } + return null; +} + +function parseModuleExports(filePath, visited = new Set()) { + const result = { values: new Set(), types: new Set() }; + if (visited.has(filePath)) return result; + visited.add(filePath); + + const stripped = stripCommentsPreserveStrings(fs.readFileSync(filePath, "utf8")); + + // export { ... } / export type { ... } + for (const match of stripped.matchAll(/export\s+(type\s+)?\{([^}]*)\}/g)) { + const blockIsType = Boolean(match[1]); + for (const part of match[2].split(",")) { + const raw = part.trim(); + if (!raw) continue; + const itemIsType = blockIsType || /^type\s+/.test(raw); + const cleaned = raw.replace(/^type\s+/, ""); + const pieces = cleaned.split(/\s+as\s+/); + const exported = (pieces[1] ?? pieces[0]).trim(); + if (!exported) continue; + if (itemIsType) result.types.add(exported); + else result.values.add(exported); + } + } + + // export [declare] [async] function/const/let/var/class/enum + for (const match of stripped.matchAll( + /export\s+(?:declare\s+)?(?:async\s+)?(?:function|const|let|var|class|enum)\s+([A-Za-z_$][\w$]*)/g, + )) { + result.values.add(match[1]); + } + + // export [declare] interface/type + for (const match of stripped.matchAll( + /export\s+(?:declare\s+)?(?:interface|type)\s+([A-Za-z_$][\w$]*)/g, + )) { + result.types.add(match[1]); + } + + // export [type] * as ns from "..." + for (const match of stripped.matchAll( + /export\s+(type\s+)?\*\s+as\s+([A-Za-z_$][\w$]*)\s+from\s+["']([^"']+)["']/g, + )) { + if (match[1]) result.types.add(match[2]); + else result.values.add(match[2]); + } + + // export [type] * from "..." + for (const match of stripped.matchAll(/export\s+(type\s+)?\*\s+from\s+["']([^"']+)["']/g)) { + const starIsType = Boolean(match[1]); + const target = resolveTsFile(filePath, match[2]); + if (!target || !fs.existsSync(target)) continue; + const nested = parseModuleExports(target, visited); + for (const name of nested.types) result.types.add(name); + for (const name of nested.values) { + if (starIsType) result.types.add(name); + else result.values.add(name); + } + } + + return result; +} + +function collectMarkdownFiles(dir, out = []) { + if (!fs.existsSync(dir)) return out; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) collectMarkdownFiles(full, out); + else if (/\.(?:md|mdx)$/.test(entry.name)) out.push(full); + } + return out; +} + +function extractCodeBlocksFromMarkdown(markdown) { + const blocks = []; + for (const match of markdown.matchAll(/```[^\n]*\n([\s\S]*?)```/g)) { + blocks.push(match[1]); + } + return blocks; +} + +function validateSnippetImports(relFile, snippet, exportMap, errors) { + const cleaned = stripCommentsPreserveStrings(snippet); + + // Check static import declarations: + // import { ... } from "spec" + // import type { ... } from "spec" + // import * as ns from "spec" + // import Def from "spec" + // import Def, { ... } from "spec" + // import "spec" + const staticImportRe = + /(?:^|[\s;])import\s+(?:(type)\s+)?(?:(\*\s+as\s+[A-Za-z_$][\w$]*)|(\{[^}]*\})|([A-Za-z_$][\w$]*)(?:\s*,\s*(\{[^}]*\}|\*\s+as\s+[A-Za-z_$][\w$]*))?)\s+from\s+["'](@layoutit\/polycss[^"']*)["']|(?:^|[\s;])import\s+["'](@layoutit\/polycss[^"']*)["']/g; + + for (const match of cleaned.matchAll(staticImportRe)) { + const isTypeImport = Boolean(match[1]); + const namedBlock = match[3] ?? (match[5]?.startsWith("{") ? match[5] : undefined); + const defaultIdent = match[4]; + const spec = match[6] ?? match[7]; + + if (PRIVATE_SUBPATHS.has(spec)) { + errors.push(`${relFile}: imports private subpath "${spec}"`); + continue; + } + const allowed = exportMap[spec]; + if (!allowed) { + errors.push(`${relFile}: unknown package specifier "${spec}"`); + continue; + } + if (defaultIdent) { + errors.push(`${relFile}: default import "${defaultIdent}" from "${spec}" (no default export)`); + } + if (namedBlock) { + const inner = namedBlock.slice(1, -1); + for (const part of inner.split(",")) { + const raw = part.trim(); + if (!raw) continue; + const itemIsType = isTypeImport || /^type\s+/.test(raw); + const sym = raw.replace(/^type\s+/, "").split(/\s+as\s+/)[0].trim(); + if (!sym) continue; + if (itemIsType) { + if (!allowed.values.has(sym) && !allowed.types.has(sym)) { + errors.push(`${relFile}: type "${sym}" is not exported by "${spec}"`); + } + } else if (!allowed.values.has(sym)) { + if (allowed.types.has(sym)) { + errors.push(`${relFile}: "${sym}" is a type-only export of "${spec}" (use "import type")`); + } else { + errors.push(`${relFile}: "${sym}" is not exported by "${spec}"`); + } + } + } + } + } + + // Dynamic import("@layoutit/polycss...") + for (const match of cleaned.matchAll(/\bimport\(\s*["'](@layoutit\/polycss[^"']*)["']\s*\)/g)) { + const spec = match[1]; + if (PRIVATE_SUBPATHS.has(spec)) { + errors.push(`${relFile}: dynamic import of private subpath "${spec}"`); + } else if (!exportMap[spec]) { + errors.push(`${relFile}: dynamic import of unknown specifier "${spec}"`); + } + } +} + +test("every @layoutit/polycss* import in READMEs, docs, landing tabs, and agent skill resolves against live barrels", () => { + const exportMap = {}; + for (const [spec, rel] of Object.entries(WORKSPACE_SOURCE_ENTRIES)) { + if (PRIVATE_SUBPATHS.has(spec)) continue; + const abs = path.join(packagesRoot, rel); + assert.ok(fs.existsSync(abs), `missing barrel packages/${rel} for ${spec}`); + exportMap[spec] = parseModuleExports(abs); + } + + const pkgReadmes = fs + .readdirSync(packagesRoot) + .filter((d) => d !== "domformat") + .map((d) => path.join(packagesRoot, d, "README.md")) + .filter((f) => fs.existsSync(f)); + + const docFiles = [ + path.join(repoRoot, "README.md"), + ...pkgReadmes, + ...collectMarkdownFiles(path.join(repoRoot, "packages/skills/skill")), + ...collectMarkdownFiles(path.join(repoRoot, "website/src/content/docs")), + ].sort(); + + assert.ok(docFiles.length >= 25, `expected at least 25 doc/skill files, found ${docFiles.length}`); + + const errors = []; + for (const absFile of docFiles) { + const relFile = path.relative(repoRoot, absFile); + const blocks = extractCodeBlocksFromMarkdown(fs.readFileSync(absFile, "utf8")); + for (const block of blocks) { + validateSnippetImports(relFile, block, exportMap, errors); + } + } + + // Also check the landing page's embedded Vanilla/React/Vue code-tab examples. + const landingPath = path.join(repoRoot, "website/src/pages/index.astro"); + if (fs.existsSync(landingPath)) { + const landingSrc = fs.readFileSync(landingPath, "utf8"); + const relLanding = path.relative(repoRoot, landingPath); + for (const match of landingSrc.matchAll(/code:\s*`([\s\S]*?)`/g)) { + validateSnippetImports(relLanding, match[1], exportMap, errors); + } + } + + assert.deepEqual(errors, []); +}); + +test("validateSnippetImports catches type-as-value imports, default imports, bad subpaths, and /internal leaks", () => { + const mockExportMap = { + "@layoutit/polycss": { values: new Set(["createPolyScene"]), types: new Set(["Polygon"]) }, + "@layoutit/polycss/three": { values: new Set(["mountPolyThreeScene"]), types: new Set() }, + }; + const errors = []; + validateSnippetImports( + "doc.md", + [ + 'import { Polygon } from "@layoutit/polycss";', + 'import type { Polygon } from "@layoutit/polycss";', + 'import Poly from "@layoutit/polycss";', + 'import { applyThreeOrthographicCameraProps } from "@layoutit/polycss/three";', + 'import { foo } from "@layoutit/polycss/internal";', + 'import "@layoutit/polycss/element";', + 'const m = await import("@layoutit/polycss/bogus");', + ].join("\n"), + mockExportMap, + errors, + ); + assert.equal(errors.length, 6); + assert.ok(errors.some((e) => e.includes('type-only export of "@layoutit/polycss"'))); + assert.ok(errors.some((e) => e.includes('default import "Poly"'))); + assert.ok(errors.some((e) => e.includes('"applyThreeOrthographicCameraProps" is not exported'))); + assert.ok(errors.some((e) => e.includes('private subpath "@layoutit/polycss/internal"'))); + assert.ok(errors.some((e) => e.includes('unknown package specifier "@layoutit/polycss/element"'))); + assert.ok(errors.some((e) => e.includes('dynamic import of unknown specifier "@layoutit/polycss/bogus"'))); +}); diff --git a/package.json b/package.json index 100592b7f..a76c64e1d 100644 --- a/package.json +++ b/package.json @@ -11,12 +11,12 @@ "license": "MIT", "repository": { "type": "git", - "url": "git+https://github.com/LayoutitStudio/polycss.git" + "url": "git+https://github.com/layoutit/polycss.git" }, "bugs": { - "url": "https://github.com/LayoutitStudio/polycss/issues" + "url": "https://github.com/layoutit/polycss/issues" }, - "homepage": "https://github.com/LayoutitStudio/polycss#readme", + "homepage": "https://github.com/layoutit/polycss#readme", "scripts": { "build": "pnpm -r --if-present build", "build:packages": "pnpm --filter './packages/*' -r build", @@ -36,16 +36,17 @@ "check:packs": "node .github/scripts/check-packs.mjs", "check:ir": "node --test bench/renderer-ir-conformance.test.mjs", "typecheck": "pnpm --filter './packages/*' -r --if-present typecheck", + "typecheck:website": "pnpm --filter @layoutit/polycss-website typecheck", "test:scripts": "node --test .github/scripts/*.test.mjs bench/visual-gate.test.mjs bench/perf-gate.test.mjs bench/lifecycle-gate.test.mjs", "check:guards": "pnpm test:scripts && pnpm check:readmes && pnpm check:skill && pnpm check:map && pnpm check:boundaries && pnpm check:mirrors --require-base && pnpm check:exports", - "verify": "pnpm check:guards && pnpm test && pnpm build:packages && pnpm typecheck && pnpm check:ir && pnpm check:packs && pnpm bench:build && pnpm --filter './examples/*' -r build", + "verify": "pnpm check:guards && pnpm test && pnpm build:packages && pnpm typecheck && pnpm typecheck:website && pnpm check:ir && pnpm check:packs && pnpm bench:build && pnpm --filter './examples/*' -r build", "publish:all": "pnpm sync:readmes && pnpm --filter './packages/*' --filter '!@layoutit/polycss-domformat' -r publish --access public", "dev:website": "pnpm --filter @layoutit/polycss-website dev", "gallery:domformat": "pnpm --filter @layoutit/polycss-website generate:domformat", "gallery:domformat:prove": "pnpm --filter @layoutit/polycss-website prove:domformat", "gallery:domformat:verify": "pnpm --filter @layoutit/polycss-website verify:domformat", "gallery:domformat:verify:fresh": "pnpm --filter @layoutit/polycss-website verify:domformat:fresh", - "build:website": "pnpm --filter @layoutit/polycss-website build", + "build:website": "pnpm typecheck:website && pnpm --filter @layoutit/polycss-website build", "bench:build": "node bench/build.mjs", "bench:serve": "node bench/perf-serve.mjs --port 4400", "bench:perf": "node bench/build.mjs && node bench/perf-bench.mjs", diff --git a/packages/core/package.json b/packages/core/package.json index cff306e8e..e0f3de9f9 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -9,13 +9,13 @@ "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/LayoutitStudio/polycss.git", + "url": "https://github.com/layoutit/polycss.git", "directory": "packages/core" }, "bugs": { - "url": "https://github.com/LayoutitStudio/polycss/issues" + "url": "https://github.com/layoutit/polycss/issues" }, - "homepage": "https://github.com/LayoutitStudio/polycss#readme", + "homepage": "https://github.com/layoutit/polycss#readme", "files": [ "dist" ], diff --git a/packages/core/src/atlas/plan.ts b/packages/core/src/atlas/plan.ts index 12a29c298..9c72b60e0 100644 --- a/packages/core/src/atlas/plan.ts +++ b/packages/core/src/atlas/plan.ts @@ -1,29 +1,8 @@ -import type { - Polygon, - PolyPointLight, - TextureTriangle, - Vec2, - Vec3, -} from "../types"; +import type { Polygon, Vec3 } from "../types"; import { crossVec } from "../math/vec3"; -export { crossVec }; import { DEFAULT_TILE, - DEFAULT_LIGHT_DIR, - DEFAULT_LIGHT_COLOR, - DEFAULT_LIGHT_INTENSITY, - DEFAULT_AMBIENT_COLOR, - DEFAULT_AMBIENT_INTENSITY, - BASIS_EPS, - RECT_EPS, - SURFACE_NORMAL_EPS, - SURFACE_DISTANCE_EPS, - SEAM_LIGHT_EPS, ATLAS_CANONICAL_SIZE_EXPLICIT, - PROJECTIVE_QUAD_DENOM_EPS, - PROJECTIVE_QUAD_MAX_WEIGHT_RATIO, - PROJECTIVE_QUAD_BLEED, - SOLID_QUAD_CANONICAL_SIZE, resolveSeamBleedPx, seamBleedPrimitiveRatio, } from "./constants"; @@ -32,710 +11,81 @@ import type { TextureTrianglePlan, UvAffine, UvSampleRect, - LocalBasis, - BasisOptions, BasisHint, - PolygonBasisInfo, ProjectiveQuadGuardSettings, ProjectiveQuadGuardOverrides, - ProjectiveQuadCoefficients, SolidTrianglePlanOptions, InternalSolidTrianglePlanOptions, - StablePlanBasis, ComputeTextureAtlasPlanOptions, } from "./types"; import { formatMatrix3dValues } from "./matrix"; import { cssPoints, computeSurfaceNormal, - isConvexPolygonPoints, - offsetConvexPolygonPoints, - offsetConvexPolygonPointsByEdgeAmounts, stableBasisFromPlan, } from "./solidTriangle"; -import { textureTintFactors, shadePolygon, type PointLightContrib } from "./paintDefaults"; import { computePlanSeamBleedEdgeAmounts, computeSeamBleedInsets, - seamBleedAmountArray, } from "./edgeRepair"; import { resolvePolyTextureUrl } from "./textureSource"; - -function finiteNumber(value: unknown, fallback: number): number { - return typeof value === "number" && Number.isFinite(value) ? value : fallback; -} - -export function resolveProjectiveQuadGuards(overrides: ProjectiveQuadGuardOverrides | undefined): ProjectiveQuadGuardSettings { - const overrideMaxWeightRatio = overrides?.maxWeightRatio; - const denomEps = Math.max( - 0, - finiteNumber(overrides?.denomEps, PROJECTIVE_QUAD_DENOM_EPS), - ); - const maxWeightRatio = typeof overrideMaxWeightRatio === "number" && - Number.isFinite(overrideMaxWeightRatio) && - overrideMaxWeightRatio > 0 - ? Math.max(1, overrideMaxWeightRatio) - : PROJECTIVE_QUAD_MAX_WEIGHT_RATIO; - const bleed = Math.max( - 0, - finiteNumber(overrides?.bleed, PROJECTIVE_QUAD_BLEED), - ); - - return { - denomEps, - maxWeightRatio, - bleed, - disableGuards: overrides?.disableGuards === true, - }; -} - -export function computeProjectiveQuadCoefficients( - q: Array<[number, number]>, - guards: ProjectiveQuadGuardSettings, -): ProjectiveQuadCoefficients | null { - if (q.length !== 4 || !isConvexPolygonPoints(q)) return null; - - const [q0, q1, q2, q3] = q; - const sx = q0[0] - q1[0] + q2[0] - q3[0]; - const sy = q0[1] - q1[1] + q2[1] - q3[1]; - const dx1 = q1[0] - q2[0]; - const dx2 = q3[0] - q2[0]; - const dy1 = q1[1] - q2[1]; - const dy2 = q3[1] - q2[1]; - const det = dx1 * dy2 - dy1 * dx2; - if (Math.abs(det) <= BASIS_EPS) return null; - - const g = (sx * dy2 - sy * dx2) / det; - const h = (dx1 * sy - dy1 * sx) / det; - const weights = [1, 1 + g, 1 + g + h, 1 + h]; - if (weights.some((weight) => !Number.isFinite(weight))) { - return null; - } - - const minWeight = Math.min(...weights); - const maxWeight = Math.max(...weights); - if (!guards.disableGuards) { - if (minWeight <= guards.denomEps) return null; - // Very large homogeneous-weight variation means the rectangle's vanishing - // line is too close to the primitive. Chrome can then tessellate the leaf - // visibly wrong; the clipped polygon path is steadier for those quads. - if (maxWeight / minWeight > guards.maxWeightRatio) return null; - } - - return { - g, - h, - w1: 1 + g, - w3: 1 + h, - }; -} - -export function computeProjectiveQuadMatrix( - screenPts: number[], - xAxis: Vec3, - yAxis: Vec3, - normal: Vec3, - tx: number, - ty: number, - tz: number, - guards: ProjectiveQuadGuardSettings, - seamBleedEdgeAmounts?: ReadonlyMap, -): string | null { - if (screenPts.length !== 8) return null; - const rawQ: Array<[number, number]> = [ - [screenPts[0], screenPts[1]], - [screenPts[2], screenPts[3]], - [screenPts[4], screenPts[5]], - [screenPts[6], screenPts[7]], - ]; - if (!computeProjectiveQuadCoefficients(rawQ, guards)) return null; - - const edgeAmounts = seamBleedAmountArray(4, seamBleedEdgeAmounts); - const expandedPts = edgeAmounts - ? offsetConvexPolygonPointsByEdgeAmounts(screenPts, edgeAmounts) - : offsetConvexPolygonPoints(screenPts, guards.bleed); - const q: Array<[number, number]> = [ - [expandedPts[0], expandedPts[1]], - [expandedPts[2], expandedPts[3]], - [expandedPts[4], expandedPts[5]], - [expandedPts[6], expandedPts[7]], - ]; - const coeffs = computeProjectiveQuadCoefficients(q, guards); - if (!coeffs) return null; - const { g, h, w1, w3 } = coeffs; - const [q0, q1, , q3] = q; - - const p0: Vec3 = [ - tx + q0[0] * xAxis[0] + q0[1] * yAxis[0], - ty + q0[0] * xAxis[1] + q0[1] * yAxis[1], - tz + q0[0] * xAxis[2] + q0[1] * yAxis[2], - ]; - const projectiveColumn = ([x, y]: Vec2, weight: number): Vec3 => [ - (weight - 1) * tx + (weight * x - q0[0]) * xAxis[0] + (weight * y - q0[1]) * yAxis[0], - (weight - 1) * ty + (weight * x - q0[0]) * xAxis[1] + (weight * y - q0[1]) * yAxis[1], - (weight - 1) * tz + (weight * x - q0[0]) * xAxis[2] + (weight * y - q0[1]) * yAxis[2], - ]; - - const values = [ - ...projectiveColumn(q1, w1), g, - ...projectiveColumn(q3, w3), h, - normal[0], normal[1], normal[2], 0, - p0[0], p0[1], p0[2], 1, - ]; - for (let i = 0; i < 8; i += 1) values[i] /= SOLID_QUAD_CANONICAL_SIZE; - return formatMatrix3dValues(values, 6); -} - -export function dotVec(a: Vec3, b: Vec3): number { - return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; -} - -export function isBasisOptimizable(polygon: Polygon): boolean { - return !polygon.texture; -} - -export function getPolygonBasisInfo( - polygon: Polygon, - tile: number, - elev: number, -): PolygonBasisInfo | null { - if (!polygon.vertices || polygon.vertices.length < 3) return null; - const pts = cssPoints(polygon.vertices, tile, elev); - const normal = computeSurfaceNormal(pts); - if (!normal) return null; - return { - pts, - normal, - planeD: dotVec(normal, pts[0]), - optimizable: isBasisOptimizable(polygon), - }; -} - -export function compatibleSurface( - a: PolygonBasisInfo | null, - b: PolygonBasisInfo | null, -): boolean { - if (!a || !b || !a.optimizable || !b.optimizable) return false; - return compatibleBleedSurface(a, b); -} - -export function compatibleBleedSurface( - a: PolygonBasisInfo | null, - b: PolygonBasisInfo | null, -): boolean { - if (!a || !b) return false; - if (dotVec(a.normal, b.normal) < 1 - SURFACE_NORMAL_EPS) return false; - return Math.abs(a.planeD - b.planeD) <= SURFACE_DISTANCE_EPS; -} - -export function seamLightBrightness( - info: PolygonBasisInfo | null, - options: SolidTrianglePlanOptions, -): number | null { - if (!info) return null; - const directionalCfg = options.directionalLight; - const ambientCfg = options.ambientLight; - const lightDir = directionalCfg?.direction ?? DEFAULT_LIGHT_DIR; - const lightColor = directionalCfg?.color ?? DEFAULT_LIGHT_COLOR; - const lightIntensity = Math.max(0, directionalCfg?.intensity ?? DEFAULT_LIGHT_INTENSITY); - const ambientColor = ambientCfg?.color ?? DEFAULT_AMBIENT_COLOR; - const ambientIntensity = Math.max(0, ambientCfg?.intensity ?? DEFAULT_AMBIENT_INTENSITY); - const lLen = Math.hypot(lightDir[0], lightDir[1], lightDir[2]) || 1; - const lx = lightDir[0] / lLen, ly = lightDir[1] / lLen, lz = lightDir[2] / lLen; - const directScale = lightIntensity * Math.max(0, info.normal[0] * lx + info.normal[1] * ly + info.normal[2] * lz); - const tint = textureTintFactors(directScale, lightColor, ambientColor, ambientIntensity); - return tint.r * 0.2126 + tint.g * 0.7152 + tint.b * 0.0722; -} - -/** - * Per-face point-light contributions for a polygon. Each scene point light - * (already in MESH-LOCAL user coords via the renderer) is converted to the - * CSS frame the polygon's `cssPts` use, then a direction-only Lambert scale - * is computed against the face centroid + normal. Returns `undefined` when - * there are no point lights so the shading fast path is unchanged. - */ -export function computePointContribs( - pointLights: readonly PolyPointLight[] | undefined, - cssPts: Vec3[], - normal: Vec3, - tile: number, - elev: number, -): PointLightContrib[] | undefined { - if (!pointLights || pointLights.length === 0) return undefined; - let cx = 0, cy = 0, cz = 0; - for (const p of cssPts) { cx += p[0]; cy += p[1]; cz += p[2]; } - const inv = 1 / cssPts.length; - cx *= inv; cy *= inv; cz *= inv; - const out: PointLightContrib[] = []; - for (const pl of pointLights) { - // Mesh-local user position → CSS frame (same axis swap × tile/elev as cssPoints). - const px = pl.position[1] * tile, py = pl.position[0] * tile, pz = pl.position[2] * elev; - let dx = px - cx, dy = py - cy, dz = pz - cz; - const d = Math.hypot(dx, dy, dz) || 1; - dx /= d; dy /= d; dz /= d; - const lambert = normal[0] * dx + normal[1] * dy + normal[2] * dz; - if (lambert <= 0) continue; - out.push({ color: pl.color ?? "#ffffff", scale: Math.max(0, pl.intensity ?? 1) * lambert }); - } - return out.length ? out : undefined; -} - -export function basisAxisKey(axis: Vec3): string { - const canonical: Vec3 = [...axis] as Vec3; - const first = Math.abs(canonical[0]) > BASIS_EPS - ? 0 - : Math.abs(canonical[1]) > BASIS_EPS - ? 1 - : 2; - if (canonical[first] < 0) { - canonical[0] *= -1; - canonical[1] *= -1; - canonical[2] *= -1; - } - return `${canonical[0].toFixed(6)},${canonical[1].toFixed(6)},${canonical[2].toFixed(6)}`; -} - -export function makeLocalBasis( - pts: Vec3[], - origin: Vec3, - normal: Vec3, - rawXAxis: Vec3, - options: { boundsOrigin?: Vec3; snapBounds?: boolean } = {}, -): LocalBasis | null { - const dot = dotVec(rawXAxis, normal); - const planeX: Vec3 = [ - rawXAxis[0] - dot * normal[0], - rawXAxis[1] - dot * normal[1], - rawXAxis[2] - dot * normal[2], - ]; - const xLength = Math.hypot(planeX[0], planeX[1], planeX[2]); - if (xLength <= BASIS_EPS) return null; - - const xAxis: Vec3 = [ - planeX[0] / xLength, - planeX[1] / xLength, - planeX[2] / xLength, - ]; - const yAxisRaw: Vec3 = [ - normal[1] * xAxis[2] - normal[2] * xAxis[1], - normal[2] * xAxis[0] - normal[0] * xAxis[2], - normal[0] * xAxis[1] - normal[1] * xAxis[0], - ]; - const yLength = Math.hypot(yAxisRaw[0], yAxisRaw[1], yAxisRaw[2]); - if (yLength <= BASIS_EPS) return null; - const yAxis: Vec3 = [ - yAxisRaw[0] / yLength, - yAxisRaw[1] / yLength, - yAxisRaw[2] / yLength, - ]; - - const local2D = pts.map((p): Vec2 => { - const dx = p[0] - origin[0], dy = p[1] - origin[1], dz = p[2] - origin[2]; - return [ - dx * xAxis[0] + dy * xAxis[1] + dz * xAxis[2], - dx * yAxis[0] + dy * yAxis[1] + dz * yAxis[2], - ]; - }); - - const boundsOrigin = options.boundsOrigin ?? origin; - const odx = origin[0] - boundsOrigin[0]; - const ody = origin[1] - boundsOrigin[1]; - const odz = origin[2] - boundsOrigin[2]; - const originOffsetX = odx * xAxis[0] + ody * xAxis[1] + odz * xAxis[2]; - const originOffsetY = odx * yAxis[0] + ody * yAxis[1] + odz * yAxis[2]; - let xMin = Infinity, yMin = Infinity, xMax = -Infinity, yMax = -Infinity; - for (const [x, y] of local2D) { - const boundsX = x + originOffsetX; - const boundsY = y + originOffsetY; - if (boundsX < xMin) xMin = boundsX; if (boundsX > xMax) xMax = boundsX; - if (boundsY < yMin) yMin = boundsY; if (boundsY > yMax) yMax = boundsY; - } - - const w = xMax - xMin; - const h = yMax - yMin; - if (!Number.isFinite(w) || !Number.isFinite(h)) return null; - - const boxMinX = options.snapBounds ? Math.floor(xMin + RECT_EPS) : xMin; - const boxMinY = options.snapBounds ? Math.floor(yMin + RECT_EPS) : yMin; - const boxMaxX = options.snapBounds ? Math.ceil(xMax - RECT_EPS) : xMax; - const boxMaxY = options.snapBounds ? Math.ceil(yMax - RECT_EPS) : yMax; - const canvasW = Math.max(1, options.snapBounds ? boxMaxX - boxMinX : Math.ceil(w)); - const canvasH = Math.max(1, options.snapBounds ? boxMaxY - boxMinY : Math.ceil(h)); - return { - xAxis, - yAxis, - local2D, - shiftX: originOffsetX - boxMinX, - shiftY: originOffsetY - boxMinY, - canvasW, - canvasH, - pixelArea: canvasW * canvasH, - rawArea: w * h, - }; -} - -function pointKey(point: Vec3): string { - return `${point[0]},${point[1]},${point[2]}`; -} - -function canonicalEdgeVector(a: Vec3, b: Vec3): Vec3 { - return pointKey(a) < pointKey(b) - ? [b[0] - a[0], b[1] - a[1], b[2] - a[2]] - : [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; -} - -function edgeKey(a: Vec3, b: Vec3): string { - const ak = pointKey(a); - const bk = pointKey(b); - return ak < bk ? `${ak}|${bk}` : `${bk}|${ak}`; -} - -export function evaluateIslandAxis( - component: number[], - infos: Array, - axis: Vec3, - boundsOrigin: Vec3, -): { pixelArea: number; rawArea: number } | null { - let pixelArea = 0; - let rawArea = 0; - for (const index of component) { - const info = infos[index]; - if (!info) return null; - const basis = makeLocalBasis(info.pts, info.pts[0], info.normal, axis, { - boundsOrigin, - snapBounds: true, - }); - if (!basis) return null; - pixelArea += basis.pixelArea; - rawArea += basis.rawArea; - } - return { pixelArea, rawArea }; -} - -export function chooseIslandXAxis( - component: number[], - infos: Array, -): BasisHint | null { - const boundsOrigin = infos[component[0]]?.pts[0]; - if (!boundsOrigin) return null; - let baseline: { pixelArea: number; rawArea: number } | null = { pixelArea: 0, rawArea: 0 }; - let best: { xAxis: Vec3; pixelArea: number; rawArea: number } | null = null; - const seen = new Set(); - - for (const polygonIndex of component) { - const info = infos[polygonIndex]; - if (!info) continue; - - const firstEdge: Vec3 = [ - info.pts[1][0] - info.pts[0][0], - info.pts[1][1] - info.pts[0][1], - info.pts[1][2] - info.pts[0][2], - ]; - const firstBasis = makeLocalBasis(info.pts, info.pts[0], info.normal, firstEdge); - if (baseline && firstBasis) { - baseline.pixelArea += firstBasis.pixelArea; - baseline.rawArea += firstBasis.rawArea; - } else { - baseline = null; - } - - for (let i = 0; i < info.pts.length; i++) { - const rawAxis = canonicalEdgeVector(info.pts[i], info.pts[(i + 1) % info.pts.length]); - const basis = makeLocalBasis(info.pts, info.pts[0], info.normal, rawAxis); - if (!basis) continue; - const key = basisAxisKey(basis.xAxis); - if (seen.has(key)) continue; - seen.add(key); - - const candidate = evaluateIslandAxis(component, infos, basis.xAxis, boundsOrigin); - if (!candidate) continue; - if ( - !best || - candidate.pixelArea < best.pixelArea || - (candidate.pixelArea === best.pixelArea && candidate.rawArea < best.rawArea - RECT_EPS) - ) { - best = { xAxis: basis.xAxis, ...candidate }; - } - } - } - - if (!best) return null; - if ( - baseline && - ( - best.pixelArea < baseline.pixelArea || - (best.pixelArea === baseline.pixelArea && best.rawArea <= baseline.rawArea + RECT_EPS) - ) - ) { - return { xAxis: best.xAxis, boundsOrigin, seamEdges: new Set() }; - } - return null; -} - -export function buildBasisHints( - polygons: Polygon[], - options: SolidTrianglePlanOptions, -): Array { - const tile = options.tileSize ?? DEFAULT_TILE; - const elev = options.layerElevation ?? tile; - const infos = polygons.map((polygon) => getPolygonBasisInfo(polygon, tile, elev)); - const edgeOwners = new Map>(); - const seamEdges = polygons.map(() => new Set()); - const textureEdgeRepairEdges = polygons.map(() => new Set()); - for (let polygonIndex = 0; polygonIndex < polygons.length; polygonIndex++) { - const vertices = polygons[polygonIndex].vertices; - if (!vertices || vertices.length < 3) continue; - for (let edgeIndex = 0; edgeIndex < vertices.length; edgeIndex++) { - const key = edgeKey( - vertices[edgeIndex], - vertices[(edgeIndex + 1) % vertices.length], - ); - const owners = edgeOwners.get(key); - const owner = { polygon: polygonIndex, edge: edgeIndex }; - if (owners) owners.push(owner); - else edgeOwners.set(key, [owner]); - } - } - - const adjacency = polygons.map(() => new Set()); - for (const owners of edgeOwners.values()) { - if (owners.length < 2) continue; - for (let i = 0; i < owners.length; i++) { - for (let j = i + 1; j < owners.length; j++) { - const aOwner = owners[i]; - const bOwner = owners[j]; - const a = aOwner.polygon; - const b = bOwner.polygon; - if (polygons[a].texture && polygons[b].texture) { - textureEdgeRepairEdges[aOwner.polygon].add(aOwner.edge); - textureEdgeRepairEdges[bOwner.polygon].add(bOwner.edge); - } - if (compatibleBleedSurface(infos[a], infos[b])) { - seamEdges[aOwner.polygon].add(aOwner.edge); - seamEdges[bOwner.polygon].add(bOwner.edge); - } else { - const aLight = seamLightBrightness(infos[a], options); - const bLight = seamLightBrightness(infos[b], options); - if (aLight !== null && bLight !== null) { - if (aLight <= bLight + SEAM_LIGHT_EPS) seamEdges[aOwner.polygon].add(aOwner.edge); - if (bLight <= aLight + SEAM_LIGHT_EPS) seamEdges[bOwner.polygon].add(bOwner.edge); - } - } - if (!compatibleSurface(infos[a], infos[b])) continue; - adjacency[a].add(b); - adjacency[b].add(a); - } - } - } - - const hints: Array = Array(polygons.length).fill(undefined); - const visited = new Set(); - for (let i = 0; i < polygons.length; i++) { - if (visited.has(i) || !infos[i]?.optimizable) continue; - const component: number[] = []; - const stack = [i]; - visited.add(i); - while (stack.length > 0) { - const current = stack.pop()!; - component.push(current); - for (const next of adjacency[current]) { - if (visited.has(next)) continue; - visited.add(next); - stack.push(next); - } - } - - if (component.length < 2) continue; - const hint = chooseIslandXAxis(component, infos); - if (!hint) continue; - for (const index of component) { - hints[index] = { - xAxis: hint.xAxis, - boundsOrigin: hint.boundsOrigin, - seamEdges: seamEdges[index], - textureEdgeRepairEdges: textureEdgeRepairEdges[index], - }; - } - } - - for (let i = 0; i < polygons.length; i++) { - if (!hints[i] && (seamEdges[i].size > 0 || textureEdgeRepairEdges[i].size > 0)) { - hints[i] = { - seamEdges: seamEdges[i], - textureEdgeRepairEdges: textureEdgeRepairEdges[i], - }; - } - } - - return hints; -} - -export function chooseLocalBasis( - pts: Vec3[], - origin: Vec3, - normal: Vec3, - options: BasisOptions, -): LocalBasis | null { - if (options.optimize && options.fixedXAxis) { - return makeLocalBasis(pts, origin, normal, options.fixedXAxis, { - boundsOrigin: options.boundsOrigin, - snapBounds: options.snapBounds, - }); - } - - let best: LocalBasis | null = null; - const seamCandidates = options.optimize && options.seamEdges && options.seamEdges.size > 0 - ? Array.from(options.seamEdges) - : null; - const candidateEdges = seamCandidates ?? ( - options.optimize - ? pts.map((_, edgeIndex) => edgeIndex) - : [0] - ); - - for (const i of candidateEdges) { - const next = (i + 1) % pts.length; - const edge = seamCandidates - ? canonicalEdgeVector(pts[i], pts[next]) - : [ - pts[next][0] - pts[i][0], - pts[next][1] - pts[i][1], - pts[next][2] - pts[i][2], - ] as Vec3; - const candidate = makeLocalBasis(pts, origin, normal, edge, { - boundsOrigin: options.boundsOrigin, - snapBounds: options.snapBounds, - }); - if (!candidate) continue; - - if ( - !best || - candidate.pixelArea < best.pixelArea || - (candidate.pixelArea === best.pixelArea && candidate.rawArea < best.rawArea - RECT_EPS) - ) { - best = candidate; - } - } - - return best; -} - -export function isFullRectBasis(basis: LocalBasis): boolean { - if (basis.local2D.length !== 4) return false; - - const xs: number[] = []; - const ys: number[] = []; - const addUnique = (list: number[], value: number): void => { - for (const existing of list) { - if (Math.abs(existing - value) <= RECT_EPS) return; - } - list.push(value); - }; - - for (const [x, y] of basis.local2D) { - addUnique(xs, x + basis.shiftX); - addUnique(ys, y + basis.shiftY); - } - if (xs.length !== 2 || ys.length !== 2) return false; - - xs.sort((a, b) => a - b); - ys.sort((a, b) => a - b); - if ( - Math.abs(xs[0]) > RECT_EPS || - Math.abs(ys[0]) > RECT_EPS || - xs[1] - xs[0] <= RECT_EPS || - ys[1] - ys[0] <= RECT_EPS - ) { - return false; - } - - for (const [rawX, rawY] of basis.local2D) { - const x = rawX + basis.shiftX; - const y = rawY + basis.shiftY; - const onX = Math.abs(x - xs[0]) <= RECT_EPS || Math.abs(x - xs[1]) <= RECT_EPS; - const onY = Math.abs(y - ys[0]) <= RECT_EPS || Math.abs(y - ys[1]) <= RECT_EPS; - if (!onX || !onY) return false; - } - return true; -} - -export function computeUvAffine(points: Vec2[], uvs: Vec2[]): UvAffine | null { - if (points.length < 3 || uvs.length < 3) return null; - const [p0, p1, p2] = points; - const [uv0, uv1, uv2] = uvs; - const sx0 = p0[0], sy0 = p0[1]; - const sx1 = p1[0], sy1 = p1[1]; - const sx2 = p2[0], sy2 = p2[1]; - const u0 = uv0[0], V0 = 1 - uv0[1]; - const u1 = uv1[0], V1 = 1 - uv1[1]; - const u2 = uv2[0], V2 = 1 - uv2[1]; - const du1 = u1 - u0, dV1 = V1 - V0; - const du2 = u2 - u0, dV2 = V2 - V0; - const det = du1 * dV2 - du2 * dV1; - if (Math.abs(det) <= 1e-9) return null; - - const dx1 = sx1 - sx0, dx2 = sx2 - sx0; - const dy1 = sy1 - sy0, dy2 = sy2 - sy0; - const affine = { - a: (dx1 * dV2 - dx2 * dV1) / det, - b: (du1 * dx2 - du2 * dx1) / det, - c: (dy1 * dV2 - dy2 * dV1) / det, - d: (du1 * dy2 - du2 * dy1) / det, - e: 0, - f: 0, - }; - affine.e = sx0 - affine.a * u0 - affine.b * V0; - affine.f = sy0 - affine.c * u0 - affine.d * V0; - return affine; -} - -export function computeUvSampleRect(uvs: Vec2[]): UvSampleRect | null { - if (uvs.length === 0) return null; - let minU = Infinity; - let minV = Infinity; - let maxU = -Infinity; - let maxV = -Infinity; - for (const uv of uvs) { - const u = uv[0]; - const v = 1 - uv[1]; - if (!Number.isFinite(u) || !Number.isFinite(v)) return null; - minU = Math.min(minU, u); - maxU = Math.max(maxU, u); - minV = Math.min(minV, v); - maxV = Math.max(maxV, v); - } - return { minU, minV, maxU, maxV }; -} - -export function projectTextureTriangle( - triangle: TextureTriangle, - tile: number, - elev: number, - origin: Vec3, - xAxis: Vec3, - yAxis: Vec3, - shiftX: number, - shiftY: number, -): TextureTrianglePlan | null { - const pts = cssPoints(triangle.vertices, tile, elev); - const points = pts.map((point): Vec2 => { - const dx = point[0] - origin[0]; - const dy = point[1] - origin[1]; - const dz = point[2] - origin[2]; - return [ - dx * xAxis[0] + dy * xAxis[1] + dz * xAxis[2] + shiftX, - dx * yAxis[0] + dy * yAxis[1] + dz * yAxis[2] + shiftY, - ]; - }); - const uvAffine = computeUvAffine(points, triangle.uvs); - const uvSampleRect = computeUvSampleRect(triangle.uvs); - if (!uvAffine && !uvSampleRect) return null; - return { - screenPts: points.flatMap(([x, y]) => [x, y]), - uvAffine, - uvSampleRect, - }; -} +import { + resolveProjectiveQuadGuards, + computeProjectiveQuadCoefficients, + computeProjectiveQuadMatrix, +} from "./plan/projectiveQuad"; +import { + dotVec, + basisAxisKey, + makeLocalBasis, + chooseLocalBasis, + isFullRectBasis, +} from "./plan/localBasis"; +import { + seamLightBrightness, + computePointContribs, + computePlanLighting, +} from "./plan/lighting"; +import { + isBasisOptimizable, + getPolygonBasisInfo, + compatibleSurface, + compatibleBleedSurface, + evaluateIslandAxis, + chooseIslandXAxis, + buildBasisHints, +} from "./plan/basisHints"; +import { + computeUvAffine, + computeUvSampleRect, + projectTextureTriangle, +} from "./plan/uv"; + +export { + crossVec, + resolveProjectiveQuadGuards, + computeProjectiveQuadCoefficients, + computeProjectiveQuadMatrix, + dotVec, + isBasisOptimizable, + getPolygonBasisInfo, + compatibleSurface, + compatibleBleedSurface, + seamLightBrightness, + computePointContribs, + basisAxisKey, + makeLocalBasis, + evaluateIslandAxis, + chooseIslandXAxis, + buildBasisHints, + chooseLocalBasis, + isFullRectBasis, + computeUvAffine, + computeUvSampleRect, + projectTextureTriangle, + // Re-export from solidTriangle so callers that import from plan continue to work. + stableBasisFromPlan, +}; export function computeTextureAtlasPlan( polygon: Polygon, @@ -842,26 +192,15 @@ export function computeTextureAtlasPlan( ) : null; - const directionalCfg = options.directionalLight; - const ambientCfg = options.ambientLight; - const lightDir = directionalCfg?.direction ?? DEFAULT_LIGHT_DIR; - const lightColor = directionalCfg?.color ?? DEFAULT_LIGHT_COLOR; - const lightIntensity = Math.max(0, directionalCfg?.intensity ?? DEFAULT_LIGHT_INTENSITY); - const ambientColor = ambientCfg?.color ?? DEFAULT_AMBIENT_COLOR; - const ambientIntensity = Math.max(0, ambientCfg?.intensity ?? DEFAULT_AMBIENT_INTENSITY); - const lLen = Math.hypot(lightDir[0], lightDir[1], lightDir[2]) || 1; - const lx = lightDir[0] / lLen, ly = lightDir[1] / lLen, lz = lightDir[2] / lLen; - // Decoupled: directional and ambient sum independently. No (1 - ambient) - // budget — matches three.js's lighting model. - const occluded = options.lightOccludedPolyIndices?.has(index) ?? false; - const directScale = occluded - ? 0 - : lightIntensity * Math.max(0, normal[0] * lx + normal[1] * ly + normal[2] * lz); - // Point lights are occlusion-shaded the same as directional: a polygon the - // directional light can't reach (occluded) still gets point-light + ambient. - const pointContribs = computePointContribs(options.pointLights, pts, normal, tile, elev); - const textureTint = textureTintFactors(directScale, lightColor, ambientColor, ambientIntensity, pointContribs); - const shadedColor = shadePolygon(polygon.color ?? "#cccccc", directScale, lightColor, ambientColor, ambientIntensity, pointContribs); + const { textureTint, shadedColor } = computePlanLighting( + polygon, + index, + pts, + normal, + tile, + elev, + options, + ); let uvAffine: UvAffine | null = null; let uvSampleRect: UvSampleRect | null = null; @@ -958,6 +297,3 @@ export function computeTextureAtlasPlanPublic( : undefined); return computeTextureAtlasPlan(polygon, index, internalOptions, projectiveQuadGuards, basisHint); } - -// Re-export from solidTriangle so callers that import from plan continue to work. -export { stableBasisFromPlan }; diff --git a/packages/core/src/atlas/plan/basisHints.ts b/packages/core/src/atlas/plan/basisHints.ts new file mode 100644 index 000000000..4216d20d8 --- /dev/null +++ b/packages/core/src/atlas/plan/basisHints.ts @@ -0,0 +1,240 @@ +import type { Polygon, Vec3 } from "../../types"; +import { + DEFAULT_TILE, + RECT_EPS, + SURFACE_NORMAL_EPS, + SURFACE_DISTANCE_EPS, + SEAM_LIGHT_EPS, +} from "../constants"; +import type { + BasisHint, + PolygonBasisInfo, + SolidTrianglePlanOptions, +} from "../types"; +import { cssPoints, computeSurfaceNormal } from "../solidTriangle"; +import { + dotVec, + basisAxisKey, + makeLocalBasis, + canonicalEdgeVector, + edgeKey, +} from "./localBasis"; +import { seamLightBrightness } from "./lighting"; + +export function isBasisOptimizable(polygon: Polygon): boolean { + return !polygon.texture; +} + +export function getPolygonBasisInfo( + polygon: Polygon, + tile: number, + elev: number, +): PolygonBasisInfo | null { + if (!polygon.vertices || polygon.vertices.length < 3) return null; + const pts = cssPoints(polygon.vertices, tile, elev); + const normal = computeSurfaceNormal(pts); + if (!normal) return null; + return { + pts, + normal, + planeD: dotVec(normal, pts[0]), + optimizable: isBasisOptimizable(polygon), + }; +} + +export function compatibleSurface( + a: PolygonBasisInfo | null, + b: PolygonBasisInfo | null, +): boolean { + if (!a || !b || !a.optimizable || !b.optimizable) return false; + return compatibleBleedSurface(a, b); +} + +export function compatibleBleedSurface( + a: PolygonBasisInfo | null, + b: PolygonBasisInfo | null, +): boolean { + if (!a || !b) return false; + if (dotVec(a.normal, b.normal) < 1 - SURFACE_NORMAL_EPS) return false; + return Math.abs(a.planeD - b.planeD) <= SURFACE_DISTANCE_EPS; +} + +export function evaluateIslandAxis( + component: number[], + infos: Array, + axis: Vec3, + boundsOrigin: Vec3, +): { pixelArea: number; rawArea: number } | null { + let pixelArea = 0; + let rawArea = 0; + for (const index of component) { + const info = infos[index]; + if (!info) return null; + const basis = makeLocalBasis(info.pts, info.pts[0], info.normal, axis, { + boundsOrigin, + snapBounds: true, + }); + if (!basis) return null; + pixelArea += basis.pixelArea; + rawArea += basis.rawArea; + } + return { pixelArea, rawArea }; +} + +export function chooseIslandXAxis( + component: number[], + infos: Array, +): BasisHint | null { + const boundsOrigin = infos[component[0]]?.pts[0]; + if (!boundsOrigin) return null; + let baseline: { pixelArea: number; rawArea: number } | null = { pixelArea: 0, rawArea: 0 }; + let best: { xAxis: Vec3; pixelArea: number; rawArea: number } | null = null; + const seen = new Set(); + + for (const polygonIndex of component) { + const info = infos[polygonIndex]; + if (!info) continue; + + const firstEdge: Vec3 = [ + info.pts[1][0] - info.pts[0][0], + info.pts[1][1] - info.pts[0][1], + info.pts[1][2] - info.pts[0][2], + ]; + const firstBasis = makeLocalBasis(info.pts, info.pts[0], info.normal, firstEdge); + if (baseline && firstBasis) { + baseline.pixelArea += firstBasis.pixelArea; + baseline.rawArea += firstBasis.rawArea; + } else { + baseline = null; + } + + for (let i = 0; i < info.pts.length; i++) { + const rawAxis = canonicalEdgeVector(info.pts[i], info.pts[(i + 1) % info.pts.length]); + const basis = makeLocalBasis(info.pts, info.pts[0], info.normal, rawAxis); + if (!basis) continue; + const key = basisAxisKey(basis.xAxis); + if (seen.has(key)) continue; + seen.add(key); + + const candidate = evaluateIslandAxis(component, infos, basis.xAxis, boundsOrigin); + if (!candidate) continue; + if ( + !best || + candidate.pixelArea < best.pixelArea || + (candidate.pixelArea === best.pixelArea && candidate.rawArea < best.rawArea - RECT_EPS) + ) { + best = { xAxis: basis.xAxis, ...candidate }; + } + } + } + + if (!best) return null; + if ( + baseline && + ( + best.pixelArea < baseline.pixelArea || + (best.pixelArea === baseline.pixelArea && best.rawArea <= baseline.rawArea + RECT_EPS) + ) + ) { + return { xAxis: best.xAxis, boundsOrigin, seamEdges: new Set() }; + } + return null; +} + +export function buildBasisHints( + polygons: Polygon[], + options: SolidTrianglePlanOptions, +): Array { + const tile = options.tileSize ?? DEFAULT_TILE; + const elev = options.layerElevation ?? tile; + const infos = polygons.map((polygon) => getPolygonBasisInfo(polygon, tile, elev)); + const edgeOwners = new Map>(); + const seamEdges = polygons.map(() => new Set()); + const textureEdgeRepairEdges = polygons.map(() => new Set()); + for (let polygonIndex = 0; polygonIndex < polygons.length; polygonIndex++) { + const vertices = polygons[polygonIndex].vertices; + if (!vertices || vertices.length < 3) continue; + for (let edgeIndex = 0; edgeIndex < vertices.length; edgeIndex++) { + const key = edgeKey( + vertices[edgeIndex], + vertices[(edgeIndex + 1) % vertices.length], + ); + const owners = edgeOwners.get(key); + const owner = { polygon: polygonIndex, edge: edgeIndex }; + if (owners) owners.push(owner); + else edgeOwners.set(key, [owner]); + } + } + + const adjacency = polygons.map(() => new Set()); + for (const owners of edgeOwners.values()) { + if (owners.length < 2) continue; + for (let i = 0; i < owners.length; i++) { + for (let j = i + 1; j < owners.length; j++) { + const aOwner = owners[i]; + const bOwner = owners[j]; + const a = aOwner.polygon; + const b = bOwner.polygon; + if (polygons[a].texture && polygons[b].texture) { + textureEdgeRepairEdges[aOwner.polygon].add(aOwner.edge); + textureEdgeRepairEdges[bOwner.polygon].add(bOwner.edge); + } + if (compatibleBleedSurface(infos[a], infos[b])) { + seamEdges[aOwner.polygon].add(aOwner.edge); + seamEdges[bOwner.polygon].add(bOwner.edge); + } else { + const aLight = seamLightBrightness(infos[a], options); + const bLight = seamLightBrightness(infos[b], options); + if (aLight !== null && bLight !== null) { + if (aLight <= bLight + SEAM_LIGHT_EPS) seamEdges[aOwner.polygon].add(aOwner.edge); + if (bLight <= aLight + SEAM_LIGHT_EPS) seamEdges[bOwner.polygon].add(bOwner.edge); + } + } + if (!compatibleSurface(infos[a], infos[b])) continue; + adjacency[a].add(b); + adjacency[b].add(a); + } + } + } + + const hints: Array = Array(polygons.length).fill(undefined); + const visited = new Set(); + for (let i = 0; i < polygons.length; i++) { + if (visited.has(i) || !infos[i]?.optimizable) continue; + const component: number[] = []; + const stack = [i]; + visited.add(i); + while (stack.length > 0) { + const current = stack.pop()!; + component.push(current); + for (const next of adjacency[current]) { + if (visited.has(next)) continue; + visited.add(next); + stack.push(next); + } + } + + if (component.length < 2) continue; + const hint = chooseIslandXAxis(component, infos); + if (!hint) continue; + for (const index of component) { + hints[index] = { + xAxis: hint.xAxis, + boundsOrigin: hint.boundsOrigin, + seamEdges: seamEdges[index], + textureEdgeRepairEdges: textureEdgeRepairEdges[index], + }; + } + } + + for (let i = 0; i < polygons.length; i++) { + if (!hints[i] && (seamEdges[i].size > 0 || textureEdgeRepairEdges[i].size > 0)) { + hints[i] = { + seamEdges: seamEdges[i], + textureEdgeRepairEdges: textureEdgeRepairEdges[i], + }; + } + } + + return hints; +} diff --git a/packages/core/src/atlas/plan/lighting.ts b/packages/core/src/atlas/plan/lighting.ts new file mode 100644 index 000000000..1a216d7d1 --- /dev/null +++ b/packages/core/src/atlas/plan/lighting.ts @@ -0,0 +1,102 @@ +import type { Polygon, PolyPointLight, Vec3 } from "../../types"; +import { + DEFAULT_LIGHT_DIR, + DEFAULT_LIGHT_COLOR, + DEFAULT_LIGHT_INTENSITY, + DEFAULT_AMBIENT_COLOR, + DEFAULT_AMBIENT_INTENSITY, +} from "../constants"; +import type { + PolygonBasisInfo, + RGBFactors, + SolidTrianglePlanOptions, +} from "../types"; +import { + textureTintFactors, + shadePolygon, + type PointLightContrib, +} from "../paintDefaults"; + +export function seamLightBrightness( + info: PolygonBasisInfo | null, + options: SolidTrianglePlanOptions, +): number | null { + if (!info) return null; + const directionalCfg = options.directionalLight; + const ambientCfg = options.ambientLight; + const lightDir = directionalCfg?.direction ?? DEFAULT_LIGHT_DIR; + const lightColor = directionalCfg?.color ?? DEFAULT_LIGHT_COLOR; + const lightIntensity = Math.max(0, directionalCfg?.intensity ?? DEFAULT_LIGHT_INTENSITY); + const ambientColor = ambientCfg?.color ?? DEFAULT_AMBIENT_COLOR; + const ambientIntensity = Math.max(0, ambientCfg?.intensity ?? DEFAULT_AMBIENT_INTENSITY); + const lLen = Math.hypot(lightDir[0], lightDir[1], lightDir[2]) || 1; + const lx = lightDir[0] / lLen, ly = lightDir[1] / lLen, lz = lightDir[2] / lLen; + const directScale = lightIntensity * Math.max(0, info.normal[0] * lx + info.normal[1] * ly + info.normal[2] * lz); + const tint = textureTintFactors(directScale, lightColor, ambientColor, ambientIntensity); + return tint.r * 0.2126 + tint.g * 0.7152 + tint.b * 0.0722; +} + +/** + * Per-face point-light contributions for a polygon. Each scene point light + * (already in MESH-LOCAL user coords via the renderer) is converted to the + * CSS frame the polygon's `cssPts` use, then a direction-only Lambert scale + * is computed against the face centroid + normal. Returns `undefined` when + * there are no point lights so the shading fast path is unchanged. + */ +export function computePointContribs( + pointLights: readonly PolyPointLight[] | undefined, + cssPts: Vec3[], + normal: Vec3, + tile: number, + elev: number, +): PointLightContrib[] | undefined { + if (!pointLights || pointLights.length === 0) return undefined; + let cx = 0, cy = 0, cz = 0; + for (const p of cssPts) { cx += p[0]; cy += p[1]; cz += p[2]; } + const inv = 1 / cssPts.length; + cx *= inv; cy *= inv; cz *= inv; + const out: PointLightContrib[] = []; + for (const pl of pointLights) { + // Mesh-local user position → CSS frame (same axis swap × tile/elev as cssPoints). + const px = pl.position[1] * tile, py = pl.position[0] * tile, pz = pl.position[2] * elev; + let dx = px - cx, dy = py - cy, dz = pz - cz; + const d = Math.hypot(dx, dy, dz) || 1; + dx /= d; dy /= d; dz /= d; + const lambert = normal[0] * dx + normal[1] * dy + normal[2] * dz; + if (lambert <= 0) continue; + out.push({ color: pl.color ?? "#ffffff", scale: Math.max(0, pl.intensity ?? 1) * lambert }); + } + return out.length ? out : undefined; +} + +export function computePlanLighting( + polygon: Polygon, + index: number, + pts: Vec3[], + normal: Vec3, + tile: number, + elev: number, + options: SolidTrianglePlanOptions, +): { textureTint: RGBFactors; shadedColor: string } { + const directionalCfg = options.directionalLight; + const ambientCfg = options.ambientLight; + const lightDir = directionalCfg?.direction ?? DEFAULT_LIGHT_DIR; + const lightColor = directionalCfg?.color ?? DEFAULT_LIGHT_COLOR; + const lightIntensity = Math.max(0, directionalCfg?.intensity ?? DEFAULT_LIGHT_INTENSITY); + const ambientColor = ambientCfg?.color ?? DEFAULT_AMBIENT_COLOR; + const ambientIntensity = Math.max(0, ambientCfg?.intensity ?? DEFAULT_AMBIENT_INTENSITY); + const lLen = Math.hypot(lightDir[0], lightDir[1], lightDir[2]) || 1; + const lx = lightDir[0] / lLen, ly = lightDir[1] / lLen, lz = lightDir[2] / lLen; + // Decoupled: directional and ambient sum independently. No (1 - ambient) + // budget — matches three.js's lighting model. + const occluded = options.lightOccludedPolyIndices?.has(index) ?? false; + const directScale = occluded + ? 0 + : lightIntensity * Math.max(0, normal[0] * lx + normal[1] * ly + normal[2] * lz); + // Point lights are occlusion-shaded the same as directional: a polygon the + // directional light can't reach (occluded) still gets point-light + ambient. + const pointContribs = computePointContribs(options.pointLights, pts, normal, tile, elev); + const textureTint = textureTintFactors(directScale, lightColor, ambientColor, ambientIntensity, pointContribs); + const shadedColor = shadePolygon(polygon.color ?? "#cccccc", directScale, lightColor, ambientColor, ambientIntensity, pointContribs); + return { textureTint, shadedColor }; +} diff --git a/packages/core/src/atlas/plan/localBasis.ts b/packages/core/src/atlas/plan/localBasis.ts new file mode 100644 index 000000000..6e62944ff --- /dev/null +++ b/packages/core/src/atlas/plan/localBasis.ts @@ -0,0 +1,206 @@ +import type { Vec2, Vec3 } from "../../types"; +import { BASIS_EPS, RECT_EPS } from "../constants"; +import type { BasisOptions, LocalBasis } from "../types"; + +export function dotVec(a: Vec3, b: Vec3): number { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +} + +function pointKey(point: Vec3): string { + return `${point[0]},${point[1]},${point[2]}`; +} + +export function canonicalEdgeVector(a: Vec3, b: Vec3): Vec3 { + return pointKey(a) < pointKey(b) + ? [b[0] - a[0], b[1] - a[1], b[2] - a[2]] + : [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; +} + +export function edgeKey(a: Vec3, b: Vec3): string { + const ak = pointKey(a); + const bk = pointKey(b); + return ak < bk ? `${ak}|${bk}` : `${bk}|${ak}`; +} + +export function basisAxisKey(axis: Vec3): string { + const canonical: Vec3 = [...axis] as Vec3; + const first = Math.abs(canonical[0]) > BASIS_EPS + ? 0 + : Math.abs(canonical[1]) > BASIS_EPS + ? 1 + : 2; + if (canonical[first] < 0) { + canonical[0] *= -1; + canonical[1] *= -1; + canonical[2] *= -1; + } + return `${canonical[0].toFixed(6)},${canonical[1].toFixed(6)},${canonical[2].toFixed(6)}`; +} + +export function makeLocalBasis( + pts: Vec3[], + origin: Vec3, + normal: Vec3, + rawXAxis: Vec3, + options: { boundsOrigin?: Vec3; snapBounds?: boolean } = {}, +): LocalBasis | null { + const dot = dotVec(rawXAxis, normal); + const planeX: Vec3 = [ + rawXAxis[0] - dot * normal[0], + rawXAxis[1] - dot * normal[1], + rawXAxis[2] - dot * normal[2], + ]; + const xLength = Math.hypot(planeX[0], planeX[1], planeX[2]); + if (xLength <= BASIS_EPS) return null; + + const xAxis: Vec3 = [ + planeX[0] / xLength, + planeX[1] / xLength, + planeX[2] / xLength, + ]; + const yAxisRaw: Vec3 = [ + normal[1] * xAxis[2] - normal[2] * xAxis[1], + normal[2] * xAxis[0] - normal[0] * xAxis[2], + normal[0] * xAxis[1] - normal[1] * xAxis[0], + ]; + const yLength = Math.hypot(yAxisRaw[0], yAxisRaw[1], yAxisRaw[2]); + if (yLength <= BASIS_EPS) return null; + const yAxis: Vec3 = [ + yAxisRaw[0] / yLength, + yAxisRaw[1] / yLength, + yAxisRaw[2] / yLength, + ]; + + const local2D = pts.map((p): Vec2 => { + const dx = p[0] - origin[0], dy = p[1] - origin[1], dz = p[2] - origin[2]; + return [ + dx * xAxis[0] + dy * xAxis[1] + dz * xAxis[2], + dx * yAxis[0] + dy * yAxis[1] + dz * yAxis[2], + ]; + }); + + const boundsOrigin = options.boundsOrigin ?? origin; + const odx = origin[0] - boundsOrigin[0]; + const ody = origin[1] - boundsOrigin[1]; + const odz = origin[2] - boundsOrigin[2]; + const originOffsetX = odx * xAxis[0] + ody * xAxis[1] + odz * xAxis[2]; + const originOffsetY = odx * yAxis[0] + ody * yAxis[1] + odz * yAxis[2]; + let xMin = Infinity, yMin = Infinity, xMax = -Infinity, yMax = -Infinity; + for (const [x, y] of local2D) { + const boundsX = x + originOffsetX; + const boundsY = y + originOffsetY; + if (boundsX < xMin) xMin = boundsX; if (boundsX > xMax) xMax = boundsX; + if (boundsY < yMin) yMin = boundsY; if (boundsY > yMax) yMax = boundsY; + } + + const w = xMax - xMin; + const h = yMax - yMin; + if (!Number.isFinite(w) || !Number.isFinite(h)) return null; + + const boxMinX = options.snapBounds ? Math.floor(xMin + RECT_EPS) : xMin; + const boxMinY = options.snapBounds ? Math.floor(yMin + RECT_EPS) : yMin; + const boxMaxX = options.snapBounds ? Math.ceil(xMax - RECT_EPS) : xMax; + const boxMaxY = options.snapBounds ? Math.ceil(yMax - RECT_EPS) : yMax; + const canvasW = Math.max(1, options.snapBounds ? boxMaxX - boxMinX : Math.ceil(w)); + const canvasH = Math.max(1, options.snapBounds ? boxMaxY - boxMinY : Math.ceil(h)); + return { + xAxis, + yAxis, + local2D, + shiftX: originOffsetX - boxMinX, + shiftY: originOffsetY - boxMinY, + canvasW, + canvasH, + pixelArea: canvasW * canvasH, + rawArea: w * h, + }; +} + +export function chooseLocalBasis( + pts: Vec3[], + origin: Vec3, + normal: Vec3, + options: BasisOptions, +): LocalBasis | null { + if (options.optimize && options.fixedXAxis) { + return makeLocalBasis(pts, origin, normal, options.fixedXAxis, { + boundsOrigin: options.boundsOrigin, + snapBounds: options.snapBounds, + }); + } + + let best: LocalBasis | null = null; + const seamCandidates = options.optimize && options.seamEdges && options.seamEdges.size > 0 + ? Array.from(options.seamEdges) + : null; + const candidateEdges = seamCandidates ?? ( + options.optimize + ? pts.map((_, edgeIndex) => edgeIndex) + : [0] + ); + + for (const i of candidateEdges) { + const next = (i + 1) % pts.length; + const edge = seamCandidates + ? canonicalEdgeVector(pts[i], pts[next]) + : [ + pts[next][0] - pts[i][0], + pts[next][1] - pts[i][1], + pts[next][2] - pts[i][2], + ] as Vec3; + const candidate = makeLocalBasis(pts, origin, normal, edge, { + boundsOrigin: options.boundsOrigin, + snapBounds: options.snapBounds, + }); + if (!candidate) continue; + + if ( + !best || + candidate.pixelArea < best.pixelArea || + (candidate.pixelArea === best.pixelArea && candidate.rawArea < best.rawArea - RECT_EPS) + ) { + best = candidate; + } + } + + return best; +} + +export function isFullRectBasis(basis: LocalBasis): boolean { + if (basis.local2D.length !== 4) return false; + + const xs: number[] = []; + const ys: number[] = []; + const addUnique = (list: number[], value: number): void => { + for (const existing of list) { + if (Math.abs(existing - value) <= RECT_EPS) return; + } + list.push(value); + }; + + for (const [x, y] of basis.local2D) { + addUnique(xs, x + basis.shiftX); + addUnique(ys, y + basis.shiftY); + } + if (xs.length !== 2 || ys.length !== 2) return false; + + xs.sort((a, b) => a - b); + ys.sort((a, b) => a - b); + if ( + Math.abs(xs[0]) > RECT_EPS || + Math.abs(ys[0]) > RECT_EPS || + xs[1] - xs[0] <= RECT_EPS || + ys[1] - ys[0] <= RECT_EPS + ) { + return false; + } + + for (const [rawX, rawY] of basis.local2D) { + const x = rawX + basis.shiftX; + const y = rawY + basis.shiftY; + const onX = Math.abs(x - xs[0]) <= RECT_EPS || Math.abs(x - xs[1]) <= RECT_EPS; + const onY = Math.abs(y - ys[0]) <= RECT_EPS || Math.abs(y - ys[1]) <= RECT_EPS; + if (!onX || !onY) return false; + } + return true; +} diff --git a/packages/core/src/atlas/plan/projectiveQuad.ts b/packages/core/src/atlas/plan/projectiveQuad.ts new file mode 100644 index 000000000..16f8d0fa2 --- /dev/null +++ b/packages/core/src/atlas/plan/projectiveQuad.ts @@ -0,0 +1,147 @@ +import type { Vec2, Vec3 } from "../../types"; +import { + BASIS_EPS, + PROJECTIVE_QUAD_DENOM_EPS, + PROJECTIVE_QUAD_MAX_WEIGHT_RATIO, + PROJECTIVE_QUAD_BLEED, + SOLID_QUAD_CANONICAL_SIZE, +} from "../constants"; +import type { + ProjectiveQuadGuardSettings, + ProjectiveQuadGuardOverrides, + ProjectiveQuadCoefficients, +} from "../types"; +import { formatMatrix3dValues } from "../matrix"; +import { + isConvexPolygonPoints, + offsetConvexPolygonPoints, + offsetConvexPolygonPointsByEdgeAmounts, +} from "../solidTriangle"; +import { seamBleedAmountArray } from "../edgeRepair"; + +function finiteNumber(value: unknown, fallback: number): number { + return typeof value === "number" && Number.isFinite(value) ? value : fallback; +} + +export function resolveProjectiveQuadGuards( + overrides: ProjectiveQuadGuardOverrides | undefined, +): ProjectiveQuadGuardSettings { + const overrideMaxWeightRatio = overrides?.maxWeightRatio; + const denomEps = Math.max( + 0, + finiteNumber(overrides?.denomEps, PROJECTIVE_QUAD_DENOM_EPS), + ); + const maxWeightRatio = typeof overrideMaxWeightRatio === "number" && + Number.isFinite(overrideMaxWeightRatio) && + overrideMaxWeightRatio > 0 + ? Math.max(1, overrideMaxWeightRatio) + : PROJECTIVE_QUAD_MAX_WEIGHT_RATIO; + const bleed = Math.max( + 0, + finiteNumber(overrides?.bleed, PROJECTIVE_QUAD_BLEED), + ); + + return { + denomEps, + maxWeightRatio, + bleed, + disableGuards: overrides?.disableGuards === true, + }; +} + +export function computeProjectiveQuadCoefficients( + q: Array<[number, number]>, + guards: ProjectiveQuadGuardSettings, +): ProjectiveQuadCoefficients | null { + if (q.length !== 4 || !isConvexPolygonPoints(q)) return null; + + const [q0, q1, q2, q3] = q; + const sx = q0[0] - q1[0] + q2[0] - q3[0]; + const sy = q0[1] - q1[1] + q2[1] - q3[1]; + const dx1 = q1[0] - q2[0]; + const dx2 = q3[0] - q2[0]; + const dy1 = q1[1] - q2[1]; + const dy2 = q3[1] - q2[1]; + const det = dx1 * dy2 - dy1 * dx2; + if (Math.abs(det) <= BASIS_EPS) return null; + + const g = (sx * dy2 - sy * dx2) / det; + const h = (dx1 * sy - dy1 * sx) / det; + const weights = [1, 1 + g, 1 + g + h, 1 + h]; + if (weights.some((weight) => !Number.isFinite(weight))) { + return null; + } + + const minWeight = Math.min(...weights); + const maxWeight = Math.max(...weights); + if (!guards.disableGuards) { + if (minWeight <= guards.denomEps) return null; + // Very large homogeneous-weight variation means the rectangle's vanishing + // line is too close to the primitive. Chrome can then tessellate the leaf + // visibly wrong; the clipped polygon path is steadier for those quads. + if (maxWeight / minWeight > guards.maxWeightRatio) return null; + } + + return { + g, + h, + w1: 1 + g, + w3: 1 + h, + }; +} + +export function computeProjectiveQuadMatrix( + screenPts: number[], + xAxis: Vec3, + yAxis: Vec3, + normal: Vec3, + tx: number, + ty: number, + tz: number, + guards: ProjectiveQuadGuardSettings, + seamBleedEdgeAmounts?: ReadonlyMap, +): string | null { + if (screenPts.length !== 8) return null; + const rawQ: Array<[number, number]> = [ + [screenPts[0], screenPts[1]], + [screenPts[2], screenPts[3]], + [screenPts[4], screenPts[5]], + [screenPts[6], screenPts[7]], + ]; + if (!computeProjectiveQuadCoefficients(rawQ, guards)) return null; + + const edgeAmounts = seamBleedAmountArray(4, seamBleedEdgeAmounts); + const expandedPts = edgeAmounts + ? offsetConvexPolygonPointsByEdgeAmounts(screenPts, edgeAmounts) + : offsetConvexPolygonPoints(screenPts, guards.bleed); + const q: Array<[number, number]> = [ + [expandedPts[0], expandedPts[1]], + [expandedPts[2], expandedPts[3]], + [expandedPts[4], expandedPts[5]], + [expandedPts[6], expandedPts[7]], + ]; + const coeffs = computeProjectiveQuadCoefficients(q, guards); + if (!coeffs) return null; + const { g, h, w1, w3 } = coeffs; + const [q0, q1, , q3] = q; + + const p0: Vec3 = [ + tx + q0[0] * xAxis[0] + q0[1] * yAxis[0], + ty + q0[0] * xAxis[1] + q0[1] * yAxis[1], + tz + q0[0] * xAxis[2] + q0[1] * yAxis[2], + ]; + const projectiveColumn = ([x, y]: Vec2, weight: number): Vec3 => [ + (weight - 1) * tx + (weight * x - q0[0]) * xAxis[0] + (weight * y - q0[1]) * yAxis[0], + (weight - 1) * ty + (weight * x - q0[0]) * xAxis[1] + (weight * y - q0[1]) * yAxis[1], + (weight - 1) * tz + (weight * x - q0[0]) * xAxis[2] + (weight * y - q0[1]) * yAxis[2], + ]; + + const values = [ + ...projectiveColumn(q1, w1), g, + ...projectiveColumn(q3, w3), h, + normal[0], normal[1], normal[2], 0, + p0[0], p0[1], p0[2], 1, + ]; + for (let i = 0; i < 8; i += 1) values[i] /= SOLID_QUAD_CANONICAL_SIZE; + return formatMatrix3dValues(values, 6); +} diff --git a/packages/core/src/atlas/plan/uv.ts b/packages/core/src/atlas/plan/uv.ts new file mode 100644 index 000000000..cf757d30a --- /dev/null +++ b/packages/core/src/atlas/plan/uv.ts @@ -0,0 +1,81 @@ +import type { TextureTriangle, Vec2, Vec3 } from "../../types"; +import type { TextureTrianglePlan, UvAffine, UvSampleRect } from "../types"; +import { cssPoints } from "../solidTriangle"; + +export function computeUvAffine(points: Vec2[], uvs: Vec2[]): UvAffine | null { + if (points.length < 3 || uvs.length < 3) return null; + const [p0, p1, p2] = points; + const [uv0, uv1, uv2] = uvs; + const sx0 = p0[0], sy0 = p0[1]; + const sx1 = p1[0], sy1 = p1[1]; + const sx2 = p2[0], sy2 = p2[1]; + const u0 = uv0[0], V0 = 1 - uv0[1]; + const u1 = uv1[0], V1 = 1 - uv1[1]; + const u2 = uv2[0], V2 = 1 - uv2[1]; + const du1 = u1 - u0, dV1 = V1 - V0; + const du2 = u2 - u0, dV2 = V2 - V0; + const det = du1 * dV2 - du2 * dV1; + if (Math.abs(det) <= 1e-9) return null; + + const dx1 = sx1 - sx0, dx2 = sx2 - sx0; + const dy1 = sy1 - sy0, dy2 = sy2 - sy0; + const affine = { + a: (dx1 * dV2 - dx2 * dV1) / det, + b: (du1 * dx2 - du2 * dx1) / det, + c: (dy1 * dV2 - dy2 * dV1) / det, + d: (du1 * dy2 - du2 * dy1) / det, + e: 0, + f: 0, + }; + affine.e = sx0 - affine.a * u0 - affine.b * V0; + affine.f = sy0 - affine.c * u0 - affine.d * V0; + return affine; +} + +export function computeUvSampleRect(uvs: Vec2[]): UvSampleRect | null { + if (uvs.length === 0) return null; + let minU = Infinity; + let minV = Infinity; + let maxU = -Infinity; + let maxV = -Infinity; + for (const uv of uvs) { + const u = uv[0]; + const v = 1 - uv[1]; + if (!Number.isFinite(u) || !Number.isFinite(v)) return null; + minU = Math.min(minU, u); + maxU = Math.max(maxU, u); + minV = Math.min(minV, v); + maxV = Math.max(maxV, v); + } + return { minU, minV, maxU, maxV }; +} + +export function projectTextureTriangle( + triangle: TextureTriangle, + tile: number, + elev: number, + origin: Vec3, + xAxis: Vec3, + yAxis: Vec3, + shiftX: number, + shiftY: number, +): TextureTrianglePlan | null { + const pts = cssPoints(triangle.vertices, tile, elev); + const points = pts.map((point): Vec2 => { + const dx = point[0] - origin[0]; + const dy = point[1] - origin[1]; + const dz = point[2] - origin[2]; + return [ + dx * xAxis[0] + dy * xAxis[1] + dz * xAxis[2] + shiftX, + dx * yAxis[0] + dy * yAxis[1] + dz * yAxis[2] + shiftY, + ]; + }); + const uvAffine = computeUvAffine(points, triangle.uvs); + const uvSampleRect = computeUvSampleRect(triangle.uvs); + if (!uvAffine && !uvSampleRect) return null; + return { + screenPts: points.flatMap(([x, y]) => [x, y]), + uvAffine, + uvSampleRect, + }; +} diff --git a/packages/fonts/README.md b/packages/fonts/README.md index fdcb0e999..f05098d53 100644 --- a/packages/fonts/README.md +++ b/packages/fonts/README.md @@ -1,6 +1,6 @@ # @layoutit/polycss-fonts -Turn **fonts + text into extruded 3D polygon meshes** for [PolyCSS](https://github.com/LayoutitStudio/polycss). Framework-agnostic: it returns plain `Polygon[]`, so the same call works in the vanilla, React, and Vue renderers — no per-framework wrappers. +Turn **fonts + text into extruded 3D polygon meshes** for [PolyCSS](https://github.com/layoutit/polycss). Framework-agnostic: it returns plain `Polygon[]`, so the same call works in the vanilla, React, and Vue renderers — no per-framework wrappers. ```bash pnpm add @layoutit/polycss-fonts @layoutit/polycss diff --git a/packages/fonts/package.json b/packages/fonts/package.json index 63c72ea9f..f3b30ccb7 100644 --- a/packages/fonts/package.json +++ b/packages/fonts/package.json @@ -9,13 +9,13 @@ "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/LayoutitStudio/polycss.git", + "url": "https://github.com/layoutit/polycss.git", "directory": "packages/fonts" }, "bugs": { - "url": "https://github.com/LayoutitStudio/polycss/issues" + "url": "https://github.com/layoutit/polycss/issues" }, - "homepage": "https://github.com/LayoutitStudio/polycss#readme", + "homepage": "https://github.com/layoutit/polycss#readme", "files": [ "dist" ], diff --git a/packages/morph/package.json b/packages/morph/package.json index 02f53b67a..10276e7e4 100644 --- a/packages/morph/package.json +++ b/packages/morph/package.json @@ -18,13 +18,13 @@ "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/LayoutitStudio/polycss.git", + "url": "https://github.com/layoutit/polycss.git", "directory": "packages/morph" }, "bugs": { - "url": "https://github.com/LayoutitStudio/polycss/issues" + "url": "https://github.com/layoutit/polycss/issues" }, - "homepage": "https://github.com/LayoutitStudio/polycss#readme", + "homepage": "https://github.com/layoutit/polycss#readme", "files": [ "dist" ], diff --git a/packages/polycss/package.json b/packages/polycss/package.json index d2fe3ba36..56f6b5714 100644 --- a/packages/polycss/package.json +++ b/packages/polycss/package.json @@ -9,13 +9,13 @@ "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/LayoutitStudio/polycss.git", + "url": "https://github.com/layoutit/polycss.git", "directory": "packages/polycss" }, "bugs": { - "url": "https://github.com/LayoutitStudio/polycss/issues" + "url": "https://github.com/layoutit/polycss/issues" }, - "homepage": "https://github.com/LayoutitStudio/polycss#readme", + "homepage": "https://github.com/layoutit/polycss#readme", "files": [ "dist" ], diff --git a/packages/polycss/src/render/atlas/render/asyncRender.ts b/packages/polycss/src/render/atlas/render/asyncRender.ts new file mode 100644 index 000000000..a1d507b3f --- /dev/null +++ b/packages/polycss/src/render/atlas/render/asyncRender.ts @@ -0,0 +1,139 @@ +import type { Polygon, TextureAtlasPlan } from "@layoutit/polycss-core"; +import { + ASYNC_RENDER_BUDGET_MS, + buildBasisHints, + computeTextureAtlasPlan, +} from "@layoutit/polycss-core"; +import type { + InternalRenderTextureAtlasOptions, + RenderedPoly, + RenderTextureAtlasAsyncResult, + RenderTextureAtlasOptions, +} from "../types"; +import { resolveProjectiveQuadGuards } from "../plan"; +import { getSolidPaintDefaultsForPlans } from "../strategy"; +import { packTextureAtlasPlansWithScale } from "../packing"; +import { + buildRenderSeamBleedEdges, + classifyPolygonRenderPlans, + projectiveQuadGuardDefaults, + resolveAtlasRenderCapabilities, + seamAtlasOptions, + type ClassifiedPolygonPlans, +} from "./planning"; +import { attachAtlasPageHydration, emitPolygonLeaf } from "./emitLeaves"; + +function yieldToMainThread(): Promise { + return new Promise((resolve) => setTimeout(resolve, 0)); +} + +async function yieldIfOverBudget(started: number): Promise { + if (performance.now() - started < ASYNC_RENDER_BUDGET_MS) return started; + await yieldToMainThread(); + return performance.now(); +} + +export async function renderPolygonsWithTextureAtlasAsync( + polygons: Polygon[], + options: RenderTextureAtlasOptions = {}, + shouldCancel: () => boolean = () => false, +): Promise { + const doc = options.doc ?? (typeof document !== "undefined" ? document : null); + if (!doc || shouldCancel()) { + return { rendered: [], solidPaintDefaults: {}, dispose: () => {} }; + } + + const textureLighting = options.textureLighting ?? "baked"; + const internalOptions = options as InternalRenderTextureAtlasOptions; + const skipDynamicNormalVars = + textureLighting === "dynamic" && internalOptions.skipDynamicNormalVars === true; + const capabilities = resolveAtlasRenderCapabilities(doc, options); + await yieldToMainThread(); + if (shouldCancel()) return { rendered: [], solidPaintDefaults: {}, dispose: () => {} }; + + const basisHints = buildBasisHints(polygons, options); + const projectiveQuadGuards = resolveProjectiveQuadGuards(doc, projectiveQuadGuardDefaults(options)); + const seamBleedEdges = buildRenderSeamBleedEdges(polygons, options); + let batchStarted = performance.now(); + const plans: Array = new Array(polygons.length); + for (let i = 0; i < polygons.length; i++) { + plans[i] = computeTextureAtlasPlan( + polygons[i], + i, + seamAtlasOptions(i, seamBleedEdges, options), + projectiveQuadGuards, + basisHints[i], + ); + batchStarted = await yieldIfOverBudget(batchStarted); + if (shouldCancel()) return { rendered: [], solidPaintDefaults: {}, dispose: () => {} }; + } + + const solidPaintDefaults = options.solidPaintDefaults ?? + getSolidPaintDefaultsForPlans(plans, textureLighting, doc, options.strategies); + const triangleOptions = { ...options, solidPaintDefaults }; + const classifiedPlans: ClassifiedPolygonPlans[] = new Array(plans.length); + const atlasPlans: Array = new Array(plans.length); + for (let i = 0; i < plans.length; i++) { + const classified = classifyPolygonRenderPlans( + plans[i], + capabilities, + options, + triangleOptions, + projectiveQuadGuards, + ); + classifiedPlans[i] = classified; + atlasPlans[i] = classified.atlasPlan; + batchStarted = await yieldIfOverBudget(batchStarted); + if (shouldCancel()) return { rendered: [], solidPaintDefaults, dispose: () => {} }; + } + + const { packed, atlasScale } = packTextureAtlasPlansWithScale( + atlasPlans, + options.textureQuality, + doc, + options.textureLeafSizing, + ); + const atlasElements = new Map(); + const rendered: RenderedPoly[] = []; + const emitContext = { + doc, + textureLighting, + skipDynamicNormalVars, + textureImageRendering: options.textureImageRendering, + solidPaintDefaults, + capabilities, + packed, + atlasElements, + rendered, + }; + + for (let i = 0; i < polygons.length; i++) { + const plan = plans[i]; + if (!plan) continue; + emitPolygonLeaf(i, plan, classifiedPlans[i], emitContext); + batchStarted = await yieldIfOverBudget(batchStarted); + if (shouldCancel()) { + for (const item of rendered) item.dispose(); + return { rendered: [], solidPaintDefaults, dispose: () => {} }; + } + } + + rendered.sort((a, b) => a.polygonIndex - b.polygonIndex); + + const { pagesReady, dispose } = attachAtlasPageHydration( + packed, + atlasScale, + atlasElements, + textureLighting, + doc, + options.textureImageRendering, + shouldCancel, + ); + + return { + rendered, + solidPaintDefaults, + pagesReady, + dispose, + }; +} diff --git a/packages/polycss/src/render/atlas/render/emitLeaves.ts b/packages/polycss/src/render/atlas/render/emitLeaves.ts new file mode 100644 index 000000000..f7923b1cd --- /dev/null +++ b/packages/polycss/src/render/atlas/render/emitLeaves.ts @@ -0,0 +1,133 @@ +import type { + PackedAtlas, + PolyTextureImageRendering, + PolyTextureLightingMode, + SolidPaintDefaults, + TextureAtlasPlan, +} from "@layoutit/polycss-core"; +import type { RenderedPoly } from "../types"; +import { isFullRectSolid, isProjectiveQuadPlan } from "../strategy"; +import { buildAtlasPages } from "../rasterise"; +import { + applyAtlasBackground, + createAtlasElement, + createBorderShapeSolidElement, + createCornerShapeSolidElement, + createProjectiveSolidElement, + createSolidElement, + createTextureImageElement, +} from "../emit"; +import { setInlineStyleProperty } from "../paintDefaults"; +import { createSolidTriangleElement } from "../stableTriangle"; +import type { AtlasRenderCapabilities, ClassifiedPolygonPlans } from "./planning"; + +export interface EmitPolygonLeafContext { + doc: Document; + textureLighting: PolyTextureLightingMode; + skipDynamicNormalVars: boolean; + textureImageRendering: PolyTextureImageRendering | undefined; + solidPaintDefaults: SolidPaintDefaults | undefined; + capabilities: AtlasRenderCapabilities; + packed: PackedAtlas; + atlasElements: Map; + rendered: RenderedPoly[]; +} + +export function emitPolygonLeaf( + index: number, + plan: TextureAtlasPlan, + classified: ClassifiedPolygonPlans, + context: EmitPolygonLeafContext, +): void { + const { + doc, + textureLighting, + skipDynamicNormalVars, + textureImageRendering, + solidPaintDefaults, + capabilities, + packed, + atlasElements, + rendered, + } = context; + const { useFullRectSolid, useProjectiveQuad, useBorderShape } = capabilities; + const { trianglePlan, cornerShapePlan, imagePlan } = classified; + + const entry = packed.entries[index]; + if (entry) { + const element = createAtlasElement(entry, textureLighting, doc, skipDynamicNormalVars, textureImageRendering); + atlasElements.set(index, element); + rendered.push({ polygonIndex: index, element, kind: "atlas", plan: entry, dispose: () => {} }); + } else if (imagePlan) { + const element = createTextureImageElement(plan, imagePlan, doc, skipDynamicNormalVars); + rendered.push({ polygonIndex: index, element, kind: "image", plan, dispose: () => {} }); + } else if (!plan.texture && useFullRectSolid && isFullRectSolid(plan)) { + const element = createSolidElement(plan, textureLighting, doc, solidPaintDefaults, skipDynamicNormalVars); + rendered.push({ polygonIndex: index, element, kind: "solid", plan, dispose: () => {} }); + } else if (!plan.texture && trianglePlan) { + const element = createSolidTriangleElement(trianglePlan, doc); + rendered.push({ polygonIndex: index, element, kind: "triangle", plan, dispose: () => {} }); + } else if (!plan.texture && useProjectiveQuad && isProjectiveQuadPlan(plan)) { + const element = createProjectiveSolidElement(plan, textureLighting, doc, solidPaintDefaults, skipDynamicNormalVars); + rendered.push({ polygonIndex: index, element, kind: "solid", plan, dispose: () => {} }); + } else if (!plan.texture && cornerShapePlan) { + const element = createCornerShapeSolidElement(plan, cornerShapePlan, textureLighting, doc, solidPaintDefaults, skipDynamicNormalVars); + rendered.push({ polygonIndex: index, element, kind: "corner", plan, dispose: () => {} }); + } else if (!plan.texture && useBorderShape) { + const element = createBorderShapeSolidElement(plan, textureLighting, doc, solidPaintDefaults, skipDynamicNormalVars); + rendered.push({ polygonIndex: index, element, kind: "border", plan, dispose: () => {} }); + } +} + +export function attachAtlasPageHydration( + packed: PackedAtlas, + atlasScale: number, + atlasElements: Map, + textureLighting: PolyTextureLightingMode, + doc: Document, + textureImageRendering: PolyTextureImageRendering | undefined, + shouldCancel?: () => boolean, +): { pagesReady: Promise; dispose: () => void } { + let cancelled = false; + let urls: string[] = []; + const isCancelled = () => cancelled || (shouldCancel ? shouldCancel() : false); + + const pagesReady = buildAtlasPages(packed.pages, textureLighting, doc, atlasScale, isCancelled) + .then((pages) => { + if (isCancelled()) { + for (const page of pages) { + if (page.url?.startsWith("blob:")) URL.revokeObjectURL(page.url); + } + return; + } + urls = pages.flatMap((page) => page.url?.startsWith("blob:") ? [page.url] : []); + for (let pageIndex = 0; pageIndex < packed.pages.length; pageIndex++) { + const page = packed.pages[pageIndex]; + const built = pages[pageIndex]; + if (!built) continue; + for (const entry of page.entries) { + const el = atlasElements.get(entry.index); + if (!el || !built.url) continue; + // preserveDynamicNormalVars is always true here: this callback fires + // after syncMountedRendered has restored inline normals on solo polys. + applyAtlasBackground(el, built, textureLighting, entry, true, textureImageRendering); + } + } + }) + .catch(() => { + if (isCancelled()) return; + for (const element of atlasElements.values()) { + setInlineStyleProperty(element, "opacity", "0.5"); + setInlineStyleProperty(element, "outline", "1px dashed rgba(255, 0, 0, 0.6)"); + } + }); + + return { + pagesReady, + dispose() { + cancelled = true; + for (const url of urls) URL.revokeObjectURL(url); + urls = []; + }, + }; +} diff --git a/packages/polycss/src/render/atlas/render/planning.ts b/packages/polycss/src/render/atlas/render/planning.ts new file mode 100644 index 000000000..3293709f9 --- /dev/null +++ b/packages/polycss/src/render/atlas/render/planning.ts @@ -0,0 +1,176 @@ +import type { + CornerShapeGeometry, + Polygon, + PolySeamBleed, + ProjectiveQuadGuardSettings, + SolidTrianglePlan, + SolidTrianglePrimitive, + TextureAtlasPlan, +} from "@layoutit/polycss-core"; +import { + buildSeamBleedPolygonEdges, + cornerShapeGeometryForPlan, + PROJECTIVE_QUAD_BLEED, + resolvePolyTextureLeafGeometry, + resolveSeamBleedPx, + seamBleedPrimitiveRatio, +} from "@layoutit/polycss-core"; +import type { RenderTextureAtlasOptions } from "../types"; +import { + borderShapeSupported, + cornerShapeSupported, + isFullRectSolid, + isProjectiveQuadPlan, + isSolidTrianglePlan, + projectiveQuadSupported, + resolveSolidTrianglePrimitive, +} from "../strategy"; +import { computeSolidTrianglePlan } from "../solidTrianglePlan"; + +// `options.seamBleed` is the raw public option (`number | "auto" | +// undefined`) and passes straight through to core plan construction, +// which owns the resolution: `resolveSeamBleedPx` yields the absolute +// shared-edge overscan in CSS px (default 1.5) and +// `seamBleedPrimitiveRatio` scales the per-strategy primitive bleeds +// (SOLID_TRIANGLE_BLEED, BORDER_SHAPE_BLEED, TEXTURE_TRIANGLE_BLEED, +// PROJECTIVE_QUAD_BLEED). The helpers below only attach the detected +// per-polygon seam-edge sets. + +export type RenderTextureAtlasOptionsWithSeams = RenderTextureAtlasOptions & { + seamBleed?: PolySeamBleed; + seamEdges?: Set; +}; + +export interface AtlasRenderCapabilities { + useFullRectSolid: boolean; + useProjectiveQuad: boolean; + solidTrianglePrimitive: SolidTrianglePrimitive | null; + useStableTriangle: boolean; + useCornerShapeSolid: boolean; + useBorderShape: boolean; +} + +export interface ClassifiedPolygonPlans { + trianglePlan: SolidTrianglePlan | null; + cornerShapePlan: CornerShapeGeometry | null; + imagePlan: ReturnType; + atlasPlan: TextureAtlasPlan | null; +} + +export function resolveAtlasRenderCapabilities( + doc: Document | null, + options: RenderTextureAtlasOptions, +): AtlasRenderCapabilities { + const disabled = new Set(options.strategies?.disable ?? []); + const useFullRectSolid = !disabled.has("b"); + const useProjectiveQuad = !!doc && useFullRectSolid && projectiveQuadSupported(doc); + const solidTrianglePrimitive = doc + ? resolveSolidTrianglePrimitive(doc, options.strategies) + : null; + const useStableTriangle = solidTrianglePrimitive !== null; + const useCornerShapeSolid = !!doc && !disabled.has("i") && cornerShapeSupported(doc); + const useBorderShape = !!doc && !disabled.has("i") && borderShapeSupported(doc); + return { + useFullRectSolid, + useProjectiveQuad, + solidTrianglePrimitive, + useStableTriangle, + useCornerShapeSolid, + useBorderShape, + }; +} + +function seamTriangleOptions( + plan: TextureAtlasPlan, + options: RenderTextureAtlasOptionsWithSeams, +): RenderTextureAtlasOptionsWithSeams { + // Raw `options.seamBleed` passes through — core resolves it. Only the + // seam-edge set detected on the atlas plan is attached here. + return plan.seamBleedEdges?.size + ? { ...options, seamEdges: plan.seamBleedEdges } + : { ...options, seamEdges: undefined }; +} + +export function buildRenderSeamBleedEdges( + polygons: Polygon[], + options: RenderTextureAtlasOptionsWithSeams, +): Map> | null { + // A resolved overscan of 0 disables the shared-edge bleed entirely, so + // skip the O(edges) seam-map build (mirrors React/Vue). + if (resolveSeamBleedPx(options.seamBleed) <= 0) return null; + return buildSeamBleedPolygonEdges(polygons, { + tileSize: options.tileSize, + layerElevation: options.layerElevation, + directionalLight: options.directionalLight, + ambientLight: options.ambientLight, + }); +} + +export function seamAtlasOptions( + index: number, + seamBleedEdges: Map> | null, + options: RenderTextureAtlasOptionsWithSeams, +): RenderTextureAtlasOptionsWithSeams { + return seamBleedEdges + ? { ...options, seamEdges: seamBleedEdges.get(index) } + : options; +} + +// Default projective-quad guard bleed, scaled by the seamBleed-derived +// primitive ratio. resolveProjectiveQuadGuards merges these UNDER the +// `window.__polycssProjectiveQuadGuards` debug override. +export function projectiveQuadGuardDefaults( + options: RenderTextureAtlasOptionsWithSeams, +): { bleed: number } { + return { bleed: PROJECTIVE_QUAD_BLEED * seamBleedPrimitiveRatio(options.seamBleed) }; +} + +export function classifyPolygonRenderPlans( + plan: TextureAtlasPlan | null, + capabilities: AtlasRenderCapabilities, + options: RenderTextureAtlasOptionsWithSeams, + triangleOptions: RenderTextureAtlasOptionsWithSeams, + projectiveQuadGuards: ProjectiveQuadGuardSettings, +): ClassifiedPolygonPlans { + const { + useFullRectSolid, + useProjectiveQuad, + solidTrianglePrimitive, + useStableTriangle, + useCornerShapeSolid, + useBorderShape, + } = capabilities; + const trianglePlan = plan && useStableTriangle && isSolidTrianglePlan(plan) + ? computeSolidTrianglePlan(plan.polygon, plan.index, seamTriangleOptions(plan, triangleOptions), { + primitive: solidTrianglePrimitive ?? undefined, + }) + : null; + const cornerShapePlan = plan && + useCornerShapeSolid && + !isSolidTrianglePlan(plan) && + !(useFullRectSolid && isFullRectSolid(plan)) && + !(useProjectiveQuad && isProjectiveQuadPlan(plan)) + ? cornerShapeGeometryForPlan(plan) + : null; + const imagePlan = plan + ? resolvePolyTextureLeafGeometry(plan, { + imageRendering: options.textureImageRendering, + backend: options.textureBackend, + projection: options.textureProjection, + allowProjective: useProjectiveQuad, + projectiveQuadGuards, + }) + : null; + const atlasPlan = imagePlan + ? null + : plan && + (plan.texture + ? plan + : (!(useFullRectSolid && isFullRectSolid(plan)) && !trianglePlan && !(useProjectiveQuad && isProjectiveQuadPlan(plan)) && !cornerShapePlan && !useBorderShape) ? plan : null); + return { + trianglePlan, + cornerShapePlan, + imagePlan, + atlasPlan, + }; +} diff --git a/packages/polycss/src/render/atlas/render/stableTopologyUpdate.ts b/packages/polycss/src/render/atlas/render/stableTopologyUpdate.ts new file mode 100644 index 000000000..cfcdad519 --- /dev/null +++ b/packages/polycss/src/render/atlas/render/stableTopologyUpdate.ts @@ -0,0 +1,277 @@ +import type { + Polygon, + SolidTriangleColorPlan, + SolidTrianglePlan, + TextureAtlasPlan, +} from "@layoutit/polycss-core"; +import { + computeSolidTriangleColorPlan, + computeTextureAtlasPlan, + cornerShapeGeometryForPlan, + PROJECTIVE_QUAD_BLEED, + PROJECTIVE_QUAD_DENOM_EPS, + PROJECTIVE_QUAD_MAX_WEIGHT_RATIO, + seamBleedPrimitiveRatio, + stableTriangleMatrixDecimals, +} from "@layoutit/polycss-core"; +import type { + InternalRenderTextureAtlasOptions, + RenderedPoly, + RenderTextureAtlasOptions, + SolidTriangleElement, +} from "../types"; +import { resolveProjectiveQuadGuards } from "../plan"; +import { + isFullRectSolid, + isProjectiveQuadPlan, + isSolidTrianglePlan, +} from "../strategy"; +import { + updateAtlasElementWithStablePlan, + updateBorderShapeElementWithStablePlan, + updateCornerShapeElementWithStablePlan, + updateSolidElementWithStablePlan, +} from "../emit"; +import { computeSolidTrianglePlan } from "../solidTrianglePlan"; +import { + applySolidTriangleElement, + applySolidTriangleElementColorOnly, + applySolidTriangleElementFast, + applySolidTriangleElementTransformOnly, + hideSolidTriangleElement, + selectAdaptiveTriangleColorUpdates, + shouldComputeStableTriangleColor, + stableTriangleColorState, + updateStableTriangleElementsStreaming, +} from "../stableTriangle"; +import { resolveAtlasRenderCapabilities } from "./planning"; + +export function updatePolygonsWithStableTopology( + rendered: RenderedPoly[], + polygons: Polygon[], + options: RenderTextureAtlasOptions = {}, +): boolean { + if (rendered.length !== polygons.length) return false; + const internalOptions = options as InternalRenderTextureAtlasOptions; + const doc = options.doc ?? (typeof document !== "undefined" ? document : null); + const textureLighting = options.textureLighting ?? "baked"; + const { + useFullRectSolid, + useProjectiveQuad, + solidTrianglePrimitive: resolvedSolidTrianglePrimitive, + useCornerShapeSolid, + useBorderShape, + } = resolveAtlasRenderCapabilities(doc, options); + // Resolve the per-strategy ratio once so projective-quad / corner-shape + // checks below all read from the same value as the plan stamping. + const bleedRatio = seamBleedPrimitiveRatio(internalOptions.seamBleed); + // Pass the resolved bleed as an explicit override so resolveProjectiveQuadGuards + // (which has its own fallback path) returns the scaled value too. + const projectiveQuadGuards = doc + ? resolveProjectiveQuadGuards(doc, { bleed: PROJECTIVE_QUAD_BLEED * bleedRatio }) + : { + denomEps: PROJECTIVE_QUAD_DENOM_EPS, + maxWeightRatio: PROJECTIVE_QUAD_MAX_WEIGHT_RATIO, + bleed: PROJECTIVE_QUAD_BLEED * bleedRatio, + disableGuards: false, + }; + const optimizeTriangleStyle = + internalOptions.optimizeStableTriangleStyle === true && + textureLighting === "baked"; + const stableTriangleDebug = internalOptions.stableTriangleDebug; + const stableTriangleUpdateMode = internalOptions.stableTriangleUpdateMode ?? + (stableTriangleDebug === "plan-only" || stableTriangleDebug === "transform-only" + ? stableTriangleDebug + : "full"); + const colorOnly = optimizeTriangleStyle && stableTriangleUpdateMode === "color-only"; + const colorState = stableTriangleColorState(internalOptions); + const matrixDecimals = stableTriangleMatrixDecimals(internalOptions.stableTriangleMatrixDecimals); + const solidTrianglePrimitive = resolvedSolidTrianglePrimitive ?? "border"; + if ( + updateStableTriangleElementsStreaming( + rendered, + polygons, + options, + optimizeTriangleStyle, + stableTriangleUpdateMode, + colorState, + ) + ) { + return true; + } + const nextTrianglePlans: Array = []; + const nextTriangleColorPlans: Array = []; + const nextTexturePlans: Array = []; + + for (let i = 0; i < rendered.length; i++) { + const item = rendered[i]; + if (item.polygonIndex !== i) return false; + const polygon = polygons[i]; + if (!polygon) return false; + if (colorOnly && item.kind !== "triangle") return false; + if (item.kind === "atlas") { + if ( + !item.plan || + !updateAtlasElementWithStablePlan(item.element, item.plan, polygon, textureLighting) + ) { + return false; + } + continue; + } + if (item.kind === "triangle") { + const element = item.element as SolidTriangleElement; + if (colorOnly) { + const shouldComputeColor = internalOptions.stableTriangleColorPolicy === "adaptive" || + shouldComputeStableTriangleColor( + element, + i, + optimizeTriangleStyle, + stableTriangleDebug, + internalOptions.stableTriangleColorPolicy, + colorState, + ); + nextTriangleColorPlans[i] = shouldComputeColor + ? computeSolidTriangleColorPlan(polygon, i, options) + : null; + continue; + } + const plan = computeSolidTrianglePlan(polygon, i, options, { + basis: element.__polycssSolidTriangleBasis, + matrixDecimals, + primitive: solidTrianglePrimitive, + includeColor: stableTriangleUpdateMode !== "plan-only" && + stableTriangleUpdateMode !== "transform-only" && + shouldComputeStableTriangleColor( + element, + i, + optimizeTriangleStyle, + stableTriangleDebug, + internalOptions.stableTriangleColorPolicy, + colorState, + ), + }); + if (!plan) { + nextTrianglePlans[i] = null; + continue; + } + nextTrianglePlans[i] = plan; + continue; + } + if (item.kind === "solid") { + if (!item.plan || polygon.texture || polygon.vertices.length !== item.plan.polygon.vertices.length) return false; + nextTexturePlans[i] = item.plan; + continue; + } + if (item.kind === "border") { + const plan = computeTextureAtlasPlan(polygon, i, options, projectiveQuadGuards); + if ( + !plan || + plan.texture || + !useBorderShape || + (useFullRectSolid && isFullRectSolid(plan)) || + (useProjectiveQuad && isProjectiveQuadPlan(plan)) || + (useCornerShapeSolid && !!cornerShapeGeometryForPlan(plan)) + ) { + return false; + } + nextTexturePlans[i] = plan; + continue; + } + if (item.kind === "corner") { + const plan = computeTextureAtlasPlan(polygon, i, options, projectiveQuadGuards); + if ( + !plan || + plan.texture || + !useCornerShapeSolid || + isSolidTrianglePlan(plan) || + (useFullRectSolid && isFullRectSolid(plan)) || + (useProjectiveQuad && isProjectiveQuadPlan(plan)) || + !cornerShapeGeometryForPlan(plan) + ) { + return false; + } + nextTexturePlans[i] = plan; + continue; + } + return false; + } + + const adaptiveColorUpdates = optimizeTriangleStyle && stableTriangleUpdateMode !== "plan-only" && + stableTriangleUpdateMode !== "transform-only" + ? selectAdaptiveTriangleColorUpdates( + rendered, + colorOnly ? nextTriangleColorPlans : nextTrianglePlans, + internalOptions, + ) + : null; + + for (let i = 0; i < rendered.length; i++) { + const item = rendered[i]; + if (item.kind === "triangle") { + if (colorOnly) { + const plan = nextTriangleColorPlans[i]; + if (plan) { + applySolidTriangleElementColorOnly( + item.element, + plan, + colorState, + adaptiveColorUpdates?.has(i), + ); + } + continue; + } + const plan = nextTrianglePlans[i]; + if (!plan) { + hideSolidTriangleElement(item.element); + continue; + } + if (optimizeTriangleStyle && stableTriangleUpdateMode === "plan-only") { + continue; + } else if (optimizeTriangleStyle && stableTriangleUpdateMode === "transform-only") { + applySolidTriangleElementTransformOnly(item.element, plan); + } else if (optimizeTriangleStyle) { + applySolidTriangleElementFast( + item.element, + plan, + colorState, + adaptiveColorUpdates?.has(i), + ); + } else { + applySolidTriangleElement(item.element, plan); + } + } else if (item.kind === "solid") { + const plan = nextTexturePlans[i]; + if (!plan) return false; + if ( + !updateSolidElementWithStablePlan( + item.element, + plan, + polygons[i], + textureLighting, + options, + projectiveQuadGuards, + internalOptions.solidPaintDefaults, + ) + ) { + return false; + } + } else if (item.kind === "border") { + const plan = nextTexturePlans[i]; + if (!plan) return false; + updateBorderShapeElementWithStablePlan(item.element, plan, textureLighting, internalOptions.solidPaintDefaults); + } else if (item.kind === "corner") { + const plan = nextTexturePlans[i]; + const geometry = plan ? cornerShapeGeometryForPlan(plan) : null; + if (!plan || !geometry) return false; + updateCornerShapeElementWithStablePlan( + item.element, + plan, + geometry, + textureLighting, + internalOptions.solidPaintDefaults, + ); + } + } + + return true; +} diff --git a/packages/polycss/src/render/atlas/render/stableTriangleFrame.ts b/packages/polycss/src/render/atlas/render/stableTriangleFrame.ts new file mode 100644 index 000000000..448515f14 --- /dev/null +++ b/packages/polycss/src/render/atlas/render/stableTriangleFrame.ts @@ -0,0 +1,127 @@ +import type { Polygon, SolidTriangleFrame } from "@layoutit/polycss-core"; +import { + DEFAULT_TILE, + stableTriangleMatrixDecimals, +} from "@layoutit/polycss-core"; +import type { + InternalRenderTextureAtlasOptions, + RenderedPoly, + RenderTextureAtlasOptions, + SolidTriangleElement, +} from "../types"; +import { resolveSolidTrianglePrimitive } from "../strategy"; +import { computeSolidTrianglePlanFromCssPoints } from "../solidTrianglePlan"; +import { + applySolidTriangleElementFast, + applySolidTriangleElementTransformOnly, + hideSolidTriangleElement, + shouldComputeStableTriangleColor, + stableTriangleColorState, +} from "../stableTriangle"; + +export function updateStableTriangleFrame( + 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; + 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, + 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; +} diff --git a/packages/polycss/src/render/atlas/renderPolygons.ts b/packages/polycss/src/render/atlas/renderPolygons.ts index 2593cce48..4b772e0fd 100644 --- a/packages/polycss/src/render/atlas/renderPolygons.ts +++ b/packages/polycss/src/render/atlas/renderPolygons.ts @@ -1,151 +1,26 @@ -import type { Polygon } from "@layoutit/polycss-core"; +import type { Polygon, SolidPaintDefaults } from "@layoutit/polycss-core"; +import { buildBasisHints, computeTextureAtlasPlan } from "@layoutit/polycss-core"; import type { - TextureAtlasPlan, - SolidPaintDefaults, - SolidTrianglePlan, - SolidTriangleColorPlan, - SolidTriangleFrame, - CornerShapeGeometry, -} from "@layoutit/polycss-core"; -import type { - RenderTextureAtlasOptions, InternalRenderTextureAtlasOptions, RenderedPoly, + RenderTextureAtlasOptions, RenderTextureAtlasResult, - RenderTextureAtlasAsyncResult, - SolidTriangleElement, } from "./types"; -import { - ASYNC_RENDER_BUDGET_MS, - DEFAULT_TILE, - PROJECTIVE_QUAD_DENOM_EPS, - PROJECTIVE_QUAD_MAX_WEIGHT_RATIO, - PROJECTIVE_QUAD_BLEED, - resolveSeamBleedPx, - seamBleedPrimitiveRatio, -} from "@layoutit/polycss-core"; -import { - buildBasisHints, - buildSeamBleedPolygonEdges, - computeTextureAtlasPlan, - resolvePolyTextureLeafGeometry, -} from "@layoutit/polycss-core"; import { resolveProjectiveQuadGuards } from "./plan"; -import { - getSolidPaintDefaultsForPlans, - isFullRectSolid, - isSolidTrianglePlan, - isProjectiveQuadPlan, - projectiveQuadSupported, - cornerShapeSupported, - borderShapeSupported, - resolveSolidTrianglePrimitive, -} from "./strategy"; -import { cornerShapeGeometryForPlan } from "@layoutit/polycss-core"; +import { getSolidPaintDefaultsForPlans } from "./strategy"; import { packTextureAtlasPlansWithScale } from "./packing"; -import { buildAtlasPages } from "./rasterise"; -import { - createAtlasElement, - createTextureImageElement, - createSolidElement, - createBorderShapeSolidElement, - createCornerShapeSolidElement, - createProjectiveSolidElement, - applyAtlasBackground, - updateAtlasElementWithStablePlan, - updateSolidElementWithStablePlan, - updateBorderShapeElementWithStablePlan, - updateCornerShapeElementWithStablePlan, -} from "./emit"; -import { setInlineStyleProperty } from "./paintDefaults"; -import { computeSolidTriangleColorPlan } from "@layoutit/polycss-core"; import { - computeSolidTrianglePlan, - computeSolidTrianglePlanFromCssPoints, -} from "./solidTrianglePlan"; -import { - createSolidTriangleElement, - createHiddenSolidTriangleElement, - applySolidTriangleElement, - applySolidTriangleElementFast, - applySolidTriangleElementColorOnly, - applySolidTriangleElementTransformOnly, - hideSolidTriangleElement, - stableTriangleColorState, - shouldComputeStableTriangleColor, - selectAdaptiveTriangleColorUpdates, - updateStableTriangleElementsStreaming, -} from "./stableTriangle"; -import { stableTriangleMatrixDecimals } from "@layoutit/polycss-core"; - -// `options.seamBleed` is the raw public option (`number | "auto" | -// undefined`) and passes straight through to core plan construction, -// which owns the resolution: `resolveSeamBleedPx` yields the absolute -// shared-edge overscan in CSS px (default 1.5) and -// `seamBleedPrimitiveRatio` scales the per-strategy primitive bleeds -// (SOLID_TRIANGLE_BLEED, BORDER_SHAPE_BLEED, TEXTURE_TRIANGLE_BLEED, -// PROJECTIVE_QUAD_BLEED). The helpers below only attach the detected -// per-polygon seam-edge sets. - -type RenderTextureAtlasOptionsWithSeams = RenderTextureAtlasOptions & { - seamBleed?: import("@layoutit/polycss-core").PolySeamBleed; - seamEdges?: Set; -}; - -function yieldToMainThread(): Promise { - return new Promise((resolve) => setTimeout(resolve, 0)); -} - -async function yieldIfOverBudget(started: number): Promise { - if (performance.now() - started < ASYNC_RENDER_BUDGET_MS) return started; - await yieldToMainThread(); - return performance.now(); -} - -function seamTriangleOptions( - plan: TextureAtlasPlan, - options: RenderTextureAtlasOptionsWithSeams, -): RenderTextureAtlasOptionsWithSeams { - // Raw `options.seamBleed` passes through — core resolves it. Only the - // seam-edge set detected on the atlas plan is attached here. - return plan.seamBleedEdges?.size - ? { ...options, seamEdges: plan.seamBleedEdges } - : { ...options, seamEdges: undefined }; -} - -function buildRenderSeamBleedEdges( - polygons: Polygon[], - options: RenderTextureAtlasOptionsWithSeams, -): Map> | null { - // A resolved overscan of 0 disables the shared-edge bleed entirely, so - // skip the O(edges) seam-map build (mirrors React/Vue). - if (resolveSeamBleedPx(options.seamBleed) <= 0) return null; - return buildSeamBleedPolygonEdges(polygons, { - tileSize: options.tileSize, - layerElevation: options.layerElevation, - directionalLight: options.directionalLight, - ambientLight: options.ambientLight, - }); -} - -function seamAtlasOptions( - index: number, - seamBleedEdges: Map> | null, - options: RenderTextureAtlasOptionsWithSeams, -): RenderTextureAtlasOptionsWithSeams { - return seamBleedEdges - ? { ...options, seamEdges: seamBleedEdges.get(index) } - : options; -} - -// Default projective-quad guard bleed, scaled by the seamBleed-derived -// primitive ratio. resolveProjectiveQuadGuards merges these UNDER the -// `window.__polycssProjectiveQuadGuards` debug override. -function projectiveQuadGuardDefaults( - options: RenderTextureAtlasOptionsWithSeams, -): { bleed: number } { - return { bleed: PROJECTIVE_QUAD_BLEED * seamBleedPrimitiveRatio(options.seamBleed) }; -} + buildRenderSeamBleedEdges, + classifyPolygonRenderPlans, + projectiveQuadGuardDefaults, + resolveAtlasRenderCapabilities, + seamAtlasOptions, +} from "./render/planning"; +import { attachAtlasPageHydration, emitPolygonLeaf } from "./render/emitLeaves"; + +export { renderPolygonsWithTextureAtlasAsync } from "./render/asyncRender"; +export { updateStableTriangleFrame } from "./render/stableTriangleFrame"; +export { updatePolygonsWithStableTopology } from "./render/stableTopologyUpdate"; export function getSolidPaintDefaults( polygons: Polygon[], @@ -177,13 +52,7 @@ export function renderPolygonsWithTextureAtlas( const internalOptions = options as InternalRenderTextureAtlasOptions; const skipDynamicNormalVars = textureLighting === "dynamic" && internalOptions.skipDynamicNormalVars === true; - const disabled = new Set(options.strategies?.disable ?? []); - const useFullRectSolid = !disabled.has("b"); - const useProjectiveQuad = useFullRectSolid && projectiveQuadSupported(doc); - const solidTrianglePrimitive = resolveSolidTrianglePrimitive(doc, options.strategies); - const useStableTriangle = solidTrianglePrimitive !== null; - const useCornerShapeSolid = !disabled.has("i") && cornerShapeSupported(doc); - const useBorderShape = !disabled.has("i") && borderShapeSupported(doc); + const capabilities = resolveAtlasRenderCapabilities(doc, options); const basisHints = buildBasisHints(polygons, options); const projectiveQuadGuards = resolveProjectiveQuadGuards(doc, projectiveQuadGuardDefaults(options)); const seamBleedEdges = buildRenderSeamBleedEdges(polygons, options); @@ -203,40 +72,10 @@ export function renderPolygonsWithTextureAtlas( const triangleOptions = solidPaintDefaults ? { ...options, solidPaintDefaults } : options; - const trianglePlans = plans.map((plan) => - plan && useStableTriangle && isSolidTrianglePlan(plan) - ? computeSolidTrianglePlan(plan.polygon, plan.index, seamTriangleOptions(plan, triangleOptions), { - primitive: solidTrianglePrimitive ?? undefined, - }) - : null - ); - const cornerShapePlans = plans.map((plan) => - plan && - useCornerShapeSolid && - !isSolidTrianglePlan(plan) && - !(useFullRectSolid && isFullRectSolid(plan)) && - !(useProjectiveQuad && isProjectiveQuadPlan(plan)) - ? cornerShapeGeometryForPlan(plan) - : null - ); - const imagePlans = plans.map((plan) => plan - ? resolvePolyTextureLeafGeometry(plan, { - imageRendering: options.textureImageRendering, - backend: options.textureBackend, - projection: options.textureProjection, - allowProjective: useProjectiveQuad, - projectiveQuadGuards, - }) - : null - ); - const atlasPlans = plans.map((plan, index) => - imagePlans[index] - ? null - : plan && - (plan.texture - ? plan - : (!(useFullRectSolid && isFullRectSolid(plan)) && !trianglePlans[index] && !(useProjectiveQuad && isProjectiveQuadPlan(plan)) && !cornerShapePlans[index] && !useBorderShape) ? plan : null) + const classifiedPlans = plans.map((plan) => + classifyPolygonRenderPlans(plan, capabilities, options, triangleOptions, projectiveQuadGuards) ); + const atlasPlans = classifiedPlans.map((classified) => classified.atlasPlan); const { packed, atlasScale } = packTextureAtlasPlansWithScale( atlasPlans, options.textureQuality, @@ -245,596 +84,40 @@ export function renderPolygonsWithTextureAtlas( ); const atlasElements = new Map(); const rendered: RenderedPoly[] = []; - let cancelled = false; - let urls: string[] = []; + const emitContext = { + doc, + textureLighting, + skipDynamicNormalVars, + textureImageRendering: options.textureImageRendering, + solidPaintDefaults, + capabilities, + packed, + atlasElements, + rendered, + }; for (let i = 0; i < polygons.length; i++) { const plan = plans[i]; - const trianglePlan = trianglePlans[i]; - const cornerShapePlan = cornerShapePlans[i]; - const imagePlan = imagePlans[i]; if (!plan) continue; - - const entry = packed.entries[i]; - if (entry) { - const element = createAtlasElement(entry, textureLighting, doc, skipDynamicNormalVars, options.textureImageRendering); - atlasElements.set(i, element); - rendered.push({ polygonIndex: i, element, kind: "atlas", plan: entry, dispose: () => {} }); - } else if (imagePlan) { - const element = createTextureImageElement(plan, imagePlan, doc, skipDynamicNormalVars); - rendered.push({ polygonIndex: i, element, kind: "image", plan, dispose: () => {} }); - } else if (!plan.texture && useFullRectSolid && isFullRectSolid(plan)) { - const element = createSolidElement(plan, textureLighting, doc, solidPaintDefaults, skipDynamicNormalVars); - rendered.push({ polygonIndex: i, element, kind: "solid", plan, dispose: () => {} }); - } else if (!plan.texture && trianglePlan) { - const element = createSolidTriangleElement(trianglePlan, doc); - rendered.push({ polygonIndex: i, element, kind: "triangle", plan, dispose: () => {} }); - } else if (!plan.texture && useProjectiveQuad && isProjectiveQuadPlan(plan)) { - const element = createProjectiveSolidElement(plan, textureLighting, doc, solidPaintDefaults, skipDynamicNormalVars); - rendered.push({ polygonIndex: i, element, kind: "solid", plan, dispose: () => {} }); - } else if (!plan.texture && cornerShapePlan) { - const element = createCornerShapeSolidElement(plan, cornerShapePlan, textureLighting, doc, solidPaintDefaults, skipDynamicNormalVars); - rendered.push({ polygonIndex: i, element, kind: "corner", plan, dispose: () => {} }); - } else if (!plan.texture && useBorderShape) { - const element = createBorderShapeSolidElement(plan, textureLighting, doc, solidPaintDefaults, skipDynamicNormalVars); - rendered.push({ polygonIndex: i, element, kind: "border", plan, dispose: () => {} }); - } + emitPolygonLeaf(i, plan, classifiedPlans[i], emitContext); } rendered.sort((a, b) => a.polygonIndex - b.polygonIndex); - const pagesReady = buildAtlasPages(packed.pages, textureLighting, doc, atlasScale, () => cancelled) - .then((pages) => { - if (cancelled) { - for (const page of pages) { - if (page.url?.startsWith("blob:")) URL.revokeObjectURL(page.url); - } - return; - } - urls = pages.flatMap((page) => page.url?.startsWith("blob:") ? [page.url] : []); - for (let pageIndex = 0; pageIndex < packed.pages.length; pageIndex++) { - const page = packed.pages[pageIndex]; - const built = pages[pageIndex]; - if (!built) continue; - for (const entry of page.entries) { - const el = atlasElements.get(entry.index); - if (!el || !built.url) continue; - // preserveDynamicNormalVars is always true here: this callback fires - // after syncMountedRendered has restored inline normals on solo polys. - applyAtlasBackground(el, built, textureLighting, entry, true, options.textureImageRendering); - } - } - }) - .catch(() => { - if (cancelled) return; - for (const element of atlasElements.values()) { - setInlineStyleProperty(element, "opacity", "0.5"); - setInlineStyleProperty(element, "outline", "1px dashed rgba(255, 0, 0, 0.6)"); - } - }); + const { pagesReady, dispose } = attachAtlasPageHydration( + packed, + atlasScale, + atlasElements, + textureLighting, + doc, + options.textureImageRendering, + ); const result = { rendered, solidPaintDefaults: solidPaintDefaults ?? {}, pagesReady, - dispose() { - cancelled = true; - for (const url of urls) URL.revokeObjectURL(url); - urls = []; - }, + dispose, }; return result; } - -export async function renderPolygonsWithTextureAtlasAsync( - polygons: Polygon[], - options: RenderTextureAtlasOptions = {}, - shouldCancel: () => boolean = () => false, -): Promise { - const doc = options.doc ?? (typeof document !== "undefined" ? document : null); - if (!doc || shouldCancel()) { - return { rendered: [], solidPaintDefaults: {}, dispose: () => {} }; - } - - const textureLighting = options.textureLighting ?? "baked"; - const internalOptions = options as InternalRenderTextureAtlasOptions; - const skipDynamicNormalVars = - textureLighting === "dynamic" && internalOptions.skipDynamicNormalVars === true; - const disabled = new Set(options.strategies?.disable ?? []); - const useFullRectSolid = !disabled.has("b"); - const useProjectiveQuad = useFullRectSolid && projectiveQuadSupported(doc); - const solidTrianglePrimitive = resolveSolidTrianglePrimitive(doc, options.strategies); - const useStableTriangle = solidTrianglePrimitive !== null; - const useCornerShapeSolid = !disabled.has("i") && cornerShapeSupported(doc); - const useBorderShape = !disabled.has("i") && borderShapeSupported(doc); - await yieldToMainThread(); - if (shouldCancel()) return { rendered: [], solidPaintDefaults: {}, dispose: () => {} }; - - const basisHints = buildBasisHints(polygons, options); - const projectiveQuadGuards = resolveProjectiveQuadGuards(doc, projectiveQuadGuardDefaults(options)); - const seamBleedEdges = buildRenderSeamBleedEdges(polygons, options); - let batchStarted = performance.now(); - const plans: Array = new Array(polygons.length); - for (let i = 0; i < polygons.length; i++) { - plans[i] = computeTextureAtlasPlan( - polygons[i], - i, - seamAtlasOptions(i, seamBleedEdges, options), - projectiveQuadGuards, - basisHints[i], - ); - batchStarted = await yieldIfOverBudget(batchStarted); - if (shouldCancel()) return { rendered: [], solidPaintDefaults: {}, dispose: () => {} }; - } - - const solidPaintDefaults = options.solidPaintDefaults ?? - getSolidPaintDefaultsForPlans(plans, textureLighting, doc, options.strategies); - const trianglePlans: Array = new Array(plans.length); - const cornerShapePlans: Array = new Array(plans.length); - const imagePlans: Array> = new Array(plans.length); - const atlasPlans: Array = new Array(plans.length); - for (let i = 0; i < plans.length; i++) { - const plan = plans[i]; - const trianglePlan = plan && useStableTriangle && isSolidTrianglePlan(plan) - ? computeSolidTrianglePlan(plan.polygon, plan.index, seamTriangleOptions(plan, { ...options, solidPaintDefaults }), { - primitive: solidTrianglePrimitive ?? undefined, - }) - : null; - trianglePlans[i] = trianglePlan; - const cornerShapePlan = plan && - useCornerShapeSolid && - !isSolidTrianglePlan(plan) && - !(useFullRectSolid && isFullRectSolid(plan)) && - !(useProjectiveQuad && isProjectiveQuadPlan(plan)) - ? cornerShapeGeometryForPlan(plan) - : null; - cornerShapePlans[i] = cornerShapePlan; - const imagePlan = plan - ? resolvePolyTextureLeafGeometry(plan, { - imageRendering: options.textureImageRendering, - backend: options.textureBackend, - projection: options.textureProjection, - allowProjective: useProjectiveQuad, - projectiveQuadGuards, - }) - : null; - imagePlans[i] = imagePlan; - atlasPlans[i] = imagePlan - ? null - : plan && - (plan.texture - ? plan - : (!(useFullRectSolid && isFullRectSolid(plan)) && !trianglePlan && !(useProjectiveQuad && isProjectiveQuadPlan(plan)) && !cornerShapePlan && !useBorderShape) ? plan : null); - batchStarted = await yieldIfOverBudget(batchStarted); - if (shouldCancel()) return { rendered: [], solidPaintDefaults, dispose: () => {} }; - } - - const { packed, atlasScale } = packTextureAtlasPlansWithScale( - atlasPlans, - options.textureQuality, - doc, - options.textureLeafSizing, - ); - const atlasElements = new Map(); - const rendered: RenderedPoly[] = []; - let cancelled = false; - let urls: string[] = []; - - for (let i = 0; i < polygons.length; i++) { - const plan = plans[i]; - const trianglePlan = trianglePlans[i]; - const cornerShapePlan = cornerShapePlans[i]; - const imagePlan = imagePlans[i]; - if (!plan) continue; - - const entry = packed.entries[i]; - if (entry) { - const element = createAtlasElement(entry, textureLighting, doc, skipDynamicNormalVars, options.textureImageRendering); - atlasElements.set(i, element); - rendered.push({ polygonIndex: i, element, kind: "atlas", plan: entry, dispose: () => {} }); - } else if (imagePlan) { - const element = createTextureImageElement(plan, imagePlan, doc, skipDynamicNormalVars); - rendered.push({ polygonIndex: i, element, kind: "image", plan, dispose: () => {} }); - } else if (!plan.texture && useFullRectSolid && isFullRectSolid(plan)) { - const element = createSolidElement(plan, textureLighting, doc, solidPaintDefaults, skipDynamicNormalVars); - rendered.push({ polygonIndex: i, element, kind: "solid", plan, dispose: () => {} }); - } else if (!plan.texture && trianglePlan) { - const element = createSolidTriangleElement(trianglePlan, doc); - rendered.push({ polygonIndex: i, element, kind: "triangle", plan, dispose: () => {} }); - } else if (!plan.texture && useProjectiveQuad && isProjectiveQuadPlan(plan)) { - const element = createProjectiveSolidElement(plan, textureLighting, doc, solidPaintDefaults, skipDynamicNormalVars); - rendered.push({ polygonIndex: i, element, kind: "solid", plan, dispose: () => {} }); - } else if (!plan.texture && cornerShapePlan) { - const element = createCornerShapeSolidElement(plan, cornerShapePlan, textureLighting, doc, solidPaintDefaults, skipDynamicNormalVars); - rendered.push({ polygonIndex: i, element, kind: "corner", plan, dispose: () => {} }); - } else if (!plan.texture && useBorderShape) { - const element = createBorderShapeSolidElement(plan, textureLighting, doc, solidPaintDefaults, skipDynamicNormalVars); - rendered.push({ polygonIndex: i, element, kind: "border", plan, dispose: () => {} }); - } - batchStarted = await yieldIfOverBudget(batchStarted); - if (shouldCancel()) { - for (const item of rendered) item.dispose(); - return { rendered: [], solidPaintDefaults, dispose: () => {} }; - } - } - - rendered.sort((a, b) => a.polygonIndex - b.polygonIndex); - - const pagesReady = buildAtlasPages(packed.pages, textureLighting, doc, atlasScale, () => cancelled || shouldCancel()) - .then((pages) => { - if (cancelled || shouldCancel()) { - for (const page of pages) { - if (page.url?.startsWith("blob:")) URL.revokeObjectURL(page.url); - } - return; - } - urls = pages.flatMap((page) => page.url?.startsWith("blob:") ? [page.url] : []); - for (let pageIndex = 0; pageIndex < packed.pages.length; pageIndex++) { - const page = packed.pages[pageIndex]; - const built = pages[pageIndex]; - if (!built) continue; - for (const entry of page.entries) { - const el = atlasElements.get(entry.index); - if (!el || !built.url) continue; - // preserveDynamicNormalVars is always true here: this callback fires - // after syncMountedRendered has restored inline normals on solo polys. - applyAtlasBackground(el, built, textureLighting, entry, true, options.textureImageRendering); - } - } - }) - .catch(() => { - if (cancelled || shouldCancel()) return; - for (const element of atlasElements.values()) { - setInlineStyleProperty(element, "opacity", "0.5"); - setInlineStyleProperty(element, "outline", "1px dashed rgba(255, 0, 0, 0.6)"); - } - }); - - return { - rendered, - solidPaintDefaults, - pagesReady, - dispose() { - cancelled = true; - for (const url of urls) URL.revokeObjectURL(url); - urls = []; - }, - }; -} - -export function updateStableTriangleFrame( - 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; - 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, - 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 updatePolygonsWithStableTopology( - rendered: RenderedPoly[], - polygons: Polygon[], - options: RenderTextureAtlasOptions = {}, -): boolean { - if (rendered.length !== polygons.length) return false; - const internalOptions = options as InternalRenderTextureAtlasOptions; - const doc = options.doc ?? (typeof document !== "undefined" ? document : null); - const textureLighting = options.textureLighting ?? "baked"; - const disabled = new Set(options.strategies?.disable ?? []); - const useFullRectSolid = !disabled.has("b"); - const useProjectiveQuad = !!doc && useFullRectSolid && projectiveQuadSupported(doc); - const useCornerShapeSolid = !!doc && !disabled.has("i") && cornerShapeSupported(doc); - const useBorderShape = !!doc && !disabled.has("i") && borderShapeSupported(doc); - // Resolve the per-strategy ratio once so projective-quad / corner-shape - // checks below all read from the same value as the plan stamping. - const bleedRatio = seamBleedPrimitiveRatio(internalOptions.seamBleed); - // Pass the resolved bleed as an explicit override so resolveProjectiveQuadGuards - // (which has its own fallback path) returns the scaled value too. - const projectiveQuadGuards = doc - ? resolveProjectiveQuadGuards(doc, { bleed: PROJECTIVE_QUAD_BLEED * bleedRatio }) - : { - denomEps: PROJECTIVE_QUAD_DENOM_EPS, - maxWeightRatio: PROJECTIVE_QUAD_MAX_WEIGHT_RATIO, - bleed: PROJECTIVE_QUAD_BLEED * bleedRatio, - disableGuards: false, - }; - const optimizeTriangleStyle = - internalOptions.optimizeStableTriangleStyle === true && - textureLighting === "baked"; - const stableTriangleDebug = internalOptions.stableTriangleDebug; - const stableTriangleUpdateMode = internalOptions.stableTriangleUpdateMode ?? - (stableTriangleDebug === "plan-only" || stableTriangleDebug === "transform-only" - ? stableTriangleDebug - : "full"); - const colorOnly = optimizeTriangleStyle && stableTriangleUpdateMode === "color-only"; - const colorState = stableTriangleColorState(internalOptions); - const matrixDecimals = stableTriangleMatrixDecimals(internalOptions.stableTriangleMatrixDecimals); - const solidTrianglePrimitive = doc - ? resolveSolidTrianglePrimitive(doc, options.strategies) ?? "border" - : "border"; - if ( - updateStableTriangleElementsStreaming( - rendered, - polygons, - options, - optimizeTriangleStyle, - stableTriangleUpdateMode, - colorState, - ) - ) { - return true; - } - const nextTrianglePlans: Array = []; - const nextTriangleColorPlans: Array = []; - const nextTexturePlans: Array = []; - - for (let i = 0; i < rendered.length; i++) { - const item = rendered[i]; - if (item.polygonIndex !== i) return false; - const polygon = polygons[i]; - if (!polygon) return false; - if (colorOnly && item.kind !== "triangle") return false; - if (item.kind === "atlas") { - if ( - !item.plan || - !updateAtlasElementWithStablePlan(item.element, item.plan, polygon, textureLighting) - ) { - return false; - } - continue; - } - if (item.kind === "triangle") { - const element = item.element as SolidTriangleElement; - if (colorOnly) { - const shouldComputeColor = internalOptions.stableTriangleColorPolicy === "adaptive" || - shouldComputeStableTriangleColor( - element, - i, - optimizeTriangleStyle, - stableTriangleDebug, - internalOptions.stableTriangleColorPolicy, - colorState, - ); - nextTriangleColorPlans[i] = shouldComputeColor - ? computeSolidTriangleColorPlan(polygon, i, options) - : null; - continue; - } - const plan = computeSolidTrianglePlan(polygon, i, options, { - basis: element.__polycssSolidTriangleBasis, - matrixDecimals, - primitive: solidTrianglePrimitive, - includeColor: stableTriangleUpdateMode !== "plan-only" && - stableTriangleUpdateMode !== "transform-only" && - shouldComputeStableTriangleColor( - element, - i, - optimizeTriangleStyle, - stableTriangleDebug, - internalOptions.stableTriangleColorPolicy, - colorState, - ), - }); - if (!plan) { - nextTrianglePlans[i] = null; - continue; - } - nextTrianglePlans[i] = plan; - continue; - } - if (item.kind === "solid") { - if (!item.plan || polygon.texture || polygon.vertices.length !== item.plan.polygon.vertices.length) return false; - nextTexturePlans[i] = item.plan; - continue; - } - if (item.kind === "border") { - const plan = computeTextureAtlasPlan(polygon, i, options, projectiveQuadGuards); - if ( - !plan || - plan.texture || - !useBorderShape || - (useFullRectSolid && isFullRectSolid(plan)) || - (useProjectiveQuad && isProjectiveQuadPlan(plan)) || - (useCornerShapeSolid && !!cornerShapeGeometryForPlan(plan)) - ) { - return false; - } - nextTexturePlans[i] = plan; - continue; - } - if (item.kind === "corner") { - const plan = computeTextureAtlasPlan(polygon, i, options, projectiveQuadGuards); - if ( - !plan || - plan.texture || - !useCornerShapeSolid || - isSolidTrianglePlan(plan) || - (useFullRectSolid && isFullRectSolid(plan)) || - (useProjectiveQuad && isProjectiveQuadPlan(plan)) || - !cornerShapeGeometryForPlan(plan) - ) { - return false; - } - nextTexturePlans[i] = plan; - continue; - } - return false; - } - - const adaptiveColorUpdates = optimizeTriangleStyle && stableTriangleUpdateMode !== "plan-only" && - stableTriangleUpdateMode !== "transform-only" - ? selectAdaptiveTriangleColorUpdates( - rendered, - colorOnly ? nextTriangleColorPlans : nextTrianglePlans, - internalOptions, - ) - : null; - - for (let i = 0; i < rendered.length; i++) { - const item = rendered[i]; - if (item.kind === "triangle") { - if (colorOnly) { - const plan = nextTriangleColorPlans[i]; - if (plan) { - applySolidTriangleElementColorOnly( - item.element, - plan, - colorState, - adaptiveColorUpdates?.has(i), - ); - } - continue; - } - const plan = nextTrianglePlans[i]; - if (!plan) { - hideSolidTriangleElement(item.element); - continue; - } - if (optimizeTriangleStyle && stableTriangleUpdateMode === "plan-only") { - continue; - } else if (optimizeTriangleStyle && stableTriangleUpdateMode === "transform-only") { - applySolidTriangleElementTransformOnly(item.element, plan); - } else if (optimizeTriangleStyle) { - applySolidTriangleElementFast( - item.element, - plan, - colorState, - adaptiveColorUpdates?.has(i), - ); - } else { - applySolidTriangleElement(item.element, plan); - } - } else if (item.kind === "solid") { - const plan = nextTexturePlans[i]; - if (!plan) return false; - if ( - !updateSolidElementWithStablePlan( - item.element, - plan, - polygons[i], - textureLighting, - options, - projectiveQuadGuards, - internalOptions.solidPaintDefaults, - ) - ) { - return false; - } - } else if (item.kind === "border") { - const plan = nextTexturePlans[i]; - if (!plan) return false; - updateBorderShapeElementWithStablePlan(item.element, plan, textureLighting, internalOptions.solidPaintDefaults); - } else if (item.kind === "corner") { - const plan = nextTexturePlans[i]; - const geometry = plan ? cornerShapeGeometryForPlan(plan) : null; - if (!plan || !geometry) return false; - updateCornerShapeElementWithStablePlan( - item.element, - plan, - geometry, - textureLighting, - internalOptions.solidPaintDefaults, - ); - } - } - - return true; -} diff --git a/packages/polycss/src/render/voxel/items.ts b/packages/polycss/src/render/voxel/items.ts new file mode 100644 index 000000000..5421cec06 --- /dev/null +++ b/packages/polycss/src/render/voxel/items.ts @@ -0,0 +1,241 @@ +import type { Polygon, Vec3 } from "@layoutit/polycss-core"; +import { BASE_TILE, PROJECTIVE_QUAD_BLEED } from "@layoutit/polycss-core"; +import { canonicalBrushColor } from "./shading"; +import type { + DirectMatrixItem, + VoxelSeamBleed, + VoxelSeamSide, + WorldAxisIndex, +} from "./types"; +import { FACE_BY_NORMAL } from "./types"; + +interface VoxelSeamSegment { + item: DirectMatrixItem; + side: VoxelSeamSide; + variableAxis: WorldAxisIndex; + fixed: [number, number, number]; + start: number; + end: number; +} + +const VOXEL_SEAM_BLEED = PROJECTIVE_QUAD_BLEED; +const VOXEL_SEAM_EPS = 1e-6; + +function zeroVoxelSeamBleed(): VoxelSeamBleed { + return { left: 0, right: 0, top: 0, bottom: 0 }; +} + +function cssNormalForPolygon(polygon: Polygon): Vec3 | null { + const vertices = polygon.vertices; + if (vertices.length < 3) return null; + const v0 = vertices[0]; + let nx = 0; + let ny = 0; + let nz = 0; + for (let i = 1; i + 1 < vertices.length; i += 1) { + const v1 = vertices[i]; + const v2 = vertices[i + 1]; + const e1x = v1[1] - v0[1]; + const e1y = v1[0] - v0[0]; + const e1z = v1[2] - v0[2]; + const e2x = v2[1] - v0[1]; + const e2y = v2[0] - v0[0]; + const e2z = v2[2] - v0[2]; + nx -= e1y * e2z - e1z * e2y; + ny -= e1z * e2x - e1x * e2z; + nz -= e1x * e2y - e1y * e2x; + } + const len = Math.hypot(nx, ny, nz); + if (len <= 1e-9) return null; + return [ + Math.round(nx / len), + Math.round(ny / len), + Math.round(nz / len), + ]; +} + +function polygonBrush(polygon: Polygon): Omit | null { + if (polygon.texture || polygon.material || polygon.uvs || polygon.textureTriangles) return null; + if (polygon.vertices.length !== 4) return null; + const normal = cssNormalForPolygon(polygon); + const face = normal ? FACE_BY_NORMAL.get(normal.join(",")) : undefined; + if (!face) return null; + + let minX = Infinity; + let minY = Infinity; + let minZ = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + let maxZ = -Infinity; + for (const v of polygon.vertices) { + minX = Math.min(minX, v[0]); + minY = Math.min(minY, v[1]); + minZ = Math.min(minZ, v[2]); + maxX = Math.max(maxX, v[0]); + maxY = Math.max(maxY, v[1]); + maxZ = Math.max(maxZ, v[2]); + } + + const eps = 1e-6; + const baseColor = canonicalBrushColor(polygon.color); + if (Math.abs(maxZ - minZ) <= eps) { + return { + axis: "z", + face, + left: minY * BASE_TILE, + top: minX * BASE_TILE, + width: Math.max(0, (maxY - minY) * BASE_TILE), + height: Math.max(0, (maxX - minX) * BASE_TILE), + z: minZ * BASE_TILE, + baseColor, + bleed: zeroVoxelSeamBleed(), + }; + } + if (Math.abs(maxX - minX) <= eps) { + return { + axis: "x", + face, + left: minY * BASE_TILE, + top: minZ * BASE_TILE, + width: Math.max(0, (maxY - minY) * BASE_TILE), + height: Math.max(0, (maxZ - minZ) * BASE_TILE), + z: -minX * BASE_TILE, + baseColor, + bleed: zeroVoxelSeamBleed(), + }; + } + if (Math.abs(maxY - minY) <= eps) { + return { + axis: "y", + face, + left: minZ * BASE_TILE, + top: minX * BASE_TILE, + width: Math.max(0, (maxZ - minZ) * BASE_TILE), + height: Math.max(0, (maxX - minX) * BASE_TILE), + z: -minY * BASE_TILE, + baseColor, + bleed: zeroVoxelSeamBleed(), + }; + } + return null; +} + +function worldLineKey(segment: VoxelSeamSegment): string { + const coordKey = (value: number): string => String(Number(value.toFixed(6))); + let key = `${segment.item.baseColor}|${segment.variableAxis}`; + for (let axis = 0; axis < 3; axis += 1) { + if (axis === segment.variableAxis) continue; + key += `|${axis}:${coordKey(segment.fixed[axis])}`; + } + return key; +} + +function cssPointForVertex(v: Vec3): Vec3 { + return [v[1] * BASE_TILE, v[0] * BASE_TILE, v[2] * BASE_TILE]; +} + +function localPointForItem(item: DirectMatrixItem, p: Vec3): [number, number] { + if (item.axis === "x") return [p[0], p[2]]; + if (item.axis === "y") return [p[2], p[1]]; + return [p[0], p[1]]; +} + +function sideForLocalEdge( + item: DirectMatrixItem, + a: [number, number], + b: [number, number], +): VoxelSeamSide | null { + const left = item.left; + const right = item.left + item.width; + const top = item.top; + const bottom = item.top + item.height; + if (Math.abs(a[0] - b[0]) <= VOXEL_SEAM_EPS) { + if (Math.abs(a[0] - left) <= VOXEL_SEAM_EPS) return "left"; + if (Math.abs(a[0] - right) <= VOXEL_SEAM_EPS) return "right"; + } + if (Math.abs(a[1] - b[1]) <= VOXEL_SEAM_EPS) { + if (Math.abs(a[1] - top) <= VOXEL_SEAM_EPS) return "top"; + if (Math.abs(a[1] - bottom) <= VOXEL_SEAM_EPS) return "bottom"; + } + return null; +} + +function variableAxisForSegment(a: Vec3, b: Vec3): WorldAxisIndex | null { + let axis: WorldAxisIndex | null = null; + for (let i = 0; i < 3; i += 1) { + if (Math.abs(a[i] - b[i]) <= VOXEL_SEAM_EPS) continue; + if (axis !== null) return null; + axis = i as WorldAxisIndex; + } + return axis; +} + +function voxelSeamSegmentForEdge( + item: DirectMatrixItem, + polygon: Polygon, + edgeIndex: number, +): VoxelSeamSegment | null { + const vertices = polygon.vertices; + const a = cssPointForVertex(vertices[edgeIndex]); + const b = cssPointForVertex(vertices[(edgeIndex + 1) % vertices.length]); + const side = sideForLocalEdge(item, localPointForItem(item, a), localPointForItem(item, b)); + if (!side) return null; + const variableAxis = variableAxisForSegment(a, b); + if (variableAxis === null) return null; + const start = Math.min(a[variableAxis], b[variableAxis]); + const end = Math.max(a[variableAxis], b[variableAxis]); + return end - start > VOXEL_SEAM_EPS + ? { item, side, variableAxis, fixed: a, start, end } + : null; +} + +function markVoxelSeam(segment: VoxelSeamSegment): void { + segment.item.bleed[segment.side] = Math.max(segment.item.bleed[segment.side], VOXEL_SEAM_BLEED); +} + +function applyVoxelSeamBleed(polygons: readonly Polygon[], items: DirectMatrixItem[]): void { + const groups = new Map(); + for (const item of items) { + const polygon = polygons[item.sourceIndex]; + if (!polygon) continue; + for (let edgeIndex = 0; edgeIndex < polygon.vertices.length; edgeIndex += 1) { + const segment = voxelSeamSegmentForEdge(item, polygon, edgeIndex); + if (!segment) continue; + const key = worldLineKey(segment); + const group = groups.get(key); + if (group) group.push(segment); + else groups.set(key, [segment]); + } + } + + for (const segments of groups.values()) { + if (segments.length < 2) continue; + segments.sort((a, b) => a.start - b.start || a.end - b.end); + let active: VoxelSeamSegment[] = []; + for (const segment of segments) { + active = active.filter((candidate) => candidate.end > segment.start + VOXEL_SEAM_EPS); + for (const candidate of active) { + if (candidate.item.sourceIndex === segment.item.sourceIndex) continue; + markVoxelSeam(candidate); + markVoxelSeam(segment); + } + active.push(segment); + } + } +} + +export function buildDirectMatrixItems(polygons: readonly Polygon[] | undefined): DirectMatrixItem[] { + if (!polygons?.length) return []; + const items: DirectMatrixItem[] = []; + for (let sourceIndex = 0; sourceIndex < polygons.length; sourceIndex += 1) { + const polygon = polygons[sourceIndex]; + const brush = polygonBrush(polygon); + if (!brush || brush.width <= 0 || brush.height <= 0) return []; + items.push({ + ...brush, + sourceIndex, + }); + } + applyVoxelSeamBleed(polygons, items); + return items; +} diff --git a/packages/polycss/src/render/voxel/matrix.ts b/packages/polycss/src/render/voxel/matrix.ts new file mode 100644 index 000000000..9b6c729dd --- /dev/null +++ b/packages/polycss/src/render/voxel/matrix.ts @@ -0,0 +1,126 @@ +import type { Vec3 } from "@layoutit/polycss-core"; +import { + computeProjectiveQuadMatrix, + resolveProjectiveQuadGuards, + SOLID_QUAD_CANONICAL_SIZE, +} from "@layoutit/polycss-core"; +import type { DirectMatrixItem } from "./types"; + +const VOXEL_PROJECTIVE_QUAD_GUARDS = resolveProjectiveQuadGuards({ bleed: 0 }); + +function voxelProjectiveBasis(item: DirectMatrixItem): { + xAxis: Vec3; + yAxis: Vec3; + normal: Vec3; + tx: number; + ty: number; + tz: number; +} { + if (item.axis === "x") { + return { + xAxis: [1, 0, 0], + yAxis: [0, 0, 1], + normal: [0, -1, 0], + tx: 0, + ty: -item.z, + tz: 0, + }; + } + if (item.axis === "y") { + return { + xAxis: [0, 0, 1], + yAxis: [0, 1, 0], + normal: [-1, 0, 0], + tx: -item.z, + ty: 0, + tz: 0, + }; + } + return { + xAxis: [1, 0, 0], + yAxis: [0, 1, 0], + normal: [0, 0, 1], + tx: 0, + ty: 0, + tz: item.z, + }; +} + +function voxelScreenPts(item: DirectMatrixItem): number[] { + const left = item.left; + const top = item.top; + const right = item.left + item.width; + const bottom = item.top + item.height; + return [ + left, top, + right, top, + right, bottom, + left, bottom, + ]; +} + +function voxelSeamEdgeAmounts(item: DirectMatrixItem): Map { + return new Map([ + [0, item.bleed.top], + [1, item.bleed.right], + [2, item.bleed.bottom], + [3, item.bleed.left], + ]); +} + +function rescaleProjectiveMatrix(matrix: string, primitiveSize: number): string | null { + const values = matrix.split(",").map(Number); + if (values.length !== 16 || values.some((value) => !Number.isFinite(value))) return null; + const scale = SOLID_QUAD_CANONICAL_SIZE / primitiveSize; + for (let i = 0; i < 8; i += 1) values[i] *= scale; + return `matrix3d(${values.map((value) => Number(value.toFixed(6))).join(",")})`; +} + +function affineVoxelMatrix(item: DirectMatrixItem, primitiveSize: number): string { + const left = item.left - item.bleed.left; + const top = item.top - item.bleed.top; + const width = item.width + item.bleed.left + item.bleed.right; + const height = item.height + item.bleed.top + item.bleed.bottom; + const zOffset = item.z; + const scaleX = width / primitiveSize; + const scaleY = height / primitiveSize; + const values = item.axis === "x" + ? [ + scaleX, 0, 0, 0, + 0, 0, scaleY, 0, + 0, -1, 0, 0, + left, -zOffset, top, 1, + ] + : item.axis === "y" + ? [ + 0, 0, scaleX, 0, + 0, scaleY, 0, 0, + -1, 0, 0, 0, + -zOffset, top, left, 1, + ] + : [ + scaleX, 0, 0, 0, + 0, scaleY, 0, 0, + 0, 0, 1, 0, + left, top, zOffset, 1, + ]; + return `matrix3d(${values.map((value) => Number(value.toFixed(6))).join(",")})`; +} + +export function directMatrix(item: DirectMatrixItem, primitiveSize: number): string { + const { xAxis, yAxis, normal, tx, ty, tz } = voxelProjectiveBasis(item); + const projective = computeProjectiveQuadMatrix( + voxelScreenPts(item), + xAxis, + yAxis, + normal, + tx, + ty, + tz, + VOXEL_PROJECTIVE_QUAD_GUARDS, + voxelSeamEdgeAmounts(item), + ); + return projective + ? rescaleProjectiveMatrix(projective, primitiveSize) ?? affineVoxelMatrix(item, primitiveSize) + : affineVoxelMatrix(item, primitiveSize); +} diff --git a/packages/polycss/src/render/voxel/ordering.ts b/packages/polycss/src/render/voxel/ordering.ts new file mode 100644 index 000000000..026017076 --- /dev/null +++ b/packages/polycss/src/render/voxel/ordering.ts @@ -0,0 +1,117 @@ +import type { + CameraCullRotation, + PolyVoxelFace, + Vec3, +} from "@layoutit/polycss-core"; +import { + normalFacesCamera, + rotateVec3, + rotateVec3InWrapperCssFrame, +} from "@layoutit/polycss-core"; +import type { DirectMatrixItem } from "./types"; +import { FACE_NORMALS, FACE_ORDER } from "./types"; + +export function visibleFaceSignature(rotation: CameraCullRotation): string { + const visible: string[] = []; + for (const face of FACE_ORDER) { + if (normalFacesCamera(FACE_NORMALS[face], rotation)) visible.push(face); + } + return visible.join("|"); +} + +function itemCenter(item: DirectMatrixItem): Vec3 { + if (item.axis === "x") { + return [item.left + item.width / 2, -item.z, item.top + item.height / 2]; + } + if (item.axis === "y") { + return [-item.z, item.top + item.height / 2, item.left + item.width / 2]; + } + return [item.left + item.width / 2, item.top + item.height / 2, item.z]; +} + +function projectedPoint(item: DirectMatrixItem, rotation: CameraCullRotation): { x: number; y: number } { + let center = itemCenter(item); + const meshRotation = rotation.meshRotation; + if (meshRotation) { + // Match the wrapper's actual CSS rotation (world↔CSS conjugation) so + // item-ordering uses the same projected positions the browser composites. + center = rotateVec3InWrapperCssFrame(center, meshRotation); + } + const [x, y] = rotateVec3(center, rotation.rotX, 0, rotation.rotY); + return { x, y }; +} + +export function orderDirectMatrixItems( + items: readonly DirectMatrixItem[], + visibleFaces: Set, + rotation: CameraCullRotation, +): DirectMatrixItem[] { + const entries = items + .filter((item) => visibleFaces.has(item.face)) + .map((item) => ({ item, ...projectedPoint(item, rotation) })); + if (entries.length === 0) return []; + + let minX = Infinity; + let maxX = -Infinity; + let minY = Infinity; + let maxY = -Infinity; + for (const entry of entries) { + minX = Math.min(minX, entry.x); + maxX = Math.max(maxX, entry.x); + minY = Math.min(minY, entry.y); + maxY = Math.max(maxY, entry.y); + } + + const tileCount = 4; + const spanX = Math.max(1e-6, maxX - minX); + const spanY = Math.max(1e-6, maxY - minY); + const tiles = new Map(); + for (const entry of entries) { + const tx = Math.min( + tileCount - 1, + Math.max(0, Math.floor(((entry.x - minX) / spanX) * tileCount)), + ); + const ty = Math.min( + tileCount - 1, + Math.max(0, Math.floor(((entry.y - minY) / spanY) * tileCount)), + ); + const key = `${tx}:${ty}`; + let tile = tiles.get(key); + if (!tile) { + tile = { tx, ty, sourceIndex: entry.item.sourceIndex, items: [] }; + tiles.set(key, tile); + } + tile.items.push(entry.item); + tile.sourceIndex = Math.min(tile.sourceIndex, entry.item.sourceIndex); + } + + return Array.from(tiles.values()) + .sort((a, b) => (a.ty - b.ty) || (a.tx - b.tx) || a.sourceIndex - b.sourceIndex) + .flatMap((tile) => tile.items); +} + +export function itemsByFaceOrder( + orderedItems: readonly DirectMatrixItem[], +): { orderedFaces: PolyVoxelFace[]; itemsByFace: Map } { + const seen = new Set(); + const orderedFaces: PolyVoxelFace[] = []; + const itemsByFace = new Map(); + for (const item of orderedItems) { + if (!seen.has(item.face)) { + seen.add(item.face); + orderedFaces.push(item.face); + } + let faceItems = itemsByFace.get(item.face); + if (!faceItems) { + faceItems = []; + itemsByFace.set(item.face, faceItems); + } + faceItems.push(item); + } + return { orderedFaces, itemsByFace }; +} diff --git a/packages/polycss/src/render/voxel/shading.ts b/packages/polycss/src/render/voxel/shading.ts new file mode 100644 index 000000000..d2e2da3bf --- /dev/null +++ b/packages/polycss/src/render/voxel/shading.ts @@ -0,0 +1,89 @@ +import type { + PolyAmbientLight, + PolyDirectionalLight, + Vec3, +} from "@layoutit/polycss-core"; +import { + parsePureColor, + rgbToHex, + shadePolygon, +} from "@layoutit/polycss-core"; + +interface RGB { + r: number; + g: number; + b: number; + alpha: number; +} + +const DEFAULT_LIGHT_DIR: Vec3 = [0.4, -0.7, 0.59]; +const DEFAULT_LIGHT_COLOR = "#ffffff"; +const DEFAULT_LIGHT_INTENSITY = 1; +const DEFAULT_AMBIENT_COLOR = "#ffffff"; +const DEFAULT_AMBIENT_INTENSITY = 0.4; + +function parseColor(input: string): RGB { + const parsed = parsePureColor(input); + if (!parsed) return { r: 255, g: 255, b: 255, alpha: 1 }; + return { + r: parsed.rgb[0], + g: parsed.rgb[1], + b: parsed.rgb[2], + alpha: parsed.alpha, + }; +} + +function clampChannel(value: number): number { + return Math.round(Math.max(0, Math.min(255, value))); +} + +export function canonicalBrushColor(input: string | undefined): string { + if (!input) return "#cccccc"; + const parsed = parsePureColor(input); + if (!parsed) return input; + const rgb: RGB = { + r: parsed.rgb[0], + g: parsed.rgb[1], + b: parsed.rgb[2], + alpha: parsed.alpha, + }; + if (rgb.alpha < 1) { + const alpha = Math.round(Math.max(0, rgb.alpha) * 1000) / 1000; + return `rgba(${clampChannel(rgb.r)}, ${clampChannel(rgb.g)}, ${clampChannel(rgb.b)}, ${alpha})`; + } + return rgbToHex(rgb); +} + +export function shadeBrushColor( + normal: Vec3, + baseColor: string, + directionalLight: PolyDirectionalLight | undefined, + ambientLight: PolyAmbientLight | undefined, +): string { + const lightDir = directionalLight?.direction ?? DEFAULT_LIGHT_DIR; + const lightLen = Math.hypot(lightDir[0], lightDir[1], lightDir[2]) || 1; + const lx = lightDir[0] / lightLen; + const ly = lightDir[1] / lightLen; + const lz = lightDir[2] / lightLen; + const directScale = Math.max(0, directionalLight?.intensity ?? DEFAULT_LIGHT_INTENSITY) * + Math.max(0, normal[0] * lx + normal[1] * ly + normal[2] * lz); + const ambientIntensity = Math.max(0, ambientLight?.intensity ?? DEFAULT_AMBIENT_INTENSITY); + const lightColor = directionalLight?.color ?? DEFAULT_LIGHT_COLOR; + const ambientColor = ambientLight?.color ?? DEFAULT_AMBIENT_COLOR; + // Delegate to the same physically-based Lambert (sRGB→linear, /π, sRGB + // back) that polygon meshes use, so voxel brushes match Three.js parity. + // Without this the voxel path used pre-parity multiply-in-sRGB, which + // came out ~π× brighter than the polygon-path shading for the same + // light + base color (visible as blown-out voxel scenes vs polygon + // scenes side by side). + const shaded = shadePolygon(baseColor, directScale, lightColor, ambientColor, ambientIntensity); + // Preserve alpha when the source had it (rare but supported for + // translucent voxels). shadePolygon returns a hex string; if the input + // had non-1 alpha, re-attach it via rgba(...). + const base = parseColor(baseColor); + if (base.alpha >= 1) return shaded; + const r = parseInt(shaded.slice(1, 3), 16); + const g = parseInt(shaded.slice(3, 5), 16); + const b = parseInt(shaded.slice(5, 7), 16); + return `rgba(${r}, ${g}, ${b}, ${base.alpha})`; +} diff --git a/packages/polycss/src/render/voxel/types.ts b/packages/polycss/src/render/voxel/types.ts new file mode 100644 index 000000000..a0e53e808 --- /dev/null +++ b/packages/polycss/src/render/voxel/types.ts @@ -0,0 +1,61 @@ +import type { PolyVoxelFace, Vec3 } from "@layoutit/polycss-core"; + +export type Axis = "x" | "y" | "z"; +export type VoxelSeamSide = "left" | "right" | "top" | "bottom"; +export type WorldAxisIndex = 0 | 1 | 2; + +export interface VoxelSeamBleed { + left: number; + right: number; + top: number; + bottom: number; +} + +export interface BrushState { + color?: string; + transform?: string; +} + +export type BrushElement = HTMLElement & { + __polycssVoxelBrushState?: BrushState; +}; + +export type FaceHostElement = HTMLElement & { + __polycssVoxelFaceHost?: true; +}; + +export interface DirectMatrixItem { + axis: Axis; + face: PolyVoxelFace; + left: number; + top: number; + width: number; + height: number; + z: number; + baseColor: string; + sourceIndex: number; + bleed: VoxelSeamBleed; +} + +export const DESKTOP_PRIMITIVE_SIZE = 1; +export const MOBILE_PRIMITIVE_SIZE = 8; + +export const FACE_NORMALS: Record = { + t: [0, 0, 1], + b: [0, 0, -1], + fl: [0, 1, 0], + br: [0, -1, 0], + fr: [1, 0, 0], + bl: [-1, 0, 0], +}; + +export const FACE_ORDER: PolyVoxelFace[] = ["t", "b", "bl", "br", "fr", "fl"]; + +export const FACE_BY_NORMAL = new Map([ + ["0,0,1", "t"], + ["0,0,-1", "b"], + ["0,1,0", "fl"], + ["0,-1,0", "br"], + ["1,0,0", "fr"], + ["-1,0,0", "bl"], +]); diff --git a/packages/polycss/src/render/voxelRenderer.ts b/packages/polycss/src/render/voxelRenderer.ts index 13e2e1035..4a23664f0 100644 --- a/packages/polycss/src/render/voxelRenderer.ts +++ b/packages/polycss/src/render/voxelRenderer.ts @@ -4,45 +4,26 @@ import type { PolyDirectionalLight, PolyVoxelFace, Polygon, - Vec3, } from "@layoutit/polycss-core"; +import { buildDirectMatrixItems } from "./voxel/items"; +import { directMatrix } from "./voxel/matrix"; import { - BASE_TILE, - computeProjectiveQuadMatrix, - normalFacesCamera, - parsePureColor, - PROJECTIVE_QUAD_BLEED, - resolveProjectiveQuadGuards, - rgbToHex, - rotateVec3, - rotateVec3InWrapperCssFrame, - shadePolygon, - SOLID_QUAD_CANONICAL_SIZE, -} from "@layoutit/polycss-core"; - -type Axis = "x" | "y" | "z"; -type VoxelSeamSide = "left" | "right" | "top" | "bottom"; -type WorldAxisIndex = 0 | 1 | 2; - -interface VoxelSeamBleed { - left: number; - right: number; - top: number; - bottom: number; -} - -interface BrushState { - color?: string; - transform?: string; -} - -type BrushElement = HTMLElement & { - __polycssVoxelBrushState?: BrushState; -}; - -type FaceHostElement = HTMLElement & { - __polycssVoxelFaceHost?: true; -}; + itemsByFaceOrder, + orderDirectMatrixItems, + visibleFaceSignature, +} from "./voxel/ordering"; +import { shadeBrushColor } from "./voxel/shading"; +import type { + BrushElement, + DirectMatrixItem, + FaceHostElement, +} from "./voxel/types"; +import { + DESKTOP_PRIMITIVE_SIZE, + FACE_NORMALS, + FACE_ORDER, + MOBILE_PRIMITIVE_SIZE, +} from "./voxel/types"; export interface PolyVoxelRenderer { readonly brushCount: number; @@ -59,69 +40,6 @@ export interface PolyVoxelRendererOptions { ambientLight?: PolyAmbientLight; } -interface RGB { r: number; g: number; b: number; alpha: number; } - -interface DirectMatrixItem { - axis: Axis; - face: PolyVoxelFace; - left: number; - top: number; - width: number; - height: number; - z: number; - baseColor: string; - sourceIndex: number; - bleed: VoxelSeamBleed; -} - -interface VoxelSeamSegment { - item: DirectMatrixItem; - side: VoxelSeamSide; - variableAxis: WorldAxisIndex; - fixed: [number, number, number]; - start: number; - end: number; -} - -const DEFAULT_LIGHT_DIR: Vec3 = [0.4, -0.7, 0.59]; -const DEFAULT_LIGHT_COLOR = "#ffffff"; -const DEFAULT_LIGHT_INTENSITY = 1; -const DEFAULT_AMBIENT_COLOR = "#ffffff"; -const DEFAULT_AMBIENT_INTENSITY = 0.4; -const DESKTOP_PRIMITIVE_SIZE = 1; -const MOBILE_PRIMITIVE_SIZE = 8; -const VOXEL_SEAM_BLEED = PROJECTIVE_QUAD_BLEED; -const VOXEL_SEAM_EPS = 1e-6; -const VOXEL_PROJECTIVE_QUAD_GUARDS = resolveProjectiveQuadGuards({ bleed: 0 }); - -const FACE_NORMALS: Record = { - t: [0, 0, 1], - b: [0, 0, -1], - fl: [0, 1, 0], - br: [0, -1, 0], - fr: [1, 0, 0], - bl: [-1, 0, 0], -}; - -const FACE_ORDER: PolyVoxelFace[] = ["t", "b", "bl", "br", "fr", "fl"]; - -const FACE_BY_NORMAL = new Map([ - ["0,0,1", "t"], - ["0,0,-1", "b"], - ["0,1,0", "fl"], - ["0,-1,0", "br"], - ["1,0,0", "fr"], - ["-1,0,0", "bl"], -]); - -function visibleFaceSignature(rotation: CameraCullRotation): string { - const visible: string[] = []; - for (const face of FACE_ORDER) { - if (normalFacesCamera(FACE_NORMALS[face], rotation)) visible.push(face); - } - return visible.join("|"); -} - function applyBrush( el: BrushElement, color: string, @@ -138,408 +56,6 @@ function applyBrush( } } -function cssNormalForPolygon(polygon: Polygon): Vec3 | null { - const vertices = polygon.vertices; - if (vertices.length < 3) return null; - const v0 = vertices[0]; - let nx = 0; - let ny = 0; - let nz = 0; - for (let i = 1; i + 1 < vertices.length; i += 1) { - const v1 = vertices[i]; - const v2 = vertices[i + 1]; - const e1x = v1[1] - v0[1]; - const e1y = v1[0] - v0[0]; - const e1z = v1[2] - v0[2]; - const e2x = v2[1] - v0[1]; - const e2y = v2[0] - v0[0]; - const e2z = v2[2] - v0[2]; - nx -= e1y * e2z - e1z * e2y; - ny -= e1z * e2x - e1x * e2z; - nz -= e1x * e2y - e1y * e2x; - } - const len = Math.hypot(nx, ny, nz); - if (len <= 1e-9) return null; - return [ - Math.round(nx / len), - Math.round(ny / len), - Math.round(nz / len), - ]; -} - -function polygonBrush(polygon: Polygon): Omit | null { - if (polygon.texture || polygon.material || polygon.uvs || polygon.textureTriangles) return null; - if (polygon.vertices.length !== 4) return null; - const normal = cssNormalForPolygon(polygon); - const face = normal ? FACE_BY_NORMAL.get(normal.join(",")) : undefined; - if (!face) return null; - - let minX = Infinity; - let minY = Infinity; - let minZ = Infinity; - let maxX = -Infinity; - let maxY = -Infinity; - let maxZ = -Infinity; - for (const v of polygon.vertices) { - minX = Math.min(minX, v[0]); - minY = Math.min(minY, v[1]); - minZ = Math.min(minZ, v[2]); - maxX = Math.max(maxX, v[0]); - maxY = Math.max(maxY, v[1]); - maxZ = Math.max(maxZ, v[2]); - } - - const eps = 1e-6; - const baseColor = canonicalBrushColor(polygon.color); - if (Math.abs(maxZ - minZ) <= eps) { - return { - axis: "z", - face, - left: minY * BASE_TILE, - top: minX * BASE_TILE, - width: Math.max(0, (maxY - minY) * BASE_TILE), - height: Math.max(0, (maxX - minX) * BASE_TILE), - z: minZ * BASE_TILE, - baseColor, - bleed: zeroVoxelSeamBleed(), - }; - } - if (Math.abs(maxX - minX) <= eps) { - return { - axis: "x", - face, - left: minY * BASE_TILE, - top: minZ * BASE_TILE, - width: Math.max(0, (maxY - minY) * BASE_TILE), - height: Math.max(0, (maxZ - minZ) * BASE_TILE), - z: -minX * BASE_TILE, - baseColor, - bleed: zeroVoxelSeamBleed(), - }; - } - if (Math.abs(maxY - minY) <= eps) { - return { - axis: "y", - face, - left: minZ * BASE_TILE, - top: minX * BASE_TILE, - width: Math.max(0, (maxZ - minZ) * BASE_TILE), - height: Math.max(0, (maxX - minX) * BASE_TILE), - z: -minY * BASE_TILE, - baseColor, - bleed: zeroVoxelSeamBleed(), - }; - } - return null; -} - -function zeroVoxelSeamBleed(): VoxelSeamBleed { - return { left: 0, right: 0, top: 0, bottom: 0 }; -} - -function worldLineKey(segment: VoxelSeamSegment): string { - const coordKey = (value: number): string => String(Number(value.toFixed(6))); - let key = `${segment.item.baseColor}|${segment.variableAxis}`; - for (let axis = 0; axis < 3; axis += 1) { - if (axis === segment.variableAxis) continue; - key += `|${axis}:${coordKey(segment.fixed[axis])}`; - } - return key; -} - -function cssPointForVertex(v: Vec3): Vec3 { - return [v[1] * BASE_TILE, v[0] * BASE_TILE, v[2] * BASE_TILE]; -} - -function localPointForItem(item: DirectMatrixItem, p: Vec3): [number, number] { - if (item.axis === "x") return [p[0], p[2]]; - if (item.axis === "y") return [p[2], p[1]]; - return [p[0], p[1]]; -} - -function sideForLocalEdge( - item: DirectMatrixItem, - a: [number, number], - b: [number, number], -): VoxelSeamSide | null { - const left = item.left; - const right = item.left + item.width; - const top = item.top; - const bottom = item.top + item.height; - if (Math.abs(a[0] - b[0]) <= VOXEL_SEAM_EPS) { - if (Math.abs(a[0] - left) <= VOXEL_SEAM_EPS) return "left"; - if (Math.abs(a[0] - right) <= VOXEL_SEAM_EPS) return "right"; - } - if (Math.abs(a[1] - b[1]) <= VOXEL_SEAM_EPS) { - if (Math.abs(a[1] - top) <= VOXEL_SEAM_EPS) return "top"; - if (Math.abs(a[1] - bottom) <= VOXEL_SEAM_EPS) return "bottom"; - } - return null; -} - -function variableAxisForSegment(a: Vec3, b: Vec3): WorldAxisIndex | null { - let axis: WorldAxisIndex | null = null; - for (let i = 0; i < 3; i += 1) { - if (Math.abs(a[i] - b[i]) <= VOXEL_SEAM_EPS) continue; - if (axis !== null) return null; - axis = i as WorldAxisIndex; - } - return axis; -} - -function voxelSeamSegmentForEdge( - item: DirectMatrixItem, - polygon: Polygon, - edgeIndex: number, -): VoxelSeamSegment | null { - const vertices = polygon.vertices; - const a = cssPointForVertex(vertices[edgeIndex]); - const b = cssPointForVertex(vertices[(edgeIndex + 1) % vertices.length]); - const side = sideForLocalEdge(item, localPointForItem(item, a), localPointForItem(item, b)); - if (!side) return null; - const variableAxis = variableAxisForSegment(a, b); - if (variableAxis === null) return null; - const start = Math.min(a[variableAxis], b[variableAxis]); - const end = Math.max(a[variableAxis], b[variableAxis]); - return end - start > VOXEL_SEAM_EPS - ? { item, side, variableAxis, fixed: a, start, end } - : null; -} - -function markVoxelSeam(segment: VoxelSeamSegment): void { - segment.item.bleed[segment.side] = Math.max(segment.item.bleed[segment.side], VOXEL_SEAM_BLEED); -} - -function applyVoxelSeamBleed(polygons: readonly Polygon[], items: DirectMatrixItem[]): void { - const groups = new Map(); - for (const item of items) { - const polygon = polygons[item.sourceIndex]; - if (!polygon) continue; - for (let edgeIndex = 0; edgeIndex < polygon.vertices.length; edgeIndex += 1) { - const segment = voxelSeamSegmentForEdge(item, polygon, edgeIndex); - if (!segment) continue; - const key = worldLineKey(segment); - const group = groups.get(key); - if (group) group.push(segment); - else groups.set(key, [segment]); - } - } - - for (const segments of groups.values()) { - if (segments.length < 2) continue; - segments.sort((a, b) => a.start - b.start || a.end - b.end); - let active: VoxelSeamSegment[] = []; - for (const segment of segments) { - active = active.filter((candidate) => candidate.end > segment.start + VOXEL_SEAM_EPS); - for (const candidate of active) { - if (candidate.item.sourceIndex === segment.item.sourceIndex) continue; - markVoxelSeam(candidate); - markVoxelSeam(segment); - } - active.push(segment); - } - } -} - -function parseColor(input: string): RGB { - const parsed = parsePureColor(input); - if (!parsed) return { r: 255, g: 255, b: 255, alpha: 1 }; - return { - r: parsed.rgb[0], - g: parsed.rgb[1], - b: parsed.rgb[2], - alpha: parsed.alpha, - }; -} - -function canonicalBrushColor(input: string | undefined): string { - if (!input) return "#cccccc"; - const parsed = parsePureColor(input); - if (!parsed) return input; - const rgb: RGB = { - r: parsed.rgb[0], - g: parsed.rgb[1], - b: parsed.rgb[2], - alpha: parsed.alpha, - }; - if (rgb.alpha < 1) { - const alpha = Math.round(Math.max(0, rgb.alpha) * 1000) / 1000; - return `rgba(${clampChannel(rgb.r)}, ${clampChannel(rgb.g)}, ${clampChannel(rgb.b)}, ${alpha})`; - } - return rgbToHex(rgb); -} - -function clampChannel(value: number): number { - return Math.round(Math.max(0, Math.min(255, value))); -} - -function shadeBrushColor( - normal: Vec3, - baseColor: string, - directionalLight: PolyDirectionalLight | undefined, - ambientLight: PolyAmbientLight | undefined, -): string { - const lightDir = directionalLight?.direction ?? DEFAULT_LIGHT_DIR; - const lightLen = Math.hypot(lightDir[0], lightDir[1], lightDir[2]) || 1; - const lx = lightDir[0] / lightLen; - const ly = lightDir[1] / lightLen; - const lz = lightDir[2] / lightLen; - const directScale = Math.max(0, directionalLight?.intensity ?? DEFAULT_LIGHT_INTENSITY) * - Math.max(0, normal[0] * lx + normal[1] * ly + normal[2] * lz); - const ambientIntensity = Math.max(0, ambientLight?.intensity ?? DEFAULT_AMBIENT_INTENSITY); - const lightColor = directionalLight?.color ?? DEFAULT_LIGHT_COLOR; - const ambientColor = ambientLight?.color ?? DEFAULT_AMBIENT_COLOR; - // Delegate to the same physically-based Lambert (sRGB→linear, /π, sRGB - // back) that polygon meshes use, so voxel brushes match Three.js parity. - // Without this the voxel path used pre-parity multiply-in-sRGB, which - // came out ~π× brighter than the polygon-path shading for the same - // light + base color (visible as blown-out voxel scenes vs polygon - // scenes side by side). - const shaded = shadePolygon(baseColor, directScale, lightColor, ambientColor, ambientIntensity); - // Preserve alpha when the source had it (rare but supported for - // translucent voxels). shadePolygon returns a hex string; if the input - // had non-1 alpha, re-attach it via rgba(...). - const base = parseColor(baseColor); - if (base.alpha >= 1) return shaded; - const r = parseInt(shaded.slice(1, 3), 16); - const g = parseInt(shaded.slice(3, 5), 16); - const b = parseInt(shaded.slice(5, 7), 16); - return `rgba(${r}, ${g}, ${b}, ${base.alpha})`; -} - -function buildDirectMatrixItems(polygons: readonly Polygon[] | undefined): DirectMatrixItem[] { - if (!polygons?.length) return []; - const items: DirectMatrixItem[] = []; - for (let sourceIndex = 0; sourceIndex < polygons.length; sourceIndex += 1) { - const polygon = polygons[sourceIndex]; - const brush = polygonBrush(polygon); - if (!brush || brush.width <= 0 || brush.height <= 0) return []; - items.push({ - ...brush, - sourceIndex, - }); - } - applyVoxelSeamBleed(polygons, items); - return items; -} - -function voxelProjectiveBasis(item: DirectMatrixItem): { - xAxis: Vec3; - yAxis: Vec3; - normal: Vec3; - tx: number; - ty: number; - tz: number; -} { - if (item.axis === "x") { - return { - xAxis: [1, 0, 0], - yAxis: [0, 0, 1], - normal: [0, -1, 0], - tx: 0, - ty: -item.z, - tz: 0, - }; - } - if (item.axis === "y") { - return { - xAxis: [0, 0, 1], - yAxis: [0, 1, 0], - normal: [-1, 0, 0], - tx: -item.z, - ty: 0, - tz: 0, - }; - } - return { - xAxis: [1, 0, 0], - yAxis: [0, 1, 0], - normal: [0, 0, 1], - tx: 0, - ty: 0, - tz: item.z, - }; -} - -function voxelScreenPts(item: DirectMatrixItem): number[] { - const left = item.left; - const top = item.top; - const right = item.left + item.width; - const bottom = item.top + item.height; - return [ - left, top, - right, top, - right, bottom, - left, bottom, - ]; -} - -function voxelSeamEdgeAmounts(item: DirectMatrixItem): Map { - return new Map([ - [0, item.bleed.top], - [1, item.bleed.right], - [2, item.bleed.bottom], - [3, item.bleed.left], - ]); -} - -function rescaleProjectiveMatrix(matrix: string, primitiveSize: number): string | null { - const values = matrix.split(",").map(Number); - if (values.length !== 16 || values.some((value) => !Number.isFinite(value))) return null; - const scale = SOLID_QUAD_CANONICAL_SIZE / primitiveSize; - for (let i = 0; i < 8; i += 1) values[i] *= scale; - return `matrix3d(${values.map((value) => Number(value.toFixed(6))).join(",")})`; -} - -function affineVoxelMatrix(item: DirectMatrixItem, primitiveSize: number): string { - const left = item.left - item.bleed.left; - const top = item.top - item.bleed.top; - const width = item.width + item.bleed.left + item.bleed.right; - const height = item.height + item.bleed.top + item.bleed.bottom; - const zOffset = item.z; - const scaleX = width / primitiveSize; - const scaleY = height / primitiveSize; - const values = item.axis === "x" - ? [ - scaleX, 0, 0, 0, - 0, 0, scaleY, 0, - 0, -1, 0, 0, - left, -zOffset, top, 1, - ] - : item.axis === "y" - ? [ - 0, 0, scaleX, 0, - 0, scaleY, 0, 0, - -1, 0, 0, 0, - -zOffset, top, left, 1, - ] - : [ - scaleX, 0, 0, 0, - 0, scaleY, 0, 0, - 0, 0, 1, 0, - left, top, zOffset, 1, - ]; - return `matrix3d(${values.map((value) => Number(value.toFixed(6))).join(",")})`; -} - -function directMatrix(item: DirectMatrixItem, primitiveSize: number): string { - const { xAxis, yAxis, normal, tx, ty, tz } = voxelProjectiveBasis(item); - const projective = computeProjectiveQuadMatrix( - voxelScreenPts(item), - xAxis, - yAxis, - normal, - tx, - ty, - tz, - VOXEL_PROJECTIVE_QUAD_GUARDS, - voxelSeamEdgeAmounts(item), - ); - return projective - ? rescaleProjectiveMatrix(projective, primitiveSize) ?? affineVoxelMatrix(item, primitiveSize) - : affineVoxelMatrix(item, primitiveSize); -} - function isMobileDocument(doc: Document): boolean { const media = doc.defaultView?.matchMedia; if (!media) return false; @@ -550,82 +66,6 @@ function primitiveSizeForDocument(doc: Document): number { return isMobileDocument(doc) ? MOBILE_PRIMITIVE_SIZE : DESKTOP_PRIMITIVE_SIZE; } -function itemCenter(item: DirectMatrixItem): Vec3 { - if (item.axis === "x") { - return [item.left + item.width / 2, -item.z, item.top + item.height / 2]; - } - if (item.axis === "y") { - return [-item.z, item.top + item.height / 2, item.left + item.width / 2]; - } - return [item.left + item.width / 2, item.top + item.height / 2, item.z]; -} - -function projectedPoint(item: DirectMatrixItem, rotation: CameraCullRotation): { x: number; y: number } { - let center = itemCenter(item); - const meshRotation = rotation.meshRotation; - if (meshRotation) { - // Match the wrapper's actual CSS rotation (world↔CSS conjugation) so - // item-ordering uses the same projected positions the browser composites. - center = rotateVec3InWrapperCssFrame(center, meshRotation); - } - const [x, y] = rotateVec3(center, rotation.rotX, 0, rotation.rotY); - return { x, y }; -} - -function orderDirectMatrixItems( - items: readonly DirectMatrixItem[], - visibleFaces: Set, - rotation: CameraCullRotation, -): DirectMatrixItem[] { - const entries = items - .filter((item) => visibleFaces.has(item.face)) - .map((item) => ({ item, ...projectedPoint(item, rotation) })); - if (entries.length === 0) return []; - - let minX = Infinity; - let maxX = -Infinity; - let minY = Infinity; - let maxY = -Infinity; - for (const entry of entries) { - minX = Math.min(minX, entry.x); - maxX = Math.max(maxX, entry.x); - minY = Math.min(minY, entry.y); - maxY = Math.max(maxY, entry.y); - } - - const tileCount = 4; - const spanX = Math.max(1e-6, maxX - minX); - const spanY = Math.max(1e-6, maxY - minY); - const tiles = new Map(); - for (const entry of entries) { - const tx = Math.min( - tileCount - 1, - Math.max(0, Math.floor(((entry.x - minX) / spanX) * tileCount)), - ); - const ty = Math.min( - tileCount - 1, - Math.max(0, Math.floor(((entry.y - minY) / spanY) * tileCount)), - ); - const key = `${tx}:${ty}`; - let tile = tiles.get(key); - if (!tile) { - tile = { tx, ty, sourceIndex: entry.item.sourceIndex, items: [] }; - tiles.set(key, tile); - } - tile.items.push(entry.item); - tile.sourceIndex = Math.min(tile.sourceIndex, entry.item.sourceIndex); - } - - return Array.from(tiles.values()) - .sort((a, b) => (a.ty - b.ty) || (a.tx - b.tx) || a.sourceIndex - b.sourceIndex) - .flatMap((tile) => tile.items); -} - export function createPolyVoxelRenderer( options: PolyVoxelRendererOptions, ): PolyVoxelRenderer | null { @@ -730,27 +170,6 @@ export function createPolyVoxelRenderer( return count; }; - const itemsByFaceOrder = ( - orderedItems: readonly DirectMatrixItem[], - ): { orderedFaces: PolyVoxelFace[]; itemsByFace: Map } => { - const seen = new Set(); - const orderedFaces: PolyVoxelFace[] = []; - const itemsByFace = new Map(); - for (const item of orderedItems) { - if (!seen.has(item.face)) { - seen.add(item.face); - orderedFaces.push(item.face); - } - let faceItems = itemsByFace.get(item.face); - if (!faceItems) { - faceItems = []; - itemsByFace.set(item.face, faceItems); - } - faceItems.push(item); - } - return { orderedFaces, itemsByFace }; - }; - const mountFaceHosts = (orderedFaces: readonly PolyVoxelFace[], reorderMountedFaces: boolean): void => { const nextFaces = new Set(orderedFaces); for (const face of mountedFaces) { diff --git a/packages/polycss/src/snapshot/exportPolySceneSnapshot.ts b/packages/polycss/src/snapshot/exportPolySceneSnapshot.ts index 910dba49a..51fac3c5a 100644 --- a/packages/polycss/src/snapshot/exportPolySceneSnapshot.ts +++ b/packages/polycss/src/snapshot/exportPolySceneSnapshot.ts @@ -1,901 +1,14 @@ -export type PolySceneSnapshotErrorCode = - | "INVALID_TARGET" - | "SCENE_NOT_FOUND" - | "ASSET_INLINE_FAILED"; - -export class PolySceneSnapshotError extends Error { - readonly code: PolySceneSnapshotErrorCode; - readonly url?: string; - - constructor(code: PolySceneSnapshotErrorCode, message: string, url?: string) { - super(message); - this.name = "PolySceneSnapshotError"; - this.code = code; - this.url = url; - Object.setPrototypeOf(this, new.target.prototype); - } -} - -interface InlineContext { - baseUrl: string; - cache: Map>; -} - -interface SnapshotAssetRule { - attr: string; - value: string; - property: "background-image" | "--polycss-atlas-url"; - dataUrl: string; -} - -const SNAPSHOT_DOCUMENT_CSS = ` -html, -body { - width: 100%; - height: 100%; - margin: 0; -} - -body { - position: relative; - overflow: hidden; -} -`; - -type PolyLeafTag = "b" | "i" | "s" | "u"; - -interface SnapshotCssFeatures { - hasCamera: boolean; - hasScene: boolean; - hasMesh: boolean; - hasFpvHost: boolean; - hasBucket: boolean; - hasVoxelMesh: boolean; - hasTransformGizmo: boolean; - hasTransformRing: boolean; - hasDynamicLighting: boolean; - hasQ: boolean; - leafTags: PolyLeafTag[]; - solidLeafTags: PolyLeafTag[]; -} - -const POLY_LEAF_TAGS: PolyLeafTag[] = ["b", "i", "s", "u"]; -const SOLID_POLY_LEAF_TAGS: PolyLeafTag[] = ["b", "i", "u"]; -const LIGHTING_CUSTOM_PROPS = [ - "--plx", "--ply", "--plz", - "--plr", "--plg", "--plb", "--pli", - "--par", "--pag", "--pab", "--pai", - "--pnx", "--pny", "--pnz", - "--psr", "--psg", "--psb", - "--plam", - "--polycss-light-preview-active", - "--polycss-preview-r", - "--polycss-preview-g", - "--polycss-preview-b", -] as const; -const SHADOW_CUSTOM_PROPS = [ - "--clx", "--cly", "--clz", "--shadow-ground-cssz", -] as const; -const ATLAS_CUSTOM_PROPS = [ - "--polycss-atlas-size", - "--polycss-atlas-width", - "--polycss-atlas-height", - "--polycss-atlas-leaf-sizing", - "--polycss-atlas-url", - "--polycss-atlas-position", - "--polycss-atlas-image-size", -] as const; -const ATLAS_DIMENSION_CUSTOM_PROPS = [ - "--polycss-atlas-size", - "--polycss-atlas-width", - "--polycss-atlas-height", - "--polycss-atlas-leaf-sizing", -] as const; - -function isElement(value: unknown): value is Element { - return !!value - && typeof (value as Element).querySelector === "function" - && typeof (value as Element).cloneNode === "function"; -} - -function findPolySnapshotRoot(target: Element): Element | null { - const closestCamera = target.closest(".polycss-camera"); - if (closestCamera) return closestCamera; - - const closestScene = target.closest(".polycss-scene"); - if (closestScene) return closestScene.closest(".polycss-camera") ?? closestScene; - - return target.querySelector(".polycss-camera") - ?? target.querySelector(".polycss-scene"); -} - -function allElements(root: Element): Element[] { - return [root, ...Array.from(root.querySelectorAll("*"))]; -} - -function matchesOrContains(root: Element, selector: string): boolean { - return root.matches(selector) || !!root.querySelector(selector); -} - -function containsTag(root: Element, tagName: string): boolean { - return root.tagName.toLowerCase() === tagName || !!root.querySelector(tagName); -} - -function collectSnapshotCssFeatures(root: Element): SnapshotCssFeatures { - const leafTags = POLY_LEAF_TAGS.filter((tag) => containsTag(root, tag)); - const solidLeafTags = SOLID_POLY_LEAF_TAGS.filter((tag) => leafTags.includes(tag)); - return { - hasCamera: matchesOrContains(root, ".polycss-camera"), - hasScene: matchesOrContains(root, ".polycss-scene"), - hasMesh: matchesOrContains(root, ".polycss-mesh"), - hasFpvHost: matchesOrContains(root, ".polycss-fpv-host"), - hasBucket: matchesOrContains(root, ".polycss-bucket"), - hasVoxelMesh: matchesOrContains(root, ".polycss-voxel-mesh"), - hasTransformGizmo: matchesOrContains(root, ".polycss-transform-gizmo"), - hasTransformRing: matchesOrContains(root, ".polycss-transform-ring"), - hasDynamicLighting: matchesOrContains(root, '.polycss-scene[data-polycss-lighting="dynamic"]'), - hasQ: containsTag(root, "q"), - leafTags, - solidLeafTags, - }; -} - -function selectorList(tags: readonly string[], prefix = ".polycss-scene "): string { - return tags.map((tag) => `${prefix}${tag}`).join(",\n"); -} - -function directLeafSelectorList(tags: readonly string[]): string { - return tags - .map((tag) => `.polycss-scene[data-polycss-lighting="dynamic"] :not(.polycss-bucket) > ${tag}`) - .join(",\n"); -} - -function dynamicPropertyCss(includeShadowProjection: boolean): string { - const props = [ - '@property --plx { syntax: ""; inherits: true; initial-value: 0; }', - '@property --ply { syntax: ""; inherits: true; initial-value: 0; }', - '@property --plz { syntax: ""; inherits: true; initial-value: 1; }', - '@property --plr { syntax: ""; inherits: true; initial-value: 1; }', - '@property --plg { syntax: ""; inherits: true; initial-value: 1; }', - '@property --plb { syntax: ""; inherits: true; initial-value: 1; }', - '@property --pli { syntax: ""; inherits: true; initial-value: 1; }', - '@property --par { syntax: ""; inherits: true; initial-value: 1; }', - '@property --pag { syntax: ""; inherits: true; initial-value: 1; }', - '@property --pab { syntax: ""; inherits: true; initial-value: 1; }', - '@property --pai { syntax: ""; inherits: true; initial-value: 0.4; }', - '@property --pnx { syntax: ""; inherits: true; initial-value: 0; }', - '@property --pny { syntax: ""; inherits: true; initial-value: 0; }', - '@property --pnz { syntax: ""; inherits: true; initial-value: 1; }', - '@property --psr { syntax: ""; inherits: true; initial-value: 1; }', - '@property --psg { syntax: ""; inherits: true; initial-value: 1; }', - '@property --psb { syntax: ""; inherits: true; initial-value: 1; }', - '@property --plam { syntax: ""; inherits: true; initial-value: 0; }', - ]; - if (includeShadowProjection) { - props.push( - '@property --clx { syntax: ""; inherits: true; initial-value: 0.01; }', - '@property --cly { syntax: ""; inherits: true; initial-value: 0; }', - '@property --clz { syntax: ""; inherits: true; initial-value: 1; }', - '@property --shadow-ground-cssz { syntax: ""; inherits: true; initial-value: 0; }', - ); - } - return props.join("\n"); -} - -function buildDynamicLightingCss(features: SnapshotCssFeatures): string { - const parts = [dynamicPropertyCss(features.hasQ)]; - - if (features.hasBucket) { - parts.push(` -.polycss-scene[data-polycss-lighting="dynamic"] .polycss-bucket { - --plam: max(0, calc( - var(--pnx) * var(--plx) + - var(--pny) * var(--ply) + - var(--pnz) * var(--plz) - )); -} -`); - } - - if (features.leafTags.length > 0) { - parts.push(` -${directLeafSelectorList(features.leafTags)} { - --plam: max(0, calc( - var(--pnx) * var(--plx) + - var(--pny) * var(--ply) + - var(--pnz) * var(--plz) - )); -} -`); - } - - if (features.leafTags.includes("s")) { - parts.push(` -.polycss-scene[data-polycss-lighting="dynamic"] s { - contain: strict; - background-color: rgb( - calc(255 * (var(--par) * var(--pai) - + var(--plr) * var(--pli) * var(--plam))) - calc(255 * (var(--pag) * var(--pai) - + var(--plg) * var(--pli) * var(--plam))) - calc(255 * (var(--pab) * var(--pai) - + var(--plb) * var(--pli) * var(--plam))) - ); - background-blend-mode: multiply; - background-image: var(--polycss-atlas-url); - background-position: var(--polycss-atlas-position); - background-repeat: no-repeat; - background-size: var(--polycss-atlas-image-size); - mask-image: var(--polycss-atlas-url); - mask-mode: alpha; - mask-position: var(--polycss-atlas-position); - mask-repeat: no-repeat; - mask-size: var(--polycss-atlas-image-size); - -webkit-mask-image: var(--polycss-atlas-url); - -webkit-mask-position: var(--polycss-atlas-position); - -webkit-mask-repeat: no-repeat; - -webkit-mask-size: var(--polycss-atlas-image-size); -} -`); - } - - if (features.solidLeafTags.length > 0) { - parts.push(` -${selectorList(features.solidLeafTags)} { - color: rgb( - calc(255 * var(--psr) * (var(--par) * var(--pai) - + var(--plr) * var(--pli) * var(--plam))) - calc(255 * var(--psg) * (var(--pag) * var(--pai) - + var(--plg) * var(--pli) * var(--plam))) - calc(255 * var(--psb) * (var(--pab) * var(--pai) - + var(--plb) * var(--pli) * var(--plam))) - ); -} -`); - } - - if (features.hasQ) { - parts.push(` -.polycss-scene[data-polycss-lighting="dynamic"] { - --shadow-proj: matrix3d( - 1, 0, 0, 0, - 0, 1, 0, 0, - calc(-1 * var(--clx) / var(--clz)), - calc(-1 * var(--cly) / var(--clz)), - 0.01, - 0, - calc(var(--shadow-ground-cssz) * var(--clx) / var(--clz)), - calc(var(--shadow-ground-cssz) * var(--cly) / var(--clz)), - calc(var(--shadow-ground-cssz) * 0.99), - 1 - ); -} - -.polycss-scene[data-polycss-lighting="dynamic"] q { - opacity: clamp(0, calc((var(--pnx) * var(--clx) + var(--pny) * var(--cly) + var(--pnz) * var(--clz)) * 10), 1); -} -`); - } - - return parts.join("\n"); -} - -function buildPolySnapshotCss(features: SnapshotCssFeatures): string { - const parts = [SNAPSHOT_DOCUMENT_CSS]; - - if (features.hasScene) { - parts.push(` -.polycss-scene, -.polycss-scene *, -.polycss-scene *::before, -.polycss-scene *::after { - box-sizing: border-box; -} - -.polycss-scene { - position: absolute; - top: 50%; - left: 50%; - width: 0; - height: 0; - transform-style: preserve-3d; -} -`); - } - - if (features.hasCamera) { - parts.push(` -.polycss-camera { - position: relative; - display: block; - width: 100%; - height: 100%; -} -`); - } - - if (features.hasFpvHost) { - parts.push(` -.polycss-fpv-host { - perspective: var(--polycss-fpv-perspective, 2000px) !important; - transform-style: preserve-3d !important; -} -`); - } - - if (features.hasMesh) { - parts.push(` -.polycss-mesh { - position: absolute; - transform-style: preserve-3d; -} -`); - } - - if (features.hasBucket) { - parts.push(` -.polycss-bucket { - position: absolute; - transform-style: preserve-3d; -} -`); - } - - if (features.leafTags.length > 0) { - parts.push(` -${selectorList(features.leafTags)} { - position: absolute; - display: block; - transform-origin: 0 0; - transform-style: preserve-3d; - margin: 0; - padding: 0; - font: inherit; - font-weight: normal; - font-style: normal; - line-height: 0; - text-decoration: none; - backface-visibility: hidden; - background-repeat: no-repeat; -} -`); - } - - if (features.solidLeafTags.length > 0 && !features.hasDynamicLighting) { - parts.push(` -${selectorList(features.solidLeafTags)} { - color: currentColor; -} -`); - } - - if (features.leafTags.includes("b")) { - parts.push(` -.polycss-scene b { - background: currentColor; - width: 64px; - height: 64px; -} -`); - } - - if (features.hasVoxelMesh) { - parts.push(` -.polycss-mesh.polycss-voxel-mesh > .polycss-voxel-face { - position: absolute; - display: block; - top: 0; - left: 0; - width: 0; - height: 0; - transform-style: preserve-3d; - transform-origin: 0 0; - margin: 0; - padding: 0; - font: inherit; - line-height: 0; - pointer-events: none; -} - -.polycss-mesh.polycss-voxel-mesh > .polycss-voxel-face > b { - top: 0; - left: 0; - width: var(--polycss-voxel-primitive, 1px); - height: var(--polycss-voxel-primitive, 1px); - backface-visibility: visible; - pointer-events: none; -} -`); - } - - if (features.leafTags.includes("i")) { - parts.push(` -.polycss-scene i { - width: 16px; - height: 16px; - border-color: currentColor; -} -`); - } - - if (features.leafTags.includes("s")) { - parts.push(` -.polycss-scene s { - width: 64px; - height: 64px; -} -`); - } - - if (features.leafTags.includes("u")) { - parts.push(` -.polycss-scene u { - width: 0; - height: 0; - background: transparent; - box-sizing: content-box; - border: 0 solid transparent; - border-color: transparent transparent currentColor transparent; - border-width: 0 16px 32px 16px; -} - -@supports (corner-top-left-shape: bevel) and (corner-top-right-shape: bevel) { - .polycss-scene > u, - .polycss-mesh > u, - .polycss-bucket > u { - border-width: 0; - width: 32px; - height: 32px; - background-color: currentColor; - border-top-left-radius: 50% 100%; - border-top-right-radius: 50% 100%; - corner-top-left-shape: bevel; - corner-top-right-shape: bevel; - } - - .polycss-scene > u.polycss-corner-shape-solid, - .polycss-mesh > u.polycss-corner-shape-solid, - .polycss-bucket > u.polycss-corner-shape-solid { - width: 16px; - height: 16px; - box-sizing: border-box; - border: 0; - background: currentColor; - border-radius: 0; - corner-top-left-shape: initial; - corner-top-right-shape: initial; - corner-bottom-right-shape: initial; - corner-bottom-left-shape: initial; - } -} -`); - } - - if (features.hasQ) { - parts.push(` -.polycss-scene q { - position: absolute; - display: block; - transform-origin: 0 0; - transform-style: preserve-3d; - margin: 0; - padding: 0; - font: inherit; - font-weight: normal; - font-style: normal; - line-height: 0; - text-decoration: none; - backface-visibility: visible; - border-color: currentColor; - pointer-events: none; -} - -.polycss-scene q::before, -.polycss-scene q::after { - content: none; -} -`); - } - - if (features.hasTransformGizmo) { - const tags = features.leafTags.length > 0 ? features.leafTags : POLY_LEAF_TAGS; - parts.push(` -${selectorList(tags, ".polycss-mesh.polycss-transform-gizmo ")} { - backface-visibility: visible; - transition: color 150ms ease-out, border-color 150ms ease-out, background-color 150ms ease-out; -} -`); - } - - if (features.hasTransformRing) { - const tags = features.leafTags.length > 0 ? features.leafTags : POLY_LEAF_TAGS; - parts.push(` -${selectorList(tags, ".polycss-mesh.polycss-transform-ring ")} { - --ring-inner-r: calc(var(--ring-inner-ratio, 0.92) * 50%); - --ring-outer-r: calc(var(--ring-outer-ratio, 1) * 50%); - -webkit-mask: radial-gradient(circle at 50% 50%, - transparent 0%, - transparent var(--ring-inner-r), - black var(--ring-inner-r), - black var(--ring-outer-r), - transparent var(--ring-outer-r)); - mask: radial-gradient(circle at 50% 50%, - transparent 0%, - transparent var(--ring-inner-r), - black var(--ring-inner-r), - black var(--ring-outer-r), - transparent var(--ring-outer-r)); -} -`); - } - - if (features.hasDynamicLighting) { - parts.push(buildDynamicLightingCss(features)); - } - - return parts.map((part) => part.trim()).filter(Boolean).join("\n\n"); -} - -function inlineStyleFor(el: Element): CSSStyleDeclaration | null { - const value = (el as unknown as ElementCSSInlineStyle).style; - return value && typeof value.getPropertyValue === "function" ? value : null; -} - -function cleanupEmptyStyleAttr(el: Element): void { - const style = el.getAttribute("style"); - if (style !== null && style.trim() === "") el.removeAttribute("style"); -} - -function inheritedInlineCustomProperty(el: Element, property: string): string { - let current: Element | null = el; - while (current) { - const value = inlineStyleFor(current)?.getPropertyValue(property).trim(); - if (value) return value; - current = current.parentElement; - } - return ""; -} - -function inlineSnapshotStaticStyleHints( - sourceRoot: Element, - cloneRoot: Element, - features: SnapshotCssFeatures, -): void { - const sourceElements = allElements(sourceRoot); - const cloneElements = allElements(cloneRoot); - for (let i = 0; i < cloneElements.length; i++) { - const sourceEl = sourceElements[i]; - const cloneEl = cloneElements[i]; - if (!sourceEl || !cloneEl) continue; - const cloneStyle = inlineStyleFor(cloneEl); - if (!cloneStyle) continue; - - if (cloneEl.classList.contains("polycss-mesh")) { - const origin = cloneStyle.getPropertyValue("--origin").trim(); - if (origin) { - cloneStyle.setProperty("transform-origin", origin); - cloneStyle.removeProperty("--origin"); - } - } - - const tag = cloneEl.tagName.toLowerCase(); - if (tag === "s") { - const atlasSize = cloneStyle.getPropertyValue("--polycss-atlas-size").trim(); - const atlasWidth = cloneStyle.getPropertyValue("--polycss-atlas-width").trim() || atlasSize; - const atlasHeight = cloneStyle.getPropertyValue("--polycss-atlas-height").trim() || atlasSize; - if (atlasWidth) { - cloneStyle.setProperty("width", atlasWidth); - } - if (atlasHeight) { - cloneStyle.setProperty("height", atlasHeight); - } - if (!features.hasDynamicLighting) { - for (const property of ATLAS_CUSTOM_PROPS) { - cloneStyle.removeProperty(property); - } - } else { - for (const property of ATLAS_DIMENSION_CUSTOM_PROPS) { - cloneStyle.removeProperty(property); - } - } - } else if (tag === "b" || tag === "i" || tag === "u") { - const paint = inheritedInlineCustomProperty(sourceEl, "--polycss-paint"); - const computedColor = !features.hasDynamicLighting - ? sourceEl.ownerDocument.defaultView?.getComputedStyle(sourceEl).color - : ""; - if (computedColor) { - cloneStyle.setProperty("color", computedColor); - } else if (paint && !cloneStyle.getPropertyValue("color")) { - cloneStyle.setProperty("color", paint); - } - } - - if (!features.hasDynamicLighting) { - for (const property of LIGHTING_CUSTOM_PROPS) { - cloneStyle.removeProperty(property); - } - } - if (!features.hasQ) { - for (const property of SHADOW_CUSTOM_PROPS) { - cloneStyle.removeProperty(property); - } - } - cloneStyle.removeProperty("will-change"); - cloneStyle.removeProperty("--polycss-paint"); - cleanupEmptyStyleAttr(cloneEl); - } -} - -function sanitizeClone(root: Element): void { - for (const script of Array.from(root.querySelectorAll("script"))) { - script.remove(); - } - - for (const el of allElements(root)) { - for (const attr of Array.from(el.attributes)) { - if (attr.name.toLowerCase().startsWith("on")) { - el.removeAttribute(attr.name); - } - } - } -} - -function isInlineOrLocalReference(url: string): boolean { - const value = url.trim(); - return value === "" || value.startsWith("#") || /^data:/i.test(value); -} - -function inlineAssetKey(rawUrl: string, ctx: InlineContext): string { - if (/^data:/i.test(rawUrl.trim())) return rawUrl.trim(); - return resolveAssetUrl(rawUrl, ctx.baseUrl); -} - -function extractCssUrl(value: string): string | null { - const match = /url\(\s*(?:(["'])(.*?)\1|([^)]*?))\s*\)/i.exec(value); - return (match?.[2] ?? match?.[3] ?? "").trim() || null; -} - -function escapeCssString(value: string): string { - return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\a "); -} - -function resolveAssetUrl(url: string, baseUrl: string): string { - try { - return new URL(url, baseUrl).href; - } catch { - throw new PolySceneSnapshotError( - "ASSET_INLINE_FAILED", - `exportPolySceneSnapshot: could not resolve asset URL "${url}".`, - url, - ); - } -} - -function inferMimeType(url: string): string { - const pathname = (() => { - try { - return new URL(url).pathname.toLowerCase(); - } catch { - return url.toLowerCase(); - } - })(); - - if (pathname.endsWith(".jpg") || pathname.endsWith(".jpeg")) return "image/jpeg"; - if (pathname.endsWith(".png")) return "image/png"; - if (pathname.endsWith(".webp")) return "image/webp"; - if (pathname.endsWith(".gif")) return "image/gif"; - if (pathname.endsWith(".svg")) return "image/svg+xml"; - if (pathname.endsWith(".avif")) return "image/avif"; - return "application/octet-stream"; -} - -function arrayBufferToBase64(buffer: ArrayBuffer): string { - const bytes = new Uint8Array(buffer); - const chunkSize = 0x8000; - let binary = ""; - for (let i = 0; i < bytes.length; i += chunkSize) { - const chunk = bytes.subarray(i, i + chunkSize); - binary += String.fromCharCode(...chunk); - } - return btoa(binary); -} - -function isObjectUrl(url: string): boolean { - return /^(blob|filesystem):/i.test(url.trim()); -} - -function loadBlobViaXhr(url: string): Promise { - return new Promise((resolve, reject) => { - const xhr = new XMLHttpRequest(); - xhr.open("GET", url, true); - xhr.responseType = "blob"; - xhr.onload = () => { - // Object URLs report status 0 on success; treat that as OK. - if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) { - resolve(xhr.response as Blob); - } else { - reject(new Error(`XHR ${xhr.status}`)); - } - }; - xhr.onerror = () => reject(new Error("XHR request failed")); - xhr.send(); - }); -} - -async function loadAssetBlob(url: string): Promise { - // Object URLs (blob:/filesystem:) are same-document; a credentials mode is - // meaningless for them and trips some WebKit builds, so omit it there. - const objectUrl = isObjectUrl(url); - try { - if (typeof fetch !== "function") { - throw new Error("fetch is not available"); - } - const response = await fetch(url, objectUrl ? undefined : { credentials: "same-origin" }); - if (!response.ok) { - throw new Error(`HTTP ${response.status}`); - } - return await response.blob(); - } catch (error) { - // WebKit/Safari intermittently fails to fetch() object URLs ("Load - // failed"); XMLHttpRequest is the reliable fallback for same-document - // object URLs and is why a textured/atlas export breaks only on Safari. - if (objectUrl && typeof XMLHttpRequest === "function") { - return loadBlobViaXhr(url); - } - throw error; - } -} - -async function inlineAssetUrl(rawUrl: string, ctx: InlineContext): Promise { - if (isInlineOrLocalReference(rawUrl)) return rawUrl; - - const resolvedUrl = resolveAssetUrl(rawUrl, ctx.baseUrl); - const cached = ctx.cache.get(resolvedUrl); - if (cached) return cached; - - const next = (async () => { - try { - const blob = await loadAssetBlob(resolvedUrl); - const mime = blob.type || inferMimeType(resolvedUrl); - const base64 = arrayBufferToBase64(await blob.arrayBuffer()); - return `data:${mime};base64,${base64}`; - } catch { - throw new PolySceneSnapshotError( - "ASSET_INLINE_FAILED", - `exportPolySceneSnapshot: could not inline asset "${resolvedUrl}".`, - resolvedUrl, - ); - } - })(); - - ctx.cache.set(resolvedUrl, next); - return next; -} - -async function inlineCssUrls(cssText: string, ctx: InlineContext): Promise { - const urlPattern = /url\(\s*(?:(["'])(.*?)\1|([^)]*?))\s*\)/gi; - let output = ""; - let lastIndex = 0; - let match: RegExpExecArray | null; - - while ((match = urlPattern.exec(cssText)) !== null) { - output += cssText.slice(lastIndex, match.index); - const rawUrl = (match[2] ?? match[3] ?? "").trim(); - const inlinedUrl = await inlineAssetUrl(rawUrl, ctx); - output += isInlineOrLocalReference(rawUrl) ? match[0] : `url("${inlinedUrl}")`; - lastIndex = urlPattern.lastIndex; - } - - return output + cssText.slice(lastIndex); -} - -async function inlineCloneStyleUrls(root: Element, ctx: InlineContext): Promise { - for (const el of allElements(root)) { - const style = el.getAttribute("style"); - if (style) { - el.setAttribute("style", await inlineCssUrls(style, ctx)); - } - } - - for (const styleEl of Array.from(root.querySelectorAll("style"))) { - styleEl.textContent = await inlineCssUrls(styleEl.textContent ?? "", ctx); - } -} - -function backgroundLonghands(style: CSSStyleDeclaration): { - position: string; - size: string; - repeat: string; -} { - return { - position: style.getPropertyValue("background-position").trim(), - size: style.getPropertyValue("background-size").trim(), - repeat: style.getPropertyValue("background-repeat").trim(), - }; -} - -function restoreBackgroundLonghands( - style: CSSStyleDeclaration, - values: ReturnType, -): void { - if (values.position) style.setProperty("background-position", values.position); - if (values.size) style.setProperty("background-size", values.size); - if (values.repeat) style.setProperty("background-repeat", values.repeat); -} - -async function compactSharedInlineAssets(root: Element, ctx: InlineContext): Promise { - const rules: SnapshotAssetRule[] = []; - const assetIds = new Map(); - const assetDataUrls = new Map(); - - const assetIdFor = async (rawUrl: string): Promise => { - const key = inlineAssetKey(rawUrl, ctx); - const existing = assetIds.get(key); - if (existing) return existing; - const id = `a${assetIds.size}`; - assetIds.set(key, id); - assetDataUrls.set(key, await inlineAssetUrl(rawUrl, ctx)); - return id; - }; - - const dataUrlForId = (id: string): string => { - for (const [key, candidateId] of assetIds) { - if (candidateId === id) return assetDataUrls.get(key) ?? ""; - } - return ""; - }; - - for (const el of allElements(root)) { - const style = inlineStyleFor(el); - if (!style || el.tagName.toLowerCase() !== "s") continue; - - const atlasUrl = extractCssUrl(style.getPropertyValue("--polycss-atlas-url")); - if (atlasUrl && !atlasUrl.startsWith("#")) { - const id = await assetIdFor(atlasUrl); - const attr = "data-polycss-snapshot-atlas"; - el.setAttribute(attr, id); - style.removeProperty("--polycss-atlas-url"); - rules.push({ - attr, - value: id, - property: "--polycss-atlas-url", - dataUrl: dataUrlForId(id), - }); - } - - const backgroundUrl = extractCssUrl(style.getPropertyValue("background-image")); - if (!backgroundUrl || backgroundUrl.startsWith("#")) continue; - const id = await assetIdFor(backgroundUrl); - const attr = "data-polycss-snapshot-bg"; - const longhands = backgroundLonghands(style); - el.setAttribute(attr, id); - style.removeProperty("background"); - style.removeProperty("background-image"); - restoreBackgroundLonghands(style, longhands); - rules.push({ - attr, - value: id, - property: "background-image", - dataUrl: dataUrlForId(id), - }); - cleanupEmptyStyleAttr(el); - } - - const seenRules = new Set(); - return rules - .filter((rule) => { - const key = `${rule.attr}|${rule.value}|${rule.property}`; - if (seenRules.has(key)) return false; - seenRules.add(key); - return true; - }) - .map((rule) => ( - `.polycss-scene [${rule.attr}="${rule.value}"] {\n` + - ` ${rule.property}: url("${escapeCssString(rule.dataUrl)}");\n` + - "}" - )) - .join("\n\n"); -} +import { compactSharedInlineAssets } from "./exporter/compactAssets"; +import { collectSnapshotCssFeatures } from "./exporter/cssFeatures"; +import { findPolySnapshotRoot, isElement } from "./exporter/dom"; +import { PolySceneSnapshotError } from "./exporter/errors"; +import type { InlineContext } from "./exporter/inlineAssets"; +import { inlineCloneStyleUrls, inlineCssUrls } from "./exporter/inlineAssets"; +import { inlineSnapshotStaticStyleHints, sanitizeClone } from "./exporter/prepareClone"; +import { buildPolySnapshotCss } from "./exporter/snapshotCss"; + +export { PolySceneSnapshotError } from "./exporter/errors"; +export type { PolySceneSnapshotErrorCode } from "./exporter/errors"; function escapeHtmlText(text: string): string { return text diff --git a/packages/polycss/src/snapshot/exporter/compactAssets.ts b/packages/polycss/src/snapshot/exporter/compactAssets.ts new file mode 100644 index 000000000..f4f23e02d --- /dev/null +++ b/packages/polycss/src/snapshot/exporter/compactAssets.ts @@ -0,0 +1,113 @@ +import { allElements, cleanupEmptyStyleAttr, inlineStyleFor } from "./dom"; +import type { InlineContext } from "./inlineAssets"; +import { + escapeCssString, + extractCssUrl, + inlineAssetKey, + inlineAssetUrl, +} from "./inlineAssets"; + +interface SnapshotAssetRule { + attr: string; + value: string; + property: "background-image" | "--polycss-atlas-url"; + dataUrl: string; +} + +function backgroundLonghands(style: CSSStyleDeclaration): { + position: string; + size: string; + repeat: string; +} { + return { + position: style.getPropertyValue("background-position").trim(), + size: style.getPropertyValue("background-size").trim(), + repeat: style.getPropertyValue("background-repeat").trim(), + }; +} + +function restoreBackgroundLonghands( + style: CSSStyleDeclaration, + values: ReturnType, +): void { + if (values.position) style.setProperty("background-position", values.position); + if (values.size) style.setProperty("background-size", values.size); + if (values.repeat) style.setProperty("background-repeat", values.repeat); +} + +export async function compactSharedInlineAssets( + root: Element, + ctx: InlineContext, +): Promise { + const rules: SnapshotAssetRule[] = []; + const assetIds = new Map(); + const assetDataUrls = new Map(); + + const assetIdFor = async (rawUrl: string): Promise => { + const key = inlineAssetKey(rawUrl, ctx); + const existing = assetIds.get(key); + if (existing) return existing; + const id = `a${assetIds.size}`; + assetIds.set(key, id); + assetDataUrls.set(key, await inlineAssetUrl(rawUrl, ctx)); + return id; + }; + + const dataUrlForId = (id: string): string => { + for (const [key, candidateId] of assetIds) { + if (candidateId === id) return assetDataUrls.get(key) ?? ""; + } + return ""; + }; + + for (const el of allElements(root)) { + const style = inlineStyleFor(el); + if (!style || el.tagName.toLowerCase() !== "s") continue; + + const atlasUrl = extractCssUrl(style.getPropertyValue("--polycss-atlas-url")); + if (atlasUrl && !atlasUrl.startsWith("#")) { + const id = await assetIdFor(atlasUrl); + const attr = "data-polycss-snapshot-atlas"; + el.setAttribute(attr, id); + style.removeProperty("--polycss-atlas-url"); + rules.push({ + attr, + value: id, + property: "--polycss-atlas-url", + dataUrl: dataUrlForId(id), + }); + } + + const backgroundUrl = extractCssUrl(style.getPropertyValue("background-image")); + if (!backgroundUrl || backgroundUrl.startsWith("#")) continue; + const id = await assetIdFor(backgroundUrl); + const attr = "data-polycss-snapshot-bg"; + const longhands = backgroundLonghands(style); + el.setAttribute(attr, id); + style.removeProperty("background"); + style.removeProperty("background-image"); + restoreBackgroundLonghands(style, longhands); + rules.push({ + attr, + value: id, + property: "background-image", + dataUrl: dataUrlForId(id), + }); + cleanupEmptyStyleAttr(el); + } + + const seenRules = new Set(); + return rules + .filter((rule) => { + const key = `${rule.attr}|${rule.value}|${rule.property}`; + if (seenRules.has(key)) return false; + seenRules.add(key); + return true; + }) + .map((rule) => ( + `.polycss-scene [${rule.attr}="${rule.value}"] {\n` + + ` ${rule.property}: url("${escapeCssString(rule.dataUrl)}");\n` + + "}" + )) + .join("\n\n"); +} diff --git a/packages/polycss/src/snapshot/exporter/cssFeatures.ts b/packages/polycss/src/snapshot/exporter/cssFeatures.ts new file mode 100644 index 000000000..e5f5d6db0 --- /dev/null +++ b/packages/polycss/src/snapshot/exporter/cssFeatures.ts @@ -0,0 +1,50 @@ +export type PolyLeafTag = "b" | "i" | "s" | "u"; + +export interface SnapshotCssFeatures { + hasCamera: boolean; + hasScene: boolean; + hasMesh: boolean; + hasFpvHost: boolean; + hasBucket: boolean; + hasVoxelMesh: boolean; + hasTransformGizmo: boolean; + hasTransformRing: boolean; + hasDynamicLighting: boolean; + hasQ: boolean; + leafTags: PolyLeafTag[]; + solidLeafTags: PolyLeafTag[]; +} + +export const POLY_LEAF_TAGS: PolyLeafTag[] = ["b", "i", "s", "u"]; +const SOLID_POLY_LEAF_TAGS: PolyLeafTag[] = ["b", "i", "u"]; + +function matchesOrContains(root: Element, selector: string): boolean { + return root.matches(selector) || !!root.querySelector(selector); +} + +function containsTag(root: Element, tagName: string): boolean { + return root.tagName.toLowerCase() === tagName || !!root.querySelector(tagName); +} + +export function collectSnapshotCssFeatures(root: Element): SnapshotCssFeatures { + const leafTags = POLY_LEAF_TAGS.filter((tag) => containsTag(root, tag)); + const solidLeafTags = SOLID_POLY_LEAF_TAGS.filter((tag) => leafTags.includes(tag)); + return { + hasCamera: matchesOrContains(root, ".polycss-camera"), + hasScene: matchesOrContains(root, ".polycss-scene"), + hasMesh: matchesOrContains(root, ".polycss-mesh"), + hasFpvHost: matchesOrContains(root, ".polycss-fpv-host"), + hasBucket: matchesOrContains(root, ".polycss-bucket"), + hasVoxelMesh: matchesOrContains(root, ".polycss-voxel-mesh"), + hasTransformGizmo: matchesOrContains(root, ".polycss-transform-gizmo"), + hasTransformRing: matchesOrContains(root, ".polycss-transform-ring"), + hasDynamicLighting: matchesOrContains(root, '.polycss-scene[data-polycss-lighting="dynamic"]'), + hasQ: containsTag(root, "q"), + leafTags, + solidLeafTags, + }; +} + +export function selectorList(tags: readonly string[], prefix = ".polycss-scene "): string { + return tags.map((tag) => `${prefix}${tag}`).join(",\n"); +} diff --git a/packages/polycss/src/snapshot/exporter/dom.ts b/packages/polycss/src/snapshot/exporter/dom.ts new file mode 100644 index 000000000..a76bca424 --- /dev/null +++ b/packages/polycss/src/snapshot/exporter/dom.ts @@ -0,0 +1,30 @@ +export function isElement(value: unknown): value is Element { + return !!value + && typeof (value as Element).querySelector === "function" + && typeof (value as Element).cloneNode === "function"; +} + +export function findPolySnapshotRoot(target: Element): Element | null { + const closestCamera = target.closest(".polycss-camera"); + if (closestCamera) return closestCamera; + + const closestScene = target.closest(".polycss-scene"); + if (closestScene) return closestScene.closest(".polycss-camera") ?? closestScene; + + return target.querySelector(".polycss-camera") + ?? target.querySelector(".polycss-scene"); +} + +export function allElements(root: Element): Element[] { + return [root, ...Array.from(root.querySelectorAll("*"))]; +} + +export function inlineStyleFor(el: Element): CSSStyleDeclaration | null { + const value = (el as unknown as ElementCSSInlineStyle).style; + return value && typeof value.getPropertyValue === "function" ? value : null; +} + +export function cleanupEmptyStyleAttr(el: Element): void { + const style = el.getAttribute("style"); + if (style !== null && style.trim() === "") el.removeAttribute("style"); +} diff --git a/packages/polycss/src/snapshot/exporter/dynamicLightingCss.ts b/packages/polycss/src/snapshot/exporter/dynamicLightingCss.ts new file mode 100644 index 000000000..9be8dedc7 --- /dev/null +++ b/packages/polycss/src/snapshot/exporter/dynamicLightingCss.ts @@ -0,0 +1,138 @@ +import type { SnapshotCssFeatures } from "./cssFeatures"; +import { selectorList } from "./cssFeatures"; + +function directLeafSelectorList(tags: readonly string[]): string { + return tags + .map((tag) => `.polycss-scene[data-polycss-lighting="dynamic"] :not(.polycss-bucket) > ${tag}`) + .join(",\n"); +} + +function dynamicPropertyCss(includeShadowProjection: boolean): string { + const props = [ + '@property --plx { syntax: ""; inherits: true; initial-value: 0; }', + '@property --ply { syntax: ""; inherits: true; initial-value: 0; }', + '@property --plz { syntax: ""; inherits: true; initial-value: 1; }', + '@property --plr { syntax: ""; inherits: true; initial-value: 1; }', + '@property --plg { syntax: ""; inherits: true; initial-value: 1; }', + '@property --plb { syntax: ""; inherits: true; initial-value: 1; }', + '@property --pli { syntax: ""; inherits: true; initial-value: 1; }', + '@property --par { syntax: ""; inherits: true; initial-value: 1; }', + '@property --pag { syntax: ""; inherits: true; initial-value: 1; }', + '@property --pab { syntax: ""; inherits: true; initial-value: 1; }', + '@property --pai { syntax: ""; inherits: true; initial-value: 0.4; }', + '@property --pnx { syntax: ""; inherits: true; initial-value: 0; }', + '@property --pny { syntax: ""; inherits: true; initial-value: 0; }', + '@property --pnz { syntax: ""; inherits: true; initial-value: 1; }', + '@property --psr { syntax: ""; inherits: true; initial-value: 1; }', + '@property --psg { syntax: ""; inherits: true; initial-value: 1; }', + '@property --psb { syntax: ""; inherits: true; initial-value: 1; }', + '@property --plam { syntax: ""; inherits: true; initial-value: 0; }', + ]; + if (includeShadowProjection) { + props.push( + '@property --clx { syntax: ""; inherits: true; initial-value: 0.01; }', + '@property --cly { syntax: ""; inherits: true; initial-value: 0; }', + '@property --clz { syntax: ""; inherits: true; initial-value: 1; }', + '@property --shadow-ground-cssz { syntax: ""; inherits: true; initial-value: 0; }', + ); + } + return props.join("\n"); +} + +export function buildDynamicLightingCss(features: SnapshotCssFeatures): string { + const parts = [dynamicPropertyCss(features.hasQ)]; + + if (features.hasBucket) { + parts.push(` +.polycss-scene[data-polycss-lighting="dynamic"] .polycss-bucket { + --plam: max(0, calc( + var(--pnx) * var(--plx) + + var(--pny) * var(--ply) + + var(--pnz) * var(--plz) + )); +} +`); + } + + if (features.leafTags.length > 0) { + parts.push(` +${directLeafSelectorList(features.leafTags)} { + --plam: max(0, calc( + var(--pnx) * var(--plx) + + var(--pny) * var(--ply) + + var(--pnz) * var(--plz) + )); +} +`); + } + + if (features.leafTags.includes("s")) { + parts.push(` +.polycss-scene[data-polycss-lighting="dynamic"] s { + contain: strict; + background-color: rgb( + calc(255 * (var(--par) * var(--pai) + + var(--plr) * var(--pli) * var(--plam))) + calc(255 * (var(--pag) * var(--pai) + + var(--plg) * var(--pli) * var(--plam))) + calc(255 * (var(--pab) * var(--pai) + + var(--plb) * var(--pli) * var(--plam))) + ); + background-blend-mode: multiply; + background-image: var(--polycss-atlas-url); + background-position: var(--polycss-atlas-position); + background-repeat: no-repeat; + background-size: var(--polycss-atlas-image-size); + mask-image: var(--polycss-atlas-url); + mask-mode: alpha; + mask-position: var(--polycss-atlas-position); + mask-repeat: no-repeat; + mask-size: var(--polycss-atlas-image-size); + -webkit-mask-image: var(--polycss-atlas-url); + -webkit-mask-position: var(--polycss-atlas-position); + -webkit-mask-repeat: no-repeat; + -webkit-mask-size: var(--polycss-atlas-image-size); +} +`); + } + + if (features.solidLeafTags.length > 0) { + parts.push(` +${selectorList(features.solidLeafTags)} { + color: rgb( + calc(255 * var(--psr) * (var(--par) * var(--pai) + + var(--plr) * var(--pli) * var(--plam))) + calc(255 * var(--psg) * (var(--pag) * var(--pai) + + var(--plg) * var(--pli) * var(--plam))) + calc(255 * var(--psb) * (var(--pab) * var(--pai) + + var(--plb) * var(--pli) * var(--plam))) + ); +} +`); + } + + if (features.hasQ) { + parts.push(` +.polycss-scene[data-polycss-lighting="dynamic"] { + --shadow-proj: matrix3d( + 1, 0, 0, 0, + 0, 1, 0, 0, + calc(-1 * var(--clx) / var(--clz)), + calc(-1 * var(--cly) / var(--clz)), + 0.01, + 0, + calc(var(--shadow-ground-cssz) * var(--clx) / var(--clz)), + calc(var(--shadow-ground-cssz) * var(--cly) / var(--clz)), + calc(var(--shadow-ground-cssz) * 0.99), + 1 + ); +} + +.polycss-scene[data-polycss-lighting="dynamic"] q { + opacity: clamp(0, calc((var(--pnx) * var(--clx) + var(--pny) * var(--cly) + var(--pnz) * var(--clz)) * 10), 1); +} +`); + } + + return parts.join("\n"); +} diff --git a/packages/polycss/src/snapshot/exporter/errors.ts b/packages/polycss/src/snapshot/exporter/errors.ts new file mode 100644 index 000000000..83e95696e --- /dev/null +++ b/packages/polycss/src/snapshot/exporter/errors.ts @@ -0,0 +1,17 @@ +export type PolySceneSnapshotErrorCode = + | "INVALID_TARGET" + | "SCENE_NOT_FOUND" + | "ASSET_INLINE_FAILED"; + +export class PolySceneSnapshotError extends Error { + readonly code: PolySceneSnapshotErrorCode; + readonly url?: string; + + constructor(code: PolySceneSnapshotErrorCode, message: string, url?: string) { + super(message); + this.name = "PolySceneSnapshotError"; + this.code = code; + this.url = url; + Object.setPrototypeOf(this, new.target.prototype); + } +} diff --git a/packages/polycss/src/snapshot/exporter/inlineAssets.ts b/packages/polycss/src/snapshot/exporter/inlineAssets.ts new file mode 100644 index 000000000..ed8d1ef76 --- /dev/null +++ b/packages/polycss/src/snapshot/exporter/inlineAssets.ts @@ -0,0 +1,169 @@ +import { allElements } from "./dom"; +import { PolySceneSnapshotError } from "./errors"; + +export interface InlineContext { + baseUrl: string; + cache: Map>; +} + +function isInlineOrLocalReference(url: string): boolean { + const value = url.trim(); + return value === "" || value.startsWith("#") || /^data:/i.test(value); +} + +export function inlineAssetKey(rawUrl: string, ctx: InlineContext): string { + if (/^data:/i.test(rawUrl.trim())) return rawUrl.trim(); + return resolveAssetUrl(rawUrl, ctx.baseUrl); +} + +export function extractCssUrl(value: string): string | null { + const match = /url\(\s*(?:(["'])(.*?)\1|([^)]*?))\s*\)/i.exec(value); + return (match?.[2] ?? match?.[3] ?? "").trim() || null; +} + +export function escapeCssString(value: string): string { + return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\a "); +} + +function resolveAssetUrl(url: string, baseUrl: string): string { + try { + return new URL(url, baseUrl).href; + } catch { + throw new PolySceneSnapshotError( + "ASSET_INLINE_FAILED", + `exportPolySceneSnapshot: could not resolve asset URL "${url}".`, + url, + ); + } +} + +function inferMimeType(url: string): string { + const pathname = (() => { + try { + return new URL(url).pathname.toLowerCase(); + } catch { + return url.toLowerCase(); + } + })(); + + if (pathname.endsWith(".jpg") || pathname.endsWith(".jpeg")) return "image/jpeg"; + if (pathname.endsWith(".png")) return "image/png"; + if (pathname.endsWith(".webp")) return "image/webp"; + if (pathname.endsWith(".gif")) return "image/gif"; + if (pathname.endsWith(".svg")) return "image/svg+xml"; + if (pathname.endsWith(".avif")) return "image/avif"; + return "application/octet-stream"; +} + +function arrayBufferToBase64(buffer: ArrayBuffer): string { + const bytes = new Uint8Array(buffer); + const chunkSize = 0x8000; + let binary = ""; + for (let i = 0; i < bytes.length; i += chunkSize) { + const chunk = bytes.subarray(i, i + chunkSize); + binary += String.fromCharCode(...chunk); + } + return btoa(binary); +} + +function isObjectUrl(url: string): boolean { + return /^(blob|filesystem):/i.test(url.trim()); +} + +function loadBlobViaXhr(url: string): Promise { + return new Promise((resolve, reject) => { + const xhr = new XMLHttpRequest(); + xhr.open("GET", url, true); + xhr.responseType = "blob"; + xhr.onload = () => { + // Object URLs report status 0 on success; treat that as OK. + if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) { + resolve(xhr.response as Blob); + } else { + reject(new Error(`XHR ${xhr.status}`)); + } + }; + xhr.onerror = () => reject(new Error("XHR request failed")); + xhr.send(); + }); +} + +async function loadAssetBlob(url: string): Promise { + // Object URLs (blob:/filesystem:) are same-document; a credentials mode is + // meaningless for them and trips some WebKit builds, so omit it there. + const objectUrl = isObjectUrl(url); + try { + if (typeof fetch !== "function") { + throw new Error("fetch is not available"); + } + const response = await fetch(url, objectUrl ? undefined : { credentials: "same-origin" }); + if (!response.ok) { + throw new Error(`HTTP ${response.status}`); + } + return await response.blob(); + } catch (error) { + // WebKit/Safari intermittently fails to fetch() object URLs ("Load + // failed"); XMLHttpRequest is the reliable fallback for same-document + // object URLs and is why a textured/atlas export breaks only on Safari. + if (objectUrl && typeof XMLHttpRequest === "function") { + return loadBlobViaXhr(url); + } + throw error; + } +} + +export async function inlineAssetUrl(rawUrl: string, ctx: InlineContext): Promise { + if (isInlineOrLocalReference(rawUrl)) return rawUrl; + + const resolvedUrl = resolveAssetUrl(rawUrl, ctx.baseUrl); + const cached = ctx.cache.get(resolvedUrl); + if (cached) return cached; + + const next = (async () => { + try { + const blob = await loadAssetBlob(resolvedUrl); + const mime = blob.type || inferMimeType(resolvedUrl); + const base64 = arrayBufferToBase64(await blob.arrayBuffer()); + return `data:${mime};base64,${base64}`; + } catch { + throw new PolySceneSnapshotError( + "ASSET_INLINE_FAILED", + `exportPolySceneSnapshot: could not inline asset "${resolvedUrl}".`, + resolvedUrl, + ); + } + })(); + + ctx.cache.set(resolvedUrl, next); + return next; +} + +export async function inlineCssUrls(cssText: string, ctx: InlineContext): Promise { + const urlPattern = /url\(\s*(?:(["'])(.*?)\1|([^)]*?))\s*\)/gi; + let output = ""; + let lastIndex = 0; + let match: RegExpExecArray | null; + + while ((match = urlPattern.exec(cssText)) !== null) { + output += cssText.slice(lastIndex, match.index); + const rawUrl = (match[2] ?? match[3] ?? "").trim(); + const inlinedUrl = await inlineAssetUrl(rawUrl, ctx); + output += isInlineOrLocalReference(rawUrl) ? match[0] : `url("${inlinedUrl}")`; + lastIndex = urlPattern.lastIndex; + } + + return output + cssText.slice(lastIndex); +} + +export async function inlineCloneStyleUrls(root: Element, ctx: InlineContext): Promise { + for (const el of allElements(root)) { + const style = el.getAttribute("style"); + if (style) { + el.setAttribute("style", await inlineCssUrls(style, ctx)); + } + } + + for (const styleEl of Array.from(root.querySelectorAll("style"))) { + styleEl.textContent = await inlineCssUrls(styleEl.textContent ?? "", ctx); + } +} diff --git a/packages/polycss/src/snapshot/exporter/prepareClone.ts b/packages/polycss/src/snapshot/exporter/prepareClone.ts new file mode 100644 index 000000000..5abea5daa --- /dev/null +++ b/packages/polycss/src/snapshot/exporter/prepareClone.ts @@ -0,0 +1,130 @@ +import type { SnapshotCssFeatures } from "./cssFeatures"; +import { allElements, cleanupEmptyStyleAttr, inlineStyleFor } from "./dom"; + +const LIGHTING_CUSTOM_PROPS = [ + "--plx", "--ply", "--plz", + "--plr", "--plg", "--plb", "--pli", + "--par", "--pag", "--pab", "--pai", + "--pnx", "--pny", "--pnz", + "--psr", "--psg", "--psb", + "--plam", + "--polycss-light-preview-active", + "--polycss-preview-r", + "--polycss-preview-g", + "--polycss-preview-b", +] as const; + +const SHADOW_CUSTOM_PROPS = [ + "--clx", "--cly", "--clz", "--shadow-ground-cssz", +] as const; + +const ATLAS_CUSTOM_PROPS = [ + "--polycss-atlas-size", + "--polycss-atlas-width", + "--polycss-atlas-height", + "--polycss-atlas-leaf-sizing", + "--polycss-atlas-url", + "--polycss-atlas-position", + "--polycss-atlas-image-size", +] as const; + +const ATLAS_DIMENSION_CUSTOM_PROPS = [ + "--polycss-atlas-size", + "--polycss-atlas-width", + "--polycss-atlas-height", + "--polycss-atlas-leaf-sizing", +] as const; + +function inheritedInlineCustomProperty(el: Element, property: string): string { + let current: Element | null = el; + while (current) { + const value = inlineStyleFor(current)?.getPropertyValue(property).trim(); + if (value) return value; + current = current.parentElement; + } + return ""; +} + +export function inlineSnapshotStaticStyleHints( + sourceRoot: Element, + cloneRoot: Element, + features: SnapshotCssFeatures, +): void { + const sourceElements = allElements(sourceRoot); + const cloneElements = allElements(cloneRoot); + for (let i = 0; i < cloneElements.length; i++) { + const sourceEl = sourceElements[i]; + const cloneEl = cloneElements[i]; + if (!sourceEl || !cloneEl) continue; + const cloneStyle = inlineStyleFor(cloneEl); + if (!cloneStyle) continue; + + if (cloneEl.classList.contains("polycss-mesh")) { + const origin = cloneStyle.getPropertyValue("--origin").trim(); + if (origin) { + cloneStyle.setProperty("transform-origin", origin); + cloneStyle.removeProperty("--origin"); + } + } + + const tag = cloneEl.tagName.toLowerCase(); + if (tag === "s") { + const atlasSize = cloneStyle.getPropertyValue("--polycss-atlas-size").trim(); + const atlasWidth = cloneStyle.getPropertyValue("--polycss-atlas-width").trim() || atlasSize; + const atlasHeight = cloneStyle.getPropertyValue("--polycss-atlas-height").trim() || atlasSize; + if (atlasWidth) { + cloneStyle.setProperty("width", atlasWidth); + } + if (atlasHeight) { + cloneStyle.setProperty("height", atlasHeight); + } + if (!features.hasDynamicLighting) { + for (const property of ATLAS_CUSTOM_PROPS) { + cloneStyle.removeProperty(property); + } + } else { + for (const property of ATLAS_DIMENSION_CUSTOM_PROPS) { + cloneStyle.removeProperty(property); + } + } + } else if (tag === "b" || tag === "i" || tag === "u") { + const paint = inheritedInlineCustomProperty(sourceEl, "--polycss-paint"); + const computedColor = !features.hasDynamicLighting + ? sourceEl.ownerDocument.defaultView?.getComputedStyle(sourceEl).color + : ""; + if (computedColor) { + cloneStyle.setProperty("color", computedColor); + } else if (paint && !cloneStyle.getPropertyValue("color")) { + cloneStyle.setProperty("color", paint); + } + } + + if (!features.hasDynamicLighting) { + for (const property of LIGHTING_CUSTOM_PROPS) { + cloneStyle.removeProperty(property); + } + } + if (!features.hasQ) { + for (const property of SHADOW_CUSTOM_PROPS) { + cloneStyle.removeProperty(property); + } + } + cloneStyle.removeProperty("will-change"); + cloneStyle.removeProperty("--polycss-paint"); + cleanupEmptyStyleAttr(cloneEl); + } +} + +export function sanitizeClone(root: Element): void { + for (const script of Array.from(root.querySelectorAll("script"))) { + script.remove(); + } + + for (const el of allElements(root)) { + for (const attr of Array.from(el.attributes)) { + if (attr.name.toLowerCase().startsWith("on")) { + el.removeAttribute(attr.name); + } + } + } +} diff --git a/packages/polycss/src/snapshot/exporter/snapshotCss.ts b/packages/polycss/src/snapshot/exporter/snapshotCss.ts new file mode 100644 index 000000000..3e3632d89 --- /dev/null +++ b/packages/polycss/src/snapshot/exporter/snapshotCss.ts @@ -0,0 +1,273 @@ +import type { SnapshotCssFeatures } from "./cssFeatures"; +import { POLY_LEAF_TAGS, selectorList } from "./cssFeatures"; +import { buildDynamicLightingCss } from "./dynamicLightingCss"; + +const SNAPSHOT_DOCUMENT_CSS = ` +html, +body { + width: 100%; + height: 100%; + margin: 0; +} + +body { + position: relative; + overflow: hidden; +} +`; + +export function buildPolySnapshotCss(features: SnapshotCssFeatures): string { + const parts = [SNAPSHOT_DOCUMENT_CSS]; + + if (features.hasScene) { + parts.push(` +.polycss-scene, +.polycss-scene *, +.polycss-scene *::before, +.polycss-scene *::after { + box-sizing: border-box; +} + +.polycss-scene { + position: absolute; + top: 50%; + left: 50%; + width: 0; + height: 0; + transform-style: preserve-3d; +} +`); + } + + if (features.hasCamera) { + parts.push(` +.polycss-camera { + position: relative; + display: block; + width: 100%; + height: 100%; +} +`); + } + + if (features.hasFpvHost) { + parts.push(` +.polycss-fpv-host { + perspective: var(--polycss-fpv-perspective, 2000px) !important; + transform-style: preserve-3d !important; +} +`); + } + + if (features.hasMesh) { + parts.push(` +.polycss-mesh { + position: absolute; + transform-style: preserve-3d; +} +`); + } + + if (features.hasBucket) { + parts.push(` +.polycss-bucket { + position: absolute; + transform-style: preserve-3d; +} +`); + } + + if (features.leafTags.length > 0) { + parts.push(` +${selectorList(features.leafTags)} { + position: absolute; + display: block; + transform-origin: 0 0; + transform-style: preserve-3d; + margin: 0; + padding: 0; + font: inherit; + font-weight: normal; + font-style: normal; + line-height: 0; + text-decoration: none; + backface-visibility: hidden; + background-repeat: no-repeat; +} +`); + } + + if (features.solidLeafTags.length > 0 && !features.hasDynamicLighting) { + parts.push(` +${selectorList(features.solidLeafTags)} { + color: currentColor; +} +`); + } + + if (features.leafTags.includes("b")) { + parts.push(` +.polycss-scene b { + background: currentColor; + width: 64px; + height: 64px; +} +`); + } + + if (features.hasVoxelMesh) { + parts.push(` +.polycss-mesh.polycss-voxel-mesh > .polycss-voxel-face { + position: absolute; + display: block; + top: 0; + left: 0; + width: 0; + height: 0; + transform-style: preserve-3d; + transform-origin: 0 0; + margin: 0; + padding: 0; + font: inherit; + line-height: 0; + pointer-events: none; +} + +.polycss-mesh.polycss-voxel-mesh > .polycss-voxel-face > b { + top: 0; + left: 0; + width: var(--polycss-voxel-primitive, 1px); + height: var(--polycss-voxel-primitive, 1px); + backface-visibility: visible; + pointer-events: none; +} +`); + } + + if (features.leafTags.includes("i")) { + parts.push(` +.polycss-scene i { + width: 16px; + height: 16px; + border-color: currentColor; +} +`); + } + + if (features.leafTags.includes("s")) { + parts.push(` +.polycss-scene s { + width: 64px; + height: 64px; +} +`); + } + + if (features.leafTags.includes("u")) { + parts.push(` +.polycss-scene u { + width: 0; + height: 0; + background: transparent; + box-sizing: content-box; + border: 0 solid transparent; + border-color: transparent transparent currentColor transparent; + border-width: 0 16px 32px 16px; +} + +@supports (corner-top-left-shape: bevel) and (corner-top-right-shape: bevel) { + .polycss-scene > u, + .polycss-mesh > u, + .polycss-bucket > u { + border-width: 0; + width: 32px; + height: 32px; + background-color: currentColor; + border-top-left-radius: 50% 100%; + border-top-right-radius: 50% 100%; + corner-top-left-shape: bevel; + corner-top-right-shape: bevel; + } + + .polycss-scene > u.polycss-corner-shape-solid, + .polycss-mesh > u.polycss-corner-shape-solid, + .polycss-bucket > u.polycss-corner-shape-solid { + width: 16px; + height: 16px; + box-sizing: border-box; + border: 0; + background: currentColor; + border-radius: 0; + corner-top-left-shape: initial; + corner-top-right-shape: initial; + corner-bottom-right-shape: initial; + corner-bottom-left-shape: initial; + } +} +`); + } + + if (features.hasQ) { + parts.push(` +.polycss-scene q { + position: absolute; + display: block; + transform-origin: 0 0; + transform-style: preserve-3d; + margin: 0; + padding: 0; + font: inherit; + font-weight: normal; + font-style: normal; + line-height: 0; + text-decoration: none; + backface-visibility: visible; + border-color: currentColor; + pointer-events: none; +} + +.polycss-scene q::before, +.polycss-scene q::after { + content: none; +} +`); + } + + if (features.hasTransformGizmo) { + const tags = features.leafTags.length > 0 ? features.leafTags : POLY_LEAF_TAGS; + parts.push(` +${selectorList(tags, ".polycss-mesh.polycss-transform-gizmo ")} { + backface-visibility: visible; + transition: color 150ms ease-out, border-color 150ms ease-out, background-color 150ms ease-out; +} +`); + } + + if (features.hasTransformRing) { + const tags = features.leafTags.length > 0 ? features.leafTags : POLY_LEAF_TAGS; + parts.push(` +${selectorList(tags, ".polycss-mesh.polycss-transform-ring ")} { + --ring-inner-r: calc(var(--ring-inner-ratio, 0.92) * 50%); + --ring-outer-r: calc(var(--ring-outer-ratio, 1) * 50%); + -webkit-mask: radial-gradient(circle at 50% 50%, + transparent 0%, + transparent var(--ring-inner-r), + black var(--ring-inner-r), + black var(--ring-outer-r), + transparent var(--ring-outer-r)); + mask: radial-gradient(circle at 50% 50%, + transparent 0%, + transparent var(--ring-inner-r), + black var(--ring-inner-r), + black var(--ring-outer-r), + transparent var(--ring-outer-r)); +} +`); + } + + if (features.hasDynamicLighting) { + parts.push(buildDynamicLightingCss(features)); + } + + return parts.map((part) => part.trim()).filter(Boolean).join("\n\n"); +} diff --git a/packages/react/package.json b/packages/react/package.json index 4ee33b6b0..a680fff41 100644 --- a/packages/react/package.json +++ b/packages/react/package.json @@ -9,13 +9,13 @@ "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/LayoutitStudio/polycss.git", + "url": "https://github.com/layoutit/polycss.git", "directory": "packages/react" }, "bugs": { - "url": "https://github.com/LayoutitStudio/polycss/issues" + "url": "https://github.com/layoutit/polycss/issues" }, - "homepage": "https://github.com/LayoutitStudio/polycss#readme", + "homepage": "https://github.com/layoutit/polycss#readme", "files": [ "dist" ], diff --git a/packages/skills/package.json b/packages/skills/package.json index 058ad8687..b0bb86335 100644 --- a/packages/skills/package.json +++ b/packages/skills/package.json @@ -14,13 +14,13 @@ "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/LayoutitStudio/polycss.git", + "url": "https://github.com/layoutit/polycss.git", "directory": "packages/skills" }, "bugs": { - "url": "https://github.com/LayoutitStudio/polycss/issues" + "url": "https://github.com/layoutit/polycss/issues" }, - "homepage": "https://github.com/LayoutitStudio/polycss#readme", + "homepage": "https://github.com/layoutit/polycss#readme", "files": [ "bin", "src/install.mjs", diff --git a/packages/vue/package.json b/packages/vue/package.json index 253837eea..df40227be 100644 --- a/packages/vue/package.json +++ b/packages/vue/package.json @@ -9,13 +9,13 @@ "license": "MIT", "repository": { "type": "git", - "url": "https://github.com/LayoutitStudio/polycss.git", + "url": "https://github.com/layoutit/polycss.git", "directory": "packages/vue" }, "bugs": { - "url": "https://github.com/LayoutitStudio/polycss/issues" + "url": "https://github.com/layoutit/polycss/issues" }, - "homepage": "https://github.com/LayoutitStudio/polycss#readme", + "homepage": "https://github.com/layoutit/polycss#readme", "files": [ "dist" ], diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 55756808e..7ff67497e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -229,7 +229,7 @@ importers: packages/react: dependencies: '@layoutit/polycss': - specifier: workspace:^ + specifier: workspace:* version: link:../polycss '@layoutit/polycss-core': specifier: workspace:^ @@ -275,7 +275,7 @@ importers: packages/vue: dependencies: '@layoutit/polycss': - specifier: workspace:^ + specifier: workspace:* version: link:../polycss '@layoutit/polycss-core': specifier: workspace:^ @@ -354,6 +354,9 @@ importers: '@types/react-dom': specifier: ^19.2.3 version: 19.2.3(@types/react@19.2.14) + typescript: + specifier: ^5.3.3 + version: 5.9.3 packages: diff --git a/website/astro.config.mjs b/website/astro.config.mjs index 0a71df46d..609451569 100644 --- a/website/astro.config.mjs +++ b/website/astro.config.mjs @@ -40,7 +40,7 @@ export default defineConfig({ SiteTitle: './src/components/SiteTitle.astro', }, social: [ - { icon: 'github', label: 'GitHub', href: 'https://github.com/LayoutitStudio/polycss' }, + { icon: 'github', label: 'GitHub', href: 'https://github.com/layoutit/polycss' }, ], customCss: ['./src/styles/custom.css'], sidebar: [ diff --git a/website/package.json b/website/package.json index 356ea9900..64f1d4815 100644 --- a/website/package.json +++ b/website/package.json @@ -8,6 +8,7 @@ "scripts": { "dev": "astro dev", "build": "astro build && node scripts/generate-llms-txt.mjs", + "typecheck": "ASTRO_TELEMETRY_DISABLED=1 astro sync && tsc --noEmit", "generate:domformat": "node scripts/generate-gallery-domformat.mjs", "prove:domformat": "node scripts/prove-gallery-domformat.mjs", "verify:domformat": "node scripts/verify-gallery-domformat.mjs", @@ -35,6 +36,7 @@ }, "devDependencies": { "@types/react": "^19.2.14", - "@types/react-dom": "^19.2.3" + "@types/react-dom": "^19.2.3", + "typescript": "^5.3.3" } } diff --git a/website/scripts/gallery-domformat-browser.ts b/website/scripts/gallery-domformat-browser.ts index 1b2d270b6..d582cedfc 100644 --- a/website/scripts/gallery-domformat-browser.ts +++ b/website/scripts/gallery-domformat-browser.ts @@ -181,7 +181,7 @@ function imageUrl(value: string): string | null { return match ? (match[1] ?? match[2] ?? match[3]).trim() : null; } -async function pngBytes(blob: Blob): Promise { +async function pngBytes(blob: Blob): Promise> { const bitmap = await createImageBitmap(blob); try { const canvas = document.createElement("canvas"); @@ -342,21 +342,26 @@ async function capturePreset(id: string, retain = false): Promise entry.element); + const leaves = leafEntries.map((entry) => entry.element as HTMLElement); if (leaves.length === 0) throw new Error(`Gallery preset ${id} mounted no visual leaves.`); const frames: CapturedFrame[] = []; - if (effectiveClip && rendered.animation) { + const animation = rendered.animation; + const animatedSetPolygonsOptions = { + merge: false, + stableDom: true, + recomputeAutoCenter: false, + stableTriangleColorPolicy: "cadence", + stableTriangleColorFreezeFrames: 0, + } as Parameters[1] & { + stableTriangleColorPolicy: "cadence" | "adaptive"; + stableTriangleColorFreezeFrames: number; + }; + if (effectiveClip && animation) { const applyAnimationFrame = async (frame: number): Promise => { const time = frame / ANIMATION_TICK_RATE; - mesh.setPolygons(rendered.animation.sample(effectiveClip.index, time), { - merge: false, - stableDom: true, - recomputeAutoCenter: false, - stableTriangleColorPolicy: "cadence", - stableTriangleColorFreezeFrames: 0, - }); + mesh.setPolygons(animation.sample(effectiveClip.index, time), animatedSetPolygonsOptions); await paint(); - const current = queryPolyLeaves(mesh.element).map((entry) => entry.element); + const current = queryPolyLeaves(mesh.element).map((entry) => entry.element as HTMLElement); if (current.length !== leaves.length || current.some((element, index) => element !== leaves[index])) { throw new Error(`Gallery preset ${id} did not preserve animated leaf identity.`); } @@ -468,20 +473,14 @@ async function capturePreset(id: string, retain = false): Promise= animationFrameCount) { throw new Error(`Gallery proof frame ${frame} is outside 0..${animationFrameCount - 1}.`); } - mesh.setPolygons(rendered.animation.sample(effectiveClip.index, frame / ANIMATION_TICK_RATE), { - merge: false, - stableDom: true, - recomputeAutoCenter: false, - stableTriangleColorPolicy: "cadence", - stableTriangleColorFreezeFrames: 0, - }); + mesh.setPolygons(animation.sample(effectiveClip.index, frame / ANIMATION_TICK_RATE), animatedSetPolygonsOptions); await paint(); }, destroy() { diff --git a/website/scripts/generate-llms-txt.mjs b/website/scripts/generate-llms-txt.mjs index 17c23bacd..92aa4d0fd 100644 --- a/website/scripts/generate-llms-txt.mjs +++ b/website/scripts/generate-llms-txt.mjs @@ -75,7 +75,7 @@ for (const file of files) { indexLines.push(`- [${title}](${url})`); } -indexLines.push('', '## Source', '', '- GitHub: https://github.com/LayoutitStudio/polycss', '- License: MIT', ''); +indexLines.push('', '## Source', '', '- GitHub: https://github.com/layoutit/polycss', '- License: MIT', ''); writeFileSync(join(DIST_DIR, 'llms.txt'), indexLines.join('\n')); diff --git a/website/src/components/BuilderWorkbench/defaults.ts b/website/src/components/BuilderWorkbench/defaults.ts index 47a2bed20..ed167fa1b 100644 --- a/website/src/components/BuilderWorkbench/defaults.ts +++ b/website/src/components/BuilderWorkbench/defaults.ts @@ -47,6 +47,7 @@ export const DEFAULT_SCENE: SceneOptionsState = { target: [0, 0, 0], disableStrategies: [], castShadow: true, + selfShadow: false, shadowMaxExtend: 600, shadowParametric: false, shadowDefinition: 16, diff --git a/website/src/components/DocsHeader.astro b/website/src/components/DocsHeader.astro index 7a91a71fa..ac7288ffb 100644 --- a/website/src/components/DocsHeader.astro +++ b/website/src/components/DocsHeader.astro @@ -63,7 +63,7 @@ const topLinks = [
async function fetchStars() { try { - const res = await fetch("https://api.github.com/repos/LayoutitStudio/polycss"); + const res = await fetch("https://api.github.com/repos/layoutit/polycss"); if (!res.ok) return; const json = await res.json(); if (typeof json?.stargazers_count === "number") { diff --git a/website/src/components/DropOverlay/DropOverlay.tsx b/website/src/components/DropOverlay/DropOverlay.tsx index 359a3e6a1..31b171da7 100644 --- a/website/src/components/DropOverlay/DropOverlay.tsx +++ b/website/src/components/DropOverlay/DropOverlay.tsx @@ -1,4 +1,6 @@ -export function DropOverlay({ active }: { active: boolean }): JSX.Element | null { +import type { ReactElement } from "react"; + +export function DropOverlay({ active }: { active: boolean }): ReactElement | null { if (!active) return null; return
Drop OBJ / GLB / VOX
; } diff --git a/website/src/components/GalleryWorkbench/hooks/useRouteSync.ts b/website/src/components/GalleryWorkbench/hooks/useRouteSync.ts index 70283de2a..180968aaa 100644 --- a/website/src/components/GalleryWorkbench/hooks/useRouteSync.ts +++ b/website/src/components/GalleryWorkbench/hooks/useRouteSync.ts @@ -239,7 +239,10 @@ function addNumber( if (!sameNumber(value, defaultValue)) out[key] = round(value) as SerializedGallerySceneOptions[K]; } -function addString( +function addString< + K extends keyof SerializedGallerySceneOptions, + T extends string & NonNullable, +>( out: SerializedGallerySceneOptions, key: K, value: T, @@ -386,9 +389,9 @@ function strategiesFromMask(value: string): string | undefined { } function encodeCompactValue(key: SerializedGallerySceneOptionKey, value: SerializedGallerySceneOptions[SerializedGallerySceneOptionKey]): string | undefined { + if (key === "p") return value === false ? "n" : typeof value === "number" ? encodePackedNumber(value) : undefined; if (typeof value === "boolean") return value ? "" : "0"; if (typeof value === "number") return encodePackedNumber(value); - if (key === "p") return value === false ? "n" : typeof value === "number" ? encodePackedNumber(value) : undefined; if (key === "t" && isVec3(value)) return value.map(encodePackedNumber).join(""); if (isColorOption(key)) return typeof value === "string" ? encodeCompactColor(value) : undefined; if (key === "ds") return typeof value === "string" ? strategiesMask(value) : undefined; diff --git a/website/src/content/docs/api/headless.mdx b/website/src/content/docs/api/headless.mdx index 2136b65b1..fee76ae8c 100644 --- a/website/src/content/docs/api/headless.mdx +++ b/website/src/content/docs/api/headless.mdx @@ -537,7 +537,7 @@ Register the custom elements by importing the side-effect entry point: ``` -See the [PolyCSS README](https://github.com/LayoutitStudio/polycss/tree/main/packages/polycss) for the full custom element attribute reference. +See the [PolyCSS README](https://github.com/layoutit/polycss/tree/main/packages/polycss) for the full custom element attribute reference. Registered element families include: diff --git a/website/src/pages/index.astro b/website/src/pages/index.astro index 7d9485176..7f2d5b48e 100644 --- a/website/src/pages/index.astro +++ b/website/src/pages/index.astro @@ -91,7 +91,7 @@ const ldJson = { url: siteUrl, image: ogImage, offers: { "@type": "Offer", price: "0", priceCurrency: "USD" }, - sameAs: ["https://github.com/LayoutitStudio/polycss"], + sameAs: ["https://github.com/layoutit/polycss"], publisher: { "@type": "Organization", name: "PolyCSS", @@ -155,7 +155,7 @@ const ldJson = {