Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
53 commits
Select commit Hold shift + click to select a range
01cd30e
viewer, nodes, core: a committed edit settles without fixed waits
wass08 Dec 4, 2026
998e786
viewer, nodes, editor, core: only a finished edit skips batch coalescing
wass08 Dec 4, 2026
06dcd3a
nodes: the general element's proof fragments as a public builder
wass08 Dec 4, 2026
97533ba
core: scene bounds include the placement rows of repeated elements
wass08 Dec 4, 2026
55c8aa5
nodes: box-like element recipes declare the dimensions they read
wass08 Dec 4, 2026
a7411d4
Element in the app: class-named actions and a sample route
wass08 Dec 4, 2026
6f7294f
core, nodes, editor: the document scales to 50k (row patches, staged …
wass08 Dec 4, 2026
bc76031
core, editor: row patches fail safely, history diffs see deletes, aut…
wass08 Dec 4, 2026
a4fdd41
viewer: render compiler for elements and static items (step 5c slice 3)
wass08 Dec 4, 2026
09a300e
viewer, nodes, core: legacy walls drain at 50k
wass08 Dec 4, 2026
2023a40
core: replay settlers run after a staged load
wass08 Dec 4, 2026
fe2f96e
viewer, nodes, editor: compiled nodes stay visible to every consumer
wass08 Dec 4, 2026
9232940
nodes, viewer: sliced wall treatment keeps invalidations and settles …
wass08 Dec 4, 2026
a94ecdc
core, viewer, nodes, editor: worker builds, progressive load, cell or…
wass08 Dec 4, 2026
a64d756
core, viewer, nodes, editor: workers fall back, rows and loads stay c…
wass08 Dec 4, 2026
ddca50e
core, viewer, nodes: geometry workers evaluate under Next, silent wor…
wass08 Dec 4, 2026
b1fca39
viewer: compiled pages survive a scene observer during publication
wass08 Dec 4, 2026
78bb56f
viewer, nodes: culling, visible shadow fit, element paint (step 5c sl…
wass08 Dec 4, 2026
bfad21d
viewer, nodes: shadows unchanged, culling on the current camera, elem…
wass08 Dec 4, 2026
1ad055f
core, viewer, nodes: worker loads publish in batches, workers stay fe…
wass08 Dec 4, 2026
92f78ea
core, viewer, nodes: houses load on the main thread, cheap builds sta…
wass08 Dec 4, 2026
5a13184
core, viewer, nodes: load batching review fixes
wass08 Dec 4, 2026
85800ee
core, viewer: large loads settle their ceiling clamps once, deferred …
wass08 Dec 5, 2026
b5df2b7
viewer: perf probe exposes a node's world matrix
wass08 Dec 5, 2026
0d6ddc2
viewer: a pick updates storey frames only, so it never materializes e…
wass08 Dec 5, 2026
d650ba4
nodes: a batch wave checks hosted elements through the host index
wass08 Dec 5, 2026
821086d
viewer: BatchedMesh pages of one material share their shader build
wass08 Dec 5, 2026
87f5f8c
viewer: the daylight glass scan reads compiled materials once per com…
wass08 Dec 5, 2026
1f34dc5
viewer: pages of a classic material share their shader build as well
wass08 Dec 5, 2026
b8d395d
viewer: a large load publishes compiled geometry in bounded parts
wass08 Dec 5, 2026
7fedd45
core, viewer: clamp, pick and BVH review fixes
wass08 Dec 5, 2026
9b00593
viewer: compiled-geometry nodes mount no React renderer before public…
wass08 Dec 5, 2026
e665181
viewer: a tint or paint preview on a compiled slot keeps cached shado…
wass08 Dec 5, 2026
7259591
viewer: batched pages reuse each camera's draw list while nothing cha…
wass08 Dec 5, 2026
f90ca40
viewer: a paint that keeps a part's shadow keeps the cached shadow maps
wass08 Dec 5, 2026
856e9c6
viewer: sound preloads wait for the page's first gesture
wass08 Dec 5, 2026
7a5e9b8
viewer: the publication shadow check stops at the first added part
wass08 Dec 5, 2026
07c4ac5
viewer, editor: shared builds keyed by material, atomic edits, captur…
wass08 Dec 5, 2026
c9d7242
viewer, editor: shadow cache only for provably neutral swaps, draw-li…
wass08 Dec 5, 2026
e0a5b9b
viewer: a committed edit's walls rebuild within a settle-frame budget
wass08 Dec 5, 2026
547475f
viewer: a daylight rebuild at rest takes 20 ms slices
wass08 Dec 5, 2026
187249b
viewer: revert the settle-budget changes for walls and daylight
wass08 Dec 5, 2026
c5391e0
viewer: a pointer over a compiled element no longer materializes it
wass08 Dec 5, 2026
a7bfd12
viewer: framing a scene measures compiled elements without materializ…
wass08 Dec 5, 2026
1f3e920
viewer: the perf probe projects compiled elements without materializi…
wass08 Dec 5, 2026
89beb21
core: a room that only re-lists its walls dirties the walls joining o…
wass08 Dec 5, 2026
f3fbbd7
nodes: a node deferred for its tint waits for the tint to change, not…
wass08 Dec 5, 2026
484cda8
viewer: real pick hits refresh only their proxy, bounds use current s…
wass08 Dec 5, 2026
923d2d6
nodes, viewer, editor: batcher deferrals wait on events, deselect nev…
wass08 Dec 5, 2026
285a733
viewer, editor: time budgets scale with host speed on CI runners
wass08 Dec 5, 2026
6af1149
viewer, editor: test timeouts and budgets hold under contended CI run…
wass08 Dec 5, 2026
ed90b27
viewer: the worker backpressure test waits on pool readiness, not a t…
wass08 Dec 5, 2026
ec70c4a
core, nodes: every step-5 time budget scales with host speed
wass08 Dec 5, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions apps/editor/app/samples/[id]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { notFound } from 'next/navigation'
import { SampleClient } from './sample-client'

export const dynamic = 'force-dynamic'

const SAMPLE_IDS = new Set(['rack-hall', 'colosseum-arc'])

/**
* `/samples/<id>`, development only: saves one of the general element's proof fragments
* (`rack-hall`, `colosseum-arc`) as a new project and opens it, so the element can be
* checked in the app with the same scene the benches measure.
*/
export default async function SamplePage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
if (process.env.NODE_ENV === 'production' || !SAMPLE_IDS.has(id)) notFound()
return <SampleClient id={id as 'rack-hall' | 'colosseum-arc'} />
}
66 changes: 66 additions & 0 deletions apps/editor/app/samples/[id]/sample-client.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
'use client'

import { usePascalI18n } from '@pascal-app/core'
import type { ElementFragmentId } from '@pascal-app/nodes/element-fragments'
import { useRouter } from 'next/navigation'
import { useEffect, useRef, useState } from 'react'
import { AppCard } from '@/components/app-shell'

/** Builds the fragment in the browser and creates the project through the regular scene route. */
export function SampleClient({ id }: { id: ElementFragmentId }) {
const i18n = usePascalI18n()
const router = useRouter()
const [failed, setFailed] = useState<number | 'build' | null>(null)
// Development strict mode runs effects twice; one visit creates one project.
const started = useRef(false)

useEffect(() => {
if (started.current) return
started.current = true
;(async () => {
let body: string
try {
const { ELEMENT_FRAGMENTS } = await import('@pascal-app/nodes/element-fragments')
const sample = ELEMENT_FRAGMENTS[id]
const snapshot = sample.build().doc.snapshot()
body = JSON.stringify({
name: sample.name,
graph: { nodes: snapshot.nodes, rootNodeIds: snapshot.rootNodeIds },
})
} catch {
setFailed('build')
return
}
const response = await fetch('/api/scenes', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
})
if (!response.ok) {
setFailed(response.status)
return
}
const meta = (await response.json()) as { id: string }
router.replace(`/project/${meta.id}`)
})()
}, [id, router])

return (
<AppCard>
<p className="mt-6 text-muted-foreground text-sm">
{failed === null
? i18n._({ id: 'app.samples.creating', message: 'Creating the sample project…' })
: failed === 'build'
? i18n._({
id: 'app.samples.buildFailed',
message: 'The sample scene could not be built.',
})
: i18n._({
id: 'app.samples.createFailed',
message: 'Creating the sample project failed ({status}).',
values: { status: failed },
})}
</p>
</AppCard>
)
}
15 changes: 10 additions & 5 deletions apps/editor/components/scene-loader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -245,8 +245,11 @@ function SceneEditor({ initialScene, meta: initialMeta }: SceneLoaderProps) {
)

