@react-three/fiber 10.0.0-canary.eb6c14f → 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 -15366
  11. package/dist/index.d.cts +123 -3875
  12. package/dist/index.d.mts +123 -3875
  13. package/dist/index.d.ts +122 -3846
  14. package/dist/index.mjs +10 -15267
  15. package/dist/legacy.cjs +97 -15321
  16. package/dist/legacy.d.cts +114 -3876
  17. package/dist/legacy.d.mts +114 -3876
  18. package/dist/legacy.d.ts +115 -3851
  19. package/dist/legacy.mjs +14 -15225
  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 -16206
  34. package/dist/webgpu/index.d.cts +112 -4192
  35. package/dist/webgpu/index.d.mts +112 -4192
  36. package/dist/webgpu/index.d.ts +112 -4164
  37. package/dist/webgpu/index.mjs +15 -16090
  38. package/package.json +11 -8
  39. package/readme.md +1 -1
@@ -1,4111 +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
- onUpdate?: (self: T) => void
925
- }
926
-
927
- interface Instance<O = any> {
928
- root: RootStore
929
- type: string
930
- parent: Instance | null
931
- children: Instance[]
932
- props: InstanceProps<O> & Record<string, unknown>
933
- object: O & { __r3f?: Instance<O> }
934
- eventCount: number
935
- handlers: Partial<EventHandlers>
936
- attach?: AttachType<O>
937
- previousAttach?: any
938
- isHidden: boolean
939
- /** Set of props that have been applied via once() */
940
- appliedOnce?: Set<string>
941
- }
942
-
943
- interface HostConfig {
944
- type: string
945
- props: Instance['props']
946
- container: RootStore
947
- instance: Instance
948
- textInstance: void
949
- suspenseInstance: Instance
950
- hydratableInstance: never
951
- formInstance: never
952
- publicInstance: Instance['object']
953
- hostContext: {}
954
- childSet: never
955
- timeoutHandle: number | undefined
956
- noTimeout: -1
957
- TransitionStatus: null
958
- }
959
- declare global {
960
- var IS_REACT_ACT_ENVIRONMENT: boolean | undefined
961
- }
962
-
963
- //* Loop Types ==============================
964
-
965
- type GlobalRenderCallback = (timestamp: number) => void
966
-
967
- type GlobalEffectType = 'before' | 'after' | 'tail'
968
-
969
- declare const presetsObj: {
970
- apartment: string;
971
- city: string;
972
- dawn: string;
973
- forest: string;
974
- lobby: string;
975
- night: string;
976
- park: string;
977
- studio: string;
978
- sunset: string;
979
- warehouse: string;
980
- };
981
- type PresetsType = keyof typeof presetsObj;
982
-
983
- //* Background Types ==============================
984
-
985
- /**
986
- * Expanded object form for background configuration.
987
- * Allows separate textures for background (visual backdrop) and environment (PBR lighting).
988
- */
989
- interface BackgroundConfig {
990
- /** HDRI preset name: 'apartment', 'city', 'dawn', 'forest', 'lobby', 'night', 'park', 'studio', 'sunset', 'warehouse' */
991
- preset?: PresetsType
992
- /** Files for cube texture (6 faces) or single HDR/EXR */
993
- files?: string | string[]
994
- /** Separate files for scene.background (visual backdrop) */
995
- backgroundMap?: string | string[]
996
- backgroundRotation?: Euler$1 | [number, number, number]
997
- backgroundBlurriness?: number
998
- backgroundIntensity?: number
999
- /** Separate files for scene.environment (PBR lighting/reflections) */
1000
- envMap?: string | string[]
1001
- environmentRotation?: Euler$1 | [number, number, number]
1002
- environmentIntensity?: number
1003
- path?: string
1004
- extensions?: (loader: Loader) => void
1005
- }
1006
-
1007
- /**
1008
- * Background prop type for Canvas.
1009
- *
1010
- * String detection priority:
1011
- * 1. Preset - exact match against known presets (apartment, city, dawn, forest, lobby, night, park, studio, sunset, warehouse)
1012
- * 2. URL - starts with /, ./, ../, http://, https://, OR has image extension
1013
- * 3. Color - default fallback (CSS color names, hex values, rgb(), etc.)
1014
- *
1015
- * @example Color
1016
- * ```tsx
1017
- * <Canvas background="red" />
1018
- * <Canvas background="#ff0000" />
1019
- * <Canvas background={0xff0000} />
1020
- * ```
1021
- *
1022
- * @example Preset
1023
- * ```tsx
1024
- * <Canvas background="city" />
1025
- * ```
1026
- *
1027
- * @example URL
1028
- * ```tsx
1029
- * <Canvas background="/path/to/env.hdr" />
1030
- * <Canvas background="./sky.jpg" />
1031
- * ```
1032
- *
1033
- * @example Object form
1034
- * ```tsx
1035
- * <Canvas background={{
1036
- * files: ['px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'],
1037
- * backgroundMap: 'path/to/sky.jpg',
1038
- * envMap: 'path/to/lighting.hdr',
1039
- * backgroundBlurriness: 0.5,
1040
- * }} />
1041
- * ```
1042
- */
1043
- type BackgroundProp =
1044
- | ColorRepresentation // "red", "#ff0000", 0xff0000
1045
- | string // URL or preset
1046
- | BackgroundConfig // Expanded object form
1047
-
1048
- //* Canvas Types ==============================
1049
-
1050
- interface CanvasProps
1051
- extends
1052
- Omit<RenderProps<HTMLCanvasElement>, 'size' | 'primaryCanvas' | 'scheduler'>,
1053
- React$1.HTMLAttributes<HTMLDivElement> {
1054
- children?: React$1.ReactNode
1055
- ref?: React$1.Ref<HTMLCanvasElement>
1056
- /** Canvas fallback content, similar to img's alt prop */
1057
- fallback?: React$1.ReactNode
1058
- /**
1059
- * Options to pass to useMeasure.
1060
- * @see https://github.com/pmndrs/react-use-measure#api
1061
- */
1062
- resize?: Options
1063
- /** The target where events are being subscribed to, default: the div that wraps canvas */
1064
- eventSource?: Element | React$1.RefObject<Element | null>
1065
- /** The event prefix that is cast into canvas pointer x/y events, default: "offset" */
1066
- eventPrefix?: 'offset' | 'client' | 'page' | 'layer' | 'screen'
1067
- /** Enable/disable automatic HMR refresh for TSL nodes and uniforms, default: true in dev */
1068
- hmr?: boolean
1069
- /** Canvas resolution width in pixels. If omitted, uses container width. */
1070
- width?: number
1071
- /** Canvas resolution height in pixels. If omitted, uses container height. */
1072
- height?: number
1073
- /** Force canvas dimensions to even numbers (fixes Safari rendering issues with odd/fractional sizes) */
1074
- forceEven?: boolean
1075
- /**
1076
- * Scene background configuration.
1077
- * Accepts colors, URLs, presets, or an expanded object for separate background/environment.
1078
- * @see BackgroundProp for full documentation and examples
1079
- */
1080
- background?: BackgroundProp
1081
- }
1082
-
1083
- //* Loader Types ==============================
1084
-
1085
- type InputLike = string | string[] | string[][] | Readonly<string | string[] | string[][]>
1086
-
1087
- // Define a loader-like interface that matches THREE.Loader's load signature
1088
- // This works for both generic and non-generic THREE.Loader instances
1089
- interface LoaderLike {
1090
- load(
1091
- url: InputLike,
1092
- onLoad?: (result: any) => void,
1093
- onProgress?: (event: ProgressEvent<EventTarget>) => void,
1094
- onError?: (error: unknown) => void,
1095
- ): any
1096
- }
1097
-
1098
- type GLTFLike = { scene: THREE$1.Object3D }
1099
-
1100
- type LoaderInstance<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
1101
- T extends ConstructorRepresentation<LoaderLike> ? InstanceType<T> : T
1102
-
1103
- // Infer result type from the load method's callback parameter
1104
- type InferLoadResult<T> = T extends {
1105
- load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
1106
- }
1107
- ? R
1108
- : T extends ConstructorRepresentation<any>
1109
- ? InstanceType<T> extends {
1110
- load(url: any, onLoad?: (result: infer R) => void, ...args: any[]): any
1111
- }
1112
- ? R
1113
- : any
1114
- : any
1115
-
1116
- type LoaderResult<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> =
1117
- InferLoadResult<LoaderInstance<T>> extends infer R ? (R extends GLTFLike ? R & ObjectMap : R) : never
1118
-
1119
- type Extensions<T extends LoaderLike | ConstructorRepresentation<LoaderLike>> = (
1120
- loader: LoaderInstance<T>,
1121
- ) => void
1122
-
1123
- //* Renderer Props ========================================
1124
-
1125
- type WebGLDefaultProps = Omit<THREE$1.WebGLRendererParameters, 'canvas'> & BaseRendererProps
1126
-
1127
- type WebGLProps =
1128
- | RendererFactory<THREE$1.WebGLRenderer, WebGLDefaultProps>
1129
- | Partial<Properties<THREE$1.WebGLRenderer> | THREE$1.WebGLRendererParameters>
1130
-
1131
- interface WebGLShadowConfig {
1132
- shadows?: boolean | 'basic' | 'percentage' | 'soft' | 'variance' | Partial<THREE$1.WebGLShadowMap>
1133
- }
1134
-
1135
- //* Legacy-specific Types ========================================
1136
-
1137
- /** Legacy (WebGL) renderer type - re-exported as R3FRenderer from @react-three/fiber/legacy */
1138
- type LegacyRenderer = THREE$1.WebGLRenderer
1139
-
1140
- /** Legacy internal state with narrowed renderer type */
1141
- interface LegacyInternalState extends Omit<InternalState, 'actualRenderer'> {
1142
- actualRenderer: THREE$1.WebGLRenderer
1143
- }
1144
-
1145
- /**
1146
- * Legacy-specific RootState with narrowed renderer type.
1147
- * Automatically used when importing from `@react-three/fiber/legacy`.
1148
- *
1149
- * @example
1150
- * ```tsx
1151
- * import { useThree } from '@react-three/fiber/legacy'
1152
- *
1153
- * function MyComponent() {
1154
- * const { renderer } = useThree()
1155
- * // renderer is typed as THREE.WebGLRenderer
1156
- * renderer.shadowMap.enabled = true
1157
- * }
1158
- * ```
1159
- */
1160
- interface LegacyRootState extends Omit<RootState, 'renderer' | 'internal'> {
1161
- /** The WebGL renderer instance */
1162
- renderer: THREE$1.WebGLRenderer
1163
- /** Internals with WebGL renderer */
1164
- internal: LegacyInternalState
1165
- }
1166
-
1167
- //* RenderTarget Types ==============================
1168
-
1169
-
1170
- type RenderTargetOptions = RenderTargetOptions$1
1171
-
1172
- //* Global TSL Types ==============================
1173
-
1174
- declare global {
1175
- /**
1176
- * Broad callable-node fallback for dynamic store readers.
1177
- * Creator hooks preserve the exact function signatures inferred from Three's `Fn`.
1178
- */
1179
- type CallableTSLNode = ((...params: never[]) => unknown) & {
1180
- readonly shaderNode: unknown
1181
- readonly id: number
1182
- }
1183
-
1184
- /** Legacy structural node accepted when at least one historical marker exists. */
1185
- type LegacyTSLNodeLike = {
1186
- label?: ((label: string) => unknown) | string
1187
- setName?: (name: string) => unknown
1188
- } & ({ uuid: string | undefined; nodeType?: string | null } | { uuid?: string; nodeType: string | null | undefined })
1189
-
1190
- /** Node type accepted by broad dynamic node-store readers. */
1191
- type TSLNodeType = three_webgpu.Node | CallableTSLNode
1192
-
1193
- /**
1194
- * Derive Three's shader node type from an existing node or a supported raw input.
1195
- * Existing InputNode generics take precedence over structural value normalization.
1196
- * Both generics must be inferred because Three's UniformNode intersects an unknown-typed
1197
- * InputNode base with its concrete InputNode specialization.
1198
- */
1199
- type UniformNodeType<T> = T extends three_webgpu.UniformNode<infer TNodeType, infer _TValue>
1200
- ? TNodeType
1201
- : T extends three_webgpu.InputNode<infer TNodeType, infer _TValue>
1202
- ? TNodeType
1203
- : T extends number
1204
- ? 'float'
1205
- : T extends boolean
1206
- ? 'bool'
1207
- : T extends string | three_webgpu.Color | { r: number; g: number; b: number }
1208
- ? 'color'
1209
- : T extends three_webgpu.Vector4 | { x: number; y: number; z: number; w: number }
1210
- ? 'vec4'
1211
- : T extends three_webgpu.Vector3 | { x: number; y: number; z: number }
1212
- ? 'vec3'
1213
- : T extends three_webgpu.Vector2 | { x: number; y: number }
1214
- ? 'vec2'
1215
- : T extends three_webgpu.Matrix4
1216
- ? 'mat4'
1217
- : T extends three_webgpu.Matrix3
1218
- ? 'mat3'
1219
- : T extends three_webgpu.Matrix2
1220
- ? 'mat2'
1221
- : unknown
1222
-
1223
- /** Derive the normalized JavaScript value stored by a uniform node. */
1224
- type UniformNodeValue<T> = T extends three_webgpu.UniformNode<infer _TNodeType, infer TValue>
1225
- ? TValue
1226
- : T extends three_webgpu.InputNode<infer _TNodeType, infer TValue>
1227
- ? TValue
1228
- : T extends string | { r: number; g: number; b: number }
1229
- ? three_webgpu.Color
1230
- : T extends { x: number; y: number; z: number; w: number }
1231
- ? three_webgpu.Vector4
1232
- : T extends { x: number; y: number; z: number }
1233
- ? three_webgpu.Vector3
1234
- : T extends { x: number; y: number }
1235
- ? three_webgpu.Vector2
1236
- : T extends number
1237
- ? number
1238
- : T extends boolean
1239
- ? boolean
1240
- : T
1241
-
1242
- /** Three's exact UniformNode with shader and value generics derived from an input. */
1243
- type UniformNodeFor<T> = three_webgpu.UniformNode<UniformNodeType<T>, UniformNodeValue<T>>
1244
-
1245
- /** Preserve every input key while mapping values to exact Three uniform nodes. */
1246
- type UniformNodesFor<T extends UniformInputRecord> = {
1247
- [K in keyof T]: UniformNodeFor<T[K]>
1248
- }
1249
-
1250
- /** Backward-compatible single-parameter uniform alias. */
1251
- type UniformNode<T = unknown> = UniformNodeFor<T>
1252
-
1253
- /** Flat record of uniform nodes (no nested scopes) */
1254
- type UniformRecord<T extends UniformNode = UniformNode> = Record<string, T>
1255
-
1256
- /**
1257
- * Uniform store that can contain both root-level uniforms and scoped uniform objects
1258
- * Used by state.uniforms which has structure like:
1259
- * { uTime: UniformNode, player: { uHealth: UniformNode }, enemy: { uHealth: UniformNode } }
1260
- */
1261
- type UniformStore = Record<string, UniformNode | UniformRecord>
1262
-
1263
- /**
1264
- * Helper to safely access a uniform node from the store.
1265
- * Use this when accessing state.uniforms to get proper typing.
1266
- * @example
1267
- * const uTime = uniforms.uTime as UniformNode<number>
1268
- * const uColor = uniforms.uColor as UniformNode<import('three/webgpu').Color>
1269
- */
1270
- type GetUniform<T = unknown> = UniformNode<T>
1271
-
1272
- /**
1273
- * Acceptable input values for useUniforms - raw values that get converted to UniformNodes
1274
- * Supports:
1275
- * - Primitives: number, string (color), boolean
1276
- * - Three.js types: Color, Vector2/3/4, Matrix2/3/4
1277
- * - Plain objects: { x, y, z, w } converted to vectors
1278
- * - TSL nodes: color(), vec3(), float() for type casting
1279
- * - UniformNode: existing uniforms (reused as-is)
1280
- */
1281
- type UniformValue =
1282
- | number
1283
- | string
1284
- | boolean
1285
- | three_webgpu.Color
1286
- | three_webgpu.Vector2
1287
- | three_webgpu.Vector3
1288
- | three_webgpu.Vector4
1289
- | three_webgpu.Matrix2
1290
- | three_webgpu.Matrix3
1291
- | three_webgpu.Matrix4
1292
- | { x: number; y: number }
1293
- | { x: number; y: number; z: number }
1294
- | { x: number; y: number; z: number; w: number }
1295
- | { r: number; g: number; b: number; a?: number } // Plain objects converted to Color
1296
- | three_webgpu.Node // TSL nodes like color(), vec3(), float() for type casting
1297
- | UniformNode
1298
-
1299
- /** Input record for useUniforms - accepts raw values or UniformNodes */
1300
- type UniformInputRecord = Record<string, UniformValue>
1301
- }
1302
-
1303
- declare global {
1304
- /**
1305
- * three's own render pipeline type. Named here so the rest of R3F refers to three's shape
1306
- * rather than `any`. three r183 renamed `PostProcessing` to `RenderPipeline`; our peer floor
1307
- * is r185, so the new name is the only one.
1308
- */
1309
- type ThreeRenderPipeline = three_webgpu.RenderPipeline
1310
-
1311
- /**
1312
- * The pass `useRenderPipeline` creates for you: three's own `PassNode`, as returned by
1313
- * `pass(scene, camera)` from `three/tsl`. Referenced from three so members like
1314
- * `getTextureNode`, `setMRT` and `dispose` track the installed version.
1315
- */
1316
- type ScenePassNode = three_webgpu.PassNode
1317
-
1318
- /**
1319
- * Pass record - stores TSL pass nodes for render pipeline.
1320
- *
1321
- * `scenePass` is the only key the library owns. It is optional here because this is also the
1322
- * shape of `state.passes`, which is `{}` before the pipeline exists and again after `reset()`
1323
- * or `clearPasses()`. Inside the callbacks it is always present; see
1324
- * {@link RenderPipelineCallbackState}.
1325
- *
1326
- * Every other key is user-registered, via a callback's return value. Those are TSL nodes of
1327
- * any kind, not only passes: texture reads of an MRT attachment, effect nodes, extra
1328
- * `pass()` instances. `Node` is the common base, so that is the bound. Narrow at the call
1329
- * site when you need a member, e.g. `passes.velocity as TextureNode`.
1330
- *
1331
- * The index signature admits `undefined` because a key may simply not be registered, and
1332
- * because the optional `scenePass` must be assignable to it: under `skipLibCheck: false` an
1333
- * optional property whose type excludes `undefined` from the index signature is an error
1334
- * (TS2411) for every consumer compiling these declarations.
1335
- */
1336
- interface PassRecord {
1337
- scenePass?: ScenePassNode
1338
- [key: string]: three_webgpu.Node | undefined
1339
- }
1340
-
1341
- /**
1342
- * State passed to pipeline callbacks after the active pipeline has been created.
1343
- *
1344
- * `passes.scenePass` is required here: the hook installs the default scene pass before either
1345
- * callback runs, so callbacks can use it without a guard or a cast.
1346
- *
1347
- * `renderer` is narrowed to `WebGPURenderer` and `isLegacy` to `false`: the hook throws under
1348
- * the legacy renderer before either callback can run, so a callback never sees WebGL.
1349
- */
1350
- type RenderPipelineCallbackState = RootState & {
1351
- renderPipeline: ThreeRenderPipeline
1352
- passes: PassRecord & { scenePass: ScenePassNode }
1353
- renderer: three_webgpu.WebGPURenderer
1354
- isLegacy: false
1355
- }
1356
-
1357
- /**
1358
- * What a callback may return to register entries into `state.passes`.
1359
- *
1360
- * `scenePass` is reserved. The hook owns that entry and its lifecycle: it caches the pass it
1361
- * created, and `rebuild()` / `reset()` dispose that cached pass. A callback overwriting the
1362
- * store entry would leave the store pointing at a node the hook never disposes, and the hook
1363
- * disposing a pass nothing references. So returning it is a type error.
1364
- */
1365
- type RegisteredPasses = Record<string, three_webgpu.Node> & { scenePass?: never }
1366
-
1367
- /** Setup callback - runs first to configure MRT, create additional passes */
1368
- type RenderPipelineSetupCallback = (state: RenderPipelineCallbackState) => RegisteredPasses | void
1369
-
1370
- /** Main callback - runs second to configure outputNode, create effect passes */
1371
- type RenderPipelineMainCallback = (state: RenderPipelineCallbackState) => RegisteredPasses | void
1372
-
1373
- /** The imperative half of useRenderPipeline's return value, present in every state */
1374
- interface UseRenderPipelineActions {
1375
- /** Current passes from state */
1376
- passes: PassRecord
1377
- /** Clear all passes from state */
1378
- clearPasses: () => void
1379
- /** Reset RenderPipeline entirely (clears PP + passes) */
1380
- reset: () => void
1381
- /** Re-run setup/main callbacks with current closure values */
1382
- rebuild: () => void
1383
- }
1384
-
1385
- /**
1386
- * Return type for useRenderPipeline hook, discriminated on `isReady`.
1387
- *
1388
- * `if (isReady)` narrows `renderPipeline` to non-null, which is what the docs already tell
1389
- * callers to check. `passes.scenePass` deliberately stays optional in the ready branch:
1390
- * `clearPasses()` empties the record while leaving the pipeline in place.
1391
- */
1392
- type UseRenderPipelineReturn = UseRenderPipelineActions &
1393
- (
1394
- | {
1395
- /** True when RenderPipeline is configured and ready */
1396
- isReady: true
1397
- /** RenderPipeline instance */
1398
- renderPipeline: ThreeRenderPipeline
1399
- }
1400
- | {
1401
- /** False until the pipeline has been created */
1402
- isReady: false
1403
- /** Not initialized yet, or torn down by reset() */
1404
- renderPipeline: null
1405
- }
1406
- )
1407
- }
1408
-
1409
- type MutableOrReadonlyParameters<T extends (...args: any) => any> = Parameters<T> | Readonly<Parameters<T>>
1410
-
1411
- interface MathRepresentation {
1412
- set(...args: number[]): any
1413
- }
1414
- interface VectorRepresentation extends MathRepresentation {
1415
- setScalar(value: number): any
1416
- }
1417
- type MathTypes = MathRepresentation | Euler$2 | Color$2
1418
-
1419
- type MathType<T extends MathTypes> = T extends Color$2
1420
- ? Args<typeof Color$2> | ColorRepresentation$1
1421
- : T extends VectorRepresentation | Layers$1 | Euler$2
1422
- ? T | MutableOrReadonlyParameters<T['set']> | number
1423
- : T | MutableOrReadonlyParameters<T['set']>
1424
-
1425
- type MathProps<P> = {
1426
- [K in keyof P as P[K] extends MathTypes ? K : never]: P[K] extends MathTypes ? MathType<P[K]> : never
1427
- }
1428
-
1429
- type Vector2 = MathType<Vector2$1>
1430
- type Vector3 = MathType<Vector3$1>
1431
- type Vector4 = MathType<Vector4$1>
1432
- type Color = MathType<Color$2>
1433
- type Layers = MathType<Layers$1>
1434
- type Quaternion = MathType<Quaternion$1>
1435
- type Euler = MathType<Euler$2>
1436
- type Matrix3 = MathType<Matrix3$1>
1437
- type Matrix4 = MathType<Matrix4$1>
1438
-
1439
- interface RaycastableRepresentation {
1440
- raycast(raycaster: Raycaster, intersects: Intersection$1[]): void
1441
- }
1442
- type EventProps<P> = P extends RaycastableRepresentation ? Partial<EventHandlers> : {}
1443
-
1444
- /**
1445
- * Props for geometry transform methods that can be called with `once()`.
1446
- * These methods modify the geometry in-place and only make sense to call once on mount.
1447
- *
1448
- * @example
1449
- * import { once } from '@react-three/fiber'
1450
- *
1451
- * <boxGeometry args={[1, 1, 1]} rotateX={once(Math.PI / 2)} />
1452
- * <planeGeometry args={[10, 10]} translate={once(0, 0, 5)} />
1453
- * <bufferGeometry applyMatrix4={once(matrix)} center={once()} />
1454
- */
1455
- interface GeometryTransformProps {
1456
- /** Rotate the geometry about the X axis (radians). Use with once(). */
1457
- rotateX?: number
1458
- /** Rotate the geometry about the Y axis (radians). Use with once(). */
1459
- rotateY?: number
1460
- /** Rotate the geometry about the Z axis (radians). Use with once(). */
1461
- rotateZ?: number
1462
- /** Translate the geometry (x, y, z). Use with once(). */
1463
- translate?: [x: number, y: number, z: number]
1464
- /** Scale the geometry (x, y, z). Use with once(). */
1465
- scale?: [x: number, y: number, z: number]
1466
- /** Center the geometry based on bounding box. Use with once(). */
1467
- center?: true
1468
- /** Apply a Matrix4 transformation. Use with once(). */
1469
- applyMatrix4?: Matrix4$1
1470
- /** Apply a Quaternion rotation. Use with once(). */
1471
- applyQuaternion?: Quaternion$1
1472
- }
1473
-
1474
- type GeometryProps<P> = P extends BufferGeometry ? GeometryTransformProps : {}
1475
-
1476
- /**
1477
- * Workaround for @types/three TSL node type issues.
1478
- * The Node base class has properties that subclasses (OperatorNode, ConstNode, etc.) don't inherit.
1479
- * This transforms `Node | null` properties to accept any object with node-like shape.
1480
- */
1481
- type TSLNodeInput = { nodeType?: string | null; uuid?: string } | null
1482
-
1483
- /**
1484
- * For node material properties (colorNode, positionNode, etc.), accept broader types
1485
- * since @types/three has broken inheritance for TSL node subclasses. NodeClass requires
1486
- * `nodeType`, so this structural key test remains neutral to the selected Three entry.
1487
- */
1488
- type NodeProps<P> = {
1489
- [K in keyof P as NonNullable<P[K]> extends { nodeType: string | null } ? K : never]?: TSLNodeInput
1490
- }
1491
-
1492
- interface ReactProps<P> {
1493
- children?: React.ReactNode
1494
- ref?: React.Ref<P>
1495
- key?: React.Key
1496
- }
1497
-
1498
- type ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = Partial<
1499
- Overwrite<P, MathProps<P> & ReactProps<P> & EventProps<P> & GeometryProps<P> & NodeProps<P>>
1500
- >
1501
-
1502
- type ThreeElement<T extends ConstructorRepresentation> = Mutable<
1503
- Overwrite<ElementProps<T>, Omit<InstanceProps<InstanceType<T>, T>, 'object'>>
1504
- >
1505
-
1506
- type ThreeToJSXElements<T extends Record<string, any>> = {
1507
- [K in keyof T & string as Uncapitalize<K>]: T[K] extends ConstructorRepresentation ? ThreeElement<T[K]> : never
1508
- }
1509
-
1510
- /** Method names of Object3D, excluded from the `primitive` element's typed props. */
1511
- type Object3DMethod = NonNullable<
1512
- {
1513
- [K in keyof Object3D]-?: Object3D[K] extends (...args: any[]) => any ? K : never
1514
- }[keyof Object3D]
1515
- >
1516
-
1517
- type ThreeExports = typeof import('three/webgpu')
1518
- type ThreeElementsImpl = ThreeToJSXElements<ThreeExports>
1519
-
1520
- interface ThreeElements extends Omit<ThreeElementsImpl, 'audio' | 'source' | 'line' | 'path'> {
1521
- /**
1522
- * `primitive` wraps a pre-existing object, so its props cannot be derived from one class.
1523
- * Events are typed from `EventHandlers` (`onClick={(e) => ...}` infers `e`), the ref is
1524
- * untyped, and any other prop is accepted and applied to the object by name. Object3D's own
1525
- * methods are left out of the typed surface: they return `this`, so a subclass element's
1526
- * props (`ThreeElements['group']`) could not be spread onto a primitive otherwise.
1527
- */
1528
- primitive: Omit<ThreeElement<typeof Object3D>, 'args' | 'object' | 'ref' | 'onUpdate' | Object3DMethod> & {
1529
- object: object
1530
- ref?: React.Ref<any>
1531
- onUpdate?: (self: any) => void
1532
- [prop: string]: unknown
1533
- }
1534
- // Conflicts with DOM types can be accessed through a three* prefix
1535
- threeAudio: ThreeElementsImpl['audio']
1536
- threeSource: ThreeElementsImpl['source']
1537
- threeLine: ThreeElementsImpl['line']
1538
- threePath: ThreeElementsImpl['path']
1539
- }
1540
-
1541
- declare module 'react' {
1542
- namespace JSX {
1543
- interface IntrinsicElements extends ThreeElements {}
1544
- }
1545
- }
1546
-
1547
- declare module 'react/jsx-runtime' {
1548
- namespace JSX {
1549
- interface IntrinsicElements extends ThreeElements {}
1550
- }
1551
- }
1552
-
1553
- declare module 'react/jsx-dev-runtime' {
1554
- namespace JSX {
1555
- interface IntrinsicElements extends ThreeElements {}
1556
- }
1557
- }
1558
-
1559
- type three_d_Color = Color;
1560
- type three_d_ElementProps<T extends ConstructorRepresentation, P = InstanceType<T>> = ElementProps<T, P>;
1561
- type three_d_Euler = Euler;
1562
- type three_d_EventProps<P> = EventProps<P>;
1563
- type three_d_GeometryProps<P> = GeometryProps<P>;
1564
- type three_d_GeometryTransformProps = GeometryTransformProps;
1565
- type three_d_Layers = Layers;
1566
- type three_d_MathProps<P> = MathProps<P>;
1567
- type three_d_MathRepresentation = MathRepresentation;
1568
- type three_d_MathType<T extends MathTypes> = MathType<T>;
1569
- type three_d_MathTypes = MathTypes;
1570
- type three_d_Matrix3 = Matrix3;
1571
- type three_d_Matrix4 = Matrix4;
1572
- type three_d_MutableOrReadonlyParameters<T extends (...args: any) => any> = MutableOrReadonlyParameters<T>;
1573
- type three_d_NodeProps<P> = NodeProps<P>;
1574
- type three_d_Object3DMethod = Object3DMethod;
1575
- type three_d_Quaternion = Quaternion;
1576
- type three_d_RaycastableRepresentation = RaycastableRepresentation;
1577
- type three_d_ReactProps<P> = ReactProps<P>;
1578
- type three_d_TSLNodeInput = TSLNodeInput;
1579
- type three_d_ThreeElement<T extends ConstructorRepresentation> = ThreeElement<T>;
1580
- type three_d_ThreeElements = ThreeElements;
1581
- type three_d_ThreeElementsImpl = ThreeElementsImpl;
1582
- type three_d_ThreeExports = ThreeExports;
1583
- type three_d_ThreeToJSXElements<T extends Record<string, any>> = ThreeToJSXElements<T>;
1584
- type three_d_Vector2 = Vector2;
1585
- type three_d_Vector3 = Vector3;
1586
- type three_d_Vector4 = Vector4;
1587
- type three_d_VectorRepresentation = VectorRepresentation;
1588
- declare namespace three_d {
1589
- 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 };
1590
- }
1591
-
1592
- /**
1593
- * @fileoverview Registry for primary canvases that can be targeted by secondary canvases
1594
- *
1595
- * Enables multi-canvas WebGPU rendering where multiple Canvas components share
1596
- * a single WebGPURenderer using Three.js CanvasTarget API.
1597
- *
1598
- * Primary canvas: Has `id` prop, creates its own renderer, registers here
1599
- * Secondary canvas: Has `renderer={{ primaryCanvas: 'id' }}`, shares primary's renderer via CanvasTarget
1600
- */
1601
-
1602
- interface PrimaryCanvasEntry {
1603
- /** The WebGPURenderer instance owned by this primary canvas */
1604
- renderer: WebGPURenderer;
1605
- /** The zustand store for this canvas */
1606
- store: RootStore;
1607
- }
1608
- /**
1609
- * Register a primary canvas that can be targeted by secondary canvases.
1610
- *
1611
- * @param id - Unique identifier for this primary canvas
1612
- * @param renderer - The WebGPURenderer owned by this canvas
1613
- * @param store - The zustand store for this canvas
1614
- * @returns Cleanup function to unregister on unmount
1615
- */
1616
- declare function registerPrimary(id: string, renderer: WebGPURenderer, store: RootStore): () => void;
1617
- /**
1618
- * Get a registered primary canvas by id.
1619
- *
1620
- * @param id - The id of the primary canvas to look up
1621
- * @returns The primary canvas entry or undefined if not found
1622
- */
1623
- declare function getPrimary(id: string): PrimaryCanvasEntry | undefined;
1624
- /**
1625
- * Wait for a primary canvas to be registered.
1626
- * Returns immediately if already registered, otherwise waits.
1627
- *
1628
- * @param id - The id of the primary canvas to wait for
1629
- * @param timeout - Optional timeout in ms (default: 5000)
1630
- * @returns Promise that resolves with the primary canvas entry
1631
- */
1632
- declare function waitForPrimary(id: string, timeout?: number): Promise<PrimaryCanvasEntry>;
1633
- /**
1634
- * Check if a primary canvas with the given id exists.
1635
- *
1636
- * @param id - The id to check
1637
- * @returns True if a primary canvas with this id is registered
1638
- */
1639
- declare function hasPrimary(id: string): boolean;
1640
- /**
1641
- * Unregister a primary canvas. Called on unmount.
1642
- *
1643
- * @param id - The id of the primary canvas to unregister
1644
- */
1645
- declare function unregisterPrimary(id: string): void;
1646
- /**
1647
- * Get all registered primary canvas ids. Useful for debugging.
1648
- */
1649
- declare function getPrimaryIds(): string[];
1650
-
1651
- type EnvironmentLoaderProps = {
1652
- files?: string | string[];
1653
- path?: string;
1654
- preset?: PresetsType;
1655
- extensions?: (loader: Loader$1) => void;
1656
- colorSpace?: ColorSpace;
1657
- };
1658
- /**
1659
- * Loads environment textures for reflections and lighting.
1660
- * Supports HDR files, presets, and cubemaps.
1661
- *
1662
- * @example Basic usage
1663
- * ```jsx
1664
- * const texture = useEnvironment({ preset: 'sunset' })
1665
- * ```
1666
- */
1667
- declare function useEnvironment({ files, path, preset, colorSpace, extensions, }?: Partial<EnvironmentLoaderProps>): Texture$1<unknown, THREE$1.TextureEventMap> | CubeTexture<unknown>;
1668
- declare namespace useEnvironment {
1669
- var preload: (preloadOptions?: EnvironmentLoaderPreloadOptions) => void;
1670
- var clear: (clearOptions?: EnvironmentLoaderClearOptions) => void;
1671
- }
1672
- /**
1673
- * Options accepted by `useEnvironment.preload`.
1674
- *
1675
- * `colorSpace` is deliberately omitted: preload only warms the loader cache, and colorSpace is
1676
- * applied to the texture by `useEnvironment()` at use time, per consumer. Accepting it here would
1677
- * advertise an option this function silently ignores.
1678
- *
1679
- * This previously read `Omit<…, 'encoding'>` — omitting a key that does not exist on
1680
- * `EnvironmentLoaderProps`, a leftover from three's pre-`colorSpace` `encoding` API. That made the
1681
- * type equivalent to the full props, so `colorSpace` was accepted and then dropped on the floor.
1682
- */
1683
- type EnvironmentLoaderPreloadOptions = Omit<EnvironmentLoaderProps, 'colorSpace'>;
1684
- type EnvironmentLoaderClearOptions = Pick<EnvironmentLoaderProps, 'files' | 'preset'>;
1685
-
1686
- /**
1687
- * Props for Environment component that sets up global cubemap for PBR materials and backgrounds.
1688
- *
1689
- * @property children - React children to render into custom environment portal
1690
- * @property frames - Number of frames to render the environment. Use 1 for static, Infinity for animated (default: 1)
1691
- * @property near - Near clipping plane for cube camera (default: 0.1)
1692
- * @property far - Far clipping plane for cube camera (default: 1000)
1693
- * @property resolution - Resolution of the cube render target (default: 256)
1694
- * @property background - Whether to set scene.background. Can be true, false, or "only" (which only sets background) (default: false)
1695
- *
1696
- * @property blur - @deprecated Use backgroundBlurriness instead
1697
- * @property backgroundBlurriness - Blur factor between 0 and 1 for background (default: 0, requires three.js 0.146+)
1698
- * @property backgroundIntensity - Intensity factor for background (default: 1, requires three.js 0.163+)
1699
- * @property backgroundRotation - Rotation for background as Euler angles (default: [0,0,0], requires three.js 0.163+)
1700
- * @property environmentIntensity - Intensity factor for environment lighting (default: 1, requires three.js 0.163+)
1701
- * @property environmentRotation - Rotation for environment as Euler angles (default: [0,0,0], requires three.js 0.163+)
1702
- *
1703
- * @property map - Pre-existing texture to use as environment map
1704
- * @property preset - HDRI Haven preset: 'apartment', 'city', 'dawn', 'forest', 'lobby', 'night', 'park', 'studio', 'sunset', 'warehouse'. Not for production use.
1705
- * @property scene - Custom THREE.Scene or ref to apply environment to (default: uses default scene)
1706
- * @property ground - Ground projection settings. Use true for defaults or object with:
1707
- * - height: Height of camera used to create env map (default: 15)
1708
- * - radius: Radius of the world (default: 60)
1709
- * - scale: Scale of backside projected sphere (default: 1000)
1710
- *
1711
- * Additional loader props:
1712
- * @property files - File path(s) for environment. Supports .hdr, .exr, gainmap .jpg/.webp, or array of 6 cube faces
1713
- * @property path - Base path for file loading
1714
- * @property extensions - Texture extensions override
1715
- */
1716
- type EnvironmentProps = {
1717
- children?: React$1.ReactNode;
1718
- frames?: number;
1719
- near?: number;
1720
- far?: number;
1721
- resolution?: number;
1722
- background?: boolean | 'only';
1723
- /** deprecated, use backgroundBlurriness */
1724
- blur?: number;
1725
- backgroundBlurriness?: number;
1726
- backgroundIntensity?: number;
1727
- backgroundRotation?: Euler;
1728
- environmentIntensity?: number;
1729
- environmentRotation?: Euler;
1730
- map?: Texture$1;
1731
- preset?: PresetsType;
1732
- scene?: Scene | React$1.RefObject<Scene>;
1733
- ground?: boolean | {
1734
- radius?: number;
1735
- height?: number;
1736
- scale?: number;
1737
- };
1738
- /** Solid color for background (alternative to files/preset) */
1739
- color?: ColorRepresentation$1;
1740
- /** Separate files for background (when different from environment files) */
1741
- backgroundFiles?: string | string[];
1742
- } & EnvironmentLoaderProps;
1743
- /**
1744
- * Internal component that applies a pre-existing texture as environment map.
1745
- * Sets scene.environment and optionally scene.background.
1746
- *
1747
- * @example
1748
- * ```jsx
1749
- * <CubeCamera>{(texture) => <EnvironmentMap map={texture} />}</CubeCamera>
1750
- * ```
1751
- */
1752
- declare function EnvironmentMap({ scene, background, map, ...config }: EnvironmentProps): null;
1753
- /**
1754
- * Internal component that loads environment textures from files or presets.
1755
- * Uses HDRLoader for .hdr, EXRLoader for .exr, UltraHDRLoader for .jpg/.jpeg HDR,
1756
- * GainMapLoader for gainmap .webp, or CubeTextureLoader for arrays of images.
1757
- *
1758
- * @example With preset
1759
- * ```jsx
1760
- * <EnvironmentCube preset="sunset" />
1761
- * ```
1762
- *
1763
- * @example From HDR file
1764
- * ```jsx
1765
- * <EnvironmentCube files="environment.hdr" />
1766
- * ```
1767
- *
1768
- * @example From gainmap (smallest footprint)
1769
- * ```jsx
1770
- * <EnvironmentCube files={['file.webp', 'file-gainmap.webp', 'file.json']} />
1771
- * ```
1772
- *
1773
- * @example From cube faces
1774
- * ```jsx
1775
- * <EnvironmentCube files={['px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png']} />
1776
- * ```
1777
- */
1778
- declare function EnvironmentCube({ background, scene, blur, backgroundBlurriness, backgroundIntensity, backgroundRotation, environmentIntensity, environmentRotation, ...rest }: EnvironmentProps): null;
1779
- /**
1780
- * Internal component that renders custom environment using a portal and cube camera.
1781
- * Renders children into an off-buffer and films with a cube camera to create environment map.
1782
- * Can be static (frames=1) or animated (frames=Infinity).
1783
- *
1784
- * @example Custom environment with sphere
1785
- * ```jsx
1786
- * <EnvironmentPortal background near={1} far={1000} resolution={256}>
1787
- * <mesh scale={100}>
1788
- * <sphereGeometry args={[1, 64, 64]} />
1789
- * <meshBasicMaterial map={texture} side={THREE.BackSide} />
1790
- * </mesh>
1791
- * </EnvironmentPortal>
1792
- * ```
1793
- *
1794
- * @example Animated environment
1795
- * ```jsx
1796
- * <EnvironmentPortal frames={Infinity} resolution={256}>
1797
- * <Float>
1798
- * <mesh />
1799
- * </Float>
1800
- * </EnvironmentPortal>
1801
- * ```
1802
- *
1803
- * @example Mixed with preset
1804
- * ```jsx
1805
- * <EnvironmentPortal preset="warehouse">
1806
- * <mesh />
1807
- * </EnvironmentPortal>
1808
- * ```
1809
- */
1810
- 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;
1811
- declare module '@react-three/fiber' {
1812
- interface ThreeElements {
1813
- groundProjectedEnvImpl: ThreeElement<typeof GroundedSkybox>;
1814
- }
1815
- }
1816
- /**
1817
- * Sets up a global environment map for PBR materials and backgrounds.
1818
- * Affects scene.environment and optionally scene.background unless a custom scene is passed.
1819
- *
1820
- * Supports multiple input methods:
1821
- * - **Presets**: Selection of HDRI Haven assets (apartment, city, dawn, forest, lobby, night, park, studio, sunset, warehouse)
1822
- * - **Files**: HDR (.hdr), EXR (.exr), gainmap JPEG (.jpg), gainmap WebP (.webp), or cube faces (array of 6 images)
1823
- * - **Texture**: Pre-existing cube texture via `map` prop
1824
- * - **Custom Scene**: Render children into environment using portal and cube camera
1825
- * - **Ground Projection**: Project environment onto ground plane
1826
- *
1827
- * @remarks
1828
- * - Preset property is NOT meant for production and may fail (relies on CDNs)
1829
- * - Gainmap format has the smallest file footprint
1830
- * - Use `frames={Infinity}` for animated environments with low resolution for performance
1831
- * - Ground projection places models on the "ground" within the environment map
1832
- * - Supports self-hosting with @pmndrs/assets using dynamic imports
1833
- *
1834
- * @example Basic preset usage
1835
- * ```jsx
1836
- * <Environment preset="sunset" />
1837
- * ```
1838
- *
1839
- * @example From HDR file
1840
- * ```jsx
1841
- * <Environment files="/hdr/environment.hdr" />
1842
- * ```
1843
- *
1844
- * @example From gainmap (smallest footprint)
1845
- * ```jsx
1846
- * <Environment files={['file.webp', 'file-gainmap.webp', 'file.json']} />
1847
- * ```
1848
- *
1849
- * @example With self-hosted assets
1850
- * ```jsx
1851
- * import { suspend } from 'suspend-react'
1852
- * const city = import('@pmndrs/assets/hdri/city.exr').then(m => m.default)
1853
- *
1854
- * <Environment files={suspend(city)} />
1855
- * ```
1856
- *
1857
- * @example From existing texture
1858
- * ```jsx
1859
- * <CubeCamera>{(texture) => <Environment map={texture} />}</CubeCamera>
1860
- * ```
1861
- *
1862
- * @example Custom environment scene
1863
- * ```jsx
1864
- * <Environment background near={1} far={1000} resolution={256}>
1865
- * <mesh scale={100}>
1866
- * <sphereGeometry args={[1, 64, 64]} />
1867
- * <meshBasicMaterial map={texture} side={THREE.BackSide} />
1868
- * </mesh>
1869
- * </Environment>
1870
- * ```
1871
- *
1872
- * @example Animated environment
1873
- * ```jsx
1874
- * <Environment frames={Infinity} resolution={256}>
1875
- * <Float>
1876
- * <mesh />
1877
- * </Float>
1878
- * </Environment>
1879
- * ```
1880
- *
1881
- * @example Mixed custom scene with preset
1882
- * ```jsx
1883
- * <Environment background preset="warehouse">
1884
- * <mesh />
1885
- * </Environment>
1886
- * ```
1887
- *
1888
- * @example With ground projection
1889
- * ```jsx
1890
- * <Environment ground={{ height: 15, radius: 60 }} preset="city" />
1891
- * ```
1892
- *
1893
- * @example As background only
1894
- * ```jsx
1895
- * <Environment background="only" preset="sunset" />
1896
- * ```
1897
- *
1898
- * @example With rotation and intensity
1899
- * ```jsx
1900
- * <Environment
1901
- * background
1902
- * backgroundBlurriness={0.5}
1903
- * backgroundIntensity={0.8}
1904
- * backgroundRotation={[0, Math.PI / 2, 0]}
1905
- * environmentIntensity={1.2}
1906
- * environmentRotation={[0, Math.PI / 4, 0]}
1907
- * preset="studio"
1908
- * />
1909
- * ```
1910
- */
1911
- declare function Environment(props: EnvironmentProps): react_jsx_runtime.JSX.Element;
1912
-
1913
- /**
1914
- * Moves every trace of interactivity from one object to its replacement, for reconstruction.
1915
- *
1916
- * When `args` or a `primitive`'s `object` changes, R3F builds a new three object and keeps the same
1917
- * instance. Removing the old object from the interaction state and registering the new one from
1918
- * scratch makes events *work* again (#3778), but it forgets what was in flight: a pointer resting on
1919
- * the object fires a second `onPointerEnter` without ever having left, and an active pointer capture
1920
- * is dropped mid-drag. Rewriting the references instead keeps the interaction continuous across a
1921
- * swap the user never asked to see (#3744).
1922
- *
1923
- * Captures are re-keyed rather than released, so the DOM-level capture on `captureData.target` is
1924
- * left alone — releasing and re-acquiring it is precisely the glitch being avoided.
1925
- *
1926
- * Visibility handlers are deliberately not transferred: that registry is keyed by `object.uuid`, so
1927
- * the replacement re-registers itself through `applyProps`. The old entry is dropped here so it
1928
- * cannot outlive the object it described.
1929
- */
1930
- declare function swapInteractivity(store: RootStore, object: Object3D, newObject: Object3D): void;
1931
- declare function removeInteractivity(store: RootStore, object: Object3D): void;
1932
- declare function createEvents(store: RootStore): {
1933
- handlePointer: (name: string) => (event: DomEvent) => void;
1934
- flushDeferredPointers: () => void;
1935
- processDeferredPointer: (event: DomEvent, pointerId: number) => void;
1936
- };
1937
- /** Default R3F event manager for web */
1938
- declare function createPointerEvents(store: RootStore): EventManager<Element>;
1939
-
1940
- /**
1941
- * Gets or creates a memoized loader instance from a loader constructor or returns the loader if it's already an instance.
1942
- * This allows external code to access loader methods like abort().
1943
- */
1944
- declare function getLoader<L extends LoaderLike | ConstructorRepresentation<LoaderLike>>(Proto: L): L extends ConstructorRepresentation<infer T> ? T : L;
1945
- /**
1946
- * Synchronously loads and caches assets with a three loader.
1947
- *
1948
- * Note: this hook's caller must be wrapped with `React.Suspense`
1949
- * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#useloader
1950
- */
1951
- 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>;
1952
- declare namespace useLoader {
1953
- 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;
1954
- var clear: <I extends InputLike, L extends LoaderLike | ConstructorRepresentation<LoaderLike>>(loader: L, input: I, cacheKey?: InputLike) => void;
1955
- var loader: typeof getLoader;
1956
- }
1957
-
1958
- declare const IsObject: (url: unknown) => url is Record<string, string>;
1959
- type TextureArray<T> = T extends string[] ? Texture$1[] : never;
1960
- type TextureRecord<T> = T extends Record<string, string> ? {
1961
- [key in keyof T]: Texture$1;
1962
- } : never;
1963
- type SingleTexture<T> = T extends string ? Texture$1 : never;
1964
- type MappedTextureType<T extends string[] | string | Record<string, string>> = TextureArray<T> | TextureRecord<T> | SingleTexture<T>;
1965
- /** Options for useTexture hook */
1966
- type UseTextureOptions<Url extends string[] | string | Record<string, string>> = {
1967
- /** Callback when texture(s) finish loading */
1968
- onLoad?: (texture: MappedTextureType<Url>) => void;
1969
- /**
1970
- * Register the texture(s) in R3F's global texture registry for access via useTextures().
1971
- * When true (the default):
1972
- * - Textures persist until explicitly disposed
1973
- * - On mount, returns existing registered textures if available (preserving modifications like colorSpace)
1974
- *
1975
- * Reads are taken once at mount — a mounted `useTexture` does not re-render when the registry
1976
- * changes. To react to registry swaps, use `useTextures(s => s.get(key))` instead.
1977
- *
1978
- * Pass `false` to opt out of registry enrollment entirely.
1979
- * @default true
1980
- */
1981
- cache?: boolean;
1982
- };
1983
- /**
1984
- * Load texture(s) using Three's TextureLoader with Suspense support.
1985
- *
1986
- * @param input - URL string, array of URLs, or object mapping keys to URLs
1987
- * @param optionsOrOnLoad - Options object or legacy onLoad callback
1988
- *
1989
- * @example
1990
- * ```tsx
1991
- * // Single texture
1992
- * const diffuse = useTexture('/textures/diffuse.png')
1993
- *
1994
- * // Multiple textures (array)
1995
- * const [diffuse, normal] = useTexture(['/diffuse.png', '/normal.png'])
1996
- *
1997
- * // Named textures (object)
1998
- * const { diffuse, normal } = useTexture({
1999
- * diffuse: '/diffuse.png',
2000
- * normal: '/normal.png'
2001
- * })
2002
- *
2003
- * // Textures are registered in the global registry by default — the same texture
2004
- * // object is shared across components and modifications (colorSpace, wrapS, etc.) are preserved
2005
- * const diffuse = useTexture('/diffuse.png')
2006
- * diffuse.colorSpace = THREE.SRGBColorSpace
2007
- *
2008
- * // Another component gets the SAME texture with colorSpace already set
2009
- * const sameDiffuse = useTexture('/diffuse.png')
2010
- *
2011
- * // Opt out of registry enrollment for a one-off texture
2012
- * const scratch = useTexture('/scratch.png', { cache: false })
2013
- *
2014
- * // Access the registry directly
2015
- * const { get } = useTextures()
2016
- * const cached = get('/diffuse.png')
2017
- * ```
2018
- */
2019
- declare function useTexture<Url extends string[] | string | Record<string, string>>(input: Url, optionsOrOnLoad?: UseTextureOptions<Url> | ((texture: MappedTextureType<Url>) => void)): MappedTextureType<Url>;
2020
- declare namespace useTexture {
2021
- var preload: (url: string | string[]) => void;
2022
- var clear: (input: string | string[]) => void;
2023
- }
2024
- declare const Texture: ({ children, input, onLoad, cache, }: {
2025
- children?: (texture: ReturnType<typeof useTexture>) => ReactNode;
2026
- input: Parameters<typeof useTexture>[0];
2027
- onLoad?: Parameters<typeof useTexture>[1];
2028
- cache?: boolean;
2029
- }) => react_jsx_runtime.JSX.Element;
2030
-
2031
- /** Accepted shapes for a registry read: a single key, a list of keys, or a name→key map. */
2032
- type TextureInput = string | string[] | Record<string, string>;
2033
- /** Result of a `get()` read, mirroring the input shape. */
2034
- type TextureResult<Input extends TextureInput> = Input extends string ? Texture$1 | undefined : Input extends string[] ? (Texture$1 | undefined)[] : {
2035
- [K in keyof Input]: Texture$1 | undefined;
2036
- };
2037
- /** Options for `dispose()`. */
2038
- interface DisposeOptions {
2039
- /** Dispose even if the texture still has active references (default false). */
2040
- force?: boolean;
2041
- }
2042
- interface UseTexturesReturn {
2043
- /** The live registry Map (key → Texture). Treat as read-only. */
2044
- readonly all: Map<string, Texture$1>;
2045
- /** Read one texture, an array of textures, or a name→texture record (mirrors the input shape). */
2046
- get<Input extends TextureInput>(input: Input): TextureResult<Input>;
2047
- /** Check whether a key exists in the registry. */
2048
- has(key: string): boolean;
2049
- /**
2050
- * Register a texture (or a record of textures) that has no URL — e.g. a render
2051
- * target or procedural texture. URL-loaded textures are registered automatically
2052
- * by `useTexture` (registry enrollment is on by default).
2053
- */
2054
- add(key: string, texture: Texture$1): void;
2055
- add(record: Record<string, Texture$1>): void;
2056
- /**
2057
- * Dispose a texture's GPU resources and remove it from the registry.
2058
- * Refcount-aware: if the key is still in use by a mounted `useTexture` consumer it is
2059
- * skipped (with a warning) unless `{ force: true }` is passed.
2060
- * @returns true if disposed, false if skipped.
2061
- */
2062
- dispose(key: string, options?: DisposeOptions): boolean;
2063
- /** Dispose every texture in the registry and clear it. Use on scene teardown. */
2064
- disposeAll(): void;
2065
- }
2066
- /**
2067
- * Reactive Texture registry — load once with `useTexture`, reach the textures from anywhere.
2068
- *
2069
- * This is a registry of plain `Texture` objects (not TSL nodes), so the same texture can feed
2070
- * a material map, a heightmap sampler, or anything else. It does **not** load — pair it with
2071
- * `useTexture` for loading (registry enrollment is on by default); `useTextures` is for access and lifecycle.
2072
- *
2073
- * The returned handle is **reactive**: the calling component re-renders when the registry
2074
- * changes. Pass a selector to scope the subscription to a single read.
2075
- *
2076
- * @example
2077
- * ```tsx
2078
- * // Load + register once (anywhere in the tree) — registered by default
2079
- * useTexture({ map: '/diffuse.jpg', normalMap: '/normal.jpg' })
2080
- *
2081
- * // Reach them from another component — record form lands straight into a material
2082
- * const { map, normalMap } = useTextures().get({ map: '/diffuse.jpg', normalMap: '/normal.jpg' })
2083
- * return <meshStandardMaterial map={map} normalMap={normalMap} />
2084
- *
2085
- * // A set of heightmaps at once
2086
- * const [a, b, c] = useTextures().get(['/h0.png', '/h1.png', '/h2.png'])
2087
- *
2088
- * // Register a non-URL texture (render target / procedural)
2089
- * useTextures().add('rt-main', renderTarget.texture)
2090
- *
2091
- * // Deliberate GPU cleanup (refcount-aware; force to override)
2092
- * useTextures().dispose('/diffuse.jpg')
2093
- * useTextures().disposeAll() // scene teardown
2094
- * ```
2095
- *
2096
- * @remarks
2097
- * **Future expansion:** an imperative async loader (e.g. `await useTextures().load('/x.jpg')`) is
2098
- * intentionally not included yet. It would let non-React code (loading screens, dynamic streaming)
2099
- * populate the registry without Suspense, at the cost of putting loading back into this hook. It
2100
- * will be added only if a concrete consumer needs imperative loading; for now, loading lives in
2101
- * `useTexture`.
2102
- */
2103
- declare function useTextures(): UseTexturesReturn;
2104
- declare function useTextures<T>(selector: (registry: UseTexturesReturn) => T): T;
2105
-
2106
- /**
2107
- * Creates a render target compatible with the current renderer.
2108
- *
2109
- * - Legacy build: Returns WebGLRenderTarget
2110
- * - WebGPU build: Returns RenderTarget
2111
- * - Default build: Returns whichever matches the active renderer
2112
- *
2113
- * @example
2114
- * ```tsx
2115
- * // Use canvas size
2116
- * const fbo = useRenderTarget()
2117
- *
2118
- * // Use canvas size with options
2119
- * const fbo = useRenderTarget({ samples: 4 })
2120
- *
2121
- * // Square render target
2122
- * const fbo = useRenderTarget(512)
2123
- *
2124
- * // Square render target with options
2125
- * const fbo = useRenderTarget(512, { depthBuffer: true })
2126
- *
2127
- * // Explicit dimensions
2128
- * const fbo = useRenderTarget(512, 256)
2129
- *
2130
- * // Explicit dimensions with options
2131
- * const fbo = useRenderTarget(512, 256, { samples: 4 })
2132
- * ```
2133
- */
2134
- declare function useRenderTarget(options?: RenderTargetOptions): RenderTarget;
2135
- declare function useRenderTarget(size: number, options?: RenderTargetOptions): RenderTarget;
2136
- declare function useRenderTarget(width: number, height: number, options?: RenderTargetOptions): RenderTarget;
2137
-
2138
- /**
2139
- * Returns the R3F Canvas' Zustand store. Useful for [transient updates](https://github.com/pmndrs/zustand#transient-updates-for-often-occurring-state-changes).
2140
- * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#usestore
2141
- */
2142
- declare function useStore(): RootStore;
2143
- /**
2144
- * Exposes an object's {@link Instance}.
2145
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#useInstanceHandle
2146
- *
2147
- * **Note**: this is an escape hatch to react-internal fields. Expect this to change significantly between versions.
2148
- */
2149
- declare function useInstanceHandle<T>(ref: React.RefObject<T>): React.RefObject<Instance<T>>;
2150
- /**
2151
- * Returns a node graph of an object with named nodes & materials.
2152
- * @see https://docs.pmnd.rs/react-three-fiber/api/hooks#usegraph
2153
- */
2154
- declare function useGraph(object: Object3D): ObjectMap;
2155
-
2156
- /**
2157
- * Adds a global render callback which is called each frame BEFORE rendering.
2158
- *
2159
- * @deprecated Use `useFrame(callback, { phase: 'start' })` instead.
2160
- * This function will be removed in a future version.
2161
- *
2162
- * @param callback - Function called each frame with timestamp
2163
- * @returns Unsubscribe function
2164
- *
2165
- * @example
2166
- * // OLD (deprecated)
2167
- * const unsub = addEffect((timestamp) => { ... })
2168
- *
2169
- * // NEW
2170
- * useFrame((state, delta) => { ... }, { phase: 'start' })
2171
- *
2172
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addEffect
2173
- */
2174
- declare function addEffect(callback: GlobalRenderCallback): () => void;
2175
- /**
2176
- * Adds a global after-render callback which is called each frame AFTER rendering.
2177
- *
2178
- * @deprecated Use `useFrame(callback, { phase: 'finish' })` instead.
2179
- * This function will be removed in a future version.
2180
- *
2181
- * @param callback - Function called each frame with timestamp
2182
- * @returns Unsubscribe function
2183
- *
2184
- * @example
2185
- * // OLD (deprecated)
2186
- * const unsub = addAfterEffect((timestamp) => { ... })
2187
- *
2188
- * // NEW
2189
- * useFrame((state, delta) => { ... }, { phase: 'finish' })
2190
- *
2191
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addAfterEffect
2192
- */
2193
- declare function addAfterEffect(callback: GlobalRenderCallback): () => void;
2194
- /**
2195
- * Adds a global callback which is called when rendering stops.
2196
- *
2197
- * @deprecated Use `scheduler.onIdle(callback)` instead.
2198
- * This function will be removed in a future version.
2199
- *
2200
- * @param callback - Function called when rendering stops
2201
- * @returns Unsubscribe function
2202
- *
2203
- * @example
2204
- * // OLD (deprecated)
2205
- * const unsub = addTail((timestamp) => { ... })
2206
- *
2207
- * // NEW
2208
- * const { scheduler } = useFrame()
2209
- * const unsub = scheduler.onIdle((timestamp) => { ... })
2210
- *
2211
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addTail
2212
- */
2213
- declare function addTail(callback: GlobalRenderCallback): () => void;
2214
- /**
2215
- * Invalidates the view, requesting a frame to be rendered.
2216
- * In demand mode, this triggers the scheduler to run frames.
2217
- *
2218
- * With a state argument, only that root's jobs run on the requested frames; other
2219
- * roots on 'demand' stay idle. Without one, every registered root is invalidated.
2220
- *
2221
- * @param state - Optional root state; targets the invalidation at that root
2222
- * @param frames - Number of frames to request (default: 1)
2223
- * @param stackFrames - If false, sets pendingFrames to frames. If true, adds to existing pendingFrames (default: false)
2224
- *
2225
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#invalidate
2226
- */
2227
- declare function invalidate(state?: RootState, frames?: number, stackFrames?: boolean): void;
2228
- /**
2229
- * Advances the frameloop and runs render effects.
2230
- * Useful for when manually rendering via `frameloop="never"`.
2231
- *
2232
- * With a state argument, only that root is stepped. Without one, every
2233
- * registered root is stepped for backwards compatibility.
2234
- *
2235
- * @param timestamp - The timestamp to use for this frame
2236
- * @param runGlobalEffects - Ignored (kept for backwards compat, global effects always run)
2237
- * @param state - Optional root state; targets the manual step at that root
2238
- *
2239
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#advance
2240
- */
2241
- declare function advance(timestamp: number, runGlobalEffects?: boolean, state?: RootState): void;
2242
-
2243
- /* eslint-disable @definitelytyped/no-unnecessary-generics */
2244
- declare function ReactReconciler<
2245
- Type,
2246
- Props,
2247
- Container,
2248
- Instance,
2249
- TextInstance,
2250
- SuspenseInstance,
2251
- HydratableInstance,
2252
- FormInstance,
2253
- PublicInstance,
2254
- HostContext,
2255
- ChildSet,
2256
- TimeoutHandle,
2257
- NoTimeout,
2258
- TransitionStatus,
2259
- >(
2260
- /* eslint-enable @definitelytyped/no-unnecessary-generics */
2261
- config: ReactReconciler.HostConfig<
2262
- Type,
2263
- Props,
2264
- Container,
2265
- Instance,
2266
- TextInstance,
2267
- SuspenseInstance,
2268
- HydratableInstance,
2269
- FormInstance,
2270
- PublicInstance,
2271
- HostContext,
2272
- ChildSet,
2273
- TimeoutHandle,
2274
- NoTimeout,
2275
- TransitionStatus
2276
- >,
2277
- ): ReactReconciler.Reconciler<Container, Instance, TextInstance, SuspenseInstance, FormInstance, PublicInstance>;
2278
-
2279
- declare namespace ReactReconciler {
2280
- interface HostConfig<
2281
- Type,
2282
- Props,
2283
- Container,
2284
- Instance,
2285
- TextInstance,
2286
- SuspenseInstance,
2287
- HydratableInstance,
2288
- FormInstance,
2289
- PublicInstance,
2290
- HostContext,
2291
- ChildSet,
2292
- TimeoutHandle,
2293
- NoTimeout,
2294
- TransitionStatus,
2295
- > {
2296
- // -------------------
2297
- // Modes
2298
- // -------------------
2299
- /**
2300
- * The reconciler has two modes: mutation mode and persistent mode. You must specify one of them.
2301
- *
2302
- * 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.
2303
- *
2304
- * ```js
2305
- * const HostConfig = {
2306
- * // ...
2307
- * supportsMutation: true,
2308
- * // ...
2309
- * }
2310
- * ```
2311
- *
2312
- * Depending on the mode, the reconciler will call different methods on your host config.
2313
- *
2314
- * If you're not sure which one you want, you likely need the mutation mode.
2315
- */
2316
- supportsMutation: boolean;
2317
-
2318
- /**
2319
- * The reconciler has two modes: mutation mode and persistent mode. You must specify one of them.
2320
- *
2321
- * 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".
2322
- *
2323
- * ```js
2324
- * const HostConfig = {
2325
- * // ...
2326
- * supportsPersistence: true,
2327
- * // ...
2328
- * }
2329
- * ```
2330
- *
2331
- * Depending on the mode, the reconciler will call different methods on your host config.
2332
- *
2333
- * If you're not sure which one you want, you likely need the mutation mode.
2334
- */
2335
- supportsPersistence: boolean;
2336
-
2337
- // -------------------
2338
- // Core Methods
2339
- // -------------------
2340
-
2341
- /**
2342
- * 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`.
2343
- *
2344
- * 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.
2345
- *
2346
- * 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.
2347
- *
2348
- * 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.
2349
- *
2350
- * 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.
2351
- */
2352
- createInstance(
2353
- type: Type,
2354
- props: Props,
2355
- rootContainer: Container,
2356
- hostContext: HostContext,
2357
- internalHandle: OpaqueHandle,
2358
- ): Instance;
2359
-
2360
- /**
2361
- * Same as `createInstance`, but for text nodes. If your renderer doesn't support text nodes, you can throw here.
2362
- */
2363
- createTextInstance(
2364
- text: string,
2365
- rootContainer: Container,
2366
- hostContext: HostContext,
2367
- internalHandle: OpaqueHandle,
2368
- ): TextInstance;
2369
-
2370
- /**
2371
- * 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.
2372
- *
2373
- * 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.
2374
- */
2375
- appendInitialChild(parentInstance: Instance, child: Instance | TextInstance): void;
2376
-
2377
- /**
2378
- * 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.
2379
- *
2380
- * 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.
2381
- *
2382
- * 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.
2383
- *
2384
- * If you don't want to do anything here, you should return `false`.
2385
- */
2386
- finalizeInitialChildren(
2387
- instance: Instance,
2388
- type: Type,
2389
- props: Props,
2390
- rootContainer: Container,
2391
- hostContext: HostContext,
2392
- ): boolean;
2393
-
2394
- /**
2395
- * 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.
2396
- *
2397
- * 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.
2398
- *
2399
- * If you don't want to do anything here, you should return `false`.
2400
- *
2401
- * This method happens **in the render phase**. Do not mutate the tree from it.
2402
- */
2403
- shouldSetTextContent(type: Type, props: Props): boolean;
2404
-
2405
- /**
2406
- * This method lets you return the initial host context from the root of the tree. See `getChildHostContext` for the explanation of host context.
2407
- *
2408
- * If you don't intend to use host context, you can return `null`.
2409
- *
2410
- * This method happens **in the render phase**. Do not mutate the tree from it.
2411
- */
2412
- getRootHostContext(rootContainer: Container): HostContext | null;
2413
-
2414
- /**
2415
- * 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.
2416
- *
2417
- * 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.
2418
- *
2419
- * If you don't want to do anything here, return `parentHostContext`.
2420
- *
2421
- * This method happens **in the render phase**. Do not mutate the tree from it.
2422
- */
2423
- getChildHostContext(parentHostContext: HostContext, type: Type, rootContainer: Container): HostContext;
2424
-
2425
- /**
2426
- * 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.
2427
- *
2428
- * If you don't want to do anything here, return `instance`.
2429
- */
2430
- getPublicInstance(instance: Instance | TextInstance): PublicInstance;
2431
-
2432
- /**
2433
- * 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`.
2434
- *
2435
- * Even if you don't want to do anything here, you need to return `null` from it.
2436
- */
2437
- prepareForCommit(containerInfo: Container): Record<string, any> | null;
2438
-
2439
- /**
2440
- * 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.
2441
- *
2442
- * You can leave it empty.
2443
- */
2444
- resetAfterCommit(containerInfo: Container): void;
2445
-
2446
- /**
2447
- * This method is called for a container that's used as a portal target. Usually you can leave it empty.
2448
- */
2449
- preparePortalMount(containerInfo: Container): void;
2450
-
2451
- /**
2452
- * You can proxy this to `setTimeout` or its equivalent in your environment.
2453
- */
2454
- scheduleTimeout(fn: (...args: unknown[]) => unknown, delay?: number): TimeoutHandle;
2455
-
2456
- /**
2457
- * You can proxy this to `clearTimeout` or its equivalent in your environment.
2458
- */
2459
- cancelTimeout(id: TimeoutHandle): void;
2460
-
2461
- /**
2462
- * 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`.
2463
- */
2464
- noTimeout: NoTimeout;
2465
-
2466
- /**
2467
- * 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.
2468
- */
2469
- supportsMicrotasks?: boolean;
2470
-
2471
- /**
2472
- * Optional. You can proxy this to `queueMicrotask` or its equivalent in your environment.
2473
- */
2474
- scheduleMicrotask?(fn: () => unknown): void;
2475
-
2476
- /**
2477
- * 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`.
2478
- */
2479
- isPrimaryRenderer: boolean;
2480
-
2481
- /**
2482
- * Whether the renderer shouldn't trigger missing `act()` warnings
2483
- */
2484
- warnsIfNotActing?: boolean;
2485
-
2486
- getInstanceFromNode(node: any): Fiber | null | undefined;
2487
-
2488
- beforeActiveInstanceBlur(): void;
2489
-
2490
- afterActiveInstanceBlur(): void;
2491
-
2492
- prepareScopeUpdate(scopeInstance: any, instance: any): void;
2493
-
2494
- getInstanceFromScope(scopeInstance: any): null | Instance;
2495
-
2496
- detachDeletedInstance(node: Instance): void;
2497
-
2498
- // -------------------
2499
- // Mutation Methods
2500
- // (optional)
2501
- // If you're using React in mutation mode (you probably do), you'll need to implement a few more methods.
2502
- // -------------------
2503
-
2504
- /**
2505
- * 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.
2506
- *
2507
- * 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`.
2508
- */
2509
- appendChild?(parentInstance: Instance, child: Instance | TextInstance): void;
2510
-
2511
- /**
2512
- * 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.
2513
- */
2514
- appendChildToContainer?(container: Container, child: Instance | TextInstance): void;
2515
-
2516
- /**
2517
- * 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.
2518
- *
2519
- * 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.
2520
- */
2521
- insertBefore?(
2522
- parentInstance: Instance,
2523
- child: Instance | TextInstance,
2524
- beforeChild: Instance | TextInstance | SuspenseInstance,
2525
- ): void;
2526
-
2527
- /**
2528
- * 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.
2529
- */
2530
- insertInContainerBefore?(
2531
- container: Container,
2532
- child: Instance | TextInstance,
2533
- beforeChild: Instance | TextInstance | SuspenseInstance,
2534
- ): void;
2535
-
2536
- /**
2537
- * This method should mutate the `parentInstance` to remove the `child` from the list of its children.
2538
- *
2539
- * 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.
2540
- */
2541
- removeChild?(parentInstance: Instance, child: Instance | TextInstance | SuspenseInstance): void;
2542
-
2543
- /**
2544
- * 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.
2545
- */
2546
- removeChildFromContainer?(container: Container, child: Instance | TextInstance | SuspenseInstance): void;
2547
-
2548
- /**
2549
- * 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 = ''`.
2550
- *
2551
- * If you never return `true` from `shouldSetTextContent`, you can leave it empty.
2552
- */
2553
- resetTextContent?(instance: Instance): void;
2554
-
2555
- /**
2556
- * This method should mutate the `textInstance` and update its text content to `nextText`.
2557
- *
2558
- * Here, `textInstance` is a node created by `createTextInstance`.
2559
- */
2560
- commitTextUpdate?(textInstance: TextInstance, oldText: string, newText: string): void;
2561
-
2562
- /**
2563
- * This method is only called if you returned `true` from `finalizeInitialChildren` for this instance.
2564
- *
2565
- * 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.
2566
- *
2567
- * 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.
2568
- *
2569
- * 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.
2570
- *
2571
- * If you never return `true` from `finalizeInitialChildren`, you can leave it empty.
2572
- */
2573
- commitMount?(instance: Instance, type: Type, props: Props, internalInstanceHandle: OpaqueHandle): void;
2574
-
2575
- /**
2576
- * This method should mutate the instance to match nextProps.
2577
- *
2578
- * 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.
2579
- */
2580
- commitUpdate?(
2581
- instance: Instance,
2582
- type: Type,
2583
- prevProps: Props,
2584
- nextProps: Props,
2585
- internalHandle: OpaqueHandle,
2586
- ): void;
2587
-
2588
- /**
2589
- * 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.
2590
- */
2591
- hideInstance?(instance: Instance): void;
2592
-
2593
- /**
2594
- * Same as `hideInstance`, but for nodes created by `createTextInstance`.
2595
- */
2596
- hideTextInstance?(textInstance: TextInstance): void;
2597
-
2598
- /**
2599
- * This method should make the `instance` visible, undoing what `hideInstance` did.
2600
- */
2601
- unhideInstance?(instance: Instance, props: Props): void;
2602
-
2603
- /**
2604
- * Same as `unhideInstance`, but for nodes created by `createTextInstance`.
2605
- */
2606
- unhideTextInstance?(textInstance: TextInstance, text: string): void;
2607
-
2608
- /**
2609
- * This method should mutate the `container` root node and remove all children from it.
2610
- */
2611
- clearContainer?(container: Container): void;
2612
-
2613
- // -------------------
2614
- // Persistence Methods
2615
- // (optional)
2616
- // 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.
2617
- // -------------------
2618
- cloneInstance?(
2619
- instance: Instance,
2620
- type: Type,
2621
- oldProps: Props,
2622
- newProps: Props,
2623
- keepChildren: boolean,
2624
- recyclableInstance: null | Instance,
2625
- ): Instance;
2626
- createContainerChildSet?(container: Container): ChildSet;
2627
- appendChildToContainerChildSet?(childSet: ChildSet, child: Instance | TextInstance): void;
2628
- finalizeContainerChildren?(container: Container, newChildren: ChildSet): void;
2629
- replaceContainerChildren?(container: Container, newChildren: ChildSet): void;
2630
- cloneHiddenInstance?(
2631
- instance: Instance,
2632
- type: Type,
2633
- props: Props,
2634
- internalInstanceHandle: OpaqueHandle,
2635
- ): Instance;
2636
- cloneHiddenTextInstance?(instance: Instance, text: Type, internalInstanceHandle: OpaqueHandle): TextInstance;
2637
-
2638
- // -------------------
2639
- // Hydration Methods
2640
- // (optional)
2641
- // 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.
2642
- //
2643
- // 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.
2644
- // -------------------
2645
- supportsHydration: boolean;
2646
-
2647
- canHydrateInstance?(instance: HydratableInstance, type: Type, props: Props): null | Instance;
2648
-
2649
- canHydrateTextInstance?(instance: HydratableInstance, text: string): null | TextInstance;
2650
-
2651
- canHydrateSuspenseInstance?(instance: HydratableInstance): null | SuspenseInstance;
2652
-
2653
- isSuspenseInstancePending?(instance: SuspenseInstance): boolean;
2654
-
2655
- isSuspenseInstanceFallback?(instance: SuspenseInstance): boolean;
2656
-
2657
- registerSuspenseInstanceRetry?(instance: SuspenseInstance, callback: () => void): void;
2658
-
2659
- getNextHydratableSibling?(instance: HydratableInstance): null | HydratableInstance;
2660
-
2661
- getFirstHydratableChild?(parentInstance: Container | Instance): null | HydratableInstance;
2662
-
2663
- hydrateInstance?(
2664
- instance: Instance,
2665
- type: Type,
2666
- props: Props,
2667
- rootContainerInstance: Container,
2668
- hostContext: HostContext,
2669
- internalInstanceHandle: any,
2670
- ): null | any[];
2671
-
2672
- hydrateTextInstance?(textInstance: TextInstance, text: string, internalInstanceHandle: any): boolean;
2673
-
2674
- hydrateSuspenseInstance?(suspenseInstance: SuspenseInstance, internalInstanceHandle: any): void;
2675
-
2676
- getNextHydratableInstanceAfterSuspenseInstance?(suspenseInstance: SuspenseInstance): null | HydratableInstance;
2677
-
2678
- // Returns the SuspenseInstance if this node is a direct child of a
2679
- // SuspenseInstance. I.e. if its previous sibling is a Comment with
2680
- // SUSPENSE_x_START_DATA. Otherwise, null.
2681
- getParentSuspenseInstance?(targetInstance: any): null | SuspenseInstance;
2682
-
2683
- commitHydratedContainer?(container: Container): void;
2684
-
2685
- commitHydratedSuspenseInstance?(suspenseInstance: SuspenseInstance): void;
2686
-
2687
- didNotMatchHydratedContainerTextInstance?(
2688
- parentContainer: Container,
2689
- textInstance: TextInstance,
2690
- text: string,
2691
- ): void;
2692
-
2693
- didNotMatchHydratedTextInstance?(
2694
- parentType: Type,
2695
- parentProps: Props,
2696
- parentInstance: Instance,
2697
- textInstance: TextInstance,
2698
- text: string,
2699
- ): void;
2700
-
2701
- didNotHydrateContainerInstance?(parentContainer: Container, instance: HydratableInstance): void;
2702
-
2703
- didNotHydrateInstance?(
2704
- parentType: Type,
2705
- parentProps: Props,
2706
- parentInstance: Instance,
2707
- instance: HydratableInstance,
2708
- ): void;
2709
-
2710
- didNotFindHydratableContainerInstance?(parentContainer: Container, type: Type, props: Props): void;
2711
-
2712
- didNotFindHydratableContainerTextInstance?(parentContainer: Container, text: string): void;
2713
-
2714
- didNotFindHydratableContainerSuspenseInstance?(parentContainer: Container): void;
2715
-
2716
- didNotFindHydratableInstance?(
2717
- parentType: Type,
2718
- parentProps: Props,
2719
- parentInstance: Instance,
2720
- type: Type,
2721
- props: Props,
2722
- ): void;
2723
-
2724
- didNotFindHydratableTextInstance?(
2725
- parentType: Type,
2726
- parentProps: Props,
2727
- parentInstance: Instance,
2728
- text: string,
2729
- ): void;
2730
-
2731
- didNotFindHydratableSuspenseInstance?(parentType: Type, parentProps: Props, parentInstance: Instance): void;
2732
-
2733
- errorHydratingContainer?(parentContainer: Container): void;
2734
-
2735
- // Undocumented
2736
- // https://github.com/facebook/react/pull/26722
2737
- NotPendingTransition: TransitionStatus | null;
2738
- HostTransitionContext: ReactContext<TransitionStatus>;
2739
-
2740
- // https://github.com/facebook/react/pull/28751
2741
- setCurrentUpdatePriority(newPriority: EventPriority): void;
2742
- getCurrentUpdatePriority(): EventPriority;
2743
- resolveUpdatePriority(): EventPriority;
2744
-
2745
- // https://github.com/facebook/react/pull/28804
2746
- resetFormInstance(form: FormInstance): void;
2747
-
2748
- // https://github.com/facebook/react/pull/25105
2749
- requestPostPaintCallback(callback: (time: number) => void): void;
2750
-
2751
- // https://github.com/facebook/react/pull/26025
2752
- shouldAttemptEagerTransition(): boolean;
2753
-
2754
- // https://github.com/facebook/react/pull/31528
2755
- trackSchedulerEvent(): void;
2756
-
2757
- // https://github.com/facebook/react/pull/31008
2758
- resolveEventType(): null | string;
2759
- resolveEventTimeStamp(): number;
2760
-
2761
- /**
2762
- * 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.
2763
- */
2764
- maySuspendCommit(type: Type, props: Props): boolean;
2765
-
2766
- /**
2767
- * 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.
2768
- */
2769
- preloadInstance(type: Type, props: Props): boolean;
2770
-
2771
- /**
2772
- * 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.
2773
- */
2774
- startSuspendingCommit(): void;
2775
-
2776
- /**
2777
- * This method is called after `startSuspendingCommit` for each Host Component that indicated it might suspend a commit.
2778
- */
2779
- suspendInstance(type: Type, props: Props): void;
2780
-
2781
- /**
2782
- * This method is called after all `suspendInstance` calls are complete.
2783
- *
2784
- * Return `null` if the commit can happen immediately.
2785
- *
2786
- * 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.
2787
- */
2788
- waitForCommitToBeReady():
2789
- | ((initiateCommit: (...args: unknown[]) => unknown) => (...args: unknown[]) => unknown)
2790
- | null;
2791
- }
2792
-
2793
- interface Thenable<T> {
2794
- then(resolve: () => T, reject?: () => T): T;
2795
- }
2796
-
2797
- type RootTag = 0 | 1 | 2;
2798
-
2799
- type WorkTag =
2800
- | 0
2801
- | 1
2802
- | 2
2803
- | 3
2804
- | 4
2805
- | 5
2806
- | 6
2807
- | 7
2808
- | 8
2809
- | 9
2810
- | 10
2811
- | 11
2812
- | 12
2813
- | 13
2814
- | 14
2815
- | 15
2816
- | 16
2817
- | 17
2818
- | 18
2819
- | 19
2820
- | 20
2821
- | 21
2822
- | 22
2823
- | 23
2824
- | 24;
2825
-
2826
- type HookType =
2827
- | "useState"
2828
- | "useReducer"
2829
- | "useContext"
2830
- | "useRef"
2831
- | "useEffect"
2832
- | "useLayoutEffect"
2833
- | "useCallback"
2834
- | "useMemo"
2835
- | "useImperativeHandle"
2836
- | "useDebugValue"
2837
- | "useDeferredValue"
2838
- | "useTransition"
2839
- | "useMutableSource"
2840
- | "useOpaqueIdentifier"
2841
- | "useCacheRefresh";
2842
-
2843
- interface Source {
2844
- fileName: string;
2845
- lineNumber: number;
2846
- }
2847
-
2848
- // TODO: Ideally these types would be opaque but that doesn't work well with
2849
- // our reconciler fork infra, since these leak into non-reconciler packages.
2850
- type LanePriority = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17;
2851
-
2852
- type Lanes = number;
2853
- type Lane = number;
2854
-
2855
- type Flags = number;
2856
-
2857
- type TypeOfMode = number;
2858
-
2859
- type EventPriority = number;
2860
-
2861
- interface ReactProvider<T> {
2862
- $$typeof: symbol | number;
2863
- type: ReactProviderType<T>;
2864
- key: null | string;
2865
- ref: null;
2866
- props: {
2867
- value: T;
2868
- children?: ReactNode;
2869
- };
2870
- }
2871
-
2872
- interface ReactProviderType<T> {
2873
- $$typeof: symbol | number;
2874
- _context: ReactContext<T>;
2875
- }
2876
-
2877
- interface ReactConsumer<T> {
2878
- $$typeof: symbol | number;
2879
- type: ReactContext<T>;
2880
- key: null | string;
2881
- ref: null;
2882
- props: {
2883
- children: (value: T) => ReactNode;
2884
- unstable_observedBits?: number;
2885
- };
2886
- }
2887
-
2888
- interface ReactContext<T> {
2889
- $$typeof: symbol | number;
2890
- Consumer: ReactContext<T>;
2891
- Provider: ReactProviderType<T>;
2892
- _currentValue: T;
2893
- _currentValue2: T;
2894
- _threadCount: number;
2895
- // DEV only
2896
- _currentRenderer?: {
2897
- [key: string]: any;
2898
- } | null;
2899
- _currentRenderer2?: {
2900
- [key: string]: any;
2901
- } | null;
2902
- // This value may be added by application code
2903
- // to improve DEV tooling display names
2904
- displayName?: string;
2905
- }
2906
-
2907
- interface ReactPortal {
2908
- $$typeof: symbol | number;
2909
- key: null | string;
2910
- containerInfo: any;
2911
- children: ReactNode;
2912
- // TODO: figure out the API for cross-renderer implementation.
2913
- implementation: any;
2914
- }
2915
-
2916
- interface RefObject {
2917
- current: any;
2918
- }
2919
-
2920
- interface ContextDependency<T> {
2921
- context: ReactContext<T>;
2922
- observedBits: number;
2923
- next: ContextDependency<unknown> | null;
2924
- }
2925
-
2926
- interface Dependencies {
2927
- lanes: Lanes;
2928
- firstContext: ContextDependency<unknown> | null;
2929
- }
2930
-
2931
- interface Fiber {
2932
- // These first fields are conceptually members of an Instance. This used to
2933
- // be split into a separate type and intersected with the other Fiber fields,
2934
- // but until Flow fixes its intersection bugs, we've merged them into a
2935
- // single type.
2936
-
2937
- // An Instance is shared between all versions of a component. We can easily
2938
- // break this out into a separate object to avoid copying so much to the
2939
- // alternate versions of the tree. We put this on a single object for now to
2940
- // minimize the number of objects created during the initial render.
2941
-
2942
- // Tag identifying the type of fiber.
2943
- tag: WorkTag;
2944
-
2945
- // Unique identifier of this child.
2946
- key: null | string;
2947
-
2948
- // The value of element.type which is used to preserve the identity during
2949
- // reconciliation of this child.
2950
- elementType: any;
2951
-
2952
- // The resolved function/class/ associated with this fiber.
2953
- type: any;
2954
-
2955
- // The local state associated with this fiber.
2956
- stateNode: any;
2957
-
2958
- // Conceptual aliases
2959
- // parent : Instance -> return The parent happens to be the same as the
2960
- // return fiber since we've merged the fiber and instance.
2961
-
2962
- // Remaining fields belong to Fiber
2963
-
2964
- // The Fiber to return to after finishing processing this one.
2965
- // This is effectively the parent, but there can be multiple parents (two)
2966
- // so this is only the parent of the thing we're currently processing.
2967
- // It is conceptually the same as the return address of a stack frame.
2968
- return: Fiber | null;
2969
-
2970
- // Singly Linked List Tree Structure.
2971
- child: Fiber | null;
2972
- sibling: Fiber | null;
2973
- index: number;
2974
-
2975
- // The ref last used to attach this node.
2976
- // I'll avoid adding an owner field for prod and model that as functions.
2977
- ref:
2978
- | null
2979
- | (((handle: unknown) => void) & {
2980
- _stringRef?: string | null;
2981
- })
2982
- | RefObject;
2983
-
2984
- // Input is the data coming into process this fiber. Arguments. Props.
2985
- pendingProps: any; // This type will be more specific once we overload the tag.
2986
- memoizedProps: any; // The props used to create the output.
2987
-
2988
- // A queue of state updates and callbacks.
2989
- updateQueue: unknown;
2990
-
2991
- // The state used to create the output
2992
- memoizedState: any;
2993
-
2994
- // Dependencies (contexts, events) for this fiber, if it has any
2995
- dependencies: Dependencies | null;
2996
-
2997
- // Bitfield that describes properties about the fiber and its subtree. E.g.
2998
- // the ConcurrentMode flag indicates whether the subtree should be async-by-
2999
- // default. When a fiber is created, it inherits the mode of its
3000
- // parent. Additional flags can be set at creation time, but after that the
3001
- // value should remain unchanged throughout the fiber's lifetime, particularly
3002
- // before its child fibers are created.
3003
- mode: TypeOfMode;
3004
-
3005
- // Effect
3006
- flags: Flags;
3007
- subtreeFlags: Flags;
3008
- deletions: Fiber[] | null;
3009
-
3010
- // Singly linked list fast path to the next fiber with side-effects.
3011
- nextEffect: Fiber | null;
3012
-
3013
- // The first and last fiber with side-effect within this subtree. This allows
3014
- // us to reuse a slice of the linked list when we reuse the work done within
3015
- // this fiber.
3016
- firstEffect: Fiber | null;
3017
- lastEffect: Fiber | null;
3018
-
3019
- lanes: Lanes;
3020
- childLanes: Lanes;
3021
-
3022
- // This is a pooled version of a Fiber. Every fiber that gets updated will
3023
- // eventually have a pair. There are cases when we can clean up pairs to save
3024
- // memory if we need to.
3025
- alternate: Fiber | null;
3026
-
3027
- // Time spent rendering this Fiber and its descendants for the current update.
3028
- // This tells us how well the tree makes use of sCU for memoization.
3029
- // It is reset to 0 each time we render and only updated when we don't bailout.
3030
- // This field is only set when the enableProfilerTimer flag is enabled.
3031
- actualDuration?: number;
3032
-
3033
- // If the Fiber is currently active in the "render" phase,
3034
- // This marks the time at which the work began.
3035
- // This field is only set when the enableProfilerTimer flag is enabled.
3036
- actualStartTime?: number;
3037
-
3038
- // Duration of the most recent render time for this Fiber.
3039
- // This value is not updated when we bailout for memoization purposes.
3040
- // This field is only set when the enableProfilerTimer flag is enabled.
3041
- selfBaseDuration?: number;
3042
-
3043
- // Sum of base times for all descendants of this Fiber.
3044
- // This value bubbles up during the "complete" phase.
3045
- // This field is only set when the enableProfilerTimer flag is enabled.
3046
- treeBaseDuration?: number;
3047
-
3048
- // Conceptual aliases
3049
- // workInProgress : Fiber -> alternate The alternate used for reuse happens
3050
- // to be the same as work in progress.
3051
- // __DEV__ only
3052
- _debugID?: number;
3053
- _debugSource?: Source | null;
3054
- _debugOwner?: Fiber | null;
3055
- _debugIsCurrentlyTiming?: boolean;
3056
- _debugNeedsRemount?: boolean;
3057
-
3058
- // Used to verify that the order of hooks does not change between renders.
3059
- _debugHookTypes?: HookType[] | null;
3060
- }
3061
-
3062
- type FiberRoot = any;
3063
-
3064
- // Concurrent related struct
3065
- type MutableSource = any;
3066
-
3067
- type OpaqueHandle = any;
3068
- type OpaqueRoot = any;
3069
-
3070
- // 0 is PROD, 1 is DEV.
3071
- // Might add PROFILE later.
3072
- type BundleType = 0 | 1;
3073
-
3074
- interface DevToolsConfig<Instance, TextInstance, RendererInspectionConfig> {
3075
- bundleType: BundleType;
3076
- version: string;
3077
- rendererPackageName: string;
3078
- // Note: this actually *does* depend on Fiber internal fields.
3079
- // Used by "inspect clicked DOM element" in React DevTools.
3080
- findFiberByHostInstance?: (instance: Instance | TextInstance) => Fiber | null;
3081
- rendererConfig?: RendererInspectionConfig;
3082
- }
3083
-
3084
- interface SuspenseHydrationCallbacks<SuspenseInstance> {
3085
- onHydrated?: (suspenseInstance: SuspenseInstance) => void;
3086
- onDeleted?: (suspenseInstance: SuspenseInstance) => void;
3087
- }
3088
-
3089
- interface TransitionTracingCallbacks {
3090
- onTransitionStart?: (transitionName: string, startTime: number) => void;
3091
- onTransitionProgress?: (
3092
- transitionName: string,
3093
- startTime: number,
3094
- currentTime: number,
3095
- pending: Array<{ name: null | string }>,
3096
- ) => void;
3097
- onTransitionIncomplete?: (
3098
- transitionName: string,
3099
- startTime: number,
3100
- deletions: Array<{
3101
- type: string;
3102
- name?: string;
3103
- newName?: string;
3104
- endTime: number;
3105
- }>,
3106
- ) => void;
3107
- onTransitionComplete?: (transitionName: string, startTime: number, endTime: number) => void;
3108
- onMarkerProgress?: (
3109
- transitionName: string,
3110
- marker: string,
3111
- startTime: number,
3112
- currentTime: number,
3113
- pending: Array<{ name: null | string }>,
3114
- ) => void;
3115
- onMarkerIncomplete?: (
3116
- transitionName: string,
3117
- marker: string,
3118
- startTime: number,
3119
- deletions: Array<{
3120
- type: string;
3121
- name?: string;
3122
- newName?: string;
3123
- endTime: number;
3124
- }>,
3125
- ) => void;
3126
- onMarkerComplete?: (transitionName: string, marker: string, startTime: number, endTime: number) => void;
3127
- }
3128
-
3129
- interface ComponentSelector {
3130
- $$typeof: symbol | number;
3131
- value: React$AbstractComponent<never, unknown>;
3132
- }
3133
-
3134
- interface HasPseudoClassSelector {
3135
- $$typeof: symbol | number;
3136
- value: Selector[];
3137
- }
3138
-
3139
- interface RoleSelector {
3140
- $$typeof: symbol | number;
3141
- value: string;
3142
- }
3143
-
3144
- interface TextSelector {
3145
- $$typeof: symbol | number;
3146
- value: string;
3147
- }
3148
-
3149
- interface TestNameSelector {
3150
- $$typeof: symbol | number;
3151
- value: string;
3152
- }
3153
-
3154
- type Selector = ComponentSelector | HasPseudoClassSelector | RoleSelector | TextSelector | TestNameSelector;
3155
-
3156
- // TODO can not find React$AbstractComponent def
3157
- type React$AbstractComponent<Config, Instance = any> = any;
3158
-
3159
- interface BoundingRect {
3160
- x: number;
3161
- y: number;
3162
- width: number;
3163
- height: number;
3164
- }
3165
-
3166
- type IntersectionObserverOptions = any;
3167
-
3168
- interface BaseErrorInfo {
3169
- componentStack?: string;
3170
- }
3171
-
3172
- interface Reconciler<Container, Instance, TextInstance, SuspenseInstance, FormInstance, PublicInstance> {
3173
- createContainer(
3174
- containerInfo: Container,
3175
- tag: RootTag,
3176
- hydrationCallbacks: null | SuspenseHydrationCallbacks<SuspenseInstance>,
3177
- isStrictMode: boolean,
3178
- concurrentUpdatesByDefaultOverride: null | boolean,
3179
- identifierPrefix: string,
3180
- onUncaughtError: (error: Error, info: BaseErrorInfo & { errorBoundary?: Component }) => void,
3181
- onCaughtError: (error: Error, info: BaseErrorInfo) => void,
3182
- onRecoverableError: (error: Error, info: BaseErrorInfo) => void,
3183
- onDefaultTransitionIndicator: () => void,
3184
- transitionCallbacks: null | TransitionTracingCallbacks,
3185
- ): OpaqueRoot;
3186
-
3187
- createPortal(
3188
- children: ReactNode,
3189
- containerInfo: any, // TODO: figure out the API for cross-renderer implementation.
3190
- implementation: any,
3191
- key?: string | null,
3192
- ): ReactPortal;
3193
-
3194
- registerMutableSourceForHydration(root: FiberRoot, mutableSource: MutableSource): void;
3195
-
3196
- createComponentSelector(component: React$AbstractComponent<never, unknown>): ComponentSelector;
3197
-
3198
- createHasPseudoClassSelector(selectors: Selector[]): HasPseudoClassSelector;
3199
-
3200
- createRoleSelector(role: string): RoleSelector;
3201
-
3202
- createTextSelector(text: string): TextSelector;
3203
-
3204
- createTestNameSelector(id: string): TestNameSelector;
3205
-
3206
- getFindAllNodesFailureDescription(hostRoot: Instance, selectors: Selector[]): string | null;
3207
-
3208
- findAllNodes(hostRoot: Instance, selectors: Selector[]): Instance[];
3209
-
3210
- findBoundingRects(hostRoot: Instance, selectors: Selector[]): BoundingRect[];
3211
-
3212
- focusWithin(hostRoot: Instance, selectors: Selector[]): boolean;
3213
-
3214
- observeVisibleRects(
3215
- hostRoot: Instance,
3216
- selectors: Selector[],
3217
- callback: (intersections: Array<{ ratio: number; rect: BoundingRect }>) => void,
3218
- options?: IntersectionObserverOptions,
3219
- ): { disconnect: () => void };
3220
-
3221
- createHydrationContainer(
3222
- initialChildren: ReactNode,
3223
- callback: (() => void) | null | undefined,
3224
- containerInfo: Container,
3225
- tag: RootTag,
3226
- hydrationCallbacks: null | SuspenseHydrationCallbacks<SuspenseInstance>,
3227
- isStrictMode: boolean,
3228
- concurrentUpdatesByDefaultOverride: null | boolean,
3229
- identifierPrefix: string,
3230
- onRecoverableError: (error: Error) => void,
3231
- transitionCallbacks: null | TransitionTracingCallbacks,
3232
- ): OpaqueRoot;
3233
-
3234
- updateContainer(
3235
- element: ReactNode,
3236
- container: OpaqueRoot,
3237
- parentComponent?: Component<any, any> | null,
3238
- callback?: (() => void) | null,
3239
- ): Lane;
3240
-
3241
- batchedUpdates<A, R>(fn: (a: A) => R, a: A): R;
3242
-
3243
- deferredUpdates<A>(fn: () => A): A;
3244
-
3245
- 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;
3246
-
3247
- flushControlled(fn: () => any): void;
3248
-
3249
- flushSync(): void;
3250
- flushSync<R>(fn: () => R): R;
3251
-
3252
- isAlreadyRendering(): boolean;
3253
-
3254
- flushPassiveEffects(): boolean;
3255
-
3256
- getPublicRootInstance(container: OpaqueRoot): Component<any, any> | PublicInstance | null;
3257
-
3258
- attemptSynchronousHydration(fiber: Fiber): void;
3259
-
3260
- attemptDiscreteHydration(fiber: Fiber): void;
3261
-
3262
- attemptContinuousHydration(fiber: Fiber): void;
3263
-
3264
- attemptHydrationAtCurrentPriority(fiber: Fiber): void;
3265
-
3266
- getCurrentUpdatePriority(): LanePriority;
3267
-
3268
- runWithPriority<T>(priority: LanePriority, fn: () => T): T;
3269
-
3270
- findHostInstance(component: any): PublicInstance | null;
3271
-
3272
- findHostInstanceWithWarning(component: any, methodName: string): PublicInstance | null;
3273
-
3274
- findHostInstanceWithNoPortals(fiber: Fiber): PublicInstance | null;
3275
-
3276
- shouldError(fiber: Fiber): boolean | undefined;
3277
-
3278
- shouldSuspend(fiber: Fiber): boolean;
3279
-
3280
- injectIntoDevTools(devToolsConfig: DevToolsConfig<Instance, TextInstance, any>): boolean;
3281
- }
3282
- }
3283
-
3284
- declare function extend<T extends ConstructorRepresentation>(objects: T): React$1.ExoticComponent<ThreeElement<T>>;
3285
- declare function extend<T extends Catalogue>(objects: T): void;
3286
- declare function extend(objects: Record<string, unknown>): void;
3287
- declare const reconciler: ReactReconciler.Reconciler<RootStore, Instance<any>, void, Instance<any>, never, any>;
3288
-
3289
- declare const isRenderer: (def: any) => boolean;
3290
- interface OffscreenCanvas extends EventTarget {
3291
- }
3292
- declare const _roots: Map<HTMLCanvasElement | OffscreenCanvas, Root>;
3293
- declare function createRoot<TCanvas extends HTMLCanvasElement | OffscreenCanvas>(canvas: TCanvas): ReconcilerRoot<TCanvas>;
3294
- declare function unmountComponentAtNode<TCanvas extends HTMLCanvasElement | OffscreenCanvas>(canvas: TCanvas, callback?: (canvas: TCanvas) => void): void;
3295
- declare function createPortal(children: ReactNode, container: Object3D | RefObject<Object3D | null> | RefObject<Object3D>, state?: InjectState): JSX.Element;
3296
- interface PortalProps {
3297
- children: ReactNode;
3298
- state?: InjectState;
3299
- container: Object3D | RefObject<Object3D | null> | RefObject<Object3D>;
3300
- }
3301
- declare function Portal({ children, container, state }: PortalProps): JSX.Element;
3302
- /**
3303
- * Force React to flush any updates inside the provided callback synchronously and immediately.
3304
- * All the same caveats documented for react-dom's `flushSync` apply here (see https://react.dev/reference/react-dom/flushSync).
3305
- * Nevertheless, sometimes one needs to render synchronously, for example to keep DOM and 3D changes in lock-step without
3306
- * having to revert to a non-React solution. Note: this will only flush updates within the `Canvas` root.
3307
- */
3308
- declare function flushSync<R>(fn: () => R): R;
3309
-
3310
- declare const context: React$1.Context<RootStore>;
3311
- declare const createStore: (invalidate: (state?: RootState, frames?: number, stackFrames?: boolean) => void, advance: (timestamp: number, runGlobalEffects?: boolean, state?: RootState, frame?: XRFrame) => void) => RootStore;
3312
-
3313
- /**
3314
- * An SSR-friendly useLayoutEffect.
3315
- *
3316
- * React currently throws a warning when using useLayoutEffect on the server.
3317
- * To get around it, we can conditionally useEffect on the server (no-op) and
3318
- * useLayoutEffect elsewhere.
3319
- *
3320
- * @see https://github.com/facebook/react/issues/14927
3321
- */
3322
- declare const useIsomorphicLayoutEffect: typeof React$1.useLayoutEffect;
3323
- /**
3324
- * Creates a stable ref that always contains the latest callback.
3325
- * Useful for avoiding dependency arrays while ensuring the latest closure is called.
3326
- *
3327
- * @param fn - The callback function to wrap
3328
- * @returns A ref containing the current callback
3329
- */
3330
- declare function useMutableCallback<T>(fn: T): React$1.RefObject<T>;
3331
- /**
3332
- * Bridges renderer Context and StrictMode from a primary renderer.
3333
- * Used to maintain React context when rendering into portals or secondary canvases.
3334
- *
3335
- * @returns A Bridge component that wraps children with the parent renderer's context
3336
- */
3337
- declare function useBridge(): Bridge;
3338
- /**
3339
- * Internal component that blocks rendering until a promise resolves.
3340
- * Used for suspense-like blocking behavior.
3341
- *
3342
- * @param set - Function to set the blocking promise
3343
- */
3344
- declare function Block({ set }: Omit<UnblockProps, 'children'>): null;
3345
- /**
3346
- * Error boundary component for catching and handling errors in the React tree.
3347
- * Forwards errors to a state setter for external handling.
3348
- *
3349
- * NOTE: static members get down-level transpiled to mutations which break tree-shaking
3350
- */
3351
- declare const ErrorBoundary: {
3352
- new (props: {
3353
- set: React$1.Dispatch<Error | undefined>;
3354
- children: React$1.ReactNode;
3355
- }): {
3356
- state: {
3357
- error: boolean;
3358
- };
3359
- componentDidCatch(err: Error): void;
3360
- render(): React$1.ReactNode;
3361
- context: unknown;
3362
- setState<K extends "error">(state: {
3363
- error: boolean;
3364
- } | ((prevState: Readonly<{
3365
- error: boolean;
3366
- }>, props: Readonly<{
3367
- set: React$1.Dispatch<Error | undefined>;
3368
- children: React$1.ReactNode;
3369
- }>) => {
3370
- error: boolean;
3371
- } | Pick<{
3372
- error: boolean;
3373
- }, K> | null) | Pick<{
3374
- error: boolean;
3375
- }, K> | null, callback?: (() => void) | undefined): void;
3376
- forceUpdate(callback?: (() => void) | undefined): void;
3377
- readonly props: Readonly<{
3378
- set: React$1.Dispatch<Error | undefined>;
3379
- children: React$1.ReactNode;
3380
- }>;
3381
- componentDidMount?(): void;
3382
- shouldComponentUpdate?(nextProps: Readonly<{
3383
- set: React$1.Dispatch<Error | undefined>;
3384
- children: React$1.ReactNode;
3385
- }>, nextState: Readonly<{
3386
- error: boolean;
3387
- }>, nextContext: any): boolean;
3388
- componentWillUnmount?(): void;
3389
- getSnapshotBeforeUpdate?(prevProps: Readonly<{
3390
- set: React$1.Dispatch<Error | undefined>;
3391
- children: React$1.ReactNode;
3392
- }>, prevState: Readonly<{
3393
- error: boolean;
3394
- }>): any;
3395
- componentDidUpdate?(prevProps: Readonly<{
3396
- set: React$1.Dispatch<Error | undefined>;
3397
- children: React$1.ReactNode;
3398
- }>, prevState: Readonly<{
3399
- error: boolean;
3400
- }>, snapshot?: any): void;
3401
- componentWillMount?(): void;
3402
- UNSAFE_componentWillMount?(): void;
3403
- componentWillReceiveProps?(nextProps: Readonly<{
3404
- set: React$1.Dispatch<Error | undefined>;
3405
- children: React$1.ReactNode;
3406
- }>, nextContext: any): void;
3407
- UNSAFE_componentWillReceiveProps?(nextProps: Readonly<{
3408
- set: React$1.Dispatch<Error | undefined>;
3409
- children: React$1.ReactNode;
3410
- }>, nextContext: any): void;
3411
- componentWillUpdate?(nextProps: Readonly<{
3412
- set: React$1.Dispatch<Error | undefined>;
3413
- children: React$1.ReactNode;
3414
- }>, nextState: Readonly<{
3415
- error: boolean;
3416
- }>, nextContext: any): void;
3417
- UNSAFE_componentWillUpdate?(nextProps: Readonly<{
3418
- set: React$1.Dispatch<Error | undefined>;
3419
- children: React$1.ReactNode;
3420
- }>, nextState: Readonly<{
3421
- error: boolean;
3422
- }>, nextContext: any): void;
3423
- };
3424
- new (props: {
3425
- set: React$1.Dispatch<Error | undefined>;
3426
- children: React$1.ReactNode;
3427
- }, context: any): {
3428
- state: {
3429
- error: boolean;
3430
- };
3431
- componentDidCatch(err: Error): void;
3432
- render(): React$1.ReactNode;
3433
- context: unknown;
3434
- setState<K extends "error">(state: {
3435
- error: boolean;
3436
- } | ((prevState: Readonly<{
3437
- error: boolean;
3438
- }>, props: Readonly<{
3439
- set: React$1.Dispatch<Error | undefined>;
3440
- children: React$1.ReactNode;
3441
- }>) => {
3442
- error: boolean;
3443
- } | Pick<{
3444
- error: boolean;
3445
- }, K> | null) | Pick<{
3446
- error: boolean;
3447
- }, K> | null, callback?: (() => void) | undefined): void;
3448
- forceUpdate(callback?: (() => void) | undefined): void;
3449
- readonly props: Readonly<{
3450
- set: React$1.Dispatch<Error | undefined>;
3451
- children: React$1.ReactNode;
3452
- }>;
3453
- componentDidMount?(): void;
3454
- shouldComponentUpdate?(nextProps: Readonly<{
3455
- set: React$1.Dispatch<Error | undefined>;
3456
- children: React$1.ReactNode;
3457
- }>, nextState: Readonly<{
3458
- error: boolean;
3459
- }>, nextContext: any): boolean;
3460
- componentWillUnmount?(): void;
3461
- getSnapshotBeforeUpdate?(prevProps: Readonly<{
3462
- set: React$1.Dispatch<Error | undefined>;
3463
- children: React$1.ReactNode;
3464
- }>, prevState: Readonly<{
3465
- error: boolean;
3466
- }>): any;
3467
- componentDidUpdate?(prevProps: Readonly<{
3468
- set: React$1.Dispatch<Error | undefined>;
3469
- children: React$1.ReactNode;
3470
- }>, prevState: Readonly<{
3471
- error: boolean;
3472
- }>, snapshot?: any): void;
3473
- componentWillMount?(): void;
3474
- UNSAFE_componentWillMount?(): void;
3475
- componentWillReceiveProps?(nextProps: Readonly<{
3476
- set: React$1.Dispatch<Error | undefined>;
3477
- children: React$1.ReactNode;
3478
- }>, nextContext: any): void;
3479
- UNSAFE_componentWillReceiveProps?(nextProps: Readonly<{
3480
- set: React$1.Dispatch<Error | undefined>;
3481
- children: React$1.ReactNode;
3482
- }>, nextContext: any): void;
3483
- componentWillUpdate?(nextProps: Readonly<{
3484
- set: React$1.Dispatch<Error | undefined>;
3485
- children: React$1.ReactNode;
3486
- }>, nextState: Readonly<{
3487
- error: boolean;
3488
- }>, nextContext: any): void;
3489
- UNSAFE_componentWillUpdate?(nextProps: Readonly<{
3490
- set: React$1.Dispatch<Error | undefined>;
3491
- children: React$1.ReactNode;
3492
- }>, nextState: Readonly<{
3493
- error: boolean;
3494
- }>, nextContext: any): void;
3495
- };
3496
- getDerivedStateFromError: () => {
3497
- error: boolean;
3498
- };
3499
- contextType?: React$1.Context<any> | undefined;
3500
- propTypes?: any;
3501
- };
3502
-
3503
- /**
3504
- * React internal props that should not be passed to Three.js objects.
3505
- */
3506
- declare const REACT_INTERNAL_PROPS: string[];
3507
- /**
3508
- * Returns the instance's initial (outermost) root.
3509
- * Traverses through previousRoot links to find the original root store.
3510
- *
3511
- * @param instance - R3F instance to find root for
3512
- * @returns The outermost root store
3513
- */
3514
- declare function findInitialRoot<T>(instance: Instance<T>): RootStore;
3515
- /**
3516
- * Returns instance root state.
3517
- * If the object doesn't have __r3f (e.g., child meshes in primitives/GLTFs),
3518
- * traverses ancestors to find the nearest managed parent.
3519
- *
3520
- * @param obj - Three.js object to get root state for
3521
- * @returns Root state if found, undefined otherwise
3522
- */
3523
- declare function getRootState<T extends Object3D = Object3D>(obj: T): RootState | undefined;
3524
- /**
3525
- * Collects nodes, materials, and meshes from a Three.js Object3D hierarchy.
3526
- * Handles duplicate material names by appending UUID prefixes.
3527
- *
3528
- * @param object - Root object to traverse
3529
- * @returns ObjectMap containing named nodes, materials, and meshes
3530
- *
3531
- * @example
3532
- * const { nodes, materials, meshes } = buildGraph(gltf.scene)
3533
- * // Access by name: nodes.Head, materials.Metal, meshes.Body
3534
- */
3535
- declare function buildGraph(object: Object3D): ObjectMap;
3536
- /**
3537
- * Disposes an object and all its disposable properties.
3538
- * Skips Scene objects as they should not be disposed automatically.
3539
- *
3540
- * @param obj - Object to dispose
3541
- */
3542
- declare function dispose<T extends Disposable>(obj: T): void;
3543
- /**
3544
- * Extracts instance props from React reconciler fiber props.
3545
- * Filters out React-internal props (children, key, ref).
3546
- *
3547
- * @param queue - Pending props from reconciler fiber
3548
- * @returns Props object without React-internal keys
3549
- */
3550
- declare function getInstanceProps<T = any>(pendingProps: Record<string, unknown>): Instance<T>['props'];
3551
- /**
3552
- * Creates or retrieves an R3F instance descriptor for a Three.js object.
3553
- * Each object in the scene carries a LocalState descriptor (__r3f).
3554
- *
3555
- * @param target - Target object to prepare
3556
- * @param root - Root store for this instance
3557
- * @param type - String identifier for the object type
3558
- * @param props - Initial props for the instance
3559
- * @returns Instance descriptor
3560
- */
3561
- declare function prepare<T = any>(target: T, root: RootStore, type: string, props: Instance<T>['props']): Instance<T>;
3562
- /**
3563
- * Triggers an update for an instance.
3564
- * Calls onUpdate callback and invalidates the frame if necessary.
3565
- *
3566
- * @param instance - Instance to invalidate
3567
- */
3568
- declare function invalidateInstance(instance: Instance): void;
3569
-
3570
- /**
3571
- * Reserved prop names that should not be applied to Three.js objects.
3572
- */
3573
- declare const RESERVED_PROPS: string[];
3574
- /**
3575
- * Resolves a potentially pierced property key (e.g., 'material-color' → material.color).
3576
- * First tries the entire key as a single property, then attempts piercing.
3577
- *
3578
- * @param root - Root object to resolve from
3579
- * @param key - Property key (may contain dashes for piercing)
3580
- * @returns Object containing root, key, and target value
3581
- *
3582
- * @example
3583
- * resolve(mesh, 'material-color')
3584
- * // => { root: mesh.material, key: 'color', target: mesh.material.color }
3585
- */
3586
- declare function resolve(root: any, key: string): {
3587
- root: any;
3588
- key: string;
3589
- target: any;
3590
- };
3591
- /**
3592
- * Attaches a child instance to a parent instance.
3593
- * Handles both string-based attachment (e.g., 'geometry', 'material-map')
3594
- * and function-based attachment for custom logic.
3595
- *
3596
- * @param parent - Parent instance
3597
- * @param child - Child instance to attach
3598
- *
3599
- * @example
3600
- * // String attachment
3601
- * <bufferGeometry attach="geometry" />
3602
- * // Array attachment
3603
- * <light attach="lights-0" />
3604
- * // Function attachment
3605
- * <thing attach={(parent, self) => { parent.customProp = self }} />
3606
- */
3607
- declare function attach(parent: Instance, child: Instance): void;
3608
- /**
3609
- * Detaches a child instance from a parent instance.
3610
- * Restores the previous value or deletes the property if it was never set.
3611
- *
3612
- * @param parent - Parent instance
3613
- * @param child - Child instance to detach
3614
- */
3615
- declare function detach(parent: Instance, child: Instance): void;
3616
- /**
3617
- * Compares old and new props to determine which properties have changed.
3618
- * Also handles resetting removed props for HMR/fast-refresh.
3619
- *
3620
- * @param instance - Instance to diff props for
3621
- * @param newProps - New props to compare against
3622
- * @returns Object containing only changed props
3623
- *
3624
- * @example
3625
- * const changes = diffProps(instance, { position: [1, 2, 3], color: 'red' })
3626
- * // => { position: [1, 2, 3] } (only if position changed)
3627
- */
3628
- declare function diffProps<T = any>(instance: Instance<T>, newProps: Instance<T>['props']): Instance<T>['props'];
3629
- /**
3630
- * Applies a set of props to a Three.js object.
3631
- * Handles special cases like colors, vectors, textures, events, and pierced props.
3632
- *
3633
- * @param object - Three.js object to apply props to
3634
- * @param props - Props to apply
3635
- * @returns The object with props applied
3636
- *
3637
- * @example
3638
- * applyProps(mesh, { position: [0, 1, 0], 'material-color': 'red' })
3639
- */
3640
- declare function applyProps<T = any>(object: Instance<T>['object'], props: Instance<T>['props']): Instance<T>['object'];
3641
-
3642
- /**
3643
- * Calculates the device pixel ratio for rendering.
3644
- * Handles array DPR ranges [min, max] to clamp devicePixelRatio.
3645
- *
3646
- * @param dpr - Target DPR value or [min, max] range
3647
- * @returns Calculated DPR value
3648
- *
3649
- * @example
3650
- * calculateDpr(2) // => 2
3651
- * calculateDpr([1, 2]) // => clamps window.devicePixelRatio between 1 and 2
3652
- */
3653
- declare function calculateDpr(dpr: Dpr): number;
3654
- /**
3655
- * Extracts the first segment of a UUID string (before the first hyphen).
3656
- * Used for creating unique material names when duplicates exist.
3657
- *
3658
- * @param uuid - UUID string to extract prefix from
3659
- * @returns First segment of the UUID
3660
- *
3661
- * @example
3662
- * getUuidPrefix('a1b2c3d4-e5f6-g7h8-i9j0') // => 'a1b2c3d4'
3663
- */
3664
- declare function getUuidPrefix(uuid: string): string;
3665
- /**
3666
- * Updates camera projection based on viewport size.
3667
- * Adjusts aspect ratio for perspective cameras or bounds for orthographic cameras.
3668
- * Respects camera.manual flag - manual cameras are not modified.
3669
- *
3670
- * @param camera - Camera to update
3671
- * @param size - Current viewport size
3672
- */
3673
- declare function updateCamera(camera: ThreeCamera, size: Size): void;
3674
- /**
3675
- * Updates a frustum from a camera's projection and world matrices.
3676
- * If no target frustum is provided, creates and returns a new one.
3677
- *
3678
- * @param camera - Camera to extract frustum from
3679
- * @param frustum - Optional existing frustum to update (creates new if not provided)
3680
- * @returns The updated or newly created frustum
3681
- *
3682
- * @example
3683
- * // Create new frustum
3684
- * const frustum = updateFrustum(camera)
3685
- *
3686
- * // Update existing frustum (no allocation)
3687
- * updateFrustum(camera, existingFrustum)
3688
- *
3689
- * // Use for visibility checks
3690
- * if (frustum.containsPoint(point)) { ... }
3691
- * if (frustum.intersectsObject(mesh)) { ... }
3692
- */
3693
- declare function updateFrustum(camera: ThreeCamera, frustum?: Frustum): Frustum;
3694
-
3695
- declare const is: {
3696
- obj: (a: any) => boolean;
3697
- fun: (a: any) => a is Function;
3698
- str: (a: any) => a is string;
3699
- num: (a: any) => a is number;
3700
- boo: (a: any) => a is boolean;
3701
- und: (a: any) => boolean;
3702
- nul: (a: any) => boolean;
3703
- arr: (a: any) => a is any[];
3704
- equ(a: any, b: any, { arrays, objects, strict }?: EquConfig): boolean;
3705
- };
3706
- declare const isOrthographicCamera: (def: ThreeCamera) => def is OrthographicCamera;
3707
- declare const isRef: (obj: unknown) => obj is React.RefObject<unknown>;
3708
- declare const isColorRepresentation: (value: unknown) => value is ColorRepresentation$1;
3709
- declare const isObject3D: (object: any) => object is Object3D;
3710
- declare const isTexture: (value: unknown) => value is Texture$1;
3711
- type VectorLike = {
3712
- set: (...args: any[]) => void;
3713
- constructor?: Function;
3714
- };
3715
- declare const isVectorLike: (object: unknown) => object is VectorLike;
3716
- type Copyable = {
3717
- copy: (...args: any[]) => void;
3718
- constructor?: Function;
3719
- };
3720
- declare const isCopyable: (object: unknown) => object is Copyable;
3721
- declare const hasConstructor: (object: unknown) => object is {
3722
- constructor?: Function;
3723
- };
3724
-
3725
- /**
3726
- * Symbol marker for deferred ref resolution.
3727
- * Used to identify values that should be resolved from refs after mount.
3728
- */
3729
- declare const FROM_REF: unique symbol;
3730
- /** The marker `fromRef()` returns; resolved by the reconciler in `commitMount`. */
3731
- interface FromRefMarker<T = unknown, R = T> {
3732
- [FROM_REF]: React$1.RefObject<T | null>;
3733
- /** Optional transform applied to the resolved ref before assignment. */
3734
- transform?: (value: T) => R;
3735
- }
3736
- /**
3737
- * Defers prop application until the referenced object is available.
3738
- * Useful for props like `target` that need sibling refs to be populated.
3739
- *
3740
- * Only top-level props on a three element are resolved: a marker nested inside another value
3741
- * (an array, an options object) is never seen. When the prop needs the sibling *wrapped* rather
3742
- * than assigned as-is, pass a `transform`; it runs once the ref is populated and its result is
3743
- * what gets assigned.
3744
- *
3745
- * @param ref - React ref object to resolve at mount time
3746
- * @param transform - Optional mapping from the resolved object to the value the prop expects
3747
- * @returns A marker value that the reconciler resolves after mount
3748
- *
3749
- * @example
3750
- * const targetRef = useRef<THREE.Object3D>(null)
3751
- *
3752
- * <group ref={targetRef} position={[-3, -2, -15]} />
3753
- * <spotLight target={fromRef(targetRef)} intensity={100} />
3754
- *
3755
- * @example
3756
- * // Wrap the sibling: a node material's lightsNode needs a LightsNode, not the light itself
3757
- * <meshPhongNodeMaterial lightsNode={fromRef(lightRef, (light) => lights([light]))} />
3758
- */
3759
- declare function fromRef<T>(ref: React$1.RefObject<T | null>): T;
3760
- declare function fromRef<T, R>(ref: React$1.RefObject<T | null>, transform: (value: T) => R): R;
3761
- /**
3762
- * Type guard to check if a value is a fromRef marker.
3763
- *
3764
- * @param value - Value to check
3765
- * @returns True if value is a fromRef marker
3766
- */
3767
- declare function isFromRef(value: unknown): value is FromRefMarker<any, unknown>;
3768
-
3769
- /**
3770
- * Symbol marker for mount-only method calls.
3771
- * Used to identify methods that should only be called once on initial mount.
3772
- */
3773
- declare const ONCE: unique symbol;
3774
- /**
3775
- * Marks a method call to be executed only on initial mount.
3776
- * Useful for geometry transforms that should not be reapplied on every render.
3777
- *
3778
- * When `args` prop changes (triggering reconstruction), the method will be
3779
- * called again on the new instance since appliedOnce is not carried over.
3780
- *
3781
- * @param args - Arguments to pass to the method
3782
- * @returns A marker value that applyProps will execute once
3783
- *
3784
- * @example
3785
- * // Rotate geometry on mount
3786
- * <boxGeometry args={[1, 1, 1]} rotateX={once(Math.PI / 2)} />
3787
- *
3788
- * // Multiple arguments
3789
- * <bufferGeometry applyMatrix4={once(matrix)} />
3790
- *
3791
- * // No arguments
3792
- * <geometry center={once()} />
3793
- */
3794
- declare function once<A extends unknown[]>(...args: A): OnceValue<A>;
3795
- /**
3796
- * What `once(...args)` is typed as, so the marker is assignable to the prop it targets:
3797
- * the single argument itself (`rotateX={once(angle)}`), the argument tuple for multi-argument
3798
- * methods (`translate={once(x, y, z)}`), or `true` for a bare call (`center={once()}`).
3799
- *
3800
- * The runtime value is always the marker object; only the declared type follows the prop.
3801
- */
3802
- type OnceValue<A extends unknown[]> = A extends [] ? true : A extends [infer Single] ? Single : A;
3803
- /**
3804
- * Type guard to check if a value is a once marker.
3805
- *
3806
- * @param value - Value to check
3807
- * @returns True if value is a once marker
3808
- */
3809
- declare function isOnce(value: unknown): value is {
3810
- [ONCE]: any[] | true;
3811
- };
3812
-
3813
- /** Distinguishes a resource leaf from a nested resource scope. */
3814
- type ResourceLeafGuard<T> = (value: unknown) => value is T;
3815
-
3816
- /**
3817
- * ScopedStore - Type-safe wrapper for nested stores (uniforms, nodes)
3818
- *
3819
- * Provides TypeScript-friendly access to uniform/node stores where the runtime
3820
- * structure is `Record<string, T | Record<string, T>>` (leaf nodes or nested scopes).
3821
- *
3822
- * The wrapper uses a Proxy to:
3823
- * 1. Return `T` for property access (type assumption: assumes leaf node)
3824
- * 2. Provide `.scope(key)` method for explicit nested access
3825
- * 3. Support iteration methods: has(), keys(), Object.keys(), for...in
3826
- *
3827
- * @example
3828
- * ```tsx
3829
- * useLocalNodes(({ uniforms }) => ({
3830
- * wobble: sin(uniforms.uTime.mul(2)), // No cast needed!
3831
- * playerHealth: uniforms.scope('player').uHealth // Explicit scope access
3832
- * }))
3833
- * ```
3834
- */
3835
-
3836
- /**
3837
- * Type-safe wrapper interface for accessing nested store data.
3838
- * Property access returns `T` (assumes leaf node).
3839
- * Use `.scope(key)` for nested object access.
3840
- *
3841
- */
3842
- type ScopedStoreMethods<TLeaf> = {
3843
- /** Access a nested scope by key. Returns empty wrapper if scope doesn't exist. */
3844
- scope<TScope extends Record<string, TLeaf> = Record<string, TLeaf>>(key: string): ScopedStoreType<TLeaf, TScope>;
3845
- /** Check if a key exists in the store */
3846
- has(key: string): boolean;
3847
- /** Get all keys in the store */
3848
- keys(): string[];
3849
- };
3850
- type ScopedStoreType<TLeaf, TEntries extends Record<string, TLeaf> = Record<string, TLeaf>> = Readonly<TEntries> & ScopedStoreMethods<TLeaf>;
3851
- interface ScopedStoreData<TLeaf> {
3852
- [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 };
3853
85
  }
