@react-three-dom/core 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,6 +1,6 @@
1
- import { Object3D, Camera, WebGLRenderer, Vector3 } from 'three';
1
+ import { Object3D, Scene, Camera, WebGLRenderer, Intersection, Vector3 } from 'three';
2
2
 
3
- declare const version = "0.1.0";
3
+ declare const version = "0.3.0";
4
4
 
5
5
  /**
6
6
  * Enable or disable debug logging globally.
@@ -44,6 +44,14 @@ interface ObjectMetadata {
44
44
  triangleCount?: number;
45
45
  /** Instance count for InstancedMesh */
46
46
  instanceCount?: number;
47
+ /** Field of view in degrees (PerspectiveCamera only) */
48
+ fov?: number;
49
+ /** Near clipping plane (cameras only) */
50
+ near?: number;
51
+ /** Far clipping plane (cameras only) */
52
+ far?: number;
53
+ /** Zoom level (cameras only) */
54
+ zoom?: number;
47
55
  /** Local position as [x, y, z] */
48
56
  position: [number, number, number];
49
57
  /** Local euler rotation as [x, y, z] in radians */
@@ -57,6 +65,11 @@ interface ObjectMetadata {
57
65
  /** Flag indicating bounds need recomputation */
58
66
  boundsDirty: boolean;
59
67
  }
68
+ /** Options for inspect(). Include geometry buffers only when needed to avoid perf impact. */
69
+ interface InspectOptions {
70
+ /** If true, include vertex positions and triangle indices in geometry. Default: false. */
71
+ includeGeometryData?: boolean;
72
+ }
60
73
  interface GeometryInspection {
61
74
  /** Geometry class type */
62
75
  type: string;
@@ -74,6 +87,10 @@ interface GeometryInspection {
74
87
  center: [number, number, number];
75
88
  radius: number;
76
89
  };
90
+ /** Position attribute data (x,y,z per vertex). Only set when inspect(..., { includeGeometryData: true }). */
91
+ positionData?: number[];
92
+ /** Index buffer (triangle indices). Only set when inspect(..., { includeGeometryData: true }) and geometry is indexed. */
93
+ indexData?: number[];
77
94
  }
