@react-three/fiber 10.0.0-alpha.1 → 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,14 +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 react_reconciler from 'C:\\dev\\react-three-fiber\\node_modules\\.pnpm\\@types+react-reconciler@0.32.3_@types+react@19.2.7\\node_modules\\@types\\react-reconciler\\index.d.ts';
8
- import * as three_webgpu from 'three/webgpu';
9
- import { Node, ShaderNodeObject } from 'three/webgpu';
10
9
  import { Options } from 'react-use-measure';
11
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';
12
13
 
13
14
  function _mergeNamespaces(n, m) {
14
15
  m.forEach(function (e) {
@@ -55,1270 +56,1741 @@ var THREE = /*#__PURE__*/_mergeNamespaces({
55
56
  WebGPURenderer: WebGPURenderer
56
57
  }, [THREE$1]);
57
58
 
58
- //* Utility Types ==============================
59
-
60
- type NonFunctionKeys<P> = { [K in keyof P]-?: P[K] extends Function ? never : K }[keyof P]
61
- type Overwrite<P, O> = Omit<P, NonFunctionKeys<O>> & O
62
- type Properties<T> = Pick<T, NonFunctionKeys<T>>
63
- type Mutable<P> = { [K in keyof P]: P[K] | Readonly<P[K]> }
64
- type IsOptional<T> = undefined extends T ? true : false
65
- type IsAllOptional<T extends any[]> = T extends [infer First, ...infer Rest]
66
- ? IsOptional<First> extends true
67
- ? IsAllOptional<Rest>
68
- : false
69
- : true
70
-
71
- //* Camera Types ==============================
72
-
73
- type ThreeCamera = (THREE$1.OrthographicCamera | THREE$1.PerspectiveCamera) & { manual?: boolean }
74
-
75
- //* Act Type ==============================
76
-
77
- type Act = <T = any>(cb: () => Promise<T>) => Promise<T>
78
-
79
- //* Bridge & Block Types ==============================
80
-
81
- type Bridge = React$1.FC<{ children?: React$1.ReactNode }>
82
-
83
- type SetBlock = false | Promise<null> | null
84
- type UnblockProps = { set: React$1.Dispatch<React$1.SetStateAction<SetBlock>>; children: React$1.ReactNode }
85
-
86
- //* Object Map Type ==============================
87
-
88
- interface ObjectMap {
89
- nodes: { [name: string]: THREE$1.Object3D }
90
- materials: { [name: string]: THREE$1.Material }
91
- meshes: { [name: string]: THREE$1.Mesh }
92
- }
93
-
94
- //* Equality Config ==============================
95
-
96
- interface EquConfig {
97
- /** Compare arrays by reference equality a === b (default), or by shallow equality */
98
- arrays?: 'reference' | 'shallow'
99
- /** Compare objects by reference equality a === b (default), or by shallow equality */
100
- objects?: 'reference' | 'shallow'
101
- /** If true the keys in both a and b must match 1:1 (default), if false a's keys must intersect b's */
102
- strict?: boolean
103
- }
104
-
105
- //* Disposable Type ==============================
106
-
107
- interface Disposable {
108
- type?: string
109
- dispose?: () => void
110
- }
111
-
112
- //* Event-related Types =====================================
113
-
114
- interface Intersection extends THREE$1.Intersection {
115
- /** The event source (the object which registered the handler) */
116
- eventObject: THREE$1.Object3D
117
- }
118
-
119
- type Camera = THREE$1.OrthographicCamera | THREE$1.PerspectiveCamera
120
-
121
- interface IntersectionEvent<TSourceEvent> extends Intersection {
122
- /** The event source (the object which registered the handler) */
123
- eventObject: THREE$1.Object3D
124
- /** An array of intersections */
125
- intersections: Intersection[]
126
- /** vec3.set(pointer.x, pointer.y, 0).unproject(camera) */
127
- unprojectedPoint: THREE$1.Vector3
128
- /** Normalized event coordinates */
129
- pointer: THREE$1.Vector2
130
- /** Delta between first click and this event */
131
- delta: number
132
- /** The ray that pierced it */
133
- ray: THREE$1.Ray
134
- /** The camera that was used by the raycaster */
135
- camera: Camera
136
- /** stopPropagation will stop underlying handlers from firing */
137
- stopPropagation: () => void
138
- /** The original host event */
139
- nativeEvent: TSourceEvent
140
- /** If the event was stopped by calling stopPropagation */
141
- stopped: boolean
142
- }
143
-
144
- type ThreeEvent<TEvent> = IntersectionEvent<TEvent> & Properties<TEvent>
145
- type DomEvent = PointerEvent | MouseEvent | WheelEvent
146
-
147
- /** DOM event handlers registered on the canvas element */
148
- interface Events {
149
- onClick: EventListener
150
- onContextMenu: EventListener
151
- onDoubleClick: EventListener
152
- onWheel: EventListener
153
- onPointerDown: EventListener
154
- onPointerUp: EventListener
155
- onPointerLeave: EventListener
156
- onPointerMove: EventListener
157
- onPointerCancel: EventListener
158
- onLostPointerCapture: EventListener
159
- onDragEnter: EventListener
160
- onDragLeave: EventListener
161
- onDragOver: EventListener
162
- onDrop: EventListener
163
- }
164
-
165
- /** Event handlers that can be attached to R3F objects (meshes, groups, etc.) */
166
- interface EventHandlers {
167
- onClick?: (event: ThreeEvent<MouseEvent>) => void
168
- onContextMenu?: (event: ThreeEvent<MouseEvent>) => void
169
- onDoubleClick?: (event: ThreeEvent<MouseEvent>) => void
170
- /** Fires continuously while dragging over the object */
171
- onDragOver?: (event: ThreeEvent<DragEvent>) => void
172
- /** Fires once when drag enters the object */
173
- onDragOverEnter?: (event: ThreeEvent<DragEvent>) => void
174
- /** Fires once when drag leaves the object */
175
- onDragOverLeave?: (event: ThreeEvent<DragEvent>) => void
176
- /** Fires when drag misses this object (for objects that have drag handlers) */
177
- onDragOverMissed?: (event: DragEvent) => void
178
- /** Fires when a drop occurs on this object */
179
- onDrop?: (event: ThreeEvent<DragEvent>) => void
180
- /** Fires when a drop misses this object (for objects that have drop handlers) */
181
- onDropMissed?: (event: DragEvent) => void
182
- onPointerUp?: (event: ThreeEvent<PointerEvent>) => void
183
- onPointerDown?: (event: ThreeEvent<PointerEvent>) => void
184
- onPointerOver?: (event: ThreeEvent<PointerEvent>) => void
185
- onPointerOut?: (event: ThreeEvent<PointerEvent>) => void
186
- onPointerEnter?: (event: ThreeEvent<PointerEvent>) => void
187
- onPointerLeave?: (event: ThreeEvent<PointerEvent>) => void
188
- onPointerMove?: (event: ThreeEvent<PointerEvent>) => void
189
- onPointerMissed?: (event: MouseEvent) => void
190
- onPointerCancel?: (event: ThreeEvent<PointerEvent>) => void
191
- onWheel?: (event: ThreeEvent<WheelEvent>) => void
192
- onLostPointerCapture?: (event: ThreeEvent<PointerEvent>) => void
193
-
194
- //* Visibility Events --------------------------------
195
- /** Fires when object enters/exits camera frustum. Receives true when in view, false when out. */
196
- onFramed?: (inView: boolean) => void
197
- /** Fires when object occlusion state changes (WebGPU only, requires occlusionTest=true on object) */
198
- onOccluded?: (occluded: boolean) => void
199
- /** Fires when combined visibility changes (frustum + occlusion + visible prop) */
200
- onVisible?: (visible: boolean) => void
201
- }
202
-
203
- type FilterFunction = (items: THREE$1.Intersection[], state: RootState) => THREE$1.Intersection[]
204
- type ComputeFunction = (event: DomEvent, root: RootState, previous?: RootState) => void
205
-
206
- interface EventManager<TTarget> {
207
- /** Determines if the event layer is active */
208
- enabled: boolean
209
- /** Event layer priority, higher prioritized layers come first and may stop(-propagate) lower layer */
210
- priority: number
211
- /** The compute function needs to set up the raycaster and an xy- pointer */
212
- compute?: ComputeFunction
213
- /** The filter can re-order or re-structure the intersections */
214
- filter?: FilterFunction
215
- /** The target node the event layer is tied to */
216
- connected?: TTarget
217
- /** All the pointer event handlers through which the host forwards native events */
218
- handlers?: Events
219
- /** Allows re-connecting to another target */
220
- connect?: (target: TTarget) => void
221
- /** Removes all existing events handlers from the target */
222
- disconnect?: () => void
223
- /** Triggers a onPointerMove with the last known event. This can be useful to enable raycasting without
224
- * explicit user interaction, for instance when the camera moves a hoverable object underneath the cursor.
225
- */
226
- update?: () => void
227
- }
228
-
229
- interface PointerCaptureTarget {
230
- intersection: Intersection
231
- target: Element
232
- }
233
-
234
- //* Visibility System Types =====================================
235
-
236
- /** Entry in the visibility registry for tracking object visibility state */
237
- interface VisibilityEntry {
238
- object: THREE$1.Object3D
239
- handlers: Pick<EventHandlers, 'onFramed' | 'onOccluded' | 'onVisible'>
240
- lastFramedState: boolean | null
241
- lastOccludedState: boolean | null
242
- lastVisibleState: boolean | null
243
- }
244
-
245
- //* Scheduler Types (useFrame) ==============================
246
-
247
-
248
-
249
- // Public Options --------------------------------
250
-
251
- /**
252
- * Options for useFrame hook
253
- */
254
- interface UseFrameNextOptions {
255
- /** Optional stable id for the job. Auto-generated if not provided */
256
- id?: string
257
- /** Named phase to run in. Default: 'update' */
258
- phase?: string
259
- /** Run before this phase or job id */
260
- before?: string | string[]
261
- /** Run after this phase or job id */
262
- after?: string | string[]
263
- /** Priority within phase. Higher runs first. Default: 0 */
264
- priority?: number
265
- /** Max frames per second for this job */
266
- fps?: number
267
- /** If true, skip frames when behind. If false, try to catch up. Default: true */
268
- drop?: boolean
269
- /** Enable/disable without unregistering. Default: true */
270
- enabled?: boolean
271
- }
272
-
273
- /** Alias for UseFrameNextOptions */
274
- type UseFrameOptions = UseFrameNextOptions
275
-
276
- /**
277
- * Options for addPhase
278
- */
279
- interface AddPhaseOptions {
280
- /** Insert this phase before the specified phase */
281
- before?: string
282
- /** Insert this phase after the specified phase */
283
- after?: string
284
- }
285
-
286
- // Frame State --------------------------------
287
-
288
- /**
289
- * Timing-only state for independent/outside mode (no RootState)
290
- */
291
- interface FrameTimingState {
292
- /** High-resolution timestamp from RAF (ms) */
293
- time: number
294
- /** Time since last frame in seconds (for legacy compatibility with THREE.Clock) */
295
- delta: number
296
- /** Elapsed time since first frame in seconds (for legacy compatibility with THREE.Clock) */
297
- elapsed: number
298
- /** Incrementing frame counter */
299
- frame: number
300
- }
301
-
302
- /**
303
- * State passed to useFrame callbacks (extends RootState with timing)
304
- */
305
- interface FrameNextState extends RootState, FrameTimingState {}
306
-
307
- /** Alias for FrameNextState */
308
- type FrameState = FrameNextState
309
-
310
- // Root Options --------------------------------
311
-
312
- /**
313
- * Options for registerRoot
314
- */
315
- interface RootOptions {
316
- /** State provider for callbacks. Optional in independent mode. */
317
- getState?: () => any
318
- /** Error handler for job errors. Falls back to console.error if not provided. */
319
- onError?: (error: Error) => void
320
- }
321
-
322
- // Callback Types --------------------------------
323
-
324
- /**
325
- * Callback function for useFrame
326
- */
327
- type FrameNextCallback = (state: FrameNextState, delta: number) => void
328
-
329
- /** Alias for FrameNextCallback */
330
- type FrameCallback = FrameNextCallback
331
-
332
- // Controls returned from useFrame --------------------------------
333
-
334
- /**
335
- * Controls object returned from useFrame hook
336
- */
337
- interface FrameNextControls {
338
- /** The job's unique ID */
339
- id: string
340
- /** Access to the global scheduler for frame loop control */
341
- scheduler: SchedulerApi
342
- /** Manually step this job only (bypasses FPS limiting) */
343
- step(timestamp?: number): void
344
- /** Manually step ALL jobs in the scheduler */
345
- stepAll(timestamp?: number): void
346
- /** Pause this job (set enabled=false) */
347
- pause(): void
348
- /** Resume this job (set enabled=true) */
349
- resume(): void
350
- /** Reactive paused state - automatically triggers re-render when changed */
351
- isPaused: boolean
352
- }
353
-
354
- /** Alias for FrameNextControls */
355
- type FrameControls = FrameNextControls
356
-
357
- // Scheduler Interface --------------------------------
358
-
359
- /**
360
- * Public interface for the global Scheduler
361
- */
362
- interface SchedulerApi {
363
- //* Phase Management --------------------------------
364
-
365
- /** Add a named phase to the scheduler */
366
- addPhase(name: string, options?: AddPhaseOptions): void
367
- /** Get the ordered list of phase names */
368
- readonly phases: string[]
369
- /** Check if a phase exists */
370
- hasPhase(name: string): boolean
371
-
372
- //* Root Management --------------------------------
373
-
374
- /** Register a root (Canvas) with the scheduler. Returns unsubscribe function. */
375
- registerRoot(id: string, options?: RootOptions): () => void
376
- /** Unregister a root */
377
- unregisterRoot(id: string): void
378
- /** Generate a unique root ID */
379
- generateRootId(): string
380
- /** Get the number of registered roots */
381
- getRootCount(): number
382
- /** Check if any root is registered and ready */
383
- readonly isReady: boolean
384
- /** Subscribe to root-ready event. Fires immediately if already ready. Returns unsubscribe. */
385
- onRootReady(callback: () => void): () => void
386
-
387
- //* Job Registration --------------------------------
388
-
389
- /** Register a job with the scheduler (returns unsubscribe function) */
390
- register(
391
- callback: FrameNextCallback,
392
- options?: {
393
- id?: string
394
- rootId?: string
395
- phase?: string
396
- before?: string | string[]
397
- after?: string | string[]
398
- priority?: number
399
- fps?: number
400
- drop?: boolean
401
- enabled?: boolean
402
- },
403
- ): () => void
404
- /** Update a job's options */
405
- updateJob(
406
- id: string,
407
- options: {
408
- priority?: number
409
- fps?: number
410
- drop?: boolean
411
- enabled?: boolean
412
- phase?: string
413
- before?: string | string[]
414
- after?: string | string[]
415
- },
416
- ): void
417
- /** Unregister a job by ID */
418
- unregister(id: string, rootId?: string): void
419
- /** Get the number of registered jobs */
420
- getJobCount(): number
421
- /** Get all job IDs */
422
- getJobIds(): string[]
423
-
424
- //* Global Jobs (for legacy addEffect/addAfterEffect) --------------------------------
425
-
426
- /** Register a global job (runs once per frame, not per-root). Returns unsubscribe function. */
427
- registerGlobal(phase: 'before' | 'after', id: string, callback: (timestamp: number) => void): () => void
428
-
429
- //* Idle Callbacks (for legacy addTail) --------------------------------
430
-
431
- /** Register an idle callback (fires when loop stops). Returns unsubscribe function. */
432
- onIdle(callback: (timestamp: number) => void): () => void
433
-
434
- //* Frame Loop Control --------------------------------
435
-
436
- /** Start the scheduler loop */
437
- start(): void
438
- /** Stop the scheduler loop */
439
- stop(): void
440
- /** Check if the scheduler is running */
441
- readonly isRunning: boolean
442
- /** Get/set the frameloop mode ('always', 'demand', 'never') */
443
- frameloop: Frameloop
444
- /** Independent mode - runs without Canvas, callbacks receive timing-only state */
445
- independent: boolean
446
-
447
- //* Manual Stepping --------------------------------
448
-
449
- /** Manually step all jobs once (for frameloop='never' or testing) */
450
- step(timestamp?: number): void
451
- /** Manually step a single job by ID */
452
- stepJob(id: string, timestamp?: number): void
453
- /** Request frame(s) to be rendered (for frameloop='demand') */
454
- invalidate(frames?: number): void
455
-
456
- //* Per-Job Control --------------------------------
457
-
458
- /** Check if a job is paused */
459
- isJobPaused(id: string): boolean
460
- /** Pause a job */
461
- pauseJob(id: string): void
462
- /** Resume a job */
463
- resumeJob(id: string): void
464
- /** Subscribe to job state changes (for reactive isPaused). Returns unsubscribe function. */
465
- subscribeJobState(id: string, listener: () => void): () => void
466
- }
467
-
468
- //* Core Store Types ========================================
469
-
470
- type Subscription = {
471
- ref: React$1.RefObject<RenderCallback>
472
- priority: number
473
- store: RootStore
474
- }
475
-
476
- type Dpr = number | [min: number, max: number]
477
-
478
- interface Size {
479
- width: number
480
- height: number
481
- top: number
482
- left: number
483
- }
484
-
485
- type Frameloop = 'always' | 'demand' | 'never'
486
-
487
- interface Viewport extends Size {
488
- /** The initial pixel ratio */
489
- initialDpr: number
490
- /** Current pixel ratio */
491
- dpr: number
492
- /** size.width / viewport.width */
493
- factor: number
494
- /** Camera distance */
495
- distance: number
496
- /** Camera aspect ratio: width / height */
497
- aspect: number
498
- }
499
-
500
- type RenderCallback = (state: RootState, delta: number, frame?: XRFrame) => void
501
-
502
- interface Performance {
503
- /** Current performance normal, between min and max */
504
- current: number
505
- /** How low the performance can go, between 0 and max */
506
- min: number
507
- /** How high the performance can go, between min and max */
508
- max: number
509
- /** Time until current returns to max in ms */
510
- debounce: number
511
- /** Sets current to min, puts the system in regression */
512
- regress: () => void
513
- }
514
-
515
- interface InternalState {
516
- interaction: THREE$1.Object3D[]
517
- hovered: Map<string, ThreeEvent<DomEvent>>
518
- subscribers: Subscription[]
519
- capturedMap: Map<number, Map<THREE$1.Object3D, PointerCaptureTarget>>
520
- initialClick: [x: number, y: number]
521
- initialHits: THREE$1.Object3D[]
522
- lastEvent: React$1.RefObject<DomEvent | null>
523
- /** Visibility event registry (onFramed, onOccluded, onVisible) */
524
- visibilityRegistry: Map<string, VisibilityEntry>
525
- /** Whether occlusion queries are enabled (WebGPU only) */
526
- occlusionEnabled: boolean
527
- /** Reference to the invisible occlusion observer mesh */
528
- occlusionObserver: THREE$1.Mesh | null
529
- /** Cached occlusion results from render pass - keyed by Object3D */
530
- occlusionCache: Map<THREE$1.Object3D, boolean | null>
531
- /** Internal helper group for R3F system objects (occlusion observer, etc.) */
532
- helperGroup: THREE$1.Group | null
533
- active: boolean
534
- priority: number
535
- frames: number
536
- subscribe: (callback: React$1.RefObject<RenderCallback>, priority: number, store: RootStore) => () => void
537
- /** Internal renderer storage - use state.renderer or state.gl to access */
538
- actualRenderer: THREE$1.WebGLRenderer | any // WebGPURenderer when available
539
- /** Global scheduler reference (for useFrame hook) */
540
- scheduler: SchedulerApi | null
541
- /** This root's unique ID in the global scheduler */
542
- rootId?: string
543
- /** Function to unregister this root from the global scheduler */
544
- unregisterRoot?: () => void
545
- /** Container for child attachment (scene for root, original container for portals) */
546
- container?: THREE$1.Object3D
547
- }
548
-
549
- interface XRManager {
550
- connect: () => void
551
- disconnect: () => void
552
- }
553
-
554
- //* Root State Interface ====================================
555
-
556
- interface RootState {
557
- /** Set current state */
558
- set: StoreApi<RootState>['setState']
559
- /** Get current state */
560
- get: StoreApi<RootState>['getState']
561
- /** (deprecated) The instance of the WebGLrenderer */
562
- gl: THREE$1.WebGLRenderer
563
- /** The instance of the WebGPU renderer, the fallback, OR the default renderer as a mask of gl */
564
- renderer: THREE$1.WebGLRenderer | any // WebGPURenderer when available
565
- /** Inspector of the webGPU Renderer. Init in the canvas */
566
- inspector: any // Inspector type from three/webgpu
567
-
568
- /** Default camera */
569
- camera: ThreeCamera
570
- /** Camera frustum for visibility checks - auto-updated each frame when autoUpdateFrustum is true */
571
- frustum: THREE$1.Frustum
572
- /** Whether to automatically update the frustum each frame (default: true) */
573
- autoUpdateFrustum: boolean
574
- /** Default scene (may be overridden in portals to point to the portal container) */
575
- scene: THREE$1.Scene
576
- /** The actual root THREE.Scene - always points to the true scene, even inside portals */
577
- rootScene: THREE$1.Scene
578
- /** Default raycaster */
579
- raycaster: THREE$1.Raycaster
580
- /** Event layer interface, contains the event handler and the node they're connected to */
581
- events: EventManager<any>
582
- /** XR interface */
583
- xr: XRManager
584
- /** Currently used controls */
585
- controls: THREE$1.EventDispatcher | null
586
- /** Normalized event coordinates */
587
- pointer: THREE$1.Vector2
588
- /** @deprecated Normalized event coordinates, use "pointer" instead! */
589
- mouse: THREE$1.Vector2
590
- /* Whether to enable r139's THREE.ColorManagement */
591
- legacy: boolean
592
- /** Shortcut to gl.outputColorSpace = THREE.LinearSRGBColorSpace */
593
- linear: boolean
594
- /** Shortcut to gl.toneMapping = NoTonemapping */
595
- flat: boolean
596
- /** Color space assigned to 8-bit input textures (color maps). Most textures are authored in sRGB. */
597
- textureColorSpace: THREE$1.ColorSpace
598
- /** Render loop flags */
599
- frameloop: Frameloop
600
- performance: Performance
601
- /** Reactive pixel-size of the canvas */
602
- size: Size
603
- /** Reactive size of the viewport in threejs units */
604
- viewport: Viewport & {
605
- getCurrentViewport: (
606
- camera?: ThreeCamera,
607
- target?: THREE$1.Vector3 | Parameters<THREE$1.Vector3['set']>,
608
- size?: Size,
609
- ) => Omit<Viewport, 'dpr' | 'initialDpr'>
610
- }
611
- /** Flags the canvas for render, but doesn't render in itself */
612
- invalidate: (frames?: number, stackFrames?: boolean) => void
613
- /** Advance (render) one step */
614
- advance: (timestamp: number, runGlobalEffects?: boolean) => void
615
- /** Shortcut to setting the event layer */
616
- setEvents: (events: Partial<EventManager<any>>) => void
617
- /** Shortcut to manual sizing */
618
- setSize: (width: number, height: number, top?: number, left?: number) => void
619
- /** Shortcut to manual setting the pixel ratio */
620
- setDpr: (dpr: Dpr) => void
621
- /** Shortcut to setting frameloop flags */
622
- setFrameloop: (frameloop: Frameloop) => void
623
- /** Set error state to propagate to error boundary */
624
- setError: (error: Error | null) => void
625
- /** Current error state (null when no error) */
626
- error: Error | null
627
- /** Global TSL uniform nodes - root-level uniforms + scoped sub-objects. Use useUniforms() hook */
628
- uniforms: UniformStore
629
- /** Global TSL nodes - root-level nodes + scoped sub-objects. Use useNodes() hook */
630
- nodes: Record<string, any>
631
- /** Global TSL texture nodes - use useTextures() hook for operations */
632
- textures: Map<string, any>
633
- /** WebGPU PostProcessing instance - use usePostProcessing() hook */
634
- postProcessing: any | null // THREE.PostProcessing when available
635
- /** Global TSL pass nodes for post-processing - use usePostProcessing() hook */
636
- passes: Record<string, any>
637
- /** When the canvas was clicked but nothing was hit */
638
- onPointerMissed?: (event: MouseEvent) => void
639
- /** When a dragover event has missed any target */
640
- onDragOverMissed?: (event: DragEvent) => void
641
- /** When a drop event has missed any target */
642
- onDropMissed?: (event: DragEvent) => void
643
- /** If this state model is layered (via createPortal) then this contains the previous layer */
644
- previousRoot?: RootStore
645
- /** Internals */
646
- internal: InternalState
647
- // flags for triggers
648
- // if we are using the webGl renderer, this will be true
649
- isLegacy: boolean
650
- // regardless of renderer, if the system supports webGpu, this will be true
651
- webGPUSupported: boolean
652
- //if we are on native
653
- isNative: boolean
654
- }
655
-
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
+
656
834
  type RootStore = UseBoundStoreWithEqualityFn<StoreApi<RootState>>
657
835
 
658
- //* Base Renderer Types =====================================
659
-
660
- // Shim for OffscreenCanvas since it was removed from DOM types
661
- interface OffscreenCanvas$1 extends EventTarget {}
662
-
663
- interface BaseRendererProps {
664
- canvas: HTMLCanvasElement | OffscreenCanvas$1
665
- powerPreference?: 'high-performance' | 'low-power' | 'default'
666
- antialias?: boolean
667
- alpha?: boolean
668
- }
669
-
670
- type RendererFactory<TRenderer, TParams> =
671
- | TRenderer
672
- | ((defaultProps: TParams) => TRenderer)
673
- | ((defaultProps: TParams) => Promise<TRenderer>)
674
-
675
- interface Renderer {
676
- render: (scene: THREE$1.Scene, camera: THREE$1.Camera) => any
677
- }
678
-
679
- //* WebGL Renderer Props ==============================
680
-
681
- type DefaultGLProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & {
682
- canvas: HTMLCanvasElement | OffscreenCanvas$1
683
- }
684
-
685
- type GLProps =
686
- | Renderer
687
- | ((defaultProps: DefaultGLProps) => Renderer)
688
- | ((defaultProps: DefaultGLProps) => Promise<Renderer>)
689
- | Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters>
690
-
691
- //* WebGPU Renderer Props ==============================
692
-
693
- type DefaultRendererProps = {
694
- canvas: HTMLCanvasElement | OffscreenCanvas$1
695
- [key: string]: any
696
- }
697
-
698
- type RendererProps =
699
- | any // WebGPURenderer
700
- | ((defaultProps: DefaultRendererProps) => any)
701
- | ((defaultProps: DefaultRendererProps) => Promise<any>)
702
- | Partial<Properties<any> | Record<string, any>>
703
-
704
- //* Camera Props ==============================
705
-
706
- type CameraProps = (
707
- | THREE$1.Camera
708
- | Partial<
709
- ThreeElement<typeof THREE$1.Camera> &
710
- ThreeElement<typeof THREE$1.PerspectiveCamera> &
711
- ThreeElement<typeof THREE$1.OrthographicCamera>
712
- >
713
- ) & {
714
- /** Flags the camera as manual, putting projection into your own hands */
715
- manual?: boolean
716
- }
717
-
718
- //* Render Props ==============================
719
-
720
- interface RenderProps<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
721
- /** A threejs renderer instance or props that go into the default renderer */
722
- gl?: GLProps
723
- /** A WebGPU renderer instance or props that go into the default renderer */
724
- renderer?: RendererProps
725
- /** Dimensions to fit the renderer to. Will measure canvas dimensions if omitted */
726
- size?: Size
727
- /**
728
- * Enables shadows (by default PCFsoft). Can accept `gl.shadowMap` options for fine-tuning,
729
- * but also strings: 'basic' | 'percentage' | 'soft' | 'variance'.
730
- * @see https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
731
- */
732
- shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
733
- /**
734
- * Disables three r139 color management.
735
- * @see https://threejs.org/docs/#manual/en/introduction/Color-management
736
- */
737
- legacy?: boolean
738
- /** Switch off automatic sRGB encoding and gamma correction */
739
- linear?: boolean
740
- /** Use `THREE.NoToneMapping` instead of `THREE.ACESFilmicToneMapping` */
741
- flat?: boolean
742
- /** Working color space for automatic texture colorspace assignment. Defaults to THREE.SRGBColorSpace */
743
- /** Color space assigned to 8-bit input textures (color maps). Defaults to sRGB. Most textures are authored in sRGB. */
744
- textureColorSpace?: THREE$1.ColorSpace
745
- /** Creates an orthographic camera */
746
- orthographic?: boolean
747
- /**
748
- * R3F's render mode. Set to `demand` to only render on state change or `never` to take control.
749
- * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#on-demand-rendering
750
- */
751
- frameloop?: Frameloop
752
- /**
753
- * R3F performance options for adaptive performance.
754
- * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#movement-regression
755
- */
756
- performance?: Partial<Omit<Performance, 'regress'>>
757
- /** Target pixel ratio. Can clamp between a range: `[min, max]` */
758
- dpr?: Dpr
759
- /** Props that go into the default raycaster */
760
- raycaster?: Partial<THREE$1.Raycaster>
761
- /** A `THREE.Scene` instance or props that go into the default scene */
762
- scene?: THREE$1.Scene | Partial<THREE$1.Scene>
763
- /** A `THREE.Camera` instance or props that go into the default camera */
764
- camera?: CameraProps
765
- /** An R3F event manager to manage elements' pointer events */
766
- events?: (store: RootStore) => EventManager<HTMLElement>
767
- /** Callback after the canvas has rendered (but not yet committed) */
768
- onCreated?: (state: RootState) => void
769
- /** Response for pointer clicks that have missed any target */
770
- onPointerMissed?: (event: MouseEvent) => void
771
- /** Response for dragover events that have missed any target */
772
- onDragOverMissed?: (event: DragEvent) => void
773
- /** Response for drop events that have missed any target */
774
- onDropMissed?: (event: DragEvent) => void
775
- /** Whether to automatically update the frustum each frame (default: true) */
776
- autoUpdateFrustum?: boolean
777
- /**
778
- * Enable WebGPU occlusion queries for onOccluded/onVisible events.
779
- * Auto-enabled when any object uses onOccluded or onVisible handlers.
780
- * Only works with WebGPU renderer - WebGL will log a warning.
781
- */
782
- occlusion?: boolean
783
- }
784
-
785
- //* Reconciler Root ==============================
786
-
787
- interface ReconcilerRoot<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
788
- configure: (config?: RenderProps<TCanvas>) => Promise<ReconcilerRoot<TCanvas>>
789
- render: (element: ReactNode) => RootStore
790
- unmount: () => void
791
- }
792
-
793
- //* Inject State ==============================
794
-
795
- type InjectState = Partial<
796
- Omit<RootState, 'events'> & {
797
- events?: {
798
- enabled?: boolean
799
- priority?: number
800
- compute?: ComputeFunction
801
- connected?: any
802
- }
803
- /**
804
- * When true (default), injects a THREE.Scene between container and children if container isn't already a Scene.
805
- * This ensures state.scene is always a real THREE.Scene with proper properties (background, environment, fog).
806
- * Set to false to use the container directly as scene (anti-pattern, but supported for edge cases).
807
- */
808
- injectScene?: boolean
809
- }
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
+ }
810
1043
  >
