@react-three/fiber 10.0.0-alpha.2 → 10.0.0-canary.1b98c17

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.cts CHANGED
@@ -1,13 +1,15 @@
1
1
  import * as THREE$1 from 'three';
2
- import { WebGLRenderTarget, Color as Color$1, ColorRepresentation, RenderTargetOptions as RenderTargetOptions$1, Euler as Euler$1, Layers as Layers$1, Raycaster, Intersection as Intersection$1, Vector2 as Vector2$1, Vector3 as Vector3$1, Vector4 as Vector4$1, Quaternion as Quaternion$1, Matrix3 as Matrix3$1, Matrix4 as Matrix4$1, Object3D, Texture as Texture$1, Frustum, OrthographicCamera } from 'three';
2
+ import { WebGLRenderTarget, Color as Color$1, ColorRepresentation, Euler as Euler$1, Loader, RenderTargetOptions as RenderTargetOptions$1, Layers as Layers$1, Raycaster, Intersection as Intersection$1, BufferGeometry, Matrix4 as Matrix4$1, Quaternion as Quaternion$1, Node as Node$1, Vector2 as Vector2$1, Vector3 as Vector3$1, Vector4 as Vector4$1, Matrix3 as Matrix3$1, ColorSpace, Texture as Texture$1, CubeTexture, Scene, Object3D, Frustum, OrthographicCamera } from 'three';
3
3
  import * as React$1 from 'react';
4
4
  import { ReactNode, Component, RefObject, JSX } from 'react';
5
+ import * as three_webgpu from 'three/webgpu';
6
+ import { WebGPURenderer as WebGPURenderer$1, Node, StorageTexture, Data3DTexture, CanvasTarget, ShaderNodeObject } from 'three/webgpu';
5
7
  import { StoreApi } from 'zustand';
6
8
  import { UseBoundStoreWithEqualityFn } from 'zustand/traditional';
7
- import * as three_webgpu from 'three/webgpu';
8
- import { Node, ShaderNodeObject } from 'three/webgpu';
9
9
  import { Options } from 'react-use-measure';
10
10
  import * as react_jsx_runtime from 'react/jsx-runtime';
11
+ import { ThreeElement as ThreeElement$1, Euler as Euler$2 } from '@react-three/fiber';
12
+ import { GroundedSkybox } from 'three/examples/jsm/objects/GroundedSkybox.js';
11
13
 
