@react-three/fiber 10.0.0-alpha.2 → 10.0.0-alpha.4

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/legacy.d.ts CHANGED
@@ -1,13 +1,16 @@
1
1
  import * as THREE$1 from 'three';
2
- import { WebGLRenderTarget, Color as Color$1, ColorRepresentation, RenderTargetOptions as RenderTargetOptions$1, Euler as Euler$1, Layers as Layers$1, Raycaster, Intersection as Intersection$1, Vector2 as Vector2$1, Vector3 as Vector3$1, Vector4 as Vector4$1, Quaternion as Quaternion$1, Matrix3 as Matrix3$1, Matrix4 as Matrix4$1, Object3D, Texture as Texture$1, Frustum, OrthographicCamera } from 'three';
2
+ import { WebGLCubeRenderTarget, WebGLRenderTarget, Color as Color$1, ColorRepresentation, Euler as Euler$1, Loader, RenderTargetOptions as RenderTargetOptions$1, Layers as Layers$1, Raycaster, Intersection as Intersection$1, BufferGeometry, Matrix4 as Matrix4$1, Quaternion as Quaternion$1, Node as Node$1, Vector2 as Vector2$1, Vector3 as Vector3$1, Vector4 as Vector4$1, Matrix3 as Matrix3$1, ColorSpace, Texture as Texture$1, CubeTexture, Scene, Object3D, Frustum, OrthographicCamera } from 'three';
3
3
  import * as React$1 from 'react';
4
4
  import { ReactNode, Component, RefObject, JSX } from 'react';
5
+ import * as three_webgpu from 'three/webgpu';
6
+ import { WebGPURenderer as WebGPURenderer$1, Node, StorageTexture, Data3DTexture, CanvasTarget, ShaderNodeObject } from 'three/webgpu';
5
7
  import { StoreApi } from 'zustand';
6
8
  import { UseBoundStoreWithEqualityFn } from 'zustand/traditional';
7
- import * as three_webgpu from 'three/webgpu';
8
- import { Node, ShaderNodeObject } from 'three/webgpu';
9
+ import { FrameTimingState, FrameCallback as FrameCallback$1, SchedulerApi, UseFrameNextOptions, FrameNextControls } from '@pmndrs/scheduler';
10
+ export { AddPhaseOptions, FrameControls, FrameNextControls, FrameTimingState, RootOptions, Scheduler, SchedulerApi, UseFrameNextOptions, UseFrameOptions, getScheduler } from '@pmndrs/scheduler';
9
11
  import { Options } from 'react-use-measure';
10
12
  import * as react_jsx_runtime from 'react/jsx-runtime';
13
+ import { GroundedSkybox } from 'three/examples/jsm/objects/GroundedSkybox.js';
11
14
 
