@react-three/fiber 10.0.0-canary.9806389 → 10.0.0-canary.ab9effa

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