12
14
  function _mergeNamespaces(n, m) {
13
15
  m.forEach(function (e) {
@@ -54,1282 +56,1741 @@ var THREE = /*#__PURE__*/_mergeNamespaces({
54
56
  WebGPURenderer: WebGPURenderer
55
57
  }, [THREE$1]);
56
58
 
57
- //* Utility Types ==============================
58
-
59
- type NonFunctionKeys<P> = { [K in keyof P]-?: P[K] extends Function ? never : K }[keyof P]
60
- type Overwrite<P, O> = Omit<P, NonFunctionKeys<O>> & O
61
- type Properties<T> = Pick<T, NonFunctionKeys<T>>
62
- type Mutable<P> = { [K in keyof P]: P[K] | Readonly<P[K]> }
63
- type IsOptional<T> = undefined extends T ? true : false
64
- type IsAllOptional<T extends any[]> = T extends [infer First, ...infer Rest]
65
- ? IsOptional<First> extends true
66
- ? IsAllOptional<Rest>
67
- : false
68
- : true
69
-
70
- //* Camera Types ==============================
71
-
72
- type ThreeCamera = (THREE$1.OrthographicCamera | THREE$1.PerspectiveCamera) & { manual?: boolean }
73
-
74
- //* Act Type ==============================
75
-
76
- type Act = <T = any>(cb: () => Promise<T>) => Promise<T>
77
-
78
- //* Bridge & Block Types ==============================
79
-
80
- type Bridge = React$1.FC<{ children?: React$1.ReactNode }>
81
-
82
- type SetBlock = false | Promise<null> | null
83
- type UnblockProps = { set: React$1.Dispatch<React$1.SetStateAction<SetBlock>>; children: React$1.ReactNode }
84
-
85
- //* Object Map Type ==============================
86
-
87
- interface ObjectMap {
88
- nodes: { [name: string]: THREE$1.Object3D }
89
- materials: { [name: string]: THREE$1.Material }
90
- meshes: { [name: string]: THREE$1.Mesh }
91
- }
92
-
93
- //* Equality Config ==============================
94
-
95
- interface EquConfig {
96
- /** Compare arrays by reference equality a === b (default), or by shallow equality */
97
- arrays?: 'reference' | 'shallow'
98
- /** Compare objects by reference equality a === b (default), or by shallow equality */
99
- objects?: 'reference' | 'shallow'
100
- /** If true the keys in both a and b must match 1:1 (default), if false a's keys must intersect b's */
101
- strict?: boolean
102
- }
103
-
104
- //* Disposable Type ==============================
105
-
106
- interface Disposable {
107
- type?: string
108
- dispose?: () => void
109
- }
110
-
111
- //* Event-related Types =====================================
112
-
113
- interface Intersection extends THREE$1.Intersection {
114
- /** The event source (the object which registered the handler) */
115
- eventObject: THREE$1.Object3D
116
- }
117
-
118
- type Camera = THREE$1.OrthographicCamera | THREE$1.PerspectiveCamera
119
-
120
- interface IntersectionEvent<TSourceEvent> extends Intersection {
121
- /** The event source (the object which registered the handler) */
122
- eventObject: THREE$1.Object3D
123
- /** An array of intersections */
124
- intersections: Intersection[]
125
- /** vec3.set(pointer.x, pointer.y, 0).unproject(camera) */
126
- unprojectedPoint: THREE$1.Vector3
127
- /** Normalized event coordinates */
128
- pointer: THREE$1.Vector2
129
- /** Delta between first click and this event */
130
- delta: number
131
- /** The ray that pierced it */
132
- ray: THREE$1.Ray
133
- /** The camera that was used by the raycaster */
134
- camera: Camera
135
- /** stopPropagation will stop underlying handlers from firing */
136
- stopPropagation: () => void
137
- /** The original host event */
138
- nativeEvent: TSourceEvent
139
- /** If the event was stopped by calling stopPropagation */
140
- stopped: boolean
141
- }
142
-
143
- type ThreeEvent<TEvent> = IntersectionEvent<TEvent> & Properties<TEvent>
144
- type DomEvent = PointerEvent | MouseEvent | WheelEvent
145
-
146
- /** DOM event handlers registered on the canvas element */
147
- interface Events {
148
- onClick: EventListener
149
- onContextMenu: EventListener
150
- onDoubleClick: EventListener
151
- onWheel: EventListener
152
- onPointerDown: EventListener
153
- onPointerUp: EventListener
154
- onPointerLeave: EventListener
155
- onPointerMove: EventListener
156
- onPointerCancel: EventListener
157
- onLostPointerCapture: EventListener
158
- onDragEnter: EventListener
159
- onDragLeave: EventListener
160
- onDragOver: EventListener
161
- onDrop: EventListener
162
- }
163
-
164
- /** Event handlers that can be attached to R3F objects (meshes, groups, etc.) */
165
- interface EventHandlers {
166
- onClick?: (event: ThreeEvent<MouseEvent>) => void
167
- onContextMenu?: (event: ThreeEvent<MouseEvent>) => void
168
- onDoubleClick?: (event: ThreeEvent<MouseEvent>) => void
169
- /** Fires continuously while dragging over the object */
170
- onDragOver?: (event: ThreeEvent<DragEvent>) => void
171
- /** Fires once when drag enters the object */
172
- onDragOverEnter?: (event: ThreeEvent<DragEvent>) => void
173
- /** Fires once when drag leaves the object */
174
- onDragOverLeave?: (event: ThreeEvent<DragEvent>) => void
175
- /** Fires when drag misses this object (for objects that have drag handlers) */
176
- onDragOverMissed?: (event: DragEvent) => void
177
- /** Fires when a drop occurs on this object */
178
- onDrop?: (event: ThreeEvent<DragEvent>) => void
179
- /** Fires when a drop misses this object (for objects that have drop handlers) */
180
- onDropMissed?: (event: DragEvent) => void
181
- onPointerUp?: (event: ThreeEvent<PointerEvent>) => void
182
- onPointerDown?: (event: ThreeEvent<PointerEvent>) => void
183
- onPointerOver?: (event: ThreeEvent<PointerEvent>) => void
184
- onPointerOut?: (event: ThreeEvent<PointerEvent>) => void
185
- onPointerEnter?: (event: ThreeEvent<PointerEvent>) => void
186
- onPointerLeave?: (event: ThreeEvent<PointerEvent>) => void
187
- onPointerMove?: (event: ThreeEvent<PointerEvent>) => void
188
- onPointerMissed?: (event: MouseEvent) => void
189
- onPointerCancel?: (event: ThreeEvent<PointerEvent>) => void
190
- onWheel?: (event: ThreeEvent<WheelEvent>) => void
191
- onLostPointerCapture?: (event: ThreeEvent<PointerEvent>) => void
192
-
193
- //* Visibility Events --------------------------------
194
- /** Fires when object enters/exits camera frustum. Receives true when in view, false when out. */
195
- onFramed?: (inView: boolean) => void
196
- /** Fires when object occlusion state changes (WebGPU only, requires occlusionTest=true on object) */
197
- onOccluded?: (occluded: boolean) => void
198
- /** Fires when combined visibility changes (frustum + occlusion + visible prop) */
199
- onVisible?: (visible: boolean) => void
200
- }
201
-
202
- type FilterFunction = (items: THREE$1.Intersection[], state: RootState) => THREE$1.Intersection[]
203
- type ComputeFunction = (event: DomEvent, root: RootState, previous?: RootState) => void
204
-
205
- interface EventManager<TTarget> {
206
- /** Determines if the event layer is active */
207
- enabled: boolean
208
- /** Event layer priority, higher prioritized layers come first and may stop(-propagate) lower layer */
209
- priority: number
210
- /** The compute function needs to set up the raycaster and an xy- pointer */
211
- compute?: ComputeFunction
212
- /** The filter can re-order or re-structure the intersections */
213
- filter?: FilterFunction
214
- /** The target node the event layer is tied to */
215
- connected?: TTarget
216
- /** All the pointer event handlers through which the host forwards native events */
217
- handlers?: Events
218
- /** Allows re-connecting to another target */
219
- connect?: (target: TTarget) => void
220
- /** Removes all existing events handlers from the target */
221
- disconnect?: () => void
222
- /** Triggers a onPointerMove with the last known event. This can be useful to enable raycasting without
223
- * explicit user interaction, for instance when the camera moves a hoverable object underneath the cursor.
224
- */
225
- update?: () => void
226
- }
227
-
228
- interface PointerCaptureTarget {
229
- intersection: Intersection
230
- target: Element
231
- }
232
-
233
- //* Visibility System Types =====================================
234
-
235
- /** Entry in the visibility registry for tracking object visibility state */
236
- interface VisibilityEntry {
237
- object: THREE$1.Object3D
238
- handlers: Pick<EventHandlers, 'onFramed' | 'onOccluded' | 'onVisible'>
239
- lastFramedState: boolean | null
240
- lastOccludedState: boolean | null
241
- lastVisibleState: boolean | null
242
- }
243
-
244
- //* Scheduler Types (useFrame) ==============================
245
-
246
-
247
-
248
- // Public Options --------------------------------
249
-
250
- /**
251
- * Options for useFrame hook
252
- */
253
- interface UseFrameNextOptions {
254
- /** Optional stable id for the job. Auto-generated if not provided */
255
- id?: string
256
- /** Named phase to run in. Default: 'update' */
257
- phase?: string
258
- /** Run before this phase or job id */
259
- before?: string | string[]
260
- /** Run after this phase or job id */
261
- after?: string | string[]
262
- /** Priority within phase. Higher runs first. Default: 0 */
263
- priority?: number
264
- /** Max frames per second for this job */
265
- fps?: number
266
- /** If true, skip frames when behind. If false, try to catch up. Default: true */
267
- drop?: boolean
268
- /** Enable/disable without unregistering. Default: true */
269
- enabled?: boolean
270
- }
271
-
272
- /** Alias for UseFrameNextOptions */
273
- type UseFrameOptions = UseFrameNextOptions
274
-
275
- /**
276
- * Options for addPhase
277
- */
278
- interface AddPhaseOptions {
279
- /** Insert this phase before the specified phase */
280
- before?: string
281
- /** Insert this phase after the specified phase */
282
- after?: string
283
- }
284
-
285
- // Frame State --------------------------------
286
-
287
- /**
288
- * Timing-only state for independent/outside mode (no RootState)
289
- */
290
- interface FrameTimingState {
291
- /** High-resolution timestamp from RAF (ms) */
292
- time: number
293
- /** Time since last frame in seconds (for legacy compatibility with THREE.Clock) */
294
- delta: number
295
- /** Elapsed time since first frame in seconds (for legacy compatibility with THREE.Clock) */
296
- elapsed: number
297
- /** Incrementing frame counter */
298
- frame: number
299
- }
300
-
301
- /**
302
- * State passed to useFrame callbacks (extends RootState with timing)
303
- */
304
- interface FrameNextState extends RootState, FrameTimingState {}
305
-
306
- /** Alias for FrameNextState */
307
- type FrameState = FrameNextState
308
-
309
- // Root Options --------------------------------
310
-
311
- /**
312
- * Options for registerRoot
313
- */
314
- interface RootOptions {
315
- /** State provider for callbacks. Optional in independent mode. */
316
- getState?: () => any
317
- /** Error handler for job errors. Falls back to console.error if not provided. */
318
- onError?: (error: Error) => void
319
- }
320
-
321
- // Callback Types --------------------------------
322
-
323
- /**
324
- * Callback function for useFrame
325
- */
326
- type FrameNextCallback = (state: FrameNextState, delta: number) => void
327
-
328
- /** Alias for FrameNextCallback */
329
- type FrameCallback = FrameNextCallback
330
-
331
- // Controls returned from useFrame --------------------------------
332
-
333
- /**
334
- * Controls object returned from useFrame hook
335
- */
336
- interface FrameNextControls {
337
- /** The job's unique ID */
338
- id: string
339
- /** Access to the global scheduler for frame loop control */
340
- scheduler: SchedulerApi
341
- /** Manually step this job only (bypasses FPS limiting) */
342
- step(timestamp?: number): void
343
- /** Manually step ALL jobs in the scheduler */
344
- stepAll(timestamp?: number): void
345
- /** Pause this job (set enabled=false) */
346
- pause(): void
347
- /** Resume this job (set enabled=true) */
348
- resume(): void
349
- /** Reactive paused state - automatically triggers re-render when changed */
350
- isPaused: boolean
351
- }
352
-
353
- /** Alias for FrameNextControls */
354
- type FrameControls = FrameNextControls
355
-
356
- // Scheduler Interface --------------------------------
357
-
358
- /**
359
- * Public interface for the global Scheduler
360
- */
361
- interface SchedulerApi {
362
- //* Phase Management --------------------------------
363
-
364
- /** Add a named phase to the scheduler */
365
- addPhase(name: string, options?: AddPhaseOptions): void
366
- /** Get the ordered list of phase names */
367
- readonly phases: string[]
368
- /** Check if a phase exists */
369
- hasPhase(name: string): boolean
370
-
371
- //* Root Management --------------------------------
372
-
373
- /** Register a root (Canvas) with the scheduler. Returns unsubscribe function. */
374
- registerRoot(id: string, options?: RootOptions): () => void
375
- /** Unregister a root */
376
- unregisterRoot(id: string): void
377
- /** Generate a unique root ID */
378
- generateRootId(): string
379
- /** Get the number of registered roots */
380
- getRootCount(): number
381
- /** Check if any root is registered and ready */
382
- readonly isReady: boolean
383
- /** Subscribe to root-ready event. Fires immediately if already ready. Returns unsubscribe. */
384
- onRootReady(callback: () => void): () => void
385
-
386
- //* Job Registration --------------------------------
387
-
388
- /** Register a job with the scheduler (returns unsubscribe function) */
389
- register(
390
- callback: FrameNextCallback,
391
- options?: {
392
- id?: string
393
- rootId?: string
394
- phase?: string
395
- before?: string | string[]
396
- after?: string | string[]
397
- priority?: number
398
- fps?: number
399
- drop?: boolean
400
- enabled?: boolean
401
- },
402
- ): () => void
403
- /** Update a job's options */
404
- updateJob(
405
- id: string,
406
- options: {
407
- priority?: number
408
- fps?: number
409
- drop?: boolean
410
- enabled?: boolean
411
- phase?: string
412
- before?: string | string[]
413
- after?: string | string[]
414
- },
415
- ): void
416
- /** Unregister a job by ID */
417
- unregister(id: string, rootId?: string): void
418
- /** Get the number of registered jobs */
419
- getJobCount(): number
420
- /** Get all job IDs */
421
- getJobIds(): string[]
422
-
423
- //* Global Jobs (for legacy addEffect/addAfterEffect) --------------------------------
424
-
425
- /** Register a global job (runs once per frame, not per-root). Returns unsubscribe function. */
426
- registerGlobal(phase: 'before' | 'after', id: string, callback: (timestamp: number) => void): () => void
427
-
428
- //* Idle Callbacks (for legacy addTail) --------------------------------
429
-
430
- /** Register an idle callback (fires when loop stops). Returns unsubscribe function. */
431
- onIdle(callback: (timestamp: number) => void): () => void
432
-
433
- //* Frame Loop Control --------------------------------
434
-
435
- /** Start the scheduler loop */
436
- start(): void
437
- /** Stop the scheduler loop */
438
- stop(): void
439
- /** Check if the scheduler is running */
440
- readonly isRunning: boolean
441
- /** Get/set the frameloop mode ('always', 'demand', 'never') */
442
- frameloop: Frameloop
443
- /** Independent mode - runs without Canvas, callbacks receive timing-only state */
444
- independent: boolean
445
-
446
- //* Manual Stepping --------------------------------
447
-
448
- /** Manually step all jobs once (for frameloop='never' or testing) */
449
- step(timestamp?: number): void
450
- /** Manually step a single job by ID */
451
- stepJob(id: string, timestamp?: number): void
452
- /** Request frame(s) to be rendered (for frameloop='demand') */
453
- invalidate(frames?: number): void
454
-
455
- //* Per-Job Control --------------------------------
456
-
457
- /** Check if a job is paused */
458
- isJobPaused(id: string): boolean
459
- /** Pause a job */
460
- pauseJob(id: string): void
461
- /** Resume a job */
462
- resumeJob(id: string): void
463
- /** Subscribe to job state changes (for reactive isPaused). Returns unsubscribe function. */
464
- subscribeJobState(id: string, listener: () => void): () => void
465
- }
466
-
467
- //* Core Store Types ========================================
468
-
469
- type Subscription = {
470
- ref: React$1.RefObject<RenderCallback>
471
- priority: number
472
- store: RootStore
473
- }
474
-
475
- type Dpr = number | [min: number, max: number]
476
-
477
- interface Size {
478
- width: number
479
- height: number
480
- top: number
481
- left: number
482
- }
483
-
484
- type Frameloop = 'always' | 'demand' | 'never'
485
-
486
- interface Viewport extends Size {
487
- /** The initial pixel ratio */
488
- initialDpr: number
489
- /** Current pixel ratio */
490
- dpr: number
491
- /** size.width / viewport.width */
492
- factor: number
493
- /** Camera distance */
494
- distance: number
495
- /** Camera aspect ratio: width / height */
496
- aspect: number
497
- }
498
-
499
- type RenderCallback = (state: RootState, delta: number, frame?: XRFrame) => void
500
-
501
- interface Performance {
502
- /** Current performance normal, between min and max */
503
- current: number
504
- /** How low the performance can go, between 0 and max */
505
- min: number
506
- /** How high the performance can go, between min and max */
507
- max: number
508
- /** Time until current returns to max in ms */
509
- debounce: number
510
- /** Sets current to min, puts the system in regression */
511
- regress: () => void
512
- }
513
-
514
- interface InternalState {
515
- interaction: THREE$1.Object3D[]
516
- hovered: Map<string, ThreeEvent<DomEvent>>
517
- subscribers: Subscription[]
518
- capturedMap: Map<number, Map<THREE$1.Object3D, PointerCaptureTarget>>
519
- initialClick: [x: number, y: number]
520
- initialHits: THREE$1.Object3D[]
521
- lastEvent: React$1.RefObject<DomEvent | null>
522
- /** Visibility event registry (onFramed, onOccluded, onVisible) */
523
- visibilityRegistry: Map<string, VisibilityEntry>
524
- /** Whether occlusion queries are enabled (WebGPU only) */
525
- occlusionEnabled: boolean
526
- /** Reference to the invisible occlusion observer mesh */
527
- occlusionObserver: THREE$1.Mesh | null
528
- /** Cached occlusion results from render pass - keyed by Object3D */
529
- occlusionCache: Map<THREE$1.Object3D, boolean | null>
530
- /** Internal helper group for R3F system objects (occlusion observer, etc.) */
531
- helperGroup: THREE$1.Group | null
532
- active: boolean
533
- priority: number
534
- frames: number
535
- subscribe: (callback: React$1.RefObject<RenderCallback>, priority: number, store: RootStore) => () => void
536
- /** Internal renderer storage - use state.renderer or state.gl to access */
537
- actualRenderer: THREE$1.WebGLRenderer | any // WebGPURenderer when available
538
- /** Global scheduler reference (for useFrame hook) */
539
- scheduler: SchedulerApi | null
540
- /** This root's unique ID in the global scheduler */
541
- rootId?: string
542
- /** Function to unregister this root from the global scheduler */
543
- unregisterRoot?: () => void
544
- /** Container for child attachment (scene for root, original container for portals) */
545
- container?: THREE$1.Object3D
546
- }
547
-
548
- interface XRManager {
549
- connect: () => void
550
- disconnect: () => void
551
- }
552
-
553
- //* Root State Interface ====================================
554
-
555
- interface RootState {
556
- /** Set current state */
557
- set: StoreApi<RootState>['setState']
558
- /** Get current state */
559
- get: StoreApi<RootState>['getState']
560
- /** (deprecated) The instance of the WebGLrenderer */
561
- gl: THREE$1.WebGLRenderer
562
- /** The instance of the WebGPU renderer, the fallback, OR the default renderer as a mask of gl */
563
- renderer: THREE$1.WebGLRenderer | any // WebGPURenderer when available
564
- /** Inspector of the webGPU Renderer. Init in the canvas */
565
- inspector: any // Inspector type from three/webgpu
566
-
567
- /** Default camera */
568
- camera: ThreeCamera
569
- /** Camera frustum for visibility checks - auto-updated each frame when autoUpdateFrustum is true */
570
- frustum: THREE$1.Frustum
571
- /** Whether to automatically update the frustum each frame (default: true) */
572
- autoUpdateFrustum: boolean
573
- /** Default scene (may be overridden in portals to point to the portal container) */
574
- scene: THREE$1.Scene
575
- /** The actual root THREE.Scene - always points to the true scene, even inside portals */
576
- rootScene: THREE$1.Scene
577
- /** Default raycaster */
578
- raycaster: THREE$1.Raycaster
579
- /** Event layer interface, contains the event handler and the node they're connected to */
580
- events: EventManager<any>
581
- /** XR interface */
582
- xr: XRManager
583
- /** Currently used controls */
584
- controls: THREE$1.EventDispatcher | null
585
- /** Normalized event coordinates */
586
- pointer: THREE$1.Vector2
587
- /** @deprecated Normalized event coordinates, use "pointer" instead! */
588
- mouse: THREE$1.Vector2
589
- /* Whether to enable r139's THREE.ColorManagement */
590
- legacy: boolean
591
- /** Shortcut to gl.outputColorSpace = THREE.LinearSRGBColorSpace */
592
- linear: boolean
593
- /** Shortcut to gl.toneMapping = NoTonemapping */
594
- flat: boolean
595
- /** Color space assigned to 8-bit input textures (color maps). Most textures are authored in sRGB. */
596
- textureColorSpace: THREE$1.ColorSpace
597
- /** Render loop flags */
598
- frameloop: Frameloop
599
- performance: Performance
600
- /** Reactive pixel-size of the canvas */
601
- size: Size
602
- /** Reactive size of the viewport in threejs units */
603
- viewport: Viewport & {
604
- getCurrentViewport: (
605
- camera?: ThreeCamera,
606
- target?: THREE$1.Vector3 | Parameters<THREE$1.Vector3['set']>,
607
- size?: Size,
608
- ) => Omit<Viewport, 'dpr' | 'initialDpr'>
609
- }
610
- /** Flags the canvas for render, but doesn't render in itself */
611
- invalidate: (frames?: number, stackFrames?: boolean) => void
612
- /** Advance (render) one step */
613
- advance: (timestamp: number, runGlobalEffects?: boolean) => void
614
- /** Shortcut to setting the event layer */
615
- setEvents: (events: Partial<EventManager<any>>) => void
616
- /** Shortcut to manual sizing. No args resets to props/container. Single arg creates square. */
617
- setSize: (width?: number, height?: number, top?: number, left?: number) => void
618
- /** Shortcut to manual setting the pixel ratio */
619
- setDpr: (dpr: Dpr) => void
620
- /** Shortcut to setting frameloop flags */
621
- setFrameloop: (frameloop: Frameloop) => void
622
- /** Set error state to propagate to error boundary */
623
- setError: (error: Error | null) => void
624
- /** Current error state (null when no error) */
625
- error: Error | null
626
- /** Global TSL uniform nodes - root-level uniforms + scoped sub-objects. Use useUniforms() hook */
627
- uniforms: UniformStore
628
- /** Global TSL nodes - root-level nodes + scoped sub-objects. Use useNodes() hook */
629
- nodes: Record<string, any>
630
- /** Global TSL texture nodes - use useTextures() hook for operations */
631
- textures: Map<string, any>
632
- /** WebGPU PostProcessing instance - use usePostProcessing() hook */
633
- postProcessing: any | null // THREE.PostProcessing when available
634
- /** Global TSL pass nodes for post-processing - use usePostProcessing() hook */
635
- passes: Record<string, any>
636
- /** Internal version counter for HMR - incremented by rebuildNodes/rebuildUniforms to bust memoization */
637
- _hmrVersion: number
638
- /** Internal: whether setSize() has taken ownership of canvas dimensions */
639
- _sizeImperative: boolean
640
- /** Internal: stored size props from Canvas for reset functionality */
641
- _sizeProps: { width?: number; height?: number } | null
642
- /** When the canvas was clicked but nothing was hit */
643
- onPointerMissed?: (event: MouseEvent) => void
644
- /** When a dragover event has missed any target */
645
- onDragOverMissed?: (event: DragEvent) => void
646
- /** When a drop event has missed any target */
647
- onDropMissed?: (event: DragEvent) => void
648
- /** If this state model is layered (via createPortal) then this contains the previous layer */
649
- previousRoot?: RootStore
650
- /** Internals */
651
- internal: InternalState
652
- // flags for triggers
653
- // if we are using the webGl renderer, this will be true
654
- isLegacy: boolean
655
- // regardless of renderer, if the system supports webGpu, this will be true
656
- webGPUSupported: boolean
657
- //if we are on native
658
- isNative: boolean
659
- }
660
-
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
+ }
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
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
832
+ }
833
+
661
834
  type RootStore = UseBoundStoreWithEqualityFn<StoreApi<RootState>>
662
835
 
663
- //* Base Renderer Types =====================================
664
-
665
- // Shim for OffscreenCanvas since it was removed from DOM types
666
- interface OffscreenCanvas$1 extends EventTarget {}
667
-
668
- interface BaseRendererProps {
669
- canvas: HTMLCanvasElement | OffscreenCanvas$1
670
- powerPreference?: 'high-performance' | 'low-power' | 'default'
671
- antialias?: boolean
672
- alpha?: boolean
673
- }
674
-
675
- type RendererFactory<TRenderer, TParams> =
676
- | TRenderer
677
- | ((defaultProps: TParams) => TRenderer)
678
- | ((defaultProps: TParams) => Promise<TRenderer>)
679
-
680
- interface Renderer {
681
- render: (scene: THREE$1.Scene, camera: THREE$1.Camera) => any
682
- }
683
-
684
- //* WebGL Renderer Props ==============================
685
-
686
- type DefaultGLProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & {
687
- canvas: HTMLCanvasElement | OffscreenCanvas$1
688
- }
689
-
690
- type GLProps =
691
- | Renderer
692
- | ((defaultProps: DefaultGLProps) => Renderer)
693
- | ((defaultProps: DefaultGLProps) => Promise<Renderer>)
694
- | Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters>
695
-
696
- //* WebGPU Renderer Props ==============================
697
-
698
- type DefaultRendererProps = {
699
- canvas: HTMLCanvasElement | OffscreenCanvas$1
700
- [key: string]: any
701
- }
702
-
703
- type RendererProps =
704
- | any // WebGPURenderer
705
- | ((defaultProps: DefaultRendererProps) => any)
706
- | ((defaultProps: DefaultRendererProps) => Promise<any>)
707
- | Partial<Properties<any> | Record<string, any>>
708
-
709
- //* Camera Props ==============================
710
-
711
- type CameraProps = (
712
- | THREE$1.Camera
713
- | Partial<
714
- ThreeElement<typeof THREE$1.Camera> &
715
- ThreeElement<typeof THREE$1.PerspectiveCamera> &
716
- ThreeElement<typeof THREE$1.OrthographicCamera>
717
- >
718
- ) & {
719
- /** Flags the camera as manual, putting projection into your own hands */
720
- manual?: boolean
721
- }
722
-
723
- //* Render Props ==============================
724
-
725
- interface RenderProps<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
726
- /** A threejs renderer instance or props that go into the default renderer */
727
- gl?: GLProps
728
- /** A WebGPU renderer instance or props that go into the default renderer */
729
- renderer?: RendererProps
730
- /** Dimensions to fit the renderer to. Will measure canvas dimensions if omitted */
731
- size?: Size
732
- /**
733
- * Enables shadows (by default PCFsoft). Can accept `gl.shadowMap` options for fine-tuning,
734
- * but also strings: 'basic' | 'percentage' | 'soft' | 'variance'.
735
- * @see https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
736
- */
737
- shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
738
- /**
739
- * Disables three r139 color management.
740
- * @see https://threejs.org/docs/#manual/en/introduction/Color-management
741
- */
742
- legacy?: boolean
743
- /** Switch off automatic sRGB encoding and gamma correction */
744
- linear?: boolean
745
- /** Use `THREE.NoToneMapping` instead of `THREE.ACESFilmicToneMapping` */
746
- flat?: boolean
747
- /** Working color space for automatic texture colorspace assignment. Defaults to THREE.SRGBColorSpace */
748
- /** Color space assigned to 8-bit input textures (color maps). Defaults to sRGB. Most textures are authored in sRGB. */
749
- textureColorSpace?: THREE$1.ColorSpace
750
- /** Creates an orthographic camera */
751
- orthographic?: boolean
752
- /**
753
- * R3F's render mode. Set to `demand` to only render on state change or `never` to take control.
754
- * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#on-demand-rendering
755
- */
756
- frameloop?: Frameloop
757
- /**
758
- * R3F performance options for adaptive performance.
759
- * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#movement-regression
760
- */
761
- performance?: Partial<Omit<Performance, 'regress'>>
762
- /** Target pixel ratio. Can clamp between a range: `[min, max]` */
763
- dpr?: Dpr
764
- /** Props that go into the default raycaster */
765
- raycaster?: Partial<THREE$1.Raycaster>
766
- /** A `THREE.Scene` instance or props that go into the default scene */
767
- scene?: THREE$1.Scene | Partial<THREE$1.Scene>
768
- /** A `THREE.Camera` instance or props that go into the default camera */
769
- camera?: CameraProps
770
- /** An R3F event manager to manage elements' pointer events */
771
- events?: (store: RootStore) => EventManager<HTMLElement>
772
- /** Callback after the canvas has rendered (but not yet committed) */
773
- onCreated?: (state: RootState) => void
774
- /** Response for pointer clicks that have missed any target */
775
- onPointerMissed?: (event: MouseEvent) => void
776
- /** Response for dragover events that have missed any target */
777
- onDragOverMissed?: (event: DragEvent) => void
778
- /** Response for drop events that have missed any target */
779
- onDropMissed?: (event: DragEvent) => void
780
- /** Whether to automatically update the frustum each frame (default: true) */
781
- autoUpdateFrustum?: boolean
782
- /**
783
- * Enable WebGPU occlusion queries for onOccluded/onVisible events.
784
- * Auto-enabled when any object uses onOccluded or onVisible handlers.
785
- * Only works with WebGPU renderer - WebGL will log a warning.
786
- */
787
- occlusion?: boolean
788
- /** Internal: stored size props from Canvas for reset functionality */
789
- _sizeProps?: { width?: number; height?: number } | null
790
- }
791
-
792
- //* Reconciler Root ==============================
793
-
794
- interface ReconcilerRoot<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
795
- configure: (config?: RenderProps<TCanvas>) => Promise<ReconcilerRoot<TCanvas>>
796
- render: (element: ReactNode) => RootStore
797
- unmount: () => void
798
- }
799
-
800
- //* Inject State ==============================
801
-
802
- type InjectState = Partial<
803
- Omit<RootState, 'events'> & {
804
- events?: {
805
- enabled?: boolean
806
- priority?: number
807
- compute?: ComputeFunction
808
- connected?: any
809
- }
810
- /**
811
- * When true (default), injects a THREE.Scene between container and children if container isn't already a Scene.
812
- * This ensures state.scene is always a real THREE.Scene with proper properties (background, environment, fog).
813
- * Set to false to use the container directly as scene (anti-pattern, but supported for edge cases).
814
- */
815
- injectScene?: boolean
816
- }
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
+ }
817
1043
  >
