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

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.
@@ -1,15 +1,16 @@
1
1
  import * as three_webgpu from 'three/webgpu';
2
- import { RenderTarget, Node, ShaderNodeObject, Euler as Euler$1, Color as Color$2, ColorRepresentation as ColorRepresentation$1, Layers as Layers$1, Raycaster, Intersection as Intersection$1, Vector2 as Vector2$1, Vector3 as Vector3$1, Vector4 as Vector4$1, Quaternion as Quaternion$1, Matrix3 as Matrix3$1, Matrix4 as Matrix4$1, Object3D, Texture as Texture$1, Frustum, OrthographicCamera } from 'three/webgpu';
2
+ import { RenderTarget, WebGPURenderer, CanvasTarget, Node, ShaderNodeObject, Euler as Euler$2, Color as Color$2, ColorRepresentation as ColorRepresentation$1, Layers as Layers$1, Raycaster, Intersection as Intersection$1, BufferGeometry, Matrix4 as Matrix4$1, Quaternion as Quaternion$1, Vector2 as Vector2$1, Vector3 as Vector3$1, Vector4 as Vector4$1, Matrix3 as Matrix3$1, Loader as Loader$1, ColorSpace, Texture as Texture$1, CubeTexture, Scene, Object3D, Frustum, OrthographicCamera, WebGPURendererParameters } from 'three/webgpu';
3
3
  import { Inspector } from 'three/addons/inspector/Inspector.js';
4
4
  import * as THREE$1 from 'three';
5
- import { Color as Color$1, ColorRepresentation, RenderTargetOptions as RenderTargetOptions$1 } from 'three';
5
+ import { Color as Color$1, ColorRepresentation, Euler as Euler$1, Loader, RenderTargetOptions as RenderTargetOptions$1 } from 'three';
6
6
  import * as React$1 from 'react';
7
7
  import { ReactNode, Component, RefObject, JSX } from 'react';
8
8
  import { StoreApi } from 'zustand';
9
9
  import { UseBoundStoreWithEqualityFn } from 'zustand/traditional';
10
- 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';
11
10
  import { Options } from 'react-use-measure';
12
11
  import * as react_jsx_runtime from 'react/jsx-runtime';
12
+ import { ThreeElement as ThreeElement$1, Euler as Euler$3 } from '@react-three/fiber';
13
+ import { GroundedSkybox } from 'three/examples/jsm/objects/GroundedSkybox.js';
13
14
 