12
15
  function _mergeNamespaces(n, m) {
13
16
  m.forEach(function (e) {
@@ -35,1301 +38,1466 @@ function _mergeNamespaces(n, m) {
35
38
  declare const R3F_BUILD_LEGACY = true;
36
39
  declare const R3F_BUILD_WEBGPU = false;
37
40
 
38
- declare const Inspector: {
39
- new (): {};
40
- };
41
+ type Inspector = never;
42
+ /** Not available on the legacy (WebGL-only) entry. */
43
+ declare function loadInspector(): Promise<never>;
41
44
  declare const WebGPURenderer: {
42
45
  new (): {};
43
46
  };
44
47
 
45
48
  declare const RenderTarget: any;
46
49
 
50
+ declare const CubeRenderTarget: any;
51
+
47
52
  var THREE = /*#__PURE__*/_mergeNamespaces({
48
53
  __proto__: null,
54
+ CubeRenderTarget: CubeRenderTarget,
55
+ CubeRenderTargetCompat: WebGLCubeRenderTarget,
49
56
  Inspector: Inspector,
50
57
  R3F_BUILD_LEGACY: R3F_BUILD_LEGACY,
51
58
  R3F_BUILD_WEBGPU: R3F_BUILD_WEBGPU,
52
59
  RenderTarget: RenderTarget,
53
60
  RenderTargetCompat: WebGLRenderTarget,
54
- WebGPURenderer: WebGPURenderer
61
+ WebGPURenderer: WebGPURenderer,
62
+ loadInspector: loadInspector
55
63
  }, [THREE$1]);
56
64
 
57
- //* Utility Types ==============================
58
-
59
- type NonFunctionKeys<P> = { [K in keyof P]-?: P[K] extends Function ? never : K }[keyof P]
60
- type Overwrite<P, O> = Omit<P, NonFunctionKeys<O>> & O
61
- type Properties<T> = Pick<T, NonFunctionKeys<T>>
62
- type Mutable<P> = { [K in keyof P]: P[K] | Readonly<P[K]> }
63
- type IsOptional<T> = undefined extends T ? true : false
64
- type IsAllOptional<T extends any[]> = T extends [infer First, ...infer Rest]
65
- ? IsOptional<First> extends true
66
- ? IsAllOptional<Rest>
67
- : false
68
- : true
69
-
70
- //* Camera Types ==============================
71
-
72
- type ThreeCamera = (THREE$1.OrthographicCamera | THREE$1.PerspectiveCamera) & { manual?: boolean }
73
-
74
- //* Act Type ==============================
75
-
76
- type Act = <T = any>(cb: () => Promise<T>) => Promise<T>
77
-
78
- //* Bridge & Block Types ==============================
79
-
80
- type Bridge = React$1.FC<{ children?: React$1.ReactNode }>
81
-
82
- type SetBlock = false | Promise<null> | null
83
- type UnblockProps = { set: React$1.Dispatch<React$1.SetStateAction<SetBlock>>; children: React$1.ReactNode }
84
-
85
- //* Object Map Type ==============================
86
-
87
- interface ObjectMap {
88
- nodes: { [name: string]: THREE$1.Object3D }
89
- materials: { [name: string]: THREE$1.Material }
90
- meshes: { [name: string]: THREE$1.Mesh }
91
- }
92
-
93
- //* Equality Config ==============================
94
-
95
- interface EquConfig {
96
- /** Compare arrays by reference equality a === b (default), or by shallow equality */
97
- arrays?: 'reference' | 'shallow'
98
- /** Compare objects by reference equality a === b (default), or by shallow equality */
99
- objects?: 'reference' | 'shallow'
100
- /** If true the keys in both a and b must match 1:1 (default), if false a's keys must intersect b's */
101
- strict?: boolean
102
- }
103
-
104
- //* Disposable Type ==============================
105
-
106
- interface Disposable {
107
- type?: string
108
- dispose?: () => void
109
- }
110
-
111
- //* Event-related Types =====================================
112
-
113
- interface Intersection extends THREE$1.Intersection {
114
- /** The event source (the object which registered the handler) */
115
- eventObject: THREE$1.Object3D
116
- }
117
-
118
- type Camera = THREE$1.OrthographicCamera | THREE$1.PerspectiveCamera
119
-
120
- interface IntersectionEvent<TSourceEvent> extends Intersection {
121
- /** The event source (the object which registered the handler) */
122
- eventObject: THREE$1.Object3D
123
- /** An array of intersections */
124
- intersections: Intersection[]
125
- /** vec3.set(pointer.x, pointer.y, 0).unproject(camera) */
126
- unprojectedPoint: THREE$1.Vector3
127
- /** Normalized event coordinates */
128
- pointer: THREE$1.Vector2
129
- /** Delta between first click and this event */
130
- delta: number
131
- /** The ray that pierced it */
132
- ray: THREE$1.Ray
133
- /** The camera that was used by the raycaster */
134
- camera: Camera
135
- /** stopPropagation will stop underlying handlers from firing */
136
- stopPropagation: () => void
137
- /** The original host event */
138
- nativeEvent: TSourceEvent
139
- /** If the event was stopped by calling stopPropagation */
140
- stopped: boolean
141
- }
142
-
143
- type ThreeEvent<TEvent> = IntersectionEvent<TEvent> & Properties<TEvent>
144
- type DomEvent = PointerEvent | MouseEvent | WheelEvent
145
-
146
- /** DOM event handlers registered on the canvas element */
147
- interface Events {
148
- onClick: EventListener
149
- onContextMenu: EventListener
150
- onDoubleClick: EventListener
151
- onWheel: EventListener
152
- onPointerDown: EventListener
153
- onPointerUp: EventListener
154
- onPointerLeave: EventListener
155
- onPointerMove: EventListener
156
- onPointerCancel: EventListener
157
- onLostPointerCapture: EventListener
158
- onDragEnter: EventListener
159
- onDragLeave: EventListener
160
- onDragOver: EventListener
161
- onDrop: EventListener
162
- }
163
-
164
- /** Event handlers that can be attached to R3F objects (meshes, groups, etc.) */
165
- interface EventHandlers {
166
- onClick?: (event: ThreeEvent<MouseEvent>) => void
167
- onContextMenu?: (event: ThreeEvent<MouseEvent>) => void
168
- onDoubleClick?: (event: ThreeEvent<MouseEvent>) => void
169
- /** Fires continuously while dragging over the object */
170
- onDragOver?: (event: ThreeEvent<DragEvent>) => void
171
- /** Fires once when drag enters the object */
172
- onDragOverEnter?: (event: ThreeEvent<DragEvent>) => void
173
- /** Fires once when drag leaves the object */
174
- onDragOverLeave?: (event: ThreeEvent<DragEvent>) => void
175
- /** Fires when drag misses this object (for objects that have drag handlers) */
176
- onDragOverMissed?: (event: DragEvent) => void
177
- /** Fires when a drop occurs on this object */
178
- onDrop?: (event: ThreeEvent<DragEvent>) => void
179
- /** Fires when a drop misses this object (for objects that have drop handlers) */
180
- onDropMissed?: (event: DragEvent) => void
181
- onPointerUp?: (event: ThreeEvent<PointerEvent>) => void
182
- onPointerDown?: (event: ThreeEvent<PointerEvent>) => void
183
- onPointerOver?: (event: ThreeEvent<PointerEvent>) => void
184
- onPointerOut?: (event: ThreeEvent<PointerEvent>) => void
185
- onPointerEnter?: (event: ThreeEvent<PointerEvent>) => void
186
- onPointerLeave?: (event: ThreeEvent<PointerEvent>) => void
187
- onPointerMove?: (event: ThreeEvent<PointerEvent>) => void
188
- onPointerMissed?: (event: MouseEvent) => void
189
- onPointerCancel?: (event: ThreeEvent<PointerEvent>) => void
190
- onWheel?: (event: ThreeEvent<WheelEvent>) => void
191
- onLostPointerCapture?: (event: ThreeEvent<PointerEvent>) => void
192
-
193
- //* Visibility Events --------------------------------
194
- /** Fires when object enters/exits camera frustum. Receives true when in view, false when out. */
195
- onFramed?: (inView: boolean) => void
196
- /** Fires when object occlusion state changes (WebGPU only, requires occlusionTest=true on object) */
197
- onOccluded?: (occluded: boolean) => void
198
- /** Fires when combined visibility changes (frustum + occlusion + visible prop) */
199
- onVisible?: (visible: boolean) => void
200
- }
201
-
202
- type FilterFunction = (items: THREE$1.Intersection[], state: RootState) => THREE$1.Intersection[]
203
- type ComputeFunction = (event: DomEvent, root: RootState, previous?: RootState) => void
204
-
205
- interface EventManager<TTarget> {
206
- /** Determines if the event layer is active */
207
- enabled: boolean
208
- /** Event layer priority, higher prioritized layers come first and may stop(-propagate) lower layer */
209
- priority: number
210
- /** The compute function needs to set up the raycaster and an xy- pointer */
211
- compute?: ComputeFunction
212
- /** The filter can re-order or re-structure the intersections */
213
- filter?: FilterFunction
214
- /** The target node the event layer is tied to */
215
- connected?: TTarget
216
- /** All the pointer event handlers through which the host forwards native events */
217
- handlers?: Events
218
- /** Allows re-connecting to another target */
219
- connect?: (target: TTarget) => void
220
- /** Removes all existing events handlers from the target */
221
- disconnect?: () => void
222
- /** Triggers a onPointerMove with the last known event. This can be useful to enable raycasting without
223
- * explicit user interaction, for instance when the camera moves a hoverable object underneath the cursor.
224
- */
225
- update?: () => void
226
- }
227
-
228
- interface PointerCaptureTarget {
229
- intersection: Intersection
230
- target: Element
231
- }
232
-
233
- //* Visibility System Types =====================================
234
-
235
- /** Entry in the visibility registry for tracking object visibility state */
236
- interface VisibilityEntry {
237
- object: THREE$1.Object3D
238
- handlers: Pick<EventHandlers, 'onFramed' | 'onOccluded' | 'onVisible'>
239
- lastFramedState: boolean | null
240
- lastOccludedState: boolean | null
241
- lastVisibleState: boolean | null
242
- }
243
-
244
- //* Scheduler Types (useFrame) ==============================
245
-
246
-
247
-
248
- // Public Options --------------------------------
249
-
250
- /**
251
- * Options for useFrame hook
252
- */
253
- interface UseFrameNextOptions {
254
- /** Optional stable id for the job. Auto-generated if not provided */
255
- id?: string
256
- /** Named phase to run in. Default: 'update' */
257
- phase?: string
258
- /** Run before this phase or job id */
259
- before?: string | string[]
260
- /** Run after this phase or job id */
261
- after?: string | string[]
262
- /** Priority within phase. Higher runs first. Default: 0 */
263
- priority?: number
264
- /** Max frames per second for this job */
265
- fps?: number
266
- /** If true, skip frames when behind. If false, try to catch up. Default: true */
267
- drop?: boolean
268
- /** Enable/disable without unregistering. Default: true */
269
- enabled?: boolean
270
- }
271
-
272
- /** Alias for UseFrameNextOptions */
273
- type UseFrameOptions = UseFrameNextOptions
274
-
275
- /**
276
- * Options for addPhase
277
- */
278
- interface AddPhaseOptions {
279
- /** Insert this phase before the specified phase */
280
- before?: string
281
- /** Insert this phase after the specified phase */
282
- after?: string
283
- }
284
-
285
- // Frame State --------------------------------
286
-
287
- /**
288
- * Timing-only state for independent/outside mode (no RootState)
289
- */
290
- interface FrameTimingState {
291
- /** High-resolution timestamp from RAF (ms) */
292
- time: number
293
- /** Time since last frame in seconds (for legacy compatibility with THREE.Clock) */
294
- delta: number
295
- /** Elapsed time since first frame in seconds (for legacy compatibility with THREE.Clock) */
296
- elapsed: number
297
- /** Incrementing frame counter */
298
- frame: number
299
- }
300
-
301
- /**
302
- * State passed to useFrame callbacks (extends RootState with timing)
303
- */
304
- interface FrameNextState extends RootState, FrameTimingState {}
305
-
306
- /** Alias for FrameNextState */
307
- type FrameState = FrameNextState
308
-
309
- // Root Options --------------------------------
310
-
311
- /**
312
- * Options for registerRoot
313
- */
314
- interface RootOptions {
315
- /** State provider for callbacks. Optional in independent mode. */
316
- getState?: () => any
317
- /** Error handler for job errors. Falls back to console.error if not provided. */
318
- onError?: (error: Error) => void
319
- }
320
-
321
- // Callback Types --------------------------------
322
-
323
- /**
324
- * Callback function for useFrame
325
- */
326
- type FrameNextCallback = (state: FrameNextState, delta: number) => void
327
-
328
- /** Alias for FrameNextCallback */
329
- type FrameCallback = FrameNextCallback
330
-
331
- // Controls returned from useFrame --------------------------------
332
-
333
- /**
334
- * Controls object returned from useFrame hook
335
- */
336
- interface FrameNextControls {
337
- /** The job's unique ID */
338
- id: string
339
- /** Access to the global scheduler for frame loop control */
340
- scheduler: SchedulerApi
341
- /** Manually step this job only (bypasses FPS limiting) */
342
- step(timestamp?: number): void
343
- /** Manually step ALL jobs in the scheduler */
344
- stepAll(timestamp?: number): void
345
- /** Pause this job (set enabled=false) */
346
- pause(): void
347
- /** Resume this job (set enabled=true) */
348
- resume(): void
349
- /** Reactive paused state - automatically triggers re-render when changed */
350
- isPaused: boolean
351
- }
352
-
353
- /** Alias for FrameNextControls */
354
- type FrameControls = FrameNextControls
355
-
356
- // Scheduler Interface --------------------------------
357
-
358
- /**
359
- * Public interface for the global Scheduler
360
- */
361
- interface SchedulerApi {
362
- //* Phase Management --------------------------------
363
-
364
- /** Add a named phase to the scheduler */
365
- addPhase(name: string, options?: AddPhaseOptions): void
366
- /** Get the ordered list of phase names */
367
- readonly phases: string[]
368
- /** Check if a phase exists */
369
- hasPhase(name: string): boolean
370
-
371
- //* Root Management --------------------------------
372
-
373
- /** Register a root (Canvas) with the scheduler. Returns unsubscribe function. */
374
- registerRoot(id: string, options?: RootOptions): () => void
375
- /** Unregister a root */
376
- unregisterRoot(id: string): void
377
- /** Generate a unique root ID */
378
- generateRootId(): string
379
- /** Get the number of registered roots */
380
- getRootCount(): number
381
- /** Check if any root is registered and ready */
382
- readonly isReady: boolean
383
- /** Subscribe to root-ready event. Fires immediately if already ready. Returns unsubscribe. */
384
- onRootReady(callback: () => void): () => void
385
-
386
- //* Job Registration --------------------------------
387
-
388
- /** Register a job with the scheduler (returns unsubscribe function) */
389
- register(
390
- callback: FrameNextCallback,
391
- options?: {
392
- id?: string
393
- rootId?: string
394
- phase?: string
395
- before?: string | string[]
396
- after?: string | string[]
397
- priority?: number
398
- fps?: number
399
- drop?: boolean
400
- enabled?: boolean
401
- },
402
- ): () => void
403
- /** Update a job's options */
404
- updateJob(
405
- id: string,
406
- options: {
407
- priority?: number
408
- fps?: number
409
- drop?: boolean
410
- enabled?: boolean
411
- phase?: string
412
- before?: string | string[]
413
- after?: string | string[]
414
- },
415
- ): void
416
- /** Unregister a job by ID */
417
- unregister(id: string, rootId?: string): void
418
- /** Get the number of registered jobs */
419
- getJobCount(): number
420
- /** Get all job IDs */
421
- getJobIds(): string[]
422
-
423
- //* Global Jobs (for legacy addEffect/addAfterEffect) --------------------------------
424
-
425
- /** Register a global job (runs once per frame, not per-root). Returns unsubscribe function. */
426
- registerGlobal(phase: 'before' | 'after', id: string, callback: (timestamp: number) => void): () => void
427
-
428
- //* Idle Callbacks (for legacy addTail) --------------------------------
429
-
430
- /** Register an idle callback (fires when loop stops). Returns unsubscribe function. */
431
- onIdle(callback: (timestamp: number) => void): () => void
432
-
433
- //* Frame Loop Control --------------------------------
434
-
435
- /** Start the scheduler loop */
436
- start(): void
437
- /** Stop the scheduler loop */
438
- stop(): void
439
- /** Check if the scheduler is running */
440
- readonly isRunning: boolean
441
- /** Get/set the frameloop mode ('always', 'demand', 'never') */
442
- frameloop: Frameloop
443
- /** Independent mode - runs without Canvas, callbacks receive timing-only state */
444
- independent: boolean
445
-
446
- //* Manual Stepping --------------------------------
447
-
448
- /** Manually step all jobs once (for frameloop='never' or testing) */
449
- step(timestamp?: number): void
450
- /** Manually step a single job by ID */
451
- stepJob(id: string, timestamp?: number): void
452
- /** Request frame(s) to be rendered (for frameloop='demand') */
453
- invalidate(frames?: number): void
454
-
455
- //* Per-Job Control --------------------------------
456
-
457
- /** Check if a job is paused */
458
- isJobPaused(id: string): boolean
459
- /** Pause a job */
460
- pauseJob(id: string): void
461
- /** Resume a job */
462
- resumeJob(id: string): void
463
- /** Subscribe to job state changes (for reactive isPaused). Returns unsubscribe function. */
464
- subscribeJobState(id: string, listener: () => void): () => void
465
- }
466
-
467
- //* Core Store Types ========================================
468
-
469
- type Subscription = {
470
- ref: React$1.RefObject<RenderCallback>
471
- priority: number
472
- store: RootStore
473
- }
474
-
475
- type Dpr = number | [min: number, max: number]
476
-
477
- interface Size {
478
- width: number
479
- height: number
480
- top: number
481
- left: number
482
- }
483
-
484
- type Frameloop = 'always' | 'demand' | 'never'
485
-
486
- interface Viewport extends Size {
487
- /** The initial pixel ratio */
488
- initialDpr: number
489
- /** Current pixel ratio */
490
- dpr: number
491
- /** size.width / viewport.width */
492
- factor: number
493
- /** Camera distance */
494
- distance: number
495
- /** Camera aspect ratio: width / height */
496
- aspect: number
497
- }
498
-
499
- type RenderCallback = (state: RootState, delta: number, frame?: XRFrame) => void
500
-
501
- interface Performance {
502
- /** Current performance normal, between min and max */
503
- current: number
504
- /** How low the performance can go, between 0 and max */
505
- min: number
506
- /** How high the performance can go, between min and max */
507
- max: number
508
- /** Time until current returns to max in ms */
509
- debounce: number
510
- /** Sets current to min, puts the system in regression */
511
- regress: () => void
512
- }
513
-
514
- interface InternalState {
515
- interaction: THREE$1.Object3D[]
516
- hovered: Map<string, ThreeEvent<DomEvent>>
517
- subscribers: Subscription[]
518
- capturedMap: Map<number, Map<THREE$1.Object3D, PointerCaptureTarget>>
519
- initialClick: [x: number, y: number]
520
- initialHits: THREE$1.Object3D[]
521
- lastEvent: React$1.RefObject<DomEvent | null>
522
- /** Visibility event registry (onFramed, onOccluded, onVisible) */
523
- visibilityRegistry: Map<string, VisibilityEntry>
524
- /** Whether occlusion queries are enabled (WebGPU only) */
525
- occlusionEnabled: boolean
526
- /** Reference to the invisible occlusion observer mesh */
527
- occlusionObserver: THREE$1.Mesh | null
528
- /** Cached occlusion results from render pass - keyed by Object3D */
529
- occlusionCache: Map<THREE$1.Object3D, boolean | null>
530
- /** Internal helper group for R3F system objects (occlusion observer, etc.) */
531
- helperGroup: THREE$1.Group | null
532
- active: boolean
533
- priority: number
534
- frames: number
535
- subscribe: (callback: React$1.RefObject<RenderCallback>, priority: number, store: RootStore) => () => void
536
- /** Internal renderer storage - use state.renderer or state.gl to access */
537
- actualRenderer: THREE$1.WebGLRenderer | any // WebGPURenderer when available
538
- /** Global scheduler reference (for useFrame hook) */
539
- scheduler: SchedulerApi | null
540
- /** This root's unique ID in the global scheduler */
541
- rootId?: string
542
- /** Function to unregister this root from the global scheduler */
543
- unregisterRoot?: () => void
544
- /** Container for child attachment (scene for root, original container for portals) */
545
- container?: THREE$1.Object3D
546
- }
547
-
548
- interface XRManager {
549
- connect: () => void
550
- disconnect: () => void
551
- }
552
-
553
- //* Root State Interface ====================================
554
-
555
- interface RootState {
556
- /** Set current state */
557
- set: StoreApi<RootState>['setState']
558
- /** Get current state */
559
- get: StoreApi<RootState>['getState']
560
- /** (deprecated) The instance of the WebGLrenderer */
561
- gl: THREE$1.WebGLRenderer
562
- /** The instance of the WebGPU renderer, the fallback, OR the default renderer as a mask of gl */
563
- renderer: THREE$1.WebGLRenderer | any // WebGPURenderer when available
564
- /** Inspector of the webGPU Renderer. Init in the canvas */
565
- inspector: any // Inspector type from three/webgpu
566
-
567
- /** Default camera */
568
- camera: ThreeCamera
569
- /** Camera frustum for visibility checks - auto-updated each frame when autoUpdateFrustum is true */
570
- frustum: THREE$1.Frustum
571
- /** Whether to automatically update the frustum each frame (default: true) */
572
- autoUpdateFrustum: boolean
573
- /** Default scene (may be overridden in portals to point to the portal container) */
574
- scene: THREE$1.Scene
575
- /** The actual root THREE.Scene - always points to the true scene, even inside portals */
576
- rootScene: THREE$1.Scene
577
- /** Default raycaster */
578
- raycaster: THREE$1.Raycaster
579
- /** Event layer interface, contains the event handler and the node they're connected to */
580
- events: EventManager<any>
581
- /** XR interface */
582
- xr: XRManager
583
- /** Currently used controls */
584
- controls: THREE$1.EventDispatcher | null
585
- /** Normalized event coordinates */
586
- pointer: THREE$1.Vector2
587
- /** @deprecated Normalized event coordinates, use "pointer" instead! */
588
- mouse: THREE$1.Vector2
589
- /* Whether to enable r139's THREE.ColorManagement */
590
- legacy: boolean
591
- /** Shortcut to gl.outputColorSpace = THREE.LinearSRGBColorSpace */
592
- linear: boolean
593
- /** Shortcut to gl.toneMapping = NoTonemapping */
594
- flat: boolean
595
- /** Color space assigned to 8-bit input textures (color maps). Most textures are authored in sRGB. */
596
- textureColorSpace: THREE$1.ColorSpace
597
- /** Render loop flags */
598
- frameloop: Frameloop
599
- performance: Performance
600
- /** Reactive pixel-size of the canvas */
601
- size: Size
602
- /** Reactive size of the viewport in threejs units */
603
- viewport: Viewport & {
604
- getCurrentViewport: (
605
- camera?: ThreeCamera,
606
- target?: THREE$1.Vector3 | Parameters<THREE$1.Vector3['set']>,
607
- size?: Size,
608
- ) => Omit<Viewport, 'dpr' | 'initialDpr'>
609
- }
610
- /** Flags the canvas for render, but doesn't render in itself */
611
- invalidate: (frames?: number, stackFrames?: boolean) => void
612
- /** Advance (render) one step */
613
- advance: (timestamp: number, runGlobalEffects?: boolean) => void
614
- /** Shortcut to setting the event layer */
615
- setEvents: (events: Partial<EventManager<any>>) => void
616
- /** Shortcut to manual sizing. No args resets to props/container. Single arg creates square. */
617
- setSize: (width?: number, height?: number, top?: number, left?: number) => void
618
- /** Shortcut to manual setting the pixel ratio */
619
- setDpr: (dpr: Dpr) => void
620
- /** Shortcut to setting frameloop flags */
621
- setFrameloop: (frameloop: Frameloop) => void
622
- /** Set error state to propagate to error boundary */
623
- setError: (error: Error | null) => void
624
- /** Current error state (null when no error) */
625
- error: Error | null
626
- /** Global TSL uniform nodes - root-level uniforms + scoped sub-objects. Use useUniforms() hook */
627
- uniforms: UniformStore
628
- /** Global TSL nodes - root-level nodes + scoped sub-objects. Use useNodes() hook */
629
- nodes: Record<string, any>
630
- /** Global TSL texture nodes - use useTextures() hook for operations */
631
- textures: Map<string, any>
632
- /** WebGPU PostProcessing instance - use usePostProcessing() hook */
633
- postProcessing: any | null // THREE.PostProcessing when available
634
- /** Global TSL pass nodes for post-processing - use usePostProcessing() hook */
635
- passes: Record<string, any>
636
- /** Internal version counter for HMR - incremented by rebuildNodes/rebuildUniforms to bust memoization */
637
- _hmrVersion: number
638
- /** Internal: whether setSize() has taken ownership of canvas dimensions */
639
- _sizeImperative: boolean
640
- /** Internal: stored size props from Canvas for reset functionality */
641
- _sizeProps: { width?: number; height?: number } | null
642
- /** When the canvas was clicked but nothing was hit */
643
- onPointerMissed?: (event: MouseEvent) => void
644
- /** When a dragover event has missed any target */
645
- onDragOverMissed?: (event: DragEvent) => void
646
- /** When a drop event has missed any target */
647
- onDropMissed?: (event: DragEvent) => void
648
- /** If this state model is layered (via createPortal) then this contains the previous layer */
649
- previousRoot?: RootStore
650
- /** Internals */
651
- internal: InternalState
652
- // flags for triggers
653
- // if we are using the webGl renderer, this will be true
654
- isLegacy: boolean
655
- // regardless of renderer, if the system supports webGpu, this will be true
656
- webGPUSupported: boolean
657
- //if we are on native
658
- isNative: boolean
659
- }
660
-
65
+ //* Utility Types ==============================
66
+
67
+ type NonFunctionKeys<P> = { [K in keyof P]-?: P[K] extends Function ? never : K }[keyof P]
68
+ type Overwrite<P, O> = Omit<P, NonFunctionKeys<O>> & O
69
+ type Properties<T> = Pick<T, NonFunctionKeys<T>>
70
+ type Mutable<P> = { -readonly [K in keyof P]: P[K] }
71
+ type IsOptional<T> = undefined extends T ? true : false
72
+ type IsAllOptional<T extends any[]> = T extends [infer First, ...infer Rest]
73
+ ? IsOptional<First> extends true
74
+ ? IsAllOptional<Rest>
75
+ : false
76
+ : true
77
+
78
+ //* Camera Types ==============================
79
+
80
+ type ThreeCamera = (THREE$1.OrthographicCamera | THREE$1.PerspectiveCamera) & { manual?: boolean }
81
+
82
+ //* Act Type ==============================
83
+
84
+ type Act = <T = any>(cb: () => Promise<T>) => Promise<T>
85
+
86
+ //* Bridge & Block Types ==============================
87
+
88
+ type Bridge = React$1.FC<{ children?: React$1.ReactNode }>
89
+
90
+ type SetBlock = false | Promise<null> | null
91
+ type UnblockProps = { set: React$1.Dispatch<React$1.SetStateAction<SetBlock>>; children: React$1.ReactNode }
92
+
93
+ //* Object Map Type ==============================
94
+
95
+ /* Original version
96
+ export interface ObjectMap {
97
+ nodes: { [name: string]: THREE.Object3D }
98
+ materials: { [name: string]: THREE.Material }
99
+ meshes: { [name: string]: THREE.Mesh }
100
+ }
101
+ */
102
+ /* This version is an expansion found in a PR by itsdouges that seems abandoned but looks useful.
103
+ It allows expansion but falls back to the original shape. (deleted due to stale, but If it doesnt conflict
104
+ I will keep the use here)
105
+ https://github.com/pmndrs/react-three-fiber/commits/generic-object-map/
106
+ His description is:
107
+ The object map type is now generic and can optionally declare the available properties for nodes, materials, and meshes.
108
+ */
109
+ interface ObjectMap<
110
+ T extends { nodes?: string; materials?: string; meshes?: string } = {
111
+ nodes: string
112
+ materials: string
113
+ meshes: string
114
+ },
115
+ > {
116
+ nodes: Record<T['nodes'] extends string ? T['nodes'] : string, THREE$1.Object3D>
117
+ materials: Record<T['materials'] extends string ? T['materials'] : string, THREE$1.Material>
118
+ meshes: Record<T['meshes'] extends string ? T['meshes'] : string, THREE$1.Mesh>
119
+ }
120
+
121
+ //* Equality Config ==============================
122
+
123
+ interface EquConfig {
124
+ /** Compare arrays by reference equality a === b (default), or by shallow equality */
125
+ arrays?: 'reference' | 'shallow'
126
+ /** Compare objects by reference equality a === b (default), or by shallow equality */
127
+ objects?: 'reference' | 'shallow'
128
+ /** If true the keys in both a and b must match 1:1 (default), if false a's keys must intersect b's */
129
+ strict?: boolean
130
+ }
131
+
132
+ //* Disposable Type ==============================
133
+
134
+ interface Disposable {
135
+ type?: string
136
+ dispose?: () => void
137
+ }
138
+
139
+ //* Event-related Types =====================================
140
+
141
+ interface Intersection extends THREE$1.Intersection {
142
+ /** The event source (the object which registered the handler) */
143
+ eventObject: THREE$1.Object3D
144
+ }
145
+
146
+ type Camera = THREE$1.OrthographicCamera | THREE$1.PerspectiveCamera
147
+
148
+ interface IntersectionEvent<TSourceEvent> extends Intersection {
149
+ /** The event source (the object which registered the handler) */
150
+ eventObject: THREE$1.Object3D
151
+ /** An array of intersections */
152
+ intersections: Intersection[]
153
+ /** vec3.set(pointer.x, pointer.y, 0).unproject(camera) */
154
+ unprojectedPoint: THREE$1.Vector3
155
+ /** Normalized event coordinates */
156
+ pointer: THREE$1.Vector2
157
+ /** pointerId of the original event for multiple pointer events */
158
+ pointerId: number
159
+ /** Delta between first click and this event */
160
+ delta: number
161
+ /** The ray that pierced it */
162
+ ray: THREE$1.Ray
163
+ /** The camera that was used by the raycaster */
164
+ camera: Camera
165
+ /** stopPropagation will stop underlying handlers from firing */
166
+ stopPropagation: () => void
167
+ /** The original host event */
168
+ nativeEvent: TSourceEvent
169
+ /** If the event was stopped by calling stopPropagation */
170
+ stopped: boolean
171
+ }
172
+
173
+ type ThreeEvent<TEvent> = IntersectionEvent<TEvent> & Properties<TEvent>
174
+ type DomEvent = PointerEvent | MouseEvent | WheelEvent
175
+
176
+ /** DOM event handlers registered on the canvas element */
177
+ interface Events {
178
+ onClick: EventListener
179
+ onContextMenu: EventListener
180
+ onDoubleClick: EventListener
181
+ onWheel: EventListener
182
+ onPointerDown: EventListener
183
+ onPointerUp: EventListener
184
+ onPointerLeave: EventListener
185
+ onPointerMove: EventListener
186
+ onPointerCancel: EventListener
187
+ onLostPointerCapture: EventListener
188
+ onDragEnter: EventListener
189
+ onDragLeave: EventListener
190
+ onDragOver: EventListener
191
+ onDrop: EventListener
192
+ }
193
+
194
+ /** Event handlers that can be attached to R3F objects (meshes, groups, etc.) */
195
+ interface EventHandlers {
196
+ onClick?: (event: ThreeEvent<MouseEvent>) => void
197
+ onContextMenu?: (event: ThreeEvent<MouseEvent>) => void
198
+ onDoubleClick?: (event: ThreeEvent<MouseEvent>) => void
199
+ /** Fires continuously while dragging over the object */
200
+ onDragOver?: (event: ThreeEvent<DragEvent>) => void
201
+ /** Fires once when drag enters the object */
202
+ onDragOverEnter?: (event: ThreeEvent<DragEvent>) => void
203
+ /** Fires once when drag leaves the object */
204
+ onDragOverLeave?: (event: ThreeEvent<DragEvent>) => void
205
+ /** Fires when drag misses this object (for objects that have drag handlers) */
206
+ onDragOverMissed?: (event: DragEvent) => void
207
+ /** Fires when a drop occurs on this object */
208
+ onDrop?: (event: ThreeEvent<DragEvent>) => void
209
+ /** Fires when a drop misses this object (for objects that have drop handlers) */
210
+ onDropMissed?: (event: DragEvent) => void
211
+ onPointerUp?: (event: ThreeEvent<PointerEvent>) => void
212
+ onPointerDown?: (event: ThreeEvent<PointerEvent>) => void
213
+ onPointerOver?: (event: ThreeEvent<PointerEvent>) => void
214
+ onPointerOut?: (event: ThreeEvent<PointerEvent>) => void
215
+ onPointerEnter?: (event: ThreeEvent<PointerEvent>) => void
216
+ onPointerLeave?: (event: ThreeEvent<PointerEvent>) => void
217
+ onPointerMove?: (event: ThreeEvent<PointerEvent>) => void
218
+ onPointerMissed?: (event: MouseEvent) => void
219
+ onPointerCancel?: (event: ThreeEvent<PointerEvent>) => void
220
+ onWheel?: (event: ThreeEvent<WheelEvent>) => void
221
+ onLostPointerCapture?: (event: ThreeEvent<PointerEvent>) => void
222
+
223
+ //* Visibility Events --------------------------------
224
+ /** Fires when object enters/exits camera frustum. Receives true when in view, false when out. */
225
+ onFramed?: (inView: boolean) => void
226
+ /** Fires when object occlusion state changes (WebGPU only, requires occlusionTest=true on object) */
227
+ onOccluded?: (occluded: boolean) => void
228
+ /** Fires when combined visibility changes (frustum + occlusion + visible prop) */
229
+ onVisible?: (visible: boolean) => void
230
+ }
231
+
232
+ type FilterFunction = (items: THREE$1.Intersection[], state: RootState) => THREE$1.Intersection[]
233
+ type ComputeFunction = (event: DomEvent, root: RootState, previous?: RootState) => void
234
+
235
+ /** Configuration for XR pointer registration (controllers/hands) */
236
+ interface XRPointerConfig {
237
+ /** Ray origin (updated each frame by XR system) */
238
+ ray: THREE$1.Ray
239
+ /** Optional: custom compute function for this pointer */
240
+ compute?: (state: RootState) => void
241
+ /** Pointer type identifier */
242
+ type: 'controller' | 'hand' | 'gaze'
243
+ /** Which hand (for controller/hand types) */
244
+ handedness?: 'left' | 'right'
245
+ }
246
+
247
+ interface EventManager<TTarget> {
248
+ /** Determines if the event layer is active */
249
+ enabled: boolean
250
+ /** Event layer priority, higher prioritized layers come first and may stop(-propagate) lower layer */
251
+ priority: number
252
+ /** The compute function needs to set up the raycaster and an xy- pointer */
253
+ compute?: ComputeFunction
254
+ /** The filter can re-order or re-structure the intersections */
255
+ filter?: FilterFunction
256
+ /** The target node the event layer is tied to */
257
+ connected?: TTarget
258
+ /** All the pointer event handlers through which the host forwards native events */
259
+ handlers?: Events
260
+ /** Allows re-connecting to another target */
261
+ connect?: (target: TTarget) => void
262
+ /** Removes all existing events handlers from the target */
263
+ disconnect?: () => void
264
+ /** Triggers a onPointerMove with the last known event. This can be useful to enable raycasting without
265
+ * explicit user interaction, for instance when the camera moves a hoverable object underneath the cursor.
266
+ * @param pointerId - Optional pointer ID to update specific pointer only
267
+ */
268
+ update?: (pointerId?: number) => void
269
+ /** Defer pointer move raycasting to frame start (default: true) */
270
+ frameTimedRaycasts?: boolean
271
+ /** Always fire raycaster immediately on scroll events (default: true) */
272
+ alwaysFireOnScroll?: boolean
273
+ /** Automatically re-raycast every frame to detect hover changes from moving objects/camera (default: false) */
274
+ updateOnFrame?: boolean
275
+ /** Flush deferred pointer raycasts. Called by scheduler at frame start (input phase). */
276
+ flush?: () => void
277
+ /** Register an XR pointer (controller/hand). Returns assigned pointerId */
278
+ registerPointer?: (config: XRPointerConfig) => number
279
+ /** Unregister an XR pointer */
280
+ unregisterPointer?: (pointerId: number) => void
281
+ }
282
+
283
+ interface PointerCaptureTarget {
284
+ intersection: Intersection
285
+ target: Element
286
+ }
287
+
288
+ //* Visibility System Types =====================================
289
+
290
+ /** Entry in the visibility registry for tracking object visibility state */
291
+ interface VisibilityEntry {
292
+ object: THREE$1.Object3D
293
+ handlers: Pick<EventHandlers, 'onFramed' | 'onOccluded' | 'onVisible'>
294
+ lastFramedState: boolean | null
295
+ lastOccludedState: boolean | null
296
+ lastVisibleState: boolean | null
297
+ }
298
+
299
+ //* Scheduler Types (useFrame) ==============================
300
+ //
301
+ // The generic, framework-agnostic scheduler types now live in @pmndrs/scheduler.
302
+ // This file re-exports them and layers r3f's RootState-aware frame state on top,
303
+ // so existing `#types` imports across the codebase keep resolving unchanged.
304
+
305
+
306
+
307
+ // Frame State (r3f-specific) --------------------------------
308
+
309
+ /**
310
+ * State passed to useFrame callbacks (extends RootState with timing).
311
+ */
312
+ interface FrameNextState extends RootState, FrameTimingState {}
313
+
314
+ /** Alias for FrameNextState */
315
+ type FrameState = FrameNextState
316
+
317
+ // Callback Types (r3f-specific) --------------------------------
318
+
319
+ /**
320
+ * Callback function for useFrame. Receives the full r3f RootState plus timing.
321
+ */
322
+ type FrameNextCallback = FrameCallback$1<RootState>
323
+
324
+ /** Alias for FrameNextCallback */
325
+ type FrameCallback = FrameNextCallback
326
+
327
+ //* Buffer Types (useBuffers) ========================================
328
+
329
+ /**
330
+ * Buffer-like types for GPU compute and storage operations.
331
+ * Includes raw CPU arrays, Three.js buffer attributes, and TSL buffer nodes.
332
+ *
333
+ * @example
334
+ * ```tsx
335
+ * const { positions, velocities } = useBuffers(() => ({
336
+ * positions: instancedArray(count, 'vec3'), // StorageBufferNode
337
+ * velocities: new Float32Array(count * 3), // TypedArray
338
+ * }), 'particles')
339
+ * ```
340
+ */
341
+ type BufferLike =
342
+ | Float32Array
343
+ | Uint32Array
344
+ | Int32Array
345
+ | Float64Array
346
+ | Uint8Array
347
+ | Int8Array
348
+ | Uint16Array
349
+ | Int16Array
350
+ | THREE$1.BufferAttribute // Base class for all buffer attributes
351
+ | Node // TSL buffer nodes (instancedArray, storage)
352
+
353
+ /** Flat record of buffer-like values (no nested scopes) */
354
+ type BufferRecord = Record<string, BufferLike>
355
+
356
+ /**
357
+ * Buffer store that can contain both root-level buffers and scoped buffer objects.
358
+ * Structure: { positions: Float32Array, particles: { vel: StorageBufferNode } }
359
+ */
360
+ type BufferStore = Record<string, BufferLike | BufferRecord>
361
+
362
+ //* Storage Types (useGPUStorage) ========================================
363
+
364
+ /**
365
+ * GPU storage types for texture-based storage operations.
366
+ * Includes Three.js storage textures and TSL storage texture nodes.
367
+ *
368
+ * @example
369
+ * ```tsx
370
+ * const { heightMap } = useGPUStorage(() => ({
371
+ * heightMap: new StorageTexture(512, 512),
372
+ * }), 'terrain')
373
+ * ```
374
+ */
375
+ type StorageLike =
376
+ | StorageTexture // GPU storage texture
377
+ | Data3DTexture // 3D texture (can be used as storage)
378
+ | Node // TSL storage texture nodes (storageTexture)
379
+
380
+ /** Flat record of storage-like values (no nested scopes) */
381
+ type StorageRecord = Record<string, StorageLike>
382
+
383
+ /**
384
+ * Storage store that can contain both root-level storage and scoped storage objects.
385
+ * Structure: { heightMap: StorageTexture, terrain: { normal: StorageTextureNode } }
386
+ */
387
+ type StorageStore = Record<string, StorageLike | StorageRecord>
388
+
389
+ //* Renderer Types ========================================
390
+
391
+ /** Default renderer type - union of WebGL and WebGPU renderers */
392
+ type R3FRenderer = THREE$1.WebGLRenderer | WebGPURenderer$1
393
+
394
+ //* Core Store Types ========================================
395
+
396
+ type Subscription = {
397
+ ref: React$1.RefObject<RenderCallback>
398
+ priority: number
399
+ store: RootStore
400
+ }
401
+
402
+ /** Per-pointer state for multi-touch and XR support */
403
+ type PointerState = {
404
+ /** Objects currently hovered by this pointer */
405
+ hovered: Map<string, ThreeEvent<DomEvent>>
406
+ /** Objects capturing this pointer */
407
+ captured: Map<THREE$1.Object3D, PointerCaptureTarget>
408
+ /** Initial click position [x, y] */
409
+ initialClick: [x: number, y: number]
410
+ /** Objects hit on initial click */
411
+ initialHits: THREE$1.Object3D[]
412
+ }
413
+
414
+ type Dpr = number | [min: number, max: number]
415
+
416
+ interface Size {
417
+ width: number
418
+ height: number
419
+ top: number
420
+ left: number
421
+ }
422
+
423
+ type Frameloop = 'always' | 'demand' | 'never'
424
+
425
+ interface Viewport extends Size {
426
+ /** The initial pixel ratio */
427
+ initialDpr: number
428
+ /** Current pixel ratio */
429
+ dpr: number
430
+ /** size.width / viewport.width */
431
+ factor: number
432
+ /** Camera distance */
433
+ distance: number
434
+ /** Camera aspect ratio: width / height */
435
+ aspect: number
436
+ }
437
+
438
+ type RenderCallback = (state: RootState, delta: number, frame?: XRFrame) => void
439
+
440
+ interface Performance {
441
+ /** Current performance normal, between min and max */
442
+ current: number
443
+ /** How low the performance can go, between 0 and max */
444
+ min: number
445
+ /** How high the performance can go, between min and max */
446
+ max: number
447
+ /** Time until current returns to max in ms */
448
+ debounce: number
449
+ /** Sets current to min, puts the system in regression */
450
+ regress: () => void
451
+ }
452
+
453
+ interface InternalState {
454
+ interaction: THREE$1.Object3D[]
455
+ subscribers: Subscription[]
456
+ /** Per-pointer state (hover, capture, click tracking) - replaces hovered, capturedMap, initialClick, initialHits */
457
+ pointerMap: Map<number, PointerState>
458
+ /** Pointers needing raycast this frame (used with frameTimedRaycasts) */
459
+ pointerDirty: Map<number, DomEvent>
460
+ /** Last event received (for events.update() compatibility) */
461
+ lastEvent: React$1.RefObject<DomEvent | null>
462
+ /** @deprecated Use pointerMap.get(pointerId).hovered instead */
463
+ hovered: Map<string, ThreeEvent<DomEvent>>
464
+ /** @deprecated Use pointerMap.get(pointerId).captured instead */
465
+ capturedMap: Map<number, Map<THREE$1.Object3D, PointerCaptureTarget>>
466
+ /** @deprecated Use pointerMap.get(pointerId).initialClick instead */
467
+ initialClick: [x: number, y: number]
468
+ /** @deprecated Use pointerMap.get(pointerId).initialHits instead */
469
+ initialHits: THREE$1.Object3D[]
470
+ /** Visibility event registry (onFramed, onOccluded, onVisible) */
471
+ visibilityRegistry: Map<string, VisibilityEntry>
472
+ /** Whether occlusion queries are enabled (WebGPU only) */
473
+ occlusionEnabled: boolean
474
+ /** Reference to the invisible occlusion observer mesh */
475
+ occlusionObserver: THREE$1.Mesh | null
476
+ /** Cached occlusion results from render pass - keyed by Object3D */
477
+ occlusionCache: Map<THREE$1.Object3D, boolean | null>
478
+ /** Internal helper group for R3F system objects (occlusion observer, etc.) */
479
+ helperGroup: THREE$1.Group | null
480
+ active: boolean
481
+ priority: number
482
+ frames: number
483
+ subscribe: (callback: React$1.RefObject<RenderCallback>, priority: number, store: RootStore) => () => void
484
+ /** Internal renderer storage - use state.renderer or state.gl to access */
485
+ actualRenderer: R3FRenderer
486
+ /** Global scheduler reference (for useFrame hook) */
487
+ scheduler: SchedulerApi | null
488
+ /** This root's unique ID in the global scheduler */
489
+ rootId?: string
490
+ /** Function to unregister this root from the global scheduler */
491
+ unregisterRoot?: () => void
492
+ /** Container for child attachment (scene for root, original container for portals) */
493
+ container?: THREE$1.Object3D
494
+ /**
495
+ * CanvasTarget for multi-canvas WebGPU rendering.
496
+ * Created for all WebGPU canvases to support renderer sharing.
497
+ * @see https://threejs.org/docs/#api/en/renderers/common/CanvasTarget
498
+ */
499
+ canvasTarget?: CanvasTarget
500
+ /**
501
+ * Set when this root's canvas target has been resized and the backend's cached render pass
502
+ * descriptor (which holds a depth-stencil view built once per canvas) is therefore stale.
503
+ *
504
+ * Flushed by the canvas-target job in the `start` phase, which is the only place this root's
505
+ * target is guaranteed to be the renderer's active one — `backend.updateSize()` operates on
506
+ * whatever `getCanvasTarget()` returns, so calling it from the resize subscription would
507
+ * invalidate some other canvas's descriptor instead.
508
+ *
509
+ * @see https://github.com/pmndrs/react-three-fiber/issues/3847
510
+ */
511
+ canvasTargetSizeDirty?: boolean
512
+ /**
513
+ * Whether multi-canvas rendering is active.
514
+ * True when any canvas uses `renderer={{ primaryCanvas: 'id' }}` to share a renderer.
515
+ * When true, setCanvasTarget is called before each render.
516
+ */
517
+ isMultiCanvas?: boolean
518
+ /**
519
+ * Whether this canvas is a secondary canvas sharing another's renderer.
520
+ * True when `target` prop is used.
521
+ */
522
+ isSecondary?: boolean
523
+ /**
524
+ * The id of the primary canvas this secondary canvas targets.
525
+ * Only set when isSecondary is true.
526
+ */
527
+ targetId?: string
528
+ /**
529
+ * Function to unregister this primary canvas from the registry.
530
+ * Only set when this canvas has an `id` prop.
531
+ */
532
+ unregisterPrimary?: () => void
533
+ /** Whether canvas dimensions are forced to even numbers */
534
+ forceEven?: boolean
535
+ }
536
+
537
+ interface XRManager {
538
+ connect: () => void
539
+ disconnect: () => void
540
+ }
541
+
542
+ //* Root State Interface ====================================
543
+
544
+ interface RootState {
545
+ /** Set current state */
546
+ set: StoreApi<RootState>['setState']
547
+ /** Get current state */
548
+ get: StoreApi<RootState>['getState']
549
+ /**
550
+ * Reference to the authoritative store for shared TSL resources (uniforms, nodes, etc).
551
+ * - For primary/independent canvases: points to its own store (self-reference)
552
+ * - For secondary canvases: points to the primary canvas's store
553
+ *
554
+ * Hooks like useNodes/useUniforms should read from primaryStore to ensure
555
+ * consistent shared state across all canvases sharing a renderer.
556
+ */
557
+ primaryStore: RootStore
558
+ /** @deprecated Use `renderer` instead. The instance of the renderer (typed as WebGLRenderer for backwards compat) */
559
+ gl: THREE$1.WebGLRenderer
560
+ /** The renderer instance - type depends on entry point (WebGPU, Legacy, or union for default) */
561
+ renderer: R3FRenderer
562
+ /** Inspector of the webGPU Renderer. Init in the canvas */
563
+ inspector: any // Inspector type from three/webgpu
564
+
565
+ /** Default camera */
566
+ camera: ThreeCamera
567
+ /** Camera frustum for visibility checks - auto-updated each frame when autoUpdateFrustum is true */
568
+ frustum: THREE$1.Frustum
569
+ /** Whether to automatically update the frustum each frame (default: true) */
570
+ autoUpdateFrustum: boolean
571
+ /** Default scene (may be overridden in portals to point to the portal container) */
572
+ scene: THREE$1.Scene
573
+ /** The actual root THREE.Scene - always points to the true scene, even inside portals */
574
+ rootScene: THREE$1.Scene
575
+ /** Default raycaster */
576
+ raycaster: THREE$1.Raycaster
577
+ /** Event layer interface, contains the event handler and the node they're connected to */
578
+ events: EventManager<any>
579
+ /** XR interface */
580
+ xr: XRManager
581
+ /** Currently used controls */
582
+ controls: THREE$1.EventDispatcher | null
583
+ /** Normalized event coordinates */
584
+ pointer: THREE$1.Vector2
585
+ /** @deprecated Normalized event coordinates, use "pointer" instead! */
586
+ mouse: THREE$1.Vector2
587
+ /** Color space assigned to 8-bit input textures (color maps). Most textures are authored in sRGB. */
588
+ textureColorSpace: THREE$1.ColorSpace
589
+ /** Render loop flags */
590
+ frameloop: Frameloop
591
+ performance: Performance
592
+ /** Reactive pixel-size of the canvas */
593
+ size: Size
594
+ /** Reactive size of the viewport in threejs units */
595
+ viewport: Viewport & {
596
+ getCurrentViewport: (
597
+ camera?: ThreeCamera,
598
+ target?: THREE$1.Vector3 | Parameters<THREE$1.Vector3['set']>,
599
+ size?: Size,
600
+ ) => Omit<Viewport, 'dpr' | 'initialDpr'>
601
+ }
602
+ /** Flags the canvas for render, but doesn't render in itself */
603
+ invalidate: (frames?: number, stackFrames?: boolean) => void
604
+ /** Advance (render) one step */
605
+ advance: (timestamp: number, runGlobalEffects?: boolean) => void
606
+ /** Shortcut to setting the event layer */
607
+ setEvents: (events: Partial<EventManager<any>>) => void
608
+ /** Shortcut to manual sizing. No args resets to props/container. Single arg creates square. */
609
+ setSize: (width?: number, height?: number, top?: number, left?: number) => void
610
+ /** Shortcut to manual setting the pixel ratio */
611
+ setDpr: (dpr: Dpr) => void
612
+ /** Shortcut to setting frameloop flags. No args resets to 'always'. */
613
+ setFrameloop: (frameloop?: Frameloop) => void
614
+ /** Set error state to propagate to error boundary */
615
+ setError: (error: Error | null) => void
616
+ /** Current error state (null when no error) */
617
+ error: Error | null
618
+ /** Global TSL uniform nodes - root-level uniforms + scoped sub-objects. Use useUniforms() hook */
619
+ uniforms: UniformStore
620
+ /** Global TSL nodes - root-level nodes + scoped sub-objects. Use useNodes() hook */
621
+ nodes: Record<string, any>
622
+ /** Global TSL buffer nodes - root-level buffers + scoped sub-objects. Use useBuffers() hook */
623
+ buffers: BufferStore
624
+ /** Global GPU storage (textures, etc.) - root-level storage + scoped sub-objects. Use useGPUStorage() hook */
625
+ gpuStorage: StorageStore
626
+ /** Global Texture registry (key → Texture, usually keyed by URL) - use useTextures() hook for access + lifecycle */
627
+ textures: Map<string, THREE$1.Texture>
628
+ /** Internal: refcount per texture key, driven by mounted useTexture consumers (registry enrollment is on by default) */
629
+ _textureRefs: Map<string, number>
630
+ /** WebGPU RenderPipeline instance - use useRenderPipeline() hook */
631
+ renderPipeline: ThreeRenderPipeline | null
632
+ /** Global TSL pass nodes for render pipeline - use useRenderPipeline() hook */
633
+ passes: Record<string, any>
634
+ /** Internal version counter for HMR - incremented by rebuildNodes/rebuildUniforms to bust memoization */
635
+ _hmrVersion: number
636
+ /** Internal: whether setSize() has taken ownership of canvas dimensions */
637
+ _sizeImperative: boolean
638
+ /** Internal: stored size props from Canvas for reset functionality */
639
+ _sizeProps: { width?: number; height?: number } | null
640
+ /** When the canvas was clicked but nothing was hit */
641
+ onPointerMissed?: (event: MouseEvent) => void
642
+ /** When a dragover event has missed any target */
643
+ onDragOverMissed?: (event: DragEvent) => void
644
+ /** When a drop event has missed any target */
645
+ onDropMissed?: (event: DragEvent) => void
646
+ /** If this state model is layered (via createPortal) then this contains the previous layer */
647
+ previousRoot?: RootStore
648
+ /** Internals */
649
+ internal: InternalState
650
+ // flags for triggers
651
+ // if we are using the webGl renderer, this will be true
652
+ isLegacy: boolean
653
+ // regardless of renderer, if the system supports webGpu, this will be true
654
+ webGPUSupported: boolean
655
+ //if we are on native
656
+ isNative: boolean
657
+ }
658
+
661
659
  type RootStore = UseBoundStoreWithEqualityFn<StoreApi<RootState>>
662
660
 
663
- //* Base Renderer Types =====================================
664
-
665
- // Shim for OffscreenCanvas since it was removed from DOM types
666
- interface OffscreenCanvas$1 extends EventTarget {}
667
-
668
- interface BaseRendererProps {
669
- canvas: HTMLCanvasElement | OffscreenCanvas$1
670
- powerPreference?: 'high-performance' | 'low-power' | 'default'
671
- antialias?: boolean
672
- alpha?: boolean
673
- }
674
-
675
- type RendererFactory<TRenderer, TParams> =
676
- | TRenderer
677
- | ((defaultProps: TParams) => TRenderer)
678
- | ((defaultProps: TParams) => Promise<TRenderer>)
679
-
680
- interface Renderer {
681
- render: (scene: THREE$1.Scene, camera: THREE$1.Camera) => any
682
- }
683
-
684
- //* WebGL Renderer Props ==============================
685
-
686
- type DefaultGLProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & {
687
- canvas: HTMLCanvasElement | OffscreenCanvas$1
688
- }
689
-
690
- type GLProps =
691
- | Renderer
692
- | ((defaultProps: DefaultGLProps) => Renderer)
693
- | ((defaultProps: DefaultGLProps) => Promise<Renderer>)
694
- | Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters>
695
-
696
- //* WebGPU Renderer Props ==============================
697
-
698
- type DefaultRendererProps = {
699
- canvas: HTMLCanvasElement | OffscreenCanvas$1
700
- [key: string]: any
701
- }
702
-
703
- type RendererProps =
704
- | any // WebGPURenderer
705
- | ((defaultProps: DefaultRendererProps) => any)
706
- | ((defaultProps: DefaultRendererProps) => Promise<any>)
707
- | Partial<Properties<any> | Record<string, any>>
708
-
709
- //* Camera Props ==============================
710
-
711
- type CameraProps = (
712
- | THREE$1.Camera
713
- | Partial<
714
- ThreeElement<typeof THREE$1.Camera> &
715
- ThreeElement<typeof THREE$1.PerspectiveCamera> &
716
- ThreeElement<typeof THREE$1.OrthographicCamera>
717
- >
718
- ) & {
719
- /** Flags the camera as manual, putting projection into your own hands */
720
- manual?: boolean
721
- }
722
-
723
- //* Render Props ==============================
724
-
725
- interface RenderProps<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
726
- /** A threejs renderer instance or props that go into the default renderer */
727
- gl?: GLProps
728
- /** A WebGPU renderer instance or props that go into the default renderer */
729
- renderer?: RendererProps
730
- /** Dimensions to fit the renderer to. Will measure canvas dimensions if omitted */
731
- size?: Size
732
- /**
733
- * Enables shadows (by default PCFsoft). Can accept `gl.shadowMap` options for fine-tuning,
734
- * but also strings: 'basic' | 'percentage' | 'soft' | 'variance'.
735
- * @see https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
736
- */
737
- shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
738
- /**
739
- * Disables three r139 color management.
740
- * @see https://threejs.org/docs/#manual/en/introduction/Color-management
741
- */
742
- legacy?: boolean
743
- /** Switch off automatic sRGB encoding and gamma correction */
744
- linear?: boolean
745
- /** Use `THREE.NoToneMapping` instead of `THREE.ACESFilmicToneMapping` */
746
- flat?: boolean
747
- /** Working color space for automatic texture colorspace assignment. Defaults to THREE.SRGBColorSpace */
748
- /** Color space assigned to 8-bit input textures (color maps). Defaults to sRGB. Most textures are authored in sRGB. */
749
- textureColorSpace?: THREE$1.ColorSpace
750
- /** Creates an orthographic camera */
751
- orthographic?: boolean
752
- /**
753
- * R3F's render mode. Set to `demand` to only render on state change or `never` to take control.
754
- * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#on-demand-rendering
755
- */
756
- frameloop?: Frameloop
757
- /**
758
- * R3F performance options for adaptive performance.
759
- * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#movement-regression
760
- */
761
- performance?: Partial<Omit<Performance, 'regress'>>
762
- /** Target pixel ratio. Can clamp between a range: `[min, max]` */
763
- dpr?: Dpr
764
- /** Props that go into the default raycaster */
765
- raycaster?: Partial<THREE$1.Raycaster>
766
- /** A `THREE.Scene` instance or props that go into the default scene */
767
- scene?: THREE$1.Scene | Partial<THREE$1.Scene>
768
- /** A `THREE.Camera` instance or props that go into the default camera */
769
- camera?: CameraProps
770
- /** An R3F event manager to manage elements' pointer events */
771
- events?: (store: RootStore) => EventManager<HTMLElement>
772
- /** Callback after the canvas has rendered (but not yet committed) */
773
- onCreated?: (state: RootState) => void
774
- /** Response for pointer clicks that have missed any target */
775
- onPointerMissed?: (event: MouseEvent) => void
776
- /** Response for dragover events that have missed any target */
777
- onDragOverMissed?: (event: DragEvent) => void
778
- /** Response for drop events that have missed any target */
779
- onDropMissed?: (event: DragEvent) => void
780
- /** Whether to automatically update the frustum each frame (default: true) */
781
- autoUpdateFrustum?: boolean
782
- /**
783
- * Enable WebGPU occlusion queries for onOccluded/onVisible events.
784
- * Auto-enabled when any object uses onOccluded or onVisible handlers.
785
- * Only works with WebGPU renderer - WebGL will log a warning.
786
- */
787
- occlusion?: boolean
788
- /** Internal: stored size props from Canvas for reset functionality */
789
- _sizeProps?: { width?: number; height?: number } | null
790
- }
791
-
792
- //* Reconciler Root ==============================
793
-
794
- interface ReconcilerRoot<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
795
- configure: (config?: RenderProps<TCanvas>) => Promise<ReconcilerRoot<TCanvas>>
796
- render: (element: ReactNode) => RootStore
797
- unmount: () => void
798
- }
799
-
800
- //* Inject State ==============================
801
-
802
- type InjectState = Partial<
803
- Omit<RootState, 'events'> & {
804
- events?: {
805
- enabled?: boolean
806
- priority?: number
807
- compute?: ComputeFunction
808
- connected?: any
809
- }
810
- /**
811
- * When true (default), injects a THREE.Scene between container and children if container isn't already a Scene.
812
- * This ensures state.scene is always a real THREE.Scene with proper properties (background, environment, fog).
813
- * Set to false to use the container directly as scene (anti-pattern, but supported for edge cases).
814
- */
815
- injectScene?: boolean
816
- }
661
+ //* Base Renderer Types =====================================
662
+
663
+ // Shim for OffscreenCanvas since it was removed from DOM types
664
+ interface OffscreenCanvas$1 extends EventTarget {}
665
+
666
+ interface BaseRendererProps {
667
+ canvas: HTMLCanvasElement | OffscreenCanvas$1
668
+ powerPreference?: 'high-performance' | 'low-power' | 'default'
669
+ antialias?: boolean
670
+ alpha?: boolean
671
+ }
672
+
673
+ type RendererFactory<TRenderer, TParams> =
674
+ | TRenderer
675
+ | ((defaultProps: TParams) => TRenderer)
676
+ | ((defaultProps: TParams) => Promise<TRenderer>)
677
+
678
+ interface Renderer {
679
+ render: (scene: THREE$1.Scene, camera: THREE$1.Camera) => any
680
+ }
681
+
682
+ //* Color Management Config ==============================
683
+
684
+ /**
685
+ * Color management configuration shared by both WebGL and WebGPU renderers.
686
+ */
687
+ interface ColorManagementConfig {
688
+ /**
689
+ * Color space assigned to 8-bit input textures (color maps).
690
+ * Defaults to sRGB. Most textures are authored in sRGB.
691
+ * @default THREE.SRGBColorSpace
692
+ */
693
+ textureColorSpace?: THREE$1.ColorSpace
694
+ }
695
+
696
+ //* WebGL Renderer Props ==============================
697
+
698
+ type DefaultGLProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & {
699
+ canvas: HTMLCanvasElement | OffscreenCanvas$1
700
+ }
701
+
702
+ type GLProps =
703
+ | Renderer
704
+ | ((defaultProps: DefaultGLProps) => Renderer)
705
+ | ((defaultProps: DefaultGLProps) => Promise<Renderer>)
706
+ | (Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters> & ColorManagementConfig)
707
+
708
+ //* WebGPU Renderer Props ==============================
709
+
710
+ type DefaultRendererProps = {
711
+ canvas: HTMLCanvasElement | OffscreenCanvas$1
712
+ [key: string]: any
713
+ }
714
+
715
+ /**
716
+ * Canvas-level scheduler configuration.
717
+ * Controls render timing relative to other canvases.
718
+ */
719
+ interface CanvasSchedulerConfig {
720
+ /**
721
+ * Run this Canvas root before the referenced Canvas root id(s).
722
+ */
723
+ before?: string | string[]
724
+ /**
725
+ * Run this Canvas root after the referenced Canvas root id(s).
726
+ */
727
+ after?: string | string[]
728
+ /**
729
+ * Numeric root order. Lower values run first.
730
+ */
731
+ order?: number
732
+ /**
733
+ * Limit this Canvas's default render job (frames per second).
734
+ */
735
+ fps?: number
736
+ }
737
+
738
+ /**
739
+ * Extended renderer configuration for multi-canvas support and color management.
740
+ */
741
+ interface RendererConfigExtended extends ColorManagementConfig {
742
+ /** Share renderer from another canvas (WebGPU only) */
743
+ primaryCanvas?: string
744
+ /** Canvas-level scheduler options */
745
+ scheduler?: CanvasSchedulerConfig
746
+ }
747
+
748
+ type RendererProps =
749
+ | any // WebGPURenderer
750
+ | ((defaultProps: DefaultRendererProps) => any)
751
+ | ((defaultProps: DefaultRendererProps) => Promise<any>)
752
+ | (Partial<Properties<any> | Record<string, any>> & RendererConfigExtended)
753
+
754
+ //* Camera Props ==============================
755
+
756
+ type CameraProps = (
757
+ | THREE$1.Camera
758
+ | Partial<
759
+ ThreeElement<typeof THREE$1.Camera> &
760
+ ThreeElement<typeof THREE$1.PerspectiveCamera> &
761
+ ThreeElement<typeof THREE$1.OrthographicCamera>
762
+ >
763
+ ) & {
764
+ /** Flags the camera as manual, putting projection into your own hands */
765
+ manual?: boolean
766
+ }
767
+
768
+ //* Render Props ==============================
769
+
770
+ interface RenderProps<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
771
+ /**
772
+ * Unique identifier for multi-canvas renderer sharing.
773
+ * Makes this canvas targetable by other canvases using the `primaryCanvas` prop.
774
+ * Also sets the HTML `id` attribute on the canvas element.
775
+ * @example <Canvas id="main-viewer">...</Canvas>
776
+ */
777
+ id?: string
778
+ /**
779
+ * Share the renderer from another canvas instead of creating a new one.
780
+ * Pass the `id` of the primary canvas to share its WebGPURenderer.
781
+ * Only available with WebGPU (not legacy WebGL).
782
+ *
783
+ * Note: This is extracted from `renderer={{ primaryCanvas: "id" }}` by Canvas.
784
+ * @internal
785
+ */
786
+ primaryCanvas?: string
787
+ /**
788
+ * Canvas-level scheduler options. Controls render timing relative to other canvases.
789
+ *
790
+ * Note: This is extracted from `renderer={{ scheduler: {...} }}` by Canvas.
791
+ * @internal
792
+ */
793
+ scheduler?: CanvasSchedulerConfig
794
+ /** A threejs renderer instance or props that go into the default renderer */
795
+ gl?: GLProps
796
+ /** A WebGPU renderer instance or props that go into the default renderer */
797
+ renderer?: RendererProps
798
+ /** Dimensions to fit the renderer to. Will measure canvas dimensions if omitted */
799
+ size?: Size
800
+ /**
801
+ * Enables shadows (by default PCFsoft). Can accept `gl.shadowMap` options for fine-tuning,
802
+ * but also strings: 'basic' | 'percentage' | 'soft' | 'variance'.
803
+ * @see https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
804
+ */
805
+ shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
806
+ /** Creates an orthographic camera */
807
+ orthographic?: boolean
808
+ /**
809
+ * R3F's render mode. Set to `demand` to only render on state change or `never` to take control.
810
+ * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#on-demand-rendering
811
+ */
812
+ frameloop?: Frameloop
813
+ /**
814
+ * R3F performance options for adaptive performance.
815
+ * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#movement-regression
816
+ */
817
+ performance?: Partial<Omit<Performance, 'regress'>>
818
+ /** Target pixel ratio. Can clamp between a range: `[min, max]` */
819
+ dpr?: Dpr
820
+ /** Props that go into the default raycaster */
821
+ raycaster?: Partial<THREE$1.Raycaster>
822
+ /** A `THREE.Scene` instance or props that go into the default scene */
823
+ scene?: THREE$1.Scene | Partial<THREE$1.Scene>
824
+ /** A `THREE.Camera` instance or props that go into the default camera */
825
+ camera?: CameraProps
826
+ /** An R3F event manager to manage elements' pointer events */
827
+ events?: (store: RootStore) => EventManager<HTMLElement>
828
+ /** Callback after the canvas has rendered (but not yet committed) */
829
+ onCreated?: (state: RootState) => void
830
+ /** Response for pointer clicks that have missed any target */
831
+ onPointerMissed?: (event: MouseEvent) => void
832
+ /** Response for dragover events that have missed any target */
833
+ onDragOverMissed?: (event: DragEvent) => void
834
+ /** Response for drop events that have missed any target */
835
+ onDropMissed?: (event: DragEvent) => void
836
+ /** Whether to automatically update the frustum each frame (default: true) */
837
+ autoUpdateFrustum?: boolean
838
+ /**
839
+ * Enable WebGPU occlusion queries for onOccluded/onVisible events.
840
+ * Auto-enabled when any object uses onOccluded or onVisible handlers.
841
+ * Only works with WebGPU renderer - WebGL will log a warning.
842
+ */
843
+ occlusion?: boolean
844
+ /** Internal: stored size props from Canvas for reset functionality */
845
+ _sizeProps?: { width?: number; height?: number } | null
846
+ /** Force canvas dimensions to even numbers (fixes Safari rendering issues with odd/fractional sizes) */
847
+ forceEven?: boolean
848
+ }
849
+
850
+ //* Reconciler Root ==============================
851
+
852
+ interface ReconcilerRoot<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
853
+ configure: (config?: RenderProps<TCanvas>) => Promise<ReconcilerRoot<TCanvas>>
854
+ render: (element: ReactNode) => RootStore
855
+ unmount: () => void
856
+ }
857
+
858
+ //* Inject State ==============================
859
+
860
+ type InjectState = Partial<
861
+ Omit<RootState, 'events'> & {
862
+ events?: {
863
+ enabled?: boolean
864
+ priority?: number
865
+ compute?: ComputeFunction
866
+ connected?: any
867
+ }
868
+ /**
869
+ * When true (default), injects a THREE.Scene between container and children if container isn't already a Scene.
870
+ * This ensures state.scene is always a real THREE.Scene with proper properties (background, environment, fog).
871
+ * Set to false to use the container directly as scene (anti-pattern, but supported for edge cases).
872
+ */
873
+ injectScene?: boolean
874
+ }
817
875
  >