818
1044
 
819
- //* Reconciler Types ==============================
820
-
821
- // FiberRoot is an opaque internal React type - we define it locally
822
- // to avoid bundling @types/react-reconciler which causes absolute path issues
823
- type FiberRoot = any
824
-
825
- interface Root {
826
- fiber: FiberRoot
827
- store: RootStore
828
- }
829
-
830
- type AttachFnType<O = any> = (parent: any, self: O) => () => void
831
- type AttachType<O = any> = string | AttachFnType<O>
832
-
833
- type ConstructorRepresentation<T = any> = new (...args: any[]) => T
834
-
835
- interface Catalogue {
836
- [name: string]: ConstructorRepresentation
837
- }
838
-
839
- // TODO: handle constructor overloads
840
- // https://github.com/pmndrs/react-three-fiber/pull/2931
841
- // https://github.com/microsoft/TypeScript/issues/37079
842
- type Args<T> = T extends ConstructorRepresentation
843
- ? T extends typeof Color$1
844
- ? [r: number, g: number, b: number] | [color: ColorRepresentation]
845
- : ConstructorParameters<T>
846
- : any[]
847
-
848
- type ArgsProp<P> = P extends ConstructorRepresentation
849
- ? IsAllOptional<ConstructorParameters<P>> extends true
850
- ? { args?: Args<P> }
851
- : { args: Args<P> }
852
- : { args: unknown[] }
853
-
854
- type InstanceProps<T = any, P = any> = ArgsProp<P> & {
855
- object?: T
856
- dispose?: null
857
- attach?: AttachType<T>
858
- onUpdate?: (self: T) => void
859
- }
860
-
861
- interface Instance<O = any> {
862
- root: RootStore
863
- type: string
864
- parent: Instance | null
865
- children: Instance[]
866
- props: InstanceProps<O> & Record<string, unknown>
867
- object: O & { __r3f?: Instance<O> }
868
- eventCount: number
869
- handlers: Partial<EventHandlers>
870
- attach?: AttachType<O>
871
- previousAttach?: any
872
- isHidden: boolean
873
- }
874
-
875
- interface HostConfig {
876
- type: string
877
- props: Instance['props']
878
- container: RootStore
879
- instance: Instance
880
- textInstance: void
881
- suspenseInstance: Instance
882
- hydratableInstance: never
883
- formInstance: never
884
- publicInstance: Instance['object']
885
- hostContext: {}
886
- childSet: never
887
- timeoutHandle: number | undefined
888
- noTimeout: -1
889
- TransitionStatus: null
890
- }
891
- declare global {
892
- var IS_REACT_ACT_ENVIRONMENT: boolean | undefined
893
- }
894
-
895
- //* Loop Types ==============================
896
-
897
- type GlobalRenderCallback = (timestamp: number) => void
898
-
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
1123
+ }
1124
+
1125
+ //* Loop Types ==============================
1126
+
1127
+ type GlobalRenderCallback = (timestamp: number) => void
1128
+
899
1129
  type GlobalEffectType = 'before' | 'after' | 'tail'
