@react-three/fiber 10.0.0-canary.ea31ccd → 10.0.0-canary.ee5a08a

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.
Files changed (39) hide show
  1. package/dist/chunks/webgl.cjs +27 -0
  2. package/dist/chunks/webgl.mjs +11 -0
  3. package/dist/chunks/webgpu.cjs +37 -0
  4. package/dist/chunks/webgpu.mjs +21 -0
  5. package/dist/extension.cjs +13 -0
  6. package/dist/extension.d.cts +19 -0
  7. package/dist/extension.d.mts +19 -0
  8. package/dist/extension.d.ts +19 -0
  9. package/dist/extension.mjs +1 -0
  10. package/dist/index.cjs +97 -15371
  11. package/dist/index.d.cts +123 -3873
  12. package/dist/index.d.mts +123 -3873
  13. package/dist/index.d.ts +122 -3844
  14. package/dist/index.mjs +10 -15272
  15. package/dist/legacy.cjs +97 -15326
  16. package/dist/legacy.d.cts +114 -3874
  17. package/dist/legacy.d.mts +114 -3874
  18. package/dist/legacy.d.ts +115 -3849
  19. package/dist/legacy.mjs +14 -15230
  20. package/dist/shared/fiber.B0oukOFO.mjs +364 -0
  21. package/dist/shared/fiber.BDWBTuAk.d.mts +2797 -0
  22. package/dist/shared/fiber.BU0vBHc9.d.mts +48 -0
  23. package/dist/shared/fiber.Cx-UAmMb.d.ts +48 -0
  24. package/dist/shared/fiber.DAl4H27x.d.cts +48 -0
  25. package/dist/shared/fiber.DNgUv56V.d.ts +2797 -0
  26. package/dist/shared/fiber.DlTSmVjz.d.cts +2797 -0
  27. package/dist/shared/fiber.I5Q4dVvl.d.cts +778 -0
  28. package/dist/shared/fiber.I5Q4dVvl.d.mts +778 -0
  29. package/dist/shared/fiber.I5Q4dVvl.d.ts +778 -0
  30. package/dist/shared/fiber.khFlPHPf.cjs +397 -0
  31. package/dist/shared/fiber.oKEFddXj.cjs +16059 -0
  32. package/dist/shared/fiber.tsM9NKZ9.mjs +15961 -0
  33. package/dist/webgpu/index.cjs +100 -16211
  34. package/dist/webgpu/index.d.cts +112 -4190
  35. package/dist/webgpu/index.d.mts +112 -4190
  36. package/dist/webgpu/index.d.ts +112 -4162
  37. package/dist/webgpu/index.mjs +15 -16095
  38. package/package.json +11 -8
  39. package/readme.md +1 -1
@@ -1,4109 +1,88 @@
1
- import * as three_examples_jsm_inspector_Inspector_js from 'three/examples/jsm/inspector/Inspector.js';
2
- import * as three_webgpu from 'three/webgpu';
3
- import { CubeRenderTarget, RenderTarget, WebGPURenderer, Node, StorageTexture, Storage3DTexture, StorageArrayTexture, Data3DTexture, CanvasTarget, 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, Object3D, 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, Frustum, OrthographicCamera, Matrix2, WebGPURendererParameters } from 'three/webgpu';
4
- import { Inspector } from 'three/addons/inspector/Inspector.js';
5
- import * as THREE$1 from 'three';
6
- import { Color as Color$1, ColorRepresentation, Euler as Euler$1, Loader, RenderTargetOptions as RenderTargetOptions$1 } from 'three';
7
- import * as React$1 from 'react';
8
- import { ReactNode, Component, RefObject, JSX } from 'react';
1
+ import * as ThreeWebGPU from 'three/webgpu';
2
+ import { WebGPURenderer, WebGPURendererParameters, RenderTarget } from 'three/webgpu';
3
+ import { M as MutableOrReadonlyParameters$1, a as MathRepresentation$1, V as VectorRepresentation$1, b as MathTypes$1, c as MathType$1, d as MathProps$1, e as Vector2$1, f as Vector3$1, g as Vector4$1, C as Color$1, L as Layers$1, Q as Quaternion$1, E as Euler$1, h as Matrix3$1, i as Matrix4$1, R as RaycastableRepresentation$1, j as EventProps$1, G as GeometryTransformProps$1, k as GeometryProps$1, T as TSLNodeInput$1, N as NodeProps$1, l as ReactProps$1, m as ElementProps$1, n as ThreeElement$1, o as ThreeToJSXElements$1, O as Object3DMethod$1, p as ThreeElementsOf$1, q as ElementOf$1, z as RendererFactory, B as BaseRendererProps, t as CanvasProps, s as ReconcilerRoot, r as RenderTargetOptions } from '../shared/fiber.DNgUv56V.js';
4
+ export { Z as BackgroundConfig, _ as BackgroundProp, aZ as Block, S as CameraProps, J as CanvasSchedulerConfig, D as ColorManagementConfig, F as DefaultGLProps, I as DefaultRendererProps, aD as DisposeOptions, an as Environment, al as EnvironmentCube, aG as EnvironmentLoaderProps, ak as EnvironmentMap, am as EnvironmentPortal, aj as EnvironmentProps, a_ as ErrorBoundary, a5 as Extensions, bs as FROM_REF, bt as FromRefMarker, H as GLProps, a1 as GLTFLike, Y as GlobalEffectType, X as GlobalRenderCallback, a3 as InferLoadResult, W as InjectState, $ as InputLike, aw as IsObject, aa as LegacyInternalState, a9 as LegacyRenderer, ab as LegacyRootState, a2 as LoaderInstance, a0 as LoaderLike, a4 as LoaderResult, ax as MappedTextureType, bw as ONCE, y as OffscreenCanvas, by as OnceValue, aT as Portal, ap as PresetsType, ac as PrimaryCanvasEntry, a$ as REACT_INTERNAL_PROPS, b7 as RESERVED_PROPS, U as RenderProps, A as Renderer, K as RendererConfigExtended, P as RendererProps, aA as Texture, aB as TextureInput, aC as TextureResult, ay as UseTextureOptions, aE as UseTexturesReturn, a6 as WebGLDefaultProps, a7 as WebGLProps, a8 as WebGLShadowConfig, aQ as _roots, aJ as addAfterEffect, aI as addEffect, aK as addTail, aM as advance, bc as applyProps, b9 as attach, b2 as buildGraph, bd as calculateDpr, as as createEvents, u as createPointerEvents, aS as createPortal, aV as createStore, ba as detach, bb as diffProps, b3 as dispose, u as events, aN as extend, b0 as findInitialRoot, aU as flushSync, bu as fromRef, b4 as getInstanceProps, ae as getPrimary, ai as getPrimaryIds, b1 as getRootState, v as getThree, be as getUuidPrefix, br as hasConstructor, ag as hasPrimary, w as hasThree, aL as invalidate, b6 as invalidateInstance, bh as is, bk as isColorRepresentation, bq as isCopyable, bv as isFromRef, bn as isLayers, bl as isObject3D, bz as isOnce, bi as isOrthographicCamera, bj as isRef, aP as isRenderer, bm as isTexture, bo as isUniform, bp as isVectorLike, bx as once, b5 as prepare, ao as presetsObj, aO as reconciler, ad as registerPrimary, ar as removeInteractivity, b8 as resolve, aq as swapInteractivity, aR as unmountComponentAtNode, ah as unregisterPrimary, bf as updateCamera, bg as updateFrustum, aY as useBridge, aH as useEnvironment, au as useGraph, at as useInstanceHandle, aW as useIsomorphicLayoutEffect, av as useLoader, aX as useMutableCallback, az as useTexture, aF as useTextures, af as waitForPrimary, x as whenThree } from '../shared/fiber.DNgUv56V.js';
5
+ import { C as ConstructorRepresentation, f as RootState, I as InternalState, J as Properties } from '../shared/fiber.I5Q4dVvl.js';
6
+ export { U as Act, y as Args, z as ArgsProp, A as AttachFnType, w as AttachType, W as Bridge, i as Camera, x as Catalogue, n as ComputeFunction, a0 as Disposable, k as DomEvent, D as Dpr, $ as EquConfig, l as EventHandlers, p as EventManager, E as Events, u as FiberRoot, m as FilterFunction, ae as ForRegisteredRenderer, a4 as FrameCallback, a3 as FrameNextCallback, a1 as FrameNextState, a2 as FrameState, F as Frameloop, H as HostConfig, G as Instance, B as InstanceProps, h as Intersection, j as IntersectionEvent, L as IsAllOptional, K as IsOptional, M as Mutable, N as NonFunctionKeys, _ as ObjectMap, a7 as OcclusionSupport, O as Overwrite, e as Performance, q as PointerCaptureTarget, P as PointerState, R as R3FRenderTarget, af as R3FRendererSupport, ac as Register, ad as RegisteredRenderer, d as RenderCallback, ab as RendererProvider, aa as RendererSupport, v as Root, a as RootExtension, g as RootStore, Y as SetBlock, c as Size, S as Subscription, Q as ThreeCamera, a6 as ThreeCore, T as ThreeEvent, a5 as ThreeNamespace, Z as UnblockProps, V as Viewport, t as VisibilityEntry, a8 as WebGLSupport, a9 as WebGPUSupport, X as XRManager, o as XRPointerConfig, ai as context, r as registerRootExtension, s as setRenderOverride, ag as useStore } from '../shared/fiber.I5Q4dVvl.js';
7
+ import { Texture } from 'three';
9
8
  import { StoreApi } from 'zustand';
10
- import { UseBoundStoreWithEqualityFn } from 'zustand/traditional';
11
- import { FrameTimingState, FrameCallback as FrameCallback$1, SchedulerApi, UseFrameNextOptions, FrameNextControls } from '@pmndrs/scheduler';
9
+ import { FrameCallback, UseFrameNextOptions, FrameNextControls } from '@pmndrs/scheduler';
12
10
  export { AddPhaseOptions, FrameControls, FrameNextControls, FrameTimingState, RootOptions, Scheduler, SchedulerApi, UseFrameNextOptions, UseFrameOptions, getScheduler } from '@pmndrs/scheduler';