3854
- /**
3855
- * Create a type-safe ScopedStore wrapper around store data.
3856
- * @param data - The raw store data (uniforms or nodes from RootState)
3857
- * @returns A ScopedStoreType wrapper with type-safe access
3858
- */
3859
- declare function createScopedStore<TLeaf>(data: ScopedStoreData<TLeaf>, isLeaf: ResourceLeafGuard<TLeaf>): ScopedStoreType<TLeaf>;
3860
- /**
3861
- * State type passed to creator functions with ScopedStore wrappers.
3862
- * Provides type-safe access to uniforms, nodes, buffers, and gpuStorage without manual casting.
3863
- */
3864
- type CreatorState = Omit<RootState, 'uniforms' | 'nodes' | 'buffers' | 'gpuStorage'> & {
3865
- /** Type-safe uniform access - property access returns UniformNode */
3866
- uniforms: ScopedStoreType<UniformNode>;
3867
- /** Type-safe node access for real, callable, and legacy structural nodes */
3868
- nodes: ScopedStoreType<NodeLike>;
3869
- /** Type-safe buffer access - property access returns BufferLike (TypedArrays, BufferAttributes, TSL nodes) */
3870
- buffers: ScopedStoreType<BufferLike>;
3871
- /** Type-safe GPU storage access - property access returns StorageLike (StorageTexture, TSL nodes) */
3872
- gpuStorage: ScopedStoreType<StorageLike>;
3873
- };
3874
-
3875
- /** Creator function that returns uniform inputs (can be raw values or UniformNodes) */
3876
- type UniformCreator<T extends UniformInputRecord = UniformInputRecord> = (state: CreatorState) => T;
3877
- /** Function signature for removeUniforms util */
3878
- type RemoveUniformsFn = (names: string | string[], scope?: string) => void;
3879
- /** Function signature for clearUniforms util */
3880
- type ClearUniformsFn = (scope?: string) => void;
3881
- /** Function signature for rebuildUniforms util */
3882
- type RebuildUniformsFn = (scope?: string) => void;
3883
- /** Return type with utils included */
3884
- type UniformsWithUtils<T extends UniformRecord | UniformStore = UniformRecord> = T & {
3885
- removeUniforms: RemoveUniformsFn;
3886
- clearUniforms: ClearUniformsFn;
3887
- rebuildUniforms: RebuildUniformsFn;
3888
- };
3889
- declare function useUniforms<T extends UniformInputRecord>(creator: UniformCreator<T>): UniformsWithUtils<UniformNodesFor<T>>;
3890
- declare function useUniforms<T extends UniformInputRecord>(creator: UniformCreator<T>, scope: string): UniformsWithUtils<UniformNodesFor<T>>;
3891
- declare function useUniforms<T extends UniformInputRecord>(uniforms: T): UniformsWithUtils<UniformNodesFor<T>>;
3892
- declare function useUniforms<T extends UniformInputRecord>(uniforms: T, scope: string): UniformsWithUtils<UniformNodesFor<T>>;
3893
- declare function useUniforms(): UniformsWithUtils<UniformStore>;
3894
- declare function useUniforms(scope: string): UniformsWithUtils;
3895
- declare function useUniforms<T extends UniformInputRecord>(scope?: string): UniformsWithUtils<UniformNodesFor<T>>;
3896
- /**
3897
- * Global rebuildUniforms function for HMR integration.
3898
- * Invalidates cached uniforms and increments _hmrVersion to trigger re-creation.
3899
- * Call this when HMR is detected to refresh all uniform creators.
3900
- *
3901
- * Resolves to the primary store so shared TSL resources rebuild on the
3902
- * authoritative store.
3903
- *
3904
- * @param store - The R3F store (from useStore or context)
3905
- * @param scope - Optional scope to rebuild ('root' for root only, string for specific scope, undefined for all)
3906
- */
3907
- declare function rebuildAllUniforms(store: ReturnType<typeof useStore>, scope?: string): void;
3908
- /**
3909
- * Remove uniforms by name from root level or a scope
3910
- * @deprecated Use `const { removeUniforms } = useUniforms()` instead
3911
- */
3912
- declare function removeUniforms(set: ReturnType<typeof useStore>['setState'], names: string[], scope?: string): void;
3913
- /**
3914
- * Clear all uniforms from a scope (removes the entire scope object)
3915
- * @deprecated Use `const { clearUniforms } = useUniforms()` instead
3916
- */
3917
- declare function clearScope(set: ReturnType<typeof useStore>['setState'], scope: string): void;
3918
- /**
3919
- * Clear all root-level uniforms (preserves scopes)
3920
- * @deprecated Use `const { clearUniforms } = useUniforms()` with `clearUniforms('root')` instead
3921
- */
3922
- declare function clearRootUniforms(set: ReturnType<typeof useStore>['setState']): void;
3923
-
3924
- /**
3925
- * Supported uniform value types:
3926
- * - Raw values: number, boolean, Vector2, Vector3, Vector4, Color, Matrix2, Matrix3, Matrix4
3927
- * - String colors: '#ff0000', 'red', 'rgb(255,0,0)' (auto-converted to Color)
3928
- * - TSL nodes: color(), vec3(), float(), etc. (for type casting)
3929
- * - UniformNode: existing uniforms (reused as-is)
3930
- */
3931
- type UniformValue = number | boolean | string | Vector2$1 | Vector3$1 | Vector4$1 | Color$2 | Matrix2 | Matrix3$1 | Matrix4$1 | Node | UniformNode;
3932
- declare function useUniform<T extends UniformValue = UniformValue>(name: string): UniformNodeFor<T>;
3933
- declare function useUniform<T extends UniformValue>(name: string, value: T): UniformNodeFor<T>;
3934
-
3935
- /**
3936
- * Every node representation a creator may return. The definition lives with the store types as
3937
- * `NodeLike`, so the shape creators return and the shape `state.nodes` holds are one type by
3938
- * construction: three's real `Node`, the callable proxy `Fn()` returns, or the legacy structural
3939
- * `{ uuid, nodeType }` shape.
3940
- */
3941
- type TSLNodeLike = NodeLike;
3942
-
3943
- /** Backward-compatible alias covering every accepted node representation. */
3944
- type TSLNode = TSLNodeLike;
3945
- /**
3946
- * Creator function that returns a record of nodes.
3947
- * Exact creator return inference is preserved within the compatible node constraint.
3948
- */
3949
- type NodeCreator<T extends Record<string, TSLNodeLike>> = (state: CreatorState) => T;
3950
- /** Function signature for removeNodes util */
3951
- type RemoveNodesFn = (names: string | string[], scope?: string) => void;
3952
- /** Function signature for clearNodes util */
3953
- type ClearNodesFn = (scope?: string) => void;
3954
- /** Function signature for rebuildNodes util */
3955
- type RebuildNodesFn = (scope?: string) => void;
3956
- /** Return type with utils included */
3957
- type NodesWithUtils<T extends Record<string, unknown> = NodeRecord> = T & {
3958
- removeNodes: RemoveNodesFn;
3959
- clearNodes: ClearNodesFn;
3960
- rebuildNodes: RebuildNodesFn;
3961
- };
3962
- declare function useNodes(): NodesWithUtils<NodeStore>;
3963
- declare function useNodes(scope: string): NodesWithUtils<NodeRecord>;
3964
- declare function useNodes<T extends NodeRecord>(scope?: string): NodesWithUtils<T>;
3965
- declare function useNodes<T extends NodeRecord>(creator: NodeCreator<T>): NodesWithUtils<T>;
3966
- declare function useNodes<T extends NodeRecord>(creator: NodeCreator<T>, scope: string): NodesWithUtils<T>;
3967
- declare function useNodes(creatorOrScope?: NodeCreator<NodeRecord> | string, scope?: string): NodesWithUtils<Record<string, unknown>>;
3968
- /**
3969
- * Global rebuildNodes function for HMR integration.
3970
- * Invalidates cached nodes and increments _hmrVersion to trigger re-creation.
3971
- * Call this when HMR is detected to refresh all node creators.
3972
- *
3973
- * Resolves to the primary store so shared TSL resources rebuild on the
3974
- * authoritative store.
3975
- *
3976
- * @param store - The R3F store (from useStore or context)
3977
- * @param scope - Optional scope to rebuild ('root' for root only, string for specific scope, undefined for all)
3978
- */
3979
- declare function rebuildAllNodes(store: ReturnType<typeof useStore>, scope?: string): void;
3980
- /**
3981
- * Remove nodes by name from root level or a scope
3982
- * @deprecated Use `const { removeNodes } = useNodes()` instead
3983
- */
3984
- declare function removeNodes(set: ReturnType<typeof useStore>['setState'], names: string[], scope?: string): void;
3985
- /**
3986
- * Clear all nodes from a scope (removes the entire scope object)
3987
- * @deprecated Use `const { clearNodes } = useNodes()` instead
3988
- */
3989
- declare function clearNodeScope(set: ReturnType<typeof useStore>['setState'], scope: string): void;
3990
- /**
3991
- * Clear all root-level nodes (preserves scopes)
3992
- * @deprecated Use `const { clearNodes } = useNodes()` with `clearNodes('root')` instead
3993
- */
3994
- declare function clearRootNodes(set: ReturnType<typeof useStore>['setState']): void;
3995
-
3996
- /** Creator receives CreatorState with ScopedStore wrappers for type-safe access. Returns any record. */
3997
- type LocalNodeCreator<T extends Record<string, unknown>> = (state: CreatorState) => T;
3998
- /**
3999
- * Creates local values that rebuild when uniforms, nodes, or textures change.
4000
- *
4001
- * Unlike `useNodes`, this does NOT register to the global store.
4002
- * Use for component-specific nodes/values that depend on shared resources.
4003
- *
4004
- * @example
4005
- * ```tsx
4006
- * // Destructure what you need from state
4007
- * const { wobble, uTime } = useLocalNodes(({ uniforms, nodes }) => ({
4008
- * wobble: sin(uniforms.uTime.mul(2)),
4009
- * uTime: uniforms.uTime, // can return uniforms too
4010
- * }))
4011
- *
4012
- * // Or access anything else from RootState
4013
- * const { scaled } = useLocalNodes(({ camera, nodes }) => ({
4014
- * scaled: nodes.basePos.mul(camera.zoom),
4015
- * }))
4016
- *
4017
- * // Type-safe uniform access
4018
- * const { colorNode } = useLocalNodes(({ uniforms }) => {
4019
- * const uValue = uniforms.myUniform as UniformNode<number>
4020
- * return { colorNode: mix(colorA, colorB, uValue) }
4021
- * })
4022
- * ```
4023
- */
4024
- declare function useLocalNodes<T extends Record<string, unknown>>(creator: LocalNodeCreator<T>): T;
4025
-
4026
- /**
4027
- * A record of buffer-like values - allows mixed types (TypedArrays, BufferAttributes, TSL nodes)
4028
- */
4029
- type BufferRecordType<T extends BufferLike = BufferLike> = Record<string, T>;
4030
- /**
4031
- * Creator function that returns a record of buffers.
4032
- * Receives CreatorState with access to existing buffers, gpuStorage, uniforms, nodes, etc.
4033
- */
4034
- type BufferCreator<T extends Record<string, BufferLike>> = (state: CreatorState) => T;
4035
- /** Function signature for removeBuffers util */
4036
- type RemoveBuffersFn = (names: string | string[], scope?: string) => void;
4037
- /** Function signature for clearBuffers util */
4038
- type ClearBuffersFn = (scope?: string) => void;
4039
- /** Function signature for rebuildBuffers util */
4040
- type RebuildBuffersFn = (scope?: string) => void;
4041
- /** Function signature for disposeBuffers util - releases GPU resources */
4042
- type DisposeBuffersFn = (names: string | string[], scope?: string) => void;
4043
- /** Return type with utils included */
4044
- type BuffersWithUtils<T extends BufferRecordType | BufferStore = BufferRecordType> = T & {
4045
- removeBuffers: RemoveBuffersFn;
4046
- clearBuffers: ClearBuffersFn;
4047
- rebuildBuffers: RebuildBuffersFn;
4048
- disposeBuffers: DisposeBuffersFn;
4049
- };
4050
- declare function useBuffers(): BuffersWithUtils<BufferStore>;
4051
- declare function useBuffers(scope: string): BuffersWithUtils<Record<string, BufferLike>>;
4052
- declare function useBuffers<T extends Record<string, BufferLike>>(scope?: string): BuffersWithUtils<T>;
4053
- declare function useBuffers<T extends Record<string, BufferLike>>(creator: BufferCreator<T>): BuffersWithUtils<T>;
4054
- declare function useBuffers<T extends Record<string, BufferLike>>(creator: BufferCreator<T>, scope: string): BuffersWithUtils<T>;
4055
- /**
4056
- * Global rebuildBuffers function for HMR integration.
4057
- * Invalidates cached buffers and increments _hmrVersion to trigger re-creation.
4058
- * Call this when HMR is detected to refresh all buffer creators.
4059
- *
4060
- * Resolves to the primary store so shared TSL resources rebuild on the
4061
- * authoritative store.
4062
- *
4063
- * @param store - The R3F store (from useStore or context)
4064
- * @param scope - Optional scope to rebuild ('root' for root only, string for specific scope, undefined for all)
4065
- */
4066
- declare function rebuildAllBuffers(store: ReturnType<typeof useStore>, scope?: string): void;
4067
-
4068
- /**
4069
- * A record of storage-like values - allows mixed types (StorageTexture, Storage3DTexture, TSL nodes)
4070
- */
4071
- type StorageRecordType<T extends StorageLike = StorageLike> = Record<string, T>;
4072
- /**
4073
- * Creator function that returns a record of GPU storage objects.
4074
- * Receives CreatorState with access to existing buffers, gpuStorage, uniforms, nodes, etc.
4075
- */
4076
- type StorageCreator<T extends Record<string, StorageLike>> = (state: CreatorState) => T;
4077
- /** Function signature for removeStorage util */
4078
- type RemoveStorageFn = (names: string | string[], scope?: string) => void;
4079
- /** Function signature for clearStorage util */
4080
- type ClearStorageFn = (scope?: string) => void;
4081
- /** Function signature for rebuildStorage util */
4082
- type RebuildStorageFn = (scope?: string) => void;
4083
- /** Function signature for disposeStorage util - releases GPU resources */
4084
- type DisposeStorageFn = (names: string | string[], scope?: string) => void;
4085
- /** Return type with utils included */
4086
- type StorageWithUtils<T extends StorageRecordType | StorageStore = StorageRecordType> = T & {
4087
- removeStorage: RemoveStorageFn;
4088
- clearStorage: ClearStorageFn;
4089
- rebuildStorage: RebuildStorageFn;
4090
- disposeStorage: DisposeStorageFn;
4091
- };
4092
- declare function useGPUStorage(): StorageWithUtils<StorageStore>;
4093
- declare function useGPUStorage(scope: string): StorageWithUtils<Record<string, StorageLike>>;
4094
- declare function useGPUStorage<T extends Record<string, StorageLike>>(scope?: string): StorageWithUtils<T>;
4095
- declare function useGPUStorage<T extends Record<string, StorageLike>>(creator: StorageCreator<T>): StorageWithUtils<T>;
4096
- declare function useGPUStorage<T extends Record<string, StorageLike>>(creator: StorageCreator<T>, scope: string): StorageWithUtils<T>;
4097
- /**
4098
- * Global rebuildStorage function for HMR integration.
4099
- * Invalidates cached storage and increments _hmrVersion to trigger re-creation.
4100
- * Call this when HMR is detected to refresh all storage creators.
4101
- *
4102
- * Resolves to the primary store so shared TSL resources rebuild on the
4103
- * authoritative store.
4104
- *
4105
- * @param store - The R3F store (from useStore or context)
4106
- * @param scope - Optional scope to rebuild ('root' for root only, string for specific scope, undefined for all)
4107
- */
4108
- declare function rebuildAllStorage(store: ReturnType<typeof useStore>, scope?: string): void;
4109
86
 