900
1130
 
901
- //* Canvas Types ==============================
902
-
903
- interface CanvasProps
904
- extends Omit<RenderProps<HTMLCanvasElement>, 'size'>, React$1.HTMLAttributes<HTMLDivElement> {
905
- children?: React$1.ReactNode
906
- ref?: React$1.Ref<HTMLCanvasElement>
907
- /** Canvas fallback content, similar to img's alt prop */
908
- fallback?: React$1.ReactNode
909
- /**
910
- * Options to pass to useMeasure.
911
- * @see https://github.com/pmndrs/react-use-measure#api
912
- */
913
- resize?: Options
914
- /** The target where events are being subscribed to, default: the div that wraps canvas */
915
- eventSource?: HTMLElement | React$1.RefObject<HTMLElement>
916
- /** The event prefix that is cast into canvas pointer x/y events, default: "offset" */
917
- eventPrefix?: 'offset' | 'client' | 'page' | 'layer' | 'screen'
918
- /** Enable/disable automatic HMR refresh for TSL nodes and uniforms, default: true in dev */
919
- hmr?: boolean
920
- /** Canvas resolution width in pixels. If omitted, uses container width. */
921
- width?: number
922
- /** Canvas resolution height in pixels. If omitted, uses container height. */
923
- height?: number
924
- }
925
-
926
- //* Loader Types ==============================
927
-
928
- type InputLike = string | string[] | string[][] | Readonly<string | string[] | string[][]>
929
-
930
- // Define a loader-like interface that matches THREE.Loader's load signature
931
- // This works for both generic and non-generic THREE.Loader instances
932
- interface LoaderLike {
933
- load(
934
- url: InputLike,
935
- onLoad?: (result: any) => void,
936
- onProgress?: (event: ProgressEvent<EventTarget>) => void,
937
- onError?: (error: unknown) => void,
938
- ): any
939
- }
940
-
941
- type GLTFLike = { scene: THREE$1.Object3D }
942
-
943
- type LoaderInstance<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
944
- T extends ConstructorRepresentation<LoaderLike> ? InstanceType<T> : T
945
-
946
- // Infer result type from the load method's callback parameter
947
- type InferLoadResult<T> = T extends {
948
- load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
949
- }
950
- ? R
951
- : T extends ConstructorRepresentation<any>
952
- ? InstanceType<T> extends {
953
- load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
954
- }
955
- ? R
956
- : any
957
- : any
958
-
959
- type LoaderResult<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
960
- InferLoadResult<LoaderInstance<T>> extends infer R ? (R extends GLTFLike ? R & ObjectMap : R) : never
961
-
962
- type Extensions<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> = (
963
- loader: LoaderInstance<T>,
1131
+ declare const presetsObj: {
1132
+ apartment: string;
1133
+ city: string;
1134
+ dawn: string;
1135
+ forest: string;
1136
+ lobby: string;
1137
+ night: string;
1138
+ park: string;
1139
+ studio: string;
1140
+ sunset: string;
1141
+ warehouse: string;
1142
+ };
1143
+ type PresetsType = keyof typeof presetsObj;
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
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>,
964
1283
  ) => void
965
1284
 
966
- type WebGLDefaultProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & BaseRendererProps
967
-
968
- type WebGLProps =
969
- | RendererFactory<THREE$1.WebGLRenderer, WebGLDefaultProps>
970
- | Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters>
971
-
972
- interface WebGLShadowConfig {
973
- shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
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
974
1305
  }
975
1306
 
976
- //* RenderTarget Types ==============================
977
-
978
-
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
+ }
1328
+
1329
+ //* RenderTarget Types ==============================
1330
+
1331
+
979
1332
  type RenderTargetOptions = RenderTargetOptions$1
980
1333
 