811
1044
 
812
- //* Reconciler Types ==============================
813
-
814
- interface Root {
815
- fiber: react_reconciler.FiberRoot
816
- store: RootStore
817
- }
818
-
819
- type AttachFnType<O = any> = (parent: any, self: O) => () => void
820
- type AttachType<O = any> = string | AttachFnType<O>
821
-
822
- type ConstructorRepresentation<T = any> = new (...args: any[]) => T
823
-
824
- interface Catalogue {
825
- [name: string]: ConstructorRepresentation
826
- }
827
-
828
- // TODO: handle constructor overloads
829
- // https://github.com/pmndrs/react-three-fiber/pull/2931
830
- // https://github.com/microsoft/TypeScript/issues/37079
831
- type Args<T> = T extends ConstructorRepresentation
832
- ? T extends typeof Color$1
833
- ? [r: number, g: number, b: number] | [color: ColorRepresentation]
834
- : ConstructorParameters<T>
835
- : any[]
836
-
837
- type ArgsProp<P> = P extends ConstructorRepresentation
838
- ? IsAllOptional<ConstructorParameters<P>> extends true
839
- ? { args?: Args<P> }
840
- : { args: Args<P> }
841
- : { args: unknown[] }
842
-
843
- type InstanceProps<T = any, P = any> = ArgsProp<P> & {
844
- object?: T
845
- dispose?: null
846
- attach?: AttachType<T>
847
- onUpdate?: (self: T) => void
848
- }
849
-
850
- interface Instance<O = any> {
851
- root: RootStore
852
- type: string
853
- parent: Instance | null
854
- children: Instance[]
855
- props: InstanceProps<O> & Record<string, unknown>
856
- object: O & { __r3f?: Instance<O> }
857
- eventCount: number
858
- handlers: Partial<EventHandlers>
859
- attach?: AttachType<O>
860
- previousAttach?: any
861
- isHidden: boolean
862
- }
863
-
864
- interface HostConfig {
865
- type: string
866
- props: Instance['props']
867
- container: RootStore
868
- instance: Instance
869
- textInstance: void
870
- suspenseInstance: Instance
871
- hydratableInstance: never
872
- formInstance: never
873
- publicInstance: Instance['object']
874
- hostContext: {}
875
- childSet: never
876
- timeoutHandle: number | undefined
877
- noTimeout: -1
878
- TransitionStatus: null
879
- }
880
- declare global {
881
- var IS_REACT_ACT_ENVIRONMENT: boolean | undefined
882
- }
883
-
884
- //* Loop Types ==============================
885
-
886
- type GlobalRenderCallback = (timestamp: number) => void
887
-
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
+
888
1129
  type GlobalEffectType = 'before' | 'after' | 'tail'