4110
87
  /**
4111
88
  * Re-export from core - useTextures is now a core R3F hook (a reactive Texture registry).
@@ -4117,12 +94,12 @@ declare function rebuildAllStorage(store: ReturnType<typeof useStore>, scope?: s
4117
94
  * @deprecated The registry now stores plain `Texture` objects, not TSL nodes. Use `Texture` directly.
4118
95
  * Kept as an alias for backwards compatibility.
4119
96
  */
4120
- type TextureEntry = Texture$1;
97
+ type TextureEntry = Texture;
4121
98
  /**
4122
99
  * @deprecated The registry now stores plain `Texture` objects, not TSL nodes. Use `Texture` directly.
4123
100
  * Kept as an alias for backwards compatibility.
4124
101
  */
4125
- type TextureNode = Texture$1;
102
+ type TextureNode = Texture;
4126
103
 
4127
104
  interface TextureOperations {
4128
105
  add: (key: string, value: any) => void;
@@ -4132,49 +109,6 @@ interface TextureOperations {
4132
109
  }
4133
110
  declare function createTextureOperations(set: StoreApi<RootState>['setState']): TextureOperations;
4134
111
 
4135
- /**
4136
- * Hook for managing WebGPU RenderPipeline with automatic scenePass setup.
4137
- *
4138
- * Features:
4139
- * - Creates RenderPipeline instance if not exists
4140
- * - Creates default scenePass (no MRT) automatically
4141
- * - Callbacks receive full RootState for flexibility
4142
- * - No auto-cleanup on unmount - use reset() for explicit cleanup
4143
- * - Scene/camera changes trigger scenePass recreation
4144
- * - A replaced scenePass is disposed once the new graph is installed, so rebuild() does not
4145
- * strand its render target (and MRT attachments) on the GPU
4146
- * - Any run that changes the output node sets RenderPipeline.needsUpdate, so rebuild() actually
4147
- * recompiles instead of silently keeping the first compiled graph
4148
- *
4149
- * @param mainCB - Main callback to configure outputNode and create effect passes
4150
- * @param setupCB - Optional setup callback to configure MRT on scenePass
4151
- * @returns { passes, renderPipeline, clearPasses, reset, rebuild }
4152
- *
4153
- * @example
4154
- * ```tsx
4155
- * // Simple effect
4156
- * useRenderPipeline(({ renderPipeline, passes }) => {
4157
- * renderPipeline.outputNode = bloom(passes.scenePass.getTextureNode())
4158
- * })
4159
- *
4160
- * // With MRT setup
4161
- * useRenderPipeline(
4162
- * ({ renderPipeline, passes }) => {
4163
- * const beauty = passes.scenePass.getTextureNode().toInspector('Color')
4164
- * const vel = passes.scenePass.getTextureNode('velocity')
4165
- * renderPipeline.outputNode = motionBlur(beauty, vel)
4166
- * },
4167
- * ({ passes }) => {
4168
- * passes.scenePass.setMRT(mrt({ output, velocity }))
4169
- * }
4170
- * )
4171
- *
4172
- * // Read-only access
4173
- * const { renderPipeline, passes } = useRenderPipeline()
4174
- * ```
4175
- */
4176
- declare function useRenderPipeline(mainCB?: RenderPipelineMainCallback, setupCB?: RenderPipelineSetupCallback): UseRenderPipelineReturn;
4177
-
4178
112
  //* Renderer Props ========================================
4179
113
 
4180
114
  type WebGPUDefaultProps = Omit<WebGPURendererParameters, 'canvas'> & BaseRendererProps
@@ -4222,23 +156,23 @@ interface WebGPURootState extends Omit<RootState, 'renderer' | 'gl' | 'internal'
4222
156
  internal: WebGPUInternalState
4223
157
  }
