@react-three/fiber 10.0.0-canary.dc0ec15 → 10.0.0-canary.e53bd54

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