889
1130
 
890
- //* Canvas Types ==============================
891
-
892
- interface CanvasProps
893
- extends Omit<RenderProps<HTMLCanvasElement>, 'size'>,
894
- React$1.HTMLAttributes<HTMLDivElement> {
895
- children?: React$1.ReactNode
896
- ref?: React$1.Ref<HTMLCanvasElement>
897
- /** Canvas fallback content, similar to img's alt prop */
898
- fallback?: React$1.ReactNode
899
- /**
900
- * Options to pass to useMeasure.
901
- * @see https://github.com/pmndrs/react-use-measure#api
902
- */
903
- resize?: Options
904
- /** The target where events are being subscribed to, default: the div that wraps canvas */
905
- eventSource?: HTMLElement | React$1.RefObject<HTMLElement>
906
- /** The event prefix that is cast into canvas pointer x/y events, default: "offset" */
907
- eventPrefix?: 'offset' | 'client' | 'page' | 'layer' | 'screen'
908
- }
909
-
910
- //* Loader Types ==============================
911
-
912
- type InputLike = string | string[] | string[][] | Readonly<string | string[] | string[][]>
913
-
914
- // Define a loader-like interface that matches THREE.Loader's load signature
915
- // This works for both generic and non-generic THREE.Loader instances
916
- interface LoaderLike {
917
- load(
918
- url: InputLike,
919
- onLoad?: (result: any) => void,
920
- onProgress?: (event: ProgressEvent<EventTarget>) => void,
921
- onError?: (error: unknown) => void,
922
- ): any
923
- }
924
-
925
- type GLTFLike = { scene: THREE$1.Object3D }
926
-
927
- type LoaderInstance<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
928
- T extends ConstructorRepresentation<LoaderLike> ? InstanceType<T> : T
929
-
930
- // Infer result type from the load method's callback parameter
931
- type InferLoadResult<T> = T extends {
932
- load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
933
- }
934
- ? R
935
- : T extends ConstructorRepresentation<any>
936
- ? InstanceType<T> extends {
937
- load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
938
- }
939
- ? R
940
- : any
941
- : any
942
-
943
- type LoaderResult<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> = InferLoadResult<
944
- LoaderInstance<T>
945
- > extends infer R
946
- ? R extends GLTFLike
947
- ? R & ObjectMap
948
- : R
949
- : never
950
-
951
- type Extensions<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> = (
952
- 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>,
953
1283
  ) => void