981
- //* Global Types ==============================
982
-
983
- declare global {
984
- /** Uniform node type - a Node with a value property (matches Three.js UniformNode) */
985
- interface UniformNode<T = unknown> extends Node {
986
- value: T
987
- }
988
-
989
- /** Flat record of uniform nodes (no nested scopes) */
990
- type UniformRecord<T extends UniformNode = UniformNode> = Record<string, T>
991
-
992
- /**
993
- * Uniform store that can contain both root-level uniforms and scoped uniform objects
994
- * Used by state.uniforms which has structure like:
995
- * { uTime: UniformNode, player: { uHealth: UniformNode }, enemy: { uHealth: UniformNode } }
996
- */
997
- type UniformStore = Record<string, UniformNode | UniformRecord>
998
-
999
- /**
1000
- * Helper to safely access a uniform node from the store.
1001
- * Use this when accessing state.uniforms to get proper typing.
1002
- * @example
1003
- * const uTime = uniforms.uTime as UniformNode<number>
1004
- * const uColor = uniforms.uColor as UniformNode<import('three/webgpu').Color>
1005
- */
1006
- type GetUniform<T = unknown> = UniformNode<T>
1007
-
1008
- /**
1009
- * Acceptable input values for useUniforms - raw values that get converted to UniformNodes
1010
- * Supports: primitives, Three.js types, plain objects (converted to vectors), and UniformNodes
1011
- */
1012
- type UniformValue =
1013
- | number
1014
- | string
1015
- | boolean
1016
- | three_webgpu.Color
1017
- | three_webgpu.Vector2
1018
- | three_webgpu.Vector3
1019
- | three_webgpu.Vector4
1020
- | three_webgpu.Matrix3
1021
- | three_webgpu.Matrix4
1022
- | three_webgpu.Euler
1023
- | three_webgpu.Quaternion
1024
- | { x: number; y?: number; z?: number; w?: number } // Plain objects converted to vectors
1025
- | UniformNode
1026
-
1027
- /** Input record for useUniforms - accepts raw values or UniformNodes */
1028
- type UniformInputRecord = Record<string, UniformValue>
1029
- }
1030
-
1031
- //* Fn Return Type ==============================
1032
-
1033
- /** The return type of Fn() - a callable shader function node */
1034
- type ShaderCallable<R extends Node = Node> = ((...params: unknown[]) => ShaderNodeObject<R>) & Node
1035
-
1036
- //* Module Augmentation ==============================
1037
-
1038
- declare module 'three/tsl' {
1039
- /**
1040
- * Fn with array parameter destructuring
1041
- * @example Fn(([uv, skew]) => { ... })
1042
- */
1043
- export function Fn<R extends Node = Node>(
1044
- jsFunc: (inputs: ShaderNodeObject<Node>[]) => ShaderNodeObject<R>,
1045
- ): ShaderCallable<R>
1046
-
1047
- /**
1048
- * Fn with object parameter destructuring
1049
- * @example Fn(({ color, intensity }) => { ... })
1050
- */
1051
- export function Fn<T extends Record<string, unknown>, R extends Node = Node>(
1052
- jsFunc: (inputs: T) => ShaderNodeObject<R>,
1053
- ): ShaderCallable<R>
1054
-
1055
- /**
1056
- * Fn with array params + layout
1057
- * @example Fn(([a, b]) => { ... }, { layout: [...] })
1058
- */
1059
- export function Fn<R extends Node = Node>(
1060
- jsFunc: (inputs: ShaderNodeObject<Node>[]) => ShaderNodeObject<R>,
1061
- layout: { layout?: unknown },
1062
- ): ShaderCallable<R>
1063
-
1064
- /**
1065
- * Fn with object params + layout
1066
- */
1067
- export function Fn<T extends Record<string, unknown>, R extends Node = Node>(
1068
- jsFunc: (inputs: T) => ShaderNodeObject<R>,
1069
- layout: { layout?: unknown },
1070
- ): ShaderCallable<R>
1071
- }
1072
-
1073
- /**
1074
- * PostProcessing Types for usePostProcessing hook (WebGPU only)
1075
- */
1076
-
1077
-
1078
-
1079
- declare global {
1080
- /** Pass record - stores TSL pass nodes for post-processing */
1081
- type PassRecord = Record<string, any>
1082
-
1083
- /** Setup callback - runs first to configure MRT, create additional passes */
1084
- type PostProcessingSetupCallback = (state: RootState) => PassRecord | void
1085
-
1086
- /** Main callback - runs second to configure outputNode, create effect passes */
1087
- type PostProcessingMainCallback = (state: RootState) => PassRecord | void
1088
-
1089
- /** Return type for usePostProcessing hook */
1090
- interface UsePostProcessingReturn {
1091
- /** Current passes from state */
1092
- passes: PassRecord
1093
- /** PostProcessing instance (null if not initialized) */
1094
- postProcessing: any | null // THREE.PostProcessing
1095
- /** Clear all passes from state */
1096
- clearPasses: () => void
1097
- /** Reset PostProcessing entirely (clears PP + passes) */
1098
- reset: () => void
1099
- /** Re-run setup/main callbacks with current closure values */
1100
- rebuild: () => void
1101
- /** True when PostProcessing is configured and ready */
1102
- isReady: boolean
1103
- }
1104
- }
1105
-
1106
- //* useFrameNext Types ==============================
1107
-
1108
-
1109
-
1110
- //* Global Type Declarations ==============================
1111
-
1112
- declare global {
1113
- // Job --------------------------------
1114
-
1115
- /**
1116
- * Internal job representation in the scheduler
1117
- */
1118
- interface Job {
1119
- /** Unique identifier */
1120
- id: string
1121
- /** The callback to execute */
1122
- callback: FrameNextCallback
1123
- /** Phase this job belongs to */
1124
- phase: string
1125
- /** Run before these phases/job ids */
1126
- before: Set<string>
1127
- /** Run after these phases/job ids */
1128
- after: Set<string>
1129
- /** Priority within phase (higher first) */
1130
- priority: number
1131
- /** Insertion order for deterministic tie-breaking */
1132
- index: number
1133
- /** Max FPS for this job (undefined = no limit) */
1134
- fps?: number
1135
- /** Drop frames when behind (true) or catch up (false) */
1136
- drop: boolean
1137
- /** Last run timestamp (ms) */
1138
- lastRun?: number
1139
- /** Whether job is enabled */
1140
- enabled: boolean
1141
- /** Internal flag: system jobs (like default render) don't block user render takeover */
1142
- system?: boolean
1143
- }
1144
-
1145
- // Phase Graph --------------------------------
1146
-
1147
- /**
1148
- * A node in the phase graph
1149
- */
1150
- interface PhaseNode {
1151
- /** Phase name */
1152
- name: string
1153
- /** Whether this was auto-generated from a before/after constraint */
1154
- isAutoGenerated: boolean
1155
- }
1156
-
1157
- /**
1158
- * Options for creating a job from hook options
1159
- */
1160
- interface JobOptions {
1161
- id?: string
1162
- phase?: string
1163
- before?: string | string[]
1164
- after?: string | string[]
1165
- priority?: number
1166
- fps?: number
1167
- drop?: boolean
1168
- enabled?: boolean
1169
- }
1170
-
1171
- // Frame Loop State --------------------------------
1172
-
1173
- /**
1174
- * Internal frame loop state
1175
- */
1176
- interface FrameLoopState {
1177
- /** Whether the loop is running */
1178
- running: boolean
1179
- /** Current RAF handle */
1180
- rafHandle: number | null
1181
- /** Last frame timestamp in ms (null = uninitialized) */
1182
- lastTime: number | null
1183
- /** Frame counter */
1184
- frameCount: number
1185
- /** Elapsed time since first frame in ms */
1186
- elapsedTime: number
1187
- /** createdAt timestamp in ms */
1188
- createdAt: number
1189
- }
1190
-
1191
- // Root Entry --------------------------------
1192
-
1193
- /**
1194
- * Internal representation of a registered root (Canvas).
1195
- * Tracks jobs and manages rebuild state for this root.
1196
- * @internal
1197
- */
1198
- interface RootEntry {
1199
- /** Unique identifier for this root */
1200
- id: string
1201
- /** Function to get the root's current state. Returns any to support independent mode. */
1202
- getState: () => any
1203
- /** Map of job IDs to Job objects */
1204
- jobs: Map<string, Job>
1205
- /** Cached sorted job list for execution order */
1206
- sortedJobs: Job[]
1207
- /** Whether sortedJobs needs rebuilding */
1208
- needsRebuild: boolean
1209
- }
1210
-
1211
- /**
1212
- * Internal representation of a global job (deprecated API).
1213
- * Global jobs run once per frame, not per-root.
1214
- * Used by legacy addEffect/addAfterEffect APIs.
1215
- * @internal
1216
- * @deprecated Use useFrame with phases instead
1217
- */
1218
- interface GlobalJob {
1219
- /** Unique identifier for this global job */
1220
- id: string
1221
- /** Callback invoked with RAF timestamp in ms */
1222
- callback: (timestamp: number) => void
1223
- }
1224
-
1225
- // HMR Support --------------------------------
1226
-
1227
- /**
1228
- * Hot Module Replacement data structure for preserving scheduler state
1229
- * @internal
1230
- */
1231
- interface HMRData {
1232
- /** Shared data object for storing values across reloads */
1233
- data: Record<string, any>
1234
- /** Optional function to accept HMR updates */
1235
- accept?: () => void
1236
- }
1237
-
1238
- // Default Phases --------------------------------
1239
-
1240
- /**
1241
- * Default phase names for the scheduler
1242
- */
1243
- type DefaultPhase = 'start' | 'input' | 'physics' | 'update' | 'render' | 'finish'
1244
- }
1245
-
1246
- type MutableOrReadonlyParameters<T extends (...args: any) => any> = Parameters<T> | Readonly<Parameters<T>>
1247
-
1248
- interface MathRepresentation {
1249
- set(...args: number[]): any
1250
- }
1251
- interface VectorRepresentation extends MathRepresentation {
1252
- setScalar(value: number): any
1253
- }
1254
- type MathTypes = MathRepresentation | Euler$1 | Color$1
1255
-
1256
- type MathType<T extends MathTypes> = T extends Color$1
1257
- ? Args<typeof Color$1> | ColorRepresentation
1258
- : T extends VectorRepresentation | Layers$1 | Euler$1
1259
- ? T | MutableOrReadonlyParameters<T['set']> | number
1260
- : T | MutableOrReadonlyParameters<T['set']>
1261
-
1262
- type MathProps<P> = {
1263
- [K in keyof P as P[K] extends MathTypes ? K : never]: P[K] extends MathTypes ? MathType<P[K]> : never
1264
- }
1265
-
1266
- type Vector2 = MathType<Vector2$1>
1267
- type Vector3 = MathType<Vector3$1>
1268
- type Vector4 = MathType<Vector4$1>
1269
- type Color = MathType<Color$1>
1270
- type Layers = MathType<Layers$1>
1271
- type Quaternion = MathType<Quaternion$1>
1272
- type Euler = MathType<Euler$1>
1273
- type Matrix3 = MathType<Matrix3$1>
1274
- type Matrix4 = MathType<Matrix4$1>
1275
-
1276
- interface RaycastableRepresentation {
1277
- raycast(raycaster: Raycaster, intersects: Intersection$1[]): void
1278
- }
1279
- type EventProps<P> = P extends RaycastableRepresentation ? Partial<EventHandlers> : {}
1280
-
1281
- interface ReactProps<P> {
1282
- children?: React.ReactNode
1283
- ref?: React.Ref<P>
1284
- key?: React.Key
1285
- }
1286
-
1287
- type ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = Partial<
1288
- Overwrite<P, MathProps<P> & ReactProps<P> & EventProps<P>>
1289
- >
1290
-
1291
- type ThreeElement<T extends ConstructorRepresentation> = Mutable<
1292
- Overwrite<ElementProps<T>, Omit<InstanceProps<InstanceType<T>, T>, 'object'>>
1293
- >
1294
-
1295
- type ThreeToJSXElements<T extends Record<string, any>> = {
1296
- [K in keyof T & string as Uncapitalize<K>]: T[K] extends ConstructorRepresentation ? ThreeElement<T[K]> : never
1297
- }
1298
-
1299
- type ThreeExports = typeof THREE
1300
- type ThreeElementsImpl = ThreeToJSXElements<ThreeExports>
1301
-
1302
- interface ThreeElements extends Omit<ThreeElementsImpl, 'audio' | 'source' | 'line' | 'path'> {
1303
- primitive: Omit<ThreeElement<any>, 'args'> & { object: object }
1304
- // Conflicts with DOM types can be accessed through a three* prefix
1305
- threeAudio: ThreeElementsImpl['audio']
1306
- threeSource: ThreeElementsImpl['source']
1307
- threeLine: ThreeElementsImpl['line']
1308
- threePath: ThreeElementsImpl['path']
1309
- }
1310
-
1311
- declare module 'react' {
1312
- namespace JSX {
1313
- interface IntrinsicElements extends ThreeElements {}
1314
- }
1315
- }
1316
-
1317
- declare module 'react/jsx-runtime' {
1318
- namespace JSX {
1319
- interface IntrinsicElements extends ThreeElements {}
1320
- }
1321
- }
1322
-
1323
- declare module 'react/jsx-dev-runtime' {
1324
- namespace JSX {
1325
- interface IntrinsicElements extends ThreeElements {}
1326
- }
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']
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
+ }
1327
1786
  }
1328
1787
 
1329
1788
  type three_d_Color = Color;
1330
1789
  type three_d_ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = ElementProps<T, P>;
1331
1790
  type three_d_Euler = Euler;
1332
1791
  type three_d_EventProps<P> = EventProps<P>;
1792
+ type three_d_GeometryProps<P> = GeometryProps<P>;
1793
+ type three_d_GeometryTransformProps = GeometryTransformProps;
1333
1794
  type three_d_Layers = Layers;
1334
1795
  type three_d_MathProps<P> = MathProps<P>;
1335
1796
  type three_d_MathRepresentation = MathRepresentation;
@@ -1338,9 +1799,11 @@ type three_d_MathTypes = MathTypes;
1338
1799
  type three_d_Matrix3 = Matrix3;
1339
1800
  type three_d_Matrix4 = Matrix4;