818
876
 
819
- //* Reconciler Types ==============================
820
-
821
- // FiberRoot is an opaque internal React type - we define it locally
822
- // to avoid bundling @types/react-reconciler which causes absolute path issues
823
- type FiberRoot = any
824
-
825
- interface Root {
826
- fiber: FiberRoot
827
- store: RootStore
828
- }
829
-
830
- type AttachFnType<O = any> = (parent: any, self: O) => () => void
831
- type AttachType<O = any> = string | AttachFnType<O>
832
-
833
- type ConstructorRepresentation<T = any> = new (...args: any[]) => T
834
-
835
- interface Catalogue {
836
- [name: string]: ConstructorRepresentation
837
- }
838
-
839
- // TODO: handle constructor overloads
840
- // https://github.com/pmndrs/react-three-fiber/pull/2931
841
- // https://github.com/microsoft/TypeScript/issues/37079
842
- type Args<T> = T extends ConstructorRepresentation
843
- ? T extends typeof Color$1
844
- ? [r: number, g: number, b: number] | [color: ColorRepresentation]
845
- : ConstructorParameters<T>
846
- : any[]
847
-
848
- type ArgsProp<P> = P extends ConstructorRepresentation
849
- ? IsAllOptional<ConstructorParameters<P>> extends true
850
- ? { args?: Args<P> }
851
- : { args: Args<P> }
852
- : { args: unknown[] }
853
-
854
- type InstanceProps<T = any, P = any> = ArgsProp<P> & {
855
- object?: T
856
- dispose?: null
857
- attach?: AttachType<T>
858
- onUpdate?: (self: T) => void
859
- }
860
-
861
- interface Instance<O = any> {
862
- root: RootStore
863
- type: string
864
- parent: Instance | null
865
- children: Instance[]
866
- props: InstanceProps<O> & Record<string, unknown>
867
- object: O & { __r3f?: Instance<O> }
868
- eventCount: number
869
- handlers: Partial<EventHandlers>
870
- attach?: AttachType<O>
871
- previousAttach?: any
872
- isHidden: boolean
873
- }
874
-
875
- interface HostConfig {
876
- type: string
877
- props: Instance['props']
878
- container: RootStore
879
- instance: Instance
880
- textInstance: void
881
- suspenseInstance: Instance
882
- hydratableInstance: never
883
- formInstance: never
884
- publicInstance: Instance['object']
885
- hostContext: {}
886
- childSet: never
887
- timeoutHandle: number | undefined
888
- noTimeout: -1
889
- TransitionStatus: null
890
- }
891
- declare global {
892
- var IS_REACT_ACT_ENVIRONMENT: boolean | undefined
893
- }
894
-
895
- //* Loop Types ==============================
896
-
897
- type GlobalRenderCallback = (timestamp: number) => void
898
-
877
+ //* Reconciler Types ==============================
878
+
879
+ // FiberRoot is an opaque internal React type - we define it locally
880
+ // to avoid bundling @types/react-reconciler which causes absolute path issues
881
+ type FiberRoot = any
882
+
883
+ interface Root {
884
+ fiber: FiberRoot
885
+ store: RootStore
886
+ }
887
+
888
+ type AttachFnType<O = any> = (parent: any, self: O) => () => void
889
+ type AttachType<O = any> = string | AttachFnType<O>
890
+
891
+ type ConstructorRepresentation<T = any> = new (...args: any[]) => T
892
+
893
+ interface Catalogue {
894
+ [name: string]: ConstructorRepresentation
895
+ }
896
+
897
+ // TODO: handle constructor overloads
898
+ // https://github.com/pmndrs/react-three-fiber/pull/2931
899
+ // https://github.com/microsoft/TypeScript/issues/37079
900
+ type Args<T> = T extends ConstructorRepresentation
901
+ ? T extends typeof Color$1
902
+ ? [r: number, g: number, b: number] | [color: ColorRepresentation]
903
+ : ConstructorParameters<T>
904
+ : any[]
905
+
906
+ type ArgsProp<P> = P extends ConstructorRepresentation
907
+ ? IsAllOptional<ConstructorParameters<P>> extends true
908
+ ? { args?: Args<P> }
909
+ : { args: Args<P> }
910
+ : { args: unknown[] }
911
+
912
+ type InstanceProps<T = any, P = any> = ArgsProp<P> & {
913
+ object?: T
914
+ dispose?: null
915
+ attach?: AttachType<T>
916
+ onUpdate?: (self: T) => void
917
+ }
918
+
919
+ interface Instance<O = any> {
920
+ root: RootStore
921
+ type: string
922
+ parent: Instance | null
923
+ children: Instance[]
924
+ props: InstanceProps<O> & Record<string, unknown>
925
+ object: O & { __r3f?: Instance<O> }
926
+ eventCount: number
927
+ handlers: Partial<EventHandlers>
928
+ attach?: AttachType<O>
929
+ previousAttach?: any
930
+ isHidden: boolean
931
+ /** Set of props that have been applied via once() */
932
+ appliedOnce?: Set<string>
933
+ }
934
+
935
+ interface HostConfig {
936
+ type: string
937
+ props: Instance['props']
938
+ container: RootStore
939
+ instance: Instance
940
+ textInstance: void
941
+ suspenseInstance: Instance
942
+ hydratableInstance: never
943
+ formInstance: never
944
+ publicInstance: Instance['object']
945
+ hostContext: {}
946
+ childSet: never
947
+ timeoutHandle: number | undefined
948
+ noTimeout: -1
949
+ TransitionStatus: null
950
+ }
951
+ declare global {
952
+ var IS_REACT_ACT_ENVIRONMENT: boolean | undefined
953
+ }
954
+
955
+ //* Loop Types ==============================
956
+
957
+ type GlobalRenderCallback = (timestamp: number) => void
958
+
899
959
  type GlobalEffectType = 'before' | 'after' | 'tail'
