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