954
1284
 
955
- type WebGLDefaultProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & BaseRendererProps
956
-
957
- type WebGLProps =
958
- | RendererFactory<THREE$1.WebGLRenderer, WebGLDefaultProps>
959
- | Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters>
960
-
961
- interface WebGLShadowConfig {
962
- 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
963
1305
  }
964
1306
 
965
- //* RenderTarget Types ==============================
966
-
967
-
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
+
968
1332
  type RenderTargetOptions = RenderTargetOptions$1
969
1333
 
970
- //* Global Types ==============================
971
-
972
- declare global {
973
- /** Uniform node type - a Node with a value property (matches Three.js UniformNode) */
974
- interface UniformNode<T = unknown> extends Node {
975
- value: T
976
- }
977
-
978
- /** Flat record of uniform nodes (no nested scopes) */
979
- type UniformRecord<T extends UniformNode = UniformNode> = Record<string, T>
980
-
981
- /**
982
- * Uniform store that can contain both root-level uniforms and scoped uniform objects
983
- * Used by state.uniforms which has structure like:
984
- * { uTime: UniformNode, player: { uHealth: UniformNode }, enemy: { uHealth: UniformNode } }
985
- */
986
- type UniformStore = Record<string, UniformNode | UniformRecord>
987
-
988
- /**
989
- * Helper to safely access a uniform node from the store.
990
- * Use this when accessing state.uniforms to get proper typing.
991
- * @example
992
- * const uTime = uniforms.uTime as UniformNode<number>
993
- * const uColor = uniforms.uColor as UniformNode<import('three/webgpu').Color>
994
- */
995
- type GetUniform<T = unknown> = UniformNode<T>
996
-
997
- /**
998
- * Acceptable input values for useUniforms - raw values that get converted to UniformNodes
999
- * Supports: primitives, Three.js types, plain objects (converted to vectors), and UniformNodes
1000
- */
1001
- type UniformValue =
1002
- | number
1003
- | string
1004
- | boolean
1005
- | three_webgpu.Color
1006
- | three_webgpu.Vector2
1007
- | three_webgpu.Vector3
1008
- | three_webgpu.Vector4
1009
- | three_webgpu.Matrix3
1010
- | three_webgpu.Matrix4
1011
- | three_webgpu.Euler
1012
- | three_webgpu.Quaternion
1013
- | { x: number; y?: number; z?: number; w?: number } // Plain objects converted to vectors
1014
- | UniformNode
1015
-
1016
- /** Input record for useUniforms - accepts raw values or UniformNodes */
1017
- type UniformInputRecord = Record<string, UniformValue>
1018
- }
1019
-
1020
- //* Fn Return Type ==============================
1021
-
1022
- /** The return type of Fn() - a callable shader function node */
1023
- type ShaderCallable<R extends Node = Node> = ((...params: unknown[]) => ShaderNodeObject<R>) & Node
1024
-
1025
- //* Module Augmentation ==============================
1026
-
1027
- declare module 'three/tsl' {
1028
- /**
1029
- * Fn with array parameter destructuring
1030
- * @example Fn(([uv, skew]) => { ... })
1031
- */
1032
- export function Fn<R extends Node = Node>(
1033
- jsFunc: (inputs: ShaderNodeObject<Node>[]) => ShaderNodeObject<R>,
1034
- ): ShaderCallable<R>
1035
-
1036
- /**
1037
- * Fn with object parameter destructuring
1038
- * @example Fn(({ color, intensity }) => { ... })
1039
- */
1040
- export function Fn<T extends Record<string, unknown>, R extends Node = Node>(
1041
- jsFunc: (inputs: T) => ShaderNodeObject<R>,
1042
- ): ShaderCallable<R>
1043
-
1044
- /**
1045
- * Fn with array params + layout
1046
- * @example Fn(([a, b]) => { ... }, { layout: [...] })
1047
- */
1048
- export function Fn<R extends Node = Node>(
1049
- jsFunc: (inputs: ShaderNodeObject<Node>[]) => ShaderNodeObject<R>,
1050
- layout: { layout?: unknown },
1051
- ): ShaderCallable<R>
1052
-
1053
- /**
1054
- * Fn with object params + layout
1055
- */
1056
- export function Fn<T extends Record<string, unknown>, R extends Node = Node>(
1057
- jsFunc: (inputs: T) => ShaderNodeObject<R>,
1058
- layout: { layout?: unknown },
1059
- ): ShaderCallable<R>
1060
- }
1061
-
1062
- /**
1063
- * PostProcessing Types for usePostProcessing hook (WebGPU only)
1064
- */
1065
-
1066
-
1067
-
1068
- declare global {
1069
- /** Pass record - stores TSL pass nodes for post-processing */
1070
- type PassRecord = Record<string, any>
1071
-
1072
- /** Setup callback - runs first to configure MRT, create additional passes */
1073
- type PostProcessingSetupCallback = (state: RootState) => PassRecord | void
1074
-
1075
- /** Main callback - runs second to configure outputNode, create effect passes */
1076
- type PostProcessingMainCallback = (state: RootState) => PassRecord | void
1077
-
1078
- /** Return type for usePostProcessing hook */
1079
- interface UsePostProcessingReturn {
1080
- /** Current passes from state */
1081
- passes: PassRecord
1082
- /** PostProcessing instance (null if not initialized) */
1083
- postProcessing: any | null // THREE.PostProcessing
1084
- /** Clear all passes from state */
1085
- clearPasses: () => void
1086
- /** Reset PostProcessing entirely (clears PP + passes) */
1087
- reset: () => void
1088
- /** Re-run setup/main callbacks with current closure values */
1089
- rebuild: () => void
1090
- /** True when PostProcessing is configured and ready */
1091
- isReady: boolean
1092
- }
1093
- }
1094
-
1095
- //* useFrameNext Types ==============================
1096
-
1097
-
1098
-
1099
- //* Global Type Declarations ==============================
1100
-
1101
- declare global {
1102
- // Job --------------------------------
1103
-
1104
- /**
1105
- * Internal job representation in the scheduler
1106
- */
1107
- interface Job {
1108
- /** Unique identifier */
1109
- id: string
1110
- /** The callback to execute */
1111
- callback: FrameNextCallback
1112
- /** Phase this job belongs to */
1113
- phase: string
1114
- /** Run before these phases/job ids */
1115
- before: Set<string>
1116
- /** Run after these phases/job ids */
1117
- after: Set<string>
1118
- /** Priority within phase (higher first) */
1119
- priority: number
1120
- /** Insertion order for deterministic tie-breaking */
1121
- index: number
1122
- /** Max FPS for this job (undefined = no limit) */
1123
- fps?: number
1124
- /** Drop frames when behind (true) or catch up (false) */
1125
- drop: boolean
1126
- /** Last run timestamp (ms) */
1127
- lastRun?: number
1128
- /** Whether job is enabled */
1129
- enabled: boolean
1130
- /** Internal flag: system jobs (like default render) don't block user render takeover */
1131
- system?: boolean
1132
- }
1133
-
1134
- // Phase Graph --------------------------------
1135
-
1136
- /**
1137
- * A node in the phase graph
1138
- */
1139
- interface PhaseNode {
1140
- /** Phase name */
1141
- name: string
1142
- /** Whether this was auto-generated from a before/after constraint */
1143
- isAutoGenerated: boolean
1144
- }
1145
-
1146
- /**
1147
- * Options for creating a job from hook options
1148
- */
1149
- interface JobOptions {
1150
- id?: string
1151
- phase?: string
1152
- before?: string | string[]
1153
- after?: string | string[]
1154
- priority?: number
1155
- fps?: number
1156
- drop?: boolean
1157
- enabled?: boolean
1158
- }
1159
-
1160
- // Frame Loop State --------------------------------
1161
-
1162
- /**
1163
- * Internal frame loop state
1164
- */
1165
- interface FrameLoopState {
1166
- /** Whether the loop is running */
1167
- running: boolean
1168
- /** Current RAF handle */
1169
- rafHandle: number | null
1170
- /** Last frame timestamp in ms (null = uninitialized) */
1171
- lastTime: number | null
1172
- /** Frame counter */
1173
- frameCount: number
1174
- /** Elapsed time since first frame in ms */
1175
- elapsedTime: number
1176
- /** createdAt timestamp in ms */
1177
- createdAt: number
1178
- }
1179
-
1180
- // Root Entry --------------------------------
1181
-
1182
- /**
1183
- * Internal representation of a registered root (Canvas).
1184
- * Tracks jobs and manages rebuild state for this root.
1185
- * @internal
1186
- */
1187
- interface RootEntry {
1188
- /** Unique identifier for this root */
1189
- id: string
1190
- /** Function to get the root's current state. Returns any to support independent mode. */
1191
- getState: () => any
1192
- /** Map of job IDs to Job objects */
1193
- jobs: Map<string, Job>
1194
- /** Cached sorted job list for execution order */
1195
- sortedJobs: Job[]
1196
- /** Whether sortedJobs needs rebuilding */
1197
- needsRebuild: boolean
1198
- }
1199
-
1200
- /**
1201
- * Internal representation of a global job (deprecated API).
1202
- * Global jobs run once per frame, not per-root.
1203
- * Used by legacy addEffect/addAfterEffect APIs.
1204
- * @internal
1205
- * @deprecated Use useFrame with phases instead
1206
- */
1207
- interface GlobalJob {
1208
- /** Unique identifier for this global job */
1209
- id: string
1210
- /** Callback invoked with RAF timestamp in ms */
1211
- callback: (timestamp: number) => void
1212
- }
1213
-
1214
- // HMR Support --------------------------------
1215
-
1216
- /**
1217
- * Hot Module Replacement data structure for preserving scheduler state
1218
- * @internal
1219
- */
1220
- interface HMRData {
1221
- /** Shared data object for storing values across reloads */
1222
- data: Record<string, any>
1223
- /** Optional function to accept HMR updates */
1224
- accept?: () => void
1225
- }
1226
-
1227
- // Default Phases --------------------------------
1228
-
1229
- /**
1230
- * Default phase names for the scheduler
1231
- */
1232
- type DefaultPhase = 'start' | 'input' | 'physics' | 'update' | 'render' | 'finish'
1233
- }
1234
-
1235
- type MutableOrReadonlyParameters<T extends (...args: any) => any> = Parameters<T> | Readonly<Parameters<T>>
1236
-
1237
- interface MathRepresentation {
1238
- set(...args: number[]): any
1239
- }
1240
- interface VectorRepresentation extends MathRepresentation {
1241
- setScalar(value: number): any
1242
- }
1243
- type MathTypes = MathRepresentation | Euler$1 | Color$1
1244
-
1245
- type MathType<T extends MathTypes> = T extends Color$1
1246
- ? Args<typeof Color$1> | ColorRepresentation
1247
- : T extends VectorRepresentation | Layers$1 | Euler$1
1248
- ? T | MutableOrReadonlyParameters<T['set']> | number
1249
- : T | MutableOrReadonlyParameters<T['set']>
1250
-
1251
- type MathProps<P> = {
1252
- [K in keyof P as P[K] extends MathTypes ? K : never]: P[K] extends MathTypes ? MathType<P[K]> : never
1253
- }
1254
-
1255
- type Vector2 = MathType<Vector2$1>
1256
- type Vector3 = MathType<Vector3$1>
1257
- type Vector4 = MathType<Vector4$1>
1258
- type Color = MathType<Color$1>
1259
- type Layers = MathType<Layers$1>
1260
- type Quaternion = MathType<Quaternion$1>
1261
- type Euler = MathType<Euler$1>
1262
- type Matrix3 = MathType<Matrix3$1>
1263
- type Matrix4 = MathType<Matrix4$1>
1264
-
1265
- interface RaycastableRepresentation {
1266
- raycast(raycaster: Raycaster, intersects: Intersection$1[]): void
1267
- }
1268
- type EventProps<P> = P extends RaycastableRepresentation ? Partial<EventHandlers> : {}
1269
-
1270
- interface ReactProps<P> {
1271
- children?: React.ReactNode
1272
- ref?: React.Ref<P>
1273
- key?: React.Key
1274
- }
1275
-
1276
- type ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = Partial<
1277
- Overwrite<P, MathProps<P> & ReactProps<P> & EventProps<P>>
1278
- >
1279
-
1280
- type ThreeElement<T extends ConstructorRepresentation> = Mutable<
1281
- Overwrite<ElementProps<T>, Omit<InstanceProps<InstanceType<T>, T>, 'object'>>
1282
- >
1283
-
1284
- type ThreeToJSXElements<T extends Record<string, any>> = {
1285
- [K in keyof T & string as Uncapitalize<K>]: T[K] extends ConstructorRepresentation ? ThreeElement<T[K]> : never
1286
- }
1287
-
1288
- type ThreeExports = typeof THREE
1289
- type ThreeElementsImpl = ThreeToJSXElements<ThreeExports>
1290
-
1291
- interface ThreeElements extends Omit<ThreeElementsImpl, 'audio' | 'source' | 'line' | 'path'> {
1292
- primitive: Omit<ThreeElement<any>, 'args'> & { object: object }
1293
- // Conflicts with DOM types can be accessed through a three* prefix
1294
- threeAudio: ThreeElementsImpl['audio']
1295
- threeSource: ThreeElementsImpl['source']
1296
- threeLine: ThreeElementsImpl['line']
1297
- threePath: ThreeElementsImpl['path']
1298
- }
1299
-
1300
- declare module 'react' {
1301
- namespace JSX {
1302
- interface IntrinsicElements extends ThreeElements {}
1303
- }
1304
- }
1305
-
1306
- declare module 'react/jsx-runtime' {
1307
- namespace JSX {
1308
- interface IntrinsicElements extends ThreeElements {}
1309
- }
1310
- }
1311
-
1312
- declare module 'react/jsx-dev-runtime' {
1313
- namespace JSX {
1314
- interface IntrinsicElements extends ThreeElements {}
1315
- }
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
+ }
1316
1786
  }