900
960
 
901
- //* Canvas Types ==============================
902
-
903
- interface CanvasProps
904
- extends Omit<RenderProps<HTMLCanvasElement>, 'size'>, React$1.HTMLAttributes<HTMLDivElement> {
905
- children?: React$1.ReactNode
906
- ref?: React$1.Ref<HTMLCanvasElement>
907
- /** Canvas fallback content, similar to img's alt prop */
908
- fallback?: React$1.ReactNode
909
- /**
910
- * Options to pass to useMeasure.
911
- * @see https://github.com/pmndrs/react-use-measure#api
912
- */
913
- resize?: Options
914
- /** The target where events are being subscribed to, default: the div that wraps canvas */
915
- eventSource?: HTMLElement | React$1.RefObject<HTMLElement>
916
- /** The event prefix that is cast into canvas pointer x/y events, default: "offset" */
917
- eventPrefix?: 'offset' | 'client' | 'page' | 'layer' | 'screen'
918
- /** Enable/disable automatic HMR refresh for TSL nodes and uniforms, default: true in dev */
919
- hmr?: boolean
920
- /** Canvas resolution width in pixels. If omitted, uses container width. */
921
- width?: number
922
- /** Canvas resolution height in pixels. If omitted, uses container height. */
923
- height?: number
924
- }
925
-
926
- //* Loader Types ==============================
927
-
928
- type InputLike = string | string[] | string[][] | Readonly<string | string[] | string[][]>
929
-
930
- // Define a loader-like interface that matches THREE.Loader's load signature
931
- // This works for both generic and non-generic THREE.Loader instances
932
- interface LoaderLike {
933
- load(
934
- url: InputLike,
935
- onLoad?: (result: any) => void,
936
- onProgress?: (event: ProgressEvent<EventTarget>) => void,
937
- onError?: (error: unknown) => void,
938
- ): any
939
- }
940
-
941
- type GLTFLike = { scene: THREE$1.Object3D }
942
-
943
- type LoaderInstance<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
944
- T extends ConstructorRepresentation<LoaderLike> ? InstanceType<T> : T
945
-
946
- // Infer result type from the load method's callback parameter
947
- type InferLoadResult<T> = T extends {
948
- load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
949
- }
950
- ? R
951
- : T extends ConstructorRepresentation<any>
952
- ? InstanceType<T> extends {
953
- load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
954
- }
955
- ? R
956
- : any
957
- : any
958
-
959
- type LoaderResult<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
960
- InferLoadResult<LoaderInstance<T>> extends infer R ? (R extends GLTFLike ? R & ObjectMap : R) : never
961
-
962
- type Extensions<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> = (
963
- loader: LoaderInstance<T>,
961
+ declare const presetsObj: {
962
+ apartment: string;
963
+ city: string;
964
+ dawn: string;
965
+ forest: string;
966
+ lobby: string;
967
+ night: string;
968
+ park: string;
969
+ studio: string;
970
+ sunset: string;
971
+ warehouse: string;
972
+ };
973
+ type PresetsType = keyof typeof presetsObj;
974
+
975
+ //* Background Types ==============================
976
+
977
+ /**
978
+ * Expanded object form for background configuration.
979
+ * Allows separate textures for background (visual backdrop) and environment (PBR lighting).
980
+ */
981
+ interface BackgroundConfig {
982
+ /** HDRI preset name: 'apartment', 'city', 'dawn', 'forest', 'lobby', 'night', 'park', 'studio', 'sunset', 'warehouse' */
983
+ preset?: PresetsType
984
+ /** Files for cube texture (6 faces) or single HDR/EXR */
985
+ files?: string | string[]
986
+ /** Separate files for scene.background (visual backdrop) */
987
+ backgroundMap?: string | string[]
988
+ backgroundRotation?: Euler$1 | [number, number, number]
989
+ backgroundBlurriness?: number
990
+ backgroundIntensity?: number
991
+ /** Separate files for scene.environment (PBR lighting/reflections) */
992
+ envMap?: string | string[]
993
+ environmentRotation?: Euler$1 | [number, number, number]
994
+ environmentIntensity?: number
995
+ path?: string
996
+ extensions?: (loader: Loader) => void
997
+ }
998
+
999
+ /**
1000
+ * Background prop type for Canvas.
1001
+ *
1002
+ * String detection priority:
1003
+ * 1. Preset - exact match against known presets (apartment, city, dawn, forest, lobby, night, park, studio, sunset, warehouse)
1004
+ * 2. URL - starts with /, ./, ../, http://, https://, OR has image extension
1005
+ * 3. Color - default fallback (CSS color names, hex values, rgb(), etc.)
1006
+ *
1007
+ * @example Color
1008
+ * ```tsx
1009
+ * <Canvas background="red" />
1010
+ * <Canvas background="#ff0000" />
1011
+ * <Canvas background={0xff0000} />
1012
+ * ```
1013
+ *
1014
+ * @example Preset
1015
+ * ```tsx
1016
+ * <Canvas background="city" />
1017
+ * ```
1018
+ *
1019
+ * @example URL
1020
+ * ```tsx
1021
+ * <Canvas background="/path/to/env.hdr" />
1022
+ * <Canvas background="./sky.jpg" />
1023
+ * ```
1024
+ *
1025
+ * @example Object form
1026
+ * ```tsx
1027
+ * <Canvas background={{
1028
+ * files: ['px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'],
1029
+ * backgroundMap: 'path/to/sky.jpg',
1030
+ * envMap: 'path/to/lighting.hdr',
1031
+ * backgroundBlurriness: 0.5,
1032
+ * }} />
1033
+ * ```
1034
+ */
1035
+ type BackgroundProp =
1036
+ | ColorRepresentation // "red", "#ff0000", 0xff0000
1037
+ | string // URL or preset
1038
+ | BackgroundConfig // Expanded object form
1039
+
1040
+ //* Canvas Types ==============================
1041
+
1042
+ interface CanvasProps
1043
+ extends
1044
+ Omit<RenderProps<HTMLCanvasElement>, 'size' | 'primaryCanvas' | 'scheduler'>,
1045
+ React$1.HTMLAttributes<HTMLDivElement> {
1046
+ children?: React$1.ReactNode
1047
+ ref?: React$1.Ref<HTMLCanvasElement>
1048
+ /** Canvas fallback content, similar to img's alt prop */
1049
+ fallback?: React$1.ReactNode
1050
+ /**
1051
+ * Options to pass to useMeasure.
1052
+ * @see https://github.com/pmndrs/react-use-measure#api
1053
+ */
1054
+ resize?: Options
1055
+ /** The target where events are being subscribed to, default: the div that wraps canvas */
1056
+ eventSource?: HTMLElement | React$1.RefObject<HTMLElement | null>
1057
+ /** The event prefix that is cast into canvas pointer x/y events, default: "offset" */
1058
+ eventPrefix?: 'offset' | 'client' | 'page' | 'layer' | 'screen'
1059
+ /** Enable/disable automatic HMR refresh for TSL nodes and uniforms, default: true in dev */
1060
+ hmr?: boolean
1061
+ /** Canvas resolution width in pixels. If omitted, uses container width. */
1062
+ width?: number
1063
+ /** Canvas resolution height in pixels. If omitted, uses container height. */
1064
+ height?: number
1065
+ /** Force canvas dimensions to even numbers (fixes Safari rendering issues with odd/fractional sizes) */
1066
+ forceEven?: boolean
1067
+ /**
1068
+ * Scene background configuration.
1069
+ * Accepts colors, URLs, presets, or an expanded object for separate background/environment.
1070
+ * @see BackgroundProp for full documentation and examples
1071
+ */
1072
+ background?: BackgroundProp
1073
+ }
1074
+
1075
+ //* Loader Types ==============================
1076
+
1077
+ type InputLike = string | string[] | string[][] | Readonly<string | string[] | string[][]>
1078
+
1079
+ // Define a loader-like interface that matches THREE.Loader's load signature
1080
+ // This works for both generic and non-generic THREE.Loader instances
1081
+ interface LoaderLike {
1082
+ load(
1083
+ url: InputLike,
1084
+ onLoad?: (result: any) => void,
1085
+ onProgress?: (event: ProgressEvent<EventTarget>) => void,
1086
+ onError?: (error: unknown) => void,
1087
+ ): any
1088
+ }
1089
+
1090
+ type GLTFLike = { scene: THREE$1.Object3D }
1091
+
1092
+ type LoaderInstance<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
1093
+ T extends ConstructorRepresentation<LoaderLike> ? InstanceType<T> : T
1094
+
1095
+ // Infer result type from the load method's callback parameter
1096
+ type InferLoadResult<T> = T extends {
1097
+ load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
1098
+ }
1099
+ ? R
1100
+ : T extends ConstructorRepresentation<any>
1101
+ ? InstanceType<T> extends {
1102
+ load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
1103
+ }
1104
+ ? R
1105
+ : any
1106
+ : any
1107
+
1108
+ type LoaderResult<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
1109
+ InferLoadResult<LoaderInstance<T>> extends infer R ? (R extends GLTFLike ? R & ObjectMap : R) : never
1110
+
1111
+ type Extensions<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> = (
1112
+ loader: LoaderInstance<T>,
964
1113
  ) => void
965
1114
 
966
- type WebGLDefaultProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & BaseRendererProps
967
-
968
- type WebGLProps =
969
- | RendererFactory<THREE$1.WebGLRenderer, WebGLDefaultProps>
970
- | Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters>
971
-
972
- interface WebGLShadowConfig {
973
- shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
1115
+ //* Renderer Props ========================================
1116
+
1117
+ type WebGLDefaultProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & BaseRendererProps
1118
+
1119
+ type WebGLProps =
1120
+ | RendererFactory<THREE$1.WebGLRenderer, WebGLDefaultProps>
1121
+ | Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters>
1122
+
1123
+ interface WebGLShadowConfig {
1124
+ shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
1125
+ }
1126
+
1127
+ //* Legacy-specific Types ========================================
1128
+
1129
+ /** Legacy (WebGL) renderer type - re-exported as R3FRenderer from @react-three/fiber/legacy */
1130
+ type LegacyRenderer = THREE$1.WebGLRenderer
1131
+
1132
+ /** Legacy internal state with narrowed renderer type */
1133
+ interface LegacyInternalState extends Omit<InternalState, 'actualRenderer'> {
1134
+ actualRenderer: THREE$1.WebGLRenderer
1135
+ }
1136
+
1137
+ /**
1138
+ * Legacy-specific RootState with narrowed renderer type.
1139
+ * Automatically used when importing from `@react-three/fiber/legacy`.
1140
+ *
1141
+ * @example
1142
+ * ```tsx
1143
+ * import { useThree } from '@react-three/fiber/legacy'
1144
+ *
1145
+ * function MyComponent() {
1146
+ * const { renderer } = useThree()
1147
+ * // renderer is typed as THREE.WebGLRenderer
1148
+ * renderer.shadowMap.enabled = true
1149
+ * }
1150
+ * ```
1151
+ */
1152
+ interface LegacyRootState extends Omit<RootState, 'renderer' | 'internal'> {
1153
+ /** The WebGL renderer instance */
1154
+ renderer: THREE$1.WebGLRenderer
1155
+ /** Internals with WebGL renderer */
1156
+ internal: LegacyInternalState
974
1157
  }
975
1158
 
976
- //* RenderTarget Types ==============================
977
-
978
-
1159
+ //* RenderTarget Types ==============================
1160
+
1161
+
979
1162
  type RenderTargetOptions = RenderTargetOptions$1
980
1163
 
981
- //* Global Types ==============================
982
-
983
- declare global {
984
- /** Uniform node type - a Node with a value property (matches Three.js UniformNode) */
985
- interface UniformNode<T = unknown> extends Node {
986
- value: T
987
- }
988
-
989
- /** Flat record of uniform nodes (no nested scopes) */
990
- type UniformRecord<T extends UniformNode = UniformNode> = Record<string, T>
991
-
992
- /**
993
- * Uniform store that can contain both root-level uniforms and scoped uniform objects
994
- * Used by state.uniforms which has structure like:
995
- * { uTime: UniformNode, player: { uHealth: UniformNode }, enemy: { uHealth: UniformNode } }
996
- */
997
- type UniformStore = Record<string, UniformNode | UniformRecord>
998
-
999
- /**
1000
- * Helper to safely access a uniform node from the store.
1001
- * Use this when accessing state.uniforms to get proper typing.
1002
- * @example
1003
- * const uTime = uniforms.uTime as UniformNode<number>
1004
- * const uColor = uniforms.uColor as UniformNode<import('three/webgpu').Color>
1005
- */
1006
- type GetUniform<T = unknown> = UniformNode<T>
1007
-
1008
- /**
1009
- * Acceptable input values for useUniforms - raw values that get converted to UniformNodes
1010
- * Supports: primitives, Three.js types, plain objects (converted to vectors), and UniformNodes
1011
- */
1012
- type UniformValue =
1013
- | number
1014
- | string
1015
- | boolean
1016
- | three_webgpu.Color
1017
- | three_webgpu.Vector2
1018
- | three_webgpu.Vector3
1019
- | three_webgpu.Vector4
1020
- | three_webgpu.Matrix3
1021
- | three_webgpu.Matrix4
1022
- | three_webgpu.Euler
1023
- | three_webgpu.Quaternion
1024
- | { x: number; y?: number; z?: number; w?: number } // Plain objects converted to vectors
1025
- | UniformNode
1026
-
1027
- /** Input record for useUniforms - accepts raw values or UniformNodes */
1028
- type UniformInputRecord = Record<string, UniformValue>
1029
- }
1030
-
1031
- //* Fn Return Type ==============================
1032
-
1033
- /** The return type of Fn() - a callable shader function node */
1034
- type ShaderCallable<R extends Node = Node> = ((...params: unknown[]) => ShaderNodeObject<R>) & Node
1035
-
1036
- //* Module Augmentation ==============================
1037
-
1038
- declare module 'three/tsl' {
1039
- /**
1040
- * Fn with array parameter destructuring
1041
- * @example Fn(([uv, skew]) => { ... })
1042
- */
1043
- export function Fn<R extends Node = Node>(
1044
- jsFunc: (inputs: ShaderNodeObject<Node>[]) => ShaderNodeObject<R>,
1045
- ): ShaderCallable<R>
1046
-
1047
- /**
1048
- * Fn with object parameter destructuring
1049
- * @example Fn(({ color, intensity }) => { ... })
1050
- */
1051
- export function Fn<T extends Record<string, unknown>, R extends Node = Node>(
1052
- jsFunc: (inputs: T) => ShaderNodeObject<R>,
1053
- ): ShaderCallable<R>
1054
-
1055
- /**
1056
- * Fn with array params + layout
1057
- * @example Fn(([a, b]) => { ... }, { layout: [...] })
1058
- */
1059
- export function Fn<R extends Node = Node>(
1060
- jsFunc: (inputs: ShaderNodeObject<Node>[]) => ShaderNodeObject<R>,
1061
- layout: { layout?: unknown },
1062
- ): ShaderCallable<R>
1063
-
1064
- /**
1065
- * Fn with object params + layout
1066
- */
1067
- export function Fn<T extends Record<string, unknown>, R extends Node = Node>(
1068
- jsFunc: (inputs: T) => ShaderNodeObject<R>,
1069
- layout: { layout?: unknown },
1070
- ): ShaderCallable<R>
1071
- }
1072
-
1073
- /**
1074
- * PostProcessing Types for usePostProcessing hook (WebGPU only)
1075
- */
1076
-
1077
-
1078
-
1079
- declare global {
1080
- /** Pass record - stores TSL pass nodes for post-processing */
1081
- type PassRecord = Record<string, any>
1082
-
1083
- /** Setup callback - runs first to configure MRT, create additional passes */
1084
- type PostProcessingSetupCallback = (state: RootState) => PassRecord | void
1085
-
1086
- /** Main callback - runs second to configure outputNode, create effect passes */
1087
- type PostProcessingMainCallback = (state: RootState) => PassRecord | void
1088
-
1089
- /** Return type for usePostProcessing hook */
1090
- interface UsePostProcessingReturn {
1091
- /** Current passes from state */
1092
- passes: PassRecord
1093
- /** PostProcessing instance (null if not initialized) */
1094
- postProcessing: any | null // THREE.PostProcessing
1095
- /** Clear all passes from state */
1096
- clearPasses: () => void
1097
- /** Reset PostProcessing entirely (clears PP + passes) */
1098
- reset: () => void
1099
- /** Re-run setup/main callbacks with current closure values */
1100
- rebuild: () => void
1101
- /** True when PostProcessing is configured and ready */
1102
- isReady: boolean
1103
- }
1104
- }
1105
-
1106
- //* useFrameNext Types ==============================
1107
-
1108
-
1109
-
1110
- //* Global Type Declarations ==============================
1111
-
1112
- declare global {
1113
- // Job --------------------------------
1114
-
1115
- /**
1116
- * Internal job representation in the scheduler
1117
- */
1118
- interface Job {
1119
- /** Unique identifier */
1120
- id: string
1121
- /** The callback to execute */
1122
- callback: FrameNextCallback
1123
- /** Phase this job belongs to */
1124
- phase: string
1125
- /** Run before these phases/job ids */
1126
- before: Set<string>
1127
- /** Run after these phases/job ids */
1128
- after: Set<string>
1129
- /** Priority within phase (higher first) */
1130
- priority: number
1131
- /** Insertion order for deterministic tie-breaking */
1132
- index: number
1133
- /** Max FPS for this job (undefined = no limit) */
1134
- fps?: number
1135
- /** Drop frames when behind (true) or catch up (false) */
1136
- drop: boolean
1137
- /** Last run timestamp (ms) */
1138
- lastRun?: number
1139
- /** Whether job is enabled */
1140
- enabled: boolean
1141
- /** Internal flag: system jobs (like default render) don't block user render takeover */
1142
- system?: boolean
1143
- }
1144
-
1145
- // Phase Graph --------------------------------
1146
-
1147
- /**
1148
- * A node in the phase graph
1149
- */
1150
- interface PhaseNode {
1151
- /** Phase name */
1152
- name: string
1153
- /** Whether this was auto-generated from a before/after constraint */
1154
- isAutoGenerated: boolean
1155
- }
1156
-
1157
- /**
1158
- * Options for creating a job from hook options
1159
- */
1160
- interface JobOptions {
1161
- id?: string
1162
- phase?: string
1163
- before?: string | string[]
1164
- after?: string | string[]
1165
- priority?: number
1166
- fps?: number
1167
- drop?: boolean
1168
- enabled?: boolean
1169
- }
1170
-
1171
- // Frame Loop State --------------------------------
1172
-
1173
- /**
1174
- * Internal frame loop state
1175
- */
1176
- interface FrameLoopState {
1177
- /** Whether the loop is running */
1178
- running: boolean
1179
- /** Current RAF handle */
1180
- rafHandle: number | null
1181
- /** Last frame timestamp in ms (null = uninitialized) */
1182
- lastTime: number | null
1183
- /** Frame counter */
1184
- frameCount: number
1185
- /** Elapsed time since first frame in ms */
1186
- elapsedTime: number
1187
- /** createdAt timestamp in ms */
1188
- createdAt: number
1189
- }
1190
-
1191
- // Root Entry --------------------------------
1192
-
1193
- /**
1194
- * Internal representation of a registered root (Canvas).
1195
- * Tracks jobs and manages rebuild state for this root.
1196
- * @internal
1197
- */
1198
- interface RootEntry {
1199
- /** Unique identifier for this root */
1200
- id: string
1201
- /** Function to get the root's current state. Returns any to support independent mode. */
1202
- getState: () => any
1203
- /** Map of job IDs to Job objects */
1204
- jobs: Map<string, Job>
1205
- /** Cached sorted job list for execution order */
1206
- sortedJobs: Job[]
1207
- /** Whether sortedJobs needs rebuilding */
1208
- needsRebuild: boolean
1209
- }
1210
-
1211
- /**
1212
- * Internal representation of a global job (deprecated API).
1213
- * Global jobs run once per frame, not per-root.
1214
- * Used by legacy addEffect/addAfterEffect APIs.
1215
- * @internal
1216
- * @deprecated Use useFrame with phases instead
1217
- */
1218
- interface GlobalJob {
1219
- /** Unique identifier for this global job */
1220
- id: string
1221
- /** Callback invoked with RAF timestamp in ms */
1222
- callback: (timestamp: number) => void
1223
- }
1224
-
1225
- // HMR Support --------------------------------
1226
-
1227
- /**
1228
- * Hot Module Replacement data structure for preserving scheduler state
1229
- * @internal
1230
- */
1231
- interface HMRData {
1232
- /** Shared data object for storing values across reloads */
1233
- data: Record<string, any>
1234
- /** Optional function to accept HMR updates */
1235
- accept?: () => void
1236
- }
1237
-
1238
- // Default Phases --------------------------------
1239
-
1240
- /**
1241
- * Default phase names for the scheduler
1242
- */
1243
- type DefaultPhase = 'start' | 'input' | 'physics' | 'update' | 'render' | 'finish'
1244
- }
1245
-
1246
- type MutableOrReadonlyParameters<T extends (...args: any) => any> = Parameters<T> | Readonly<Parameters<T>>
1247
-
1248
- interface MathRepresentation {
1249
- set(...args: number[]): any
1250
- }
1251
- interface VectorRepresentation extends MathRepresentation {
1252
- setScalar(value: number): any
1253
- }
1254
- type MathTypes = MathRepresentation | Euler$1 | Color$1
1255
-
1256
- type MathType<T extends MathTypes> = T extends Color$1
1257
- ? Args<typeof Color$1> | ColorRepresentation
1258
- : T extends VectorRepresentation | Layers$1 | Euler$1
1259
- ? T | MutableOrReadonlyParameters<T['set']> | number
1260
- : T | MutableOrReadonlyParameters<T['set']>
1261
-
1262
- type MathProps<P> = {
1263
- [K in keyof P as P[K] extends MathTypes ? K : never]: P[K] extends MathTypes ? MathType<P[K]> : never
1264
- }
1265
-
1266
- type Vector2 = MathType<Vector2$1>
1267
- type Vector3 = MathType<Vector3$1>
1268
- type Vector4 = MathType<Vector4$1>
1269
- type Color = MathType<Color$1>
1270
- type Layers = MathType<Layers$1>
1271
- type Quaternion = MathType<Quaternion$1>
1272
- type Euler = MathType<Euler$1>
1273
- type Matrix3 = MathType<Matrix3$1>
1274
- type Matrix4 = MathType<Matrix4$1>
1275
-
1276
- interface RaycastableRepresentation {
1277
- raycast(raycaster: Raycaster, intersects: Intersection$1[]): void
1278
- }
1279
- type EventProps<P> = P extends RaycastableRepresentation ? Partial<EventHandlers> : {}
1280
-
1281
- interface ReactProps<P> {
1282
- children?: React.ReactNode
1283
- ref?: React.Ref<P>
1284
- key?: React.Key
1285
- }
1286
-
1287
- type ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = Partial<
1288
- Overwrite<P, MathProps<P> & ReactProps<P> & EventProps<P>>
1289
- >
1290
-
1291
- type ThreeElement<T extends ConstructorRepresentation> = Mutable<
1292
- Overwrite<ElementProps<T>, Omit<InstanceProps<InstanceType<T>, T>, 'object'>>
1293
- >
1294
-
1295
- type ThreeToJSXElements<T extends Record<string, any>> = {
1296
- [K in keyof T & string as Uncapitalize<K>]: T[K] extends ConstructorRepresentation ? ThreeElement<T[K]> : never
1297
- }
1298
-
1299
- type ThreeExports = typeof THREE
1300
- type ThreeElementsImpl = ThreeToJSXElements<ThreeExports>
1301
-
1302
- interface ThreeElements extends Omit<ThreeElementsImpl, 'audio' | 'source' | 'line' | 'path'> {
1303
- primitive: Omit<ThreeElement<any>, 'args'> & { object: object }
1304
- // Conflicts with DOM types can be accessed through a three* prefix
1305
- threeAudio: ThreeElementsImpl['audio']
1306
- threeSource: ThreeElementsImpl['source']
1307
- threeLine: ThreeElementsImpl['line']
1308
- threePath: ThreeElementsImpl['path']
1309
- }
1310
-
1311
- declare module 'react' {
1312
- namespace JSX {
1313
- interface IntrinsicElements extends ThreeElements {}
1314
- }
1315
- }
1316
-
1317
- declare module 'react/jsx-runtime' {
1318
- namespace JSX {
1319
- interface IntrinsicElements extends ThreeElements {}
1320
- }
1321
- }
1322
-
1323
- declare module 'react/jsx-dev-runtime' {
1324
- namespace JSX {
1325
- interface IntrinsicElements extends ThreeElements {}
1326
- }
1164
+ //* Global Types ==============================
1165
+
1166
+ declare global {
1167
+ /**
1168
+ * Uniform node type.
1169
+ *
1170
+ * This is three's own `UniformNode`, not a re-declaration of it. It previously was a
1171
+ * hand-rolled `interface UniformNode<T> extends Node { value: T }`, which shadowed the real
1172
+ * exported type globally — so R3F's ~58 references resolved to an approximation that was
1173
+ * missing members three actually ships (`setName` among them) and had drifted to the wrong
1174
+ * arity when three made `UniformNode` two-parameter.
1175
+ *
1176
+ * three's signature is `UniformNode<TNodeType, TValue>`. R3F only ever varies the value type,
1177
+ * so the node type is fixed to `unknown` and the single parameter is kept for call-site
1178
+ * ergonomics. The result is three's structural type, so members stay in sync with the
1179
+ * installed three instead of needing to be mirrored by hand.
1180
+ */
1181
+ type UniformNode<T = unknown> = three_webgpu.UniformNode<unknown, T>
1182
+
1183
+ /**
1184
+ * ShaderCallable - the return type of Fn()
1185
+ * A callable shader function node that can be invoked with parameters.
1186
+ * The function returns a ShaderNodeObject when called.
1187
+ *
1188
+ * @example
1189
+ * ```tsx
1190
+ * // Define a shader function
1191
+ * const blendColorFn = Fn(([color1, color2, factor]) => {
1192
+ * return mix(color1, color2, factor)
1193
+ * })
1194
+ *
1195
+ * // Type when retrieving from nodes store
1196
+ * const { blendColorFn } = nodes as { blendColorFn: ShaderCallable }
1197
+ *
1198
+ * // Or with specific return type
1199
+ * const { myFn } = nodes as { myFn: ShaderCallable<THREE.Node> }
1200
+ * ```
1201
+ */
1202
+ type ShaderCallable<R extends Node = Node> = ((...params: unknown[]) => ShaderNodeObject<R>) & Node
1203
+
1204
+ /**
1205
+ * ShaderNodeRef - a ShaderNodeObject wrapper around a Node
1206
+ * This is the common return type for TSL operations (add, mul, sin, etc.)
1207
+ *
1208
+ * @example
1209
+ * ```tsx
1210
+ * const { wobble } = nodes as { wobble: ShaderNodeRef }
1211
+ * ```
1212
+ */
1213
+ type ShaderNodeRef<T extends Node = Node> = ShaderNodeObject<T>
1214
+
1215
+ /**
1216
+ * TSLNodeType - Union of all common TSL node types
1217
+ * Used by ScopedStore to properly type node access from the store.
1218
+ *
1219
+ * Includes:
1220
+ * - Node: base Three.js node type
1221
+ * - ShaderCallable: function nodes created with Fn()
1222
+ * - ShaderNodeObject: wrapped nodes from TSL operations (sin, mul, mix, etc.)
1223
+ *
1224
+ * @example
1225
+ * ```tsx
1226
+ * // In useLocalNodes, nodes are typed as TSLNodeType
1227
+ * const { positionNode, blendColorFn } = useLocalNodes(({ nodes }) => ({
1228
+ * positionNode: nodes.myPosition, // Works - Node is in union
1229
+ * blendColorFn: nodes.myFn, // Works - ShaderCallable is in union
1230
+ * }))
1231
+ *
1232
+ * // Can narrow with type guard or assertion when needed
1233
+ * if (typeof blendColorFn === 'function') {
1234
+ * blendColorFn(someColor, 0.5)
1235
+ * }
1236
+ * ```
1237
+ */
1238
+ type TSLNodeType = Node | ShaderCallable<Node> | ShaderNodeObject<Node>
1239
+
1240
+ /** Flat record of uniform nodes (no nested scopes) */
1241
+ type UniformRecord<T extends UniformNode = UniformNode> = Record<string, T>
1242
+
1243
+ /**
1244
+ * Uniform store that can contain both root-level uniforms and scoped uniform objects
1245
+ * Used by state.uniforms which has structure like:
1246
+ * { uTime: UniformNode, player: { uHealth: UniformNode }, enemy: { uHealth: UniformNode } }
1247
+ */
1248
+ type UniformStore = Record<string, UniformNode | UniformRecord>
1249
+
1250
+ /**
1251
+ * Helper to safely access a uniform node from the store.
1252
+ * Use this when accessing state.uniforms to get proper typing.
1253
+ * @example
1254
+ * const uTime = uniforms.uTime as UniformNode<number>
1255
+ * const uColor = uniforms.uColor as UniformNode<import('three/webgpu').Color>
1256
+ */
1257
+ type GetUniform<T = unknown> = UniformNode<T>
1258
+
1259
+ /**
1260
+ * Acceptable input values for useUniforms - raw values that get converted to UniformNodes
1261
+ * Supports:
1262
+ * - Primitives: number, string (color), boolean
1263
+ * - Three.js types: Color, Vector2/3/4, Matrix3/4, Euler, Quaternion
1264
+ * - Plain objects: { x, y, z, w } converted to vectors
1265
+ * - TSL nodes: color(), vec3(), float() for type casting
1266
+ * - UniformNode: existing uniforms (reused as-is)
1267
+ */
1268
+ type UniformValue =
1269
+ | number
1270
+ | string
1271
+ | boolean
1272
+ | three_webgpu.Color
1273
+ | three_webgpu.Vector2
1274
+ | three_webgpu.Vector3
1275
+ | three_webgpu.Vector4
1276
+ | three_webgpu.Matrix3
1277
+ | three_webgpu.Matrix4
1278
+ | three_webgpu.Euler
1279
+ | three_webgpu.Quaternion
1280
+ | { x: number; y?: number; z?: number; w?: number } // Plain objects converted to vectors
1281
+ | { r: number; g: number; b: number; a?: number } // Plain objects converted to Color
1282
+ | Node // TSL nodes like color(), vec3(), float() for type casting
1283
+ | UniformNode
1284
+
1285
+ /** Input record for useUniforms - accepts raw values or UniformNodes */
1286
+ type UniformInputRecord = Record<string, UniformValue>
1287
+ }
1288
+
1289
+ //* Module Augmentation ==============================
1290
+
1291
+ declare module 'three/tsl' {
1292
+ /**
1293
+ * Fn with array parameter destructuring
1294
+ * @example Fn(([uv, skew]) => { ... })
1295
+ */
1296
+ export function Fn<R extends Node = Node>(
1297
+ jsFunc: (inputs: ShaderNodeObject<Node>[]) => ShaderNodeObject<R>,
1298
+ ): ShaderCallable<R>
1299
+
1300
+ /**
1301
+ * Fn with object parameter destructuring
1302
+ * @example Fn(({ color, intensity }) => { ... })
1303
+ */
1304
+ export function Fn<T extends Record<string, unknown>, R extends Node = Node>(
1305
+ jsFunc: (inputs: T) => ShaderNodeObject<R>,
1306
+ ): ShaderCallable<R>
1307
+
1308
+ /**
1309
+ * Fn with array params + layout
1310
+ * @example Fn(([a, b]) => { ... }, { layout: [...] })
1311
+ */
1312
+ export function Fn<R extends Node = Node>(
1313
+ jsFunc: (inputs: ShaderNodeObject<Node>[]) => ShaderNodeObject<R>,
1314
+ layout: { layout?: unknown },
1315
+ ): ShaderCallable<R>
1316
+
1317
+ /**
1318
+ * Fn with object params + layout
1319
+ */
1320
+ export function Fn<T extends Record<string, unknown>, R extends Node = Node>(
1321
+ jsFunc: (inputs: T) => ShaderNodeObject<R>,
1322
+ layout: { layout?: unknown },
1323
+ ): ShaderCallable<R>
1324
+ }
1325
+
1326
+ declare global {
1327
+ /**
1328
+ * three's own render pipeline type. Named here so the rest of R3F refers to three's shape
1329
+ * rather than `any`. three r183 renamed `PostProcessing` to `RenderPipeline`; our peer floor
1330
+ * is r185, so the new name is the only one.
1331
+ */
1332
+ type ThreeRenderPipeline = three_webgpu.RenderPipeline
1333
+
1334
+ /** Pass record - stores TSL pass nodes for render pipeline */
1335
+ type PassRecord = Record<string, any>
1336
+
1337
+ /** State passed to pipeline callbacks after the active pipeline has been created */
1338
+ type RenderPipelineCallbackState = RootState & {
1339
+ renderPipeline: ThreeRenderPipeline
1340
+ }
1341
+
1342
+ /** Setup callback - runs first to configure MRT, create additional passes */
1343
+ type RenderPipelineSetupCallback = (state: RenderPipelineCallbackState) => PassRecord | void
1344
+
1345
+ /** Main callback - runs second to configure outputNode, create effect passes */
1346
+ type RenderPipelineMainCallback = (state: RenderPipelineCallbackState) => PassRecord | void
1347
+
1348
+ /** Return type for useRenderPipeline hook */
1349
+ interface UseRenderPipelineReturn {
1350
+ /** Current passes from state */
1351
+ passes: PassRecord
1352
+ /** RenderPipeline instance (null if not initialized) */
1353
+ renderPipeline: ThreeRenderPipeline | null
1354
+ /** Clear all passes from state */
1355
+ clearPasses: () => void
1356
+ /** Reset RenderPipeline entirely (clears PP + passes) */
1357
+ reset: () => void
1358
+ /** Re-run setup/main callbacks with current closure values */
1359
+ rebuild: () => void
1360
+ /** True when RenderPipeline is configured and ready */
1361
+ isReady: boolean
1362
+ }
1363
+ }
1364
+
1365
+ type MutableOrReadonlyParameters<T extends (...args: any) => any> = Parameters<T> | Readonly<Parameters<T>>
1366
+
1367
+ interface MathRepresentation {
1368
+ set(...args: number[]): any
1369
+ }
1370
+ interface VectorRepresentation extends MathRepresentation {
1371
+ setScalar(value: number): any
1372
+ }
1373
+ type MathTypes = MathRepresentation | Euler$1 | Color$1
1374
+
1375
+ type MathType<T extends MathTypes> = T extends Color$1
1376
+ ? Args<typeof Color$1> | ColorRepresentation
1377
+ : T extends VectorRepresentation | Layers$1 | Euler$1
1378
+ ? T | MutableOrReadonlyParameters<T['set']> | number
1379
+ : T | MutableOrReadonlyParameters<T['set']>
1380
+
1381
+ type MathProps<P> = {
1382
+ [K in keyof P as P[K] extends MathTypes ? K : never]: P[K] extends MathTypes ? MathType<P[K]> : never
1383
+ }
1384
+
1385
+ type Vector2 = MathType<Vector2$1>
1386
+ type Vector3 = MathType<Vector3$1>
1387
+ type Vector4 = MathType<Vector4$1>
1388
+ type Color = MathType<Color$1>
1389
+ type Layers = MathType<Layers$1>
1390
+ type Quaternion = MathType<Quaternion$1>
1391
+ type Euler = MathType<Euler$1>
1392
+ type Matrix3 = MathType<Matrix3$1>
1393
+ type Matrix4 = MathType<Matrix4$1>
1394
+
1395
+ interface RaycastableRepresentation {
1396
+ raycast(raycaster: Raycaster, intersects: Intersection$1[]): void
1397
+ }
1398
+ type EventProps<P> = P extends RaycastableRepresentation ? Partial<EventHandlers> : {}
1399
+
1400
+ /**
1401
+ * Props for geometry transform methods that can be called with `once()`.
1402
+ * These methods modify the geometry in-place and only make sense to call once on mount.
1403
+ *
1404
+ * @example
1405
+ * import { once } from '@react-three/fiber'
1406
+ *
1407
+ * <boxGeometry args={[1, 1, 1]} rotateX={once(Math.PI / 2)} />
1408
+ * <planeGeometry args={[10, 10]} translate={once(0, 0, 5)} />
1409
+ * <bufferGeometry applyMatrix4={once(matrix)} center={once()} />
1410
+ */
1411
+ interface GeometryTransformProps {
1412
+ /** Rotate the geometry about the X axis (radians). Use with once(). */
1413
+ rotateX?: number
1414
+ /** Rotate the geometry about the Y axis (radians). Use with once(). */
1415
+ rotateY?: number
1416
+ /** Rotate the geometry about the Z axis (radians). Use with once(). */
1417
+ rotateZ?: number
1418
+ /** Translate the geometry (x, y, z). Use with once(). */
1419
+ translate?: [x: number, y: number, z: number]
1420
+ /** Scale the geometry (x, y, z). Use with once(). */
1421
+ scale?: [x: number, y: number, z: number]
1422
+ /** Center the geometry based on bounding box. Use with once(). */
1423
+ center?: true
1424
+ /** Apply a Matrix4 transformation. Use with once(). */
1425
+ applyMatrix4?: Matrix4$1
1426
+ /** Apply a Quaternion rotation. Use with once(). */
1427
+ applyQuaternion?: Quaternion$1
1428
+ }
1429
+
1430
+ type GeometryProps<P> = P extends BufferGeometry ? GeometryTransformProps : {}
1431
+
1432
+ /**
1433
+ * Workaround for @types/three TSL node type issues.
1434
+ * The Node base class has properties that subclasses (OperatorNode, ConstNode, etc.) don't inherit.
1435
+ * This transforms `Node | null` properties to accept any object with node-like shape.
1436
+ */
1437
+ type TSLNodeInput = { nodeType?: string | null; uuid?: string } | null
1438
+
1439
+ /**
1440
+ * For node material properties (colorNode, positionNode, etc.), accept broader types
1441
+ * since @types/three has broken inheritance for TSL node subclasses.
1442
+ */
1443
+ type NodeProps<P> = {
1444
+ [K in keyof P as P[K] extends Node$1 | null ? K : never]?: TSLNodeInput
1445
+ }
1446
+
1447
+ interface ReactProps<P> {
1448
+ children?: React.ReactNode
1449
+ ref?: React.Ref<P>
1450
+ key?: React.Key
1451
+ }
1452
+
1453
+ type ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = Partial<
1454
+ Overwrite<P, MathProps<P> & ReactProps<P> & EventProps<P> & GeometryProps<P> & NodeProps<P>>
1455
+ >
1456
+
1457
+ type ThreeElement<T extends ConstructorRepresentation> = Mutable<
1458
+ Overwrite<ElementProps<T>, Omit<InstanceProps<InstanceType<T>, T>, 'object'>>
1459
+ >
1460
+
1461
+ type ThreeToJSXElements<T extends Record<string, any>> = {
1462
+ [K in keyof T & string as Uncapitalize<K>]: T[K] extends ConstructorRepresentation ? ThreeElement<T[K]> : never
1463
+ }
1464
+
1465
+ type ThreeExports = typeof import('three')
1466
+ type ThreeElementsImpl = ThreeToJSXElements<ThreeExports>
1467
+
1468
+ interface ThreeElements extends Omit<ThreeElementsImpl, 'audio' | 'source' | 'line' | 'path'> {
1469
+ primitive: Omit<ThreeElement<any>, 'args'> & { object: object }
1470
+ // Conflicts with DOM types can be accessed through a three* prefix
1471
+ threeAudio: ThreeElementsImpl['audio']
1472
+ threeSource: ThreeElementsImpl['source']
1473
+ threeLine: ThreeElementsImpl['line']
1474
+ threePath: ThreeElementsImpl['path']
1475
+ }
1476
+
1477
+ declare module 'react' {
1478
+ namespace JSX {
1479
+ interface IntrinsicElements extends ThreeElements {}
1480
+ }
1481
+ }
1482
+
1483
+ declare module 'react/jsx-runtime' {
1484
+ namespace JSX {
1485
+ interface IntrinsicElements extends ThreeElements {}
1486
+ }
1487
+ }
1488
+
1489
+ declare module 'react/jsx-dev-runtime' {
1490
+ namespace JSX {
1491
+ interface IntrinsicElements extends ThreeElements {}
1492
+ }
1327
1493
  }
1328
1494
 
1329
1495
  type three_d_Color = Color;
1330
1496
  type three_d_ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = ElementProps<T, P>;
1331
1497
  type three_d_Euler = Euler;
1332
1498
  type three_d_EventProps<P> = EventProps<P>;
1499
+ type three_d_GeometryProps<P> = GeometryProps<P>;
1500
+ type three_d_GeometryTransformProps = GeometryTransformProps;
1333
1501
  type three_d_Layers = Layers;
1334
1502
  type three_d_MathProps<P> = MathProps<P>;
1335
1503
  type three_d_MathRepresentation = MathRepresentation;
@@ -1338,9 +1506,11 @@ type three_d_MathTypes = MathTypes;
1338
1506
  type three_d_Matrix3 = Matrix3;
1339
1507
  type three_d_Matrix4 = Matrix4;
1340
1508
  type three_d_MutableOrReadonlyParameters<T extends (...args: any) => any> = MutableOrReadonlyParameters<T>;
1509
+ type three_d_NodeProps<P> = NodeProps<P>;
1341
1510
  type three_d_Quaternion = Quaternion;
1342
1511
  type three_d_RaycastableRepresentation = RaycastableRepresentation;
1343
1512
  type three_d_ReactProps<P> = ReactProps<P>;
1513
+ type three_d_TSLNodeInput = TSLNodeInput;
1344
1514
  type three_d_ThreeElement<T extends ConstructorRepresentation> = ThreeElement<T>;
1345
1515
  type three_d_ThreeElements = ThreeElements;
1346
1516
  type three_d_ThreeElementsImpl = ThreeElementsImpl;
@@ -1351,12 +1521,353 @@ type three_d_Vector3 = Vector3;
1351
1521
  type three_d_Vector4 = Vector4;
1352
1522
  type three_d_VectorRepresentation = VectorRepresentation;
1353
1523
  declare namespace three_d {
1354
- export type { three_d_Color as Color, three_d_ElementProps as ElementProps, three_d_Euler as Euler, three_d_EventProps as EventProps, three_d_Layers as Layers, three_d_MathProps as MathProps, three_d_MathRepresentation as MathRepresentation, three_d_MathType as MathType, three_d_MathTypes as MathTypes, three_d_Matrix3 as Matrix3, three_d_Matrix4 as Matrix4, three_d_MutableOrReadonlyParameters as MutableOrReadonlyParameters, three_d_Quaternion as Quaternion, three_d_RaycastableRepresentation as RaycastableRepresentation, three_d_ReactProps as ReactProps, three_d_ThreeElement as ThreeElement, three_d_ThreeElements as ThreeElements, three_d_ThreeElementsImpl as ThreeElementsImpl, three_d_ThreeExports as ThreeExports, three_d_ThreeToJSXElements as ThreeToJSXElements, three_d_Vector2 as Vector2, three_d_Vector3 as Vector3, three_d_Vector4 as Vector4, three_d_VectorRepresentation as VectorRepresentation };
1524
+ export type { three_d_Color as Color, three_d_ElementProps as ElementProps, three_d_Euler as Euler, three_d_EventProps as EventProps, three_d_GeometryProps as GeometryProps, three_d_GeometryTransformProps as GeometryTransformProps, three_d_Layers as Layers, three_d_MathProps as MathProps, three_d_MathRepresentation as MathRepresentation, three_d_MathType as MathType, three_d_MathTypes as MathTypes, three_d_Matrix3 as Matrix3, three_d_Matrix4 as Matrix4, three_d_MutableOrReadonlyParameters as MutableOrReadonlyParameters, three_d_NodeProps as NodeProps, three_d_Quaternion as Quaternion, three_d_RaycastableRepresentation as RaycastableRepresentation, three_d_ReactProps as ReactProps, three_d_TSLNodeInput as TSLNodeInput, three_d_ThreeElement as ThreeElement, three_d_ThreeElements as ThreeElements, three_d_ThreeElementsImpl as ThreeElementsImpl, three_d_ThreeExports as ThreeExports, three_d_ThreeToJSXElements as ThreeToJSXElements, three_d_Vector2 as Vector2, three_d_Vector3 as Vector3, three_d_Vector4 as Vector4, three_d_VectorRepresentation as VectorRepresentation };
1355
1525
  }
1356
1526
 
1527
+ /**
1528
+ * @fileoverview Registry for primary canvases that can be targeted by secondary canvases
1529
+ *
1530
+ * Enables multi-canvas WebGPU rendering where multiple Canvas components share
1531
+ * a single WebGPURenderer using Three.js CanvasTarget API.
1532
+ *
1533
+ * Primary canvas: Has `id` prop, creates its own renderer, registers here
1534
+ * Secondary canvas: Has `renderer={{ primaryCanvas: 'id' }}`, shares primary's renderer via CanvasTarget
1535
+ */
1536
+
1537
+ interface PrimaryCanvasEntry {
1538
+ /** The WebGPURenderer instance owned by this primary canvas */
1539
+ renderer: WebGPURenderer;
1540
+ /** The zustand store for this canvas */
1541
+ store: RootStore;
1542
+ }
1543
+ /**
1544
+ * Register a primary canvas that can be targeted by secondary canvases.
1545
+ *
1546
+ * @param id - Unique identifier for this primary canvas
1547
+ * @param renderer - The WebGPURenderer owned by this canvas
1548
+ * @param store - The zustand store for this canvas
1549
+ * @returns Cleanup function to unregister on unmount
1550
+ */
1551
+ declare function registerPrimary(id: string, renderer: WebGPURenderer, store: RootStore): () => void;
1552
+ /**
1553
+ * Get a registered primary canvas by id.
1554
+ *
1555
+ * @param id - The id of the primary canvas to look up
1556
+ * @returns The primary canvas entry or undefined if not found
1557
+ */
1558
+ declare function getPrimary(id: string): PrimaryCanvasEntry | undefined;
1559
+ /**
1560
+ * Wait for a primary canvas to be registered.
1561
+ * Returns immediately if already registered, otherwise waits.
1562
+ *
1563
+ * @param id - The id of the primary canvas to wait for
1564
+ * @param timeout - Optional timeout in ms (default: 5000)
1565
+ * @returns Promise that resolves with the primary canvas entry
1566
+ */
1567
+ declare function waitForPrimary(id: string, timeout?: number): Promise<PrimaryCanvasEntry>;
1568
+ /**
1569
+ * Check if a primary canvas with the given id exists.
1570
+ *
1571
+ * @param id - The id to check
1572
+ * @returns True if a primary canvas with this id is registered
1573
+ */
1574
+ declare function hasPrimary(id: string): boolean;
1575
+ /**
1576
+ * Unregister a primary canvas. Called on unmount.
1577
+ *
1578
+ * @param id - The id of the primary canvas to unregister
1579
+ */
1580
+ declare function unregisterPrimary(id: string): void;
1581
+ /**
1582
+ * Get all registered primary canvas ids. Useful for debugging.
1583
+ */
1584
+ declare function getPrimaryIds(): string[];
1585
+
1586
+ type EnvironmentLoaderProps = {
1587
+ files?: string | string[];
1588
+ path?: string;
1589
+ preset?: PresetsType;
1590
+ extensions?: (loader: Loader) => void;
1591
+ colorSpace?: ColorSpace;
1592
+ };
1593
+ /**
1594
+ * Loads environment textures for reflections and lighting.
1595
+ * Supports HDR files, presets, and cubemaps.
1596
+ *
1597
+ * @example Basic usage
1598
+ * ```jsx
1599
+ * const texture = useEnvironment({ preset: 'sunset' })
1600
+ * ```
1601
+ */
1602
+ declare function useEnvironment({ files, path, preset, colorSpace, extensions, }?: Partial<EnvironmentLoaderProps>): Texture$1<unknown, THREE$1.TextureEventMap> | CubeTexture<unknown>;
1603
+ declare namespace useEnvironment {
1604
+ var preload: (preloadOptions?: EnvironmentLoaderPreloadOptions) => void;
1605
+ var clear: (clearOptions?: EnvironmentLoaderClearOptions) => void;
1606
+ }
1607
+ /**
1608
+ * Options accepted by `useEnvironment.preload`.
1609
+ *
1610
+ * `colorSpace` is deliberately omitted: preload only warms the loader cache, and colorSpace is
1611
+ * applied to the texture by `useEnvironment()` at use time, per consumer. Accepting it here would
1612
+ * advertise an option this function silently ignores.
1613
+ *
1614
+ * This previously read `Omit<…, 'encoding'>` — omitting a key that does not exist on
1615
+ * `EnvironmentLoaderProps`, a leftover from three's pre-`colorSpace` `encoding` API. That made the
1616
+ * type equivalent to the full props, so `colorSpace` was accepted and then dropped on the floor.
1617
+ */
1618
+ type EnvironmentLoaderPreloadOptions = Omit<EnvironmentLoaderProps, 'colorSpace'>;
1619
+ type EnvironmentLoaderClearOptions = Pick<EnvironmentLoaderProps, 'files' | 'preset'>;
1620
+
1621
+ /**
1622
+ * Props for Environment component that sets up global cubemap for PBR materials and backgrounds.
1623
+ *
1624
+ * @property children - React children to render into custom environment portal
1625
+ * @property frames - Number of frames to render the environment. Use 1 for static, Infinity for animated (default: 1)
1626
+ * @property near - Near clipping plane for cube camera (default: 0.1)
1627
+ * @property far - Far clipping plane for cube camera (default: 1000)
1628
+ * @property resolution - Resolution of the cube render target (default: 256)
1629
+ * @property background - Whether to set scene.background. Can be true, false, or "only" (which only sets background) (default: false)
1630
+ *
1631
+ * @property blur - @deprecated Use backgroundBlurriness instead
1632
+ * @property backgroundBlurriness - Blur factor between 0 and 1 for background (default: 0, requires three.js 0.146+)
1633
+ * @property backgroundIntensity - Intensity factor for background (default: 1, requires three.js 0.163+)
1634
+ * @property backgroundRotation - Rotation for background as Euler angles (default: [0,0,0], requires three.js 0.163+)
1635
+ * @property environmentIntensity - Intensity factor for environment lighting (default: 1, requires three.js 0.163+)
1636
+ * @property environmentRotation - Rotation for environment as Euler angles (default: [0,0,0], requires three.js 0.163+)
1637
+ *
1638
+ * @property map - Pre-existing texture to use as environment map
1639
+ * @property preset - HDRI Haven preset: 'apartment', 'city', 'dawn', 'forest', 'lobby', 'night', 'park', 'studio', 'sunset', 'warehouse'. Not for production use.
1640
+ * @property scene - Custom THREE.Scene or ref to apply environment to (default: uses default scene)
1641
+ * @property ground - Ground projection settings. Use true for defaults or object with:
1642
+ * - height: Height of camera used to create env map (default: 15)
1643
+ * - radius: Radius of the world (default: 60)
1644
+ * - scale: Scale of backside projected sphere (default: 1000)
1645
+ *
1646
+ * Additional loader props:
1647
+ * @property files - File path(s) for environment. Supports .hdr, .exr, gainmap .jpg/.webp, or array of 6 cube faces
1648
+ * @property path - Base path for file loading
1649
+ * @property extensions - Texture extensions override
1650
+ */
1651
+ type EnvironmentProps = {
1652
+ children?: React$1.ReactNode;
1653
+ frames?: number;
1654
+ near?: number;
1655
+ far?: number;
1656
+ resolution?: number;
1657
+ background?: boolean | 'only';
1658
+ /** deprecated, use backgroundBlurriness */
1659
+ blur?: number;
1660
+ backgroundBlurriness?: number;
1661
+ backgroundIntensity?: number;
1662
+ backgroundRotation?: Euler;
1663
+ environmentIntensity?: number;
1664
+ environmentRotation?: Euler;
1665
+ map?: Texture$1;
1666
+ preset?: PresetsType;
1667
+ scene?: Scene | React$1.RefObject<Scene>;
1668
+ ground?: boolean | {
1669
+ radius?: number;
1670
+ height?: number;
1671
+ scale?: number;
1672
+ };
1673
+ /** Solid color for background (alternative to files/preset) */
1674
+ color?: ColorRepresentation;
1675
+ /** Separate files for background (when different from environment files) */
1676
+ backgroundFiles?: string | string[];
1677
+ } & EnvironmentLoaderProps;
1678
+ /**
1679
+ * Internal component that applies a pre-existing texture as environment map.
1680
+ * Sets scene.environment and optionally scene.background.
1681
+ *
1682
+ * @example
1683
+ * ```jsx
1684
+ * <CubeCamera>{(texture) => <EnvironmentMap map={texture} />}</CubeCamera>
1685
+ * ```
1686
+ */
1687
+ declare function EnvironmentMap({ scene, background, map, ...config }: EnvironmentProps): null;
1688
+ /**
1689
+ * Internal component that loads environment textures from files or presets.
1690
+ * Uses HDRLoader for .hdr, EXRLoader for .exr, UltraHDRLoader for .jpg/.jpeg HDR,
1691
+ * GainMapLoader for gainmap .webp, or CubeTextureLoader for arrays of images.
1692
+ *
1693
+ * @example With preset
1694
+ * ```jsx
1695
+ * <EnvironmentCube preset="sunset" />
1696
+ * ```
1697
+ *
1698
+ * @example From HDR file
1699
+ * ```jsx
1700
+ * <EnvironmentCube files="environment.hdr" />
1701
+ * ```
1702
+ *
1703
+ * @example From gainmap (smallest footprint)
1704
+ * ```jsx
1705
+ * <EnvironmentCube files={['file.webp', 'file-gainmap.webp', 'file.json']} />
1706
+ * ```
1707
+ *
1708
+ * @example From cube faces
1709
+ * ```jsx
1710
+ * <EnvironmentCube files={['px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png']} />
1711
+ * ```
1712
+ */
1713
+ declare function EnvironmentCube({ background, scene, blur, backgroundBlurriness, backgroundIntensity, backgroundRotation, environmentIntensity, environmentRotation, ...rest }: EnvironmentProps): null;
1714
+ /**
1715
+ * Internal component that renders custom environment using a portal and cube camera.
1716
+ * Renders children into an off-buffer and films with a cube camera to create environment map.
1717
+ * Can be static (frames=1) or animated (frames=Infinity).
1718
+ *
1719
+ * @example Custom environment with sphere
1720
+ * ```jsx
1721
+ * <EnvironmentPortal background near={1} far={1000} resolution={256}>
1722
+ * <mesh scale={100}>
1723
+ * <sphereGeometry args={[1, 64, 64]} />
1724
+ * <meshBasicMaterial map={texture} side={THREE.BackSide} />
1725
+ * </mesh>
1726
+ * </EnvironmentPortal>
1727
+ * ```
1728
+ *
1729
+ * @example Animated environment
1730
+ * ```jsx
1731
+ * <EnvironmentPortal frames={Infinity} resolution={256}>
1732
+ * <Float>
1733
+ * <mesh />
1734
+ * </Float>
1735
+ * </EnvironmentPortal>
1736
+ * ```
1737
+ *
1738
+ * @example Mixed with preset
1739
+ * ```jsx
1740
+ * <EnvironmentPortal preset="warehouse">
1741
+ * <mesh />
1742
+ * </EnvironmentPortal>
1743
+ * ```
1744
+ */
1745
+ declare function EnvironmentPortal({ children, near, far, resolution, frames, map, background, blur, backgroundBlurriness, backgroundIntensity, backgroundRotation, environmentIntensity, environmentRotation, scene, files, path, preset, extensions, }: EnvironmentProps): react_jsx_runtime.JSX.Element;
1746
+ declare module '@react-three/fiber' {
1747
+ interface ThreeElements {
1748
+ groundProjectedEnvImpl: ThreeElement<typeof GroundedSkybox>;
1749
+ }
1750
+ }
1751
+ /**
1752
+ * Sets up a global environment map for PBR materials and backgrounds.
1753
+ * Affects scene.environment and optionally scene.background unless a custom scene is passed.
1754
+ *
1755
+ * Supports multiple input methods:
1756
+ * - **Presets**: Selection of HDRI Haven assets (apartment, city, dawn, forest, lobby, night, park, studio, sunset, warehouse)
1757
+ * - **Files**: HDR (.hdr), EXR (.exr), gainmap JPEG (.jpg), gainmap WebP (.webp), or cube faces (array of 6 images)
1758
+ * - **Texture**: Pre-existing cube texture via `map` prop
1759
+ * - **Custom Scene**: Render children into environment using portal and cube camera
1760
+ * - **Ground Projection**: Project environment onto ground plane
1761
+ *
1762
+ * @remarks
1763
+ * - Preset property is NOT meant for production and may fail (relies on CDNs)
1764
+ * - Gainmap format has the smallest file footprint
1765
+ * - Use `frames={Infinity}` for animated environments with low resolution for performance
1766
+ * - Ground projection places models on the "ground" within the environment map
1767
+ * - Supports self-hosting with @pmndrs/assets using dynamic imports
1768
+ *
1769
+ * @example Basic preset usage
1770
+ * ```jsx
1771
+ * <Environment preset="sunset" />
1772
+ * ```
1773
+ *
1774
+ * @example From HDR file
1775
+ * ```jsx
1776
+ * <Environment files="/hdr/environment.hdr" />
1777
+ * ```
1778
+ *
1779
+ * @example From gainmap (smallest footprint)
1780
+ * ```jsx
1781
+ * <Environment files={['file.webp', 'file-gainmap.webp', 'file.json']} />
1782
+ * ```
1783
+ *
1784
+ * @example With self-hosted assets
1785
+ * ```jsx
1786
+ * import { suspend } from 'suspend-react'
1787
+ * const city = import('@pmndrs/assets/hdri/city.exr').then(m => m.default)
1788
+ *
1789
+ * <Environment files={suspend(city)} />
1790
+ * ```
1791
+ *
1792
+ * @example From existing texture
1793
+ * ```jsx
1794
+ * <CubeCamera>{(texture) => <Environment map={texture} />}</CubeCamera>
1795
+ * ```
1796
+ *
1797
+ * @example Custom environment scene
1798
+ * ```jsx
1799
+ * <Environment background near={1} far={1000} resolution={256}>
1800
+ * <mesh scale={100}>
1801
+ * <sphereGeometry args={[1, 64, 64]} />
1802
+ * <meshBasicMaterial map={texture} side={THREE.BackSide} />
1803
+ * </mesh>
1804
+ * </Environment>
1805
+ * ```
1806
+ *
1807
+ * @example Animated environment
1808
+ * ```jsx
1809
+ * <Environment frames={Infinity} resolution={256}>
1810
+ * <Float>
1811
+ * <mesh />
1812
+ * </Float>
1813
+ * </Environment>
1814
+ * ```
1815
+ *
1816
+ * @example Mixed custom scene with preset
1817
+ * ```jsx
1818
+ * <Environment background preset="warehouse">
1819
+ * <mesh />
1820
+ * </Environment>
1821
+ * ```
1822
+ *
1823
+ * @example With ground projection
1824
+ * ```jsx
1825
+ * <Environment ground={{ height: 15, radius: 60 }} preset="city" />
1826
+ * ```
1827
+ *
1828
+ * @example As background only
1829
+ * ```jsx
1830
+ * <Environment background="only" preset="sunset" />
1831
+ * ```
1832
+ *
1833
+ * @example With rotation and intensity
1834
+ * ```jsx
1835
+ * <Environment
1836
+ * background
1837
+ * backgroundBlurriness={0.5}
1838
+ * backgroundIntensity={0.8}
1839
+ * backgroundRotation={[0, Math.PI / 2, 0]}
1840
+ * environmentIntensity={1.2}
1841
+ * environmentRotation={[0, Math.PI / 4, 0]}
1842
+ * preset="studio"
1843
+ * />
1844
+ * ```
1845
+ */
1846
+ declare function Environment(props: EnvironmentProps): react_jsx_runtime.JSX.Element;
1847
+
1848
+ /**
1849
+ * Moves every trace of interactivity from one object to its replacement, for reconstruction.
1850
+ *
1851
+ * When `args` or a `primitive`'s `object` changes, R3F builds a new three object and keeps the same
1852
+ * instance. Removing the old object from the interaction state and registering the new one from
1853
+ * scratch makes events *work* again (#3778), but it forgets what was in flight: a pointer resting on
1854
+ * the object fires a second `onPointerEnter` without ever having left, and an active pointer capture
1855
+ * is dropped mid-drag. Rewriting the references instead keeps the interaction continuous across a
1856
+ * swap the user never asked to see (#3744).
1857
+ *
1858
+ * Captures are re-keyed rather than released, so the DOM-level capture on `captureData.target` is
1859
+ * left alone — releasing and re-acquiring it is precisely the glitch being avoided.
1860
+ *
1861
+ * Visibility handlers are deliberately not transferred: that registry is keyed by `object.uuid`, so
1862
+ * the replacement re-registers itself through `applyProps`. The old entry is dropped here so it
1863
+ * cannot outlive the object it described.
1864
+ */
1865
+ declare function swapInteractivity(store: RootStore, object: Object3D, newObject: Object3D): void;
1357
1866
  declare function removeInteractivity(store: RootStore, object: Object3D): void;
1358
1867
  declare function createEvents(store: RootStore): {
1359
1868
  handlePointer: (name: string) => (event: DomEvent) => void;
1869
+ flushDeferredPointers: () => void;
1870
+ processDeferredPointer: (event: DomEvent, pointerId: number) => void;
1360
1871
  };
1361
1872
  /** Default R3F event manager for web */
1362
1873
  declare function createPointerEvents(store: RootStore): EventManager<HTMLElement>;
@@ -1372,389 +1883,27 @@ declare function getLoader<L extends LoaderLike | ConstructorRepresentation<Load
1372
1883
  * Note: this hook's caller must be wrapped with `React.Suspense`
1373
1884
  * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#useloader
1374
1885
  */
1375
- declare function useLoader<I extends InputLike, L extends LoaderLike | ConstructorRepresentation<LoaderLike>>(loader: L, input: I, extensions?: Extensions<L>, onProgress?: (event: ProgressEvent<EventTarget>) => void): I extends any[] ? LoaderResult<L>[] : LoaderResult<L>;
1886
+ declare function useLoader<I extends InputLike, L extends LoaderLike | ConstructorRepresentation<LoaderLike>>(loader: L, input: I, extensions?: Extensions<L>, onProgress?: (event: ProgressEvent<EventTarget>) => void, cacheKey?: InputLike): I extends any[] ? LoaderResult<L>[] : LoaderResult<L>;
1376
1887
  declare namespace useLoader {
1377
- var preload: <I extends InputLike, L extends LoaderLike | ConstructorRepresentation<LoaderLike>>(loader: L, input: I, extensions?: Extensions<L>, onProgress?: (event: ProgressEvent<EventTarget>) => void) => void;
1378
- var clear: <I extends InputLike, L extends LoaderLike | ConstructorRepresentation<LoaderLike>>(loader: L, input: I) => void;
1888
+ var preload: <I extends InputLike, L extends LoaderLike | ConstructorRepresentation<LoaderLike>>(loader: L, input: I, extensions?: Extensions<L>, onProgress?: (event: ProgressEvent<EventTarget>) => void, cacheKey?: InputLike) => void;
1889
+ var clear: <I extends InputLike, L extends LoaderLike | ConstructorRepresentation<LoaderLike>>(loader: L, input: I, cacheKey?: InputLike) => void;
1379
1890
  var loader: typeof getLoader;
1380
1891
  }
1381
1892
 
1382
- /**
1383
- * Global Singleton Scheduler - manages the frame loop and job execution for ALL R3F roots.
1384
- *
1385
- * Features:
1386
- * - Single RAF loop for entire application
1387
- * - Root registration (multiple Canvas support)
1388
- * - Global phases for addEffect/addAfterEffect (deprecated)
1389
- * - Per-root job management with phases, priorities, FPS throttling
1390
- * - onIdle callbacks for addTail (deprecated)
1391
- * - Demand mode support via invalidate()
1392
- */
1393
- declare class Scheduler {
1394
- private static readonly INSTANCE_KEY;
1395
- private static get instance();
1396
- private static set instance(value);
1397
- /**
1398
- * Get the global scheduler instance (creates if doesn't exist).
1399
- * Uses HMR data to preserve instance across hot reloads.
1400
- * @returns {Scheduler} The singleton scheduler instance
1401
- */
1402
- static get(): Scheduler;
1403
- /**
1404
- * Reset the singleton instance. Stops the loop and clears all state.
1405
- * Primarily used for testing to ensure clean state between tests.
1406
- * @returns {void}
1407
- */
1408
- static reset(): void;
1409
- private roots;
1410
- private phaseGraph;
1411
- private loopState;
1412
- private stoppedTime;
1413
- private nextRootIndex;
1414
- private globalBeforeJobs;
1415
- private globalAfterJobs;
1416
- private nextGlobalIndex;
1417
- private idleCallbacks;
1418
- private nextJobIndex;
1419
- private jobStateListeners;
1420
- private pendingFrames;
1421
- private _frameloop;
1422
- private _independent;
1423
- private errorHandler;
1424
- private rootReadyCallbacks;
1425
- get phases(): string[];
1426
- get frameloop(): Frameloop;
1427
- set frameloop(mode: Frameloop);
1428
- get isRunning(): boolean;
1429
- get isReady(): boolean;
1430
- get independent(): boolean;
1431
- set independent(value: boolean);
1432
- constructor();
1433
- /**
1434
- * Register a root (Canvas) with the scheduler.
1435
- * The first root to register starts the RAF loop (if frameloop='always').
1436
- * @param {string} id - Unique identifier for this root
1437
- * @param {RootOptions} [options] - Optional configuration with getState and onError callbacks
1438
- * @returns {() => void} Unsubscribe function to remove this root
1439
- */
1440
- registerRoot(id: string, options?: RootOptions): () => void;
1441
- /**
1442
- * Unregister a root from the scheduler.
1443
- * Cleans up all job state listeners for this root's jobs.
1444
- * The last root to unregister stops the RAF loop.
1445
- * @param {string} id - The root ID to unregister
1446
- * @returns {void}
1447
- */
1448
- unregisterRoot(id: string): void;
1449
- /**
1450
- * Subscribe to be notified when a root becomes available.
1451
- * Fires immediately if a root already exists.
1452
- * @param {() => void} callback - Function called when first root registers
1453
- * @returns {() => void} Unsubscribe function
1454
- */
1455
- onRootReady(callback: () => void): () => void;
1456
- /**
1457
- * Notify all registered root-ready callbacks.
1458
- * Called when the first root registers.
1459
- * @returns {void}
1460
- * @private
1461
- */
1462
- private notifyRootReady;
1463
- /**
1464
- * Ensure a default root exists for independent mode.
1465
- * Creates a minimal root with no state provider.
1466
- * @returns {void}
1467
- * @private
1468
- */
1469
- private ensureDefaultRoot;
1470
- /**
1471
- * Trigger error handling for job errors.
1472
- * Uses the bound error handler if available, otherwise logs to console.
1473
- * @param {Error} error - The error to handle
1474
- * @returns {void}
1475
- */
1476
- triggerError(error: Error): void;
1477
- /**
1478
- * Add a named phase to the scheduler's execution order.
1479
- * Marks all roots for rebuild to incorporate the new phase.
1480
- * @param {string} name - The phase name (e.g., 'physics', 'postprocess')
1481
- * @param {AddPhaseOptions} [options] - Positioning options (before/after other phases)
1482
- * @returns {void}
1483
- * @example
1484
- * scheduler.addPhase('physics', { before: 'update' });
1485
- * scheduler.addPhase('postprocess', { after: 'render' });
1486
- */
1487
- addPhase(name: string, options?: AddPhaseOptions): void;
1488
- /**
1489
- * Check if a phase exists in the scheduler.
1490
- * @param {string} name - The phase name to check
1491
- * @returns {boolean} True if the phase exists
1492
- */
1493
- hasPhase(name: string): boolean;
1494
- /**
1495
- * Register a global job that runs once per frame (not per-root).
1496
- * Used internally by deprecated addEffect/addAfterEffect APIs.
1497
- * @param {'before' | 'after'} phase - When to run: 'before' all roots or 'after' all roots
1498
- * @param {string} id - Unique identifier for this global job
1499
- * @param {(timestamp: number) => void} callback - Function called each frame with RAF timestamp
1500
- * @returns {() => void} Unsubscribe function to remove this global job
1501
- * @deprecated Use useFrame with phases instead
1502
- */
1503
- registerGlobal(phase: 'before' | 'after', id: string, callback: (timestamp: number) => void): () => void;
1504
- /**
1505
- * Register an idle callback that fires when the loop stops.
1506
- * Used internally by deprecated addTail API.
1507
- * @param {(timestamp: number) => void} callback - Function called when loop becomes idle
1508
- * @returns {() => void} Unsubscribe function to remove this idle callback
1509
- * @deprecated Use demand mode with invalidate() instead
1510
- */
1511
- onIdle(callback: (timestamp: number) => void): () => void;
1512
- /**
1513
- * Notify all registered idle callbacks.
1514
- * Called when the loop stops in demand mode.
1515
- * @param {number} timestamp - The RAF timestamp when idle occurred
1516
- * @returns {void}
1517
- * @private
1518
- */
1519
- private notifyIdle;
1520
- /**
1521
- * Register a job (frame callback) with a specific root.
1522
- * This is the core registration method used by useFrame internally.
1523
- * @param {FrameNextCallback} callback - The function to call each frame
1524
- * @param {JobOptions & { rootId?: string; system?: boolean }} [options] - Job configuration
1525
- * @param {string} [options.rootId] - Target root ID (defaults to first registered root)
1526
- * @param {string} [options.id] - Unique job ID (auto-generated if not provided)
1527
- * @param {string} [options.phase] - Execution phase (defaults to 'update')
1528
- * @param {number} [options.priority] - Priority within phase (higher = earlier, default 0)
1529
- * @param {number} [options.fps] - FPS throttle limit
1530
- * @param {boolean} [options.drop] - Drop frames when behind (default true)
1531
- * @param {boolean} [options.enabled] - Whether job is active (default true)
1532
- * @param {boolean} [options.system] - Internal flag for system jobs (not user-facing)
1533
- * @returns {() => void} Unsubscribe function to remove this job
1534
- */
1535
- register(callback: FrameNextCallback, options?: JobOptions & {
1536
- rootId?: string;
1537
- system?: boolean;
1538
- }): () => void;
1539
- /**
1540
- * Unregister a job by its ID.
1541
- * Searches all roots if rootId is not provided.
1542
- * @param {string} id - The job ID to unregister
1543
- * @param {string} [rootId] - Optional root ID to search (searches all if not provided)
1544
- * @returns {void}
1545
- */
1546
- unregister(id: string, rootId?: string): void;
1547
- /**
1548
- * Update a job's options dynamically.
1549
- * Searches all roots to find the job by ID.
1550
- * Phase/constraint changes trigger a rebuild of the sorted job list.
1551
- * @param {string} id - The job ID to update
1552
- * @param {Partial<JobOptions>} options - The options to update
1553
- * @returns {void}
1554
- */
1555
- updateJob(id: string, options: Partial<JobOptions>): void;
1556
- /**
1557
- * Check if a job is currently paused (disabled).
1558
- * @param {string} id - The job ID to check
1559
- * @returns {boolean} True if the job exists and is paused
1560
- */
1561
- isJobPaused(id: string): boolean;
1562
- /**
1563
- * Subscribe to state changes for a specific job.
1564
- * Listener is called when job is paused or resumed.
1565
- * @param {string} id - The job ID to subscribe to
1566
- * @param {() => void} listener - Callback invoked on state changes
1567
- * @returns {() => void} Unsubscribe function
1568
- */
1569
- subscribeJobState(id: string, listener: () => void): () => void;
1570
- /**
1571
- * Notify all listeners that a job's state has changed.
1572
- * @param {string} id - The job ID that changed
1573
- * @returns {void}
1574
- * @private
1575
- */
1576
- private notifyJobStateChange;
1577
- /**
1578
- * Pause a job by ID (sets enabled=false).
1579
- * Notifies any subscribed state listeners.
1580
- * @param {string} id - The job ID to pause
1581
- * @returns {void}
1582
- */
1583
- pauseJob(id: string): void;
1584
- /**
1585
- * Resume a paused job by ID (sets enabled=true).
1586
- * Resets job timing to prevent frame accumulation.
1587
- * Notifies any subscribed state listeners.
1588
- * @param {string} id - The job ID to resume
1589
- * @returns {void}
1590
- */
1591
- resumeJob(id: string): void;
1592
- /**
1593
- * Start the requestAnimationFrame loop.
1594
- * Resets timing state (elapsedTime, frameCount) on start.
1595
- * No-op if already running.
1596
- * @returns {void}
1597
- */
1598
- start(): void;
1599
- /**
1600
- * Stop the requestAnimationFrame loop.
1601
- * Cancels any pending RAF callback.
1602
- * No-op if not running.
1603
- * @returns {void}
1604
- */
1605
- stop(): void;
1606
- /**
1607
- * Request frames to be rendered in demand mode.
1608
- * Accumulates pending frames (capped at 60) and starts the loop if not running.
1609
- * No-op if frameloop is not 'demand'.
1610
- * @param {number} [frames=1] - Number of frames to request
1611
- * @param {boolean} [stackFrames=false] - Whether to add frames to existing pending count
1612
- * - `false` (default): Sets pending frames to the specified value (replaces existing count)
1613
- * - `true`: Adds frames to existing pending count (useful for accumulating invalidations)
1614
- * @returns {void}
1615
- * @example
1616
- * // Request a single frame render
1617
- * scheduler.invalidate();
1618
- *
1619
- * @example
1620
- * // Request 5 frames (e.g., for animations)
1621
- * scheduler.invalidate(5);
1622
- *
1623
- * @example
1624
- * // Set pending frames to exactly 3 (don't stack with existing)
1625
- * scheduler.invalidate(3, false);
1626
- *
1627
- * @example
1628
- * // Add 2 more frames to existing pending count
1629
- * scheduler.invalidate(2, true);
1630
- */
1631
- invalidate(frames?: number, stackFrames?: boolean): void;
1632
- /**
1633
- * Reset timing state for deterministic testing.
1634
- * Preserves jobs and roots but resets lastTime, frameCount, elapsedTime, etc.
1635
- * @returns {void}
1636
- */
1637
- resetTiming(): void;
1638
- /**
1639
- * Manually execute a single frame for all roots.
1640
- * Useful for frameloop='never' mode or testing scenarios.
1641
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
1642
- * @returns {void}
1643
- * @example
1644
- * // Manual control mode
1645
- * scheduler.frameloop = 'never';
1646
- * scheduler.step(); // Execute one frame
1647
- */
1648
- step(timestamp?: number): void;
1649
- /**
1650
- * Manually execute a single job by its ID.
1651
- * Useful for testing individual job callbacks in isolation.
1652
- * @param {string} id - The job ID to step
1653
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
1654
- * @returns {void}
1655
- */
1656
- stepJob(id: string, timestamp?: number): void;
1657
- /**
1658
- * Main RAF loop callback.
1659
- * Executes frame, handles demand mode, and schedules next frame.
1660
- * @param {number} timestamp - RAF timestamp in milliseconds
1661
- * @returns {void}
1662
- * @private
1663
- */
1664
- private loop;
1665
- /**
1666
- * Execute a single frame across all roots.
1667
- * Order: globalBefore → each root's jobs → globalAfter
1668
- * @param {number} timestamp - RAF timestamp in milliseconds
1669
- * @returns {void}
1670
- * @private
1671
- */
1672
- private executeFrame;
1673
- /**
1674
- * Run all global jobs from a job map.
1675
- * Catches and logs errors without stopping execution.
1676
- * @param {Map<string, GlobalJob>} jobs - The global jobs map to execute
1677
- * @param {number} timestamp - RAF timestamp in milliseconds
1678
- * @returns {void}
1679
- * @private
1680
- */
1681
- private runGlobalJobs;
1682
- /**
1683
- * Execute all jobs for a single root in sorted order.
1684
- * Rebuilds sorted job list if needed, then dispatches each job.
1685
- * Errors are caught and propagated via triggerError.
1686
- * @param {RootEntry} root - The root entry to tick
1687
- * @param {number} timestamp - RAF timestamp in milliseconds
1688
- * @param {number} delta - Time since last frame in seconds
1689
- * @returns {void}
1690
- * @private
1691
- */
1692
- private tickRoot;
1693
- /**
1694
- * Get the total number of registered jobs across all roots.
1695
- * Includes both per-root jobs and global before/after jobs.
1696
- * @returns {number} Total job count
1697
- */
1698
- getJobCount(): number;
1699
- /**
1700
- * Get all registered job IDs across all roots.
1701
- * Includes both per-root jobs and global before/after jobs.
1702
- * @returns {string[]} Array of all job IDs
1703
- */
1704
- getJobIds(): string[];
1705
- /**
1706
- * Get the number of registered roots (Canvas instances).
1707
- * @returns {number} Number of registered roots
1708
- */
1709
- getRootCount(): number;
1710
- /**
1711
- * Check if any user (non-system) jobs are registered in a specific phase.
1712
- * Used by the default render job to know if a user has taken over rendering.
1713
- *
1714
- * @param phase The phase to check
1715
- * @param rootId Optional root ID to check (checks all roots if not provided)
1716
- * @returns true if any user jobs exist in the phase
1717
- */
1718
- hasUserJobsInPhase(phase: string, rootId?: string): boolean;
1719
- /**
1720
- * Generate a unique root ID for automatic root registration.
1721
- * @returns {string} A unique root ID in the format 'root_N'
1722
- */
1723
- generateRootId(): string;
1724
- /**
1725
- * Generate a unique job ID.
1726
- * @returns {string} A unique job ID in the format 'job_N'
1727
- * @private
1728
- */
1729
- private generateJobId;
1730
- /**
1731
- * Normalize before/after constraints to a Set.
1732
- * Handles undefined, single string, or array inputs.
1733
- * @param {string | string[] | undefined} value - The constraint value(s)
1734
- * @returns {Set<string>} Normalized Set of constraint strings
1735
- * @private
1736
- */
1737
- private normalizeConstraints;
1738
- }
1739
- /**
1740
- * Get the global scheduler instance.
1741
- * Creates one if it doesn't exist.
1742
- */
1743
- declare const getScheduler: () => Scheduler;
1744
-
1745
1893
  /**
1746
1894
  * Frame hook with phase-based ordering, priority, and FPS throttling.
1747
1895
  *
1748
- * Works both inside and outside Canvas context:
1749
- * - Inside Canvas: Full RootState (gl, scene, camera, etc.)
1750
- * - Outside Canvas (waiting mode): Waits for Canvas to mount, then gets full state
1751
- * - Outside Canvas (independent mode): Fires immediately with timing-only state
1896
+ * Always delivers full RootState — works both inside and outside Canvas context:
1897
+ * - Inside Canvas: Full RootState (renderer, scene, camera, etc.)
1898
+ * - Outside Canvas: The job registers immediately but the callback is held until a
1899
+ * Canvas adopts it, then runs with full RootState. For hostless / standalone
1900
+ * frame loops with no Canvas, use `@pmndrs/scheduler` directly.
1752
1901
  *
1753
1902
  * Returns a controls object for manual stepping, pausing, and resuming.
1754
1903
  *
1755
1904
  * @param callback - Function called each frame with (state, delta). Optional if you only need scheduler access.
1756
1905
  * @param priorityOrOptions - Either a priority number (backwards compat) or options object
1757
- * @returns Controls object with step(), stepAll(), pause(), resume(), isPaused, id, scheduler
1906
+ * @returns Controls object with step(), stepAll(), invalidate(), pause(), resume(), isPaused, id, rootId, scheduler
1758
1907
  *
1759
1908
  * @example
1760
1909
  * // Simple priority (backwards compat)
@@ -1765,16 +1914,16 @@ declare const getScheduler: () => Scheduler;
1765
1914
  * useFrame((state, delta) => { ... }, { phase: 'physics' })
1766
1915
  *
1767
1916
  * @example
1768
- * // Outside Canvas - waits for Canvas to mount
1917
+ * // Outside Canvas - callback waits for a Canvas, then always has full state
1769
1918
  * function UI() {
1770
1919
  * useFrame((state, delta) => { syncUI(state.camera) });
1771
1920
  * return <button>...</button>;
1772
1921
  * }
1773
1922
  *
1774
1923
  * @example
1775
- * // Independent mode - no Canvas needed
1776
- * getScheduler().independent = true;
1777
- * useFrame((state, delta) => { updateGame(delta) });
1924
+ * // Hostless / standalone loop (no Canvas) - use @pmndrs/scheduler directly
1925
+ * import { getScheduler } from '@pmndrs/scheduler'
1926
+ * getScheduler().register((state, delta) => { updateGame(delta) })
1778
1927
  *
1779
1928
  * @example
1780
1929
  * // Scheduler-only access (no callback)
@@ -1797,11 +1946,16 @@ type UseTextureOptions<Url extends string[] | string | Record<string, string>> =
1797
1946
  /** Callback when texture(s) finish loading */
1798
1947
  onLoad?: (texture: MappedTextureType<Url>) => void;
1799
1948
  /**
1800
- * Cache the texture in R3F's global state for access via useTextures().
1801
- * When true:
1949
+ * Register the texture(s) in R3F's global texture registry for access via useTextures().
1950
+ * When true (the default):
1802
1951
  * - Textures persist until explicitly disposed
1803
- * - Returns existing cached textures if available (preserving modifications like colorSpace)
1804
- * @default false
1952
+ * - On mount, returns existing registered textures if available (preserving modifications like colorSpace)
1953
+ *
1954
+ * Reads are taken once at mount — a mounted `useTexture` does not re-render when the registry
1955
+ * changes. To react to registry swaps, use `useTextures(s => s.get(key))` instead.
1956
+ *
1957
+ * Pass `false` to opt out of registry enrollment entirely.
1958
+ * @default true
1805
1959
  */
1806
1960
  cache?: boolean;
1807
1961
  };
@@ -1825,15 +1979,18 @@ type UseTextureOptions<Url extends string[] | string | Record<string, string>> =
1825
1979
  * normal: '/normal.png'
1826
1980
  * })
