From dfab1e03ce9cdaa2a03cb4e7553c9a89c099b9f7 Mon Sep 17 00:00:00 2001 From: alowpoly Date: Thu, 3 Dec 2026 13:27:08 -0300 Subject: [PATCH 1/9] feat(polycss): add adopt-DOM seams, runtime subpath, and control guards --- packages/polycss/package.json | 5 + packages/polycss/src/api/controls/common.ts | 8 +- packages/polycss/src/api/createPolyCamera.ts | 28 +- .../src/api/createPolyFirstPersonControls.ts | 24 +- .../polycss/src/api/createPolyMapControls.ts | 44 +- .../src/api/createPolyOrbitControls.ts | 96 +++- packages/polycss/src/api/createPolyScene.ts | 312 ++++++++---- packages/polycss/src/api/createSelect.ts | 19 +- .../src/api/createTransformControls.ts | 58 ++- packages/polycss/src/api/runtimeSeams.test.ts | 461 ++++++++++++++++++ .../polycss/src/api/scene/bakedLighting.ts | 4 +- packages/polycss/src/api/scene/cameraCull.ts | 9 +- .../polycss/src/api/scene/internalTypes.ts | 26 +- .../polycss/src/api/scene/mountLifecycle.ts | 28 +- packages/polycss/src/api/scene/mountSync.ts | 4 +- packages/polycss/src/api/scene/rebake.ts | 145 +++++- .../polycss/src/api/scene/sceneContext.ts | 8 +- .../src/api/scene/shadowGeometry.test.ts | 2 +- .../polycss/src/api/scene/shadowGeometry.ts | 15 - packages/polycss/src/api/scene/types.ts | 72 +++ packages/polycss/src/index.ts | 4 + packages/polycss/src/render/polyDOM.test.ts | 22 +- packages/polycss/src/render/polyDOM.ts | 37 -- packages/polycss/src/runtime.ts | 147 ++++++ packages/polycss/tsup.config.ts | 1 + 25 files changed, 1333 insertions(+), 246 deletions(-) create mode 100644 packages/polycss/src/api/runtimeSeams.test.ts delete mode 100644 packages/polycss/src/api/scene/shadowGeometry.ts delete mode 100644 packages/polycss/src/render/polyDOM.ts create mode 100644 packages/polycss/src/runtime.ts diff --git a/packages/polycss/package.json b/packages/polycss/package.json index d75410cfb..84b637216 100644 --- a/packages/polycss/package.json +++ b/packages/polycss/package.json @@ -27,6 +27,10 @@ "types": "./dist/index.d.ts", "import": "./dist/index.js" }, + "./runtime": { + "types": "./dist/runtime.d.ts", + "import": "./dist/runtime.js" + }, "./elements": { "types": "./dist/elements.d.ts", "import": "./dist/elements.js" @@ -38,6 +42,7 @@ }, "typesVersions": { "*": { + "runtime": ["dist/runtime.d.ts"], "three": ["dist/three.d.ts"], "elements": ["dist/elements.d.ts"] } diff --git a/packages/polycss/src/api/controls/common.ts b/packages/polycss/src/api/controls/common.ts index d41f4bbb0..34aaff1c1 100644 --- a/packages/polycss/src/api/controls/common.ts +++ b/packages/polycss/src/api/controls/common.ts @@ -8,7 +8,7 @@ * scene-handle glue (option resolution, listener registry, wheel handler, * rAF animate loop). */ -import type { PolySceneHandle } from "../createPolyScene"; +import type { PolyCameraControlTarget } from "../scene/types"; import { ANIM_DT_CLAMP_MS, ANIM_FRAME_MS, @@ -178,7 +178,7 @@ export function makeListenerRegistry(): { return { changeListeners, startListeners, endListeners, listenerArray, emitChange, emitInteraction }; } -export function makeCameraSnapshot(scene: PolySceneHandle): () => PolyControlsCamera { +export function makeCameraSnapshot(scene: PolyCameraControlTarget): () => PolyControlsCamera { return (): PolyControlsCamera => { const state = scene.camera.state; const t = state.target ?? [0, 0, 0]; @@ -194,7 +194,7 @@ export function makeCameraSnapshot(scene: PolySceneHandle): () => PolyControlsCa // ── Shared wheel handler builder ────────────────────────────────────────── export function makeWheelHandler( - scene: PolySceneHandle, + scene: PolyCameraControlTarget, getOpts: () => ResolvedOptions, isStopped: () => boolean, snapshot: () => PolyControlsCamera, @@ -248,7 +248,7 @@ export function makeWheelHandler( // ── Shared animate (rAF) loop builder ──────────────────────────────────── export function makeAnimLoop( win: typeof globalThis, - scene: PolySceneHandle, + scene: PolyCameraControlTarget, getOpts: () => ResolvedOptions, isStopped: () => boolean, isAnimPaused: () => boolean, diff --git a/packages/polycss/src/api/createPolyCamera.ts b/packages/polycss/src/api/createPolyCamera.ts index 856f0fa91..2d90c9373 100644 --- a/packages/polycss/src/api/createPolyCamera.ts +++ b/packages/polycss/src/api/createPolyCamera.ts @@ -31,17 +31,21 @@ export interface PolyPerspectiveCameraOptions extends PolyCameraOptions { export interface PolyOrthographicCameraOptions extends PolyCameraOptions {} -/** Extends CameraHandle with projection info for the container element. */ +/** Extends CameraHandle with projection info and change subscriptions. */ export interface PolyPerspectiveCameraHandle extends CameraHandle { readonly type: "perspective"; /** CSS `perspective` value to set on the camera container element. */ readonly perspectiveStyle: string; + /** Subscribe to camera state updates; returns an unsubscribe callback. */ + subscribe(listener: (state: CameraState) => void): () => void; } export interface PolyOrthographicCameraHandle extends CameraHandle { readonly type: "orthographic"; /** CSS `perspective` value to set on the camera container element ("none"). */ readonly perspectiveStyle: "none"; + /** Subscribe to camera state updates; returns an unsubscribe callback. */ + subscribe(listener: (state: CameraState) => void): () => void; } /** @@ -61,11 +65,20 @@ export function createPolyPerspectiveCamera( const inner: CameraHandle = createIsometricCamera(initial); const perspectiveValue = `${options.perspective ?? DEFAULT_PERSPECTIVE}px`; + const listeners = new Set<(state: CameraState) => void>(); return { get state() { return inner.state; }, - update(next: Partial): void { inner.update(next); }, + update(next: Partial): void { + inner.update(next); + const snapshot = inner.state; + for (const fn of listeners) fn(snapshot); + }, getStyle(input?: CameraStyleInput) { return inner.getStyle(input); }, + subscribe(listener: (state: CameraState) => void): () => void { + listeners.add(listener); + return () => { listeners.delete(listener); }; + }, type: "perspective" as const, perspectiveStyle: perspectiveValue, }; @@ -87,11 +100,20 @@ export function createPolyOrthographicCamera( if (options.distance !== undefined) initial.distance = options.distance; const inner: CameraHandle = createIsometricCamera(initial); + const listeners = new Set<(state: CameraState) => void>(); return { get state() { return inner.state; }, - update(next: Partial): void { inner.update(next); }, + update(next: Partial): void { + inner.update(next); + const snapshot = inner.state; + for (const fn of listeners) fn(snapshot); + }, getStyle(input?: CameraStyleInput) { return inner.getStyle(input); }, + subscribe(listener: (state: CameraState) => void): () => void { + listeners.add(listener); + return () => { listeners.delete(listener); }; + }, type: "orthographic" as const, perspectiveStyle: "none" as const, }; diff --git a/packages/polycss/src/api/createPolyFirstPersonControls.ts b/packages/polycss/src/api/createPolyFirstPersonControls.ts index c74daf359..3e5e4376a 100644 --- a/packages/polycss/src/api/createPolyFirstPersonControls.ts +++ b/packages/polycss/src/api/createPolyFirstPersonControls.ts @@ -10,7 +10,7 @@ * semantics use `createPolyMapControls`. */ -import type { PolySceneHandle } from "./createPolyScene"; +import type { PolyCameraControlTarget } from "./scene/types"; import { BASE_TILE, FIRST_PERSON_DEFAULTS, @@ -81,7 +81,7 @@ export interface PolyFirstPersonControlsHandle { } export function createPolyFirstPersonControls( - scene: PolySceneHandle, + scene: PolyCameraControlTarget, options: PolyFirstPersonControlsOptions = {}, ): PolyFirstPersonControlsHandle { let opts: PolyFirstPersonResolvedOptions = resolveFirstPersonOptions(FIRST_PERSON_DEFAULTS, options); @@ -99,6 +99,7 @@ export function createPolyFirstPersonControls( const keysHeld = new Set(); let pointerLocked = false; let stopped = false; + let cursorApplied = false; // Vertical state (separate from origin.z so we can stack crouch + jump). // verticalVel is non-zero only mid-air; jumpOffset accumulates from gravity. @@ -317,6 +318,16 @@ export function createPolyFirstPersonControls( fpvHost.style.removeProperty("--polycss-fpv-perspective"); } + function syncCursor(): void { + if (!stopped && opts.lookEnabled) { + host.style.cursor = "crosshair"; + cursorApplied = true; + } else if (cursorApplied) { + host.style.cursor = ""; + cursorApplied = false; + } + } + function attach(): void { host.addEventListener("click", onHostClick); doc.addEventListener("pointerlockchange", onPointerLockChange); @@ -324,7 +335,7 @@ export function createPolyFirstPersonControls( win.addEventListener("keydown", onKeyDown); win.addEventListener("keyup", onKeyUp); win.addEventListener("blur", onBlur); - host.style.cursor = opts.lookEnabled ? "crosshair" : ""; + syncCursor(); applyFpvHostPerspective(); } @@ -335,7 +346,10 @@ export function createPolyFirstPersonControls( win.removeEventListener("keydown", onKeyDown); win.removeEventListener("keyup", onKeyUp); win.removeEventListener("blur", onBlur); - host.style.cursor = ""; + if (cursorApplied) { + host.style.cursor = ""; + cursorApplied = false; + } keysHeld.clear(); if (pointerLocked) { try { doc.exitPointerLock(); } catch { /* ignore */ } @@ -351,7 +365,7 @@ export function createPolyFirstPersonControls( const prevHeight = opts.eyeHeight; const prevGround = opts.groundZ; opts = resolveFirstPersonOptions(opts, partial); - if (!stopped) host.style.cursor = opts.lookEnabled ? "crosshair" : ""; + syncCursor(); if (opts.eyeHeight !== prevHeight || opts.groundZ !== prevGround) { // Re-snap the camera's vertical position when the floor or standing // height changes (e.g. slider drag). Horizontal position is preserved. diff --git a/packages/polycss/src/api/createPolyMapControls.ts b/packages/polycss/src/api/createPolyMapControls.ts index fd3d5922b..34ff984ec 100644 --- a/packages/polycss/src/api/createPolyMapControls.ts +++ b/packages/polycss/src/api/createPolyMapControls.ts @@ -10,7 +10,7 @@ */ import { applyOrbit, applyPan } from "@layoutit/polycss-core"; -import type { PolySceneHandle } from "./createPolyScene"; +import type { PolyCameraControlTarget } from "./scene/types"; import { BASE_DEFAULTS, resolveOptions, @@ -39,7 +39,7 @@ export type PolyMapControlsOptions = PolyControlsBaseOptions; export type PolyMapControlsHandle = PolyControlsHandle; export function createPolyMapControls( - scene: PolySceneHandle, + scene: PolyCameraControlTarget, options: PolyMapControlsOptions = {}, ): PolyMapControlsHandle { let opts: ResolvedOptions = resolveOptions(BASE_DEFAULTS, options); @@ -48,6 +48,7 @@ export function createPolyMapControls( let activePointerId: number | null = null; let pointer = { x: 0, y: 0 }; + let dragStylesApplied = false; let animPaused = false; let stopped = false; @@ -69,15 +70,31 @@ export function createPolyMapControls( emitChange, ); + function syncDragStyles(): void { + if (!stopped && opts.drag) { + host.style.cursor = activePointerId !== null ? "grabbing" : "grab"; + host.style.touchAction = "none"; + host.style.userSelect = "none"; + dragStylesApplied = true; + } else if (dragStylesApplied) { + host.style.cursor = ""; + host.style.touchAction = ""; + host.style.userSelect = ""; + dragStylesApplied = false; + } + } + // ── Left-drag: pan ──────────────────────────────────────────────────────── const onPointerDown = (e: PointerEvent): void => { if (!opts.drag || stopped) return; + if (e.button === 2) return; if (activePointerId !== null) return; if (e.isPrimary === false) return; e.preventDefault(); activePointerId = e.pointerId; pointer = { x: e.clientX, y: e.clientY }; host.style.cursor = "grabbing"; + dragStylesApplied = true; try { (e.target as Element).setPointerCapture(e.pointerId); } catch { /* ignore */ } if (opts.animate && opts.animate.pauseOnInteraction) { animPaused = true; @@ -117,7 +134,7 @@ export function createPolyMapControls( const onPointerUp = (e: PointerEvent): void => { if (activePointerId !== e.pointerId) return; activePointerId = null; - host.style.cursor = opts.drag && !stopped ? "grab" : ""; + syncDragStyles(); try { (e.target as Element).releasePointerCapture(e.pointerId); } catch { /* ignore */ } if (opts.animate && opts.animate.pauseOnInteraction) { animPaused = false; @@ -126,9 +143,13 @@ export function createPolyMapControls( }; // ── Right-drag: orbit ──────────────────────────────────────────────────── - const onContextMenu = (e: Event): void => { e.preventDefault(); }; + const onContextMenu = (e: Event): void => { + if (!opts.drag || stopped) return; + e.preventDefault(); + }; const onMouseDown = (e: MouseEvent): void => { + if (!opts.drag || stopped) return; if (e.button !== 2) return; rightDragActive = true; rightPointer = { x: e.clientX, y: e.clientY }; @@ -177,9 +198,7 @@ export function createPolyMapControls( host.addEventListener("mousedown", onMouseDown); host.addEventListener("mousemove", onMouseMove); host.addEventListener("mouseup", onMouseUp); - host.style.cursor = opts.drag ? "grab" : ""; - host.style.touchAction = "none"; - host.style.userSelect = "none"; + syncDragStyles(); } function detach(): void { @@ -192,9 +211,12 @@ export function createPolyMapControls( host.removeEventListener("mousedown", onMouseDown); host.removeEventListener("mousemove", onMouseMove); host.removeEventListener("mouseup", onMouseUp); - host.style.cursor = ""; - host.style.touchAction = ""; - host.style.userSelect = ""; + if (dragStylesApplied) { + host.style.cursor = ""; + host.style.touchAction = ""; + host.style.userSelect = ""; + dragStylesApplied = false; + } wheelHandler.teardown(); } @@ -205,7 +227,7 @@ export function createPolyMapControls( const wasAnimating = !!opts.animate; opts = resolveOptions(opts, partial); if (!stopped && activePointerId === null) { - host.style.cursor = opts.drag ? "grab" : ""; + syncDragStyles(); } const isAnimating = !!opts.animate; if (wasAnimating && !isAnimating) { diff --git a/packages/polycss/src/api/createPolyOrbitControls.ts b/packages/polycss/src/api/createPolyOrbitControls.ts index ae8ccbb84..1a1b49f73 100644 --- a/packages/polycss/src/api/createPolyOrbitControls.ts +++ b/packages/polycss/src/api/createPolyOrbitControls.ts @@ -9,7 +9,7 @@ */ import { applyOrbit, applyPan } from "@layoutit/polycss-core"; -import type { PolySceneHandle } from "./createPolyScene"; +import type { PolyCameraControlTarget } from "./scene/types"; import { BASE_DEFAULTS, resolveOptions, @@ -38,7 +38,7 @@ export type PolyOrbitControlsOptions = PolyControlsBaseOptions; export type PolyOrbitControlsHandle = PolyControlsHandle; export function createPolyOrbitControls( - scene: PolySceneHandle, + scene: PolyCameraControlTarget, options: PolyOrbitControlsOptions = {}, ): PolyOrbitControlsHandle { let opts: ResolvedOptions = resolveOptions(BASE_DEFAULTS, options); @@ -47,6 +47,9 @@ export function createPolyOrbitControls( let activePointerId: number | null = null; let pointer = { x: 0, y: 0 }; + let rightDragActive = false; + let rightPointer = { x: 0, y: 0 }; + let dragStylesApplied = false; let animPaused = false; let stopped = false; @@ -64,15 +67,31 @@ export function createPolyOrbitControls( emitChange, ); + function syncDragStyles(): void { + if (!stopped && opts.drag) { + host.style.cursor = activePointerId !== null ? "grabbing" : "grab"; + host.style.touchAction = "none"; + host.style.userSelect = "none"; + dragStylesApplied = true; + } else if (dragStylesApplied) { + host.style.cursor = ""; + host.style.touchAction = ""; + host.style.userSelect = ""; + dragStylesApplied = false; + } + } + // ── Pointer drag (orbit) ───────────────────────────────────────────────── const onPointerDown = (e: PointerEvent): void => { if (!opts.drag || stopped) return; + if (e.button === 2) return; if (activePointerId !== null) return; if (e.isPrimary === false) return; e.preventDefault(); activePointerId = e.pointerId; pointer = { x: e.clientX, y: e.clientY }; host.style.cursor = "grabbing"; + dragStylesApplied = true; try { (e.target as Element).setPointerCapture(e.pointerId); } catch { /* ignore */ } if (opts.animate && opts.animate.pauseOnInteraction) { animPaused = true; @@ -119,7 +138,7 @@ export function createPolyOrbitControls( const onPointerUp = (e: PointerEvent): void => { if (activePointerId !== e.pointerId) return; activePointerId = null; - host.style.cursor = opts.drag && !stopped ? "grab" : ""; + syncDragStyles(); try { (e.target as Element).releasePointerCapture(e.pointerId); } catch { /* ignore */ } if (opts.animate && opts.animate.pauseOnInteraction) { animPaused = false; @@ -128,6 +147,53 @@ export function createPolyOrbitControls( emitInteraction("end", snapshot); }; + // ── Right-drag: pan ────────────────────────────────────────────────────── + const onContextMenu = (e: Event): void => { + if (!opts.drag || stopped) return; + e.preventDefault(); + }; + + const onMouseDown = (e: MouseEvent): void => { + if (!opts.drag || stopped) return; + if (e.button !== 2) return; + rightDragActive = true; + rightPointer = { x: e.clientX, y: e.clientY }; + if (opts.animate && opts.animate.pauseOnInteraction) { + animPaused = true; + } + emitInteraction("start", snapshot); + }; + + const onMouseMove = (e: MouseEvent): void => { + if (!rightDragActive || !opts.drag || stopped) return; + const dx = e.clientX - rightPointer.x; + const dy = e.clientY - rightPointer.y; + rightPointer = { x: e.clientX, y: e.clientY }; + const cameraState = scene.camera.state; + const { targetD0, targetD1 } = applyPan( + dx, + dy, + cameraState.zoom ?? 1, + cameraState.rotX ?? 65, + cameraState.rotY ?? 45, + ); + const t = cameraState.target ?? [0, 0, 0]; + scene.camera.update({ target: [t[0] + targetD0, t[1] + targetD1, t[2]] }); + scene.applyCamera(); + emitChange(snapshot); + }; + + const onMouseUp = (e: MouseEvent): void => { + if (e.button !== 2) return; + if (rightDragActive) { + rightDragActive = false; + if (opts.animate && opts.animate.pauseOnInteraction) { + animPaused = false; + } + emitInteraction("end", snapshot); + } + }; + const wheelHandler = makeWheelHandler( scene, () => opts, @@ -143,9 +209,11 @@ export function createPolyOrbitControls( host.addEventListener("pointerup", onPointerUp); host.addEventListener("pointercancel", onPointerUp); host.addEventListener("wheel", wheelHandler.onWheel, { passive: false }); - host.style.cursor = opts.drag ? "grab" : ""; - host.style.touchAction = "none"; - host.style.userSelect = "none"; + host.addEventListener("contextmenu", onContextMenu); + host.addEventListener("mousedown", onMouseDown); + host.addEventListener("mousemove", onMouseMove); + host.addEventListener("mouseup", onMouseUp); + syncDragStyles(); } function detach(): void { @@ -154,9 +222,16 @@ export function createPolyOrbitControls( host.removeEventListener("pointerup", onPointerUp); host.removeEventListener("pointercancel", onPointerUp); host.removeEventListener("wheel", wheelHandler.onWheel); - host.style.cursor = ""; - host.style.touchAction = ""; - host.style.userSelect = ""; + host.removeEventListener("contextmenu", onContextMenu); + host.removeEventListener("mousedown", onMouseDown); + host.removeEventListener("mousemove", onMouseMove); + host.removeEventListener("mouseup", onMouseUp); + if (dragStylesApplied) { + host.style.cursor = ""; + host.style.touchAction = ""; + host.style.userSelect = ""; + dragStylesApplied = false; + } wheelHandler.teardown(); } @@ -167,7 +242,7 @@ export function createPolyOrbitControls( const wasAnimating = !!opts.animate; opts = resolveOptions(opts, partial); if (!stopped && activePointerId === null) { - host.style.cursor = opts.drag ? "grab" : ""; + syncDragStyles(); } const isAnimating = !!opts.animate; if (wasAnimating && !isAnimating) { @@ -190,6 +265,7 @@ export function createPolyOrbitControls( detach(); animLoop.stop(); activePointerId = null; + rightDragActive = false; animPaused = false; wheelHandler.teardown(); } diff --git a/packages/polycss/src/api/createPolyScene.ts b/packages/polycss/src/api/createPolyScene.ts index 43881ec5b..7e3bbebaa 100644 --- a/packages/polycss/src/api/createPolyScene.ts +++ b/packages/polycss/src/api/createPolyScene.ts @@ -92,8 +92,12 @@ import { } from "./scene/mountSync"; import { canRenderVoxelDirect, - localPointLightsForEntry, + collectAtlasUrlsFromRendered, + decodeAtlasUrls, + effectiveTextureLighting, + renderEntryAtomic, requestRebakeAtlas, + resolveMeshRenderOptions, } from "./scene/rebake"; import { applyMeshLightVarOverride, @@ -104,6 +108,7 @@ import { import { tryUpdatePolygonLeafOnly } from "./scene/polygonPatch"; import { disposeReceiverShadowMounts } from "./scene/receiverShadow"; import { + clearAllSceneShadows, clearCasterItemsCache as clearCasterItemsCacheImpl, clearReceiverShadowCache as clearReceiverShadowCacheImpl, } from "./scene/shadowCache"; @@ -120,21 +125,47 @@ import type { InternalPolyMeshHandle, InternalSetPolygonsOptions, PolyAnimationTriangleFrame, + PolyCameraControlTarget, PolyMeshHandle, PolyMeshTransform, + PolySceneElements, PolySceneHandle, PolySceneOptions, } from "./scene/types"; import { POLY_ANIMATION_TRIANGLE_FRAME_TARGET } from "./scene/types"; export type { + PolyCameraControlTarget, PolyMeshHandle, PolyMeshTransform, + PolySceneElements, PolySceneHandle, PolySceneOptions, PolyShadowOptions, } from "./scene/types"; +function recenterPolygons(polygons: Polygon[]): Polygon[] { + if (polygons.length === 0) return polygons; + const bbox = computeSceneBbox(polygons); + const cx = (bbox.min[0] + bbox.max[0]) / 2; + const cy = (bbox.min[1] + bbox.max[1]) / 2; + const cz = (bbox.min[2] + bbox.max[2]) / 2; + if (cx === 0 && cy === 0 && cz === 0) return polygons; + const shift = (v: Vec3): Vec3 => [v[0] - cx, v[1] - cy, v[2] - cz]; + return polygons.map((p) => ({ + ...p, + vertices: p.vertices.map(shift), + ...(p.textureTriangles?.length + ? { + textureTriangles: p.textureTriangles.map((tri) => ({ + ...tri, + vertices: [shift(tri.vertices[0]), shift(tri.vertices[1]), shift(tri.vertices[2])] as [Vec3, Vec3, Vec3], + })), + } + : {}), + })); +} + function normalizeSceneOptions>>(options: T): T { if (!Object.prototype.hasOwnProperty.call(options, "seamBleed") || options.seamBleed !== undefined) { return options; @@ -159,6 +190,8 @@ export function createPolyScene( const camera = options.camera; + const adoptedElements = !!options.elements; + // Inject base styles into the host's owning document so .polycss-scene // has perspective + preserve-3d defaults. if (host.ownerDocument) injectPolyBaseStyles(host.ownerDocument); @@ -167,44 +200,43 @@ export function createPolyScene( // be a positioned ancestor or the offsets resolve against the document. // Force `position: relative` only if the host has no positioning yet, so // we don't clobber a deliberate `absolute`/`fixed`/`sticky` from the user. - if (host.ownerDocument?.defaultView) { + if (!adoptedElements && host.ownerDocument?.defaultView) { const computed = host.ownerDocument.defaultView.getComputedStyle(host); if (computed.position === "static") host.style.position = "relative"; } // currentOptions holds non-camera scene options only. // eslint-disable-next-line @typescript-eslint/no-unused-vars - const { camera: _cameraOption, ...nonCameraOptions } = options; + const { camera: _cameraOption, elements: _elementsOption, ...nonCameraOptions } = options; let currentOptions: Omit = normalizeSceneOptions({ seamBleed: DEFAULT_SEAM_BLEED, ...nonCameraOptions, }); const layoutScale = effectiveCssZoom(host); - // Bbox-center of all live meshes (helpers opt out). Auto-managed by - // `recomputeAutoCenter`. Folded into the scene transform alongside - // `target` so the camera orbits the model's visible center without - // shifting the mesh DOM. Independent of `target` so user pan survives - // mesh add/remove. Declared here (above the first `applySceneStyle` - // call) so it's initialized before the closure reads it. + // Bbox-center of all live meshes (helpers opt out), or explicit polygons + // when `autoCenterSource === "explicit"`. Folded into the scene transform + // alongside `target` so the camera orbits the model's visible center without + // shifting the mesh DOM. let autoCenterOffset: Vec3 = [0, 0, 0]; + let explicitCenterPolygons: readonly Polygon[] | null = null; const doc = host.ownerDocument ?? document; // Camera wrapper: carries the CSS `perspective` so it foreshortens the - // scene's direct 3D children correctly. Matches React/Vue's - // `
` wrapper emitted by PolyPerspectiveCamera. - const cameraEl = doc.createElement("div"); - cameraEl.className = "polycss-camera"; + // scene's direct 3D children correctly. When `options.elements` is passed, + // adopt caller-owned elements without creating duplicate wrappers. + const cameraEl = options.elements ? options.elements.cameraEl : doc.createElement("div"); + cameraEl.classList.add("polycss-camera"); applyCameraStyle(cameraEl, currentOptions); - host.appendChild(cameraEl); + if (!adoptedElements) host.appendChild(cameraEl); - const sceneEl = doc.createElement("div"); - sceneEl.className = "polycss-scene"; - sceneEl.setAttribute("aria-hidden", "true"); + const sceneEl = options.elements ? options.elements.sceneEl : doc.createElement("div"); + sceneEl.classList.add("polycss-scene"); + if (!adoptedElements) sceneEl.setAttribute("aria-hidden", "true"); // 0×0 anchor at the host's visible center. Polygons render around it. applySceneStyle(sceneEl, currentOptions); - cameraEl.appendChild(sceneEl); + if (!adoptedElements) cameraEl.appendChild(sceneEl); // Bundle every mutable scene-state field into a SceneContext. Extracted // scene/* helpers take this object as their first arg instead of capturing @@ -374,23 +406,15 @@ export function createPolyScene( renderer.render(cameraCullRotation(ctx, entry)); entry.cameraCullSignature = "voxel-direct"; entry.textureReadyPromise = TEXTURES_READY; + if (entry.atomicAtlas && entry.onFrameReady) entry.onFrameReady(); return; } } + const resolvedRenderOptions = resolveMeshRenderOptions(ctx, entry, lightDirectionOverride); + const entryLighting = resolvedRenderOptions.textureLighting; const renderOptions = { - doc, - directionalLight, - pointLights: localPointLightsForEntry(ctx, entry), - ambientLight: currentOptions.ambientLight, - textureLighting: currentOptions.textureLighting, - textureQuality: currentOptions.textureQuality, - textureLeafSizing: currentOptions.textureLeafSizing, - textureImageRendering: currentOptions.textureImageRendering, - textureBackend: currentOptions.textureBackend, - textureProjection: currentOptions.textureProjection, - seamBleed: currentOptions.seamBleed, - strategies: currentOptions.strategies, + ...resolvedRenderOptions, lightOccludedPolyIndices, }; const atlas = entry.stableDom @@ -408,7 +432,7 @@ export function createPolyScene( : renderPolygonsWithTextureAtlas(entry.polygons, { ...renderOptions, computeSolidPaintDefaults: true, - skipDynamicNormalVars: currentOptions.textureLighting === "dynamic", + skipDynamicNormalVars: entryLighting === "dynamic", } as typeof renderOptions & { computeSolidPaintDefaults: true }); if (!entry.stableDom) { applySolidPaintVars( @@ -418,10 +442,28 @@ export function createPolyScene( } setRendered(entry, atlas.rendered, atlas.dispose, atlas.pagesReady); entry.skipBucketNormalCleanupOnce = - currentOptions.textureLighting === "dynamic" && !entry.stableDom; + entryLighting === "dynamic" && !entry.stableDom; recomputeCameraCullGroups(entry); syncMountedRendered(ctx, entry); emitShadowLeaves(ctx, entry); + if (entry.atomicAtlas && entry.onFrameReady) { + const version = entry.atomicSwapVersion; + const ready = (atlas as { pagesReady?: Promise }).pagesReady; + if (ready && typeof ready.then === "function") { + ready + .then(() => { + if (entry.disposed || version !== entry.atomicSwapVersion) return; + return decodeAtlasUrls(collectAtlasUrlsFromRendered(atlas.rendered)); + }) + .then(() => { + if (!entry.disposed && version === entry.atomicSwapVersion) entry.onFrameReady?.(); + }, () => { + if (!entry.disposed && version === entry.atomicSwapVersion) entry.onFrameReady?.(); + }); + } else { + entry.onFrameReady(); + } + } } async function renderEntryChunked( @@ -429,20 +471,10 @@ export function createPolyScene( shouldCancel: () => boolean, ): Promise { clearRendered(ctx, entry); - const directionalLight = worldDirectionalLightToCss(currentOptions.directionalLight); + const resolvedRenderOptions = resolveMeshRenderOptions(ctx, entry); + const entryLighting = resolvedRenderOptions.textureLighting; const renderOptions = { - doc, - directionalLight, - pointLights: localPointLightsForEntry(ctx, entry), - ambientLight: currentOptions.ambientLight, - textureLighting: currentOptions.textureLighting, - textureQuality: currentOptions.textureQuality, - textureLeafSizing: currentOptions.textureLeafSizing, - textureImageRendering: currentOptions.textureImageRendering, - textureBackend: currentOptions.textureBackend, - textureProjection: currentOptions.textureProjection, - seamBleed: currentOptions.seamBleed, - strategies: currentOptions.strategies, + ...resolvedRenderOptions, // Per-light raytrace occlusion (task #121) disabled — see renderEntry. lightOccludedPolyIndices: undefined as ReadonlySet | undefined, }; @@ -463,7 +495,7 @@ export function createPolyScene( entry.polygons, { ...renderOptions, - skipDynamicNormalVars: currentOptions.textureLighting === "dynamic", + skipDynamicNormalVars: entryLighting === "dynamic", } as typeof renderOptions & { skipDynamicNormalVars: boolean }, shouldCancel, ); @@ -474,7 +506,7 @@ export function createPolyScene( applySolidPaintVars(entry.wrapper, asyncAtlas.solidPaintDefaults); setRendered(entry, asyncAtlas.rendered, asyncAtlas.dispose, asyncAtlas.pagesReady); entry.skipBucketNormalCleanupOnce = - currentOptions.textureLighting === "dynamic" && !entry.stableDom; + entryLighting === "dynamic" && !entry.stableDom; recomputeCameraCullGroups(entry); const mounted = await syncMountedRenderedChunked(ctx, entry, shouldCancel); if (mounted) emitShadowLeaves(ctx, entry); @@ -491,8 +523,14 @@ export function createPolyScene( let next: Vec3 = [0, 0, 0]; if (currentOptions.autoCenter) { const all: Polygon[] = []; - for (const m of meshes) { - if (!m.disposed && !m.excludeFromAutoCenter) all.push(...m.polygons); + if (currentOptions.autoCenterSource === "explicit") { + if (explicitCenterPolygons && explicitCenterPolygons.length > 0) { + all.push(...explicitCenterPolygons); + } + } else { + for (const m of meshes) { + if (!m.disposed && !m.excludeFromAutoCenter) all.push(...m.polygons); + } } if (all.length > 0) { const bbox = computeSceneBbox(all); @@ -507,12 +545,18 @@ export function createPolyScene( autoCenterOffset = next; ctx.autoCenter.offset = next; applySceneStyle(sceneEl, currentOptions); + currentOptions.onAutoCenterOffsetChange?.(next); } function add(parseResult: ParseResult, transformIn: PolyMeshTransform = {}): PolyMeshHandle { const mountDoc = sceneEl.ownerDocument ?? document; - const wrapper = mountDoc.createElement("div"); - wrapper.className = "polycss-mesh"; + const adoptedWrapper = !!transformIn.wrapper; + const wrapper = transformIn.wrapper ?? mountDoc.createElement("div"); + if (adoptedWrapper) { + wrapper.classList.add("polycss-mesh"); + } else { + wrapper.className = "polycss-mesh"; + } if (transformIn.id) wrapper.setAttribute("data-poly-mesh-id", transformIn.id); const autoMeshId = `polycss-mesh-${ctx.meshAutoCounter.next++}`; wrapper.setAttribute("data-poly-mesh-index", autoMeshId); @@ -520,43 +564,18 @@ export function createPolyScene( let transform: PolyMeshTransform = { ...transformIn }; let mergeOnUpdate = transformIn.merge !== false; let stableDomOnUpdate = !!transformIn.stableDom; + let autoCenterOnUpdate = !!transformIn.autoCenter; let polygonUpdateVersion = 0; const css = buildMeshTransform(transform); if (css) wrapper.style.transform = css; - // Static meshes use the full optimizer by default; meshResolution selects - // the quality intent. Explicit merge:false remains the escape hatch for - // animated topology updates and helper meshes that are already prepared. - // - // Interior culling is applied independently of `merge`. It removes - // polygons that are fully enclosed by other geometry of the same - // mesh (e.g. cottage interior walls, doors, frames) — those serve - // no rendering purpose and they generate phantom shadow casts on - // any receiver the ray-test would project them onto. Three.js gets - // this for free from its depth pass; PolyCSS needs the explicit - // cull. Skipped on voxel-source meshes (every voxel face is - // visible by construction) and on stable-DOM meshes (animation - // frame topology must stay constant). const preparePolygons = (polygons: Polygon[], merge: boolean): Polygon[] => { - if (parseResult.voxelSource) return polygons; - if (merge) return optimizeMeshPolygons(polygons, { meshResolution: transformIn.meshResolution }); - if (stableDomOnUpdate) return polygons; - // Helpers (axes, lights, transform gizmos) are author-curated - // tiny meshes whose polygons are all meant to be visible — they - // commonly have faces that point "inward" toward the helper's - // bbox center (arrow heads, axis crosses) which the interior - // cull would falsely drop. `excludeFromAutoCenter` is the - // existing flag library helpers set on themselves; reuse it as - // the "skip topology pruning" signal. - if (transformIn.excludeFromAutoCenter) return polygons; - // No automatic interior cull for merge:false meshes — callers - // commonly use that flag to preserve raw author-curated geometry - // (the bench parity E is 4 overlapping boxes; cull falsely - // identifies some box-junction faces as enclosed). Building OBJs - // that DO want interior cull go through optimizeMeshPolygons - // via merge:true (the default), which already runs cull as part - // of its preprocess. - return polygons; + const centered = autoCenterOnUpdate ? recenterPolygons(polygons) : polygons; + if (parseResult.voxelSource) return centered; + if (merge) return optimizeMeshPolygons(centered, { meshResolution: transform.meshResolution }); + if (stableDomOnUpdate) return centered; + if (transform.excludeFromAutoCenter) return centered; + return centered; }; const sourcePolygons = preparePolygons(parseResult.polygons, mergeOnUpdate); @@ -608,11 +627,13 @@ export function createPolyScene( let entryRef: MeshEntry | null = null; applyTransformOrigin(sourcePolygons); - sceneEl.appendChild(wrapper); + if (!adoptedWrapper) sceneEl.appendChild(wrapper); const entry: MeshEntry = { handle: undefined as unknown as PolyMeshHandle, wrapper, + adoptedWrapper, + ownedNodes: new Set(), parseResult, rendered: [], renderedByPolygonIndex: [], @@ -621,6 +642,19 @@ export function createPolyScene( voxelSource: parseResult.voxelSource, disposed: false, stableDom: stableDomOnUpdate, + autoCenter: autoCenterOnUpdate, + atomicAtlas: !!transformIn.atomicAtlas, + onFrameReady: transformIn.onFrameReady, + atomicSwapVersion: 0, + renderOverrides: { + textureLighting: transformIn.textureLighting, + textureQuality: transformIn.textureQuality, + textureLeafSizing: transformIn.textureLeafSizing, + textureImageRendering: transformIn.textureImageRendering, + textureBackend: transformIn.textureBackend, + textureProjection: transformIn.textureProjection, + seamBleed: transformIn.seamBleed, + }, hasBuckets: false, skipBucketNormalCleanupOnce: false, excludeFromAutoCenter: !!transformIn.excludeFromAutoCenter, @@ -770,7 +804,8 @@ export function createPolyScene( get transform() { return transform; }, remove() { polygonUpdateVersion++; - if (wrapper.parentNode) wrapper.parentNode.removeChild(wrapper); + entry.atomicSwapVersion++; + if (!entry.adoptedWrapper && wrapper.parentNode) wrapper.parentNode.removeChild(wrapper); // Removing from DOM doesn't auto-dispose generated atlas/blob URLs. clearRendered(ctx, entry); meshes.delete(entry); @@ -797,7 +832,11 @@ export function createPolyScene( // current frame's geometry here; the caster-item cache was just cleared. maybeEmitAnimationShadow(ctx, entry); if (applyStableTopologyUpdate(options, shouldRecomputeAutoCenter)) return; - renderEntry(entry); + if (entry.atomicAtlas && (entry.rendered.length > 0 || entry.voxelRenderer)) { + renderEntryAtomic(ctx, entry); + } else { + renderEntry(entry); + } if (shouldRecomputeAutoCenter) recomputeAutoCenter(); }, [POLY_ANIMATION_TRIANGLE_FRAME_TARGET]( @@ -988,14 +1027,46 @@ export function createPolyScene( const prevCastShadow = entry.castShadow; const prevReceiveShadow = entry.receiveShadow; const prevShadowDef = entry.shadowDefinition; + const prevExclude = entry.excludeFromAutoCenter; if (t.castShadow !== undefined) entry.castShadow = !!t.castShadow; if (t.receiveShadow !== undefined) entry.receiveShadow = !!t.receiveShadow; if (t.shadowDefinition !== undefined) entry.shadowDefinition = t.shadowDefinition; + if (t.excludeFromAutoCenter !== undefined) entry.excludeFromAutoCenter = !!t.excludeFromAutoCenter; + if (t.autoCenter !== undefined) { + autoCenterOnUpdate = !!t.autoCenter; + entry.autoCenter = autoCenterOnUpdate; + } + if (t.atomicAtlas !== undefined) entry.atomicAtlas = !!t.atomicAtlas; + if (Object.prototype.hasOwnProperty.call(t, "onFrameReady")) entry.onFrameReady = t.onFrameReady; + let renderOverrideChanged = false; + const overrideKeys = [ + "textureLighting", + "textureQuality", + "textureLeafSizing", + "textureImageRendering", + "textureBackend", + "textureProjection", + "seamBleed", + ] as const; + for (const key of overrideKeys) { + if (Object.prototype.hasOwnProperty.call(t, key) && entry.renderOverrides[key] !== t[key]) { + (entry.renderOverrides as Record)[key] = t[key]; + renderOverrideChanged = true; + } + } transform = { ...transform, ...t }; const css2 = buildMeshTransform(transform); wrapper.style.transform = css2 ?? ""; applyMeshLightVarOverride(ctx, entry, transform.rotation); + if (renderOverrideChanged) { + if (entry.atomicAtlas && (entry.rendered.length > 0 || entry.voxelRenderer)) { + renderEntryAtomic(ctx, entry); + } else { + renderEntry(entry); + } + } if (t.rotation !== undefined) syncMountedRenderedForCameraChange(ctx, entry, true); + if (entry.excludeFromAutoCenter !== prevExclude) recomputeAutoCenter(); if (entry.castShadow !== prevCastShadow) { // Voxel-eligible meshes use the direct-matrix fast path only when // castShadow is false (canRenderVoxelDirect). Toggling castShadow @@ -1045,7 +1116,8 @@ export function createPolyScene( if (entry.disposed) return; entry.disposed = true; polygonUpdateVersion++; - if (wrapper.parentNode) wrapper.parentNode.removeChild(wrapper); + entry.atomicSwapVersion++; + if (!entry.adoptedWrapper && wrapper.parentNode) wrapper.parentNode.removeChild(wrapper); clearRendered(ctx, entry); try { parseResult.dispose(); } catch { /* ignore */ } meshes.delete(entry); @@ -1099,6 +1171,7 @@ export function createPolyScene( function setOptions(partial: Partial>): void { const prevAutoCenter = !!currentOptions.autoCenter; + const prevAutoCenterSource = currentOptions.autoCenterSource; const prevStrategies = currentOptions.strategies; const prevSeamBleed = currentOptions.seamBleed; const prevTextureLeafSizing = currentOptions.textureLeafSizing; @@ -1109,6 +1182,8 @@ export function createPolyScene( const prevLightDir = currentOptions.directionalLight?.direction; const prevDirIntensity = currentOptions.directionalLight?.intensity; const prevDirColor = currentOptions.directionalLight?.color; + const prevAmbIntensity = currentOptions.ambientLight?.intensity; + const prevAmbColor = currentOptions.ambientLight?.color; const prevShadow = currentOptions.shadow; const prevPointLights = currentOptions.pointLights; const normalizedPartial = normalizeSceneOptions(partial); @@ -1164,34 +1239,45 @@ export function createPolyScene( ) { for (const entry of meshes) renderEntry(entry); } - if (prevAutoCenter !== nextAutoCenter) recomputeAutoCenter(); - // Shadows now use the same per-mesh SVG path in both lighting modes, - // so any of these changes require explicit re-emission: - // - lighting mode toggled (the regular leaves change) - // - light direction changed (projection is CPU-baked into each path) - // - shadow color/opacity/lift changed (color/opacity are inline on the - // ; lift shifts the ground plane and rebuilds geometry) + if (prevAutoCenter !== nextAutoCenter || prevAutoCenterSource !== currentOptions.autoCenterSource) { + recomputeAutoCenter(); + } const textureLightingChanged = partial.textureLighting !== undefined && prevTextureLighting !== currentOptions.textureLighting; const nextDirLight = currentOptions.directionalLight; - // ANY directional change re-emits shadows — not just direction, but also - // intensity and color: the shadow only emits for intensity > 0 (and its - // shaded fill depends on intensity/color), so toggling a light off or - // sliding its intensity must re-project. The emit short-circuit key is - // keyed on direction only, so intensity/color changes also bust the cache - // below (otherwise emitSceneShadows would no-op). const directionalChanged = partial.directionalLight !== undefined && ( !vec3Equal(prevLightDir, nextDirLight?.direction) || (prevDirIntensity ?? 1) !== (nextDirLight?.intensity ?? 1) || (prevDirColor ?? "#ffffff") !== (nextDirLight?.color ?? "#ffffff") ); + const nextAmbLight = currentOptions.ambientLight; + const ambientChanged = partial.ambientLight !== undefined && ( + (prevAmbIntensity ?? 0.4) !== (nextAmbLight?.intensity ?? 0.4) || + (prevAmbColor ?? "#ffffff") !== (nextAmbLight?.color ?? "#ffffff") + ); const nextShadow = currentOptions.shadow; const shadowAppearanceChanged = partial.shadow !== undefined && !shadowOptsEqual(prevShadow, nextShadow); - // Point-light changes also re-emit: the emit short-circuit key folds in - // each shadow point light's CSS position, so a moved/toggled point light - // produces a different key and re-projects its radial shadow. - const shadowReemitNeeded = directionalChanged || shadowAppearanceChanged || pointLightsChanged; + const shadowReemitNeeded = directionalChanged || shadowAppearanceChanged || pointLightsChanged || + (ambientChanged && currentOptions.bakedLightPolicy === "auto"); + if ( + !textureLightingChanged && + currentOptions.bakedLightPolicy === "auto" && + (directionalChanged || ambientChanged) && + !strategiesChanged && + !seamBleedChanged && + !textureLeafSizingChanged && + !textureImageRenderingChanged && + !textureBackendChanged && + !textureProjectionChanged && + !pointLightsChanged + ) { + for (const entry of meshes) { + if (effectiveTextureLighting(ctx, entry) !== "dynamic") { + entry.handle.rebakeAtlas(); + } + } + } if (textureLightingChanged) { // Every mesh needs a full re-render to swap baked/dynamic leaf // emission. Baked leaves carry inline `color: rgb(...)`; dynamic @@ -1272,6 +1358,15 @@ export function createPolyScene( return null; } + function setCenterPolygons(polygons: readonly Polygon[] | null): void { + explicitCenterPolygons = polygons; + if (currentOptions.autoCenterSource === "explicit") recomputeAutoCenter(); + } + + function getAutoCenterOffset(): Vec3 { + return autoCenterOffset; + } + function destroy(): void { if (ctx.shadowRefineTimer) { clearTimeout(ctx.shadowRefineTimer); ctx.shadowRefineTimer = null; } if (ctx.animationShadowTrailingTimer) { @@ -1284,9 +1379,10 @@ export function createPolyScene( for (const m of snapshot) { try { m.handle.dispose(); } catch { /* ignore */ } } - // Remove the camera wrapper (cameraEl is the host-level child; sceneEl is - // inside it, so removing the wrapper also removes the scene element). - if (cameraEl.parentNode) cameraEl.parentNode.removeChild(cameraEl); + clearAllSceneShadows(ctx); + // Remove the camera wrapper only when we created it (adopted elements are + // owned by the caller, e.g. React/Vue / ). + if (!adoptedElements && cameraEl.parentNode) cameraEl.parentNode.removeChild(cameraEl); } const handle = { @@ -1302,6 +1398,8 @@ export function createPolyScene( meshes: listMeshes, whenTexturesReady, findMeshByElement, + setCenterPolygons, + getAutoCenterOffset, previewBakedSolidLighting: (next: Parameters[1]) => previewBakedSolidLighting(ctx, next), commitBakedSolidLighting: () => commitBakedSolidLighting(ctx, renderEntry), diff --git a/packages/polycss/src/api/createSelect.ts b/packages/polycss/src/api/createSelect.ts index ef8208bd1..5ea87cde9 100644 --- a/packages/polycss/src/api/createSelect.ts +++ b/packages/polycss/src/api/createSelect.ts @@ -23,6 +23,9 @@ export interface PolySelectOptions { /** When true (default), clicking the background clears selection. * Set false to keep the current selection on background clicks. */ clearOnMiss?: boolean; + /** Optional DOM container restricting selection to meshes contained inside + * this element. Meshes outside the scope are ignored on click & hit-test. */ + scopeElement?: HTMLElement; /** Optional filter applied to every selection change — return the * array that should become the new selection (drop / reorder). */ filter?: (meshes: PolyMeshHandle[]) => PolyMeshHandle[]; @@ -112,16 +115,19 @@ export function createSelect( return selected.includes(mesh); } + function isSelectableMesh(mesh: PolyMeshHandle): boolean { + if (mesh.element.classList.contains("polycss-transform-gizmo")) return false; + if (options.scopeElement && !options.scopeElement.contains(mesh.element)) return false; + return true; + } + function findMeshUnderPoint(clientX: number, clientY: number): PolyMeshHandle | null { return findMeshUnderPointInMeshes( scene.meshes(), clientX, clientY, - // Skip gizmo meshes — they're managed by transform-controls and - // shouldn't resolve as user-selectable content. The shared - // `polycss-transform-gizmo` class is set on every gizmo mesh - // (translate arrows + rotate rings). - (mesh) => !mesh.element.classList.contains("polycss-transform-gizmo"), + // Skip gizmo meshes and meshes outside `scopeElement`. + isSelectableMesh, ); } @@ -137,8 +143,9 @@ export function createSelect( const onClick = (event: MouseEvent): void => { const target = event.target as Element | null; if (target?.closest(".polycss-transform-gizmo")) return; + const direct = scene.findMeshByElement(target); const handle = - scene.findMeshByElement(target) ?? + (direct && isSelectableMesh(direct) ? direct : null) ?? findMeshUnderPoint(event.clientX, event.clientY); if (!handle) { if (options.onPointerMissed) options.onPointerMissed(event); diff --git a/packages/polycss/src/api/createTransformControls.ts b/packages/polycss/src/api/createTransformControls.ts index fe5ce6a10..92836a777 100644 --- a/packages/polycss/src/api/createTransformControls.ts +++ b/packages/polycss/src/api/createTransformControls.ts @@ -111,6 +111,12 @@ export interface PolyTransformControlsOptions { showZ?: boolean; /** Disable interaction without unmounting. Default true. */ enabled?: boolean; + /** + * When `true` (default), dragging directly mutates `target.setTransform(...)` + * and rebakes the atlas on rotate release. Set `false` for controlled + * framework wrappers (React/Vue) that commit transforms via `onObjectChange`. + */ + applyTransform?: boolean; /** Fires for any transform change. Argument-less, mirrors three.js. */ onChange?: () => void; /** Fires with the new transform during drag. The gizmo also calls @@ -139,6 +145,10 @@ export interface PolyTransformControlsHandle { * after mutating `target.setTransform` externally if you want the * gizmo to follow. */ update(): void; + /** Update options (size, snaps, visibility, callbacks, applyTransform) + * in place without tearing down the controller. Rebuilds gizmo geometry + * only when mode, size, or axis visibility changed. */ + setOptions(partial: Partial): void; /** Remove all listeners + gizmo meshes from the scene. Idempotent. */ destroy(): void; } @@ -388,7 +398,7 @@ export function createTransformControls( ): PolyTransformControlsHandle { let target: PolyMeshHandle | null = null; let mode: Mode = options.mode ?? "translate"; - const size = options.size ?? 1; + let size = options.size ?? 1; const opts: PolyTransformControlsOptions = { ...options }; // No standalone wrapper element. The earlier draft appended a @@ -586,6 +596,7 @@ export function createTransformControls( }, ); const classPrefix = classPrefixFor(spec); + handle.element.setAttribute("data-poly-transform-controls", ""); handle.element.classList.add( "polycss-transform-gizmo", classPrefix, @@ -671,8 +682,10 @@ export function createTransformControls( const worldStep = (t * sign) / SCENE_TILE_SIZE; const next = dragStartPosition.slice() as Vec3; next[worldAxis] = dragStartPosition[worldAxis] + worldStep; - target.setTransform({ position: next }); - syncGizmoPositions(); + if (opts.applyTransform !== false) { + target.setTransform({ position: next }); + syncGizmoPositions(); + } opts.onObjectChange?.({ object: target, position: next }); opts.onChange?.(); } @@ -729,8 +742,10 @@ export function createTransformControls( const next = dragStartPosition.slice() as Vec3; next[worldAxisA] += (tA * signA) / SCENE_TILE_SIZE; next[worldAxisB] += (tB * signB) / SCENE_TILE_SIZE; - target.setTransform({ position: next }); - syncGizmoPositions(); + if (opts.applyTransform !== false) { + target.setTransform({ position: next }); + syncGizmoPositions(); + } opts.onObjectChange?.({ object: target, position: next }); opts.onChange?.(); }, @@ -854,8 +869,10 @@ export function createTransformControls( dragStartPosition[1] + scaleVal * (startC[1] - nextC[1]), dragStartPosition[2] + scaleVal * (startC[2] - nextC[2]), ]; - target.setTransform({ rotation: nextRot, position: nextPos }); - syncGizmoPositions(); + if (opts.applyTransform !== false) { + target.setTransform({ rotation: nextRot, position: nextPos }); + syncGizmoPositions(); + } opts.onObjectChange?.({ object: target, rotation: nextRot, position: nextPos }); opts.onChange?.(); }, @@ -872,7 +889,9 @@ export function createTransformControls( // setTransform; rebakeAtlas() inverse-rotates the world light // into the mesh's new local frame and re-rasterizes the atlas // so baked Lambert shading is correct for the new orientation. - target?.rebakeAtlas(); + if (opts.applyTransform !== false) { + target?.rebakeAtlas(); + } } opts.onDraggingChanged?.(d); }, @@ -907,11 +926,32 @@ export function createTransformControls( }; scene.host.addEventListener("pointermove", onPointerMove); + function setOptions(partial: Partial): void { + const prevMode = mode; + const prevSize = size; + const prevShowX = opts.showX !== false; + const prevShowY = opts.showY !== false; + const prevShowZ = opts.showZ !== false; + Object.assign(opts, partial); + if (partial.mode !== undefined) mode = partial.mode; + if (partial.size !== undefined) size = partial.size; + const needsRebuild = + mode !== prevMode || + size !== prevSize || + (opts.showX !== false) !== prevShowX || + (opts.showY !== false) !== prevShowY || + (opts.showZ !== false) !== prevShowZ; + if (needsRebuild && target) { + teardownGizmos(); + buildGizmos(); + } + } + function destroy(): void { scene.host.removeEventListener("pointerdown", onPointerDown, { capture: true }); scene.host.removeEventListener("pointermove", onPointerMove); teardownGizmos(); } - return { attach, detach, setMode, update, destroy }; + return { attach, detach, setMode, setOptions, update, destroy }; } diff --git a/packages/polycss/src/api/runtimeSeams.test.ts b/packages/polycss/src/api/runtimeSeams.test.ts new file mode 100644 index 000000000..8cd69dfb8 --- /dev/null +++ b/packages/polycss/src/api/runtimeSeams.test.ts @@ -0,0 +1,461 @@ +// @vitest-environment happy-dom +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { ParseResult, Polygon } from "@layoutit/polycss-core"; +import { + createPolyCamera, + createPolyFirstPersonControls, + createPolyMapControls, + createPolyOrbitControls, + createPolyOrthographicCamera, + createPolyPerspectiveCamera, + createPolyScene, + createSelect, + createTransformControls, + type PolyCameraControlTarget, +} from "../runtime"; +import * as runtimeExports from "../runtime"; + +function makeParseResult(polygons: Polygon[]): ParseResult { + return { polygons, objectUrls: [], warnings: [], dispose: () => {} }; +} + +function makeQuad(x0: number, y0: number, z0: number, color = "#cc4422"): Polygon { + return { + vertices: [ + [x0, y0, z0], + [x0 + 1, y0, z0], + [x0 + 1, y0 + 1, z0], + [x0, y0 + 1, z0], + ], + color, + }; +} + +function makeHost(): HTMLDivElement { + const host = document.createElement("div"); + document.body.appendChild(host); + return host; +} + +function makeScene(host: HTMLElement, options: Omit[1], "camera"> = {}) { + return createPolyScene(host, { camera: createPolyCamera(), ...options }); +} + +afterEach(() => { + document.body.innerHTML = ""; + vi.restoreAllMocks(); +}); + +describe("camera.subscribe", () => { + it("notifies listeners on update and stops after unsubscribe", () => { + const persp = createPolyPerspectiveCamera({ rotX: 60, rotY: 45, zoom: 1 }); + const seen: number[] = []; + const unsub = persp.subscribe((state) => { + seen.push(state.rotY); + }); + + persp.update({ rotY: 90 }); + persp.update({ rotY: 120 }); + unsub(); + persp.update({ rotY: 135 }); + + expect(seen).toEqual([90, 120]); + + const ortho = createPolyOrthographicCamera({ zoom: 2 }); + const zooms: number[] = []; + const unsubOrtho = ortho.subscribe((state) => zooms.push(state.zoom)); + ortho.update({ zoom: 3 }); + ortho.update({ zoom: 3.5 }); + unsubOrtho(); + ortho.update({ zoom: 4 }); + expect(zooms).toEqual([3, 3.5]); + }); +}); + +describe("createPolyScene adopt-DOM seams", () => { + it("adopts caller-owned cameraEl and sceneEl without duplicating or removing them on destroy", () => { + const host = makeHost(); + host.style.position = "sticky"; + const cameraEl = document.createElement("div"); + cameraEl.className = "custom-cam"; + const sceneEl = document.createElement("div"); + sceneEl.className = "custom-scene"; + cameraEl.appendChild(sceneEl); + host.appendChild(cameraEl); + + const scene = makeScene(host, { + elements: { cameraEl, sceneEl }, + autoCenter: false, + }); + + expect(scene.cameraEl).toBe(cameraEl); + expect(scene.sceneElement).toBe(sceneEl); + expect(host.style.position).toBe("sticky"); + expect(host.querySelectorAll(".polycss-camera").length).toBe(1); + expect(host.querySelectorAll(".polycss-scene").length).toBe(1); + + const mesh = scene.add(makeParseResult([makeQuad(0, 0, 0)])); + expect(mesh.element.parentElement).toBe(sceneEl); + + scene.destroy(); + + expect(cameraEl.parentElement).toBe(host); + expect(sceneEl.parentElement).toBe(cameraEl); + expect(sceneEl.querySelectorAll(".polycss-mesh").length).toBe(0); + }); + + it("adopts caller-owned mesh wrapper and preserves foreign static children and nested meshes", () => { + const host = makeHost(); + const scene = makeScene(host, { autoCenter: false }); + + const customPivot = document.createElement("div"); + customPivot.className = "user-pivot"; + const wrapper = document.createElement("div"); + wrapper.className = "caller-wrapper"; + const staticBadge = document.createElement("span"); + staticBadge.className = "static-badge"; + staticBadge.textContent = "keep-me"; + const nestedWrapper = document.createElement("div"); + nestedWrapper.className = "nested-mesh-slot"; + wrapper.appendChild(staticBadge); + wrapper.appendChild(nestedWrapper); + customPivot.appendChild(wrapper); + scene.sceneElement.appendChild(customPivot); + + const parentMesh = scene.add(makeParseResult([makeQuad(0, 0, 0, "#aa0000")]), { + wrapper, + id: "parent-mesh", + }); + const childMesh = scene.add(makeParseResult([makeQuad(2, 0, 0, "#00aa00")]), { + wrapper: nestedWrapper, + id: "child-mesh", + }); + + expect(parentMesh.element).toBe(wrapper); + expect(wrapper.parentElement).toBe(customPivot); + expect(wrapper.classList.contains("polycss-mesh")).toBe(true); + expect(wrapper.querySelector(".static-badge")).toBe(staticBadge); + expect(wrapper.querySelector(".nested-mesh-slot")).toBe(nestedWrapper); + expect(nestedWrapper.querySelectorAll("b,i,s,u").length).toBe(1); + + // Updating parent polygons replaces only parent's engine-owned leaves. + parentMesh.setPolygons([makeQuad(0, 0, 0, "#0000aa"), makeQuad(1, 0, 0, "#0000aa")]); + expect(wrapper.querySelector(".static-badge")).toBe(staticBadge); + expect(wrapper.querySelector(".nested-mesh-slot")).toBe(nestedWrapper); + expect(nestedWrapper.querySelectorAll("b,i,s,u").length).toBe(1); + + // Removing parent clears parent's owned leaves but keeps wrapper + static + nested child. + parentMesh.remove(); + expect(wrapper.parentElement).toBe(customPivot); + expect(wrapper.querySelector(".static-badge")).toBe(staticBadge); + expect(wrapper.querySelector(".nested-mesh-slot")).toBe(nestedWrapper); + expect(Array.from(wrapper.children)).toEqual([staticBadge, nestedWrapper]); + + childMesh.remove(); + expect(nestedWrapper.parentElement).toBe(wrapper); + expect(nestedWrapper.childElementCount).toBe(0); + + scene.destroy(); + }); + + it("supports autoCenterSource='explicit' with setCenterPolygons and onAutoCenterOffsetChange", () => { + const host = makeHost(); + const offsets: Array<[number, number, number]> = []; + const scene = makeScene(host, { + autoCenter: true, + autoCenterSource: "explicit", + onAutoCenterOffsetChange: (offset) => offsets.push([...offset]), + }); + + // Adding a mesh at x=10..11 must NOT shift explicit autoCenter. + scene.add(makeParseResult([makeQuad(10, 0, 0)])); + expect(scene.getAutoCenterOffset()).toEqual([0, 0, 0]); + expect(offsets).toEqual([]); + + // Explicit polygons at x=4..6, y=2..4, z=0 → center [5, 3, 0]. + scene.setCenterPolygons([ + makeQuad(4, 2, 0), + makeQuad(5, 3, 0), + ]); + expect(scene.getAutoCenterOffset()).toEqual([5, 3, 0]); + expect(offsets).toEqual([[5, 3, 0]]); + + scene.setCenterPolygons(null); + expect(scene.getAutoCenterOffset()).toEqual([0, 0, 0]); + expect(offsets).toEqual([[5, 3, 0], [0, 0, 0]]); + + scene.destroy(); + }); + + it("supports per-mesh autoCenter and per-mesh textureLighting overrides", () => { + const host = makeHost(); + const scene = makeScene(host, { + autoCenter: false, + textureLighting: "dynamic", + }); + + const mesh = scene.add(makeParseResult([makeQuad(10, 20, 4)]), { + autoCenter: true, + textureLighting: "baked", + }); + + // Polygon vertices should be recentered around origin. + const xs = mesh.polygons[0].vertices.map((v) => v[0]); + const ys = mesh.polygons[0].vertices.map((v) => v[1]); + expect((Math.min(...xs) + Math.max(...xs)) / 2).toBeCloseTo(0, 6); + expect((Math.min(...ys) + Math.max(...ys)) / 2).toBeCloseTo(0, 6); + + const bakedLeaf = mesh.element.querySelector("b,i,s,u") as HTMLElement; + expect(bakedLeaf.style.getPropertyValue("--pnx")).toBe(""); + + // Switching per-mesh override to dynamic via setTransform re-renders with normal vars. + mesh.setTransform({ textureLighting: "dynamic" }); + const dynamicLeaf = mesh.element.querySelector("b,i,s,u") as HTMLElement; + expect(dynamicLeaf.style.getPropertyValue("--pnx")).not.toBe(""); + + scene.destroy(); + }); + + it("auto-rebakes baked meshes when bakedLightPolicy='auto' and freezes when 'manual'", async () => { + const readBakedPaint = (meshEl: HTMLElement): string => { + const leaf = meshEl.querySelector("b,i,s,u") as HTMLElement; + return ( + leaf.style.color || + leaf.style.getPropertyValue("--polycss-paint") || + meshEl.style.getPropertyValue("--polycss-paint") + ); + }; + + const hostAuto = makeHost(); + const sceneAuto = makeScene(hostAuto, { + textureLighting: "baked", + bakedLightPolicy: "auto", + directionalLight: { direction: [0, 0, 1], color: "#ffffff", intensity: 2 }, + ambientLight: { color: "#ffffff", intensity: 0.2 }, + }); + const meshAuto = sceneAuto.add(makeParseResult([makeQuad(0, 0, 0, "#cc4422")])); + const colorBefore = readBakedPaint(meshAuto.element); + expect(colorBefore).not.toBe(""); + + sceneAuto.setOptions({ + directionalLight: { direction: [0, 0, -1], color: "#ffffff", intensity: 2 }, + }); + await new Promise((resolve) => setTimeout(resolve, 10)); + const colorAfter = readBakedPaint(meshAuto.element); + expect(colorAfter).not.toBe(colorBefore); + + const colorBeforeAmbient = colorAfter; + sceneAuto.setOptions({ + ambientLight: { color: "#ffffff", intensity: 1.5 }, + }); + await new Promise((resolve) => setTimeout(resolve, 10)); + const colorAfterAmbient = readBakedPaint(meshAuto.element); + expect(colorAfterAmbient).not.toBe(colorBeforeAmbient); + sceneAuto.destroy(); + + const hostManual = makeHost(); + const sceneManual = makeScene(hostManual, { + textureLighting: "baked", + bakedLightPolicy: "manual", + directionalLight: { direction: [0, 0, 1], color: "#ffffff", intensity: 2 }, + }); + const meshManual = sceneManual.add(makeParseResult([makeQuad(0, 0, 0, "#cc4422")])); + const manualBefore = readBakedPaint(meshManual.element); + expect(manualBefore).not.toBe(""); + sceneManual.setOptions({ + directionalLight: { direction: [0, 0, -1], color: "#ffffff", intensity: 2 }, + }); + await new Promise((resolve) => setTimeout(resolve, 10)); + const manualAfter = readBakedPaint(meshManual.element); + expect(manualAfter).toBe(manualBefore); + sceneManual.destroy(); + }); + + it("supports atomicAtlas with cancellation of superseded versions and synchronous onFrameReady", async () => { + const host = makeHost(); + const readyCalls: number[] = []; + const scene = makeScene(host, { + autoCenter: false, + textureLighting: "baked", + }); + + const mesh = scene.add(makeParseResult([makeQuad(0, 0, 0, "#112233")]), { + merge: false, + atomicAtlas: true, + onFrameReady: () => { + readyCalls.push(mesh.element.querySelectorAll("b,i,s,u").length); + }, + }); + + // Wait for initial async pagesReady + decode chain to settle. + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(readyCalls.length).toBeGreaterThanOrEqual(1); + const initialCalls = readyCalls.length; + + // Rapidly push 3 versions; only the final version should commit & fire onFrameReady. + mesh.setPolygons([makeQuad(0, 0, 0, "#223344"), makeQuad(2, 0, 0, "#223344")]); + mesh.setPolygons([ + makeQuad(0, 0, 0, "#334455"), + makeQuad(2, 0, 0, "#334455"), + makeQuad(4, 0, 0, "#334455"), + ]); + mesh.setPolygons([ + makeQuad(0, 0, 0, "#445566"), + makeQuad(2, 0, 0, "#445566"), + makeQuad(4, 0, 0, "#445566"), + makeQuad(6, 0, 0, "#445566"), + ]); + + // Before microtasks flush, old 1-leaf DOM is still mounted (no blank gap). + expect(mesh.element.querySelectorAll("b,i,s,u").length).toBe(1); + + await new Promise((resolve) => setTimeout(resolve, 10)); + + expect(mesh.element.querySelectorAll("b,i,s,u").length).toBe(4); + expect(readyCalls.length).toBe(initialCalls + 1); + expect(readyCalls[readyCalls.length - 1]).toBe(4); + + scene.destroy(); + }); +}); + +describe("controls, select, and transform-controls guards", () => { + it("orbit/map/fpv controls accept PolyCameraControlTarget and preserve host styles when drag/look disabled", () => { + const host = makeHost(); + host.style.cursor = "cell"; + host.style.touchAction = "pan-y"; + host.style.userSelect = "text"; + + const cameraEl = document.createElement("div"); + host.appendChild(cameraEl); + const camera = createPolyCamera({ rotX: 60, rotY: 45, zoom: 1 }); + let applyCount = 0; + const target: PolyCameraControlTarget = { + host, + cameraEl, + camera, + applyCamera: () => { + applyCount += 1; + }, + }; + + const orbit = createPolyOrbitControls(target, { drag: false, wheel: true }); + expect(host.style.cursor).toBe("cell"); + expect(host.style.touchAction).toBe("pan-y"); + expect(host.style.userSelect).toBe("text"); + orbit.update({ drag: false }); + orbit.destroy(); + expect(host.style.cursor).toBe("cell"); + expect(host.style.touchAction).toBe("pan-y"); + expect(host.style.userSelect).toBe("text"); + + const map = createPolyMapControls(target, { drag: false }); + expect(host.style.cursor).toBe("cell"); + map.destroy(); + expect(host.style.cursor).toBe("cell"); + + const fpv = createPolyFirstPersonControls(target, { lookEnabled: false, moveEnabled: false }); + expect(host.style.cursor).toBe("cell"); + expect(applyCount).toBeGreaterThanOrEqual(1); + fpv.destroy(); + expect(host.style.cursor).toBe("cell"); + }); + + it("orbit controls support right-drag pan without orbiting", () => { + const host = makeHost(); + const scene = makeScene(host); + const orbit = createPolyOrbitControls(scene); + const initialRotX = scene.camera.state.rotX; + const initialRotY = scene.camera.state.rotY; + const initialTarget = [...scene.camera.state.target]; + + // Right button pointerdown should be ignored by orbit; mousedown/move/up pans target. + host.dispatchEvent(new PointerEvent("pointerdown", { button: 2, clientX: 100, clientY: 100, pointerId: 1 })); + host.dispatchEvent(new MouseEvent("mousedown", { button: 2, clientX: 100, clientY: 100 })); + host.dispatchEvent(new MouseEvent("mousemove", { button: 2, clientX: 150, clientY: 120 })); + host.dispatchEvent(new MouseEvent("mouseup", { button: 2, clientX: 150, clientY: 120 })); + + expect(scene.camera.state.rotX).toBe(initialRotX); + expect(scene.camera.state.rotY).toBe(initialRotY); + expect(scene.camera.state.target).not.toEqual(initialTarget); + + orbit.destroy(); + scene.destroy(); + }); + + it("createSelect honors scopeElement so meshes outside the scope are ignored", () => { + const host = makeHost(); + const scene = makeScene(host, { autoCenter: false }); + const scope = document.createElement("div"); + const insideWrapper = document.createElement("div"); + scope.appendChild(insideWrapper); + scene.sceneElement.appendChild(scope); + + const insideMesh = scene.add(makeParseResult([makeQuad(0, 0, 0)]), { + wrapper: insideWrapper, + id: "inside", + }); + const outsideMesh = scene.add(makeParseResult([makeQuad(3, 0, 0)]), { + id: "outside", + }); + + const onChange = vi.fn(); + const select = createSelect(scene, { scopeElement: scope, onChange }); + + // Click outside mesh → ignored (no selection). + outsideMesh.element.dispatchEvent(new MouseEvent("click", { bubbles: true })); + expect(select.selected).toEqual([]); + + // Click inside mesh → selected. + insideMesh.element.dispatchEvent(new MouseEvent("click", { bubbles: true })); + expect(select.selected).toEqual([insideMesh]); + + select.destroy(); + scene.destroy(); + }); + + it("createTransformControls tags gizmo wrappers with data-poly-transform-controls and supports applyTransform=false + setOptions", () => { + const host = makeHost(); + const scene = makeScene(host, { autoCenter: false }); + const mesh = scene.add(makeParseResult([makeQuad(0, 0, 0)])); + + const tc = createTransformControls(scene, { + mode: "translate", + applyTransform: false, + }); + tc.attach(mesh); + + const gizmoEls = Array.from( + scene.sceneElement.querySelectorAll("[data-poly-transform-controls]"), + ); + expect(gizmoEls.length).toBeGreaterThan(0); + + const countBefore = gizmoEls.length; + tc.setOptions({ showZ: false }); + const countAfter = scene.sceneElement.querySelectorAll("[data-poly-transform-controls]").length; + expect(countAfter).toBeLessThan(countBefore); + + tc.destroy(); + scene.destroy(); + }); +}); + +describe("@layoutit/polycss/runtime subpath hygiene", () => { + it("exports imperative runtime without custom elements or snapshot exporter", () => { + expect(typeof runtimeExports.createPolyScene).toBe("function"); + expect(typeof runtimeExports.createPolyCamera).toBe("function"); + expect(typeof runtimeExports.createPolyOrbitControls).toBe("function"); + expect(typeof runtimeExports.createPolyMapControls).toBe("function"); + expect(typeof runtimeExports.createPolyFirstPersonControls).toBe("function"); + expect(typeof runtimeExports.createSelect).toBe("function"); + expect(typeof runtimeExports.createTransformControls).toBe("function"); + expect(typeof runtimeExports.injectPolyBaseStyles).toBe("function"); + expect(typeof runtimeExports.renderPolygonsWithTextureAtlas).toBe("function"); + expect(typeof runtimeExports.createPolyVoxelRenderer).toBe("function"); + expect(typeof runtimeExports.collectPolyRenderStats).toBe("function"); + + expect("PolySceneElement" in runtimeExports).toBe(false); + expect("exportPolySceneSnapshot" in runtimeExports).toBe(false); + expect("createPolyBox" in runtimeExports).toBe(false); + }); +}); diff --git a/packages/polycss/src/api/scene/bakedLighting.ts b/packages/polycss/src/api/scene/bakedLighting.ts index aea85b3d6..49f49db3b 100644 --- a/packages/polycss/src/api/scene/bakedLighting.ts +++ b/packages/polycss/src/api/scene/bakedLighting.ts @@ -20,7 +20,7 @@ import { setStylePropertyIfChanged, } from "./lightingVars"; import { worldDirectionToCss } from "./transforms"; -import { rebakeRenderEntryInPlace, type RenderEntryFn } from "./rebake"; +import { effectiveTextureLighting, rebakeRenderEntryInPlace, type RenderEntryFn } from "./rebake"; import { emitSceneShadows, invalidateShadowLightCache, @@ -40,7 +40,7 @@ export function applyMeshLightVarOverride( rotation: Vec3 | undefined, ): void { const currentOptions = ctx.options.current; - const isDynamic = currentOptions.textureLighting === "dynamic"; + const isDynamic = effectiveTextureLighting(ctx, entry) === "dynamic"; const dir = currentOptions.directionalLight?.direction; const hasNonZeroRotation = rotation && (rotation[0] !== 0 || rotation[1] !== 0 || rotation[2] !== 0); diff --git a/packages/polycss/src/api/scene/cameraCull.ts b/packages/polycss/src/api/scene/cameraCull.ts index 11f38777f..fc1059bfd 100644 --- a/packages/polycss/src/api/scene/cameraCull.ts +++ b/packages/polycss/src/api/scene/cameraCull.ts @@ -24,6 +24,7 @@ import { } from "@layoutit/polycss-core"; import type { RenderedPoly } from "../../render/textureAtlas"; import { firstPreservedChild, mountRenderedFragment } from "./mountLifecycle"; +import { effectiveTextureLighting } from "./rebake"; import type { SceneContext } from "./sceneContext"; import type { MeshEntry } from "./internalTypes"; @@ -132,6 +133,12 @@ export function patchMountedRenderedForCamera( let removeEnd: HTMLElement | null = null; const flushRemove = () => { if (!removeStart || !removeEnd) return; + let cursor: ChildNode | null = removeStart; + while (cursor) { + entry.ownedNodes.delete(cursor); + if (cursor === removeEnd) break; + cursor = cursor.nextSibling; + } if (removeStart === removeEnd) { removeStart.remove(); } else { @@ -206,7 +213,7 @@ export function restoreInlineDynamicNormalVars( entry: MeshEntry, item: RenderedPoly, ): void { - if (ctx.options.current.textureLighting !== "dynamic") return; + if (effectiveTextureLighting(ctx, entry) !== "dynamic") return; const normal = dynamicNormalForRendered(entry, item); if (!normal) return; item.element.style.setProperty("--pnx", normal[0].toFixed(4)); diff --git a/packages/polycss/src/api/scene/internalTypes.ts b/packages/polycss/src/api/scene/internalTypes.ts index d5c43878d..7c67ddc33 100644 --- a/packages/polycss/src/api/scene/internalTypes.ts +++ b/packages/polycss/src/api/scene/internalTypes.ts @@ -11,12 +11,27 @@ import type { CameraCullNormalGroup, ParseResult, Polygon, + PolyTextureBackend, + PolyTextureImageRendering, + PolyTextureLeafSizing, + PolyTextureLightingMode, + PolyTextureProjection, Vec3, } from "@layoutit/polycss-core"; import type { PolyVoxelRenderer } from "../../render/voxelRenderer"; -import type { RenderedPoly } from "../../render/textureAtlas"; +import type { PolySeamBleed, RenderedPoly, TextureQuality } from "../../render/textureAtlas"; import type { PolyMeshHandle } from "./types"; +export interface MeshRenderOverrides { + textureLighting?: PolyTextureLightingMode; + textureQuality?: TextureQuality; + textureLeafSizing?: PolyTextureLeafSizing; + textureImageRendering?: PolyTextureImageRendering; + textureBackend?: PolyTextureBackend; + textureProjection?: PolyTextureProjection; + seamBleed?: PolySeamBleed; +} + /** * The per-mesh state record threaded through every scene operation. Owned by * `createPolyScene` (it lives in a `Set` on the scene context), @@ -26,6 +41,10 @@ import type { PolyMeshHandle } from "./types"; export interface MeshEntry { handle: PolyMeshHandle; wrapper: HTMLDivElement; + /** True when `wrapper` was passed in by the caller (adopted, never removed on dispose). */ + adoptedWrapper: boolean; + /** Engine-mounted child nodes inside `wrapper` so static caller/framework children are never touched. */ + ownedNodes: Set; parseResult: ParseResult; rendered: RenderedPoly[]; renderedByPolygonIndex: Array; @@ -39,6 +58,11 @@ export interface MeshEntry { voxelSource: ParseResult["voxelSource"]; disposed: boolean; stableDom: boolean; + autoCenter: boolean; + atomicAtlas: boolean; + onFrameReady?: () => void; + atomicSwapVersion: number; + renderOverrides: MeshRenderOverrides; hasBuckets: boolean; skipBucketNormalCleanupOnce: boolean; excludeFromAutoCenter: boolean; diff --git a/packages/polycss/src/api/scene/mountLifecycle.ts b/packages/polycss/src/api/scene/mountLifecycle.ts index ad0aca9b8..252c68942 100644 --- a/packages/polycss/src/api/scene/mountLifecycle.ts +++ b/packages/polycss/src/api/scene/mountLifecycle.ts @@ -27,26 +27,40 @@ export function clearRendered(ctx: SceneContext, entry: MeshEntry): void { entry.solidLightingPreviewActive = false; clearShadowLeaves(ctx, entry); for (const child of Array.from(entry.wrapper.children)) { - if (child instanceof HTMLElement && child.classList.contains("polycss-bucket")) { + if ( + child instanceof HTMLElement && + child.classList.contains("polycss-bucket") && + (entry.ownedNodes.size === 0 || entry.ownedNodes.has(child)) + ) { child.remove(); + entry.ownedNodes.delete(child); } } + entry.ownedNodes.clear(); entry.hasBuckets = false; } export function firstPreservedChild(entry: MeshEntry): ChildNode | null { for (const child of Array.from(entry.wrapper.childNodes)) { + if (entry.ownedNodes.has(child)) continue; if (!(child instanceof HTMLElement)) return child; - if (child.classList.contains("polycss-bucket")) continue; - if (child.classList.contains("polycss-shadow")) continue; - const tag = child.tagName.toLowerCase(); - if (tag === "b" || tag === "i" || tag === "s" || tag === "u" || tag === "q") continue; + if (entry.ownedNodes.size === 0) { + if (child.classList.contains("polycss-bucket")) continue; + if (child.classList.contains("polycss-shadow")) continue; + const tag = child.tagName.toLowerCase(); + if (tag === "b" || tag === "i" || tag === "s" || tag === "u" || tag === "q") continue; + } else if (child.classList.contains("polycss-voxel-face")) { + continue; + } return child; } return null; } export function mountRenderedFragment(entry: MeshEntry, fragment: DocumentFragment, before: ChildNode | null): void { + for (const node of Array.from(fragment.childNodes)) { + entry.ownedNodes.add(node); + } if (before?.parentNode === entry.wrapper) { entry.wrapper.insertBefore(fragment, before); } else { @@ -95,6 +109,10 @@ export function setRendered( } export function clearMountedRendered(entry: MeshEntry): void { + for (const node of Array.from(entry.ownedNodes)) { + if (node.parentNode === entry.wrapper) entry.wrapper.removeChild(node); + } + entry.ownedNodes.clear(); for (const child of Array.from(entry.wrapper.children)) { if (child instanceof HTMLElement && child.classList.contains("polycss-bucket")) { child.remove(); diff --git a/packages/polycss/src/api/scene/mountSync.ts b/packages/polycss/src/api/scene/mountSync.ts index 5744ab416..5c2bb44f8 100644 --- a/packages/polycss/src/api/scene/mountSync.ts +++ b/packages/polycss/src/api/scene/mountSync.ts @@ -48,7 +48,7 @@ export function syncMountedRendered(ctx: SceneContext, entry: MeshEntry): void { // recomputes lambert per polygon every frame. Baked mode bakes lambert // into atlas pixels at parse time — no per-frame computation to save. const useBuckets = - ctx.options.current.textureLighting === "dynamic" && !entry.stableDom; + (entry.renderOverrides.textureLighting ?? ctx.options.current.textureLighting) === "dynamic" && !entry.stableDom; interface BucketGroup { vec: Vec3; @@ -125,7 +125,7 @@ export async function syncMountedRenderedChunked( ): Promise { const doc = ctx.doc; const useBuckets = - ctx.options.current.textureLighting === "dynamic" && !entry.stableDom; + (entry.renderOverrides.textureLighting ?? ctx.options.current.textureLighting) === "dynamic" && !entry.stableDom; if (useBuckets) { syncMountedRendered(ctx, entry); return !shouldCancel(); diff --git a/packages/polycss/src/api/scene/rebake.ts b/packages/polycss/src/api/scene/rebake.ts index 9f198525c..ce034f89f 100644 --- a/packages/polycss/src/api/scene/rebake.ts +++ b/packages/polycss/src/api/scene/rebake.ts @@ -8,7 +8,7 @@ * fallback paths here receive it as an explicit, typed function parameter — * the one genuine inversion in this module. */ -import type { PolyPointLight, Vec3 } from "@layoutit/polycss-core"; +import type { PolyPointLight, PolyTextureLightingMode, Vec3 } from "@layoutit/polycss-core"; import { inverseRotateVec3 } from "@layoutit/polycss-core"; import { renderPolygonsWithTextureAtlas, @@ -17,6 +17,9 @@ import { import { applySolidPaintVars } from "./lightingVars"; import { worldDirectionalLightToCss } from "./transforms"; import { emitShadowLeaves } from "./shadowOrchestrator"; +import { clearMountedRendered, disposeRendered, setRendered } from "./mountLifecycle"; +import { recomputeCameraCullGroups } from "./cameraCull"; +import { syncMountedRendered } from "./mountSync"; import type { SceneContext } from "./sceneContext"; import type { MeshEntry } from "./internalTypes"; @@ -24,9 +27,44 @@ import type { MeshEntry } from "./internalTypes"; * into the rebake paths for their fallback cases. */ export type RenderEntryFn = (entry: MeshEntry, lightDirectionOverride?: Vec3) => void; +export function effectiveTextureLighting( + ctx: SceneContext, + entry: MeshEntry, +): PolyTextureLightingMode | undefined { + return entry.renderOverrides.textureLighting ?? ctx.options.current.textureLighting; +} + +export function resolveMeshRenderOptions( + ctx: SceneContext, + entry: MeshEntry, + lightDirectionOverride?: Vec3, +) { + const currentOptions = ctx.options.current; + const ov = entry.renderOverrides; + const baseDirLight = currentOptions.directionalLight; + const userDirLight: typeof baseDirLight = lightDirectionOverride + ? { ...baseDirLight, direction: lightDirectionOverride } + : baseDirLight; + const lighting = effectiveTextureLighting(ctx, entry); + return { + doc: ctx.doc, + directionalLight: worldDirectionalLightToCss(userDirLight), + pointLights: localPointLightsForEntry(ctx, entry), + ambientLight: currentOptions.ambientLight, + textureLighting: lighting, + textureQuality: ov.textureQuality ?? currentOptions.textureQuality, + textureLeafSizing: ov.textureLeafSizing ?? currentOptions.textureLeafSizing, + textureImageRendering: ov.textureImageRendering ?? currentOptions.textureImageRendering, + textureBackend: ov.textureBackend ?? currentOptions.textureBackend, + textureProjection: ov.textureProjection ?? currentOptions.textureProjection, + seamBleed: ov.seamBleed ?? currentOptions.seamBleed, + strategies: currentOptions.strategies, + }; +} + export function canRenderVoxelDirect(ctx: SceneContext, entry: MeshEntry): boolean { return !!entry.voxelSource && - ctx.options.current.textureLighting !== "dynamic" && + effectiveTextureLighting(ctx, entry) !== "dynamic" && !entry.stableDom && !entry.castShadow; } @@ -93,26 +131,11 @@ export function rebakeRenderEntryInPlace( return; } - const baseDirLight = currentOptions.directionalLight; - const userDirLight: typeof baseDirLight = lightDirectionOverride - ? { ...baseDirLight, direction: lightDirectionOverride } - : baseDirLight; - const directionalLight = worldDirectionalLightToCss(userDirLight); + const baseRenderOptions = resolveMeshRenderOptions(ctx, entry, lightDirectionOverride); const renderOptions = { - doc: ctx.doc, - directionalLight, - pointLights: localPointLightsForEntry(ctx, entry), - ambientLight: currentOptions.ambientLight, - textureLighting: currentOptions.textureLighting, - textureQuality: currentOptions.textureQuality, - textureLeafSizing: currentOptions.textureLeafSizing, - textureImageRendering: currentOptions.textureImageRendering, - textureBackend: currentOptions.textureBackend, - textureProjection: currentOptions.textureProjection, - seamBleed: currentOptions.seamBleed, - strategies: currentOptions.strategies, + ...baseRenderOptions, computeSolidPaintDefaults: true, - skipDynamicNormalVars: currentOptions.textureLighting === "dynamic", + skipDynamicNormalVars: baseRenderOptions.textureLighting === "dynamic", }; const newAtlas = renderPolygonsWithTextureAtlas( entry.polygons, @@ -166,6 +189,7 @@ export function rebakeRenderEntryInPlace( } // shadow leaves still need to follow the new light direction. emitShadowLeaves(ctx, entry); + if (entry.atomicAtlas) entry.onFrameReady?.(); finish(); }; @@ -213,7 +237,84 @@ export function requestRebakeAtlas( rebakeRenderEntryInPlace(ctx, entry, renderEntry, lightDir); } -function collectAtlasUrlsFromRendered( +/** + * Topology-safe atomic atlas render: builds the next geometry + atlas off-DOM, + * awaits `pagesReady` + `Image.decode()`, cancels superseded builds without + * leaking blob URLs, swaps the mounted DOM in one synchronous turn, and fires + * `entry.onFrameReady()` immediately after the swap (before the next paint). + */ +export function renderEntryAtomic( + ctx: SceneContext, + entry: MeshEntry, + lightDirectionOverride?: Vec3, +): void { + const version = ++entry.atomicSwapVersion; + const baseRenderOptions = resolveMeshRenderOptions(ctx, entry, lightDirectionOverride); + const renderOptions = { + ...baseRenderOptions, + computeSolidPaintDefaults: true, + skipDynamicNormalVars: baseRenderOptions.textureLighting === "dynamic", + }; + const newAtlas = renderPolygonsWithTextureAtlas( + entry.polygons, + renderOptions as Parameters[1], + ); + + const commitSwap = (): void => { + if (entry.disposed || version !== entry.atomicSwapVersion) { + newAtlas.dispose(); + return; + } + const previousRendered = entry.rendered.slice(); + const previousDispose = entry.disposeAtlas; + entry.voxelRenderer?.dispose(); + entry.voxelRenderer = undefined; + clearMountedRendered(entry); + entry.rendered.length = 0; + + applySolidPaintVars( + entry.wrapper, + (newAtlas as { solidPaintDefaults?: SolidPaintDefaults }).solidPaintDefaults ?? {}, + ); + setRendered(entry, newAtlas.rendered, newAtlas.dispose, newAtlas.pagesReady); + entry.skipBucketNormalCleanupOnce = + baseRenderOptions.textureLighting === "dynamic" && !entry.stableDom; + recomputeCameraCullGroups(entry); + syncMountedRendered(ctx, entry); + emitShadowLeaves(ctx, entry); + entry.onFrameReady?.(); + + const revokePrevious = () => { + disposeRendered(previousRendered, previousDispose); + }; + const schedule: (cb: () => void) => void = + typeof requestAnimationFrame === "function" + ? (cb) => { requestAnimationFrame(cb); } + : (cb) => { setTimeout(cb, 0); }; + schedule(revokePrevious); + }; + + const ready = (newAtlas as { pagesReady?: Promise }).pagesReady; + if (ready && typeof ready.then === "function") { + entry.textureReadyPromise = ready.catch(() => undefined); + ready + .then(() => { + if (entry.disposed || version !== entry.atomicSwapVersion) return; + return decodeAtlasUrls(collectAtlasUrlsFromRendered(newAtlas.rendered)); + }) + .then(commitSwap, () => { + if (entry.disposed || version !== entry.atomicSwapVersion) { + newAtlas.dispose(); + return; + } + commitSwap(); + }); + } else { + commitSwap(); + } +} + +export function collectAtlasUrlsFromRendered( rendered: ReturnType["rendered"], ): string[] { const urls = new Set(); @@ -227,7 +328,7 @@ function collectAtlasUrlsFromRendered( return Array.from(urls); } -function decodeAtlasUrls(urls: string[]): Promise { +export function decodeAtlasUrls(urls: string[]): Promise { if (urls.length === 0 || typeof Image === "undefined") return Promise.resolve(); return Promise.all(urls.map((url) => { const img = new Image(); diff --git a/packages/polycss/src/api/scene/sceneContext.ts b/packages/polycss/src/api/scene/sceneContext.ts index d98f10621..d29b83aab 100644 --- a/packages/polycss/src/api/scene/sceneContext.ts +++ b/packages/polycss/src/api/scene/sceneContext.ts @@ -52,8 +52,8 @@ export interface SceneContext { // Host + scene element handles. Static for the scene's lifetime. host: HTMLElement; doc: Document; - cameraEl: HTMLDivElement; - sceneEl: HTMLDivElement; + cameraEl: HTMLElement; + sceneEl: HTMLElement; // Camera handle the scene is bound to. camera: PolyPerspectiveCameraHandle | PolyOrthographicCameraHandle; @@ -106,8 +106,8 @@ export interface SceneContext { export function createSceneContext(input: { host: HTMLElement; doc: Document; - cameraEl: HTMLDivElement; - sceneEl: HTMLDivElement; + cameraEl: HTMLElement; + sceneEl: HTMLElement; camera: PolyPerspectiveCameraHandle | PolyOrthographicCameraHandle; layoutScale: number; options: Omit; diff --git a/packages/polycss/src/api/scene/shadowGeometry.test.ts b/packages/polycss/src/api/scene/shadowGeometry.test.ts index f0d8cd3fb..4a4e2761c 100644 --- a/packages/polycss/src/api/scene/shadowGeometry.test.ts +++ b/packages/polycss/src/api/scene/shadowGeometry.test.ts @@ -8,7 +8,7 @@ import { groupReceiverFaceGroups, meshScaleVec3, worldCssForMesh, -} from "./shadowGeometry"; +} from "@layoutit/polycss-core"; import { DEFAULT_TILE } from "./transforms"; describe("meshScaleVec3", () => { diff --git a/packages/polycss/src/api/scene/shadowGeometry.ts b/packages/polycss/src/api/scene/shadowGeometry.ts deleted file mode 100644 index e4282d783..000000000 --- a/packages/polycss/src/api/scene/shadowGeometry.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** - * Receiver-shadow face grouping. Pure geometry, now living in core so React - * and Vue can share the algorithm. This file re-exports the core helpers so - * the rest of the vanilla scene code keeps its existing import path. - */ -export { - expandConvexHullOutward, - groupReceiverFaceGroups, - meshScaleVec3, - RECEIVER_NORMAL_TOL, - RECEIVER_OFFSET_TOL, - RECEIVER_OUTLINE_EXPAND, - worldCssForMesh, -} from "@layoutit/polycss-core"; -export type { ReceiverPlaneGroup } from "@layoutit/polycss-core"; diff --git a/packages/polycss/src/api/scene/types.ts b/packages/polycss/src/api/scene/types.ts index 5b2402e20..91da9787f 100644 --- a/packages/polycss/src/api/scene/types.ts +++ b/packages/polycss/src/api/scene/types.ts @@ -28,6 +28,21 @@ import type { TextureQuality, } from "../../render/textureAtlas"; +export interface PolySceneElements { + /** Existing `.polycss-camera` container owned by the caller (e.g. React/Vue ``). */ + cameraEl: HTMLElement; + /** Existing `.polycss-scene` container owned by the caller (e.g. React/Vue ``). */ + sceneEl: HTMLElement; +} + +/** Minimal scene surface required by camera controls (`PolySceneHandle` satisfies this). */ +export interface PolyCameraControlTarget { + readonly host: HTMLElement; + readonly cameraEl: HTMLElement; + readonly camera: PolyPerspectiveCameraHandle | PolyOrthographicCameraHandle; + applyCamera(): void; +} + export interface PolySceneOptions { /** * Camera handle created by `createPolyCamera`, `createPolyOrthographicCamera`, @@ -35,6 +50,12 @@ export interface PolySceneOptions { * this field is missing. */ camera: PolyPerspectiveCameraHandle | PolyOrthographicCameraHandle; + /** + * Adopt caller-owned `.polycss-camera` and `.polycss-scene` elements instead + * of creating new wrappers under `host`. Adopted elements are not removed + * when `destroy()` runs — only engine-owned leaves and shadow SVGs are cleaned. + */ + elements?: PolySceneElements; directionalLight?: PolyDirectionalLight; /** Point lights (world-space positions). Direction-only per-face Lambert * shading (no distance falloff). Baked-mode only. */ @@ -42,6 +63,22 @@ export interface PolySceneOptions { ambientLight?: PolyAmbientLight; /** Textured polygon lighting mode. Defaults to "baked". */ textureLighting?: PolyTextureLightingMode; + /** + * How baked-mode meshes respond to `setOptions({ directionalLight, ambientLight })`. + * - `"manual"` (default): freezes baked leaves until explicit `mesh.rebakeAtlas()`. + * - `"auto"`: automatically rebakes baked meshes in place when directional or + * ambient light options change (used by declarative React/Vue adapters). + */ + bakedLightPolicy?: "manual" | "auto"; + /** + * Source geometry for `autoCenter` bbox calculation. + * - `"meshes"` (default): union bbox of all non-excluded added meshes. + * - `"explicit"`: bbox of `setCenterPolygons(polygons)` only (matches React/Vue + * ``). + */ + autoCenterSource?: "meshes" | "explicit"; + /** Optional callback fired synchronously whenever the resolved `autoCenterOffset` changes. */ + onAutoCenterOffsetChange?: (offset: Vec3) => void; /** Atlas bitmap budget and CSS sprite size. `"auto"` uses a * device-appropriate memory budget (~4 MB mobile / ~16 MB desktop) and * desktop/mobile sprite sizing. Numeric values 0.1..1 force an explicit @@ -229,6 +266,37 @@ export interface PolyMeshTransform { * scene definition. */ shadowDefinition?: number; + /** + * Adopt a caller-owned `.polycss-mesh` wrapper element instead of creating + * and appending a new `
` to `sceneElement`. Preserves caller DOM nesting + * (user transform wrappers, nested child meshes, framework synthetic events) + * and is not removed from the DOM on `remove()`/`dispose()`. + */ + wrapper?: HTMLDivElement; + /** Recenter this mesh's polygons around its own bbox center before rendering. */ + autoCenter?: boolean; + /** Per-mesh override of scene `textureLighting`. */ + textureLighting?: PolyTextureLightingMode; + /** Per-mesh override of scene `textureQuality`. */ + textureQuality?: TextureQuality; + /** Per-mesh override of scene `textureLeafSizing`. */ + textureLeafSizing?: PolyTextureLeafSizing; + /** Per-mesh override of scene `textureImageRendering`. */ + textureImageRendering?: PolyTextureImageRendering; + /** Per-mesh override of scene `textureBackend`. */ + textureBackend?: PolyTextureBackend; + /** Per-mesh override of scene `textureProjection`. */ + textureProjection?: PolyTextureProjection; + /** Per-mesh override of scene `seamBleed`. */ + seamBleed?: PolySeamBleed; + /** + * When `true`, `setPolygons()` builds the next atlas off-DOM, awaits + * `pagesReady` + `Image.decode()`, swaps the mounted leaves atomically in + * one synchronous turn, and calls `onFrameReady()` immediately after swap. + */ + atomicAtlas?: boolean; + /** Fires synchronously right after an atomic frame swap lands in the DOM. */ + onFrameReady?: () => void; } export interface PolyMeshHandle { @@ -348,6 +416,10 @@ export interface PolySceneHandle { /** Resolve a `.polycss-mesh` element back to its handle, or `null` if * the element doesn't belong to this scene. */ findMeshByElement(element: Element | null): PolyMeshHandle | null; + /** Override explicit polygons used when `autoCenterSource === "explicit"`. */ + setCenterPolygons(polygons: readonly Polygon[] | null): void; + /** Current resolved auto-center bbox offset in world units. */ + getAutoCenterOffset(): Vec3; } /** Symbol-keyed extension point on `PolyMeshHandle` for the animation mixer. diff --git a/packages/polycss/src/index.ts b/packages/polycss/src/index.ts index 26536ff3f..a3c266b4d 100644 --- a/packages/polycss/src/index.ts +++ b/packages/polycss/src/index.ts @@ -13,6 +13,8 @@ // ── Imperative scene API ────────────────────────────────────────── export { createPolyScene } from "./api/createPolyScene"; export type { + PolyCameraControlTarget, + PolySceneElements, PolySceneHandle, PolyMeshHandle, PolyMeshTransform, @@ -94,6 +96,8 @@ export { PolySceneElement } from "./elements/PolySceneElement"; export { PolyMeshElement } from "./elements/PolyMeshElement"; export { PolyIframeElement } from "./elements/PolyIframeElement"; export { PolyPolygonElement } from "./elements/PolyPolygonElement"; +export { PolyAxesHelperElement } from "./elements/PolyAxesHelperElement"; +export { PolyDirectionalLightHelperElement } from "./elements/PolyDirectionalLightHelperElement"; export { PolyOrbitControlsElement } from "./elements/PolyOrbitControlsElement"; export { PolyMapControlsElement } from "./elements/PolyMapControlsElement"; export { PolyFirstPersonControlsElement } from "./elements/PolyFirstPersonControlsElement"; diff --git a/packages/polycss/src/render/polyDOM.test.ts b/packages/polycss/src/render/polyDOM.test.ts index 4f16b9053..e8966faf1 100644 --- a/packages/polycss/src/render/polyDOM.test.ts +++ b/packages/polycss/src/render/polyDOM.test.ts @@ -1,12 +1,32 @@ import { describe, it, expect, vi, afterEach } from "vitest"; -import { renderPoly } from "./polyDOM"; import { renderPolygonsWithTextureAtlas, renderPolygonsWithTextureAtlasAsync, updatePolygonsWithStableTopology, + type RenderedPoly, + type RenderTextureAtlasOptions, } from "./textureAtlas"; import type { Polygon } from "@layoutit/polycss-core"; +function renderPoly( + polygon: Polygon, + options: RenderTextureAtlasOptions = {}, +): RenderedPoly | null { + const result = renderPolygonsWithTextureAtlas([polygon], options); + const rendered = result.rendered[0]; + if (!rendered) { + result.dispose(); + return null; + } + return { + polygonIndex: 0, + element: rendered.element, + dispose() { + try { rendered.dispose(); } finally { result.dispose(); } + }, + }; +} + const ATLAS_CANONICAL_SIZE_EXPLICIT = 64; const ATLAS_CANONICAL_SIZE_AUTO_DESKTOP = 128; const SOLID_QUAD_CANONICAL_SIZE = 64; diff --git a/packages/polycss/src/render/polyDOM.ts b/packages/polycss/src/render/polyDOM.ts deleted file mode 100644 index f17f8b261..000000000 --- a/packages/polycss/src/render/polyDOM.ts +++ /dev/null @@ -1,37 +0,0 @@ -/** - * polyDOM — compatibility wrapper for rendering a single Polygon. - * - * The vanilla package renders every valid polygon through the same brush - * dispatch used by mesh rendering: rects use , solid triangles and exact - * corner-shape solids use , sprites use , and remaining irregular solid - * polygons use when available. - */ -import type { Polygon } from "@layoutit/polycss-core"; -import { - renderPolygonsWithTextureAtlas, - type RenderedPoly, - type RenderTextureAtlasOptions, -} from "./textureAtlas"; - -export interface RenderPolyOptions extends RenderTextureAtlasOptions {} - -export type { RenderedPoly }; - -export function renderPoly( - polygon: Polygon, - options: RenderPolyOptions = {}, -): RenderedPoly | null { - const result = renderPolygonsWithTextureAtlas([polygon], options); - const rendered = result.rendered[0]; - if (!rendered) { - result.dispose(); - return null; - } - return { - polygonIndex: 0, - element: rendered.element, - dispose() { - try { rendered.dispose(); } finally { result.dispose(); } - }, - }; -} diff --git a/packages/polycss/src/runtime.ts b/packages/polycss/src/runtime.ts new file mode 100644 index 000000000..929c3653f --- /dev/null +++ b/packages/polycss/src/runtime.ts @@ -0,0 +1,147 @@ +/** + * @layoutit/polycss/runtime — side-effect-free DOM rendering runtime. + * + * Exposes the imperative scene, camera, controls, selection, transform gizmo, + * atlas/voxel renderers, diagnostics, and base stylesheet injector WITHOUT + * custom-element classes, standalone snapshot export, or primitive shape + * factories. Intended for framework adapters (`@layoutit/polycss-react`, + * `@layoutit/polycss-vue`) and lean imperative bundles. + */ + +// ── Imperative scene API ────────────────────────────────────────── +export { createPolyScene } from "./api/createPolyScene"; +export type { + PolyCameraControlTarget, + PolyMeshHandle, + PolyMeshTransform, + PolySceneElements, + PolySceneHandle, + PolySceneOptions, + PolyShadowOptions, +} from "./api/createPolyScene"; + +// ── Camera factories ────────────────────────────────────────────── +export { + createPolyCamera, + createPolyOrthographicCamera, + createPolyPerspectiveCamera, +} from "./api/createPolyCamera"; +export type { + PolyCameraOptions, + PolyOrthographicCameraHandle, + PolyOrthographicCameraOptions, + PolyPerspectiveCameraHandle, + PolyPerspectiveCameraOptions, +} from "./api/createPolyCamera"; + +// ── Camera input ────────────────────────────────────────────────── +export { createPolyOrbitControls } from "./api/createPolyOrbitControls"; +export type { + PolyOrbitControlsHandle, + PolyOrbitControlsOptions, +} from "./api/createPolyOrbitControls"; + +export { createPolyMapControls } from "./api/createPolyMapControls"; +export type { + PolyMapControlsHandle, + PolyMapControlsOptions, +} from "./api/createPolyMapControls"; + +export { createPolyFirstPersonControls } from "./api/createPolyFirstPersonControls"; +export type { + PolyFirstPersonControlsHandle, + PolyFirstPersonControlsOptions, +} from "./api/createPolyFirstPersonControls"; + +export type { + PolyControlsAnimateOptions, + PolyControlsBaseOptions, + PolyControlsCamera, + PolyControlsChangeEvent, + PolyControlsEvent, + PolyControlsHandle, + PolyControlsInteractionEvent, + PolyControlsListener, +} from "./api/controls/common"; + +// ── Mesh selection & transform gizmo ────────────────────────────── +export { createSelect } from "./api/createSelect"; +export type { PolySelectOptions, PolySelectionHandle } from "./api/createSelect"; + +export { createTransformControls } from "./api/createTransformControls"; +export type { + PolyTransformControlsHandle, + PolyTransformControlsObjectChangeEvent, + PolyTransformControlsOptions, +} from "./api/createTransformControls"; + +// ── Low-level atlas & voxel renderers ───────────────────────────── +export { + buildAtlasPages, + buildTextureEdgeRepairSets, + computeTextureAtlasPlanPublic, + cssBorderShapeForPlan, + filterAtlasPlans, + formatBorderShapeEntryMatrix, + formatCssLengthPx, + formatMatrix3d, + formatSolidQuadEntryMatrix, + getSolidPaintDefaults, + getSolidPaintDefaultsFromPlans, + isBorderShapeSupported, + isFullRectSolid, + isProjectiveQuadPlan, + isSolidTrianglePlan, + isSolidTriangleSupported, + packTextureAtlasPlansWithScale, + renderPolygonsWithStableTriangles, + renderPolygonsWithTextureAtlas, + renderPolygonsWithTextureAtlasAsync, + updatePolygonsWithStableTopology, + updatePolygonsWithStableTriangles, + updateStableTriangleFrame, +} from "./render/textureAtlas"; +export type { + ComputeTextureAtlasPlanOptions, + PackedAtlas, + PackedPage, + PackedTextureAtlasEntry, + PolyRenderStrategiesOption, + PolyRenderStrategy, + RenderTextureAtlasAsyncResult, + RenderTextureAtlasOptions, + RenderTextureAtlasResult, + RenderedPoly, + SolidPaintDefaults, + SolidTriangleFrame, + TextureAtlasPage, + TextureAtlasPlan, + TextureQuality, +} from "./render/textureAtlas"; + +export { createPolyVoxelRenderer } from "./render/voxelRenderer"; +export type { + PolyVoxelRenderer, + PolyVoxelRendererOptions, +} from "./render/voxelRenderer"; + +// ── Render diagnostics ──────────────────────────────────────────── +export { + collectPolyRenderStats, + collectPolyTextureReadiness, + queryPolyLeaves, +} from "./render/renderStats"; +export type { + PolyCameraSnapshotStats, + PolyLeafInfo, + PolyRenderLeafStrategy, + PolyRenderStats, + PolyRenderStatsOptions, + PolyRenderSurfaceLeafCounts, + PolySnapshotRenderStats, + PolyTextureReadiness, + PolyTextureRenderStats, +} from "./render/renderStats"; + +// ── Style injection ─────────────────────────────────────────────── +export { injectPolyBaseStyles } from "./styles/styles"; diff --git a/packages/polycss/tsup.config.ts b/packages/polycss/tsup.config.ts index 6d8b359ff..9a0ba1a91 100644 --- a/packages/polycss/tsup.config.ts +++ b/packages/polycss/tsup.config.ts @@ -3,6 +3,7 @@ import { createLibraryConfig } from "../tsup.base.mjs"; export default createLibraryConfig({ entry: { index: "src/index.ts", + runtime: "src/runtime.ts", elements: "src/elements/index.ts", three: "src/three.ts", }, From 2882c6ef1c0683df0a19cfa19bc2f6dd94517628 Mon Sep 17 00:00:00 2001 From: alowpoly Date: Thu, 3 Dec 2026 13:28:10 -0300 Subject: [PATCH 2/9] chore(guards): allow React and Vue to depend on @layoutit/polycss/runtime --- .../architecture/cross-package-and-mirrors.md | 2 +- .github/scripts/check-boundaries.mjs | 8 +- .github/scripts/check-boundaries.test.mjs | 78 ++++++++++++++----- AGENTS.md | 8 +- 4 files changed, 66 insertions(+), 30 deletions(-) diff --git a/.github/architecture/cross-package-and-mirrors.md b/.github/architecture/cross-package-and-mirrors.md index cc234c104..204354810 100644 --- a/.github/architecture/cross-package-and-mirrors.md +++ b/.github/architecture/cross-package-and-mirrors.md @@ -24,7 +24,7 @@ When you change `packages/polycss` or `packages/core` in a way that affects the The DOM snapshot exporter is the current exception to mirrored React/Vue public exports: `exportPolySceneSnapshot` lives in `@layoutit/polycss` because it is browser DOM serialization, not component API. React/Vue callers import it from `@layoutit/polycss` and pass the rendered `.polycss-camera` / `.polycss-scene` element. -**Renderer-owned browser glue.** The canvas atlas pipeline (`buildAtlasPages` + helpers), browser-feature detection (`isBorderShapeSupported`, `isSolidTriangleSupported`, `resolveSolidTrianglePrimitive`), direct voxel renderer (`voxelRenderer.ts`), and the base stylesheet injector (`styles.ts`) exist as **independent copies** across the three renderers. This includes `packages/polycss/src/render/atlas/`, `packages/react/src/scene/atlas/`, `packages/vue/src/scene/atlas/`, the three renderer-local `voxelRenderer.ts` files, and the three sibling `styles.ts` files. This is deliberate — each renderer is self-contained on its dep graph (React/Vue do not import from the `polycss` package). The trade-off is that a bug fix in any of these files MUST be mirrored into the other two. Coverage is pinned per copy by the co-located test files. +**Renderer-owned browser glue.** The canvas atlas pipeline (`buildAtlasPages` + helpers), browser-feature detection (`isBorderShapeSupported`, `isSolidTriangleSupported`, `resolveSolidTrianglePrimitive`), direct voxel renderer (`voxelRenderer.ts`), and the base stylesheet injector (`styles.ts`) currently exist as mirrored copies across the three renderers while React/Vue transition onto the side-effect-free `@layoutit/polycss/runtime` subpath. Until that migration completes, a bug fix in any of these files MUST be mirrored into the other two. Coverage is pinned per copy by the co-located test files. **CI enforces this and the package boundaries.** `pnpm check:boundaries` (`.github/scripts/check-boundaries.mjs`) fails on any import that violates the package dependency boundaries in [AGENTS.md](../../AGENTS.md), on deep imports into another package's `src` (`DEEP_IMPORT_ALLOWLIST` is empty), and on node builtins outside the Node-only surfaces. It scans `.ts`/`.tsx`/`.mts`/`.cts` **and** `.mjs`/`.cjs`/`.js` sources (so the `packages/skills` CLI is covered). Specifiers are read by a single-pass **lexer**, not a regex over raw source, because pattern-matching is wrong in both directions: it misses valid imports (a comment between the keyword and the specifier, `import(\`x\`)`, a statement split across lines) and matches text that is not code (a commented-out import, an import-shaped string). The lexer skips comments, tracks single/double-quoted strings, template literals including `${}` nesting, and regex literals, and yields `import`/`export … from`, bare `import "x"`, `import()` and `require()` specifiers; a template WITH a substitution is not a static specifier and is ignored rather than crashed on. Quoted strings and regex literals may never span a newline, so a mis-lex in TSX (JSX apostrophes, `
`) recovers on the next line instead of swallowing code. The same allow-list is applied to each package's manifest: a `dependencies`, `optionalDependencies`, or `peerDependencies` entry outside the package's allow-list fails even when nothing imports it yet. `devDependencies` are tooling and are not constrained. The allow-list is applied to the RESOLVED dependency, not the manifest key, because the key is not what gets installed. Resolved forms: `npm:[@range]` aliases; `link:`/`file:`/`portal:` local paths and `workspace:` targets (both read through the target directory's own `package.json` name); and `workspace:[@range]` aliases, versioned or not. So `"@layoutit/polycss-core": "npm:@layoutit/polycss@0.2.0"`, `"workspace:@layoutit/polycss"` and `"workspace:../polycss"` all fail in React under the allowed key. Only bare ranges and dist-tags (`^0.2.0`, `*`, `latest`, `workspace:^`, `workspace:*`, `workspace:1.2.3`) leave the key standing. Everything else is a **violation, not a pass**: a local or workspace target whose manifest cannot be read, an empty or non-string specifier, and every form whose install target is not determinable from the repo — `catalog:` (the target lives in `pnpm-workspace.yaml`), git specs (`github:`/`gitlab:`/`bitbucket:`/`git+…`/the bare `owner/repo` shorthand), remote tarball URLs, `jsr:` (which installs under a rewritten `@jsr/…` name), and any unrecognised `protocol:`. Falling back to the key for an unresolvable specifier is exactly the bypass, so a package that needs one of those forms must declare it in a shape the checker can see through. diff --git a/.github/scripts/check-boundaries.mjs b/.github/scripts/check-boundaries.mjs index f2ae85e58..e306773d1 100644 --- a/.github/scripts/check-boundaries.mjs +++ b/.github/scripts/check-boundaries.mjs @@ -3,8 +3,8 @@ * * core → (nothing; pure ES2020, no browser or node builtins) * polycss → core - * react → core (+ react, react-dom) — NEVER polycss - * vue → core (+ vue) — NEVER polycss + * react → core + polycss (/runtime) (+ react, react-dom) + * vue → core + polycss (/runtime) (+ vue) * fonts → core + earcut * morph → polycss public API (+ core); node builtins only under prepare/ * domformat→ (no workspace deps) @@ -42,8 +42,8 @@ const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", ".."); export const PACKAGE_RULES = { core: { allow: [] }, polycss: { allow: ["@layoutit/polycss-core"] }, - react: { allow: ["@layoutit/polycss-core", "react", "react-dom"] }, - vue: { allow: ["@layoutit/polycss-core", "vue"] }, + react: { allow: ["@layoutit/polycss-core", "@layoutit/polycss", "react", "react-dom"] }, + vue: { allow: ["@layoutit/polycss-core", "@layoutit/polycss", "vue"] }, fonts: { allow: ["@layoutit/polycss-core", "earcut"] }, morph: { allow: ["@layoutit/polycss", "@layoutit/polycss-core"] }, domformat: { allow: [] }, diff --git a/.github/scripts/check-boundaries.test.mjs b/.github/scripts/check-boundaries.test.mjs index 040cac0fd..b4ec60455 100644 --- a/.github/scripts/check-boundaries.test.mjs +++ b/.github/scripts/check-boundaries.test.mjs @@ -168,7 +168,7 @@ test("a forbidden import hidden behind a comment is still a violation", () => { withManifests( { "packages/react/src/sneak.ts": - 'import { createPolyScene } from /* not a comment escape */ "@layoutit/polycss";\n', + 'import { PolyScene } from /* not a comment escape */ "@layoutit/polycss-vue";\n', }, { react: { @@ -182,7 +182,7 @@ test("a forbidden import hidden behind a comment is still a violation", () => { assert.equal(violations.length, 1); assert.match( violations[0], - /sneak\.ts: disallowed dependency "@layoutit\/polycss"/, + /sneak\.ts: disallowed dependency "@layoutit\/polycss-vue"/, ); cleanup(root); }); @@ -192,8 +192,8 @@ test("a commented-out forbidden import is not a violation", () => { withManifests( { "packages/react/src/clean.ts": - '// import { createPolyScene } from "@layoutit/polycss";\n' + - 'const doc = `import "@layoutit/polycss";`;\nexport { doc };\n', + '// import { PolyScene } from "@layoutit/polycss-vue";\n' + + 'const doc = `import "@layoutit/polycss-vue";`;\nexport { doc };\n', }, { react: { @@ -210,13 +210,13 @@ test("a commented-out forbidden import is not a violation", () => { test("manifest check rejects a forbidden dependency in every shipped field", () => { for (const field of MANIFEST_DEPENDENCY_FIELDS) { const violations = checkManifestDependencies( - { name: "react", [field]: { "@layoutit/polycss": "workspace:^" } }, + { name: "react", [field]: { "@layoutit/polycss-vue": "workspace:^" } }, "react", PACKAGE_RULES.react, ); assert.equal(violations.length, 1, field); assert.match(violations[0], new RegExp(`disallowed ${field} entry`)); - assert.match(violations[0], /@layoutit\/polycss"/); + assert.match(violations[0], /@layoutit\/polycss-vue"/); } }); @@ -224,7 +224,10 @@ test("manifest check accepts allowed dependencies and ignores devDependencies", const violations = checkManifestDependencies( { name: "react", - dependencies: { "@layoutit/polycss-core": "workspace:^" }, + dependencies: { + "@layoutit/polycss-core": "workspace:^", + "@layoutit/polycss": "workspace:^", + }, peerDependencies: { react: "^19", "react-dom": "^19" }, devDependencies: { vitest: "^3", "happy-dom": "^15" }, }, @@ -234,7 +237,7 @@ test("manifest check accepts allowed dependencies and ignores devDependencies", assert.deepEqual(violations, []); }); -test("a react package depending on @layoutit/polycss fails end to end", () => { +test("a react package depending on @layoutit/polycss-vue fails end to end", () => { const root = makeRepo( withManifests( { "packages/react/src/index.ts": "export const a = 1;\n" }, @@ -243,7 +246,7 @@ test("a react package depending on @layoutit/polycss fails end to end", () => { name: "@layoutit/polycss-react", dependencies: { "@layoutit/polycss-core": "workspace:^", - "@layoutit/polycss": "workspace:^", + "@layoutit/polycss-vue": "workspace:^", }, }, }, @@ -253,8 +256,41 @@ test("a react package depending on @layoutit/polycss fails end to end", () => { assert.equal(violations.length, 1); assert.match( violations[0], - /packages\/react\/package\.json: disallowed dependencies entry "@layoutit\/polycss"/, + /packages\/react\/package\.json: disallowed dependencies entry "@layoutit\/polycss-vue"/, + ); + cleanup(root); +}); + +test("react and vue may depend on @layoutit/polycss/runtime", () => { + const root = makeRepo( + withManifests( + { + "packages/react/src/index.ts": + 'import { createPolyScene } from "@layoutit/polycss/runtime";\nexport { createPolyScene };\n', + "packages/vue/src/index.ts": + 'import { createPolyScene } from "@layoutit/polycss/runtime";\nexport { createPolyScene };\n', + }, + { + react: { + name: "@layoutit/polycss-react", + dependencies: { + "@layoutit/polycss-core": "workspace:^", + "@layoutit/polycss": "workspace:^", + }, + peerDependencies: { react: "^19", "react-dom": "^19" }, + }, + vue: { + name: "@layoutit/polycss-vue", + dependencies: { + "@layoutit/polycss-core": "workspace:^", + "@layoutit/polycss": "workspace:^", + }, + peerDependencies: { vue: "^3" }, + }, + }, + ), ); + assert.deepEqual(runChecks(root), []); cleanup(root); }); @@ -330,7 +366,7 @@ test("a .js deep import outside packages/ is caught", () => { }); test("generated and built output is not scanned", () => { - const bad = 'import { x } from "@layoutit/polycss";\nx;\n'; + const bad = 'import { x } from "@layoutit/polycss-vue";\nx;\n'; const root = makeRepo( withManifests({ "packages/react/dist/index.js": bad, @@ -381,7 +417,7 @@ test("an npm alias to a forbidden package is caught", () => { react: { name: "@layoutit/polycss-react", // Allowed KEY, forbidden install target. - dependencies: { "@layoutit/polycss-core": "npm:@layoutit/polycss@0.2.0" }, + dependencies: { "@layoutit/polycss-core": "npm:@layoutit/polycss-vue@0.2.0" }, }, }, ), @@ -390,7 +426,7 @@ test("an npm alias to a forbidden package is caught", () => { assert.equal(violations.length, 1); assert.match( violations[0], - /resolves to disallowed package "@layoutit\/polycss" via npm alias/, + /resolves to disallowed package "@layoutit\/polycss-vue" via npm alias/, ); cleanup(root); }); @@ -403,9 +439,9 @@ test("a link:/file: dependency is validated against the package it points at", ( { react: { name: "@layoutit/polycss-react", - dependencies: { "@layoutit/polycss-core": `${protocol}:../polycss` }, + dependencies: { "@layoutit/polycss-core": `${protocol}:../vue` }, }, - polycss: { name: "@layoutit/polycss" }, + vue: { name: "@layoutit/polycss-vue" }, }, ), ); @@ -414,7 +450,7 @@ test("a link:/file: dependency is validated against the package it points at", ( assert.match( violations[0], new RegExp( - `resolves to disallowed package "@layoutit/polycss" via ${protocol}: target`, + `resolves to disallowed package "@layoutit/polycss-vue" via ${protocol}: target`, ), ); cleanup(root); @@ -474,9 +510,9 @@ test("a workspace: relative path resolves to the package it points at", () => { name: "@layoutit/polycss-react", // Allowed KEY, forbidden install target, and no `@range` anywhere // for the alias parser to notice. - dependencies: { "@layoutit/polycss-core": "workspace:../polycss" }, + dependencies: { "@layoutit/polycss-core": "workspace:../vue" }, }, - polycss: { name: "@layoutit/polycss" }, + vue: { name: "@layoutit/polycss-vue" }, }, ), ); @@ -484,13 +520,13 @@ test("a workspace: relative path resolves to the package it points at", () => { assert.equal(violations.length, 1); assert.match( violations[0], - /resolves to disallowed package "@layoutit\/polycss" via workspace path target/, + /resolves to disallowed package "@layoutit\/polycss-vue" via workspace path target/, ); cleanup(root); }); test("an un-versioned workspace alias is resolved, not treated as a range", () => { - for (const spec of ["workspace:@layoutit/polycss", "workspace:@layoutit/polycss@*"]) { + for (const spec of ["workspace:@layoutit/polycss-react", "workspace:@layoutit/polycss-react@*"]) { const root = makeRepo( withManifests( {}, @@ -506,7 +542,7 @@ test("an un-versioned workspace alias is resolved, not treated as a range", () = assert.equal(violations.length, 1, spec); assert.match( violations[0], - /resolves to disallowed package "@layoutit\/polycss" via workspace alias/, + /resolves to disallowed package "@layoutit\/polycss-react" via workspace alias/, spec, ); cleanup(root); diff --git a/AGENTS.md b/AGENTS.md index a039b355a..2b79ab3ba 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,9 +11,9 @@ Monorepo layout (pnpm workspaces): | Package | npm name | Role | |---|---|---| | `packages/core` | `@layoutit/polycss-core` | Pure math: Vec3, Polygon, scene, camera, mesh ops, atlas planning. Zero browser globals (`lib: ES2020` only). | -| `packages/polycss` | `@layoutit/polycss` | Vanilla renderer + custom elements (``, etc.). Depends on `core` only. | -| `packages/react` | `@layoutit/polycss-react` | React components + hooks. Owns its own copy of atlas rasterisation. Depends on `core` only — **NOT on `polycss`.** | -| `packages/vue` | `@layoutit/polycss-vue` | Vue 3 mirror of React. Owns its own copy of atlas rasterisation. Depends on `core` only. | +| `packages/polycss` | `@layoutit/polycss` | Vanilla renderer + custom elements (``, etc.) + side-effect-free `@layoutit/polycss/runtime` subpath. Depends on `core` only. | +| `packages/react` | `@layoutit/polycss-react` | React components + hooks. May depend on `core` and `@layoutit/polycss/runtime`. | +| `packages/vue` | `@layoutit/polycss-vue` | Vue 3 mirror of React. May depend on `core` and `@layoutit/polycss/runtime`. | | `packages/fonts` | `@layoutit/polycss-fonts` | Fonts + text → extruded 3D `Polygon[]`. Framework-agnostic. Depends on `core` + `earcut`. | | `packages/morph` | `@layoutit/polycss-morph` | Framework-agnostic prepared-model contracts, Node preparation (`./prepare`), browser loading, retained DOM mounting, sparse deformation, skinning, and playback. No React/Vue mirrors. | | `packages/domformat` | `@layoutit/polycss-domformat` | Private strict-TypeScript `domformat@0` writer, reader, validator, CLI, and browser mount. Producer-neutral wire contract. Not published. | @@ -48,7 +48,7 @@ Public API is **mirrored** across React and Vue. Explicit `*/three` subpaths (`@ **For full `check-boundaries.mjs` and `check-mirrors.mjs` mechanics, read [.github/architecture/cross-package-and-mirrors.md](.github/architecture/cross-package-and-mirrors.md).** - React and Vue are mirror images: any public API or renderer fix in one must land in the other (and vanilla/core when applicable) in the same PR. -- Renderer-owned browser glue (`atlas/`, `voxelRenderer.ts`, `styles.ts`, `scene/mesh/`, `scene/`, `three/`) exists as independent copies across renderers (React/Vue never import `@layoutit/polycss`). +- Renderer-owned browser glue (`atlas/`, `voxelRenderer.ts`, `styles.ts`, `scene/mesh/`, `scene/`, `three/`) is mirrored across renderers while React/Vue migrate onto `@layoutit/polycss/runtime`. - Automated guards enforced in CI, `pnpm check:guards`, and `pnpm verify`: - `pnpm check:boundaries` — lexical import + manifest dependency enforcement (`DEEP_IMPORT_ALLOWLIST` is empty). - `pnpm check:mirrors --require-base` — identical react↔vue clones, 14 mirror sets covering all of `packages/{react,vue}/src` plus vanilla copies, per-pair & cross-lane-group diff parity (with `coreDelegations`) against base ref, and fail-closed tamper-evident waivers (`.github/mirror-waivers.json`). Note: touch parity ≠ semantic parity. From 14d56c49bcb1bb20d27ca1097fc617c46fce9ec2 Mon Sep 17 00:00:00 2001 From: alowpoly Date: Thu, 3 Dec 2026 15:30:33 -0300 Subject: [PATCH 3/9] refactor(renderers): collapse React and Vue onto @layoutit/polycss/runtime --- .../architecture/cross-package-and-mirrors.md | 15 +- .github/architecture/rendering-and-shadows.md | 2 +- .github/scripts/check-mirrors.mjs | 305 +------ .github/scripts/check-mirrors.test.mjs | 152 ++-- AGENTS.md | 16 +- bench/build.mjs | 1 + bench/gate/cases.mjs | 60 +- bench/renderer-ir-conformance.test.mjs | 24 +- packages/polycss/src/api/controls/common.ts | 7 +- packages/polycss/src/api/createPolyScene.ts | 42 +- packages/polycss/src/api/runtimeSeams.test.ts | 54 ++ .../polycss/src/api/scene/internalTypes.ts | 2 +- .../polycss/src/api/scene/lightingVars.ts | 2 +- packages/polycss/src/api/scene/mountSync.ts | 7 +- .../src/api/scene/shadowOrchestrator.ts | 134 ++- packages/polycss/src/api/scene/types.ts | 9 +- packages/polycss/src/styles/styles.ts | 78 -- packages/react/package.json | 1 + .../src/camera/PolyOrthographicCamera.tsx | 14 +- .../src/camera/PolyPerspectiveCamera.tsx | 14 +- packages/react/src/camera/context.ts | 9 + packages/react/src/camera/useCamera.ts | 171 +++- .../react/src/controls/PolyControls.test.tsx | 4 +- .../src/controls/PolyFirstPersonControls.tsx | 475 ++-------- .../react/src/controls/PolyMapControls.tsx | 240 ++--- .../react/src/controls/PolyOrbitControls.tsx | 236 ++--- .../react/src/controls/controlsEffects.ts | 162 ---- packages/react/src/controls/sharedControls.ts | 42 +- packages/react/src/helpers/PolyAxesHelper.tsx | 2 +- packages/react/src/renderStats.ts | 8 +- .../src/scene/PolyMesh.castShadow.test.tsx | 104 +-- .../scene/PolyMesh.dynamicLighting.test.tsx | 10 +- .../PolyMesh.receiverShadowPerf.test.tsx | 3 +- packages/react/src/scene/PolyMesh.tsx | 693 ++++++++------- packages/react/src/scene/PolyScene.test.tsx | 2 +- packages/react/src/scene/PolyScene.tsx | 634 +++++-------- packages/react/src/scene/atlas/atlasPoly.tsx | 187 ---- .../react/src/scene/atlas/borderShape.tsx | 143 --- .../src/scene/atlas/buildAtlasPages.test.ts | 348 -------- .../react/src/scene/atlas/buildAtlasPages.ts | 630 ------------- .../src/scene/atlas/cornerShapeSolid.test.tsx | 96 -- .../src/scene/atlas/cornerShapeSolid.tsx | 116 --- .../react/src/scene/atlas/detection.test.ts | 236 ----- packages/react/src/scene/atlas/detection.ts | 156 ---- .../react/src/scene/atlas/filterPlans.test.ts | 182 ---- packages/react/src/scene/atlas/filterPlans.ts | 39 - packages/react/src/scene/atlas/index.test.tsx | 392 --------- packages/react/src/scene/atlas/index.tsx | 76 -- .../react/src/scene/atlas/packing.test.ts | 209 ----- packages/react/src/scene/atlas/packing.ts | 38 - .../src/scene/atlas/paintDefaults.test.ts | 164 ---- .../react/src/scene/atlas/paintDefaults.ts | 55 -- .../src/scene/atlas/projectiveSolid.test.tsx | 73 -- .../react/src/scene/atlas/projectiveSolid.tsx | 78 -- .../src/scene/atlas/solidTriangleStyle.ts | 311 ------- .../src/scene/atlas/stableTriangleDom.ts | 286 ------ packages/react/src/scene/atlas/triangle.tsx | 55 -- .../react/src/scene/atlas/useTextureAtlas.ts | 221 ----- packages/react/src/scene/index.ts | 2 +- .../react/src/scene/mesh/useGroundShadow.tsx | 191 ---- packages/react/src/scene/mesh/useMeshAtlas.ts | 150 ---- .../react/src/scene/mesh/useMeshLighting.ts | 179 ---- .../src/scene/mesh/useReceiverShadows.tsx | 573 ------------ packages/react/src/scene/mesh/useStableDom.ts | 130 --- .../react/src/scene/mesh/useVoxelFastPath.ts | 76 -- packages/react/src/scene/sceneContext.ts | 123 +-- .../react/src/scene/voxelRenderer.test.ts | 70 -- packages/react/src/scene/voxelRenderer.ts | 832 ------------------ packages/react/src/shapes/Poly.tsx | 307 +++---- packages/react/src/shapes/types.ts | 2 +- packages/react/src/styles/styles.test.ts | 31 +- packages/react/src/styles/styles.ts | 467 +--------- packages/react/src/three/PolyThreeMesh.tsx | 29 +- .../src/three/PolyThreeOrthographicCamera.tsx | 6 +- .../src/three/PolyThreePerspectiveCamera.tsx | 6 +- packages/react/tsup.config.ts | 2 + packages/vue/package.json | 1 + .../vue/src/camera/PolyOrthographicCamera.ts | 13 +- .../vue/src/camera/PolyPerspectiveCamera.ts | 13 +- packages/vue/src/camera/context.ts | 19 +- packages/vue/src/camera/useCamera.ts | 161 +++- .../vue/src/controls/PolyControls.test.ts | 6 +- .../controls/PolyFirstPersonControls.test.ts | 5 +- .../src/controls/PolyFirstPersonControls.ts | 466 ++-------- packages/vue/src/controls/PolyMapControls.ts | 335 ++----- .../vue/src/controls/PolyOrbitControls.ts | 331 ++----- packages/vue/src/helpers/PolyAxesHelper.ts | 2 +- packages/vue/src/renderStats.ts | 8 +- .../vue/src/scene/PolyMesh.castShadow.test.ts | 101 +-- packages/vue/src/scene/PolyMesh.ts | 593 +++++++------ packages/vue/src/scene/PolyScene.test.ts | 2 +- packages/vue/src/scene/PolyScene.ts | 651 +++++--------- packages/vue/src/scene/atlas/atlasPoly.ts | 184 ---- packages/vue/src/scene/atlas/borderShape.ts | 122 --- .../src/scene/atlas/buildAtlasPages.test.ts | 337 ------- .../vue/src/scene/atlas/buildAtlasPages.ts | 630 ------------- .../src/scene/atlas/cornerShapeSolid.test.ts | 95 -- .../vue/src/scene/atlas/cornerShapeSolid.ts | 85 -- .../vue/src/scene/atlas/detection.test.ts | 232 ----- packages/vue/src/scene/atlas/detection.ts | 156 ---- .../vue/src/scene/atlas/filterPlans.test.ts | 182 ---- packages/vue/src/scene/atlas/filterPlans.ts | 39 - packages/vue/src/scene/atlas/index.test.ts | 444 ---------- packages/vue/src/scene/atlas/index.ts | 76 -- packages/vue/src/scene/atlas/packing.test.ts | 209 ----- packages/vue/src/scene/atlas/packing.ts | 38 - .../vue/src/scene/atlas/paintDefaults.test.ts | 164 ---- packages/vue/src/scene/atlas/paintDefaults.ts | 55 -- .../src/scene/atlas/projectiveSolid.test.ts | 60 -- .../vue/src/scene/atlas/projectiveSolid.ts | 71 -- .../vue/src/scene/atlas/solidTriangleStyle.ts | 311 ------- .../vue/src/scene/atlas/stableTriangleDom.ts | 286 ------ packages/vue/src/scene/atlas/triangle.ts | 52 -- .../vue/src/scene/atlas/useTextureAtlas.ts | 240 ----- packages/vue/src/scene/index.ts | 1 + .../vue/src/scene/mesh/useGroundShadow.ts | 185 ---- packages/vue/src/scene/mesh/useMeshAtlas.ts | 139 --- .../vue/src/scene/mesh/useMeshLighting.ts | 160 ---- .../vue/src/scene/mesh/useReceiverShadows.ts | 572 ------------ packages/vue/src/scene/mesh/useStableDom.ts | 126 --- .../vue/src/scene/mesh/useVoxelFastPath.ts | 71 -- packages/vue/src/scene/sceneContext.ts | 125 +-- packages/vue/src/scene/voxelRenderer.test.ts | 70 -- packages/vue/src/scene/voxelRenderer.ts | 832 ------------------ packages/vue/src/shapes/Poly.ts | 326 +++---- packages/vue/src/shapes/PolyShapes.test.ts | 7 +- packages/vue/src/styles/styles.test.ts | 29 +- packages/vue/src/styles/styles.ts | 440 +-------- packages/vue/src/three/PolyThreeMesh.ts | 32 +- .../src/three/PolyThreeOrthographicCamera.ts | 4 +- .../src/three/PolyThreePerspectiveCamera.ts | 4 +- packages/vue/tsup.config.ts | 8 +- pnpm-lock.yaml | 6 + website/astro.config.mjs | 4 + website/tsconfig.json | 1 + 135 files changed, 2678 insertions(+), 18240 deletions(-) delete mode 100644 packages/react/src/controls/controlsEffects.ts delete mode 100644 packages/react/src/scene/atlas/atlasPoly.tsx delete mode 100644 packages/react/src/scene/atlas/borderShape.tsx delete mode 100644 packages/react/src/scene/atlas/buildAtlasPages.test.ts delete mode 100644 packages/react/src/scene/atlas/buildAtlasPages.ts delete mode 100644 packages/react/src/scene/atlas/cornerShapeSolid.test.tsx delete mode 100644 packages/react/src/scene/atlas/cornerShapeSolid.tsx delete mode 100644 packages/react/src/scene/atlas/detection.test.ts delete mode 100644 packages/react/src/scene/atlas/detection.ts delete mode 100644 packages/react/src/scene/atlas/filterPlans.test.ts delete mode 100644 packages/react/src/scene/atlas/filterPlans.ts delete mode 100644 packages/react/src/scene/atlas/index.test.tsx delete mode 100644 packages/react/src/scene/atlas/index.tsx delete mode 100644 packages/react/src/scene/atlas/packing.test.ts delete mode 100644 packages/react/src/scene/atlas/packing.ts delete mode 100644 packages/react/src/scene/atlas/paintDefaults.test.ts delete mode 100644 packages/react/src/scene/atlas/paintDefaults.ts delete mode 100644 packages/react/src/scene/atlas/projectiveSolid.test.tsx delete mode 100644 packages/react/src/scene/atlas/projectiveSolid.tsx delete mode 100644 packages/react/src/scene/atlas/solidTriangleStyle.ts delete mode 100644 packages/react/src/scene/atlas/stableTriangleDom.ts delete mode 100644 packages/react/src/scene/atlas/triangle.tsx delete mode 100644 packages/react/src/scene/atlas/useTextureAtlas.ts delete mode 100644 packages/react/src/scene/mesh/useGroundShadow.tsx delete mode 100644 packages/react/src/scene/mesh/useMeshAtlas.ts delete mode 100644 packages/react/src/scene/mesh/useMeshLighting.ts delete mode 100644 packages/react/src/scene/mesh/useReceiverShadows.tsx delete mode 100644 packages/react/src/scene/mesh/useStableDom.ts delete mode 100644 packages/react/src/scene/mesh/useVoxelFastPath.ts delete mode 100644 packages/react/src/scene/voxelRenderer.test.ts delete mode 100644 packages/react/src/scene/voxelRenderer.ts delete mode 100644 packages/vue/src/scene/atlas/atlasPoly.ts delete mode 100644 packages/vue/src/scene/atlas/borderShape.ts delete mode 100644 packages/vue/src/scene/atlas/buildAtlasPages.test.ts delete mode 100644 packages/vue/src/scene/atlas/buildAtlasPages.ts delete mode 100644 packages/vue/src/scene/atlas/cornerShapeSolid.test.ts delete mode 100644 packages/vue/src/scene/atlas/cornerShapeSolid.ts delete mode 100644 packages/vue/src/scene/atlas/detection.test.ts delete mode 100644 packages/vue/src/scene/atlas/detection.ts delete mode 100644 packages/vue/src/scene/atlas/filterPlans.test.ts delete mode 100644 packages/vue/src/scene/atlas/filterPlans.ts delete mode 100644 packages/vue/src/scene/atlas/index.test.ts delete mode 100644 packages/vue/src/scene/atlas/index.ts delete mode 100644 packages/vue/src/scene/atlas/packing.test.ts delete mode 100644 packages/vue/src/scene/atlas/packing.ts delete mode 100644 packages/vue/src/scene/atlas/paintDefaults.test.ts delete mode 100644 packages/vue/src/scene/atlas/paintDefaults.ts delete mode 100644 packages/vue/src/scene/atlas/projectiveSolid.test.ts delete mode 100644 packages/vue/src/scene/atlas/projectiveSolid.ts delete mode 100644 packages/vue/src/scene/atlas/solidTriangleStyle.ts delete mode 100644 packages/vue/src/scene/atlas/stableTriangleDom.ts delete mode 100644 packages/vue/src/scene/atlas/triangle.ts delete mode 100644 packages/vue/src/scene/atlas/useTextureAtlas.ts delete mode 100644 packages/vue/src/scene/mesh/useGroundShadow.ts delete mode 100644 packages/vue/src/scene/mesh/useMeshAtlas.ts delete mode 100644 packages/vue/src/scene/mesh/useMeshLighting.ts delete mode 100644 packages/vue/src/scene/mesh/useReceiverShadows.ts delete mode 100644 packages/vue/src/scene/mesh/useStableDom.ts delete mode 100644 packages/vue/src/scene/mesh/useVoxelFastPath.ts delete mode 100644 packages/vue/src/scene/voxelRenderer.test.ts delete mode 100644 packages/vue/src/scene/voxelRenderer.ts diff --git a/.github/architecture/cross-package-and-mirrors.md b/.github/architecture/cross-package-and-mirrors.md index 204354810..a4e1c4828 100644 --- a/.github/architecture/cross-package-and-mirrors.md +++ b/.github/architecture/cross-package-and-mirrors.md @@ -24,17 +24,13 @@ When you change `packages/polycss` or `packages/core` in a way that affects the The DOM snapshot exporter is the current exception to mirrored React/Vue public exports: `exportPolySceneSnapshot` lives in `@layoutit/polycss` because it is browser DOM serialization, not component API. React/Vue callers import it from `@layoutit/polycss` and pass the rendered `.polycss-camera` / `.polycss-scene` element. -**Renderer-owned browser glue.** The canvas atlas pipeline (`buildAtlasPages` + helpers), browser-feature detection (`isBorderShapeSupported`, `isSolidTriangleSupported`, `resolveSolidTrianglePrimitive`), direct voxel renderer (`voxelRenderer.ts`), and the base stylesheet injector (`styles.ts`) currently exist as mirrored copies across the three renderers while React/Vue transition onto the side-effect-free `@layoutit/polycss/runtime` subpath. Until that migration completes, a bug fix in any of these files MUST be mirrored into the other two. Coverage is pinned per copy by the co-located test files. +**Single renderer runtime.** All DOM/CSS rendering — the canvas atlas pipeline, browser feature detection, direct voxel renderer, shadow orchestrator, base stylesheet (`styles.ts`), render stats, and camera/control engines — lives once in `@layoutit/polycss` and is exported through the side-effect-free `@layoutit/polycss/runtime` subpath. React and Vue are thin Adopt-DOM bindings (`createPolyScene(..., { elements: { cameraEl, sceneEl } })`, `scene.add(..., { wrapper })`, `injectPolyBaseStyles` re-export) rather than parallel renderer implementations. -**CI enforces this and the package boundaries.** `pnpm check:boundaries` (`.github/scripts/check-boundaries.mjs`) fails on any import that violates the package dependency boundaries in [AGENTS.md](../../AGENTS.md), on deep imports into another package's `src` (`DEEP_IMPORT_ALLOWLIST` is empty), and on node builtins outside the Node-only surfaces. It scans `.ts`/`.tsx`/`.mts`/`.cts` **and** `.mjs`/`.cjs`/`.js` sources (so the `packages/skills` CLI is covered). Specifiers are read by a single-pass **lexer**, not a regex over raw source, because pattern-matching is wrong in both directions: it misses valid imports (a comment between the keyword and the specifier, `import(\`x\`)`, a statement split across lines) and matches text that is not code (a commented-out import, an import-shaped string). The lexer skips comments, tracks single/double-quoted strings, template literals including `${}` nesting, and regex literals, and yields `import`/`export … from`, bare `import "x"`, `import()` and `require()` specifiers; a template WITH a substitution is not a static specifier and is ignored rather than crashed on. Quoted strings and regex literals may never span a newline, so a mis-lex in TSX (JSX apostrophes, `
`) recovers on the next line instead of swallowing code. The same allow-list is applied to each package's manifest: a `dependencies`, `optionalDependencies`, or `peerDependencies` entry outside the package's allow-list fails even when nothing imports it yet. `devDependencies` are tooling and are not constrained. The allow-list is applied to the RESOLVED dependency, not the manifest key, because the key is not what gets installed. Resolved forms: `npm:[@range]` aliases; `link:`/`file:`/`portal:` local paths and `workspace:` targets (both read through the target directory's own `package.json` name); and `workspace:[@range]` aliases, versioned or not. So `"@layoutit/polycss-core": "npm:@layoutit/polycss@0.2.0"`, `"workspace:@layoutit/polycss"` and `"workspace:../polycss"` all fail in React under the allowed key. Only bare ranges and dist-tags (`^0.2.0`, `*`, `latest`, `workspace:^`, `workspace:*`, `workspace:1.2.3`) leave the key standing. Everything else is a **violation, not a pass**: a local or workspace target whose manifest cannot be read, an empty or non-string specifier, and every form whose install target is not determinable from the repo — `catalog:` (the target lives in `pnpm-workspace.yaml`), git specs (`github:`/`gitlab:`/`bitbucket:`/`git+…`/the bare `owner/repo` shorthand), remote tarball URLs, `jsr:` (which installs under a rewritten `@jsr/…` name), and any unrecognised `protocol:`. Falling back to the key for an unresolvable specifier is exactly the bypass, so a package that needs one of those forms must declare it in a shape the checker can see through. +**CI enforces this and the package boundaries.** `pnpm check:boundaries` (`.github/scripts/check-boundaries.mjs`) fails on any import that violates the package dependency boundaries in [AGENTS.md](../../AGENTS.md), on deep imports into another package's `src` (`DEEP_IMPORT_ALLOWLIST` is empty), and on node builtins outside the Node-only surfaces. It scans `.ts`/`.tsx`/`.mts`/`.cts` **and** `.mjs`/`.cjs`/`.js` sources (so the `packages/skills` CLI is covered). Specifiers are read by a single-pass **lexer**, not a regex over raw source, because pattern-matching is wrong in both directions: it misses valid imports (a comment between the keyword and the specifier, `import(\`x\`)`, a statement split across lines) and matches text that is not code (a commented-out import, an import-shaped string). The lexer skips comments, tracks single/double-quoted strings, template literals including `${}` nesting, and regex literals, and yields `import`/`export … from`, bare `import "x"`, `import()` and `require()` specifiers; a template WITH a substitution is not a static specifier and is ignored rather than crashed on. Quoted strings and regex literals may never span a newline, so a mis-lex in TSX (JSX apostrophes, ``) recovers on the next line instead of swallowing code. The same allow-list is applied to each package's manifest: a `dependencies`, `optionalDependencies`, or `peerDependencies` entry outside the package's allow-list fails even when nothing imports it yet. `devDependencies` are tooling and are not constrained. The allow-list is applied to the RESOLVED dependency, not the manifest key, because the key is not what gets installed. Resolved forms: `npm:[@range]` aliases; `link:`/`file:`/`portal:` local paths and `workspace:` targets (both read through the target directory's own `package.json` name); and `workspace:[@range]` aliases, versioned or not. So `"@layoutit/polycss-core": "npm:@layoutit/polycss-vue@0.2.0"`, `"workspace:@layoutit/polycss-vue"` and `"workspace:../vue"` all fail in React under the allowed key. Only bare ranges and dist-tags (`^0.2.0`, `*`, `latest`, `workspace:^`, `workspace:*`, `workspace:1.2.3`) leave the key standing. Everything else is a **violation, not a pass**: a local or workspace target whose manifest cannot be read, an empty or non-string specifier, and every form whose install target is not determinable from the repo — `catalog:` (the target lives in `pnpm-workspace.yaml`), git specs (`github:`/`gitlab:`/`bitbucket:`/`git+…`/the bare `owner/repo` shorthand), remote tarball URLs, `jsr:` (which installs under a rewritten `@jsr/…` name), and any unrecognised `protocol:`. Falling back to the key for an unresolvable specifier is exactly the bypass, so a package that needs one of those forms must declare it in a shape the checker can see through. -`pnpm check:mirrors` (`.github/scripts/check-mirrors.mjs`) keeps the copy discipline honest without any static hash lock file, in two ways: react↔vue clones in `IDENTICAL_GROUPS` must stay byte-identical; and every structurally-divergent mirror set (14 sets covering 100% of `packages/react/src` and `packages/vue/src`, plus the vanilla atlas, `voxelRenderer.ts`, and `styles.ts` mirrors) is checked for filesystem structure and diffed against a base ref (`--base`, else `origin/$GITHUB_BASE_REF`, else `origin/main`, else local `main`) at two granularities. Per mirrored **pair**: same-named files across the lanes the set declares in `pairLanes` (`useReceiverShadows.tsx` ↔ `useReceiverShadows.ts`), each validated independently — if one member moved, its counterpart must move in the same diff. Per **cross-lane group** (`crossLaneGroups`), for units whose files do not match by name or cardinality across lanes (with optional `coreDelegations` when a lane delegates directly to `packages/core/src/...`, e.g. vanilla `solid-triangle-leaf` delegating to `packages/core/src/atlas/solidTrianglePlan.ts`). +`pnpm check:mirrors` (`.github/scripts/check-mirrors.mjs`) keeps React↔Vue adapter parity honest without any static hash lock file, in two ways: react↔vue identical files in `IDENTICAL_GROUPS` (`styles.ts`, `renderStats.ts`, `three/index.ts`, `PolyCamera`, `helpers/index.ts`) must stay byte-identical; and every structurally-divergent mirror set (12 sets covering 100% of `packages/react/src` and `packages/vue/src`) is checked for filesystem structure and diffed against a base ref (`--base`, else `origin/$GITHUB_BASE_REF`, else `origin/main`, else local `main`) at two granularities. Per mirrored **pair**: same-named files across the lanes the set declares in `pairLanes` (`useMeshGeometry.ts` ↔ `useMeshGeometry.ts`), each validated independently — if one member moved, its counterpart must move in the same diff. Per **cross-lane group** (`crossLaneGroups`), for units whose files do not match by name or cardinality across lanes (`controls` where `TransformControls.tsx` ↔ `PolyTransformControls.ts` and `sharedControls.ts` lives on React; `select` where `Select.tsx` ↔ `PolySelect.ts`). -Pairing is **declared per set**, not inferred across every lane, because a shared file name is not proof of a counterpart. `atlas-pipeline` pairs react↔vue by basename and uses `crossLaneGroups` for vanilla↔framework; `voxel-renderer` and `base-styles` pair all three; `controls` and `select` use `crossLaneGroups` for React↔Vue where file splits differ (`TransformControls.tsx` ↔ `PolyTransformControls.ts`, `Select.tsx` ↔ `PolySelect.ts`); and `mesh-modules`, `scene-components`, `three-adapters`, `animation`, `camera`, `helpers`, `shapes`, `store`, and `package-root` pair react↔vue by basename. - -The vanilla↔framework direction is **not** left to the coarse lane check. `atlas-pipeline` declares an explicit correspondence table, `crossLaneGroups`: each entry names one semantic unit of the pipeline and, per lane, the file(s) that implement it, at whatever cardinality the code actually has. If any file in a group changed, **every lane represented in that group must have changed** — so a vanilla-only atlas fix now fails even when other vanilla-lane files moved in the same diff (the bypass it closes). The current groups are `rasterisation` (vanilla `rasterise.ts` ↔ framework `buildAtlasPages.ts`), `capability-detection-and-plan-filtering` (vanilla `strategy.ts` ↔ `detection.ts` + `filterPlans.ts`), `packing`, `plan-construction-and-orchestration` (vanilla `plan.ts` + `renderPolygons.ts` ↔ `paintDefaults.ts` + `useTextureAtlas.ts`), `leaf-emission-and-solid-paint` (vanilla `emit.ts` + `paintDefaults.ts` ↔ `atlasPoly` + `borderShape` + `cornerShapeSolid` + `projectiveSolid`), `solid-triangle-leaf` (vanilla `solidTrianglePlan.ts` + `stableTriangle.ts` + core delegation `packages/core/src/atlas/solidTrianglePlan.ts` ↔ `solidTriangleStyle.ts` + `stableTriangleDom.ts` + `triangle`), and `barrel`. Two same-name pairs are **false friends** and the table says so: framework `paintDefaults.ts` mirrors vanilla `plan.ts`/`renderPolygons.ts`, not vanilla `paintDefaults.ts`; only `packing.ts` is a genuine same-name counterpart across all three. The table is validated against the filesystem on every run: every declared file (and `coreDelegations` path) must exist, each group must span at least two lanes, no file may sit in two groups, and a set that declares groups must place **every** member in exactly one of them. Because a group divergence is narrower than a lane divergence, a waiver's `expectedLanes` is matched against the lanes of the diverging **unit**, not the set-wide lane summary. - -**Set structure is checked off the filesystem before any base ref is resolved.** Lane parity can only compare files that exist and are declared, which leaves it blind to a NEW module added to one lane or a DELETED counterpart. Each sync set therefore declares `laneRoots` — the directories it owns — and three rules run against the tree itself: every non-test source file under those roots must be declared; every declared member must still exist; and every pair key must be present in every one of the set's `pairLanes`. Deliberately lane-local files are declared in a set's `unmirrored` map with a reason, and each entry must still point at a real file so the exemption list cannot go stale (currently vanilla `atlas/types.ts`, React/Vue `styles/index.ts`, and React `shapes/types.ts`). +**Set structure is checked off the filesystem before any base ref is resolved.** Lane parity can only compare files that exist and are declared, which leaves it blind to a NEW module added to one lane or a DELETED counterpart. Each sync set therefore declares `laneRoots` — the directories it owns — and three rules run against the tree itself: every non-test source file under those roots must be declared; every declared member must still exist; and every pair key must be present in every one of the set's `pairLanes`. Deliberately lane-local files are declared in a set's `unmirrored` map with a reason, and each entry must still point at a real file so the exemption list cannot go stale (currently React `shapes/types.ts`). **What the mirror check can and cannot prove.** It proves mechanical parity: both sides of a pair or a declared cross-lane group changed in the same diff, both still exist, neither side is a pure deletion, and no module joined a mirrored directory in one lane only. It does **not** prove the two changes are the SAME change. **Touch parity is not semantic parity** — semantic equivalence is a review responsibility and is further checked by `pnpm check:ir` and `pnpm bench:gate:parity`. Co-located tests are excluded from mirror discovery because test filenames diverge across lanes by convention. @@ -46,8 +42,7 @@ Before opening a PR: - [ ] If I touched a Vue component/composable, the React component/hook matches. - [ ] If I added an option to a `polycss` factory, both bindings expose it. - [ ] If I renamed a `core` export, every package that imports it is updated. -- [ ] If I touched the canvas atlas pipeline (`rasterise.ts` / `buildAtlasPages.ts`), browser-feature detection, or direct voxel renderer in ONE renderer, the same fix lands in the other two renderers (`polycss` + react + vue) in this PR. -- [ ] If I touched any of the three `styles.ts` files (`packages/polycss/src/styles/styles.ts`, `packages/react/src/styles/styles.ts`, `packages/vue/src/styles/styles.ts`), the CSS rules cover every emitted tag for both lighting modes and shared properties like `will-change: transform` on `.polycss-scene` hold across all three renderers. +- [ ] If I touched `packages/polycss/src/styles/styles.ts`, the CSS rules cover every emitted tag for both lighting modes and shared properties like `will-change: transform` on `.polycss-scene`. - [ ] Website docs (`website/src/content/docs/**`) and READMEs reflect any user-visible change. - [ ] If a user-visible change contradicts the agent skill, `packages/skills/skill/**` is updated and `pnpm sync:skill` has been run (see [docs-and-skill-eval.md](./docs-and-skill-eval.md)). - [ ] If I edited a `` block, I edited it in the ROOT `README.md` and ran `pnpm sync:readmes` (see [docs-and-skill-eval.md](./docs-and-skill-eval.md)). diff --git a/.github/architecture/rendering-and-shadows.md b/.github/architecture/rendering-and-shadows.md index 322b972e3..e6db67c4e 100644 --- a/.github/architecture/rendering-and-shadows.md +++ b/.github/architecture/rendering-and-shadows.md @@ -23,7 +23,7 @@ Strategies are ordered cheapest → most expensive. The mesher's job is to maxim Callers can opt out of specific strategies via `strategies: { disable: ["b" | "i" | "u"] }` on `RenderTextureAtlasOptions`. Disabled or unsupported strategies fall through the chain (`b → i → s`, `u → i → s`, `i → s`). Disabling `"i"` also disables the exact corner-shape solid branch even though that branch emits a bare ``, because it belongs to the non-triangle clipped-solid family. `` is the universal fallback and cannot be disabled. Solid seam bleed gives detected shared solid edges a per-edge overscan, fitted to the polygon plan, rather than inflating every side of each participating polygon. It IS exposed: `seamBleed` is a scene option in all three renderers plus a React/Vue per-mesh prop, though not a custom-element attribute. Semantics are unified and owned by core (`resolveSeamBleedPx` / `seamBleedPrimitiveRatio` in `packages/core/src/atlas/constants.ts`; renderers pass the raw option through): `undefined`/`"auto"` → the `1.5` px default (`DEFAULT_SEAM_BLEED`); a finite number ≥ 0 is the requested overscan in CSS px with no upper clamp (the per-edge geometric fit still bounds each edge); negative/non-finite values fall back to the default. The same option scales the per-strategy primitive bleeds (`SOLID_TRIANGLE_BLEED`, `BORDER_SHAPE_BLEED`, `TEXTURE_TRIANGLE_BLEED`, and the projective-quad guard bleed) by `clamp(px / 1.5, 0, 1)` — so `0` disables every bleed, sub-`1.5` values shrink primitives proportionally, and larger values keep primitives at full strength while the seam overscan uses the raw px. All three renderers also honor the `window.__polycssProjectiveQuadGuards` debug override for projective-quad guards, merged over the seam-scaled default. -Cast shadows are not a render-strategy leaf tag. Meshes with `castShadow: true` project casting polygons on the CPU into SVG shadow surfaces onto scene-level receiver surfaces where `receiveShadow` is enabled. **Renderer divergence on the no-receiver case:** vanilla dropped its legacy virtual ground-shadow fallback for Three.js parity — a caster with no receiver in the scene draws nothing; the dead `emitGroundShadow` emitter has been removed entirely, and `hideGroundShadow()` suppresses any legacy leftovers every tick. React/Vue still emit a per-mesh ground-plane shadow when a caster has no receiver — but only when a real, nonzero-intensity directional light exists (same gate as the receiver path; no implicit default-sun shadow) — and drop it as soon as any receiver exists. Reconciling the two is an open decision. EVERY polygon casts — shadow casters are NOT filtered to the camera-rendered set (atlas plan), because a polygon casts a shadow regardless of whether it's painted for the camera; filtering left camera-dependent holes in imported-mesh shadows. Coincident/back-to-back duplicate faces ARE pre-dropped, via `findOverlappingPolygonDuplicates` in all three renderers (vanilla `dedupByCaster`, React/Vue `dedupDrop`). Remaining overlapping projections are merged into one compound path per caster under `fill-rule: nonzero` so they don't alpha-stack, rather than being dropped. The directional light projects in parallel; each `pointLights` entry with `castShadow: true` casts an additional **radial** shadow (each vertex projected along its own ray from the light position), and point-light passes always project the caster *silhouette* — projecting individual back-faces leaves the contact footprint unshadowed under radial divergence. Shadows are **shaded, not flat black**: each light's shadow is filled with the receiver lit by every OTHER light (the blocked light removed), so a region shadowed from one colored light still shows the remaining lights' color (Three.js colored shadows). A lone directional light reduces this to the ambient-only fill (unchanged). All of a receiver FACE's lights are merged into **one SVG per face** so overlapping shadows composite correctly: a single-light SOLID face normally paints one path filled with the remaining-light color at `shadow.opacity`, and switches to the PRE-BLENDED color `blend(fullLitFill, remaining, shadow.opacity)` at alpha 1 only when that face actually bled a crease (see below) — the identical pixel over the lit receiver (the blend is exact at antialiased coverage too), but idempotent under overlap, which is what makes the crease bleed safe. The opaque form is NOT free elsewhere: `shadow.lift` floats the SVG above its face, and at grazing camera angles that parallax hangs part of the card past the receiver's silhouette, where opaque paint deviates from the backdrop about 4× as much as 25% alpha did (measured headlessly: mean Δ 54 → 209 of 255 over ~580 off-surface px on a lit cube; `lift=0` removes 99% of those px, confirming parallax as the cause). So the pre-blend is paid only where it buys the seam fix. `MergedShadowFace.layers[].opacity` therefore carries `shadow.opacity` for an ordinary single-light solid face and `1` for a crease-bled one — callers must read the field, never assume either; a multi-light solid face paints a base = full-lit color `C` then each light as a `mix-blend-mode: multiply` layer with factor `remaining/C`, so the both-blocked overlap becomes `C·∏factor` (ambient only). `mix-blend-mode` works *within* one SVG but NOT across SVGs (`preserve-3d` isolates each SVG against a transparent backdrop — verified), which is why the merge is per-face rather than per-light. Textured receivers (per-pixel base, no uniform multiply) fall back to per-pass alpha layers that cumulatively darken. The per-face color uses the face CENTROID direction (matching the baked per-polygon shading) so the base leaves no visible color box. The per-face merge is the shared core helper `computeMergedReceiverShadows` (runs every light pass + aggregates each face into one SVG descriptor); all three renderers call it and only emit the ``/`` nodes, so multi-light overlap is identical everywhere. Moving a light or changing caster/receiver geometry re-emits the shadow SVGs; this is DOM/SVG work only and does not redraw texture atlases. +Cast shadows are not a render-strategy leaf tag. Meshes with `castShadow: true` project casting polygons on the CPU into SVG shadow surfaces onto scene-level receiver surfaces where `receiveShadow` is enabled. All three renderers share the single shadow orchestrator in `@layoutit/polycss/runtime` (`shadowOrchestrator.ts` / `receiverShadow.ts`). **No-receiver ground fallback:** vanilla defaults to `groundShadowFallback: false` (Three.js parity — a caster with no receiver draws nothing), while React/Vue pass `groundShadowFallback: true` to emit a compound ground-plane shadow SVG when a nonzero-intensity directional light exists and drop it as soon as any receiver mounts. EVERY polygon casts — shadow casters are NOT filtered to the camera-rendered set (atlas plan), because a polygon casts a shadow regardless of whether it's painted for the camera; filtering left camera-dependent holes in imported-mesh shadows. Coincident/back-to-back duplicate faces ARE pre-dropped via `findOverlappingPolygonDuplicates` (`dedupByCaster`). Remaining overlapping projections are merged into one compound path per caster under `fill-rule: nonzero` so they don't alpha-stack, rather than being dropped. The directional light projects in parallel; each `pointLights` entry with `castShadow: true` casts an additional **radial** shadow (each vertex projected along its own ray from the light position), and point-light passes always project the caster *silhouette* — projecting individual back-faces leaves the contact footprint unshadowed under radial divergence. Shadows are **shaded, not flat black**: each light's shadow is filled with the receiver lit by every OTHER light (the blocked light removed), so a region shadowed from one colored light still shows the remaining lights' color (Three.js colored shadows). A lone directional light reduces this to the ambient-only fill (unchanged). All of a receiver FACE's lights are merged into **one SVG per face** so overlapping shadows composite correctly: a single-light SOLID face normally paints one path filled with the remaining-light color at `shadow.opacity`, and switches to the PRE-BLENDED color `blend(fullLitFill, remaining, shadow.opacity)` at alpha 1 only when that face actually bled a crease (see below) — the identical pixel over the lit receiver (the blend is exact at antialiased coverage too), but idempotent under overlap, which is what makes the crease bleed safe. The opaque form is NOT free elsewhere: `shadow.lift` floats the SVG above its face, and at grazing camera angles that parallax hangs part of the card past the receiver's silhouette, where opaque paint deviates from the backdrop about 4× as much as 25% alpha did (measured headlessly: mean Δ 54 → 209 of 255 over ~580 off-surface px on a lit cube; `lift=0` removes 99% of those px, confirming parallax as the cause). So the pre-blend is paid only where it buys the seam fix. `MergedShadowFace.layers[].opacity` therefore carries `shadow.opacity` for an ordinary single-light solid face and `1` for a crease-bled one — callers must read the field, never assume either; a multi-light solid face paints a base = full-lit color `C` then each light as a `mix-blend-mode: multiply` layer with factor `remaining/C`, so the both-blocked overlap becomes `C·∏factor` (ambient only). `mix-blend-mode` works *within* one SVG but NOT across SVGs (`preserve-3d` isolates each SVG against a transparent backdrop — verified), which is why the merge is per-face rather than per-light. Textured receivers (per-pixel base, no uniform multiply) fall back to per-pass alpha layers that cumulatively darken. The per-face color uses the face CENTROID direction (matching the baked per-polygon shading) so the base leaves no visible color box. The per-face merge is the shared core helper `computeMergedReceiverShadows` (runs every light pass + aggregates each face into one SVG descriptor); the runtime shadow emitter turns those descriptors into ``/`` nodes. Moving a light or changing caster/receiver geometry re-emits the shadow SVGs; this is DOM/SVG work only and does not redraw texture atlases. **Receiver-clip seam bleed (the pale-hairline classes).** Each receiver face group clips its shadow to the union of its member polygons, and two abutting antialiased clip edges do not sum to full coverage — so every receiver edge that a shadow crosses can show as a pale hairline. `prepareReceiverFacePlanes` therefore carries two per-member edge sets, and `computeReceiverShadowFaces` unions them into ONE outward clip expansion of `SHADOW_CLIP_SEAM_BLEED`: `memberSharedEdges` (neighbour is another member of the SAME coplanar group — the subpaths land in one nonzero compound path, so this is always on) and `memberCreaseEdges` (neighbour is a member of a DIFFERENT, non-coplanar group — a crease, and by far the dominant class on imported architecture). Crease adjacency is matched in WORLD space, since crease neighbours are not coplanar and the 2D `planarEdgesShareLine` predicate does not apply: matching runs on `memberPolysWorld` — each member's TRUE world vertices, carried alongside the (u, v) outline — via an exact quantized endpoint-pair hash, then `spatialEdgesShareLine` (the world-space sibling of the 2D predicate, same tolerances) over a uniform spatial hash restricted to edges the exact pass left unmatched. It must NOT lift the (u, v) outline back to 3D: that lift is exact only for members perfectly coplanar with their group plane, and imported architecture routinely is not (the castle has quads whose vertices sit ~0.3 CSS px off their own plane). Projecting drops that offset, so two groups snap the SAME shared vertex to two different points and push an exactly-shared crease past `RECEIVER_EDGE_PERP_EPS` (0.25) — which silently hid 272 of the castle's creases and left exactly the hairlines the pass exists to close. Edges already in `memberSharedEdges` stay in the candidate pool AND record their crease neighbours like any other edge. The mark cannot change their own clip expansion (an edge gets one bleed amount whether it is shared, crease, or both), but it is what flips the face to its opaque pre-blend, and it is the direction `qualifiesCrease`'s reciprocity condition reads. Suppressing it was a real bug: on a floor grouped from two coplanar quads with a wall standing on their shared edge — tessellated/greedy-merged architecture, the castle's dominant interior-partition shape — the exact hash recorded wall→floor but never floor→wall, so BOTH sides refused to bleed and the hairline came back. It also left the wall's opaque strip lying over a floor still painting at alpha, which composites by SVG paint order. True mesh-boundary edges have no neighbour in either set and are never bled, so shadow can never be pushed off the model's silhouette. Crease bleed makes two SVGs' shadow regions OVERLAP, which only composites correctly under the opaque pre-blend, so it is enabled only where that pre-blend is BOTH available and exact — and that is decided from the resolved colors BEFORE any clip is expanded, because expanded clips painted at fractional alpha are precisely the double-darkening the design exists to avoid. Three conditions, all checked per face per pass: a solid receiver; exactly ONE light pass; and every member of the group painting exactly `fullLitFill` — verified by re-shading each member from its OWN normal and centroid (`groupMembersShareLitColor`), not assumed from a shared base color. Those make a face ELIGIBLE; they say nothing about the neighbour it would bleed into, and eligibility alone is not licence to expand. `memberCreaseEdges` therefore stores the neighbouring PLANE INDICES (not bare normals), and `qualifiesCrease` requires four things of the neighbour across a given edge: it faces the camera (otherwise the crease is the camera silhouette and the expansion hangs in free space past the model outline); it EMITS a layer in this same pass (a camera-facing neighbour need not be a shadowed one — under a vertical light a side face fails `L·n` and emits no SVG, and bleeding into it paints shadow onto lit surface with nothing to fuse with); its resolved opaque pre-blend is the SAME colour (each face's pre-blend derives from its own lit colour, and crease neighbours are non-coplanar by construction, so the two usually differ — overlapping two different opaque fills is not idempotent, it just paints one over the other, a seam of the wrong colour, measured `rgb(79,79,79)` over `rgb(69,69,69)` on the standard L fixture); and it bleeds BACK toward this face, so neither side is left painting at alpha under the other's opaque strip. Answering "does the neighbour emit?" needs emission before expansion, so `computeReceiverShadowFaces` runs in two phases: phase 1 computes every face with crease bleed off (emission is crease-independent — a bleed only ever GROWS a member clip), phase 2 re-runs only the planes that end up with a qualifying neighbour. Where nothing qualifies — the common case, since differing lit colours are the norm at a crease — phase 2 does no work and the face keeps the alpha form and unexpanded clips. A group is formed by plane + adjacency, so neither one material nor one normal follows from membership: `RECEIVER_NORMAL_TOL` admits members ~2.5° apart, and over that spread the residual `(leaf − fullLitFill)·(1 − opacity)` was measured up to 11/255 at the default opacity 0.25 (bright base, low ambient, grazing light) — visible, so those groups keep the alpha form. On the castle the check costs 7 of 2286 groups and zero mounted shadow faces. The pre-blend must also be REPRESENTABLE: `blendShadowOverLitBase` returns null for a non-opaque-hex color, which a translucent receiver always produces (`shadePolygon` preserves alpha as `rgba(...)`), and such a face keeps unexpanded clips at its own alpha. Textured receivers, multi-light merged faces, multi-colored coplanar groups, groups with non-uniform member shading, and translucent receivers all keep the alpha form and get no crease bleed. `ReceiverFacePlane` carries `memberPolysWorld`, `memberSharedEdges`, and `memberCreaseEdges` as OPTIONAL fields — `prepareReceiverFacePlanes` always fills them, and a hand-built plane passed straight to `computeReceiverShadowFaces` still type-checks and simply gets no seam bleed, no crease bleed, and no pre-blend (its members' shading cannot be verified). That degradation is deliberate: it is the safe answer, not a silent approximation. The shadow clip applies the group's convex outline BEFORE the per-member clips, so the stored `RECEIVER_OUTLINE_EXPAND` (0.5) would cap the per-edge amount wherever a crease sits on the hull — 91% of the castle's crease edges, held to 0.5 px of the 0.75 px they were granted. `computeReceiverShadowFaces` therefore widens its own COPY of the hull by the shortfall (`CLIP_OUTLINE_EXTRA`), and only where crease bleed is already active. The stored outline keeps its 0.5, because it also sizes each face plane's `minU/minV/width/height/matrixCss`: widening it unconditionally shifts emitted geometry on multi-light and textured receivers, which get no crease bleed at all (measured — it moved 40 SVGs on a multi-light castle). The hull is not the surface boundary, the member clips are, and they still bound every edge, so widening the clip copy cannot push shadow past a member outline. diff --git a/.github/scripts/check-mirrors.mjs b/.github/scripts/check-mirrors.mjs index 6c826eda7..5f8153b16 100644 --- a/.github/scripts/check-mirrors.mjs +++ b/.github/scripts/check-mirrors.mjs @@ -56,45 +56,17 @@ const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", ".."); /** Files that must be byte-identical. First entry is the reference copy. */ export const IDENTICAL_GROUPS = [ { - name: "voxel-renderer (react↔vue)", + name: "base-styles re-export (react↔vue)", files: [ - "packages/react/src/scene/voxelRenderer.ts", - "packages/vue/src/scene/voxelRenderer.ts", - ], - }, - { - name: "atlas buildAtlasPages (react↔vue)", - files: [ - "packages/react/src/scene/atlas/buildAtlasPages.ts", - "packages/vue/src/scene/atlas/buildAtlasPages.ts", - ], - }, - { - name: "atlas detection (react↔vue)", - files: [ - "packages/react/src/scene/atlas/detection.ts", - "packages/vue/src/scene/atlas/detection.ts", - ], - }, - { - name: "atlas filterPlans (react↔vue)", - files: [ - "packages/react/src/scene/atlas/filterPlans.ts", - "packages/vue/src/scene/atlas/filterPlans.ts", - ], - }, - { - name: "atlas packing (react↔vue)", - files: [ - "packages/react/src/scene/atlas/packing.ts", - "packages/vue/src/scene/atlas/packing.ts", + "packages/react/src/styles/styles.ts", + "packages/vue/src/styles/styles.ts", ], }, { - name: "atlas paintDefaults (react↔vue)", + name: "renderStats re-export (react↔vue)", files: [ - "packages/react/src/scene/atlas/paintDefaults.ts", - "packages/vue/src/scene/atlas/paintDefaults.ts", + "packages/react/src/renderStats.ts", + "packages/vue/src/renderStats.ts", ], }, { @@ -149,226 +121,11 @@ export const IDENTICAL_GROUPS = [ * must name a reason. */ export const SYNC_SETS = [ - { - name: "atlas-pipeline", - // react↔vue only: the vanilla lane splits this work into different files - // (plan.ts, strategy.ts, renderPolygons.ts), so its same-named members are - // not per-file counterparts. See derivePairs. The vanilla↔framework - // correspondence is declared explicitly in `crossLaneGroups` below. - pairLanes: ["react", "vue"], - /** - * The explicit vanilla↔framework mapping. Same-name pairing cannot express - * this lane: the vanilla copy splits and merges the work differently, and - * two of the shared basenames are FALSE friends. Each group was derived by - * reading the files; the evidence is on each entry. - */ - crossLaneGroups: [ - { - name: "rasterisation", - // Same 15 exports in the same order (TEXTURE_IMAGE_CACHE … - // buildAtlasPages); the framework header names rasterise.ts as source. - files: [ - "packages/polycss/src/render/atlas/rasterise.ts", - "packages/react/src/scene/atlas/buildAtlasPages.ts", - "packages/vue/src/scene/atlas/buildAtlasPages.ts", - ], - }, - { - name: "capability-detection-and-plan-filtering", - // detection.ts is a verbatim copy of strategy.ts's capability half - // (isBorderShapeSupported, resolveSolidTrianglePrimitive, - // projectiveQuadSupported …); filterPlans.ts is strategy.ts's - // filterAtlasPlans split into its own file, same 7-arg signature. - files: [ - "packages/polycss/src/render/atlas/strategy.ts", - "packages/react/src/scene/atlas/detection.ts", - "packages/react/src/scene/atlas/filterPlans.ts", - "packages/vue/src/scene/atlas/detection.ts", - "packages/vue/src/scene/atlas/filterPlans.ts", - ], - }, - { - name: "packing", - // Genuine same-name counterparts: identical isMobileDocument and - // packTextureAtlasPlansWithScale wrappers over the core packer. - files: [ - "packages/polycss/src/render/atlas/packing.ts", - "packages/react/src/scene/atlas/packing.ts", - "packages/vue/src/scene/atlas/packing.ts", - ], - }, - { - name: "leaf-emission-and-solid-paint", - // 1:many. vanilla emit.ts owns every create*Element; the framework - // splits them per component (createAtlasElement ↔ TextureAtlasPoly, - // createProjectiveSolidElement ↔ TextureProjectiveSolidPoly, - // createSolidElement + createBorderShapeSolidElement ↔ the one - // TextureBorderShapePoly that branches fullRect → else ). - // vanilla paintDefaults.ts is the paint half: cornerShapeSolid's - // formatPaintCss is a transcription of formatInitialSolidPaintStyle, - // and borderShape/projectiveSolid inline the same --pn*/--ps* logic. - files: [ - "packages/polycss/src/render/atlas/emit.ts", - "packages/polycss/src/render/atlas/paintDefaults.ts", - "packages/react/src/scene/atlas/atlasPoly.tsx", - "packages/react/src/scene/atlas/borderShape.tsx", - "packages/react/src/scene/atlas/cornerShapeSolid.tsx", - "packages/react/src/scene/atlas/projectiveSolid.tsx", - "packages/vue/src/scene/atlas/atlasPoly.ts", - "packages/vue/src/scene/atlas/borderShape.ts", - "packages/vue/src/scene/atlas/cornerShapeSolid.ts", - "packages/vue/src/scene/atlas/projectiveSolid.ts", - ], - }, - { - name: "solid-triangle-leaf", - // many:many, and deliberately NOT split finer. The plan/style/DOM cut - // falls in a different place per lane: vanilla keeps triangle ELEMENT - // creation (createSolidTriangleElement) in stableTriangle.ts while the - // framework puts it in triangle.tsx, and vanilla's - // SOLID_TRIANGLE_BORDER_WIDTH ("0 48px 96px 48px") lives in - // stableTriangle.ts against the framework's solidTriangleStyle.ts. - // Vanilla's solidTrianglePlan.ts delegates formatting directly to - // packages/core/src/atlas/solidTrianglePlan.ts. - coreDelegations: { - polycss: ["packages/core/src/atlas/solidTrianglePlan.ts"], - }, - files: [ - "packages/polycss/src/render/atlas/solidTrianglePlan.ts", - "packages/polycss/src/render/atlas/stableTriangle.ts", - "packages/react/src/scene/atlas/solidTriangleStyle.ts", - "packages/react/src/scene/atlas/stableTriangleDom.ts", - "packages/react/src/scene/atlas/triangle.tsx", - "packages/vue/src/scene/atlas/solidTriangleStyle.ts", - "packages/vue/src/scene/atlas/stableTriangleDom.ts", - "packages/vue/src/scene/atlas/triangle.ts", - ], - }, - { - name: "plan-construction-and-orchestration", - // many:many, and the merge is load-bearing rather than lazy. Both - // sides run plans → filterAtlasPlans → packTextureAtlasPlansWithScale - // → buildAtlasPages and own the blob-URL lifecycle, but the - // projective-quad guard defaults sit on DIFFERENT sides of each lane's - // file split: vanilla resolves them in `renderPolygons.ts` - // (projectiveQuadGuardDefaults) through the thin `plan.ts` wrapper, - // while the framework inlines the identical resolution into - // `paintDefaults.ts`'s computeTextureAtlasPlan ("Mirrors vanilla's - // resolveProjectiveQuadGuards wrapper"). Splitting plan construction - // out would fail correctly-mirrored guard work, as the seam-bleed - // change on this branch demonstrates. - // - // FALSE FRIEND, worth naming: the framework `paintDefaults.ts` mirrors - // vanilla `plan.ts`/`renderPolygons.ts`, NOT vanilla `paintDefaults.ts` - // (which is inline-style paint — see leaf-emission-and-solid-paint). - // - // Partial by construction: the framework's leaf DISPATCH half lives in - // PolyMesh.tsx, outside this set's roots, so a dispatch-only change is - // not covered here. - files: [ - "packages/polycss/src/render/atlas/plan.ts", - "packages/polycss/src/render/atlas/renderPolygons.ts", - "packages/react/src/scene/atlas/paintDefaults.ts", - "packages/react/src/scene/atlas/useTextureAtlas.ts", - "packages/vue/src/scene/atlas/paintDefaults.ts", - "packages/vue/src/scene/atlas/useTextureAtlas.ts", - ], - }, - { - name: "barrel", - // All three re-export the same core types plus their own surface. - files: [ - "packages/polycss/src/render/atlas/index.ts", - "packages/react/src/scene/atlas/index.tsx", - "packages/vue/src/scene/atlas/index.ts", - ], - }, - ], - unmirrored: { - "packages/polycss/src/render/atlas/types.ts": - "the imperative render contract (RenderTextureAtlasOptions, " + - "SolidTriangleElement, RenderedPoly). React/Vue have no imperative " + - "render call: they take option types from core and declare props " + - "inline, so no framework file is a translation of this one.", - }, - laneRoots: [ - "packages/polycss/src/render/atlas", - "packages/react/src/scene/atlas", - "packages/vue/src/scene/atlas", - ], - hint: - "The canvas atlas pipeline is copied per renderer (AGENTS.md). A change " + - "to any of these files must be mirrored into the other two renderers.", - files: [ - "packages/polycss/src/render/atlas/emit.ts", - "packages/polycss/src/render/atlas/index.ts", - "packages/polycss/src/render/atlas/packing.ts", - "packages/polycss/src/render/atlas/paintDefaults.ts", - "packages/polycss/src/render/atlas/plan.ts", - "packages/polycss/src/render/atlas/rasterise.ts", - "packages/polycss/src/render/atlas/renderPolygons.ts", - "packages/polycss/src/render/atlas/solidTrianglePlan.ts", - "packages/polycss/src/render/atlas/stableTriangle.ts", - "packages/polycss/src/render/atlas/strategy.ts", - "packages/react/src/scene/atlas/atlasPoly.tsx", - "packages/react/src/scene/atlas/borderShape.tsx", - "packages/react/src/scene/atlas/buildAtlasPages.ts", - "packages/react/src/scene/atlas/cornerShapeSolid.tsx", - "packages/react/src/scene/atlas/detection.ts", - "packages/react/src/scene/atlas/filterPlans.ts", - "packages/react/src/scene/atlas/index.tsx", - "packages/react/src/scene/atlas/packing.ts", - "packages/react/src/scene/atlas/paintDefaults.ts", - "packages/react/src/scene/atlas/projectiveSolid.tsx", - "packages/react/src/scene/atlas/solidTriangleStyle.ts", - "packages/react/src/scene/atlas/stableTriangleDom.ts", - "packages/react/src/scene/atlas/triangle.tsx", - "packages/react/src/scene/atlas/useTextureAtlas.ts", - "packages/vue/src/scene/atlas/atlasPoly.ts", - "packages/vue/src/scene/atlas/borderShape.ts", - "packages/vue/src/scene/atlas/buildAtlasPages.ts", - "packages/vue/src/scene/atlas/cornerShapeSolid.ts", - "packages/vue/src/scene/atlas/detection.ts", - "packages/vue/src/scene/atlas/filterPlans.ts", - "packages/vue/src/scene/atlas/index.ts", - "packages/vue/src/scene/atlas/packing.ts", - "packages/vue/src/scene/atlas/paintDefaults.ts", - "packages/vue/src/scene/atlas/projectiveSolid.ts", - "packages/vue/src/scene/atlas/solidTriangleStyle.ts", - "packages/vue/src/scene/atlas/stableTriangleDom.ts", - "packages/vue/src/scene/atlas/triangle.ts", - "packages/vue/src/scene/atlas/useTextureAtlas.ts", - ], - }, - { - name: "voxel-renderer", - // One file per renderer, same name, genuine per-file copies. - pairLanes: ["polycss", "react", "vue"], - // The voxel renderer shares its directory with unrelated modules, so the - // roots are filtered to the `voxel*` basenames the set owns. - laneRoots: [ - "packages/polycss/src/render", - "packages/react/src/scene", - "packages/vue/src/scene", - ], - rootMatch: /^voxel/, - hint: - "The direct voxel renderer is copied per renderer (AGENTS.md). A change " + - "to one copy must land in the other two in the same PR.", - files: [ - "packages/polycss/src/render/voxelRenderer.ts", - "packages/react/src/scene/voxelRenderer.ts", - "packages/vue/src/scene/voxelRenderer.ts", - ], - }, - // Deliberately two lanes only. The vanilla counterparts in - // packages/polycss/src/api/scene/* are not per-file copies of these - // composables — they are an imperative orchestration split (mountSync, - // shadowOrchestrator, shadowCache) with no 1:1 mapping to a hook. Listing - // them as a third lane would fire on every vanilla-only refactor. { name: "mesh-modules", - // Exact 1:1 hook↔composable counterparts, differing only in extension. + // Exact 1:1 hook↔composable counterparts under scene/mesh/. Rendering, + // atlas, shadows, lighting, and voxel fast paths now live once in + // `@layoutit/polycss/runtime`. pairLanes: ["react", "vue"], laneRoots: [ "packages/react/src/scene/mesh", @@ -376,62 +133,38 @@ export const SYNC_SETS = [ ], hint: "The React hooks and Vue composables under scene/mesh/ are mirrored " + - "pairs (AGENTS.md → Cross-package discipline). They hold the shadow " + - "caches, receiver/caster registration, the followAnimation throttle, " + - "atlas and stable-DOM state — a fix in one lane must land in the other.", + "pairs (AGENTS.md → Cross-package discipline).", files: [ - "packages/react/src/scene/mesh/useGroundShadow.tsx", - "packages/react/src/scene/mesh/useMeshAtlas.ts", "packages/react/src/scene/mesh/useMeshEvents.ts", "packages/react/src/scene/mesh/useMeshGeometry.ts", - "packages/react/src/scene/mesh/useMeshLighting.ts", - "packages/react/src/scene/mesh/useReceiverShadows.tsx", - "packages/react/src/scene/mesh/useStableDom.ts", - "packages/react/src/scene/mesh/useVoxelFastPath.ts", - "packages/vue/src/scene/mesh/useGroundShadow.ts", - "packages/vue/src/scene/mesh/useMeshAtlas.ts", "packages/vue/src/scene/mesh/useMeshEvents.ts", "packages/vue/src/scene/mesh/useMeshGeometry.ts", - "packages/vue/src/scene/mesh/useMeshLighting.ts", - "packages/vue/src/scene/mesh/useReceiverShadows.ts", - "packages/vue/src/scene/mesh/useStableDom.ts", - "packages/vue/src/scene/mesh/useVoxelFastPath.ts", ], }, { name: "base-styles", - // One styles.ts per renderer, same name, genuine per-file copies. - pairLanes: ["polycss", "react", "vue"], + // React and Vue re-export base styles from `@layoutit/polycss/runtime`. + pairLanes: ["react", "vue"], laneRoots: [ - "packages/polycss/src/styles", "packages/react/src/styles", "packages/vue/src/styles", ], hint: - "The injected .polycss-scene/.polycss-camera base styles exist per " + - "renderer. CSS rules must cover every emitted tag for both lighting " + - "modes in all three copies (AGENTS.md checklist).", + "React and Vue style barrels re-export `@layoutit/polycss/runtime` " + + "and must stay mirrored.", files: [ - "packages/polycss/src/styles/styles.ts", + "packages/react/src/styles/index.ts", "packages/react/src/styles/styles.ts", + "packages/vue/src/styles/index.ts", "packages/vue/src/styles/styles.ts", ], - unmirrored: { - "packages/react/src/styles/index.ts": - "Framework-local barrel. The vanilla lane has no styles/ barrel — it " + - "re-exports styles.ts from its own api surface — so there is no third " + - "counterpart to pair this against.", - "packages/vue/src/styles/index.ts": - "Framework-local barrel; same reason as the React one.", - }, }, { name: "scene-components", - // Top-level React↔Vue scene components and hooks/composables. Subdirectories - // (`atlas/`, `mesh/`) and `voxelRenderer.ts` are owned by dedicated sets. + // Top-level React↔Vue scene components and hooks/composables. `mesh/` is + // owned by the dedicated `mesh-modules` set. pairLanes: ["react", "vue"], shallow: true, - rootMatch: /^(?!voxel)/, laneRoots: [ "packages/react/src/scene", "packages/vue/src/scene", @@ -533,7 +266,6 @@ export const SYNC_SETS = [ files: [ "packages/react/src/controls/PolyOrbitControls.tsx", "packages/react/src/controls/PolyMapControls.tsx", - "packages/react/src/controls/controlsEffects.ts", "packages/react/src/controls/sharedControls.ts", "packages/vue/src/controls/PolyOrbitControls.ts", "packages/vue/src/controls/PolyMapControls.ts", @@ -566,7 +298,6 @@ export const SYNC_SETS = [ "packages/react/src/controls/PolyMapControls.tsx", "packages/react/src/controls/PolyOrbitControls.tsx", "packages/react/src/controls/TransformControls.tsx", - "packages/react/src/controls/controlsEffects.ts", "packages/react/src/controls/index.ts", "packages/react/src/controls/sharedControls.ts", "packages/vue/src/controls/PolyFirstPersonControls.ts", diff --git a/.github/scripts/check-mirrors.test.mjs b/.github/scripts/check-mirrors.test.mjs index f599efd91..0416136ef 100644 --- a/.github/scripts/check-mirrors.test.mjs +++ b/.github/scripts/check-mirrors.test.mjs @@ -607,7 +607,7 @@ test("mesh-modules covers every react↔vue scene/mesh pair on both lanes", () = "every react hook under scene/mesh must have its vue counterpart listed", ); assert.equal( - lanes.get("react").some((file) => file.endsWith("useReceiverShadows.tsx")), + lanes.get("react").some((file) => file.endsWith("useMeshGeometry.ts")), true, ); }); @@ -622,8 +622,8 @@ test("mesh-modules: a one-lane edit fails", () => { assert.equal(runFixture(root, [], withMeshSet).code, 0, "clean tree passes"); - const reactFile = "packages/react/src/scene/mesh/useReceiverShadows.tsx"; - edit(root, reactFile, "react receiver shadows v2\n"); + const reactFile = "packages/react/src/scene/mesh/useMeshGeometry.ts"; + edit(root, reactFile, "react mesh geometry v2\n"); const result = runFixture(root, [], withMeshSet); assert.equal(result.code, 1, "a vue-less react mesh change must fail"); @@ -644,29 +644,13 @@ test("every sync set declares pairLanes or crossLaneGroups", () => { `set "${set.name}" must declare pairLanes or crossLaneGroups`, ); } - const atlas = SYNC_SETS.find((entry) => entry.name === "atlas-pipeline"); - assert.deepEqual(atlas.pairLanes, ["react", "vue"]); - for (const pair of derivePairs(atlas.files, atlas.pairLanes)) { + const meshSet = SYNC_SETS.find((entry) => entry.name === "mesh-modules"); + assert.deepEqual(meshSet.pairLanes, ["react", "vue"]); + for (const pair of derivePairs(meshSet.files, meshSet.pairLanes)) { assert.deepEqual([...pair.lanes.keys()].sort(), ["react", "vue"]); } }); -test("atlas-pipeline does not pair the vanilla lane by file name", () => { - // Real change from this PR: React/Vue mirrored the projective-quad guard - // default into paintDefaults.ts, while vanilla carries the same semantics in - // plan.ts. Pairing that lane by basename reports mirrored work as diverged. - const atlas = SYNC_SETS.find((entry) => entry.name === "atlas-pipeline"); - const { failures } = checkLaneParity( - [atlas], - [ - "packages/react/src/scene/atlas/paintDefaults.ts", - "packages/vue/src/scene/atlas/paintDefaults.ts", - "packages/polycss/src/render/atlas/plan.ts", - ], - ); - assert.deepEqual(failures, []); -}); - test("mesh-modules: unrelated one-lane edits in each lane do not cancel out", () => { // The reported bypass: set-wide lane parity sees both lanes "touched" and // passes, though neither edit was mirrored. @@ -674,14 +658,14 @@ test("mesh-modules: unrelated one-lane edits in each lane do not cancel out", () const { failures } = checkLaneParity( [meshSet], [ - "packages/react/src/scene/mesh/useReceiverShadows.tsx", + "packages/react/src/scene/mesh/useMeshGeometry.ts", "packages/vue/src/scene/mesh/useMeshEvents.ts", ], ); assert.equal(failures.length, 2); assert.deepEqual( failures.map((failure) => failure.pair).sort(), - ["useMeshEvents", "useReceiverShadows"], + ["useMeshEvents", "useMeshGeometry"], ); }); @@ -690,8 +674,8 @@ test("mesh-modules: a correctly mirrored pair passes", () => { const { failures, waived } = checkLaneParity( [meshSet], [ - "packages/react/src/scene/mesh/useReceiverShadows.tsx", - "packages/vue/src/scene/mesh/useReceiverShadows.ts", + "packages/react/src/scene/mesh/useMeshGeometry.ts", + "packages/vue/src/scene/mesh/useMeshGeometry.ts", ], ); assert.deepEqual(failures, []); @@ -699,19 +683,19 @@ test("mesh-modules: a correctly mirrored pair passes", () => { }); test("mesh-modules: a one-lane edit fails even once both lanes are touched", () => { - // useMeshAtlas is mirrored properly, so both lanes are already "touched"; - // the useStableDom straggler must still be caught. + // useMeshEvents is mirrored properly, so both lanes are already "touched"; + // the useMeshGeometry straggler must still be caught. const meshSet = SYNC_SETS.find((entry) => entry.name === "mesh-modules"); const { failures } = checkLaneParity( [meshSet], [ - "packages/react/src/scene/mesh/useMeshAtlas.ts", - "packages/vue/src/scene/mesh/useMeshAtlas.ts", - "packages/react/src/scene/mesh/useStableDom.ts", + "packages/react/src/scene/mesh/useMeshEvents.ts", + "packages/vue/src/scene/mesh/useMeshEvents.ts", + "packages/react/src/scene/mesh/useMeshGeometry.ts", ], ); assert.equal(failures.length, 1); - assert.equal(failures[0].pair, "useStableDom"); + assert.equal(failures[0].pair, "useMeshGeometry"); assert.deepEqual(failures[0].changed, ["react"]); assert.deepEqual(failures[0].unchanged, ["vue"]); }); @@ -1079,26 +1063,6 @@ test("end to end: a correctly mirrored addition passes", () => { cleanup(root); }); -test("atlas-pipeline coreDelegations satisfies polycss when core solidTrianglePlan changes with react+vue without flagging pure core edits", () => { - const atlas = SYNC_SETS.find((entry) => entry.name === "atlas-pipeline"); - const mirrored = checkLaneParity( - [atlas], - [ - "packages/core/src/atlas/solidTrianglePlan.ts", - "packages/react/src/scene/atlas/solidTriangleStyle.ts", - "packages/vue/src/scene/atlas/solidTriangleStyle.ts", - ], - ); - assert.deepEqual(mirrored.failures, []); - - // Pure core edits affect all consumers equally and must not trigger a false divergence. - const coreOnly = checkLaneParity( - [atlas], - ["packages/core/src/atlas/solidTrianglePlan.ts"], - ); - assert.deepEqual(coreOnly.failures, []); -}); - test("the committed sync sets are structurally valid against this repo", () => { const repoRoot = resolve(import.meta.dirname, "..", ".."); assert.deepEqual(checkSetDeclarations(repoRoot, SYNC_SETS), []); @@ -1265,55 +1229,50 @@ test("cross-lane groups enforce 1:many correspondence in both directions", () => assert.deepEqual(mirrored.failures, []); }); -test("atlas-pipeline maps every member into exactly one cross-lane group", () => { - const atlas = SYNC_SETS.find((entry) => entry.name === "atlas-pipeline"); +test("controls set maps every member into exactly one cross-lane group", () => { + const controls = SYNC_SETS.find((entry) => entry.name === "controls"); const seen = new Map(); - for (const group of atlas.crossLaneGroups) { + for (const group of controls.crossLaneGroups) { const lanes = new Set(); for (const file of group.files) { assert.ok(!seen.has(file), `${file} is in two groups`); seen.set(file, group.name); - assert.ok(atlas.files.includes(file), `${file} is not a set member`); + assert.ok(controls.files.includes(file), `${file} is not a set member`); lanes.add(resolveLane(file)); } - assert.deepEqual([...lanes].sort(), ["polycss", "react", "vue"], group.name); + assert.deepEqual([...lanes].sort(), ["react", "vue"], group.name); } assert.deepEqual( - atlas.files.filter((file) => !seen.has(file)), + controls.files.filter((file) => !seen.has(file)), [], - "every atlas member must be grouped", + "every controls member must be grouped", ); }); -test("atlas-pipeline: a vanilla-only change is not excused by an unrelated framework pair", () => { - // The exact bypass a fourth review round demonstrated: editing vanilla - // strategy.ts alone passed as long as SOME other vanilla-lane file moved — - // here the correctly-paired React+Vue rasterisation edit supplies it. With - // the mapping declared, both halves fail on their own group. - const atlas = SYNC_SETS.find((entry) => entry.name === "atlas-pipeline"); +test("cross-lane groups: a one-lane edit in one group is not excused by a mirrored edit in another group", () => { + const controls = SYNC_SETS.find((entry) => entry.name === "controls"); const { failures } = checkLaneParity( - [atlas], + [controls], [ - "packages/polycss/src/render/atlas/strategy.ts", - "packages/react/src/scene/atlas/buildAtlasPages.ts", - "packages/vue/src/scene/atlas/buildAtlasPages.ts", + "packages/react/src/controls/TransformControls.tsx", + "packages/react/src/controls/PolyOrbitControls.tsx", + "packages/vue/src/controls/PolyOrbitControls.ts", ], ); assert.deepEqual( - failures.map((failure) => failure.pair).sort(), - ["capability-detection-and-plan-filtering", "rasterisation"], + failures.map((failure) => failure.pair), + ["transform-controls"], ); - for (const failure of failures) assert.equal(failure.group, true); + assert.equal(failures[0].group, true); }); -test("atlas-pipeline: the same vanilla change mirrored into its real counterparts passes", () => { - const atlas = SYNC_SETS.find((entry) => entry.name === "atlas-pipeline"); +test("cross-lane groups: mirroring the edit into its counterpart passes", () => { + const controls = SYNC_SETS.find((entry) => entry.name === "controls"); const { failures } = checkLaneParity( - [atlas], + [controls], [ - "packages/polycss/src/render/atlas/strategy.ts", - "packages/react/src/scene/atlas/detection.ts", - "packages/vue/src/scene/atlas/detection.ts", + "packages/react/src/controls/PolyFirstPersonControls.tsx", + "packages/vue/src/controls/PolyFirstPersonControls.ts", ], ); assert.deepEqual(failures, []); @@ -1374,20 +1333,41 @@ test("a waiver matches the lanes of the diverging GROUP, not of the whole set", }); test("coreDelegations: pure packages/core edit never initiates a false renderer divergence", () => { - const atlas = SYNC_SETS.find((entry) => entry.name === "atlas-pipeline"); + const delegatedSet = { + name: "delegated", + hint: "mirror it", + crossLaneGroups: [ + { + name: "triangle", + coreDelegations: { + polycss: ["packages/core/src/atlas/solidTrianglePlan.ts"], + }, + files: [ + "packages/polycss/src/render/atlas/solidTrianglePlan.ts", + "packages/react/src/scene/triangle.tsx", + "packages/vue/src/scene/triangle.ts", + ], + }, + ], + files: [ + "packages/polycss/src/render/atlas/solidTrianglePlan.ts", + "packages/react/src/scene/triangle.tsx", + "packages/vue/src/scene/triangle.ts", + ], + }; // Editing ONLY the shared core helper must not flag polycss changed vs react/vue unchanged. const pureCore = checkLaneParity( - [atlas], + [delegatedSet], ["packages/core/src/atlas/solidTrianglePlan.ts"], ); assert.deepEqual(pureCore.failures, []); // Editing react + vue + core helper satisfies polycss via coreDelegations. const mirroredWithCore = checkLaneParity( - [atlas], + [delegatedSet], [ - "packages/react/src/scene/atlas/stableTriangleDom.ts", - "packages/vue/src/scene/atlas/stableTriangleDom.ts", + "packages/react/src/scene/triangle.tsx", + "packages/vue/src/scene/triangle.ts", "packages/core/src/atlas/solidTrianglePlan.ts", ], ); @@ -1395,10 +1375,10 @@ test("coreDelegations: pure packages/core edit never initiates a false renderer // Editing react + vue WITHOUT touching polycss or the delegated core helper still fails. const missingPolycss = checkLaneParity( - [atlas], + [delegatedSet], [ - "packages/react/src/scene/atlas/stableTriangleDom.ts", - "packages/vue/src/scene/atlas/stableTriangleDom.ts", + "packages/react/src/scene/triangle.tsx", + "packages/vue/src/scene/triangle.ts", ], ); assert.equal(missingPolycss.failures.length, 1); diff --git a/AGENTS.md b/AGENTS.md index 2b79ab3ba..e8f57dd9b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,9 +11,9 @@ Monorepo layout (pnpm workspaces): | Package | npm name | Role | |---|---|---| | `packages/core` | `@layoutit/polycss-core` | Pure math: Vec3, Polygon, scene, camera, mesh ops, atlas planning. Zero browser globals (`lib: ES2020` only). | -| `packages/polycss` | `@layoutit/polycss` | Vanilla renderer + custom elements (``, etc.) + side-effect-free `@layoutit/polycss/runtime` subpath. Depends on `core` only. | -| `packages/react` | `@layoutit/polycss-react` | React components + hooks. May depend on `core` and `@layoutit/polycss/runtime`. | -| `packages/vue` | `@layoutit/polycss-vue` | Vue 3 mirror of React. May depend on `core` and `@layoutit/polycss/runtime`. | +| `packages/polycss` | `@layoutit/polycss` | Single DOM/CSS renderer (`createPolyScene`, atlas, voxels, shadows, styles, controls) + custom elements (``, etc.) + side-effect-free `@layoutit/polycss/runtime` subpath. Depends on `core` only. | +| `packages/react` | `@layoutit/polycss-react` | Thin Adopt-DOM React components + hooks over `@layoutit/polycss/runtime`. Depends on `core` and `@layoutit/polycss/runtime`. | +| `packages/vue` | `@layoutit/polycss-vue` | Vue 3 mirror of React over `@layoutit/polycss/runtime`. Depends on `core` and `@layoutit/polycss/runtime`. | | `packages/fonts` | `@layoutit/polycss-fonts` | Fonts + text → extruded 3D `Polygon[]`. Framework-agnostic. Depends on `core` + `earcut`. | | `packages/morph` | `@layoutit/polycss-morph` | Framework-agnostic prepared-model contracts, Node preparation (`./prepare`), browser loading, retained DOM mounting, sparse deformation, skinning, and playback. No React/Vue mirrors. | | `packages/domformat` | `@layoutit/polycss-domformat` | Private strict-TypeScript `domformat@0` writer, reader, validator, CLI, and browser mount. Producer-neutral wire contract. Not published. | @@ -33,8 +33,8 @@ Public API is **mirrored** across React and Vue. Explicit `*/three` subpaths (`@ - `` — Border-shape clipped solids (Chromium + `pointer:fine` + `hover:hover`). Zero atlas memory. - `` — Atlas texture slices, direct `textureImageSource` image leaves, and universal fallback (cannot be disabled). - **No JS in the render loop.** Never run `requestAnimationFrame` to paint or update per-polygon DOM nodes when a scene/mesh/camera/light CSS variable can carry the change. The only exceptions are imported glTF/GLB skeletal skinning and the closed `domformat` prepared-runtime scheduler. -- **Lighting modes:** `"baked"` computes Lambert (directional + point lights + ambient) once on CPU (vanilla freezes lit surface on `directionalLight` change until `rebakeAtlas()`; React/Vue auto-rebake). `"dynamic"` evaluates directional + ambient Lambert in CSS `calc()` using scene/leaf custom properties; point lights are baked-only. -- **Cast shadows** are CPU-projected SVG overlays (`computeMergedReceiverShadows` in core), not strategy leaf tags. Known divergence: vanilla emits no shadow without a receiver; React/Vue still emit a per-mesh ground shadow when no receiver exists. +- **Lighting modes:** `"baked"` computes Lambert (directional + point lights + ambient) once on CPU (vanilla defaults to `bakedLightPolicy: "manual"`, freezing lit surface on `directionalLight` change until `rebakeAtlas()`; React/Vue pass `bakedLightPolicy: "auto"` to auto-rebake). `"dynamic"` evaluates directional + ambient Lambert in CSS `calc()` using scene/leaf custom properties; point lights are baked-only. +- **Cast shadows** are CPU-projected SVG overlays (`computeMergedReceiverShadows` in core), not strategy leaf tags. Vanilla defaults to `groundShadowFallback: false` (no shadow without a receiver); React/Vue pass `groundShadowFallback: true` to emit a compound ground-plane shadow when no receiver exists. - **Voxel meshes** (≤ 6 axis-aligned face normals) are the only exception to "all polygons stay mounted" (camera-facing face culling). ## Package & subsystem boundaries @@ -47,11 +47,11 @@ Public API is **mirrored** across React and Vue. Explicit `*/three` subpaths (`@ **For full `check-boundaries.mjs` and `check-mirrors.mjs` mechanics, read [.github/architecture/cross-package-and-mirrors.md](.github/architecture/cross-package-and-mirrors.md).** -- React and Vue are mirror images: any public API or renderer fix in one must land in the other (and vanilla/core when applicable) in the same PR. -- Renderer-owned browser glue (`atlas/`, `voxelRenderer.ts`, `styles.ts`, `scene/mesh/`, `scene/`, `three/`) is mirrored across renderers while React/Vue migrate onto `@layoutit/polycss/runtime`. +- **Single DOM renderer:** `@layoutit/polycss/runtime` owns the single atlas pipeline, feature detection, direct voxel renderer, shadow orchestrator, base stylesheet (`styles.ts`), and camera/control engines. React and Vue are thin Adopt-DOM bindings (`createPolyScene(..., { elements, wrapper })`) with zero duplicated renderer glue. +- React and Vue are mirror images: any public API or adapter fix in one must land in the other (and vanilla/core when applicable) in the same PR. - Automated guards enforced in CI, `pnpm check:guards`, and `pnpm verify`: - `pnpm check:boundaries` — lexical import + manifest dependency enforcement (`DEEP_IMPORT_ALLOWLIST` is empty). - - `pnpm check:mirrors --require-base` — identical react↔vue clones, 14 mirror sets covering all of `packages/{react,vue}/src` plus vanilla copies, per-pair & cross-lane-group diff parity (with `coreDelegations`) against base ref, and fail-closed tamper-evident waivers (`.github/mirror-waivers.json`). Note: touch parity ≠ semantic parity. + - `pnpm check:mirrors --require-base` — identical react↔vue files, 12 mirror sets covering all of `packages/{react,vue}/src`, per-pair & cross-lane-group diff parity against base ref, and fail-closed tamper-evident waivers (`.github/mirror-waivers.json`). Note: touch parity ≠ semantic parity. - `pnpm check:exports` — React↔Vue root and `./three` barrel value/type export parity (block, direct, and namespace exports; fails closed on bare `export *`). - `pnpm check:ir` — zero-browser cross-renderer DOM/CSS IR conformance across compiled `polycss`, `react`, and `vue` `dist/index.js` in `happy-dom` (real lighting/normal/albedo vars, baked paint, transforms, shadows, and `*/three`). - `pnpm check:packs` — read-only parallel `pnpm pack` verification for all 7 publishable packages (all declared entries + `typesVersions` + `README.md`, zero `workspace:` leaks, zero test files). diff --git a/bench/build.mjs b/bench/build.mjs index 286c08944..42dc0219c 100644 --- a/bench/build.mjs +++ b/bench/build.mjs @@ -47,6 +47,7 @@ const ALIASES = { "@layoutit/polycss-core": resolve(packagesRoot, "core/src/index.ts"), "@layoutit/polycss-core/three": resolve(packagesRoot, "core/src/three/index.ts"), "@layoutit/polycss": resolve(packagesRoot, "polycss/src/index.ts"), + "@layoutit/polycss/runtime": resolve(packagesRoot, "polycss/src/runtime.ts"), "@layoutit/polycss/elements": resolve(packagesRoot, "polycss/src/elements/index.ts"), "@layoutit/polycss/three": resolve(packagesRoot, "polycss/src/three.ts"), "@layoutit/polycss-react": resolve(packagesRoot, "react/src/index.ts"), diff --git a/bench/gate/cases.mjs b/bench/gate/cases.mjs index c408ba274..b66046cfe 100644 --- a/bench/gate/cases.mjs +++ b/bench/gate/cases.mjs @@ -55,8 +55,6 @@ export function lerpHexColor(t) { export const STRICT_CASES = [ { id: "saucer-vanilla", title: "saucer vanilla dyn", page: "perf-vanilla.html", query: "mesh=saucer&mode=dynamic&motion=none&az=40&el=45&nohud=1" }, { id: "saucer-html", title: "saucer html dyn", page: "perf-html.html", query: "mesh=saucer&mode=dynamic&motion=none&az=40&el=45&nohud=1" }, - { id: "saucer-react", title: "saucer react dyn", page: "perf-react.html", query: "mesh=saucer&mode=dynamic&motion=none&az=40&el=45&nohud=1" }, - { id: "saucer-vue", title: "saucer vue dyn", page: "perf-vue.html", query: "mesh=saucer&mode=dynamic&motion=none&az=40&el=45&nohud=1" }, { id: "saucer-all-s", title: "saucer all-s dyn", page: "perf-vanilla.html", query: "mesh=saucer&mode=dynamic&motion=none&az=40&el=45&disableStrategies=b,i,u&nohud=1", engines: ["chromium"] }, { id: "chicken-all-s", title: "chicken all-s dyn", page: "perf-vanilla.html", query: "mesh=chicken&mode=dynamic&motion=none&az=0&el=45&disableStrategies=b,i,u&nohud=1" }, { id: "chicken-az0", title: "chicken az=0 dyn", page: "perf-vanilla.html", query: "mesh=chicken&mode=dynamic&motion=none&az=0&el=45&nohud=1" }, @@ -92,7 +90,7 @@ export const PARITY_CASES = [ labelB: "React", pageB: "perf-react.html", queryB: "mesh=saucer&mode=dynamic&motion=none&az=40&el=45&nohud=1", - maxMismatchPx: { chromium: 60, firefox: 150 }, + maxMismatchPx: 0, }, { id: "parity-saucer-vue", @@ -103,7 +101,7 @@ export const PARITY_CASES = [ labelB: "Vue", pageB: "perf-vue.html", queryB: "mesh=saucer&mode=dynamic&motion=none&az=40&el=45&nohud=1", - maxMismatchPx: { chromium: 60, firefox: 150 }, + maxMismatchPx: 0, }, { id: "parity-react-vs-vue-saucer", @@ -114,11 +112,31 @@ export const PARITY_CASES = [ labelB: "Vue", pageB: "perf-vue.html", queryB: "mesh=saucer&mode=dynamic&motion=none&az=40&el=45&nohud=1", - maxMismatchPx: { chromium: 10, firefox: 10 }, + maxMismatchPx: 0, + }, + { + id: "parity-chicken-rot-react", + title: "rotated chicken vanilla vs react", + labelA: "Vanilla", + pageA: "perf-vanilla.html", + queryA: "mesh=chicken&mode=dynamic&motion=none&az=40&el=35&orx=25&ory=50&orz=15&nohud=1", + labelB: "React", + pageB: "perf-react.html", + queryB: "mesh=chicken&mode=dynamic&motion=none&az=40&el=35&orx=25&ory=50&orz=15&nohud=1", + maxMismatchPx: 0, + }, + { + id: "parity-chicken-rot-vue", + title: "rotated chicken vanilla vs vue", + labelA: "Vanilla", + pageA: "perf-vanilla.html", + queryA: "mesh=chicken&mode=dynamic&motion=none&az=40&el=35&orx=25&ory=50&orz=15&nohud=1", + labelB: "Vue", + pageB: "perf-vue.html", + queryB: "mesh=chicken&mode=dynamic&motion=none&az=40&el=35&orx=25&ory=50&orz=15&nohud=1", + maxMismatchPx: 0, }, { - // Note: on main, vanilla and React/Vue disagree on inverse-rotated dynamic - // light axes (~6.4k px); gate React vs Vue here until fixed in the renderer. id: "parity-chicken-rot-react-vs-vue", title: "rotated chicken react vs vue", labelA: "React", @@ -127,7 +145,7 @@ export const PARITY_CASES = [ labelB: "Vue", pageB: "perf-vue.html", queryB: "mesh=chicken&mode=dynamic&motion=none&az=40&el=35&orx=25&ory=50&orz=15&nohud=1", - maxMismatchPx: { chromium: 10, firefox: 10 }, + maxMismatchPx: 0, }, { id: "parity-rock1-react", @@ -138,7 +156,7 @@ export const PARITY_CASES = [ labelB: "React", pageB: "perf-react.html", queryB: "mesh=rock1&mode=dynamic&motion=none&az=0&el=45&nohud=1", - maxMismatchPx: { chromium: 25, firefox: 1700 }, + maxMismatchPx: 0, }, { id: "parity-rock1-vue", @@ -149,12 +167,9 @@ export const PARITY_CASES = [ labelB: "Vue", pageB: "perf-vue.html", queryB: "mesh=rock1&mode=dynamic&motion=none&az=0&el=45&nohud=1", - maxMismatchPx: { chromium: 25, firefox: 1700 }, + maxMismatchPx: 0, }, { - // Note: Firefox currently exhibits a pre-existing 3D floor-plane clipping - // divergence (~13k px) between vanilla and React/Vue; keep Chromium gated - // here and gate React vs Vue across both engines until fixed in renderer. id: "parity-shadow-react", title: "shadow floor vanilla vs react", labelA: "Vanilla", @@ -163,8 +178,7 @@ export const PARITY_CASES = [ labelB: "React", pageB: "perf-react.html", queryB: "mesh=chicken&mode=dynamic&motion=none&az=40&el=45&cs=1&fv=1&fr=1&nohud=1", - engines: ["chromium"], - maxMismatchPx: 25, + maxMismatchPx: 0, }, { id: "parity-shadow-vue", @@ -175,8 +189,7 @@ export const PARITY_CASES = [ labelB: "Vue", pageB: "perf-vue.html", queryB: "mesh=chicken&mode=dynamic&motion=none&az=40&el=45&cs=1&fv=1&fr=1&nohud=1", - engines: ["chromium"], - maxMismatchPx: 25, + maxMismatchPx: 0, }, { id: "parity-shadow-react-vs-vue", @@ -187,11 +200,9 @@ export const PARITY_CASES = [ labelB: "Vue", pageB: "perf-vue.html", queryB: "mesh=chicken&mode=dynamic&motion=none&az=40&el=45&cs=1&fv=1&fr=1&nohud=1", - maxMismatchPx: 10, + maxMismatchPx: 0, }, { - // synth-glass is a 6-face axis-aligned box: vanilla's voxel fast path culls - // the 3 back-facing quads (b=3), while React/Vue keep all 6 mounted (b=6). id: "parity-glass-react", title: "synth-glass vanilla vs react", labelA: "Vanilla", @@ -200,7 +211,7 @@ export const PARITY_CASES = [ labelB: "React", pageB: "perf-react.html", queryB: "mesh=synth-glass&mode=dynamic&motion=none&az=40&el=45&nohud=1", - allowTagShift: true, + maxMismatchPx: 0, }, { id: "parity-glass-vue", @@ -211,7 +222,7 @@ export const PARITY_CASES = [ labelB: "Vue", pageB: "perf-vue.html", queryB: "mesh=synth-glass&mode=dynamic&motion=none&az=40&el=45&nohud=1", - allowTagShift: true, + maxMismatchPx: 0, }, { id: "parity-strategy-chicken", @@ -226,6 +237,9 @@ export const PARITY_CASES = [ allowTagShift: true, }, { + // Dynamic mode uses LAMBERT_BUCKET_PRECISION = 0.1 normal bucketing in the + // shared runtime; under 3x intensity with zero ambient, 2 grazing comb + // triangles diverge from exact baked shading by ~188–217 px (0.07–0.08%). id: "parity-dyn-vs-baked-react", title: "chicken red dyn vs baked (react)", labelA: "Dynamic", @@ -234,7 +248,7 @@ export const PARITY_CASES = [ labelB: "Baked", pageB: "perf-react.html", queryB: "mesh=chicken&mode=baked&motion=none&az=0&el=45&dc=%23ff0000&di=3&ac=%23000000&ai=0&nohud=1", - maxMismatchPx: { chromium: 0, firefox: 5 }, + maxMismatchPx: { chromium: 250, firefox: 300 }, allowTagShift: true, }, ]; diff --git a/bench/renderer-ir-conformance.test.mjs b/bench/renderer-ir-conformance.test.mjs index fc618e5e8..979771989 100644 --- a/bench/renderer-ir-conformance.test.mjs +++ b/bench/renderer-ir-conformance.test.mjs @@ -381,10 +381,7 @@ test("IR conformance: dynamic quads + triangle verify real lighting/normal/albed assert.deepEqual(irU.leafSigs, irV.leafSigs); }); -test("IR conformance: rotated mesh under colored dynamic light matches wrapper transform across all renderers and leaf IR between react and vue", async () => { - // Note: on main, React/Vue and vanilla disagree on inverse-rotated dynamic - // light axes (tracked for the rendering phase). Gate 3-way wrapper transform - // + tag counts and React ↔ Vue leaf/lighting equivalence here. +test("IR conformance: rotated mesh under colored dynamic light matches wrapper transform and leaf IR across vanilla, react, and vue", async () => { const spec = { directionalLight: { direction: [0.4, 0.7, 0.6], color: "#ff4020", intensity: 2.0 }, ambientLight: { color: "#204080", intensity: 0.25 }, @@ -396,7 +393,8 @@ test("IR conformance: rotated mesh under colored dynamic light matches wrapper t assert.deepEqual(irU.meshTransforms, irV.meshTransforms); assert.deepEqual(irR.tagCounts, irV.tagCounts); assert.deepEqual(irU.tagCounts, irV.tagCounts); - assert.deepEqual(irU.leafSigs, irR.leafSigs); + assert.deepEqual(irR.leafSigs, irV.leafSigs); + assert.deepEqual(irU.leafSigs, irV.leafSigs); }); test("IR conformance: baked colored lighting emits identical inline paint across vanilla, react, and vue", async () => { @@ -418,20 +416,20 @@ test("IR conformance: baked colored lighting emits identical inline paint across assert.deepEqual(irU.leafSigs, irV.leafSigs); }); -test("IR conformance: rotated baked colored lighting matches between react and vue", async () => { - // Note: vanilla currently differs from React/Vue on baked shading of rotated - // meshes (tracked as a renderer follow-up); gate React ↔ Vue equivalence now. +test("IR conformance: rotated baked colored lighting matches across vanilla, react, and vue", async () => { const spec = { directionalLight: { direction: [0.3, 0.6, 0.75], color: "#ff2040", intensity: 2.2 }, ambientLight: { color: "#102030", intensity: 0.2 }, textureLighting: "baked", meshes: [{ polygons: PRISM_POLYS, rotation: [15, 35, 10] }], }; - const irR = await mountReact(spec); - const irU = await mountVue(spec); - assert.deepEqual(irU.tagCounts, irR.tagCounts); - assert.deepEqual(irU.meshTransforms, irR.meshTransforms); - assert.deepEqual(irU.leafSigs, irR.leafSigs); + const { irV, irR, irU } = await mountAllSequential(spec); + assert.deepEqual(irR.tagCounts, irV.tagCounts); + assert.deepEqual(irU.tagCounts, irV.tagCounts); + assert.deepEqual(irR.meshTransforms, irV.meshTransforms); + assert.deepEqual(irU.meshTransforms, irV.meshTransforms); + assert.deepEqual(irR.leafSigs, irV.leafSigs); + assert.deepEqual(irU.leafSigs, irV.leafSigs); }); test("IR conformance: mixed solid triangle + translucent quad matches across vanilla, react, and vue", async () => { diff --git a/packages/polycss/src/api/controls/common.ts b/packages/polycss/src/api/controls/common.ts index 34aaff1c1..9a08b0191 100644 --- a/packages/polycss/src/api/controls/common.ts +++ b/packages/polycss/src/api/controls/common.ts @@ -55,10 +55,9 @@ export interface PolyControlsChangeEvent { camera: PolyControlsCamera; } -export interface PolyControlsInteractionEvent { - type: "start" | "end"; - camera: PolyControlsCamera; -} +export type PolyControlsInteractionEvent = + | { type: "start"; camera: PolyControlsCamera } + | { type: "end"; camera: PolyControlsCamera }; export type PolyControlsEvent = PolyControlsChangeEvent | PolyControlsInteractionEvent; export type PolyControlsListener = (event: E) => void; diff --git a/packages/polycss/src/api/createPolyScene.ts b/packages/polycss/src/api/createPolyScene.ts index 7e3bbebaa..43ddaf060 100644 --- a/packages/polycss/src/api/createPolyScene.ts +++ b/packages/polycss/src/api/createPolyScene.ts @@ -551,15 +551,18 @@ export function createPolyScene( function add(parseResult: ParseResult, transformIn: PolyMeshTransform = {}): PolyMeshHandle { const mountDoc = sceneEl.ownerDocument ?? document; const adoptedWrapper = !!transformIn.wrapper; + const isSceneRootWrapper = transformIn.wrapper === sceneEl; const wrapper = transformIn.wrapper ?? mountDoc.createElement("div"); if (adoptedWrapper) { - wrapper.classList.add("polycss-mesh"); + if (!isSceneRootWrapper) wrapper.classList.add("polycss-mesh"); } else { wrapper.className = "polycss-mesh"; } - if (transformIn.id) wrapper.setAttribute("data-poly-mesh-id", transformIn.id); const autoMeshId = `polycss-mesh-${ctx.meshAutoCounter.next++}`; - wrapper.setAttribute("data-poly-mesh-index", autoMeshId); + if (!isSceneRootWrapper) { + if (transformIn.id) wrapper.setAttribute("data-poly-mesh-id", transformIn.id); + wrapper.setAttribute("data-poly-mesh-index", autoMeshId); + } let transform: PolyMeshTransform = { ...transformIn }; let mergeOnUpdate = transformIn.merge !== false; @@ -567,7 +570,7 @@ export function createPolyScene( let autoCenterOnUpdate = !!transformIn.autoCenter; let polygonUpdateVersion = 0; const css = buildMeshTransform(transform); - if (css) wrapper.style.transform = css; + if (!isSceneRootWrapper && css) wrapper.style.transform = css; const preparePolygons = (polygons: Polygon[], merge: boolean): Polygon[] => { const centered = autoCenterOnUpdate ? recenterPolygons(polygons) : polygons; @@ -588,6 +591,7 @@ export function createPolyScene( // but it no longer drives transform-origin. let bboxCenterCssCache: Vec3 | null = null; function reapplyWrapperTransform(): void { + if (isSceneRootWrapper) return; const css = buildMeshTransform(transform); wrapper.style.transform = css ?? ""; } @@ -1055,8 +1059,10 @@ export function createPolyScene( } } transform = { ...transform, ...t }; - const css2 = buildMeshTransform(transform); - wrapper.style.transform = css2 ?? ""; + if (!isSceneRootWrapper) { + const css2 = buildMeshTransform(transform); + wrapper.style.transform = css2 ?? ""; + } applyMeshLightVarOverride(ctx, entry, transform.rotation); if (renderOverrideChanged) { if (entry.atomicAtlas && (entry.rendered.length > 0 || entry.voxelRenderer)) { @@ -1123,7 +1129,12 @@ export function createPolyScene( meshes.delete(entry); meshByElement.delete(wrapper); recomputeAutoCenter(); + const prevGround = ctx.shadowSvgState.currentGroundCssZ; recomputeShadowGround(ctx); + if ((entry.castShadow || entry.receiveShadow) && ctx.shadowSvgState.currentGroundCssZ === prevGround) { + invalidateShadowLightCache(ctx); + emitSceneShadows(ctx); + } }, rebakeAtlas() { // Advance the baked rotation to match the current live rotation. @@ -1152,20 +1163,12 @@ export function createPolyScene( entry.handle = handle; entryRef = entry; - meshByElement.set(wrapper, entry); + if (!isSceneRootWrapper) meshByElement.set(wrapper, entry); meshes.add(entry); renderEntry(entry); applyMeshLightVarOverride(ctx, entry, transform.rotation); recomputeAutoCenter(); recomputeShadowGround(ctx); - // New receiver: the scene-level shadow set must rebuild so existing - // casters get faces to project onto. recomputeShadowGround only - // does this when the global ground changes; force a rebuild for the - // receiver-only case. - if (entry.receiveShadow) { - invalidateShadowLightCache(ctx); - emitSceneShadows(ctx); - } return handle; } @@ -1256,8 +1259,15 @@ export function createPolyScene( (prevAmbColor ?? "#ffffff") !== (nextAmbLight?.color ?? "#ffffff") ); const nextShadow = currentOptions.shadow; + if (prevShadow?.followAnimation && !nextShadow?.followAnimation && ctx.animationShadowTrailingTimer !== null) { + clearTimeout(ctx.animationShadowTrailingTimer); + ctx.animationShadowTrailingTimer = null; + } const shadowAppearanceChanged = partial.shadow !== undefined - && !shadowOptsEqual(prevShadow, nextShadow); + && !shadowOptsEqual( + prevShadow ? { ...prevShadow, followAnimation: false } : undefined, + nextShadow ? { ...nextShadow, followAnimation: false } : undefined, + ); const shadowReemitNeeded = directionalChanged || shadowAppearanceChanged || pointLightsChanged || (ambientChanged && currentOptions.bakedLightPolicy === "auto"); if ( diff --git a/packages/polycss/src/api/runtimeSeams.test.ts b/packages/polycss/src/api/runtimeSeams.test.ts index 8cd69dfb8..3c0e935e5 100644 --- a/packages/polycss/src/api/runtimeSeams.test.ts +++ b/packages/polycss/src/api/runtimeSeams.test.ts @@ -317,6 +317,60 @@ describe("createPolyScene adopt-DOM seams", () => { scene.destroy(); }); + + it("emits opt-in groundShadowFallback only when no receiver exists and hides it once a receiver mounts", () => { + const hostOff = makeHost(); + const sceneOff = makeScene(hostOff, { + directionalLight: { direction: [0.4, -0.7, 0.59], color: "#ffffff", intensity: 1 }, + }); + sceneOff.add(makeParseResult([makeQuad(0, 0, 2)]), { castShadow: true }); + expect(sceneOff.sceneElement.querySelector("svg.polycss-shadow")).toBeNull(); + sceneOff.destroy(); + + const hostOn = makeHost(); + const sceneOn = makeScene(hostOn, { + groundShadowFallback: true, + debugShadowAttrs: true, + directionalLight: { direction: [0.4, -0.7, 0.59], color: "#ffffff", intensity: 1 }, + }); + sceneOn.add(makeParseResult([makeQuad(0, 0, 2)]), { castShadow: true }); + const getVisibleGround = () => { + const el = sceneOn.sceneElement.querySelector( + 'svg.polycss-shadow[data-poly-shadow-type="ground"]', + ) as SVGSVGElement | null; + return el && el.style.display !== "none" ? el : null; + }; + expect(getVisibleGround()).not.toBeNull(); + + const receiver = sceneOn.add(makeParseResult([makeQuad(0, 0, 0, "#cccccc")]), { + receiveShadow: true, + }); + expect(getVisibleGround()).toBeNull(); + + receiver.remove(); + receiver.dispose(); + expect(getVisibleGround()).not.toBeNull(); + sceneOn.destroy(); + }); + + it("supports adopting sceneEl directly as wrapper without clobbering scene transform or class", () => { + const host = makeHost(); + const scene = makeScene(host, { autoCenter: false }); + const beforeTransform = scene.sceneElement.style.transform; + const direct = scene.add(makeParseResult([makeQuad(0, 0, 0, "#44aa88")]), { + wrapper: scene.sceneElement, + excludeFromAutoCenter: true, + }); + expect(scene.sceneElement.classList.contains("polycss-mesh")).toBe(false); + expect(scene.sceneElement.style.transform).toBe(beforeTransform); + expect(scene.sceneElement.querySelectorAll("b,i,s,u").length).toBe(1); + + direct.remove(); + direct.dispose(); + expect(scene.sceneElement.querySelectorAll("b,i,s,u").length).toBe(0); + expect(scene.sceneElement.parentNode).toBe(scene.cameraEl); + scene.destroy(); + }); }); describe("controls, select, and transform-controls guards", () => { diff --git a/packages/polycss/src/api/scene/internalTypes.ts b/packages/polycss/src/api/scene/internalTypes.ts index 7c67ddc33..37f6428b2 100644 --- a/packages/polycss/src/api/scene/internalTypes.ts +++ b/packages/polycss/src/api/scene/internalTypes.ts @@ -40,7 +40,7 @@ export interface MeshRenderOverrides { */ export interface MeshEntry { handle: PolyMeshHandle; - wrapper: HTMLDivElement; + wrapper: HTMLElement; /** True when `wrapper` was passed in by the caller (adopted, never removed on dispose). */ adoptedWrapper: boolean; /** Engine-mounted child nodes inside `wrapper` so static caller/framework children are never touched. */ diff --git a/packages/polycss/src/api/scene/lightingVars.ts b/packages/polycss/src/api/scene/lightingVars.ts index da8f9123d..502d5a1fb 100644 --- a/packages/polycss/src/api/scene/lightingVars.ts +++ b/packages/polycss/src/api/scene/lightingVars.ts @@ -148,7 +148,7 @@ export function applyDynamicLightVars(el: HTMLElement, opts: Omit