@gnsx/react-three-fiber 10.0.1 → 10.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/legacy.d.mts CHANGED
@@ -56,1076 +56,1076 @@ var THREE = /*#__PURE__*/_mergeNamespaces({
56
56
  WebGPURenderer: WebGPURenderer
57
57
  }, [THREE$1]);
58
58
 
59
- //* Utility Types ==============================
60
-
61
- type NonFunctionKeys<P> = { [K in keyof P]-?: P[K] extends Function ? never : K }[keyof P]
62
- type Overwrite<P, O> = Omit<P, NonFunctionKeys<O>> & O
63
- type Properties<T> = Pick<T, NonFunctionKeys<T>>
64
- type Mutable<P> = { -readonly [K in keyof P]: P[K] }
65
- type IsOptional<T> = undefined extends T ? true : false
66
- type IsAllOptional<T extends any[]> = T extends [infer First, ...infer Rest]
67
- ? IsOptional<First> extends true
68
- ? IsAllOptional<Rest>
69
- : false
70
- : true
71
-
72
- //* Camera Types ==============================
73
-
74
- type ThreeCamera = (THREE$1.OrthographicCamera | THREE$1.PerspectiveCamera) & { manual?: boolean }
75
-
76
- //* Act Type ==============================
77
-
78
- type Act = <T = any>(cb: () => Promise<T>) => Promise<T>
79
-
80
- //* Bridge & Block Types ==============================
81
-
82
- type Bridge = React$1.FC<{ children?: React$1.ReactNode }>
83
-
84
- type SetBlock = false | Promise<null> | null
85
- type UnblockProps = { set: React$1.Dispatch<React$1.SetStateAction<SetBlock>>; children: React$1.ReactNode }
86
-
87
- //* Object Map Type ==============================
88
-
89
- /* Original version
90
- export interface ObjectMap {
91
- nodes: { [name: string]: THREE.Object3D }
92
- materials: { [name: string]: THREE.Material }
93
- meshes: { [name: string]: THREE.Mesh }
94
- }
95
- */
96
- /* This version is an expansion found in a PR by itsdouges that seems abandoned but looks useful.
97
- It allows expansion but falls back to the original shape. (deleted due to stale, but If it doesnt conflict
98
- I will keep the use here)
99
- https://github.com/pmndrs/react-three-fiber/commits/generic-object-map/
100
- His description is:
101
- The object map type is now generic and can optionally declare the available properties for nodes, materials, and meshes.
102
- */
103
- interface ObjectMap<
104
- T extends { nodes?: string; materials?: string; meshes?: string } = {
105
- nodes: string
106
- materials: string
107
- meshes: string
108
- },
109
- > {
110
- nodes: Record<T['nodes'] extends string ? T['nodes'] : string, THREE$1.Object3D>
111
- materials: Record<T['materials'] extends string ? T['materials'] : string, THREE$1.Material>
112
- meshes: Record<T['meshes'] extends string ? T['meshes'] : string, THREE$1.Mesh>
113
- }
114
-
115
- //* Equality Config ==============================
116
-
117
- interface EquConfig {
118
- /** Compare arrays by reference equality a === b (default), or by shallow equality */
119
- arrays?: 'reference' | 'shallow'
120
- /** Compare objects by reference equality a === b (default), or by shallow equality */
121
- objects?: 'reference' | 'shallow'
122
- /** If true the keys in both a and b must match 1:1 (default), if false a's keys must intersect b's */
123
- strict?: boolean
124
- }
125
-
126
- //* Disposable Type ==============================
127
-
128
- interface Disposable {
129
- type?: string
130
- dispose?: () => void
59
+ //* Utility Types ==============================
60
+
61
+ type NonFunctionKeys<P> = { [K in keyof P]-?: P[K] extends Function ? never : K }[keyof P]
62
+ type Overwrite<P, O> = Omit<P, NonFunctionKeys<O>> & O
63
+ type Properties<T> = Pick<T, NonFunctionKeys<T>>
64
+ type Mutable<P> = { -readonly [K in keyof P]: P[K] }
65
+ type IsOptional<T> = undefined extends T ? true : false
66
+ type IsAllOptional<T extends any[]> = T extends [infer First, ...infer Rest]
67
+ ? IsOptional<First> extends true
68
+ ? IsAllOptional<Rest>
69
+ : false
70
+ : true
71
+
72
+ //* Camera Types ==============================
73
+
74
+ type ThreeCamera = (THREE$1.OrthographicCamera | THREE$1.PerspectiveCamera) & { manual?: boolean }
75
+
76
+ //* Act Type ==============================
77
+
78
+ type Act = <T = any>(cb: () => Promise<T>) => Promise<T>
79
+
80
+ //* Bridge & Block Types ==============================
81
+
82
+ type Bridge = React$1.FC<{ children?: React$1.ReactNode }>
83
+
84
+ type SetBlock = false | Promise<null> | null
85
+ type UnblockProps = { set: React$1.Dispatch<React$1.SetStateAction<SetBlock>>; children: React$1.ReactNode }
86
+
87
+ //* Object Map Type ==============================
88
+
89
+ /* Original version
90
+ export interface ObjectMap {
91
+ nodes: { [name: string]: THREE.Object3D }
92
+ materials: { [name: string]: THREE.Material }
93
+ meshes: { [name: string]: THREE.Mesh }
94
+ }
95
+ */
96
+ /* This version is an expansion found in a PR by itsdouges that seems abandoned but looks useful.
97
+ It allows expansion but falls back to the original shape. (deleted due to stale, but If it doesnt conflict
98
+ I will keep the use here)
99
+ https://github.com/pmndrs/react-three-fiber/commits/generic-object-map/
100
+ His description is:
101
+ The object map type is now generic and can optionally declare the available properties for nodes, materials, and meshes.
102
+ */
103
+ interface ObjectMap<
104
+ T extends { nodes?: string; materials?: string; meshes?: string } = {
105
+ nodes: string
106
+ materials: string
107
+ meshes: string
108
+ },
109
+ > {
110
+ nodes: Record<T['nodes'] extends string ? T['nodes'] : string, THREE$1.Object3D>
111
+ materials: Record<T['materials'] extends string ? T['materials'] : string, THREE$1.Material>
112
+ meshes: Record<T['meshes'] extends string ? T['meshes'] : string, THREE$1.Mesh>
113
+ }
114
+
115
+ //* Equality Config ==============================
116
+
117
+ interface EquConfig {
118
+ /** Compare arrays by reference equality a === b (default), or by shallow equality */
119
+ arrays?: 'reference' | 'shallow'
120
+ /** Compare objects by reference equality a === b (default), or by shallow equality */
121
+ objects?: 'reference' | 'shallow'
122
+ /** If true the keys in both a and b must match 1:1 (default), if false a's keys must intersect b's */
123
+ strict?: boolean
124
+ }
125
+
126
+ //* Disposable Type ==============================
127
+
128
+ interface Disposable {
129
+ type?: string
130
+ dispose?: () => void
131
131
  }
132
132
 
133
- //* Event-related Types =====================================
134
-
135
- interface Intersection extends THREE$1.Intersection {
136
- /** The event source (the object which registered the handler) */
137
- eventObject: THREE$1.Object3D
138
- }
139
-
140
- type Camera = THREE$1.OrthographicCamera | THREE$1.PerspectiveCamera
141
-
142
- interface IntersectionEvent<TSourceEvent> extends Intersection {
143
- /** The event source (the object which registered the handler) */
144
- eventObject: THREE$1.Object3D
145
- /** An array of intersections */
146
- intersections: Intersection[]
147
- /** vec3.set(pointer.x, pointer.y, 0).unproject(camera) */
148
- unprojectedPoint: THREE$1.Vector3
149
- /** Normalized event coordinates */
150
- pointer: THREE$1.Vector2
151
- /** pointerId of the original event for multiple pointer events */
152
- pointerId: number
153
- /** Delta between first click and this event */
154
- delta: number
155
- /** The ray that pierced it */
156
- ray: THREE$1.Ray
157
- /** The camera that was used by the raycaster */
158
- camera: Camera
159
- /** stopPropagation will stop underlying handlers from firing */
160
- stopPropagation: () => void
161
- /** The original host event */
162
- nativeEvent: TSourceEvent
163
- /** If the event was stopped by calling stopPropagation */
164
- stopped: boolean
165
- }
166
-
167
- type ThreeEvent<TEvent> = IntersectionEvent<TEvent> & Properties<TEvent>
168
- type DomEvent = PointerEvent | MouseEvent | WheelEvent
169
-
170
- /** DOM event handlers registered on the canvas element */
171
- interface Events {
172
- onClick: EventListener
173
- onContextMenu: EventListener
174
- onDoubleClick: EventListener
175
- onWheel: EventListener
176
- onPointerDown: EventListener
177
- onPointerUp: EventListener
178
- onPointerLeave: EventListener
179
- onPointerMove: EventListener
180
- onPointerCancel: EventListener
181
- onLostPointerCapture: EventListener
182
- onDragEnter: EventListener
183
- onDragLeave: EventListener
184
- onDragOver: EventListener
185
- onDrop: EventListener
186
- }
187
-
188
- /** Event handlers that can be attached to R3F objects (meshes, groups, etc.) */
189
- interface EventHandlers {
190
- onClick?: (event: ThreeEvent<MouseEvent>) => void
191
- onContextMenu?: (event: ThreeEvent<MouseEvent>) => void
192
- onDoubleClick?: (event: ThreeEvent<MouseEvent>) => void
193
- /** Fires continuously while dragging over the object */
194
- onDragOver?: (event: ThreeEvent<DragEvent>) => void
195
- /** Fires once when drag enters the object */
196
- onDragOverEnter?: (event: ThreeEvent<DragEvent>) => void
197
- /** Fires once when drag leaves the object */
198
- onDragOverLeave?: (event: ThreeEvent<DragEvent>) => void
199
- /** Fires when drag misses this object (for objects that have drag handlers) */
200
- onDragOverMissed?: (event: DragEvent) => void
201
- /** Fires when a drop occurs on this object */
202
- onDrop?: (event: ThreeEvent<DragEvent>) => void
203
- /** Fires when a drop misses this object (for objects that have drop handlers) */
204
- onDropMissed?: (event: DragEvent) => void
205
- onPointerUp?: (event: ThreeEvent<PointerEvent>) => void
206
- onPointerDown?: (event: ThreeEvent<PointerEvent>) => void
207
- onPointerOver?: (event: ThreeEvent<PointerEvent>) => void
208
- onPointerOut?: (event: ThreeEvent<PointerEvent>) => void
209
- onPointerEnter?: (event: ThreeEvent<PointerEvent>) => void
210
- onPointerLeave?: (event: ThreeEvent<PointerEvent>) => void
211
- onPointerMove?: (event: ThreeEvent<PointerEvent>) => void
212
- onPointerMissed?: (event: MouseEvent) => void
213
- onPointerCancel?: (event: ThreeEvent<PointerEvent>) => void
214
- onWheel?: (event: ThreeEvent<WheelEvent>) => void
215
- onLostPointerCapture?: (event: ThreeEvent<PointerEvent>) => void
216
-
217
- //* Visibility Events --------------------------------
218
- /** Fires when object enters/exits camera frustum. Receives true when in view, false when out. */
219
- onFramed?: (inView: boolean) => void
220
- /** Fires when object occlusion state changes (WebGPU only, requires occlusionTest=true on object) */
221
- onOccluded?: (occluded: boolean) => void
222
- /** Fires when combined visibility changes (frustum + occlusion + visible prop) */
223
- onVisible?: (visible: boolean) => void
224
- }
225
-
226
- type FilterFunction = (items: THREE$1.Intersection[], state: RootState) => THREE$1.Intersection[]
227
- type ComputeFunction = (event: DomEvent, root: RootState, previous?: RootState) => void
228
-
229
- /** Configuration for XR pointer registration (controllers/hands) */
230
- interface XRPointerConfig {
231
- /** Ray origin (updated each frame by XR system) */
232
- ray: THREE$1.Ray
233
- /** Optional: custom compute function for this pointer */
234
- compute?: (state: RootState) => void
235
- /** Pointer type identifier */
236
- type: 'controller' | 'hand' | 'gaze'
237
- /** Which hand (for controller/hand types) */
238
- handedness?: 'left' | 'right'
239
- }
240
-
241
- interface EventManager<TTarget> {
242
- /** Determines if the event layer is active */
243
- enabled: boolean
244
- /** Event layer priority, higher prioritized layers come first and may stop(-propagate) lower layer */
245
- priority: number
246
- /** The compute function needs to set up the raycaster and an xy- pointer */
247
- compute?: ComputeFunction
248
- /** The filter can re-order or re-structure the intersections */
249
- filter?: FilterFunction
250
- /** The target node the event layer is tied to */
251
- connected?: TTarget
252
- /** All the pointer event handlers through which the host forwards native events */
253
- handlers?: Events
254
- /** Allows re-connecting to another target */
255
- connect?: (target: TTarget) => void
256
- /** Removes all existing events handlers from the target */
257
- disconnect?: () => void
258
- /** Triggers a onPointerMove with the last known event. This can be useful to enable raycasting without
259
- * explicit user interaction, for instance when the camera moves a hoverable object underneath the cursor.
260
- * @param pointerId - Optional pointer ID to update specific pointer only
261
- */
262
- update?: (pointerId?: number) => void
263
- /** Defer pointer move raycasting to frame start (default: true) */
264
- frameTimedRaycasts?: boolean
265
- /** Always fire raycaster immediately on scroll events (default: true) */
266
- alwaysFireOnScroll?: boolean
267
- /** Automatically re-raycast every frame to detect hover changes from moving objects/camera (default: false) */
268
- updateOnFrame?: boolean
269
- /** Flush deferred pointer raycasts. Called by scheduler at frame start (input phase). */
270
- flush?: () => void
271
- /** Register an XR pointer (controller/hand). Returns assigned pointerId */
272
- registerPointer?: (config: XRPointerConfig) => number
273
- /** Unregister an XR pointer */
274
- unregisterPointer?: (pointerId: number) => void
275
- }
276
-
277
- interface PointerCaptureTarget {
278
- intersection: Intersection
279
- target: Element
280
- }
281
-
282
- //* Visibility System Types =====================================
283
-
284
- /** Entry in the visibility registry for tracking object visibility state */
285
- interface VisibilityEntry {
286
- object: THREE$1.Object3D
287
- handlers: Pick<EventHandlers, 'onFramed' | 'onOccluded' | 'onVisible'>
288
- lastFramedState: boolean | null
289
- lastOccludedState: boolean | null
290
- lastVisibleState: boolean | null
133
+ //* Event-related Types =====================================
134
+
135
+ interface Intersection extends THREE$1.Intersection {
136
+ /** The event source (the object which registered the handler) */
137
+ eventObject: THREE$1.Object3D
138
+ }
139
+
140
+ type Camera = THREE$1.OrthographicCamera | THREE$1.PerspectiveCamera
141
+
142
+ interface IntersectionEvent<TSourceEvent> extends Intersection {
143
+ /** The event source (the object which registered the handler) */
144
+ eventObject: THREE$1.Object3D
145
+ /** An array of intersections */
146
+ intersections: Intersection[]
147
+ /** vec3.set(pointer.x, pointer.y, 0).unproject(camera) */
148
+ unprojectedPoint: THREE$1.Vector3
149
+ /** Normalized event coordinates */
150
+ pointer: THREE$1.Vector2
151
+ /** pointerId of the original event for multiple pointer events */
152
+ pointerId: number
153
+ /** Delta between first click and this event */
154
+ delta: number
155
+ /** The ray that pierced it */
156
+ ray: THREE$1.Ray
157
+ /** The camera that was used by the raycaster */
158
+ camera: Camera
159
+ /** stopPropagation will stop underlying handlers from firing */
160
+ stopPropagation: () => void
161
+ /** The original host event */
162
+ nativeEvent: TSourceEvent
163
+ /** If the event was stopped by calling stopPropagation */
164
+ stopped: boolean
165
+ }
166
+
167
+ type ThreeEvent<TEvent> = IntersectionEvent<TEvent> & Properties<TEvent>
168
+ type DomEvent = PointerEvent | MouseEvent | WheelEvent
169
+
170
+ /** DOM event handlers registered on the canvas element */
171
+ interface Events {
172
+ onClick: EventListener
173
+ onContextMenu: EventListener
174
+ onDoubleClick: EventListener
175
+ onWheel: EventListener
176
+ onPointerDown: EventListener
177
+ onPointerUp: EventListener
178
+ onPointerLeave: EventListener
179
+ onPointerMove: EventListener
180
+ onPointerCancel: EventListener
181
+ onLostPointerCapture: EventListener
182
+ onDragEnter: EventListener
183
+ onDragLeave: EventListener
184
+ onDragOver: EventListener
185
+ onDrop: EventListener
186
+ }
187
+
188
+ /** Event handlers that can be attached to R3F objects (meshes, groups, etc.) */
189
+ interface EventHandlers {
190
+ onClick?: (event: ThreeEvent<MouseEvent>) => void
191
+ onContextMenu?: (event: ThreeEvent<MouseEvent>) => void
192
+ onDoubleClick?: (event: ThreeEvent<MouseEvent>) => void
193
+ /** Fires continuously while dragging over the object */
194
+ onDragOver?: (event: ThreeEvent<DragEvent>) => void
195
+ /** Fires once when drag enters the object */
196
+ onDragOverEnter?: (event: ThreeEvent<DragEvent>) => void
197
+ /** Fires once when drag leaves the object */
198
+ onDragOverLeave?: (event: ThreeEvent<DragEvent>) => void
199
+ /** Fires when drag misses this object (for objects that have drag handlers) */
200
+ onDragOverMissed?: (event: DragEvent) => void
201
+ /** Fires when a drop occurs on this object */
202
+ onDrop?: (event: ThreeEvent<DragEvent>) => void
203
+ /** Fires when a drop misses this object (for objects that have drop handlers) */
204
+ onDropMissed?: (event: DragEvent) => void
205
+ onPointerUp?: (event: ThreeEvent<PointerEvent>) => void
206
+ onPointerDown?: (event: ThreeEvent<PointerEvent>) => void
207
+ onPointerOver?: (event: ThreeEvent<PointerEvent>) => void
208
+ onPointerOut?: (event: ThreeEvent<PointerEvent>) => void
209
+ onPointerEnter?: (event: ThreeEvent<PointerEvent>) => void
210
+ onPointerLeave?: (event: ThreeEvent<PointerEvent>) => void
211
+ onPointerMove?: (event: ThreeEvent<PointerEvent>) => void
212
+ onPointerMissed?: (event: MouseEvent) => void
213
+ onPointerCancel?: (event: ThreeEvent<PointerEvent>) => void
214
+ onWheel?: (event: ThreeEvent<WheelEvent>) => void
215
+ onLostPointerCapture?: (event: ThreeEvent<PointerEvent>) => void
216
+
217
+ //* Visibility Events --------------------------------
218
+ /** Fires when object enters/exits camera frustum. Receives true when in view, false when out. */
219
+ onFramed?: (inView: boolean) => void
220
+ /** Fires when object occlusion state changes (WebGPU only, requires occlusionTest=true on object) */
221
+ onOccluded?: (occluded: boolean) => void
222
+ /** Fires when combined visibility changes (frustum + occlusion + visible prop) */
223
+ onVisible?: (visible: boolean) => void
224
+ }
225
+
226
+ type FilterFunction = (items: THREE$1.Intersection[], state: RootState) => THREE$1.Intersection[]
227
+ type ComputeFunction = (event: DomEvent, root: RootState, previous?: RootState) => void
228
+
229
+ /** Configuration for XR pointer registration (controllers/hands) */
230
+ interface XRPointerConfig {
231
+ /** Ray origin (updated each frame by XR system) */
232
+ ray: THREE$1.Ray
233
+ /** Optional: custom compute function for this pointer */
234
+ compute?: (state: RootState) => void
235
+ /** Pointer type identifier */
236
+ type: 'controller' | 'hand' | 'gaze'
237
+ /** Which hand (for controller/hand types) */
238
+ handedness?: 'left' | 'right'
291
239
  }
292
240
 
293
- //* Scheduler Types (useFrame) ==============================
294
-
295
-
296
-
297
- // Public Options --------------------------------
298
-
299
- /**
300
- * Options for useFrame hook
301
- */
302
- interface UseFrameNextOptions {
303
- /** Optional stable id for the job. Auto-generated if not provided */
304
- id?: string
305
- /** Named phase to run in. Default: 'update' */
306
- phase?: string
307
- /** Run before this phase or job id */
308
- before?: string | string[]
309
- /** Run after this phase or job id */
310
- after?: string | string[]
311
- /** Priority within phase. Higher runs first. Default: 0 */
312
- priority?: number
313
- /** Max frames per second for this job */
314
- fps?: number
315
- /** If true, skip frames when behind. If false, try to catch up. Default: true */
316
- drop?: boolean
317
- /** Enable/disable without unregistering. Default: true */
318
- enabled?: boolean
319
- }
320
-
321
- /** Alias for UseFrameNextOptions */
322
- type UseFrameOptions = UseFrameNextOptions
323
-
324
- /**
325
- * Options for addPhase
326
- */
327
- interface AddPhaseOptions {
328
- /** Insert this phase before the specified phase */
329
- before?: string
330
- /** Insert this phase after the specified phase */
331
- after?: string
332
- }
333
-
334
- // Frame State --------------------------------
335
-
336
- /**
337
- * Timing-only state for independent/outside mode (no RootState)
338
- */
339
- interface FrameTimingState {
340
- /** High-resolution timestamp from RAF (ms) */
341
- time: number
342
- /** Time since last frame in seconds (for legacy compatibility with THREE.Clock) */
343
- delta: number
344
- /** Elapsed time since first frame in seconds (for legacy compatibility with THREE.Clock) */
345
- elapsed: number
346
- /** Incrementing frame counter */
347
- frame: number
348
- }
349
-
350
- /**
351
- * State passed to useFrame callbacks (extends RootState with timing)
352
- */
353
- interface FrameNextState extends RootState, FrameTimingState {}
354
-
355
- /** Alias for FrameNextState */
356
- type FrameState = FrameNextState
357
-
358
- // Root Options --------------------------------
359
-
360
- /**
361
- * Options for registerRoot
362
- */
363
- interface RootOptions {
364
- /** State provider for callbacks. Optional in independent mode. */
365
- getState?: () => any
366
- /** Error handler for job errors. Falls back to console.error if not provided. */
367
- onError?: (error: Error) => void
368
- }
369
-
370
- // Callback Types --------------------------------
371
-
372
- /**
373
- * Callback function for useFrame
374
- */
375
- type FrameNextCallback = (state: FrameNextState, delta: number) => void
376
-
377
- /** Alias for FrameNextCallback */
378
- type FrameCallback = FrameNextCallback
379
-
380
- // Controls returned from useFrame --------------------------------
381
-
382
- /**
383
- * Controls object returned from useFrame hook
384
- */
385
- interface FrameNextControls {
386
- /** The job's unique ID */
387
- id: string
388
- /** Access to the global scheduler for frame loop control */
389
- scheduler: SchedulerApi
390
- /** Manually step this job only (bypasses FPS limiting) */
391
- step(timestamp?: number): void
392
- /** Manually step ALL jobs in the scheduler */
393
- stepAll(timestamp?: number): void
394
- /** Pause this job (set enabled=false) */
395
- pause(): void
396
- /** Resume this job (set enabled=true) */
397
- resume(): void
398
- /** Reactive paused state - automatically triggers re-render when changed */
399
- isPaused: boolean
400
- }
401
-
402
- /** Alias for FrameNextControls */
403
- type FrameControls = FrameNextControls
404
-
405
- // Scheduler Interface --------------------------------
406
-
407
- /**
408
- * Public interface for the global Scheduler
409
- */
410
- interface SchedulerApi {
411
- //* Phase Management --------------------------------
412
-
413
- /** Add a named phase to the scheduler */
414
- addPhase(name: string, options?: AddPhaseOptions): void
415
- /** Get the ordered list of phase names */
416
- readonly phases: string[]
417
- /** Check if a phase exists */
418
- hasPhase(name: string): boolean
419
-
420
- //* Root Management --------------------------------
421
-
422
- /** Register a root (Canvas) with the scheduler. Returns unsubscribe function. */
423
- registerRoot(id: string, options?: RootOptions): () => void
424
- /** Unregister a root */
425
- unregisterRoot(id: string): void
426
- /** Generate a unique root ID */
427
- generateRootId(): string
428
- /** Get the number of registered roots */
429
- getRootCount(): number
430
- /** Check if any root is registered and ready */
431
- readonly isReady: boolean
432
- /** Subscribe to root-ready event. Fires immediately if already ready. Returns unsubscribe. */
433
- onRootReady(callback: () => void): () => void
434
-
435
- //* Job Registration --------------------------------
436
-
437
- /** Register a job with the scheduler (returns unsubscribe function) */
438
- register(
439
- callback: FrameNextCallback,
440
- options?: {
441
- id?: string
442
- rootId?: string
443
- phase?: string
444
- before?: string | string[]
445
- after?: string | string[]
446
- priority?: number
447
- fps?: number
448
- drop?: boolean
449
- enabled?: boolean
450
- },
451
- ): () => void
452
- /** Update a job's options */
453
- updateJob(
454
- id: string,
455
- options: {
456
- priority?: number
457
- fps?: number
458
- drop?: boolean
459
- enabled?: boolean
460
- phase?: string
461
- before?: string | string[]
462
- after?: string | string[]
463
- },
464
- ): void
465
- /** Unregister a job by ID */
466
- unregister(id: string, rootId?: string): void
467
- /** Get the number of registered jobs */
468
- getJobCount(): number
469
- /** Get all job IDs */
470
- getJobIds(): string[]
471
-
472
- //* Global Jobs (for legacy addEffect/addAfterEffect) --------------------------------
473
-
474
- /** Register a global job (runs once per frame, not per-root). Returns unsubscribe function. */
475
- registerGlobal(phase: 'before' | 'after', id: string, callback: (timestamp: number) => void): () => void
476
-
477
- //* Idle Callbacks (for legacy addTail) --------------------------------
478
-
479
- /** Register an idle callback (fires when loop stops). Returns unsubscribe function. */
480
- onIdle(callback: (timestamp: number) => void): () => void
481
-
482
- //* Frame Loop Control --------------------------------
483
-
484
- /** Start the scheduler loop */
485
- start(): void
486
- /** Stop the scheduler loop */
487
- stop(): void
488
- /** Check if the scheduler is running */
489
- readonly isRunning: boolean
490
- /** Get/set the frameloop mode ('always', 'demand', 'never') */
491
- frameloop: Frameloop
492
- /** Independent mode - runs without Canvas, callbacks receive timing-only state */
493
- independent: boolean
494
-
495
- //* Manual Stepping --------------------------------
496
-
497
- /** Manually step all jobs once (for frameloop='never' or testing) */
498
- step(timestamp?: number): void
499
- /** Manually step a single job by ID */
500
- stepJob(id: string, timestamp?: number): void
501
- /** Request frame(s) to be rendered (for frameloop='demand') */
502
- invalidate(frames?: number): void
503
-
504
- //* Per-Job Control --------------------------------
505
-
506
- /** Check if a job is paused */
507
- isJobPaused(id: string): boolean
508
- /** Pause a job */
509
- pauseJob(id: string): void
510
- /** Resume a job */
511
- resumeJob(id: string): void
512
- /** Subscribe to job state changes (for reactive isPaused). Returns unsubscribe function. */
513
- subscribeJobState(id: string, listener: () => void): () => void
241
+ interface EventManager<TTarget> {
242
+ /** Determines if the event layer is active */
243
+ enabled: boolean
244
+ /** Event layer priority, higher prioritized layers come first and may stop(-propagate) lower layer */
245
+ priority: number
246
+ /** The compute function needs to set up the raycaster and an xy- pointer */
247
+ compute?: ComputeFunction
248
+ /** The filter can re-order or re-structure the intersections */
249
+ filter?: FilterFunction
250
+ /** The target node the event layer is tied to */
251
+ connected?: TTarget
252
+ /** All the pointer event handlers through which the host forwards native events */
253
+ handlers?: Events
254
+ /** Allows re-connecting to another target */
255
+ connect?: (target: TTarget) => void
256
+ /** Removes all existing events handlers from the target */
257
+ disconnect?: () => void
258
+ /** Triggers a onPointerMove with the last known event. This can be useful to enable raycasting without
259
+ * explicit user interaction, for instance when the camera moves a hoverable object underneath the cursor.
260
+ * @param pointerId - Optional pointer ID to update specific pointer only
261
+ */
262
+ update?: (pointerId?: number) => void
263
+ /** Defer pointer move raycasting to frame start (default: true) */
264
+ frameTimedRaycasts?: boolean
265
+ /** Always fire raycaster immediately on scroll events (default: true) */
266
+ alwaysFireOnScroll?: boolean
267
+ /** Automatically re-raycast every frame to detect hover changes from moving objects/camera (default: false) */
268
+ updateOnFrame?: boolean
269
+ /** Flush deferred pointer raycasts. Called by scheduler at frame start (input phase). */
270
+ flush?: () => void
271
+ /** Register an XR pointer (controller/hand). Returns assigned pointerId */
272
+ registerPointer?: (config: XRPointerConfig) => number
273
+ /** Unregister an XR pointer */
274
+ unregisterPointer?: (pointerId: number) => void
275
+ }
276
+
277
+ interface PointerCaptureTarget {
278
+ intersection: Intersection
279
+ target: Element
280
+ }
281
+
282
+ //* Visibility System Types =====================================
283
+
284
+ /** Entry in the visibility registry for tracking object visibility state */
285
+ interface VisibilityEntry {
286
+ object: THREE$1.Object3D
287
+ handlers: Pick<EventHandlers, 'onFramed' | 'onOccluded' | 'onVisible'>
288
+ lastFramedState: boolean | null
289
+ lastOccludedState: boolean | null
290
+ lastVisibleState: boolean | null
291
+ }
292
+
293
+ //* Scheduler Types (useFrame) ==============================
294
+
295
+
296
+
297
+ // Public Options --------------------------------
298
+
299
+ /**
300
+ * Options for useFrame hook
301
+ */
302
+ interface UseFrameNextOptions {
303
+ /** Optional stable id for the job. Auto-generated if not provided */
304
+ id?: string
305
+ /** Named phase to run in. Default: 'update' */
306
+ phase?: string
307
+ /** Run before this phase or job id */
308
+ before?: string | string[]
309
+ /** Run after this phase or job id */
310
+ after?: string | string[]
311
+ /** Priority within phase. Higher runs first. Default: 0 */
312
+ priority?: number
313
+ /** Max frames per second for this job */
314
+ fps?: number
315
+ /** If true, skip frames when behind. If false, try to catch up. Default: true */
316
+ drop?: boolean
317
+ /** Enable/disable without unregistering. Default: true */
318
+ enabled?: boolean
319
+ }
320
+
321
+ /** Alias for UseFrameNextOptions */
322
+ type UseFrameOptions = UseFrameNextOptions
323
+
324
+ /**
325
+ * Options for addPhase
326
+ */
327
+ interface AddPhaseOptions {
328
+ /** Insert this phase before the specified phase */
329
+ before?: string
330
+ /** Insert this phase after the specified phase */
331
+ after?: string
332
+ }
333
+
334
+ // Frame State --------------------------------
335
+
336
+ /**
337
+ * Timing-only state for independent/outside mode (no RootState)
338
+ */
339
+ interface FrameTimingState {
340
+ /** High-resolution timestamp from RAF (ms) */
341
+ time: number
342
+ /** Time since last frame in seconds (for legacy compatibility with THREE.Clock) */
343
+ delta: number
344
+ /** Elapsed time since first frame in seconds (for legacy compatibility with THREE.Clock) */
345
+ elapsed: number
346
+ /** Incrementing frame counter */
347
+ frame: number
348
+ }
349
+
350
+ /**
351
+ * State passed to useFrame callbacks (extends RootState with timing)
352
+ */
353
+ interface FrameNextState extends RootState, FrameTimingState {}
354
+
355
+ /** Alias for FrameNextState */
356
+ type FrameState = FrameNextState
357
+
358
+ // Root Options --------------------------------
359
+
360
+ /**
361
+ * Options for registerRoot
362
+ */
363
+ interface RootOptions {
364
+ /** State provider for callbacks. Optional in independent mode. */
365
+ getState?: () => any
366
+ /** Error handler for job errors. Falls back to console.error if not provided. */
367
+ onError?: (error: Error) => void
368
+ }
369
+
370
+ // Callback Types --------------------------------
371
+
372
+ /**
373
+ * Callback function for useFrame
374
+ */
375
+ type FrameNextCallback = (state: FrameNextState, delta: number) => void
376
+
377
+ /** Alias for FrameNextCallback */
378
+ type FrameCallback = FrameNextCallback
379
+
380
+ // Controls returned from useFrame --------------------------------
381
+
382
+ /**
383
+ * Controls object returned from useFrame hook
384
+ */
385
+ interface FrameNextControls {
386
+ /** The job's unique ID */
387
+ id: string
388
+ /** Access to the global scheduler for frame loop control */
389
+ scheduler: SchedulerApi
390
+ /** Manually step this job only (bypasses FPS limiting) */
391
+ step(timestamp?: number): void
392
+ /** Manually step ALL jobs in the scheduler */
393
+ stepAll(timestamp?: number): void
394
+ /** Pause this job (set enabled=false) */
395
+ pause(): void
396
+ /** Resume this job (set enabled=true) */
397
+ resume(): void
398
+ /** Reactive paused state - automatically triggers re-render when changed */
399
+ isPaused: boolean
400
+ }
401
+
402
+ /** Alias for FrameNextControls */
403
+ type FrameControls = FrameNextControls
404
+
405
+ // Scheduler Interface --------------------------------
406
+
407
+ /**
408
+ * Public interface for the global Scheduler
409
+ */
410
+ interface SchedulerApi {
411
+ //* Phase Management --------------------------------
412
+
413
+ /** Add a named phase to the scheduler */
414
+ addPhase(name: string, options?: AddPhaseOptions): void
415
+ /** Get the ordered list of phase names */
416
+ readonly phases: string[]
417
+ /** Check if a phase exists */
418
+ hasPhase(name: string): boolean
419
+
420
+ //* Root Management --------------------------------
421
+
422
+ /** Register a root (Canvas) with the scheduler. Returns unsubscribe function. */
423
+ registerRoot(id: string, options?: RootOptions): () => void
424
+ /** Unregister a root */
425
+ unregisterRoot(id: string): void
426
+ /** Generate a unique root ID */
427
+ generateRootId(): string
428
+ /** Get the number of registered roots */
429
+ getRootCount(): number
430
+ /** Check if any root is registered and ready */
431
+ readonly isReady: boolean
432
+ /** Subscribe to root-ready event. Fires immediately if already ready. Returns unsubscribe. */
433
+ onRootReady(callback: () => void): () => void
434
+
435
+ //* Job Registration --------------------------------
436
+
437
+ /** Register a job with the scheduler (returns unsubscribe function) */
438
+ register(
439
+ callback: FrameNextCallback,
440
+ options?: {
441
+ id?: string
442
+ rootId?: string
443
+ phase?: string
444
+ before?: string | string[]
445
+ after?: string | string[]
446
+ priority?: number
447
+ fps?: number
448
+ drop?: boolean
449
+ enabled?: boolean
450
+ },
451
+ ): () => void
452
+ /** Update a job's options */
453
+ updateJob(
454
+ id: string,
455
+ options: {
456
+ priority?: number
457
+ fps?: number
458
+ drop?: boolean
459
+ enabled?: boolean
460
+ phase?: string
461
+ before?: string | string[]
462
+ after?: string | string[]
463
+ },
464
+ ): void
465
+ /** Unregister a job by ID */
466
+ unregister(id: string, rootId?: string): void
467
+ /** Get the number of registered jobs */
468
+ getJobCount(): number
469
+ /** Get all job IDs */
470
+ getJobIds(): string[]
471
+
472
+ //* Global Jobs (for legacy addEffect/addAfterEffect) --------------------------------
473
+
474
+ /** Register a global job (runs once per frame, not per-root). Returns unsubscribe function. */
475
+ registerGlobal(phase: 'before' | 'after', id: string, callback: (timestamp: number) => void): () => void
476
+
477
+ //* Idle Callbacks (for legacy addTail) --------------------------------
478
+
479
+ /** Register an idle callback (fires when loop stops). Returns unsubscribe function. */
480
+ onIdle(callback: (timestamp: number) => void): () => void
481
+
482
+ //* Frame Loop Control --------------------------------
483
+
484
+ /** Start the scheduler loop */
485
+ start(): void
486
+ /** Stop the scheduler loop */
487
+ stop(): void
488
+ /** Check if the scheduler is running */
489
+ readonly isRunning: boolean
490
+ /** Get/set the frameloop mode ('always', 'demand', 'never') */
491
+ frameloop: Frameloop
492
+ /** Independent mode - runs without Canvas, callbacks receive timing-only state */
493
+ independent: boolean
494
+
495
+ //* Manual Stepping --------------------------------
496
+
497
+ /** Manually step all jobs once (for frameloop='never' or testing) */
498
+ step(timestamp?: number): void
499
+ /** Manually step a single job by ID */
500
+ stepJob(id: string, timestamp?: number): void
501
+ /** Request frame(s) to be rendered (for frameloop='demand') */
502
+ invalidate(frames?: number): void
503
+
504
+ //* Per-Job Control --------------------------------
505
+
506
+ /** Check if a job is paused */
507
+ isJobPaused(id: string): boolean
508
+ /** Pause a job */
509
+ pauseJob(id: string): void
510
+ /** Resume a job */
511
+ resumeJob(id: string): void
512
+ /** Subscribe to job state changes (for reactive isPaused). Returns unsubscribe function. */
513
+ subscribeJobState(id: string, listener: () => void): () => void
514
+ }
515
+
516
+ //* Buffer Types (useBuffers) ========================================
517
+
518
+ /**
519
+ * Buffer-like types for GPU compute and storage operations.
520
+ * Includes raw CPU arrays, Three.js buffer attributes, and TSL buffer nodes.
521
+ *
522
+ * @example
523
+ * ```tsx
524
+ * const { positions, velocities } = useBuffers(() => ({
525
+ * positions: instancedArray(count, 'vec3'), // StorageBufferNode
526
+ * velocities: new Float32Array(count * 3), // TypedArray
527
+ * }), 'particles')
528
+ * ```
529
+ */
530
+ type BufferLike =
531
+ | Float32Array
532
+ | Uint32Array
533
+ | Int32Array
534
+ | Float64Array
535
+ | Uint8Array
536
+ | Int8Array
537
+ | Uint16Array
538
+ | Int16Array
539
+ | THREE$1.BufferAttribute // Base class for all buffer attributes
540
+ | Node // TSL buffer nodes (instancedArray, storage)
541
+
542
+ /** Flat record of buffer-like values (no nested scopes) */
543
+ type BufferRecord = Record<string, BufferLike>
544
+
545
+ /**
546
+ * Buffer store that can contain both root-level buffers and scoped buffer objects.
547
+ * Structure: { positions: Float32Array, particles: { vel: StorageBufferNode } }
548
+ */
549
+ type BufferStore = Record<string, BufferLike | BufferRecord>
550
+
551
+ //* Storage Types (useGPUStorage) ========================================
552
+
553
+ /**
554
+ * GPU storage types for texture-based storage operations.
555
+ * Includes Three.js storage textures and TSL storage texture nodes.
556
+ *
557
+ * @example
558
+ * ```tsx
559
+ * const { heightMap } = useGPUStorage(() => ({
560
+ * heightMap: new StorageTexture(512, 512),
561
+ * }), 'terrain')
562
+ * ```
563
+ */
564
+ type StorageLike =
565
+ | StorageTexture // GPU storage texture
566
+ | Data3DTexture // 3D texture (can be used as storage)
567
+ | Node // TSL storage texture nodes (storageTexture)
568
+
569
+ /** Flat record of storage-like values (no nested scopes) */
570
+ type StorageRecord = Record<string, StorageLike>
571
+
572
+ /**
573
+ * Storage store that can contain both root-level storage and scoped storage objects.
574
+ * Structure: { heightMap: StorageTexture, terrain: { normal: StorageTextureNode } }
575
+ */
576
+ type StorageStore = Record<string, StorageLike | StorageRecord>
577
+
578
+ //* Renderer Types ========================================
579
+
580
+ /** Default renderer type - union of WebGL and WebGPU renderers */
581
+ type R3FRenderer = THREE$1.WebGLRenderer | WebGPURenderer$1
582
+
583
+ //* Core Store Types ========================================
584
+
585
+ type Subscription = {
586
+ ref: React$1.RefObject<RenderCallback>
587
+ priority: number
588
+ store: RootStore
589
+ }
590
+
591
+ /** Per-pointer state for multi-touch and XR support */
592
+ type PointerState = {
593
+ /** Objects currently hovered by this pointer */
594
+ hovered: Map<string, ThreeEvent<DomEvent>>
595
+ /** Objects capturing this pointer */
596
+ captured: Map<THREE$1.Object3D, PointerCaptureTarget>
597
+ /** Initial click position [x, y] */
598
+ initialClick: [x: number, y: number]
599
+ /** Objects hit on initial click */
600
+ initialHits: THREE$1.Object3D[]
601
+ }
602
+
603
+ type Dpr = number | [min: number, max: number]
604
+
605
+ interface Size {
606
+ width: number
607
+ height: number
608
+ top: number
609
+ left: number
610
+ }
611
+
612
+ type Frameloop = 'always' | 'demand' | 'never'
613
+
614
+ interface Viewport extends Size {
615
+ /** The initial pixel ratio */
616
+ initialDpr: number
617
+ /** Current pixel ratio */
618
+ dpr: number
619
+ /** size.width / viewport.width */
620
+ factor: number
621
+ /** Camera distance */
622
+ distance: number
623
+ /** Camera aspect ratio: width / height */
624
+ aspect: number
625
+ }
626
+
627
+ type RenderCallback = (state: RootState, delta: number, frame?: XRFrame) => void
628
+
629
+ interface Performance {
630
+ /** Current performance normal, between min and max */
631
+ current: number
632
+ /** How low the performance can go, between 0 and max */
633
+ min: number
634
+ /** How high the performance can go, between min and max */
635
+ max: number
636
+ /** Time until current returns to max in ms */
637
+ debounce: number
638
+ /** Sets current to min, puts the system in regression */
639
+ regress: () => void
640
+ }
641
+
642
+ interface InternalState {
643
+ interaction: THREE$1.Object3D[]
644
+ subscribers: Subscription[]
645
+ /** Per-pointer state (hover, capture, click tracking) - replaces hovered, capturedMap, initialClick, initialHits */
646
+ pointerMap: Map<number, PointerState>
647
+ /** Pointers needing raycast this frame (used with frameTimedRaycasts) */
648
+ pointerDirty: Map<number, DomEvent>
649
+ /** Last event received (for events.update() compatibility) */
650
+ lastEvent: React$1.RefObject<DomEvent | null>
651
+ /** @deprecated Use pointerMap.get(pointerId).hovered instead */
652
+ hovered: Map<string, ThreeEvent<DomEvent>>
653
+ /** @deprecated Use pointerMap.get(pointerId).captured instead */
654
+ capturedMap: Map<number, Map<THREE$1.Object3D, PointerCaptureTarget>>
655
+ /** @deprecated Use pointerMap.get(pointerId).initialClick instead */
656
+ initialClick: [x: number, y: number]
657
+ /** @deprecated Use pointerMap.get(pointerId).initialHits instead */
658
+ initialHits: THREE$1.Object3D[]
659
+ /** Visibility event registry (onFramed, onOccluded, onVisible) */
660
+ visibilityRegistry: Map<string, VisibilityEntry>
661
+ /** Whether occlusion queries are enabled (WebGPU only) */
662
+ occlusionEnabled: boolean
663
+ /** Reference to the invisible occlusion observer mesh */
664
+ occlusionObserver: THREE$1.Mesh | null
665
+ /** Cached occlusion results from render pass - keyed by Object3D */
666
+ occlusionCache: Map<THREE$1.Object3D, boolean | null>
667
+ /** Internal helper group for R3F system objects (occlusion observer, etc.) */
668
+ helperGroup: THREE$1.Group | null
669
+ active: boolean
670
+ priority: number
671
+ frames: number
672
+ subscribe: (callback: React$1.RefObject<RenderCallback>, priority: number, store: RootStore) => () => void
673
+ /** Internal renderer storage - use state.renderer or state.gl to access */
674
+ actualRenderer: R3FRenderer
675
+ /** Global scheduler reference (for useFrame hook) */
676
+ scheduler: SchedulerApi | null
677
+ /** This root's unique ID in the global scheduler */
678
+ rootId?: string
679
+ /** Function to unregister this root from the global scheduler */
680
+ unregisterRoot?: () => void
681
+ /** Container for child attachment (scene for root, original container for portals) */
682
+ container?: THREE$1.Object3D
683
+ /**
684
+ * CanvasTarget for multi-canvas WebGPU rendering.
685
+ * Created for all WebGPU canvases to support renderer sharing.
686
+ * @see https://threejs.org/docs/#api/en/renderers/common/CanvasTarget
687
+ */
688
+ canvasTarget?: CanvasTarget
689
+ /**
690
+ * Whether multi-canvas rendering is active.
691
+ * True when any canvas uses `target` prop to share a renderer.
692
+ * When true, setCanvasTarget is called before each render.
693
+ */
694
+ isMultiCanvas?: boolean
695
+ /**
696
+ * Whether this canvas is a secondary canvas sharing another's renderer.
697
+ * True when `target` prop is used.
698
+ */
699
+ isSecondary?: boolean
700
+ /**
701
+ * The id of the primary canvas this secondary canvas targets.
702
+ * Only set when isSecondary is true.
703
+ */
704
+ targetId?: string
705
+ /**
706
+ * Function to unregister this primary canvas from the registry.
707
+ * Only set when this canvas has an `id` prop.
708
+ */
709
+ unregisterPrimary?: () => void
710
+ /** Whether canvas dimensions are forced to even numbers */
711
+ forceEven?: boolean
712
+ }
713
+
714
+ interface XRManager {
715
+ connect: () => void
716
+ disconnect: () => void
717
+ }
718
+
719
+ //* Root State Interface ====================================
720
+
721
+ interface RootState {
722
+ /** Set current state */
723
+ set: StoreApi<RootState>['setState']
724
+ /** Get current state */
725
+ get: StoreApi<RootState>['getState']
726
+ /**
727
+ * Reference to the authoritative store for shared TSL resources (uniforms, nodes, etc).
728
+ * - For primary/independent canvases: points to its own store (self-reference)
729
+ * - For secondary canvases: points to the primary canvas's store
730
+ *
731
+ * Hooks like useNodes/useUniforms should read from primaryStore to ensure
732
+ * consistent shared state across all canvases sharing a renderer.
733
+ */
734
+ primaryStore: RootStore
735
+ /** @deprecated Use `renderer` instead. The instance of the renderer (typed as WebGLRenderer for backwards compat) */
736
+ gl: THREE$1.WebGLRenderer
737
+ /** The renderer instance - type depends on entry point (WebGPU, Legacy, or union for default) */
738
+ renderer: R3FRenderer
739
+ /** Inspector of the webGPU Renderer. Init in the canvas */
740
+ inspector: any // Inspector type from three/webgpu
741
+
742
+ /** Default camera */
743
+ camera: ThreeCamera
744
+ /** Camera frustum for visibility checks - auto-updated each frame when autoUpdateFrustum is true */
745
+ frustum: THREE$1.Frustum
746
+ /** Whether to automatically update the frustum each frame (default: true) */
747
+ autoUpdateFrustum: boolean
748
+ /** Default scene (may be overridden in portals to point to the portal container) */
749
+ scene: THREE$1.Scene
750
+ /** The actual root THREE.Scene - always points to the true scene, even inside portals */
751
+ rootScene: THREE$1.Scene
752
+ /** Default raycaster */
753
+ raycaster: THREE$1.Raycaster
754
+ /** Event layer interface, contains the event handler and the node they're connected to */
755
+ events: EventManager<any>
756
+ /** XR interface */
757
+ xr: XRManager
758
+ /** Currently used controls */
759
+ controls: THREE$1.EventDispatcher | null
760
+ /** Normalized event coordinates */
761
+ pointer: THREE$1.Vector2
762
+ /** @deprecated Normalized event coordinates, use "pointer" instead! */
763
+ mouse: THREE$1.Vector2
764
+ /** Color space assigned to 8-bit input textures (color maps). Most textures are authored in sRGB. */
765
+ textureColorSpace: THREE$1.ColorSpace
766
+ /** Render loop flags */
767
+ frameloop: Frameloop
768
+ performance: Performance
769
+ /** Reactive pixel-size of the canvas */
770
+ size: Size
771
+ /** Reactive size of the viewport in threejs units */
772
+ viewport: Viewport & {
773
+ getCurrentViewport: (
774
+ camera?: ThreeCamera,
775
+ target?: THREE$1.Vector3 | Parameters<THREE$1.Vector3['set']>,
776
+ size?: Size,
777
+ ) => Omit<Viewport, 'dpr' | 'initialDpr'>
778
+ }
779
+ /** Flags the canvas for render, but doesn't render in itself */
780
+ invalidate: (frames?: number, stackFrames?: boolean) => void
781
+ /** Advance (render) one step */
782
+ advance: (timestamp: number, runGlobalEffects?: boolean) => void
783
+ /** Shortcut to setting the event layer */
784
+ setEvents: (events: Partial<EventManager<any>>) => void
785
+ /** Shortcut to manual sizing. No args resets to props/container. Single arg creates square. */
786
+ setSize: (width?: number, height?: number, top?: number, left?: number) => void
787
+ /** Shortcut to manual setting the pixel ratio */
788
+ setDpr: (dpr: Dpr) => void
789
+ /** Shortcut to setting frameloop flags */
790
+ setFrameloop: (frameloop: Frameloop) => void
791
+ /** Set error state to propagate to error boundary */
792
+ setError: (error: Error | null) => void
793
+ /** Current error state (null when no error) */
794
+ error: Error | null
795
+ /** Global TSL uniform nodes - root-level uniforms + scoped sub-objects. Use useUniforms() hook */
796
+ uniforms: UniformStore
797
+ /** Global TSL nodes - root-level nodes + scoped sub-objects. Use useNodes() hook */
798
+ nodes: Record<string, any>
799
+ /** Global TSL buffer nodes - root-level buffers + scoped sub-objects. Use useBuffers() hook */
800
+ buffers: BufferStore
801
+ /** Global GPU storage (textures, etc.) - root-level storage + scoped sub-objects. Use useGPUStorage() hook */
802
+ gpuStorage: StorageStore
803
+ /** Global TSL texture nodes - use useTextures() hook for operations */
804
+ textures: Map<string, any>
805
+ /** WebGPU RenderPipeline instance - use useRenderPipeline() hook */
806
+ renderPipeline: any | null // THREE.PostProcessing (will be THREE.RenderPipeline in future Three.js release)
807
+ /** Global TSL pass nodes for render pipeline - use useRenderPipeline() hook */
808
+ passes: Record<string, any>
809
+ /** Internal version counter for HMR - incremented by rebuildNodes/rebuildUniforms to bust memoization */
810
+ _hmrVersion: number
811
+ /** Internal: whether setSize() has taken ownership of canvas dimensions */
812
+ _sizeImperative: boolean
813
+ /** Internal: stored size props from Canvas for reset functionality */
814
+ _sizeProps: { width?: number; height?: number } | null
815
+ /** When the canvas was clicked but nothing was hit */
816
+ onPointerMissed?: (event: MouseEvent) => void
817
+ /** When a dragover event has missed any target */
818
+ onDragOverMissed?: (event: DragEvent) => void
819
+ /** When a drop event has missed any target */
820
+ onDropMissed?: (event: DragEvent) => void
821
+ /** If this state model is layered (via createPortal) then this contains the previous layer */
822
+ previousRoot?: RootStore
823
+ /** Internals */
824
+ internal: InternalState
825
+ // flags for triggers
826
+ // if we are using the webGl renderer, this will be true
827
+ isLegacy: boolean
828
+ // regardless of renderer, if the system supports webGpu, this will be true
829
+ webGPUSupported: boolean
830
+ //if we are on native
831
+ isNative: boolean
514
832
  }
515
833
 
516
- //* Buffer Types (useBuffers) ========================================
517
-
518
- /**
519
- * Buffer-like types for GPU compute and storage operations.
520
- * Includes raw CPU arrays, Three.js buffer attributes, and TSL buffer nodes.
521
- *
522
- * @example
523
- * ```tsx
524
- * const { positions, velocities } = useBuffers(() => ({
525
- * positions: instancedArray(count, 'vec3'), // StorageBufferNode
526
- * velocities: new Float32Array(count * 3), // TypedArray
527
- * }), 'particles')
528
- * ```
529
- */
530
- type BufferLike =
531
- | Float32Array
532
- | Uint32Array
533
- | Int32Array
534
- | Float64Array
535
- | Uint8Array
536
- | Int8Array
537
- | Uint16Array
538
- | Int16Array
539
- | THREE$1.BufferAttribute // Base class for all buffer attributes
540
- | Node // TSL buffer nodes (instancedArray, storage)
541
-
542
- /** Flat record of buffer-like values (no nested scopes) */
543
- type BufferRecord = Record<string, BufferLike>
544
-
545
- /**
546
- * Buffer store that can contain both root-level buffers and scoped buffer objects.
547
- * Structure: { positions: Float32Array, particles: { vel: StorageBufferNode } }
548
- */
549
- type BufferStore = Record<string, BufferLike | BufferRecord>
550
-
551
- //* Storage Types (useGPUStorage) ========================================
552
-
553
- /**
554
- * GPU storage types for texture-based storage operations.
555
- * Includes Three.js storage textures and TSL storage texture nodes.
556
- *
557
- * @example
558
- * ```tsx
559
- * const { heightMap } = useGPUStorage(() => ({
560
- * heightMap: new StorageTexture(512, 512),
561
- * }), 'terrain')
562
- * ```
563
- */
564
- type StorageLike =
565
- | StorageTexture // GPU storage texture
566
- | Data3DTexture // 3D texture (can be used as storage)
567
- | Node // TSL storage texture nodes (storageTexture)
568
-
569
- /** Flat record of storage-like values (no nested scopes) */
570
- type StorageRecord = Record<string, StorageLike>
571
-
572
- /**
573
- * Storage store that can contain both root-level storage and scoped storage objects.
574
- * Structure: { heightMap: StorageTexture, terrain: { normal: StorageTextureNode } }
575
- */
576
- type StorageStore = Record<string, StorageLike | StorageRecord>
577
-
578
- //* Renderer Types ========================================
579
-
580
- /** Default renderer type - union of WebGL and WebGPU renderers */
581
- type R3FRenderer = THREE$1.WebGLRenderer | WebGPURenderer$1
582
-
583
- //* Core Store Types ========================================
584
-
585
- type Subscription = {
586
- ref: React$1.RefObject<RenderCallback>
587
- priority: number
588
- store: RootStore
589
- }
590
-
591
- /** Per-pointer state for multi-touch and XR support */
592
- type PointerState = {
593
- /** Objects currently hovered by this pointer */
594
- hovered: Map<string, ThreeEvent<DomEvent>>
595
- /** Objects capturing this pointer */
596
- captured: Map<THREE$1.Object3D, PointerCaptureTarget>
597
- /** Initial click position [x, y] */
598
- initialClick: [x: number, y: number]
599
- /** Objects hit on initial click */
600
- initialHits: THREE$1.Object3D[]
601
- }
602
-
603
- type Dpr = number | [min: number, max: number]
604
-
605
- interface Size {
606
- width: number
607
- height: number
608
- top: number
609
- left: number
610
- }
611
-
612
- type Frameloop = 'always' | 'demand' | 'never'
613
-
614
- interface Viewport extends Size {
615
- /** The initial pixel ratio */
616
- initialDpr: number
617
- /** Current pixel ratio */
618
- dpr: number
619
- /** size.width / viewport.width */
620
- factor: number
621
- /** Camera distance */
622
- distance: number
623
- /** Camera aspect ratio: width / height */
624
- aspect: number
625
- }
626
-
627
- type RenderCallback = (state: RootState, delta: number, frame?: XRFrame) => void
628
-
629
- interface Performance {
630
- /** Current performance normal, between min and max */
631
- current: number
632
- /** How low the performance can go, between 0 and max */
633
- min: number
634
- /** How high the performance can go, between min and max */
635
- max: number
636
- /** Time until current returns to max in ms */
637
- debounce: number
638
- /** Sets current to min, puts the system in regression */
639
- regress: () => void
640
- }
641
-
642
- interface InternalState {
643
- interaction: THREE$1.Object3D[]
644
- subscribers: Subscription[]
645
- /** Per-pointer state (hover, capture, click tracking) - replaces hovered, capturedMap, initialClick, initialHits */
646
- pointerMap: Map<number, PointerState>
647
- /** Pointers needing raycast this frame (used with frameTimedRaycasts) */
648
- pointerDirty: Map<number, DomEvent>
649
- /** Last event received (for events.update() compatibility) */
650
- lastEvent: React$1.RefObject<DomEvent | null>
651
- /** @deprecated Use pointerMap.get(pointerId).hovered instead */
652
- hovered: Map<string, ThreeEvent<DomEvent>>
653
- /** @deprecated Use pointerMap.get(pointerId).captured instead */
654
- capturedMap: Map<number, Map<THREE$1.Object3D, PointerCaptureTarget>>
655
- /** @deprecated Use pointerMap.get(pointerId).initialClick instead */
656
- initialClick: [x: number, y: number]
657
- /** @deprecated Use pointerMap.get(pointerId).initialHits instead */
658
- initialHits: THREE$1.Object3D[]
659
- /** Visibility event registry (onFramed, onOccluded, onVisible) */
660
- visibilityRegistry: Map<string, VisibilityEntry>
661
- /** Whether occlusion queries are enabled (WebGPU only) */
662
- occlusionEnabled: boolean
663
- /** Reference to the invisible occlusion observer mesh */
664
- occlusionObserver: THREE$1.Mesh | null
665
- /** Cached occlusion results from render pass - keyed by Object3D */
666
- occlusionCache: Map<THREE$1.Object3D, boolean | null>
667
- /** Internal helper group for R3F system objects (occlusion observer, etc.) */
668
- helperGroup: THREE$1.Group | null
669
- active: boolean
670
- priority: number
671
- frames: number
672
- subscribe: (callback: React$1.RefObject<RenderCallback>, priority: number, store: RootStore) => () => void
673
- /** Internal renderer storage - use state.renderer or state.gl to access */
674
- actualRenderer: R3FRenderer
675
- /** Global scheduler reference (for useFrame hook) */
676
- scheduler: SchedulerApi | null
677
- /** This root's unique ID in the global scheduler */
678
- rootId?: string
679
- /** Function to unregister this root from the global scheduler */
680
- unregisterRoot?: () => void
681
- /** Container for child attachment (scene for root, original container for portals) */
682
- container?: THREE$1.Object3D
683
- /**
684
- * CanvasTarget for multi-canvas WebGPU rendering.
685
- * Created for all WebGPU canvases to support renderer sharing.
686
- * @see https://threejs.org/docs/#api/en/renderers/common/CanvasTarget
687
- */
688
- canvasTarget?: CanvasTarget
689
- /**
690
- * Whether multi-canvas rendering is active.
691
- * True when any canvas uses `target` prop to share a renderer.
692
- * When true, setCanvasTarget is called before each render.
693
- */
694
- isMultiCanvas?: boolean
695
- /**
696
- * Whether this canvas is a secondary canvas sharing another's renderer.
697
- * True when `target` prop is used.
698
- */
699
- isSecondary?: boolean
700
- /**
701
- * The id of the primary canvas this secondary canvas targets.
702
- * Only set when isSecondary is true.
703
- */
704
- targetId?: string
705
- /**
706
- * Function to unregister this primary canvas from the registry.
707
- * Only set when this canvas has an `id` prop.
708
- */
709
- unregisterPrimary?: () => void
710
- /** Whether canvas dimensions are forced to even numbers */
711
- forceEven?: boolean
712
- }
713
-
714
- interface XRManager {
715
- connect: () => void
716
- disconnect: () => void
717
- }
718
-
719
- //* Root State Interface ====================================
720
-
721
- interface RootState {
722
- /** Set current state */
723
- set: StoreApi<RootState>['setState']
724
- /** Get current state */
725
- get: StoreApi<RootState>['getState']
726
- /**
727
- * Reference to the authoritative store for shared TSL resources (uniforms, nodes, etc).
728
- * - For primary/independent canvases: points to its own store (self-reference)
729
- * - For secondary canvases: points to the primary canvas's store
730
- *
731
- * Hooks like useNodes/useUniforms should read from primaryStore to ensure
732
- * consistent shared state across all canvases sharing a renderer.
733
- */
734
- primaryStore: RootStore
735
- /** @deprecated Use `renderer` instead. The instance of the renderer (typed as WebGLRenderer for backwards compat) */
736
- gl: THREE$1.WebGLRenderer
737
- /** The renderer instance - type depends on entry point (WebGPU, Legacy, or union for default) */
738
- renderer: R3FRenderer
739
- /** Inspector of the webGPU Renderer. Init in the canvas */
740
- inspector: any // Inspector type from three/webgpu
741
-
742
- /** Default camera */
743
- camera: ThreeCamera
744
- /** Camera frustum for visibility checks - auto-updated each frame when autoUpdateFrustum is true */
745
- frustum: THREE$1.Frustum
746
- /** Whether to automatically update the frustum each frame (default: true) */
747
- autoUpdateFrustum: boolean
748
- /** Default scene (may be overridden in portals to point to the portal container) */
749
- scene: THREE$1.Scene
750
- /** The actual root THREE.Scene - always points to the true scene, even inside portals */
751
- rootScene: THREE$1.Scene
752
- /** Default raycaster */
753
- raycaster: THREE$1.Raycaster
754
- /** Event layer interface, contains the event handler and the node they're connected to */
755
- events: EventManager<any>
756
- /** XR interface */
757
- xr: XRManager
758
- /** Currently used controls */
759
- controls: THREE$1.EventDispatcher | null
760
- /** Normalized event coordinates */
761
- pointer: THREE$1.Vector2
762
- /** @deprecated Normalized event coordinates, use "pointer" instead! */
763
- mouse: THREE$1.Vector2
764
- /** Color space assigned to 8-bit input textures (color maps). Most textures are authored in sRGB. */
765
- textureColorSpace: THREE$1.ColorSpace
766
- /** Render loop flags */
767
- frameloop: Frameloop
768
- performance: Performance
769
- /** Reactive pixel-size of the canvas */
770
- size: Size
771
- /** Reactive size of the viewport in threejs units */
772
- viewport: Viewport & {
773
- getCurrentViewport: (
774
- camera?: ThreeCamera,
775
- target?: THREE$1.Vector3 | Parameters<THREE$1.Vector3['set']>,
776
- size?: Size,
777
- ) => Omit<Viewport, 'dpr' | 'initialDpr'>
778
- }
779
- /** Flags the canvas for render, but doesn't render in itself */
780
- invalidate: (frames?: number, stackFrames?: boolean) => void
781
- /** Advance (render) one step */
782
- advance: (timestamp: number, runGlobalEffects?: boolean) => void
783
- /** Shortcut to setting the event layer */
784
- setEvents: (events: Partial<EventManager<any>>) => void
785
- /** Shortcut to manual sizing. No args resets to props/container. Single arg creates square. */
786
- setSize: (width?: number, height?: number, top?: number, left?: number) => void
787
- /** Shortcut to manual setting the pixel ratio */
788
- setDpr: (dpr: Dpr) => void
789
- /** Shortcut to setting frameloop flags */
790
- setFrameloop: (frameloop: Frameloop) => void
791
- /** Set error state to propagate to error boundary */
792
- setError: (error: Error | null) => void
793
- /** Current error state (null when no error) */
794
- error: Error | null
795
- /** Global TSL uniform nodes - root-level uniforms + scoped sub-objects. Use useUniforms() hook */
796
- uniforms: UniformStore
797
- /** Global TSL nodes - root-level nodes + scoped sub-objects. Use useNodes() hook */
798
- nodes: Record<string, any>
799
- /** Global TSL buffer nodes - root-level buffers + scoped sub-objects. Use useBuffers() hook */
800
- buffers: BufferStore
801
- /** Global GPU storage (textures, etc.) - root-level storage + scoped sub-objects. Use useGPUStorage() hook */
802
- gpuStorage: StorageStore
803
- /** Global TSL texture nodes - use useTextures() hook for operations */
804
- textures: Map<string, any>
805
- /** WebGPU RenderPipeline instance - use useRenderPipeline() hook */
806
- renderPipeline: any | null // THREE.PostProcessing (will be THREE.RenderPipeline in future Three.js release)
807
- /** Global TSL pass nodes for render pipeline - use useRenderPipeline() hook */
808
- passes: Record<string, any>
809
- /** Internal version counter for HMR - incremented by rebuildNodes/rebuildUniforms to bust memoization */
810
- _hmrVersion: number
811
- /** Internal: whether setSize() has taken ownership of canvas dimensions */
812
- _sizeImperative: boolean
813
- /** Internal: stored size props from Canvas for reset functionality */
814
- _sizeProps: { width?: number; height?: number } | null
815
- /** When the canvas was clicked but nothing was hit */
816
- onPointerMissed?: (event: MouseEvent) => void
817
- /** When a dragover event has missed any target */
818
- onDragOverMissed?: (event: DragEvent) => void
819
- /** When a drop event has missed any target */
820
- onDropMissed?: (event: DragEvent) => void
821
- /** If this state model is layered (via createPortal) then this contains the previous layer */
822
- previousRoot?: RootStore
823
- /** Internals */
824
- internal: InternalState
825
- // flags for triggers
826
- // if we are using the webGl renderer, this will be true
827
- isLegacy: boolean
828
- // regardless of renderer, if the system supports webGpu, this will be true
829
- webGPUSupported: boolean
830
- //if we are on native
831
- isNative: boolean
832
- }
833
-
834
834
  type RootStore = UseBoundStoreWithEqualityFn<StoreApi<RootState>>
835
835
 
836
- //* Base Renderer Types =====================================
837
-
838
- // Shim for OffscreenCanvas since it was removed from DOM types
839
- interface OffscreenCanvas$1 extends EventTarget {}
840
-
841
- interface BaseRendererProps {
842
- canvas: HTMLCanvasElement | OffscreenCanvas$1
843
- powerPreference?: 'high-performance' | 'low-power' | 'default'
844
- antialias?: boolean
845
- alpha?: boolean
846
- }
847
-
848
- type RendererFactory<TRenderer, TParams> =
849
- | TRenderer
850
- | ((defaultProps: TParams) => TRenderer)
851
- | ((defaultProps: TParams) => Promise<TRenderer>)
852
-
853
- interface Renderer {
854
- render: (scene: THREE$1.Scene, camera: THREE$1.Camera) => any
855
- }
856
-
857
- //* Color Management Config ==============================
858
-
859
- /**
860
- * Color management configuration shared by both WebGL and WebGPU renderers.
861
- */
862
- interface ColorManagementConfig {
863
- /**
864
- * Color space assigned to 8-bit input textures (color maps).
865
- * Defaults to sRGB. Most textures are authored in sRGB.
866
- * @default THREE.SRGBColorSpace
867
- */
868
- textureColorSpace?: THREE$1.ColorSpace
869
- }
870
-
871
- //* WebGL Renderer Props ==============================
872
-
873
- type DefaultGLProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & {
874
- canvas: HTMLCanvasElement | OffscreenCanvas$1
875
- }
876
-
877
- type GLProps =
878
- | Renderer
879
- | ((defaultProps: DefaultGLProps) => Renderer)
880
- | ((defaultProps: DefaultGLProps) => Promise<Renderer>)
881
- | (Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters> & ColorManagementConfig)
882
-
883
- //* WebGPU Renderer Props ==============================
884
-
885
- type DefaultRendererProps = {
886
- canvas: HTMLCanvasElement | OffscreenCanvas$1
887
- [key: string]: any
888
- }
889
-
890
- /**
891
- * Canvas-level scheduler configuration.
892
- * Controls render timing relative to other canvases.
893
- */
894
- interface CanvasSchedulerConfig {
895
- /**
896
- * Render this canvas after another canvas completes.
897
- * Pass the `id` of another canvas.
898
- */
899
- after?: string
900
- /**
901
- * Limit this canvas's render rate (frames per second).
902
- */
903
- fps?: number
904
- }
905
-
906
- /**
907
- * Extended renderer configuration for multi-canvas support and color management.
908
- */
909
- interface RendererConfigExtended extends ColorManagementConfig {
910
- /** Share renderer from another canvas (WebGPU only) */
911
- primaryCanvas?: string
912
- /** Canvas-level scheduler options */
913
- scheduler?: CanvasSchedulerConfig
914
- }
915
-
916
- type RendererProps =
917
- | any // WebGPURenderer
918
- | ((defaultProps: DefaultRendererProps) => any)
919
- | ((defaultProps: DefaultRendererProps) => Promise<any>)
920
- | (Partial<Properties<any> | Record<string, any>> & RendererConfigExtended)
921
-
922
- //* Camera Props ==============================
923
-
924
- type CameraProps = (
925
- | THREE$1.Camera
926
- | Partial<
927
- ThreeElement<typeof THREE$1.Camera> &
928
- ThreeElement<typeof THREE$1.PerspectiveCamera> &
929
- ThreeElement<typeof THREE$1.OrthographicCamera>
930
- >
931
- ) & {
932
- /** Flags the camera as manual, putting projection into your own hands */
933
- manual?: boolean
934
- }
935
-
936
- //* Render Props ==============================
937
-
938
- interface RenderProps<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
939
- /**
940
- * Unique identifier for multi-canvas renderer sharing.
941
- * Makes this canvas targetable by other canvases using the `primaryCanvas` prop.
942
- * Also sets the HTML `id` attribute on the canvas element.
943
- * @example <Canvas id="main-viewer">...</Canvas>
944
- */
945
- id?: string
946
- /**
947
- * Share the renderer from another canvas instead of creating a new one.
948
- * Pass the `id` of the primary canvas to share its WebGPURenderer.
949
- * Only available with WebGPU (not legacy WebGL).
950
- *
951
- * Note: This is extracted from `renderer={{ primaryCanvas: "id" }}` by Canvas.
952
- * @internal
953
- */
954
- primaryCanvas?: string
955
- /**
956
- * Canvas-level scheduler options. Controls render timing relative to other canvases.
957
- *
958
- * Note: This is extracted from `renderer={{ scheduler: {...} }}` by Canvas.
959
- * @internal
960
- */
961
- scheduler?: CanvasSchedulerConfig
962
- /** A threejs renderer instance or props that go into the default renderer */
963
- gl?: GLProps
964
- /** A WebGPU renderer instance or props that go into the default renderer */
965
- renderer?: RendererProps
966
- /** Dimensions to fit the renderer to. Will measure canvas dimensions if omitted */
967
- size?: Size
968
- /**
969
- * Enables shadows (by default PCFsoft). Can accept `gl.shadowMap` options for fine-tuning,
970
- * but also strings: 'basic' | 'percentage' | 'soft' | 'variance'.
971
- * @see https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
972
- */
973
- shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
974
- /** Creates an orthographic camera */
975
- orthographic?: boolean
976
- /**
977
- * R3F's render mode. Set to `demand` to only render on state change or `never` to take control.
978
- * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#on-demand-rendering
979
- */
980
- frameloop?: Frameloop
981
- /**
982
- * R3F performance options for adaptive performance.
983
- * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#movement-regression
984
- */
985
- performance?: Partial<Omit<Performance, 'regress'>>
986
- /** Target pixel ratio. Can clamp between a range: `[min, max]` */
987
- dpr?: Dpr
988
- /** Props that go into the default raycaster */
989
- raycaster?: Partial<THREE$1.Raycaster>
990
- /** A `THREE.Scene` instance or props that go into the default scene */
991
- scene?: THREE$1.Scene | Partial<THREE$1.Scene>
992
- /** A `THREE.Camera` instance or props that go into the default camera */
993
- camera?: CameraProps
994
- /** An R3F event manager to manage elements' pointer events */
995
- events?: (store: RootStore) => EventManager<HTMLElement>
996
- /** Callback after the canvas has rendered (but not yet committed) */
997
- onCreated?: (state: RootState) => void
998
- /** Response for pointer clicks that have missed any target */
999
- onPointerMissed?: (event: MouseEvent) => void
1000
- /** Response for dragover events that have missed any target */
1001
- onDragOverMissed?: (event: DragEvent) => void
1002
- /** Response for drop events that have missed any target */
1003
- onDropMissed?: (event: DragEvent) => void
1004
- /** Whether to automatically update the frustum each frame (default: true) */
1005
- autoUpdateFrustum?: boolean
1006
- /**
1007
- * Enable WebGPU occlusion queries for onOccluded/onVisible events.
1008
- * Auto-enabled when any object uses onOccluded or onVisible handlers.
1009
- * Only works with WebGPU renderer - WebGL will log a warning.
1010
- */
1011
- occlusion?: boolean
1012
- /** Internal: stored size props from Canvas for reset functionality */
1013
- _sizeProps?: { width?: number; height?: number } | null
1014
- /** Force canvas dimensions to even numbers (fixes Safari rendering issues with odd/fractional sizes) */
1015
- forceEven?: boolean
1016
- }
1017
-
1018
- //* Reconciler Root ==============================
1019
-
1020
- interface ReconcilerRoot<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
1021
- configure: (config?: RenderProps<TCanvas>) => Promise<ReconcilerRoot<TCanvas>>
1022
- render: (element: ReactNode) => RootStore
1023
- unmount: () => void
1024
- }
1025
-
1026
- //* Inject State ==============================
1027
-
1028
- type InjectState = Partial<
1029
- Omit<RootState, 'events'> & {
1030
- events?: {
1031
- enabled?: boolean
1032
- priority?: number
1033
- compute?: ComputeFunction
1034
- connected?: any
1035
- }
1036
- /**
1037
- * When true (default), injects a THREE.Scene between container and children if container isn't already a Scene.
1038
- * This ensures state.scene is always a real THREE.Scene with proper properties (background, environment, fog).
1039
- * Set to false to use the container directly as scene (anti-pattern, but supported for edge cases).
1040
- */
1041
- injectScene?: boolean
1042
- }
836
+ //* Base Renderer Types =====================================
837
+
838
+ // Shim for OffscreenCanvas since it was removed from DOM types
839
+ interface OffscreenCanvas$1 extends EventTarget {}
840
+
841
+ interface BaseRendererProps {
842
+ canvas: HTMLCanvasElement | OffscreenCanvas$1
843
+ powerPreference?: 'high-performance' | 'low-power' | 'default'
844
+ antialias?: boolean
845
+ alpha?: boolean
846
+ }
847
+
848
+ type RendererFactory<TRenderer, TParams> =
849
+ | TRenderer
850
+ | ((defaultProps: TParams) => TRenderer)
851
+ | ((defaultProps: TParams) => Promise<TRenderer>)
852
+
853
+ interface Renderer {
854
+ render: (scene: THREE$1.Scene, camera: THREE$1.Camera) => any
855
+ }
856
+
857
+ //* Color Management Config ==============================
858
+
859
+ /**
860
+ * Color management configuration shared by both WebGL and WebGPU renderers.
861
+ */
862
+ interface ColorManagementConfig {
863
+ /**
864
+ * Color space assigned to 8-bit input textures (color maps).
865
+ * Defaults to sRGB. Most textures are authored in sRGB.
866
+ * @default THREE.SRGBColorSpace
867
+ */
868
+ textureColorSpace?: THREE$1.ColorSpace
869
+ }
870
+
871
+ //* WebGL Renderer Props ==============================
872
+
873
+ type DefaultGLProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & {
874
+ canvas: HTMLCanvasElement | OffscreenCanvas$1
875
+ }
876
+
877
+ type GLProps =
878
+ | Renderer
879
+ | ((defaultProps: DefaultGLProps) => Renderer)
880
+ | ((defaultProps: DefaultGLProps) => Promise<Renderer>)
881
+ | (Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters> & ColorManagementConfig)
882
+
883
+ //* WebGPU Renderer Props ==============================
884
+
885
+ type DefaultRendererProps = {
886
+ canvas: HTMLCanvasElement | OffscreenCanvas$1
887
+ [key: string]: any
888
+ }
889
+
890
+ /**
891
+ * Canvas-level scheduler configuration.
892
+ * Controls render timing relative to other canvases.
893
+ */
894
+ interface CanvasSchedulerConfig {
895
+ /**
896
+ * Render this canvas after another canvas completes.
897
+ * Pass the `id` of another canvas.
898
+ */
899
+ after?: string
900
+ /**
901
+ * Limit this canvas's render rate (frames per second).
902
+ */
903
+ fps?: number
904
+ }
905
+
906
+ /**
907
+ * Extended renderer configuration for multi-canvas support and color management.
908
+ */
909
+ interface RendererConfigExtended extends ColorManagementConfig {
910
+ /** Share renderer from another canvas (WebGPU only) */
911
+ primaryCanvas?: string
912
+ /** Canvas-level scheduler options */
913
+ scheduler?: CanvasSchedulerConfig
914
+ }
915
+
916
+ type RendererProps =
917
+ | any // WebGPURenderer
918
+ | ((defaultProps: DefaultRendererProps) => any)
919
+ | ((defaultProps: DefaultRendererProps) => Promise<any>)
920
+ | (Partial<Properties<any> | Record<string, any>> & RendererConfigExtended)
921
+
922
+ //* Camera Props ==============================
923
+
924
+ type CameraProps = (
925
+ | THREE$1.Camera
926
+ | Partial<
927
+ ThreeElement<typeof THREE$1.Camera> &
928
+ ThreeElement<typeof THREE$1.PerspectiveCamera> &
929
+ ThreeElement<typeof THREE$1.OrthographicCamera>
930
+ >
931
+ ) & {
932
+ /** Flags the camera as manual, putting projection into your own hands */
933
+ manual?: boolean
934
+ }
935
+
936
+ //* Render Props ==============================
937
+
938
+ interface RenderProps<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
939
+ /**
940
+ * Unique identifier for multi-canvas renderer sharing.
941
+ * Makes this canvas targetable by other canvases using the `primaryCanvas` prop.
942
+ * Also sets the HTML `id` attribute on the canvas element.
943
+ * @example <Canvas id="main-viewer">...</Canvas>
944
+ */
945
+ id?: string
946
+ /**
947
+ * Share the renderer from another canvas instead of creating a new one.
948
+ * Pass the `id` of the primary canvas to share its WebGPURenderer.
949
+ * Only available with WebGPU (not legacy WebGL).
950
+ *
951
+ * Note: This is extracted from `renderer={{ primaryCanvas: "id" }}` by Canvas.
952
+ * @internal
953
+ */
954
+ primaryCanvas?: string
955
+ /**
956
+ * Canvas-level scheduler options. Controls render timing relative to other canvases.
957
+ *
958
+ * Note: This is extracted from `renderer={{ scheduler: {...} }}` by Canvas.
959
+ * @internal
960
+ */
961
+ scheduler?: CanvasSchedulerConfig
962
+ /** A threejs renderer instance or props that go into the default renderer */
963
+ gl?: GLProps
964
+ /** A WebGPU renderer instance or props that go into the default renderer */
965
+ renderer?: RendererProps
966
+ /** Dimensions to fit the renderer to. Will measure canvas dimensions if omitted */
967
+ size?: Size
968
+ /**
969
+ * Enables shadows (by default PCFsoft). Can accept `gl.shadowMap` options for fine-tuning,
970
+ * but also strings: 'basic' | 'percentage' | 'soft' | 'variance'.
971
+ * @see https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
972
+ */
973
+ shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
974
+ /** Creates an orthographic camera */
975
+ orthographic?: boolean
976
+ /**
977
+ * R3F's render mode. Set to `demand` to only render on state change or `never` to take control.
978
+ * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#on-demand-rendering
979
+ */
980
+ frameloop?: Frameloop
981
+ /**
982
+ * R3F performance options for adaptive performance.
983
+ * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#movement-regression
984
+ */
985
+ performance?: Partial<Omit<Performance, 'regress'>>
986
+ /** Target pixel ratio. Can clamp between a range: `[min, max]` */
987
+ dpr?: Dpr
988
+ /** Props that go into the default raycaster */
989
+ raycaster?: Partial<THREE$1.Raycaster>
990
+ /** A `THREE.Scene` instance or props that go into the default scene */
991
+ scene?: THREE$1.Scene | Partial<THREE$1.Scene>
992
+ /** A `THREE.Camera` instance or props that go into the default camera */
993
+ camera?: CameraProps
994
+ /** An R3F event manager to manage elements' pointer events */
995
+ events?: (store: RootStore) => EventManager<HTMLElement>
996
+ /** Callback after the canvas has rendered (but not yet committed) */
997
+ onCreated?: (state: RootState) => void
998
+ /** Response for pointer clicks that have missed any target */
999
+ onPointerMissed?: (event: MouseEvent) => void
1000
+ /** Response for dragover events that have missed any target */
1001
+ onDragOverMissed?: (event: DragEvent) => void
1002
+ /** Response for drop events that have missed any target */
1003
+ onDropMissed?: (event: DragEvent) => void
1004
+ /** Whether to automatically update the frustum each frame (default: true) */
1005
+ autoUpdateFrustum?: boolean
1006
+ /**
1007
+ * Enable WebGPU occlusion queries for onOccluded/onVisible events.
1008
+ * Auto-enabled when any object uses onOccluded or onVisible handlers.
1009
+ * Only works with WebGPU renderer - WebGL will log a warning.
1010
+ */
1011
+ occlusion?: boolean
1012
+ /** Internal: stored size props from Canvas for reset functionality */
1013
+ _sizeProps?: { width?: number; height?: number } | null
1014
+ /** Force canvas dimensions to even numbers (fixes Safari rendering issues with odd/fractional sizes) */
1015
+ forceEven?: boolean
1016
+ }
1017
+
1018
+ //* Reconciler Root ==============================
1019
+
1020
+ interface ReconcilerRoot<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
1021
+ configure: (config?: RenderProps<TCanvas>) => Promise<ReconcilerRoot<TCanvas>>
1022
+ render: (element: ReactNode) => RootStore
1023
+ unmount: () => void
1024
+ }
1025
+
1026
+ //* Inject State ==============================
1027
+
1028
+ type InjectState = Partial<
1029
+ Omit<RootState, 'events'> & {
1030
+ events?: {
1031
+ enabled?: boolean
1032
+ priority?: number
1033
+ compute?: ComputeFunction
1034
+ connected?: any
1035
+ }
1036
+ /**
1037
+ * When true (default), injects a THREE.Scene between container and children if container isn't already a Scene.
1038
+ * This ensures state.scene is always a real THREE.Scene with proper properties (background, environment, fog).
1039
+ * Set to false to use the container directly as scene (anti-pattern, but supported for edge cases).
1040
+ */
1041
+ injectScene?: boolean
1042
+ }
1043
1043
  >