1827
1981
  *
1828
- * // With caching - returns same texture object across components
1829
- * // Modifications (colorSpace, wrapS, etc.) are preserved
1830
- * const diffuse = useTexture('/diffuse.png', { cache: true })
1982
+ * // Textures are registered in the global registry by default — the same texture
1983
+ * // object is shared across components and modifications (colorSpace, wrapS, etc.) are preserved
1984
+ * const diffuse = useTexture('/diffuse.png')
1831
1985
  * diffuse.colorSpace = THREE.SRGBColorSpace
1832
1986
  *
1833
1987
  * // Another component gets the SAME texture with colorSpace already set
1834
- * const sameDiffuse = useTexture('/diffuse.png', { cache: true })
1988
+ * const sameDiffuse = useTexture('/diffuse.png')
1989
+ *
1990
+ * // Opt out of registry enrollment for a one-off texture
1991
+ * const scratch = useTexture('/scratch.png', { cache: false })
1835
1992
  *
1836
- * // Access cache directly
1993
+ * // Access the registry directly
1837
1994
  * const { get } = useTextures()
1838
1995
  * const cached = get('/diffuse.png')
1839
1996
  * ```
@@ -1850,63 +2007,80 @@ declare const Texture: ({ children, input, onLoad, cache, }: {
1850
2007
  cache?: boolean;
1851
2008
  }) => react_jsx_runtime.JSX.Element;
1852
2009
 
1853
- type TextureEntry = Texture$1 | {
1854
- value: Texture$1;
1855
- [key: string]: any;
2010
+ /** Accepted shapes for a registry read: a single key, a list of keys, or a name→key map. */
2011
+ type TextureInput = string | string[] | Record<string, string>;
2012
+ /** Result of a `get()` read, mirroring the input shape. */
2013
+ type TextureResult<Input extends TextureInput> = Input extends string ? Texture$1 | undefined : Input extends string[] ? (Texture$1 | undefined)[] : {
2014
+ [K in keyof Input]: Texture$1 | undefined;
1856
2015
  };
2016
+ /** Options for `dispose()`. */
2017
+ interface DisposeOptions {
2018
+ /** Dispose even if the texture still has active references (default false). */
2019
+ force?: boolean;
2020
+ }
1857
2021
  interface UseTexturesReturn {
1858
- /** Map of all textures currently in cache */
1859
- textures: Map<string, TextureEntry>;
1860
- /** Get a specific texture by key (usually URL) */
1861
- get: (key: string) => TextureEntry | undefined;
1862
- /** Check if a texture exists in cache */
1863
- has: (key: string) => boolean;
1864
- /** Add a texture to the cache */
1865
- add: (key: string, value: TextureEntry) => void;
1866
- /** Add multiple textures to the cache */
1867
- addMultiple: (items: Map<string, TextureEntry> | Record<string, TextureEntry>) => void;
1868
- /** Remove a texture from cache (does NOT dispose GPU resources) */
1869
- remove: (key: string) => void;
1870
- /** Remove multiple textures from cache */
1871
- removeMultiple: (keys: string[]) => void;
1872
- /** Dispose a texture's GPU resources and remove from cache */
1873
- dispose: (key: string) => void;
1874
- /** Dispose multiple textures */
1875
- disposeMultiple: (keys: string[]) => void;
1876
- /** Dispose ALL cached textures - use with caution */
1877
- disposeAll: () => void;
1878
- }
1879
- /**
1880
- * Hook for managing the global texture cache in R3F state.
1881
- *
1882
- * Textures are stored in a Map with URL/path keys for efficient lookup.
1883
- * Useful for sharing texture references across materials and components.
2022
+ /** The live registry Map (key → Texture). Treat as read-only. */
2023
+ readonly all: Map<string, Texture$1>;
2024
+ /** Read one texture, an array of textures, or a name→texture record (mirrors the input shape). */
2025
+ get<Input extends TextureInput>(input: Input): TextureResult<Input>;
2026
+ /** Check whether a key exists in the registry. */
2027
+ has(key: string): boolean;
2028
+ /**
2029
+ * Register a texture (or a record of textures) that has no URL — e.g. a render
2030
+ * target or procedural texture. URL-loaded textures are registered automatically
2031
+ * by `useTexture` (registry enrollment is on by default).
2032
+ */
2033
+ add(key: string, texture: Texture$1): void;
2034
+ add(record: Record<string, Texture$1>): void;
2035
+ /**
2036
+ * Dispose a texture's GPU resources and remove it from the registry.
2037
+ * Refcount-aware: if the key is still in use by a mounted `useTexture` consumer it is
2038
+ * skipped (with a warning) unless `{ force: true }` is passed.
2039
+ * @returns true if disposed, false if skipped.
2040
+ */
2041
+ dispose(key: string, options?: DisposeOptions): boolean;
2042
+ /** Dispose every texture in the registry and clear it. Use on scene teardown. */
2043
+ disposeAll(): void;
2044
+ }
2045
+ /**
2046
+ * Reactive Texture registry — load once with `useTexture`, reach the textures from anywhere.
2047
+ *
2048
+ * This is a registry of plain `Texture` objects (not TSL nodes), so the same texture can feed
2049
+ * a material map, a heightmap sampler, or anything else. It does **not** load — pair it with
2050
+ * `useTexture` for loading (registry enrollment is on by default); `useTextures` is for access and lifecycle.
2051
+ *
2052
+ * The returned handle is **reactive**: the calling component re-renders when the registry
2053
+ * changes. Pass a selector to scope the subscription to a single read.
1884
2054
  *
1885
2055
  * @example
1886
2056
  * ```tsx
