@react-three/fiber 10.0.0-canary.7dfc4e4 → 10.0.0-canary.975e1e7

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