diff --git a/src/components/Scene.svelte b/src/components/Scene.svelte index 9dcf78841..c5d132fa8 100644 --- a/src/components/Scene.svelte +++ b/src/components/Scene.svelte @@ -53,6 +53,7 @@ import { tickAnimatedMixers } from '$lib/animatedImports'; import { tickSim } from '$lib/sim/runtime.js'; // 36-sim: jiggle, splashes, fluid tanks import { tickTextPathsLazy } from '$lib/textPathTick.js'; // 64 D2: text on a path + import { tickArraysLazy } from '$lib/arrayTick.js'; // 102b-arrange: array copies (lazy runtime) import { startPackBehaviors, tickPackBehaviors } from '$lib/packBehavior'; import { startArchParts } from '$lib/arch/archParts.js'; import { tickAnimationPreview, captureAutoKey, playheadOf } from '$lib/animationPreview'; @@ -459,6 +460,7 @@ tickPackBehaviors(); // 33 P2: doors/lids/levers pose from their shared state (rest in Edit) tickSim($objectsGroup, camera.current, renderer, performance.now()); // 36-sim (after mixers: jiggle rides the posed bones) tickTextPathsLazy($objectsGroup, performance.now()); // 64 D2: letters follow their carriers (and linked paths) + tickArraysLazy($objectsGroup, performance.now()); // 102b-arrange: every peer draws its arrays' copies tickAnimationPreview(); // Animation window: local transform preview (not synced) tickSequences(); // 48 S2: shots / clips / audio / events of running sequences tickMeshEdit(); // vertex handles follow the object if it moves (119) @@ -1112,7 +1114,11 @@ const area = $marqueeRect; const picked = []; const center = new THREE.Vector3(); + // 102b-arrange: a box skips objects on a LOCKED layer and on a layer hidden here + const locked: Set | undefined = (editorPass() as any).lockedLayers; for (const object of $objectsGroup?.children ?? []) { + const layer = object.userData?.layer; + if (layer && (locked?.has(layer) || object.visible === false)) continue; const box = new THREE.Box3().setFromObject(object); if (!isFinite(box.min.x)) continue; box.getCenter(center).project(camera.current); diff --git a/src/components/menu/Inspector.svelte b/src/components/menu/Inspector.svelte index 1c08f58bd..8875623b5 100644 --- a/src/components/menu/Inspector.svelte +++ b/src/components/menu/Inspector.svelte @@ -2411,6 +2411,9 @@ + +
{#await import('./inspector/LayersSection.svelte') then m}{/await}
+
@@ -3781,6 +3784,11 @@ {/if} + + {#if $selectedObjects?.length} + {#await import('./inspector/TidySection.svelte') then m}{/await} + {/if} + {#if !isLight}
insTargets.length, fans: true }}> @@ -3846,6 +3854,11 @@ {/if} + {#if !isLight && !multiCount && $selectedObject?.uuid && $selectedObject?.isObject3D} + + {#await import('./inspector/ArraySection.svelte') then m}{/await} + {/if} + {#if devPrimary}
{#if lockEntry} diff --git a/src/components/menu/inspector/ArraySection.svelte b/src/components/menu/inspector/ArraySection.svelte new file mode 100644 index 000000000..73e0ffd9e --- /dev/null +++ b/src/components/menu/inspector/ArraySection.svelte @@ -0,0 +1,129 @@ + + +
+
+ {#if !rec} +

Repeat this object in a line, a grid, a circle or along a path. The copies follow every change you make to it.

+
+ +
+ {:else} +

{arraySummary(rec)}

+ + {#snippet control()} + set({ mode: v })} + /> + {/snippet} + + {#if rec.mode !== 'grid'} + set({ count: v })} /> + {/if} + {#if rec.mode === 'line'} + {#each AXES as axis, i (axis)} + setAxis('step', i, v)} /> + {/each} + {:else if rec.mode === 'grid'} + {#each AXES as axis, i (axis)} + setAxis('grid', i, v)} /> + {/each} + {#each AXES as axis, i (axis)} + setAxis('gridStep', i, v)} /> + {/each} + {:else if rec.mode === 'circle'} + set({ radius: v })} /> + set({ arc: v })} /> + + {#snippet control()} + set({ faceOut: v })} /> + {/snippet} + + {:else} + + {#snippet control()} + ({ value: t.value, name: t.name }))} value={rec.path || undefined} onchange={(v) => set({ path: String(v ?? '') })} /> + {/snippet} + + {#if !rec.path} +

Pick a Path (Add ▸ Path), a spline or a flow path. The copies follow its shape, starting at this object.

+ {/if} + set({ spacing: v })} /> + + {#snippet control()} + set({ follow: v })} /> + {/snippet} + + {/if} + {#each AXES as axis, i (axis)} + setAxis('rotStep', i, v)} /> + {/each} + set({ scaleStep: v })} /> +

Copies are drawn, not objects: they have no physics or logic and you cannot click them. Make them real objects to give them their own.

+
+ set(null)} /> + makeArrayReal(uuid)} /> +
+ {/if} +
+
diff --git a/src/components/menu/inspector/LayersSection.svelte b/src/components/menu/inspector/LayersSection.svelte new file mode 100644 index 000000000..09876bb7c --- /dev/null +++ b/src/components/menu/inspector/LayersSection.svelte @@ -0,0 +1,80 @@ + + +
+ {#if !layers.length} +

Layers group objects across the scene so you can hide, lock or select them together. Put an object on a layer in its Inspector (Tidy ▸ Layer).

+ {/if} + {#each layers as l (l.id)} +
+ updateLayer(l.id, { color: e.currentTarget.value })} + /> + updateLayer(l.id, { name: e.currentTarget.value })} + /> + {counts[l.id] ?? 0} + setLayerHidden(l.id, !$hiddenLayers.has(l.id))} + /> + updateLayer(l.id, { locked: !l.locked })} + /> + selectLayer(l.id)} /> + removeLayer(l.id)} /> +
+ {/each} +
+ addLayer()} /> +
+
+ + diff --git a/src/components/menu/inspector/TidySection.svelte b/src/components/menu/inspector/TidySection.svelte new file mode 100644 index 000000000..a2448a033 --- /dev/null +++ b/src/components/menu/inspector/TidySection.svelte @@ -0,0 +1,105 @@ + + +
+
+ + {#snippet control()} + + {/snippet} + + + {#snippet control()} +
+ {#each SIMILAR as s (s.by)} + selectSimilar(s.by)} /> + {/each} +
+ {/snippet} +
+ {#if multi} + + {#snippet control()} + + {/snippet} + + (start = v)} /> + (pad = v)} /> +

{preview}

+
+ renameMany(sel, pattern, start, pad)} /> +
+ {#each AXES as axis, i (axis)} + (rot[i] = v)} /> + {/each} + (scaleMin = v)} /> + (scaleMax = v)} /> + {#each AXES as axis, i (axis)} + (offset[i] = v)} /> + {/each} + (seed = v)} /> +
+ (seed = Math.floor(Math.random() * 99999))} /> + randomise(sel, { rot, scale: [scaleMin, scaleMax], offset, seed })} /> +
+ {/if} +
+
diff --git a/src/lib/ai/tools.js b/src/lib/ai/tools.js index 169264ae0..7b6015693 100644 --- a/src/lib/ai/tools.js +++ b/src/lib/ai/tools.js @@ -1,5 +1,6 @@ import { parentTarget } from './parentTarget.js'; import { get } from 'svelte/store'; +import { scenePhysicsState_ } from '../scenePhysics'; // 102b-arrange: layer names for list_scene import * as THREE from 'three'; import { objectsGroup, lockedObjects, pokeScene } from '../../stores/sceneStore.js'; import { peers } from '../../stores/appStore.js'; @@ -144,6 +145,12 @@ function r3(n) { return Math.round(n * 1000) / 1000; } +/** 102b-arrange: a layer id as its name (the id when the table does not name it) @param {string} id */ +function layerNameOf(id) { + const list = get(scenePhysicsState_)?.layers; + return (Array.isArray(list) && list.find((/** @type {any} */ l) => l?.id === id)?.name) || id; +} + /** @param {any} object @returns {any} */ function describeObject(object) { /** @type {any} */ @@ -160,6 +167,9 @@ function describeObject(object) { if (material.color) out.color = '#' + material.color.getHexString(); } if (object.userData?.physics) out.physics = { ...object.userData.physics }; + // 102b-arrange: a live array, as stored (drawn copies, not objects — update_objects {array, makeReal}) + if (object.userData?.array && typeof object.userData.array === 'object') out.array = { ...object.userData.array }; + if (typeof object.userData?.layer === 'string') out.layer = layerNameOf(object.userData.layer); const pivot = originOf(object); if (pivot) out.pivot = pivot.map(r3); // 85 set_pivot: object space const geometry = geometrySummary(object); @@ -773,6 +783,35 @@ async function updateOne(spec) { } } if (typeof spec.visible === 'boolean' && object.visible !== spec.visible) toggleObjectVisibility(uuid); + // 102b-arrange: the object's layer by NAME (a new name makes the layer) + if (spec.layer !== undefined) { + const tidy = await import('../tidyActions.js'); + if (spec.layer === null || spec.layer === '') tidy.setObjectsLayer([uuid], null); + else if (typeof spec.layer !== 'string' || spec.layer.length > 60) errors.push('layer: a layer name (up to 60 characters) or null'); + else { + const name = spec.layer.trim(); + const found = tidy.sceneLayers().find((l) => l.name.toLowerCase() === name.toLowerCase()); + const id = found?.id ?? tidy.addLayer(name); + if (id) tidy.setObjectsLayer([uuid], id); + else errors.push('layer: the scene is full of layers'); + } + } + // 102b-arrange: a live array (record only) and Make real objects — the Inspector's write path + /** @type {string[] | null} */ + let made = null; + if (spec.array !== undefined || spec.makeReal === true) { + const arr = await import('../arrayActions.js'); + if (spec.array === null) arr.setArray(uuid, null); + else if (spec.array !== undefined) { + if (!spec.array || typeof spec.array !== 'object' || Array.isArray(spec.array)) errors.push('array: takes an object like {"mode": "grid", "grid": [4, 1, 4]} or null'); + else if (spec.array.mode !== undefined && !['line', 'grid', 'circle', 'path'].includes(spec.array.mode)) errors.push('array.mode: one of line, grid, circle, path'); + else arr.setArray(uuid, spec.array); + } + if (spec.makeReal === true) { + if (!object.userData.array) errors.push('makeReal: this object has no array'); + else made = arr.makeArrayReal(uuid); + } + } // mcp-shapes: after the move, so a new position is where it looks from if (spec.lookAt !== undefined) { const why = lookAtTarget(object, spec.lookAt, spec.front); @@ -786,7 +825,7 @@ async function updateOne(spec) { applyAiTransform(object, was); return { uuid, ok: false, errors: [...errors, clash + ' (it was put back)'] }; } - const extra = { ...(place.placed ? { placed: place.placed } : {}), ...(unitsOf.units ? { units: unitsOf.units } : {}) }; + const extra = { ...(place.placed ? { placed: place.placed } : {}), ...(unitsOf.units ? { units: unitsOf.units } : {}), ...(made ? { made } : {}) }; return errors.length ? { uuid, ok: false, errors, ...extra } : { uuid, ok: true, ...extra }; } @@ -1545,6 +1584,12 @@ export const AI_TOOLS = [ face_user: { description: 'turn it (yaw only) so its front faces a person: true = the person you act for, or a peer id / name from where_are_users' }, front: { type: 'string', enum: ['+z', '-z', '+x', '-x', '+y', '-y'], description: 'which local axis is its front for lookAt and face_user (default +z; many models face +x or -z — look at a screenshot)' }, visible: { type: 'boolean' }, + array: { + description: + '102b: repeat this object as a live ARRAY (drawn copies that follow every change to it; one undo, one message): {mode: line|grid|circle|path, count (2-500, the object included), step [x,y,z] (line), grid [nx,ny,nz] + gridStep [x,y,z] (grid), radius + arc degrees + faceOut (circle, centre radius m on -X), path (a Path uuid) + spacing (0 = even) + follow (path), rotStep [x,y,z] degrees per copy, scaleStep per copy}. Fields merge over the current array. null removes it. Copies have no physics or logic until makeReal' + }, + layer: { type: ['string', 'null'], description: '102b: put it on the layer with this NAME (made when new; Configure Scene > Layers hides and locks layers), or null for no layer' }, + makeReal: { type: 'boolean', description: '102b: true = turn the object\'s array copies into ordinary objects (one undo); the result lists their uuids' }, parentUuid: { type: 'string', description: 'group uuid (or any object, not a light or camera) to nest under, or "root" to un-nest. The object keeps its world pose; a position given in the same update is LOCAL to the new parent. A uuid not in the scene is an error' diff --git a/src/lib/arrayActions.js b/src/lib/arrayActions.js new file mode 100644 index 000000000..6e0440df3 --- /dev/null +++ b/src/lib/arrayActions.js @@ -0,0 +1,119 @@ +// @ts-ignore - no bundled three type declarations (project-wide) +import * as THREE from 'three'; +import { get } from 'svelte/store'; +import { objectsGroup, pokeScene } from '../stores/sceneStore'; +import { peers, showToast } from '../stores/appStore'; +import { recordEntry, recordObjectPresence, beginHistoryBatch, endHistoryBatch, historyBatchOpen } from './history'; +import { withWireBatch } from './wireBatch'; +import { canEditObject, warnViewerReadOnly } from './objectPermissions'; +import { duplicateObject, applySelectionSet } from './objectActions'; +import { normalizeArray, arrayTotal, arraySummary, ARRAY_DEFAULTS } from './arrayCore.js'; +import { copyPosesOf } from './arrayRuntime.js'; +import { arraysChanged } from './arrayTick.js'; + +// 102b-arrange row 1 — THE ARRAY'S WRITE PATH (the Inspector's Array section, the object menu, the +// agent tool). A lazy chunk: nothing at boot reaches it. +// +// setArray: ONE `props` undo entry and ONE `objectParameters` message per edit, however many copies +// the record makes (a scrub folds into one step through DragRow's gesture). makeArrayReal: every +// copy becomes an ordinary object at exactly the pose it was drawn with — one history batch (one +// Ctrl+Z takes them all away and puts the array back) and one wire batch (one envelope to peers). + +/** @param {string} uuid */ +function objectOf(uuid) { + return /** @type {any} */ (get(objectsGroup))?.getObjectByProperty('uuid', uuid) ?? null; +} + +/** @param {any} object */ +function editable(object) { + if (!object) return false; + if (!canEditObject(object)) { + warnViewerReadOnly(); + return false; + } + return true; +} + +/** + * Give an object an array, change it, or (null) take it away. + * @param {string} uuid @param {any} record a partial record merged over the current one (or the + * defaults), or null to remove @returns {boolean} whether anything changed + */ +export function setArray(uuid, record) { + const object = objectOf(uuid); + if (!editable(object)) return false; + const before = object.userData.array ? normalizeArray(object.userData.array) : null; + const next = record === null ? null : normalizeArray({ ...(before ?? ARRAY_DEFAULTS), ...record }); + if (JSON.stringify(before) === JSON.stringify(next)) return false; + if (next) object.userData.array = next; + else delete object.userData.array; + recordEntry({ kind: 'props', uuid, before: { array: before }, after: { array: next } }); + /** @type {any} */ + const peer = get(peers); + peer?.send?.({ type: 'objectParameters', parameter: 'array', uuid, array: next }); + arraysChanged(); + pokeScene(); + return true; +} + +/** the array an object holds, cleaned (null when none) @param {string} uuid */ +export function arrayOf(uuid) { + const object = objectOf(uuid); + return object?.userData?.array ? normalizeArray(object.userData.array) : null; +} + +/** @param {any[]} q quaternion array → euler array (the `move` message's rot) */ +function eulerOf(q) { + return new THREE.Euler().setFromQuaternion(new THREE.Quaternion().fromArray(q)).toArray(); +} + +/** + * Turn an array's copies into real objects. The object keeps its place and loses the record. + * @param {string} uuid @returns {string[]} the new objects' uuids + */ +export function makeArrayReal(uuid) { + const object = objectOf(uuid); + if (!editable(object) || !object.userData.array) return []; + const root = get(objectsGroup); + const poses = copyPosesOf(object, root); + if (!poses.length) { + showToast('This array draws no copies yet'); + return []; + } + const rec = normalizeArray(object.userData.array); + const own = !historyBatchOpen(); + if (own) beginHistoryBatch(); + /** @type {string[]} */ + const made = []; + /** @type {any} */ + const peer = get(peers); + const base = object.name || 'Object'; + try { + withWireBatch(() => { + poses.forEach((pose, i) => { + const clone = duplicateObject(uuid, { select: false, history: false, at: pose.position, name: `${base} ${i + 2}` }); + if (!clone) return; + clone.quaternion.fromArray(pose.quaternion); + clone.scale.fromArray(pose.scale); + clone.updateMatrixWorld(true); + // the `duplicate` message carried the position; the turn and the size ride a `move` + peer?.send?.({ type: 'move', uuid: clone.uuid, pos: clone.position.toArray(), rot: eulerOf(pose.quaternion), scale: clone.scale.toArray() }); + // recorded AFTER the pose is set, so a redo recreates the copy where it stands + recordObjectPresence('create', clone); + made.push(clone.uuid); + }); + setArray(uuid, null); + }); + } finally { + if (own) endHistoryBatch('Make real objects'); + } + if (made.length) applySelectionSet([uuid, ...made]); + showToast(`${made.length + 1} objects made from ${rec ? arraySummary(rec) : 'the array'} (one undo)`); + return made; +} + +/** how many objects an object's array shows, itself included (0 = no array) @param {string} uuid */ +export function arrayCountOf(uuid) { + const rec = arrayOf(uuid); + return rec ? arrayTotal(rec) : 0; +} diff --git a/src/lib/arrayCore.js b/src/lib/arrayCore.js new file mode 100644 index 000000000..f3549c590 --- /dev/null +++ b/src/lib/arrayCore.js @@ -0,0 +1,204 @@ +// @ts-ignore - no bundled three type declarations (project-wide) +import * as THREE from 'three'; + +// 102b-arrange row 1 — THE ARRAY RECORD and the pose of every copy. A LEAF over three (the runtime, +// the Inspector, "Make real objects" and the agent tool all reach it; it records nothing). +// +// An array is a record on an ordinary object: `userData.array`. The object itself is copy 0 and +// stays a normal object; copies 1..n-1 are drawn by every peer from the record (arrayRuntime.js, +// instanced at the scene root — golden rules 5 and 8), so a save, a sync and an undo carry ONE small +// record however many copies it makes. An older build skips the field and shows the one object. +// +// Every pose is in the object's PARENT frame, relative to the object's own local pose, so moving, +// turning or scaling the object moves the whole array with it. + +/** copies in one array, the object itself included (one InstancedMesh per source mesh draws them) */ +export const ARRAY_MAX = 500; +export const ARRAY_MODES = /** @type {const} */ (['line', 'grid', 'circle', 'path']); + +/** @typedef {{v: 1, mode: 'line'|'grid'|'circle'|'path', count: number, step: number[], grid: number[], + * gridStep: number[], radius: number, arc: number, faceOut: boolean, path: string, spacing: number, + * follow: boolean, rotStep: number[], scaleStep: number}} ArrayRecord + * step: line offset between neighbours (m); grid: columns/rows/layers on x/y/z; gridStep: grid spacing; + * radius/arc (degrees, 360 = a full ring)/faceOut: the circle (centre `radius` m on -X of the object, about + * the parent's Y); path: the uuid of a Path (or any object text can follow); spacing: m along the path + * (0 = spread evenly over its length); follow: copies turn with the path; rotStep: degrees per copy + * (x, y, z, in each copy's own frame); scaleStep: size change per copy (0.1 = each 10 % bigger). */ + +/** @type {ArrayRecord} */ +export const ARRAY_DEFAULTS = Object.freeze({ + v: 1, + mode: 'line', + count: 5, + step: [2, 0, 0], + grid: [3, 1, 3], + gridStep: [2, 2, 2], + radius: 3, + arc: 360, + faceOut: true, + path: '', + spacing: 0, + follow: true, + rotStep: [0, 0, 0], + scaleStep: 0 +}); + +/** @param {any} v @param {number} lo @param {number} hi @param {number} d */ +const num = (v, lo, hi, d) => (typeof v === 'number' && Number.isFinite(v) ? Math.min(hi, Math.max(lo, v)) : d); +/** @param {any} v @param {number} lo @param {number} hi @param {number} d */ +const int = (v, lo, hi, d) => Math.round(num(v, lo, hi, d)); +/** @param {any} v @param {number} lo @param {number} hi @param {number[]} d */ +const vec = (v, lo, hi, d) => (Array.isArray(v) && v.length === 3 ? v.map((n, i) => num(n, lo, hi, d[i])) : [...d]); + +/** + * Clean a record from anywhere (a save, a peer, the agent, the Inspector). Unknown keys are dropped; + * null for anything that is not an object or names an unknown mode. + * @param {any} raw @returns {ArrayRecord | null} + */ +export function normalizeArray(raw) { + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null; + const d = ARRAY_DEFAULTS; + const mode = ARRAY_MODES.includes(raw.mode) ? raw.mode : raw.mode === undefined ? d.mode : null; + if (!mode) return null; + const grid = vec(raw.grid, 1, 50, d.grid).map((n) => Math.round(n)); + // the grid's product is the copy count: shrink the deepest axis first until it fits + for (let axis = 2; axis >= 0 && grid[0] * grid[1] * grid[2] > ARRAY_MAX; axis--) { + const others = grid.reduce((p, n, i) => (i === axis ? p : p * n), 1); + grid[axis] = Math.max(1, Math.floor(ARRAY_MAX / others)); + } + return { + v: 1, + mode, + count: int(raw.count, 2, ARRAY_MAX, d.count), + step: vec(raw.step, -1000, 1000, d.step), + grid, + gridStep: vec(raw.gridStep, -1000, 1000, d.gridStep), + radius: num(raw.radius, 0, 1000, d.radius), + arc: num(raw.arc, 1, 360, d.arc), + faceOut: typeof raw.faceOut === 'boolean' ? raw.faceOut : d.faceOut, + path: typeof raw.path === 'string' && raw.path.length <= 64 ? raw.path : '', + spacing: num(raw.spacing, 0, 1000, d.spacing), + follow: typeof raw.follow === 'boolean' ? raw.follow : d.follow, + rotStep: vec(raw.rotStep, -360, 360, d.rotStep), + scaleStep: num(raw.scaleStep, -0.9, 10, d.scaleStep) + }; +} + +/** how many objects the array shows, the original included @param {ArrayRecord} rec */ +export function arrayTotal(rec) { + return rec.mode === 'grid' ? rec.grid[0] * rec.grid[1] * rec.grid[2] : rec.count; +} + +/** a short line for the Inspector, toasts and the agent ("5 in a line") @param {ArrayRecord} rec */ +export function arraySummary(rec) { + const n = arrayTotal(rec); + if (rec.mode === 'grid') return `${rec.grid.join(' x ')} grid (${n})`; + if (rec.mode === 'circle') return `${n} in a ${rec.arc >= 360 ? 'circle' : 'arc'}`; + if (rec.mode === 'path') return `${n} along a path`; + return `${n} in a line`; +} + +/** + * A polyline measured once: cumulative lengths, for points and tangents at a distance. + * @param {number[][]} points @param {boolean} closed + */ +export function measurePolyline(points, closed) { + const pts = points.filter((p) => Array.isArray(p) && p.length >= 3 && p.every((n) => Number.isFinite(n))).map((p) => [p[0], p[1], p[2]]); + if (closed && pts.length > 2) pts.push(pts[0]); + /** @type {number[]} */ + const cum = [0]; + for (let i = 1; i < pts.length; i++) { + const a = pts[i - 1]; + const b = pts[i]; + cum.push(cum[i - 1] + Math.hypot(b[0] - a[0], b[1] - a[1], b[2] - a[2])); + } + return { pts, cum, length: cum[cum.length - 1] ?? 0, closed: closed && pts.length > 3 }; +} + +/** + * Point + unit tangent at distance `s` along a measured polyline (clamped to its ends). + * @param {ReturnType} line @param {number} s + * @returns {{point: number[], tangent: number[]}} + */ +export function pointAt(line, s) { + const { pts, cum, length } = line; + if (pts.length < 2 || length <= 0) return { point: pts[0] ?? [0, 0, 0], tangent: [1, 0, 0] }; + const at = Math.min(length, Math.max(0, s)); + let i = 1; + while (i < cum.length - 1 && cum[i] < at) i++; + // skip zero-length segments so the tangent is never NaN + while (i < cum.length - 1 && cum[i] - cum[i - 1] < 1e-9) i++; + const a = pts[i - 1]; + const b = pts[i]; + const seg = cum[i] - cum[i - 1]; + const t = seg > 1e-9 ? (at - cum[i - 1]) / seg : 0; + const tangent = seg > 1e-9 ? [(b[0] - a[0]) / seg, (b[1] - a[1]) / seg, (b[2] - a[2]) / seg] : [1, 0, 0]; + return { point: [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t], tangent }; +} + +const _q = new THREE.Quaternion(); +const _qStep = new THREE.Quaternion(); +const _e = new THREE.Euler(); +const _t0 = new THREE.Vector3(); +const _t1 = new THREE.Vector3(); +const _up = new THREE.Vector3(0, 1, 0); +const DEG = Math.PI / 180; + +/** + * The poses of copies 1..n-1 in the object's PARENT frame. `base` is the object's local pose; + * `path` is the followed polyline already in that parent frame (path mode only; absent or too + * short = no copies, the Inspector says "Pick a path"). + * @param {ArrayRecord} rec + * @param {{position: number[], quaternion: number[], scale: number[]}} base + * @param {{points: number[][], closed: boolean} | null} [path] + * @returns {{position: number[], quaternion: number[], scale: number[]}[]} + */ +export function arrayCopyPoses(rec, base, path = null) { + const n = arrayTotal(rec); + const [px, py, pz] = base.position; + const baseQ = new THREE.Quaternion().fromArray(base.quaternion); + /** @type {{position: number[], quaternion: number[], scale: number[]}[]} */ + const out = []; + let line = null; + let start = null; + if (rec.mode === 'path') { + line = path ? measurePolyline(path.points, !!path.closed) : null; + if (!line || line.length <= 1e-6) return out; + start = pointAt(line, 0); + _t0.fromArray(start.tangent); + } + for (let i = 1; i < n; i++) { + let pos = [px, py, pz]; + _q.copy(baseQ); + if (rec.mode === 'line') { + pos = [px + rec.step[0] * i, py + rec.step[1] * i, pz + rec.step[2] * i]; + } else if (rec.mode === 'grid') { + const [nx, ny] = rec.grid; + const ix = i % nx; + const iy = Math.floor(i / nx) % ny; + const iz = Math.floor(i / (nx * ny)); + pos = [px + rec.gridStep[0] * ix, py + rec.gridStep[1] * iy, pz + rec.gridStep[2] * iz]; + } else if (rec.mode === 'circle') { + const theta = rec.arc >= 360 ? (i * 2 * Math.PI) / n : (i * rec.arc * DEG) / (n - 1); + // the centre sits `radius` on -X of the object, so the object itself is at angle 0 + const cx = px - rec.radius; + pos = [cx + rec.radius * Math.cos(theta), py, pz - rec.radius * Math.sin(theta)]; + if (rec.faceOut) _q.premultiply(_qStep.setFromAxisAngle(_up, theta)); + } else if (line && start) { + const s = rec.spacing > 0 ? rec.spacing * i : line.closed ? (line.length * i) / n : (line.length * i) / (n - 1); + if (s > line.length + 1e-6) { + if (!line.closed) break; // an open path ends: no copy hangs past it + } + const at = pointAt(line, line.closed ? s % line.length : s); + pos = [px + at.point[0] - start.point[0], py + at.point[1] - start.point[1], pz + at.point[2] - start.point[2]]; + if (rec.follow) _q.premultiply(_qStep.setFromUnitVectors(_t0, _t1.fromArray(at.tangent))); + } + if (rec.rotStep[0] || rec.rotStep[1] || rec.rotStep[2]) { + _e.set(rec.rotStep[0] * DEG * i, rec.rotStep[1] * DEG * i, rec.rotStep[2] * DEG * i); + _q.multiply(_qStep.setFromEuler(_e)); + } + const f = Math.max(0.01, 1 + rec.scaleStep * i); + out.push({ position: pos, quaternion: _q.toArray(), scale: base.scale.map((s) => s * f) }); + } + return out; +} diff --git a/src/lib/arrayRuntime.js b/src/lib/arrayRuntime.js new file mode 100644 index 000000000..10f4d508b --- /dev/null +++ b/src/lib/arrayRuntime.js @@ -0,0 +1,209 @@ +// @ts-ignore - no bundled three type declarations (project-wide) +import * as THREE from 'three'; +import { normalizeArray, arrayCopyPoses } from './arrayCore.js'; +import { textPathPolylineOf, textPathSourceKey } from './textPathSources.js'; +import { isEditOverlay } from './editOverlays.js'; + +// 102b-arrange row 1 — THE ARRAY RUNTIME (a lazy chunk; arrayTick.js loads it once a scene holds +// an array). LOCAL per peer and never saved or sent: only `userData.array` travels, and every peer +// draws the same copies from it (golden rule 8). +// +// Per array, ONE InstancedMesh per mesh of the object, at the scene root (objectsGroup's parent, +// golden rule 5: serializers, pickers and the object list never see it). The instances SHARE the +// object's geometry and materials, so a colour, texture or mesh edit on the object shows on every +// copy the same frame, and the whole array costs one draw call per mesh of the object, not one per +// copy. Rebuilt only when something it depends on changes (the record, the object's pose or meshes, +// the followed path); a resting array costs a key compare per frame. +// +// What copies are NOT: objects. They have no collider, no logic, no click, and a glTF export of +// the object does not include them — "Make real objects" (arrayActions.js) turns them into objects. + +const VISUAL_NAME = 'Array copies (visual)'; + +/** @typedef {{carrier: any, key: string, recRef: any, rec: any, meshes: {src: any, inst: any}[], shape: string}} Entry */ + +/** @type {Map} */ +const entries = new Map(); +let visualParent = /** @type {any} */ (null); + +const _inv = new THREE.Matrix4(); +const _carrierInv = new THREE.Matrix4(); +const _rel = new THREE.Matrix4(); +const _copy = new THREE.Matrix4(); +const _m = new THREE.Matrix4(); +const _p = new THREE.Vector3(); +const _q = new THREE.Quaternion(); +const _s = new THREE.Vector3(); +const _parentInv = new THREE.Matrix4(); + +/** is the object shown (it and every ancestor up to the root) @param {any} o @param {any} root */ +function shown(o, root) { + for (let n = o; n && n !== root; n = n.parent) if (!n.visible) return false; + return true; +} + +/** the meshes an array repeats: the object's own meshes, never edit overlays or other arrays' visuals + * @param {any} carrier */ +function meshesOf(carrier) { + /** @type {any[]} */ + const out = []; + carrier.traverse((/** @type {any} */ n) => { + if (!n.isMesh || n.isInstancedMesh || n.isSkinnedMesh || isEditOverlay(n)) return; + if (n.userData?.textPath) return; // a text's mesh is a hit proxy that draws nothing + out.push(n); + }); + return out; +} + +/** the path an array follows, as points in the CARRIER'S PARENT frame, or null + * @param {any} carrier @param {any} rec @param {any} root */ +function pathIn(carrier, rec, root) { + if (rec.mode !== 'path' || !rec.path || !root) return null; + const pathObj = root.getObjectByProperty('uuid', rec.path); + if (!pathObj || pathObj === carrier) return null; + const line = textPathPolylineOf(pathObj); + if (!line) return null; + pathObj.updateWorldMatrix(true, false); + _parentInv.copy(carrier.parent.matrixWorld).invert(); + _m.multiplyMatrices(_parentInv, pathObj.matrixWorld); + return { + points: line.points.map((p) => _p.fromArray(p).applyMatrix4(_m).toArray()), + closed: !!line.closed + }; +} + +/** + * The copies' poses in the object's parent frame (what the runtime draws and what Make real objects + * places). [] for an object with no (valid) record or a path that cannot be read. + * @param {any} carrier @param {any} root objectsGroup + */ +export function copyPosesOf(carrier, root) { + const rec = normalizeArray(carrier?.userData?.array); + if (!rec || !carrier.parent) return []; + carrier.parent.updateWorldMatrix(true, false); + return arrayCopyPoses( + rec, + { position: carrier.position.toArray(), quaternion: carrier.quaternion.toArray(), scale: carrier.scale.toArray() }, + pathIn(carrier, rec, root) + ); +} + +/** what the drawn copies depend on, as one string @param {Entry} e @param {any} root */ +function keyOf(e, root) { + const c = e.carrier; + const parts = [JSON.stringify(e.rec), shown(c, root) ? 1 : 0]; + for (const v of c.matrixWorld.elements) parts.push(Math.round(v * 1e5)); + for (const m of meshesOf(c)) { + const mats = Array.isArray(m.material) ? m.material.map((/** @type {any} */ x) => x.uuid).join('+') : m.material?.uuid; + parts.push(m.uuid, m.geometry?.uuid, mats, m.castShadow ? 1 : 0, m.receiveShadow ? 1 : 0); + for (const v of m.matrixWorld.elements) parts.push(Math.round(v * 1e5)); + } + if (e.rec?.mode === 'path' && e.rec.path) { + const p = root.getObjectByProperty('uuid', e.rec.path); + if (p) { + for (const v of p.matrixWorld.elements) parts.push(Math.round(v * 1e5)); + const k = textPathSourceKey(p); + parts.push(typeof k === 'object' ? JSON.stringify(k) : String(k)); + } else parts.push('no-path'); + } + return parts.join(','); +} + +/** @param {Entry} e */ +function dropMeshes(e) { + for (const { inst } of e.meshes) { + inst.parent?.remove(inst); + inst.dispose(); // the instance buffers only: geometry and materials belong to the object + } + e.meshes = []; + e.shape = ''; +} + +/** (re)build an entry's instanced meshes and their matrices @param {Entry} e @param {any} root */ +function rebuild(e, root) { + const c = e.carrier; + const poses = e.rec && shown(c, root) ? copyPosesOf(c, root) : []; + const meshes = poses.length ? meshesOf(c) : []; + const shape = meshes.map((m) => `${m.uuid}:${m.geometry?.uuid}`).join('|') + `#${poses.length}`; + if (shape !== e.shape) { + dropMeshes(e); + for (const src of meshes) { + const inst = new THREE.InstancedMesh(src.geometry, src.material, poses.length); + inst.name = VISUAL_NAME; + inst.userData.arrayVisual = c.uuid; + inst.matrixAutoUpdate = false; + inst.raycast = () => {}; // not pickable: a click on a copy goes to what is behind it + visualParent.add(inst); + e.meshes.push({ src, inst }); + } + e.shape = shape; + } + if (!poses.length) return; + _inv.copy(visualParent.matrixWorld).invert(); + _carrierInv.copy(c.matrixWorld).invert(); + for (const { src, inst } of e.meshes) { + inst.material = src.material; // a material swap (Make it metal, a texture) follows + inst.castShadow = src.castShadow; + inst.receiveShadow = src.receiveShadow; + _rel.multiplyMatrices(_carrierInv, src.matrixWorld); + poses.forEach((pose, i) => { + _copy.compose(_p.fromArray(pose.position), _q.fromArray(pose.quaternion), _s.fromArray(pose.scale)); + _m.multiplyMatrices(c.parent.matrixWorld, _copy).premultiply(_inv).multiply(_rel); + inst.setMatrixAt(i, _m); + }); + inst.instanceMatrix.needsUpdate = true; + inst.computeBoundingSphere(); + } +} + +/** + * Per frame (arrayTick): one set of instanced copies per array. Nothing here is sent or saved. + * @param {any[]} carriers objects holding `userData.array` @param {any} root objectsGroup + */ +export function tickArrays(carriers, root) { + visualParent = root?.parent ?? null; + /** @type {Set} */ + const alive = new Set(); + if (visualParent) { + visualParent.updateWorldMatrix(true, false); + for (const c of carriers) { + if (!c.parent || !c.userData?.array) continue; + alive.add(c.uuid); + let e = entries.get(c.uuid); + if (e && e.carrier !== c) { + dropMeshes(e); // a replaced object under the same uuid (an override sync, an undo) + e = undefined; + } + if (!e) { + e = { carrier: c, key: '', recRef: null, rec: null, meshes: [], shape: '' }; + entries.set(c.uuid, e); + } + if (c.userData.array !== e.recRef) { + e.recRef = c.userData.array; + e.rec = normalizeArray(e.recRef); + } + c.updateWorldMatrix(true, true); + const key = keyOf(e, root); + if (key === e.key) continue; + e.key = key; + rebuild(e, root); + } + } + for (const [uuid, e] of entries) { + if (alive.has(uuid)) continue; + dropMeshes(e); + entries.delete(uuid); + } +} + +/** the debug read: {uuid: copies drawn} plus the draw calls it costs */ +export function arraysDebug() { + /** @type {Record} */ + const copies = {}; + let draws = 0; + for (const [uuid, e] of entries) { + copies[uuid] = e.meshes[0]?.inst.count ?? 0; + draws += e.meshes.length; + } + return { copies, draws }; +} diff --git a/src/lib/arrayTick.js b/src/lib/arrayTick.js new file mode 100644 index 000000000..b22f136f3 --- /dev/null +++ b/src/lib/arrayTick.js @@ -0,0 +1,54 @@ +import { objectsGroup } from '../stores/sceneStore'; + +// 102b-arrange row 1: the per-frame entry for arrays — ONE line in Scene's useTask (editor, Play and +// exported games share Scene.svelte). The textPathTick shape: the runtime is a lazy chunk imported +// only once a scene holds an array; a scene with none pays a scan per scene poke (and one a second). + +const FALLBACK_MS = 1000; + +let wanted = true; +let lastScan = 0; +/** @type {any[]} */ +let carriers = []; +/** @type {null | ((carriers: any[], root: any) => void)} */ +let tick = null; +let loading = false; +let ever = false; + +objectsGroup.subscribe(() => { + wanted = true; +}); + +/** @param {any} root objectsGroup @param {number} now ms */ +export function tickArraysLazy(root, now) { + if (!root) return; + if (wanted || now - lastScan > FALLBACK_MS) { + wanted = false; + lastScan = now; + /** @type {any[]} */ + const found = []; + root.traverse((/** @type {any} */ o) => { + if (o !== root && o.userData?.array) found.push(o); + }); + carriers = found; + } + if (tick) { + // the last array went: one more pass lets the runtime drop its copies, then it rests + if (carriers.length || ever) tick(carriers, root); + ever = carriers.length > 0; + return; + } + if (loading || !carriers.length) return; + loading = true; + import('./arrayRuntime.js') + .then((m) => { + tick = m.tickArrays; + }) + .catch((err) => console.log('array runtime failed to load', err)) + .finally(() => (loading = false)); +} + +/** a scene poke the runtime's own writes do not make (the Inspector's live preview calls it) */ +export function arraysChanged() { + wanted = true; +} diff --git a/src/lib/commandsHandler.svelte.js b/src/lib/commandsHandler.svelte.js index 410ddff15..39cf93271 100644 --- a/src/lib/commandsHandler.svelte.js +++ b/src/lib/commandsHandler.svelte.js @@ -724,6 +724,23 @@ export async function objectParameters(data, from = 'peer') { else delete mesh.userData.textPath; pokeScene(); } + } else if (data.parameter == 'layer') { + // 102b-arrange: which layer an object is on (an id from the scene's layer table) or null + let mesh = sceneObjects.getObjectByProperty('uuid', data.uuid); + if (mesh) { + if (typeof data.layer === 'string' && data.layer) mesh.userData.layer = data.layer; + else delete mesh.userData.layer; + pokeScene(); + } + } else if (data.parameter == 'array') { + // 102b-arrange: an array record (wireValidate checked the shape; the runtime normalizes on + // read) or null = the array is gone. Every peer draws the copies itself. + let mesh = sceneObjects.getObjectByProperty('uuid', data.uuid); + if (mesh) { + if (data.array) mesh.userData.array = JSON.parse(JSON.stringify(data.array)); + else delete mesh.userData.array; + pokeScene(); + } } else if (data.parameter == 'fluidInteraction') { // 36-fb F23: how a mesh meets particle fluid (absent = auto) let mesh = sceneObjects.getObjectByProperty('uuid', data.uuid); diff --git a/src/lib/debugHooks.js b/src/lib/debugHooks.js index 226957a49..337b99d33 100644 --- a/src/lib/debugHooks.js +++ b/src/lib/debugHooks.js @@ -648,6 +648,11 @@ export const DEBUG_HOOKS = [ // 64 D2: text on a path (textPathDebug, setLetterOverrides) ['textPath', () => import('./textPathRuntime.js')], ['textPathEdit', () => import('./textPathEdit.js')], + // 102b-arrange: arrays (runtime debug + actions), tidy, vertex snap + ['arrayRuntime', () => import('./arrayRuntime.js')], + ['arrayActions', () => import('./arrayActions.js')], + ['tidyActions', () => import('./tidyActions.js')], + ['layersRuntime', () => import('./layersRuntime.js')], // 64-text: fonts (bundled + Library + Google), the solid build, the export licence walk ['textFonts', () => import('./textFonts.js')], ['text3dBuild', () => import('./text3dBuild.js')], diff --git a/src/lib/layersCore.js b/src/lib/layersCore.js new file mode 100644 index 000000000..526fd9e0a --- /dev/null +++ b/src/lib/layersCore.js @@ -0,0 +1,35 @@ +// 102b-arrange row 2 — LAYERS, the schema half (a zero-import LEAF: scenePhysics, pickPass and the +// layer UI read it). The table lives in the scenePhysics singleton as `layers` (present only when +// authored, so a scene without layers is byte-identical) and an object names its layer in +// `userData.layer` (an id). Name, colour and lock are scene data (saved, replicated); HIDE is this +// screen's (layersRuntime.js), so one person tidying never blanks somebody else's view. + +export const LAYERS_MAX = 64; +const HEX = /^#[0-9a-f]{6}$/i; +/** the colours a new layer takes in turn (colour-blind safe hues; the swatch is never the only cue) */ +export const LAYER_COLORS = ['#4e79a7', '#f28e2b', '#59a14f', '#e15759', '#b07aa1', '#76b7b2', '#edc948', '#9c755f']; + +/** @typedef {{id: string, name: string, color: string, locked?: true}} Layer */ + +/** One boundary for the table: bad rows dropped, names trimmed, at most LAYERS_MAX; null when empty. + * @param {any} raw @returns {Layer[] | null} */ +export function normalizeLayers(raw) { + if (!Array.isArray(raw)) return null; + /** @type {Layer[]} */ + const out = []; + const seen = new Set(); + for (const r of raw) { + if (!r || typeof r.id !== 'string' || !r.id || r.id.length > 64 || seen.has(r.id)) continue; + seen.add(r.id); + const name = typeof r.name === 'string' && r.name.trim() ? r.name.trim().slice(0, 60) : 'Layer'; + const color = typeof r.color === 'string' && HEX.test(r.color) ? r.color.toLowerCase() : LAYER_COLORS[out.length % LAYER_COLORS.length]; + out.push(r.locked === true ? { id: r.id, name, color, locked: true } : { id: r.id, name, color }); + if (out.length >= LAYERS_MAX) break; + } + return out.length ? out : null; +} + +/** the ids of the locked layers @param {any} layers @returns {Set} */ +export function lockedLayerIds(layers) { + return new Set((Array.isArray(layers) ? layers : []).filter((l) => l?.locked === true).map((l) => l.id)); +} diff --git a/src/lib/layersRuntime.js b/src/lib/layersRuntime.js new file mode 100644 index 000000000..3c0761bf8 --- /dev/null +++ b/src/lib/layersRuntime.js @@ -0,0 +1,66 @@ +import { writable, get } from 'svelte/store'; +import { objectsGroup, sceneRevision, isLocked } from '../stores/sceneStore'; +import { registerParkHook } from './parkHooks.js'; + +// 102b-arrange row 2 — HIDE A LAYER ON THIS SCREEN (a lazy chunk: loaded the first time someone hides +// a layer). Hiding is LOCAL: nothing is sent, and a hidden layer never reaches a save — a park hook +// shows the objects again for the moment a serializer reads the scene (golden rule 10's ritual), so a +// file saved here, an autosave or a joiner's full sync carries every object's own visibility. Play +// shows everything (you test the game you made, not your tidy view). +// +// Only what THIS module hid comes back: an object somebody hid with its own eye stays hidden. + +/** @type {import('svelte/store').Writable>} the layer ids hidden on this screen */ +export const hiddenLayers = writable(new Set()); +/** @type {Set} objects this module hid */ +const hiddenByUs = new Set(); + +function reconcile() { + const group = /** @type {any} */ (get(objectsGroup)); + const hidden = get(hiddenLayers); + const playing = get(isLocked) === true; + /** @type {Set} */ + const want = new Set(); + if (group && hidden.size && !playing) + group.traverse((/** @type {any} */ o) => { + if (o !== group && o.userData?.layer && hidden.has(o.userData.layer)) want.add(o); + }); + for (const o of hiddenByUs) { + if (want.has(o)) continue; + hiddenByUs.delete(o); + if (o.visible === false) o.visible = true; + } + for (const o of want) { + if (hiddenByUs.has(o) || o.visible === false) continue; // already hidden by its own eye + o.visible = false; + hiddenByUs.add(o); + } +} + +sceneRevision.subscribe(reconcile); +hiddenLayers.subscribe(reconcile); +isLocked.subscribe(reconcile); + +registerParkHook(() => { + if (!hiddenByUs.size) return null; + const list = [...hiddenByUs]; + for (const o of list) o.visible = true; + return () => { + for (const o of list) if (hiddenByUs.has(o)) o.visible = false; + }; +}); + +/** hide or show one layer on this screen @param {string} id @param {boolean} hide */ +export function setLayerHidden(id, hide) { + hiddenLayers.update((s) => { + const next = new Set(s); + if (hide) next.add(id); + else next.delete(id); + return next; + }); +} + +/** how many objects are hidden here right now (debug + suites) */ +export function layersHiddenCount() { + return hiddenByUs.size; +} diff --git a/src/lib/objectActions.js b/src/lib/objectActions.js index ce080f5a3..725f72dd8 100644 --- a/src/lib/objectActions.js +++ b/src/lib/objectActions.js @@ -938,6 +938,18 @@ registerHistoryKind('props', (entry, state) => { if (peer) peer.send({ type: 'objectParameters', parameter: 'textPath', uuid: entry.uuid, textPath: state.textPath ?? null, ...(state.bake ? { bake: true } : {}) }); } + if ('layer' in state) { + // 102b-arrange: the object's layer id (tidyActions.setObjectsLayer is the write path) + if (state.layer) object.userData.layer = state.layer; + else delete object.userData.layer; + if (peer) peer.send({ type: 'objectParameters', parameter: 'layer', uuid: entry.uuid, layer: state.layer ?? null }); + } + if ('array' in state) { + // 102b-arrange: the array record (arrayActions.setArray is the write path) + if (state.array) object.userData.array = state.array; + else delete object.userData.array; + if (peer) peer.send({ type: 'objectParameters', parameter: 'array', uuid: entry.uuid, array: state.array ?? null }); + } if ('fluidInteraction' in state) { // 36-fb F23: how a mesh meets particle fluid (none / collide / float; absent = auto) if (state.fluidInteraction) object.userData.fluidInteraction = state.fluidInteraction; diff --git a/src/lib/pickPass.js b/src/lib/pickPass.js index 6eea0e9e2..66d3b6c94 100644 --- a/src/lib/pickPass.js +++ b/src/lib/pickPass.js @@ -7,10 +7,15 @@ import { get } from 'svelte/store'; import { scenePhysicsState_ } from './scenePhysics'; import { normalizePassThrough, gamePassThrough } from './selectThrough'; import { gameFeelActive } from './gameFeel'; +import { lockedLayerIds } from './layersCore.js'; /** What the editor's selection passes through in this scene. */ export function editorPass() { - return normalizePassThrough(get(scenePhysicsState_)?.pick); + const state = get(scenePhysicsState_); + // 102b-arrange: a LOCKED layer's objects are click-through for the editor only (never a game's rays) + const locked = state?.layers ? lockedLayerIds(state.layers) : null; + const pass = normalizePassThrough(state?.pick); + return locked?.size ? { ...pass, lockedLayers: locked } : pass; } /** What a game's interaction rays pass through in this scene. */ diff --git a/src/lib/scenePhysics.js b/src/lib/scenePhysics.js index f3969b59f..59e81ee2c 100644 --- a/src/lib/scenePhysics.js +++ b/src/lib/scenePhysics.js @@ -1,4 +1,5 @@ import { writable, derived, get } from 'svelte/store'; +import { normalizeLayers } from './layersCore.js'; import { sessionNow } from './sessionClock'; // 25-E: stamps another peer compares import { peers } from '../stores/appStore'; import { normalizeLocomotion, normalizeSpawn } from './locomotionPolicy'; // 30b P3/P4 @@ -253,6 +254,8 @@ export function normalizeScenePhysics(raw) { // 93 LP0: the game's ONE Levels table (+ its keep list and loading screen) — present only when // authored, so a scene that never used it stays byte-identical (gameLevels/table.js) ...optional('levels', normalizeLevelsTable(source.levels)), + // 102b-arrange: the scene's LAYERS (name, colour, lock) — present only when authored (layersCore.js) + ...optional('layers', normalizeLayers(source.layers)), changedAt: typeof source.changedAt === 'number' ? source.changedAt : 0 }; return withUnknown(source, state, [ @@ -271,6 +274,7 @@ export function normalizeScenePhysics(raw) { 'simOnLoad', 'fluidBudget', 'levels', + 'layers', 'changedAt', 'type' // the wire envelope's own field, never state ]); diff --git a/src/lib/selectThrough.js b/src/lib/selectThrough.js index 7e7de20b3..ce4d072f0 100644 --- a/src/lib/selectThrough.js +++ b/src/lib/selectThrough.js @@ -156,9 +156,13 @@ export function pickStack(hits, topOf, pass = PASS_DEFAULTS) { const stack = []; /** @type {Map} */ const at = new Map(); + // 102b-arrange: an object on a LOCKED layer is not pickable in the viewport at all (the editor + // pass carries the set; a see-through entry would still be the fallback pick of primaryIndex) + const locked = /** @type {any} */ (pass)?.lockedLayers; for (const hit of hits ?? []) { const target = topOf(hit.object); if (!target) continue; + if (locked?.size && target.userData?.layer && locked.has(target.userData.layer)) continue; const through = isSeeThrough(hit, target, pass); const index = at.get(target.uuid); if (index === undefined) { diff --git a/src/lib/shortcuts.js b/src/lib/shortcuts.js index a9d306b70..96e94ce2f 100644 --- a/src/lib/shortcuts.js +++ b/src/lib/shortcuts.js @@ -731,6 +731,16 @@ export const shortcuts = [ showToast(enabled ? 'Element snapping on' : 'Element snapping off'); } }, + { + // 102b-arrange row 3: corner snap — read straight off the keyboard by snapEngine (needs keyup) + id: 'scene.cornerSnap', + keys: 'B (hold)', + group: 'Scene', + scope: 'viewport', + label: 'Hold while moving: snap the nearest corner onto a corner or edge middle', + fixed: true, + fixedReason: 'hold key, handled by the snap engine' + }, { // 37 R18: the HUD view-mode quick toggle — cycle Shaded / Shaded + AO / Wireframe // (LOCAL, never replicated); viewMode.js is a leaf, so the static edge is safe diff --git a/src/lib/snapEngine.js b/src/lib/snapEngine.js index d6a2841e6..256759a74 100644 --- a/src/lib/snapEngine.js +++ b/src/lib/snapEngine.js @@ -81,6 +81,91 @@ let alignApplied = false; let started = false; const SEARCH_INTERVAL_MS = 33; + +// ---- 102b-arrange row 3: CORNER SNAP (hold B while moving) --------------------- +// A momentary mode on top of element snap: while B is held during a translate drag, the search +// offers only exact points (the hovered triangle's corners, edge MIDPOINTS, and the hovered object's +// box corners + box edge midpoints) and the anchor is the dragged object's NEAREST CORNER to that +// point (its own vertices, capped; else its box corners). The stored snapTargets are untouched, and +// with no candidate in range the grid snap applies as it always did. LOCAL, never sent. +/** @type {import('svelte/store').Writable} */ +export const cornerSnapHeld = writable(false); +/** the hold key (V is push-to-talk) */ +export const CORNER_SNAP_CODE = 'KeyB'; +/** the most own vertices a drag remembers as anchors (beyond: the 8 box corners) */ +const CORNER_VERTEX_CAP = 4000; +/** @type {Float32Array|null} the dragged object's corner points in ITS OWN local frame */ +let cornerLocal = null; +/** @type {any} the object `cornerLocal` was read from (null = not read this drag) */ +let cornerFor = null; +const CORNER_TARGETS = { enabled: true, vertex: true, edge: true, face: false, surface: false, object: false, edgeMid: true, boxCorners: true }; +if (typeof window !== 'undefined') { + const typing = (/** @type {any} */ t) => !!t && (t.isContentEditable || t.tagName === 'TEXTAREA' || (t.tagName === 'INPUT' && !['range', 'checkbox', 'button', 'radio'].includes(t.type))); + window.addEventListener('keydown', (e) => { + if (e.code === CORNER_SNAP_CODE && !e.ctrlKey && !e.metaKey && !e.altKey && !typing(e.target)) cornerSnapHeld.set(true); + }); + window.addEventListener('keyup', (e) => { + if (e.code === CORNER_SNAP_CODE) cornerSnapHeld.set(false); + }); + window.addEventListener('blur', () => cornerSnapHeld.set(false)); +} + +/** the 8 corners of a box, then its 12 edge midpoints @param {any} box @returns {any[]} */ +function boxCornerPoints(box) { + const out = []; + for (let i = 0; i < 8; i++) out.push(new THREE.Vector3(i & 1 ? box.max.x : box.min.x, i & 2 ? box.max.y : box.min.y, i & 4 ? box.max.z : box.min.z)); + for (let i = 0; i < 8; i++) + for (const bit of [1, 2, 4]) if (!(i & bit)) out.push(out[i].clone().add(out[i | bit]).multiplyScalar(0.5)); + return out; +} + +/** remember the dragged object's corners in its own frame (its vertices, or its box corners) + * @param {any} object */ +function captureCorners(object) { + cornerLocal = null; + if (!object) return; + object.updateMatrixWorld(true); + const inv = new THREE.Matrix4().copy(object.matrixWorld).invert(); + /** @type {number[]} */ + const pts = []; + let over = false; + object.traverse((/** @type {any} */ n) => { + const pos = n.isMesh && n.geometry?.attributes?.position; + if (!pos || over) return; + if (pts.length / 3 + pos.count > CORNER_VERTEX_CAP) return void (over = true); + const m = new THREE.Matrix4().multiplyMatrices(inv, n.matrixWorld); + for (let i = 0; i < pos.count; i++) pts.push(..._corner.fromBufferAttribute(pos, i).applyMatrix4(m).toArray()); + }); + if (over || !pts.length) { + const box = new THREE.Box3().setFromObject(object).applyMatrix4(inv); + if (box.isEmpty()) return; + pts.length = 0; + for (const p of boxCornerPoints(box).slice(0, 8)) pts.push(p.x, p.y, p.z); + } + cornerLocal = new Float32Array(pts); +} + +/** the nearest of `object`'s remembered corners to `target`, in WORLD space (null without any) + * @param {any} object @param {any} target @param {any} out */ +function nearestCorner(object, target, out) { + if (!object) return null; + if (cornerFor !== object) { + captureCorners(object); + cornerFor = object; + } + if (!cornerLocal) return null; + object.updateMatrixWorld(true); + let best = Infinity; + for (let i = 0; i < cornerLocal.length; i += 3) { + _corner.set(cornerLocal[i], cornerLocal[i + 1], cornerLocal[i + 2]).applyMatrix4(object.matrixWorld); + const d = _corner.distanceToSquared(target); + if (d < best) { + best = d; + out.copy(_corner); + } + } + return best < Infinity ? out : null; +} const MARKER_NAME = 'snap-candidate-marker'; const FACE_TINT_NAME = 'snap-candidate-face'; const MARKER_COLOR = 0xffa02e; @@ -175,6 +260,7 @@ export function beginSnapDrag(excludeUuids) { }; } } + if (!reentrant) cornerFor = null; // 102b-arrange: corners are read on the first held-B frame const targets = get(snapTargets); if (!targets.enabled || !targets.object) return; if (!group) return; @@ -190,6 +276,8 @@ export function endSnapDrag() { dragActive = false; dragExclude = []; dragObjectPoints = null; + cornerLocal = null; + cornerFor = null; pivotDragStart = null; pointerClient = null; // P4: deliberately NO restore here — a drag that ENDS on a live candidate @@ -486,7 +574,8 @@ export function findSnapCandidate(camera, pointerNdc, excludeUuids, opts) { // is perspective-exact by construction (the knife's screen-parameter trap) const onEdge = new THREE.Vector3(); _raycaster.ray.distanceSqToSegment(v0, v1, undefined, onEdge); - candidates.push({ + // 102b-arrange: corner snap wants exact points only — the sliding point is skipped + if (!(/** @type {any} */ (targets).edgeMid)) candidates.push({ type: 'edge', point: onEdge, normal, @@ -506,6 +595,13 @@ export function findSnapCandidate(camera, pointerNdc, excludeUuids, opts) { }); } } + // 102b-arrange: the hovered object's box corners + box edge midpoints (corner snap) + if (/** @type {any} */ (targets).boxCorners && uuid) { + const top = get(objectsGroup)?.getObjectByProperty('uuid', uuid); + const box = top ? new THREE.Box3().setFromObject(top) : null; + if (box && !box.isEmpty()) + boxCornerPoints(box).forEach((point, i) => candidates.push({ type: 'vertex', bonus: i < 8 ? 0 : 1, point, normal: null, uuid, px: projectPx(point, camera, rect) })); + } if (targets.object && dragObjectPoints) { for (const entry of dragObjectPoints) { candidates.push({ @@ -544,6 +640,8 @@ export function anchorWorldPoint(object, candidate) { return _anchor.fromArray(anchor.local).applyMatrix4(picked.matrixWorld); } } + // 102b-arrange: B held = the object's nearest corner to the target lands on it + if (get(cornerSnapHeld) && nearestCorner(object, candidate.point, _anchor)) return _anchor; const targets = get(snapTargets); if (targets.anchorMode === 'pivot') return originWorld(object, _anchor.set(0, 0, 0)); _box.setFromObject(object); @@ -612,9 +710,10 @@ export function applyElementSnap(target, primaryObject) { function snapGatesOpen() { if (!dragActive) return false; const targets = get(snapTargets); - if (!targets.enabled) return false; - if (!(targets.vertex || targets.edge || targets.face || targets.surface || targets.object)) - return false; + if (!get(cornerSnapHeld)) { + if (!targets.enabled) return false; + if (!(targets.vertex || targets.edge || targets.face || targets.surface || targets.object)) return false; + } /** @type {any} */ const controls = get(TControls); if (!controls?.dragging || controls.mode !== 'translate') return false; @@ -638,7 +737,7 @@ function runThrottledSearch() { -((pointerClient[1] - rect.top) / rect.height) * 2 + 1 ]; } - findSnapCandidate(camera, ndc, dragExclude); + findSnapCandidate(camera, ndc, dragExclude, get(cornerSnapHeld) ? { targets: CORNER_TARGETS } : undefined); } /** @@ -685,6 +784,18 @@ function adjustPivotForSnap(pivot, primary) { const targets = get(snapTargets); if (anchor.mode === 'picked' && anchor.uuid && anchor.local) { _anchor.copy(pivot.position); + } else if (get(cornerSnapHeld) && pivotDragStart) { + // 102b-arrange: a set anchors on the nearest corner of the primary's box, moved with the pivot + _pivotShift.copy(pivot.position).sub(pivotDragStart.pivotPos); + _boxProposed.copy(pivotDragStart.primaryBox).translate(_pivotShift); + let best = Infinity; + for (const c of boxCornerPoints(_boxProposed).slice(0, 8)) { + const d = c.distanceToSquared(candidate.point); + if (d < best) { + best = d; + _anchor.copy(c); + } + } } else if (targets.anchorMode === 'pivot' && pivotDragStart) { _anchor.copy(pivot.position).add(pivotDragStart.originOffset); } else if (pivotDragStart) { diff --git a/src/lib/tidyActions.js b/src/lib/tidyActions.js new file mode 100644 index 000000000..9db231e3b --- /dev/null +++ b/src/lib/tidyActions.js @@ -0,0 +1,238 @@ +import { get } from 'svelte/store'; +import { objectsGroup, selectedObjects, pokeScene } from '../stores/sceneStore'; +import { peers, showToast } from '../stores/appStore'; +import { recordEntry, recordTransformSet, beginHistoryBatch, endHistoryBatch, historyBatchOpen, registerHistoryKind } from './history'; +import { withWireBatch } from './wireBatch'; +import { applySelectionSet, renameObject } from './objectActions'; +import { canEditObject } from './objectPermissions'; +import { scenePhysicsState_, setScenePhysics } from './scenePhysics'; +import { normalizeLayers, LAYER_COLORS, LAYERS_MAX } from './layersCore.js'; +import { similarKey, matchesSimilar, renamePlan, randomisePlan } from './tidyCore.js'; +import { linkOf } from './prefabSync'; +import { materialIdOf } from './materialSharing'; + +// 102b-arrange row 2 — TIDY BIG SCENES, the write path (a lazy chunk: the Inspector's Layers and Tidy +// sections, the object menu and the agent reach it). Layers: the table rides the scenePhysics +// singleton (no new message), an object's layer is `userData.layer` (objectParameters 'layer', props +// undo). Every multi-object op is ONE history batch and ONE wire envelope. + +/** @param {string} uuid */ +const objectOf = (uuid) => /** @type {any} */ (get(objectsGroup))?.getObjectByProperty('uuid', uuid) ?? null; + +// ---- the layer table ----------------------------------------------------------------------------- + +/** the scene's layers (never null) @returns {import('./layersCore.js').Layer[]} */ +export function sceneLayers() { + return normalizeLayers(get(scenePhysicsState_)?.layers) ?? []; +} + +// one undo step per table edit: the whole table before and after (small, at most 64 rows) +registerHistoryKind('layertable', (/** @type {any} */ _entry, /** @type {any} */ state) => { + setScenePhysics({ layers: state ?? null }); + return true; +}); + +/** @param {any[] | null} next */ +function writeTable(next) { + const before = get(scenePhysicsState_)?.layers ?? null; + const after = normalizeLayers(next); + if (JSON.stringify(before ?? null) === JSON.stringify(after ?? null)) return false; + setScenePhysics({ layers: after }); + recordEntry({ kind: 'layertable', before, after }); + return true; +} + +/** add a layer (named, the next colour) @param {string} [name] @returns {string | null} its id */ +export function addLayer(name) { + const list = sceneLayers(); + if (list.length >= LAYERS_MAX) { + showToast(`A scene holds up to ${LAYERS_MAX} layers`); + return null; + } + const id = crypto.randomUUID(); + writeTable([...list, { id, name: name?.trim() || `Layer ${list.length + 1}`, color: LAYER_COLORS[list.length % LAYER_COLORS.length] }]); + return id; +} + +/** change one layer's name / colour / lock @param {string} id @param {{name?: string, color?: string, locked?: boolean}} patch */ +export function updateLayer(id, patch) { + const list = sceneLayers(); + return writeTable( + list.map((l) => { + if (l.id !== id) return l; + const next = { ...l, ...patch }; + if (patch.locked === false) delete next.locked; + return next; + }) + ); +} + +/** remove a layer: its objects go back to no layer (one undo for both) @param {string} id */ +export function removeLayer(id) { + const own = !historyBatchOpen(); + if (own) beginHistoryBatch(); + try { + withWireBatch(() => { + setObjectsLayer(membersOf(id), null); + writeTable(sceneLayers().filter((l) => l.id !== id)); + }); + } finally { + if (own) endHistoryBatch('Remove layer'); + } +} + +/** every object on a layer (any depth) @param {string} id @returns {string[]} */ +export function membersOf(id) { + const group = /** @type {any} */ (get(objectsGroup)); + /** @type {string[]} */ + const out = []; + group?.traverse((/** @type {any} */ o) => { + if (o !== group && o.userData?.layer === id) out.push(o.uuid); + }); + return out; +} + +/** + * Put objects on a layer (null = no layer): one props entry each inside ONE batch, one envelope. + * @param {string[]} uuids @param {string | null} id @returns {number} how many changed + */ +export function setObjectsLayer(uuids, id) { + const objects = uuids.map(objectOf).filter((o) => o && canEditObject(o) && (o.userData.layer ?? null) !== (id ?? null)); + if (!objects.length) return 0; + const own = !historyBatchOpen() && objects.length > 1; + if (own) beginHistoryBatch(); + /** @type {any} */ + const peer = get(peers); + try { + withWireBatch(() => { + for (const o of objects) { + const before = o.userData.layer ?? null; + if (id) o.userData.layer = id; + else delete o.userData.layer; + recordEntry({ kind: 'props', uuid: o.uuid, before: { layer: before }, after: { layer: id ?? null } }); + peer?.send?.({ type: 'objectParameters', parameter: 'layer', uuid: o.uuid, layer: id ?? null }); + } + }); + } finally { + if (own) endHistoryBatch('Set layer'); + } + pokeScene(); + return objects.length; +} + +/** select every object on a layer @param {string} id */ +export function selectLayer(id) { + const list = membersOf(id); + applySelectionSet(list, true); + return list.length; +} + +/** hide / show a layer on THIS screen (lazy runtime) @param {string} id @param {boolean} hide */ +export async function setLayerHidden(id, hide) { + const m = await import('./layersRuntime.js'); + m.setLayerHidden(id, hide); +} + +// ---- select similar -------------------------------------------------------------------------------- + +/** the plain descriptor tidyCore matches on @param {any} o */ +export function describeForSimilar(o) { + let mesh = o?.isMesh ? o : null; + if (!mesh) o?.traverse?.((/** @type {any} */ n) => (mesh ??= n.isMesh ? n : null)); + const material = mesh && !Array.isArray(mesh.material) ? mesh.material : null; + return { + gtype: o?.userData?.geometryParams?.gtype ?? null, + geomType: mesh?.geometry?.type ?? null, + verts: mesh?.geometry?.attributes?.position?.count ?? 0, + materialId: mesh ? materialIdOf(mesh) : null, + matType: material?.type ?? null, + color: material?.color?.getHexString?.() ?? null, + mapped: !!material?.map, + prefab: linkOf(o)?.id ?? null, + tags: Array.isArray(o?.userData?.tags) ? o.userData.tags : null, + layer: o?.userData?.layer ?? null + }; +} + +/** + * Select every top-level object like `uuid` by one rule (shape / material / prefab / tag / layer). + * @param {string} by @param {string} [uuid] defaults to the last picked object @returns {number} + */ +export function selectSimilar(by, uuid) { + const sel = /** @type {string[]} */ (get(selectedObjects)); + const from = objectOf(uuid ?? sel[sel.length - 1]); + if (!from) { + showToast('Select an object first'); + return 0; + } + const key = similarKey(describeForSimilar(from), by); + if (key == null) { + showToast(`This object has no ${by} to match`); + return 0; + } + const group = /** @type {any} */ (get(objectsGroup)); + const list = group.children.filter((/** @type {any} */ o) => o === from || matchesSimilar(describeForSimilar(o), by, key)).map((/** @type {any} */ o) => o.uuid); + // the object we matched FROM stays the primary (last) + applySelectionSet([...list.filter((/** @type {string} */ u) => u !== from.uuid), from.uuid], true); + showToast(`${list.length} object${list.length === 1 ? '' : 's'} with the same ${by}`); + return list.length; +} + +// ---- rename many ----------------------------------------------------------------------------------- + +/** rename a set by pattern ({n} counter, {name} old name) in selection order, ONE undo + * @param {string[]} uuids @param {string} pattern @param {number} [start] @param {number} [pad] */ +export function renameMany(uuids, pattern, start = 1, pad = 0) { + const objects = uuids.map(objectOf).filter((o) => o && canEditObject(o)); + if (!objects.length) return 0; + const names = renamePlan( + objects.map((o) => o.name || o.type), + pattern, + start, + pad + ); + const own = !historyBatchOpen(); + if (own) beginHistoryBatch(); + try { + withWireBatch(() => objects.forEach((o, i) => renameObject(o.uuid, names[i]))); + } finally { + if (own) endHistoryBatch('Rename'); + } + showToast(`Renamed ${objects.length} object${objects.length === 1 ? '' : 's'} (one undo)`); + return objects.length; +} + +// ---- randomise ------------------------------------------------------------------------------------- + +/** + * Randomise turn / size / place within ranges (degrees, factors, metres), ONE undo and ONE envelope. + * @param {string[]} uuids @param {{rot?: number[], scale?: number[], offset?: number[], seed?: number}} opts + */ +export function randomise(uuids, opts) { + const objects = uuids.map(objectOf).filter((o) => o && canEditObject(o)); + if (!objects.length) return 0; + const before = objects.map((o) => ({ pos: o.position.toArray(), rot: o.rotation.toArray().slice(0, 3), scale: o.scale.toArray() })); + const after = randomisePlan(before, opts); + /** @type {{uuid: string, before: any, after: any}[]} */ + const items = []; + objects.forEach((o, i) => { + const a = after[i]; + if (JSON.stringify(a) === JSON.stringify(before[i])) return; + o.position.fromArray(a.pos); + o.rotation.set(a.rot[0], a.rot[1], a.rot[2]); + o.scale.fromArray(a.scale); + o.updateMatrixWorld(true); + items.push({ uuid: o.uuid, before: { pos: before[i].pos, rot: [...before[i].rot, 'XYZ'], scale: before[i].scale }, after: { pos: a.pos, rot: o.rotation.toArray(), scale: a.scale } }); + }); + if (!items.length) { + showToast('Randomise: set a range first'); + return 0; + } + recordTransformSet(items); + /** @type {any} */ + const peer = get(peers); + if (peer) withWireBatch(() => items.forEach((it) => peer.send({ type: 'move', uuid: it.uuid, pos: it.after.pos, rot: it.after.rot, scale: it.after.scale }))); + pokeScene(); + showToast(`Randomised ${items.length} object${items.length === 1 ? '' : 's'} (one undo)`); + return items.length; +} diff --git a/src/lib/tidyCore.js b/src/lib/tidyCore.js new file mode 100644 index 000000000..c4e380231 --- /dev/null +++ b/src/lib/tidyCore.js @@ -0,0 +1,90 @@ +// 102b-arrange row 2 — TIDY, the pure half (vitest): select similar keys, rename many, randomise. +// A LEAF: plain data in, plain data out; tidyActions.js reads the scene and records. + +/** mulberry32: a small seeded generator, [0, 1) (the duplicateCore one, so the agent and the + * Inspector make the same scatter from the same seed) @param {number} seed */ +export function seeded(seed) { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +export const SIMILAR_BY = /** @type {const} */ (['shape', 'material', 'prefab', 'tag', 'layer']); + +/** + * What makes two objects "similar" by one rule, as a key (null = this object has nothing to match + * on). `d` is a plain descriptor tidyActions builds: {gtype, geomType, verts, materialId, matType, + * color, mapped, prefab, tags, layer}. + * @param {any} d @param {string} by @returns {string | string[] | null} + */ +export function similarKey(d, by) { + if (!d) return null; + if (by === 'shape') return d.gtype ? 'prim:' + d.gtype : d.geomType ? `geo:${d.geomType}:${d.verts ?? 0}` : null; + if (by === 'material') return d.materialId ? 'id:' + d.materialId : d.matType ? `${d.matType}:${d.color ?? ''}:${d.mapped ? 1 : 0}` : null; + if (by === 'prefab') return d.prefab ? String(d.prefab) : null; + if (by === 'tag') return Array.isArray(d.tags) && d.tags.length ? d.tags.map(String) : null; + if (by === 'layer') return d.layer ? String(d.layer) : null; + return null; +} + +/** does `d` match `key` (tags: any shared tag) @param {any} d @param {string} by @param {any} key */ +export function matchesSimilar(d, by, key) { + const k = similarKey(d, by); + if (k == null || key == null) return false; + if (Array.isArray(key)) return Array.isArray(k) && k.some((t) => key.includes(t)); + return k === key; +} + +/** + * Rename many: `pattern` with {n} (the counter, zero-padded to `pad` digits) and {name} (the old + * name). A pattern without {n} gets " {n}" added, so the names stay distinct. + * @param {string[]} names @param {string} pattern @param {number} [start] @param {number} [pad] + * @returns {string[]} + */ +export function renamePlan(names, pattern, start = 1, pad = 0) { + let p = typeof pattern === 'string' ? pattern.trim().slice(0, 100) : ''; + if (!p) p = '{name}'; + if (!p.includes('{n}')) p += ' {n}'; + const first = Number.isFinite(start) ? Math.round(start) : 1; + const width = Math.max(0, Math.min(6, Math.round(pad) || 0)); + return names.map((old, i) => { + const n = String(first + i).padStart(width, '0'); + return p.replaceAll('{n}', n).replaceAll('{name}', old ?? '').slice(0, 120); + }); +} + +/** @param {any} v @param {number} lo @param {number} hi */ +const clampNum = (v, lo, hi) => (typeof v === 'number' && Number.isFinite(v) ? Math.min(hi, Math.max(lo, v)) : 0); + +/** + * Randomise within ranges: each object turns by up to ±rot degrees per axis, is resized by a factor + * in [scale[0], scale[1]] (uniform) and moves by up to ±offset metres per axis. Seeded, so the same + * call gives the same result on every run. Poses are local {pos, rot (radians, XYZ), scale}. + * @param {{pos: number[], rot: number[], scale: number[]}[]} poses + * @param {{rot?: number[], scale?: number[], offset?: number[], seed?: number}} opts + */ +export function randomisePlan(poses, opts) { + const rot = (opts.rot ?? [0, 0, 0]).map((d) => (clampNum(d, 0, 180) * Math.PI) / 180); + const off = (opts.offset ?? [0, 0, 0]).map((m) => clampNum(m, 0, 1000)); + let [lo, hi] = Array.isArray(opts.scale) ? opts.scale.map((f) => clampNum(f, 0.01, 100)) : [1, 1]; + if (!lo) lo = 1; + if (!hi) hi = 1; + if (lo > hi) [lo, hi] = [hi, lo]; + const rand = seeded(Number.isInteger(opts.seed) ? /** @type {number} */ (opts.seed) : 1); + const r6 = (/** @type {number} */ n) => Math.round(n * 1e6) / 1e6; + return poses.map((p) => { + const dr = rot.map((r) => (r ? (rand() * 2 - 1) * r : 0)); + const f = lo === hi ? lo : lo + rand() * (hi - lo); + const dp = off.map((m) => (m ? (rand() * 2 - 1) * m : 0)); + return { + pos: p.pos.map((v, i) => r6(v + dp[i])), + rot: p.rot.map((v, i) => r6(v + dr[i])), + scale: p.scale.map((v) => r6(v * f)) + }; + }); +} diff --git a/src/lib/wireValidate.js b/src/lib/wireValidate.js index 4a5460207..616ab6add 100644 --- a/src/lib/wireValidate.js +++ b/src/lib/wireValidate.js @@ -513,6 +513,11 @@ export const VALIDATORS = { if (v === null) return isUuid(d.uuid); return isUuid(d.uuid) && !!v && typeof v === 'object' && !isArray(v) && (v.text === undefined || (typeof v.text === 'string' && v.text.length <= 4000)); } + // 102b-arrange: an object's layer id (from the scene's layer table) or null + if (d.parameter === 'layer') return isUuid(d.uuid) && (d.layer === null || (typeof d.layer === 'string' && d.layer.length <= 64)); + // 102b-arrange: an array record is a small plain object or null (normalizeArray cleans it on read) + if (d.parameter === 'array') + return isUuid(d.uuid) && (d.array === null || (!!d.array && typeof d.array === 'object' && !isArray(d.array) && JSON.stringify(d.array).length <= 2000)); if (d.parameter === 'water' || d.parameter === 'bubbles' || d.parameter === 'pour') { const v = d[d.parameter]; return isUuid(d.uuid) && (v === null || (!!v && typeof v === 'object' && !isArray(v))); diff --git a/tests/e2e/arrange-compat.test.cjs b/tests/e2e/arrange-compat.test.cjs new file mode 100644 index 000000000..aad886934 --- /dev/null +++ b/tests/e2e/arrange-compat.test.cjs @@ -0,0 +1,121 @@ +// 102b-arrange — SAVE-FILE COMPATIBILITY, run twice: once against the OLDER release's tree +// (ARRANGE_COMPAT=base: v1.71.0) and once against this lane (ARRANGE_COMPAT=lane, the default). +// base: 1. the files this lane saved (lane-saved-array / lane-saved-layers .tpscene, from the +// array-tool and tidy-layers suites) OPEN with no page error, every object arrives and +// the new keys (userData.array, userData.layer, physics.layers) are KEPT when the old +// release saves the scene again (it simply does not draw them); +// 2. a scene MADE in the old release (boxes, a group, physics, a look) is saved as +// old-base.tpscene with its content signature, loaded back twice = the same signature +// (the measurement is stable). +// lane: 3. old-base.tpscene loads here with the SAME signature the old release computed: +// an old scene loads unchanged, and nothing new is written for it. +// Files live in test-results/102b-arrange/ (copy them between the trees for the base run). +// Run: ARRANGE_COMPAT=base APP_URL=https://localhost:/ npm run e2e -- arrange-compat +const h = require('./helpers.cjs'); +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); + +const MODE = process.env.ARRANGE_COMPAT === 'base' ? 'base' : 'lane'; +const DIR = path.resolve(__dirname, '../../test-results/102b-arrange'); + +/** open a .tpscene's bytes on the page and return what the scene now holds + its signature */ +async function openBytes(page, bytes) { + return page.evaluate(async (arr) => { + const s = window.__tp.test.v1; + const payload = await s.sessions.readSessionZip(new Uint8Array(arr).buffer); + if (!payload) return { error: 'readSessionZip refused the file' }; + await s.sessions.applySession(payload, { backup: false }); + await new Promise((r) => setTimeout(r, 1500)); + let g; + s.objectsGroup.subscribe((v) => (g = v))(); + const objects = []; + g.traverse((o) => { + if (o !== g && (o.userData?.array || o.userData?.layer)) objects.push({ name: o.name, array: o.userData.array ?? null, layer: o.userData.layer ?? null }); + }); + const again = s.sessions.buildSessionPayload('compat'); + return { + count: g.children.length, + marked: objects, + layers: again.physics?.layers ?? null, + resavedArray: JSON.stringify(again.objects ?? []).includes('"array"'), + resavedLayer: JSON.stringify(again.objects ?? []).includes('"layer"'), + signature: s.levels.sceneSignature(again) + }; + }, Array.from(bytes)); +} +const sha = (s) => crypto.createHash('sha256').update(s).digest('hex').slice(0, 16); + +h.run(async () => { + const browser = await h.launch({ args: h.GPU_ARGS }); + const A = await h.setupPage(browser, 'A'); + fs.mkdirSync(DIR, { recursive: true }); + console.log(`mode: ${MODE}`); + + if (MODE === 'base') { + console.log('\n=== 1. the files this lane saved open in the older release ==='); + for (const [file, want] of [ + ['lane-saved-array.tpscene', 'array'], + ['lane-saved-layers.tpscene', 'layer'] + ]) { + const p = path.join(DIR, file); + if (!fs.existsSync(p)) { + h.check(false, `${file} exists (run array-tool and tidy-layers on the lane first)`); + continue; + } + const r = await openBytes(A.page, fs.readFileSync(p)); + h.check(!r.error && r.count >= 1, `${file}: opens, objects arrive | ` + JSON.stringify({ error: r.error, count: r.count })); + h.check(r.marked.some((m) => m[want]), `${file}: the ${want} key rides along on the object | ` + JSON.stringify(r.marked).slice(0, 300)); + h.check(want === 'array' ? r.resavedArray : r.resavedLayer, `${file}: the older release saves it again with the key kept`); + if (want === 'layer') h.check(Array.isArray(r.layers) && r.layers.length >= 1, `${file}: the layer table is kept in the scene physics block | ` + JSON.stringify(r.layers)); + } + h.check(h.pageErrors(A).length === 0, 'no page error opening the lane files | ' + h.pageErrors(A).join(' / ').slice(0, 300)); + + console.log('\n=== 2. a scene made in the older release (the "old scene") ==='); + const bytes = await A.page.evaluate(async () => { + const s = window.__tp.test.v1; + s.commandsHandler.sceneCommand('/clear all'); + // /clear keeps the scene physics block, which still holds the lane file's layer table + s.scenePhysics.scenePhysicsRestore(null); + await new Promise((r) => setTimeout(r, 600)); + for (const cmd of ['/create Box 1 1 1', '/create Sphere', '/create Cylinder', '/create Box 2 0.2 2']) { + s.commandsHandler.sceneCommand(cmd); + await new Promise((r) => setTimeout(r, 400)); + } + let g; + s.objectsGroup.subscribe((v) => (g = v))(); + g.children.forEach((o, i) => { + o.position.set(i * 1.5, 0.5, 0); + o.updateMatrixWorld(true); + }); + s.scenePhysics.setScenePhysics({ gravity: -7 }); + const zip = await s.sessions.exportSessionZip(s.sessions.buildSessionPayload('old-base'), { assets: true, packs: false, flow: true }); + return Array.from(zip); + }); + fs.writeFileSync(path.join(DIR, 'old-base.tpscene'), Buffer.from(bytes)); + const r1 = await openBytes(A.page, bytes); + const r2 = await openBytes(A.page, bytes); + h.check(r1.count >= 4 && r1.signature === r2.signature, `old-base: opens with 4 objects and the same signature twice (${sha(r1.signature)})`); + h.check(!r1.layers && !r1.resavedArray && !r1.resavedLayer, 'old-base: carries no array, layer or layer table | ' + JSON.stringify({ layers: r1.layers, array: r1.resavedArray, layer: r1.resavedLayer })); + fs.writeFileSync(path.join(DIR, 'old-base.signature.txt'), r1.signature); + } else { + console.log('\n=== 3. the old scene loads unchanged in this lane ==='); + const p = path.join(DIR, 'old-base.tpscene'); + const sigFile = path.join(DIR, 'old-base.signature.txt'); + if (!fs.existsSync(p) || !fs.existsSync(sigFile)) h.check(false, 'old-base.tpscene + signature exist (run the base mode first)'); + else { + const base = fs.readFileSync(sigFile, 'utf8'); + const r = await openBytes(A.page, fs.readFileSync(p)); + h.check(r.count >= 4, 'old-base opens with its objects | ' + r.count); + h.check(r.signature === base, `the content signature equals the older release's (${sha(r.signature)} vs ${sha(base)})`); + h.check(!r.layers && !r.resavedArray && !r.resavedLayer, 'nothing new is written for an old scene (no array, layer or layer table) | ' + JSON.stringify({ layers: r.layers, array: r.resavedArray, layer: r.resavedLayer })); + if (r.signature !== base) { + fs.writeFileSync(path.join(DIR, 'old-base.lane-signature.txt'), r.signature); + console.log('signatures differ: see old-base.lane-signature.txt'); + } + } + h.check(h.pageErrors(A).length === 0, 'no page error | ' + h.pageErrors(A).join(' / ').slice(0, 300)); + } + + await h.finish(browser); +}); diff --git a/tests/e2e/array-tool.test.cjs b/tests/e2e/array-tool.test.cjs new file mode 100644 index 000000000..47be9140b --- /dev/null +++ b/tests/e2e/array-tool.test.cjs @@ -0,0 +1,175 @@ +// 102b-arrange row 1 — the Array tool on two connected peers through the real Inspector: +// 1. "Make an array" on a box: ONE objectParameters message, both peers draw the copies +// (one InstancedMesh per mesh = one draw call for the whole array), no object is added; +// 2. count / shape edits: both peers follow, ONE undo puts the previous array back on both; +// 3. the copies sit where the record says on both peers (same poses), circle + grid; +// 4. Make real objects: every copy becomes an object on both peers, ONE wire envelope, +// ONE undo takes them all away and brings the array back; +// 5. a scene saved with an array (kept for the older-release check) and B reloading + rejoining +// draws the array again; a scene with no array draws nothing (feature unused = no change). +// Counterfactual on v1.71.0: there is no #array-section and no `array` record. +// Run: APP_URL=https://localhost:7090/ npm run e2e -- array-tool +const h = require('./helpers.cjs'); + +async function spyWire(page) { + await page.evaluate(() => { + let peer; + window.__tp.test.v1.peers.subscribe((x) => (peer = x))(); + window.__wire = []; + for (const conn of Object.values(peer.connections)) { + if (conn.__spied) continue; + const send = conn.send.bind(conn); + conn.send = (m) => { + window.__wire.push(m?.type === 'batch' ? { type: 'batch', items: m.items.map((i) => i.type) } : { type: m?.type, parameter: m?.parameter }); + return send(m); + }; + conn.__spied = true; + } + }); +} +const wire = (page) => page.evaluate(() => (window.__wire = window.__wire ?? []).splice(0)); +const SCENE_TYPES = new Set(['objectParameters', 'duplicate', 'move', 'batch', 'create', 'object', 'delete']); +const sceneMsgs = (list) => list.filter((m) => SCENE_TYPES.has(m.type)); + +const drawn = (peer, uuid) => peer.page.evaluate((id) => window.__tp.test.v1.arrayRuntime.arraysDebug().copies[id] ?? 0, uuid); +const draws = (peer) => peer.page.evaluate(() => window.__tp.test.v1.arrayRuntime.arraysDebug().draws); +const record = (peer, uuid) => + peer.page.evaluate((id) => { + let g; + window.__tp.test.v1.objectsGroup.subscribe((v) => (g = v))(); + return g.getObjectByProperty('uuid', id)?.userData?.array ?? null; + }, uuid); +const childCount = (peer) => + peer.page.evaluate(() => { + let g; + window.__tp.test.v1.objectsGroup.subscribe((v) => (g = v))(); + return g.children.length; + }); +const posesOf = (peer, uuid) => + peer.page.evaluate((id) => { + const w = window.__tp.test.v1; + let g; + w.objectsGroup.subscribe((v) => (g = v))(); + const o = g.getObjectByProperty('uuid', id); + return o ? w.arrayRuntime.copyPosesOf(o, g).map((p) => p.position.map((n) => Math.round(n * 1000) / 1000)) : null; + }, uuid); +const undo = (peer) => peer.page.evaluate(() => window.__tp.test.v1.history.undo()); +const sameArr = (a, b) => JSON.stringify(a) === JSON.stringify(b); + +h.run(async () => { + const browser = await h.launch({ args: h.GPU_ARGS }); + const A = await h.setupPage(browser, 'A', { context: { viewport: { width: 1440, height: 900 } } }); + const B = await h.setupPage(browser, 'B'); + for (const p of [A, B]) await p.page.waitForFunction(() => !!window.__tp?.test.v1?.arrayRuntime, null, { timeout: 60000 }); + await h.connect(B, A); + + const uuid = await A.page.evaluate(async () => { + const w = window.__tp.test.v1; + w.commandsHandler.sceneCommand('/create Box 1 1 1'); + await new Promise((r) => setTimeout(r, 500)); + let g; + w.objectsGroup.subscribe((v) => (g = v))(); + return g.children[g.children.length - 1].uuid; + }); + await A.page.waitForTimeout(1500); + await h.eventually(() => childCount(B), (n) => n >= 1, 'premise: B has the box', 10000); + const kidsA0 = await childCount(A); + const kidsB0 = await childCount(B); + h.check((await draws(A)) === 0 && (await draws(B)) === 0, 'feature unused: no array copies drawn on either peer'); + + console.log('\n=== 1. Make an array (the real Inspector button) ==='); + await A.page.evaluate((id) => window.__tp.test.v1.objectActions.applySelectionSet([id], true), uuid); + await A.page.waitForSelector('#array-start', { timeout: 20000 }).catch(() => {}); + h.check(await A.page.locator('#array-start').isVisible().catch(() => false), 'the Inspector shows the Array section with "Make an array"'); + await spyWire(A.page); + await wire(A.page); + await A.page.locator('#array-start').scrollIntoViewIfNeeded(); + await A.page.locator('#array-start').click(); + await A.page.waitForTimeout(600); + const sent1 = sceneMsgs(await wire(A.page)); + h.check(sent1.length === 1 && sent1[0].type === 'objectParameters' && sent1[0].parameter === 'array', 'ONE objectParameters message for the whole array' + ' | ' + JSON.stringify(sent1)); + const recA = await record(A, uuid); + h.check(recA?.mode === 'line' && recA?.count === 5, 'A: the object holds a 5-in-a-line record' + ' | ' + JSON.stringify(recA)); + await h.eventually(() => record(B, uuid), (r) => !!r && r.count === 5, 'B: the record arrived', 10000); + for (const [p, n] of [[A, 'A'], [B, 'B']]) { + await h.eventually(() => drawn(p, uuid), (c) => c === 4, `${n}: draws 4 copies`, 10000); + h.check((await draws(p)) === 1, `${n}: the whole array is ONE draw call (one mesh in a box)`); + } + h.check((await childCount(A)) === kidsA0 && (await childCount(B)) === kidsB0, 'no object was added on either peer (the copies are drawn, not objects)'); + await h.eventually(() => A.page.locator('#array-summary').textContent(), (t) => /5 in a line/.test(t ?? ''), 'the section says "5 in a line"', 4000); + + console.log('\n=== 2. edits follow on both peers; ONE undo puts the last array back ==='); + await A.page.evaluate((id) => window.__tp.test.v1.arrayActions.setArray(id, { count: 12 }), uuid); + for (const [p, n] of [[A, 'A'], [B, 'B']]) await h.eventually(() => drawn(p, uuid), (c) => c === 11, `${n}: count 12 -> 11 copies`, 10000); + await undo(A); + for (const [p, n] of [[A, 'A'], [B, 'B']]) await h.eventually(() => drawn(p, uuid), (c) => c === 4, `${n}: ONE undo -> back to 4 copies`, 10000); + // the Shape control (a real click on the Segmented's Grid) + await A.page.locator('#array-mode').getByText('Grid', { exact: true }).click(); + for (const [p, n] of [[A, 'A'], [B, 'B']]) await h.eventually(() => drawn(p, uuid), (c) => c === 8, `${n}: Grid 3 x 1 x 3 -> 8 copies`, 10000); + + console.log('\n=== 3. the copies stand in the same places on both peers ==='); + await A.page.evaluate((id) => window.__tp.test.v1.arrayActions.setArray(id, { mode: 'circle', count: 6, radius: 3, arc: 360 }), uuid); + await h.eventually(() => drawn(B, uuid), (c) => c === 5, 'B: circle of 6 -> 5 copies', 10000); + const pa = await posesOf(A, uuid); + await h.eventually(() => posesOf(B, uuid), (pb) => sameArr(pa, pb), 'circle: B places every copy where A does', 10000); + const box = await A.page.evaluate((id) => { + let g; + window.__tp.test.v1.objectsGroup.subscribe((v) => (g = v))(); + return g.getObjectByProperty('uuid', id).position.toArray(); + }, uuid); + const centre = [box[0] - 3, box[2]]; + h.check(pa.every((p) => Math.abs(Math.hypot(p[0] - centre[0], p[2] - centre[1]) - 3) < 0.01), 'circle: every copy is 3 m from the centre' + ' | ' + JSON.stringify(pa)); + + console.log('\n=== 4. Make real objects: one envelope, one undo ==='); + await A.page.evaluate((id) => window.__tp.test.v1.arrayActions.setArray(id, { mode: 'line', count: 4, step: [2, 0, 0] }), uuid); + await h.eventually(() => drawn(B, uuid), (c) => c === 3, 'B: a line of 4 again (3 copies)', 10000); + await A.page.evaluate((id) => window.__tp.test.v1.objectActions.applySelectionSet([id], true), uuid); + await A.page.waitForSelector('#array-make-real', { timeout: 10000 }).catch(() => {}); + await spyWire(A.page); + await wire(A.page); + await A.page.locator('#array-make-real').scrollIntoViewIfNeeded(); + await A.page.locator('#array-make-real').click(); + await A.page.waitForTimeout(800); + const sent4 = sceneMsgs(await wire(A.page)); + h.check(sent4.length === 1 && sent4[0].type === 'batch', 'Make real objects left as ONE wire envelope' + ' | ' + JSON.stringify(sent4)); + h.check((await childCount(A)) === kidsA0 + 3, 'A: 3 new objects' + ' | ' + String(await childCount(A))); + await h.eventually(() => childCount(B), (n) => n === kidsB0 + 3, 'B: the same 3 new objects', 10000); + h.check((await record(A, uuid)) === null && (await drawn(A, uuid)) === 0, 'A: the record is gone, nothing drawn any more'); + const xs = await A.page.evaluate((k) => { + let g; + window.__tp.test.v1.objectsGroup.subscribe((v) => (g = v))(); + return g.children.slice(k).map((o) => Math.round(o.position.x * 1000) / 1000); + }, kidsA0); + h.check(sameArr(xs, [box[0] + 2, box[0] + 4, box[0] + 6].map((n) => Math.round(n * 1000) / 1000)), 'the objects stand where the copies were (2 m apart)' + ' | ' + JSON.stringify(xs)); + await undo(A); + await h.eventually(() => childCount(A), (n) => n === kidsA0, 'A: ONE undo takes all 3 away', 10000); + await h.eventually(() => childCount(B), (n) => n === kidsB0, 'B: and on the other peer', 10000); + await h.eventually(() => drawn(B, uuid), (c) => c === 3, 'B: the array is back (3 copies drawn)', 10000); + + console.log('\n=== 5. a saved array; B reloads and rejoins ==='); + const bytes = await A.page.evaluate(async () => { + const s = window.__tp.test.v1; + const zip = await s.sessions.exportSessionZip(s.sessions.buildSessionPayload('array-tool'), { assets: true, packs: false, flow: true }); + return Array.from(zip); + }); + const out = require('path').resolve(__dirname, '../../test-results/102b-arrange'); + require('fs').mkdirSync(out, { recursive: true }); + require('fs').writeFileSync(out + '/lane-saved-array.tpscene', Buffer.from(bytes)); + h.check(bytes.length > 1000, 'saved test-results/102b-arrange/lane-saved-array.tpscene' + ' | ' + String(bytes.length)); + await h.freshReload(B); + // a joiner's reload REJOINS by itself (no restore question, no dial input): wait for that, and + // only a page that does not rejoin answers the restore and dials (the text-object pattern) + const rejoined = await B.page + .waitForFunction(() => { let p; window.__tp.test.v1.peers.subscribe((v) => (p = v))(); return (p?.openedPeers?.length ?? p?.openedPeers?.size ?? 0) > 0; }, null, { timeout: 30000, polling: 250 }) + .then(() => true) + .catch(() => false); + console.log('B rejoined after its reload by itself:', rejoined); + if (!rejoined) { + await h.answerRestore(B, 'dismiss').catch(() => {}); + await h.connect(B, A); + } + await h.eventually(() => record(B, uuid), (r) => !!r && r.count === 4, 'B after reload: the record came back with the object', 60000); + await h.eventually(() => drawn(B, uuid), (c) => c === 3, 'B after reload: draws the 3 copies again', 20000); + + await h.finish(browser); +}); diff --git a/tests/e2e/battery.json b/tests/e2e/battery.json index ae35625c1..eb34fb768 100644 --- a/tests/e2e/battery.json +++ b/tests/e2e/battery.json @@ -305,6 +305,9 @@ }, "suites": { "render-seam": 180, + "array-tool": 300, + "corner-snap": 180, + "tidy-layers": 300, "load-check": 240, "schema-two-peers": 360, "uir-people": 300, @@ -963,6 +966,9 @@ "local": ["cinematic-view","fb-water-phone","fluid-gpu","net-stress","quality-phone","throw-peer"] }, "exclude": { + "102b-arrange save-file compatibility across two trees (ARRANGE_COMPAT=base on the older release, then the lane); a lane proof, not a battery suite": [ + "arrange-compat" + ], "test data of ~1.3 GB fetched on demand (scripts/fetch-wild-assets.cjs), ~1 h on the pc: run it when importing or Replace changes; SKIPs without the cache": ["import-wild"], "a VR (IWER) editing suite not in the 1.43 integrator battery: triage owed (test-health-1)": ["music-vr-patch","novr-inset","play-here-iwer","vr-ai-panel","vr-ai-voice","vr-bounded-teleport","vr-box-select","vr-chat","vr-collider-edit","vr-controller-handedness","vr-create-face","vr-create-face-facing","vr-edit-caps","vr-edit-menu","vr-editmenu-reposition","vr-editmenu-tabs","vr-editmode-persist","vr-face-correctness","vr-face-edit","vr-face-live-adjust","vr-face-manip","vr-face-move-fix","vr-face-polygon","vr-face-weld","vr-grips-by-mode","vr-helper-eyes","vr-hz-pinch","vr-keyboard","vr-keyboard-search","vr-laser-panels","vr-mesh-undo","vr-multi-prefab","vr-multiselect-ring","vr-nav-suppression","vr-objects-groups","vr-objects-panel","vr-palette","vr-panel-sharpness-all","vr-panels-on-top","vr-peer-approve","vr-peer-hands","vr-peer-hands-net","vr-ping-accuracy","vr-prefabs","vr-props-panel","vr-ptt","vr-radial-stick","vr-ray-hover","vr-reticle-v2","vr-sleeve","vr-snap-menu","vr-source-rebind","vr-stats","vr-stretch","vr-stretch-fix","vr-stretch-sliders","vr-sweep","vr-teleport-handedness","vr-teleport-toggle","vr-two-hand-grab","vr-ungroup","vr-vertex-edit","vr-vertex-handle-bounds","vr-vertex-hold","vr-vertex-polish","vr-vertex-ray","vr-vertex-trigger","vr-window-grab","vr-world-grab","vr-world-reel","vr-worldgrab-presence"], "a docs / screenshot generator, not a gate": ["flow-node-docs","shader-node-docs","vr-eye-shots","schema-capture"], diff --git a/tests/e2e/corner-snap.test.cjs b/tests/e2e/corner-snap.test.cjs new file mode 100644 index 000000000..d46d7b4aa --- /dev/null +++ b/tests/e2e/corner-snap.test.cjs @@ -0,0 +1,139 @@ +// 102b-arrange row 3 — CORNER SNAP: hold B while moving an object with the gizmo, and its nearest +// corner lands exactly on a corner (or an edge middle) of another object. Driven through the REAL +// Scene gizmo handlers (synthetic dragging-changed + change, the snap-advanced recipe) with the real +// keyboard for B. +// 1. element snapping OFF in the stored targets: without B nothing snaps (the premise); +// 2. B held: A's +X top front corner lands ON B's -X top front corner (A moves to x = 2); +// 3. B held over the middle of B's top front edge: the candidate is the edge MIDDLE (4, 2, 1); +// 4. B typed into a text field does not arm it; releasing B disarms it; the stored targets never changed. +// Counterfactual on v1.71.0: no cornerSnapHeld, nothing snaps in 2 (A stays at x = 0.5). +// Run: APP_URL=https://localhost:7090/ npm run e2e -- corner-snap +const h = require('./helpers.cjs'); + +/** one synthetic drag of A by +0.5 on X with the pointer aimed at `aim` (world) */ +const drag = (page, ids, aim) => + page.evaluate( + ({ a, aim }) => { + const w = window.__tp.test.v1; + let controls, camera, g; + w.TControls.subscribe((v) => (controls = v))(); + w.globalCamera.subscribe((v) => (camera = v))(); + w.objectsGroup.subscribe((v) => (g = v))(); + const boxA = g.getObjectByProperty('uuid', a); + if (!controls || controls.object !== boxA) return { attached: false }; + boxA.position.set(0.5, 1, 0); + boxA.updateMatrixWorld(true); + const p = new w.THREE.Vector3(...aim).project(camera); + let renderer; + w.globalRenderer.subscribe((v) => (renderer = v))(); + const rect = renderer.domElement.getBoundingClientRect(); + w.snapEngine.setSnapPointer(rect.left + (p.x * 0.5 + 0.5) * rect.width, rect.top + (-p.y * 0.5 + 0.5) * rect.height); + controls.dragging = true; + controls.dispatchEvent({ type: 'dragging-changed', value: true }); + boxA.position.x = 0.5; + boxA.updateMatrixWorld(true); + controls.dispatchEvent({ type: 'change' }); // Scene's onchange = three's 'change' (threlte maps it) + let candidate = null; + w.snapEngine.activeSnapCandidate.subscribe((v) => (candidate = v))(); + const box = new w.THREE.Box3().setFromObject(boxA); + // diagnosis: the same search called directly + const ndc = [p.x, p.y]; + const probe = w.snapEngine.findSnapCandidate(camera, ndc, [a], { targets: { enabled: true, vertex: true, edge: true, edgeMid: true, boxCorners: true } }); + const out = { + probe: probe ? probe.type + '@' + probe.point.toArray().map((n) => n.toFixed(2)).join(',') : null, + ndc: ndc.map((n) => n.toFixed(3)), + live: { + mode: controls.mode, + dragging: controls.dragging, + sameCanvas: document.querySelector('canvas') === renderer.domElement, + rect: [rect.left, rect.top, rect.width, rect.height].map((n) => Math.round(n)) + }, + attached: true, + type: candidate?.type ?? null, + point: candidate ? candidate.point.toArray().map((n) => Math.round(n * 1000) / 1000) : null, + pos: boxA.position.toArray().map((n) => Math.round(n * 1000) / 1000), + max: box.max.toArray().map((n) => Math.round(n * 1000) / 1000) + }; + controls.dragging = false; + controls.dispatchEvent({ type: 'dragging-changed', value: false }); + return out; + }, + { a: ids.a, aim } + ); +const held = (page) => page.evaluate(() => new Promise((r) => window.__tp.test.v1.snapEngine.cornerSnapHeld.subscribe((v) => r(v))())); +const near3 = (a, b) => !!a && a.every((v, i) => Math.abs(v - b[i]) < 2e-3); + +h.run(async () => { + const browser = await h.launch({ args: h.GPU_ARGS }); + const A = await h.setupPage(browser, 'A', { context: { viewport: { width: 1440, height: 900 } } }); + + const ids = await A.page.evaluate(async () => { + const w = window.__tp.test.v1; + w.commandsHandler.sceneCommand('/create Box 2 2 2'); + w.commandsHandler.sceneCommand('/create Box 2 2 2'); + await new Promise((r) => setTimeout(r, 600)); + let g; + w.objectsGroup.subscribe((v) => (g = v))(); + const boxes = g.children.filter((c) => c.name?.startsWith('Box')); + const [a, b] = boxes; + a.position.set(0.5, 1, 0); + b.position.set(4, 1, 0); // B spans x 3..5, y 0..2, z -1..1 + a.updateMatrixWorld(true); + b.updateMatrixWorld(true); + w.objectsGroup.update((v) => v); + // the stored element snapping is OFF: only the held key may snap + w.snapping.snapTargets.update((v) => ({ ...v, enabled: false, vertex: false, edge: false, face: false, surface: false, object: false, radiusPx: 40 })); + // look at the pair from the front, a little above + let cam; + w.globalCamera.subscribe((v) => (cam = v))(); + cam.position.set(2, 4, 9); + cam.lookAt(2.5, 1, 0); + cam.updateMatrixWorld(true); + return { a: a.uuid, b: b.uuid }; + }); + await A.page.evaluate((u) => window.__tp.test.v1.objectActions.selectObject(u), ids.a); + await A.page.waitForTimeout(800); + const stored0 = await A.page.evaluate(() => new Promise((r) => window.__tp.test.v1.snapping.snapTargets.subscribe((v) => r(JSON.stringify(v)))())); + + console.log('\n=== 1. without B: nothing snaps ==='); + const AIM_CORNER = [3.03, 1.97, 1]; // just inside B's front face, at its top -X corner (3, 2, 1) + const r1 = await drag(A.page, ids, AIM_CORNER); + h.check(r1.attached, 'the gizmo is on box A'); + h.check(r1.type === null && near3(r1.pos, [0.5, 1, 0]), 'no candidate, A stays at x = 0.5' + ' | ' + JSON.stringify(r1)); + + console.log('\n=== 2. hold B: the nearest corner lands on the corner ==='); + await A.page.mouse.move(20, 450); + await A.page.keyboard.down('b'); + h.check((await held(A.page)) === true, 'B down arms corner snap'); + const r2 = await drag(A.page, ids, AIM_CORNER); + h.check(r2.type === 'vertex' && near3(r2.point, [3, 2, 1]), "the candidate is B's corner (3, 2, 1)" + ' | ' + JSON.stringify(r2)); + h.check(near3(r2.max, [3, 2, 1]), "A's +X top front corner sits ON it" + ' | ' + JSON.stringify(r2.max)); + h.check(near3(r2.pos, [2, 1, 0]), 'A moved to x = 2' + ' | ' + JSON.stringify(r2.pos)); + + console.log('\n=== 3. hold B over an edge middle ==='); + const r3 = await drag(A.page, ids, [4.0, 1.97, 1]); + h.check(near3(r3.point, [4, 2, 1]), "the candidate is the middle of B's top front edge (4, 2, 1)" + ' | ' + JSON.stringify(r3)); + h.check(near3(r3.max, [4, 2, 1]), "A's nearest corner sits on the edge middle" + ' | ' + JSON.stringify(r3.max)); + await A.page.keyboard.up('b'); + h.check((await held(A.page)) === false, 'releasing B disarms it'); + const r4 = await drag(A.page, ids, AIM_CORNER); + h.check(r4.type === null, 'after release nothing snaps again' + ' | ' + JSON.stringify(r4)); + + console.log('\n=== 4. B in a text field; stored targets untouched ==='); + await A.page.evaluate(() => { + const i = document.createElement('input'); + i.id = 'corner-snap-probe'; + document.body.appendChild(i); + i.focus(); + }); + await A.page.keyboard.down('b'); + h.check((await held(A.page)) === false, 'typing B into a text field does not arm corner snap'); + await A.page.keyboard.up('b'); + await A.page.evaluate(() => document.getElementById('corner-snap-probe')?.remove()); + const stored1 = await A.page.evaluate(() => new Promise((r) => window.__tp.test.v1.snapping.snapTargets.subscribe((v) => r(JSON.stringify(v)))())); + h.check(stored0 === stored1, 'the stored snap targets never changed'); + const listed = await A.page.evaluate(() => window.__tp.test.v1.shortcuts?.shortcuts?.some?.((s) => s.id === 'scene.cornerSnap')); + if (listed !== undefined) h.check(listed === true, 'Settings > Shortcuts lists "B (hold)"'); + + await h.finish(browser); +}); diff --git a/tests/e2e/tidy-layers.test.cjs b/tests/e2e/tidy-layers.test.cjs new file mode 100644 index 000000000..75bf05994 --- /dev/null +++ b/tests/e2e/tidy-layers.test.cjs @@ -0,0 +1,224 @@ +// 102b-arrange row 2 — TIDY BIG SCENES on two connected peers: +// 1. layers: a layer made on A reaches B (the scenePhysics singleton); putting two boxes on it is +// ONE wire envelope and ONE undo on both peers; +// 2. hide is THIS screen's: A's boxes hide, B's stay; a serializer's park shows them (saves keep +// them visible); Play shows them; +// 3. lock: a real viewport click on a locked box selects nothing of it; unlocked it selects; +// 4. select similar (the real Tidy button): the two boxes, not the sphere; +// 5. rename many (the real field + button): "Wall-1", "Wall-2" on both peers, ONE undo (a hyphen: +// a joiner's full sync is glTF, whose loader turns a space into '_' — pre-existing, see summary); +// 6. randomise: the same poses on both peers, ONE undo; +// 7. a scene saved with layers (kept for the older-release check); B reloads + rejoins: the table, +// the objects' layers and names come back; a scene with no layers saves no `layers` key. +// Counterfactual on v1.71.0: no layer table, no #tidy-section. +// Run: APP_URL=https://localhost:7090/ npm run e2e -- tidy-layers +const h = require('./helpers.cjs'); + +async function spyWire(page) { + await page.evaluate(() => { + let peer; + window.__tp.test.v1.peers.subscribe((x) => (peer = x))(); + window.__wire = []; + for (const conn of Object.values(peer.connections)) { + if (conn.__spied) continue; + const send = conn.send.bind(conn); + conn.send = (m) => { + window.__wire.push(m?.type === 'batch' ? { type: 'batch', items: m.items.map((i) => i.type) } : { type: m?.type, parameter: m?.parameter }); + return send(m); + }; + conn.__spied = true; + } + }); +} +const wire = (page) => page.evaluate(() => (window.__wire = window.__wire ?? []).splice(0)); +const SCENE_TYPES = new Set(['objectParameters', 'name', 'move', 'batch', 'scenephysics']); + +const obj = (peer, uuid, fn) => + peer.page.evaluate( + ({ id, src }) => { + let g; + window.__tp.test.v1.objectsGroup.subscribe((v) => (g = v))(); + const o = g.getObjectByProperty('uuid', id); + return o ? new Function('o', 'return (' + src + ')(o)')(o) : null; + }, + { id: uuid, src: fn.toString() } + ); +const layerOf = (peer, uuid) => obj(peer, uuid, (o) => o.userData.layer ?? null); +const visibleOf = (peer, uuid) => obj(peer, uuid, (o) => o.visible); +const nameOf = (peer, uuid) => obj(peer, uuid, (o) => o.name); +const poseOf = (peer, uuid) => obj(peer, uuid, (o) => [...o.position.toArray(), ...o.rotation.toArray().slice(0, 3), ...o.scale.toArray()].map((n) => Math.round(n * 1e4) / 1e4)); +const table = (peer) => peer.page.evaluate(() => new Promise((r) => window.__tp.test.v1.scenePhysics.scenePhysicsState_.subscribe((s) => r(s.layers ?? null))())); +const selection = (peer) => peer.page.evaluate(() => new Promise((r) => window.__tp.test.v1.selectedObjects.subscribe((s) => r([...(s ?? [])]))())); +const undo = (peer) => peer.page.evaluate(() => window.__tp.test.v1.history.undo()); +const redo = (peer) => peer.page.evaluate(() => window.__tp.test.v1.history.redo()); +const tidy = (peer, fn, ...args) => peer.page.evaluate(({ src, args }) => new Function('t', 'args', 'return (' + src + ')(t, ...args)')(window.__tp.test.v1.tidyActions, args), { src: fn.toString(), args }); + +h.run(async () => { + const browser = await h.launch({ args: h.GPU_ARGS }); + const A = await h.setupPage(browser, 'A', { context: { viewport: { width: 1440, height: 900 } } }); + const B = await h.setupPage(browser, 'B'); + for (const p of [A, B]) await p.page.waitForFunction(() => !!window.__tp?.test.v1?.tidyActions, null, { timeout: 60000 }); + await h.connect(B, A); + + const bare = await A.page.evaluate(() => window.__tp.test.v1.scenePhysics.scenePhysicsSnapshot()?.layers ?? null); + h.check(bare === null, 'feature unused: a scene with no layers saves no layers key'); + + const [b1, b2, sp] = await A.page.evaluate(async () => { + const w = window.__tp.test.v1; + const out = []; + for (const cmd of ['/create Box 1 1 1', '/create Box 1 1 1', '/create Sphere']) { + w.commandsHandler.sceneCommand(cmd); + await new Promise((r) => setTimeout(r, 450)); + let g; + w.objectsGroup.subscribe((v) => (g = v))(); + out.push(g.children[g.children.length - 1].uuid); + } + let g; + w.objectsGroup.subscribe((v) => (g = v))(); + let p; + w.peers.subscribe((v) => (p = v))(); + [[-2, 0.5, 0], [0, 0.5, 0], [2, 0.5, 0]].forEach((pos, i) => { + const o = g.getObjectByProperty('uuid', out[i]); + o.position.set(...pos); + o.updateMatrixWorld(true); + p.send({ type: 'move', uuid: o.uuid, pos, rot: [0, 0, 0], scale: [1, 1, 1] }); + }); + return out; + }); + await A.page.waitForTimeout(1500); + await h.eventually(() => nameOf(B, sp), (n) => !!n, 'premise: B has the three objects', 10000); + + console.log('\n=== 1. a layer; two boxes on it: one envelope, one undo ==='); + const id = await tidy(A, (t) => t.addLayer('Walls')); + await h.eventually(() => table(B), (t) => Array.isArray(t) && t.some((l) => l.id === id && l.name === 'Walls'), 'B: the layer "Walls" arrived', 10000); + await spyWire(A.page); + await wire(A.page); + await tidy(A, (t, ids, id) => t.setObjectsLayer(ids, id), [b1, b2], id); + await A.page.waitForTimeout(500); + const sent = (await wire(A.page)).filter((m) => SCENE_TYPES.has(m.type)); + h.check(sent.length === 1 && sent[0].type === 'batch', 'two objects onto a layer = ONE envelope | ' + JSON.stringify(sent)); + for (const u of [b1, b2]) await h.eventually(() => layerOf(B, u), (l) => l === id, 'B: the box is on Walls', 10000); + h.check((await layerOf(A, sp)) === null, 'the sphere is on no layer'); + await undo(A); + for (const u of [b1, b2]) await h.eventually(() => layerOf(B, u), (l) => l === null, 'ONE undo: B has the box back on no layer', 10000); + await redo(A); + for (const u of [b1, b2]) await h.eventually(() => layerOf(B, u), (l) => l === id, 'redo: back on Walls on B', 10000); + + console.log('\n=== 2. hide is this screen only; saves and Play see everything ==='); + await tidy(A, (t, id) => t.setLayerHidden(id, true), id); + await A.page.waitForTimeout(400); + h.check((await visibleOf(A, b1)) === false && (await visibleOf(A, b2)) === false, 'A: the two boxes are hidden'); + h.check((await visibleOf(A, sp)) === true, 'A: the sphere stays'); + await B.page.waitForTimeout(600); + h.check((await visibleOf(B, b1)) === true && (await visibleOf(B, b2)) === true, 'B: nothing hidden (hide is local)'); + const parked = await A.page.evaluate((ids) => { + const w = window.__tp.test.v1; + let g; + w.objectsGroup.subscribe((v) => (g = v))(); + const unpark = w.flowRuntime.parkAnimatedAtBase(); + const during = ids.map((u) => g.getObjectByProperty('uuid', u).visible); + unpark(); + const after = ids.map((u) => g.getObjectByProperty('uuid', u).visible); + return { during, after }; + }, [b1, b2]); + h.check(parked.during.every((v) => v === true) && parked.after.every((v) => v === false), 'a serializer\'s park shows them, then they hide again | ' + JSON.stringify(parked)); + await A.page.evaluate(() => window.__tp.test.v1.isLocked.set(true)); + await A.page.waitForTimeout(300); + h.check((await visibleOf(A, b1)) === true, 'Play shows a hidden layer'); + await A.page.evaluate(() => window.__tp.test.v1.isLocked.set(null)); + await A.page.waitForTimeout(300); + h.check((await visibleOf(A, b1)) === false, 'back in the editor it hides again'); + await tidy(A, (t, id) => t.setLayerHidden(id, false), id); + await A.page.waitForTimeout(300); + h.check((await visibleOf(A, b1)) === true, 'Show brings them back'); + + console.log('\n=== 3. lock: a viewport click passes through ==='); + await tidy(A, (t, id) => t.updateLayer(id, { locked: true }), id); + await h.eventually(() => table(B), (t) => t?.find((l) => l.id === id)?.locked === true, 'B: the layer is locked too (scene data)', 10000); + const clickOn = async (uuid) => { + await A.page.evaluate(() => window.__tp.test.v1.objectActions.deselectObject()); + await A.page.waitForTimeout(300); + const px = await A.page.evaluate((u) => { + const w = window.__tp.test.v1; + let g, cam; + w.objectsGroup.subscribe((v) => (g = v))(); + w.globalCamera.subscribe((v) => (cam = v))(); + const o = g.getObjectByProperty('uuid', u); + const p = o.getWorldPosition(new w.THREE.Vector3()).project(cam); + let renderer; + w.globalRenderer.subscribe((v) => (renderer = v))(); + const r = renderer.domElement.getBoundingClientRect(); + return [r.left + ((p.x + 1) / 2) * r.width, r.top + ((1 - p.y) / 2) * r.height]; + }, uuid); + await A.page.mouse.click(px[0], px[1]); + await A.page.waitForTimeout(700); + return selection(A); + }; + const lockedSel = await clickOn(b1); + h.check(!lockedSel.includes(b1), 'a click on a box of the locked layer does not select it | ' + JSON.stringify(lockedSel)); + await tidy(A, (t, id) => t.updateLayer(id, { locked: false }), id); + await A.page.waitForTimeout(300); + const openSel = await clickOn(b1); + h.check(openSel.includes(b1), 'unlocked, the same click selects it | ' + JSON.stringify(openSel)); + + console.log('\n=== 4. select similar (the real button) ==='); + await A.page.evaluate((u) => window.__tp.test.v1.objectActions.applySelectionSet([u], true), b1); + await A.page.waitForSelector('#tidy-similar-shape', { timeout: 15000 }).catch(() => {}); + await A.page.locator('#tidy-similar-shape').scrollIntoViewIfNeeded(); + await A.page.locator('#tidy-similar-shape').click(); + await A.page.waitForTimeout(500); + const sim = await selection(A); + h.check(sim.length === 2 && sim.includes(b1) && sim.includes(b2) && !sim.includes(sp), 'Same shape selects the two boxes, not the sphere | ' + JSON.stringify(sim)); + + console.log('\n=== 5. rename many (the real field and button) ==='); + await A.page.evaluate((ids) => window.__tp.test.v1.objectActions.applySelectionSet(ids, true), [b1, b2]); + await A.page.waitForSelector('#tidy-rename-pattern', { timeout: 10000 }).catch(() => {}); + await A.page.locator('#tidy-rename-pattern').fill('Wall-{n}'); + await A.page.waitForTimeout(200); + h.check(/Wall-1, Wall-2/.test((await A.page.locator('#tidy-rename-preview').textContent()) ?? ''), 'the preview reads "Wall-1, Wall-2"'); + const names0 = [await nameOf(A, b1), await nameOf(A, b2)]; + await A.page.locator('#tidy-rename').click(); + await A.page.waitForTimeout(500); + for (const [u, n] of [[b1, 'Wall-1'], [b2, 'Wall-2']]) await h.eventually(() => nameOf(B, u), (v) => v === n, `B: renamed "${n}"`, 10000); + await undo(A); + await h.eventually(async () => [await nameOf(B, b1), await nameOf(B, b2)], (v) => JSON.stringify(v) === JSON.stringify(names0), 'ONE undo puts both names back on B', 10000); + await redo(A); + await h.eventually(() => nameOf(B, b2), (v) => v === 'Wall-2', 'redo: renamed again on B', 10000); + + console.log('\n=== 6. randomise ==='); + const p0 = [await poseOf(A, b1), await poseOf(A, b2)]; + await tidy(A, (t, ids) => t.randomise(ids, { rot: [0, 90, 0], scale: [0.5, 1.5], offset: [0.5, 0, 0.5], seed: 3 }), [b1, b2]); + const pa = [await poseOf(A, b1), await poseOf(A, b2)]; + h.check(JSON.stringify(pa) !== JSON.stringify(p0), 'A: the boxes turned, resized and moved'); + await h.eventually(async () => [await poseOf(B, b1), await poseOf(B, b2)], (pb) => JSON.stringify(pb) === JSON.stringify(pa), 'B: the same poses', 10000); + await undo(A); + await h.eventually(async () => [await poseOf(B, b1), await poseOf(B, b2)], (pb) => JSON.stringify(pb) === JSON.stringify(p0), 'ONE undo restores both on B', 10000); + + console.log('\n=== 7. saved with layers; B reloads and rejoins ==='); + const bytes = await A.page.evaluate(async () => { + const s = window.__tp.test.v1; + const zip = await s.sessions.exportSessionZip(s.sessions.buildSessionPayload('tidy-layers'), { assets: true, packs: false, flow: true }); + return Array.from(zip); + }); + const out = require('path').resolve(__dirname, '../../test-results/102b-arrange'); + require('fs').mkdirSync(out, { recursive: true }); + require('fs').writeFileSync(out + '/lane-saved-layers.tpscene', Buffer.from(bytes)); + h.check(bytes.length > 1000, 'saved test-results/102b-arrange/lane-saved-layers.tpscene | ' + bytes.length); + await h.freshReload(B); + // a joiner's reload REJOINS by itself (no restore question, no dial input): wait for that, and + // only a page that does not rejoin answers the restore and dials (the text-object pattern) + const rejoined = await B.page + .waitForFunction(() => { let p; window.__tp.test.v1.peers.subscribe((v) => (p = v))(); return (p?.openedPeers?.length ?? p?.openedPeers?.size ?? 0) > 0; }, null, { timeout: 30000, polling: 250 }) + .then(() => true) + .catch(() => false); + console.log('B rejoined after its reload by itself:', rejoined); + if (!rejoined) { + await h.answerRestore(B, 'dismiss').catch(() => {}); + await h.connect(B, A); + } + await h.eventually(() => table(B), (t) => Array.isArray(t) && t.some((l) => l.id === id), 'B after reload: the layer table is back', 60000); + await h.eventually(() => layerOf(B, b1), (l) => l === id, 'B after reload: the box is on its layer', 20000); + await h.eventually(() => nameOf(B, b2), (v) => v === 'Wall-2', 'B after reload: the names are back', 20000); + + await h.finish(browser); +}); diff --git a/tests/unit/arrayCore.test.js b/tests/unit/arrayCore.test.js new file mode 100644 index 000000000..cb77d0d3a --- /dev/null +++ b/tests/unit/arrayCore.test.js @@ -0,0 +1,103 @@ +// @ts-nocheck — fixture records as plain literals +import { describe, it, expect } from 'vitest'; +import { normalizeArray, arrayTotal, arrayCopyPoses, arraySummary, measurePolyline, pointAt, ARRAY_MAX } from '../../src/lib/arrayCore.js'; + +// 102b-arrange row 1: the array record and the copy poses. + +const base = { position: [1, 0, 2], quaternion: [0, 0, 0, 1], scale: [1, 1, 1] }; +const near = (a, b, eps = 1e-6) => a.every((v, i) => Math.abs(v - b[i]) < eps); + +describe('normalizeArray', () => { + it('fills defaults and drops junk', () => { + const r = normalizeArray({ mode: 'line', count: 3, evil: 1 }); + expect(r.count).toBe(3); + expect(r.evil).toBeUndefined(); + expect(r.step).toEqual([2, 0, 0]); + }); + it('refuses non-objects and unknown modes', () => { + expect(normalizeArray(null)).toBeNull(); + expect(normalizeArray([])).toBeNull(); + expect(normalizeArray({ mode: 'spiral' })).toBeNull(); + }); + it('clamps the count and shrinks a grid over the cap', () => { + expect(normalizeArray({ count: 99999 }).count).toBe(ARRAY_MAX); + expect(normalizeArray({ count: 1 }).count).toBe(2); + const g = normalizeArray({ mode: 'grid', grid: [50, 50, 50] }); + expect(arrayTotal(g)).toBeLessThanOrEqual(ARRAY_MAX); + expect(g.grid[0]).toBe(50); + }); + it('keeps NaN and Infinity out', () => { + const r = normalizeArray({ step: [NaN, Infinity, 1], radius: -4 }); + expect(r.step).toEqual([2, 0, 1]); + expect(r.radius).toBe(0); + }); +}); + +describe('arrayCopyPoses', () => { + it('line: n-1 copies at i x step from the object', () => { + const p = arrayCopyPoses(normalizeArray({ mode: 'line', count: 4, step: [0, 0, 1.5] }), base); + expect(p.length).toBe(3); + expect(p.map((c) => c.position)).toEqual([ + [1, 0, 3.5], + [1, 0, 5], + [1, 0, 6.5] + ]); + }); + it('grid: x fastest, then y, then z', () => { + const p = arrayCopyPoses(normalizeArray({ mode: 'grid', grid: [2, 1, 2], gridStep: [1, 1, 3] }), base); + expect(p.map((c) => c.position)).toEqual([ + [2, 0, 2], + [1, 0, 5], + [2, 0, 5] + ]); + }); + it('circle: a full ring stays on the radius and faces out', () => { + const rec = normalizeArray({ mode: 'circle', count: 4, radius: 2 }); + const p = arrayCopyPoses(rec, base); + // centre at (-1, 0, 2) + for (const c of p) expect(Math.hypot(c.position[0] + 1, c.position[2] - 2)).toBeCloseTo(2, 6); + expect(near(p[1].position, [-3, 0, 2])).toBe(true); // half way round + // a quarter turn about Y for copy 1 + expect(Math.abs(p[0].quaternion[1])).toBeCloseTo(Math.sin(Math.PI / 4), 6); + }); + it('circle: an arc ends exactly on its last angle', () => { + const p = arrayCopyPoses(normalizeArray({ mode: 'circle', count: 3, radius: 1, arc: 180, faceOut: false }), base); + expect(near(p[1].position, [-1, 0, 2])).toBe(true); + expect(p[1].quaternion).toEqual([0, 0, 0, 1]); + }); + it('path: follows the shape of the polyline from the object, evenly spread', () => { + const path = { points: [[0, 0, 0], [4, 0, 0], [4, 0, 4]], closed: false }; + const p = arrayCopyPoses(normalizeArray({ mode: 'path', count: 3 }), base, path); + expect(p.length).toBe(2); + expect(near(p[0].position, [5, 0, 2])).toBe(true); // 4 m along: the corner + expect(near(p[1].position, [5, 0, 6])).toBe(true); // the end + }); + it('path: spacing past an open end makes no copy; no path = none', () => { + const path = { points: [[0, 0, 0], [3, 0, 0]], closed: false }; + expect(arrayCopyPoses(normalizeArray({ mode: 'path', count: 10, spacing: 1 }), base, path).length).toBe(3); + expect(arrayCopyPoses(normalizeArray({ mode: 'path', count: 10 }), base, null)).toEqual([]); + }); + it('rotation and scale steps grow per copy', () => { + const p = arrayCopyPoses(normalizeArray({ count: 3, rotStep: [0, 90, 0], scaleStep: 0.5 }), base); + expect(p[0].scale).toEqual([1.5, 1.5, 1.5]); + expect(p[1].scale).toEqual([2, 2, 2]); + expect(Math.abs(p[1].quaternion[1])).toBeCloseTo(1, 6); // 180 degrees + }); + it('never shrinks a copy to nothing', () => { + const p = arrayCopyPoses(normalizeArray({ count: 5, scaleStep: -0.9 }), base); + expect(Math.min(...p.map((c) => c.scale[0]))).toBeGreaterThan(0); + }); +}); + +describe('polyline helpers + summary', () => { + it('measures and samples', () => { + const l = measurePolyline([[0, 0, 0], [0, 0, 0], [0, 2, 0]], false); + expect(l.length).toBe(2); + expect(pointAt(l, 1).point).toEqual([0, 1, 0]); + expect(pointAt(l, 1).tangent).toEqual([0, 1, 0]); + }); + it('says what the array is', () => { + expect(arraySummary(normalizeArray({ count: 5 }))).toBe('5 in a line'); + expect(arraySummary(normalizeArray({ mode: 'grid', grid: [2, 3, 1] }))).toBe('2 x 3 x 1 grid (6)'); + }); +}); diff --git a/tests/unit/tidyCore.test.js b/tests/unit/tidyCore.test.js new file mode 100644 index 000000000..a634a708b --- /dev/null +++ b/tests/unit/tidyCore.test.js @@ -0,0 +1,87 @@ +// @ts-nocheck — plain descriptors +import { describe, it, expect } from 'vitest'; +import { similarKey, matchesSimilar, renamePlan, randomisePlan, seeded } from '../../src/lib/tidyCore.js'; +import { normalizeLayers, lockedLayerIds, LAYERS_MAX } from '../../src/lib/layersCore.js'; +import { pickStack } from '../../src/lib/selectThrough.js'; + +// 102b-arrange row 2: select similar, rename many, randomise, the layer table, the lock pass. + +describe('select similar', () => { + const box = { gtype: 'Box', matType: 'MeshStandardMaterial', color: 'ff0000', tags: ['coin', 'gold'], layer: 'L1' }; + it('keys per rule', () => { + expect(similarKey(box, 'shape')).toBe('prim:Box'); + expect(similarKey({ geomType: 'BufferGeometry', verts: 24 }, 'shape')).toBe('geo:BufferGeometry:24'); + expect(similarKey(box, 'material')).toBe('MeshStandardMaterial:ff0000:0'); + expect(similarKey({ materialId: 'm1', matType: 'x' }, 'material')).toBe('id:m1'); + expect(similarKey({ prefab: 'p9' }, 'prefab')).toBe('p9'); + expect(similarKey({}, 'prefab')).toBeNull(); + }); + it('tags match on any shared tag', () => { + expect(matchesSimilar({ tags: ['gold'] }, 'tag', ['coin', 'gold'])).toBe(true); + expect(matchesSimilar({ tags: ['silver'] }, 'tag', ['coin', 'gold'])).toBe(false); + expect(matchesSimilar({}, 'layer', 'L1')).toBe(false); + }); +}); + +describe('renamePlan', () => { + it('counts with padding and keeps the old name on request', () => { + expect(renamePlan(['a', 'b', 'c'], 'Post {n}', 1, 2)).toEqual(['Post 01', 'Post 02', 'Post 03']); + expect(renamePlan(['Box', 'Box'], '{name}-{n}', 5)).toEqual(['Box-5', 'Box-6']); + }); + it('adds a counter when the pattern has none, and never returns empty names', () => { + expect(renamePlan(['a', 'b'], 'Fence')).toEqual(['Fence 1', 'Fence 2']); + expect(renamePlan(['a'], '')).toEqual(['a 1']); + }); +}); + +describe('randomisePlan', () => { + const poses = [0, 1, 2].map((i) => ({ pos: [i, 0, 0], rot: [0, 0, 0], scale: [1, 1, 1] })); + it('is seeded and stays inside the ranges', () => { + const a = randomisePlan(poses, { rot: [0, 90, 0], scale: [0.5, 2], offset: [1, 0, 1], seed: 7 }); + const b = randomisePlan(poses, { rot: [0, 90, 0], scale: [0.5, 2], offset: [1, 0, 1], seed: 7 }); + expect(a).toEqual(b); + for (const [i, p] of a.entries()) { + expect(Math.abs(p.rot[1])).toBeLessThanOrEqual(Math.PI / 2 + 1e-9); + expect(p.rot[0]).toBe(0); + expect(p.scale[0]).toBeGreaterThanOrEqual(0.5); + expect(p.scale[0]).toBeLessThanOrEqual(2); + expect(p.scale[0]).toBe(p.scale[2]); // uniform + expect(Math.abs(p.pos[0] - i)).toBeLessThanOrEqual(1); + expect(p.pos[1]).toBe(0); + } + }); + it('nothing asked = nothing changes; another seed = another result', () => { + expect(randomisePlan(poses, {})).toEqual(poses); + expect(randomisePlan(poses, { rot: [0, 90, 0], seed: 1 })).not.toEqual(randomisePlan(poses, { rot: [0, 90, 0], seed: 2 })); + }); + it('the generator is the duplicateCore one', () => { + const r = seeded(1); + expect(r()).toBeGreaterThanOrEqual(0); + expect(r()).toBeLessThan(1); + }); +}); + +describe('layers', () => { + it('normalizes the table', () => { + const t = normalizeLayers([{ id: 'a', name: ' Walls ', color: '#FF0000', locked: true }, { id: 'a' }, { id: '', name: 'x' }, { id: 'b', color: 'red' }]); + expect(t).toEqual([ + { id: 'a', name: 'Walls', color: '#ff0000', locked: true }, + { id: 'b', name: 'Layer', color: expect.stringMatching(/^#[0-9a-f]{6}$/) } + ]); + expect(normalizeLayers([])).toBeNull(); + expect(normalizeLayers('x')).toBeNull(); + expect(normalizeLayers(Array.from({ length: 99 }, (_, i) => ({ id: 'l' + i }))).length).toBe(LAYERS_MAX); + }); + it('a locked layer leaves the pick stack only when the pass carries it', () => { + const locked = { uuid: 'a', userData: { layer: 'a' } }; + const other = { uuid: 'b', userData: { layer: 'b' } }; + const hits = [{ object: locked, distance: 1 }, { object: other, distance: 2 }]; + const pass = { water: true, transparent: false, triggers: false }; + const top = (o) => o; + expect(pickStack(hits, top, pass).map((e) => e.uuid)).toEqual(['a', 'b']); + const stack = pickStack(hits, top, { ...pass, lockedLayers: lockedLayerIds([{ id: 'a', locked: true }]) }); + expect(stack.map((e) => e.uuid)).toEqual(['b']); + // nothing but the locked object under the click: nothing to select (primaryIndex never falls back to it) + expect(pickStack([hits[0]], top, { ...pass, lockedLayers: new Set(['a']) })).toEqual([]); + }); +});