1887
- * const { textures, add, get, remove, has, dispose } = useTextures()
1888
- *
1889
- * // Check if texture is already cached
1890
- * if (!has('/textures/diffuse.png')) {
1891
- * // Load with useTexture and cache: true, or manually add
1892
- * const tex = useTexture('/textures/diffuse.png', { cache: true })
1893
- * }
2057
+ * // Load + register once (anywhere in the tree) — registered by default
2058
+ * useTexture({ map: '/diffuse.jpg', normalMap: '/normal.jpg' })
1894
2059
  *
1895
- * // Access cached texture from anywhere
1896
- * const diffuse = get('/textures/diffuse.png')
1897
- * if (diffuse) material.map = diffuse
2060
+ * // Reach them from another component — record form lands straight into a material
2061
+ * const { map, normalMap } = useTextures().get({ map: '/diffuse.jpg', normalMap: '/normal.jpg' })
2062
+ * return <meshStandardMaterial map={map} normalMap={normalMap} />
1898
2063
  *
1899
- * // Remove from cache only (texture still in GPU memory)
1900
- * remove('/textures/old.png')
2064
+ * // A set of heightmaps at once
2065
+ * const [a, b, c] = useTextures().get(['/h0.png', '/h1.png', '/h2.png'])
1901
2066
  *