1317
1787
 
1318
1788
  type three_d_Color = Color;
1319
1789
  type three_d_ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = ElementProps<T, P>;
1320
1790
  type three_d_Euler = Euler;
1321
1791
  type three_d_EventProps<P> = EventProps<P>;
1792
+ type three_d_GeometryProps<P> = GeometryProps<P>;
1793
+ type three_d_GeometryTransformProps = GeometryTransformProps;
1322
1794
  type three_d_Layers = Layers;
1323
1795
  type three_d_MathProps<P> = MathProps<P>;
1324
1796
  type three_d_MathRepresentation = MathRepresentation;
@@ -1327,9 +1799,11 @@ type three_d_MathTypes = MathTypes;
1327
1799
  type three_d_Matrix3 = Matrix3;
1328
1800
  type three_d_Matrix4 = Matrix4;
1329
1801
  type three_d_MutableOrReadonlyParameters<T extends (...args: any) => any> = MutableOrReadonlyParameters<T>;
1802
+ type three_d_NodeProps<P> = NodeProps<P>;
1330
1803
  type three_d_Quaternion = Quaternion;
1331
1804
  type three_d_RaycastableRepresentation = RaycastableRepresentation;
1332
1805
  type three_d_ReactProps<P> = ReactProps<P>;
1806
+ type three_d_TSLNodeInput = TSLNodeInput;
1333
1807
  type three_d_ThreeElement<T extends ConstructorRepresentation> = ThreeElement<T>;