14
15
  function _mergeNamespaces(n, m) {
15
16
  m.forEach(function (e) {
@@ -58,1270 +59,1614 @@ var THREE = /*#__PURE__*/_mergeNamespaces({
58
59
  WebGLShadowMap: WebGLShadowMap
59
60
  }, [three_webgpu]);
60
61
 
61
- //* Utility Types ==============================
62
-
63
- type NonFunctionKeys<P> = { [K in keyof P]-?: P[K] extends Function ? never : K }[keyof P]
64
- type Overwrite<P, O> = Omit<P, NonFunctionKeys<O>> & O
65
- type Properties<T> = Pick<T, NonFunctionKeys<T>>
66
- type Mutable<P> = { [K in keyof P]: P[K] | Readonly<P[K]> }
67
- type IsOptional<T> = undefined extends T ? true : false
68
- type IsAllOptional<T extends any[]> = T extends [infer First, ...infer Rest]
69
- ? IsOptional<First> extends true
70
- ? IsAllOptional<Rest>
71
- : false
72
- : true
73
-
74
- //* Camera Types ==============================
75
-
76
- type ThreeCamera = (THREE$1.OrthographicCamera | THREE$1.PerspectiveCamera) & { manual?: boolean }
77
-
78
- //* Act Type ==============================
79
-
80
- type Act = <T = any>(cb: () => Promise<T>) => Promise<T>
81
-
82
- //* Bridge & Block Types ==============================
83
-
84
- type Bridge = React$1.FC<{ children?: React$1.ReactNode }>
85
-
86
- type SetBlock = false | Promise<null> | null
87
- type UnblockProps = { set: React$1.Dispatch<React$1.SetStateAction<SetBlock>>; children: React$1.ReactNode }
88
-
89
- //* Object Map Type ==============================
90
-
91
- interface ObjectMap {
92
- nodes: { [name: string]: THREE$1.Object3D }
93
- materials: { [name: string]: THREE$1.Material }
94
- meshes: { [name: string]: THREE$1.Mesh }
95
- }
96
-
97
- //* Equality Config ==============================
98
-
99
- interface EquConfig {
100
- /** Compare arrays by reference equality a === b (default), or by shallow equality */
101
- arrays?: 'reference' | 'shallow'
102
- /** Compare objects by reference equality a === b (default), or by shallow equality */
103
- objects?: 'reference' | 'shallow'
104
- /** If true the keys in both a and b must match 1:1 (default), if false a's keys must intersect b's */
105
- strict?: boolean
106
- }
107
-
108
- //* Disposable Type ==============================
109
-
110
- interface Disposable {
111
- type?: string
112
- dispose?: () => void
113
- }
114
-
115
- //* Event-related Types =====================================
116
-
117
- interface Intersection extends THREE$1.Intersection {
118
- /** The event source (the object which registered the handler) */
119
- eventObject: THREE$1.Object3D
120
- }
121
-
122
- type Camera = THREE$1.OrthographicCamera | THREE$1.PerspectiveCamera
123
-
124
- interface IntersectionEvent<TSourceEvent> extends Intersection {
125
- /** The event source (the object which registered the handler) */
126
- eventObject: THREE$1.Object3D
127
- /** An array of intersections */
128
- intersections: Intersection[]
129
- /** vec3.set(pointer.x, pointer.y, 0).unproject(camera) */
130
- unprojectedPoint: THREE$1.Vector3
131
- /** Normalized event coordinates */
132
- pointer: THREE$1.Vector2
133
- /** Delta between first click and this event */
134
- delta: number
135
- /** The ray that pierced it */
136
- ray: THREE$1.Ray
137
- /** The camera that was used by the raycaster */
138
- camera: Camera
139
- /** stopPropagation will stop underlying handlers from firing */
140
- stopPropagation: () => void
141
- /** The original host event */
142
- nativeEvent: TSourceEvent
143
- /** If the event was stopped by calling stopPropagation */
144
- stopped: boolean
145
- }
146
-
147
- type ThreeEvent<TEvent> = IntersectionEvent<TEvent> & Properties<TEvent>
148
- type DomEvent = PointerEvent | MouseEvent | WheelEvent
149
-
150
- /** DOM event handlers registered on the canvas element */
151
- interface Events {
152
- onClick: EventListener
153
- onContextMenu: EventListener
154
- onDoubleClick: EventListener
155
- onWheel: EventListener
156
- onPointerDown: EventListener
157
- onPointerUp: EventListener
158
- onPointerLeave: EventListener
159
- onPointerMove: EventListener
160
- onPointerCancel: EventListener
161
- onLostPointerCapture: EventListener
162
- onDragEnter: EventListener
163
- onDragLeave: EventListener
164
- onDragOver: EventListener
165
- onDrop: EventListener
166
- }
167
-
168
- /** Event handlers that can be attached to R3F objects (meshes, groups, etc.) */
169
- interface EventHandlers {
170
- onClick?: (event: ThreeEvent<MouseEvent>) => void
171
- onContextMenu?: (event: ThreeEvent<MouseEvent>) => void
172
- onDoubleClick?: (event: ThreeEvent<MouseEvent>) => void
173
- /** Fires continuously while dragging over the object */
174
- onDragOver?: (event: ThreeEvent<DragEvent>) => void
175
- /** Fires once when drag enters the object */
176
- onDragOverEnter?: (event: ThreeEvent<DragEvent>) => void
177
- /** Fires once when drag leaves the object */
178
- onDragOverLeave?: (event: ThreeEvent<DragEvent>) => void
179
- /** Fires when drag misses this object (for objects that have drag handlers) */
180
- onDragOverMissed?: (event: DragEvent) => void
181
- /** Fires when a drop occurs on this object */
182
- onDrop?: (event: ThreeEvent<DragEvent>) => void
183
- /** Fires when a drop misses this object (for objects that have drop handlers) */
184
- onDropMissed?: (event: DragEvent) => void
185
- onPointerUp?: (event: ThreeEvent<PointerEvent>) => void
186
- onPointerDown?: (event: ThreeEvent<PointerEvent>) => void
187
- onPointerOver?: (event: ThreeEvent<PointerEvent>) => void
188
- onPointerOut?: (event: ThreeEvent<PointerEvent>) => void
189
- onPointerEnter?: (event: ThreeEvent<PointerEvent>) => void
190
- onPointerLeave?: (event: ThreeEvent<PointerEvent>) => void
191
- onPointerMove?: (event: ThreeEvent<PointerEvent>) => void
192
- onPointerMissed?: (event: MouseEvent) => void
193
- onPointerCancel?: (event: ThreeEvent<PointerEvent>) => void
194
- onWheel?: (event: ThreeEvent<WheelEvent>) => void
195
- onLostPointerCapture?: (event: ThreeEvent<PointerEvent>) => void
196
-
197
- //* Visibility Events --------------------------------
198
- /** Fires when object enters/exits camera frustum. Receives true when in view, false when out. */
199
- onFramed?: (inView: boolean) => void
200
- /** Fires when object occlusion state changes (WebGPU only, requires occlusionTest=true on object) */
201
- onOccluded?: (occluded: boolean) => void
202
- /** Fires when combined visibility changes (frustum + occlusion + visible prop) */
203
- onVisible?: (visible: boolean) => void
204
- }
205
-
206
- type FilterFunction = (items: THREE$1.Intersection[], state: RootState) => THREE$1.Intersection[]
207
- type ComputeFunction = (event: DomEvent, root: RootState, previous?: RootState) => void
208
-
209
- interface EventManager<TTarget> {
210
- /** Determines if the event layer is active */
211
- enabled: boolean
212
- /** Event layer priority, higher prioritized layers come first and may stop(-propagate) lower layer */
213
- priority: number
214
- /** The compute function needs to set up the raycaster and an xy- pointer */
215
- compute?: ComputeFunction
216
- /** The filter can re-order or re-structure the intersections */
217
- filter?: FilterFunction
218
- /** The target node the event layer is tied to */
219
- connected?: TTarget
220
- /** All the pointer event handlers through which the host forwards native events */
221
- handlers?: Events
222
- /** Allows re-connecting to another target */
223
- connect?: (target: TTarget) => void
224
- /** Removes all existing events handlers from the target */
225
- disconnect?: () => void
226
- /** Triggers a onPointerMove with the last known event. This can be useful to enable raycasting without
227
- * explicit user interaction, for instance when the camera moves a hoverable object underneath the cursor.
228
- */
229
- update?: () => void
230
- }
231
-
232
- interface PointerCaptureTarget {
233
- intersection: Intersection
234
- target: Element
235
- }
236
-
237
- //* Visibility System Types =====================================
238
-
239
- /** Entry in the visibility registry for tracking object visibility state */
240
- interface VisibilityEntry {
241
- object: THREE$1.Object3D
242
- handlers: Pick<EventHandlers, 'onFramed' | 'onOccluded' | 'onVisible'>
243
- lastFramedState: boolean | null
244
- lastOccludedState: boolean | null
245
- lastVisibleState: boolean | null
246
- }
247
-
248
- //* Scheduler Types (useFrame) ==============================
249
-
250
-
251
-
252
- // Public Options --------------------------------
253
-
254
- /**
255
- * Options for useFrame hook
256
- */
257
- interface UseFrameNextOptions {
258
- /** Optional stable id for the job. Auto-generated if not provided */
259
- id?: string
260
- /** Named phase to run in. Default: 'update' */
261
- phase?: string
262
- /** Run before this phase or job id */
263
- before?: string | string[]
264
- /** Run after this phase or job id */
265
- after?: string | string[]
266
- /** Priority within phase. Higher runs first. Default: 0 */
267
- priority?: number
268
- /** Max frames per second for this job */
269
- fps?: number
270
- /** If true, skip frames when behind. If false, try to catch up. Default: true */
271
- drop?: boolean
272
- /** Enable/disable without unregistering. Default: true */
273
- enabled?: boolean
274
- }
275
-
276
- /** Alias for UseFrameNextOptions */
277
- type UseFrameOptions = UseFrameNextOptions
278
-
279
- /**
280
- * Options for addPhase
281
- */
282
- interface AddPhaseOptions {
283
- /** Insert this phase before the specified phase */
284
- before?: string
285
- /** Insert this phase after the specified phase */
286
- after?: string
287
- }
288
-
289
- // Frame State --------------------------------
290
-
291
- /**
292
- * Timing-only state for independent/outside mode (no RootState)
293
- */
294
- interface FrameTimingState {
295
- /** High-resolution timestamp from RAF (ms) */
296
- time: number
297
- /** Time since last frame in seconds (for legacy compatibility with THREE.Clock) */
298
- delta: number
299
- /** Elapsed time since first frame in seconds (for legacy compatibility with THREE.Clock) */
300
- elapsed: number
301
- /** Incrementing frame counter */
302
- frame: number
303
- }
304
-
305
- /**
306
- * State passed to useFrame callbacks (extends RootState with timing)
307
- */
308
- interface FrameNextState extends RootState, FrameTimingState {}
309
-
310
- /** Alias for FrameNextState */
311
- type FrameState = FrameNextState
312
-
313
- // Root Options --------------------------------
314
-
315
- /**
316
- * Options for registerRoot
317
- */
318
- interface RootOptions {
319
- /** State provider for callbacks. Optional in independent mode. */
320
- getState?: () => any
321
- /** Error handler for job errors. Falls back to console.error if not provided. */
322
- onError?: (error: Error) => void
323
- }
324
-
325
- // Callback Types --------------------------------
326
-
327
- /**
328
- * Callback function for useFrame
329
- */
330
- type FrameNextCallback = (state: FrameNextState, delta: number) => void
331
-
332
- /** Alias for FrameNextCallback */
333
- type FrameCallback = FrameNextCallback
334
-
335
- // Controls returned from useFrame --------------------------------
336
-
337
- /**
338
- * Controls object returned from useFrame hook
339
- */
340
- interface FrameNextControls {
341
- /** The job's unique ID */
342
- id: string
343
- /** Access to the global scheduler for frame loop control */
344
- scheduler: SchedulerApi
345
- /** Manually step this job only (bypasses FPS limiting) */
346
- step(timestamp?: number): void
347
- /** Manually step ALL jobs in the scheduler */
348
- stepAll(timestamp?: number): void
349
- /** Pause this job (set enabled=false) */
350
- pause(): void
351
- /** Resume this job (set enabled=true) */
352
- resume(): void
353
- /** Reactive paused state - automatically triggers re-render when changed */
354
- isPaused: boolean
355
- }
356
-
357
- /** Alias for FrameNextControls */
358
- type FrameControls = FrameNextControls
359
-
360
- // Scheduler Interface --------------------------------
361
-
362
- /**
363
- * Public interface for the global Scheduler
364
- */
365
- interface SchedulerApi {
366
- //* Phase Management --------------------------------
367
-
368
- /** Add a named phase to the scheduler */
369
- addPhase(name: string, options?: AddPhaseOptions): void
370
- /** Get the ordered list of phase names */
371
- readonly phases: string[]
372
- /** Check if a phase exists */
373
- hasPhase(name: string): boolean
374
-
375
- //* Root Management --------------------------------
376
-
377
- /** Register a root (Canvas) with the scheduler. Returns unsubscribe function. */
378
- registerRoot(id: string, options?: RootOptions): () => void
379
- /** Unregister a root */
380
- unregisterRoot(id: string): void
381
- /** Generate a unique root ID */
382
- generateRootId(): string
383
- /** Get the number of registered roots */
384
- getRootCount(): number
385
- /** Check if any root is registered and ready */
386
- readonly isReady: boolean
387
- /** Subscribe to root-ready event. Fires immediately if already ready. Returns unsubscribe. */
388
- onRootReady(callback: () => void): () => void
389
-
390
- //* Job Registration --------------------------------
391
-
392
- /** Register a job with the scheduler (returns unsubscribe function) */
393
- register(
394
- callback: FrameNextCallback,
395
- options?: {
396
- id?: string
397
- rootId?: string
398
- phase?: string
399
- before?: string | string[]
400
- after?: string | string[]
401
- priority?: number
402
- fps?: number
403
- drop?: boolean
404
- enabled?: boolean
405
- },
406
- ): () => void
407
- /** Update a job's options */
408
- updateJob(
409
- id: string,
410
- options: {
411
- priority?: number
412
- fps?: number
413
- drop?: boolean
414
- enabled?: boolean
415
- phase?: string
416
- before?: string | string[]
417
- after?: string | string[]
418
- },
419
- ): void
420
- /** Unregister a job by ID */
421
- unregister(id: string, rootId?: string): void
422
- /** Get the number of registered jobs */
423
- getJobCount(): number
424
- /** Get all job IDs */
425
- getJobIds(): string[]
426
-
427
- //* Global Jobs (for legacy addEffect/addAfterEffect) --------------------------------
428
-
429
- /** Register a global job (runs once per frame, not per-root). Returns unsubscribe function. */
430
- registerGlobal(phase: 'before' | 'after', id: string, callback: (timestamp: number) => void): () => void
431
-
432
- //* Idle Callbacks (for legacy addTail) --------------------------------
433
-
434
- /** Register an idle callback (fires when loop stops). Returns unsubscribe function. */
435
- onIdle(callback: (timestamp: number) => void): () => void
436
-
437
- //* Frame Loop Control --------------------------------
438
-
439
- /** Start the scheduler loop */
440
- start(): void
441
- /** Stop the scheduler loop */
442
- stop(): void
443
- /** Check if the scheduler is running */
444
- readonly isRunning: boolean
445
- /** Get/set the frameloop mode ('always', 'demand', 'never') */
446
- frameloop: Frameloop
447
- /** Independent mode - runs without Canvas, callbacks receive timing-only state */
448
- independent: boolean
449
-
450
- //* Manual Stepping --------------------------------
451
-
452
- /** Manually step all jobs once (for frameloop='never' or testing) */
453
- step(timestamp?: number): void
454
- /** Manually step a single job by ID */
455
- stepJob(id: string, timestamp?: number): void
456
- /** Request frame(s) to be rendered (for frameloop='demand') */
457
- invalidate(frames?: number): void
458
-
459
- //* Per-Job Control --------------------------------
460
-
461
- /** Check if a job is paused */
462
- isJobPaused(id: string): boolean
463
- /** Pause a job */
464
- pauseJob(id: string): void
465
- /** Resume a job */
466
- resumeJob(id: string): void
467
- /** Subscribe to job state changes (for reactive isPaused). Returns unsubscribe function. */
468
- subscribeJobState(id: string, listener: () => void): () => void
469
- }
470
-
471
- //* Core Store Types ========================================
472
-
473
- type Subscription = {
474
- ref: React$1.RefObject<RenderCallback>
475
- priority: number
476
- store: RootStore
477
- }
478
-
479
- type Dpr = number | [min: number, max: number]
480
-
481
- interface Size {
482
- width: number
483
- height: number
484
- top: number
485
- left: number
486
- }
487
-
488
- type Frameloop = 'always' | 'demand' | 'never'
489
-
490
- interface Viewport extends Size {
491
- /** The initial pixel ratio */
492
- initialDpr: number
493
- /** Current pixel ratio */
494
- dpr: number
495
- /** size.width / viewport.width */
496
- factor: number
497
- /** Camera distance */
498
- distance: number
499
- /** Camera aspect ratio: width / height */
500
- aspect: number
501
- }
502
-
503
- type RenderCallback = (state: RootState, delta: number, frame?: XRFrame) => void
504
-
505
- interface Performance {
506
- /** Current performance normal, between min and max */
507
- current: number
508
- /** How low the performance can go, between 0 and max */
509
- min: number
510
- /** How high the performance can go, between min and max */
511
- max: number
512
- /** Time until current returns to max in ms */
513
- debounce: number
514
- /** Sets current to min, puts the system in regression */
515
- regress: () => void
516
- }
517
-
518
- interface InternalState {
519
- interaction: THREE$1.Object3D[]
520
- hovered: Map<string, ThreeEvent<DomEvent>>
521
- subscribers: Subscription[]
522
- capturedMap: Map<number, Map<THREE$1.Object3D, PointerCaptureTarget>>
523
- initialClick: [x: number, y: number]
524
- initialHits: THREE$1.Object3D[]
525
- lastEvent: React$1.RefObject<DomEvent | null>
526
- /** Visibility event registry (onFramed, onOccluded, onVisible) */
527
- visibilityRegistry: Map<string, VisibilityEntry>
528
- /** Whether occlusion queries are enabled (WebGPU only) */
529
- occlusionEnabled: boolean
530
- /** Reference to the invisible occlusion observer mesh */
531
- occlusionObserver: THREE$1.Mesh | null
532
- /** Cached occlusion results from render pass - keyed by Object3D */
533
- occlusionCache: Map<THREE$1.Object3D, boolean | null>
534
- /** Internal helper group for R3F system objects (occlusion observer, etc.) */
535
- helperGroup: THREE$1.Group | null
536
- active: boolean
537
- priority: number
538
- frames: number
539
- subscribe: (callback: React$1.RefObject<RenderCallback>, priority: number, store: RootStore) => () => void
540
- /** Internal renderer storage - use state.renderer or state.gl to access */
541
- actualRenderer: THREE$1.WebGLRenderer | any // WebGPURenderer when available
542
- /** Global scheduler reference (for useFrame hook) */
543
- scheduler: SchedulerApi | null
544
- /** This root's unique ID in the global scheduler */
545
- rootId?: string
546
- /** Function to unregister this root from the global scheduler */
547
- unregisterRoot?: () => void
548
- /** Container for child attachment (scene for root, original container for portals) */
549
- container?: THREE$1.Object3D
550
- }
551
-
552
- interface XRManager {
553
- connect: () => void
554
- disconnect: () => void
555
- }
556
-
557
- //* Root State Interface ====================================
558
-
559
- interface RootState {
560
- /** Set current state */
561
- set: StoreApi<RootState>['setState']
562
- /** Get current state */
563
- get: StoreApi<RootState>['getState']
564
- /** (deprecated) The instance of the WebGLrenderer */
565
- gl: THREE$1.WebGLRenderer
566
- /** The instance of the WebGPU renderer, the fallback, OR the default renderer as a mask of gl */
567
- renderer: THREE$1.WebGLRenderer | any // WebGPURenderer when available
568
- /** Inspector of the webGPU Renderer. Init in the canvas */
569
- inspector: any // Inspector type from three/webgpu
570
-
571
- /** Default camera */
572
- camera: ThreeCamera
573
- /** Camera frustum for visibility checks - auto-updated each frame when autoUpdateFrustum is true */
574
- frustum: THREE$1.Frustum
575
- /** Whether to automatically update the frustum each frame (default: true) */
576
- autoUpdateFrustum: boolean
577
- /** Default scene (may be overridden in portals to point to the portal container) */
578
- scene: THREE$1.Scene
579
- /** The actual root THREE.Scene - always points to the true scene, even inside portals */
580
- rootScene: THREE$1.Scene
581
- /** Default raycaster */
582
- raycaster: THREE$1.Raycaster
583
- /** Event layer interface, contains the event handler and the node they're connected to */
584
- events: EventManager<any>
585
- /** XR interface */
586
- xr: XRManager
587
- /** Currently used controls */
588
- controls: THREE$1.EventDispatcher | null
589
- /** Normalized event coordinates */
590
- pointer: THREE$1.Vector2
591
- /** @deprecated Normalized event coordinates, use "pointer" instead! */
592
- mouse: THREE$1.Vector2
593
- /* Whether to enable r139's THREE.ColorManagement */
594
- legacy: boolean
595
- /** Shortcut to gl.outputColorSpace = THREE.LinearSRGBColorSpace */
596
- linear: boolean
597
- /** Shortcut to gl.toneMapping = NoTonemapping */
598
- flat: boolean
599
- /** Color space assigned to 8-bit input textures (color maps). Most textures are authored in sRGB. */
600
- textureColorSpace: THREE$1.ColorSpace
601
- /** Render loop flags */
602
- frameloop: Frameloop
603
- performance: Performance
604
- /** Reactive pixel-size of the canvas */
605
- size: Size
606
- /** Reactive size of the viewport in threejs units */
607
- viewport: Viewport & {
608
- getCurrentViewport: (
609
- camera?: ThreeCamera,
610
- target?: THREE$1.Vector3 | Parameters<THREE$1.Vector3['set']>,
611
- size?: Size,
612
- ) => Omit<Viewport, 'dpr' | 'initialDpr'>
613
- }
614
- /** Flags the canvas for render, but doesn't render in itself */
615
- invalidate: (frames?: number, stackFrames?: boolean) => void
616
- /** Advance (render) one step */
617
- advance: (timestamp: number, runGlobalEffects?: boolean) => void
618
- /** Shortcut to setting the event layer */
619
- setEvents: (events: Partial<EventManager<any>>) => void
620
- /** Shortcut to manual sizing */
621
- setSize: (width: number, height: number, top?: number, left?: number) => void
622
- /** Shortcut to manual setting the pixel ratio */
623
- setDpr: (dpr: Dpr) => void
624
- /** Shortcut to setting frameloop flags */
625
- setFrameloop: (frameloop: Frameloop) => void
626
- /** Set error state to propagate to error boundary */
627
- setError: (error: Error | null) => void
628
- /** Current error state (null when no error) */
629
- error: Error | null
630
- /** Global TSL uniform nodes - root-level uniforms + scoped sub-objects. Use useUniforms() hook */
631
- uniforms: UniformStore
632
- /** Global TSL nodes - root-level nodes + scoped sub-objects. Use useNodes() hook */
633
- nodes: Record<string, any>
634
- /** Global TSL texture nodes - use useTextures() hook for operations */
635
- textures: Map<string, any>
636
- /** WebGPU PostProcessing instance - use usePostProcessing() hook */
637
- postProcessing: any | null // THREE.PostProcessing when available
638
- /** Global TSL pass nodes for post-processing - use usePostProcessing() hook */
639
- passes: Record<string, any>
640
- /** When the canvas was clicked but nothing was hit */
641
- onPointerMissed?: (event: MouseEvent) => void
642
- /** When a dragover event has missed any target */
643
- onDragOverMissed?: (event: DragEvent) => void
644
- /** When a drop event has missed any target */
645
- onDropMissed?: (event: DragEvent) => void
646
- /** If this state model is layered (via createPortal) then this contains the previous layer */
647
- previousRoot?: RootStore
648
- /** Internals */
649
- internal: InternalState
650
- // flags for triggers
651
- // if we are using the webGl renderer, this will be true
652
- isLegacy: boolean
653
- // regardless of renderer, if the system supports webGpu, this will be true
654
- webGPUSupported: boolean
655
- //if we are on native
656
- isNative: boolean
657
- }
658
-
62
+ //* Utility Types ==============================
63
+
64
+ type NonFunctionKeys<P> = { [K in keyof P]-?: P[K] extends Function ? never : K }[keyof P]
65
+ type Overwrite<P, O> = Omit<P, NonFunctionKeys<O>> & O
66
+ type Properties<T> = Pick<T, NonFunctionKeys<T>>
67
+ type Mutable<P> = { -readonly [K in keyof P]: P[K] }
68
+ type IsOptional<T> = undefined extends T ? true : false
69
+ type IsAllOptional<T extends any[]> = T extends [infer First, ...infer Rest]
70
+ ? IsOptional<First> extends true
71
+ ? IsAllOptional<Rest>
72
+ : false
73
+ : true
74
+
75
+ //* Camera Types ==============================
76
+
77
+ type ThreeCamera = (THREE$1.OrthographicCamera | THREE$1.PerspectiveCamera) & { manual?: boolean }
78
+
79
+ //* Act Type ==============================
80
+
81
+ type Act = <T = any>(cb: () => Promise<T>) => Promise<T>
82
+
83
+ //* Bridge & Block Types ==============================
84
+
85
+ type Bridge = React$1.FC<{ children?: React$1.ReactNode }>
86
+
87
+ type SetBlock = false | Promise<null> | null
88
+ type UnblockProps = { set: React$1.Dispatch<React$1.SetStateAction<SetBlock>>; children: React$1.ReactNode }
89
+
90
+ //* Object Map Type ==============================
91
+
92
+ /* Original version
93
+ export interface ObjectMap {
94
+ nodes: { [name: string]: THREE.Object3D }
95
+ materials: { [name: string]: THREE.Material }
96
+ meshes: { [name: string]: THREE.Mesh }
97
+ }
98
+ */
99
+ /* This version is an expansion found in a PR by itsdouges that seems abandoned but looks useful.
100
+ It allows expansion but falls back to the original shape. (deleted due to stale, but If it doesnt conflict
101
+ I will keep the use here)
102
+ https://github.com/pmndrs/react-three-fiber/commits/generic-object-map/
103
+ His description is:
104
+ The object map type is now generic and can optionally declare the available properties for nodes, materials, and meshes.
105
+ */
106
+ interface ObjectMap<
107
+ T extends { nodes?: string; materials?: string; meshes?: string } = {
108
+ nodes: string
109
+ materials: string
110
+ meshes: string
111
+ },
112
+ > {
113
+ nodes: Record<T['nodes'] extends string ? T['nodes'] : string, THREE$1.Object3D>
114
+ materials: Record<T['materials'] extends string ? T['materials'] : string, THREE$1.Material>
115
+ meshes: Record<T['meshes'] extends string ? T['meshes'] : string, THREE$1.Mesh>
116
+ }
117
+
118
+ //* Equality Config ==============================
119
+
120
+ interface EquConfig {
121
+ /** Compare arrays by reference equality a === b (default), or by shallow equality */
122
+ arrays?: 'reference' | 'shallow'
123
+ /** Compare objects by reference equality a === b (default), or by shallow equality */
124
+ objects?: 'reference' | 'shallow'
125
+ /** If true the keys in both a and b must match 1:1 (default), if false a's keys must intersect b's */
126
+ strict?: boolean
127
+ }
128
+
129
+ //* Disposable Type ==============================
130
+
131
+ interface Disposable {
132
+ type?: string
133
+ dispose?: () => void
134
+ }
135
+
136
+ //* Event-related Types =====================================
137
+
138
+ interface Intersection extends THREE$1.Intersection {
139
+ /** The event source (the object which registered the handler) */
140
+ eventObject: THREE$1.Object3D
141
+ }
142
+
143
+ type Camera = THREE$1.OrthographicCamera | THREE$1.PerspectiveCamera
144
+
145
+ interface IntersectionEvent<TSourceEvent> extends Intersection {
146
+ /** The event source (the object which registered the handler) */
147
+ eventObject: THREE$1.Object3D
148
+ /** An array of intersections */
149
+ intersections: Intersection[]
150
+ /** vec3.set(pointer.x, pointer.y, 0).unproject(camera) */
151
+ unprojectedPoint: THREE$1.Vector3
152
+ /** Normalized event coordinates */
153
+ pointer: THREE$1.Vector2
154
+ /** Delta between first click and this event */
155
+ delta: number
156
+ /** The ray that pierced it */
157
+ ray: THREE$1.Ray
158
+ /** The camera that was used by the raycaster */
159
+ camera: Camera
160
+ /** stopPropagation will stop underlying handlers from firing */
161
+ stopPropagation: () => void
162
+ /** The original host event */
163
+ nativeEvent: TSourceEvent
164
+ /** If the event was stopped by calling stopPropagation */
165
+ stopped: boolean
166
+ }
167
+
168
+ type ThreeEvent<TEvent> = IntersectionEvent<TEvent> & Properties<TEvent>
169
+ type DomEvent = PointerEvent | MouseEvent | WheelEvent
170
+
171
+ /** DOM event handlers registered on the canvas element */
172
+ interface Events {
173
+ onClick: EventListener
174
+ onContextMenu: EventListener
175
+ onDoubleClick: EventListener
176
+ onWheel: EventListener
177
+ onPointerDown: EventListener
178
+ onPointerUp: EventListener
179
+ onPointerLeave: EventListener
180
+ onPointerMove: EventListener
181
+ onPointerCancel: EventListener
182
+ onLostPointerCapture: EventListener
183
+ onDragEnter: EventListener
184
+ onDragLeave: EventListener
185
+ onDragOver: EventListener
186
+ onDrop: EventListener
187
+ }
188
+
189
+ /** Event handlers that can be attached to R3F objects (meshes, groups, etc.) */
190
+ interface EventHandlers {
191
+ onClick?: (event: ThreeEvent<MouseEvent>) => void
192
+ onContextMenu?: (event: ThreeEvent<MouseEvent>) => void
193
+ onDoubleClick?: (event: ThreeEvent<MouseEvent>) => void
194
+ /** Fires continuously while dragging over the object */
195
+ onDragOver?: (event: ThreeEvent<DragEvent>) => void
196
+ /** Fires once when drag enters the object */
197
+ onDragOverEnter?: (event: ThreeEvent<DragEvent>) => void
198
+ /** Fires once when drag leaves the object */
199
+ onDragOverLeave?: (event: ThreeEvent<DragEvent>) => void
200
+ /** Fires when drag misses this object (for objects that have drag handlers) */
201
+ onDragOverMissed?: (event: DragEvent) => void
202
+ /** Fires when a drop occurs on this object */
203
+ onDrop?: (event: ThreeEvent<DragEvent>) => void
204
+ /** Fires when a drop misses this object (for objects that have drop handlers) */
205
+ onDropMissed?: (event: DragEvent) => void
206
+ onPointerUp?: (event: ThreeEvent<PointerEvent>) => void
207
+ onPointerDown?: (event: ThreeEvent<PointerEvent>) => void
208
+ onPointerOver?: (event: ThreeEvent<PointerEvent>) => void
209
+ onPointerOut?: (event: ThreeEvent<PointerEvent>) => void
210
+ onPointerEnter?: (event: ThreeEvent<PointerEvent>) => void
211
+ onPointerLeave?: (event: ThreeEvent<PointerEvent>) => void
212
+ onPointerMove?: (event: ThreeEvent<PointerEvent>) => void
213
+ onPointerMissed?: (event: MouseEvent) => void
214
+ onPointerCancel?: (event: ThreeEvent<PointerEvent>) => void
215
+ onWheel?: (event: ThreeEvent<WheelEvent>) => void
216
+ onLostPointerCapture?: (event: ThreeEvent<PointerEvent>) => void
217
+
218
+ //* Visibility Events --------------------------------
219
+ /** Fires when object enters/exits camera frustum. Receives true when in view, false when out. */
220
+ onFramed?: (inView: boolean) => void
221
+ /** Fires when object occlusion state changes (WebGPU only, requires occlusionTest=true on object) */
222
+ onOccluded?: (occluded: boolean) => void
223
+ /** Fires when combined visibility changes (frustum + occlusion + visible prop) */
224
+ onVisible?: (visible: boolean) => void
225
+ }
226
+
227
+ type FilterFunction = (items: THREE$1.Intersection[], state: RootState) => THREE$1.Intersection[]
228
+ type ComputeFunction = (event: DomEvent, root: RootState, previous?: RootState) => void
229
+
230
+ interface EventManager<TTarget> {
231
+ /** Determines if the event layer is active */
232
+ enabled: boolean
233
+ /** Event layer priority, higher prioritized layers come first and may stop(-propagate) lower layer */
234
+ priority: number
235
+ /** The compute function needs to set up the raycaster and an xy- pointer */
236
+ compute?: ComputeFunction
237
+ /** The filter can re-order or re-structure the intersections */
238
+ filter?: FilterFunction
239
+ /** The target node the event layer is tied to */
240
+ connected?: TTarget
241
+ /** All the pointer event handlers through which the host forwards native events */
242
+ handlers?: Events
243
+ /** Allows re-connecting to another target */
244
+ connect?: (target: TTarget) => void
245
+ /** Removes all existing events handlers from the target */
246
+ disconnect?: () => void
247
+ /** Triggers a onPointerMove with the last known event. This can be useful to enable raycasting without
248
+ * explicit user interaction, for instance when the camera moves a hoverable object underneath the cursor.
249
+ */
250
+ update?: () => void
251
+ }
252
+
253
+ interface PointerCaptureTarget {
254
+ intersection: Intersection
255
+ target: Element
256
+ }
257
+
258
+ //* Visibility System Types =====================================
259
+
260
+ /** Entry in the visibility registry for tracking object visibility state */
261
+ interface VisibilityEntry {
262
+ object: THREE$1.Object3D
263
+ handlers: Pick<EventHandlers, 'onFramed' | 'onOccluded' | 'onVisible'>
264
+ lastFramedState: boolean | null
265
+ lastOccludedState: boolean | null
266
+ lastVisibleState: boolean | null
267
+ }
268
+
269
+ //* Scheduler Types (useFrame) ==============================
270
+
271
+
272
+
273
+ // Public Options --------------------------------
274
+
275
+ /**
276
+ * Options for useFrame hook
277
+ */
278
+ interface UseFrameNextOptions {
279
+ /** Optional stable id for the job. Auto-generated if not provided */
280
+ id?: string
281
+ /** Named phase to run in. Default: 'update' */
282
+ phase?: string
283
+ /** Run before this phase or job id */
284
+ before?: string | string[]
285
+ /** Run after this phase or job id */
286
+ after?: string | string[]
287
+ /** Priority within phase. Higher runs first. Default: 0 */
288
+ priority?: number
289
+ /** Max frames per second for this job */
290
+ fps?: number
291
+ /** If true, skip frames when behind. If false, try to catch up. Default: true */
292
+ drop?: boolean
293
+ /** Enable/disable without unregistering. Default: true */
294
+ enabled?: boolean
295
+ }
296
+
297
+ /** Alias for UseFrameNextOptions */
298
+ type UseFrameOptions = UseFrameNextOptions
299
+
300
+ /**
301
+ * Options for addPhase
302
+ */
303
+ interface AddPhaseOptions {
304
+ /** Insert this phase before the specified phase */
305
+ before?: string
306
+ /** Insert this phase after the specified phase */
307
+ after?: string
308
+ }
309
+
310
+ // Frame State --------------------------------
311
+
312
+ /**
313
+ * Timing-only state for independent/outside mode (no RootState)
314
+ */
315
+ interface FrameTimingState {
316
+ /** High-resolution timestamp from RAF (ms) */
317
+ time: number
318
+ /** Time since last frame in seconds (for legacy compatibility with THREE.Clock) */
319
+ delta: number
320
+ /** Elapsed time since first frame in seconds (for legacy compatibility with THREE.Clock) */
321
+ elapsed: number
322
+ /** Incrementing frame counter */
323
+ frame: number
324
+ }
325
+
326
+ /**
327
+ * State passed to useFrame callbacks (extends RootState with timing)
328
+ */
329
+ interface FrameNextState extends RootState, FrameTimingState {}
330
+
331
+ /** Alias for FrameNextState */
332
+ type FrameState = FrameNextState
333
+
334
+ // Root Options --------------------------------
335
+
336
+ /**
337
+ * Options for registerRoot
338
+ */
339
+ interface RootOptions {
340
+ /** State provider for callbacks. Optional in independent mode. */
341
+ getState?: () => any
342
+ /** Error handler for job errors. Falls back to console.error if not provided. */
343
+ onError?: (error: Error) => void
344
+ }
345
+
346
+ // Callback Types --------------------------------
347
+
348
+ /**
349
+ * Callback function for useFrame
350
+ */
351
+ type FrameNextCallback = (state: FrameNextState, delta: number) => void
352
+
353
+ /** Alias for FrameNextCallback */
354
+ type FrameCallback = FrameNextCallback
355
+
356
+ // Controls returned from useFrame --------------------------------
357
+
358
+ /**
359
+ * Controls object returned from useFrame hook
360
+ */
361
+ interface FrameNextControls {
362
+ /** The job's unique ID */
363
+ id: string
364
+ /** Access to the global scheduler for frame loop control */
365
+ scheduler: SchedulerApi
366
+ /** Manually step this job only (bypasses FPS limiting) */
367
+ step(timestamp?: number): void
368
+ /** Manually step ALL jobs in the scheduler */
369
+ stepAll(timestamp?: number): void
370
+ /** Pause this job (set enabled=false) */
371
+ pause(): void
372
+ /** Resume this job (set enabled=true) */
373
+ resume(): void
374
+ /** Reactive paused state - automatically triggers re-render when changed */
375
+ isPaused: boolean
376
+ }
377
+
378
+ /** Alias for FrameNextControls */
379
+ type FrameControls = FrameNextControls
380
+
381
+ // Scheduler Interface --------------------------------
382
+
383
+ /**
384
+ * Public interface for the global Scheduler
385
+ */
386
+ interface SchedulerApi {
387
+ //* Phase Management --------------------------------
388
+
389
+ /** Add a named phase to the scheduler */
390
+ addPhase(name: string, options?: AddPhaseOptions): void
391
+ /** Get the ordered list of phase names */
392
+ readonly phases: string[]
393
+ /** Check if a phase exists */
394
+ hasPhase(name: string): boolean
395
+
396
+ //* Root Management --------------------------------
397
+
398
+ /** Register a root (Canvas) with the scheduler. Returns unsubscribe function. */
399
+ registerRoot(id: string, options?: RootOptions): () => void
400
+ /** Unregister a root */
401
+ unregisterRoot(id: string): void
402
+ /** Generate a unique root ID */
403
+ generateRootId(): string
404
+ /** Get the number of registered roots */
405
+ getRootCount(): number
406
+ /** Check if any root is registered and ready */
407
+ readonly isReady: boolean
408
+ /** Subscribe to root-ready event. Fires immediately if already ready. Returns unsubscribe. */
409
+ onRootReady(callback: () => void): () => void
410
+
411
+ //* Job Registration --------------------------------
412
+
413
+ /** Register a job with the scheduler (returns unsubscribe function) */
414
+ register(
415
+ callback: FrameNextCallback,
416
+ options?: {
417
+ id?: string
418
+ rootId?: string
419
+ phase?: string
420
+ before?: string | string[]
421
+ after?: string | string[]
422
+ priority?: number
423
+ fps?: number
424
+ drop?: boolean
425
+ enabled?: boolean
426
+ },
427
+ ): () => void
428
+ /** Update a job's options */
429
+ updateJob(
430
+ id: string,
431
+ options: {
432
+ priority?: number
433
+ fps?: number
434
+ drop?: boolean
435
+ enabled?: boolean
436
+ phase?: string
437
+ before?: string | string[]
438
+ after?: string | string[]
439
+ },
440
+ ): void
441
+ /** Unregister a job by ID */
442
+ unregister(id: string, rootId?: string): void
443
+ /** Get the number of registered jobs */
444
+ getJobCount(): number
445
+ /** Get all job IDs */
446
+ getJobIds(): string[]
447
+
448
+ //* Global Jobs (for legacy addEffect/addAfterEffect) --------------------------------
449
+
450
+ /** Register a global job (runs once per frame, not per-root). Returns unsubscribe function. */
451
+ registerGlobal(phase: 'before' | 'after', id: string, callback: (timestamp: number) => void): () => void
452
+
453
+ //* Idle Callbacks (for legacy addTail) --------------------------------
454
+
455
+ /** Register an idle callback (fires when loop stops). Returns unsubscribe function. */
456
+ onIdle(callback: (timestamp: number) => void): () => void
457
+
458
+ //* Frame Loop Control --------------------------------
459
+
460
+ /** Start the scheduler loop */
461
+ start(): void
462
+ /** Stop the scheduler loop */
463
+ stop(): void
464
+ /** Check if the scheduler is running */
465
+ readonly isRunning: boolean
466
+ /** Get/set the frameloop mode ('always', 'demand', 'never') */
467
+ frameloop: Frameloop
468
+ /** Independent mode - runs without Canvas, callbacks receive timing-only state */
469
+ independent: boolean
470
+
471
+ //* Manual Stepping --------------------------------
472
+
473
+ /** Manually step all jobs once (for frameloop='never' or testing) */
474
+ step(timestamp?: number): void
475
+ /** Manually step a single job by ID */
476
+ stepJob(id: string, timestamp?: number): void
477
+ /** Request frame(s) to be rendered (for frameloop='demand') */
478
+ invalidate(frames?: number): void
479
+
480
+ //* Per-Job Control --------------------------------
481
+
482
+ /** Check if a job is paused */
483
+ isJobPaused(id: string): boolean
484
+ /** Pause a job */
485
+ pauseJob(id: string): void
486
+ /** Resume a job */
487
+ resumeJob(id: string): void
488
+ /** Subscribe to job state changes (for reactive isPaused). Returns unsubscribe function. */
489
+ subscribeJobState(id: string, listener: () => void): () => void
490
+ }
491
+
492
+ //* Renderer Types ========================================
493
+
494
+ /** Default renderer type - union of WebGL and WebGPU renderers */
495
+ type R3FRenderer = THREE$1.WebGLRenderer | WebGPURenderer
496
+
497
+ //* Core Store Types ========================================
498
+
499
+ type Subscription = {
500
+ ref: React$1.RefObject<RenderCallback>
501
+ priority: number
502
+ store: RootStore
503
+ }
504
+
505
+ type Dpr = number | [min: number, max: number]
506
+
507
+ interface Size {
508
+ width: number
509
+ height: number
510
+ top: number
511
+ left: number
512
+ }
513
+
514
+ type Frameloop = 'always' | 'demand' | 'never'
515
+
516
+ interface Viewport extends Size {
517
+ /** The initial pixel ratio */
518
+ initialDpr: number
519
+ /** Current pixel ratio */
520
+ dpr: number
521
+ /** size.width / viewport.width */
522
+ factor: number
523
+ /** Camera distance */
524
+ distance: number
525
+ /** Camera aspect ratio: width / height */
526
+ aspect: number
527
+ }
528
+
529
+ type RenderCallback = (state: RootState, delta: number, frame?: XRFrame) => void
530
+
531
+ interface Performance {
532
+ /** Current performance normal, between min and max */
533
+ current: number
534
+ /** How low the performance can go, between 0 and max */
535
+ min: number
536
+ /** How high the performance can go, between min and max */
537
+ max: number
538
+ /** Time until current returns to max in ms */
539
+ debounce: number
540
+ /** Sets current to min, puts the system in regression */
541
+ regress: () => void
542
+ }
543
+
544
+ interface InternalState {
545
+ interaction: THREE$1.Object3D[]
546
+ hovered: Map<string, ThreeEvent<DomEvent>>
547
+ subscribers: Subscription[]
548
+ capturedMap: Map<number, Map<THREE$1.Object3D, PointerCaptureTarget>>
549
+ initialClick: [x: number, y: number]
550
+ initialHits: THREE$1.Object3D[]
551
+ lastEvent: React$1.RefObject<DomEvent | null>
552
+ /** Visibility event registry (onFramed, onOccluded, onVisible) */
553
+ visibilityRegistry: Map<string, VisibilityEntry>
554
+ /** Whether occlusion queries are enabled (WebGPU only) */
555
+ occlusionEnabled: boolean
556
+ /** Reference to the invisible occlusion observer mesh */
557
+ occlusionObserver: THREE$1.Mesh | null
558
+ /** Cached occlusion results from render pass - keyed by Object3D */
559
+ occlusionCache: Map<THREE$1.Object3D, boolean | null>
560
+ /** Internal helper group for R3F system objects (occlusion observer, etc.) */
561
+ helperGroup: THREE$1.Group | null
562
+ active: boolean
563
+ priority: number
564
+ frames: number
565
+ subscribe: (callback: React$1.RefObject<RenderCallback>, priority: number, store: RootStore) => () => void
566
+ /** Internal renderer storage - use state.renderer or state.gl to access */
567
+ actualRenderer: R3FRenderer
568
+ /** Global scheduler reference (for useFrame hook) */
569
+ scheduler: SchedulerApi | null
570
+ /** This root's unique ID in the global scheduler */
571
+ rootId?: string
572
+ /** Function to unregister this root from the global scheduler */
573
+ unregisterRoot?: () => void
574
+ /** Container for child attachment (scene for root, original container for portals) */
575
+ container?: THREE$1.Object3D
576
+ /**
577
+ * CanvasTarget for multi-canvas WebGPU rendering.
578
+ * Created for all WebGPU canvases to support renderer sharing.
579
+ * @see https://threejs.org/docs/#api/en/renderers/common/CanvasTarget
580
+ */
581
+ canvasTarget?: CanvasTarget
582
+ /**
583
+ * Whether multi-canvas rendering is active.
584
+ * True when any canvas uses `target` prop to share a renderer.
585
+ * When true, setCanvasTarget is called before each render.
586
+ */
587
+ isMultiCanvas?: boolean
588
+ /**
589
+ * Whether this canvas is a secondary canvas sharing another's renderer.
590
+ * True when `target` prop is used.
591
+ */
592
+ isSecondary?: boolean
593
+ /**
594
+ * The id of the primary canvas this secondary canvas targets.
595
+ * Only set when isSecondary is true.
596
+ */
597
+ targetId?: string
598
+ /**
599
+ * Function to unregister this primary canvas from the registry.
600
+ * Only set when this canvas has an `id` prop.
601
+ */
602
+ unregisterPrimary?: () => void
603
+ /** Whether canvas dimensions are forced to even numbers */
604
+ forceEven?: boolean
605
+ }
606
+
607
+ interface XRManager {
608
+ connect: () => void
609
+ disconnect: () => void
610
+ }
611
+
612
+ //* Root State Interface ====================================
613
+
614
+ interface RootState {
615
+ /** Set current state */
616
+ set: StoreApi<RootState>['setState']
617
+ /** Get current state */
618
+ get: StoreApi<RootState>['getState']
619
+ /**
620
+ * Reference to the authoritative store for shared TSL resources (uniforms, nodes, etc).
621
+ * - For primary/independent canvases: points to its own store (self-reference)
622
+ * - For secondary canvases: points to the primary canvas's store
623
+ *
624
+ * Hooks like useNodes/useUniforms should read from primaryStore to ensure
625
+ * consistent shared state across all canvases sharing a renderer.
626
+ */
627
+ primaryStore: RootStore
628
+ /** @deprecated Use `renderer` instead. The instance of the renderer (typed as WebGLRenderer for backwards compat) */
629
+ gl: THREE$1.WebGLRenderer
630
+ /** The renderer instance - type depends on entry point (WebGPU, Legacy, or union for default) */
631
+ renderer: R3FRenderer
632
+ /** Inspector of the webGPU Renderer. Init in the canvas */
633
+ inspector: any // Inspector type from three/webgpu
634
+
635
+ /** Default camera */
636
+ camera: ThreeCamera
637
+ /** Camera frustum for visibility checks - auto-updated each frame when autoUpdateFrustum is true */
638
+ frustum: THREE$1.Frustum
639
+ /** Whether to automatically update the frustum each frame (default: true) */
640
+ autoUpdateFrustum: boolean
641
+ /** Default scene (may be overridden in portals to point to the portal container) */
642
+ scene: THREE$1.Scene
643
+ /** The actual root THREE.Scene - always points to the true scene, even inside portals */
644
+ rootScene: THREE$1.Scene
645
+ /** Default raycaster */
646
+ raycaster: THREE$1.Raycaster
647
+ /** Event layer interface, contains the event handler and the node they're connected to */
648
+ events: EventManager<any>
649
+ /** XR interface */
650
+ xr: XRManager
651
+ /** Currently used controls */
652
+ controls: THREE$1.EventDispatcher | null
653
+ /** Normalized event coordinates */
654
+ pointer: THREE$1.Vector2
655
+ /** @deprecated Normalized event coordinates, use "pointer" instead! */
656
+ mouse: THREE$1.Vector2
657
+ /** Color space assigned to 8-bit input textures (color maps). Most textures are authored in sRGB. */
658
+ textureColorSpace: THREE$1.ColorSpace
659
+ /** Render loop flags */
660
+ frameloop: Frameloop
661
+ performance: Performance
662
+ /** Reactive pixel-size of the canvas */
663
+ size: Size
664
+ /** Reactive size of the viewport in threejs units */
665
+ viewport: Viewport & {
666
+ getCurrentViewport: (
667
+ camera?: ThreeCamera,
668
+ target?: THREE$1.Vector3 | Parameters<THREE$1.Vector3['set']>,
669
+ size?: Size,
670
+ ) => Omit<Viewport, 'dpr' | 'initialDpr'>
671
+ }
672
+ /** Flags the canvas for render, but doesn't render in itself */
673
+ invalidate: (frames?: number, stackFrames?: boolean) => void
674
+ /** Advance (render) one step */
675
+ advance: (timestamp: number, runGlobalEffects?: boolean) => void
676
+ /** Shortcut to setting the event layer */
677
+ setEvents: (events: Partial<EventManager<any>>) => void
678
+ /** Shortcut to manual sizing. No args resets to props/container. Single arg creates square. */
679
+ setSize: (width?: number, height?: number, top?: number, left?: number) => void
680
+ /** Shortcut to manual setting the pixel ratio */
681
+ setDpr: (dpr: Dpr) => void
682
+ /** Shortcut to setting frameloop flags */
683
+ setFrameloop: (frameloop: Frameloop) => void
684
+ /** Set error state to propagate to error boundary */
685
+ setError: (error: Error | null) => void
686
+ /** Current error state (null when no error) */
687
+ error: Error | null
688
+ /** Global TSL uniform nodes - root-level uniforms + scoped sub-objects. Use useUniforms() hook */
689
+ uniforms: UniformStore
690
+ /** Global TSL nodes - root-level nodes + scoped sub-objects. Use useNodes() hook */
691
+ nodes: Record<string, any>
692
+ /** Global TSL texture nodes - use useTextures() hook for operations */
693
+ textures: Map<string, any>
694
+ /** WebGPU PostProcessing instance - use usePostProcessing() hook */
695
+ postProcessing: any | null // THREE.PostProcessing when available
696
+ /** Global TSL pass nodes for post-processing - use usePostProcessing() hook */
697
+ passes: Record<string, any>
698
+ /** Internal version counter for HMR - incremented by rebuildNodes/rebuildUniforms to bust memoization */
699
+ _hmrVersion: number
700
+ /** Internal: whether setSize() has taken ownership of canvas dimensions */
701
+ _sizeImperative: boolean
702
+ /** Internal: stored size props from Canvas for reset functionality */
703
+ _sizeProps: { width?: number; height?: number } | null
704
+ /** When the canvas was clicked but nothing was hit */
705
+ onPointerMissed?: (event: MouseEvent) => void
706
+ /** When a dragover event has missed any target */
707
+ onDragOverMissed?: (event: DragEvent) => void
708
+ /** When a drop event has missed any target */
709
+ onDropMissed?: (event: DragEvent) => void
710
+ /** If this state model is layered (via createPortal) then this contains the previous layer */
711
+ previousRoot?: RootStore
712
+ /** Internals */
713
+ internal: InternalState
714
+ // flags for triggers
715
+ // if we are using the webGl renderer, this will be true
716
+ isLegacy: boolean
717
+ // regardless of renderer, if the system supports webGpu, this will be true
718
+ webGPUSupported: boolean
719
+ //if we are on native
720
+ isNative: boolean
721
+ }
722
+
659
723
  type RootStore = UseBoundStoreWithEqualityFn<StoreApi<RootState>>
660
724
 
661
- //* Base Renderer Types =====================================
662
-
663
- // Shim for OffscreenCanvas since it was removed from DOM types
664
- interface OffscreenCanvas$1 extends EventTarget {}
665
-
666
- interface BaseRendererProps {
667
- canvas: HTMLCanvasElement | OffscreenCanvas$1
668
- powerPreference?: 'high-performance' | 'low-power' | 'default'
669
- antialias?: boolean
670
- alpha?: boolean
671
- }
672
-
673
- type RendererFactory<TRenderer, TParams> =
674
- | TRenderer
675
- | ((defaultProps: TParams) => TRenderer)
676
- | ((defaultProps: TParams) => Promise<TRenderer>)
677
-
678
- interface Renderer {
679
- render: (scene: THREE$1.Scene, camera: THREE$1.Camera) => any
680
- }
681
-
682
- //* WebGL Renderer Props ==============================
683
-
684
- type DefaultGLProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & {
685
- canvas: HTMLCanvasElement | OffscreenCanvas$1
686
- }
687
-
688
- type GLProps =
689
- | Renderer
690
- | ((defaultProps: DefaultGLProps) => Renderer)
691
- | ((defaultProps: DefaultGLProps) => Promise<Renderer>)
692
- | Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters>
693
-
694
- //* WebGPU Renderer Props ==============================
695
-
696
- type DefaultRendererProps = {
697
- canvas: HTMLCanvasElement | OffscreenCanvas$1
698
- [key: string]: any
699
- }
700
-
701
- type RendererProps =
702
- | any // WebGPURenderer
703
- | ((defaultProps: DefaultRendererProps) => any)
704
- | ((defaultProps: DefaultRendererProps) => Promise<any>)
705
- | Partial<Properties<any> | Record<string, any>>
706
-
707
- //* Camera Props ==============================
708
-
709
- type CameraProps = (
710
- | THREE$1.Camera
711
- | Partial<
712
- ThreeElement<typeof THREE$1.Camera> &
713
- ThreeElement<typeof THREE$1.PerspectiveCamera> &
714
- ThreeElement<typeof THREE$1.OrthographicCamera>
715
- >
716
- ) & {
717
- /** Flags the camera as manual, putting projection into your own hands */
718
- manual?: boolean
719
- }
720
-
721
- //* Render Props ==============================
722
-
723
- interface RenderProps<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
724
- /** A threejs renderer instance or props that go into the default renderer */
725
- gl?: GLProps
726
- /** A WebGPU renderer instance or props that go into the default renderer */
727
- renderer?: RendererProps
728
- /** Dimensions to fit the renderer to. Will measure canvas dimensions if omitted */
729
- size?: Size
730
- /**
731
- * Enables shadows (by default PCFsoft). Can accept `gl.shadowMap` options for fine-tuning,
732
- * but also strings: 'basic' | 'percentage' | 'soft' | 'variance'.
733
- * @see https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
734
- */
735
- shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
736
- /**
737
- * Disables three r139 color management.
738
- * @see https://threejs.org/docs/#manual/en/introduction/Color-management
739
- */
740
- legacy?: boolean
741
- /** Switch off automatic sRGB encoding and gamma correction */
742
- linear?: boolean
743
- /** Use `THREE.NoToneMapping` instead of `THREE.ACESFilmicToneMapping` */
744
- flat?: boolean
745
- /** Working color space for automatic texture colorspace assignment. Defaults to THREE.SRGBColorSpace */
746
- /** Color space assigned to 8-bit input textures (color maps). Defaults to sRGB. Most textures are authored in sRGB. */
747
- textureColorSpace?: THREE$1.ColorSpace
748
- /** Creates an orthographic camera */
749
- orthographic?: boolean
750
- /**
751
- * R3F's render mode. Set to `demand` to only render on state change or `never` to take control.
752
- * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#on-demand-rendering
753
- */
754
- frameloop?: Frameloop
755
- /**
756
- * R3F performance options for adaptive performance.
757
- * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#movement-regression
758
- */
759
- performance?: Partial<Omit<Performance, 'regress'>>
760
- /** Target pixel ratio. Can clamp between a range: `[min, max]` */
761
- dpr?: Dpr
762
- /** Props that go into the default raycaster */
763
- raycaster?: Partial<THREE$1.Raycaster>
764
- /** A `THREE.Scene` instance or props that go into the default scene */
765
- scene?: THREE$1.Scene | Partial<THREE$1.Scene>
766
- /** A `THREE.Camera` instance or props that go into the default camera */
767
- camera?: CameraProps
768
- /** An R3F event manager to manage elements' pointer events */
769
- events?: (store: RootStore) => EventManager<HTMLElement>
770
- /** Callback after the canvas has rendered (but not yet committed) */
771
- onCreated?: (state: RootState) => void
772
- /** Response for pointer clicks that have missed any target */
773
- onPointerMissed?: (event: MouseEvent) => void
774
- /** Response for dragover events that have missed any target */
775
- onDragOverMissed?: (event: DragEvent) => void
776
- /** Response for drop events that have missed any target */
777
- onDropMissed?: (event: DragEvent) => void
778
- /** Whether to automatically update the frustum each frame (default: true) */
779
- autoUpdateFrustum?: boolean
780
- /**
781
- * Enable WebGPU occlusion queries for onOccluded/onVisible events.
782
- * Auto-enabled when any object uses onOccluded or onVisible handlers.
783
- * Only works with WebGPU renderer - WebGL will log a warning.
784
- */
785
- occlusion?: boolean
786
- }
787
-
788
- //* Reconciler Root ==============================
789
-
790
- interface ReconcilerRoot<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
791
- configure: (config?: RenderProps<TCanvas>) => Promise<ReconcilerRoot<TCanvas>>
792
- render: (element: ReactNode) => RootStore
793
- unmount: () => void
794
- }
795
-
796
- //* Inject State ==============================
797
-
798
- type InjectState = Partial<
799
- Omit<RootState, 'events'> & {
800
- events?: {
801
- enabled?: boolean
802
- priority?: number
803
- compute?: ComputeFunction
804
- connected?: any
805
- }
806
- /**
807
- * When true (default), injects a THREE.Scene between container and children if container isn't already a Scene.
808
- * This ensures state.scene is always a real THREE.Scene with proper properties (background, environment, fog).
809
- * Set to false to use the container directly as scene (anti-pattern, but supported for edge cases).
810
- */
811
- injectScene?: boolean
812
- }
725
+ //* Base Renderer Types =====================================
726
+
727
+ // Shim for OffscreenCanvas since it was removed from DOM types
728
+ interface OffscreenCanvas$1 extends EventTarget {}
729
+
730
+ interface BaseRendererProps {
731
+ canvas: HTMLCanvasElement | OffscreenCanvas$1
732
+ powerPreference?: 'high-performance' | 'low-power' | 'default'
733
+ antialias?: boolean
734
+ alpha?: boolean
735
+ }
736
+
737
+ type RendererFactory<TRenderer, TParams> =
738
+ | TRenderer
739
+ | ((defaultProps: TParams) => TRenderer)
740
+ | ((defaultProps: TParams) => Promise<TRenderer>)
741
+
742
+ interface Renderer {
743
+ render: (scene: THREE$1.Scene, camera: THREE$1.Camera) => any
744
+ }
745
+
746
+ //* WebGL Renderer Props ==============================
747
+
748
+ type DefaultGLProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & {
749
+ canvas: HTMLCanvasElement | OffscreenCanvas$1
750
+ }
751
+
752
+ type GLProps =
753
+ | Renderer
754
+ | ((defaultProps: DefaultGLProps) => Renderer)
755
+ | ((defaultProps: DefaultGLProps) => Promise<Renderer>)
756
+ | Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters>
757
+
758
+ //* WebGPU Renderer Props ==============================
759
+
760
+ type DefaultRendererProps = {
761
+ canvas: HTMLCanvasElement | OffscreenCanvas$1
762
+ [key: string]: any
763
+ }
764
+
765
+ /**
766
+ * Canvas-level scheduler configuration.
767
+ * Controls render timing relative to other canvases.
768
+ */
769
+ interface CanvasSchedulerConfig {
770
+ /**
771
+ * Render this canvas after another canvas completes.
772
+ * Pass the `id` of another canvas.
773
+ */
774
+ after?: string
775
+ /**
776
+ * Limit this canvas's render rate (frames per second).
777
+ */
778
+ fps?: number
779
+ }
780
+
781
+ /**
782
+ * Extended renderer configuration for multi-canvas support.
783
+ */
784
+ interface RendererConfigExtended {
785
+ /** Share renderer from another canvas (WebGPU only) */
786
+ primaryCanvas?: string
787
+ /** Canvas-level scheduler options */
788
+ scheduler?: CanvasSchedulerConfig
789
+ }
790
+
791
+ type RendererProps =
792
+ | any // WebGPURenderer
793
+ | ((defaultProps: DefaultRendererProps) => any)
794
+ | ((defaultProps: DefaultRendererProps) => Promise<any>)
795
+ | (Partial<Properties<any> | Record<string, any>> & RendererConfigExtended)
796
+
797
+ //* Camera Props ==============================
798
+
799
+ type CameraProps = (
800
+ | THREE$1.Camera
801
+ | Partial<
802
+ ThreeElement<typeof THREE$1.Camera> &
803
+ ThreeElement<typeof THREE$1.PerspectiveCamera> &
804
+ ThreeElement<typeof THREE$1.OrthographicCamera>
805
+ >
806
+ ) & {
807
+ /** Flags the camera as manual, putting projection into your own hands */
808
+ manual?: boolean
809
+ }
810
+
811
+ //* Render Props ==============================
812
+
813
+ interface RenderProps<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
814
+ /**
815
+ * Unique identifier for multi-canvas renderer sharing.
816
+ * Makes this canvas targetable by other canvases using the `primaryCanvas` prop.
817
+ * Also sets the HTML `id` attribute on the canvas element.
818
+ * @example <Canvas id="main-viewer">...</Canvas>
819
+ */
820
+ id?: string
821
+ /**
822
+ * Share the renderer from another canvas instead of creating a new one.
823
+ * Pass the `id` of the primary canvas to share its WebGPURenderer.
824
+ * Only available with WebGPU (not legacy WebGL).
825
+ *
826
+ * Note: This is extracted from `renderer={{ primaryCanvas: "id" }}` by Canvas.
827
+ * @internal
828
+ */
829
+ primaryCanvas?: string
830
+ /**
831
+ * Canvas-level scheduler options. Controls render timing relative to other canvases.
832
+ *
833
+ * Note: This is extracted from `renderer={{ scheduler: {...} }}` by Canvas.
834
+ * @internal
835
+ */
836
+ scheduler?: CanvasSchedulerConfig
837
+ /** A threejs renderer instance or props that go into the default renderer */
838
+ gl?: GLProps
839
+ /** A WebGPU renderer instance or props that go into the default renderer */
840
+ renderer?: RendererProps
841
+ /** Dimensions to fit the renderer to. Will measure canvas dimensions if omitted */
842
+ size?: Size
843
+ /**
844
+ * Enables shadows (by default PCFsoft). Can accept `gl.shadowMap` options for fine-tuning,
845
+ * but also strings: 'basic' | 'percentage' | 'soft' | 'variance'.
846
+ * @see https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
847
+ */
848
+ shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
849
+ /** Color space assigned to 8-bit input textures (color maps). Defaults to sRGB. Most textures are authored in sRGB. */
850
+ textureColorSpace?: THREE$1.ColorSpace
851
+ /** Creates an orthographic camera */
852
+ orthographic?: boolean
853
+ /**
854
+ * R3F's render mode. Set to `demand` to only render on state change or `never` to take control.
855
+ * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#on-demand-rendering
856
+ */
857
+ frameloop?: Frameloop
858
+ /**
859
+ * R3F performance options for adaptive performance.
860
+ * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#movement-regression
861
+ */
862
+ performance?: Partial<Omit<Performance, 'regress'>>
863
+ /** Target pixel ratio. Can clamp between a range: `[min, max]` */
864
+ dpr?: Dpr
865
+ /** Props that go into the default raycaster */
866
+ raycaster?: Partial<THREE$1.Raycaster>
867
+ /** A `THREE.Scene` instance or props that go into the default scene */
868
+ scene?: THREE$1.Scene | Partial<THREE$1.Scene>
869
+ /** A `THREE.Camera` instance or props that go into the default camera */
870
+ camera?: CameraProps
871
+ /** An R3F event manager to manage elements' pointer events */
872
+ events?: (store: RootStore) => EventManager<HTMLElement>
873
+ /** Callback after the canvas has rendered (but not yet committed) */
874
+ onCreated?: (state: RootState) => void
875
+ /** Response for pointer clicks that have missed any target */
876
+ onPointerMissed?: (event: MouseEvent) => void
877
+ /** Response for dragover events that have missed any target */
878
+ onDragOverMissed?: (event: DragEvent) => void
879
+ /** Response for drop events that have missed any target */
880
+ onDropMissed?: (event: DragEvent) => void
881
+ /** Whether to automatically update the frustum each frame (default: true) */
882
+ autoUpdateFrustum?: boolean
883
+ /**
884
+ * Enable WebGPU occlusion queries for onOccluded/onVisible events.
885
+ * Auto-enabled when any object uses onOccluded or onVisible handlers.
886
+ * Only works with WebGPU renderer - WebGL will log a warning.
887
+ */
888
+ occlusion?: boolean
889
+ /** Internal: stored size props from Canvas for reset functionality */
890
+ _sizeProps?: { width?: number; height?: number } | null
891
+ /** Force canvas dimensions to even numbers (fixes Safari rendering issues with odd/fractional sizes) */
892
+ forceEven?: boolean
893
+ }
894
+
895
+ //* Reconciler Root ==============================
896
+
897
+ interface ReconcilerRoot<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
898
+ configure: (config?: RenderProps<TCanvas>) => Promise<ReconcilerRoot<TCanvas>>
899
+ render: (element: ReactNode) => RootStore
900
+ unmount: () => void
901
+ }
902
+
903
+ //* Inject State ==============================
904
+
905
+ type InjectState = Partial<
906
+ Omit<RootState, 'events'> & {
907
+ events?: {
908
+ enabled?: boolean
909
+ priority?: number
910
+ compute?: ComputeFunction
911
+ connected?: any
912
+ }
913
+ /**
914
+ * When true (default), injects a THREE.Scene between container and children if container isn't already a Scene.
915
+ * This ensures state.scene is always a real THREE.Scene with proper properties (background, environment, fog).
916
+ * Set to false to use the container directly as scene (anti-pattern, but supported for edge cases).
917
+ */
918
+ injectScene?: boolean
919
+ }
813
920
  >