const handleSave = useCallback(
async (graph: SceneGraph, options?: { keepalive?: boolean }) => {
const graphJson = sceneGraphSignature(graph)
async (
scene: import('@pascal-app/core/document').SerializedScene,
options?: { keepalive?: boolean },
) => {
const graphJson = scene.json
const isRecentRemoteApply = Date.now() < suppressRemoteSaveUntilRef.current
if (lastRemoteGraphJsonRef.current === graphJson) {
lastRemoteGraphJsonRef.current = null
Expand All @@ -258,7 +261,7 @@ function SceneEditor({ initialScene, meta: initialMeta }: SceneLoaderProps) {
// Wipe guard: never PUT an empty graph over a populated server copy.
// An empty serialization here means the editor store was not hydrated
// (load in flight or failed), not that the user deleted everything.
const outgoingNodeCount = countGraphNodes(graph)
const outgoingNodeCount = scene.nodeCount
if (isEmptyGraphOverwrite(outgoingNodeCount, serverNodeCountRef.current)) {
console.error(
`[scene-loader] Blocked autosave: refusing to overwrite scene ${meta.id} ` +
Expand All @@ -276,7 +279,9 @@ function SceneEditor({ initialScene, meta: initialMeta }: SceneLoaderProps) {
'Content-Type': 'application/json',
'If-Match': String(versionRef.current),
},
body: JSON.stringify({ name: meta.name, graph }),
body: new Blob(['{"name":', JSON.stringify(meta.name), ',"graph":', graphJson, '}'], {
type: 'application/json',
}),
// `keepalive` lets the request outlive a page unload (the autosave
// flush on refresh/close). Browsers cap keepalive bodies at 64KB, so
// only the unload flush opts in — normal debounced saves omit it and
Expand Down Expand Up @@ -416,7 +421,7 @@ function SceneEditor({ initialScene, meta: initialMeta }: SceneLoaderProps) {
layoutVersion="v2"
navbarSlot={<EditorNavbar name={meta.name} onRename={handleRename} sceneId={meta.id} />}
onLoad={handleLoad}
onSave={handleSave}
onSaveSerialized={handleSave}
onThumbnailCapture={handleThumb}
projectId={meta.projectId ?? 'default'}
projectName={meta.name}
Expand Down
5 changes: 5 additions & 0 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,11 @@
"import": "./dist/document/index.js",
"default": "./dist/document/index.js"
},
"./worker-scope": {
"types": "./dist/document/worker-scope.d.ts",
"import": "./dist/document/worker-scope.js",
"default": "./dist/document/worker-scope.js"
},
"./runtime": {
"types": "./dist/runtime/index.d.ts",
"import": "./dist/runtime/index.js",
Expand Down
60 changes: 60 additions & 0 deletions packages/core/src/document/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,3 +208,63 @@ counts whole-node-record reads, while `useScene.diagnostics.fullDiffs` counts ar
`setState` calls. Draft history projects touched IDs and keeps carry-owned fields through replay.
`useScene.temporal.getState().createdNodeIdsSince(entry)` inspects entry patches without reading
its lazy snapshot. Serialization remains part of an actual save, load, or explicit snapshot read.

### Large documents and placement rows

Placement table patches use indexed node fields (`placements.rows.12`) plus a final
`placements.rows.length` when the table changes size. Generator and retained overrides
use `placements.generator` and `placements.retainedOverrides`. A row edit carries only
that row in each direction; unchanged rows retain their identity. These fields follow
the same read/write interpreter as `source.images`. Canonical snapshots still contain
ordinary placement arrays. Repetition changes can touch many rows; replay copies their
array once per node update. Indices address a specific revision, not a collaboration
merge across reordered tables.

`loadChunked(snapshot, { budgetMs, yieldTask, onChunk, signal })` stages owned values,
orders and query indexes before publishing one load commit. Its default task budget is
8 ms. Edits or another load during hydration reject the staged result instead of
replacing newer work. Invalid stored fields remain available for repair. Synchronous
`load` uses the same hydration path. Loaded history starts from an immutable baseline;
its persistent tree contains subsequent edits, and baseline query indexes are lazy.
User migration callbacks, arbitrary subscriber work, and non-plain binary values can
still be indivisible work; the final chunk includes publication and subscriber time.

`serializeSceneSnapshot` is a pure JSON encoder. `SceneSaveReplica` accepts an initial
snapshot and revision, then `saveReplicaPatch(commit)` envelopes, including undo/redo.
It rejects revision gaps before mutation and returns revision-tagged checkpoints. A host
can run the replica and encoding in a worker: per-edit transport clones only the patch.
`DocumentWorkerPool` implements the transport: snapshots stream in bounded node/row chunks,
then edits and undo/redo send only patches. Each queued and returned job is revision checked;
termination rejects pending work. Geometry hosts use two workers on smaller machines, up to
four with additional CPU cores, divided between legacy/page work and registered builders.
Workers transfer owned geometry arrays; their caches never lose buffers to a transfer.
Construction, transport and runtime failures reject the affected work so callers can use their
main-thread implementation. A failed pool restarts once from the current snapshot; a second failure
terminates its ports and subscription. Revision gaps request a fresh snapshot before further work.
Each worker must answer `hello` before it receives jobs. A worker whose script never evaluates may
raise no `error`, so silence past `DOCUMENT_WORKER_HANDSHAKE_MS` sends its work to the main thread
without a restart; the progressive load worker uses the same handshake. Worker entries import
`@pascal-app/core/worker-scope` first: Next compiles worker chunks as client code, where
`typeof window` becomes `"object"`, and the alias keeps guarded `window` reads (three) valid.

`SceneSerializer` maintains one save worker. `checkpoint()` returns the canonical snapshot JSON
(including explicit plugin-install state) and the saved node count, with main-thread serialization
as the fallback when the worker fails.
The editor's `onSaveSerialized` callback receives that payload; the original `onSave` callback
continues to accept a graph. Draft projections and synchronous exit flushes retain the existing
save guards. Storage and network acknowledgement remain host responsibilities.

`loadSceneProgressively` parses, migrates and validates in a worker using the synchronous loader's
preparation function. It publishes the requested active level and its dependencies first, then the
complete document through `loadChunked`, retaining one load epoch. The first stage includes all
level records so upper-storey elevations are final. A superseding load aborts this load; a later
stage failure restores the preceding snapshot only while this load still owns the document.
Worker failures use the same preparation and staged publication on the main thread. Hosts must keep editing and
saving locked until the final stage. A signal cancels transport and unfinished hydration.
Registered plugin defaults are applied to bounded chunks by the host; custom executable schemas
are not cloned into the worker.

Run `PASCAL_BLENDER=/nonexistent bun run src/document/__bench__/scene-document.bench.ts --scale`
from core for 10k/30k/50k load and 10k-row edit/undo, checkpoint serialization, worker
message preparation, and measured hydration chunks. Timings are observations, not hard
real-time guarantees under GC or competing work.
75 changes: 75 additions & 0 deletions packages/core/src/document/__bench__/scale.bench.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { ElementNode } from '../../schema/nodes/element'
import type { SceneSnapshot } from '../../store/history-control'
import { overridePlacement, placeElementSet } from '../element-ops'
import { SceneDocument } from '../scene-document'
import { saveReplicaPatch, serializeSceneSnapshot } from '../serialization'

const measure = <T>(run: () => T): [T, number] => {
const start = performance.now()
return [run(), performance.now() - start]
}
for (const size of [10000, 30000, 50000]) {
const nodes = Array.from({ length: size }, () =>
ElementNode.parse({ bimClass: 'column', containedIn: null }),
)
const snapshot: SceneSnapshot = {
nodes: Object.fromEntries(nodes.map((node) => [node.id, node])),
rootNodeIds: nodes.map((node) => node.id),
collections: {},
materials: {},
installedPlugins: [],
}
const [doc, loadMs] = measure(() => new SceneDocument(snapshot))
const { node } = placeElementSet(doc, {
bimClass: 'column',
generator: {
kind: 'linear',
count: 10000,
axis: [1, 0, 0],
pitch: 1,
align: 'start',
namePattern: '{i}',
},
})
const placementId = node.placements!.rows[5000]!.placementId
const [result, editMs] = measure(() =>
overridePlacement(doc, { nodeId: node.id, placementId }, { name: 'Edited' }),
)
const [, undoMs] = measure(() => doc.history.undo())
const [, serializeMs] = measure(() => serializeSceneSnapshot(doc.snapshot()))
const [, revisionPreparationMs] = measure(() => structuredClone(saveReplicaPatch(result.commit!)))
const chunks: number[] = []
const staged = new SceneDocument()
const chunkStart = performance.now()
await staged.loadChunked(doc.snapshot(), { budgetMs: 4, onChunk: (ms) => chunks.push(ms) })
const chunkedLoadMs = performance.now() - chunkStart
const maxChunkMs = Math.max(...chunks)
const [, loadedRowPoseEditMs] = measure(() =>
overridePlacement(
staged,
{ nodeId: node.id, placementId },
{ poseDelta: [0, 0.25, 0, 0, 0, 0] },
),
)
const [, loadedRowUndoMs] = measure(() => staged.history.undo())
staged.dispose()
console.log(
JSON.stringify({
size,
loadMs,
editMs,
undoMs,
serializeMs,
revisionPreparationMs,
loadedRowPoseEditMs,
loadedRowUndoMs,
chunkedLoadMs,
maxChunkMs,
chunks: chunks.length,
slowChunks: chunks.flatMap((ms, i) => (ms > 15 ? [{ i, ms }] : [])),
patchBytes: JSON.stringify(result.commit!.patch).length,
inverseBytes: JSON.stringify(result.commit!.inverse).length,
}),
)
doc.dispose()
}
2 changes: 2 additions & 0 deletions packages/core/src/document/__bench__/scene-document.bench.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,5 @@ for (const size of [1000, 10000]) {
)
}
}

if (process.argv.includes('--scale')) await import('./scale.bench')
72 changes: 72 additions & 0 deletions packages/core/src/document/element-contract.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -417,3 +417,75 @@ describe('clone and paste', () => {
},
)
})

test('invalid row patches are refused atomically and row conflicts read nested fields', () => {
const { doc, host } = fixture()
const before = doc.snapshot()
const row = (before.nodes[host.id] as ElementNode).placements!.rows[0]!
const saved = useScene.document.snapshot()
const change = (data: Record<string, unknown>) =>
patch({ nodeUpdates: [{ id: host.id, data, removeFields: [] }] })
try {
useScene.document.load(before)
for (const data of [
{ 'placements.rows.': row },
{ 'placements.rows.01': row },
{ 'placements.rows.-1': row },
{ 'placements.rows.2': row },
{ 'placements.rows.0': null },
{ 'placements.rows.0': { placementId: 'invalid' } },
{ 'placements.rows.length': 100 },
{
'placements.rows.1': { ...row, placementId: 'new', slotKey: 'i:1' },
'placements.rows.0': row,
},
]) {
expect(nextSceneOperationState(before, change(data))).toBeNull()
expect(applySceneOperationPatch(change(data))).toBe(false)
expect(useScene.document.snapshot()).toEqual(before)
}
const appended = Object.fromEntries(
Array.from({ length: 11 }, (_, offset) => {
const index = offset + 1
return [
`placements.rows.${index}`,
{ ...row, placementId: `extra_${index}`, slotKey: `i:${index}` },
]
}),
)
expect(
applySceneOperationPatch(change({ ...appended, 'placements.rows.length': 12 }), {
undoable: true,
}),
).toBe(true)
expect((useScene.document.get(host.id) as ElementNode).placements!.rows).toHaveLength(12)
useScene.document.history.undo()
expect(useScene.document.snapshot()).toEqual(before)
const without = structuredClone(before)
delete (without.nodes[host.id] as ElementNode).placements
useScene.document.load(without)
expect(applySceneOperationPatch(change({ 'placements.rows.0': row }))).toBe(false)
const current = structuredClone(before)
;(current.nodes[host.id] as ElementNode).placements!.rows[0]!.name = 'Concurrent'
const result = applyPatchWithDependencies(
current,
change({ 'placements.rows.0': { ...row, name: 'Ours' } }),
[],
before,
)
expect(result).toEqual({
ok: false,
changed: [{ kind: 'node', id: host.id, field: 'placements.rows.0', reason: 'write' }],
})
expect(
applyPatchWithDependencies(
current,
patch({}),
[{ kind: 'node', id: host.id, fields: ['placements.rows.0'] }],
before,
).ok,
).toBe(false)
} finally {
useScene.document.load(saved)
}
})
Loading
Loading