1334
1808
  type three_d_ThreeElements = ThreeElements;
1335
1809
  type three_d_ThreeElementsImpl = ThreeElementsImpl;
@@ -1340,12 +1814,324 @@ type three_d_Vector3 = Vector3;
1340
1814
  type three_d_Vector4 = Vector4;
1341
1815
  type three_d_VectorRepresentation = VectorRepresentation;
1342
1816
  declare namespace three_d {
1343
- 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 };
1344
1818
  }
1345
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
+
1346
2130
  declare function removeInteractivity(store: RootStore, object: Object3D): void;
1347
2131
  declare function createEvents(store: RootStore): {
1348
2132
  handlePointer: (name: string) => (event: DomEvent) => void;
2133
+ flushDeferredPointers: () => void;
2134
+ processDeferredPointer: (event: DomEvent, pointerId: number) => void;
1349
2135
  };
1350
2136
  /** Default R3F event manager for web */
1351
2137
  declare function createPointerEvents(store: RootStore): EventManager<HTMLElement>;
@@ -1904,31 +2690,30 @@ declare function useTextures(): UseTexturesReturn;
1904
2690
  * - WebGPU build: Returns RenderTarget
1905
2691
  * - Default build: Returns whichever matches the active renderer
1906
2692
  *
1907
- * @param width - Target width (defaults to canvas width)
1908
- * @param height - Target height (defaults to canvas height)
1909
- * @param options - Three.js RenderTarget options
1910
- *
1911
2693
  * @example