1340
1801
  type three_d_MutableOrReadonlyParameters<T extends (...args: any) => any> = MutableOrReadonlyParameters<T>;
1802
+ type three_d_NodeProps<P> = NodeProps<P>;
1341
1803
  type three_d_Quaternion = Quaternion;
1342
1804
  type three_d_RaycastableRepresentation = RaycastableRepresentation;
1343
1805
  type three_d_ReactProps<P> = ReactProps<P>;
1806
+ type three_d_TSLNodeInput = TSLNodeInput;
1344
1807
  type three_d_ThreeElement<T extends ConstructorRepresentation> = ThreeElement<T>;
1345
1808
  type three_d_ThreeElements = ThreeElements;
1346
1809
  type three_d_ThreeElementsImpl = ThreeElementsImpl;
@@ -1351,12 +1814,324 @@ type three_d_Vector3 = Vector3;
1351
1814
  type three_d_Vector4 = Vector4;
1352
1815
  type three_d_VectorRepresentation = VectorRepresentation;
1353
1816
  declare namespace three_d {
1354
- export type { three_d_Color as Color, three_d_ElementProps as ElementProps, three_d_Euler as Euler, three_d_EventProps as EventProps, three_d_Layers as Layers, three_d_MathProps as MathProps, three_d_MathRepresentation as MathRepresentation, three_d_MathType as MathType, three_d_MathTypes as MathTypes, three_d_Matrix3 as Matrix3, three_d_Matrix4 as Matrix4, three_d_MutableOrReadonlyParameters as MutableOrReadonlyParameters, three_d_Quaternion as Quaternion, three_d_RaycastableRepresentation as RaycastableRepresentation, three_d_ReactProps as ReactProps, three_d_ThreeElement as ThreeElement, three_d_ThreeElements as ThreeElements, three_d_ThreeElementsImpl as ThreeElementsImpl, three_d_ThreeExports as ThreeExports, three_d_ThreeToJSXElements as ThreeToJSXElements, three_d_Vector2 as Vector2, three_d_Vector3 as Vector3, three_d_Vector4 as Vector4, three_d_VectorRepresentation as VectorRepresentation };
1817
+ export type { three_d_Color as Color, three_d_ElementProps as ElementProps, three_d_Euler as Euler, three_d_EventProps as EventProps, three_d_GeometryProps as GeometryProps, three_d_GeometryTransformProps as GeometryTransformProps, three_d_Layers as Layers, three_d_MathProps as MathProps, three_d_MathRepresentation as MathRepresentation, three_d_MathType as MathType, three_d_MathTypes as MathTypes, three_d_Matrix3 as Matrix3, three_d_Matrix4 as Matrix4, three_d_MutableOrReadonlyParameters as MutableOrReadonlyParameters, three_d_NodeProps as NodeProps, three_d_Quaternion as Quaternion, three_d_RaycastableRepresentation as RaycastableRepresentation, three_d_ReactProps as ReactProps, three_d_TSLNodeInput as TSLNodeInput, three_d_ThreeElement as ThreeElement, three_d_ThreeElements as ThreeElements, three_d_ThreeElementsImpl as ThreeElementsImpl, three_d_ThreeExports as ThreeExports, three_d_ThreeToJSXElements as ThreeToJSXElements, three_d_Vector2 as Vector2, three_d_Vector3 as Vector3, three_d_Vector4 as Vector4, three_d_VectorRepresentation as VectorRepresentation };
1355
1818
  }
1356
1819
 
1820
+ /**
1821
+ * @fileoverview Registry for primary canvases that can be targeted by secondary canvases
1822
+ *
1823
+ * Enables multi-canvas WebGPU rendering where multiple Canvas components share
1824
+ * a single WebGPURenderer using Three.js CanvasTarget API.
1825
+ *
1826
+ * Primary canvas: Has `id` prop, creates its own renderer, registers here
1827
+ * Secondary canvas: Has `target="id"` prop, shares primary's renderer via CanvasTarget
1828
+ */
1829
+
1830
+ interface PrimaryCanvasEntry {
1831
+ /** The WebGPURenderer instance owned by this primary canvas */
1832
+ renderer: WebGPURenderer;
1833
+ /** The zustand store for this canvas */
1834
+ store: RootStore;
1835
+ }
1836
+ /**
1837
+ * Register a primary canvas that can be targeted by secondary canvases.
1838
+ *
1839
+ * @param id - Unique identifier for this primary canvas
1840
+ * @param renderer - The WebGPURenderer owned by this canvas
1841
+ * @param store - The zustand store for this canvas
1842
+ * @returns Cleanup function to unregister on unmount
1843
+ */
1844
+ declare function registerPrimary(id: string, renderer: WebGPURenderer, store: RootStore): () => void;
1845
+ /**
1846
+ * Get a registered primary canvas by id.
1847
+ *
1848
+ * @param id - The id of the primary canvas to look up
1849
+ * @returns The primary canvas entry or undefined if not found
1850
+ */
1851
+ declare function getPrimary(id: string): PrimaryCanvasEntry | undefined;
1852
+ /**
1853
+ * Wait for a primary canvas to be registered.
1854
+ * Returns immediately if already registered, otherwise waits.
1855
+ *
1856
+ * @param id - The id of the primary canvas to wait for
1857
+ * @param timeout - Optional timeout in ms (default: 5000)
1858
+ * @returns Promise that resolves with the primary canvas entry
1859
+ */
1860
+ declare function waitForPrimary(id: string, timeout?: number): Promise<PrimaryCanvasEntry>;
1861
+ /**
1862
+ * Check if a primary canvas with the given id exists.
1863
+ *
1864
+ * @param id - The id to check
1865
+ * @returns True if a primary canvas with this id is registered
1866
+ */
1867
+ declare function hasPrimary(id: string): boolean;
1868
+ /**
1869
+ * Unregister a primary canvas. Called on unmount.
1870
+ *
1871
+ * @param id - The id of the primary canvas to unregister
1872
+ */
1873
+ declare function unregisterPrimary(id: string): void;
1874
+ /**
1875
+ * Get all registered primary canvas ids. Useful for debugging.
1876
+ */
1877
+ declare function getPrimaryIds(): string[];
1878
+
1879
+ type EnvironmentLoaderProps = {
1880
+ files?: string | string[];
1881
+ path?: string;
1882
+ preset?: PresetsType;
1883
+ extensions?: (loader: Loader) => void;
1884
+ colorSpace?: ColorSpace;
1885
+ };
1886
+ /**
1887
+ * Loads environment textures for reflections and lighting.
1888
+ * Supports HDR files, presets, and cubemaps.
1889
+ *
1890
+ * @example Basic usage
1891
+ * ```jsx
1892
+ * const texture = useEnvironment({ preset: 'sunset' })
1893
+ * ```
1894
+ */
1895
+ declare function useEnvironment({ files, path, preset, colorSpace, extensions, }?: Partial<EnvironmentLoaderProps>): Texture$1<unknown> | CubeTexture;
1896
+ declare namespace useEnvironment {
1897
+ var preload: (preloadOptions?: EnvironmentLoaderPreloadOptions) => void;
1898
+ var clear: (clearOptions?: EnvironmentLoaderClearOptions) => void;
1899
+ }
1900
+ type EnvironmentLoaderPreloadOptions = Omit<EnvironmentLoaderProps, 'encoding'>;
1901
+ type EnvironmentLoaderClearOptions = Pick<EnvironmentLoaderProps, 'files' | 'preset'>;
1902
+
1903
+ /**
1904
+ * Props for Environment component that sets up global cubemap for PBR materials and backgrounds.
1905
+ *
1906
+ * @property children - React children to render into custom environment portal
1907
+ * @property frames - Number of frames to render the environment. Use 1 for static, Infinity for animated (default: 1)
1908
+ * @property near - Near clipping plane for cube camera (default: 0.1)
1909
+ * @property far - Far clipping plane for cube camera (default: 1000)
1910
+ * @property resolution - Resolution of the cube render target (default: 256)
1911
+ * @property background - Whether to set scene.background. Can be true, false, or "only" (which only sets background) (default: false)
1912
+ *
1913
+ * @property blur - @deprecated Use backgroundBlurriness instead
1914
+ * @property backgroundBlurriness - Blur factor between 0 and 1 for background (default: 0, requires three.js 0.146+)
1915
+ * @property backgroundIntensity - Intensity factor for background (default: 1, requires three.js 0.163+)
1916
+ * @property backgroundRotation - Rotation for background as Euler angles (default: [0,0,0], requires three.js 0.163+)
1917
+ * @property environmentIntensity - Intensity factor for environment lighting (default: 1, requires three.js 0.163+)
1918
+ * @property environmentRotation - Rotation for environment as Euler angles (default: [0,0,0], requires three.js 0.163+)
1919
+ *
1920
+ * @property map - Pre-existing texture to use as environment map
1921
+ * @property preset - HDRI Haven preset: 'apartment', 'city', 'dawn', 'forest', 'lobby', 'night', 'park', 'studio', 'sunset', 'warehouse'. Not for production use.
1922
+ * @property scene - Custom THREE.Scene or ref to apply environment to (default: uses default scene)
1923
+ * @property ground - Ground projection settings. Use true for defaults or object with:
1924
+ * - height: Height of camera used to create env map (default: 15)
1925
+ * - radius: Radius of the world (default: 60)
1926
+ * - scale: Scale of backside projected sphere (default: 1000)
1927
+ *
1928
+ * Additional loader props:
1929
+ * @property files - File path(s) for environment. Supports .hdr, .exr, gainmap .jpg/.webp, or array of 6 cube faces
1930
+ * @property path - Base path for file loading
1931
+ * @property extensions - Texture extensions override
1932
+ */
1933
+ type EnvironmentProps = {
1934
+ children?: React$1.ReactNode;
1935
+ frames?: number;
1936
+ near?: number;
1937
+ far?: number;
1938
+ resolution?: number;
1939
+ background?: boolean | 'only';
1940
+ /** deprecated, use backgroundBlurriness */
1941
+ blur?: number;
1942
+ backgroundBlurriness?: number;
1943
+ backgroundIntensity?: number;
1944
+ backgroundRotation?: Euler$2;
1945
+ environmentIntensity?: number;
1946
+ environmentRotation?: Euler$2;
1947
+ map?: Texture$1;
1948
+ preset?: PresetsType;
1949
+ scene?: Scene | React$1.RefObject<Scene>;
1950
+ ground?: boolean | {
1951
+ radius?: number;
1952
+ height?: number;
1953
+ scale?: number;
1954
+ };
1955
+ /** Solid color for background (alternative to files/preset) */
1956
+ color?: ColorRepresentation;
1957
+ /** Separate files for background (when different from environment files) */
1958
+ backgroundFiles?: string | string[];
1959
+ } & EnvironmentLoaderProps;
1960
+ /**
1961
+ * Internal component that applies a pre-existing texture as environment map.
1962
+ * Sets scene.environment and optionally scene.background.
1963
+ *
1964
+ * @example
1965
+ * ```jsx
1966
+ * <CubeCamera>{(texture) => <EnvironmentMap map={texture} />}</CubeCamera>
1967
+ * ```
1968
+ */
1969
+ declare function EnvironmentMap({ scene, background, map, ...config }: EnvironmentProps): null;
1970
+ /**
1971
+ * Internal component that loads environment textures from files or presets.
1972
+ * Uses HDRLoader for .hdr, EXRLoader for .exr, UltraHDRLoader for .jpg/.jpeg HDR,
1973
+ * GainMapLoader for gainmap .webp, or CubeTextureLoader for arrays of images.
1974
+ *
1975
+ * @example With preset
1976
+ * ```jsx
1977
+ * <EnvironmentCube preset="sunset" />
1978
+ * ```
1979
+ *
1980
+ * @example From HDR file
1981
+ * ```jsx
1982
+ * <EnvironmentCube files="environment.hdr" />
1983
+ * ```
1984
+ *
1985
+ * @example From gainmap (smallest footprint)
1986
+ * ```jsx
1987
+ * <EnvironmentCube files={['file.webp', 'file-gainmap.webp', 'file.json']} />
1988
+ * ```
1989
+ *
1990
+ * @example From cube faces
1991
+ * ```jsx
1992
+ * <EnvironmentCube files={['px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png']} />
1993
+ * ```
1994
+ */
1995
+ declare function EnvironmentCube({ background, scene, blur, backgroundBlurriness, backgroundIntensity, backgroundRotation, environmentIntensity, environmentRotation, ...rest }: EnvironmentProps): null;
1996
+ /**
1997
+ * Internal component that renders custom environment using a portal and cube camera.
1998
+ * Renders children into an off-buffer and films with a cube camera to create environment map.
1999
+ * Can be static (frames=1) or animated (frames=Infinity).
2000
+ *
2001
+ * @example Custom environment with sphere
2002
+ * ```jsx
2003
+ * <EnvironmentPortal background near={1} far={1000} resolution={256}>
2004
+ * <mesh scale={100}>
2005
+ * <sphereGeometry args={[1, 64, 64]} />
2006
+ * <meshBasicMaterial map={texture} side={THREE.BackSide} />
2007
+ * </mesh>
2008
+ * </EnvironmentPortal>
2009
+ * ```
2010
+ *
2011
+ * @example Animated environment
2012
+ * ```jsx
2013
+ * <EnvironmentPortal frames={Infinity} resolution={256}>
2014
+ * <Float>
2015
+ * <mesh />
2016
+ * </Float>
2017
+ * </EnvironmentPortal>
2018
+ * ```
2019
+ *
2020
+ * @example Mixed with preset
2021
+ * ```jsx
2022
+ * <EnvironmentPortal preset="warehouse">
2023
+ * <mesh />
2024
+ * </EnvironmentPortal>
2025
+ * ```
2026
+ */
2027
+ declare function EnvironmentPortal({ children, near, far, resolution, frames, map, background, blur, backgroundBlurriness, backgroundIntensity, backgroundRotation, environmentIntensity, environmentRotation, scene, files, path, preset, extensions, }: EnvironmentProps): react_jsx_runtime.JSX.Element;
2028
+ declare module '@react-three/fiber' {
2029
+ interface ThreeElements {
2030
+ groundProjectedEnvImpl: ThreeElement$1<typeof GroundedSkybox>;
2031
+ }
2032
+ }
2033
+ /**
2034
+ * Sets up a global environment map for PBR materials and backgrounds.
2035
+ * Affects scene.environment and optionally scene.background unless a custom scene is passed.
2036
+ *
2037
+ * Supports multiple input methods:
2038
+ * - **Presets**: Selection of HDRI Haven assets (apartment, city, dawn, forest, lobby, night, park, studio, sunset, warehouse)
2039
+ * - **Files**: HDR (.hdr), EXR (.exr), gainmap JPEG (.jpg), gainmap WebP (.webp), or cube faces (array of 6 images)
2040
+ * - **Texture**: Pre-existing cube texture via `map` prop
2041
+ * - **Custom Scene**: Render children into environment using portal and cube camera
2042
+ * - **Ground Projection**: Project environment onto ground plane
2043
+ *
2044
+ * @remarks
2045
+ * - Preset property is NOT meant for production and may fail (relies on CDNs)
2046
+ * - Gainmap format has the smallest file footprint
2047
+ * - Use `frames={Infinity}` for animated environments with low resolution for performance
2048
+ * - Ground projection places models on the "ground" within the environment map
2049
+ * - Supports self-hosting with @pmndrs/assets using dynamic imports
2050
+ *
2051
+ * @example Basic preset usage
2052
+ * ```jsx
2053
+ * <Environment preset="sunset" />
2054
+ * ```
2055
+ *
2056
+ * @example From HDR file
2057
+ * ```jsx
2058
+ * <Environment files="/hdr/environment.hdr" />
2059
+ * ```
2060
+ *
2061
+ * @example From gainmap (smallest footprint)
2062
+ * ```jsx
2063
+ * <Environment files={['file.webp', 'file-gainmap.webp', 'file.json']} />
2064
+ * ```
2065
+ *
2066
+ * @example With self-hosted assets
2067
+ * ```jsx
2068
+ * import { suspend } from 'suspend-react'
2069
+ * const city = import('@pmndrs/assets/hdri/city.exr').then(m => m.default)
2070
+ *
2071
+ * <Environment files={suspend(city)} />
2072
+ * ```
2073
+ *
2074
+ * @example From existing texture
2075
+ * ```jsx
2076
+ * <CubeCamera>{(texture) => <Environment map={texture} />}</CubeCamera>
2077
+ * ```
2078
+ *
2079
+ * @example Custom environment scene
2080
+ * ```jsx
2081
+ * <Environment background near={1} far={1000} resolution={256}>
2082
+ * <mesh scale={100}>
2083
+ * <sphereGeometry args={[1, 64, 64]} />
2084
+ * <meshBasicMaterial map={texture} side={THREE.BackSide} />
2085
+ * </mesh>
2086
+ * </Environment>
2087
+ * ```
2088
+ *
2089
+ * @example Animated environment
2090
+ * ```jsx
2091
+ * <Environment frames={Infinity} resolution={256}>
2092
+ * <Float>
2093
+ * <mesh />
2094
+ * </Float>
2095
+ * </Environment>
2096
+ * ```
2097
+ *
2098
+ * @example Mixed custom scene with preset
2099
+ * ```jsx
2100
+ * <Environment background preset="warehouse">
2101
+ * <mesh />
2102
+ * </Environment>
2103
+ * ```
2104
+ *
2105
+ * @example With ground projection
2106
+ * ```jsx
2107
+ * <Environment ground={{ height: 15, radius: 60 }} preset="city" />
2108
+ * ```
2109
+ *
2110
+ * @example As background only
2111
+ * ```jsx
2112
+ * <Environment background="only" preset="sunset" />
2113
+ * ```
2114
+ *
2115
+ * @example With rotation and intensity
2116
+ * ```jsx
2117
+ * <Environment
2118
+ * background
2119
+ * backgroundBlurriness={0.5}
2120
+ * backgroundIntensity={0.8}
2121
+ * backgroundRotation={[0, Math.PI / 2, 0]}
2122
+ * environmentIntensity={1.2}
2123
+ * environmentRotation={[0, Math.PI / 4, 0]}
2124
+ * preset="studio"
2125
+ * />
2126
+ * ```
2127
+ */
2128
+ declare function Environment(props: EnvironmentProps): react_jsx_runtime.JSX.Element;
2129
+
1357
2130
  declare function removeInteractivity(store: RootStore, object: Object3D): void;