4224
158
 
4225
- /**
4226
- * @fileoverview WebGPU entry point - WebGPU only, no legacy WebGL
4227
- *
4228
- * This entry point is for apps that want to use ONLY WebGPURenderer.
4229
- * Includes WebGPU-specific hooks (useUniforms, useNodes, useTextures).
4230
- * Auto-extends THREE with WebGPU node materials (MeshBasicNodeMaterial, etc.)
4231
- *
4232
- * Usage:
4233
- * import { Canvas, useFrame, useUniforms } from '@react-three/fiber/webgpu'
4234
- */
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>;
4235
163
 
4236
164
  /** `useThree` narrowed to WebGPU state — `state.renderer` is a `WebGPURenderer`. */
4237
165
  type UseThreeWebGPU = <T = WebGPURootState>(selector?: (state: WebGPURootState) => T, equalityFn?: <U>(state: U, newState: U) => boolean) => T;
4238
166
  /** `useFrame` narrowed to WebGPU state — the callback's `state.renderer` is a `WebGPURenderer`. */
4239
- type UseFrameWebGPU = (callback?: FrameCallback$1<WebGPURootState>, priorityOrOptions?: number | UseFrameNextOptions) => FrameNextControls;
167
+ type UseFrameWebGPU = (callback?: FrameCallback<WebGPURootState>, priorityOrOptions?: number | UseFrameNextOptions) => FrameNextControls;
4240
168
  declare const useThree: UseThreeWebGPU;
4241
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
+ };
4242
176
 
4243
177
  /** Canvas props on the WebGPU entry: `onCreated` receives `WebGPURootState`. */
4244
178
  type WebGPUCanvasProps = Omit<CanvasProps, 'onCreated'> & {
@@ -4246,8 +180,22 @@ type WebGPUCanvasProps = Omit<CanvasProps, 'onCreated'> & {
4246
180
  onCreated?: (state: WebGPURootState) => void;
4247
181
  };
4248
182
 
4249
- /** `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
+ */
4250
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
+ }
4251
199
 
4252
- 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 };
4253
- 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 };