1912
2694
  * ```tsx
1913
- * function PortalScene() {
1914
- * const fbo = useRenderTarget(512, 512, { depthBuffer: true })
1915
- *
1916
- * useFrame(({ renderer, scene, camera }) => {
1917
- * renderer.setRenderTarget(fbo)
1918
- * renderer.render(scene, camera)
1919
- * renderer.setRenderTarget(null)
1920
- * })
1921
- *
1922
- * return (
1923
- * <mesh>
1924
- * <planeGeometry />
1925
- * <meshBasicMaterial map={fbo.texture} />
1926
- * </mesh>
1927
- * )
1928
- * }
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 })
1929
2712
  * ```
1930
2713
  */
1931
- 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;
1932
2717
 
1933
2718
  /**
1934
2719
  * Returns the R3F Canvas' Zustand store. Useful for [transient updates](https://github.com/pmndrs/zustand#transient-updates-for-often-occurring-state-changes).
@@ -2033,7 +2818,7 @@ declare function invalidate(state?: RootState, frames?: number, stackFrames?: bo
2033
2818
  *
2034
2819
  * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#advance
2035
2820
  */
2036
- declare function advance(timestamp: number, runGlobalEffects?: boolean, state?: RootState, frame?: XRFrame): void;
2821
+ declare function advance(timestamp: number): void;
2037
2822
 