1358
2131
  declare function createEvents(store: RootStore): {
1359
2132
  handlePointer: (name: string) => (event: DomEvent) => void;
2133
+ flushDeferredPointers: () => void;
2134
+ processDeferredPointer: (event: DomEvent, pointerId: number) => void;
1360
2135
  };
1361
2136
  /** Default R3F event manager for web */
1362
2137
  declare function createPointerEvents(store: RootStore): EventManager<HTMLElement>;
@@ -1915,31 +2690,30 @@ declare function useTextures(): UseTexturesReturn;
1915
2690
  * - WebGPU build: Returns RenderTarget
1916
2691
  * - Default build: Returns whichever matches the active renderer
1917
2692
  *
1918
- * @param width - Target width (defaults to canvas width)
1919
- * @param height - Target height (defaults to canvas height)
1920
- * @param options - Three.js RenderTarget options
1921
- *
1922
2693
  * @example
1923
2694
  * ```tsx
1924
- * function PortalScene() {
1925
- * const fbo = useRenderTarget(512, 512, { depthBuffer: true })
1926
- *
1927
- * useFrame(({ renderer, scene, camera }) => {
1928
- * renderer.setRenderTarget(fbo)
1929
- * renderer.render(scene, camera)
1930
- * renderer.setRenderTarget(null)
1931
- * })
1932
- *
1933
- * return (
1934
- * <mesh>
1935
- * <planeGeometry />
1936
- * <meshBasicMaterial map={fbo.texture} />
1937
- * </mesh>
1938
- * )
1939
- * }
2695
+ * // Use canvas size
2696
+ * const fbo = useRenderTarget()
2697
+ *
2698
+ * // Use canvas size with options
2699
+ * const fbo = useRenderTarget({ samples: 4 })
2700
+ *
2701
+ * // Square render target
2702
+ * const fbo = useRenderTarget(512)
2703
+ *
2704
+ * // Square render target with options
2705
+ * const fbo = useRenderTarget(512, { depthBuffer: true })
2706
+ *
2707
+ * // Explicit dimensions
2708
+ * const fbo = useRenderTarget(512, 256)
2709
+ *
2710
+ * // Explicit dimensions with options
2711
+ * const fbo = useRenderTarget(512, 256, { samples: 4 })
1940
2712
  * ```
1941
2713
  */
1942
- declare function useRenderTarget(width?: number, height?: number, options?: RenderTargetOptions): RenderTarget<THREE$1.Texture<unknown>>;
2714
+ declare function useRenderTarget(options?: RenderTargetOptions): WebGLRenderTarget;
2715
+ declare function useRenderTarget(size: number, options?: RenderTargetOptions): WebGLRenderTarget;
2716
+ declare function useRenderTarget(width: number, height: number, options?: RenderTargetOptions): WebGLRenderTarget;
1943
2717
 
1944
2718
  /**
1945
2719
  * Returns the R3F Canvas' Zustand store. Useful for [transient updates](https://github.com/pmndrs/zustand#transient-updates-for-often-occurring-state-changes).
@@ -2044,7 +2818,7 @@ declare function invalidate(state?: RootState, frames?: number, stackFrames?: bo
2044
2818
  *
2045
2819
  * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#advance
2046
2820
  */
2047
- declare function advance(timestamp: number, runGlobalEffects?: boolean, state?: RootState, frame?: XRFrame): void;
2821
+ declare function advance(timestamp: number): void;
2048
2822
 
2049
2823
  /* eslint-disable @definitelytyped/no-unnecessary-generics */
2050
2824
  declare function ReactReconciler<