1902
- * // Fully dispose (frees GPU memory + removes from cache)
1903
- * dispose('/textures/unused.png')
2067
+ * // Register a non-URL texture (render target / procedural)
2068
+ * useTextures().add('rt-main', renderTarget.texture)
1904
2069
  *
1905
- * // Nuclear option - dispose everything
1906
- * disposeAll()
2070
+ * // Deliberate GPU cleanup (refcount-aware; force to override)
2071
+ * useTextures().dispose('/diffuse.jpg')
2072
+ * useTextures().disposeAll() // scene teardown
1907
2073
  * ```
2074
+ *
2075
+ * @remarks
2076
+ * **Future expansion:** an imperative async loader (e.g. `await useTextures().load('/x.jpg')`) is
2077
+ * intentionally not included yet. It would let non-React code (loading screens, dynamic streaming)
2078
+ * populate the registry without Suspense, at the cost of putting loading back into this hook. It
2079
+ * will be added only if a concrete consumer needs imperative loading; for now, loading lives in
2080
+ * `useTexture`.
1908
2081
  */
1909
2082
  declare function useTextures(): UseTexturesReturn;
2083
+ declare function useTextures<T>(selector: (registry: UseTexturesReturn) => T): T;
1910
2084
 
1911
2085
  /**
1912
2086
  * Creates a render target compatible with the current renderer.
@@ -1915,31 +2089,30 @@ declare function useTextures(): UseTexturesReturn;
1915
2089
  * - WebGPU build: Returns RenderTarget
1916
2090
  * - Default build: Returns whichever matches the active renderer
1917
2091
  *
1918
- * @param width - Target width (defaults to canvas width)
1919
- * @param height - Target height (defaults to canvas height)
1920
- * @param options - Three.js RenderTarget options
1921
- *
1922
2092
  * @example
1923
2093
  * ```tsx