78
95
  interface MaterialInspection {
79
96
  /** Material class type */
@@ -164,10 +181,18 @@ interface R3FDOM {
164
181
  getByUuid(uuid: string): ObjectMetadata | null;
165
182
  /** Tier 1: O(1) lookup by name (returns array, names aren't unique) */
166
183
  getByName(name: string): ObjectMetadata[];
184
+ /** Get direct children of an object by testId or uuid */
185
+ getChildren(idOrUuid: string): ObjectMetadata[];
186
+ /** Get parent of an object by testId or uuid (null if root or not found) */
187
+ getParent(idOrUuid: string): ObjectMetadata | null;
167
188
  /** Total number of tracked objects */
168
189
  getCount(): number;
169
190
  /** Get all objects of a given Three.js type (Mesh, Group, Line, Points, etc.) */
170
191
  getByType(type: string): ObjectMetadata[];
192
+ /** Get all objects with a given geometry type (e.g. "BoxGeometry", "BufferGeometry") */
193
+ getByGeometryType(type: string): ObjectMetadata[];
194
+ /** Get all objects with a given material type (e.g. "MeshStandardMaterial") */
195
+ getByMaterialType(type: string): ObjectMetadata[];
171
196
  /** Get objects that have a specific userData key (and optionally matching value) */
172
197
  getByUserData(key: string, value?: unknown): ObjectMetadata[];
173
198
  /** Count objects of a given Three.js type */
@@ -176,8 +201,8 @@ interface R3FDOM {
176
201
  getObjects(ids: string[]): Record<string, ObjectMetadata | null>;
177
202
  /** Full structured JSON snapshot from Tier 1 store */
178
203
  snapshot(): SceneSnapshot;
179
- /** Tier 2: on-demand heavy inspection (reads live Three.js object) */
180
- inspect(idOrUuid: string): ObjectInspection | null;
204
+ /** Tier 2: on-demand heavy inspection (reads live Three.js object). Use includeGeometryData: true to get vertex/index buffers. */
205
+ inspect(idOrUuid: string, options?: InspectOptions): ObjectInspection | null;
181
206
  /** Deterministic click on a 3D object */
182
207
  click(idOrUuid: string): void;
183
208
  /** Deterministic double-click on a 3D object */
@@ -186,6 +211,8 @@ interface R3FDOM {
186
211
  contextMenu(idOrUuid: string): void;
187
212
  /** Deterministic hover on a 3D object */
188
213
  hover(idOrUuid: string): void;
214
+ /** Unhover / pointer-leave — resets hover state by moving pointer off-canvas */
215
+ unhover(): void;
189
216
  /** Deterministic drag on a 3D object (async — dispatches multi-step pointer sequence) */
190
217
  drag(idOrUuid: string, delta: {
191
218
  x: number;
@@ -220,17 +247,115 @@ interface R3FDOM {
220
247
  getSelection(): string[];
221
248
  /** Raw Three.js object access (for advanced debugging) */
222
249
  getObject3D(idOrUuid: string): Object3D | null;
250
+ /**
251
+ * Resolve uuid for display: if the object is the first mesh of a Group (e.g. table top),
252
+ * returns the parent group uuid so the whole group is highlighted; otherwise returns the given uuid.
253
+ */
254
+ getSelectionDisplayTarget(uuid: string): string;
255
+ /**
256
+ * Enable or disable "inspect mode" for the mirror DOM.
257
+ * When true, mirror elements use pointer-events: auto so the DevTools element picker
258
+ * can select 3D objects by clicking on the canvas (e.g. hold Alt while using the picker).
259
+ * When false, pointer-events: none so normal 3D interaction works.
260
+ */
261
+ setInspectMode(on: boolean): void;
262
+ /** Returns true if inspect mode is currently active. */
263
+ getInspectMode(): boolean;
264
+ /**
265
+ * Manually sweep orphaned objects from the store.
266
+ * Removes objects that are no longer in any tracked scene graph.
267
+ * Runs automatically every ~30s, but can be called after large
268
+ * scene changes (e.g. floor unload) for immediate cleanup.
269
+ * Returns the number of orphans removed.
270
+ */
271
+ sweepOrphans(): number;
272
+ /**
273
+ * Rich diagnostics for test runners and debugging.
274
+ * Returns bridge health, scene stats, and WebGL context info.
275
+ */
276
+ getDiagnostics(): BridgeDiagnostics;
277
+ /**
278
+ * Fuzzy search: find objects whose testId or name contains the query string.
279
+ * Returns up to `limit` matches. Used by test runners to suggest corrections
280
+ * when an object is not found.
281
+ */
282
+ fuzzyFind(query: string, limit?: number): ObjectMetadata[];
283
+ /** Get current camera state (position, rotation, fov, near, far, zoom, type) */
284
+ getCameraState(): CameraState;
285
+ /** Canvas identifier for multi-canvas apps. Undefined for the default/primary canvas. */
286
+ canvasId?: string;
223
287
  /** Library version */
224
288
  version: string;
225
289
  }
290
+ interface CameraState {
291
+ type: 'PerspectiveCamera' | 'OrthographicCamera' | string;
292
+ position: [number, number, number];
293
+ rotation: [number, number, number];
294
+ /** World-space target the camera is looking at (derived from camera direction) */
295
+ target: [number, number, number];
296
+ /** Field of view in degrees (PerspectiveCamera only) */
297
+ fov?: number;
298
+ /** Near clipping plane */
299
+ near: number;
300
+ /** Far clipping plane */
301
+ far: number;
302
+ /** Zoom level */
303
+ zoom: number;
304
+ /** Aspect ratio (PerspectiveCamera only) */
305
+ aspect?: number;
306
+ /** Left/right/top/bottom (OrthographicCamera only) */
307
+ left?: number;
308
+ right?: number;
309
+ top?: number;
310
+ bottom?: number;
311
+ }
312
+ interface BridgeDiagnostics {
313
+ version: string;
314
+ ready: boolean;
315
+ error?: string;
316
+ objectCount: number;
317
+ meshCount: number;
318
+ groupCount: number;
319
+ lightCount: number;
320
+ cameraCount: number;
321
+ materializedDomNodes: number;
322
+ maxDomNodes: number;
323
+ canvasWidth: number;
324
+ canvasHeight: number;
325
+ webglRenderer: string;
326
+ dirtyQueueSize: number;
327
+ }
226
328
  declare global {
227
329
  interface Window {
330
+ /** Default / primary bridge instance (last mounted, or explicitly marked primary). */
228
331
  __R3F_DOM__?: R3FDOM;
332
+ /** Registry of all active bridge instances keyed by canvasId. */
333
+ __R3F_DOM_INSTANCES__?: Record<string, R3FDOM>;
229
334
  /** Set to true to enable debug logging from @react-three-dom/core */
230
335
  __R3F_DOM_DEBUG__?: boolean;
336
+ /** @internal Mirror element currently hovered by DevTools inspector. */
337
+ __r3fdom_hovered__?: HTMLElement | null;
338
+ /** @internal Mirror element currently selected via DevTools / inspect mode. */
339
+ __r3fdom_selected_element__?: HTMLElement | null;
231
340
  }
232
341
  }
233
342
 
343
+ /**
344
+ * @module ObjectStore
345
+ *
346
+ * Central registry for all tracked Three.js objects in a react-three-dom session.
347
+ * Provides two-tier data access: Tier 1 (lightweight metadata cached per-frame)
348
+ * and Tier 2 (on-demand deep inspection of geometry, materials, and bounds).
349
+ * Designed for BIM-scale scenes (100k+ objects) with O(1) lookups by uuid,
350
+ * testId, and name, plus amortized flat-list iteration and async registration.
351
+ */
352
+
353
+ /**
354
+ * Source of truth for all tracked Three.js objects.
355
+ * Maintains O(1) indexes by uuid, testId, and name, a dirty queue for
356
+ * priority per-frame sync, and an event system for add/remove/update
357
+ * notifications consumed by DomMirror and the devtools panel.
358
+ */
234
359
  declare class ObjectStore {
235
360
  private _metaByObject;
236
361
  private _objectByUuid;
@@ -244,17 +369,32 @@ declare class ObjectStore {
244
369
  /**
245
370
  * Register a single object into the store.
246
371
  * Populates Tier 1 metadata and all indexes.
372
+ * Tags the object with `__r3fdom_tracked = true` for O(1) scene membership checks.
247
373
  */
248
374
  register(obj: Object3D): ObjectMetadata;
249
375
  /**
250
- * Register an entire subtree (object + all descendants).
251
- * Individual objects that fail to register are skipped (logged when debug
252
- * is enabled) so that one bad object doesn't prevent the rest from being
253
- * tracked.
376
+ * Register an entire subtree (object + all descendants) synchronously.
377
+ * Prefer `registerTreeAsync` for large scenes (100k+) to avoid blocking.
254
378
  */
255
379
  registerTree(root: Object3D): void;
380
+ private _asyncRegQueue;
381
+ private _asyncRegHandle;
382
+ private _asyncRegBatchSize;
383
+ /**
384
+ * Register an entire subtree asynchronously using requestIdleCallback.
385
+ * Processes ~1000 objects per idle slice to avoid blocking the main thread.
386
+ *
387
+ * IMPORTANT: install patchObject3D BEFORE calling this so that objects
388
+ * added to the scene during async registration are caught by the patch.
389
+ *
390
+ * Returns a cancel function. Also cancelled automatically by dispose().
391
+ */
392
+ registerTreeAsync(root: Object3D): () => void;
393
+ private _scheduleRegChunk;
394
+ private _cancelAsyncRegistration;
256
395
  /**
257
396
  * Unregister a single object from the store.
397
+ * Clears the `__r3fdom_tracked` flag.
258
398
  */
259
399
  unregister(obj: Object3D): void;
260
400
  /**
@@ -262,24 +402,30 @@ declare class ObjectStore {
262
402
  */
263
403
  unregisterTree(root: Object3D): void;
264
404
  /**
265
- * Refresh Tier 1 metadata from the live Three.js object.
405
+ * Refresh dynamic Tier 1 fields from the live Three.js object.
406
+ * Only reads transform, visibility, children count, and parent —
407
+ * skips static fields (geometry, material) that don't change per-frame.
408
+ * Mutates metadata in-place to avoid allocation.
266
409
  * Returns true if any values changed.
267
- * Returns false (no change) if extracting metadata throws so that the
268
- * previous metadata is preserved.
269
410
  */
270
411
  update(obj: Object3D): boolean;
271
412
  /**
272
413
  * Compute full inspection data from a live Three.js object.
273
414
  * This reads geometry buffers, material properties, world bounds, etc.
274
415
  * Cost: 0.1–2ms depending on geometry complexity.
416
+ * Pass { includeGeometryData: true } to include vertex positions and triangle indices (higher cost for large meshes).
275
417
  */
276
- inspect(idOrUuid: string): ObjectInspection | null;
418
+ inspect(idOrUuid: string, options?: InspectOptions): ObjectInspection | null;
277
419
  /** Get metadata by testId. O(1). */
278
420
  getByTestId(testId: string): ObjectMetadata | null;
279
421
  /** Get metadata by uuid. O(1). */
280
422
  getByUuid(uuid: string): ObjectMetadata | null;
281
423
  /** Get metadata by name (returns array since names aren't unique). O(1). */
282
424
  getByName(name: string): ObjectMetadata[];
425
+ /** Get direct children of an object by testId or uuid. Returns empty array if not found. */
426
+ getChildren(idOrUuid: string): ObjectMetadata[];
427
+ /** Get parent of an object by testId or uuid. Returns null if not found or if root. */
428
+ getParent(idOrUuid: string): ObjectMetadata | null;
283
429
  /**
284
430
  * Batch lookup: get metadata for multiple objects by testId or uuid.
285
431
  * Returns a Map from the requested id to its metadata (or null if not found).
@@ -293,6 +439,16 @@ declare class ObjectStore {
293
439
  * Linear scan — O(n) where n is total tracked objects.
294
440
  */
295
441
  getByType(type: string): ObjectMetadata[];
442
+ /**
443
+ * Get all objects with a given geometry type (e.g. "BoxGeometry", "BufferGeometry").
444
+ * Linear scan — O(n). Only meshes/points/lines have geometryType.
445
+ */
446
+ getByGeometryType(type: string): ObjectMetadata[];
447
+ /**
448
+ * Get all objects with a given material type (e.g. "MeshStandardMaterial").
449
+ * Linear scan — O(n). Only meshes/points/lines have materialType.
450
+ */
451
+ getByMaterialType(type: string): ObjectMetadata[];
296
452
  /**
297
453
  * Get all objects that have a specific userData key.
298
454
  * If `value` is provided, only returns objects where `userData[key]` matches.
@@ -317,9 +473,10 @@ declare class ObjectStore {
317
473
  /** Check if a root scene is tracked. */
318
474
  isTrackedRoot(obj: Object3D): boolean;
319
475
  /**
320
- * Walk up from `obj` to see if any ancestor is a tracked root.
321
- * Used by Object3D.add/remove patch to determine if an object
322
- * belongs to a monitored scene.
476
+ * Check if an object belongs to a tracked scene.
477
+ * Fast path: checks the `__r3fdom_tracked` flag set during register (O(1)).
478
+ * Fallback: walks up the parent chain to find a tracked root.
479
+ * The fallback is needed for newly added objects that aren't registered yet.
323
480
  */
324
481
  isInTrackedScene(obj: Object3D): boolean;
325
482
  /**
@@ -339,10 +496,32 @@ declare class ObjectStore {
339
496
  /** Subscribe to store events (add, remove, update). */
340
497
  subscribe(listener: StoreListener): () => void;
341
498
  private _emit;
499
+ /**
500
+ * Sweep objects in `_objectByUuid` that are no longer in any tracked scene.
501
+ * This catches objects that were removed from the scene graph without
502
+ * triggering the patched Object3D.remove (e.g. direct `.children` splice,
503
+ * or the remove hook failing silently).
504
+ *
505
+ * At BIM scale, call this periodically (e.g. every 30s or after a floor
506
+ * load/unload) to prevent memory leaks from retained Object3D references.
507
+ *
508
+ * Returns the number of orphans cleaned up.
509
+ */
510
+ sweepOrphans(): number;
342
511
  /** Remove all tracked objects and reset state. */
343
512
  dispose(): void;
344
513
  }
345
514
 
515
+ /**
516
+ * @module DomMirror
517
+ *
518
+ * Maintains a parallel DOM tree that mirrors the Three.js scene graph using
519
+ * custom elements (<three-mesh>, <three-group>, etc.). This enables standard
520
+ * DOM tooling — CSS selectors, DevTools Elements panel, Accessibility tree —
521
+ * to work with 3D objects. Only a subset of objects are materialized as DOM
522
+ * nodes at any time (capped via LRU eviction) to stay performant at BIM scale.
523
+ */
524
+
346
525
  /**
347
526
  * Manages the parallel DOM tree that mirrors the Three.js scene graph.
348
527
  *
@@ -361,12 +540,30 @@ declare class DomMirror {
361
540
  private _lruSize;
362
541
  private _maxNodes;
363
542
  private _parentMap;
543
+ /** When true, mirror elements use pointer-events: auto so DevTools element picker can select them. */
544
+ private _inspectMode;
545
+ /** Async materialization state for inspect mode */
546
+ private _asyncQueue;
547
+ private _asyncIdleHandle;
548
+ private _asyncBatchSize;
364
549
  constructor(store: ObjectStore, maxNodes?: number);
365
550
  /**
366
551
  * Set the root DOM element where the mirror tree will be appended.
367
552
  * Typically a hidden div: <div id="three-dom-root" style="display:none">
368
553
  */
369
554
  setRoot(rootElement: HTMLElement): void;
555
+ /**
556
+ * Enable or disable "inspect mode". When turning on, kicks off async
557
+ * chunked materialization so the full tree becomes browsable in the
558
+ * Elements tab without blocking the main thread.
559
+ *
560
+ * At BIM scale (100k-200k objects) the old synchronous loop would freeze
561
+ * the page for 2-10s. The new approach uses requestIdleCallback to
562
+ * spread work across idle frames (~200 nodes per idle slice, ~5ms each).
563
+ */
564
+ setInspectMode(on: boolean): void;
565
+ /** Whether inspect mode is currently enabled. */
566
+ getInspectMode(): boolean;
370
567
  /**
371
568
  * Build the initial DOM tree from the scene.
372
569
  * Materializes the top 2 levels of the scene hierarchy.
@@ -385,8 +582,14 @@ declare class DomMirror {
385
582
  /**
386
583
  * Remove a DOM node but keep JS metadata in the ObjectStore.
387
584
  * Called by LRU eviction or when an object is removed from the scene.
585
+ * Also dematerializes any materialized descendants so they don't become
586
+ * orphaned entries in the LRU / _nodes maps.
388
587
  */
389
588
  dematerialize(uuid: string): void;
589
+ /**
590
+ * Collect all materialized descendants of a uuid by walking _parentMap.
591
+ */
592
+ private _collectMaterializedDescendants;
390
593
  /**
391
594
  * Called when a new object is added to the tracked scene.
392
595
  * Only materializes if the parent is already materialized (lazy expansion).
@@ -415,6 +618,14 @@ declare class DomMirror {
415
618
  * Get the materialized DOM element for an object, if it exists.
416
619
  */
417
620
  getElement(uuid: string): HTMLElement | null;
621
+ /**
622
+ * Get or lazily materialize a DOM element for an object.
623
+ * Also materializes the ancestor chain so the element is correctly
624
+ * nested in the DOM tree. Used by InspectController so that
625
+ * hover/click always produces a valid mirror element regardless
626
+ * of whether async materialization has reached it yet.
627
+ */
628
+ getOrMaterialize(uuid: string): HTMLElement | null;
418
629
  /**
419
630
  * Check if an object has a materialized DOM node.
420
631
  */
@@ -446,6 +657,14 @@ declare class DomMirror {
446
657
  * Insert a newly created element into the correct position in the DOM tree.
447
658
  */
448
659
  private _insertIntoDom;
660
+ /**
661
+ * Materialize all ancestors of a uuid from root down, so the target
662
+ * element will be correctly nested when materialized.
663
+ */
664
+ private _materializeAncestorChain;
665
+ private _startAsyncMaterialization;
666
+ private _cancelAsyncMaterialization;
667
+ private _scheduleAsyncChunk;
449
668
  /**
450
669
  * Parse common CSS selector patterns and resolve to a uuid from the store.
451
670
  * Supports:
@@ -469,6 +688,15 @@ declare class DomMirror {
469
688
  private _evictLRU;
470
689
  }
471
690
 
691
+ /**
692
+ * @module CustomElements
693
+ *
694
+ * Defines and registers the custom HTML elements (<three-scene>, <three-mesh>,
695
+ * <three-light>, etc.) used by DomMirror to represent Three.js objects in the
696
+ * DOM. The ThreeElement base class exposes interactive properties (metadata,
697
+ * inspect, object3D) accessible from the DevTools console via `$0.metadata`.
698
+ */
699
+
472
700
  /**
473
701
  * Maps Three.js object types to custom element tag names.
474
702
  * Multiple Three.js types can map to the same tag.
@@ -560,6 +788,14 @@ declare class ThreeElement extends HTMLElement {
560
788
  */
561
789
  declare function ensureCustomElements(store: ObjectStore): void;
562
790
 
791
+ /**
792
+ * @module attributes
793
+ *
794
+ * Serializes ObjectStore Tier 1 metadata into DOM data-attributes and applies
795
+ * them to mirror elements with minimal DOM writes. Only attributes whose values
796
+ * actually changed are written, keeping per-frame cost near zero for static objects.
797
+ */
798
+
563
799
  /** All attribute names we manage (for diffing). */
564
800
  declare const MANAGED_ATTRIBUTES: string[];
565
801
  /**
@@ -579,7 +815,20 @@ declare function computeAttributes(meta: ObjectMetadata): Map<string, string>;
579
815
  */
580
816
  declare function applyAttributes(element: HTMLElement, meta: ObjectMetadata, prevAttrs: Map<string, string>): number;
581
817
 
818
+ /**
819
+ * @module SelectionManager
820
+ *
821
+ * Lightweight selection state manager for 3D objects. Supports single and
822
+ * multi-selection, notifies listeners on change so Highlighter and the
823
+ * devtools inspector panel can react. Decoupled from rendering — purely
824
+ * manages which Object3D references are "selected".
825
+ */
826
+
582
827
  type SelectionListener = (selected: Object3D[]) => void;
828
+ /**
829
+ * Tracks the set of currently selected Object3D instances and notifies
830
+ * subscribers when the selection changes.
831
+ */
583
832
  declare class SelectionManager {
584
833
  /** Currently selected objects (ordered by selection time). */
585
834
  private _selected;
@@ -609,56 +858,198 @@ declare class SelectionManager {
609
858
  dispose(): void;
610
859
  }
611
860
 
861
+ /**
862
+ * @module Highlighter
863
+ *
864
+ * Renders Chrome DevTools-style translucent fill overlays on hovered and
865
+ * selected Three.js objects. Subscribes to SelectionManager for selection
866
+ * state and polls `window.__r3fdom_hovered__` for DevTools element-picker
867
+ * hover. Highlight meshes are marked `__r3fdom_internal` so they're excluded
868
+ * from raycasting and the ObjectStore.
869
+ */
870
+
612
871
  interface HighlighterOptions {
613
- /** Whether to show a tooltip above highlighted objects. Default: true */
614
872
  showTooltip?: boolean;
615
873
  }
874
+ /**
875
+ * Manages hover and selection highlight overlays in the 3D scene.
876
+ * Attaches to a Scene + SelectionManager and creates/disposes translucent
877
+ * mesh clones that track the source object's world transform each frame.
878
+ */
616
879
  declare class Highlighter {
617
- /** Selected object overlays (persistent until deselected) */
618
- private _selectedEntries;
619
- /** Hover overlay (temporary, single object at a time) */
620
- private _hoverEntries;
621
- private _camera;
622
- private _renderer;
880
+ private _scene;
623
881
  private _unsubscribe;
624
- private _showTooltip;
625
- /** DevTools hover polling interval */
882
+ private _hoverEntries;
883
+ private _hoverTarget;
884
+ private _selectedEntries;
626
885
  private _hoverPollId;
627
- private _lastHoveredElement;
628
- /** Store reference for resolving objects */
886
+ private _lastHoveredUuid;
629
887
  private _store;
630
- constructor(options?: HighlighterOptions);
631
- attach(_scene: Object3D, selectionManager: SelectionManager, camera: Camera, renderer: WebGLRenderer, store: {
888
+ constructor(_options?: HighlighterOptions);
889
+ /** Bind to a scene and selection manager, start hover polling. */
890
+ attach(scene: Scene, selectionManager: SelectionManager, _camera: Camera, _renderer: WebGLRenderer, store: {
632
891
  getObject3D(uuid: string): Object3D | null;
633
892
  }): void;
893
+ /** Unbind from the scene, stop polling, and remove all highlights. */
634
894
  detach(): void;
895
+ /** Sync highlight group transforms to their source objects. Call each frame. */
635
896
  update(): void;
636
- highlight(obj: Object3D): void;
637
- unhighlight(obj: Object3D): void;
638
- clearAll(): void;
639
- isHighlighted(obj: Object3D): boolean;
640
- /** Show a temporary hover highlight for an object and its children */
897
+ /** Show a hover highlight on the given object (replaces any previous hover). */
641
898
  showHoverHighlight(obj: Object3D): void;
642
- /** Clear the hover highlight */
899
+ /** Remove the current hover highlight. */
643
900
  clearHoverHighlight(): void;
644
- private _syncSelectedHighlights;
645
- private _addSelectedHighlight;
646
- private _addHoverHighlightRecursive;
901
+ private _clearHoverVisuals;
902
+ /** Check if an object currently has a selection highlight. */
903
+ isHighlighted(obj: Object3D): boolean;
904
+ /** Remove all hover and selection highlights. */
905
+ clearAll(): void;
906
+ private _syncSelectionHighlights;
907
+ private _addSelectionHighlight;
908
+ private _removeSelectionHighlight;
909
+ private _clearAllSelectionHighlights;
647
910
  private _startHoverPolling;
648
911
  private _stopHoverPolling;
649
912
  private _pollDevToolsHover;
650
- private _removeOverlay;
651
- private _clearAllOverlays;
913
+ private _disposeHighlightGroup;
914
+ /** Detach and release all resources. */
915
+ dispose(): void;
916
+ }
917
+
918
+ /**
919
+ * @module RaycastAccelerator
920
+ *
921
+ * Two-layer acceleration structure for BIM-scale raycasting (100k+ objects).
922
+ * Layer 1 maintains a pre-filtered flat list of raycastable meshes from the
923
+ * ObjectStore (avoids recursive scene traversal). Layer 2 uses three-mesh-bvh
924
+ * to build per-geometry BVH trees, turning per-mesh triangle intersection
925
+ * from O(t) brute-force into O(log t). Combined: ~0.01–0.1ms at 200k objects.
926
+ */
927
+
928
+ /**
929
+ * Maintains an accelerated raycast target list and per-geometry BVH trees.
930
+ * Rebuilds lazily when the ObjectStore emits changes, with a per-rebuild
931
+ * BVH budget to avoid blocking the main thread on large model loads.
932
+ */
933
+ declare class RaycastAccelerator {
934
+ private _store;
935
+ private _targets;
936
+ private _dirty;
937
+ private _unsubscribe;
938
+ private _bvhBuiltFor;
939
+ constructor(store: ObjectStore);
940
+ /** Force a target list rebuild on the next raycast. */
941
+ markDirty(): void;
942
+ private _rebuild;
943
+ /**
944
+ * Build a BVH for a mesh's geometry if it doesn't have one yet.
945
+ * Uses indirect mode to avoid modifying the index buffer.
946
+ * Skips disposed geometries and does NOT mark failed builds so they
947
+ * can be retried (e.g. after geometry is re-uploaded).
948
+ */
949
+ private _ensureBVH;
950
+ /**
951
+ * Raycast from mouse position against only raycastable meshes.
952
+ * Returns the closest non-internal hit, or null.
953
+ */
954
+ raycastAtMouse(e: MouseEvent, camera: Camera, canvas: HTMLCanvasElement): Object3D | null;
955
+ /**
956
+ * Raycast from NDC coordinates. Used by raycastVerify.
957
+ */
958
+ raycastAtNdc(ndcX: number, ndcY: number, camera: Camera): Intersection[];
959
+ /** Current number of raycastable targets. */
960
+ get targetCount(): number;
961
+ /** Unsubscribe from the store and release the target list. */
652
962
  dispose(): void;
653
963
  }
654
964
 
965
+ /**
966
+ * @module InspectController
967
+ *
968
+ * Chrome DevTools-style inspect mode for 3D scenes. When enabled, places a
969
+ * transparent overlay on top of the WebGL canvas that intercepts all pointer
970
+ * events (preventing R3F's event system and camera controls from consuming
971
+ * them), raycasts to identify the object under the cursor, drives
972
+ * hover/selection highlights, and sets a global reference so the DevTools
973
+ * extension can reveal the corresponding mirror DOM node.
974
+ * Zero overhead when disabled — no overlay, no listeners.
975
+ */
976
+
977
+ /**
978
+ * Manages the inspect-mode lifecycle: creates/removes an overlay div,
979
+ * throttles raycasts, and coordinates Highlighter + SelectionManager + DomMirror.
980
+ */
981
+ declare class InspectController {
982
+ private _active;
983
+ private _camera;
984
+ private _renderer;
985
+ private _selectionManager;
986
+ private _highlighter;
987
+ private _raycastAccelerator;
988
+ private _mirror;
989
+ private _store;
990
+ private _lastRaycastTime;
991
+ private _hoveredObject;
992
+ private _hoverRevealTimer;
993
+ private _overlay;
994
+ private _boundPointerMove;
995
+ private _boundPointerDown;
996
+ private _boundContextMenu;
997
+ constructor(opts: {
998
+ camera: Camera;
999
+ renderer: WebGLRenderer;
1000
+ selectionManager: SelectionManager;
1001
+ highlighter: Highlighter;
1002
+ raycastAccelerator: RaycastAccelerator;
1003
+ mirror: DomMirror;
1004
+ store: {
1005
+ getObject3D(uuid: string): Object3D | null;
1006
+ };
1007
+ });
1008
+ get active(): boolean;
1009
+ /** Update the camera reference (e.g. after a camera switch). */
1010
+ updateCamera(camera: Camera): void;
1011
+ /** Activate inspect mode — creates overlay on top of canvas. */
1012
+ enable(): void;
1013
+ /** Deactivate inspect mode — removes overlay and clears hover state. */
1014
+ disable(): void;
1015
+ /** Disable and release all resources. */
1016
+ dispose(): void;
1017
+ private _raycastFromEvent;
1018
+ /**
1019
+ * Resolve a raw raycast hit to the logical selection target.
1020
+ * Walks up to find the best Group parent if applicable.
1021
+ */
1022
+ private _resolveTarget;
1023
+ private _onPointerMove;
1024
+ /**
1025
+ * After hovering an object for HOVER_REVEAL_DEBOUNCE_MS, auto-reveal its
1026
+ * mirror element in the Elements tab.
1027
+ */
1028
+ private _scheduleHoverReveal;
1029
+ private _cancelHoverReveal;
1030
+ private _onPointerDown;
1031
+ }
1032
+
655
1033
  interface ThreeDomProps {
1034
+ /**
1035
+ * Unique identifier for this canvas instance. Required when using multiple
1036
+ * canvases. The bridge is registered in `window.__R3F_DOM_INSTANCES__[canvasId]`.
1037
+ * When omitted the bridge is only set on `window.__R3F_DOM__`.
1038
+ */
1039
+ canvasId?: string;
1040
+ /**
1041
+ * Mark this canvas as the primary / default instance.
1042
+ * `window.__R3F_DOM__` always points to the primary bridge.
1043
+ * When only one canvas is used (no canvasId), it is implicitly primary.
1044
+ * Default: true when canvasId is omitted, false otherwise.
1045
+ */
1046
+ primary?: boolean;
656
1047
  /** CSS selector or HTMLElement for the mirror DOM root. Default: "#three-dom-root" */
657
1048
  root?: string | HTMLElement;
658
1049
  /** Objects to process per amortized batch per frame. Default: 500 */
659
1050
  batchSize?: number;
660
1051
  /** Max time budget (ms) for sync work per frame. Default: 0.5 */
661
- timeBudgetMs?: number;
1052
+ syncBudgetMs?: number;
662
1053
  /** Max materialized DOM nodes (LRU eviction). Default: 2000 */
663
1054
  maxDomNodes?: number;
664
1055
  /** Initial DOM tree materialization depth. Default: 3 */
@@ -667,12 +1058,22 @@ interface ThreeDomProps {
667
1058
  enabled?: boolean;
668
1059
  /** Enable debug logging to browser console. Default: false */
669
1060
  debug?: boolean;
1061
+ /** Enable inspect mode on mount. Default: false */
1062
+ inspect?: boolean;
670
1063
  }
671
- declare function getStore(): ObjectStore | null;
672
- declare function getMirror(): DomMirror | null;
673
- declare function getSelectionManager(): SelectionManager | null;
674
- declare function getHighlighter(): Highlighter | null;
675
- declare function ThreeDom({ root, batchSize, timeBudgetMs, maxDomNodes, initialDepth, enabled, debug, }?: ThreeDomProps): null;
1064
+ /** Get the store for a canvas instance. Default: primary ('') instance. */
1065
+ declare function getStore(canvasId?: string): ObjectStore | null;
1066
+ /** Get the mirror for a canvas instance. Default: primary ('') instance. */
1067
+ declare function getMirror(canvasId?: string): DomMirror | null;
1068
+ /** Get the selection manager for a canvas instance. */
1069
+ declare function getSelectionManager(canvasId?: string): SelectionManager | null;
1070
+ /** Get the highlighter for a canvas instance. */
1071
+ declare function getHighlighter(canvasId?: string): Highlighter | null;
1072
+ /** Get the inspect controller for a canvas instance. */
1073
+ declare function getInspectController(canvasId?: string): InspectController | null;
1074
+ /** List all active canvas IDs. */
1075
+ declare function getCanvasIds(): string[];
1076
+ declare function ThreeDom({ canvasId, primary, root, batchSize, syncBudgetMs, maxDomNodes, initialDepth, enabled, debug, inspect: inspectProp, }?: ThreeDomProps): null;
676
1077
 
677
1078
  /**
678
1079
  * Patch Object3D.prototype.add and Object3D.prototype.remove to intercept
@@ -724,6 +1125,16 @@ declare function createFlatSnapshot(store: ObjectStore): {
724
1125
  objects: ObjectMetadata[];
725
1126
  };
726
1127
 
1128
+ /**
1129
+ * @module projection
1130
+ *
1131
+ * Projects Three.js objects from world space to screen-space CSS pixel
1132
+ * coordinates using a multi-strategy approach (bbox center → face centers →
1133
+ * corners → origin fallback). Also provides frustum visibility checks and
1134
+ * screen-to-world conversion for drag deltas. Core utility used by all
1135
+ * interaction modules to determine where to dispatch synthetic events.
1136
+ */
1137
+
727
1138
  /** Screen-space coordinates in CSS pixels relative to the canvas. */
728
1139
  interface ScreenPoint {
729
1140
  /** X coordinate in CSS pixels, left = 0. */
@@ -782,6 +1193,15 @@ declare function screenDeltaToWorld(dx: number, dy: number, obj: Object3D, camer
782
1193
  */
783
1194
  declare function projectAllSamplePoints(obj: Object3D, camera: Camera, size: CanvasSize): ScreenPoint[];
784
1195
 
1196
+ /**
1197
+ * @module raycastVerify
1198
+ *
1199
+ * Post-dispatch raycast verification for interaction modules. After a synthetic
1200
+ * event is dispatched at projected screen coordinates, casts a ray to confirm
1201
+ * the intended object is actually the frontmost hit. Reports occlusion with
1202
+ * the identity of the occluding object for clear error messages.
1203
+ */
1204
+
785
1205
  /** Result of a raycast verification. */
786
1206
  interface RaycastResult {
787
1207
  /** Whether the intended object was hit. */
@@ -933,6 +1353,15 @@ declare function hover3D(idOrUuid: string, options?: Hover3DOptions): Hover3DRes
933
1353
  */
934
1354
  declare function unhover3D(): void;
935
1355
 
1356
+ /**
1357
+ * @module dispatch
1358
+ *
1359
+ * Low-level synthetic PointerEvent/MouseEvent/WheelEvent dispatch on the
1360
+ * canvas element. Produces the exact DOM event sequences that R3F's internal
1361
+ * event system expects (e.g. pointerdown → pointerup → click). All higher-level
1362
+ * interaction modules (click3D, hover3D, drag3D, etc.) delegate here.
1363
+ */
1364
+
936
1365
  /**
937
1366
  * Dispatch a full click sequence on the canvas at the given screen point.
938
1367
  *
@@ -1016,6 +1445,15 @@ declare function dispatchPointerMiss(canvas: HTMLCanvasElement, point?: ScreenPo
1016
1445
  */
1017
1446
  declare function dispatchUnhover(canvas: HTMLCanvasElement): void;
1018
1447
 
1448
+ /**
1449
+ * @module drag
1450
+ *
1451
+ * Deterministic drag interactions on 3D objects. Supports world-space deltas
1452
+ * (move N units along an axis) and screen-space deltas (move N pixels).
1453
+ * Projects start/end points and dispatches a full pointerdown → pointermove × N
1454
+ * → pointerup sequence on the canvas.
1455
+ */
1456
+
1019
1457
  /** World-space drag delta. */
1020
1458
  interface WorldDelta {
1021
1459
  x: number;
@@ -1313,10 +1751,19 @@ declare function circlePath(center: {
1313
1751
  y: number;
1314
1752
  }, radiusX: number, radiusY?: number, steps?: number, pressure?: number): DrawPoint[];
1315
1753
 
1754
+ /**
1755
+ * @module resolve
1756
+ *
1757
+ * Shared resolution helpers for all interaction modules. Caches references
1758
+ * to the current ObjectStore, Camera, WebGLRenderer, and canvas size (set
1759
+ * by ThreeDom each frame) so interaction functions can resolve objects and
1760
+ * access rendering state without prop-drilling.
1761
+ */
1762
+
1316
1763
  /**
1317
1764
  * Resolve a testId or uuid to a live Object3D reference.
1318
1765
  * Throws a descriptive error if the object is not found.
1319
1766
  */
1320
1767
  declare function resolveObject(idOrUuid: string): Object3D;
1321
1768
 
1322
- export { type CanvasSize, type Click3DOptions, type Click3DResult, DomMirror, type Drag3DOptions, type Drag3DResult, type DragOptions, type DrawPathOptions, type DrawPathResult, type DrawPoint, type GeometryInspection, Highlighter, type HighlighterOptions, type Hover3DOptions, type Hover3DResult, MANAGED_ATTRIBUTES, type MaterialInspection, type ObjectInspection, type ObjectMetadata, ObjectStore, type PointerMiss3DOptions, type ProjectionResult, type R3FDOM, type RaycastResult, type SceneSnapshot, type ScreenDelta, type ScreenPoint, type SelectionListener, SelectionManager, type SnapshotNode, type StoreEvent, type StoreEventType, type StoreListener, TAG_MAP, ThreeDom, type ThreeDomProps, ThreeElement, type ThreeTagName, type Wheel3DOptions, type Wheel3DResult, type WheelOptions, type WorldDelta, applyAttributes, circlePath, click3D, computeAttributes, contextMenu3D, createFlatSnapshot, createSnapshot, curvePath, dispatchClick, dispatchContextMenu, dispatchDoubleClick, dispatchDrag, dispatchHover, dispatchPointerMiss, dispatchUnhover, dispatchWheel, doubleClick3D, drag3D, drawPath, enableDebug, ensureCustomElements, getHighlighter, getMirror, getSelectionManager, getStore, getTagForType, hover3D, isDebugEnabled, isInFrustum, isPatched, linePath, patchObject3D, pointerMiss3D, previewDragWorldDelta, projectAllSamplePoints, projectToScreen, r3fLog, rectPath, resolveObject, restoreObject3D, screenDeltaToWorld, unhover3D, verifyRaycastHit, verifyRaycastHitMultiPoint, version, wheel3D };
1769
+ export { type CameraState, type CanvasSize, type Click3DOptions, type Click3DResult, DomMirror, type Drag3DOptions, type Drag3DResult, type DragOptions, type DrawPathOptions, type DrawPathResult, type DrawPoint, type GeometryInspection, Highlighter, type HighlighterOptions, type Hover3DOptions, type Hover3DResult, InspectController, type InspectOptions, MANAGED_ATTRIBUTES, type MaterialInspection, type ObjectInspection, type ObjectMetadata, ObjectStore, type PointerMiss3DOptions, type ProjectionResult, type R3FDOM, RaycastAccelerator, type RaycastResult, type SceneSnapshot, type ScreenDelta, type ScreenPoint, type SelectionListener, SelectionManager, type SnapshotNode, type StoreEvent, type StoreEventType, type StoreListener, TAG_MAP, ThreeDom, type ThreeDomProps, ThreeElement, type ThreeTagName, type Wheel3DOptions, type Wheel3DResult, type WheelOptions, type WorldDelta, applyAttributes, circlePath, click3D, computeAttributes, contextMenu3D, createFlatSnapshot, createSnapshot, curvePath, dispatchClick, dispatchContextMenu, dispatchDoubleClick, dispatchDrag, dispatchHover, dispatchPointerMiss, dispatchUnhover, dispatchWheel, doubleClick3D, drag3D, drawPath, enableDebug, ensureCustomElements, getCanvasIds, getHighlighter, getInspectController, getMirror, getSelectionManager, getStore, getTagForType, hover3D, isDebugEnabled, isInFrustum, isPatched, linePath, patchObject3D, pointerMiss3D, previewDragWorldDelta, projectAllSamplePoints, projectToScreen, r3fLog, rectPath, resolveObject, restoreObject3D, screenDeltaToWorld, unhover3D, verifyRaycastHit, verifyRaycastHitMultiPoint, version, wheel3D };