814
921
 
815
- //* Reconciler Types ==============================
816
-
817
- interface Root {
818
- fiber: react_reconciler.FiberRoot
819
- store: RootStore
820
- }
821
-
822
- type AttachFnType<O = any> = (parent: any, self: O) => () => void
823
- type AttachType<O = any> = string | AttachFnType<O>
824
-
825
- type ConstructorRepresentation<T = any> = new (...args: any[]) => T
826
-
827
- interface Catalogue {
828
- [name: string]: ConstructorRepresentation
829
- }
830
-
831
- // TODO: handle constructor overloads
832
- // https://github.com/pmndrs/react-three-fiber/pull/2931
833
- // https://github.com/microsoft/TypeScript/issues/37079
834
- type Args<T> = T extends ConstructorRepresentation
835
- ? T extends typeof Color$1
836
- ? [r: number, g: number, b: number] | [color: ColorRepresentation]
837
- : ConstructorParameters<T>
838
- : any[]
839
-
840
- type ArgsProp<P> = P extends ConstructorRepresentation
841
- ? IsAllOptional<ConstructorParameters<P>> extends true
842
- ? { args?: Args<P> }
843
- : { args: Args<P> }
844
- : { args: unknown[] }
845
-
846
- type InstanceProps<T = any, P = any> = ArgsProp<P> & {
847
- object?: T
848
- dispose?: null
849
- attach?: AttachType<T>
850
- onUpdate?: (self: T) => void
851
- }
852
-
853
- interface Instance<O = any> {
854
- root: RootStore
855
- type: string
856
- parent: Instance | null
857
- children: Instance[]
858
- props: InstanceProps<O> & Record<string, unknown>
859
- object: O & { __r3f?: Instance<O> }
860
- eventCount: number
861
- handlers: Partial<EventHandlers>
862
- attach?: AttachType<O>
863
- previousAttach?: any
864
- isHidden: boolean
865
- }
866
-
867
- interface HostConfig {
868
- type: string
869
- props: Instance['props']
870
- container: RootStore
871
- instance: Instance
872
- textInstance: void
873
- suspenseInstance: Instance
874
- hydratableInstance: never
875
- formInstance: never
876
- publicInstance: Instance['object']
877
- hostContext: {}
878
- childSet: never
879
- timeoutHandle: number | undefined
880
- noTimeout: -1
881
- TransitionStatus: null
882
- }
883
- declare global {
884
- var IS_REACT_ACT_ENVIRONMENT: boolean | undefined
885
- }
886
-
887
- //* Loop Types ==============================
888
-
889
- type GlobalRenderCallback = (timestamp: number) => void
890
-
922
+ //* Reconciler Types ==============================
923
+
924
+ // FiberRoot is an opaque internal React type - we define it locally
925
+ // to avoid bundling @types/react-reconciler which causes absolute path issues
926
+ type FiberRoot = any
927
+
928
+ interface Root {
929
+ fiber: FiberRoot
930
+ store: RootStore
931
+ }
932
+
933
+ type AttachFnType<O = any> = (parent: any, self: O) => () => void
934
+ type AttachType<O = any> = string | AttachFnType<O>
935
+
936
+ type ConstructorRepresentation<T = any> = new (...args: any[]) => T
937
+
938
+ interface Catalogue {
939
+ [name: string]: ConstructorRepresentation
940
+ }
941
+
942
+ // TODO: handle constructor overloads
943
+ // https://github.com/pmndrs/react-three-fiber/pull/2931
944
+ // https://github.com/microsoft/TypeScript/issues/37079
945
+ type Args<T> = T extends ConstructorRepresentation
946
+ ? T extends typeof Color$1
947
+ ? [r: number, g: number, b: number] | [color: ColorRepresentation]
948
+ : ConstructorParameters<T>
949
+ : any[]
950
+
951
+ type ArgsProp<P> = P extends ConstructorRepresentation
952
+ ? IsAllOptional<ConstructorParameters<P>> extends true
953
+ ? { args?: Args<P> }
954
+ : { args: Args<P> }
955
+ : { args: unknown[] }
956
+
957
+ type InstanceProps<T = any, P = any> = ArgsProp<P> & {
958
+ object?: T
959
+ dispose?: null
960
+ attach?: AttachType<T>
961
+ onUpdate?: (self: T) => void
962
+ }
963
+
964
+ interface Instance<O = any> {
965
+ root: RootStore
966
+ type: string
967
+ parent: Instance | null
968
+ children: Instance[]
969
+ props: InstanceProps<O> & Record<string, unknown>
970
+ object: O & { __r3f?: Instance<O> }
971
+ eventCount: number
972
+ handlers: Partial<EventHandlers>
973
+ attach?: AttachType<O>
974
+ previousAttach?: any
975
+ isHidden: boolean
976
+ /** Deferred ref props to apply in commitMount */
977
+ deferredRefs?: Array<{ prop: string; ref: React$1.RefObject<any> }>
978
+ /** Set of props that have been applied via once() */
979
+ appliedOnce?: Set<string>
980
+ }
981
+
982
+ interface HostConfig {
983
+ type: string
984
+ props: Instance['props']
985
+ container: RootStore
986
+ instance: Instance
987
+ textInstance: void
988
+ suspenseInstance: Instance
989
+ hydratableInstance: never
990
+ formInstance: never
991
+ publicInstance: Instance['object']
992
+ hostContext: {}
993
+ childSet: never
994
+ timeoutHandle: number | undefined
995
+ noTimeout: -1
996
+ TransitionStatus: null
997
+ }
998
+ declare global {
999
+ var IS_REACT_ACT_ENVIRONMENT: boolean | undefined
1000
+ }
1001
+
1002
+ //* Loop Types ==============================
1003
+
1004
+ type GlobalRenderCallback = (timestamp: number) => void
1005
+
891
1006
  type GlobalEffectType = 'before' | 'after' | 'tail'