1924
- * function PortalScene() {
1925
- * const fbo = useRenderTarget(512, 512, { depthBuffer: true })
1926
- *
1927
- * useFrame(({ renderer, scene, camera }) => {
1928
- * renderer.setRenderTarget(fbo)
1929
- * renderer.render(scene, camera)
1930
- * renderer.setRenderTarget(null)
1931
- * })
1932
- *
1933
- * return (
1934
- * <mesh>
1935
- * <planeGeometry />
1936
- * <meshBasicMaterial map={fbo.texture} />
1937
- * </mesh>
1938
- * )
1939
- * }
2094
+ * // Use canvas size
2095
+ * const fbo = useRenderTarget()
2096
+ *
2097
+ * // Use canvas size with options
2098
+ * const fbo = useRenderTarget({ samples: 4 })
2099
+ *
2100
+ * // Square render target
2101
+ * const fbo = useRenderTarget(512)
2102
+ *
2103
+ * // Square render target with options
2104
+ * const fbo = useRenderTarget(512, { depthBuffer: true })
2105
+ *
2106
+ * // Explicit dimensions
2107
+ * const fbo = useRenderTarget(512, 256)
2108
+ *
2109
+ * // Explicit dimensions with options
2110
+ * const fbo = useRenderTarget(512, 256, { samples: 4 })
1940
2111
  * ```
1941
2112
  */
1942
- declare function useRenderTarget(width?: number, height?: number, options?: RenderTargetOptions): RenderTarget<THREE$1.Texture<unknown>>;
2113
+ declare function useRenderTarget(options?: RenderTargetOptions): WebGLRenderTarget;
2114
+ declare function useRenderTarget(size: number, options?: RenderTargetOptions): WebGLRenderTarget;
2115
+ declare function useRenderTarget(width: number, height: number, options?: RenderTargetOptions): WebGLRenderTarget;
1943
2116
 
1944
2117
  /**
1945
2118
  * Returns the R3F Canvas' Zustand store. Useful for [transient updates](https://github.com/pmndrs/zustand#transient-updates-for-often-occurring-state-changes).
@@ -2026,7 +2199,10 @@ declare function addTail(callback: GlobalRenderCallback): () => void;
2026
2199
  * Invalidates the view, requesting a frame to be rendered.
2027
2200
  * In demand mode, this triggers the scheduler to run frames.
2028
2201
  *
2029
- * @param state - Optional root state (ignored in new scheduler, kept for backwards compat)
2202
+ * With a state argument, only that root's jobs run on the requested frames; other
2203
+ * roots on 'demand' stay idle. Without one, every registered root is invalidated.
2204
+ *
2205
+ * @param state - Optional root state; targets the invalidation at that root
2030
2206
  * @param frames - Number of frames to request (default: 1)
2031
2207
  * @param stackFrames - If false, sets pendingFrames to frames. If true, adds to existing pendingFrames (default: false)
2032
2208
  *
@@ -2037,14 +2213,16 @@ declare function invalidate(state?: RootState, frames?: number, stackFrames?: bo
2037
2213
  * Advances the frameloop and runs render effects.
2038
2214
  * Useful for when manually rendering via `frameloop="never"`.
2039
2215
  *
2216
+ * With a state argument, only that root is stepped. Without one, every
2217
+ * registered root is stepped for backwards compatibility.
2218
+ *
2040
2219
  * @param timestamp - The timestamp to use for this frame
2041
2220
  * @param runGlobalEffects - Ignored (kept for backwards compat, global effects always run)
2042
- * @param state - Ignored (kept for backwards compat)
2043
- * @param frame - Ignored (kept for backwards compat)
2221
+ * @param state - Optional root state; targets the manual step at that root
2044
2222
  *
2045
2223
  * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#advance
2046
2224
  */
2047
- declare function advance(timestamp: number, runGlobalEffects?: boolean, state?: RootState, frame?: XRFrame): void;
2225
+ declare function advance(timestamp: number, runGlobalEffects?: boolean, state?: RootState): void;
2048
2226
 
2049
2227
  /* eslint-disable @definitelytyped/no-unnecessary-generics */
2050
2228
  declare function ReactReconciler<
@@ -3098,6 +3276,12 @@ declare const _roots: Map<HTMLCanvasElement | OffscreenCanvas, Root>;
3098
3276
  declare function createRoot<TCanvas extends HTMLCanvasElement | OffscreenCanvas>(canvas: TCanvas): ReconcilerRoot<TCanvas>;
3099
3277
  declare function unmountComponentAtNode<TCanvas extends HTMLCanvasElement | OffscreenCanvas>(canvas: TCanvas, callback?: (canvas: TCanvas) => void): void;
3100
3278
  declare function createPortal(children: ReactNode, container: Object3D | RefObject<Object3D | null> | RefObject<Object3D>, state?: InjectState): JSX.Element;
3279
+ interface PortalProps {
3280
+ children: ReactNode;
3281
+ state?: InjectState;
3282
+ container: Object3D | RefObject<Object3D | null> | RefObject<Object3D>;
3283
+ }
3284
+ declare function Portal({ children, container, state }: PortalProps): JSX.Element;
3101
3285
  /**
3102
3286
  * Force React to flush any updates inside the provided callback synchronously and immediately.
3103
3287
  * All the same caveats documented for react-dom's `flushSync` apply here (see https://react.dev/reference/react-dom/flushSync).
@@ -3109,11 +3293,6 @@ declare function flushSync<R>(fn: () => R): R;
3109
3293
  declare const context: React$1.Context<RootStore>;
3110
3294
  declare const createStore: (invalidate: (state?: RootState, frames?: number, stackFrames?: boolean) => void, advance: (timestamp: number, runGlobalEffects?: boolean, state?: RootState, frame?: XRFrame) => void) => RootStore;
3111
3295
 
3112
- /**
3113
- * Safely flush async effects when testing, simulating a legacy root.
3114
- * @deprecated Import from React instead. import { act } from 'react'
3115
- */
3116
- declare const act: typeof React$1.act;
3117
3296
  /**
3118
3297
  * An SSR-friendly useLayoutEffect.
3119
3298
  *
@@ -3526,11 +3705,76 @@ declare const hasConstructor: (object: unknown) => object is {
3526
3705
  constructor?: Function;
3527
3706
  };
3528
3707
 
3708
+ /**
3709
+ * Symbol marker for deferred ref resolution.
3710
+ * Used to identify values that should be resolved from refs after mount.
3711
+ */
3712
+ declare const FROM_REF: unique symbol;
3713
+ /**
3714
+ * Defers prop application until the referenced object is available.
3715
+ * Useful for props like `target` that need sibling refs to be populated.
3716
+ *
3717
+ * @param ref - React ref object to resolve at mount time
3718
+ * @returns A marker value that applyProps will resolve after mount
3719
+ *
3720
+ * @example
3721
+ * const targetRef = useRef<THREE.Object3D>(null)
3722
+ *
3723
+ * <group ref={targetRef} position={[-3, -2, -15]} />
3724
+ * <spotLight target={fromRef(targetRef)} intensity={100} />
3725
+ */
3726
+ declare function fromRef<T>(ref: React$1.RefObject<T | null>): T;
3727
+ /**
3728
+ * Type guard to check if a value is a fromRef marker.
3729
+ *
3730
+ * @param value - Value to check
3731
+ * @returns True if value is a fromRef marker
3732
+ */
3733
+ declare function isFromRef(value: unknown): value is {
3734
+ [FROM_REF]: React$1.RefObject<any>;
3735
+ };
3736
+
3737
+ /**
3738
+ * Symbol marker for mount-only method calls.
3739
+ * Used to identify methods that should only be called once on initial mount.
3740
+ */
3741
+ declare const ONCE: unique symbol;
3742
+ /**
3743
+ * Marks a method call to be executed only on initial mount.
3744
+ * Useful for geometry transforms that should not be reapplied on every render.
3745
+ *
3746
+ * When `args` prop changes (triggering reconstruction), the method will be
3747
+ * called again on the new instance since appliedOnce is not carried over.
3748
+ *
3749
+ * @param args - Arguments to pass to the method
3750
+ * @returns A marker value that applyProps will execute once
3751
+ *
3752
+ * @example
3753
+ * // Rotate geometry on mount
3754
+ * <boxGeometry args={[1, 1, 1]} rotateX={once(Math.PI / 2)} />
3755
+ *
3756
+ * // Multiple arguments
3757
+ * <bufferGeometry applyMatrix4={once(matrix)} />
3758
+ *
3759
+ * // No arguments
3760
+ * <geometry center={once()} />
3761
+ */
3762
+ declare function once<T>(...args: T[]): T;
3763
+ /**
3764
+ * Type guard to check if a value is a once marker.
3765
+ *
3766
+ * @param value - Value to check
3767
+ * @returns True if value is a once marker
3768
+ */
3769
+ declare function isOnce(value: unknown): value is {
3770
+ [ONCE]: any[] | true;
3771
+ };
3772
+
3529
3773
  /**
3530
3774
  * A DOM canvas which accepts threejs elements as children.
3531
3775
  * @see https://docs.pmnd.rs/react-three-fiber/api/canvas
3532
3776
  */
3533
3777
  declare function Canvas(props: CanvasProps): react_jsx_runtime.JSX.Element;
3534
3778
 
3535
- export { Block, Canvas, ErrorBoundary, IsObject, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, REACT_INTERNAL_PROPS, RESERVED_PROPS, three_d as ReactThreeFiber, Scheduler, Texture, _roots, act, addAfterEffect, addEffect, addTail, advance, applyProps, attach, buildGraph, calculateDpr, context, createEvents, createPointerEvents, createPortal, createRoot, createStore, detach, diffProps, dispose, createPointerEvents as events, extend, findInitialRoot, flushSync, getInstanceProps, getRootState, getScheduler, getUuidPrefix, hasConstructor, invalidate, invalidateInstance, is, isColorRepresentation, isCopyable, isObject3D, isOrthographicCamera, isRef, isRenderer, isTexture, isVectorLike, prepare, reconciler, removeInteractivity, resolve, unmountComponentAtNode, updateCamera, updateFrustum, useBridge, useFrame, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useMutableCallback, useRenderTarget, useStore, useTexture, useTextures, useThree };
3536
- export type { Act, AddPhaseOptions, Args, ArgsProp, AttachFnType, AttachType, BaseRendererProps, Bridge, Camera, CameraProps, CanvasProps, Catalogue, Color, ComputeFunction, ConstructorRepresentation, DefaultGLProps, DefaultRendererProps, Disposable, DomEvent, Dpr, ElementProps, EquConfig, Euler, EventHandlers, EventManager, EventProps, Events, Extensions, FiberRoot, FilterFunction, FrameCallback, FrameControls, FrameNextCallback, FrameNextControls, FrameNextState, FrameState, FrameTimingState, Frameloop, GLProps, GLTFLike, GlobalEffectType, GlobalRenderCallback, HostConfig, InferLoadResult, InjectState, InputLike, Instance, InstanceProps, InternalState, Intersection, IntersectionEvent, IsAllOptional, IsOptional, Layers, LoaderInstance, LoaderLike, LoaderResult, MappedTextureType, MathProps, MathRepresentation, MathType, MathTypes, Matrix3, Matrix4, Mutable, MutableOrReadonlyParameters, NonFunctionKeys, ObjectMap, OffscreenCanvas$1 as OffscreenCanvas, Overwrite, Performance, PointerCaptureTarget, Properties, Quaternion, RaycastableRepresentation, ReactProps, ReconcilerRoot, RenderCallback, RenderProps, RenderTargetOptions, Renderer, RendererFactory, RendererProps, Root, RootOptions, RootState, RootStore, SchedulerApi, SetBlock, Size, Subscription, TextureEntry, ThreeCamera, ThreeElement, ThreeElements, ThreeElementsImpl, ThreeEvent, ThreeExports, ThreeToJSXElements, UnblockProps, UseFrameNextOptions, UseFrameOptions, UseTextureOptions, UseTexturesReturn, Vector2, Vector3, Vector4, VectorRepresentation, Viewport, VisibilityEntry, WebGLDefaultProps, WebGLProps, WebGLShadowConfig, XRManager };
3779
+ export { Block, Canvas, Environment, EnvironmentCube, EnvironmentMap, EnvironmentPortal, ErrorBoundary, FROM_REF, IsObject, ONCE, Portal, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, REACT_INTERNAL_PROPS, RESERVED_PROPS, three_d as ReactThreeFiber, Texture, _roots, addAfterEffect, addEffect, addTail, advance, applyProps, attach, buildGraph, calculateDpr, context, createEvents, createPointerEvents, createPortal, createRoot, createStore, detach, diffProps, dispose, createPointerEvents as events, extend, findInitialRoot, flushSync, fromRef, getInstanceProps, getPrimary, getPrimaryIds, getRootState, getUuidPrefix, hasConstructor, hasPrimary, invalidate, invalidateInstance, is, isColorRepresentation, isCopyable, isFromRef, isObject3D, isOnce, isOrthographicCamera, isRef, isRenderer, isTexture, isVectorLike, once, prepare, presetsObj, reconciler, registerPrimary, removeInteractivity, resolve, swapInteractivity, unmountComponentAtNode, unregisterPrimary, updateCamera, updateFrustum, useBridge, useEnvironment, useFrame, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useMutableCallback, useRenderTarget, useStore, useTexture, useTextures, useThree, waitForPrimary };
3780
+ export type { Act, Args, ArgsProp, AttachFnType, AttachType, BackgroundConfig, BackgroundProp, BaseRendererProps, Bridge, BufferLike, BufferRecord, BufferStore, Camera, CameraProps, CanvasProps, CanvasSchedulerConfig, Catalogue, Color, ColorManagementConfig, ComputeFunction, ConstructorRepresentation, DefaultGLProps, DefaultRendererProps, Disposable, DisposeOptions, DomEvent, Dpr, ElementProps, EnvironmentLoaderProps, EnvironmentProps, EquConfig, Euler, EventHandlers, EventManager, EventProps, Events, Extensions, FiberRoot, FilterFunction, FrameCallback, FrameNextCallback, FrameNextState, FrameState, Frameloop, GLProps, GLTFLike, GeometryProps, GeometryTransformProps, GlobalEffectType, GlobalRenderCallback, HostConfig, InferLoadResult, InjectState, InputLike, Instance, InstanceProps, LegacyInternalState as InternalState, Intersection, IntersectionEvent, IsAllOptional, IsOptional, Layers, LegacyInternalState, LegacyRenderer, LegacyRootState, LoaderInstance, LoaderLike, LoaderResult, MappedTextureType, MathProps, MathRepresentation, MathType, MathTypes, Matrix3, Matrix4, Mutable, MutableOrReadonlyParameters, NodeProps, NonFunctionKeys, ObjectMap, OffscreenCanvas$1 as OffscreenCanvas, Overwrite, Performance, PointerCaptureTarget, PointerState, PresetsType, PrimaryCanvasEntry, Properties, Quaternion, LegacyRenderer as R3FRenderer, RaycastableRepresentation, ReactProps, ReconcilerRoot, RenderCallback, RenderProps, RenderTargetOptions, Renderer, RendererConfigExtended, RendererFactory, RendererProps, Root, LegacyRootState as RootState, RootStore, SetBlock, Size, StorageLike, StorageRecord, StorageStore, Subscription, TSLNodeInput, TextureInput, TextureResult, ThreeCamera, ThreeElement, ThreeElements, ThreeElementsImpl, ThreeEvent, ThreeExports, ThreeToJSXElements, UnblockProps, UseTextureOptions, UseTexturesReturn, Vector2, Vector3, Vector4, VectorRepresentation, Viewport, VisibilityEntry, WebGLDefaultProps, WebGLProps, WebGLShadowConfig, XRManager, XRPointerConfig };