@@ -3098,6 +3872,12 @@ declare const _roots: Map<HTMLCanvasElement | OffscreenCanvas, Root>;
3098
3872
  declare function createRoot<TCanvas extends HTMLCanvasElement | OffscreenCanvas>(canvas: TCanvas): ReconcilerRoot<TCanvas>;
3099
3873
  declare function unmountComponentAtNode<TCanvas extends HTMLCanvasElement | OffscreenCanvas>(canvas: TCanvas, callback?: (canvas: TCanvas) => void): void;
3100
3874
  declare function createPortal(children: ReactNode, container: Object3D | RefObject<Object3D | null> | RefObject<Object3D>, state?: InjectState): JSX.Element;
3875
+ interface PortalProps {
3876
+ children: ReactNode;
3877
+ state?: InjectState;
3878
+ container: Object3D | RefObject<Object3D | null> | RefObject<Object3D>;
3879
+ }
3880
+ declare function Portal({ children, container, state }: PortalProps): JSX.Element;
3101
3881
  /**
3102
3882
  * Force React to flush any updates inside the provided callback synchronously and immediately.
3103
3883
  * All the same caveats documented for react-dom's `flushSync` apply here (see https://react.dev/reference/react-dom/flushSync).
@@ -3526,11 +4306,76 @@ declare const hasConstructor: (object: unknown) => object is {
3526
4306
  constructor?: Function;
3527
4307
  };
3528
4308
 
4309
+ /**
4310
+ * Symbol marker for deferred ref resolution.
4311
+ * Used to identify values that should be resolved from refs after mount.
4312
+ */
4313
+ declare const FROM_REF: unique symbol;
4314
+ /**
4315
+ * Defers prop application until the referenced object is available.
4316
+ * Useful for props like `target` that need sibling refs to be populated.
4317
+ *
4318
+ * @param ref - React ref object to resolve at mount time
4319
+ * @returns A marker value that applyProps will resolve after mount
4320
+ *
4321
+ * @example
4322
+ * const targetRef = useRef<THREE.Object3D>(null)
4323
+ *
4324
+ * <group ref={targetRef} position={[-3, -2, -15]} />
4325
+ * <spotLight target={fromRef(targetRef)} intensity={100} />
4326
+ */
4327
+ declare function fromRef<T>(ref: React$1.RefObject<T | null>): T;
4328
+ /**
4329
+ * Type guard to check if a value is a fromRef marker.
4330
+ *
4331
+ * @param value - Value to check
4332
+ * @returns True if value is a fromRef marker
4333
+ */
4334
+ declare function isFromRef(value: unknown): value is {
4335
+ [FROM_REF]: React$1.RefObject<any>;
4336
+ };
4337
+
4338
+ /**
4339
+ * Symbol marker for mount-only method calls.
4340
+ * Used to identify methods that should only be called once on initial mount.
4341
+ */
4342
+ declare const ONCE: unique symbol;
4343
+ /**
4344
+ * Marks a method call to be executed only on initial mount.
4345
+ * Useful for geometry transforms that should not be reapplied on every render.
4346
+ *
4347
+ * When `args` prop changes (triggering reconstruction), the method will be
4348
+ * called again on the new instance since appliedOnce is not carried over.
4349
+ *
4350
+ * @param args - Arguments to pass to the method
4351
+ * @returns A marker value that applyProps will execute once
4352
+ *
4353
+ * @example
4354
+ * // Rotate geometry on mount
4355
+ * <boxGeometry args={[1, 1, 1]} rotateX={once(Math.PI / 2)} />
4356
+ *
4357
+ * // Multiple arguments
4358
+ * <bufferGeometry applyMatrix4={once(matrix)} />
4359
+ *
4360
+ * // No arguments
4361
+ * <geometry center={once()} />
4362
+ */
4363
+ declare function once<T>(...args: T[]): T;
4364
+ /**
4365
+ * Type guard to check if a value is a once marker.
4366
+ *
4367
+ * @param value - Value to check
4368
+ * @returns True if value is a once marker
4369
+ */
4370
+ declare function isOnce(value: unknown): value is {
4371
+ [ONCE]: any[] | true;
4372
+ };
4373
+
3529
4374
  /**
3530
4375
  * A DOM canvas which accepts threejs elements as children.
3531
4376
  * @see https://docs.pmnd.rs/react-three-fiber/api/canvas
3532
4377
  */
3533
4378
  declare function Canvas(props: CanvasProps): react_jsx_runtime.JSX.Element;
3534
4379
 
3535
- export { Block, Canvas, ErrorBoundary, IsObject, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, REACT_INTERNAL_PROPS, RESERVED_PROPS, three_d as ReactThreeFiber, Scheduler, Texture, _roots, act, addAfterEffect, addEffect, addTail, advance, applyProps, attach, buildGraph, calculateDpr, context, createEvents, createPointerEvents, createPortal, createRoot, createStore, detach, diffProps, dispose, createPointerEvents as events, extend, findInitialRoot, flushSync, getInstanceProps, getRootState, getScheduler, getUuidPrefix, hasConstructor, invalidate, invalidateInstance, is, isColorRepresentation, isCopyable, isObject3D, isOrthographicCamera, isRef, isRenderer, isTexture, isVectorLike, prepare, reconciler, removeInteractivity, resolve, unmountComponentAtNode, updateCamera, updateFrustum, useBridge, useFrame, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useMutableCallback, useRenderTarget, useStore, useTexture, useTextures, useThree };
3536
- export type { Act, AddPhaseOptions, Args, ArgsProp, AttachFnType, AttachType, BaseRendererProps, Bridge, Camera, CameraProps, CanvasProps, Catalogue, Color, ComputeFunction, ConstructorRepresentation, DefaultGLProps, DefaultRendererProps, Disposable, DomEvent, Dpr, ElementProps, EquConfig, Euler, EventHandlers, EventManager, EventProps, Events, Extensions, FiberRoot, FilterFunction, FrameCallback, FrameControls, FrameNextCallback, FrameNextControls, FrameNextState, FrameState, FrameTimingState, Frameloop, GLProps, GLTFLike, GlobalEffectType, GlobalRenderCallback, HostConfig, InferLoadResult, InjectState, InputLike, Instance, InstanceProps, InternalState, Intersection, IntersectionEvent, IsAllOptional, IsOptional, Layers, LoaderInstance, LoaderLike, LoaderResult, MappedTextureType, MathProps, MathRepresentation, MathType, MathTypes, Matrix3, Matrix4, Mutable, MutableOrReadonlyParameters, NonFunctionKeys, ObjectMap, OffscreenCanvas$1 as OffscreenCanvas, Overwrite, Performance, PointerCaptureTarget, Properties, Quaternion, RaycastableRepresentation, ReactProps, ReconcilerRoot, RenderCallback, RenderProps, RenderTargetOptions, Renderer, RendererFactory, RendererProps, Root, RootOptions, RootState, RootStore, SchedulerApi, SetBlock, Size, Subscription, TextureEntry, ThreeCamera, ThreeElement, ThreeElements, ThreeElementsImpl, ThreeEvent, ThreeExports, ThreeToJSXElements, UnblockProps, UseFrameNextOptions, UseFrameOptions, UseTextureOptions, UseTexturesReturn, Vector2, Vector3, Vector4, VectorRepresentation, Viewport, VisibilityEntry, WebGLDefaultProps, WebGLProps, WebGLShadowConfig, XRManager };
4380
+ export { Block, Canvas, Environment, EnvironmentCube, EnvironmentMap, EnvironmentPortal, ErrorBoundary, FROM_REF, IsObject, ONCE, Portal, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, REACT_INTERNAL_PROPS, RESERVED_PROPS, three_d as ReactThreeFiber, Scheduler, Texture, _roots, act, addAfterEffect, addEffect, addTail, advance, applyProps, attach, buildGraph, calculateDpr, context, createEvents, createPointerEvents, createPortal, createRoot, createStore, detach, diffProps, dispose, createPointerEvents as events, extend, findInitialRoot, flushSync, fromRef, getInstanceProps, getPrimary, getPrimaryIds, getRootState, getScheduler, getUuidPrefix, hasConstructor, hasPrimary, invalidate, invalidateInstance, is, isColorRepresentation, isCopyable, isFromRef, isObject3D, isOnce, isOrthographicCamera, isRef, isRenderer, isTexture, isVectorLike, once, prepare, presetsObj, reconciler, registerPrimary, removeInteractivity, resolve, unmountComponentAtNode, unregisterPrimary, updateCamera, updateFrustum, useBridge, useEnvironment, useFrame, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useMutableCallback, useRenderTarget, useStore, useTexture, useTextures, useThree, waitForPrimary };
4381
+ export type { Act, AddPhaseOptions, Args, ArgsProp, AttachFnType, AttachType, BackgroundConfig, BackgroundProp, BaseRendererProps, Bridge, BufferLike, BufferRecord, BufferStore, Camera, CameraProps, CanvasProps, CanvasSchedulerConfig, Catalogue, Color, ColorManagementConfig, ComputeFunction, ConstructorRepresentation, DefaultGLProps, DefaultRendererProps, Disposable, DomEvent, Dpr, ElementProps, EnvironmentLoaderProps, EnvironmentProps, EquConfig, Euler, EventHandlers, EventManager, EventProps, Events, Extensions, FiberRoot, FilterFunction, FrameCallback, FrameControls, FrameNextCallback, FrameNextControls, FrameNextState, FrameState, FrameTimingState, Frameloop, GLProps, GLTFLike, GeometryProps, GeometryTransformProps, GlobalEffectType, GlobalRenderCallback, HostConfig, InferLoadResult, InjectState, InputLike, Instance, InstanceProps, LegacyInternalState as InternalState, Intersection, IntersectionEvent, IsAllOptional, IsOptional, Layers, LegacyInternalState, LegacyRenderer, LegacyRootState, LoaderInstance, LoaderLike, LoaderResult, MappedTextureType, MathProps, MathRepresentation, MathType, MathTypes, Matrix3, Matrix4, Mutable, MutableOrReadonlyParameters, NodeProps, NonFunctionKeys, ObjectMap, OffscreenCanvas$1 as OffscreenCanvas, Overwrite, Performance, PointerCaptureTarget, PointerState, PresetsType, PrimaryCanvasEntry, Properties, Quaternion, LegacyRenderer as R3FRenderer, RaycastableRepresentation, ReactProps, ReconcilerRoot, RenderCallback, RenderProps, RenderTargetOptions, Renderer, RendererConfigExtended, RendererFactory, RendererProps, Root, RootOptions, LegacyRootState as RootState, RootStore, SchedulerApi, SetBlock, Size, StorageLike, StorageRecord, StorageStore, Subscription, TSLNodeInput, TextureEntry, ThreeCamera, ThreeElement, ThreeElements, ThreeElementsImpl, ThreeEvent, ThreeExports, ThreeToJSXElements, UnblockProps, UseFrameNextOptions, UseFrameOptions, UseTextureOptions, UseTexturesReturn, Vector2, Vector3, Vector4, VectorRepresentation, Viewport, VisibilityEntry, WebGLDefaultProps, WebGLProps, WebGLShadowConfig, XRManager, XRPointerConfig };