2038
2823
  /* eslint-disable @definitelytyped/no-unnecessary-generics */
2039
2824
  declare function ReactReconciler<
@@ -3087,6 +3872,12 @@ declare const _roots: Map<HTMLCanvasElement | OffscreenCanvas, Root>;
3087
3872
  declare function createRoot<TCanvas extends HTMLCanvasElement | OffscreenCanvas>(canvas: TCanvas): ReconcilerRoot<TCanvas>;
3088
3873
  declare function unmountComponentAtNode<TCanvas extends HTMLCanvasElement | OffscreenCanvas>(canvas: TCanvas, callback?: (canvas: TCanvas) => void): void;
3089
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;
3090
3881
  /**
3091
3882
  * Force React to flush any updates inside the provided callback synchronously and immediately.
3092
3883
  * All the same caveats documented for react-dom's `flushSync` apply here (see https://react.dev/reference/react-dom/flushSync).
@@ -3515,11 +4306,76 @@ declare const hasConstructor: (object: unknown) => object is {
3515
4306
  constructor?: Function;
3516
4307
  };
3517
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
+
3518
4374
  /**
3519
4375
  * A DOM canvas which accepts threejs elements as children.
3520
4376
  * @see https://docs.pmnd.rs/react-three-fiber/api/canvas
3521
4377
  */
3522
4378
  declare function Canvas(props: CanvasProps): react_jsx_runtime.JSX.Element;
3523
4379
 
3524
- 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 };
3525
- 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, 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 };