* fix(core): elect wall slab support from the carrying profile, not face coverage An elevated deck drawn against a house wall covers the wall's outer face line end-to-end (boundary contact counts), so the max-across-polylines election handed the wall origin to the deck: every wall-hosted window/door rode along whenever the deck height changed, and placement local-Y was clamped above the deck top. Elect from the carrying profile instead (per arc segment: highest support per face, min across supported faces), with the pointer cap applied inside the profile so a capped-away deck still falls back to the floor that carries the wall. Also pass curveOffset/ thickness/supportSlabId at the window/door tool query sites so their cursor agrees with the rendered wall frame. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(core): honor live node overrides in spatial-grid support queries Group drags publish translated slab polygons and wall endpoints to useLiveNodeOverrides only; the committed spatial index made floor items and walls re-elect support against the pre-drag slab footprint, so multi-selection moves and room-preset placement jumped vertically until the validating click committed the batch. Support queries now read live-effective slab/wall records and bypass the rendered-polygon cache while a slab or wall on the level has an override; the committed cached path stays the fast path otherwise. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(editor): give the room-preset stamp tool a polygon snap context The host app's room stamp drives placement with tool='room', which has no registry entry, so snapContextOf resolved null: Shift never cycled the snapping mode and the HUD chip stayed hidden during room preset placement. A tool-level context map hands the stamp the no-angle polygon set. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(editor): only synthesize walkthrough fallback floors for ground levels Every slab-less visible level got a >=30x30m opening-free fallback floor box at its elevation, so a walkthrough spawned on an upper level (the no-spawn-node fallback ray picks the highest surface) stood on a phantom plane it could never descend from. Match the baked-GLB viewer policy: only the lowest level of each building (derived baseY === 0) gets the fallback; upper levels rely on their real slabs, whose stair openings are cut into the geometry. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(core): fold useLiveTransforms slab deltas into support queries The slab move tool and the room-preset stamp publish a translation DELTA to useLiveTransforms (no polygon override), so the spatial index still elected support against the slab's committed footprint: furniture riding a room-preset preview (or sitting on a dragged deck) dropped to ground under the visually-moved deck until the validating click. Effective slab records now apply the live delta to polygon/holes/elevation, mapped exactly once at each query's loop entry. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(viewer): reapply floor lift every frame for nodes with live previews FloorElevationSystem only wrote mesh Y for dirty nodes, but the React commit that rebinds a dragged node's base-Y group position can land between frames, after priority-2 systems consumed the dirty mark — the lift then vanished until the next pointer tick re-dirtied the node, blinking the Y of items dragged over elevated slabs. Nodes holding a live override or transform now get the lift reapplied every frame. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(editor): stop the entry camera swap from insta-cancelling walkthrough Entering walkthrough with a persisted orthographic camera swaps it to perspective, which recreates the interaction callbacks and re-ran the pointer-lock effect: its cleanup called exitPointerLock, and the unlock handler read that as "user left walkthrough" — instantly cancelling the fresh entry and arming the browser's ~1.25s re-lock cooldown (hence needing multiple button presses). The effect is now mount-stable (the changing callback rides a ref, deps down to [gl]), and the entry lock request swallows async cooldown rejections like the P-resume path. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(core): don't block build-JSON import over plugin-node children Exports from projects with plugins carry nodes like trees:tree whose ids sit in level.children; the import validator parsed parents against the static children id union, so one tree id hard-failed the level schema and blocked the whole import — while the same data loads fine from the DB (setScene never runs this gate). Parents are now validated against a copy with non-static-schema child ids filtered out; those nodes keep surfacing through the unknown-types warning and the imported payload is unchanged. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(core): treat registered plugin kinds as first-class in import validation Nodes of runtime-registered plugin kinds (trees:tree, trees:grass) were lumped into the unknown-types warning even when the plugin is loaded. The validator now consults the node registry: registered kinds validate against their own registered schema (corrupt plugin nodes still block), count under stats.pluginTypes, and raise no warning — only genuinely unregistered types do, which stays correct for hosts without the plugin. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * style: appease biome (format + forEach block body) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Pascal Editor
A 3D building editor built with React Three Fiber and WebGPU.
https://github.com/user-attachments/assets/8b50e7cf-cebe-4579-9cf3-8786b35f7b6b
Using Published Packages
The viewer runtime and built-in node definitions are separate packages. Install the full built-in
viewer set, then load the built-in plugin once before mounting <Viewer>:
npm install @pascal-app/core @pascal-app/viewer @pascal-app/editor @pascal-app/nodes
import { loadPlugin } from '@pascal-app/core'
import { builtinPlugin } from '@pascal-app/nodes'
await loadPlugin(builtinPlugin)
See the @pascal-app/viewer quick start for a React example.
Repository Architecture
This is a Turborepo monorepo with four main runtime packages:
editor/
├── apps/
│ └── editor/ # Next.js application
├── packages/
│ ├── core/ # Schemas, scene state, and registry contracts
│ ├── viewer/ # 3D rendering runtime and shared systems
│ ├── editor/ # Editing tools and UI components
│ ├── nodes/ # Built-in node definitions, renderers, and systems
│ └── ui/ # Shared UI components
Separation of Concerns
| Package | Responsibility |
|---|---|
| @pascal-app/core | Node schemas, scene state (Zustand), registry contracts, spatial queries, and event bus |
| @pascal-app/viewer | 3D rendering via React Three Fiber, shared render systems, default camera/controls, and post-processing |
| @pascal-app/editor | Editing tools, panels, selection, and direct-manipulation UI |
| @pascal-app/nodes | Built-in registry plugin with node definitions, renderers, geometry, and systems |
| apps/editor | Standalone Next.js host for the editor packages |
The viewer renders the scene with sensible defaults. The editor extends it with interactive tools, selection management, and editing capabilities.
Stores
Each package has its own Zustand store for managing state:
| Store | Package | Responsibility |
|---|---|---|
useScene |
@pascal-app/core |
Scene data: nodes, root IDs, dirty nodes, CRUD operations. Persisted to IndexedDB with undo/redo via Zundo. |
useViewer |
@pascal-app/viewer |
Viewer state: current selection (building/level/zone IDs), level display mode (stacked/exploded/solo), camera mode. |
useEditor |
apps/editor |
Editor state: active tool, structure layer visibility, panel states, editor-specific preferences. |
Access patterns:
// Subscribe to state changes (React component)
const nodes = useScene((state) => state.nodes)
const levelId = useViewer((state) => state.selection.levelId)
const activeTool = useEditor((state) => state.tool)
// Access state outside React (callbacks, systems)
const node = useScene.getState().nodes[id]
useViewer.getState().setSelection({ levelId: 'level_123' })
Core Concepts
Nodes
Nodes are the data primitives that describe the 3D scene. All nodes extend BaseNode:
BaseNode {
id: string // Auto-generated with type prefix (e.g., "wall_abc123")
type: string // Discriminator for type-safe handling
parentId: string | null // Parent node reference
visible: boolean
camera?: Camera // Optional saved camera position
metadata?: JSON // Arbitrary metadata (e.g., { isTransient: true })
}
Node Hierarchy:
Site
└── Building
└── Level
├── Wall → Item (doors, windows)
├── Slab
├── Ceiling → Item (lights)
├── Roof
├── Zone
├── Scan (3D reference)
└── Guide (2D reference)
Nodes are stored in a flat dictionary (Record<id, Node>), not a nested tree. Parent-child relationships are defined via parentId and children arrays.
Scene State (Zustand Store)
The scene is managed by a Zustand store in @pascal-app/core:
useScene.getState() = {
nodes: Record<id, AnyNode>, // All nodes
rootNodeIds: string[], // Top-level nodes (sites)
dirtyNodes: Set<string>, // Nodes pending system updates
createNode(node, parentId),
updateNode(id, updates),
deleteNode(id),
}
Middleware:
- Persist - Saves to IndexedDB (excludes transient nodes)
- Temporal (Zundo) - Undo/redo with 50-step history
Scene Registry
The registry maps node IDs to their Three.js objects for fast lookup:
sceneRegistry = {
nodes: Map<id, Object3D>, // ID → 3D object
byType: {
wall: Set<id>,
item: Set<id>,
zone: Set<id>,
// ...
}
}
Renderers register their refs using the useRegistry hook:
const ref = useRef<Mesh>(null!)
useRegistry(node.id, 'wall', ref)
This allows systems to access 3D objects directly without traversing the scene graph.
Node Renderers
Renderers are React components that create Three.js objects for each node type:
SceneRenderer
└── NodeRenderer (dispatches by type)
├── BuildingRenderer
├── LevelRenderer
├── WallRenderer
├── SlabRenderer
├── ZoneRenderer
├── ItemRenderer
└── ...
Pattern:
- Renderer creates a placeholder mesh/group
- Registers it with
useRegistry - Systems update geometry based on node data
Example (simplified):
const WallRenderer = ({ node }) => {
const ref = useRef<Mesh>(null!)
useRegistry(node.id, 'wall', ref)
return (
<mesh ref={ref}>
<boxGeometry args={[0, 0, 0]} /> {/* Replaced by WallSystem */}
<meshStandardMaterial />
{node.children.map(id => <NodeRenderer key={id} nodeId={id} />)}
</mesh>
)
}
Systems
Systems are React components that run in the render loop (useFrame) to update geometry and transforms. They process dirty nodes marked by the store.
Core Systems (in @pascal-app/core):
| System | Responsibility |
|---|---|
WallSystem |
Generates wall geometry with mitering and CSG cutouts for doors/windows |
SlabSystem |
Generates floor geometry from polygons |
CeilingSystem |
Generates ceiling geometry |
RoofSystem |
Generates roof geometry |
ItemSystem |
Positions items on walls, ceilings, or floors (slab elevation) |
Viewer Systems (in @pascal-app/viewer):
| System | Responsibility |
|---|---|
LevelSystem |
Handles level visibility and vertical positioning (stacked/exploded/solo modes) |
ScanSystem |
Controls 3D scan visibility |
GuideSystem |
Controls guide image visibility |
Processing Pattern:
useFrame(() => {
for (const id of dirtyNodes) {
const obj = sceneRegistry.nodes.get(id)
const node = useScene.getState().nodes[id]
// Update geometry, transforms, etc.
updateGeometry(obj, node)
dirtyNodes.delete(id)
}
})
Dirty Nodes
When a node changes, it's marked as dirty in useScene.getState().dirtyNodes. Systems check this set each frame and only recompute geometry for dirty nodes.
// Automatic: createNode, updateNode, deleteNode mark nodes dirty
useScene.getState().updateNode(wallId, { thickness: 0.2 })
// → wallId added to dirtyNodes
// → WallSystem regenerates geometry next frame
// → wallId removed from dirtyNodes
Manual marking:
useScene.getState().dirtyNodes.add(wallId)
Event Bus
Inter-component communication uses a typed event emitter (mitt):
// Node events
emitter.on('wall:click', (event) => { ... })
emitter.on('item:enter', (event) => { ... })
emitter.on('zone:context-menu', (event) => { ... })
// Grid events (background)
emitter.on('grid:click', (event) => { ... })
// Event payload
NodeEvent {
node: AnyNode
position: [x, y, z]
localPosition: [x, y, z]
normal?: [x, y, z]
stopPropagation: () => void
}
Spatial Grid Manager
Handles collision detection and placement validation:
spatialGridManager.canPlaceOnFloor(levelId, position, dimensions, rotation)
spatialGridManager.canPlaceOnWall(wallId, t, height, dimensions)
spatialGridManager.getSlabElevationAt(levelId, x, z)
Used by item placement tools to validate positions and calculate slab elevations.
Editor Architecture
The editor extends the viewer with:
Tools
Tools are activated via the toolbar and handle user input for specific operations:
- SelectTool - Selection and manipulation
- WallTool - Draw walls
- ZoneTool - Create zones
- ItemTool - Place furniture/fixtures
- SlabTool - Create floor slabs
Selection Manager
The editor uses a custom selection manager with hierarchical navigation:
Site → Building → Level → Zone → Items
Each depth level has its own selection strategy for hover/click behavior.
Editor-Specific Systems
ZoneSystem- Controls zone visibility based on level mode- Custom camera controls with node focusing
Data Flow
User Action (click, drag)
↓
Tool Handler
↓
useScene.createNode() / updateNode()
↓
Node added/updated in store
Node marked dirty
↓
React re-renders NodeRenderer
useRegistry() registers 3D object
↓
System detects dirty node (useFrame)
Updates geometry via sceneRegistry
Clears dirty flag
Building a Plugin
The editor is extensible: a plugin ships node kinds (schema, 3D/2D rendering, placement tools, inspector parametrics) and left-rail panels through the same Plugin manifest the built-ins use — there is no separate internal API.
- Developer guide — Create a plugin: the
Pluginshape, panel contributions, discovery, lifecycle, and what's in/out of v1. - Worked example —
pascalorg/plugin-trees: a standalone plugin with procedural trees, flowers, grass, and a presets panel. Clone it as a starting point.
Technology Stack
- React 19 + Next.js 16
- Three.js (WebGPU renderer)
- React Three Fiber + Drei
- Zustand (state management)
- Zod (schema validation)
- Zundo (undo/redo)
- three-bvh-csg (Boolean geometry operations)
- Turborepo (monorepo management)
- Bun (package manager)
Getting Started
Development
Run the development server from the root directory to enable hot reload for all packages:
# Install dependencies
bun install
# Run development server (builds packages + starts editor with watch mode)
bun dev
# This will:
# 1. Build @pascal-app/core and @pascal-app/viewer
# 2. Start watching both packages for changes
# 3. Start the Next.js editor dev server
# Open http://localhost:3002
Important: Always run bun dev from the root directory to ensure the package watchers are running. This enables hot reload when you edit files in packages/core/src/ or packages/viewer/src/.
Building for Production
# Build all packages
turbo build
# Build specific package
turbo build --filter=@pascal-app/core
Publishing Packages
# Build packages
turbo build --filter=@pascal-app/core --filter=@pascal-app/viewer
# Publish to npm
npm publish --workspace=@pascal-app/core --access public
npm publish --workspace=@pascal-app/viewer --access public
Key Files
| Path | Description |
|---|---|
packages/core/src/schema/ |
Node type definitions (Zod schemas) |
packages/core/src/store/use-scene.ts |
Scene state store |
packages/core/src/hooks/scene-registry/ |
3D object registry |
packages/core/src/systems/ |
Geometry generation systems |
packages/viewer/src/components/renderers/ |
Node renderers |
packages/viewer/src/components/viewer/ |
Main Viewer component |
apps/editor/components/tools/ |
Editor tools |
apps/editor/store/ |
Editor-specific state |