13
- import { Options } from 'react-use-measure';
14
- import * as react_jsx_runtime from 'react/jsx-runtime';
15
- import { GroundedSkybox } from 'three/examples/jsm/objects/GroundedSkybox.js';
16
-
17
-
18
- /**
19
- * @fileoverview Internal Three.js re-exports - WEBGPU ONLY ENTRY
20
- *
21
- * Pure WebGPU path - no WebGL legacy.
22
- * Use this for the explicit webgpu import path: @react-three/fiber/webgpu
23
- *
24
- * This is for apps that want ONLY WebGPU with no legacy fallback.
25
- * Attempting to use WebGLRenderer will cause type/runtime errors (intentional).
26
- */
27
- declare const R3F_BUILD_LEGACY = false;
28
- declare const R3F_BUILD_WEBGPU = true;
29
-
30
- /** Lazily load the three Inspector. Keeps it out of the eager module graph — see note above. */
31
- declare function loadInspector(): Promise<typeof three_examples_jsm_inspector_Inspector_js.Inspector>;
32
- declare const WebGLRenderer: {
33
- new (): {};
34
- };
35
- type WebGLRendererParameters = never;
36
- type WebGLShadowMap = never;
37
-
38
- declare const WebGLRenderTarget: any;
39
-
40
- declare const WebGLCubeRenderTarget: any;
41
-
42
-
43
- //* Utility Types ==============================
44
-
45
- type NonFunctionKeys<P> = { [K in keyof P]-?: P[K] extends Function ? never : K }[keyof P]
46
- type Overwrite<P, O> = Omit<P, NonFunctionKeys<O>> & O
47
- type Properties<T> = Pick<T, NonFunctionKeys<T>>
48
- type Mutable<P> = { -readonly [K in keyof P]: P[K] }
49
- type IsOptional<T> = undefined extends T ? true : false
50
- type IsAllOptional<T extends any[]> = T extends [infer First, ...infer Rest]
51
- ? IsOptional<First> extends true
52
- ? IsAllOptional<Rest>
53
- : false
54
- : true
55
-
56
- //* Camera Types ==============================
57
-
58
- type ThreeCamera = (THREE$1.OrthographicCamera | THREE$1.PerspectiveCamera) & { manual?: boolean }
59
-
60
- //* Act Type ==============================
61
-
62
- type Act = <T = any>(cb: () => Promise<T>) => Promise<T>
63
-
64
- //* Bridge & Block Types ==============================
65
-
66
- type Bridge = React$1.FC<{ children?: React$1.ReactNode }>
67
-
68
- type SetBlock = false | Promise<null> | null
69
- type UnblockProps = { set: React$1.Dispatch<React$1.SetStateAction<SetBlock>>; children: React$1.ReactNode }
70
-
71
- //* Object Map Type ==============================
72
-
73
- /* Original version
74
- export interface ObjectMap {
75
- nodes: { [name: string]: THREE.Object3D }
76
- materials: { [name: string]: THREE.Material }
77
- meshes: { [name: string]: THREE.Mesh }
78
- }
79
- */
80
- /* This version is an expansion found in a PR by itsdouges that seems abandoned but looks useful.
81
- It allows expansion but falls back to the original shape. (deleted due to stale, but If it doesnt conflict
82
- I will keep the use here)
83
- https://github.com/pmndrs/react-three-fiber/commits/generic-object-map/
84
- His description is:
85
- The object map type is now generic and can optionally declare the available properties for nodes, materials, and meshes.
86
- */
87
- interface ObjectMap<
88
- T extends { nodes?: string; materials?: string; meshes?: string } = {
89
- nodes: string
90
- materials: string
91
- meshes: string
92
- },
93
- > {
94
- nodes: Record<T['nodes'] extends string ? T['nodes'] : string, THREE$1.Object3D>
95
- materials: Record<T['materials'] extends string ? T['materials'] : string, THREE$1.Material>
96
- meshes: Record<T['meshes'] extends string ? T['meshes'] : string, THREE$1.Mesh>
97
- }
98
-
99
- //* Equality Config ==============================
100
-
101
- interface EquConfig {
102
- /** Compare arrays by reference equality a === b (default), or by shallow equality */
103
- arrays?: 'reference' | 'shallow'
104
- /** Compare objects by reference equality a === b (default), or by shallow equality */
105
- objects?: 'reference' | 'shallow'
106
- /** If true the keys in both a and b must match 1:1 (default), if false a's keys must intersect b's */
107
- strict?: boolean
108
- }
109
-
110
- //* Disposable Type ==============================
111
-
112
- interface Disposable {
113
- type?: string
114
- dispose?: () => void
115
- }
116
-
117
- //* Event-related Types =====================================
118
-
119
- interface Intersection extends THREE$1.Intersection {
120
- /** The event source (the object which registered the handler) */
121
- eventObject: THREE$1.Object3D
122
- }
123
-
124
- type Camera = THREE$1.OrthographicCamera | THREE$1.PerspectiveCamera
125
-
126
- interface IntersectionEvent<TSourceEvent> extends Intersection {
127
- /** The event source (the object which registered the handler) */
128
- eventObject: THREE$1.Object3D
129
- /** An array of intersections */
130
- intersections: Intersection[]
131
- /** vec3.set(pointer.x, pointer.y, 0).unproject(camera) */
132
- unprojectedPoint: THREE$1.Vector3
133
- /** Normalized event coordinates */
134
- pointer: THREE$1.Vector2
135
- /** pointerId of the original event for multiple pointer events */
136
- pointerId: number
137
- /** Delta between first click and this event */
138
- delta: number
139
- /** The ray that pierced it */
140
- ray: THREE$1.Ray
141
- /** The camera that was used by the raycaster */
142
- camera: Camera
143
- /** stopPropagation will stop underlying handlers from firing */
144
- stopPropagation: () => void
145
- /** The original host event */
146
- nativeEvent: TSourceEvent
147
- /** If the event was stopped by calling stopPropagation */
148
- stopped: boolean
149
- }
150
-
151
- type ThreeEvent<TEvent> = IntersectionEvent<TEvent> & Properties<TEvent>
152
- type DomEvent = PointerEvent | MouseEvent | WheelEvent
153
-
154
- /** DOM event handlers registered on the canvas element */
155
- interface Events {
156
- onClick: EventListener
157
- onContextMenu: EventListener
158
- onDoubleClick: EventListener
159
- onWheel: EventListener
160
- onPointerDown: EventListener
161
- onPointerUp: EventListener
162
- onPointerLeave: EventListener
163
- onPointerMove: EventListener
164
- onPointerCancel: EventListener
165
- onLostPointerCapture: EventListener
166
- onDragEnter: EventListener
167
- onDragLeave: EventListener
168
- onDragOver: EventListener
169
- onDrop: EventListener
170
- }
171
-
172
- /** Event handlers that can be attached to R3F objects (meshes, groups, etc.) */
173
- interface EventHandlers {
174
- onClick?: (event: ThreeEvent<MouseEvent>) => void
175
- onContextMenu?: (event: ThreeEvent<MouseEvent>) => void
176
- onDoubleClick?: (event: ThreeEvent<MouseEvent>) => void
177
- /** Fires continuously while dragging over the object */
178
- onDragOver?: (event: ThreeEvent<DragEvent>) => void
179
- /** Fires once when drag enters the object */
180
- onDragOverEnter?: (event: ThreeEvent<DragEvent>) => void
181
- /** Fires once when drag leaves the object */
182
- onDragOverLeave?: (event: ThreeEvent<DragEvent>) => void
183
- /** Fires when drag misses this object (for objects that have drag handlers) */
184
- onDragOverMissed?: (event: DragEvent) => void
185
- /** Fires when a drop occurs on this object */
186
- onDrop?: (event: ThreeEvent<DragEvent>) => void
187
- /** Fires when a drop misses this object (for objects that have drop handlers) */
188
- onDropMissed?: (event: DragEvent) => void
189
- onPointerUp?: (event: ThreeEvent<PointerEvent>) => void
190
- onPointerDown?: (event: ThreeEvent<PointerEvent>) => void
191
- onPointerOver?: (event: ThreeEvent<PointerEvent>) => void
192
- onPointerOut?: (event: ThreeEvent<PointerEvent>) => void
193
- onPointerEnter?: (event: ThreeEvent<PointerEvent>) => void
194
- onPointerLeave?: (event: ThreeEvent<PointerEvent>) => void
195
- onPointerMove?: (event: ThreeEvent<PointerEvent>) => void
196
- onPointerMissed?: (event: MouseEvent) => void
197
- onPointerCancel?: (event: ThreeEvent<PointerEvent>) => void
198
- onWheel?: (event: ThreeEvent<WheelEvent>) => void
199
- onLostPointerCapture?: (event: ThreeEvent<PointerEvent>) => void
200
-
201
- //* Visibility Events --------------------------------
202
- /** Fires when object enters/exits camera frustum. Receives true when in view, false when out. */
203
- onFramed?: (inView: boolean) => void
204
- /** Fires when object occlusion state changes (WebGPU only, requires occlusionTest=true on object) */
205
- onOccluded?: (occluded: boolean) => void
206
- /** Fires when combined visibility changes (frustum + occlusion + visible prop) */
207
- onVisible?: (visible: boolean) => void
208
- }
209
-
210
- type FilterFunction = (items: THREE$1.Intersection[], state: RootState) => THREE$1.Intersection[]
211
- type ComputeFunction = (event: DomEvent, root: RootState, previous?: RootState) => void
212
-
213
- /** Configuration for XR pointer registration (controllers/hands) */
214
- interface XRPointerConfig {
215
- /** Ray origin (updated each frame by XR system) */
216
- ray: THREE$1.Ray
217
- /** Optional: custom compute function for this pointer */
218
- compute?: (state: RootState) => void
219
- /** Pointer type identifier */
220
- type: 'controller' | 'hand' | 'gaze'
221
- /** Which hand (for controller/hand types) */
222
- handedness?: 'left' | 'right'
223
- }
224
-
225
- interface EventManager<TTarget> {
226
- /** Determines if the event layer is active */
227
- enabled: boolean
228
- /** Event layer priority, higher prioritized layers come first and may stop(-propagate) lower layer */
229
- priority: number
230
- /** The compute function needs to set up the raycaster and an xy- pointer */
231
- compute?: ComputeFunction
232
- /** The filter can re-order or re-structure the intersections */
233
- filter?: FilterFunction
234
- /** The target node the event layer is tied to */
235
- connected?: TTarget
236
- /** All the pointer event handlers through which the host forwards native events */
237
- handlers?: Events
238
- /** Allows re-connecting to another target */
239
- connect?: (target: TTarget) => void
240
- /** Removes all existing events handlers from the target */
241
- disconnect?: () => void
242
- /** Triggers a onPointerMove with the last known event. This can be useful to enable raycasting without
243
- * explicit user interaction, for instance when the camera moves a hoverable object underneath the cursor.
244
- * @param pointerId - Optional pointer ID to update specific pointer only
245
- */
246
- update?: (pointerId?: number) => void
247
- /** Defer pointer move raycasting to frame start (default: true) */
248
- frameTimedRaycasts?: boolean
249
- /** Always fire raycaster immediately on scroll events (default: true) */
250
- alwaysFireOnScroll?: boolean
251
- /** Automatically re-raycast every frame to detect hover changes from moving objects/camera (default: false) */
252
- updateOnFrame?: boolean
253
- /** Flush deferred pointer raycasts. Called by scheduler at frame start (input phase). */
254
- flush?: () => void
255
- /** Register an XR pointer (controller/hand). Returns assigned pointerId */
256
- registerPointer?: (config: XRPointerConfig) => number
257
- /** Unregister an XR pointer */
258
- unregisterPointer?: (pointerId: number) => void
259
- }
260
-
261
- interface PointerCaptureTarget {
262
- intersection: Intersection
263
- target: Element
264
- }
265
-
266
- //* Visibility System Types =====================================
267
-
268
- /** Entry in the visibility registry for tracking object visibility state */
269
- interface VisibilityEntry {
270
- object: THREE$1.Object3D
271
- handlers: Pick<EventHandlers, 'onFramed' | 'onOccluded' | 'onVisible'>
272
- lastFramedState: boolean | null
273
- lastOccludedState: boolean | null
274
- lastVisibleState: boolean | null
275
- }
276
-
277
- //* Scheduler Types (useFrame) ==============================
278
- //
279
- // The generic, framework-agnostic scheduler types now live in @pmndrs/scheduler.
280
- // This file re-exports them and layers r3f's RootState-aware frame state on top,
281
- // so existing `#types` imports across the codebase keep resolving unchanged.
282
-
283
-
284
-
285
- // Frame State (r3f-specific) --------------------------------
286
-
287
- /**
288
- * State passed to useFrame callbacks (extends RootState with timing).
289
- */
290
- interface FrameNextState extends RootState, FrameTimingState {}
291
-
292
- /** Alias for FrameNextState */
293
- type FrameState = FrameNextState
294
-
295
- // Callback Types (r3f-specific) --------------------------------
296
-
297
- /**
298
- * Callback function for useFrame. Receives the full r3f RootState plus timing.
299
- */
300
- type FrameNextCallback = FrameCallback$1<RootState>
301
-
302
- /** Alias for FrameNextCallback */
303
- type FrameCallback = FrameNextCallback
304
-
305
- //* Buffer Types (useBuffers) ========================================
306
-
307
- /**
308
- * Buffer-like types for GPU compute and storage operations.
309
- * Includes raw CPU arrays, Three.js buffer attributes, and TSL buffer nodes.
310
- *
311
- * @example
312
- * ```tsx
313
- * const { positions, velocities } = useBuffers(() => ({
314
- * positions: instancedArray(count, 'vec3'), // StorageBufferNode
315
- * velocities: new Float32Array(count * 3), // TypedArray
316
- * }), 'particles')
317
- * ```
318
- */
319
- type BufferLike =
320
- | Float32Array
321
- | Uint32Array
322
- | Int32Array
323
- | Float64Array
324
- | Uint8Array
325
- | Int8Array
326
- | Uint16Array
327
- | Int16Array
328
- | THREE$1.BufferAttribute // Base class for all buffer attributes
329
- | THREE$1.InterleavedBufferAttribute
330
- | Node // TSL buffer nodes (instancedArray, storage)
331
-
332
- /** Flat record of buffer-like values (no nested scopes) */
333
- type BufferRecord = Record<string, BufferLike>
334
-
335
- /**
336
- * Buffer store that can contain both root-level buffers and scoped buffer objects.
337
- * Structure: { positions: Float32Array, particles: { vel: StorageBufferNode } }
338
- */
339
- type BufferStore = Record<string, BufferLike | BufferRecord>
340
-
341
- //* Node Types (useNodes) ========================================
342
-
343
- /**
344
- * Every node representation `useNodes` accepts and `state.nodes` holds: three's real `Node`,
345
- * the callable proxy `Fn()` returns, and the legacy structural shape (`uuid`/`nodeType`) older
346
- * code passes through. Creators are constrained to this same type, so the shape a creator returns
347
- * and the shape the store holds are one type by construction.
348
- */
349
- type NodeLike = TSLNodeType | LegacyTSLNodeLike
350
-
351
- /** Flat record of TSL nodes (no nested scopes) */
352
- type NodeRecord<T extends NodeLike = NodeLike> = Record<string, T>
353
-
354
- /**
355
- * Node store that can contain both root-level nodes and scoped node objects.
356
- * Structure: { wobble: OperatorNode, fx: { blur: ShaderCallable } }
357
- */
358
- type NodeStore = Record<string, NodeLike | NodeRecord>
359
-
360
- //* Storage Types (useGPUStorage) ========================================
361
-
362
- /**
363
- * GPU storage types for texture-based storage operations.
364
- * Includes Three.js storage textures and TSL storage texture nodes.
365
- *
366
- * @example
367
- * ```tsx
368
- * const { heightMap } = useGPUStorage(() => ({
369
- * heightMap: new StorageTexture(512, 512),
370
- * }), 'terrain')
371
- * ```
372
- */
373
- type StorageLike =
374
- | StorageTexture // 2D GPU storage texture
375
- | Storage3DTexture // 3D GPU storage texture (volumes, fluid grids)
376
- | StorageArrayTexture // 2D-array GPU storage texture
377
- | Data3DTexture // 3D texture (can be used as storage)
378
- | Node // TSL storage texture nodes (storageTexture)
379
-
380
- /** Flat record of storage-like values (no nested scopes) */
381
- type StorageRecord = Record<string, StorageLike>
382
-
383
- /**
384
- * Storage store that can contain both root-level storage and scoped storage objects.
385
- * Structure: { heightMap: StorageTexture, terrain: { normal: StorageTextureNode } }
386
- */
387
- type StorageStore = Record<string, StorageLike | StorageRecord>
388
-
389
- //* Renderer Types ========================================
390
-
391
- /** Default renderer type - union of WebGL and WebGPU renderers */
392
- type R3FRenderer = THREE$1.WebGLRenderer | WebGPURenderer
393
-
394
- //* Core Store Types ========================================
395
-
396
- type Subscription = {
397
- ref: React$1.RefObject<RenderCallback>
398
- priority: number
399
- store: RootStore
400
- }
401
-
402
- /** Per-pointer state for multi-touch and XR support */
403
- type PointerState = {
404
- /** Objects currently hovered by this pointer */
405
- hovered: Map<string, ThreeEvent<DomEvent>>
406
- /** Objects capturing this pointer */
407
- captured: Map<THREE$1.Object3D, PointerCaptureTarget>
408
- /** Initial click position [x, y] */
409
- initialClick: [x: number, y: number]
410
- /** Objects hit on initial click */
411
- initialHits: THREE$1.Object3D[]
412
- }
413
-
414
- type Dpr = number | [min: number, max: number]
415
-
416
- interface Size {
417
- width: number
418
- height: number
419
- top: number
420
- left: number
421
- }
422
-
423
- type Frameloop = 'always' | 'demand' | 'never'
424
-
425
- interface Viewport extends Size {
426
- /** The initial pixel ratio */
427
- initialDpr: number
428
- /** Current pixel ratio */
429
- dpr: number
430
- /** size.width / viewport.width */
431
- factor: number
432
- /** Camera distance */
433
- distance: number
434
- /** Camera aspect ratio: width / height */
435
- aspect: number
436
- }
437
-
438
- type RenderCallback = (state: RootState, delta: number, frame?: XRFrame) => void
439
-
440
- interface Performance {
441
- /** Current performance normal, between min and max */
442
- current: number
443
- /** How low the performance can go, between 0 and max */
444
- min: number
445
- /** How high the performance can go, between min and max */
446
- max: number
447
- /** Time until current returns to max in ms */
448
- debounce: number
449
- /** Sets current to min, puts the system in regression */
450
- regress: () => void
451
- }
452
-
453
- interface InternalState {
454
- interaction: THREE$1.Object3D[]
455
- subscribers: Subscription[]
456
- /** Per-pointer state (hover, capture, click tracking) - replaces hovered, capturedMap, initialClick, initialHits */
457
- pointerMap: Map<number, PointerState>
458
- /** Pointers needing raycast this frame (used with frameTimedRaycasts) */
459
- pointerDirty: Map<number, DomEvent>
460
- /** Last event received (for events.update() compatibility) */
461
- lastEvent: React$1.RefObject<DomEvent | null>
462
- /** @deprecated Use pointerMap.get(pointerId).hovered instead */
463
- hovered: Map<string, ThreeEvent<DomEvent>>
464
- /** @deprecated Use pointerMap.get(pointerId).captured instead */
465
- capturedMap: Map<number, Map<THREE$1.Object3D, PointerCaptureTarget>>
466
- /** @deprecated Use pointerMap.get(pointerId).initialClick instead */
467
- initialClick: [x: number, y: number]
468
- /** @deprecated Use pointerMap.get(pointerId).initialHits instead */
469
- initialHits: THREE$1.Object3D[]
470
- /** Visibility event registry (onFramed, onOccluded, onVisible) */
471
- visibilityRegistry: Map<string, VisibilityEntry>
472
- /** Whether occlusion queries are enabled (WebGPU only) */
473
- occlusionEnabled: boolean
474
- /** Reference to the invisible occlusion observer mesh */
475
- occlusionObserver: THREE$1.Mesh | null
476
- /** Cached occlusion results from render pass - keyed by Object3D */
477
- occlusionCache: Map<THREE$1.Object3D, boolean | null>
478
- /** Internal helper group for R3F system objects (occlusion observer, etc.) */
479
- helperGroup: THREE$1.Group | null
480
- active: boolean
481
- priority: number
482
- frames: number
483
- subscribe: (callback: React$1.RefObject<RenderCallback>, priority: number, store: RootStore) => () => void
484
- /** Internal renderer storage - use state.renderer or state.gl to access */
485
- actualRenderer: R3FRenderer
486
- /** Global scheduler reference (for useFrame hook) */
487
- scheduler: SchedulerApi | null
488
- /** This root's unique ID in the global scheduler */
489
- rootId?: string
490
- /** Function to unregister this root from the global scheduler */
491
- unregisterRoot?: () => void
492
- /** Container for child attachment (scene for root, original container for portals) */
493
- container?: THREE$1.Object3D
494
- /**
495
- * The CanvasTarget this root sizes and renders through.
496
- *
497
- * A primary (`<Canvas id>`) owns the renderer's default target -- the one three itself built
498
- * around the canvas element -- so sizing it is sizing the renderer. A secondary owns a target
499
- * R3F created for its own element. Either way there is exactly one target per canvas element,
500
- * and the canvas-target job makes it the renderer's active one before this root renders.
501
- * Absent on WebGL and on an id-less WebGPU canvas, where the renderer is sized directly.
502
- * @see https://threejs.org/docs/#api/en/renderers/common/CanvasTarget
503
- */
504
- canvasTarget?: CanvasTarget
505
- /**
506
- * Set when this root's canvas target has been resized and the backend's cached render pass
507
- * descriptor (which holds a depth-stencil view built once per canvas) is therefore stale.
508
- *
509
- * Flushed by the canvas-target job in the `start` phase, which is the only place this root's
510
- * target is guaranteed to be the renderer's active one — `backend.updateSize()` operates on
511
- * whatever `getCanvasTarget()` returns, so calling it from the resize subscription would
512
- * invalidate some other canvas's descriptor instead.
513
- *
514
- * @see https://github.com/pmndrs/react-three-fiber/issues/3847
515
- */
516
- canvasTargetSizeDirty?: boolean
517
- /**
518
- * Whether multi-canvas rendering is active.
519
- * True when any canvas uses `renderer={{ primaryCanvas: 'id' }}` to share a renderer.
520
- * When true, setCanvasTarget is called before each render.
521
- */
522
- isMultiCanvas?: boolean
523
- /**
524
- * Whether this canvas is a secondary canvas sharing another's renderer.
525
- * True when `target` prop is used.
526
- */
527
- isSecondary?: boolean
528
- /**
529
- * The id of the primary canvas this secondary canvas targets.
530
- * Only set when isSecondary is true.
531
- */
532
- targetId?: string
533
- /**
534
- * Function to unregister this primary canvas from the registry.
535
- * Only set when this canvas has an `id` prop.
536
- */
537
- unregisterPrimary?: () => void
538
- /** Whether canvas dimensions are forced to even numbers */
539
- forceEven?: boolean
540
- }
541
-
542
- interface XRManager {
543
- connect: () => void
544
- disconnect: () => void
545
- }
546
-
547
- //* Root State Interface ====================================
548
-
549
- interface RootState {
550
- /** Set current state */
551
- set: StoreApi<RootState>['setState']
552
- /** Get current state */
553
- get: StoreApi<RootState>['getState']
554
- /**
555
- * Reference to the authoritative store for shared TSL resources (uniforms, nodes, etc).
556
- * - For primary/independent canvases: points to its own store (self-reference)
557
- * - For secondary canvases: points to the primary canvas's store
558
- *
559
- * Hooks like useNodes/useUniforms should read from primaryStore to ensure
560
- * consistent shared state across all canvases sharing a renderer.
561
- */
562
- primaryStore: RootStore
563
- /** @deprecated Use `renderer` instead. The instance of the renderer (typed as WebGLRenderer for backwards compat) */
564
- gl: THREE$1.WebGLRenderer
565
- /** The renderer instance - type depends on entry point (WebGPU, Legacy, or union for default) */
566
- renderer: R3FRenderer
567
- /** Inspector of the webGPU Renderer. Init in the canvas */
568
- inspector: any // Inspector type from three/webgpu
569
-
570
- /** Default camera */
571
- camera: ThreeCamera
572
- /** Camera frustum for visibility checks - auto-updated each frame when autoUpdateFrustum is true */
573
- frustum: THREE$1.Frustum
574
- /** Whether to automatically update the frustum each frame (default: true) */
575
- autoUpdateFrustum: boolean
576
- /** Default scene (may be overridden in portals to point to the portal container) */
577
- scene: THREE$1.Scene
578
- /** The actual root THREE.Scene - always points to the true scene, even inside portals */
579
- rootScene: THREE$1.Scene
580
- /** Default raycaster */
581
- raycaster: THREE$1.Raycaster
582
- /** Event layer interface, contains the event handler and the node they're connected to */
583
- events: EventManager<any>
584
- /** XR interface */
585
- xr: XRManager
586
- /** Currently used controls */
587
- controls: THREE$1.EventDispatcher | null
588
- /** Normalized event coordinates */
589
- pointer: THREE$1.Vector2
590
- /** @deprecated Normalized event coordinates, use "pointer" instead! */
591
- mouse: THREE$1.Vector2
592
- /** Color space assigned to 8-bit input textures (color maps). Most textures are authored in sRGB. */
593
- textureColorSpace: THREE$1.ColorSpace
594
- /** Render loop flags */
595
- frameloop: Frameloop
596
- performance: Performance
597
- /** Reactive pixel-size of the canvas */
598
- size: Size
599
- /** Reactive size of the viewport in threejs units */
600
- viewport: Viewport & {
601
- getCurrentViewport: (
602
- camera?: ThreeCamera,
603
- target?: THREE$1.Vector3 | Parameters<THREE$1.Vector3['set']>,
604
- size?: Size,
605
- ) => Omit<Viewport, 'dpr' | 'initialDpr'>
606
- }
607
- /** Flags the canvas for render, but doesn't render in itself */
608
- invalidate: (frames?: number, stackFrames?: boolean) => void
609
- /** Advance (render) one step */
610
- advance: (timestamp: number, runGlobalEffects?: boolean) => void
611
- /** Shortcut to setting the event layer */
612
- setEvents: (events: Partial<EventManager<any>>) => void
613
- /** Shortcut to manual sizing. No args resets to props/container. Single arg creates square. */
614
- setSize: (width?: number, height?: number, top?: number, left?: number) => void
615
- /** Shortcut to manual setting the pixel ratio */
616
- setDpr: (dpr: Dpr) => void
617
- /** Shortcut to setting frameloop flags. No args resets to 'always'. */
618
- setFrameloop: (frameloop?: Frameloop) => void
619
- /** Set error state to propagate to error boundary */
620
- setError: (error: Error | null) => void
621
- /** Current error state (null when no error) */
622
- error: Error | null
623
- /** Global TSL uniform nodes - root-level uniforms + scoped sub-objects. Use useUniforms() hook */
624
- uniforms: UniformStore
625
- /** Global TSL nodes - root-level nodes + scoped sub-objects. Use useNodes() hook */
626
- nodes: NodeStore
627
- /** Global TSL buffer nodes - root-level buffers + scoped sub-objects. Use useBuffers() hook */
628
- buffers: BufferStore
629
- /** Global GPU storage (textures, etc.) - root-level storage + scoped sub-objects. Use useGPUStorage() hook */
630
- gpuStorage: StorageStore
631
- /** Global Texture registry (key → Texture, usually keyed by URL) - use useTextures() hook for access + lifecycle */
632
- textures: Map<string, THREE$1.Texture>
633
- /** Internal: refcount per texture key, driven by mounted useTexture consumers (registry enrollment is on by default) */
634
- _textureRefs: Map<string, number>
635
- /** WebGPU RenderPipeline instance - use useRenderPipeline() hook */
636
- renderPipeline: ThreeRenderPipeline | null
637
- /** Global TSL pass nodes for render pipeline - use useRenderPipeline() hook */
638
- passes: PassRecord
639
- /** Internal version counter for HMR - incremented by rebuildNodes/rebuildUniforms to bust memoization */
640
- _hmrVersion: number
641
- /** Internal: whether setSize() has taken ownership of canvas dimensions */
642
- _sizeImperative: boolean
643
- /** Internal: stored size props from Canvas for reset functionality */
644
- _sizeProps: { width?: number; height?: number } | null
645
- /** When the canvas was clicked but nothing was hit */
646
- onPointerMissed?: (event: MouseEvent) => void
647
- /** When a dragover event has missed any target */
648
- onDragOverMissed?: (event: DragEvent) => void
649
- /** When a drop event has missed any target */
650
- onDropMissed?: (event: DragEvent) => void
651
- /** If this state model is layered (via createPortal) then this contains the previous layer */
652
- previousRoot?: RootStore
653
- /** Internals */
654
- internal: InternalState
655
- // flags for triggers
656
- // if we are using the webGl renderer, this will be true
657
- isLegacy: boolean
658
- // regardless of renderer, if the system supports webGpu, this will be true
659
- webGPUSupported: boolean
660
- //if we are on native
661
- isNative: boolean
662
- }
663
-
664
- type RootStore = UseBoundStoreWithEqualityFn<StoreApi<RootState>>
665
-
666
- //* Base Renderer Types =====================================
667
-
668
- // Shim for OffscreenCanvas since it was removed from DOM types
669
- interface OffscreenCanvas$1 extends EventTarget {}
670
-
671
- interface BaseRendererProps {
672
- canvas: HTMLCanvasElement | OffscreenCanvas$1
673
- powerPreference?: 'high-performance' | 'low-power' | 'default'
674
- antialias?: boolean
675
- alpha?: boolean
676
- }
677
-
678
- type RendererFactory<TRenderer, TParams> =
679
- | TRenderer
680
- | ((defaultProps: TParams) => TRenderer)
681
- | ((defaultProps: TParams) => Promise<TRenderer>)
682
-
683
- interface Renderer {
684
- render: (scene: THREE$1.Scene, camera: THREE$1.Camera) => any
685
- }
686
-
687
- //* Color Management Config ==============================
688
-
689
- /**
690
- * Color management configuration shared by both WebGL and WebGPU renderers.
691
- */
692
- interface ColorManagementConfig {
693
- /**
694
- * Color space assigned to 8-bit input textures (color maps).
695
- * Defaults to sRGB. Most textures are authored in sRGB.
696
- * @default THREE.SRGBColorSpace
697
- */
698
- textureColorSpace?: THREE$1.ColorSpace
699
- }
700
-
701
- //* WebGL Renderer Props ==============================
702
-
703
- type DefaultGLProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & {
704
- canvas: HTMLCanvasElement | OffscreenCanvas$1
705
- }
706
-
707
- type GLProps =
708
- | Renderer
709
- | ((defaultProps: DefaultGLProps) => Renderer)
710
- | ((defaultProps: DefaultGLProps) => Promise<Renderer>)
711
- | (Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters> & ColorManagementConfig)
712
-
713
- //* WebGPU Renderer Props ==============================
714
-
715
- type DefaultRendererProps = {
716
- canvas: HTMLCanvasElement | OffscreenCanvas$1
717
- [key: string]: any
718
- }
719
-
720
- /**
721
- * Canvas-level scheduler configuration.
722
- * Controls render timing relative to other canvases.
723
- */
724
- interface CanvasSchedulerConfig {
725
- /**
726
- * Run this Canvas root before the referenced Canvas root id(s).
727
- */
728
- before?: string | string[]
729
- /**
730
- * Run this Canvas root after the referenced Canvas root id(s).
731
- */
732
- after?: string | string[]
733
- /**
734
- * Numeric root order. Lower values run first.
735
- */
736
- order?: number
737
- /**
738
- * Limit this Canvas's default render job (frames per second).
739
- */
740
- fps?: number
741
- }
742
-
743
- /**
744
- * Extended renderer configuration for multi-canvas support and color management.
745
- */
746
- interface RendererConfigExtended extends ColorManagementConfig {
747
- /** Share renderer from another canvas (WebGPU only) */
748
- primaryCanvas?: string
749
- /** Canvas-level scheduler options */
750
- scheduler?: CanvasSchedulerConfig
751
- }
752
-
753
- type RendererProps =
754
- | any // WebGPURenderer
755
- | ((defaultProps: DefaultRendererProps) => any)
756
- | ((defaultProps: DefaultRendererProps) => Promise<any>)
757
- | (Partial<Properties<any> | Record<string, any>> & RendererConfigExtended)
758
-
759
- //* Camera Props ==============================
760
-
761
- type CameraProps = (
762
- | THREE$1.Camera
763
- | Partial<
764
- ThreeElement<typeof THREE$1.Camera> &
765
- ThreeElement<typeof THREE$1.PerspectiveCamera> &
766
- ThreeElement<typeof THREE$1.OrthographicCamera>
767
- >
768
- ) & {
769
- /** Flags the camera as manual, putting projection into your own hands */
770
- manual?: boolean
771
- }
772
-
773
- //* Render Props ==============================
774
-
775
- interface RenderProps<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
776
- /**
777
- * Unique identifier for multi-canvas renderer sharing.
778
- * Makes this canvas targetable by other canvases using the `primaryCanvas` prop.
779
- * Also sets the HTML `id` attribute on the canvas element.
780
- * @example <Canvas id="main-viewer">...</Canvas>
781
- */
782
- id?: string
783
- /**
784
- * Share the renderer from another canvas instead of creating a new one.
785
- * Pass the `id` of the primary canvas to share its WebGPURenderer.
786
- * Only available with WebGPU (not legacy WebGL).
787
- *
788
- * Note: This is extracted from `renderer={{ primaryCanvas: "id" }}` by Canvas.
789
- * @internal
790
- */
791
- primaryCanvas?: string
792
- /**
793
- * Canvas-level scheduler options. Controls render timing relative to other canvases.
794
- *
795
- * Note: This is extracted from `renderer={{ scheduler: {...} }}` by Canvas.
796
- * @internal
797
- */
798
- scheduler?: CanvasSchedulerConfig
799
- /** A threejs renderer instance or props that go into the default renderer */
800
- gl?: GLProps
801
- /** A WebGPU renderer instance or props that go into the default renderer */
802
- renderer?: RendererProps
803
- /** Dimensions to fit the renderer to. Will measure canvas dimensions if omitted */
804
- size?: Size
805
- /**
806
- * Enables shadows (by default PCFsoft). Can accept `gl.shadowMap` options for fine-tuning,
807
- * but also strings: 'basic' | 'percentage' | 'soft' | 'variance'.
808
- * @see https://threejs.org/docs/#api/en/renderers/WebGLRenderer.shadowMap
809
- */
810
- shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
811
- /** Creates an orthographic camera */
812
- orthographic?: boolean
813
- /**
814
- * R3F's render mode. Set to `demand` to only render on state change or `never` to take control.
815
- * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#on-demand-rendering
816
- */
817
- frameloop?: Frameloop
818
- /**
819
- * R3F performance options for adaptive performance.
820
- * @see https://docs.pmnd.rs/react-three-fiber/advanced/scaling-performance#movement-regression
821
- */
822
- performance?: Partial<Omit<Performance, 'regress'>>
823
- /** Target pixel ratio. Can clamp between a range: `[min, max]` */
824
- dpr?: Dpr
825
- /**
826
- * Props that go into the default raycaster. `params` is merged into the raycaster's defaults,
827
- * so a single threshold can be set: `raycaster={{ params: { Points: { threshold: 0.2 } } }}`.
828
- */
829
- raycaster?: Partial<Omit<THREE$1.Raycaster, 'params'>> & { params?: Partial<THREE$1.RaycasterParameters> }
830
- /** A `THREE.Scene` instance or props that go into the default scene */
831
- scene?: THREE$1.Scene | Partial<THREE$1.Scene>
832
- /** A `THREE.Camera` instance or props that go into the default camera */
833
- camera?: CameraProps
834
- /** An R3F event manager to manage elements' pointer events */
835
- events?: (store: RootStore) => EventManager<Element>
836
- /** Callback after the canvas has rendered (but not yet committed) */
837
- onCreated?: (state: RootState) => void
838
- /** Response for pointer clicks that have missed any target */
839
- onPointerMissed?: (event: MouseEvent) => void
840
- /** Response for dragover events that have missed any target */
841
- onDragOverMissed?: (event: DragEvent) => void
842
- /** Response for drop events that have missed any target */
843
- onDropMissed?: (event: DragEvent) => void
844
- /** Whether to automatically update the frustum each frame (default: true) */
845
- autoUpdateFrustum?: boolean
846
- /**
847
- * Enable WebGPU occlusion queries for onOccluded/onVisible events.
848
- * Auto-enabled when any object uses onOccluded or onVisible handlers.
849
- * Only works with WebGPU renderer - WebGL will log a warning.
850
- */
851
- occlusion?: boolean
852
- /** Internal: stored size props from Canvas for reset functionality */
853
- _sizeProps?: { width?: number; height?: number } | null
854
- /** Force canvas dimensions to even numbers (fixes Safari rendering issues with odd/fractional sizes) */
855
- forceEven?: boolean
856
- }
857
-
858
- //* Reconciler Root ==============================
859
-
860
- interface ReconcilerRoot<TCanvas extends HTMLCanvasElement | OffscreenCanvas$1> {
861
- configure: (config?: RenderProps<TCanvas>) => Promise<ReconcilerRoot<TCanvas>>
862
- render: (element: ReactNode) => RootStore
863
- unmount: () => void
864
- }
865
-
866
- //* Inject State ==============================
867
-
868
- type InjectState = Partial<
869
- Omit<RootState, 'events'> & {
870
- events?: {
871
- enabled?: boolean
872
- priority?: number
873
- compute?: ComputeFunction
874
- connected?: any
875
- }
876
- /**
877
- * When true (default), injects a THREE.Scene between container and children if container isn't already a Scene.
878
- * This ensures state.scene is always a real THREE.Scene with proper properties (background, environment, fog).
879
- * Set to false to use the container directly as scene (anti-pattern, but supported for edge cases).
880
- */
881
- injectScene?: boolean
882
- }
883
- >
884
-
885
- //* Reconciler Types ==============================
886
-
887
- // FiberRoot is an opaque internal React type - we define it locally
888
- // to avoid bundling @types/react-reconciler which causes absolute path issues
889
- type FiberRoot = any
890
-
891
- interface Root {
892
- fiber: FiberRoot
893
- store: RootStore
894
- }
895
-
896
- type AttachFnType<O = any> = (parent: any, self: O) => () => void
897
- type AttachType<O = any> = string | AttachFnType<O>
898
-
899
- type ConstructorRepresentation<T = any> = new (...args: any[]) => T
900
-
901
- interface Catalogue {
902
- [name: string]: ConstructorRepresentation
903
- }
904
-
905
- // TODO: handle constructor overloads
906
- // https://github.com/pmndrs/react-three-fiber/pull/2931
907
- // https://github.com/microsoft/TypeScript/issues/37079
908
- type Args<T> = T extends ConstructorRepresentation
909
- ? T extends typeof Color$1
910
- ? [r: number, g: number, b: number] | [color: ColorRepresentation]
911
- : ConstructorParameters<T>
912
- : any[]
913
-
914
- type ArgsProp<P> = P extends ConstructorRepresentation
915
- ? IsAllOptional<ConstructorParameters<P>> extends true
916
- ? { args?: Args<P> }
917
- : { args: Args<P> }
918
- : { args: unknown[] }
919
-
920
- type InstanceProps<T = any, P = any> = ArgsProp<P> & {
921
- object?: T
922
- dispose?: null
923
- attach?: AttachType<T>
924
- }
925
-
926
- interface Instance<O = any> {
927
- root: RootStore
928
- type: string
929
- parent: Instance | null
930
- children: Instance[]
931
- props: InstanceProps<O> & Record<string, unknown>
932
- object: O & { __r3f?: Instance<O> }
933
- eventCount: number
934
- handlers: Partial<EventHandlers>
935
- attach?: AttachType<O>
936
- previousAttach?: any
937
- isHidden: boolean
938
- /** Set of props that have been applied via once() */
939
- appliedOnce?: Set<string>
940
- }
941
-
942
- interface HostConfig {
943
- type: string
944
- props: Instance['props']
945
- container: RootStore
946
- instance: Instance
947
- textInstance: void
948
- suspenseInstance: Instance
949
- hydratableInstance: never
950
- formInstance: never
951
- publicInstance: Instance['object']
952
- hostContext: {}
953
- childSet: never
954
- timeoutHandle: number | undefined
955
- noTimeout: -1
956
- TransitionStatus: null
957
- }
958
- declare global {
959
- var IS_REACT_ACT_ENVIRONMENT: boolean | undefined
960
- }
961
-
962
- //* Loop Types ==============================
963
-
964
- type GlobalRenderCallback = (timestamp: number) => void
965
-
966
- type GlobalEffectType = 'before' | 'after' | 'tail'
967
-
968
- declare const presetsObj: {
969
- apartment: string;
970
- city: string;
971
- dawn: string;
972
- forest: string;
973
- lobby: string;
974
- night: string;
975
- park: string;
976
- studio: string;
977
- sunset: string;
978
- warehouse: string;
979
- };
980
- type PresetsType = keyof typeof presetsObj;
981
-
982
- //* Background Types ==============================
983
-
984
- /**
985
- * Expanded object form for background configuration.
986
- * Allows separate textures for background (visual backdrop) and environment (PBR lighting).
987
- */
988
- interface BackgroundConfig {
989
- /** HDRI preset name: 'apartment', 'city', 'dawn', 'forest', 'lobby', 'night', 'park', 'studio', 'sunset', 'warehouse' */
990
- preset?: PresetsType
991
- /** Files for cube texture (6 faces) or single HDR/EXR */
992
- files?: string | string[]
993
- /** Separate files for scene.background (visual backdrop) */
994
- backgroundMap?: string | string[]
995
- backgroundRotation?: Euler$1 | [number, number, number]
996
- backgroundBlurriness?: number
997
- backgroundIntensity?: number
998
- /** Separate files for scene.environment (PBR lighting/reflections) */
999
- envMap?: string | string[]
1000
- environmentRotation?: Euler$1 | [number, number, number]
1001
- environmentIntensity?: number
1002
- path?: string
1003
- extensions?: (loader: Loader) => void
1004
- }
1005
-
1006
- /**
1007
- * Background prop type for Canvas.
1008
- *
1009
- * String detection priority:
1010
- * 1. Preset - exact match against known presets (apartment, city, dawn, forest, lobby, night, park, studio, sunset, warehouse)
1011
- * 2. URL - starts with /, ./, ../, http://, https://, OR has image extension
1012
- * 3. Color - default fallback (CSS color names, hex values, rgb(), etc.)
1013
- *
1014
- * @example Color
1015
- * ```tsx
1016
- * <Canvas background="red" />
1017
- * <Canvas background="#ff0000" />
1018
- * <Canvas background={0xff0000} />
1019
- * ```
1020
- *
1021
- * @example Preset
1022
- * ```tsx
1023
- * <Canvas background="city" />
1024
- * ```
1025
- *
1026
- * @example URL
1027
- * ```tsx
1028
- * <Canvas background="/path/to/env.hdr" />
1029
- * <Canvas background="./sky.jpg" />
1030
- * ```
1031
- *
1032
- * @example Object form
1033
- * ```tsx
1034
- * <Canvas background={{
1035
- * files: ['px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'],
1036
- * backgroundMap: 'path/to/sky.jpg',
1037
- * envMap: 'path/to/lighting.hdr',
1038
- * backgroundBlurriness: 0.5,
1039
- * }} />
1040
- * ```
1041
- */
1042
- type BackgroundProp =
1043
- | ColorRepresentation // "red", "#ff0000", 0xff0000
1044
- | string // URL or preset
1045
- | BackgroundConfig // Expanded object form
1046
-
1047
- //* Canvas Types ==============================
1048
-
1049
- interface CanvasProps
1050
- extends
1051
- Omit<RenderProps<HTMLCanvasElement>, 'size' | 'primaryCanvas' | 'scheduler'>,
1052
- React$1.HTMLAttributes<HTMLDivElement> {
1053
- children?: React$1.ReactNode
1054
- ref?: React$1.Ref<HTMLCanvasElement>
1055
- /** Canvas fallback content, similar to img's alt prop */
1056
- fallback?: React$1.ReactNode
1057
- /**
1058
- * Options to pass to useMeasure.
1059
- * @see https://github.com/pmndrs/react-use-measure#api
1060
- */
1061
- resize?: Options
1062
- /** The target where events are being subscribed to, default: the div that wraps canvas */
1063
- eventSource?: Element | React$1.RefObject<Element | null>
1064
- /** The event prefix that is cast into canvas pointer x/y events, default: "offset" */
1065
- eventPrefix?: 'offset' | 'client' | 'page' | 'layer' | 'screen'
1066
- /** Enable/disable automatic HMR refresh for TSL nodes and uniforms, default: true in dev */
1067
- hmr?: boolean
1068
- /** Canvas resolution width in pixels. If omitted, uses container width. */
1069
- width?: number
1070
- /** Canvas resolution height in pixels. If omitted, uses container height. */
1071
- height?: number
1072
- /** Force canvas dimensions to even numbers (fixes Safari rendering issues with odd/fractional sizes) */
1073
- forceEven?: boolean
1074
- /**
1075
- * Scene background configuration.
1076
- * Accepts colors, URLs, presets, or an expanded object for separate background/environment.
1077
- * @see BackgroundProp for full documentation and examples
1078
- */
1079
- background?: BackgroundProp
1080
- }
1081
-
1082
- //* Loader Types ==============================
1083
-
1084
- type InputLike = string | string[] | string[][] | Readonly<string | string[] | string[][]>
1085
-
1086
- // Define a loader-like interface that matches THREE.Loader's load signature
1087
- // This works for both generic and non-generic THREE.Loader instances
1088
- interface LoaderLike {
1089
- load(
1090
- url: InputLike,
1091
- onLoad?: (result: any) => void,
1092
- onProgress?: (event: ProgressEvent<EventTarget>) => void,
1093
- onError?: (error: unknown) => void,
1094
- ): any
1095
- }
1096
-
1097
- type GLTFLike = { scene: THREE$1.Object3D }
1098
-
1099
- type LoaderInstance<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
1100
- T extends ConstructorRepresentation<LoaderLike> ? InstanceType<T> : T
1101
-
1102
- // Infer result type from the load method's callback parameter
1103
- type InferLoadResult<T> = T extends {
1104
- load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
1105
- }
1106
- ? R
1107
- : T extends ConstructorRepresentation<any>
1108
- ? InstanceType<T> extends {
1109
- load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
1110
- }
1111
- ? R
1112
- : any
1113
- : any
1114
-
1115
- type LoaderResult<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
1116
- InferLoadResult<LoaderInstance<T>> extends infer R ? (R extends GLTFLike ? R & ObjectMap : R) : never
1117
-
1118
- type Extensions<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> = (
1119
- loader: LoaderInstance<T>,
1120
- ) => void
1121
-
1122
- //* Renderer Props ========================================
1123
-
1124
- type WebGLDefaultProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & BaseRendererProps
1125
-
1126
- type WebGLProps =
1127
- | RendererFactory<THREE$1.WebGLRenderer, WebGLDefaultProps>
1128
- | Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters>
1129
-
1130
- interface WebGLShadowConfig {
1131
- shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
1132
- }
1133
-
1134
- //* Legacy-specific Types ========================================
1135
-
1136
- /** Legacy (WebGL) renderer type - re-exported as R3FRenderer from @react-three/fiber/legacy */
1137
- type LegacyRenderer = THREE$1.WebGLRenderer
1138
-
1139
- /** Legacy internal state with narrowed renderer type */
1140
- interface LegacyInternalState extends Omit<InternalState, 'actualRenderer'> {
1141
- actualRenderer: THREE$1.WebGLRenderer
1142
- }
1143
-
1144
- /**
1145
- * Legacy-specific RootState with narrowed renderer type.
1146
- * Automatically used when importing from `@react-three/fiber/legacy`.
1147
- *
1148
- * @example
1149
- * ```tsx
1150
- * import { useThree } from '@react-three/fiber/legacy'
1151
- *
1152
- * function MyComponent() {
1153
- * const { renderer } = useThree()
1154
- * // renderer is typed as THREE.WebGLRenderer
1155
- * renderer.shadowMap.enabled = true
1156
- * }
1157
- * ```
1158
- */
1159
- interface LegacyRootState extends Omit<RootState, 'renderer' | 'internal'> {
1160
- /** The WebGL renderer instance */
1161
- renderer: THREE$1.WebGLRenderer
1162
- /** Internals with WebGL renderer */
1163
- internal: LegacyInternalState
1164
- }
1165
-
1166
- //* RenderTarget Types ==============================
1167
-
1168
-
1169
- type RenderTargetOptions = RenderTargetOptions$1
1170
-
1171
- //* Global TSL Types ==============================
1172
-
1173
- declare global {
1174
- /**
1175
- * Broad callable-node fallback for dynamic store readers.
1176
- * Creator hooks preserve the exact function signatures inferred from Three's `Fn`.
1177
- */
1178
- type CallableTSLNode = ((...params: never[]) => unknown) & {
1179
- readonly shaderNode: unknown
1180
- readonly id: number
1181
- }
1182
-
1183
- /** Legacy structural node accepted when at least one historical marker exists. */
1184
- type LegacyTSLNodeLike = {
1185
- label?: ((label: string) => unknown) | string
1186
- setName?: (name: string) => unknown
1187
- } & ({ uuid: string | undefined; nodeType?: string | null } | { uuid?: string; nodeType: string | null | undefined })
1188
-
1189
- /** Node type accepted by broad dynamic node-store readers. */
1190
- type TSLNodeType = three_webgpu.Node | CallableTSLNode
1191
-
1192
- /**
1193
- * Derive Three's shader node type from an existing node or a supported raw input.
1194
- * Existing InputNode generics take precedence over structural value normalization.
1195
- * Both generics must be inferred because Three's UniformNode intersects an unknown-typed
1196
- * InputNode base with its concrete InputNode specialization.
1197
- */
1198
- type UniformNodeType<T> = T extends three_webgpu.UniformNode<infer TNodeType, infer _TValue>
1199
- ? TNodeType
1200
- : T extends three_webgpu.InputNode<infer TNodeType, infer _TValue>
1201
- ? TNodeType
1202
- : T extends number
1203
- ? 'float'
1204
- : T extends boolean
1205
- ? 'bool'
1206
- : T extends string | three_webgpu.Color | { r: number; g: number; b: number }
1207
- ? 'color'
1208
- : T extends three_webgpu.Vector4 | { x: number; y: number; z: number; w: number }
1209
- ? 'vec4'
1210
- : T extends three_webgpu.Vector3 | { x: number; y: number; z: number }
1211
- ? 'vec3'
1212
- : T extends three_webgpu.Vector2 | { x: number; y: number }
1213
- ? 'vec2'
1214
- : T extends three_webgpu.Matrix4
1215
- ? 'mat4'
1216
- : T extends three_webgpu.Matrix3
1217
- ? 'mat3'
1218
- : T extends three_webgpu.Matrix2
1219
- ? 'mat2'
1220
- : unknown
1221
-
1222
- /** Derive the normalized JavaScript value stored by a uniform node. */
1223
- type UniformNodeValue<T> = T extends three_webgpu.UniformNode<infer _TNodeType, infer TValue>
1224
- ? TValue
1225
- : T extends three_webgpu.InputNode<infer _TNodeType, infer TValue>
1226
- ? TValue
1227
- : T extends string | { r: number; g: number; b: number }
1228
- ? three_webgpu.Color
1229
- : T extends { x: number; y: number; z: number; w: number }
1230
- ? three_webgpu.Vector4
1231
- : T extends { x: number; y: number; z: number }
1232
- ? three_webgpu.Vector3
1233
- : T extends { x: number; y: number }
1234
- ? three_webgpu.Vector2
1235
- : T extends number
1236
- ? number
1237
- : T extends boolean
1238
- ? boolean
1239
- : T
1240
-
1241
- /** Three's exact UniformNode with shader and value generics derived from an input. */
1242
- type UniformNodeFor<T> = three_webgpu.UniformNode<UniformNodeType<T>, UniformNodeValue<T>>
1243
-
1244
- /** Preserve every input key while mapping values to exact Three uniform nodes. */
1245
- type UniformNodesFor<T extends UniformInputRecord> = {
1246
- [K in keyof T]: UniformNodeFor<T[K]>
1247
- }
1248
-
1249
- /** Backward-compatible single-parameter uniform alias. */
1250
- type UniformNode<T = unknown> = UniformNodeFor<T>
1251
-
1252
- /** Flat record of uniform nodes (no nested scopes) */
1253
- type UniformRecord<T extends UniformNode = UniformNode> = Record<string, T>
1254
-
1255
- /**
1256
- * Uniform store that can contain both root-level uniforms and scoped uniform objects
1257
- * Used by state.uniforms which has structure like:
1258
- * { uTime: UniformNode, player: { uHealth: UniformNode }, enemy: { uHealth: UniformNode } }
1259
- */
1260
- type UniformStore = Record<string, UniformNode | UniformRecord>
1261
-
1262
- /**
1263
- * Helper to safely access a uniform node from the store.
1264
- * Use this when accessing state.uniforms to get proper typing.
1265
- * @example
1266
- * const uTime = uniforms.uTime as UniformNode<number>
1267
- * const uColor = uniforms.uColor as UniformNode<import('three/webgpu').Color>
1268
- */
1269
- type GetUniform<T = unknown> = UniformNode<T>
1270
-
1271
- /**
1272
- * Acceptable input values for useUniforms - raw values that get converted to UniformNodes
1273
- * Supports:
1274
- * - Primitives: number, string (color), boolean
1275
- * - Three.js types: Color, Vector2/3/4, Matrix2/3/4
1276
- * - Plain objects: { x, y, z, w } converted to vectors
1277
- * - TSL nodes: color(), vec3(), float() for type casting
1278
- * - UniformNode: existing uniforms (reused as-is)
1279
- */
1280
- type UniformValue =
1281
- | number
1282
- | string
1283
- | boolean
1284
- | three_webgpu.Color
1285
- | three_webgpu.Vector2
1286
- | three_webgpu.Vector3
1287
- | three_webgpu.Vector4
1288
- | three_webgpu.Matrix2
1289
- | three_webgpu.Matrix3
1290
- | three_webgpu.Matrix4
1291
- | { x: number; y: number }
1292
- | { x: number; y: number; z: number }
1293
- | { x: number; y: number; z: number; w: number }
1294
- | { r: number; g: number; b: number; a?: number } // Plain objects converted to Color
1295
- | three_webgpu.Node // TSL nodes like color(), vec3(), float() for type casting
1296
- | UniformNode
1297
-
1298
- /** Input record for useUniforms - accepts raw values or UniformNodes */
1299
- type UniformInputRecord = Record<string, UniformValue>
1300
- }
1301
-
1302
- declare global {
1303
- /**
1304
- * three's own render pipeline type. Named here so the rest of R3F refers to three's shape
1305
- * rather than `any`. three r183 renamed `PostProcessing` to `RenderPipeline`; our peer floor
1306
- * is r185, so the new name is the only one.
1307
- */
1308
- type ThreeRenderPipeline = three_webgpu.RenderPipeline
1309
-
1310
- /**
1311
- * The pass `useRenderPipeline` creates for you: three's own `PassNode`, as returned by
1312
- * `pass(scene, camera)` from `three/tsl`. Referenced from three so members like
1313
- * `getTextureNode`, `setMRT` and `dispose` track the installed version.
1314
- */
1315
- type ScenePassNode = three_webgpu.PassNode
1316
-
1317
- /**
1318
- * Pass record - stores TSL pass nodes for render pipeline.
1319
- *
1320
- * `scenePass` is the only key the library owns. It is optional here because this is also the
1321
- * shape of `state.passes`, which is `{}` before the pipeline exists and again after `reset()`
1322
- * or `clearPasses()`. Inside the callbacks it is always present; see
1323
- * {@link RenderPipelineCallbackState}.
1324
- *
1325
- * Every other key is user-registered, via a callback's return value. Those are TSL nodes of
1326
- * any kind, not only passes: texture reads of an MRT attachment, effect nodes, extra
1327
- * `pass()` instances. `Node` is the common base, so that is the bound. Narrow at the call
1328
- * site when you need a member, e.g. `passes.velocity as TextureNode`.
1329
- *
1330
- * The index signature admits `undefined` because a key may simply not be registered, and
1331
- * because the optional `scenePass` must be assignable to it: under `skipLibCheck: false` an
1332
- * optional property whose type excludes `undefined` from the index signature is an error
1333
- * (TS2411) for every consumer compiling these declarations.
1334
- */
1335
- interface PassRecord {
1336
- scenePass?: ScenePassNode
1337
- [key: string]: three_webgpu.Node | undefined
1338
- }
1339
-
1340
- /**
1341
- * State passed to pipeline callbacks after the active pipeline has been created.
1342
- *
1343
- * `passes.scenePass` is required here: the hook installs the default scene pass before either
1344
- * callback runs, so callbacks can use it without a guard or a cast.
1345
- *
1346
- * `renderer` is narrowed to `WebGPURenderer` and `isLegacy` to `false`: the hook throws under
1347
- * the legacy renderer before either callback can run, so a callback never sees WebGL.
1348
- */
1349
- type RenderPipelineCallbackState = RootState & {
1350
- renderPipeline: ThreeRenderPipeline
1351
- passes: PassRecord & { scenePass: ScenePassNode }
1352
- renderer: three_webgpu.WebGPURenderer
1353
- isLegacy: false
1354
- }
1355
-
1356
- /**
1357
- * What a callback may return to register entries into `state.passes`.
1358
- *
1359
- * `scenePass` is reserved. The hook owns that entry and its lifecycle: it caches the pass it
1360
- * created, and `rebuild()` / `reset()` dispose that cached pass. A callback overwriting the
1361
- * store entry would leave the store pointing at a node the hook never disposes, and the hook
1362
- * disposing a pass nothing references. So returning it is a type error.
1363
- */
1364
- type RegisteredPasses = Record<string, three_webgpu.Node> & { scenePass?: never }
1365
-
1366
- /** Setup callback - runs first to configure MRT, create additional passes */
1367
- type RenderPipelineSetupCallback = (state: RenderPipelineCallbackState) => RegisteredPasses | void
1368
-
1369
- /** Main callback - runs second to configure outputNode, create effect passes */
1370
- type RenderPipelineMainCallback = (state: RenderPipelineCallbackState) => RegisteredPasses | void
1371
-
1372
- /** The imperative half of useRenderPipeline's return value, present in every state */
1373
- interface UseRenderPipelineActions {
1374
- /** Current passes from state */
1375
- passes: PassRecord
1376
- /** Clear all passes from state */
1377
- clearPasses: () => void
1378
- /** Reset RenderPipeline entirely (clears PP + passes) */
1379
- reset: () => void
1380
- /** Re-run setup/main callbacks with current closure values */
1381
- rebuild: () => void
1382
- }
1383
-
1384
- /**
1385
- * Return type for useRenderPipeline hook, discriminated on `isReady`.
1386
- *
1387
- * `if (isReady)` narrows `renderPipeline` to non-null, which is what the docs already tell
1388
- * callers to check. `passes.scenePass` deliberately stays optional in the ready branch:
1389
- * `clearPasses()` empties the record while leaving the pipeline in place.
1390
- */
1391
- type UseRenderPipelineReturn = UseRenderPipelineActions &
1392
- (
1393
- | {
1394
- /** True when RenderPipeline is configured and ready */
1395
- isReady: true
1396
- /** RenderPipeline instance */
1397
- renderPipeline: ThreeRenderPipeline
1398
- }
1399
- | {
1400
- /** False until the pipeline has been created */
1401
- isReady: false
1402
- /** Not initialized yet, or torn down by reset() */
1403
- renderPipeline: null
1404
- }
1405
- )
1406
- }
1407
-
1408
- type MutableOrReadonlyParameters<T extends (...args: any) => any> = Parameters<T> | Readonly<Parameters<T>>
1409
-
1410
- interface MathRepresentation {
1411
- set(...args: number[]): any
1412
- }
1413
- interface VectorRepresentation extends MathRepresentation {
1414
- setScalar(value: number): any
1415
- }
1416
- type MathTypes = MathRepresentation | Euler$2 | Color$2
1417
-
1418
- type MathType<T extends MathTypes> = T extends Color$2
1419
- ? Args<typeof Color$2> | ColorRepresentation$1
1420
- : T extends VectorRepresentation | Layers$1 | Euler$2
1421
- ? T | MutableOrReadonlyParameters<T['set']> | number
1422
- : T | MutableOrReadonlyParameters<T['set']>
1423
-
1424
- type MathProps<P> = {
1425
- [K in keyof P as P[K] extends MathTypes ? K : never]: P[K] extends MathTypes ? MathType<P[K]> : never
1426
- }
1427
-
1428
- type Vector2 = MathType<Vector2$1>
1429
- type Vector3 = MathType<Vector3$1>
1430
- type Vector4 = MathType<Vector4$1>
1431
- type Color = MathType<Color$2>
1432
- type Layers = MathType<Layers$1>
1433
- type Quaternion = MathType<Quaternion$1>
1434
- type Euler = MathType<Euler$2>
1435
- type Matrix3 = MathType<Matrix3$1>
1436
- type Matrix4 = MathType<Matrix4$1>
1437
-
1438
- interface RaycastableRepresentation {
1439
- raycast(raycaster: Raycaster, intersects: Intersection$1[]): void
1440
- }
1441
- type EventProps<P> = P extends RaycastableRepresentation ? Partial<EventHandlers> : {}
1442
-
1443
- /**
1444
- * Props for geometry transform methods that can be called with `once()`.
1445
- * These methods modify the geometry in-place and only make sense to call once on mount.
1446
- *
1447
- * @example
1448
- * import { once } from '@react-three/fiber'
1449
- *
1450
- * <boxGeometry args={[1, 1, 1]} rotateX={once(Math.PI / 2)} />
1451
- * <planeGeometry args={[10, 10]} translate={once(0, 0, 5)} />
1452
- * <bufferGeometry applyMatrix4={once(matrix)} center={once()} />
1453
- */
1454
- interface GeometryTransformProps {
1455
- /** Rotate the geometry about the X axis (radians). Use with once(). */
1456
- rotateX?: number
1457
- /** Rotate the geometry about the Y axis (radians). Use with once(). */
1458
- rotateY?: number
1459
- /** Rotate the geometry about the Z axis (radians). Use with once(). */
1460
- rotateZ?: number
1461
- /** Translate the geometry (x, y, z). Use with once(). */
1462
- translate?: [x: number, y: number, z: number]
1463
- /** Scale the geometry (x, y, z). Use with once(). */
1464
- scale?: [x: number, y: number, z: number]
1465
- /** Center the geometry based on bounding box. Use with once(). */
1466
- center?: true
1467
- /** Apply a Matrix4 transformation. Use with once(). */
1468
- applyMatrix4?: Matrix4$1
1469
- /** Apply a Quaternion rotation. Use with once(). */
1470
- applyQuaternion?: Quaternion$1
1471
- }
1472
-
1473
- type GeometryProps<P> = P extends BufferGeometry ? GeometryTransformProps : {}
1474
-
1475
- /**
1476
- * Workaround for @types/three TSL node type issues.
1477
- * The Node base class has properties that subclasses (OperatorNode, ConstNode, etc.) don't inherit.
1478
- * This transforms `Node | null` properties to accept any object with node-like shape.
1479
- */
1480
- type TSLNodeInput = { nodeType?: string | null; uuid?: string } | null
1481
-
1482
- /**
1483
- * For node material properties (colorNode, positionNode, etc.), accept broader types
1484
- * since @types/three has broken inheritance for TSL node subclasses. NodeClass requires
1485
- * `nodeType`, so this structural key test remains neutral to the selected Three entry.
1486
- */
1487
- type NodeProps<P> = {
1488
- [K in keyof P as NonNullable<P[K]> extends { nodeType: string | null } ? K : never]?: TSLNodeInput
1489
- }
1490
-
1491
- interface ReactProps<P> {
1492
- children?: React.ReactNode
1493
- ref?: React.Ref<P>
1494
- key?: React.Key
1495
- }
1496
-
1497
- type ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = Partial<
1498
- Overwrite<P, MathProps<P> & ReactProps<P> & EventProps<P> & GeometryProps<P> & NodeProps<P>>
1499
- >
1500
-
1501
- type ThreeElement<T extends ConstructorRepresentation> = Mutable<
1502
- Overwrite<ElementProps<T>, Omit<InstanceProps<InstanceType<T>, T>, 'object'>>
1503
- >
1504
-
1505
- type ThreeToJSXElements<T extends Record<string, any>> = {
1506
- [K in keyof T & string as Uncapitalize<K>]: T[K] extends ConstructorRepresentation ? ThreeElement<T[K]> : never
1507
- }
1508
-
1509
- /** Method names of Object3D, excluded from the `primitive` element's typed props. */
1510
- type Object3DMethod = NonNullable<
1511
- {
1512
- [K in keyof Object3D]-?: Object3D[K] extends (...args: any[]) => any ? K : never
1513
- }[keyof Object3D]
1514
- >
1515
-
1516
- type ThreeExports = typeof import('three/webgpu')
1517
- type ThreeElementsImpl = ThreeToJSXElements<ThreeExports>
1518
-
1519
- interface ThreeElements extends Omit<ThreeElementsImpl, 'audio' | 'source' | 'line' | 'path'> {
1520
- /**
1521
- * `primitive` wraps a pre-existing object, so its props cannot be derived from one class.
1522
- * Events are typed from `EventHandlers` (`onClick={(e) => ...}` infers `e`), the ref is
1523
- * untyped, and any other prop is accepted and applied to the object by name. Object3D's own
1524
- * methods are left out of the typed surface: they return `this`, so a subclass element's
1525
- * props (`ThreeElements['group']`) could not be spread onto a primitive otherwise.
1526
- */
1527
- primitive: Omit<ThreeElement<typeof Object3D>, 'args' | 'object' | 'ref' | Object3DMethod> & {
1528
- object: object
1529
- ref?: React.Ref<any>
1530
- [prop: string]: unknown
1531
- }
1532
- // Conflicts with DOM types can be accessed through a three* prefix
1533
- threeAudio: ThreeElementsImpl['audio']
1534
- threeSource: ThreeElementsImpl['source']
1535
- threeLine: ThreeElementsImpl['line']
1536
- threePath: ThreeElementsImpl['path']
1537
- }
1538
-
1539
- declare module 'react' {
1540
- namespace JSX {
1541
- interface IntrinsicElements extends ThreeElements {}
1542
- }
1543
- }
1544
-
1545
- declare module 'react/jsx-runtime' {
1546
- namespace JSX {
1547
- interface IntrinsicElements extends ThreeElements {}
1548
- }
1549
- }
1550
-
1551
- declare module 'react/jsx-dev-runtime' {
1552
- namespace JSX {
1553
- interface IntrinsicElements extends ThreeElements {}
1554
- }
1555
- }
1556
-
1557
- type three_d_Color = Color;
1558
- type three_d_ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = ElementProps<T, P>;
1559
- type three_d_Euler = Euler;
1560
- type three_d_EventProps<P> = EventProps<P>;
1561
- type three_d_GeometryProps<P> = GeometryProps<P>;
1562
- type three_d_GeometryTransformProps = GeometryTransformProps;
1563
- type three_d_Layers = Layers;
1564
- type three_d_MathProps<P> = MathProps<P>;
1565
- type three_d_MathRepresentation = MathRepresentation;
1566
- type three_d_MathType<T extends MathTypes> = MathType<T>;
1567
- type three_d_MathTypes = MathTypes;
1568
- type three_d_Matrix3 = Matrix3;
1569
- type three_d_Matrix4 = Matrix4;
1570
- type three_d_MutableOrReadonlyParameters<T extends (...args: any) => any> = MutableOrReadonlyParameters<T>;
1571
- type three_d_NodeProps<P> = NodeProps<P>;
1572
- type three_d_Object3DMethod = Object3DMethod;
1573
- type three_d_Quaternion = Quaternion;
1574
- type three_d_RaycastableRepresentation = RaycastableRepresentation;
1575
- type three_d_ReactProps<P> = ReactProps<P>;
1576
- type three_d_TSLNodeInput = TSLNodeInput;
1577
- type three_d_ThreeElement<T extends ConstructorRepresentation> = ThreeElement<T>;
1578
- type three_d_ThreeElements = ThreeElements;
1579
- type three_d_ThreeElementsImpl = ThreeElementsImpl;
1580
- type three_d_ThreeExports = ThreeExports;
1581
- type three_d_ThreeToJSXElements<T extends Record<string, any>> = ThreeToJSXElements<T>;
1582
- type three_d_Vector2 = Vector2;
1583
- type three_d_Vector3 = Vector3;
1584
- type three_d_Vector4 = Vector4;
1585
- type three_d_VectorRepresentation = VectorRepresentation;
1586
- declare namespace three_d {
1587
- 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_Object3DMethod as Object3DMethod, 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 };
1588
- }
1589
-
1590
- /**
1591
- * @fileoverview Registry for primary canvases that can be targeted by secondary canvases
1592
- *
1593
- * Enables multi-canvas WebGPU rendering where multiple Canvas components share
1594
- * a single WebGPURenderer using Three.js CanvasTarget API.
1595
- *
1596
- * Primary canvas: Has `id` prop, creates its own renderer, registers here
1597
- * Secondary canvas: Has `renderer={{ primaryCanvas: 'id' }}`, shares primary's renderer via CanvasTarget
1598
- */
1599
-
1600
- interface PrimaryCanvasEntry {
1601
- /** The WebGPURenderer instance owned by this primary canvas */
1602
- renderer: WebGPURenderer;
1603
- /** The zustand store for this canvas */
1604
- store: RootStore;
1605
- }
1606
- /**
1607
- * Register a primary canvas that can be targeted by secondary canvases.
1608
- *
1609
- * @param id - Unique identifier for this primary canvas
1610
- * @param renderer - The WebGPURenderer owned by this canvas
1611
- * @param store - The zustand store for this canvas
1612
- * @returns Cleanup function to unregister on unmount
1613
- */
1614
- declare function registerPrimary(id: string, renderer: WebGPURenderer, store: RootStore): () => void;
1615
- /**
1616
- * Get a registered primary canvas by id.
1617
- *
1618
- * @param id - The id of the primary canvas to look up
1619
- * @returns The primary canvas entry or undefined if not found
1620
- */
1621
- declare function getPrimary(id: string): PrimaryCanvasEntry | undefined;
1622
- /**
1623
- * Wait for a primary canvas to be registered.
1624
- * Returns immediately if already registered, otherwise waits.
1625
- *
1626
- * @param id - The id of the primary canvas to wait for
1627
- * @param timeout - Optional timeout in ms (default: 5000)
1628
- * @returns Promise that resolves with the primary canvas entry
1629
- */
1630
- declare function waitForPrimary(id: string, timeout?: number): Promise<PrimaryCanvasEntry>;
1631
- /**
1632
- * Check if a primary canvas with the given id exists.
1633
- *
1634
- * @param id - The id to check
1635
- * @returns True if a primary canvas with this id is registered
1636
- */
1637
- declare function hasPrimary(id: string): boolean;
1638
- /**
1639
- * Unregister a primary canvas. Called on unmount.
1640
- *
1641
- * @param id - The id of the primary canvas to unregister
1642
- */
1643
- declare function unregisterPrimary(id: string): void;
1644
- /**
1645
- * Get all registered primary canvas ids. Useful for debugging.
1646
- */
1647
- declare function getPrimaryIds(): string[];
1648
-
1649
- type EnvironmentLoaderProps = {
1650
- files?: string | string[];
1651
- path?: string;
1652
- preset?: PresetsType;
1653
- extensions?: (loader: Loader$1) => void;
1654
- colorSpace?: ColorSpace;
1655
- };
1656
- /**
1657
- * Loads environment textures for reflections and lighting.
1658
- * Supports HDR files, presets, and cubemaps.
1659
- *
1660
- * @example Basic usage
1661
- * ```jsx
1662
- * const texture = useEnvironment({ preset: 'sunset' })
1663
- * ```
1664
- */
1665
- declare function useEnvironment({ files, path, preset, colorSpace, extensions, }?: Partial<EnvironmentLoaderProps>): Texture$1<unknown, THREE$1.TextureEventMap> | CubeTexture<unknown>;
1666
- declare namespace useEnvironment {
1667
- var preload: (preloadOptions?: EnvironmentLoaderPreloadOptions) => void;
1668
- var clear: (clearOptions?: EnvironmentLoaderClearOptions) => void;
1669
- }
1670
- /**
1671
- * Options accepted by `useEnvironment.preload`.
1672
- *
1673
- * `colorSpace` is deliberately omitted: preload only warms the loader cache, and colorSpace is
1674
- * applied to the texture by `useEnvironment()` at use time, per consumer. Accepting it here would
1675
- * advertise an option this function silently ignores.
1676
- *
1677
- * This previously read `Omit<…, 'encoding'>` — omitting a key that does not exist on
1678
- * `EnvironmentLoaderProps`, a leftover from three's pre-`colorSpace` `encoding` API. That made the
1679
- * type equivalent to the full props, so `colorSpace` was accepted and then dropped on the floor.
1680
- */
1681
- type EnvironmentLoaderPreloadOptions = Omit<EnvironmentLoaderProps, 'colorSpace'>;
1682
- type EnvironmentLoaderClearOptions = Pick<EnvironmentLoaderProps, 'files' | 'preset'>;
1683
-
1684
- /**
1685
- * Props for Environment component that sets up global cubemap for PBR materials and backgrounds.
1686
- *
1687
- * @property children - React children to render into custom environment portal
1688
- * @property frames - Number of frames to render the environment. Use 1 for static, Infinity for animated (default: 1)
1689
- * @property near - Near clipping plane for cube camera (default: 0.1)
1690
- * @property far - Far clipping plane for cube camera (default: 1000)
1691
- * @property resolution - Resolution of the cube render target (default: 256)
1692
- * @property background - Whether to set scene.background. Can be true, false, or "only" (which only sets background) (default: false)
1693
- *
1694
- * @property blur - @deprecated Use backgroundBlurriness instead
1695
- * @property backgroundBlurriness - Blur factor between 0 and 1 for background (default: 0, requires three.js 0.146+)
1696
- * @property backgroundIntensity - Intensity factor for background (default: 1, requires three.js 0.163+)
1697
- * @property backgroundRotation - Rotation for background as Euler angles (default: [0,0,0], requires three.js 0.163+)
1698
- * @property environmentIntensity - Intensity factor for environment lighting (default: 1, requires three.js 0.163+)
1699
- * @property environmentRotation - Rotation for environment as Euler angles (default: [0,0,0], requires three.js 0.163+)
1700
- *
1701
- * @property map - Pre-existing texture to use as environment map
1702
- * @property preset - HDRI Haven preset: 'apartment', 'city', 'dawn', 'forest', 'lobby', 'night', 'park', 'studio', 'sunset', 'warehouse'. Not for production use.
1703
- * @property scene - Custom THREE.Scene or ref to apply environment to (default: uses default scene)
1704
- * @property ground - Ground projection settings. Use true for defaults or object with:
1705
- * - height: Height of camera used to create env map (default: 15)
1706
- * - radius: Radius of the world (default: 60)
1707
- * - scale: Scale of backside projected sphere (default: 1000)
1708
- *
1709
- * Additional loader props:
1710
- * @property files - File path(s) for environment. Supports .hdr, .exr, gainmap .jpg/.webp, or array of 6 cube faces
1711
- * @property path - Base path for file loading
1712
- * @property extensions - Texture extensions override
1713
- */
1714
- type EnvironmentProps = {
1715
- children?: React$1.ReactNode;
1716
- frames?: number;
1717
- near?: number;
1718
- far?: number;
1719
- resolution?: number;
1720
- background?: boolean | 'only';
1721
- /** deprecated, use backgroundBlurriness */
1722
- blur?: number;
1723
- backgroundBlurriness?: number;
1724
- backgroundIntensity?: number;
1725
- backgroundRotation?: Euler;
1726
- environmentIntensity?: number;
1727
- environmentRotation?: Euler;
1728
- map?: Texture$1;
1729
- preset?: PresetsType;
1730
- scene?: Scene | React$1.RefObject<Scene>;
1731
- ground?: boolean | {
1732
- radius?: number;
1733
- height?: number;
1734
- scale?: number;
1735
- };
1736
- /** Solid color for background (alternative to files/preset) */
1737
- color?: ColorRepresentation$1;
1738
- /** Separate files for background (when different from environment files) */
1739
- backgroundFiles?: string | string[];
1740
- } & EnvironmentLoaderProps;
1741
- /**
1742
- * Internal component that applies a pre-existing texture as environment map.
1743
- * Sets scene.environment and optionally scene.background.
1744
- *
1745
- * @example
1746
- * ```jsx
1747
- * <CubeCamera>{(texture) => <EnvironmentMap map={texture} />}</CubeCamera>
1748
- * ```
1749
- */
1750
- declare function EnvironmentMap({ scene, background, map, ...config }: EnvironmentProps): null;
1751
- /**
1752
- * Internal component that loads environment textures from files or presets.
1753
- * Uses HDRLoader for .hdr, EXRLoader for .exr, UltraHDRLoader for .jpg/.jpeg HDR,
1754
- * GainMapLoader for gainmap .webp, or CubeTextureLoader for arrays of images.
1755
- *
1756
- * @example With preset
1757
- * ```jsx
1758
- * <EnvironmentCube preset="sunset" />
1759
- * ```
1760
- *
1761
- * @example From HDR file
1762
- * ```jsx
1763
- * <EnvironmentCube files="environment.hdr" />
1764
- * ```
1765
- *
1766
- * @example From gainmap (smallest footprint)
1767
- * ```jsx
1768
- * <EnvironmentCube files={['file.webp', 'file-gainmap.webp', 'file.json']} />
1769
- * ```
1770
- *
1771
- * @example From cube faces
1772
- * ```jsx
1773
- * <EnvironmentCube files={['px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png']} />
1774
- * ```
1775
- */
1776
- declare function EnvironmentCube({ background, scene, blur, backgroundBlurriness, backgroundIntensity, backgroundRotation, environmentIntensity, environmentRotation, ...rest }: EnvironmentProps): null;
1777
- /**
1778
- * Internal component that renders custom environment using a portal and cube camera.
1779
- * Renders children into an off-buffer and films with a cube camera to create environment map.
1780
- * Can be static (frames=1) or animated (frames=Infinity).
1781
- *
1782
- * @example Custom environment with sphere
1783
- * ```jsx
1784
- * <EnvironmentPortal background near={1} far={1000} resolution={256}>
1785
- * <mesh scale={100}>
1786
- * <sphereGeometry args={[1, 64, 64]} />
1787
- * <meshBasicMaterial map={texture} side={THREE.BackSide} />
1788
- * </mesh>
1789
- * </EnvironmentPortal>
1790
- * ```
1791
- *
1792
- * @example Animated environment
1793
- * ```jsx
1794
- * <EnvironmentPortal frames={Infinity} resolution={256}>
1795
- * <Float>
1796
- * <mesh />
1797
- * </Float>
1798
- * </EnvironmentPortal>
1799
- * ```
1800
- *
1801
- * @example Mixed with preset
1802
- * ```jsx
1803
- * <EnvironmentPortal preset="warehouse">
1804
- * <mesh />
1805
- * </EnvironmentPortal>
1806
- * ```
1807
- */
1808
- 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;
1809
- declare module '@react-three/fiber' {
1810
- interface ThreeElements {
1811
- groundProjectedEnvImpl: ThreeElement<typeof GroundedSkybox>;
1812
- }
1813
- }
1814
- /**
1815
- * Sets up a global environment map for PBR materials and backgrounds.
1816
- * Affects scene.environment and optionally scene.background unless a custom scene is passed.
1817
- *
1818
- * Supports multiple input methods:
1819
- * - **Presets**: Selection of HDRI Haven assets (apartment, city, dawn, forest, lobby, night, park, studio, sunset, warehouse)
1820
- * - **Files**: HDR (.hdr), EXR (.exr), gainmap JPEG (.jpg), gainmap WebP (.webp), or cube faces (array of 6 images)
1821
- * - **Texture**: Pre-existing cube texture via `map` prop
1822
- * - **Custom Scene**: Render children into environment using portal and cube camera
1823
- * - **Ground Projection**: Project environment onto ground plane
1824
- *
1825
- * @remarks
1826
- * - Preset property is NOT meant for production and may fail (relies on CDNs)
1827
- * - Gainmap format has the smallest file footprint
1828
- * - Use `frames={Infinity}` for animated environments with low resolution for performance
1829
- * - Ground projection places models on the "ground" within the environment map
1830
- * - Supports self-hosting with @pmndrs/assets using dynamic imports
1831
- *
1832
- * @example Basic preset usage
1833
- * ```jsx
1834
- * <Environment preset="sunset" />
1835
- * ```
1836
- *
1837
- * @example From HDR file
1838
- * ```jsx
1839
- * <Environment files="/hdr/environment.hdr" />
1840
- * ```
1841
- *
1842
- * @example From gainmap (smallest footprint)
1843
- * ```jsx
1844
- * <Environment files={['file.webp', 'file-gainmap.webp', 'file.json']} />
1845
- * ```
1846
- *
1847
- * @example With self-hosted assets
1848
- * ```jsx
1849
- * import { suspend } from 'suspend-react'
1850
- * const city = import('@pmndrs/assets/hdri/city.exr').then(m => m.default)
1851
- *
1852
- * <Environment files={suspend(city)} />
1853
- * ```
1854
- *
1855
- * @example From existing texture
1856
- * ```jsx
1857
- * <CubeCamera>{(texture) => <Environment map={texture} />}</CubeCamera>
1858
- * ```
1859
- *
1860
- * @example Custom environment scene
1861
- * ```jsx
1862
- * <Environment background near={1} far={1000} resolution={256}>
1863
- * <mesh scale={100}>
1864
- * <sphereGeometry args={[1, 64, 64]} />
1865
- * <meshBasicMaterial map={texture} side={THREE.BackSide} />
1866
- * </mesh>
1867
- * </Environment>
1868
- * ```
1869
- *
1870
- * @example Animated environment
1871
- * ```jsx
1872
- * <Environment frames={Infinity} resolution={256}>
1873
- * <Float>
1874
- * <mesh />
1875
- * </Float>
1876
- * </Environment>
1877
- * ```
1878
- *
1879
- * @example Mixed custom scene with preset
1880
- * ```jsx
1881
- * <Environment background preset="warehouse">
1882
- * <mesh />
1883
- * </Environment>
1884
- * ```
1885
- *
1886
- * @example With ground projection
1887
- * ```jsx
1888
- * <Environment ground={{ height: 15, radius: 60 }} preset="city" />
1889
- * ```
1890
- *
1891
- * @example As background only
1892
- * ```jsx
1893
- * <Environment background="only" preset="sunset" />
1894
- * ```
1895
- *
1896
- * @example With rotation and intensity
1897
- * ```jsx
1898
- * <Environment
1899
- * background
1900
- * backgroundBlurriness={0.5}
1901
- * backgroundIntensity={0.8}
1902
- * backgroundRotation={[0, Math.PI / 2, 0]}
1903
- * environmentIntensity={1.2}
1904
- * environmentRotation={[0, Math.PI / 4, 0]}
1905
- * preset="studio"
1906
- * />
1907
- * ```
1908
- */
1909
- declare function Environment(props: EnvironmentProps): react_jsx_runtime.JSX.Element;
1910
-
1911
- /**
1912
- * Moves every trace of interactivity from one object to its replacement, for reconstruction.
1913
- *
1914
- * When `args` or a `primitive`'s `object` changes, R3F builds a new three object and keeps the same
1915
- * instance. Removing the old object from the interaction state and registering the new one from
1916
- * scratch makes events *work* again (#3778), but it forgets what was in flight: a pointer resting on
1917
- * the object fires a second `onPointerEnter` without ever having left, and an active pointer capture
1918
- * is dropped mid-drag. Rewriting the references instead keeps the interaction continuous across a
1919
- * swap the user never asked to see (#3744).
1920
- *
1921
- * Captures are re-keyed rather than released, so the DOM-level capture on `captureData.target` is
1922
- * left alone — releasing and re-acquiring it is precisely the glitch being avoided.
1923
- *
1924
- * Visibility handlers are deliberately not transferred: that registry is keyed by `object.uuid`, so
1925
- * the replacement re-registers itself through `applyProps`. The old entry is dropped here so it
1926
- * cannot outlive the object it described.
1927
- */
1928
- declare function swapInteractivity(store: RootStore, object: Object3D, newObject: Object3D): void;
1929
- declare function removeInteractivity(store: RootStore, object: Object3D): void;
1930
- declare function createEvents(store: RootStore): {
1931
- handlePointer: (name: string) => (event: DomEvent) => void;
1932
- flushDeferredPointers: () => void;
1933
- processDeferredPointer: (event: DomEvent, pointerId: number) => void;
1934
- };
1935
- /** Default R3F event manager for web */
1936
- declare function createPointerEvents(store: RootStore): EventManager<Element>;
1937
-
1938
- /**
1939
- * Gets or creates a memoized loader instance from a loader constructor or returns the loader if it's already an instance.
1940
- * This allows external code to access loader methods like abort().
1941
- */
1942
- declare function getLoader<L extends LoaderLike | ConstructorRepresentation<LoaderLike>>(Proto: L): L extends ConstructorRepresentation<infer T> ? T : L;
1943
- /**
1944
- * Synchronously loads and caches assets with a three loader.
1945
- *
1946
- * Note: this hook's caller must be wrapped with `React.Suspense`
1947
- * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#useloader
1948
- */
1949
- declare function useLoader<I extends InputLike, L extends LoaderLike | ConstructorRepresentation<LoaderLike>>(loader: L, input: I, extensions?: Extensions<L>, onProgress?: (event: ProgressEvent<EventTarget>) => void, cacheKey?: InputLike): I extends any[] ? LoaderResult<L>[] : LoaderResult<L>;
1950
- declare namespace useLoader {
1951
- var preload: <I extends InputLike, L extends LoaderLike | ConstructorRepresentation<LoaderLike>>(loader: L, input: I, extensions?: Extensions<L>, onProgress?: (event: ProgressEvent<EventTarget>) => void, cacheKey?: InputLike) => void;
1952
- var clear: <I extends InputLike, L extends LoaderLike | ConstructorRepresentation<LoaderLike>>(loader: L, input: I, cacheKey?: InputLike) => void;
1953
- var loader: typeof getLoader;
1954
- }
1955
-
1956
- declare const IsObject: (url: unknown) => url is Record<string, string>;
1957
- type TextureArray<T> = T extends string[] ? Texture$1[] : never;
1958
- type TextureRecord<T> = T extends Record<string, string> ? {
1959
- [key in keyof T]: Texture$1;
1960
- } : never;
1961
- type SingleTexture<T> = T extends string ? Texture$1 : never;
1962
- type MappedTextureType<T extends string[] | string | Record<string, string>> = TextureArray<T> | TextureRecord<T> | SingleTexture<T>;
1963
- /** Options for useTexture hook */
1964
- type UseTextureOptions<Url extends string[] | string | Record<string, string>> = {
1965
- /** Callback when texture(s) finish loading */
1966
- onLoad?: (texture: MappedTextureType<Url>) => void;
1967
- /**
1968
- * Register the texture(s) in R3F's global texture registry for access via useTextures().
1969
- * When true (the default):
1970
- * - Textures persist until explicitly disposed
1971
- * - On mount, returns existing registered textures if available (preserving modifications like colorSpace)
1972
- *
1973
- * Reads are taken once at mount — a mounted `useTexture` does not re-render when the registry
1974
- * changes. To react to registry swaps, use `useTextures(s => s.get(key))` instead.
1975
- *
1976
- * Pass `false` to opt out of registry enrollment entirely.
1977
- * @default true
1978
- */
1979
- cache?: boolean;
1980
- };
1981
- /**
1982
- * Load texture(s) using Three's TextureLoader with Suspense support.
1983
- *
1984
- * @param input - URL string, array of URLs, or object mapping keys to URLs
1985
- * @param optionsOrOnLoad - Options object or legacy onLoad callback
1986
- *
1987
- * @example
1988
- * ```tsx
1989
- * // Single texture
1990
- * const diffuse = useTexture('/textures/diffuse.png')
1991
- *
1992
- * // Multiple textures (array)
1993
- * const [diffuse, normal] = useTexture(['/diffuse.png', '/normal.png'])
1994
- *
1995
- * // Named textures (object)
1996
- * const { diffuse, normal } = useTexture({
1997
- * diffuse: '/diffuse.png',
1998
- * normal: '/normal.png'
1999
- * })
2000
- *
2001
- * // Textures are registered in the global registry by default — the same texture
2002
- * // object is shared across components and modifications (colorSpace, wrapS, etc.) are preserved
2003
- * const diffuse = useTexture('/diffuse.png')
2004
- * diffuse.colorSpace = THREE.SRGBColorSpace
2005
- *
2006
- * // Another component gets the SAME texture with colorSpace already set
2007
- * const sameDiffuse = useTexture('/diffuse.png')
2008
- *
2009
- * // Opt out of registry enrollment for a one-off texture
2010
- * const scratch = useTexture('/scratch.png', { cache: false })
2011
- *
2012
- * // Access the registry directly
2013
- * const { get } = useTextures()
2014
- * const cached = get('/diffuse.png')
2015
- * ```
2016
- */
2017
- declare function useTexture<Url extends string[] | string | Record<string, string>>(input: Url, optionsOrOnLoad?: UseTextureOptions<Url> | ((texture: MappedTextureType<Url>) => void)): MappedTextureType<Url>;
2018
- declare namespace useTexture {
2019
- var preload: (url: string | string[]) => void;
2020
- var clear: (input: string | string[]) => void;
2021
- }
2022
- declare const Texture: ({ children, input, onLoad, cache, }: {
2023
- children?: (texture: ReturnType<typeof useTexture>) => ReactNode;
2024
- input: Parameters<typeof useTexture>[0];
2025
- onLoad?: Parameters<typeof useTexture>[1];
2026
- cache?: boolean;
2027
- }) => react_jsx_runtime.JSX.Element;
2028
-
2029
- /** Accepted shapes for a registry read: a single key, a list of keys, or a name→key map. */
2030
- type TextureInput = string | string[] | Record<string, string>;
2031
- /** Result of a `get()` read, mirroring the input shape. */
2032
- type TextureResult<Input extends TextureInput> = Input extends string ? Texture$1 | undefined : Input extends string[] ? (Texture$1 | undefined)[] : {
2033
- [K in keyof Input]: Texture$1 | undefined;
2034
- };
2035
- /** Options for `dispose()`. */
2036
- interface DisposeOptions {
2037
- /** Dispose even if the texture still has active references (default false). */
2038
- force?: boolean;
2039
- }
2040
- interface UseTexturesReturn {
2041
- /** The live registry Map (key → Texture). Treat as read-only. */
2042
- readonly all: Map<string, Texture$1>;
2043
- /** Read one texture, an array of textures, or a name→texture record (mirrors the input shape). */
2044
- get<Input extends TextureInput>(input: Input): TextureResult<Input>;
2045
- /** Check whether a key exists in the registry. */
2046
- has(key: string): boolean;
2047
- /**
2048
- * Register a texture (or a record of textures) that has no URL — e.g. a render
2049
- * target or procedural texture. URL-loaded textures are registered automatically
2050
- * by `useTexture` (registry enrollment is on by default).
2051
- */
2052
- add(key: string, texture: Texture$1): void;
2053
- add(record: Record<string, Texture$1>): void;
2054
- /**
2055
- * Dispose a texture's GPU resources and remove it from the registry.
2056
- * Refcount-aware: if the key is still in use by a mounted `useTexture` consumer it is
2057
- * skipped (with a warning) unless `{ force: true }` is passed.
2058
- * @returns true if disposed, false if skipped.
2059
- */
2060
- dispose(key: string, options?: DisposeOptions): boolean;
2061
- /** Dispose every texture in the registry and clear it. Use on scene teardown. */
2062
- disposeAll(): void;
2063
- }
2064
- /**
2065
- * Reactive Texture registry — load once with `useTexture`, reach the textures from anywhere.
2066
- *
2067
- * This is a registry of plain `Texture` objects (not TSL nodes), so the same texture can feed
2068
- * a material map, a heightmap sampler, or anything else. It does **not** load — pair it with
2069
- * `useTexture` for loading (registry enrollment is on by default); `useTextures` is for access and lifecycle.
2070
- *
2071
- * The returned handle is **reactive**: the calling component re-renders when the registry
2072
- * changes. Pass a selector to scope the subscription to a single read.
2073
- *
2074
- * @example
2075
- * ```tsx
2076
- * // Load + register once (anywhere in the tree) — registered by default
2077
- * useTexture({ map: '/diffuse.jpg', normalMap: '/normal.jpg' })
2078
- *
2079
- * // Reach them from another component — record form lands straight into a material
2080
- * const { map, normalMap } = useTextures().get({ map: '/diffuse.jpg', normalMap: '/normal.jpg' })
2081
- * return <meshStandardMaterial map={map} normalMap={normalMap} />
2082
- *
2083
- * // A set of heightmaps at once
2084
- * const [a, b, c] = useTextures().get(['/h0.png', '/h1.png', '/h2.png'])
2085
- *
2086
- * // Register a non-URL texture (render target / procedural)
2087
- * useTextures().add('rt-main', renderTarget.texture)
2088
- *
2089
- * // Deliberate GPU cleanup (refcount-aware; force to override)
2090
- * useTextures().dispose('/diffuse.jpg')
2091
- * useTextures().disposeAll() // scene teardown
2092
- * ```
2093
- *
2094
- * @remarks
2095
- * **Future expansion:** an imperative async loader (e.g. `await useTextures().load('/x.jpg')`) is
2096
- * intentionally not included yet. It would let non-React code (loading screens, dynamic streaming)
2097
- * populate the registry without Suspense, at the cost of putting loading back into this hook. It
2098
- * will be added only if a concrete consumer needs imperative loading; for now, loading lives in
2099
- * `useTexture`.
2100
- */
2101
- declare function useTextures(): UseTexturesReturn;
2102
- declare function useTextures<T>(selector: (registry: UseTexturesReturn) => T): T;
2103
-
2104
- /**
2105
- * Creates a render target compatible with the current renderer.
2106
- *
2107
- * - Legacy build: Returns WebGLRenderTarget
2108
- * - WebGPU build: Returns RenderTarget
2109
- * - Default build: Returns whichever matches the active renderer
2110
- *
2111
- * @example
2112
- * ```tsx
2113
- * // Use canvas size
2114
- * const fbo = useRenderTarget()
2115
- *
2116
- * // Use canvas size with options
2117
- * const fbo = useRenderTarget({ samples: 4 })
2118
- *
2119
- * // Square render target
2120
- * const fbo = useRenderTarget(512)
2121
- *
2122
- * // Square render target with options
2123
- * const fbo = useRenderTarget(512, { depthBuffer: true })
2124
- *
2125
- * // Explicit dimensions
2126
- * const fbo = useRenderTarget(512, 256)
2127
- *
2128
- * // Explicit dimensions with options
2129
- * const fbo = useRenderTarget(512, 256, { samples: 4 })
2130
- * ```
2131
- */
2132
- declare function useRenderTarget(options?: RenderTargetOptions): RenderTarget;
2133
- declare function useRenderTarget(size: number, options?: RenderTargetOptions): RenderTarget;
2134
- declare function useRenderTarget(width: number, height: number, options?: RenderTargetOptions): RenderTarget;
2135
-
2136
- /**
2137
- * Returns the R3F Canvas' Zustand store. Useful for [transient updates](https://github.com/pmndrs/zustand#transient-updates-for-often-occurring-state-changes).
2138
- * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#usestore
2139
- */
2140
- declare function useStore(): RootStore;
2141
- /**
2142
- * Exposes an object's {@link Instance}.
2143
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#useInstanceHandle
2144
- *
2145
- * **Note**: this is an escape hatch to react-internal fields. Expect this to change significantly between versions.
2146
- */
2147
- declare function useInstanceHandle<T>(ref: React.RefObject<T>): React.RefObject<Instance<T>>;
2148
- /**
2149
- * Returns a node graph of an object with named nodes & materials.
2150
- * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#usegraph
2151
- */
2152
- declare function useGraph(object: Object3D): ObjectMap;
2153
-
2154
- /**
2155
- * Adds a global render callback which is called each frame BEFORE rendering.
2156
- *
2157
- * @deprecated Use `useFrame(callback, { phase: 'start' })` instead.
2158
- * This function will be removed in a future version.
2159
- *
2160
- * @param callback - Function called each frame with timestamp
2161
- * @returns Unsubscribe function
2162
- *
2163
- * @example
2164
- * // OLD (deprecated)
2165
- * const unsub = addEffect((timestamp) => { ... })
2166
- *
2167
- * // NEW
2168
- * useFrame((state, delta) => { ... }, { phase: 'start' })
2169
- *
2170
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addEffect
2171
- */
2172
- declare function addEffect(callback: GlobalRenderCallback): () => void;
2173
- /**
2174
- * Adds a global after-render callback which is called each frame AFTER rendering.
2175
- *
2176
- * @deprecated Use `useFrame(callback, { phase: 'finish' })` instead.
2177
- * This function will be removed in a future version.
2178
- *
2179
- * @param callback - Function called each frame with timestamp
2180
- * @returns Unsubscribe function
2181
- *
2182
- * @example
2183
- * // OLD (deprecated)
2184
- * const unsub = addAfterEffect((timestamp) => { ... })
2185
- *
2186
- * // NEW
2187
- * useFrame((state, delta) => { ... }, { phase: 'finish' })
2188
- *
2189
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addAfterEffect
2190
- */
2191
- declare function addAfterEffect(callback: GlobalRenderCallback): () => void;
2192
- /**
2193
- * Adds a global callback which is called when rendering stops.
2194
- *
2195
- * @deprecated Use `scheduler.onIdle(callback)` instead.
2196
- * This function will be removed in a future version.
2197
- *
2198
- * @param callback - Function called when rendering stops
2199
- * @returns Unsubscribe function
2200
- *
2201
- * @example
2202
- * // OLD (deprecated)
2203
- * const unsub = addTail((timestamp) => { ... })
2204
- *
2205
- * // NEW
2206
- * const { scheduler } = useFrame()
2207
- * const unsub = scheduler.onIdle((timestamp) => { ... })
2208
- *
2209
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addTail
2210
- */
2211
- declare function addTail(callback: GlobalRenderCallback): () => void;
2212
- /**
2213
- * Invalidates the view, requesting a frame to be rendered.
2214
- * In demand mode, this triggers the scheduler to run frames.
2215
- *
2216
- * With a state argument, only that root's jobs run on the requested frames; other
2217
- * roots on 'demand' stay idle. Without one, every registered root is invalidated.
2218
- *
2219
- * @param state - Optional root state; targets the invalidation at that root
2220
- * @param frames - Number of frames to request (default: 1)
2221
- * @param stackFrames - If false, sets pendingFrames to frames. If true, adds to existing pendingFrames (default: false)
2222
- *
2223
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#invalidate
2224
- */
2225
- declare function invalidate(state?: RootState, frames?: number, stackFrames?: boolean): void;
2226
- /**
2227
- * Advances the frameloop and runs render effects.
2228
- * Useful for when manually rendering via `frameloop="never"`.
2229
- *
2230
- * With a state argument, only that root is stepped. Without one, every
2231
- * registered root is stepped for backwards compatibility.
2232
- *
2233
- * @param timestamp - The timestamp to use for this frame
2234
- * @param runGlobalEffects - Ignored (kept for backwards compat, global effects always run)
2235
- * @param state - Optional root state; targets the manual step at that root
2236
- *
2237
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#advance
2238
- */
2239
- declare function advance(timestamp: number, runGlobalEffects?: boolean, state?: RootState): void;
2240
-
2241
- /* eslint-disable @definitelytyped/no-unnecessary-generics */
2242
- declare function ReactReconciler<
2243
- Type,
2244
- Props,
2245
- Container,
2246
- Instance,
2247
- TextInstance,
2248
- SuspenseInstance,
2249
- HydratableInstance,
2250
- FormInstance,
2251
- PublicInstance,
2252
- HostContext,
2253
- ChildSet,
2254
- TimeoutHandle,
2255
- NoTimeout,
2256
- TransitionStatus,
2257
- >(
2258
- /* eslint-enable @definitelytyped/no-unnecessary-generics */
2259
- config: ReactReconciler.HostConfig<
2260
- Type,
2261
- Props,
2262
- Container,
2263
- Instance,
2264
- TextInstance,
2265
- SuspenseInstance,
2266
- HydratableInstance,
2267
- FormInstance,
2268
- PublicInstance,
2269
- HostContext,
2270
- ChildSet,
2271
- TimeoutHandle,
2272
- NoTimeout,
2273
- TransitionStatus
2274
- >,
2275
- ): ReactReconciler.Reconciler<Container, Instance, TextInstance, SuspenseInstance, FormInstance, PublicInstance>;
2276
-
2277
- declare namespace ReactReconciler {
2278
- interface HostConfig<
2279
- Type,
2280
- Props,
2281
- Container,
2282
- Instance,
2283
- TextInstance,
2284
- SuspenseInstance,
2285
- HydratableInstance,
2286
- FormInstance,
2287
- PublicInstance,
2288
- HostContext,
2289
- ChildSet,
2290
- TimeoutHandle,
2291
- NoTimeout,
2292
- TransitionStatus,
2293
- > {
2294
- // -------------------
2295
- // Modes
2296
- // -------------------
2297
- /**
2298
- * The reconciler has two modes: mutation mode and persistent mode. You must specify one of them.
2299
- *
2300
- * If your target platform is similar to the DOM and has methods similar to `appendChild`, `removeChild`, and so on, you'll want to use the **mutation mode**. This is the same mode used by React DOM, React ART, and the classic React Native renderer.
2301
- *
2302
- * ```js
2303
- * const HostConfig = {
2304
- * // ...
2305
- * supportsMutation: true,
2306
- * // ...
2307
- * }
2308
- * ```
2309
- *
2310
- * Depending on the mode, the reconciler will call different methods on your host config.
2311
- *
2312
- * If you're not sure which one you want, you likely need the mutation mode.
2313
- */
2314
- supportsMutation: boolean;
2315
-
2316
- /**
2317
- * The reconciler has two modes: mutation mode and persistent mode. You must specify one of them.
2318
- *
2319
- * If your target platform has immutable trees, you'll want the **persistent mode** instead. In that mode, existing nodes are never mutated, and instead every change clones the parent tree and then replaces the whole parent tree at the root. This is the node used by the new React Native renderer, codenamed "Fabric".
2320
- *
2321
- * ```js
2322
- * const HostConfig = {
2323
- * // ...
2324
- * supportsPersistence: true,
2325
- * // ...
2326
- * }
2327
- * ```
2328
- *
2329
- * Depending on the mode, the reconciler will call different methods on your host config.
2330
- *
2331
- * If you're not sure which one you want, you likely need the mutation mode.
2332
- */
2333
- supportsPersistence: boolean;
2334
-
2335
- // -------------------
2336
- // Core Methods
2337
- // -------------------
2338
-
2339
- /**
2340
- * This method should return a newly created node. For example, the DOM renderer would call `document.createElement(type)` here and then set the properties from `props`.
2341
- *
2342
- * You can use `rootContainer` to access the root container associated with that tree. For example, in the DOM renderer, this is useful to get the correct `document` reference that the root belongs to.
2343
- *
2344
- * The `hostContext` parameter lets you keep track of some information about your current place in the tree. To learn more about it, see `getChildHostContext` below.
2345
- *
2346
- * The `internalHandle` data structure is meant to be opaque. If you bend the rules and rely on its internal fields, be aware that it may change significantly between versions. You're taking on additional maintenance risk by reading from it, and giving up all guarantees if you write something to it.
2347
- *
2348
- * This method happens **in the render phase**. It can (and usually should) mutate the node it has just created before returning it, but it must not modify any other nodes. It must not register any event handlers on the parent tree. This is because an instance being created doesn't guarantee it would be placed in the tree — it could be left unused and later collected by GC. If you need to do something when an instance is definitely in the tree, look at `commitMount` instead.
2349
- */
2350
- createInstance(
2351
- type: Type,
2352
- props: Props,
2353
- rootContainer: Container,
2354
- hostContext: HostContext,
2355
- internalHandle: OpaqueHandle,
2356
- ): Instance;
2357
-
2358
- /**
2359
- * Same as `createInstance`, but for text nodes. If your renderer doesn't support text nodes, you can throw here.
2360
- */
2361
- createTextInstance(
2362
- text: string,
2363
- rootContainer: Container,
2364
- hostContext: HostContext,
2365
- internalHandle: OpaqueHandle,
2366
- ): TextInstance;
2367
-
2368
- /**
2369
- * This method should mutate the `parentInstance` and add the child to its list of children. For example, in the DOM this would translate to a `parentInstance.appendChild(child)` call.
2370
- *
2371
- * This method happens **in the render phase**. It can mutate `parentInstance` and `child`, but it must not modify any other nodes. It's called while the tree is still being built up and not connected to the actual tree on the screen.
2372
- */
2373
- appendInitialChild(parentInstance: Instance, child: Instance | TextInstance): void;
2374
-
2375
- /**
2376
- * In this method, you can perform some final mutations on the `instance`. Unlike with `createInstance`, by the time `finalizeInitialChildren` is called, all the initial children have already been added to the `instance`, but the instance itself has not yet been connected to the tree on the screen.
2377
- *
2378
- * This method happens **in the render phase**. It can mutate `instance`, but it must not modify any other nodes. It's called while the tree is still being built up and not connected to the actual tree on the screen.
2379
- *
2380
- * There is a second purpose to this method. It lets you specify whether there is some work that needs to happen when the node is connected to the tree on the screen. If you return `true`, the instance will receive a `commitMount` call later. See its documentation below.
2381
- *
2382
- * If you don't want to do anything here, you should return `false`.
2383
- */
2384
- finalizeInitialChildren(
2385
- instance: Instance,
2386
- type: Type,
2387
- props: Props,
2388
- rootContainer: Container,
2389
- hostContext: HostContext,
2390
- ): boolean;
2391
-
2392
- /**
2393
- * Some target platforms support setting an instance's text content without manually creating a text node. For example, in the DOM, you can set `node.textContent` instead of creating a text node and appending it.
2394
- *
2395
- * If you return `true` from this method, React will assume that this node's children are text, and will not create nodes for them. It will instead rely on you to have filled that text during `createInstance`. This is a performance optimization. For example, the DOM renderer returns `true` only if `type` is a known text-only parent (like `'textarea'`) or if `props.children` has a `'string'` type. If you return `true`, you will need to implement `resetTextContent` too.
2396
- *
2397
- * If you don't want to do anything here, you should return `false`.
2398
- *
2399
- * This method happens **in the render phase**. Do not mutate the tree from it.
2400
- */
2401
- shouldSetTextContent(type: Type, props: Props): boolean;
2402
-
2403
- /**
2404
- * This method lets you return the initial host context from the root of the tree. See `getChildHostContext` for the explanation of host context.
2405
- *
2406
- * If you don't intend to use host context, you can return `null`.
2407
- *
2408
- * This method happens **in the render phase**. Do not mutate the tree from it.
2409
- */
2410
- getRootHostContext(rootContainer: Container): HostContext | null;
2411
-
2412
- /**
2413
- * Host context lets you track some information about where you are in the tree so that it's available inside `createInstance` as the `hostContext` parameter. For example, the DOM renderer uses it to track whether it's inside an HTML or an SVG tree, because `createInstance` implementation needs to be different for them.
2414
- *
2415
- * If the node of this `type` does not influence the context you want to pass down, you can return `parentHostContext`. Alternatively, you can return any custom object representing the information you want to pass down.
2416
- *
2417
- * If you don't want to do anything here, return `parentHostContext`.
2418
- *
2419
- * This method happens **in the render phase**. Do not mutate the tree from it.
2420
- */
2421
- getChildHostContext(parentHostContext: HostContext, type: Type, rootContainer: Container): HostContext;
2422
-
2423
- /**
2424
- * Determines what object gets exposed as a ref. You'll likely want to return the `instance` itself. But in some cases it might make sense to only expose some part of it.
2425
- *
2426
- * If you don't want to do anything here, return `instance`.
2427
- */
2428
- getPublicInstance(instance: Instance | TextInstance): PublicInstance;
2429
-
2430
- /**
2431
- * This method lets you store some information before React starts making changes to the tree on the screen. For example, the DOM renderer stores the current text selection so that it can later restore it. This method is mirrored by `resetAfterCommit`.
2432
- *
2433
- * Even if you don't want to do anything here, you need to return `null` from it.
2434
- */
2435
- prepareForCommit(containerInfo: Container): Record<string, any> | null;
2436
-
2437
- /**
2438
- * This method is called right after React has performed the tree mutations. You can use it to restore something you've stored in `prepareForCommit` — for example, text selection.
2439
- *
2440
- * You can leave it empty.
2441
- */
2442
- resetAfterCommit(containerInfo: Container): void;
2443
-
2444
- /**
2445
- * This method is called for a container that's used as a portal target. Usually you can leave it empty.
2446
- */
2447
- preparePortalMount(containerInfo: Container): void;
2448
-
2449
- /**
2450
- * You can proxy this to `setTimeout` or its equivalent in your environment.
2451
- */
2452
- scheduleTimeout(fn: (...args: unknown[]) => unknown, delay?: number): TimeoutHandle;
2453
-
2454
- /**
2455
- * You can proxy this to `clearTimeout` or its equivalent in your environment.
2456
- */
2457
- cancelTimeout(id: TimeoutHandle): void;
2458
-
2459
- /**
2460
- * This is a property (not a function) that should be set to something that can never be a valid timeout ID. For example, you can set it to `-1`.
2461
- */
2462
- noTimeout: NoTimeout;
2463
-
2464
- /**
2465
- * Set this to true to indicate that your renderer supports `scheduleMicrotask`. We use microtasks as part of our discrete event implementation in React DOM. If you're not sure if your renderer should support this, you probably should. The option to not implement `scheduleMicrotask` exists so that platforms with more control over user events, like React Native, can choose to use a different mechanism.
2466
- */
2467
- supportsMicrotasks?: boolean;
2468
-
2469
- /**
2470
- * Optional. You can proxy this to `queueMicrotask` or its equivalent in your environment.
2471
- */
2472
- scheduleMicrotask?(fn: () => unknown): void;
2473
-
2474
- /**
2475
- * This is a property (not a function) that should be set to `true` if your renderer is the main one on the page. For example, if you're writing a renderer for the Terminal, it makes sense to set it to `true`, but if your renderer is used *on top of* React DOM or some other existing renderer, set it to `false`.
2476
- */
2477
- isPrimaryRenderer: boolean;
2478
-
2479
- /**
2480
- * Whether the renderer shouldn't trigger missing `act()` warnings
2481
- */
2482
- warnsIfNotActing?: boolean;
2483
-
2484
- getInstanceFromNode(node: any): Fiber | null | undefined;
2485
-
2486
- beforeActiveInstanceBlur(): void;
2487
-
2488
- afterActiveInstanceBlur(): void;
2489
-
2490
- prepareScopeUpdate(scopeInstance: any, instance: any): void;
2491
-
2492
- getInstanceFromScope(scopeInstance: any): null | Instance;
2493
-
2494
- detachDeletedInstance(node: Instance): void;
2495
-
2496
- // -------------------
2497
- // Mutation Methods
2498
- // (optional)
2499
- // If you're using React in mutation mode (you probably do), you'll need to implement a few more methods.
2500
- // -------------------
2501
-
2502
- /**
2503
- * This method should mutate the `parentInstance` and add the child to its list of children. For example, in the DOM this would translate to a `parentInstance.appendChild(child)` call.
2504
- *
2505
- * Although this method currently runs in the commit phase, you still should not mutate any other nodes in it. If you need to do some additional work when a node is definitely connected to the visible tree, look at `commitMount`.
2506
- */
2507
- appendChild?(parentInstance: Instance, child: Instance | TextInstance): void;
2508
-
2509
- /**
2510
- * Same as `appendChild`, but for when a node is attached to the root container. This is useful if attaching to the root has a slightly different implementation, or if the root container nodes are of a different type than the rest of the tree.
2511
- */
2512
- appendChildToContainer?(container: Container, child: Instance | TextInstance): void;
2513
-
2514
- /**
2515
- * This method should mutate the `parentInstance` and place the `child` before `beforeChild` in the list of its children. For example, in the DOM this would translate to a `parentInstance.insertBefore(child, beforeChild)` call.
2516
- *
2517
- * Note that React uses this method both for insertions and for reordering nodes. Similar to DOM, it is expected that you can call `insertBefore` to reposition an existing child. Do not mutate any other parts of the tree from it.
2518
- */
2519
- insertBefore?(
2520
- parentInstance: Instance,
2521
- child: Instance | TextInstance,
2522
- beforeChild: Instance | TextInstance | SuspenseInstance,
2523
- ): void;
2524
-
2525
- /**
2526
- * Same as `insertBefore`, but for when a node is attached to the root container. This is useful if attaching to the root has a slightly different implementation, or if the root container nodes are of a different type than the rest of the tree.
2527
- */
2528
- insertInContainerBefore?(
2529
- container: Container,
2530
- child: Instance | TextInstance,
2531
- beforeChild: Instance | TextInstance | SuspenseInstance,
2532
- ): void;
2533
-
2534
- /**
2535
- * This method should mutate the `parentInstance` to remove the `child` from the list of its children.
2536
- *
2537
- * React will only call it for the top-level node that is being removed. It is expected that garbage collection would take care of the whole subtree. You are not expected to traverse the child tree in it.
2538
- */
2539
- removeChild?(parentInstance: Instance, child: Instance | TextInstance | SuspenseInstance): void;
2540
-
2541
- /**
2542
- * Same as `removeChild`, but for when a node is detached from the root container. This is useful if attaching to the root has a slightly different implementation, or if the root container nodes are of a different type than the rest of the tree.
2543
- */
2544
- removeChildFromContainer?(container: Container, child: Instance | TextInstance | SuspenseInstance): void;
2545
-
2546
- /**
2547
- * If you returned `true` from `shouldSetTextContent` for the previous props, but returned `false` from `shouldSetTextContent` for the next props, React will call this method so that you can clear the text content you were managing manually. For example, in the DOM you could set `node.textContent = ''`.
2548
- *
2549
- * If you never return `true` from `shouldSetTextContent`, you can leave it empty.
2550
- */
2551
- resetTextContent?(instance: Instance): void;
2552
-
2553
- /**
2554
- * This method should mutate the `textInstance` and update its text content to `nextText`.
2555
- *
2556
- * Here, `textInstance` is a node created by `createTextInstance`.
2557
- */
2558
- commitTextUpdate?(textInstance: TextInstance, oldText: string, newText: string): void;
2559
-
2560
- /**
2561
- * This method is only called if you returned `true` from `finalizeInitialChildren` for this instance.
2562
- *
2563
- * It lets you do some additional work after the node is actually attached to the tree on the screen for the first time. For example, the DOM renderer uses it to trigger focus on nodes with the `autoFocus` attribute.
2564
- *
2565
- * Note that `commitMount` does not mirror `removeChild` one to one because `removeChild` is only called for the top-level removed node. This is why ideally `commitMount` should not mutate any nodes other than the `instance` itself. For example, if it registers some events on some node above, it will be your responsibility to traverse the tree in `removeChild` and clean them up, which is not ideal.
2566
- *
2567
- * The `internalHandle` data structure is meant to be opaque. If you bend the rules and rely on its internal fields, be aware that it may change significantly between versions. You're taking on additional maintenance risk by reading from it, and giving up all guarantees if you write something to it.
2568
- *
2569
- * If you never return `true` from `finalizeInitialChildren`, you can leave it empty.
2570
- */
2571
- commitMount?(instance: Instance, type: Type, props: Props, internalInstanceHandle: OpaqueHandle): void;
2572
-
2573
- /**
2574
- * This method should mutate the instance to match nextProps.
2575
- *
2576
- * The internalHandle data structure is meant to be opaque. If you bend the rules and rely on its internal fields, be aware that it may change significantly between versions. You're taking on additional maintenance risk by reading from it, and giving up all guarantees if you write something to it.
2577
- */
2578
- commitUpdate?(
2579
- instance: Instance,
2580
- type: Type,
2581
- prevProps: Props,
2582
- nextProps: Props,
2583
- internalHandle: OpaqueHandle,
2584
- ): void;
2585
-
2586
- /**
2587
- * This method should make the `instance` invisible without removing it from the tree. For example, it can apply visual styling to hide it. It is used by Suspense to hide the tree while the fallback is visible.
2588
- */
2589
- hideInstance?(instance: Instance): void;
2590
-
2591
- /**
2592
- * Same as `hideInstance`, but for nodes created by `createTextInstance`.
2593
- */
2594
- hideTextInstance?(textInstance: TextInstance): void;
2595
-
2596
- /**
2597
- * This method should make the `instance` visible, undoing what `hideInstance` did.
2598
- */
2599
- unhideInstance?(instance: Instance, props: Props): void;
2600
-
2601
- /**
2602
- * Same as `unhideInstance`, but for nodes created by `createTextInstance`.
2603
- */
2604
- unhideTextInstance?(textInstance: TextInstance, text: string): void;
2605
-
2606
- /**
2607
- * This method should mutate the `container` root node and remove all children from it.
2608
- */
2609
- clearContainer?(container: Container): void;
2610
-
2611
- // -------------------
2612
- // Persistence Methods
2613
- // (optional)
2614
- // If you use the persistent mode instead of the mutation mode, you would still need the "Core Methods". However, instead of the Mutation Methods above you will implement a different set of methods that performs cloning nodes and replacing them at the root level. You can find a list of them in the "Persistence" section [listed in this file](https://github.com/facebook/react/blob/master/packages/react-reconciler/src/forks/ReactFiberConfig.custom.js). File an issue if you need help.
2615
- // -------------------
2616
- cloneInstance?(
2617
- instance: Instance,
2618
- type: Type,
2619
- oldProps: Props,
2620
- newProps: Props,
2621
- keepChildren: boolean,
2622
- recyclableInstance: null | Instance,
2623
- ): Instance;
2624
- createContainerChildSet?(container: Container): ChildSet;
2625
- appendChildToContainerChildSet?(childSet: ChildSet, child: Instance | TextInstance): void;
2626
- finalizeContainerChildren?(container: Container, newChildren: ChildSet): void;
2627
- replaceContainerChildren?(container: Container, newChildren: ChildSet): void;
2628
- cloneHiddenInstance?(
2629
- instance: Instance,
2630
- type: Type,
2631
- props: Props,
2632
- internalInstanceHandle: OpaqueHandle,
2633
- ): Instance;
2634
- cloneHiddenTextInstance?(instance: Instance, text: Type, internalInstanceHandle: OpaqueHandle): TextInstance;
2635
-
2636
- // -------------------
2637
- // Hydration Methods
2638
- // (optional)
2639
- // You can optionally implement hydration to "attach" to the existing tree during the initial render instead of creating it from scratch. For example, the DOM renderer uses this to attach to an HTML markup.
2640
- //
2641
- // To support hydration, you need to declare `supportsHydration: true` and then implement the methods in the "Hydration" section [listed in this file](https://github.com/facebook/react/blob/master/packages/react-reconciler/src/forks/ReactFiberConfig.custom.js). File an issue if you need help.
2642
- // -------------------
2643
- supportsHydration: boolean;
2644
-
2645
- canHydrateInstance?(instance: HydratableInstance, type: Type, props: Props): null | Instance;
2646
-
2647
- canHydrateTextInstance?(instance: HydratableInstance, text: string): null | TextInstance;
2648
-
2649
- canHydrateSuspenseInstance?(instance: HydratableInstance): null | SuspenseInstance;
2650
-
2651
- isSuspenseInstancePending?(instance: SuspenseInstance): boolean;
2652
-
2653
- isSuspenseInstanceFallback?(instance: SuspenseInstance): boolean;
2654
-
2655
- registerSuspenseInstanceRetry?(instance: SuspenseInstance, callback: () => void): void;
2656
-
2657
- getNextHydratableSibling?(instance: HydratableInstance): null | HydratableInstance;
2658
-
2659
- getFirstHydratableChild?(parentInstance: Container | Instance): null | HydratableInstance;
2660
-
2661
- hydrateInstance?(
2662
- instance: Instance,
2663
- type: Type,
2664
- props: Props,
2665
- rootContainerInstance: Container,
2666
- hostContext: HostContext,
2667
- internalInstanceHandle: any,
2668
- ): null | any[];
2669
-
2670
- hydrateTextInstance?(textInstance: TextInstance, text: string, internalInstanceHandle: any): boolean;
2671
-
2672
- hydrateSuspenseInstance?(suspenseInstance: SuspenseInstance, internalInstanceHandle: any): void;
2673
-
2674
- getNextHydratableInstanceAfterSuspenseInstance?(suspenseInstance: SuspenseInstance): null | HydratableInstance;
2675
-
2676
- // Returns the SuspenseInstance if this node is a direct child of a
2677
- // SuspenseInstance. I.e. if its previous sibling is a Comment with
2678
- // SUSPENSE_x_START_DATA. Otherwise, null.
2679
- getParentSuspenseInstance?(targetInstance: any): null | SuspenseInstance;
2680
-
2681
- commitHydratedContainer?(container: Container): void;
2682
-
2683
- commitHydratedSuspenseInstance?(suspenseInstance: SuspenseInstance): void;
2684
-
2685
- didNotMatchHydratedContainerTextInstance?(
2686
- parentContainer: Container,
2687
- textInstance: TextInstance,
2688
- text: string,
2689
- ): void;
2690
-
2691
- didNotMatchHydratedTextInstance?(
2692
- parentType: Type,
2693
- parentProps: Props,
2694
- parentInstance: Instance,
2695
- textInstance: TextInstance,
2696
- text: string,
2697
- ): void;
2698
-
2699
- didNotHydrateContainerInstance?(parentContainer: Container, instance: HydratableInstance): void;
2700
-
2701
- didNotHydrateInstance?(
2702
- parentType: Type,
2703
- parentProps: Props,
2704
- parentInstance: Instance,
2705
- instance: HydratableInstance,
2706
- ): void;
2707
-
2708
- didNotFindHydratableContainerInstance?(parentContainer: Container, type: Type, props: Props): void;
2709
-
2710
- didNotFindHydratableContainerTextInstance?(parentContainer: Container, text: string): void;
2711
-
2712
- didNotFindHydratableContainerSuspenseInstance?(parentContainer: Container): void;
2713
-
2714
- didNotFindHydratableInstance?(
2715
- parentType: Type,
2716
- parentProps: Props,
2717
- parentInstance: Instance,
2718
- type: Type,
2719
- props: Props,
2720
- ): void;
2721
-
2722
- didNotFindHydratableTextInstance?(
2723
- parentType: Type,
2724
- parentProps: Props,
2725
- parentInstance: Instance,
2726
- text: string,
2727
- ): void;
2728
-
2729
- didNotFindHydratableSuspenseInstance?(parentType: Type, parentProps: Props, parentInstance: Instance): void;
2730
-
2731
- errorHydratingContainer?(parentContainer: Container): void;
2732
-
2733
- // Undocumented
2734
- // https://github.com/facebook/react/pull/26722
2735
- NotPendingTransition: TransitionStatus | null;
2736
- HostTransitionContext: ReactContext<TransitionStatus>;
2737
-
2738
- // https://github.com/facebook/react/pull/28751
2739
- setCurrentUpdatePriority(newPriority: EventPriority): void;
2740
- getCurrentUpdatePriority(): EventPriority;
2741
- resolveUpdatePriority(): EventPriority;
2742
-
2743
- // https://github.com/facebook/react/pull/28804
2744
- resetFormInstance(form: FormInstance): void;
2745
-
2746
- // https://github.com/facebook/react/pull/25105
2747
- requestPostPaintCallback(callback: (time: number) => void): void;
2748
-
2749
- // https://github.com/facebook/react/pull/26025
2750
- shouldAttemptEagerTransition(): boolean;
2751
-
2752
- // https://github.com/facebook/react/pull/31528
2753
- trackSchedulerEvent(): void;
2754
-
2755
- // https://github.com/facebook/react/pull/31008
2756
- resolveEventType(): null | string;
2757
- resolveEventTimeStamp(): number;
2758
-
2759
- /**
2760
- * This method is called during render to determine if the Host Component type and props require some kind of loading process to complete before committing an update.
2761
- */
2762
- maySuspendCommit(type: Type, props: Props): boolean;
2763
-
2764
- /**
2765
- * This method may be called during render if the Host Component type and props might suspend a commit. It can be used to initiate any work that might shorten the duration of a suspended commit.
2766
- */
2767
- preloadInstance(type: Type, props: Props): boolean;
2768
-
2769
- /**
2770
- * This method is called just before the commit phase. Use it to set up any necessary state while any Host Components that might suspend this commit are evaluated to determine if the commit must be suspended.
2771
- */
2772
- startSuspendingCommit(): void;
2773
-
2774
- /**
2775
- * This method is called after `startSuspendingCommit` for each Host Component that indicated it might suspend a commit.
2776
- */
2777
- suspendInstance(type: Type, props: Props): void;
2778
-
2779
- /**
2780
- * This method is called after all `suspendInstance` calls are complete.
2781
- *
2782
- * Return `null` if the commit can happen immediately.
2783
- *
2784
- * Return `(initiateCommit: Function) => Function` if the commit must be suspended. The argument to this callback will initiate the commit when called. The return value is a cancellation function that the Reconciler can use to abort the commit.
2785
- */
2786
- waitForCommitToBeReady():
2787
- | ((initiateCommit: (...args: unknown[]) => unknown) => (...args: unknown[]) => unknown)
2788
- | null;
2789
- }
2790
-
2791
- interface Thenable<T> {
2792
- then(resolve: () => T, reject?: () => T): T;
2793
- }
2794
-
2795
- type RootTag = 0 | 1 | 2;
2796
-
2797
- type WorkTag =
2798
- | 0
2799
- | 1
2800
- | 2
2801
- | 3
2802
- | 4
2803
- | 5
2804
- | 6
2805
- | 7
2806
- | 8
2807
- | 9
2808
- | 10
2809
- | 11
2810
- | 12
2811
- | 13
2812
- | 14
2813
- | 15
2814
- | 16
2815
- | 17
2816
- | 18
2817
- | 19
2818
- | 20
2819
- | 21
2820
- | 22
2821
- | 23
2822
- | 24;
2823
-
2824
- type HookType =
2825
- | "useState"
2826
- | "useReducer"
2827
- | "useContext"
2828
- | "useRef"
2829
- | "useEffect"
2830
- | "useLayoutEffect"
2831
- | "useCallback"
2832
- | "useMemo"
2833
- | "useImperativeHandle"
2834
- | "useDebugValue"
2835
- | "useDeferredValue"
2836
- | "useTransition"
2837
- | "useMutableSource"
2838
- | "useOpaqueIdentifier"
2839
- | "useCacheRefresh";
2840
-
2841
- interface Source {
2842
- fileName: string;
2843
- lineNumber: number;
2844
- }
2845
-
2846
- // TODO: Ideally these types would be opaque but that doesn't work well with
2847
- // our reconciler fork infra, since these leak into non-reconciler packages.
2848
- type LanePriority = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17;
2849
-
2850
- type Lanes = number;
2851
- type Lane = number;
2852
-
2853
- type Flags = number;
2854
-
2855
- type TypeOfMode = number;
2856
-
2857
- type EventPriority = number;
2858
-
2859
- interface ReactProvider<T> {
2860
- $$typeof: symbol | number;
2861
- type: ReactProviderType<T>;
2862
- key: null | string;
2863
- ref: null;
2864
- props: {
2865
- value: T;
2866
- children?: ReactNode;
2867
- };
2868
- }
2869
-
2870
- interface ReactProviderType<T> {
2871
- $$typeof: symbol | number;
2872
- _context: ReactContext<T>;
2873
- }
2874
-
2875
- interface ReactConsumer<T> {
2876
- $$typeof: symbol | number;
2877
- type: ReactContext<T>;
2878
- key: null | string;
2879
- ref: null;
2880
- props: {
2881
- children: (value: T) => ReactNode;
2882
- unstable_observedBits?: number;
2883
- };
2884
- }
2885
-
2886
- interface ReactContext<T> {
2887
- $$typeof: symbol | number;
2888
- Consumer: ReactContext<T>;
2889
- Provider: ReactProviderType<T>;
2890
- _currentValue: T;
2891
- _currentValue2: T;
2892
- _threadCount: number;
2893
- // DEV only
2894
- _currentRenderer?: {
2895
- [key: string]: any;
2896
- } | null;
2897
- _currentRenderer2?: {
2898
- [key: string]: any;
2899
- } | null;
2900
- // This value may be added by application code
2901
- // to improve DEV tooling display names
2902
- displayName?: string;
2903
- }
2904
-
2905
- interface ReactPortal {
2906
- $$typeof: symbol | number;
2907
- key: null | string;
2908
- containerInfo: any;
2909
- children: ReactNode;
2910
- // TODO: figure out the API for cross-renderer implementation.
2911
- implementation: any;
2912
- }
2913
-
2914
- interface RefObject {
2915
- current: any;
2916
- }
2917
-
2918
- interface ContextDependency<T> {
2919
- context: ReactContext<T>;
2920
- observedBits: number;
2921
- next: ContextDependency<unknown> | null;
2922
- }
2923
-
2924
- interface Dependencies {
2925
- lanes: Lanes;
2926
- firstContext: ContextDependency<unknown> | null;
2927
- }
2928
-
2929
- interface Fiber {
2930
- // These first fields are conceptually members of an Instance. This used to
2931
- // be split into a separate type and intersected with the other Fiber fields,
2932
- // but until Flow fixes its intersection bugs, we've merged them into a
2933
- // single type.
2934
-
2935
- // An Instance is shared between all versions of a component. We can easily
2936
- // break this out into a separate object to avoid copying so much to the
2937
- // alternate versions of the tree. We put this on a single object for now to
2938
- // minimize the number of objects created during the initial render.
2939
-
2940
- // Tag identifying the type of fiber.
2941
- tag: WorkTag;
2942
-
2943
- // Unique identifier of this child.
2944
- key: null | string;
2945
-
2946
- // The value of element.type which is used to preserve the identity during
2947
- // reconciliation of this child.
2948
- elementType: any;
2949
-
2950
- // The resolved function/class/ associated with this fiber.
2951
- type: any;
2952
-
2953
- // The local state associated with this fiber.
2954
- stateNode: any;
2955
-
2956
- // Conceptual aliases
2957
- // parent : Instance -> return The parent happens to be the same as the
2958
- // return fiber since we've merged the fiber and instance.
2959
-
2960
- // Remaining fields belong to Fiber
2961
-
2962
- // The Fiber to return to after finishing processing this one.
2963
- // This is effectively the parent, but there can be multiple parents (two)
2964
- // so this is only the parent of the thing we're currently processing.
2965
- // It is conceptually the same as the return address of a stack frame.
2966
- return: Fiber | null;
2967
-
2968
- // Singly Linked List Tree Structure.
2969
- child: Fiber | null;
2970
- sibling: Fiber | null;
2971
- index: number;
2972
-
2973
- // The ref last used to attach this node.
2974
- // I'll avoid adding an owner field for prod and model that as functions.
2975
- ref:
2976
- | null
2977
- | (((handle: unknown) => void) & {
2978
- _stringRef?: string | null;
2979
- })
2980
- | RefObject;
2981
-
2982
- // Input is the data coming into process this fiber. Arguments. Props.
2983
- pendingProps: any; // This type will be more specific once we overload the tag.
2984
- memoizedProps: any; // The props used to create the output.
2985
-
2986
- // A queue of state updates and callbacks.
2987
- updateQueue: unknown;
2988
-
2989
- // The state used to create the output
2990
- memoizedState: any;
2991
-
2992
- // Dependencies (contexts, events) for this fiber, if it has any
2993
- dependencies: Dependencies | null;
2994
-
2995
- // Bitfield that describes properties about the fiber and its subtree. E.g.
2996
- // the ConcurrentMode flag indicates whether the subtree should be async-by-
2997
- // default. When a fiber is created, it inherits the mode of its
2998
- // parent. Additional flags can be set at creation time, but after that the
2999
- // value should remain unchanged throughout the fiber's lifetime, particularly
3000
- // before its child fibers are created.
3001
- mode: TypeOfMode;
3002
-
3003
- // Effect
3004
- flags: Flags;
3005
- subtreeFlags: Flags;
3006
- deletions: Fiber[] | null;
3007
-
3008
- // Singly linked list fast path to the next fiber with side-effects.
3009
- nextEffect: Fiber | null;
3010
-
3011
- // The first and last fiber with side-effect within this subtree. This allows
3012
- // us to reuse a slice of the linked list when we reuse the work done within
3013
- // this fiber.
3014
- firstEffect: Fiber | null;
3015
- lastEffect: Fiber | null;
3016
-
3017
- lanes: Lanes;
3018
- childLanes: Lanes;
3019
-
3020
- // This is a pooled version of a Fiber. Every fiber that gets updated will
3021
- // eventually have a pair. There are cases when we can clean up pairs to save
3022
- // memory if we need to.
3023
- alternate: Fiber | null;
3024
-
3025
- // Time spent rendering this Fiber and its descendants for the current update.
3026
- // This tells us how well the tree makes use of sCU for memoization.
3027
- // It is reset to 0 each time we render and only updated when we don't bailout.
3028
- // This field is only set when the enableProfilerTimer flag is enabled.
3029
- actualDuration?: number;
3030
-
3031
- // If the Fiber is currently active in the "render" phase,
3032
- // This marks the time at which the work began.
3033
- // This field is only set when the enableProfilerTimer flag is enabled.
3034
- actualStartTime?: number;
3035
-
3036
- // Duration of the most recent render time for this Fiber.
3037
- // This value is not updated when we bailout for memoization purposes.
3038
- // This field is only set when the enableProfilerTimer flag is enabled.
3039
- selfBaseDuration?: number;
3040
-
3041
- // Sum of base times for all descendants of this Fiber.
3042
- // This value bubbles up during the "complete" phase.
3043
- // This field is only set when the enableProfilerTimer flag is enabled.
3044
- treeBaseDuration?: number;
3045
-
3046
- // Conceptual aliases
3047
- // workInProgress : Fiber -> alternate The alternate used for reuse happens
3048
- // to be the same as work in progress.
3049
- // __DEV__ only
3050
- _debugID?: number;
3051
- _debugSource?: Source | null;
3052
- _debugOwner?: Fiber | null;
3053
- _debugIsCurrentlyTiming?: boolean;
3054
- _debugNeedsRemount?: boolean;
3055
-
3056
- // Used to verify that the order of hooks does not change between renders.
3057
- _debugHookTypes?: HookType[] | null;
3058
- }
3059
-
3060
- type FiberRoot = any;
3061
-
3062
- // Concurrent related struct
3063
- type MutableSource = any;
3064
-
3065
- type OpaqueHandle = any;
3066
- type OpaqueRoot = any;
3067
-
3068
- // 0 is PROD, 1 is DEV.
3069
- // Might add PROFILE later.
3070
- type BundleType = 0 | 1;
3071
-
3072
- interface DevToolsConfig<Instance, TextInstance, RendererInspectionConfig> {
3073
- bundleType: BundleType;
3074
- version: string;
3075
- rendererPackageName: string;
3076
- // Note: this actually *does* depend on Fiber internal fields.
3077
- // Used by "inspect clicked DOM element" in React DevTools.
3078
- findFiberByHostInstance?: (instance: Instance | TextInstance) => Fiber | null;
3079
- rendererConfig?: RendererInspectionConfig;
3080
- }
3081
-
3082
- interface SuspenseHydrationCallbacks<SuspenseInstance> {
3083
- onHydrated?: (suspenseInstance: SuspenseInstance) => void;
3084
- onDeleted?: (suspenseInstance: SuspenseInstance) => void;
3085
- }
3086
-
3087
- interface TransitionTracingCallbacks {
3088
- onTransitionStart?: (transitionName: string, startTime: number) => void;
3089
- onTransitionProgress?: (
3090
- transitionName: string,
3091
- startTime: number,
3092
- currentTime: number,
3093
- pending: Array<{ name: null | string }>,
3094
- ) => void;
3095
- onTransitionIncomplete?: (
3096
- transitionName: string,
3097
- startTime: number,
3098
- deletions: Array<{
3099
- type: string;
3100
- name?: string;
3101
- newName?: string;
3102
- endTime: number;
3103
- }>,
3104
- ) => void;
3105
- onTransitionComplete?: (transitionName: string, startTime: number, endTime: number) => void;
3106
- onMarkerProgress?: (
3107
- transitionName: string,
3108
- marker: string,
3109
- startTime: number,
3110
- currentTime: number,
3111
- pending: Array<{ name: null | string }>,
3112
- ) => void;
3113
- onMarkerIncomplete?: (
3114
- transitionName: string,
3115
- marker: string,
3116
- startTime: number,
3117
- deletions: Array<{
3118
- type: string;
3119
- name?: string;
3120
- newName?: string;
3121
- endTime: number;
3122
- }>,
3123
- ) => void;
3124
- onMarkerComplete?: (transitionName: string, marker: string, startTime: number, endTime: number) => void;
3125
- }
3126
-
3127
- interface ComponentSelector {
3128
- $$typeof: symbol | number;
3129
- value: React$AbstractComponent<never, unknown>;
3130
- }
3131
-
3132
- interface HasPseudoClassSelector {
3133
- $$typeof: symbol | number;
3134
- value: Selector[];
3135
- }
3136
-
3137
- interface RoleSelector {
3138
- $$typeof: symbol | number;
3139
- value: string;
3140
- }
3141
-
3142
- interface TextSelector {
3143
- $$typeof: symbol | number;
3144
- value: string;
3145
- }
3146
-
3147
- interface TestNameSelector {
3148
- $$typeof: symbol | number;
3149
- value: string;
3150
- }
3151
-
3152
- type Selector = ComponentSelector | HasPseudoClassSelector | RoleSelector | TextSelector | TestNameSelector;
3153
-
3154
- // TODO can not find React$AbstractComponent def
3155
- type React$AbstractComponent<Config, Instance = any> = any;
3156
-
3157
- interface BoundingRect {
3158
- x: number;
3159
- y: number;
3160
- width: number;
3161
- height: number;
3162
- }
3163
-
3164
- type IntersectionObserverOptions = any;
3165
-
3166
- interface BaseErrorInfo {
3167
- componentStack?: string;
3168
- }
3169
-
3170
- interface Reconciler<Container, Instance, TextInstance, SuspenseInstance, FormInstance, PublicInstance> {
3171
- createContainer(
3172
- containerInfo: Container,
3173
- tag: RootTag,
3174
- hydrationCallbacks: null | SuspenseHydrationCallbacks<SuspenseInstance>,
3175
- isStrictMode: boolean,
3176
- concurrentUpdatesByDefaultOverride: null | boolean,
3177
- identifierPrefix: string,
3178
- onUncaughtError: (error: Error, info: BaseErrorInfo & { errorBoundary?: Component }) => void,
3179
- onCaughtError: (error: Error, info: BaseErrorInfo) => void,
3180
- onRecoverableError: (error: Error, info: BaseErrorInfo) => void,
3181
- onDefaultTransitionIndicator: () => void,
3182
- transitionCallbacks: null | TransitionTracingCallbacks,
3183
- ): OpaqueRoot;
3184
-
3185
- createPortal(
3186
- children: ReactNode,
3187
- containerInfo: any, // TODO: figure out the API for cross-renderer implementation.
3188
- implementation: any,
3189
- key?: string | null,
3190
- ): ReactPortal;
3191
-
3192
- registerMutableSourceForHydration(root: FiberRoot, mutableSource: MutableSource): void;
3193
-
3194
- createComponentSelector(component: React$AbstractComponent<never, unknown>): ComponentSelector;
3195
-
3196
- createHasPseudoClassSelector(selectors: Selector[]): HasPseudoClassSelector;
3197
-
3198
- createRoleSelector(role: string): RoleSelector;
3199
-
3200
- createTextSelector(text: string): TextSelector;
3201
-
3202
- createTestNameSelector(id: string): TestNameSelector;
3203
-
3204
- getFindAllNodesFailureDescription(hostRoot: Instance, selectors: Selector[]): string | null;
3205
-
3206
- findAllNodes(hostRoot: Instance, selectors: Selector[]): Instance[];
3207
-
3208
- findBoundingRects(hostRoot: Instance, selectors: Selector[]): BoundingRect[];
3209
-
3210
- focusWithin(hostRoot: Instance, selectors: Selector[]): boolean;
3211
-
3212
- observeVisibleRects(
3213
- hostRoot: Instance,
3214
- selectors: Selector[],
3215
- callback: (intersections: Array<{ ratio: number; rect: BoundingRect }>) => void,
3216
- options?: IntersectionObserverOptions,
3217
- ): { disconnect: () => void };
3218
-
3219
- createHydrationContainer(
3220
- initialChildren: ReactNode,
3221
- callback: (() => void) | null | undefined,
3222
- containerInfo: Container,
3223
- tag: RootTag,
3224
- hydrationCallbacks: null | SuspenseHydrationCallbacks<SuspenseInstance>,
3225
- isStrictMode: boolean,
3226
- concurrentUpdatesByDefaultOverride: null | boolean,
3227
- identifierPrefix: string,
3228
- onRecoverableError: (error: Error) => void,
3229
- transitionCallbacks: null | TransitionTracingCallbacks,
3230
- ): OpaqueRoot;
3231
-
3232
- updateContainer(
3233
- element: ReactNode,
3234
- container: OpaqueRoot,
3235
- parentComponent?: Component<any, any> | null,
3236
- callback?: (() => void) | null,
3237
- ): Lane;
3238
-
3239
- batchedUpdates<A, R>(fn: (a: A) => R, a: A): R;
3240
-
3241
- deferredUpdates<A>(fn: () => A): A;
3242
-
3243
- discreteUpdates<A, B, C, D, R>(fn: (arg0: A, arg1: B, arg2: C, arg3: D) => R, a: A, b: B, c: C, d: D): R;
3244
-
3245
- flushControlled(fn: () => any): void;
3246
-
3247
- flushSync(): void;
3248
- flushSync<R>(fn: () => R): R;
3249
-
3250
- isAlreadyRendering(): boolean;
3251
-
3252
- flushPassiveEffects(): boolean;
3253
-
3254
- getPublicRootInstance(container: OpaqueRoot): Component<any, any> | PublicInstance | null;
3255
-
3256
- attemptSynchronousHydration(fiber: Fiber): void;
3257
-
3258
- attemptDiscreteHydration(fiber: Fiber): void;
3259
-
3260
- attemptContinuousHydration(fiber: Fiber): void;
3261
-
3262
- attemptHydrationAtCurrentPriority(fiber: Fiber): void;
3263
-
3264
- getCurrentUpdatePriority(): LanePriority;
3265
-
3266
- runWithPriority<T>(priority: LanePriority, fn: () => T): T;
3267
-
3268
- findHostInstance(component: any): PublicInstance | null;
3269
-
3270
- findHostInstanceWithWarning(component: any, methodName: string): PublicInstance | null;
3271
-
3272
- findHostInstanceWithNoPortals(fiber: Fiber): PublicInstance | null;
3273
-
3274
- shouldError(fiber: Fiber): boolean | undefined;
3275
-
3276
- shouldSuspend(fiber: Fiber): boolean;
3277
-
3278
- injectIntoDevTools(devToolsConfig: DevToolsConfig<Instance, TextInstance, any>): boolean;
3279
- }
3280
- }
3281
-
3282
- declare function extend<T extends ConstructorRepresentation>(objects: T): React$1.ExoticComponent<ThreeElement<T>>;
3283
- declare function extend<T extends Catalogue>(objects: T): void;
3284
- declare function extend(objects: Record<string, unknown>): void;
3285
- declare const reconciler: ReactReconciler.Reconciler<RootStore, Instance<any>, void, Instance<any>, never, any>;
3286
-
3287
- declare const isRenderer: (def: any) => boolean;
3288
- interface OffscreenCanvas extends EventTarget {
3289
- }
3290
- declare const _roots: Map<HTMLCanvasElement | OffscreenCanvas, Root>;
3291
- declare function createRoot<TCanvas extends HTMLCanvasElement | OffscreenCanvas>(canvas: TCanvas): ReconcilerRoot<TCanvas>;
3292
- declare function unmountComponentAtNode<TCanvas extends HTMLCanvasElement | OffscreenCanvas>(canvas: TCanvas, callback?: (canvas: TCanvas) => void): void;
3293
- declare function createPortal(children: ReactNode, container: Object3D | RefObject<Object3D | null> | RefObject<Object3D>, state?: InjectState): JSX.Element;
3294
- interface PortalProps {
3295
- children: ReactNode;
3296
- state?: InjectState;
3297
- container: Object3D | RefObject<Object3D | null> | RefObject<Object3D>;
3298
- }
3299
- declare function Portal({ children, container, state }: PortalProps): JSX.Element;
3300
- /**
3301
- * Force React to flush any updates inside the provided callback synchronously and immediately.
3302
- * All the same caveats documented for react-dom's `flushSync` apply here (see https://react.dev/reference/react-dom/flushSync).
3303
- * Nevertheless, sometimes one needs to render synchronously, for example to keep DOM and 3D changes in lock-step without
3304
- * having to revert to a non-React solution. Note: this will only flush updates within the `Canvas` root.
3305
- */
3306
- declare function flushSync<R>(fn: () => R): R;
3307
-
3308
- declare const context: React$1.Context<RootStore>;
3309
- declare const createStore: (invalidate: (state?: RootState, frames?: number, stackFrames?: boolean) => void, advance: (timestamp: number, runGlobalEffects?: boolean, state?: RootState, frame?: XRFrame) => void) => RootStore;
3310
-
3311
- /**
3312
- * An SSR-friendly useLayoutEffect.
3313
- *
3314
- * React currently throws a warning when using useLayoutEffect on the server.
3315
- * To get around it, we can conditionally useEffect on the server (no-op) and
3316
- * useLayoutEffect elsewhere.
3317
- *
3318
- * @see https://github.com/facebook/react/issues/14927
3319
- */
3320
- declare const useIsomorphicLayoutEffect: typeof React$1.useLayoutEffect;
3321
- /**
3322
- * Creates a stable ref that always contains the latest callback.
3323
- * Useful for avoiding dependency arrays while ensuring the latest closure is called.
3324
- *
3325
- * @param fn - The callback function to wrap
3326
- * @returns A ref containing the current callback
3327
- */
3328
- declare function useMutableCallback<T>(fn: T): React$1.RefObject<T>;
3329
- /**
3330
- * Bridges renderer Context and StrictMode from a primary renderer.
3331
- * Used to maintain React context when rendering into portals or secondary canvases.
3332
- *
3333
- * @returns A Bridge component that wraps children with the parent renderer's context
3334
- */
3335
- declare function useBridge(): Bridge;
3336
- /**
3337
- * Internal component that blocks rendering until a promise resolves.
3338
- * Used for suspense-like blocking behavior.
3339
- *
3340
- * @param set - Function to set the blocking promise
3341
- */
3342
- declare function Block({ set }: Omit<UnblockProps, 'children'>): null;
3343
- /**
3344
- * Error boundary component for catching and handling errors in the React tree.
3345
- * Forwards errors to a state setter for external handling.
3346
- *
3347
- * NOTE: static members get down-level transpiled to mutations which break tree-shaking
3348
- */
3349
- declare const ErrorBoundary: {
3350
- new (props: {
3351
- set: React$1.Dispatch<Error | undefined>;
3352
- children: React$1.ReactNode;
3353
- }): {
3354
- state: {
3355
- error: boolean;
3356
- };
3357
- componentDidCatch(err: Error): void;
3358
- render(): React$1.ReactNode;
3359
- context: unknown;
3360
- setState<K extends "error">(state: {
3361
- error: boolean;
3362
- } | ((prevState: Readonly<{
3363
- error: boolean;
3364
- }>, props: Readonly<{
3365
- set: React$1.Dispatch<Error | undefined>;
3366
- children: React$1.ReactNode;
3367
- }>) => {
3368
- error: boolean;
3369
- } | Pick<{
3370
- error: boolean;
3371
- }, K> | null) | Pick<{
3372
- error: boolean;
3373
- }, K> | null, callback?: (() => void) | undefined): void;
3374
- forceUpdate(callback?: (() => void) | undefined): void;
3375
- readonly props: Readonly<{
3376
- set: React$1.Dispatch<Error | undefined>;
3377
- children: React$1.ReactNode;
3378
- }>;
3379
- componentDidMount?(): void;
3380
- shouldComponentUpdate?(nextProps: Readonly<{
3381
- set: React$1.Dispatch<Error | undefined>;
3382
- children: React$1.ReactNode;
3383
- }>, nextState: Readonly<{
3384
- error: boolean;
3385
- }>, nextContext: any): boolean;
3386
- componentWillUnmount?(): void;
3387
- getSnapshotBeforeUpdate?(prevProps: Readonly<{
3388
- set: React$1.Dispatch<Error | undefined>;
3389
- children: React$1.ReactNode;
3390
- }>, prevState: Readonly<{
3391
- error: boolean;
3392
- }>): any;
3393
- componentDidUpdate?(prevProps: Readonly<{
3394
- set: React$1.Dispatch<Error | undefined>;
3395
- children: React$1.ReactNode;
3396
- }>, prevState: Readonly<{
3397
- error: boolean;
3398
- }>, snapshot?: any): void;
3399
- componentWillMount?(): void;
3400
- UNSAFE_componentWillMount?(): void;
3401
- componentWillReceiveProps?(nextProps: Readonly<{
3402
- set: React$1.Dispatch<Error | undefined>;
3403
- children: React$1.ReactNode;
3404
- }>, nextContext: any): void;
3405
- UNSAFE_componentWillReceiveProps?(nextProps: Readonly<{
3406
- set: React$1.Dispatch<Error | undefined>;
3407
- children: React$1.ReactNode;
3408
- }>, nextContext: any): void;
3409
- componentWillUpdate?(nextProps: Readonly<{
3410
- set: React$1.Dispatch<Error | undefined>;
3411
- children: React$1.ReactNode;
3412
- }>, nextState: Readonly<{
3413
- error: boolean;
3414
- }>, nextContext: any): void;
3415
- UNSAFE_componentWillUpdate?(nextProps: Readonly<{
3416
- set: React$1.Dispatch<Error | undefined>;
3417
- children: React$1.ReactNode;
3418
- }>, nextState: Readonly<{
3419
- error: boolean;
3420
- }>, nextContext: any): void;
3421
- };
3422
- new (props: {
3423
- set: React$1.Dispatch<Error | undefined>;
3424
- children: React$1.ReactNode;
3425
- }, context: any): {
3426
- state: {
3427
- error: boolean;
3428
- };
3429
- componentDidCatch(err: Error): void;
3430
- render(): React$1.ReactNode;
3431
- context: unknown;
3432
- setState<K extends "error">(state: {
3433
- error: boolean;
3434
- } | ((prevState: Readonly<{
3435
- error: boolean;
3436
- }>, props: Readonly<{
3437
- set: React$1.Dispatch<Error | undefined>;
3438
- children: React$1.ReactNode;
3439
- }>) => {
3440
- error: boolean;
3441
- } | Pick<{
3442
- error: boolean;
3443
- }, K> | null) | Pick<{
3444
- error: boolean;
3445
- }, K> | null, callback?: (() => void) | undefined): void;
3446
- forceUpdate(callback?: (() => void) | undefined): void;
3447
- readonly props: Readonly<{
3448
- set: React$1.Dispatch<Error | undefined>;
3449
- children: React$1.ReactNode;
3450
- }>;
3451
- componentDidMount?(): void;
3452
- shouldComponentUpdate?(nextProps: Readonly<{
3453
- set: React$1.Dispatch<Error | undefined>;
3454
- children: React$1.ReactNode;
3455
- }>, nextState: Readonly<{
3456
- error: boolean;
3457
- }>, nextContext: any): boolean;
3458
- componentWillUnmount?(): void;
3459
- getSnapshotBeforeUpdate?(prevProps: Readonly<{
3460
- set: React$1.Dispatch<Error | undefined>;
3461
- children: React$1.ReactNode;
3462
- }>, prevState: Readonly<{
3463
- error: boolean;
3464
- }>): any;
3465
- componentDidUpdate?(prevProps: Readonly<{
3466
- set: React$1.Dispatch<Error | undefined>;
3467
- children: React$1.ReactNode;
3468
- }>, prevState: Readonly<{
3469
- error: boolean;
3470
- }>, snapshot?: any): void;
3471
- componentWillMount?(): void;
3472
- UNSAFE_componentWillMount?(): void;
3473
- componentWillReceiveProps?(nextProps: Readonly<{
3474
- set: React$1.Dispatch<Error | undefined>;
3475
- children: React$1.ReactNode;
3476
- }>, nextContext: any): void;
3477
- UNSAFE_componentWillReceiveProps?(nextProps: Readonly<{
3478
- set: React$1.Dispatch<Error | undefined>;
3479
- children: React$1.ReactNode;
3480
- }>, nextContext: any): void;
3481
- componentWillUpdate?(nextProps: Readonly<{
3482
- set: React$1.Dispatch<Error | undefined>;
3483
- children: React$1.ReactNode;
3484
- }>, nextState: Readonly<{
3485
- error: boolean;
3486
- }>, nextContext: any): void;
3487
- UNSAFE_componentWillUpdate?(nextProps: Readonly<{
3488
- set: React$1.Dispatch<Error | undefined>;
3489
- children: React$1.ReactNode;
3490
- }>, nextState: Readonly<{
3491
- error: boolean;
3492
- }>, nextContext: any): void;
3493
- };
3494
- getDerivedStateFromError: () => {
3495
- error: boolean;
3496
- };
3497
- contextType?: React$1.Context<any> | undefined;
3498
- propTypes?: any;
3499
- };
3500
-
3501
- /**
3502
- * React internal props that should not be passed to Three.js objects.
3503
- */
3504
- declare const REACT_INTERNAL_PROPS: string[];
3505
- /**
3506
- * Returns the instance's initial (outermost) root.
3507
- * Traverses through previousRoot links to find the original root store.
3508
- *
3509
- * @param instance - R3F instance to find root for
3510
- * @returns The outermost root store
3511
- */
3512
- declare function findInitialRoot<T>(instance: Instance<T>): RootStore;
3513
- /**
3514
- * Returns instance root state.
3515
- * If the object doesn't have __r3f (e.g., child meshes in primitives/GLTFs),
3516
- * traverses ancestors to find the nearest managed parent.
3517
- *
3518
- * @param obj - Three.js object to get root state for
3519
- * @returns Root state if found, undefined otherwise
3520
- */
3521
- declare function getRootState<T extends Object3D = Object3D>(obj: T): RootState | undefined;
3522
- /**
3523
- * Collects nodes, materials, and meshes from a Three.js Object3D hierarchy.
3524
- * Handles duplicate material names by appending UUID prefixes.
3525
- *
3526
- * @param object - Root object to traverse
3527
- * @returns ObjectMap containing named nodes, materials, and meshes
3528
- *
3529
- * @example
3530
- * const { nodes, materials, meshes } = buildGraph(gltf.scene)
3531
- * // Access by name: nodes.Head, materials.Metal, meshes.Body
3532
- */
3533
- declare function buildGraph(object: Object3D): ObjectMap;
3534
- /**
3535
- * Disposes an object and all its disposable properties.
3536
- * Skips Scene objects as they should not be disposed automatically.
3537
- *
3538
- * @param obj - Object to dispose
3539
- */
3540
- declare function dispose<T extends Disposable>(obj: T): void;
3541
- /**
3542
- * Extracts instance props from React reconciler fiber props.
3543
- * Filters out React-internal props (children, key, ref).
3544
- *
3545
- * @param queue - Pending props from reconciler fiber
3546
- * @returns Props object without React-internal keys
3547
- */
3548
- declare function getInstanceProps<T = any>(pendingProps: Record<string, unknown>): Instance<T>['props'];
3549
- /**
3550
- * Creates or retrieves an R3F instance descriptor for a Three.js object.
3551
- * Each object in the scene carries a LocalState descriptor (__r3f).
3552
- *
3553
- * @param target - Target object to prepare
3554
- * @param root - Root store for this instance
3555
- * @param type - String identifier for the object type
3556
- * @param props - Initial props for the instance
3557
- * @returns Instance descriptor
3558
- */
3559
- declare function prepare<T = any>(target: T, root: RootStore, type: string, props: Instance<T>['props']): Instance<T>;
3560
- /**
3561
- * Triggers an update for an instance.
3562
- * Invalidates the frame if the root is in demand mode.
3563
- *
3564
- * @param instance - Instance to invalidate
3565
- */
3566
- declare function invalidateInstance(instance: Instance): void;
3567
-
3568
- /**
3569
- * Reserved prop names that should not be applied to Three.js objects.
3570
- */
3571
- declare const RESERVED_PROPS: string[];
3572
- /**
3573
- * Resolves a potentially pierced property key (e.g., 'material-color' → material.color).
3574
- * First tries the entire key as a single property, then attempts piercing.
3575
- *
3576
- * @param root - Root object to resolve from
3577
- * @param key - Property key (may contain dashes for piercing)
3578
- * @returns Object containing root, key, and target value
3579
- *
3580
- * @example
3581
- * resolve(mesh, 'material-color')
3582
- * // => { root: mesh.material, key: 'color', target: mesh.material.color }
3583
- */
3584
- declare function resolve(root: any, key: string): {
3585
- root: any;
3586
- key: string;
3587
- target: any;
3588
- };
3589
- /**
3590
- * Attaches a child instance to a parent instance.
3591
- * Handles both string-based attachment (e.g., 'geometry', 'material-map')
3592
- * and function-based attachment for custom logic.
3593
- *
3594
- * @param parent - Parent instance
3595
- * @param child - Child instance to attach
3596
- *
3597
- * @example
3598
- * // String attachment
3599
- * <bufferGeometry attach="geometry" />
3600
- * // Array attachment
3601
- * <light attach="lights-0" />
3602
- * // Function attachment
3603
- * <thing attach={(parent, self) => { parent.customProp = self }} />
3604
- */
3605
- declare function attach(parent: Instance, child: Instance): void;
3606
- /**
3607
- * Detaches a child instance from a parent instance.
3608
- * Restores the previous value or deletes the property if it was never set.
3609
- *
3610
- * @param parent - Parent instance
3611
- * @param child - Child instance to detach
3612
- */
3613
- declare function detach(parent: Instance, child: Instance): void;
3614
- /**
3615
- * Compares old and new props to determine which properties have changed.
3616
- * Also handles resetting removed props for HMR/fast-refresh.
3617
- *
3618
- * @param instance - Instance to diff props for
3619
- * @param newProps - New props to compare against
3620
- * @returns Object containing only changed props
3621
- *
3622
- * @example
3623
- * const changes = diffProps(instance, { position: [1, 2, 3], color: 'red' })
3624
- * // => { position: [1, 2, 3] } (only if position changed)
3625
- */
3626
- declare function diffProps<T = any>(instance: Instance<T>, newProps: Instance<T>['props']): Instance<T>['props'];
3627
- /**
3628
- * Applies a set of props to a Three.js object.
3629
- * Handles special cases like colors, vectors, textures, events, and pierced props.
3630
- *
3631
- * @param object - Three.js object to apply props to
3632
- * @param props - Props to apply
3633
- * @returns The object with props applied
3634
- *
3635
- * @example
3636
- * applyProps(mesh, { position: [0, 1, 0], 'material-color': 'red' })
3637
- */
3638
- declare function applyProps<T = any>(object: Instance<T>['object'], props: Instance<T>['props']): Instance<T>['object'];
3639
-
3640
- /**
3641
- * Calculates the device pixel ratio for rendering.
3642
- * Handles array DPR ranges [min, max] to clamp devicePixelRatio.
3643
- *
3644
- * @param dpr - Target DPR value or [min, max] range
3645
- * @returns Calculated DPR value
3646
- *
3647
- * @example
3648
- * calculateDpr(2) // => 2
3649
- * calculateDpr([1, 2]) // => clamps window.devicePixelRatio between 1 and 2
3650
- */
3651
- declare function calculateDpr(dpr: Dpr): number;
3652
- /**
3653
- * Extracts the first segment of a UUID string (before the first hyphen).
3654
- * Used for creating unique material names when duplicates exist.
3655
- *
3656
- * @param uuid - UUID string to extract prefix from
3657
- * @returns First segment of the UUID
3658
- *
3659
- * @example
3660
- * getUuidPrefix('a1b2c3d4-e5f6-g7h8-i9j0') // => 'a1b2c3d4'
3661
- */
3662
- declare function getUuidPrefix(uuid: string): string;
3663
- /**
3664
- * Updates camera projection based on viewport size.
3665
- * Adjusts aspect ratio for perspective cameras or bounds for orthographic cameras.
3666
- * Respects camera.manual flag - manual cameras are not modified.
3667
- *
3668
- * @param camera - Camera to update
3669
- * @param size - Current viewport size
3670
- */
3671
- declare function updateCamera(camera: ThreeCamera, size: Size): void;
3672
- /**
3673
- * Updates a frustum from a camera's projection and world matrices.
3674
- * If no target frustum is provided, creates and returns a new one.
3675
- *
3676
- * @param camera - Camera to extract frustum from
3677
- * @param frustum - Optional existing frustum to update (creates new if not provided)
3678
- * @returns The updated or newly created frustum
3679
- *
3680
- * @example
3681
- * // Create new frustum
3682
- * const frustum = updateFrustum(camera)
3683
- *
3684
- * // Update existing frustum (no allocation)
3685
- * updateFrustum(camera, existingFrustum)
3686
- *
3687
- * // Use for visibility checks
3688
- * if (frustum.containsPoint(point)) { ... }
3689
- * if (frustum.intersectsObject(mesh)) { ... }
3690
- */
3691
- declare function updateFrustum(camera: ThreeCamera, frustum?: Frustum): Frustum;
3692
-
3693
- declare const is: {
3694
- obj: (a: any) => boolean;
3695
- fun: (a: any) => a is Function;
3696
- str: (a: any) => a is string;
3697
- num: (a: any) => a is number;
3698
- boo: (a: any) => a is boolean;
3699
- und: (a: any) => boolean;
3700
- nul: (a: any) => boolean;
3701
- arr: (a: any) => a is any[];
3702
- equ(a: any, b: any, { arrays, objects, strict }?: EquConfig): boolean;
3703
- };
3704
- declare const isOrthographicCamera: (def: ThreeCamera) => def is OrthographicCamera;
3705
- declare const isRef: (obj: unknown) => obj is React.RefObject<unknown>;
3706
- declare const isColorRepresentation: (value: unknown) => value is ColorRepresentation$1;
3707
- declare const isObject3D: (object: any) => object is Object3D;
3708
- declare const isTexture: (value: unknown) => value is Texture$1;
3709
- type VectorLike = {
3710
- set: (...args: any[]) => void;
3711
- constructor?: Function;
3712
- };
3713
- declare const isVectorLike: (object: unknown) => object is VectorLike;
3714
- type Copyable = {
3715
- copy: (...args: any[]) => void;
3716
- constructor?: Function;
3717
- };
3718
- declare const isCopyable: (object: unknown) => object is Copyable;
3719
- declare const hasConstructor: (object: unknown) => object is {
3720
- constructor?: Function;
3721
- };
3722
-
3723
- /**
3724
- * Symbol marker for deferred ref resolution.
3725
- * Used to identify values that should be resolved from refs after mount.
3726
- */
3727
- declare const FROM_REF: unique symbol;
3728
- /** The marker `fromRef()` returns; resolved by the reconciler in `commitMount`. */
3729
- interface FromRefMarker<T = unknown, R = T> {
3730
- [FROM_REF]: React$1.RefObject<T | null>;
3731
- /** Optional transform applied to the resolved ref before assignment. */
3732
- transform?: (value: T) => R;
3733
- }
3734
- /**
3735
- * Defers prop application until the referenced object is available.
3736
- * Useful for props like `target` that need sibling refs to be populated.
3737
- *
3738
- * Only top-level props on a three element are resolved: a marker nested inside another value
3739
- * (an array, an options object) is never seen. When the prop needs the sibling *wrapped* rather
3740
- * than assigned as-is, pass a `transform`; it runs once the ref is populated and its result is
3741
- * what gets assigned.
3742
- *
3743
- * @param ref - React ref object to resolve at mount time
3744
- * @param transform - Optional mapping from the resolved object to the value the prop expects
3745
- * @returns A marker value that the reconciler resolves after mount
3746
- *
3747
- * @example
3748
- * const targetRef = useRef<THREE.Object3D>(null)
3749
- *
3750
- * <group ref={targetRef} position={[-3, -2, -15]} />
3751
- * <spotLight target={fromRef(targetRef)} intensity={100} />
3752
- *
3753
- * @example
3754
- * // Wrap the sibling: a node material's lightsNode needs a LightsNode, not the light itself
3755
- * <meshPhongNodeMaterial lightsNode={fromRef(lightRef, (light) => lights([light]))} />
3756
- */
3757
- declare function fromRef<T>(ref: React$1.RefObject<T | null>): T;
3758
- declare function fromRef<T, R>(ref: React$1.RefObject<T | null>, transform: (value: T) => R): R;
3759
- /**
3760
- * Type guard to check if a value is a fromRef marker.
3761
- *
3762
- * @param value - Value to check
3763
- * @returns True if value is a fromRef marker
3764
- */
3765
- declare function isFromRef(value: unknown): value is FromRefMarker<any, unknown>;
3766
-
3767
- /**
3768
- * Symbol marker for mount-only method calls.
3769
- * Used to identify methods that should only be called once on initial mount.
3770
- */
3771
- declare const ONCE: unique symbol;
3772
- /**
3773
- * Marks a method call to be executed only on initial mount.
3774
- * Useful for geometry transforms that should not be reapplied on every render.
3775
- *
3776
- * When `args` prop changes (triggering reconstruction), the method will be
3777
- * called again on the new instance since appliedOnce is not carried over.
3778
- *
3779
- * @param args - Arguments to pass to the method
3780
- * @returns A marker value that applyProps will execute once
3781
- *
3782
- * @example
3783
- * // Rotate geometry on mount
3784
- * <boxGeometry args={[1, 1, 1]} rotateX={once(Math.PI / 2)} />
3785
- *
3786
- * // Multiple arguments
3787
- * <bufferGeometry applyMatrix4={once(matrix)} />
3788
- *
3789
- * // No arguments
3790
- * <geometry center={once()} />
3791
- */
3792
- declare function once<A extends unknown[]>(...args: A): OnceValue<A>;
3793
- /**
3794
- * What `once(...args)` is typed as, so the marker is assignable to the prop it targets:
3795
- * the single argument itself (`rotateX={once(angle)}`), the argument tuple for multi-argument
3796
- * methods (`translate={once(x, y, z)}`), or `true` for a bare call (`center={once()}`).
3797
- *
3798
- * The runtime value is always the marker object; only the declared type follows the prop.
3799
- */
3800
- type OnceValue<A extends unknown[]> = A extends [] ? true : A extends [infer Single] ? Single : A;
3801
- /**
3802
- * Type guard to check if a value is a once marker.
3803
- *
3804
- * @param value - Value to check
3805
- * @returns True if value is a once marker
3806
- */
3807
- declare function isOnce(value: unknown): value is {
3808
- [ONCE]: any[] | true;
3809
- };
3810
-
3811
- /** Distinguishes a resource leaf from a nested resource scope. */
3812
- type ResourceLeafGuard<T> = (value: unknown) => value is T;
3813
-
3814
- /**
3815
- * ScopedStore - Type-safe wrapper for nested stores (uniforms, nodes)
3816
- *
3817
- * Provides TypeScript-friendly access to uniform/node stores where the runtime
3818
- * structure is `Record<string, T | Record<string, T>>` (leaf nodes or nested scopes).
3819
- *
3820
- * The wrapper uses a Proxy to:
3821
- * 1. Return `T` for property access (type assumption: assumes leaf node)
3822
- * 2. Provide `.scope(key)` method for explicit nested access
3823
- * 3. Support iteration methods: has(), keys(), Object.keys(), for...in
3824
- *
3825
- * @example
3826
- * ```tsx
3827
- * useLocalNodes(({ uniforms }) => ({
3828
- * wobble: sin(uniforms.uTime.mul(2)), // No cast needed!
3829
- * playerHealth: uniforms.scope('player').uHealth // Explicit scope access
3830
- * }))
3831
- * ```
3832
- */
3833
-
3834
- /**
3835
- * Type-safe wrapper interface for accessing nested store data.
3836
- * Property access returns `T` (assumes leaf node).
3837
- * Use `.scope(key)` for nested object access.
3838
- *
3839
- */
3840
- type ScopedStoreMethods<TLeaf> = {
3841
- /** Access a nested scope by key. Returns empty wrapper if scope doesn't exist. */
3842
- scope<TScope extends Record<string, TLeaf> = Record<string, TLeaf>>(key: string): ScopedStoreType<TLeaf, TScope>;
3843
- /** Check if a key exists in the store */
3844
- has(key: string): boolean;
3845
- /** Get all keys in the store */
3846
- keys(): string[];
3847
- };
3848
- type ScopedStoreType<TLeaf, TEntries extends Record<string, TLeaf> = Record<string, TLeaf>> = Readonly<TEntries> & ScopedStoreMethods<TLeaf>;
3849
- interface ScopedStoreData<TLeaf> {
3850
- [key: string]: TLeaf | ScopedStoreData<TLeaf>;
11
+ import { JSX } from 'react';
12
+ import 'react-use-measure';
13
+ import 'zustand/traditional';
14
+ import 'three/tsl';
15
+
16
+ /**
17
+ * The `ReactThreeFiber` namespace of the WebGPU entry: the shared element types plus this entry's JSX map.
18
+ *
19
+ * Explicit aliases, not `export type *`: rollup-dts otherwise re-exports the types as namespace values
20
+ * and the built declaration fails to compile for consumers.
21
+ */
22
+
23
+
24
+ type MutableOrReadonlyParameters<T extends (...args: any) => any> = MutableOrReadonlyParameters$1<T>
25
+ type MathRepresentation = MathRepresentation$1
26
+ type VectorRepresentation = VectorRepresentation$1
27
+ type MathTypes = MathTypes$1
28
+ type MathType<T extends MathTypes$1> = MathType$1<T>
29
+ type MathProps<P> = MathProps$1<P>
30
+ type Vector2 = Vector2$1
31
+ type Vector3 = Vector3$1
32
+ type Vector4 = Vector4$1
33
+ type Color = Color$1
34
+ type Layers = Layers$1
35
+ type Quaternion = Quaternion$1
36
+ type Euler = Euler$1
37
+ type Matrix3 = Matrix3$1
38
+ type Matrix4 = Matrix4$1
39
+ type RaycastableRepresentation = RaycastableRepresentation$1
40
+ type EventProps<P> = EventProps$1<P>
41
+ type GeometryTransformProps = GeometryTransformProps$1
42
+ type GeometryProps<P> = GeometryProps$1<P>
43
+ type TSLNodeInput = TSLNodeInput$1
44
+ type NodeProps<P> = NodeProps$1<P>
45
+ type ReactProps<P> = ReactProps$1<P>
46
+ type ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = ElementProps$1<T, P>
47
+ type ThreeElement<T extends ConstructorRepresentation> = ThreeElement$1<T>
48
+ type ThreeToJSXElements<T extends Record<string, any>> = ThreeToJSXElements$1<T>
49
+ type Object3DMethod = Object3DMethod$1
50
+ type ThreeElementsOf<T extends Record<string, any>> = ThreeElementsOf$1<T>
51
+ type ElementOf<E, K extends string> = ElementOf$1<E, K>
52
+
53
+ type webgpu_d_Color = Color;
54
+ type webgpu_d_ElementOf<E, K extends string> = ElementOf<E, K>;
55
+ type webgpu_d_ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = ElementProps<T, P>;
56
+ type webgpu_d_Euler = Euler;
57
+ type webgpu_d_EventProps<P> = EventProps<P>;
58
+ type webgpu_d_GeometryProps<P> = GeometryProps<P>;
59
+ type webgpu_d_GeometryTransformProps = GeometryTransformProps;
60
+ type webgpu_d_Layers = Layers;
61
+ type webgpu_d_MathProps<P> = MathProps<P>;
62
+ type webgpu_d_MathRepresentation = MathRepresentation;
63
+ type webgpu_d_MathType<T extends MathTypes$1> = MathType<T>;
64
+ type webgpu_d_MathTypes = MathTypes;
65
+ type webgpu_d_Matrix3 = Matrix3;
66
+ type webgpu_d_Matrix4 = Matrix4;
67
+ type webgpu_d_MutableOrReadonlyParameters<T extends (...args: any) => any> = MutableOrReadonlyParameters<T>;
68
+ type webgpu_d_NodeProps<P> = NodeProps<P>;
69
+ type webgpu_d_Object3DMethod = Object3DMethod;
70
+ type webgpu_d_Quaternion = Quaternion;
71
+ type webgpu_d_RaycastableRepresentation = RaycastableRepresentation;
72
+ type webgpu_d_ReactProps<P> = ReactProps<P>;
73
+ type webgpu_d_TSLNodeInput = TSLNodeInput;
74
+ type webgpu_d_ThreeElement<T extends ConstructorRepresentation> = ThreeElement<T>;
75
+ type webgpu_d_ThreeElements = ThreeElements;
76
+ type webgpu_d_ThreeElementsOf<T extends Record<string, any>> = ThreeElementsOf<T>;
77
+ type webgpu_d_ThreeExports = ThreeExports;
78
+ type webgpu_d_ThreeToJSXElements<T extends Record<string, any>> = ThreeToJSXElements<T>;
79
+ type webgpu_d_Vector2 = Vector2;
80
+ type webgpu_d_Vector3 = Vector3;
81
+ type webgpu_d_Vector4 = Vector4;
82
+ type webgpu_d_VectorRepresentation = VectorRepresentation;
83
+ declare namespace webgpu_d {
84
+ export type { webgpu_d_Color as Color, webgpu_d_ElementOf as ElementOf, webgpu_d_ElementProps as ElementProps, webgpu_d_Euler as Euler, webgpu_d_EventProps as EventProps, webgpu_d_GeometryProps as GeometryProps, webgpu_d_GeometryTransformProps as GeometryTransformProps, webgpu_d_Layers as Layers, webgpu_d_MathProps as MathProps, webgpu_d_MathRepresentation as MathRepresentation, webgpu_d_MathType as MathType, webgpu_d_MathTypes as MathTypes, webgpu_d_Matrix3 as Matrix3, webgpu_d_Matrix4 as Matrix4, webgpu_d_MutableOrReadonlyParameters as MutableOrReadonlyParameters, webgpu_d_NodeProps as NodeProps, webgpu_d_Object3DMethod as Object3DMethod, webgpu_d_Quaternion as Quaternion, webgpu_d_RaycastableRepresentation as RaycastableRepresentation, webgpu_d_ReactProps as ReactProps, webgpu_d_TSLNodeInput as TSLNodeInput, webgpu_d_ThreeElement as ThreeElement, webgpu_d_ThreeElements as ThreeElements, webgpu_d_ThreeElementsOf as ThreeElementsOf, webgpu_d_ThreeExports as ThreeExports, webgpu_d_ThreeToJSXElements as ThreeToJSXElements, webgpu_d_Vector2 as Vector2, webgpu_d_Vector3 as Vector3, webgpu_d_Vector4 as Vector4, webgpu_d_VectorRepresentation as VectorRepresentation };
3851
85
  }
3852
- /**
3853
- * Create a type-safe ScopedStore wrapper around store data.
3854
- * @param data - The raw store data (uniforms or nodes from RootState)
3855
- * @returns A ScopedStoreType wrapper with type-safe access
3856
- */
3857
- declare function createScopedStore<TLeaf>(data: ScopedStoreData<TLeaf>, isLeaf: ResourceLeafGuard<TLeaf>): ScopedStoreType<TLeaf>;
3858
- /**
3859
- * State type passed to creator functions with ScopedStore wrappers.
3860
- * Provides type-safe access to uniforms, nodes, buffers, and gpuStorage without manual casting.
3861
- */
3862
- type CreatorState = Omit<RootState, 'uniforms' | 'nodes' | 'buffers' | 'gpuStorage'> & {
3863
- /** Type-safe uniform access - property access returns UniformNode */
3864
- uniforms: ScopedStoreType<UniformNode>;
3865
- /** Type-safe node access for real, callable, and legacy structural nodes */
3866
- nodes: ScopedStoreType<NodeLike>;
3867
- /** Type-safe buffer access - property access returns BufferLike (TypedArrays, BufferAttributes, TSL nodes) */
3868
- buffers: ScopedStoreType<BufferLike>;
3869
- /** Type-safe GPU storage access - property access returns StorageLike (StorageTexture, TSL nodes) */
3870
- gpuStorage: ScopedStoreType<StorageLike>;
3871
- };
3872
-
3873
- /** Creator function that returns uniform inputs (can be raw values or UniformNodes) */
3874
- type UniformCreator<T extends UniformInputRecord = UniformInputRecord> = (state: CreatorState) => T;
3875
- /** Function signature for removeUniforms util */
3876
- type RemoveUniformsFn = (names: string | string[], scope?: string) => void;
3877
- /** Function signature for clearUniforms util */
3878
- type ClearUniformsFn = (scope?: string) => void;
3879
- /** Function signature for rebuildUniforms util */
3880
- type RebuildUniformsFn = (scope?: string) => void;
3881
- /** Return type with utils included */
3882
- type UniformsWithUtils<T extends UniformRecord | UniformStore = UniformRecord> = T & {
3883
- removeUniforms: RemoveUniformsFn;
3884
- clearUniforms: ClearUniformsFn;
3885
- rebuildUniforms: RebuildUniformsFn;
3886
- };
3887
- declare function useUniforms<T extends UniformInputRecord>(creator: UniformCreator<T>): UniformsWithUtils<UniformNodesFor<T>>;
3888
- declare function useUniforms<T extends UniformInputRecord>(creator: UniformCreator<T>, scope: string): UniformsWithUtils<UniformNodesFor<T>>;
3889
- declare function useUniforms<T extends UniformInputRecord>(uniforms: T): UniformsWithUtils<UniformNodesFor<T>>;
3890
- declare function useUniforms<T extends UniformInputRecord>(uniforms: T, scope: string): UniformsWithUtils<UniformNodesFor<T>>;
3891
- declare function useUniforms(): UniformsWithUtils<UniformStore>;
3892
- declare function useUniforms(scope: string): UniformsWithUtils;
3893
- declare function useUniforms<T extends UniformInputRecord>(scope?: string): UniformsWithUtils<UniformNodesFor<T>>;
3894
- /**
3895
- * Global rebuildUniforms function for HMR integration.
3896
- * Invalidates cached uniforms and increments _hmrVersion to trigger re-creation.
3897
- * Call this when HMR is detected to refresh all uniform creators.
3898
- *
3899
- * Resolves to the primary store so shared TSL resources rebuild on the
3900
- * authoritative store.
3901
- *
3902
- * @param store - The R3F store (from useStore or context)
3903
- * @param scope - Optional scope to rebuild ('root' for root only, string for specific scope, undefined for all)
3904
- */
3905
- declare function rebuildAllUniforms(store: ReturnType<typeof useStore>, scope?: string): void;
3906
- /**
3907
- * Remove uniforms by name from root level or a scope
3908
- * @deprecated Use `const { removeUniforms } = useUniforms()` instead
3909
- */
3910
- declare function removeUniforms(set: ReturnType<typeof useStore>['setState'], names: string[], scope?: string): void;
3911
- /**
3912
- * Clear all uniforms from a scope (removes the entire scope object)
3913
- * @deprecated Use `const { clearUniforms } = useUniforms()` instead
3914
- */
3915
- declare function clearScope(set: ReturnType<typeof useStore>['setState'], scope: string): void;
3916
- /**
3917
- * Clear all root-level uniforms (preserves scopes)
3918
- * @deprecated Use `const { clearUniforms } = useUniforms()` with `clearUniforms('root')` instead
3919
- */
3920
- declare function clearRootUniforms(set: ReturnType<typeof useStore>['setState']): void;
3921
-
3922
- /**
3923
- * Supported uniform value types:
3924
- * - Raw values: number, boolean, Vector2, Vector3, Vector4, Color, Matrix2, Matrix3, Matrix4
3925
- * - String colors: '#ff0000', 'red', 'rgb(255,0,0)' (auto-converted to Color)
3926
- * - TSL nodes: color(), vec3(), float(), etc. (for type casting)
3927
- * - UniformNode: existing uniforms (reused as-is)
3928
- */
3929
- type UniformValue = number | boolean | string | Vector2$1 | Vector3$1 | Vector4$1 | Color$2 | Matrix2 | Matrix3$1 | Matrix4$1 | Node | UniformNode;
3930
- declare function useUniform<T extends UniformValue = UniformValue>(name: string): UniformNodeFor<T>;
3931
- declare function useUniform<T extends UniformValue>(name: string, value: T): UniformNodeFor<T>;
3932
-
3933
- /**
3934
- * Every node representation a creator may return. The definition lives with the store types as
3935
- * `NodeLike`, so the shape creators return and the shape `state.nodes` holds are one type by
3936
- * construction: three's real `Node`, the callable proxy `Fn()` returns, or the legacy structural
3937
- * `{ uuid, nodeType }` shape.
3938
- */
3939
- type TSLNodeLike = NodeLike;
3940
-
3941
- /** Backward-compatible alias covering every accepted node representation. */
3942
- type TSLNode = TSLNodeLike;
3943
- /**
3944
- * Creator function that returns a record of nodes.
3945
- * Exact creator return inference is preserved within the compatible node constraint.
3946
- */
3947
- type NodeCreator<T extends Record<string, TSLNodeLike>> = (state: CreatorState) => T;
3948
- /** Function signature for removeNodes util */
3949
- type RemoveNodesFn = (names: string | string[], scope?: string) => void;
3950
- /** Function signature for clearNodes util */
3951
- type ClearNodesFn = (scope?: string) => void;
3952
- /** Function signature for rebuildNodes util */
3953
- type RebuildNodesFn = (scope?: string) => void;
3954
- /** Return type with utils included */
3955
- type NodesWithUtils<T extends Record<string, unknown> = NodeRecord> = T & {
3956
- removeNodes: RemoveNodesFn;
3957
- clearNodes: ClearNodesFn;
3958
- rebuildNodes: RebuildNodesFn;
3959
- };
3960
- declare function useNodes(): NodesWithUtils<NodeStore>;
3961
- declare function useNodes(scope: string): NodesWithUtils<NodeRecord>;
3962
- declare function useNodes<T extends NodeRecord>(scope?: string): NodesWithUtils<T>;
3963
- declare function useNodes<T extends NodeRecord>(creator: NodeCreator<T>): NodesWithUtils<T>;
3964
- declare function useNodes<T extends NodeRecord>(creator: NodeCreator<T>, scope: string): NodesWithUtils<T>;
3965
- declare function useNodes(creatorOrScope?: NodeCreator<NodeRecord> | string, scope?: string): NodesWithUtils<Record<string, unknown>>;
3966
- /**
3967
- * Global rebuildNodes function for HMR integration.
3968
- * Invalidates cached nodes and increments _hmrVersion to trigger re-creation.
3969
- * Call this when HMR is detected to refresh all node creators.
3970
- *
3971
- * Resolves to the primary store so shared TSL resources rebuild on the
3972
- * authoritative store.
3973
- *
3974
- * @param store - The R3F store (from useStore or context)
3975
- * @param scope - Optional scope to rebuild ('root' for root only, string for specific scope, undefined for all)
3976
- */
3977
- declare function rebuildAllNodes(store: ReturnType<typeof useStore>, scope?: string): void;
3978
- /**
3979
- * Remove nodes by name from root level or a scope
3980
- * @deprecated Use `const { removeNodes } = useNodes()` instead
3981
- */
3982
- declare function removeNodes(set: ReturnType<typeof useStore>['setState'], names: string[], scope?: string): void;
3983
- /**
3984
- * Clear all nodes from a scope (removes the entire scope object)
3985
- * @deprecated Use `const { clearNodes } = useNodes()` instead
3986
- */
3987
- declare function clearNodeScope(set: ReturnType<typeof useStore>['setState'], scope: string): void;
3988
- /**
3989
- * Clear all root-level nodes (preserves scopes)
3990
- * @deprecated Use `const { clearNodes } = useNodes()` with `clearNodes('root')` instead
3991
- */
3992
- declare function clearRootNodes(set: ReturnType<typeof useStore>['setState']): void;
3993
-
3994
- /** Creator receives CreatorState with ScopedStore wrappers for type-safe access. Returns any record. */
3995
- type LocalNodeCreator<T extends Record<string, unknown>> = (state: CreatorState) => T;
3996
- /**
3997
- * Creates local values that rebuild when uniforms, nodes, or textures change.
3998
- *
3999
- * Unlike `useNodes`, this does NOT register to the global store.
4000
- * Use for component-specific nodes/values that depend on shared resources.
4001
- *
4002
- * @example
4003
- * ```tsx
4004
- * // Destructure what you need from state
4005
- * const { wobble, uTime } = useLocalNodes(({ uniforms, nodes }) => ({
4006
- * wobble: sin(uniforms.uTime.mul(2)),
4007
- * uTime: uniforms.uTime, // can return uniforms too
4008
- * }))
4009
- *
4010
- * // Or access anything else from RootState
4011
- * const { scaled } = useLocalNodes(({ camera, nodes }) => ({
4012
- * scaled: nodes.basePos.mul(camera.zoom),
4013
- * }))
4014
- *
4015
- * // Type-safe uniform access
4016
- * const { colorNode } = useLocalNodes(({ uniforms }) => {
4017
- * const uValue = uniforms.myUniform as UniformNode<number>
4018
- * return { colorNode: mix(colorA, colorB, uValue) }
4019
- * })
4020
- * ```
4021
- */
4022
- declare function useLocalNodes<T extends Record<string, unknown>>(creator: LocalNodeCreator<T>): T;
4023
-
4024
- /**
4025
- * A record of buffer-like values - allows mixed types (TypedArrays, BufferAttributes, TSL nodes)
4026
- */
4027
- type BufferRecordType<T extends BufferLike = BufferLike> = Record<string, T>;
4028
- /**
4029
- * Creator function that returns a record of buffers.
4030
- * Receives CreatorState with access to existing buffers, gpuStorage, uniforms, nodes, etc.
4031
- */
4032
- type BufferCreator<T extends Record<string, BufferLike>> = (state: CreatorState) => T;
4033
- /** Function signature for removeBuffers util */
4034
- type RemoveBuffersFn = (names: string | string[], scope?: string) => void;
4035
- /** Function signature for clearBuffers util */
4036
- type ClearBuffersFn = (scope?: string) => void;
4037
- /** Function signature for rebuildBuffers util */
4038
- type RebuildBuffersFn = (scope?: string) => void;
4039
- /** Function signature for disposeBuffers util - releases GPU resources */
4040
- type DisposeBuffersFn = (names: string | string[], scope?: string) => void;
4041
- /** Return type with utils included */
4042
- type BuffersWithUtils<T extends BufferRecordType | BufferStore = BufferRecordType> = T & {
4043
- removeBuffers: RemoveBuffersFn;
4044
- clearBuffers: ClearBuffersFn;
4045
- rebuildBuffers: RebuildBuffersFn;
4046
- disposeBuffers: DisposeBuffersFn;
4047
- };
4048
- declare function useBuffers(): BuffersWithUtils<BufferStore>;
4049
- declare function useBuffers(scope: string): BuffersWithUtils<Record<string, BufferLike>>;
4050
- declare function useBuffers<T extends Record<string, BufferLike>>(scope?: string): BuffersWithUtils<T>;
4051
- declare function useBuffers<T extends Record<string, BufferLike>>(creator: BufferCreator<T>): BuffersWithUtils<T>;
4052
- declare function useBuffers<T extends Record<string, BufferLike>>(creator: BufferCreator<T>, scope: string): BuffersWithUtils<T>;
4053
- /**
4054
- * Global rebuildBuffers function for HMR integration.
4055
- * Invalidates cached buffers and increments _hmrVersion to trigger re-creation.
4056
- * Call this when HMR is detected to refresh all buffer creators.
4057
- *
4058
- * Resolves to the primary store so shared TSL resources rebuild on the
4059
- * authoritative store.
4060
- *
4061
- * @param store - The R3F store (from useStore or context)
4062
- * @param scope - Optional scope to rebuild ('root' for root only, string for specific scope, undefined for all)
4063
- */
4064
- declare function rebuildAllBuffers(store: ReturnType<typeof useStore>, scope?: string): void;
4065
-
4066
- /**
4067
- * A record of storage-like values - allows mixed types (StorageTexture, Storage3DTexture, TSL nodes)
4068
- */
4069
- type StorageRecordType<T extends StorageLike = StorageLike> = Record<string, T>;
4070
- /**
4071
- * Creator function that returns a record of GPU storage objects.
4072
- * Receives CreatorState with access to existing buffers, gpuStorage, uniforms, nodes, etc.
4073
- */
4074
- type StorageCreator<T extends Record<string, StorageLike>> = (state: CreatorState) => T;
4075
- /** Function signature for removeStorage util */
4076
- type RemoveStorageFn = (names: string | string[], scope?: string) => void;
4077
- /** Function signature for clearStorage util */
4078
- type ClearStorageFn = (scope?: string) => void;
4079
- /** Function signature for rebuildStorage util */
4080
- type RebuildStorageFn = (scope?: string) => void;
4081
- /** Function signature for disposeStorage util - releases GPU resources */
4082
- type DisposeStorageFn = (names: string | string[], scope?: string) => void;
4083
- /** Return type with utils included */
4084
- type StorageWithUtils<T extends StorageRecordType | StorageStore = StorageRecordType> = T & {
4085
- removeStorage: RemoveStorageFn;
4086
- clearStorage: ClearStorageFn;
4087
- rebuildStorage: RebuildStorageFn;
4088
- disposeStorage: DisposeStorageFn;
4089
- };
4090
- declare function useGPUStorage(): StorageWithUtils<StorageStore>;
4091
- declare function useGPUStorage(scope: string): StorageWithUtils<Record<string, StorageLike>>;
4092
- declare function useGPUStorage<T extends Record<string, StorageLike>>(scope?: string): StorageWithUtils<T>;
4093
- declare function useGPUStorage<T extends Record<string, StorageLike>>(creator: StorageCreator<T>): StorageWithUtils<T>;
4094
- declare function useGPUStorage<T extends Record<string, StorageLike>>(creator: StorageCreator<T>, scope: string): StorageWithUtils<T>;
4095
- /**
4096
- * Global rebuildStorage function for HMR integration.
4097
- * Invalidates cached storage and increments _hmrVersion to trigger re-creation.
4098
- * Call this when HMR is detected to refresh all storage creators.
4099
- *
4100
- * Resolves to the primary store so shared TSL resources rebuild on the
4101
- * authoritative store.
4102
- *
4103
- * @param store - The R3F store (from useStore or context)
4104
- * @param scope - Optional scope to rebuild ('root' for root only, string for specific scope, undefined for all)
4105
- */
4106
- declare function rebuildAllStorage(store: ReturnType<typeof useStore>, scope?: string): void;
4107
86
 
4108
87
  /**
4109
88
  * Re-export from core - useTextures is now a core R3F hook (a reactive Texture registry).
@@ -4115,12 +94,12 @@ declare function rebuildAllStorage(store: ReturnType<typeof useStore>, scope?: s
4115
94
  * @deprecated The registry now stores plain `Texture` objects, not TSL nodes. Use `Texture` directly.
4116
95
  * Kept as an alias for backwards compatibility.
4117
96
  */
4118
- type TextureEntry = Texture$1;
97
+ type TextureEntry = Texture;
4119
98
  /**
4120
99
  * @deprecated The registry now stores plain `Texture` objects, not TSL nodes. Use `Texture` directly.
4121
100
  * Kept as an alias for backwards compatibility.
4122
101
  */
4123
- type TextureNode = Texture$1;
102
+ type TextureNode = Texture;
4124
103
 
4125
104
  interface TextureOperations {
4126
105
  add: (key: string, value: any) => void;
@@ -4130,49 +109,6 @@ interface TextureOperations {
4130
109
  }
4131
110
  declare function createTextureOperations(set: StoreApi<RootState>['setState']): TextureOperations;
4132
111
 
4133
- /**
4134
- * Hook for managing WebGPU RenderPipeline with automatic scenePass setup.
4135
- *
4136
- * Features:
4137
- * - Creates RenderPipeline instance if not exists
4138
- * - Creates default scenePass (no MRT) automatically
4139
- * - Callbacks receive full RootState for flexibility
4140
- * - No auto-cleanup on unmount - use reset() for explicit cleanup
4141
- * - Scene/camera changes trigger scenePass recreation
4142
- * - A replaced scenePass is disposed once the new graph is installed, so rebuild() does not
4143
- * strand its render target (and MRT attachments) on the GPU
4144
- * - Any run that changes the output node sets RenderPipeline.needsUpdate, so rebuild() actually
4145
- * recompiles instead of silently keeping the first compiled graph
4146
- *
4147
- * @param mainCB - Main callback to configure outputNode and create effect passes
4148
- * @param setupCB - Optional setup callback to configure MRT on scenePass
4149
- * @returns { passes, renderPipeline, clearPasses, reset, rebuild }
4150
- *
4151
- * @example
4152
- * ```tsx
4153
- * // Simple effect
4154
- * useRenderPipeline(({ renderPipeline, passes }) => {
4155
- * renderPipeline.outputNode = bloom(passes.scenePass.getTextureNode())
4156
- * })
4157
- *
4158
- * // With MRT setup
4159
- * useRenderPipeline(
4160
- * ({ renderPipeline, passes }) => {
4161
- * const beauty = passes.scenePass.getTextureNode().toInspector('Color')
4162
- * const vel = passes.scenePass.getTextureNode('velocity')
4163
- * renderPipeline.outputNode = motionBlur(beauty, vel)
4164
- * },
4165
- * ({ passes }) => {
4166
- * passes.scenePass.setMRT(mrt({ output, velocity }))
4167
- * }
4168
- * )
4169
- *
4170
- * // Read-only access
4171
- * const { renderPipeline, passes } = useRenderPipeline()
4172
- * ```
4173
- */
4174
- declare function useRenderPipeline(mainCB?: RenderPipelineMainCallback, setupCB?: RenderPipelineSetupCallback): UseRenderPipelineReturn;
4175
-
4176
112
  //* Renderer Props ========================================
4177
113
 
4178
114
  type WebGPUDefaultProps = Omit<WebGPURendererParameters, 'canvas'> & BaseRendererProps
@@ -4220,23 +156,23 @@ interface WebGPURootState extends Omit<RootState, 'renderer' | 'gl' | 'internal'
4220
156
  internal: WebGPUInternalState
4221
157
  }
4222
158
 
4223
- /**
4224
- * @fileoverview WebGPU entry point - WebGPU only, no legacy WebGL
4225
- *
4226
- * This entry point is for apps that want to use ONLY WebGPURenderer.
4227
- * Includes WebGPU-specific hooks (useUniforms, useNodes, useTextures).
4228
- * Auto-extends THREE with WebGPU node materials (MeshBasicNodeMaterial, etc.)
4229
- *
4230
- * Usage:
4231
- * import { Canvas, useFrame, useUniforms } from '@react-three/fiber/webgpu'
4232
- */
159
+ declare const R3F_BUILD_LEGACY = false;
160
+ declare const R3F_BUILD_WEBGPU = true;
161
+ /** Create a root that always constructs a WebGPURenderer. */
162
+ declare function createRoot<TCanvas extends HTMLCanvasElement | OffscreenCanvas>(canvas: TCanvas): ReconcilerRoot<TCanvas>;
4233
163
 
4234
164
  /** `useThree` narrowed to WebGPU state — `state.renderer` is a `WebGPURenderer`. */
4235
165
  type UseThreeWebGPU = <T = WebGPURootState>(selector?: (state: WebGPURootState) => T, equalityFn?: <U>(state: U, newState: U) => boolean) => T;
4236
166
  /** `useFrame` narrowed to WebGPU state — the callback's `state.renderer` is a `WebGPURenderer`. */
4237
- type UseFrameWebGPU = (callback?: FrameCallback$1<WebGPURootState>, priorityOrOptions?: number | UseFrameNextOptions) => FrameNextControls;
167
+ type UseFrameWebGPU = (callback?: FrameCallback<WebGPURootState>, priorityOrOptions?: number | UseFrameNextOptions) => FrameNextControls;
4238
168
  declare const useThree: UseThreeWebGPU;
4239
169
  declare const useFrame: UseFrameWebGPU;
170
+ /** `useRenderTarget` narrowed to the target this entry's renderer produces. */
171
+ declare const useRenderTarget: {
172
+ (options?: RenderTargetOptions): RenderTarget;
173
+ (size: number, options?: RenderTargetOptions): RenderTarget;
174
+ (width: number, height: number, options?: RenderTargetOptions): RenderTarget;
175
+ };
4240
176
 
4241
177
  /** Canvas props on the WebGPU entry: `onCreated` receives `WebGPURootState`. */
4242
178
  type WebGPUCanvasProps = Omit<CanvasProps, 'onCreated'> & {
@@ -4244,8 +180,22 @@ type WebGPUCanvasProps = Omit<CanvasProps, 'onCreated'> & {
4244
180
  onCreated?: (state: WebGPURootState) => void;
4245
181
  };
4246
182
 
4247
- /** `Canvas` narrowed to WebGPU state — the same component, `onCreated` typed against `WebGPURootState`. */
183
+ /**
184
+ * A DOM canvas which accepts threejs elements as children, rendered with WebGPU. `onCreated` is
185
+ * typed against `WebGPURootState`.
186
+ * @see https://docs.pmnd.rs/react-three-fiber/api/canvas
187
+ */
4248
188
  declare const Canvas: (props: WebGPUCanvasProps) => JSX.Element;
189
+ /** Three.js constructors available as JSX elements on this entry. */
190
+ type ThreeExports = typeof ThreeWebGPU;
191
+ interface ThreeElements extends ThreeElementsOf$1<ThreeExports> {
192
+ }
193
+ declare module 'react' {
194
+ namespace JSX {
195
+ interface IntrinsicElements extends ThreeElements {
196
+ }
197
+ }
198
+ }
4249
199
 
4250
- export { Block, Canvas, Environment, EnvironmentCube, EnvironmentMap, EnvironmentPortal, ErrorBoundary, FROM_REF, IsObject, ONCE, Portal, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, REACT_INTERNAL_PROPS, RESERVED_PROPS, three_d as ReactThreeFiber, Texture, _roots, addAfterEffect, addEffect, addTail, advance, applyProps, attach, buildGraph, calculateDpr, 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, getUuidPrefix, hasConstructor, hasPrimary, invalidate, invalidateInstance, is, isColorRepresentation, isCopyable, isFromRef, isObject3D, isOnce, isOrthographicCamera, isRef, isRenderer, isTexture, isVectorLike, once, prepare, presetsObj, rebuildAllBuffers, rebuildAllNodes, rebuildAllStorage, rebuildAllUniforms, reconciler, registerPrimary, removeInteractivity, removeNodes, removeUniforms, resolve, swapInteractivity, unmountComponentAtNode, unregisterPrimary, updateCamera, updateFrustum, useBridge, useBuffers, useEnvironment, useFrame, useGPUStorage, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useLocalNodes, useMutableCallback, useNodes, useRenderPipeline, useRenderTarget, useStore, useTexture, useTextures, useThree, useUniform, useUniforms, waitForPrimary };
4251
- export type { Act, Args, ArgsProp, AttachFnType, AttachType, BackgroundConfig, BackgroundProp, BaseRendererProps, Bridge, BufferCreator, BufferLike, BufferRecord, BufferStore, BuffersWithUtils, Camera, CameraProps, WebGPUCanvasProps as CanvasProps, CanvasSchedulerConfig, Catalogue, ClearBuffersFn, ClearNodesFn, ClearStorageFn, ClearUniformsFn, Color, ColorManagementConfig, ComputeFunction, ConstructorRepresentation, CreatorState, DefaultGLProps, DefaultRendererProps, Disposable, DisposeBuffersFn, DisposeOptions, DisposeStorageFn, DomEvent, Dpr, ElementProps, EnvironmentLoaderProps, EnvironmentProps, EquConfig, Euler, EventHandlers, EventManager, EventProps, Events, Extensions, FiberRoot, FilterFunction, FrameCallback, FrameNextCallback, FrameNextState, FrameState, Frameloop, FromRefMarker, 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, NodeLike, NodeProps, NodeRecord, NodeStore, NodesWithUtils, NonFunctionKeys, Object3DMethod, ObjectMap, OffscreenCanvas$1 as OffscreenCanvas, OnceValue, Overwrite, Performance, PointerCaptureTarget, PointerState, PresetsType, PrimaryCanvasEntry, Properties, Quaternion, WebGPUR3FRenderer as R3FRenderer, RaycastableRepresentation, ReactProps, RebuildBuffersFn, RebuildNodesFn, RebuildStorageFn, RebuildUniformsFn, ReconcilerRoot, RemoveBuffersFn, RemoveNodesFn, RemoveStorageFn, RemoveUniformsFn, RenderCallback, RenderProps, RenderTargetOptions, Renderer, RendererConfigExtended, RendererFactory, RendererProps, Root, WebGPURootState as RootState, RootStore, ScopedStoreType, SetBlock, Size, StorageCreator, StorageLike, StorageRecord, StorageStore, StorageWithUtils, Subscription, TSLNode, TSLNodeInput, TSLNodeLike, TextureEntry, TextureInput, TextureNode, TextureOperations, TextureResult, ThreeCamera, ThreeElement, ThreeElements, ThreeElementsImpl, ThreeEvent, ThreeExports, ThreeToJSXElements, UnblockProps, UniformCreator, UniformValue, UniformsWithUtils, UseFrameWebGPU, UseTextureOptions, UseTexturesReturn, UseThreeWebGPU, Vector2, Vector3, Vector4, VectorRepresentation, Viewport, VisibilityEntry, WebGLDefaultProps, WebGLProps, WebGLShadowConfig, WebGPUCanvasProps, WebGPUDefaultProps, WebGPUProps, WebGPUShadowConfig, XRManager, XRPointerConfig };
200
+ export { BaseRendererProps, RootState as BaseRootState, Canvas, Color$1 as Color, ConstructorRepresentation, ElementOf$1 as ElementOf, ElementProps$1 as ElementProps, Euler$1 as Euler, EventProps$1 as EventProps, GeometryProps$1 as GeometryProps, GeometryTransformProps$1 as GeometryTransformProps, Layers$1 as Layers, MathProps$1 as MathProps, MathRepresentation$1 as MathRepresentation, MathType$1 as MathType, MathTypes$1 as MathTypes, Matrix3$1 as Matrix3, Matrix4$1 as Matrix4, MutableOrReadonlyParameters$1 as MutableOrReadonlyParameters, NodeProps$1 as NodeProps, Object3DMethod$1 as Object3DMethod, Properties, Quaternion$1 as Quaternion, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, RaycastableRepresentation$1 as RaycastableRepresentation, ReactProps$1 as ReactProps, webgpu_d as ReactThreeFiber, ReconcilerRoot, RenderTargetOptions, RendererFactory, TSLNodeInput$1 as TSLNodeInput, ThreeElement$1 as ThreeElement, ThreeElementsOf$1 as ThreeElementsOf, ThreeToJSXElements$1 as ThreeToJSXElements, Vector2$1 as Vector2, Vector3$1 as Vector3, Vector4$1 as Vector4, VectorRepresentation$1 as VectorRepresentation, createRoot, createTextureOperations, useFrame, useRenderTarget, useThree };
201
+ export type { WebGPUCanvasProps as CanvasProps, WebGPUInternalState as InternalState, WebGPUR3FRenderer as R3FRenderer, WebGPURootState as RootState, TextureEntry, TextureNode, TextureOperations, ThreeElements, ThreeExports, UseFrameWebGPU, UseThreeWebGPU, WebGPUCanvasProps, WebGPUDefaultProps, WebGPUProps, WebGPUShadowConfig };