892
1007
 
893
- //* Canvas Types ==============================
894
-
895
- interface CanvasProps
896
- extends Omit<RenderProps<HTMLCanvasElement>, 'size'>,
897
- React$1.HTMLAttributes<HTMLDivElement> {
898
- children?: React$1.ReactNode
899
- ref?: React$1.Ref<HTMLCanvasElement>
900
- /** Canvas fallback content, similar to img's alt prop */
901
- fallback?: React$1.ReactNode
902
- /**
903
- * Options to pass to useMeasure.
904
- * @see https://github.com/pmndrs/react-use-measure#api
905
- */
906
- resize?: Options
907
- /** The target where events are being subscribed to, default: the div that wraps canvas */
908
- eventSource?: HTMLElement | React$1.RefObject<HTMLElement>
909
- /** The event prefix that is cast into canvas pointer x/y events, default: "offset" */
910
- eventPrefix?: 'offset' | 'client' | 'page' | 'layer' | 'screen'
911
- }
912
-
913
- //* Loader Types ==============================
914
-
915
- type InputLike = string | string[] | string[][] | Readonly<string | string[] | string[][]>
916
-
917
- // Define a loader-like interface that matches THREE.Loader's load signature
918
- // This works for both generic and non-generic THREE.Loader instances
919
- interface LoaderLike {
920
- load(
921
- url: InputLike,
922
- onLoad?: (result: any) => void,
923
- onProgress?: (event: ProgressEvent<EventTarget>) => void,
924
- onError?: (error: unknown) => void,
925
- ): any
926
- }
927
-
928
- type GLTFLike = { scene: THREE$1.Object3D }
929
-
930
- type LoaderInstance<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
931
- T extends ConstructorRepresentation<LoaderLike> ? InstanceType<T> : T
932
-
933
- // Infer result type from the load method's callback parameter
934
- type InferLoadResult<T> = T extends {
935
- load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
936
- }
937
- ? R
938
- : T extends ConstructorRepresentation<any>
939
- ? InstanceType<T> extends {
940
- load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
941
- }
942
- ? R
943
- : any
944
- : any
945
-
946
- type LoaderResult<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> = InferLoadResult<
947
- LoaderInstance<T>
948
- > extends infer R
949
- ? R extends GLTFLike
950
- ? R & ObjectMap
951
- : R
952
- : never
953
-
954
- type Extensions<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> = (
955
- loader: LoaderInstance<T>,
1008
+ declare const presetsObj: {
1009
+ apartment: string;
1010
+ city: string;
1011
+ dawn: string;
1012
+ forest: string;
1013
+ lobby: string;
1014
+ night: string;
1015
+ park: string;
1016
+ studio: string;
1017
+ sunset: string;
1018
+ warehouse: string;
1019
+ };
1020
+ type PresetsType = keyof typeof presetsObj;
1021
+
1022
+ //* Background Types ==============================
1023
+
1024
+ /**
1025
+ * Expanded object form for background configuration.
1026
+ * Allows separate textures for background (visual backdrop) and environment (PBR lighting).
1027
+ */
1028
+ interface BackgroundConfig {
1029
+ /** HDRI preset name: 'apartment', 'city', 'dawn', 'forest', 'lobby', 'night', 'park', 'studio', 'sunset', 'warehouse' */
1030
+ preset?: PresetsType
1031
+ /** Files for cube texture (6 faces) or single HDR/EXR */
1032
+ files?: string | string[]
1033
+ /** Separate files for scene.background (visual backdrop) */
1034
+ backgroundMap?: string | string[]
1035
+ backgroundRotation?: Euler$1 | [number, number, number]
1036
+ backgroundBlurriness?: number
1037
+ backgroundIntensity?: number
1038
+ /** Separate files for scene.environment (PBR lighting/reflections) */
1039
+ envMap?: string | string[]
1040
+ environmentRotation?: Euler$1 | [number, number, number]
1041
+ environmentIntensity?: number
1042
+ path?: string
1043
+ extensions?: (loader: Loader) => void
1044
+ }
1045
+
1046
+ /**
1047
+ * Background prop type for Canvas.
1048
+ *
1049
+ * String detection priority:
1050
+ * 1. Preset - exact match against known presets (apartment, city, dawn, forest, lobby, night, park, studio, sunset, warehouse)
1051
+ * 2. URL - starts with /, ./, ../, http://, https://, OR has image extension
1052
+ * 3. Color - default fallback (CSS color names, hex values, rgb(), etc.)
1053
+ *
1054
+ * @example Color
1055
+ * ```tsx
1056
+ * <Canvas background="red" />
1057
+ * <Canvas background="#ff0000" />
1058
+ * <Canvas background={0xff0000} />
1059
+ * ```
1060
+ *
1061
+ * @example Preset
1062
+ * ```tsx
1063
+ * <Canvas background="city" />
1064
+ * ```
1065
+ *
1066
+ * @example URL
1067
+ * ```tsx
1068
+ * <Canvas background="/path/to/env.hdr" />
1069
+ * <Canvas background="./sky.jpg" />
1070
+ * ```
1071
+ *
1072
+ * @example Object form
1073
+ * ```tsx
1074
+ * <Canvas background={{
1075
+ * files: ['px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'],
1076
+ * backgroundMap: 'path/to/sky.jpg',
1077
+ * envMap: 'path/to/lighting.hdr',
1078
+ * backgroundBlurriness: 0.5,
1079
+ * }} />
1080
+ * ```
1081
+ */
1082
+ type BackgroundProp =
1083
+ | ColorRepresentation // "red", "#ff0000", 0xff0000
1084
+ | string // URL or preset
1085
+ | BackgroundConfig // Expanded object form
1086
+
1087
+ //* Canvas Types ==============================
1088
+
1089
+ interface CanvasProps
1090
+ extends
1091
+ Omit<RenderProps<HTMLCanvasElement>, 'size' | 'primaryCanvas' | 'scheduler'>,
1092
+ React$1.HTMLAttributes<HTMLDivElement> {
1093
+ children?: React$1.ReactNode
1094
+ ref?: React$1.Ref<HTMLCanvasElement>
1095
+ /** Canvas fallback content, similar to img's alt prop */
1096
+ fallback?: React$1.ReactNode
1097
+ /**
1098
+ * Options to pass to useMeasure.
1099
+ * @see https://github.com/pmndrs/react-use-measure#api
1100
+ */
1101
+ resize?: Options
1102
+ /** The target where events are being subscribed to, default: the div that wraps canvas */
1103
+ eventSource?: HTMLElement | React$1.RefObject<HTMLElement>
1104
+ /** The event prefix that is cast into canvas pointer x/y events, default: "offset" */
1105
+ eventPrefix?: 'offset' | 'client' | 'page' | 'layer' | 'screen'
1106
+ /** Enable/disable automatic HMR refresh for TSL nodes and uniforms, default: true in dev */
1107
+ hmr?: boolean
1108
+ /** Canvas resolution width in pixels. If omitted, uses container width. */
1109
+ width?: number
1110
+ /** Canvas resolution height in pixels. If omitted, uses container height. */
1111
+ height?: number
1112
+ /** Force canvas dimensions to even numbers (fixes Safari rendering issues with odd/fractional sizes) */
1113
+ forceEven?: boolean
1114
+ /**
1115
+ * Scene background configuration.
1116
+ * Accepts colors, URLs, presets, or an expanded object for separate background/environment.
1117
+ * @see BackgroundProp for full documentation and examples
1118
+ */
1119
+ background?: BackgroundProp
1120
+ }
1121
+
1122
+ //* Loader Types ==============================
1123
+
1124
+ type InputLike = string | string[] | string[][] | Readonly<string | string[] | string[][]>
1125
+
1126
+ // Define a loader-like interface that matches THREE.Loader's load signature
1127
+ // This works for both generic and non-generic THREE.Loader instances
1128
+ interface LoaderLike {
1129
+ load(
1130
+ url: InputLike,
1131
+ onLoad?: (result: any) => void,
1132
+ onProgress?: (event: ProgressEvent<EventTarget>) => void,
1133
+ onError?: (error: unknown) => void,
1134
+ ): any
1135
+ }
1136
+
1137
+ type GLTFLike = { scene: THREE$1.Object3D }
1138
+
1139
+ type LoaderInstance<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
1140
+ T extends ConstructorRepresentation<LoaderLike> ? InstanceType<T> : T
1141
+
1142
+ // Infer result type from the load method's callback parameter
1143
+ type InferLoadResult<T> = T extends {
1144
+ load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
1145
+ }
1146
+ ? R
1147
+ : T extends ConstructorRepresentation<any>
1148
+ ? InstanceType<T> extends {
1149
+ load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
1150
+ }
1151
+ ? R
1152
+ : any
1153
+ : any
1154
+
1155
+ type LoaderResult<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
1156
+ InferLoadResult<LoaderInstance<T>> extends infer R ? (R extends GLTFLike ? R & ObjectMap : R) : never
1157
+
1158
+ type Extensions<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> = (
1159
+ loader: LoaderInstance<T>,
956
1160
  ) => void
957
1161
 
958
- type WebGLDefaultProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & BaseRendererProps
959
-
960
- type WebGLProps =
961
- | RendererFactory<THREE$1.WebGLRenderer, WebGLDefaultProps>
962
- | Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters>
963
-
964
- interface WebGLShadowConfig {
965
- shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
1162
+ //* Renderer Props ========================================
1163
+
1164
+ type WebGLDefaultProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & BaseRendererProps
1165
+
1166
+ type WebGLProps =
1167
+ | RendererFactory<THREE$1.WebGLRenderer, WebGLDefaultProps>
1168
+ | Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters>
1169
+
1170
+ interface WebGLShadowConfig {
1171
+ shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
1172
+ }
1173
+
1174
+ //* Legacy-specific Types ========================================
1175
+
1176
+ /** Legacy (WebGL) renderer type - re-exported as R3FRenderer from @react-three/fiber/legacy */
1177
+ type LegacyRenderer = THREE$1.WebGLRenderer
1178
+
1179
+ /** Legacy internal state with narrowed renderer type */
1180
+ interface LegacyInternalState extends Omit<InternalState, 'actualRenderer'> {
1181
+ actualRenderer: THREE$1.WebGLRenderer
1182
+ }
1183
+
1184
+ /**
1185
+ * Legacy-specific RootState with narrowed renderer type.
1186
+ * Automatically used when importing from `@react-three/fiber/legacy`.
1187
+ *
1188
+ * @example
1189
+ * ```tsx
1190
+ * import { useThree } from '@react-three/fiber/legacy'
1191
+ *
1192
+ * function MyComponent() {
1193
+ * const { renderer } = useThree()
1194
+ * // renderer is typed as THREE.WebGLRenderer
1195
+ * renderer.shadowMap.enabled = true
1196
+ * }
1197
+ * ```
1198
+ */
1199
+ interface LegacyRootState extends Omit<RootState, 'renderer' | 'internal'> {
1200
+ /** The WebGL renderer instance */
1201
+ renderer: THREE$1.WebGLRenderer
1202
+ /** Internals with WebGL renderer */
1203
+ internal: LegacyInternalState
966
1204
  }
967
1205
 
968
- //* RenderTarget Types ==============================
969
-
970
-
1206
+ //* RenderTarget Types ==============================
1207
+
1208
+
971
1209
  type RenderTargetOptions = RenderTargetOptions$1
972
1210
 
973
- //* Global Types ==============================
974
-
975
- declare global {
976
- /** Uniform node type - a Node with a value property (matches Three.js UniformNode) */
977
- interface UniformNode<T = unknown> extends Node {
978
- value: T
979
- }
980
-
981
- /** Flat record of uniform nodes (no nested scopes) */
982
- type UniformRecord<T extends UniformNode = UniformNode> = Record<string, T>
983
-
984
- /**
985
- * Uniform store that can contain both root-level uniforms and scoped uniform objects
986
- * Used by state.uniforms which has structure like:
987
- * { uTime: UniformNode, player: { uHealth: UniformNode }, enemy: { uHealth: UniformNode } }
988
- */
989
- type UniformStore = Record<string, UniformNode | UniformRecord>
990
-
991
- /**
992
- * Helper to safely access a uniform node from the store.
993
- * Use this when accessing state.uniforms to get proper typing.
994
- * @example
995
- * const uTime = uniforms.uTime as UniformNode<number>
996
- * const uColor = uniforms.uColor as UniformNode<import('three/webgpu').Color>
997
- */
998
- type GetUniform<T = unknown> = UniformNode<T>
999
-
1000
- /**
1001
- * Acceptable input values for useUniforms - raw values that get converted to UniformNodes
1002
- * Supports: primitives, Three.js types, plain objects (converted to vectors), and UniformNodes
1003
- */
1004
- type UniformValue =
1005
- | number
1006
- | string
1007
- | boolean
1008
- | three_webgpu.Color
1009
- | three_webgpu.Vector2
1010
- | three_webgpu.Vector3
1011
- | three_webgpu.Vector4
1012
- | three_webgpu.Matrix3
1013
- | three_webgpu.Matrix4
1014
- | three_webgpu.Euler
1015
- | three_webgpu.Quaternion
1016
- | { x: number; y?: number; z?: number; w?: number } // Plain objects converted to vectors
1017
- | UniformNode
1018
-
1019
- /** Input record for useUniforms - accepts raw values or UniformNodes */
1020
- type UniformInputRecord = Record<string, UniformValue>
1021
- }
1022
-
1023
- //* Fn Return Type ==============================
1024
-
1025
- /** The return type of Fn() - a callable shader function node */
1026
- type ShaderCallable<R extends Node = Node> = ((...params: unknown[]) => ShaderNodeObject<R>) & Node
1027
-
1028
- //* Module Augmentation ==============================
1029
-
1030
- declare module 'three/tsl' {
1031
- /**
1032
- * Fn with array parameter destructuring
1033
- * @example Fn(([uv, skew]) => { ... })
1034
- */
1035
- export function Fn<R extends Node = Node>(
1036
- jsFunc: (inputs: ShaderNodeObject<Node>[]) => ShaderNodeObject<R>,
1037
- ): ShaderCallable<R>
1038
-
1039
- /**
1040
- * Fn with object parameter destructuring
1041
- * @example Fn(({ color, intensity }) => { ... })
1042
- */
1043
- export function Fn<T extends Record<string, unknown>, R extends Node = Node>(
1044
- jsFunc: (inputs: T) => ShaderNodeObject<R>,
1045
- ): ShaderCallable<R>
1046
-
1047
- /**
1048
- * Fn with array params + layout
1049
- * @example Fn(([a, b]) => { ... }, { layout: [...] })
1050
- */
1051
- export function Fn<R extends Node = Node>(
1052
- jsFunc: (inputs: ShaderNodeObject<Node>[]) => ShaderNodeObject<R>,
1053
- layout: { layout?: unknown },
1054
- ): ShaderCallable<R>
1055
-
1056
- /**
1057
- * Fn with object params + layout
1058
- */
1059
- export function Fn<T extends Record<string, unknown>, R extends Node = Node>(
1060
- jsFunc: (inputs: T) => ShaderNodeObject<R>,
1061
- layout: { layout?: unknown },
1062
- ): ShaderCallable<R>
1063
- }
1064
-
1065
- /**
1066
- * PostProcessing Types for usePostProcessing hook (WebGPU only)
1067
- */
1068
-
1069
-
1070
-
1071
- declare global {
1072
- /** Pass record - stores TSL pass nodes for post-processing */
1073
- type PassRecord = Record<string, any>
1074
-
1075
- /** Setup callback - runs first to configure MRT, create additional passes */
1076
- type PostProcessingSetupCallback = (state: RootState) => PassRecord | void
1077
-
1078
- /** Main callback - runs second to configure outputNode, create effect passes */
1079
- type PostProcessingMainCallback = (state: RootState) => PassRecord | void
1080
-
1081
- /** Return type for usePostProcessing hook */
1082
- interface UsePostProcessingReturn {
1083
- /** Current passes from state */
1084
- passes: PassRecord
1085
- /** PostProcessing instance (null if not initialized) */
1086
- postProcessing: any | null // THREE.PostProcessing
1087
- /** Clear all passes from state */
1088
- clearPasses: () => void
1089
- /** Reset PostProcessing entirely (clears PP + passes) */
1090
- reset: () => void
1091
- /** Re-run setup/main callbacks with current closure values */
1092
- rebuild: () => void
1093
- /** True when PostProcessing is configured and ready */
1094
- isReady: boolean
1095
- }
1096
- }
1097
-
1098
- //* useFrameNext Types ==============================
1099
-
1100
-
1101
-
1102
- //* Global Type Declarations ==============================
1103
-
1104
- declare global {
1105
- // Job --------------------------------
1106
-
1107
- /**
1108
- * Internal job representation in the scheduler
1109
- */
1110
- interface Job {
1111
- /** Unique identifier */
1112
- id: string
1113
- /** The callback to execute */
1114
- callback: FrameNextCallback
1115
- /** Phase this job belongs to */
1116
- phase: string
1117
- /** Run before these phases/job ids */
1118
- before: Set<string>
1119
- /** Run after these phases/job ids */
1120
- after: Set<string>
1121
- /** Priority within phase (higher first) */
1122
- priority: number
1123
- /** Insertion order for deterministic tie-breaking */
1124
- index: number
1125
- /** Max FPS for this job (undefined = no limit) */
1126
- fps?: number
1127
- /** Drop frames when behind (true) or catch up (false) */
1128
- drop: boolean
1129
- /** Last run timestamp (ms) */
1130
- lastRun?: number
1131
- /** Whether job is enabled */
1132
- enabled: boolean
1133
- /** Internal flag: system jobs (like default render) don't block user render takeover */
1134
- system?: boolean
1135
- }
1136
-
1137
- // Phase Graph --------------------------------
1138
-
1139
- /**
1140
- * A node in the phase graph
1141
- */
1142
- interface PhaseNode {
1143
- /** Phase name */
1144
- name: string
1145
- /** Whether this was auto-generated from a before/after constraint */
1146
- isAutoGenerated: boolean
1147
- }
1148
-
1149
- /**
1150
- * Options for creating a job from hook options
1151
- */
1152
- interface JobOptions {
1153
- id?: string
1154
- phase?: string
1155
- before?: string | string[]
1156
- after?: string | string[]
1157
- priority?: number
1158
- fps?: number
1159
- drop?: boolean
1160
- enabled?: boolean
1161
- }
1162
-
1163
- // Frame Loop State --------------------------------
1164
-
1165
- /**
1166
- * Internal frame loop state
1167
- */
1168
- interface FrameLoopState {
1169
- /** Whether the loop is running */
1170
- running: boolean
1171
- /** Current RAF handle */
1172
- rafHandle: number | null
1173
- /** Last frame timestamp in ms (null = uninitialized) */
1174
- lastTime: number | null
1175
- /** Frame counter */
1176
- frameCount: number
1177
- /** Elapsed time since first frame in ms */
1178
- elapsedTime: number
1179
- /** createdAt timestamp in ms */
1180
- createdAt: number
1181
- }
1182
-
1183
- // Root Entry --------------------------------
1184
-
1185
- /**
1186
- * Internal representation of a registered root (Canvas).
1187
- * Tracks jobs and manages rebuild state for this root.
1188
- * @internal
1189
- */
1190
- interface RootEntry {
1191
- /** Unique identifier for this root */
1192
- id: string
1193
- /** Function to get the root's current state. Returns any to support independent mode. */
1194
- getState: () => any
1195
- /** Map of job IDs to Job objects */
1196
- jobs: Map<string, Job>
1197
- /** Cached sorted job list for execution order */
1198
- sortedJobs: Job[]
1199
- /** Whether sortedJobs needs rebuilding */
1200
- needsRebuild: boolean
1201
- }
1202
-
1203
- /**
1204
- * Internal representation of a global job (deprecated API).
1205
- * Global jobs run once per frame, not per-root.
1206
- * Used by legacy addEffect/addAfterEffect APIs.
1207
- * @internal
1208
- * @deprecated Use useFrame with phases instead
1209
- */
1210
- interface GlobalJob {
1211
- /** Unique identifier for this global job */
1212
- id: string
1213
- /** Callback invoked with RAF timestamp in ms */
1214
- callback: (timestamp: number) => void
1215
- }
1216
-
1217
- // HMR Support --------------------------------
1218
-
1219
- /**
1220
- * Hot Module Replacement data structure for preserving scheduler state
1221
- * @internal
1222
- */
1223
- interface HMRData {
1224
- /** Shared data object for storing values across reloads */
1225
- data: Record<string, any>
1226
- /** Optional function to accept HMR updates */
1227
- accept?: () => void
1228
- }
1229
-
1230
- // Default Phases --------------------------------
1231
-
1232
- /**
1233
- * Default phase names for the scheduler
1234
- */
1235
- type DefaultPhase = 'start' | 'input' | 'physics' | 'update' | 'render' | 'finish'
1236
- }
1237
-
1238
- type MutableOrReadonlyParameters<T extends (...args: any) => any> = Parameters<T> | Readonly<Parameters<T>>
1239
-
1240
- interface MathRepresentation {
1241
- set(...args: number[]): any
1242
- }
1243
- interface VectorRepresentation extends MathRepresentation {
1244
- setScalar(value: number): any
1245
- }
1246
- type MathTypes = MathRepresentation | Euler$1 | Color$2
1247
-
1248
- type MathType<T extends MathTypes> = T extends Color$2
1249
- ? Args<typeof Color$2> | ColorRepresentation$1
1250
- : T extends VectorRepresentation | Layers$1 | Euler$1
1251
- ? T | MutableOrReadonlyParameters<T['set']> | number
1252
- : T | MutableOrReadonlyParameters<T['set']>
1253
-
1254
- type MathProps<P> = {
1255
- [K in keyof P as P[K] extends MathTypes ? K : never]: P[K] extends MathTypes ? MathType<P[K]> : never
1256
- }
1257
-
1258
- type Vector2 = MathType<Vector2$1>
1259
- type Vector3 = MathType<Vector3$1>
1260
- type Vector4 = MathType<Vector4$1>
1261
- type Color = MathType<Color$2>
1262
- type Layers = MathType<Layers$1>
1263
- type Quaternion = MathType<Quaternion$1>
1264
- type Euler = MathType<Euler$1>
1265
- type Matrix3 = MathType<Matrix3$1>
1266
- type Matrix4 = MathType<Matrix4$1>
1267
-
1268
- interface RaycastableRepresentation {
1269
- raycast(raycaster: Raycaster, intersects: Intersection$1[]): void
1270
- }
1271
- type EventProps<P> = P extends RaycastableRepresentation ? Partial<EventHandlers> : {}
1272
-
1273
- interface ReactProps<P> {
1274
- children?: React.ReactNode
1275
- ref?: React.Ref<P>
1276
- key?: React.Key
1277
- }
1278
-
1279
- type ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = Partial<
1280
- Overwrite<P, MathProps<P> & ReactProps<P> & EventProps<P>>
1281
- >
1282
-
1283
- type ThreeElement<T extends ConstructorRepresentation> = Mutable<
1284
- Overwrite<ElementProps<T>, Omit<InstanceProps<InstanceType<T>, T>, 'object'>>
1285
- >
1286
-
1287
- type ThreeToJSXElements<T extends Record<string, any>> = {
1288
- [K in keyof T & string as Uncapitalize<K>]: T[K] extends ConstructorRepresentation ? ThreeElement<T[K]> : never
1289
- }
1290
-
1291
- type ThreeExports = typeof THREE
1292
- type ThreeElementsImpl = ThreeToJSXElements<ThreeExports>
1293
-
1294
- interface ThreeElements extends Omit<ThreeElementsImpl, 'audio' | 'source' | 'line' | 'path'> {
1295
- primitive: Omit<ThreeElement<any>, 'args'> & { object: object }
1296
- // Conflicts with DOM types can be accessed through a three* prefix
1297
- threeAudio: ThreeElementsImpl['audio']
1298
- threeSource: ThreeElementsImpl['source']
1299
- threeLine: ThreeElementsImpl['line']
1300
- threePath: ThreeElementsImpl['path']
1301
- }
1302
-
1303
- declare module 'react' {
1304
- namespace JSX {
1305
- interface IntrinsicElements extends ThreeElements {}
1306
- }
1307
- }
1308
-
1309
- declare module 'react/jsx-runtime' {
1310
- namespace JSX {
1311
- interface IntrinsicElements extends ThreeElements {}
1312
- }
1313
- }
1314
-
1315
- declare module 'react/jsx-dev-runtime' {
1316
- namespace JSX {
1317
- interface IntrinsicElements extends ThreeElements {}
1318
- }
1211
+ //* Global Types ==============================
1212
+
1213
+ declare global {
1214
+ /** Uniform node type - a Node with a value property (matches Three.js UniformNode) */
1215
+ interface UniformNode<T = unknown> extends Node {
1216
+ value: T
1217
+ }
1218
+
1219
+ /**
1220
+ * ShaderCallable - the return type of Fn()
1221
+ * A callable shader function node that can be invoked with parameters.
1222
+ * The function returns a ShaderNodeObject when called.
1223
+ *
1224
+ * @example
1225
+ * ```tsx
1226
+ * // Define a shader function
1227
+ * const blendColorFn = Fn(([color1, color2, factor]) => {
1228
+ * return mix(color1, color2, factor)
1229
+ * })
1230
+ *
1231
+ * // Type when retrieving from nodes store
1232
+ * const { blendColorFn } = nodes as { blendColorFn: ShaderCallable }
1233
+ *
1234
+ * // Or with specific return type
1235
+ * const { myFn } = nodes as { myFn: ShaderCallable<THREE.Node> }
1236
+ * ```
1237
+ */
1238
+ type ShaderCallable<R extends Node = Node> = ((...params: unknown[]) => ShaderNodeObject<R>) & Node
1239
+
1240
+ /**
1241
+ * ShaderNodeRef - a ShaderNodeObject wrapper around a Node
1242
+ * This is the common return type for TSL operations (add, mul, sin, etc.)
1243
+ *
1244
+ * @example
1245
+ * ```tsx
1246
+ * const { wobble } = nodes as { wobble: ShaderNodeRef }
1247
+ * ```
1248
+ */
1249
+ type ShaderNodeRef<T extends Node = Node> = ShaderNodeObject<T>
1250
+
1251
+ /**
1252
+ * TSLNodeType - Union of all common TSL node types
1253
+ * Used by ScopedStore to properly type node access from the store.
1254
+ *
1255
+ * Includes:
1256
+ * - Node: base Three.js node type
1257
+ * - ShaderCallable: function nodes created with Fn()
1258
+ * - ShaderNodeObject: wrapped nodes from TSL operations (sin, mul, mix, etc.)
1259
+ *
1260
+ * @example
1261
+ * ```tsx
1262
+ * // In useLocalNodes, nodes are typed as TSLNodeType
1263
+ * const { positionNode, blendColorFn } = useLocalNodes(({ nodes }) => ({
1264
+ * positionNode: nodes.myPosition, // Works - Node is in union
1265
+ * blendColorFn: nodes.myFn, // Works - ShaderCallable is in union
1266
+ * }))
1267
+ *
1268
+ * // Can narrow with type guard or assertion when needed
1269
+ * if (typeof blendColorFn === 'function') {
1270
+ * blendColorFn(someColor, 0.5)
1271
+ * }
1272
+ * ```
1273
+ */
1274
+ type TSLNodeType = Node | ShaderCallable<Node> | ShaderNodeObject<Node>
1275
+
1276
+ /** Flat record of uniform nodes (no nested scopes) */
1277
+ type UniformRecord<T extends UniformNode = UniformNode> = Record<string, T>
1278
+
1279
+ /**
1280
+ * Uniform store that can contain both root-level uniforms and scoped uniform objects
1281
+ * Used by state.uniforms which has structure like:
1282
+ * { uTime: UniformNode, player: { uHealth: UniformNode }, enemy: { uHealth: UniformNode } }
1283
+ */
1284
+ type UniformStore = Record<string, UniformNode | UniformRecord>
1285
+
1286
+ /**
1287
+ * Helper to safely access a uniform node from the store.
1288
+ * Use this when accessing state.uniforms to get proper typing.
1289
+ * @example
1290
+ * const uTime = uniforms.uTime as UniformNode<number>
1291
+ * const uColor = uniforms.uColor as UniformNode<import('three/webgpu').Color>
1292
+ */
1293
+ type GetUniform<T = unknown> = UniformNode<T>
1294
+
1295
+ /**
1296
+ * Acceptable input values for useUniforms - raw values that get converted to UniformNodes
1297
+ * Supports:
1298
+ * - Primitives: number, string (color), boolean
1299
+ * - Three.js types: Color, Vector2/3/4, Matrix3/4, Euler, Quaternion
1300
+ * - Plain objects: { x, y, z, w } converted to vectors
1301
+ * - TSL nodes: color(), vec3(), float() for type casting
1302
+ * - UniformNode: existing uniforms (reused as-is)
1303
+ */
1304
+ type UniformValue =
1305
+ | number
1306
+ | string
1307
+ | boolean
1308
+ | three_webgpu.Color
1309
+ | three_webgpu.Vector2
1310
+ | three_webgpu.Vector3
1311
+ | three_webgpu.Vector4
1312
+ | three_webgpu.Matrix3
1313
+ | three_webgpu.Matrix4
1314
+ | three_webgpu.Euler
1315
+ | three_webgpu.Quaternion
1316
+ | { x: number; y?: number; z?: number; w?: number } // Plain objects converted to vectors
1317
+ | Node // TSL nodes like color(), vec3(), float() for type casting
1318
+ | UniformNode
1319
+
1320
+ /** Input record for useUniforms - accepts raw values or UniformNodes */
1321
+ type UniformInputRecord = Record<string, UniformValue>
1322
+ }
1323
+
1324
+ //* Module Augmentation ==============================
1325
+
1326
+ declare module 'three/tsl' {
1327
+ /**
1328
+ * Fn with array parameter destructuring
1329
+ * @example Fn(([uv, skew]) => { ... })
1330
+ */
1331
+ export function Fn<R extends Node = Node>(
1332
+ jsFunc: (inputs: ShaderNodeObject<Node>[]) => ShaderNodeObject<R>,
1333
+ ): ShaderCallable<R>
1334
+
1335
+ /**
1336
+ * Fn with object parameter destructuring
1337
+ * @example Fn(({ color, intensity }) => { ... })
1338
+ */
1339
+ export function Fn<T extends Record<string, unknown>, R extends Node = Node>(
1340
+ jsFunc: (inputs: T) => ShaderNodeObject<R>,
1341
+ ): ShaderCallable<R>
1342
+
1343
+ /**
1344
+ * Fn with array params + layout
1345
+ * @example Fn(([a, b]) => { ... }, { layout: [...] })
1346
+ */
1347
+ export function Fn<R extends Node = Node>(
1348
+ jsFunc: (inputs: ShaderNodeObject<Node>[]) => ShaderNodeObject<R>,
1349
+ layout: { layout?: unknown },
1350
+ ): ShaderCallable<R>
1351
+
1352
+ /**
1353
+ * Fn with object params + layout
1354
+ */
1355
+ export function Fn<T extends Record<string, unknown>, R extends Node = Node>(
1356
+ jsFunc: (inputs: T) => ShaderNodeObject<R>,
1357
+ layout: { layout?: unknown },
1358
+ ): ShaderCallable<R>
1359
+ }
1360
+
1361
+ /**
1362
+ * PostProcessing Types for usePostProcessing hook (WebGPU only)
1363
+ */
1364
+
1365
+
1366
+
1367
+ declare global {
1368
+ /** Pass record - stores TSL pass nodes for post-processing */
1369
+ type PassRecord = Record<string, any>
1370
+
1371
+ /** Setup callback - runs first to configure MRT, create additional passes */
1372
+ type PostProcessingSetupCallback = (state: RootState) => PassRecord | void
1373
+
1374
+ /** Main callback - runs second to configure outputNode, create effect passes */
1375
+ type PostProcessingMainCallback = (state: RootState) => PassRecord | void
1376
+
1377
+ /** Return type for usePostProcessing hook */
1378
+ interface UsePostProcessingReturn {
1379
+ /** Current passes from state */
1380
+ passes: PassRecord
1381
+ /** PostProcessing instance (null if not initialized) */
1382
+ postProcessing: any | null // THREE.PostProcessing
1383
+ /** Clear all passes from state */
1384
+ clearPasses: () => void
1385
+ /** Reset PostProcessing entirely (clears PP + passes) */
1386
+ reset: () => void
1387
+ /** Re-run setup/main callbacks with current closure values */
1388
+ rebuild: () => void
1389
+ /** True when PostProcessing is configured and ready */
1390
+ isReady: boolean
1391
+ }
1392
+ }
1393
+
1394
+ //* useFrameNext Types ==============================
1395
+
1396
+
1397
+
1398
+ //* Global Type Declarations ==============================
1399
+
1400
+ declare global {
1401
+ // Job --------------------------------
1402
+
1403
+ /**
1404
+ * Internal job representation in the scheduler
1405
+ */
1406
+ interface Job {
1407
+ /** Unique identifier */
1408
+ id: string
1409
+ /** The callback to execute */
1410
+ callback: FrameNextCallback
1411
+ /** Phase this job belongs to */
1412
+ phase: string
1413
+ /** Run before these phases/job ids */
1414
+ before: Set<string>
1415
+ /** Run after these phases/job ids */
1416
+ after: Set<string>
1417
+ /** Priority within phase (higher first) */
1418
+ priority: number
1419
+ /** Insertion order for deterministic tie-breaking */
1420
+ index: number
1421
+ /** Max FPS for this job (undefined = no limit) */
1422
+ fps?: number
1423
+ /** Drop frames when behind (true) or catch up (false) */
1424
+ drop: boolean
1425
+ /** Last run timestamp (ms) */
1426
+ lastRun?: number
1427
+ /** Whether job is enabled */
1428
+ enabled: boolean
1429
+ /** Internal flag: system jobs (like default render) don't block user render takeover */
1430
+ system?: boolean
1431
+ }
1432
+
1433
+ // Phase Graph --------------------------------
1434
+
1435
+ /**
1436
+ * A node in the phase graph
1437
+ */
1438
+ interface PhaseNode {
1439
+ /** Phase name */
1440
+ name: string
1441
+ /** Whether this was auto-generated from a before/after constraint */
1442
+ isAutoGenerated: boolean
1443
+ }
1444
+
1445
+ /**
1446
+ * Options for creating a job from hook options
1447
+ */
1448
+ interface JobOptions {
1449
+ id?: string
1450
+ phase?: string
1451
+ before?: string | string[]
1452
+ after?: string | string[]
1453
+ priority?: number
1454
+ fps?: number
1455
+ drop?: boolean
1456
+ enabled?: boolean
1457
+ }
1458
+
1459
+ // Frame Loop State --------------------------------
1460
+
1461
+ /**
1462
+ * Internal frame loop state
1463
+ */
1464
+ interface FrameLoopState {
1465
+ /** Whether the loop is running */
1466
+ running: boolean
1467
+ /** Current RAF handle */
1468
+ rafHandle: number | null
1469
+ /** Last frame timestamp in ms (null = uninitialized) */
1470
+ lastTime: number | null
1471
+ /** Frame counter */
1472
+ frameCount: number
1473
+ /** Elapsed time since first frame in ms */
1474
+ elapsedTime: number
1475
+ /** createdAt timestamp in ms */
1476
+ createdAt: number
1477
+ }
1478
+
1479
+ // Root Entry --------------------------------
1480
+
1481
+ /**
1482
+ * Internal representation of a registered root (Canvas).
1483
+ * Tracks jobs and manages rebuild state for this root.
1484
+ * @internal
1485
+ */
1486
+ interface RootEntry {
1487
+ /** Unique identifier for this root */
1488
+ id: string
1489
+ /** Function to get the root's current state. Returns any to support independent mode. */
1490
+ getState: () => any
1491
+ /** Map of job IDs to Job objects */
1492
+ jobs: Map<string, Job>
1493
+ /** Cached sorted job list for execution order */
1494
+ sortedJobs: Job[]
1495
+ /** Whether sortedJobs needs rebuilding */
1496
+ needsRebuild: boolean
1497
+ }
1498
+
1499
+ /**
1500
+ * Internal representation of a global job (deprecated API).
1501
+ * Global jobs run once per frame, not per-root.
1502
+ * Used by legacy addEffect/addAfterEffect APIs.
1503
+ * @internal
1504
+ * @deprecated Use useFrame with phases instead
1505
+ */
1506
+ interface GlobalJob {
1507
+ /** Unique identifier for this global job */
1508
+ id: string
1509
+ /** Callback invoked with RAF timestamp in ms */
1510
+ callback: (timestamp: number) => void
1511
+ }
1512
+
1513
+ // HMR Support --------------------------------
1514
+
1515
+ /**
1516
+ * Hot Module Replacement data structure for preserving scheduler state
1517
+ * @internal
1518
+ */
1519
+ interface HMRData {
1520
+ /** Shared data object for storing values across reloads */
1521
+ data: Record<string, any>
1522
+ /** Optional function to accept HMR updates */
1523
+ accept?: () => void
1524
+ }
1525
+
1526
+ // Default Phases --------------------------------
1527
+
1528
+ /**
1529
+ * Default phase names for the scheduler
1530
+ */
1531
+ type DefaultPhase = 'start' | 'input' | 'physics' | 'update' | 'render' | 'finish'
1532
+ }
1533
+
1534
+ type MutableOrReadonlyParameters<T extends (...args: any) => any> = Parameters<T> | Readonly<Parameters<T>>
1535
+
1536
+ interface MathRepresentation {
1537
+ set(...args: number[]): any
1538
+ }
1539
+ interface VectorRepresentation extends MathRepresentation {
1540
+ setScalar(value: number): any
1541
+ }
1542
+ type MathTypes = MathRepresentation | Euler$2 | Color$2
1543
+
1544
+ type MathType<T extends MathTypes> = T extends Color$2
1545
+ ? Args<typeof Color$2> | ColorRepresentation$1
1546
+ : T extends VectorRepresentation | Layers$1 | Euler$2
1547
+ ? T | MutableOrReadonlyParameters<T['set']> | number
1548
+ : T | MutableOrReadonlyParameters<T['set']>
1549
+
1550
+ type MathProps<P> = {
1551
+ [K in keyof P as P[K] extends MathTypes ? K : never]: P[K] extends MathTypes ? MathType<P[K]> : never
1552
+ }
1553
+
1554
+ type Vector2 = MathType<Vector2$1>
1555
+ type Vector3 = MathType<Vector3$1>
1556
+ type Vector4 = MathType<Vector4$1>
1557
+ type Color = MathType<Color$2>
1558
+ type Layers = MathType<Layers$1>
1559
+ type Quaternion = MathType<Quaternion$1>
1560
+ type Euler = MathType<Euler$2>
1561
+ type Matrix3 = MathType<Matrix3$1>
1562
+ type Matrix4 = MathType<Matrix4$1>
1563
+
1564
+ interface RaycastableRepresentation {
1565
+ raycast(raycaster: Raycaster, intersects: Intersection$1[]): void
1566
+ }
1567
+ type EventProps<P> = P extends RaycastableRepresentation ? Partial<EventHandlers> : {}
1568
+
1569
+ /**
1570
+ * Props for geometry transform methods that can be called with `once()`.
1571
+ * These methods modify the geometry in-place and only make sense to call once on mount.
1572
+ *
1573
+ * @example
1574
+ * import { once } from '@react-three/fiber'
1575
+ *
1576
+ * <boxGeometry args={[1, 1, 1]} rotateX={once(Math.PI / 2)} />
1577
+ * <planeGeometry args={[10, 10]} translate={once(0, 0, 5)} />
1578
+ * <bufferGeometry applyMatrix4={once(matrix)} center={once()} />
1579
+ */
1580
+ interface GeometryTransformProps {
1581
+ /** Rotate the geometry about the X axis (radians). Use with once(). */
1582
+ rotateX?: number
1583
+ /** Rotate the geometry about the Y axis (radians). Use with once(). */
1584
+ rotateY?: number
1585
+ /** Rotate the geometry about the Z axis (radians). Use with once(). */
1586
+ rotateZ?: number
1587
+ /** Translate the geometry (x, y, z). Use with once(). */
1588
+ translate?: [x: number, y: number, z: number]
1589
+ /** Scale the geometry (x, y, z). Use with once(). */
1590
+ scale?: [x: number, y: number, z: number]
1591
+ /** Center the geometry based on bounding box. Use with once(). */
1592
+ center?: true
1593
+ /** Apply a Matrix4 transformation. Use with once(). */
1594
+ applyMatrix4?: Matrix4$1
1595
+ /** Apply a Quaternion rotation. Use with once(). */
1596
+ applyQuaternion?: Quaternion$1
1597
+ }
1598
+
1599
+ type GeometryProps<P> = P extends BufferGeometry ? GeometryTransformProps : {}
1600
+
1601
+ /**
1602
+ * Workaround for @types/three TSL node type issues.
1603
+ * The Node base class has properties that subclasses (OperatorNode, ConstNode, etc.) don't inherit.
1604
+ * This transforms `Node | null` properties to accept any object with node-like shape.
1605
+ */
1606
+ type TSLNodeInput = { nodeType?: string | null; uuid?: string } | null
1607
+
1608
+ /**
1609
+ * For node material properties (colorNode, positionNode, etc.), accept broader types
1610
+ * since @types/three has broken inheritance for TSL node subclasses.
1611
+ */
1612
+ type NodeProps<P> = {
1613
+ [K in keyof P as P[K] extends Node | null ? K : never]?: TSLNodeInput
1614
+ }
1615
+
1616
+ interface ReactProps<P> {
1617
+ children?: React.ReactNode
1618
+ ref?: React.Ref<P>
1619
+ key?: React.Key
1620
+ }
1621
+
1622
+ type ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = Partial<
1623
+ Overwrite<P, MathProps<P> & ReactProps<P> & EventProps<P> & GeometryProps<P> & NodeProps<P>>
1624
+ >
1625
+
1626
+ type ThreeElement<T extends ConstructorRepresentation> = Mutable<
1627
+ Overwrite<ElementProps<T>, Omit<InstanceProps<InstanceType<T>, T>, 'object'>>
1628
+ >
1629
+
1630
+ type ThreeToJSXElements<T extends Record<string, any>> = {
1631
+ [K in keyof T & string as Uncapitalize<K>]: T[K] extends ConstructorRepresentation ? ThreeElement<T[K]> : never
1632
+ }
1633
+
1634
+ type ThreeExports = typeof THREE
1635
+ type ThreeElementsImpl = ThreeToJSXElements<ThreeExports>
1636
+
1637
+ interface ThreeElements extends Omit<ThreeElementsImpl, 'audio' | 'source' | 'line' | 'path'> {
1638
+ primitive: Omit<ThreeElement<any>, 'args'> & { object: object }
1639
+ // Conflicts with DOM types can be accessed through a three* prefix
1640
+ threeAudio: ThreeElementsImpl['audio']
1641
+ threeSource: ThreeElementsImpl['source']
1642
+ threeLine: ThreeElementsImpl['line']
1643
+ threePath: ThreeElementsImpl['path']
1644
+ }
1645
+
1646
+ declare module 'react' {
1647
+ namespace JSX {
1648
+ interface IntrinsicElements extends ThreeElements {}
1649
+ }
1650
+ }
1651
+
1652
+ declare module 'react/jsx-runtime' {
1653
+ namespace JSX {
1654
+ interface IntrinsicElements extends ThreeElements {}
1655
+ }
1656
+ }
1657
+
1658
+ declare module 'react/jsx-dev-runtime' {
1659
+ namespace JSX {
1660
+ interface IntrinsicElements extends ThreeElements {}
1661
+ }
1319
1662
  }
1320
1663
 
1321
1664
  type three_d_Color = Color;
1322
1665
  type three_d_ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = ElementProps<T, P>;
1323
1666
  type three_d_Euler = Euler;
1324
1667
  type three_d_EventProps<P> = EventProps<P>;
1668
+ type three_d_GeometryProps<P> = GeometryProps<P>;
1669
+ type three_d_GeometryTransformProps = GeometryTransformProps;
1325
1670
  type three_d_Layers = Layers;
1326
1671
  type three_d_MathProps<P> = MathProps<P>;
1327
1672
  type three_d_MathRepresentation = MathRepresentation;
@@ -1330,9 +1675,11 @@ type three_d_MathTypes = MathTypes;
1330
1675
  type three_d_Matrix3 = Matrix3;
1331
1676
  type three_d_Matrix4 = Matrix4;
1332
1677
  type three_d_MutableOrReadonlyParameters<T extends (...args: any) => any> = MutableOrReadonlyParameters<T>;
1678
+ type three_d_NodeProps<P> = NodeProps<P>;
1333
1679
  type three_d_Quaternion = Quaternion;
1334
1680
  type three_d_RaycastableRepresentation = RaycastableRepresentation;
1335
1681
  type three_d_ReactProps<P> = ReactProps<P>;
1682
+ type three_d_TSLNodeInput = TSLNodeInput;
1336
1683
  type three_d_ThreeElement<T extends ConstructorRepresentation> = ThreeElement<T>;
1337
1684
  type three_d_ThreeElements = ThreeElements;
1338
1685
  type three_d_ThreeElementsImpl = ThreeElementsImpl;
@@ -1343,8 +1690,318 @@ type three_d_Vector3 = Vector3;
1343
1690
  type three_d_Vector4 = Vector4;
1344
1691
  type three_d_VectorRepresentation = VectorRepresentation;
1345
1692
  declare namespace three_d {
1346
- 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 };
1693
+ 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 };
1694
+ }
1695
+
1696
+ /**
1697
+ * @fileoverview Registry for primary canvases that can be targeted by secondary canvases
1698
+ *
1699
+ * Enables multi-canvas WebGPU rendering where multiple Canvas components share
1700
+ * a single WebGPURenderer using Three.js CanvasTarget API.
1701
+ *
1702
+ * Primary canvas: Has `id` prop, creates its own renderer, registers here
1703
+ * Secondary canvas: Has `target="id"` prop, shares primary's renderer via CanvasTarget
1704
+ */
1705
+
1706
+ interface PrimaryCanvasEntry {
1707
+ /** The WebGPURenderer instance owned by this primary canvas */
1708
+ renderer: WebGPURenderer;
1709
+ /** The zustand store for this canvas */
1710
+ store: RootStore;
1711
+ }
1712
+ /**
1713
+ * Register a primary canvas that can be targeted by secondary canvases.
1714
+ *
1715
+ * @param id - Unique identifier for this primary canvas
1716
+ * @param renderer - The WebGPURenderer owned by this canvas
1717
+ * @param store - The zustand store for this canvas
1718
+ * @returns Cleanup function to unregister on unmount
1719
+ */
1720
+ declare function registerPrimary(id: string, renderer: WebGPURenderer, store: RootStore): () => void;
1721
+ /**
1722
+ * Get a registered primary canvas by id.
1723
+ *
1724
+ * @param id - The id of the primary canvas to look up
1725
+ * @returns The primary canvas entry or undefined if not found
1726
+ */
1727
+ declare function getPrimary(id: string): PrimaryCanvasEntry | undefined;
1728
+ /**
1729
+ * Wait for a primary canvas to be registered.
1730
+ * Returns immediately if already registered, otherwise waits.
1731
+ *
1732
+ * @param id - The id of the primary canvas to wait for
1733
+ * @param timeout - Optional timeout in ms (default: 5000)
1734
+ * @returns Promise that resolves with the primary canvas entry
1735
+ */
1736
+ declare function waitForPrimary(id: string, timeout?: number): Promise<PrimaryCanvasEntry>;
1737
+ /**
1738
+ * Check if a primary canvas with the given id exists.
1739
+ *
1740
+ * @param id - The id to check
1741
+ * @returns True if a primary canvas with this id is registered
1742
+ */
1743
+ declare function hasPrimary(id: string): boolean;
1744
+ /**
1745
+ * Unregister a primary canvas. Called on unmount.
1746
+ *
1747
+ * @param id - The id of the primary canvas to unregister
1748
+ */
1749
+ declare function unregisterPrimary(id: string): void;
1750
+ /**
1751
+ * Get all registered primary canvas ids. Useful for debugging.
1752
+ */
1753
+ declare function getPrimaryIds(): string[];
1754
+
1755
+ type EnvironmentLoaderProps = {
1756
+ files?: string | string[];
1757
+ path?: string;
1758
+ preset?: PresetsType;
1759
+ extensions?: (loader: Loader$1) => void;
1760
+ colorSpace?: ColorSpace;
1761
+ };
1762
+ /**
1763
+ * Loads environment textures for reflections and lighting.
1764
+ * Supports HDR files, presets, and cubemaps.
1765
+ *
1766
+ * @example Basic usage
1767
+ * ```jsx
1768
+ * const texture = useEnvironment({ preset: 'sunset' })
1769
+ * ```
1770
+ */
1771
+ declare function useEnvironment({ files, path, preset, colorSpace, extensions, }?: Partial<EnvironmentLoaderProps>): Texture$1<unknown> | CubeTexture;
1772
+ declare namespace useEnvironment {
1773
+ var preload: (preloadOptions?: EnvironmentLoaderPreloadOptions) => void;
1774
+ var clear: (clearOptions?: EnvironmentLoaderClearOptions) => void;
1775
+ }
1776
+ type EnvironmentLoaderPreloadOptions = Omit<EnvironmentLoaderProps, 'encoding'>;
1777
+ type EnvironmentLoaderClearOptions = Pick<EnvironmentLoaderProps, 'files' | 'preset'>;
1778
+
1779
+ /**
1780
+ * Props for Environment component that sets up global cubemap for PBR materials and backgrounds.
1781
+ *
1782
+ * @property children - React children to render into custom environment portal
1783
+ * @property frames - Number of frames to render the environment. Use 1 for static, Infinity for animated (default: 1)
1784
+ * @property near - Near clipping plane for cube camera (default: 0.1)
1785
+ * @property far - Far clipping plane for cube camera (default: 1000)
1786
+ * @property resolution - Resolution of the cube render target (default: 256)
1787
+ * @property background - Whether to set scene.background. Can be true, false, or "only" (which only sets background) (default: false)
1788
+ *
1789
+ * @property blur - @deprecated Use backgroundBlurriness instead
1790
+ * @property backgroundBlurriness - Blur factor between 0 and 1 for background (default: 0, requires three.js 0.146+)
1791
+ * @property backgroundIntensity - Intensity factor for background (default: 1, requires three.js 0.163+)
1792
+ * @property backgroundRotation - Rotation for background as Euler angles (default: [0,0,0], requires three.js 0.163+)
1793
+ * @property environmentIntensity - Intensity factor for environment lighting (default: 1, requires three.js 0.163+)
1794
+ * @property environmentRotation - Rotation for environment as Euler angles (default: [0,0,0], requires three.js 0.163+)
1795
+ *
1796
+ * @property map - Pre-existing texture to use as environment map
1797
+ * @property preset - HDRI Haven preset: 'apartment', 'city', 'dawn', 'forest', 'lobby', 'night', 'park', 'studio', 'sunset', 'warehouse'. Not for production use.
1798
+ * @property scene - Custom THREE.Scene or ref to apply environment to (default: uses default scene)
1799
+ * @property ground - Ground projection settings. Use true for defaults or object with:
1800
+ * - height: Height of camera used to create env map (default: 15)
1801
+ * - radius: Radius of the world (default: 60)
1802
+ * - scale: Scale of backside projected sphere (default: 1000)
1803
+ *
1804
+ * Additional loader props:
1805
+ * @property files - File path(s) for environment. Supports .hdr, .exr, gainmap .jpg/.webp, or array of 6 cube faces
1806
+ * @property path - Base path for file loading
1807
+ * @property extensions - Texture extensions override
1808
+ */
1809
+ type EnvironmentProps = {
1810
+ children?: React$1.ReactNode;
1811
+ frames?: number;
1812
+ near?: number;
1813
+ far?: number;
1814
+ resolution?: number;
1815
+ background?: boolean | 'only';
1816
+ /** deprecated, use backgroundBlurriness */
1817
+ blur?: number;
1818
+ backgroundBlurriness?: number;
1819
+ backgroundIntensity?: number;
1820
+ backgroundRotation?: Euler$3;
1821
+ environmentIntensity?: number;
1822
+ environmentRotation?: Euler$3;
1823
+ map?: Texture$1;
1824
+ preset?: PresetsType;
1825
+ scene?: Scene | React$1.RefObject<Scene>;
1826
+ ground?: boolean | {
1827
+ radius?: number;
1828
+ height?: number;
1829
+ scale?: number;
1830
+ };
1831
+ /** Solid color for background (alternative to files/preset) */
1832
+ color?: ColorRepresentation$1;
1833
+ /** Separate files for background (when different from environment files) */
1834
+ backgroundFiles?: string | string[];
1835
+ } & EnvironmentLoaderProps;
1836
+ /**
1837
+ * Internal component that applies a pre-existing texture as environment map.
1838
+ * Sets scene.environment and optionally scene.background.
1839
+ *
1840
+ * @example
1841
+ * ```jsx
1842
+ * <CubeCamera>{(texture) => <EnvironmentMap map={texture} />}</CubeCamera>
1843
+ * ```
1844
+ */
1845
+ declare function EnvironmentMap({ scene, background, map, ...config }: EnvironmentProps): null;
1846
+ /**
1847
+ * Internal component that loads environment textures from files or presets.
1848
+ * Uses HDRLoader for .hdr, EXRLoader for .exr, UltraHDRLoader for .jpg/.jpeg HDR,
1849
+ * GainMapLoader for gainmap .webp, or CubeTextureLoader for arrays of images.
1850
+ *
1851
+ * @example With preset
1852
+ * ```jsx
1853
+ * <EnvironmentCube preset="sunset" />
1854
+ * ```
1855
+ *
1856
+ * @example From HDR file
1857
+ * ```jsx
1858
+ * <EnvironmentCube files="environment.hdr" />
1859
+ * ```
1860
+ *
1861
+ * @example From gainmap (smallest footprint)
1862
+ * ```jsx
1863
+ * <EnvironmentCube files={['file.webp', 'file-gainmap.webp', 'file.json']} />
1864
+ * ```
1865
+ *
1866
+ * @example From cube faces
1867
+ * ```jsx
1868
+ * <EnvironmentCube files={['px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png']} />
1869
+ * ```
1870
+ */
1871
+ declare function EnvironmentCube({ background, scene, blur, backgroundBlurriness, backgroundIntensity, backgroundRotation, environmentIntensity, environmentRotation, ...rest }: EnvironmentProps): null;
1872
+ /**
1873
+ * Internal component that renders custom environment using a portal and cube camera.
1874
+ * Renders children into an off-buffer and films with a cube camera to create environment map.
1875
+ * Can be static (frames=1) or animated (frames=Infinity).
1876
+ *
1877
+ * @example Custom environment with sphere
1878
+ * ```jsx
1879
+ * <EnvironmentPortal background near={1} far={1000} resolution={256}>
1880
+ * <mesh scale={100}>
1881
+ * <sphereGeometry args={[1, 64, 64]} />
1882
+ * <meshBasicMaterial map={texture} side={THREE.BackSide} />
1883
+ * </mesh>
1884
+ * </EnvironmentPortal>
1885
+ * ```
1886
+ *
1887
+ * @example Animated environment
1888
+ * ```jsx
1889
+ * <EnvironmentPortal frames={Infinity} resolution={256}>
1890
+ * <Float>
1891
+ * <mesh />
1892
+ * </Float>
1893
+ * </EnvironmentPortal>
1894
+ * ```
1895
+ *
1896
+ * @example Mixed with preset
1897
+ * ```jsx
1898
+ * <EnvironmentPortal preset="warehouse">
1899
+ * <mesh />
1900
+ * </EnvironmentPortal>
1901
+ * ```
1902
+ */
1903
+ 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;
1904
+ declare module '@react-three/fiber' {
1905
+ interface ThreeElements {
1906
+ groundProjectedEnvImpl: ThreeElement$1<typeof GroundedSkybox>;
1907
+ }
1347
1908
  }
1909
+ /**
1910
+ * Sets up a global environment map for PBR materials and backgrounds.
1911
+ * Affects scene.environment and optionally scene.background unless a custom scene is passed.
1912
+ *
1913
+ * Supports multiple input methods:
1914
+ * - **Presets**: Selection of HDRI Haven assets (apartment, city, dawn, forest, lobby, night, park, studio, sunset, warehouse)
1915
+ * - **Files**: HDR (.hdr), EXR (.exr), gainmap JPEG (.jpg), gainmap WebP (.webp), or cube faces (array of 6 images)
1916
+ * - **Texture**: Pre-existing cube texture via `map` prop
1917
+ * - **Custom Scene**: Render children into environment using portal and cube camera
1918
+ * - **Ground Projection**: Project environment onto ground plane
1919
+ *
1920
+ * @remarks
1921
+ * - Preset property is NOT meant for production and may fail (relies on CDNs)
1922
+ * - Gainmap format has the smallest file footprint
1923
+ * - Use `frames={Infinity}` for animated environments with low resolution for performance
1924
+ * - Ground projection places models on the "ground" within the environment map
1925
+ * - Supports self-hosting with @pmndrs/assets using dynamic imports
1926
+ *
1927
+ * @example Basic preset usage
1928
+ * ```jsx
1929
+ * <Environment preset="sunset" />
1930
+ * ```
1931
+ *
1932
+ * @example From HDR file
1933
+ * ```jsx
1934
+ * <Environment files="/hdr/environment.hdr" />
1935
+ * ```
1936
+ *
1937
+ * @example From gainmap (smallest footprint)
1938
+ * ```jsx
1939
+ * <Environment files={['file.webp', 'file-gainmap.webp', 'file.json']} />
1940
+ * ```
1941
+ *
1942
+ * @example With self-hosted assets
1943
+ * ```jsx
1944
+ * import { suspend } from 'suspend-react'
1945
+ * const city = import('@pmndrs/assets/hdri/city.exr').then(m => m.default)
1946
+ *
1947
+ * <Environment files={suspend(city)} />
1948
+ * ```
1949
+ *
1950
+ * @example From existing texture
1951
+ * ```jsx
1952
+ * <CubeCamera>{(texture) => <Environment map={texture} />}</CubeCamera>
1953
+ * ```
1954
+ *
1955
+ * @example Custom environment scene
1956
+ * ```jsx
1957
+ * <Environment background near={1} far={1000} resolution={256}>
1958
+ * <mesh scale={100}>
1959
+ * <sphereGeometry args={[1, 64, 64]} />
1960
+ * <meshBasicMaterial map={texture} side={THREE.BackSide} />
1961
+ * </mesh>
1962
+ * </Environment>
1963
+ * ```
1964
+ *
1965
+ * @example Animated environment
1966
+ * ```jsx
1967
+ * <Environment frames={Infinity} resolution={256}>
1968
+ * <Float>
1969
+ * <mesh />
1970
+ * </Float>
1971
+ * </Environment>
1972
+ * ```
1973
+ *
1974
+ * @example Mixed custom scene with preset
1975
+ * ```jsx
1976
+ * <Environment background preset="warehouse">
1977
+ * <mesh />
1978
+ * </Environment>
1979
+ * ```
1980
+ *
1981
+ * @example With ground projection
1982
+ * ```jsx
1983
+ * <Environment ground={{ height: 15, radius: 60 }} preset="city" />
1984
+ * ```
1985
+ *
1986
+ * @example As background only
1987
+ * ```jsx
1988
+ * <Environment background="only" preset="sunset" />
1989
+ * ```
1990
+ *
1991
+ * @example With rotation and intensity
1992
+ * ```jsx
1993
+ * <Environment
1994
+ * background
1995
+ * backgroundBlurriness={0.5}
1996
+ * backgroundIntensity={0.8}
1997
+ * backgroundRotation={[0, Math.PI / 2, 0]}
1998
+ * environmentIntensity={1.2}
1999
+ * environmentRotation={[0, Math.PI / 4, 0]}
2000
+ * preset="studio"
2001
+ * />
2002
+ * ```
2003
+ */
2004
+ declare function Environment(props: EnvironmentProps): react_jsx_runtime.JSX.Element;
1348
2005
 
1349
2006
  declare function removeInteractivity(store: RootStore, object: Object3D): void;
1350
2007
  declare function createEvents(store: RootStore): {
@@ -1907,31 +2564,30 @@ declare function useTextures(): UseTexturesReturn;
1907
2564
  * - WebGPU build: Returns RenderTarget
1908
2565
  * - Default build: Returns whichever matches the active renderer
1909
2566
  *
1910
- * @param width - Target width (defaults to canvas width)
1911
- * @param height - Target height (defaults to canvas height)
1912
- * @param options - Three.js RenderTarget options
1913
- *
1914
2567
  * @example
1915
2568
  * ```tsx
1916
- * function PortalScene() {
1917
- * const fbo = useRenderTarget(512, 512, { depthBuffer: true })
1918
- *
1919
- * useFrame(({ renderer, scene, camera }) => {
1920
- * renderer.setRenderTarget(fbo)
1921
- * renderer.render(scene, camera)
1922
- * renderer.setRenderTarget(null)
1923
- * })
1924
- *
1925
- * return (
1926
- * <mesh>
1927
- * <planeGeometry />
1928
- * <meshBasicMaterial map={fbo.texture} />
1929
- * </mesh>
1930
- * )
1931
- * }
2569
+ * // Use canvas size
2570
+ * const fbo = useRenderTarget()
2571
+ *
2572
+ * // Use canvas size with options
2573
+ * const fbo = useRenderTarget({ samples: 4 })
2574
+ *
2575
+ * // Square render target
2576
+ * const fbo = useRenderTarget(512)
2577
+ *
2578
+ * // Square render target with options
2579
+ * const fbo = useRenderTarget(512, { depthBuffer: true })
2580
+ *
2581
+ * // Explicit dimensions
2582
+ * const fbo = useRenderTarget(512, 256)
2583
+ *
2584
+ * // Explicit dimensions with options
2585
+ * const fbo = useRenderTarget(512, 256, { samples: 4 })
1932
2586
  * ```
1933
2587
  */
1934
- declare function useRenderTarget(width?: number, height?: number, options?: RenderTargetOptions): RenderTarget<THREE$1.Texture<unknown>>;
2588
+ declare function useRenderTarget(options?: RenderTargetOptions): RenderTarget | WebGLRenderTarget;
2589
+ declare function useRenderTarget(size: number, options?: RenderTargetOptions): RenderTarget | WebGLRenderTarget;
2590
+ declare function useRenderTarget(width: number, height: number, options?: RenderTargetOptions): RenderTarget | WebGLRenderTarget;
1935
2591
 
1936
2592
  /**
1937
2593
  * Returns the R3F Canvas' Zustand store. Useful for [transient updates](https://github.com/pmndrs/zustand#transient-updates-for-often-occurring-state-changes).
@@ -2036,7 +2692,7 @@ declare function invalidate(state?: RootState, frames?: number, stackFrames?: bo
2036
2692
  *
2037
2693
  * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#advance
2038
2694
  */
2039
- declare function advance(timestamp: number, runGlobalEffects?: boolean, state?: RootState, frame?: XRFrame): void;
2695
+ declare function advance(timestamp: number): void;
2040
2696
 
2041
2697
  /* eslint-disable @definitelytyped/no-unnecessary-generics */
2042
2698
  declare function ReactReconciler<
@@ -3090,6 +3746,12 @@ declare const _roots: Map<HTMLCanvasElement | OffscreenCanvas, Root>;
3090
3746
  declare function createRoot<TCanvas extends HTMLCanvasElement | OffscreenCanvas>(canvas: TCanvas): ReconcilerRoot<TCanvas>;
3091
3747
  declare function unmountComponentAtNode<TCanvas extends HTMLCanvasElement | OffscreenCanvas>(canvas: TCanvas, callback?: (canvas: TCanvas) => void): void;
3092
3748
  declare function createPortal(children: ReactNode, container: Object3D | RefObject<Object3D | null> | RefObject<Object3D>, state?: InjectState): JSX.Element;
3749
+ interface PortalProps {
3750
+ children: ReactNode;
3751
+ state?: InjectState;
3752
+ container: Object3D | RefObject<Object3D | null> | RefObject<Object3D>;
3753
+ }
3754
+ declare function Portal({ children, container, state }: PortalProps): JSX.Element;
3093
3755
  /**
3094
3756
  * Force React to flush any updates inside the provided callback synchronously and immediately.
3095
3757
  * All the same caveats documented for react-dom's `flushSync` apply here (see https://react.dev/reference/react-dom/flushSync).
@@ -3518,22 +4180,148 @@ declare const hasConstructor: (object: unknown) => object is {
3518
4180
  constructor?: Function;
3519
4181
  };
3520
4182
 
4183
+ /**
4184
+ * Symbol marker for deferred ref resolution.
4185
+ * Used to identify values that should be resolved from refs after mount.
4186
+ */
4187
+ declare const FROM_REF: unique symbol;
4188
+ /**
4189
+ * Defers prop application until the referenced object is available.
4190
+ * Useful for props like `target` that need sibling refs to be populated.
4191
+ *
4192
+ * @param ref - React ref object to resolve at mount time
4193
+ * @returns A marker value that applyProps will resolve after mount
4194
+ *
4195
+ * @example
4196
+ * const targetRef = useRef<THREE.Object3D>(null)
4197
+ *
4198
+ * <group ref={targetRef} position={[-3, -2, -15]} />
4199
+ * <spotLight target={fromRef(targetRef)} intensity={100} />
4200
+ */
4201
+ declare function fromRef<T>(ref: React$1.RefObject<T | null>): T;
4202
+ /**
4203
+ * Type guard to check if a value is a fromRef marker.
4204
+ *
4205
+ * @param value - Value to check
4206
+ * @returns True if value is a fromRef marker
4207
+ */
4208
+ declare function isFromRef(value: unknown): value is {
4209
+ [FROM_REF]: React$1.RefObject<any>;
4210
+ };
4211
+
4212
+ /**
4213
+ * Symbol marker for mount-only method calls.
4214
+ * Used to identify methods that should only be called once on initial mount.
4215
+ */
4216
+ declare const ONCE: unique symbol;
4217
+ /**
4218
+ * Marks a method call to be executed only on initial mount.
4219
+ * Useful for geometry transforms that should not be reapplied on every render.
4220
+ *
4221
+ * When `args` prop changes (triggering reconstruction), the method will be
4222
+ * called again on the new instance since appliedOnce is not carried over.
4223
+ *
4224
+ * @param args - Arguments to pass to the method
4225
+ * @returns A marker value that applyProps will execute once
4226
+ *
4227
+ * @example
4228
+ * // Rotate geometry on mount
4229
+ * <boxGeometry args={[1, 1, 1]} rotateX={once(Math.PI / 2)} />
4230
+ *
4231
+ * // Multiple arguments
4232
+ * <bufferGeometry applyMatrix4={once(matrix)} />
4233
+ *
4234
+ * // No arguments
4235
+ * <geometry center={once()} />
4236
+ */
4237
+ declare function once<T>(...args: T[]): T;
4238
+ /**
4239
+ * Type guard to check if a value is a once marker.
4240
+ *
4241
+ * @param value - Value to check
4242
+ * @returns True if value is a once marker
4243
+ */
4244
+ declare function isOnce(value: unknown): value is {
4245
+ [ONCE]: any[] | true;
4246
+ };
4247
+
3521
4248
  /**
3522
4249
  * A DOM canvas which accepts threejs elements as children.
3523
4250
  * @see https://docs.pmnd.rs/react-three-fiber/api/canvas
3524
4251
  */
3525
4252
  declare function Canvas(props: CanvasProps): react_jsx_runtime.JSX.Element;
3526
4253
 
4254
+ /**
4255
+ * ScopedStore - Type-safe wrapper for nested stores (uniforms, nodes)
4256
+ *
4257
+ * Provides TypeScript-friendly access to uniform/node stores where the runtime
4258
+ * structure is `Record<string, T | Record<string, T>>` (leaf nodes or nested scopes).
4259
+ *
4260
+ * The wrapper uses a Proxy to:
4261
+ * 1. Return `T` for property access (type assumption: assumes leaf node)
4262
+ * 2. Provide `.scope(key)` method for explicit nested access
4263
+ * 3. Support iteration methods: has(), keys(), Object.keys(), for...in
4264
+ *
4265
+ * @example
4266
+ * ```tsx
4267
+ * useLocalNodes(({ uniforms }) => ({
4268
+ * wobble: sin(uniforms.uTime.mul(2)), // No cast needed!
4269
+ * playerHealth: uniforms.scope('player').uHealth // Explicit scope access
4270
+ * }))
4271
+ * ```
4272
+ */
4273
+
4274
+ /** Keys reserved for methods (excluded from index signature) */
4275
+ type MethodKeys = 'scope' | 'has' | 'keys';
4276
+ /**
4277
+ * Type-safe wrapper interface for accessing nested store data.
4278
+ * Property access returns `T` (assumes leaf node).
4279
+ * Use `.scope(key)` for nested object access.
4280
+ *
4281
+ * Uses mapped type with key filtering to exclude method names from index signature,
4282
+ * allowing methods to have their correct return types.
4283
+ */
4284
+ type ScopedStoreType<T> = {
4285
+ /** Direct property access returns the leaf type T (method keys excluded) */
4286
+ readonly [K in string as K extends MethodKeys ? never : K]: T;
4287
+ } & {
4288
+ /** Access a nested scope by key. Returns empty wrapper if scope doesn't exist. */
4289
+ scope(key: string): ScopedStoreType<T>;
4290
+ /** Check if a key exists in the store */
4291
+ has(key: string): boolean;
4292
+ /** Get all keys in the store */
4293
+ keys(): string[];
4294
+ };
4295
+ /**
4296
+ * Create a type-safe ScopedStore wrapper around store data.
4297
+ * @param data - The raw store data (uniforms or nodes from RootState)
4298
+ * @returns A ScopedStoreType wrapper with type-safe access
4299
+ */
4300
+ declare function createScopedStore<T>(data: Record<string, any>): ScopedStoreType<T>;
4301
+ /**
4302
+ * State type passed to creator functions with ScopedStore wrappers.
4303
+ * Provides type-safe access to uniforms and nodes without manual casting.
4304
+ */
4305
+ type CreatorState = Omit<RootState, 'uniforms' | 'nodes'> & {
4306
+ /** Type-safe uniform access - property access returns UniformNode */
4307
+ uniforms: ScopedStoreType<UniformNode>;
4308
+ /** Type-safe node access - property access returns TSLNodeType (Node | ShaderCallable | ShaderNodeObject) */
4309
+ nodes: ScopedStoreType<TSLNodeType>;
4310
+ };
4311
+
3527
4312
  /** Creator function that returns uniform inputs (can be raw values or UniformNodes) */
3528
- type UniformCreator<T extends UniformInputRecord = UniformInputRecord> = (state: RootState) => T;
4313
+ type UniformCreator<T extends UniformInputRecord = UniformInputRecord> = (state: CreatorState) => T;
3529
4314
  /** Function signature for removeUniforms util */
3530
4315
  type RemoveUniformsFn = (names: string | string[], scope?: string) => void;
3531
4316
  /** Function signature for clearUniforms util */
3532
4317
  type ClearUniformsFn = (scope?: string) => void;
4318
+ /** Function signature for rebuildUniforms util */
4319
+ type RebuildUniformsFn = (scope?: string) => void;
3533
4320
  /** Return type with utils included */
3534
4321
  type UniformsWithUtils<T extends UniformRecord = UniformRecord> = T & {
3535
4322
  removeUniforms: RemoveUniformsFn;
3536
4323
  clearUniforms: ClearUniformsFn;
4324
+ rebuildUniforms: RebuildUniformsFn;
3537
4325
  };
3538
4326
  declare function useUniforms(): UniformsWithUtils<UniformRecord & Record<string, UniformRecord>>;
3539
4327
  declare function useUniforms(scope: string): UniformsWithUtils;
@@ -3541,6 +4329,15 @@ declare function useUniforms<T extends UniformInputRecord>(creator: UniformCreat
3541
4329
  declare function useUniforms<T extends UniformInputRecord>(creator: UniformCreator<T>, scope: string): UniformsWithUtils<UniformRecord<UniformNode>>;
3542
4330
  declare function useUniforms<T extends UniformInputRecord>(uniforms: T): UniformsWithUtils<UniformRecord<UniformNode>>;
3543
4331
  declare function useUniforms<T extends UniformInputRecord>(uniforms: T, scope: string): UniformsWithUtils<UniformRecord<UniformNode>>;
4332
+ /**
4333
+ * Global rebuildUniforms function for HMR integration.
4334
+ * Clears cached uniforms and increments _hmrVersion to trigger re-creation.
4335
+ * Call this when HMR is detected to refresh all uniform creators.
4336
+ *
4337
+ * @param store - The R3F store (from useStore or context)
4338
+ * @param scope - Optional scope to rebuild ('root' for root only, string for specific scope, undefined for all)
4339
+ */
4340
+ declare function rebuildAllUniforms(store: ReturnType<typeof useStore>, scope?: string): void;
3544
4341
  /**
3545
4342
  * Remove uniforms by name from root level or a scope
3546
4343
  * @deprecated Use `const { removeUniforms } = useUniforms()` instead
@@ -3557,30 +4354,76 @@ declare function clearScope(set: ReturnType<typeof useStore>['setState'], scope:
3557
4354
  */
3558
4355
  declare function clearRootUniforms(set: ReturnType<typeof useStore>['setState']): void;
3559
4356
 
3560
- /** Supported uniform value types */
3561
- type UniformValue = number | boolean | Vector2$1 | Vector3$1 | Vector4$1 | Color$2 | Matrix3$1 | Matrix4$1;
3562
- /** Widen literal types to their base types (0 number, true → boolean) */
3563
- type Widen<T> = T extends number ? number : T extends boolean ? boolean : T;
4357
+ /**
4358
+ * Supported uniform value types:
4359
+ * - Raw values: number, boolean, Vector2, Vector3, Vector4, Color, Matrix3, Matrix4
4360
+ * - String colors: '#ff0000', 'red', 'rgb(255,0,0)' (auto-converted to Color)
4361
+ * - TSL nodes: color(), vec3(), float(), etc. (for type casting)
4362
+ * - UniformNode: existing uniforms (reused as-is)
4363
+ */
4364
+ type UniformValue = number | boolean | string | Vector2$1 | Vector3$1 | Vector4$1 | Color$2 | Matrix3$1 | Matrix4$1 | Node | UniformNode;
4365
+ /**
4366
+ * Widen literal types to their base types:
4367
+ * - 0 → number
4368
+ * - true → boolean
4369
+ * - '#ff0000' → Color (string colors are converted to Color objects)
4370
+ * - Node → Node (TSL nodes passed through for uniform type casting)
4371
+ */
4372
+ type Widen<T> = T extends number ? number : T extends boolean ? boolean : T extends string ? Color$2 : T;
3564
4373
  declare function useUniform<T extends UniformValue>(name: string): UniformNode<T>;
3565
4374
  declare function useUniform<T extends UniformValue>(name: string, value: T): UniformNode<Widen<T>>;
3566
4375
 
3567
- /** TSL node type - extends Three.js Node for material compatibility */
3568
- type TSLNode = Node;
3569
- type NodeRecord<T extends Node = Node> = Record<string, T>;
3570
- type NodeCreator<T extends NodeRecord> = (state: RootState) => T;
4376
+ /**
4377
+ * Minimal interface for TSL nodes.
4378
+ * Used instead of Three.js's Node type because the @types/three definitions
4379
+ * have inconsistencies where OperatorNode, ConstNode, etc. don't properly
4380
+ * extend Node with all required properties.
4381
+ */
4382
+ interface TSLNodeLike {
4383
+ uuid?: string;
4384
+ nodeType?: string | null;
4385
+ /** label method for chaining - sets the node's label and returns self */
4386
+ label?: ((label: string) => TSLNodeLike) | string;
4387
+ setName?: (name: string) => this;
4388
+ }
4389
+ /** TSL node type - alias for compatibility */
4390
+ type TSLNode = TSLNodeLike;
4391
+ /**
4392
+ * A record of TSL nodes - allows mixed node types (OperatorNode, ConstNode, etc.)
4393
+ * Uses TSLNodeLike for broader compatibility with Three.js's TSL type definitions.
4394
+ */
4395
+ type NodeRecord<T extends TSLNodeLike = TSLNodeLike> = Record<string, T>;
4396
+ /**
4397
+ * Creator function that returns a record of nodes.
4398
+ * Uses TSLNodeLike constraint to allow mixed node types
4399
+ * (e.g., { n: OperatorNode; color: ConstNode<Color> }) to pass type checking.
4400
+ */
4401
+ type NodeCreator<T extends Record<string, TSLNodeLike>> = (state: CreatorState) => T;
3571
4402
  /** Function signature for removeNodes util */
3572
4403
  type RemoveNodesFn = (names: string | string[], scope?: string) => void;
3573
4404
  /** Function signature for clearNodes util */
3574
4405
  type ClearNodesFn = (scope?: string) => void;
4406
+ /** Function signature for rebuildNodes util */
4407
+ type RebuildNodesFn = (scope?: string) => void;
3575
4408
  /** Return type with utils included */
3576
- type NodesWithUtils<T extends NodeRecord = NodeRecord> = T & {
4409
+ type NodesWithUtils<T extends Record<string, TSLNodeLike> = Record<string, TSLNodeLike>> = T & {
3577
4410
  removeNodes: RemoveNodesFn;
3578
4411
  clearNodes: ClearNodesFn;
4412
+ rebuildNodes: RebuildNodesFn;
3579
4413
  };
3580
- declare function useNodes(): NodesWithUtils<NodeRecord & Record<string, NodeRecord>>;
3581
- declare function useNodes(scope: string): NodesWithUtils;
3582
- declare function useNodes<T extends NodeRecord>(creator: NodeCreator<T>): NodesWithUtils<T>;
3583
- declare function useNodes<T extends NodeRecord>(creator: NodeCreator<T>, scope: string): NodesWithUtils<T>;
4414
+ declare function useNodes(): NodesWithUtils<Record<string, TSLNodeLike> & Record<string, Record<string, TSLNodeLike>>>;
4415
+ declare function useNodes(scope: string): NodesWithUtils<Record<string, TSLNodeLike>>;
4416
+ declare function useNodes<T extends Record<string, TSLNodeLike>>(creator: NodeCreator<T>): NodesWithUtils<T>;
4417
+ declare function useNodes<T extends Record<string, TSLNodeLike>>(creator: NodeCreator<T>, scope: string): NodesWithUtils<T>;
4418
+ /**
4419
+ * Global rebuildNodes function for HMR integration.
4420
+ * Clears cached nodes and increments _hmrVersion to trigger re-creation.
4421
+ * Call this when HMR is detected to refresh all node creators.
4422
+ *
4423
+ * @param store - The R3F store (from useStore or context)
4424
+ * @param scope - Optional scope to rebuild ('root' for root only, string for specific scope, undefined for all)
4425
+ */
4426
+ declare function rebuildAllNodes(store: ReturnType<typeof useStore>, scope?: string): void;
3584
4427
  /**
3585
4428
  * Remove nodes by name from root level or a scope
3586
4429
  * @deprecated Use `const { removeNodes } = useNodes()` instead
@@ -3597,8 +4440,8 @@ declare function clearNodeScope(set: ReturnType<typeof useStore>['setState'], sc
3597
4440
  */
3598
4441
  declare function clearRootNodes(set: ReturnType<typeof useStore>['setState']): void;
3599
4442
 
3600
- /** Creator receives RootState - destructure what you need. Returns any record. */
3601
- type LocalNodeCreator<T extends Record<string, unknown>> = (state: RootState) => T;
4443
+ /** Creator receives CreatorState with ScopedStore wrappers for type-safe access. Returns any record. */
4444
+ type LocalNodeCreator<T extends Record<string, unknown>> = (state: CreatorState) => T;
3602
4445
  /**
3603
4446
  * Creates local values that rebuild when uniforms, nodes, or textures change.
3604
4447
  *
@@ -3674,5 +4517,52 @@ declare function createTextureOperations(set: StoreApi<RootState>['setState']):
3674
4517
  */
3675
4518
  declare function usePostProcessing(mainCB?: PostProcessingMainCallback, setupCB?: PostProcessingSetupCallback): UsePostProcessingReturn;
3676
4519
 
3677
- 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, clearNodeScope, clearRootNodes, clearRootUniforms, clearScope, context, createEvents, createPointerEvents, createPortal, createRoot, createStore, createTextureOperations, 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, removeNodes, removeUniforms, resolve, unmountComponentAtNode, updateCamera, updateFrustum, useBridge, useFrame, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useLocalNodes, useMutableCallback, useNodes, usePostProcessing, useRenderTarget, useStore, useTexture, useTextures, useThree, useUniform, useUniforms };
3678
- export type { Act, AddPhaseOptions, Args, ArgsProp, AttachFnType, AttachType, BaseRendererProps, Bridge, Camera, CameraProps, CanvasProps, Catalogue, ClearNodesFn, ClearUniformsFn, 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, LocalNodeCreator, MappedTextureType, MathProps, MathRepresentation, MathType, MathTypes, Matrix3, Matrix4, Mutable, MutableOrReadonlyParameters, NodeCreator, NodeRecord, NodesWithUtils, NonFunctionKeys, ObjectMap, OffscreenCanvas$1 as OffscreenCanvas, Overwrite, Performance, PointerCaptureTarget, Properties, Quaternion, RaycastableRepresentation, ReactProps, ReconcilerRoot, RemoveNodesFn, RemoveUniformsFn, RenderCallback, RenderProps, RenderTargetOptions, Renderer, RendererFactory, RendererProps, Root, RootOptions, RootState, RootStore, SchedulerApi, SetBlock, Size, Subscription, TSLNode, TextureEntry, TextureOperations, ThreeCamera, ThreeElement, ThreeElements, ThreeElementsImpl, ThreeEvent, ThreeExports, ThreeToJSXElements, UnblockProps, UniformCreator, UniformValue, UniformsWithUtils, UseFrameNextOptions, UseFrameOptions, UseTextureOptions, UseTexturesReturn, Vector2, Vector3, Vector4, VectorRepresentation, Viewport, VisibilityEntry, WebGLDefaultProps, WebGLProps, WebGLShadowConfig, XRManager };
4520
+ //* Renderer Props ========================================
4521
+
4522
+ type WebGPUDefaultProps = Omit<WebGPURendererParameters, 'canvas'> & BaseRendererProps
4523
+
4524
+ type WebGPUProps =
4525
+ | RendererFactory<WebGPURenderer, WebGPUDefaultProps>
4526
+ | Partial<Properties<WebGPURenderer> | WebGPURendererParameters>
4527
+
4528
+ // WebGPU doesn't have shadow maps in the same way
4529
+ interface WebGPUShadowConfig {
4530
+ shadows?: boolean // Simplified for WebGPU
4531
+ }
4532
+
4533
+ //* WebGPU-specific Types ========================================
4534
+
4535
+ /** WebGPU renderer type - re-exported as R3FRenderer from @react-three/fiber/webgpu */
4536
+ type WebGPUR3FRenderer = WebGPURenderer
4537
+
4538
+ /** WebGPU internal state with narrowed renderer type */
4539
+ interface WebGPUInternalState extends Omit<InternalState, 'actualRenderer'> {
4540
+ actualRenderer: WebGPURenderer
4541
+ }
4542
+
4543
+ /**
4544
+ * WebGPU-specific RootState with narrowed renderer type.
4545
+ * Automatically used when importing from `@react-three/fiber/webgpu`.
4546
+ *
4547
+ * @example
4548
+ * ```tsx
4549
+ * import { useThree } from '@react-three/fiber/webgpu'
4550
+ *
4551
+ * function MyComponent() {
4552
+ * const { renderer } = useThree()
4553
+ * // renderer is typed as WebGPURenderer
4554
+ * renderer.compute(computePass)
4555
+ * }
4556
+ * ```
4557
+ */
4558
+ interface WebGPURootState extends Omit<RootState, 'renderer' | 'gl' | 'internal'> {
4559
+ /** @deprecated Use `renderer` instead */
4560
+ gl: WebGPURenderer
4561
+ /** The WebGPU renderer instance */
4562
+ renderer: WebGPURenderer
4563
+ /** Internals with WebGPU renderer */
4564
+ internal: WebGPUInternalState
4565
+ }
4566
+
4567
+ 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, clearNodeScope, clearRootNodes, clearRootUniforms, clearScope, context, createEvents, createPointerEvents, createPortal, createRoot, createScopedStore, createStore, createTextureOperations, 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, rebuildAllNodes, rebuildAllUniforms, reconciler, registerPrimary, removeInteractivity, removeNodes, removeUniforms, resolve, unmountComponentAtNode, unregisterPrimary, updateCamera, updateFrustum, useBridge, useEnvironment, useFrame, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useLocalNodes, useMutableCallback, useNodes, usePostProcessing, useRenderTarget, useStore, useTexture, useTextures, useThree, useUniform, useUniforms, waitForPrimary };
4568
+ export type { Act, AddPhaseOptions, Args, ArgsProp, AttachFnType, AttachType, BackgroundConfig, BackgroundProp, BaseRendererProps, Bridge, Camera, CameraProps, CanvasProps, CanvasSchedulerConfig, Catalogue, ClearNodesFn, ClearUniformsFn, Color, ComputeFunction, ConstructorRepresentation, CreatorState, 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, WebGPUInternalState as InternalState, Intersection, IntersectionEvent, IsAllOptional, IsOptional, Layers, LegacyInternalState, LegacyRenderer, LegacyRootState, LoaderInstance, LoaderLike, LoaderResult, LocalNodeCreator, MappedTextureType, MathProps, MathRepresentation, MathType, MathTypes, Matrix3, Matrix4, Mutable, MutableOrReadonlyParameters, NodeCreator, NodeProps, NodeRecord, NodesWithUtils, NonFunctionKeys, ObjectMap, OffscreenCanvas$1 as OffscreenCanvas, Overwrite, Performance, PointerCaptureTarget, PresetsType, PrimaryCanvasEntry, Properties, Quaternion, WebGPUR3FRenderer as R3FRenderer, RaycastableRepresentation, ReactProps, RebuildNodesFn, RebuildUniformsFn, ReconcilerRoot, RemoveNodesFn, RemoveUniformsFn, RenderCallback, RenderProps, RenderTargetOptions, Renderer, RendererConfigExtended, RendererFactory, RendererProps, Root, RootOptions, WebGPURootState as RootState, RootStore, SchedulerApi, ScopedStoreType, SetBlock, Size, Subscription, TSLNode, TSLNodeInput, TextureEntry, TextureOperations, ThreeCamera, ThreeElement, ThreeElements, ThreeElementsImpl, ThreeEvent, ThreeExports, ThreeToJSXElements, UnblockProps, UniformCreator, UniformValue, UniformsWithUtils, UseFrameNextOptions, UseFrameOptions, UseTextureOptions, UseTexturesReturn, Vector2, Vector3, Vector4, VectorRepresentation, Viewport, VisibilityEntry, WebGLDefaultProps, WebGLProps, WebGLShadowConfig, WebGPUDefaultProps, WebGPUProps, WebGPUShadowConfig, XRManager };