1044
1044
 
1045
- //* Reconciler Types ==============================
1046
-
1047
- // FiberRoot is an opaque internal React type - we define it locally
1048
- // to avoid bundling @types/react-reconciler which causes absolute path issues
1049
- type FiberRoot = any
1050
-
1051
- interface Root {
1052
- fiber: FiberRoot
1053
- store: RootStore
1054
- }
1055
-
1056
- type AttachFnType<O = any> = (parent: any, self: O) => () => void
1057
- type AttachType<O = any> = string | AttachFnType<O>
1058
-
1059
- type ConstructorRepresentation<T = any> = new (...args: any[]) => T
1060
-
1061
- interface Catalogue {
1062
- [name: string]: ConstructorRepresentation
1063
- }
1064
-
1065
- // TODO: handle constructor overloads
1066
- // https://github.com/pmndrs/react-three-fiber/pull/2931
1067
- // https://github.com/microsoft/TypeScript/issues/37079
1068
- type Args<T> = T extends ConstructorRepresentation
1069
- ? T extends typeof Color$1
1070
- ? [r: number, g: number, b: number] | [color: ColorRepresentation]
1071
- : ConstructorParameters<T>
1072
- : any[]
1073
-
1074
- type ArgsProp<P> = P extends ConstructorRepresentation
1075
- ? IsAllOptional<ConstructorParameters<P>> extends true
1076
- ? { args?: Args<P> }
1077
- : { args: Args<P> }
1078
- : { args: unknown[] }
1079
-
1080
- type InstanceProps<T = any, P = any> = ArgsProp<P> & {
1081
- object?: T
1082
- dispose?: null
1083
- attach?: AttachType<T>
1084
- onUpdate?: (self: T) => void
1085
- }
1086
-
1087
- interface Instance<O = any> {
1088
- root: RootStore
1089
- type: string
1090
- parent: Instance | null
1091
- children: Instance[]
1092
- props: InstanceProps<O> & Record<string, unknown>
1093
- object: O & { __r3f?: Instance<O> }
1094
- eventCount: number
1095
- handlers: Partial<EventHandlers>
1096
- attach?: AttachType<O>
1097
- previousAttach?: any
1098
- isHidden: boolean
1099
- /** Deferred ref props to apply in commitMount */
1100
- deferredRefs?: Array<{ prop: string; ref: React$1.RefObject<any> }>
1101
- /** Set of props that have been applied via once() */
1102
- appliedOnce?: Set<string>
1103
- }
1104
-
1105
- interface HostConfig {
1106
- type: string
1107
- props: Instance['props']
1108
- container: RootStore
1109
- instance: Instance
1110
- textInstance: void
1111
- suspenseInstance: Instance
1112
- hydratableInstance: never
1113
- formInstance: never
1114
- publicInstance: Instance['object']
1115
- hostContext: {}
1116
- childSet: never
1117
- timeoutHandle: number | undefined
1118
- noTimeout: -1
1119
- TransitionStatus: null
1120
- }
1121
- declare global {
1122
- var IS_REACT_ACT_ENVIRONMENT: boolean | undefined
1045
+ //* Reconciler Types ==============================
1046
+
1047
+ // FiberRoot is an opaque internal React type - we define it locally
1048
+ // to avoid bundling @types/react-reconciler which causes absolute path issues
1049
+ type FiberRoot = any
1050
+
1051
+ interface Root {
1052
+ fiber: FiberRoot
1053
+ store: RootStore
1123
1054
  }
1124
1055
 
1125
- //* Loop Types ==============================
1126
-
1127
- type GlobalRenderCallback = (timestamp: number) => void
1128
-
1056
+ type AttachFnType<O = any> = (parent: any, self: O) => () => void
1057
+ type AttachType<O = any> = string | AttachFnType<O>
1058
+
1059
+ type ConstructorRepresentation<T = any> = new (...args: any[]) => T
1060
+
1061
+ interface Catalogue {
1062
+ [name: string]: ConstructorRepresentation
1063
+ }
1064
+
1065
+ // TODO: handle constructor overloads
1066
+ // https://github.com/pmndrs/react-three-fiber/pull/2931
1067
+ // https://github.com/microsoft/TypeScript/issues/37079
1068
+ type Args<T> = T extends ConstructorRepresentation
1069
+ ? T extends typeof Color$1
1070
+ ? [r: number, g: number, b: number] | [color: ColorRepresentation]
1071
+ : ConstructorParameters<T>
1072
+ : any[]
1073
+
1074
+ type ArgsProp<P> = P extends ConstructorRepresentation
1075
+ ? IsAllOptional<ConstructorParameters<P>> extends true
1076
+ ? { args?: Args<P> }
1077
+ : { args: Args<P> }
1078
+ : { args: unknown[] }
1079
+
1080
+ type InstanceProps<T = any, P = any> = ArgsProp<P> & {
1081
+ object?: T
1082
+ dispose?: null
1083
+ attach?: AttachType<T>
1084
+ onUpdate?: (self: T) => void
1085
+ }
1086
+
1087
+ interface Instance<O = any> {
1088
+ root: RootStore
1089
+ type: string
1090
+ parent: Instance | null
1091
+ children: Instance[]
1092
+ props: InstanceProps<O> & Record<string, unknown>
1093
+ object: O & { __r3f?: Instance<O> }
1094
+ eventCount: number
1095
+ handlers: Partial<EventHandlers>
1096
+ attach?: AttachType<O>
1097
+ previousAttach?: any
1098
+ isHidden: boolean
1099
+ /** Deferred ref props to apply in commitMount */
1100
+ deferredRefs?: Array<{ prop: string; ref: React$1.RefObject<any> }>
1101
+ /** Set of props that have been applied via once() */
1102
+ appliedOnce?: Set<string>
1103
+ }
1104
+
1105
+ interface HostConfig {
1106
+ type: string
1107
+ props: Instance['props']
1108
+ container: RootStore
1109
+ instance: Instance
1110
+ textInstance: void
1111
+ suspenseInstance: Instance
1112
+ hydratableInstance: never
1113
+ formInstance: never
1114
+ publicInstance: Instance['object']
1115
+ hostContext: {}
1116
+ childSet: never
1117
+ timeoutHandle: number | undefined
1118
+ noTimeout: -1
1119
+ TransitionStatus: null
1120
+ }
1121
+ declare global {
1122
+ var IS_REACT_ACT_ENVIRONMENT: boolean | undefined
1123
+ }
1124
+
1125
+ //* Loop Types ==============================
1126
+
1127
+ type GlobalRenderCallback = (timestamp: number) => void
1128
+
1129
1129
  type GlobalEffectType = 'before' | 'after' | 'tail'
1130
1130
 
1131
1131
  declare const presetsObj: {
@@ -1142,647 +1142,647 @@ declare const presetsObj: {
1142
1142
  };
1143
1143
  type PresetsType = keyof typeof presetsObj;
1144
1144
 
1145
- //* Background Types ==============================
1146
-
1147
- /**
1148
- * Expanded object form for background configuration.
1149
- * Allows separate textures for background (visual backdrop) and environment (PBR lighting).
1150
- */
1151
- interface BackgroundConfig {
1152
- /** HDRI preset name: 'apartment', 'city', 'dawn', 'forest', 'lobby', 'night', 'park', 'studio', 'sunset', 'warehouse' */
1153
- preset?: PresetsType
1154
- /** Files for cube texture (6 faces) or single HDR/EXR */
1155
- files?: string | string[]
1156
- /** Separate files for scene.background (visual backdrop) */
1157
- backgroundMap?: string | string[]
1158
- backgroundRotation?: Euler$1 | [number, number, number]
1159
- backgroundBlurriness?: number
1160
- backgroundIntensity?: number
1161
- /** Separate files for scene.environment (PBR lighting/reflections) */
1162
- envMap?: string | string[]
1163
- environmentRotation?: Euler$1 | [number, number, number]
1164
- environmentIntensity?: number
1165
- path?: string
1166
- extensions?: (loader: Loader) => void
1167
- }
1168
-
1169
- /**
1170
- * Background prop type for Canvas.
1171
- *
1172
- * String detection priority:
1173
- * 1. Preset - exact match against known presets (apartment, city, dawn, forest, lobby, night, park, studio, sunset, warehouse)
1174
- * 2. URL - starts with /, ./, ../, http://, https://, OR has image extension
1175
- * 3. Color - default fallback (CSS color names, hex values, rgb(), etc.)
1176
- *
1177
- * @example Color
1178
- * ```tsx
1179
- * <Canvas background="red" />
1180
- * <Canvas background="#ff0000" />
1181
- * <Canvas background={0xff0000} />
1182
- * ```
1183
- *
1184
- * @example Preset
1185
- * ```tsx
1186
- * <Canvas background="city" />
1187
- * ```
1188
- *
1189
- * @example URL
1190
- * ```tsx
1191
- * <Canvas background="/path/to/env.hdr" />
1192
- * <Canvas background="./sky.jpg" />
1193
- * ```
1194
- *
1195
- * @example Object form
1196
- * ```tsx
1197
- * <Canvas background={{
1198
- * files: ['px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'],
1199
- * backgroundMap: 'path/to/sky.jpg',
1200
- * envMap: 'path/to/lighting.hdr',
1201
- * backgroundBlurriness: 0.5,
1202
- * }} />
1203
- * ```
1204
- */
1205
- type BackgroundProp =
1206
- | ColorRepresentation // "red", "#ff0000", 0xff0000
1207
- | string // URL or preset
1208
- | BackgroundConfig // Expanded object form
1209
-
1210
- //* Canvas Types ==============================
1211
-
1212
- interface CanvasProps
1213
- extends
1214
- Omit<RenderProps<HTMLCanvasElement>, 'size' | 'primaryCanvas' | 'scheduler'>,
1215
- React$1.HTMLAttributes<HTMLDivElement> {
1216
- children?: React$1.ReactNode
1217
- ref?: React$1.Ref<HTMLCanvasElement>
1218
- /** Canvas fallback content, similar to img's alt prop */
1219
- fallback?: React$1.ReactNode
1220
- /**
1221
- * Options to pass to useMeasure.
1222
- * @see https://github.com/pmndrs/react-use-measure#api
1223
- */
1224
- resize?: Options
1225
- /** The target where events are being subscribed to, default: the div that wraps canvas */
1226
- eventSource?: HTMLElement | React$1.RefObject<HTMLElement | null>
1227
- /** The event prefix that is cast into canvas pointer x/y events, default: "offset" */
1228
- eventPrefix?: 'offset' | 'client' | 'page' | 'layer' | 'screen'
1229
- /** Enable/disable automatic HMR refresh for TSL nodes and uniforms, default: true in dev */
1230
- hmr?: boolean
1231
- /** Canvas resolution width in pixels. If omitted, uses container width. */
1232
- width?: number
1233
- /** Canvas resolution height in pixels. If omitted, uses container height. */
1234
- height?: number
1235
- /** Force canvas dimensions to even numbers (fixes Safari rendering issues with odd/fractional sizes) */
1236
- forceEven?: boolean
1237
- /**
1238
- * Scene background configuration.
1239
- * Accepts colors, URLs, presets, or an expanded object for separate background/environment.
1240
- * @see BackgroundProp for full documentation and examples
1241
- */
1242
- background?: BackgroundProp
1145
+ //* Background Types ==============================
1146
+
1147
+ /**
1148
+ * Expanded object form for background configuration.
1149
+ * Allows separate textures for background (visual backdrop) and environment (PBR lighting).
1150
+ */
1151
+ interface BackgroundConfig {
1152
+ /** HDRI preset name: 'apartment', 'city', 'dawn', 'forest', 'lobby', 'night', 'park', 'studio', 'sunset', 'warehouse' */
1153
+ preset?: PresetsType
1154
+ /** Files for cube texture (6 faces) or single HDR/EXR */
1155
+ files?: string | string[]
1156
+ /** Separate files for scene.background (visual backdrop) */
1157
+ backgroundMap?: string | string[]
1158
+ backgroundRotation?: Euler$1 | [number, number, number]
1159
+ backgroundBlurriness?: number
1160
+ backgroundIntensity?: number
1161
+ /** Separate files for scene.environment (PBR lighting/reflections) */
1162
+ envMap?: string | string[]
1163
+ environmentRotation?: Euler$1 | [number, number, number]
1164
+ environmentIntensity?: number
1165
+ path?: string
1166
+ extensions?: (loader: Loader) => void
1243
1167
  }
1244
1168
 
1245
- //* Loader Types ==============================
1246
-
1247
- type InputLike = string | string[] | string[][] | Readonly<string | string[] | string[][]>
1248
-
1249
- // Define a loader-like interface that matches THREE.Loader's load signature
1250
- // This works for both generic and non-generic THREE.Loader instances
1251
- interface LoaderLike {
1252
- load(
1253
- url: InputLike,
1254
- onLoad?: (result: any) => void,
1255
- onProgress?: (event: ProgressEvent<EventTarget>) => void,
1256
- onError?: (error: unknown) => void,
1257
- ): any
1258
- }
1259
-
1260
- type GLTFLike = { scene: THREE$1.Object3D }
1261
-
1262
- type LoaderInstance<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
1263
- T extends ConstructorRepresentation<LoaderLike> ? InstanceType<T> : T
1264
-
1265
- // Infer result type from the load method's callback parameter
1266
- type InferLoadResult<T> = T extends {
1267
- load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
1268
- }
1269
- ? R
1270
- : T extends ConstructorRepresentation<any>
1271
- ? InstanceType<T> extends {
1272
- load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
1273
- }
1274
- ? R
1275
- : any
1276
- : any
1277
-
1278
- type LoaderResult<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
1279
- InferLoadResult<LoaderInstance<T>> extends infer R ? (R extends GLTFLike ? R & ObjectMap : R) : never
1280
-
1281
- type Extensions<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> = (
1282
- loader: LoaderInstance<T>,
1169
+ /**
1170
+ * Background prop type for Canvas.
1171
+ *
1172
+ * String detection priority:
1173
+ * 1. Preset - exact match against known presets (apartment, city, dawn, forest, lobby, night, park, studio, sunset, warehouse)
1174
+ * 2. URL - starts with /, ./, ../, http://, https://, OR has image extension
1175
+ * 3. Color - default fallback (CSS color names, hex values, rgb(), etc.)
1176
+ *
1177
+ * @example Color
1178
+ * ```tsx
1179
+ * <Canvas background="red" />
1180
+ * <Canvas background="#ff0000" />
1181
+ * <Canvas background={0xff0000} />
1182
+ * ```
1183
+ *
1184
+ * @example Preset
1185
+ * ```tsx
1186
+ * <Canvas background="city" />
1187
+ * ```
1188
+ *
1189
+ * @example URL
1190
+ * ```tsx
1191
+ * <Canvas background="/path/to/env.hdr" />
1192
+ * <Canvas background="./sky.jpg" />
1193
+ * ```
1194
+ *
1195
+ * @example Object form
1196
+ * ```tsx
1197
+ * <Canvas background={{
1198
+ * files: ['px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'],
1199
+ * backgroundMap: 'path/to/sky.jpg',
1200
+ * envMap: 'path/to/lighting.hdr',
1201
+ * backgroundBlurriness: 0.5,
1202
+ * }} />
1203
+ * ```
1204
+ */
1205
+ type BackgroundProp =
1206
+ | ColorRepresentation // "red", "#ff0000", 0xff0000
1207
+ | string // URL or preset
1208
+ | BackgroundConfig // Expanded object form
1209
+
1210
+ //* Canvas Types ==============================
1211
+
1212
+ interface CanvasProps
1213
+ extends
1214
+ Omit<RenderProps<HTMLCanvasElement>, 'size' | 'primaryCanvas' | 'scheduler'>,
1215
+ React$1.HTMLAttributes<HTMLDivElement> {
1216
+ children?: React$1.ReactNode
1217
+ ref?: React$1.Ref<HTMLCanvasElement>
1218
+ /** Canvas fallback content, similar to img's alt prop */
1219
+ fallback?: React$1.ReactNode
1220
+ /**
1221
+ * Options to pass to useMeasure.
1222
+ * @see https://github.com/pmndrs/react-use-measure#api
1223
+ */
1224
+ resize?: Options
1225
+ /** The target where events are being subscribed to, default: the div that wraps canvas */
1226
+ eventSource?: HTMLElement | React$1.RefObject<HTMLElement | null>
1227
+ /** The event prefix that is cast into canvas pointer x/y events, default: "offset" */
1228
+ eventPrefix?: 'offset' | 'client' | 'page' | 'layer' | 'screen'
1229
+ /** Enable/disable automatic HMR refresh for TSL nodes and uniforms, default: true in dev */
1230
+ hmr?: boolean
1231
+ /** Canvas resolution width in pixels. If omitted, uses container width. */
1232
+ width?: number
1233
+ /** Canvas resolution height in pixels. If omitted, uses container height. */
1234
+ height?: number
1235
+ /** Force canvas dimensions to even numbers (fixes Safari rendering issues with odd/fractional sizes) */
1236
+ forceEven?: boolean
1237
+ /**
1238
+ * Scene background configuration.
1239
+ * Accepts colors, URLs, presets, or an expanded object for separate background/environment.
1240
+ * @see BackgroundProp for full documentation and examples
1241
+ */
1242
+ background?: BackgroundProp
1243
+ }
1244
+
1245
+ //* Loader Types ==============================
1246
+
1247
+ type InputLike = string | string[] | string[][] | Readonly<string | string[] | string[][]>
1248
+
1249
+ // Define a loader-like interface that matches THREE.Loader's load signature
1250
+ // This works for both generic and non-generic THREE.Loader instances
1251
+ interface LoaderLike {
1252
+ load(
1253
+ url: InputLike,
1254
+ onLoad?: (result: any) => void,
1255
+ onProgress?: (event: ProgressEvent<EventTarget>) => void,
1256
+ onError?: (error: unknown) => void,
1257
+ ): any
1258
+ }
1259
+
1260
+ type GLTFLike = { scene: THREE$1.Object3D }
1261
+
1262
+ type LoaderInstance<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
1263
+ T extends ConstructorRepresentation<LoaderLike> ? InstanceType<T> : T
1264
+
1265
+ // Infer result type from the load method's callback parameter
1266
+ type InferLoadResult<T> = T extends {
1267
+ load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
1268
+ }
1269
+ ? R
1270
+ : T extends ConstructorRepresentation<any>
1271
+ ? InstanceType<T> extends {
1272
+ load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
1273
+ }
1274
+ ? R
1275
+ : any
1276
+ : any
1277
+
1278
+ type LoaderResult<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
1279
+ InferLoadResult<LoaderInstance<T>> extends infer R ? (R extends GLTFLike ? R & ObjectMap : R) : never
1280
+
1281
+ type Extensions<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> = (
1282
+ loader: LoaderInstance<T>,
1283
1283
  ) => void
1284
1284
 
1285
- //* Renderer Props ========================================
1286
-
1287
- type WebGLDefaultProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & BaseRendererProps
1288
-
1289
- type WebGLProps =
1290
- | RendererFactory<THREE$1.WebGLRenderer, WebGLDefaultProps>
1291
- | Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters>
1292
-
1293
- interface WebGLShadowConfig {
1294
- shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
1295
- }
1296
-
1297
- //* Legacy-specific Types ========================================
1298
-
1299
- /** Legacy (WebGL) renderer type - re-exported as R3FRenderer from @react-three/fiber/legacy */
1300
- type LegacyRenderer = THREE$1.WebGLRenderer
1301
-
1302
- /** Legacy internal state with narrowed renderer type */
1303
- interface LegacyInternalState extends Omit<InternalState, 'actualRenderer'> {
1304
- actualRenderer: THREE$1.WebGLRenderer
1305
- }
1306
-
1307
- /**
1308
- * Legacy-specific RootState with narrowed renderer type.
1309
- * Automatically used when importing from `@react-three/fiber/legacy`.
1310
- *
1311
- * @example
1312
- * ```tsx
1313
- * import { useThree } from '@react-three/fiber/legacy'
1314
- *
1315
- * function MyComponent() {
1316
- * const { renderer } = useThree()
1317
- * // renderer is typed as THREE.WebGLRenderer
1318
- * renderer.shadowMap.enabled = true
1319
- * }
1320
- * ```
1321
- */
1322
- interface LegacyRootState extends Omit<RootState, 'renderer' | 'internal'> {
1323
- /** The WebGL renderer instance */
1324
- renderer: THREE$1.WebGLRenderer
1325
- /** Internals with WebGL renderer */
1326
- internal: LegacyInternalState
1285
+ //* Renderer Props ========================================
1286
+
1287
+ type WebGLDefaultProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & BaseRendererProps
1288
+
1289
+ type WebGLProps =
1290
+ | RendererFactory<THREE$1.WebGLRenderer, WebGLDefaultProps>
1291
+ | Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters>
1292
+
1293
+ interface WebGLShadowConfig {
1294
+ shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
1295
+ }
1296
+
1297
+ //* Legacy-specific Types ========================================
1298
+
1299
+ /** Legacy (WebGL) renderer type - re-exported as R3FRenderer from @react-three/fiber/legacy */
1300
+ type LegacyRenderer = THREE$1.WebGLRenderer
1301
+
1302
+ /** Legacy internal state with narrowed renderer type */
1303
+ interface LegacyInternalState extends Omit<InternalState, 'actualRenderer'> {
1304
+ actualRenderer: THREE$1.WebGLRenderer
1305
+ }
1306
+
1307
+ /**
1308
+ * Legacy-specific RootState with narrowed renderer type.
1309
+ * Automatically used when importing from `@react-three/fiber/legacy`.
1310
+ *
1311
+ * @example
1312
+ * ```tsx
1313
+ * import { useThree } from '@react-three/fiber/legacy'
1314
+ *
1315
+ * function MyComponent() {
1316
+ * const { renderer } = useThree()
1317
+ * // renderer is typed as THREE.WebGLRenderer
1318
+ * renderer.shadowMap.enabled = true
1319
+ * }
1320
+ * ```
1321
+ */
1322
+ interface LegacyRootState extends Omit<RootState, 'renderer' | 'internal'> {
1323
+ /** The WebGL renderer instance */
1324
+ renderer: THREE$1.WebGLRenderer
1325
+ /** Internals with WebGL renderer */
1326
+ internal: LegacyInternalState
1327
1327
  }
1328
1328
 
1329
- //* RenderTarget Types ==============================
1330
-
1331
-
1329
+ //* RenderTarget Types ==============================
1330
+
1331
+
1332
1332
  type RenderTargetOptions = RenderTargetOptions$1
1333
1333
 
1334
- //* Global Types ==============================
1335
-
1336
- declare global {
1337
- /** Uniform node type - a Node with a value property (matches Three.js UniformNode) */
1338
- interface UniformNode<T = unknown> extends Node {
1339
- value: T
1340
- }
1341
-
1342
- /**
1343
- * ShaderCallable - the return type of Fn()
1344
- * A callable shader function node that can be invoked with parameters.
1345
- * The function returns a ShaderNodeObject when called.
1346
- *
1347
- * @example
1348
- * ```tsx
1349
- * // Define a shader function
1350
- * const blendColorFn = Fn(([color1, color2, factor]) => {
1351
- * return mix(color1, color2, factor)
1352
- * })
1353
- *
1354
- * // Type when retrieving from nodes store
1355
- * const { blendColorFn } = nodes as { blendColorFn: ShaderCallable }
1356
- *
1357
- * // Or with specific return type
1358
- * const { myFn } = nodes as { myFn: ShaderCallable<THREE.Node> }
1359
- * ```
1360
- */
1361
- type ShaderCallable<R extends Node = Node> = ((...params: unknown[]) => ShaderNodeObject<R>) & Node
1362
-
1363
- /**
1364
- * ShaderNodeRef - a ShaderNodeObject wrapper around a Node
1365
- * This is the common return type for TSL operations (add, mul, sin, etc.)
1366
- *
1367
- * @example
1368
- * ```tsx
1369
- * const { wobble } = nodes as { wobble: ShaderNodeRef }
1370
- * ```
1371
- */
1372
- type ShaderNodeRef<T extends Node = Node> = ShaderNodeObject<T>
1373
-
1374
- /**
1375
- * TSLNodeType - Union of all common TSL node types
1376
- * Used by ScopedStore to properly type node access from the store.
1377
- *
1378
- * Includes:
1379
- * - Node: base Three.js node type
1380
- * - ShaderCallable: function nodes created with Fn()
1381
- * - ShaderNodeObject: wrapped nodes from TSL operations (sin, mul, mix, etc.)
1382
- *
1383
- * @example
1384
- * ```tsx
1385
- * // In useLocalNodes, nodes are typed as TSLNodeType
1386
- * const { positionNode, blendColorFn } = useLocalNodes(({ nodes }) => ({
1387
- * positionNode: nodes.myPosition, // Works - Node is in union
1388
- * blendColorFn: nodes.myFn, // Works - ShaderCallable is in union
1389
- * }))
1390
- *
1391
- * // Can narrow with type guard or assertion when needed
1392
- * if (typeof blendColorFn === 'function') {
1393
- * blendColorFn(someColor, 0.5)
1394
- * }
1395
- * ```
1396
- */
1397
- type TSLNodeType = Node | ShaderCallable<Node> | ShaderNodeObject<Node>
1398
-
1399
- /** Flat record of uniform nodes (no nested scopes) */
1400
- type UniformRecord<T extends UniformNode = UniformNode> = Record<string, T>
1401
-
1402
- /**
1403
- * Uniform store that can contain both root-level uniforms and scoped uniform objects
1404
- * Used by state.uniforms which has structure like:
1405
- * { uTime: UniformNode, player: { uHealth: UniformNode }, enemy: { uHealth: UniformNode } }
1406
- */
1407
- type UniformStore = Record<string, UniformNode | UniformRecord>
1408
-
1409
- /**
1410
- * Helper to safely access a uniform node from the store.
1411
- * Use this when accessing state.uniforms to get proper typing.
1412
- * @example
1413
- * const uTime = uniforms.uTime as UniformNode<number>
1414
- * const uColor = uniforms.uColor as UniformNode<import('three/webgpu').Color>
1415
- */
1416
- type GetUniform<T = unknown> = UniformNode<T>
1417
-
1418
- /**
1419
- * Acceptable input values for useUniforms - raw values that get converted to UniformNodes
1420
- * Supports:
1421
- * - Primitives: number, string (color), boolean
1422
- * - Three.js types: Color, Vector2/3/4, Matrix3/4, Euler, Quaternion
1423
- * - Plain objects: { x, y, z, w } converted to vectors
1424
- * - TSL nodes: color(), vec3(), float() for type casting
1425
- * - UniformNode: existing uniforms (reused as-is)
1426
- */
1427
- type UniformValue =
1428
- | number
1429
- | string
1430
- | boolean
1431
- | three_webgpu.Color
1432
- | three_webgpu.Vector2
1433
- | three_webgpu.Vector3
1434
- | three_webgpu.Vector4
1435
- | three_webgpu.Matrix3
1436
- | three_webgpu.Matrix4
1437
- | three_webgpu.Euler
1438
- | three_webgpu.Quaternion
1439
- | { x: number; y?: number; z?: number; w?: number } // Plain objects converted to vectors
1440
- | { r: number; g: number; b: number; a?: number } // Plain objects converted to Color
1441
- | Node // TSL nodes like color(), vec3(), float() for type casting
1442
- | UniformNode
1443
-
1444
- /** Input record for useUniforms - accepts raw values or UniformNodes */
1445
- type UniformInputRecord = Record<string, UniformValue>
1446
- }
1447
-
1448
- //* Module Augmentation ==============================
1449
-
1450
- declare module 'three/tsl' {
1451
- /**
1452
- * Fn with array parameter destructuring
1453
- * @example Fn(([uv, skew]) => { ... })
1454
- */
1455
- export function Fn<R extends Node = Node>(
1456
- jsFunc: (inputs: ShaderNodeObject<Node>[]) => ShaderNodeObject<R>,
1457
- ): ShaderCallable<R>
1458
-
1459
- /**
1460
- * Fn with object parameter destructuring
1461
- * @example Fn(({ color, intensity }) => { ... })
1462
- */
1463
- export function Fn<T extends Record<string, unknown>, R extends Node = Node>(
1464
- jsFunc: (inputs: T) => ShaderNodeObject<R>,
1465
- ): ShaderCallable<R>
1466
-
1467
- /**
1468
- * Fn with array params + layout
1469
- * @example Fn(([a, b]) => { ... }, { layout: [...] })
1470
- */
1471
- export function Fn<R extends Node = Node>(
1472
- jsFunc: (inputs: ShaderNodeObject<Node>[]) => ShaderNodeObject<R>,
1473
- layout: { layout?: unknown },
1474
- ): ShaderCallable<R>
1475
-
1476
- /**
1477
- * Fn with object params + layout
1478
- */
1479
- export function Fn<T extends Record<string, unknown>, R extends Node = Node>(
1480
- jsFunc: (inputs: T) => ShaderNodeObject<R>,
1481
- layout: { layout?: unknown },
1482
- ): ShaderCallable<R>
1334
+ //* Global Types ==============================
1335
+
1336
+ declare global {
1337
+ /** Uniform node type - a Node with a value property (matches Three.js UniformNode) */
1338
+ interface UniformNode<T = unknown> extends Node {
1339
+ value: T
1340
+ }
1341
+
1342
+ /**
1343
+ * ShaderCallable - the return type of Fn()
1344
+ * A callable shader function node that can be invoked with parameters.
1345
+ * The function returns a ShaderNodeObject when called.
1346
+ *
1347
+ * @example
1348
+ * ```tsx
1349
+ * // Define a shader function
1350
+ * const blendColorFn = Fn(([color1, color2, factor]) => {
1351
+ * return mix(color1, color2, factor)
1352
+ * })
1353
+ *
1354
+ * // Type when retrieving from nodes store
1355
+ * const { blendColorFn } = nodes as { blendColorFn: ShaderCallable }
1356
+ *
1357
+ * // Or with specific return type
1358
+ * const { myFn } = nodes as { myFn: ShaderCallable<THREE.Node> }
1359
+ * ```
1360
+ */
1361
+ type ShaderCallable<R extends Node = Node> = ((...params: unknown[]) => ShaderNodeObject<R>) & Node
1362
+
1363
+ /**
1364
+ * ShaderNodeRef - a ShaderNodeObject wrapper around a Node
1365
+ * This is the common return type for TSL operations (add, mul, sin, etc.)
1366
+ *
1367
+ * @example
1368
+ * ```tsx
1369
+ * const { wobble } = nodes as { wobble: ShaderNodeRef }
1370
+ * ```
1371
+ */
1372
+ type ShaderNodeRef<T extends Node = Node> = ShaderNodeObject<T>
1373
+
1374
+ /**
1375
+ * TSLNodeType - Union of all common TSL node types
1376
+ * Used by ScopedStore to properly type node access from the store.
1377
+ *
1378
+ * Includes:
1379
+ * - Node: base Three.js node type
1380
+ * - ShaderCallable: function nodes created with Fn()
1381
+ * - ShaderNodeObject: wrapped nodes from TSL operations (sin, mul, mix, etc.)
1382
+ *
1383
+ * @example
1384
+ * ```tsx
1385
+ * // In useLocalNodes, nodes are typed as TSLNodeType
1386
+ * const { positionNode, blendColorFn } = useLocalNodes(({ nodes }) => ({
1387
+ * positionNode: nodes.myPosition, // Works - Node is in union
1388
+ * blendColorFn: nodes.myFn, // Works - ShaderCallable is in union
1389
+ * }))
1390
+ *
1391
+ * // Can narrow with type guard or assertion when needed
1392
+ * if (typeof blendColorFn === 'function') {
1393
+ * blendColorFn(someColor, 0.5)
1394
+ * }
1395
+ * ```
1396
+ */
1397
+ type TSLNodeType = Node | ShaderCallable<Node> | ShaderNodeObject<Node>
1398
+
1399
+ /** Flat record of uniform nodes (no nested scopes) */
1400
+ type UniformRecord<T extends UniformNode = UniformNode> = Record<string, T>
1401
+
1402
+ /**
1403
+ * Uniform store that can contain both root-level uniforms and scoped uniform objects
1404
+ * Used by state.uniforms which has structure like:
1405
+ * { uTime: UniformNode, player: { uHealth: UniformNode }, enemy: { uHealth: UniformNode } }
1406
+ */
1407
+ type UniformStore = Record<string, UniformNode | UniformRecord>
1408
+
1409
+ /**
1410
+ * Helper to safely access a uniform node from the store.
1411
+ * Use this when accessing state.uniforms to get proper typing.
1412
+ * @example
1413
+ * const uTime = uniforms.uTime as UniformNode<number>
1414
+ * const uColor = uniforms.uColor as UniformNode<import('three/webgpu').Color>
1415
+ */
1416
+ type GetUniform<T = unknown> = UniformNode<T>
1417
+
1418
+ /**
1419
+ * Acceptable input values for useUniforms - raw values that get converted to UniformNodes
1420
+ * Supports:
1421
+ * - Primitives: number, string (color), boolean
1422
+ * - Three.js types: Color, Vector2/3/4, Matrix3/4, Euler, Quaternion
1423
+ * - Plain objects: { x, y, z, w } converted to vectors
1424
+ * - TSL nodes: color(), vec3(), float() for type casting
1425
+ * - UniformNode: existing uniforms (reused as-is)
1426
+ */
1427
+ type UniformValue =
1428
+ | number
1429
+ | string
1430
+ | boolean
1431
+ | three_webgpu.Color
1432
+ | three_webgpu.Vector2
1433
+ | three_webgpu.Vector3
1434
+ | three_webgpu.Vector4
1435
+ | three_webgpu.Matrix3
1436
+ | three_webgpu.Matrix4
1437
+ | three_webgpu.Euler
1438
+ | three_webgpu.Quaternion
1439
+ | { x: number; y?: number; z?: number; w?: number } // Plain objects converted to vectors
1440
+ | { r: number; g: number; b: number; a?: number } // Plain objects converted to Color
1441
+ | Node // TSL nodes like color(), vec3(), float() for type casting
1442
+ | UniformNode
1443
+
1444
+ /** Input record for useUniforms - accepts raw values or UniformNodes */
1445
+ type UniformInputRecord = Record<string, UniformValue>
1446
+ }
1447
+
1448
+ //* Module Augmentation ==============================
1449
+
1450
+ declare module 'three/tsl' {
1451
+ /**
1452
+ * Fn with array parameter destructuring
1453
+ * @example Fn(([uv, skew]) => { ... })
1454
+ */
1455
+ export function Fn<R extends Node = Node>(
1456
+ jsFunc: (inputs: ShaderNodeObject<Node>[]) => ShaderNodeObject<R>,
1457
+ ): ShaderCallable<R>
1458
+
1459
+ /**
1460
+ * Fn with object parameter destructuring
1461
+ * @example Fn(({ color, intensity }) => { ... })
1462
+ */
1463
+ export function Fn<T extends Record<string, unknown>, R extends Node = Node>(
1464
+ jsFunc: (inputs: T) => ShaderNodeObject<R>,
1465
+ ): ShaderCallable<R>
1466
+
1467
+ /**
1468
+ * Fn with array params + layout
1469
+ * @example Fn(([a, b]) => { ... }, { layout: [...] })
1470
+ */
1471
+ export function Fn<R extends Node = Node>(
1472
+ jsFunc: (inputs: ShaderNodeObject<Node>[]) => ShaderNodeObject<R>,
1473
+ layout: { layout?: unknown },
1474
+ ): ShaderCallable<R>
1475
+
1476
+ /**
1477
+ * Fn with object params + layout
1478
+ */
1479
+ export function Fn<T extends Record<string, unknown>, R extends Node = Node>(
1480
+ jsFunc: (inputs: T) => ShaderNodeObject<R>,
1481
+ layout: { layout?: unknown },
1482
+ ): ShaderCallable<R>
1483
+ }
1484
+
1485
+ /**
1486
+ * RenderPipeline Types for useRenderPipeline hook (WebGPU only)
1487
+ */
1488
+
1489
+
1490
+
1491
+ declare global {
1492
+ /** Pass record - stores TSL pass nodes for render pipeline */
1493
+ type PassRecord = Record<string, any>
1494
+
1495
+ /** Setup callback - runs first to configure MRT, create additional passes */
1496
+ type RenderPipelineSetupCallback = (state: RootState) => PassRecord | void
1497
+
1498
+ /** Main callback - runs second to configure outputNode, create effect passes */
1499
+ type RenderPipelineMainCallback = (state: RootState) => PassRecord | void
1500
+
1501
+ /** Return type for useRenderPipeline hook */
1502
+ interface UseRenderPipelineReturn {
1503
+ /** Current passes from state */
1504
+ passes: PassRecord
1505
+ /** RenderPipeline instance (null if not initialized) */
1506
+ renderPipeline: any | null // THREE.PostProcessing (will be THREE.RenderPipeline in future Three.js release)
1507
+ /** Clear all passes from state */
1508
+ clearPasses: () => void
1509
+ /** Reset RenderPipeline entirely (clears PP + passes) */
1510
+ reset: () => void
1511
+ /** Re-run setup/main callbacks with current closure values */
1512
+ rebuild: () => void
1513
+ /** True when RenderPipeline is configured and ready */
1514
+ isReady: boolean
1515
+ }
1516
+ }
1517
+
1518
+ //* useFrameNext Types ==============================
1519
+
1520
+
1521
+
1522
+ //* Global Type Declarations ==============================
1523
+
1524
+ declare global {
1525
+ // Job --------------------------------
1526
+
1527
+ /**
1528
+ * Internal job representation in the scheduler
1529
+ */
1530
+ interface Job {
1531
+ /** Unique identifier */
1532
+ id: string
1533
+ /** The callback to execute */
1534
+ callback: FrameNextCallback
1535
+ /** Phase this job belongs to */
1536
+ phase: string
1537
+ /** Run before these phases/job ids */
1538
+ before: Set<string>
1539
+ /** Run after these phases/job ids */
1540
+ after: Set<string>
1541
+ /** Priority within phase (higher first) */
1542
+ priority: number
1543
+ /** Insertion order for deterministic tie-breaking */
1544
+ index: number
1545
+ /** Max FPS for this job (undefined = no limit) */
1546
+ fps?: number
1547
+ /** Drop frames when behind (true) or catch up (false) */
1548
+ drop: boolean
1549
+ /** Last run timestamp (ms) */
1550
+ lastRun?: number
1551
+ /** Whether job is enabled */
1552
+ enabled: boolean
1553
+ /** Internal flag: system jobs (like default render) don't block user render takeover */
1554
+ system?: boolean
1555
+ }
1556
+
1557
+ // Phase Graph --------------------------------
1558
+
1559
+ /**
1560
+ * A node in the phase graph
1561
+ */
1562
+ interface PhaseNode {
1563
+ /** Phase name */
1564
+ name: string
1565
+ /** Whether this was auto-generated from a before/after constraint */
1566
+ isAutoGenerated: boolean
1567
+ }
1568
+
1569
+ /**
1570
+ * Options for creating a job from hook options
1571
+ */
1572
+ interface JobOptions {
1573
+ id?: string
1574
+ phase?: string
1575
+ before?: string | string[]
1576
+ after?: string | string[]
1577
+ priority?: number
1578
+ fps?: number
1579
+ drop?: boolean
1580
+ enabled?: boolean
1581
+ }
1582
+
1583
+ // Frame Loop State --------------------------------
1584
+
1585
+ /**
1586
+ * Internal frame loop state
1587
+ */
1588
+ interface FrameLoopState {
1589
+ /** Whether the loop is running */
1590
+ running: boolean
1591
+ /** Current RAF handle */
1592
+ rafHandle: number | null
1593
+ /** Last frame timestamp in ms (null = uninitialized) */
1594
+ lastTime: number | null
1595
+ /** Frame counter */
1596
+ frameCount: number
1597
+ /** Elapsed time since first frame in ms */
1598
+ elapsedTime: number
1599
+ /** createdAt timestamp in ms */
1600
+ createdAt: number
1601
+ }
1602
+
1603
+ // Root Entry --------------------------------
1604
+
1605
+ /**
1606
+ * Internal representation of a registered root (Canvas).
1607
+ * Tracks jobs and manages rebuild state for this root.
1608
+ * @internal
1609
+ */
1610
+ interface RootEntry {
1611
+ /** Unique identifier for this root */
1612
+ id: string
1613
+ /** Function to get the root's current state. Returns any to support independent mode. */
1614
+ getState: () => any
1615
+ /** Map of job IDs to Job objects */
1616
+ jobs: Map<string, Job>
1617
+ /** Cached sorted job list for execution order */
1618
+ sortedJobs: Job[]
1619
+ /** Whether sortedJobs needs rebuilding */
1620
+ needsRebuild: boolean
1621
+ }
1622
+
1623
+ /**
1624
+ * Internal representation of a global job (deprecated API).
1625
+ * Global jobs run once per frame, not per-root.
1626
+ * Used by legacy addEffect/addAfterEffect APIs.
1627
+ * @internal
1628
+ * @deprecated Use useFrame with phases instead
1629
+ */
1630
+ interface GlobalJob {
1631
+ /** Unique identifier for this global job */
1632
+ id: string
1633
+ /** Callback invoked with RAF timestamp in ms */
1634
+ callback: (timestamp: number) => void
1635
+ }
1636
+
1637
+ // HMR Support --------------------------------
1638
+
1639
+ /**
1640
+ * Hot Module Replacement data structure for preserving scheduler state
1641
+ * @internal
1642
+ */
1643
+ interface HMRData {
1644
+ /** Shared data object for storing values across reloads */
1645
+ data: Record<string, any>
1646
+ /** Optional function to accept HMR updates */
1647
+ accept?: () => void
1648
+ }
1649
+
1650
+ // Default Phases --------------------------------
1651
+
1652
+ /**
1653
+ * Default phase names for the scheduler
1654
+ */
1655
+ type DefaultPhase = 'start' | 'input' | 'physics' | 'update' | 'render' | 'finish'
1656
+ }
1657
+
1658
+ type MutableOrReadonlyParameters<T extends (...args: any) => any> = Parameters<T> | Readonly<Parameters<T>>
1659
+
1660
+ interface MathRepresentation {
1661
+ set(...args: number[]): any
1662
+ }
1663
+ interface VectorRepresentation extends MathRepresentation {
1664
+ setScalar(value: number): any
1665
+ }
1666
+ type MathTypes = MathRepresentation | Euler$1 | Color$1
1667
+
1668
+ type MathType<T extends MathTypes> = T extends Color$1
1669
+ ? Args<typeof Color$1> | ColorRepresentation
1670
+ : T extends VectorRepresentation | Layers$1 | Euler$1
1671
+ ? T | MutableOrReadonlyParameters<T['set']> | number
1672
+ : T | MutableOrReadonlyParameters<T['set']>
1673
+
1674
+ type MathProps<P> = {
1675
+ [K in keyof P as P[K] extends MathTypes ? K : never]: P[K] extends MathTypes ? MathType<P[K]> : never
1676
+ }
1677
+
1678
+ type Vector2 = MathType<Vector2$1>
1679
+ type Vector3 = MathType<Vector3$1>
1680
+ type Vector4 = MathType<Vector4$1>
1681
+ type Color = MathType<Color$1>
1682
+ type Layers = MathType<Layers$1>
1683
+ type Quaternion = MathType<Quaternion$1>
1684
+ type Euler = MathType<Euler$1>
1685
+ type Matrix3 = MathType<Matrix3$1>
1686
+ type Matrix4 = MathType<Matrix4$1>
1687
+
1688
+ interface RaycastableRepresentation {
1689
+ raycast(raycaster: Raycaster, intersects: Intersection$1[]): void
1690
+ }
1691
+ type EventProps<P> = P extends RaycastableRepresentation ? Partial<EventHandlers> : {}
1692
+
1693
+ /**
1694
+ * Props for geometry transform methods that can be called with `once()`.
1695
+ * These methods modify the geometry in-place and only make sense to call once on mount.
1696
+ *
1697
+ * @example
1698
+ * import { once } from '@react-three/fiber'
1699
+ *
1700
+ * <boxGeometry args={[1, 1, 1]} rotateX={once(Math.PI / 2)} />
1701
+ * <planeGeometry args={[10, 10]} translate={once(0, 0, 5)} />
1702
+ * <bufferGeometry applyMatrix4={once(matrix)} center={once()} />
1703
+ */
1704
+ interface GeometryTransformProps {
1705
+ /** Rotate the geometry about the X axis (radians). Use with once(). */
1706
+ rotateX?: number
1707
+ /** Rotate the geometry about the Y axis (radians). Use with once(). */
1708
+ rotateY?: number
1709
+ /** Rotate the geometry about the Z axis (radians). Use with once(). */
1710
+ rotateZ?: number
1711
+ /** Translate the geometry (x, y, z). Use with once(). */
1712
+ translate?: [x: number, y: number, z: number]
1713
+ /** Scale the geometry (x, y, z). Use with once(). */
1714
+ scale?: [x: number, y: number, z: number]
1715
+ /** Center the geometry based on bounding box. Use with once(). */
1716
+ center?: true
1717
+ /** Apply a Matrix4 transformation. Use with once(). */
1718
+ applyMatrix4?: Matrix4$1
1719
+ /** Apply a Quaternion rotation. Use with once(). */
1720
+ applyQuaternion?: Quaternion$1
1721
+ }
1722
+
1723
+ type GeometryProps<P> = P extends BufferGeometry ? GeometryTransformProps : {}
1724
+
1725
+ /**
1726
+ * Workaround for @types/three TSL node type issues.
1727
+ * The Node base class has properties that subclasses (OperatorNode, ConstNode, etc.) don't inherit.
1728
+ * This transforms `Node | null` properties to accept any object with node-like shape.
1729
+ */
1730
+ type TSLNodeInput = { nodeType?: string | null; uuid?: string } | null
1731
+
1732
+ /**
1733
+ * For node material properties (colorNode, positionNode, etc.), accept broader types
1734
+ * since @types/three has broken inheritance for TSL node subclasses.
1735
+ */
1736
+ type NodeProps<P> = {
1737
+ [K in keyof P as P[K] extends Node$1 | null ? K : never]?: TSLNodeInput
1738
+ }
1739
+
1740
+ interface ReactProps<P> {
1741
+ children?: React.ReactNode
1742
+ ref?: React.Ref<P>
1743
+ key?: React.Key
1744
+ }
1745
+
1746
+ type ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = Partial<
1747
+ Overwrite<P, MathProps<P> & ReactProps<P> & EventProps<P> & GeometryProps<P> & NodeProps<P>>
1748
+ >
1749
+
1750
+ type ThreeElement<T extends ConstructorRepresentation> = Mutable<
1751
+ Overwrite<ElementProps<T>, Omit<InstanceProps<InstanceType<T>, T>, 'object'>>
1752
+ >
1753
+
1754
+ type ThreeToJSXElements<T extends Record<string, any>> = {
1755
+ [K in keyof T & string as Uncapitalize<K>]: T[K] extends ConstructorRepresentation ? ThreeElement<T[K]> : never
1756
+ }
1757
+
1758
+ type ThreeExports = typeof THREE
1759
+ type ThreeElementsImpl = ThreeToJSXElements<ThreeExports>
1760
+
1761
+ interface ThreeElements extends Omit<ThreeElementsImpl, 'audio' | 'source' | 'line' | 'path'> {
1762
+ primitive: Omit<ThreeElement<any>, 'args'> & { object: object }
1763
+ // Conflicts with DOM types can be accessed through a three* prefix
1764
+ threeAudio: ThreeElementsImpl['audio']
1765
+ threeSource: ThreeElementsImpl['source']
1766
+ threeLine: ThreeElementsImpl['line']
1767
+ threePath: ThreeElementsImpl['path']
1483
1768
  }
1484
1769
 
1485
- /**
1486
- * RenderPipeline Types for useRenderPipeline hook (WebGPU only)
1487
- */
1488
-
1489
-
1490
-
1491
- declare global {
1492
- /** Pass record - stores TSL pass nodes for render pipeline */
1493
- type PassRecord = Record<string, any>
1494
-
1495
- /** Setup callback - runs first to configure MRT, create additional passes */
1496
- type RenderPipelineSetupCallback = (state: RootState) => PassRecord | void
1497
-
1498
- /** Main callback - runs second to configure outputNode, create effect passes */
1499
- type RenderPipelineMainCallback = (state: RootState) => PassRecord | void
1500
-
1501
- /** Return type for useRenderPipeline hook */
1502
- interface UseRenderPipelineReturn {
1503
- /** Current passes from state */
1504
- passes: PassRecord
1505
- /** RenderPipeline instance (null if not initialized) */
1506
- renderPipeline: any | null // THREE.PostProcessing (will be THREE.RenderPipeline in future Three.js release)
1507
- /** Clear all passes from state */
1508
- clearPasses: () => void
1509
- /** Reset RenderPipeline entirely (clears PP + passes) */
1510
- reset: () => void
1511
- /** Re-run setup/main callbacks with current closure values */
1512
- rebuild: () => void
1513
- /** True when RenderPipeline is configured and ready */
1514
- isReady: boolean
1515
- }
1770
+ declare module 'react' {
1771
+ namespace JSX {
1772
+ interface IntrinsicElements extends ThreeElements {}
1773
+ }
1516
1774
  }
1517
1775
 
1518
- //* useFrameNext Types ==============================
1519
-
1520
-
1521
-
1522
- //* Global Type Declarations ==============================
1523
-
1524
- declare global {
1525
- // Job --------------------------------
1526
-
1527
- /**
1528
- * Internal job representation in the scheduler
1529
- */
1530
- interface Job {
1531
- /** Unique identifier */
1532
- id: string
1533
- /** The callback to execute */
1534
- callback: FrameNextCallback
1535
- /** Phase this job belongs to */
1536
- phase: string
1537
- /** Run before these phases/job ids */
1538
- before: Set<string>
1539
- /** Run after these phases/job ids */
1540
- after: Set<string>
1541
- /** Priority within phase (higher first) */
1542
- priority: number
1543
- /** Insertion order for deterministic tie-breaking */
1544
- index: number
1545
- /** Max FPS for this job (undefined = no limit) */
1546
- fps?: number
1547
- /** Drop frames when behind (true) or catch up (false) */
1548
- drop: boolean
1549
- /** Last run timestamp (ms) */
1550
- lastRun?: number
1551
- /** Whether job is enabled */
1552
- enabled: boolean
1553
- /** Internal flag: system jobs (like default render) don't block user render takeover */
1554
- system?: boolean
1555
- }
1556
-
1557
- // Phase Graph --------------------------------
1558
-
1559
- /**
1560
- * A node in the phase graph
1561
- */
1562
- interface PhaseNode {
1563
- /** Phase name */
1564
- name: string
1565
- /** Whether this was auto-generated from a before/after constraint */
1566
- isAutoGenerated: boolean
1567
- }
1568
-
1569
- /**
1570
- * Options for creating a job from hook options
1571
- */
1572
- interface JobOptions {
1573
- id?: string
1574
- phase?: string
1575
- before?: string | string[]
1576
- after?: string | string[]
1577
- priority?: number
1578
- fps?: number
1579
- drop?: boolean
1580
- enabled?: boolean
1581
- }
1582
-
1583
- // Frame Loop State --------------------------------
1584
-
1585
- /**
1586
- * Internal frame loop state
1587
- */
1588
- interface FrameLoopState {
1589
- /** Whether the loop is running */
1590
- running: boolean
1591
- /** Current RAF handle */
1592
- rafHandle: number | null
1593
- /** Last frame timestamp in ms (null = uninitialized) */
1594
- lastTime: number | null
1595
- /** Frame counter */
1596
- frameCount: number
1597
- /** Elapsed time since first frame in ms */
1598
- elapsedTime: number
1599
- /** createdAt timestamp in ms */
1600
- createdAt: number
1601
- }
1602
-
1603
- // Root Entry --------------------------------
1604
-
1605
- /**
1606
- * Internal representation of a registered root (Canvas).
1607
- * Tracks jobs and manages rebuild state for this root.
1608
- * @internal
1609
- */
1610
- interface RootEntry {
1611
- /** Unique identifier for this root */
1612
- id: string
1613
- /** Function to get the root's current state. Returns any to support independent mode. */
1614
- getState: () => any
1615
- /** Map of job IDs to Job objects */
1616
- jobs: Map<string, Job>
1617
- /** Cached sorted job list for execution order */
1618
- sortedJobs: Job[]
1619
- /** Whether sortedJobs needs rebuilding */
1620
- needsRebuild: boolean
1621
- }
1622
-
1623
- /**
1624
- * Internal representation of a global job (deprecated API).
1625
- * Global jobs run once per frame, not per-root.
1626
- * Used by legacy addEffect/addAfterEffect APIs.
1627
- * @internal
1628
- * @deprecated Use useFrame with phases instead
1629
- */
1630
- interface GlobalJob {
1631
- /** Unique identifier for this global job */
1632
- id: string
1633
- /** Callback invoked with RAF timestamp in ms */
1634
- callback: (timestamp: number) => void
1635
- }
1636
-
1637
- // HMR Support --------------------------------
1638
-
1639
- /**
1640
- * Hot Module Replacement data structure for preserving scheduler state
1641
- * @internal
1642
- */
1643
- interface HMRData {
1644
- /** Shared data object for storing values across reloads */
1645
- data: Record<string, any>
1646
- /** Optional function to accept HMR updates */
1647
- accept?: () => void
1648
- }
1649
-
1650
- // Default Phases --------------------------------
1651
-
1652
- /**
1653
- * Default phase names for the scheduler
1654
- */
1655
- type DefaultPhase = 'start' | 'input' | 'physics' | 'update' | 'render' | 'finish'
1776
+ declare module 'react/jsx-runtime' {
1777
+ namespace JSX {
1778
+ interface IntrinsicElements extends ThreeElements {}
1779
+ }
1656
1780
  }
1657
1781
 
1658
- type MutableOrReadonlyParameters<T extends (...args: any) => any> = Parameters<T> | Readonly<Parameters<T>>
1659
-
1660
- interface MathRepresentation {
1661
- set(...args: number[]): any
1662
- }
1663
- interface VectorRepresentation extends MathRepresentation {
1664
- setScalar(value: number): any
1665
- }
1666
- type MathTypes = MathRepresentation | Euler$1 | Color$1
1667
-
1668
- type MathType<T extends MathTypes> = T extends Color$1
1669
- ? Args<typeof Color$1> | ColorRepresentation
1670
- : T extends VectorRepresentation | Layers$1 | Euler$1
1671
- ? T | MutableOrReadonlyParameters<T['set']> | number
1672
- : T | MutableOrReadonlyParameters<T['set']>
1673
-
1674
- type MathProps<P> = {
1675
- [K in keyof P as P[K] extends MathTypes ? K : never]: P[K] extends MathTypes ? MathType<P[K]> : never
1676
- }
1677
-
1678
- type Vector2 = MathType<Vector2$1>
1679
- type Vector3 = MathType<Vector3$1>
1680
- type Vector4 = MathType<Vector4$1>
1681
- type Color = MathType<Color$1>
1682
- type Layers = MathType<Layers$1>
1683
- type Quaternion = MathType<Quaternion$1>
1684
- type Euler = MathType<Euler$1>
1685
- type Matrix3 = MathType<Matrix3$1>
1686
- type Matrix4 = MathType<Matrix4$1>
1687
-
1688
- interface RaycastableRepresentation {
1689
- raycast(raycaster: Raycaster, intersects: Intersection$1[]): void
1690
- }
1691
- type EventProps<P> = P extends RaycastableRepresentation ? Partial<EventHandlers> : {}
1692
-
1693
- /**
1694
- * Props for geometry transform methods that can be called with `once()`.
1695
- * These methods modify the geometry in-place and only make sense to call once on mount.
1696
- *
1697
- * @example
1698
- * import { once } from '@react-three/fiber'
1699
- *
1700
- * <boxGeometry args={[1, 1, 1]} rotateX={once(Math.PI / 2)} />
1701
- * <planeGeometry args={[10, 10]} translate={once(0, 0, 5)} />
1702
- * <bufferGeometry applyMatrix4={once(matrix)} center={once()} />
1703
- */
1704
- interface GeometryTransformProps {
1705
- /** Rotate the geometry about the X axis (radians). Use with once(). */
1706
- rotateX?: number
1707
- /** Rotate the geometry about the Y axis (radians). Use with once(). */
1708
- rotateY?: number
1709
- /** Rotate the geometry about the Z axis (radians). Use with once(). */
1710
- rotateZ?: number
1711
- /** Translate the geometry (x, y, z). Use with once(). */
1712
- translate?: [x: number, y: number, z: number]
1713
- /** Scale the geometry (x, y, z). Use with once(). */
1714
- scale?: [x: number, y: number, z: number]
1715
- /** Center the geometry based on bounding box. Use with once(). */
1716
- center?: true
1717
- /** Apply a Matrix4 transformation. Use with once(). */
1718
- applyMatrix4?: Matrix4$1
1719
- /** Apply a Quaternion rotation. Use with once(). */
1720
- applyQuaternion?: Quaternion$1
1721
- }
1722
-
1723
- type GeometryProps<P> = P extends BufferGeometry ? GeometryTransformProps : {}
1724
-
1725
- /**
1726
- * Workaround for @types/three TSL node type issues.
1727
- * The Node base class has properties that subclasses (OperatorNode, ConstNode, etc.) don't inherit.
1728
- * This transforms `Node | null` properties to accept any object with node-like shape.
1729
- */
1730
- type TSLNodeInput = { nodeType?: string | null; uuid?: string } | null
1731
-
1732
- /**
1733
- * For node material properties (colorNode, positionNode, etc.), accept broader types
1734
- * since @types/three has broken inheritance for TSL node subclasses.
1735
- */
1736
- type NodeProps<P> = {
1737
- [K in keyof P as P[K] extends Node$1 | null ? K : never]?: TSLNodeInput
1738
- }
1739
-
1740
- interface ReactProps<P> {
1741
- children?: React.ReactNode
1742
- ref?: React.Ref<P>
1743
- key?: React.Key
1744
- }
1745
-
1746
- type ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = Partial<
1747
- Overwrite<P, MathProps<P> & ReactProps<P> & EventProps<P> & GeometryProps<P> & NodeProps<P>>
1748
- >
1749
-
1750
- type ThreeElement<T extends ConstructorRepresentation> = Mutable<
1751
- Overwrite<ElementProps<T>, Omit<InstanceProps<InstanceType<T>, T>, 'object'>>
1752
- >
1753
-
1754
- type ThreeToJSXElements<T extends Record<string, any>> = {
1755
- [K in keyof T & string as Uncapitalize<K>]: T[K] extends ConstructorRepresentation ? ThreeElement<T[K]> : never
1756
- }
1757
-
1758
- type ThreeExports = typeof THREE
1759
- type ThreeElementsImpl = ThreeToJSXElements<ThreeExports>
1760
-
1761
- interface ThreeElements extends Omit<ThreeElementsImpl, 'audio' | 'source' | 'line' | 'path'> {
1762
- primitive: Omit<ThreeElement<any>, 'args'> & { object: object }
1763
- // Conflicts with DOM types can be accessed through a three* prefix
1764
- threeAudio: ThreeElementsImpl['audio']
1765
- threeSource: ThreeElementsImpl['source']
1766
- threeLine: ThreeElementsImpl['line']
1767
- threePath: ThreeElementsImpl['path']
1768
- }
1769
-
1770
- declare module 'react' {
1771
- namespace JSX {
1772
- interface IntrinsicElements extends ThreeElements {}
1773
- }
1774
- }
1775
-
1776
- declare module 'react/jsx-runtime' {
1777
- namespace JSX {
1778
- interface IntrinsicElements extends ThreeElements {}
1779
- }
1780
- }
1781
-
1782
- declare module 'react/jsx-dev-runtime' {
1783
- namespace JSX {
1784
- interface IntrinsicElements extends ThreeElements {}
1785
- }
1782
+ declare module 'react/jsx-dev-runtime' {
1783
+ namespace JSX {
1784
+ interface IntrinsicElements extends ThreeElements {}
1785
+ }
1786
1786
  }
1787
1787
 
1788
1788
  type three_d_Color = Color;
@@ -1892,7 +1892,7 @@ type EnvironmentLoaderProps = {
1892
1892
  * const texture = useEnvironment({ preset: 'sunset' })
1893
1893
  * ```
1894
1894
  */
1895
- declare function useEnvironment({ files, path, preset, colorSpace, extensions, }?: Partial<EnvironmentLoaderProps>): Texture$1<unknown> | CubeTexture;
1895
+ declare function useEnvironment({ files, path, preset, colorSpace, extensions, }?: Partial<EnvironmentLoaderProps>): Texture$1<unknown, THREE$1.TextureEventMap> | CubeTexture<unknown>;
1896
1896
  declare namespace useEnvironment {
1897
1897
  var preload: (preloadOptions?: EnvironmentLoaderPreloadOptions) => void;
1898
1898
  var clear: (clearOptions?: EnvironmentLoaderClearOptions) => void;