@react-three/fiber 10.0.0-alpha.1 → 10.0.0-canary.0706a92

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.
package/dist/legacy.mjs CHANGED
@@ -1,12 +1,20 @@
1
1
  import * as three from 'three';
2
- import { WebGLRenderTarget, Frustum, Matrix4, Group, BoxGeometry, MeshBasicNodeMaterial, Mesh, Node, NodeUpdateType, Layers, RGBAFormat, UnsignedByteType, Vector3, Vector2, TextureLoader, Texture as Texture$1, SRGBColorSpace, Raycaster, OrthographicCamera, PerspectiveCamera, Scene, PCFSoftShadowMap, VSMShadowMap, PCFShadowMap, BasicShadowMap, ColorManagement, LinearSRGBColorSpace, NoToneMapping, ACESFilmicToneMapping, WebGLRenderer } from 'three';
3
- import { jsx, Fragment } from 'react/jsx-runtime';
2
+ import { WebGLRenderTarget, CubeReflectionMapping, EquirectangularReflectionMapping, CubeTextureLoader, Scene, WebGLCubeRenderTarget, HalfFloatType, Color, Frustum, Matrix4, Group, BoxGeometry, MeshBasicNodeMaterial, Mesh, Node, NodeUpdateType, Layers, ShaderMaterial, Uniform, SRGBColorSpace, RGBAFormat, UnsignedByteType, Vector3, Vector2, TextureLoader, Texture as Texture$1, Raycaster, OrthographicCamera, PerspectiveCamera, PCFShadowMap, VSMShadowMap, BasicShadowMap, ACESFilmicToneMapping, WebGLRenderer } from 'three';
3
+ import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
4
4
  import * as React from 'react';
5
- import React__default, { useMemo, useLayoutEffect, useEffect, useContext, useRef, useImperativeHandle, useCallback, useState } from 'react';
5
+ import React__default, { useLayoutEffect, useRef, useMemo, useEffect, useContext, useImperativeHandle, useCallback, useState } from 'react';
6
6
  import useMeasure from 'react-use-measure';
7
7
  import { useFiber, useContextBridge, traverseFiber, FiberProvider } from 'its-fine';
8
+ import { useThree as useThree$1, useLoader as useLoader$1, useFrame as useFrame$1, createPortal as createPortal$1, applyProps as applyProps$1, extend as extend$1 } from '@react-three/fiber';
9
+ import { GroundedSkybox } from 'three/examples/jsm/objects/GroundedSkybox.js';
10
+ import { HDRLoader } from 'three/examples/jsm/loaders/HDRLoader.js';
11
+ import { EXRLoader } from 'three/examples/jsm/loaders/EXRLoader.js';
12
+ import { UltraHDRLoader } from 'three/examples/jsm/loaders/UltraHDRLoader.js';
13
+ import { GainMapLoader } from '@monogrid/gainmap-js';
8
14
  import Tb, { unstable_scheduleCallback, unstable_IdlePriority } from 'scheduler';
9
15
  import { createWithEqualityFn } from 'zustand/traditional';
16
+ import { getScheduler } from '@pmndrs/scheduler';
17
+ export { Scheduler, getScheduler } from '@pmndrs/scheduler';
10
18
  import { suspend, preload, clear } from 'suspend-react';
11
19
 
12
20
  function _mergeNamespaces(n, m) {
@@ -45,9 +53,392 @@ const THREE = /*#__PURE__*/_mergeNamespaces({
45
53
  WebGPURenderer: WebGPURenderer
46
54
  }, [three]);
47
55
 
48
- var __defProp$2 = Object.defineProperty;
49
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
50
- var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
56
+ const primaryRegistry = /* @__PURE__ */ new Map();
57
+ const pendingSubscribers = /* @__PURE__ */ new Map();
58
+ function registerPrimary(id, renderer, store) {
59
+ if (primaryRegistry.has(id)) {
60
+ console.warn(`Canvas with id="${id}" already registered. Overwriting.`);
61
+ }
62
+ const entry = { renderer, store };
63
+ primaryRegistry.set(id, entry);
64
+ const subscribers = pendingSubscribers.get(id);
65
+ if (subscribers) {
66
+ subscribers.forEach((callback) => callback(entry));
67
+ pendingSubscribers.delete(id);
68
+ }
69
+ return () => {
70
+ const currentEntry = primaryRegistry.get(id);
71
+ if (currentEntry?.renderer === renderer) {
72
+ primaryRegistry.delete(id);
73
+ }
74
+ };
75
+ }
76
+ function getPrimary(id) {
77
+ return primaryRegistry.get(id);
78
+ }
79
+ function waitForPrimary(id, timeout = 5e3) {
80
+ const existing = primaryRegistry.get(id);
81
+ if (existing) {
82
+ return Promise.resolve(existing);
83
+ }
84
+ return new Promise((resolve, reject) => {
85
+ const timeoutId = setTimeout(() => {
86
+ const subscribers = pendingSubscribers.get(id);
87
+ if (subscribers) {
88
+ const index = subscribers.indexOf(callback);
89
+ if (index !== -1) subscribers.splice(index, 1);
90
+ if (subscribers.length === 0) pendingSubscribers.delete(id);
91
+ }
92
+ reject(new Error(`Timeout waiting for canvas with id="${id}". Make sure a <Canvas id="${id}"> is mounted.`));
93
+ }, timeout);
94
+ const callback = (entry) => {
95
+ clearTimeout(timeoutId);
96
+ resolve(entry);
97
+ };
98
+ if (!pendingSubscribers.has(id)) {
99
+ pendingSubscribers.set(id, []);
100
+ }
101
+ pendingSubscribers.get(id).push(callback);
102
+ });
103
+ }
104
+ function hasPrimary(id) {
105
+ return primaryRegistry.has(id);
106
+ }
107
+ function unregisterPrimary(id) {
108
+ primaryRegistry.delete(id);
109
+ }
110
+ function getPrimaryIds() {
111
+ return Array.from(primaryRegistry.keys());
112
+ }
113
+
114
+ const presetsObj = {
115
+ apartment: "lebombo_1k.hdr",
116
+ city: "potsdamer_platz_1k.hdr",
117
+ dawn: "kiara_1_dawn_1k.hdr",
118
+ forest: "forest_slope_1k.hdr",
119
+ lobby: "st_fagans_interior_1k.hdr",
120
+ night: "dikhololo_night_1k.hdr",
121
+ park: "rooitou_park_1k.hdr",
122
+ studio: "studio_small_03_1k.hdr",
123
+ sunset: "venice_sunset_1k.hdr",
124
+ warehouse: "empty_warehouse_01_1k.hdr"
125
+ };
126
+
127
+ const CUBEMAP_ROOT = "https://raw.githack.com/pmndrs/drei-assets/456060a26bbeb8fdf79326f224b6d99b8bcce736/hdri/";
128
+ const isArray = (arr) => Array.isArray(arr);
129
+ const defaultFiles = ["/px.png", "/nx.png", "/py.png", "/ny.png", "/pz.png", "/nz.png"];
130
+ function useEnvironment({
131
+ files = defaultFiles,
132
+ path = "",
133
+ preset = void 0,
134
+ colorSpace = void 0,
135
+ extensions
136
+ } = {}) {
137
+ if (preset) {
138
+ validatePreset(preset);
139
+ files = presetsObj[preset];
140
+ path = CUBEMAP_ROOT;
141
+ }
142
+ const multiFile = isArray(files);
143
+ const { extension, isCubemap } = getExtension(files);
144
+ const loader = getLoader$1(extension);
145
+ if (!loader) throw new Error("useEnvironment: Unrecognized file extension: " + files);
146
+ const renderer = useThree$1((state) => state.renderer);
147
+ useLayoutEffect(() => {
148
+ if (extension !== "webp" && extension !== "jpg" && extension !== "jpeg") return;
149
+ function clearGainmapTexture() {
150
+ useLoader$1.clear(loader, multiFile ? [files] : files);
151
+ }
152
+ renderer.domElement.addEventListener("webglcontextlost", clearGainmapTexture, { once: true });
153
+ }, [extension, files, loader, multiFile, renderer.domElement]);
154
+ const loaderResult = useLoader$1(
155
+ loader,
156
+ multiFile ? [files] : files,
157
+ (loader2) => {
158
+ if (extension === "webp" || extension === "jpg" || extension === "jpeg") {
159
+ loader2.setRenderer?.(renderer);
160
+ }
161
+ loader2.setPath?.(path);
162
+ if (extensions) extensions(loader2);
163
+ }
164
+ );
165
+ let texture = multiFile ? (
166
+ // @ts-ignore
167
+ loaderResult[0]
168
+ ) : loaderResult;
169
+ if (extension === "jpg" || extension === "jpeg" || extension === "webp") {
170
+ texture = texture.renderTarget?.texture;
171
+ }
172
+ texture.mapping = isCubemap ? CubeReflectionMapping : EquirectangularReflectionMapping;
173
+ texture.colorSpace = colorSpace ?? (isCubemap ? "srgb" : "srgb-linear");
174
+ return texture;
175
+ }
176
+ const preloadDefaultOptions = {
177
+ files: defaultFiles,
178
+ path: "",
179
+ preset: void 0,
180
+ extensions: void 0
181
+ };
182
+ useEnvironment.preload = (preloadOptions) => {
183
+ const options = { ...preloadDefaultOptions, ...preloadOptions };
184
+ let { files, path = "" } = options;
185
+ const { preset, extensions } = options;
186
+ if (preset) {
187
+ validatePreset(preset);
188
+ files = presetsObj[preset];
189
+ path = CUBEMAP_ROOT;
190
+ }
191
+ const { extension } = getExtension(files);
192
+ if (extension === "webp" || extension === "jpg" || extension === "jpeg") {
193
+ throw new Error("useEnvironment: Preloading gainmaps is not supported");
194
+ }
195
+ const loader = getLoader$1(extension);
196
+ if (!loader) throw new Error("useEnvironment: Unrecognized file extension: " + files);
197
+ useLoader$1.preload(loader, isArray(files) ? [files] : files, (loader2) => {
198
+ loader2.setPath?.(path);
199
+ if (extensions) extensions(loader2);
200
+ });
201
+ };
202
+ const clearDefaultOptins = {
203
+ files: defaultFiles,
204
+ preset: void 0
205
+ };
206
+ useEnvironment.clear = (clearOptions) => {
207
+ const options = { ...clearDefaultOptins, ...clearOptions };
208
+ let { files } = options;
209
+ const { preset } = options;
210
+ if (preset) {
211
+ validatePreset(preset);
212
+ files = presetsObj[preset];
213
+ }
214
+ const { extension } = getExtension(files);
215
+ const loader = getLoader$1(extension);
216
+ if (!loader) throw new Error("useEnvironment: Unrecognized file extension: " + files);
217
+ useLoader$1.clear(loader, isArray(files) ? [files] : files);
218
+ };
219
+ function validatePreset(preset) {
220
+ if (!(preset in presetsObj)) throw new Error("Preset must be one of: " + Object.keys(presetsObj).join(", "));
221
+ }
222
+ function getExtension(files) {
223
+ const isCubemap = isArray(files) && files.length === 6;
224
+ const isGainmap = isArray(files) && files.length === 3 && files.some((file) => file.endsWith("json"));
225
+ const firstEntry = isArray(files) ? files[0] : files;
226
+ const extension = isCubemap ? "cube" : isGainmap ? "webp" : firstEntry.startsWith("data:application/exr") ? "exr" : firstEntry.startsWith("data:application/hdr") ? "hdr" : firstEntry.startsWith("data:image/jpeg") ? "jpg" : firstEntry.split(".").pop()?.split("?")?.shift()?.toLowerCase();
227
+ return { extension, isCubemap, isGainmap };
228
+ }
229
+ function getLoader$1(extension) {
230
+ const loader = extension === "cube" ? CubeTextureLoader : extension === "hdr" ? HDRLoader : extension === "exr" ? EXRLoader : extension === "jpg" || extension === "jpeg" ? UltraHDRLoader : extension === "webp" ? GainMapLoader : null;
231
+ return loader;
232
+ }
233
+
234
+ const isRef$1 = (obj) => obj.current && obj.current.isScene;
235
+ const resolveScene = (scene) => isRef$1(scene) ? scene.current : scene;
236
+ function setEnvProps(background, scene, defaultScene, texture, sceneProps = {}) {
237
+ sceneProps = {
238
+ backgroundBlurriness: 0,
239
+ backgroundIntensity: 1,
240
+ backgroundRotation: [0, 0, 0],
241
+ environmentIntensity: 1,
242
+ environmentRotation: [0, 0, 0],
243
+ ...sceneProps
244
+ };
245
+ const target = resolveScene(scene || defaultScene);
246
+ const oldbg = target.background;
247
+ const oldenv = target.environment;
248
+ const oldSceneProps = {
249
+ // @ts-ignore
250
+ backgroundBlurriness: target.backgroundBlurriness,
251
+ // @ts-ignore
252
+ backgroundIntensity: target.backgroundIntensity,
253
+ // @ts-ignore
254
+ backgroundRotation: target.backgroundRotation?.clone?.() ?? [0, 0, 0],
255
+ // @ts-ignore
256
+ environmentIntensity: target.environmentIntensity,
257
+ // @ts-ignore
258
+ environmentRotation: target.environmentRotation?.clone?.() ?? [0, 0, 0]
259
+ };
260
+ if (background !== "only") target.environment = texture;
261
+ if (background) target.background = texture;
262
+ applyProps$1(target, sceneProps);
263
+ return () => {
264
+ if (background !== "only") target.environment = oldenv;
265
+ if (background) target.background = oldbg;
266
+ applyProps$1(target, oldSceneProps);
267
+ };
268
+ }
269
+ function EnvironmentMap({ scene, background = false, map, ...config }) {
270
+ const defaultScene = useThree$1((state) => state.scene);
271
+ React.useLayoutEffect(() => {
272
+ if (map) return setEnvProps(background, scene, defaultScene, map, config);
273
+ });
274
+ return null;
275
+ }
276
+ function EnvironmentCube({
277
+ background = false,
278
+ scene,
279
+ blur,
280
+ backgroundBlurriness,
281
+ backgroundIntensity,
282
+ backgroundRotation,
283
+ environmentIntensity,
284
+ environmentRotation,
285
+ ...rest
286
+ }) {
287
+ const texture = useEnvironment(rest);
288
+ const defaultScene = useThree$1((state) => state.scene);
289
+ React.useLayoutEffect(() => {
290
+ return setEnvProps(background, scene, defaultScene, texture, {
291
+ backgroundBlurriness: blur ?? backgroundBlurriness,
292
+ backgroundIntensity,
293
+ backgroundRotation,
294
+ environmentIntensity,
295
+ environmentRotation
296
+ });
297
+ });
298
+ React.useEffect(() => {
299
+ return () => {
300
+ texture.dispose();
301
+ };
302
+ }, [texture]);
303
+ return null;
304
+ }
305
+ function EnvironmentPortal({
306
+ children,
307
+ near = 0.1,
308
+ far = 1e3,
309
+ resolution = 256,
310
+ frames = 1,
311
+ map,
312
+ background = false,
313
+ blur,
314
+ backgroundBlurriness,
315
+ backgroundIntensity,
316
+ backgroundRotation,
317
+ environmentIntensity,
318
+ environmentRotation,
319
+ scene,
320
+ files,
321
+ path,
322
+ preset = void 0,
323
+ extensions
324
+ }) {
325
+ const gl = useThree$1((state) => state.gl);
326
+ const defaultScene = useThree$1((state) => state.scene);
327
+ const camera = React.useRef(null);
328
+ const [virtualScene] = React.useState(() => new Scene());
329
+ const fbo = React.useMemo(() => {
330
+ const fbo2 = new WebGLCubeRenderTarget(resolution);
331
+ fbo2.texture.type = HalfFloatType;
332
+ return fbo2;
333
+ }, [resolution]);
334
+ React.useEffect(() => {
335
+ return () => {
336
+ fbo.dispose();
337
+ };
338
+ }, [fbo]);
339
+ React.useLayoutEffect(() => {
340
+ if (frames === 1) {
341
+ const autoClear = gl.autoClear;
342
+ gl.autoClear = true;
343
+ camera.current.update(gl, virtualScene);
344
+ gl.autoClear = autoClear;
345
+ }
346
+ return setEnvProps(background, scene, defaultScene, fbo.texture, {
347
+ backgroundBlurriness: blur ?? backgroundBlurriness,
348
+ backgroundIntensity,
349
+ backgroundRotation,
350
+ environmentIntensity,
351
+ environmentRotation
352
+ });
353
+ }, [
354
+ children,
355
+ virtualScene,
356
+ fbo.texture,
357
+ scene,
358
+ defaultScene,
359
+ background,
360
+ frames,
361
+ gl,
362
+ blur,
363
+ backgroundBlurriness,
364
+ backgroundIntensity,
365
+ backgroundRotation,
366
+ environmentIntensity,
367
+ environmentRotation
368
+ ]);
369
+ let count = 1;
370
+ useFrame$1(() => {
371
+ if (frames === Infinity || count < frames) {
372
+ const autoClear = gl.autoClear;
373
+ gl.autoClear = true;
374
+ camera.current.update(gl, virtualScene);
375
+ gl.autoClear = autoClear;
376
+ count++;
377
+ }
378
+ });
379
+ return /* @__PURE__ */ jsx(Fragment, { children: createPortal$1(
380
+ /* @__PURE__ */ jsxs(Fragment, { children: [
381
+ children,
382
+ /* @__PURE__ */ jsx("cubeCamera", { ref: camera, args: [near, far, fbo] }),
383
+ files || preset ? /* @__PURE__ */ jsx(EnvironmentCube, { background: true, files, preset, path, extensions }) : map ? /* @__PURE__ */ jsx(EnvironmentMap, { background: true, map, extensions }) : null
384
+ ] }),
385
+ virtualScene
386
+ ) });
387
+ }
388
+ function EnvironmentGround(props) {
389
+ const textureDefault = useEnvironment(props);
390
+ const texture = props.map || textureDefault;
391
+ React.useMemo(() => extend$1({ GroundProjectedEnvImpl: GroundedSkybox }), []);
392
+ React.useEffect(() => {
393
+ return () => {
394
+ textureDefault.dispose();
395
+ };
396
+ }, [textureDefault]);
397
+ const height = props.ground?.height ?? 15;
398
+ const radius = props.ground?.radius ?? 60;
399
+ const scale = props.ground?.scale ?? 1e3;
400
+ const args = React.useMemo(
401
+ () => [texture, height, radius],
402
+ [texture, height, radius]
403
+ );
404
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
405
+ /* @__PURE__ */ jsx(EnvironmentMap, { ...props, map: texture }),
406
+ /* @__PURE__ */ jsx("groundProjectedEnvImpl", { args, scale })
407
+ ] });
408
+ }
409
+ function EnvironmentColor({ color, scene }) {
410
+ const defaultScene = useThree$1((state) => state.scene);
411
+ React.useLayoutEffect(() => {
412
+ if (color === void 0) return;
413
+ const target = resolveScene(scene || defaultScene);
414
+ const oldBg = target.background;
415
+ target.background = new Color(color);
416
+ return () => {
417
+ target.background = oldBg;
418
+ };
419
+ });
420
+ return null;
421
+ }
422
+ function EnvironmentDualSource(props) {
423
+ const { backgroundFiles, ...envProps } = props;
424
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
425
+ /* @__PURE__ */ jsx(EnvironmentCube, { ...envProps, background: false }),
426
+ /* @__PURE__ */ jsx(EnvironmentCube, { ...props, files: backgroundFiles, background: "only" })
427
+ ] });
428
+ }
429
+ function Environment(props) {
430
+ if (props.color && !props.files && !props.preset && !props.map) {
431
+ return /* @__PURE__ */ jsx(EnvironmentColor, { ...props });
432
+ }
433
+ if (props.backgroundFiles && props.backgroundFiles !== props.files) {
434
+ return /* @__PURE__ */ jsx(EnvironmentDualSource, { ...props });
435
+ }
436
+ return props.ground ? /* @__PURE__ */ jsx(EnvironmentGround, { ...props }) : props.map ? /* @__PURE__ */ jsx(EnvironmentMap, { ...props }) : props.children ? /* @__PURE__ */ jsx(EnvironmentPortal, { ...props }) : /* @__PURE__ */ jsx(EnvironmentCube, { ...props });
437
+ }
438
+
439
+ var __defProp = Object.defineProperty;
440
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
441
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
51
442
  const act = React["act"];
52
443
  const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React.useLayoutEffect : React.useEffect;
53
444
  function useMutableCallback(fn) {
@@ -79,7 +470,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
79
470
  return _a = class extends React.Component {
80
471
  constructor() {
81
472
  super(...arguments);
82
- __publicField$2(this, "state", { error: false });
473
+ __publicField(this, "state", { error: false });
83
474
  }
84
475
  componentDidCatch(err) {
85
476
  this.props.set(err);
@@ -87,7 +478,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
87
478
  render() {
88
479
  return this.state.error ? null : this.props.children;
89
480
  }
90
- }, __publicField$2(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
481
+ }, __publicField(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
91
482
  })();
92
483
 
93
484
  const is = {
@@ -273,7 +664,7 @@ function createOcclusionObserverNode(store, uniform) {
273
664
  let occlusionSetupPromise = null;
274
665
  function enableOcclusion(store) {
275
666
  const state = store.getState();
276
- const { internal, renderer, rootScene } = state;
667
+ const { internal, renderer } = state;
277
668
  if (internal.occlusionEnabled || occlusionSetupPromise) return;
278
669
  const hasOcclusionSupport = typeof renderer?.isOccluded === "function";
279
670
  if (!hasOcclusionSupport) {
@@ -381,6 +772,17 @@ function unregisterVisibility(store, object) {
381
772
  internal.visibilityRegistry.delete(object.uuid);
382
773
  internal.occlusionCache.delete(object);
383
774
  }
775
+ function updateVisibilityHandlers(store, object, handlers) {
776
+ const { internal } = store.getState();
777
+ const entry = internal.visibilityRegistry.get(object.uuid);
778
+ if (!entry) return false;
779
+ entry.handlers = handlers;
780
+ if ((handlers.onOccluded || handlers.onVisible) && !internal.occlusionEnabled) {
781
+ object.occlusionTest = true;
782
+ enableOcclusion(store);
783
+ }
784
+ return true;
785
+ }
384
786
  function checkVisibility(state) {
385
787
  const { internal, camera } = state;
386
788
  const registry = internal.visibilityRegistry;
@@ -436,6 +838,22 @@ function hasVisibilityHandlers(handlers) {
436
838
  return !!(handlers.onFramed || handlers.onOccluded || handlers.onVisible);
437
839
  }
438
840
 
841
+ const FROM_REF = Symbol.for("@react-three/fiber.fromRef");
842
+ function fromRef(ref) {
843
+ return { [FROM_REF]: ref };
844
+ }
845
+ function isFromRef(value) {
846
+ return value !== null && typeof value === "object" && FROM_REF in value;
847
+ }
848
+
849
+ const ONCE = Symbol.for("@react-three/fiber.once");
850
+ function once(...args) {
851
+ return { [ONCE]: args.length ? args : true };
852
+ }
853
+ function isOnce(value) {
854
+ return value !== null && typeof value === "object" && ONCE in value;
855
+ }
856
+
439
857
  const RESERVED_PROPS = [
440
858
  "children",
441
859
  "key",
@@ -506,7 +924,7 @@ function getMemoizedPrototype(root) {
506
924
  ctor = new root.constructor();
507
925
  MEMOIZED_PROTOTYPES.set(root.constructor, ctor);
508
926
  }
509
- } catch (e) {
927
+ } catch {
510
928
  }
511
929
  return ctor;
512
930
  }
@@ -537,7 +955,7 @@ function applyProps(object, props) {
537
955
  const rootState = instance && findInitialRoot(instance).getState();
538
956
  const prevHandlers = instance?.eventCount;
539
957
  for (const prop in props) {
540
- let value = props[prop];
958
+ const value = props[prop];
541
959
  if (RESERVED_PROPS.includes(prop)) continue;
542
960
  if (instance && EVENT_REGEX.test(prop)) {
543
961
  if (typeof value === "function") instance.handlers[prop] = value;
@@ -552,6 +970,22 @@ function applyProps(object, props) {
552
970
  continue;
553
971
  }
554
972
  if (value === void 0) continue;
973
+ if (isFromRef(value)) continue;
974
+ if (isOnce(value)) {
975
+ if (instance?.appliedOnce?.has(prop)) continue;
976
+ if (instance) {
977
+ instance.appliedOnce ?? (instance.appliedOnce = /* @__PURE__ */ new Set());
978
+ instance.appliedOnce.add(prop);
979
+ }
980
+ const { root: targetRoot, key: targetKey } = resolve(object, prop);
981
+ const args = value[ONCE];
982
+ if (typeof targetRoot[targetKey] === "function") {
983
+ targetRoot[targetKey](...args === true ? [] : args);
984
+ } else if (args !== true && args.length > 0) {
985
+ targetRoot[targetKey] = args[0];
986
+ }
987
+ continue;
988
+ }
555
989
  let { root, key, target } = resolve(object, prop);
556
990
  if (target === void 0 && (typeof root !== "object" || root === null)) {
557
991
  throw Error(`R3F: Cannot set "${prop}". Ensure it is an object before setting "${key}".`);
@@ -572,9 +1006,25 @@ function applyProps(object, props) {
572
1006
  } else if (isVectorLike(target) && is.num(value)) {
573
1007
  if ("setScalar" in target && typeof target.setScalar === "function") target.setScalar(value);
574
1008
  else target.set(value);
1009
+ } else if (root instanceof ShaderMaterial && key === "uniforms" && is.obj(value)) {
1010
+ if (!is.obj(root.uniforms)) root.uniforms = {};
1011
+ const uniforms = root.uniforms;
1012
+ const nextUniforms = value;
1013
+ for (const name in nextUniforms) {
1014
+ const uniform = nextUniforms[name];
1015
+ const targetUniform = uniforms[name];
1016
+ if (targetUniform) Object.assign(targetUniform, uniform);
1017
+ else {
1018
+ const nextUniform = uniform instanceof Uniform ? uniform.clone() : new Uniform(uniform.value);
1019
+ uniforms[name] = nextUniform;
1020
+ }
1021
+ }
575
1022
  } else {
576
1023
  root[key] = value;
577
- if (rootState && !rootState.linear && colorMaps.includes(key) && isTexture(value) && root[key]?.isTexture && // sRGB textures must be RGBA8 since r137 https://github.com/mrdoob/three.js/pull/23129
1024
+ if (key.endsWith("Node") && root.isMaterial) {
1025
+ root.needsUpdate = true;
1026
+ }
1027
+ if (rootState && rootState.renderer?.outputColorSpace === SRGBColorSpace && colorMaps.includes(key) && isTexture(value) && root[key]?.isTexture && // sRGB textures must be RGBA8 since r137 https://github.com/mrdoob/three.js/pull/23129
578
1028
  root[key].format === RGBAFormat && root[key].type === UnsignedByteType) {
579
1029
  root[key].colorSpace = rootState.textureColorSpace;
580
1030
  }
@@ -587,6 +1037,9 @@ function applyProps(object, props) {
587
1037
  if (instance.eventCount && object2.raycast !== null) {
588
1038
  rootState.internal.interaction.push(object2);
589
1039
  }
1040
+ }
1041
+ if (instance?.parent && rootState?.internal && instance.object?.isObject3D) {
1042
+ const object2 = instance.object;
590
1043
  const root = findInitialRoot(instance);
591
1044
  const visibilityHandlers = {
592
1045
  onFramed: instance.handlers.onFramed,
@@ -594,7 +1047,9 @@ function applyProps(object, props) {
594
1047
  onVisible: instance.handlers.onVisible
595
1048
  };
596
1049
  if (hasVisibilityHandlers(visibilityHandlers)) {
597
- registerVisibility(root, object2, visibilityHandlers);
1050
+ if (!updateVisibilityHandlers(root, object2, visibilityHandlers)) {
1051
+ registerVisibility(root, object2, visibilityHandlers);
1052
+ }
598
1053
  } else {
599
1054
  unregisterVisibility(root, object2);
600
1055
  }
@@ -607,38 +1062,60 @@ function applyProps(object, props) {
607
1062
  return object;
608
1063
  }
609
1064
 
1065
+ const DEFAULT_POINTER_ID = 0;
1066
+ const XR_POINTER_ID_START = 1e3;
1067
+ function getPointerState(internal, pointerId) {
1068
+ let state = internal.pointerMap.get(pointerId);
1069
+ if (!state) {
1070
+ state = {
1071
+ hovered: /* @__PURE__ */ new Map(),
1072
+ captured: /* @__PURE__ */ new Map(),
1073
+ initialClick: [0, 0],
1074
+ initialHits: []
1075
+ };
1076
+ internal.pointerMap.set(pointerId, state);
1077
+ }
1078
+ return state;
1079
+ }
1080
+ function getPointerId(event) {
1081
+ return "pointerId" in event ? event.pointerId : DEFAULT_POINTER_ID;
1082
+ }
610
1083
  function makeId(event) {
611
1084
  return (event.eventObject || event.object).uuid + "/" + event.index + event.instanceId;
612
1085
  }
613
- function releaseInternalPointerCapture(capturedMap, obj, captures, pointerId) {
614
- const captureData = captures.get(obj);
1086
+ function releaseInternalPointerCapture(internal, obj, pointerId) {
1087
+ const pointerState = internal.pointerMap.get(pointerId);
1088
+ if (!pointerState) return;
1089
+ const captureData = pointerState.captured.get(obj);
615
1090
  if (captureData) {
616
- captures.delete(obj);
617
- if (captures.size === 0) {
618
- capturedMap.delete(pointerId);
619
- captureData.target.releasePointerCapture(pointerId);
620
- }
1091
+ pointerState.captured.delete(obj);
1092
+ captureData.target.releasePointerCapture(pointerId);
621
1093
  }
622
1094
  }
623
1095
  function removeInteractivity(store, object) {
624
1096
  const { internal } = store.getState();
625
1097
  internal.interaction = internal.interaction.filter((o) => o !== object);
626
- internal.initialHits = internal.initialHits.filter((o) => o !== object);
627
- internal.hovered.forEach((value, key) => {
628
- if (value.eventObject === object || value.object === object) {
629
- internal.hovered.delete(key);
1098
+ for (const [pointerId, pointerState] of internal.pointerMap) {
1099
+ pointerState.initialHits = pointerState.initialHits.filter((o) => o !== object);
1100
+ pointerState.hovered.forEach((value, key) => {
1101
+ if (value.eventObject === object || value.object === object) {
1102
+ pointerState.hovered.delete(key);
1103
+ }
1104
+ });
1105
+ if (pointerState.captured.has(object)) {
1106
+ releaseInternalPointerCapture(internal, object, pointerId);
630
1107
  }
631
- });
632
- internal.capturedMap.forEach((captures, pointerId) => {
633
- releaseInternalPointerCapture(internal.capturedMap, object, captures, pointerId);
634
- });
1108
+ }
635
1109
  unregisterVisibility(store, object);
636
1110
  }
637
1111
  function createEvents(store) {
638
- function calculateDistance(event) {
1112
+ function calculateDistance(event, pointerId) {
639
1113
  const { internal } = store.getState();
640
- const dx = event.offsetX - internal.initialClick[0];
641
- const dy = event.offsetY - internal.initialClick[1];
1114
+ const pointerState = internal.pointerMap.get(pointerId);
1115
+ if (!pointerState) return 0;
1116
+ const [initialX, initialY] = pointerState.initialClick;
1117
+ const dx = event.offsetX - initialX;
1118
+ const dy = event.offsetY - initialY;
642
1119
  return Math.round(Math.sqrt(dx * dx + dy * dy));
643
1120
  }
644
1121
  function filterPointerEvents(objects) {
@@ -674,6 +1151,15 @@ function createEvents(store) {
674
1151
  return state2.raycaster.camera ? state2.raycaster.intersectObject(obj, true) : [];
675
1152
  }
676
1153
  let hits = eventsObjects.flatMap(handleRaycast).sort((a, b) => {
1154
+ const aInteractivePriority = a.object.userData?.interactivePriority;
1155
+ const bInteractivePriority = b.object.userData?.interactivePriority;
1156
+ if (aInteractivePriority !== void 0 || bInteractivePriority !== void 0) {
1157
+ if (aInteractivePriority !== void 0 && bInteractivePriority === void 0) return -1;
1158
+ if (bInteractivePriority !== void 0 && aInteractivePriority === void 0) return 1;
1159
+ if (aInteractivePriority !== bInteractivePriority) {
1160
+ return (bInteractivePriority ?? 0) - (aInteractivePriority ?? 0);
1161
+ }
1162
+ }
677
1163
  const aState = getRootState(a.object);
678
1164
  const bState = getRootState(b.object);
679
1165
  const aPriority = aState?.events?.priority ?? 1;
@@ -689,14 +1175,19 @@ function createEvents(store) {
689
1175
  for (const hit of hits) {
690
1176
  let eventObject = hit.object;
691
1177
  while (eventObject) {
692
- if (eventObject.__r3f?.eventCount)
1178
+ if (eventObject.__r3f?.eventCount) {
693
1179
  intersections.push({ ...hit, eventObject });
1180
+ }
694
1181
  eventObject = eventObject.parent;
695
1182
  }
696
1183
  }
697
- if ("pointerId" in event && state.internal.capturedMap.has(event.pointerId)) {
698
- for (let captureData of state.internal.capturedMap.get(event.pointerId).values()) {
699
- if (!duplicates.has(makeId(captureData.intersection))) intersections.push(captureData.intersection);
1184
+ if ("pointerId" in event) {
1185
+ const pointerId = event.pointerId;
1186
+ const pointerState = state.internal.pointerMap.get(pointerId);
1187
+ if (pointerState?.captured.size) {
1188
+ for (const captureData of pointerState.captured.values()) {
1189
+ if (!duplicates.has(makeId(captureData.intersection))) intersections.push(captureData.intersection);
1190
+ }
700
1191
  }
701
1192
  }
702
1193
  return intersections;
@@ -709,28 +1200,26 @@ function createEvents(store) {
709
1200
  if (state) {
710
1201
  const { raycaster, pointer, camera, internal } = state;
711
1202
  const unprojectedPoint = new Vector3(pointer.x, pointer.y, 0).unproject(camera);
712
- const hasPointerCapture = (id) => internal.capturedMap.get(id)?.has(hit.eventObject) ?? false;
1203
+ const hasPointerCapture = (id) => {
1204
+ const pointerState = internal.pointerMap.get(id);
1205
+ return pointerState?.captured.has(hit.eventObject) ?? false;
1206
+ };
713
1207
  const setPointerCapture = (id) => {
714
1208
  const captureData = { intersection: hit, target: event.target };
715
- if (internal.capturedMap.has(id)) {
716
- internal.capturedMap.get(id).set(hit.eventObject, captureData);
717
- } else {
718
- internal.capturedMap.set(id, /* @__PURE__ */ new Map([[hit.eventObject, captureData]]));
719
- }
1209
+ const pointerState = getPointerState(internal, id);
1210
+ pointerState.captured.set(hit.eventObject, captureData);
720
1211
  event.target.setPointerCapture(id);
721
1212
  };
722
1213
  const releasePointerCapture = (id) => {
723
- const captures = internal.capturedMap.get(id);
724
- if (captures) {
725
- releaseInternalPointerCapture(internal.capturedMap, hit.eventObject, captures, id);
726
- }
1214
+ releaseInternalPointerCapture(internal, hit.eventObject, id);
727
1215
  };
728
- let extractEventProps = {};
729
- for (let prop in event) {
730
- let property = event[prop];
1216
+ const extractEventProps = {};
1217
+ for (const prop in event) {
1218
+ const property = event[prop];
731
1219
  if (typeof property !== "function") extractEventProps[prop] = property;
732
1220
  }
733
- let raycastEvent = {
1221
+ const eventPointerId = "pointerId" in event ? event.pointerId : void 0;
1222
+ const raycastEvent = {
734
1223
  ...hit,
735
1224
  ...extractEventProps,
736
1225
  pointer,
@@ -740,18 +1229,19 @@ function createEvents(store) {
740
1229
  unprojectedPoint,
741
1230
  ray: raycaster.ray,
742
1231
  camera,
1232
+ pointerId: eventPointerId,
743
1233
  // Hijack stopPropagation, which just sets a flag
744
1234
  stopPropagation() {
745
- const capturesForPointer = "pointerId" in event && internal.capturedMap.get(event.pointerId);
1235
+ const pointerState = eventPointerId !== void 0 ? internal.pointerMap.get(eventPointerId) : void 0;
746
1236
  if (
747
1237
  // ...if this pointer hasn't been captured
748
- !capturesForPointer || // ... or if the hit object is capturing the pointer
749
- capturesForPointer.has(hit.eventObject)
1238
+ !pointerState?.captured.size || // ... or if the hit object is capturing the pointer
1239
+ pointerState.captured.has(hit.eventObject)
750
1240
  ) {
751
1241
  raycastEvent.stopped = localState.stopped = true;
752
- if (internal.hovered.size && Array.from(internal.hovered.values()).find((i) => i.eventObject === hit.eventObject)) {
1242
+ if (pointerState?.hovered.size && Array.from(pointerState.hovered.values()).find((i) => i.eventObject === hit.eventObject)) {
753
1243
  const higher = intersections.slice(0, intersections.indexOf(hit));
754
- cancelPointer([...higher, hit]);
1244
+ cancelPointer([...higher, hit], eventPointerId);
755
1245
  }
756
1246
  }
757
1247
  },
@@ -767,15 +1257,18 @@ function createEvents(store) {
767
1257
  }
768
1258
  return intersections;
769
1259
  }
770
- function cancelPointer(intersections) {
1260
+ function cancelPointer(intersections, pointerId) {
771
1261
  const { internal } = store.getState();
772
- for (const hoveredObj of internal.hovered.values()) {
1262
+ const pid = pointerId ?? DEFAULT_POINTER_ID;
1263
+ const pointerState = internal.pointerMap.get(pid);
1264
+ if (!pointerState) return;
1265
+ for (const [hoveredId, hoveredObj] of pointerState.hovered) {
773
1266
  if (!intersections.length || !intersections.find(
774
1267
  (hit) => hit.object === hoveredObj.object && hit.index === hoveredObj.index && hit.instanceId === hoveredObj.instanceId
775
1268
  )) {
776
1269
  const eventObject = hoveredObj.eventObject;
777
1270
  const instance = eventObject.__r3f;
778
- internal.hovered.delete(makeId(hoveredObj));
1271
+ pointerState.hovered.delete(hoveredId);
779
1272
  if (instance?.eventCount) {
780
1273
  const handlers = instance.handlers;
781
1274
  const data = { ...hoveredObj, intersections };
@@ -804,41 +1297,118 @@ function createEvents(store) {
804
1297
  instance?.handlers.onDropMissed?.(event);
805
1298
  }
806
1299
  }
1300
+ function cleanupPointer(pointerId) {
1301
+ const { internal } = store.getState();
1302
+ const pointerState = internal.pointerMap.get(pointerId);
1303
+ if (pointerState) {
1304
+ for (const [, hoveredObj] of pointerState.hovered) {
1305
+ const eventObject = hoveredObj.eventObject;
1306
+ const instance = eventObject.__r3f;
1307
+ if (instance?.eventCount) {
1308
+ const handlers = instance.handlers;
1309
+ const data = { ...hoveredObj, intersections: [] };
1310
+ handlers.onPointerOut?.(data);
1311
+ handlers.onPointerLeave?.(data);
1312
+ }
1313
+ }
1314
+ internal.pointerMap.delete(pointerId);
1315
+ }
1316
+ internal.pointerDirty.delete(pointerId);
1317
+ }
1318
+ function processDeferredPointer(event, pointerId) {
1319
+ const state = store.getState();
1320
+ const { internal } = state;
1321
+ if (!state.events.enabled) return;
1322
+ const filter = filterPointerEvents;
1323
+ const hits = intersect(event, filter);
1324
+ cancelPointer(hits, pointerId);
1325
+ function onIntersect(data) {
1326
+ const eventObject = data.eventObject;
1327
+ const instance = eventObject.__r3f;
1328
+ if (!instance?.eventCount) return;
1329
+ const handlers = instance.handlers;
1330
+ if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) {
1331
+ const id = makeId(data);
1332
+ const pointerState = getPointerState(internal, pointerId);
1333
+ const hoveredItem = pointerState.hovered.get(id);
1334
+ if (!hoveredItem) {
1335
+ pointerState.hovered.set(id, data);
1336
+ handlers.onPointerOver?.(data);
1337
+ handlers.onPointerEnter?.(data);
1338
+ } else if (hoveredItem.stopped) {
1339
+ data.stopPropagation();
1340
+ }
1341
+ }
1342
+ handlers.onPointerMove?.(data);
1343
+ }
1344
+ handleIntersects(hits, event, 0, onIntersect);
1345
+ }
807
1346
  function handlePointer(name) {
808
1347
  switch (name) {
809
1348
  case "onPointerLeave":
810
- case "onPointerCancel":
811
1349
  case "onDragLeave":
812
1350
  return () => cancelPointer([]);
1351
+ // Global cancel of these events
1352
+ case "onPointerCancel":
1353
+ return (event) => {
1354
+ const pointerId = getPointerId(event);
1355
+ cleanupPointer(pointerId);
1356
+ };
813
1357
  case "onLostPointerCapture":
814
1358
  return (event) => {
815
1359
  const { internal } = store.getState();
816
- if ("pointerId" in event && internal.capturedMap.has(event.pointerId)) {
1360
+ const pointerId = getPointerId(event);
1361
+ const pointerState = internal.pointerMap.get(pointerId);
1362
+ if (pointerState?.captured.size) {
817
1363
  requestAnimationFrame(() => {
818
- if (internal.capturedMap.has(event.pointerId)) {
819
- internal.capturedMap.delete(event.pointerId);
820
- cancelPointer([]);
1364
+ const pointerState2 = internal.pointerMap.get(pointerId);
1365
+ if (pointerState2?.captured.size) {
1366
+ pointerState2.captured.clear();
821
1367
  }
1368
+ cancelPointer([], pointerId);
822
1369
  });
823
1370
  }
824
1371
  };
825
1372
  }
826
1373
  return function handleEvent(event) {
827
1374
  const state = store.getState();
828
- const { onPointerMissed, onDragOverMissed, onDropMissed, internal } = state;
1375
+ const { onPointerMissed, onDragOverMissed, onDropMissed, internal, events } = state;
1376
+ const pointerId = getPointerId(event);
829
1377
  internal.lastEvent.current = event;
830
- if (!state.events.enabled) return;
1378
+ if (!events.enabled) return;
831
1379
  const isPointerMove = name === "onPointerMove";
832
1380
  const isDragOver = name === "onDragOver";
833
1381
  const isDrop = name === "onDrop";
834
1382
  const isClickEvent = name === "onClick" || name === "onContextMenu" || name === "onDoubleClick";
1383
+ const isPointerDown = name === "onPointerDown";
1384
+ const isPointerUp = name === "onPointerUp";
1385
+ const isWheel = name === "onWheel";
1386
+ const canDeferRaycasts = events.frameTimedRaycasts && state.frameloop === "always";
1387
+ if (isPointerMove && canDeferRaycasts) {
1388
+ events.compute?.(event, state);
1389
+ internal.pointerDirty.set(pointerId, event);
1390
+ return;
1391
+ }
1392
+ if (isWheel && canDeferRaycasts && !events.alwaysFireOnScroll) {
1393
+ events.compute?.(event, state);
1394
+ internal.pointerDirty.set(pointerId, event);
1395
+ return;
1396
+ }
1397
+ if ((isClickEvent || isPointerDown || isPointerUp) && internal.pointerDirty.has(pointerId)) {
1398
+ const deferredEvent = internal.pointerDirty.get(pointerId);
1399
+ internal.pointerDirty.delete(pointerId);
1400
+ processDeferredPointer(deferredEvent, pointerId);
1401
+ }
835
1402
  const filter = isPointerMove || isDragOver || isDrop ? filterPointerEvents : void 0;
836
1403
  const hits = intersect(event, filter);
837
- const delta = isClickEvent ? calculateDistance(event) : 0;
838
- if (name === "onPointerDown") {
839
- internal.initialClick = [event.offsetX, event.offsetY];
840
- internal.initialHits = hits.map((hit) => hit.eventObject);
841
- }
1404
+ const delta = isClickEvent ? calculateDistance(event, pointerId) : 0;
1405
+ if (isPointerDown) {
1406
+ const pointerState2 = getPointerState(internal, pointerId);
1407
+ pointerState2.initialClick = [event.offsetX, event.offsetY];
1408
+ pointerState2.initialHits = hits.map((hit) => hit.eventObject);
1409
+ }
1410
+ const pointerState = internal.pointerMap.get(pointerId);
1411
+ const initialHits = pointerState?.initialHits ?? [];
842
1412
  if (isClickEvent && !hits.length) {
843
1413
  if (delta <= 2) {
844
1414
  pointerMissed(event, internal.interaction);
@@ -853,7 +1423,9 @@ function createEvents(store) {
853
1423
  dropMissed(event, internal.interaction);
854
1424
  if (onDropMissed) onDropMissed(event);
855
1425
  }
856
- if (isPointerMove || isDragOver) cancelPointer(hits);
1426
+ if (isPointerMove || isDragOver) {
1427
+ cancelPointer(hits, pointerId);
1428
+ }
857
1429
  function onIntersect(data) {
858
1430
  const eventObject = data.eventObject;
859
1431
  const instance = eventObject.__r3f;
@@ -862,9 +1434,10 @@ function createEvents(store) {
862
1434
  if (isPointerMove) {
863
1435
  if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) {
864
1436
  const id = makeId(data);
865
- const hoveredItem = internal.hovered.get(id);
1437
+ const pointerState2 = getPointerState(internal, pointerId);
1438
+ const hoveredItem = pointerState2.hovered.get(id);
866
1439
  if (!hoveredItem) {
867
- internal.hovered.set(id, data);
1440
+ pointerState2.hovered.set(id, data);
868
1441
  handlers.onPointerOver?.(data);
869
1442
  handlers.onPointerEnter?.(data);
870
1443
  } else if (hoveredItem.stopped) {
@@ -874,9 +1447,10 @@ function createEvents(store) {
874
1447
  handlers.onPointerMove?.(data);
875
1448
  } else if (isDragOver) {
876
1449
  const id = makeId(data);
877
- const hoveredItem = internal.hovered.get(id);
1450
+ const pointerState2 = getPointerState(internal, pointerId);
1451
+ const hoveredItem = pointerState2.hovered.get(id);
878
1452
  if (!hoveredItem) {
879
- internal.hovered.set(id, data);
1453
+ pointerState2.hovered.set(id, data);
880
1454
  handlers.onDragOverEnter?.(data);
881
1455
  } else if (hoveredItem.stopped) {
882
1456
  data.stopPropagation();
@@ -887,18 +1461,18 @@ function createEvents(store) {
887
1461
  } else {
888
1462
  const handler = handlers[name];
889
1463
  if (handler) {
890
- if (!isClickEvent || internal.initialHits.includes(eventObject)) {
1464
+ if (!isClickEvent || initialHits.includes(eventObject)) {
891
1465
  pointerMissed(
892
1466
  event,
893
- internal.interaction.filter((object) => !internal.initialHits.includes(object))
1467
+ internal.interaction.filter((object) => !initialHits.includes(object))
894
1468
  );
895
1469
  handler(data);
896
1470
  }
897
1471
  } else {
898
- if (isClickEvent && internal.initialHits.includes(eventObject)) {
1472
+ if (isClickEvent && initialHits.includes(eventObject)) {
899
1473
  pointerMissed(
900
1474
  event,
901
- internal.interaction.filter((object) => !internal.initialHits.includes(object))
1475
+ internal.interaction.filter((object) => !initialHits.includes(object))
902
1476
  );
903
1477
  }
904
1478
  }
@@ -907,7 +1481,15 @@ function createEvents(store) {
907
1481
  handleIntersects(hits, event, delta, onIntersect);
908
1482
  };
909
1483
  }
910
- return { handlePointer };
1484
+ function flushDeferredPointers() {
1485
+ const { internal, events } = store.getState();
1486
+ if (!events.frameTimedRaycasts) return;
1487
+ for (const [pointerId, event] of internal.pointerDirty) {
1488
+ processDeferredPointer(event, pointerId);
1489
+ }
1490
+ internal.pointerDirty.clear();
1491
+ }
1492
+ return { handlePointer, flushDeferredPointers, processDeferredPointer };
911
1493
  }
912
1494
  const DOM_EVENTS = {
913
1495
  onClick: ["click", false],
@@ -926,11 +1508,16 @@ const DOM_EVENTS = {
926
1508
  onLostPointerCapture: ["lostpointercapture", true]
927
1509
  };
928
1510
  function createPointerEvents(store) {
929
- const { handlePointer } = createEvents(store);
1511
+ const { handlePointer, flushDeferredPointers, processDeferredPointer } = createEvents(store);
1512
+ let nextXRPointerId = XR_POINTER_ID_START;
1513
+ const xrPointers = /* @__PURE__ */ new Map();
930
1514
  return {
931
1515
  priority: 1,
932
1516
  enabled: true,
933
- compute(event, state, previous) {
1517
+ frameTimedRaycasts: true,
1518
+ alwaysFireOnScroll: true,
1519
+ updateOnFrame: false,
1520
+ compute(event, state) {
934
1521
  state.pointer.set(event.offsetX / state.size.width * 2 - 1, -(event.offsetY / state.size.height) * 2 + 1);
935
1522
  state.raycaster.setFromCamera(state.pointer, state.camera);
936
1523
  },
@@ -939,11 +1526,33 @@ function createPointerEvents(store) {
939
1526
  (acc, key) => ({ ...acc, [key]: handlePointer(key) }),
940
1527
  {}
941
1528
  ),
942
- update: () => {
1529
+ update: (pointerId) => {
943
1530
  const { events, internal } = store.getState();
944
- if (internal.lastEvent?.current && events.handlers) events.handlers.onPointerMove(internal.lastEvent.current);
1531
+ if (!events.handlers) return;
1532
+ if (pointerId !== void 0) {
1533
+ const event = internal.pointerDirty.get(pointerId);
1534
+ if (event) {
1535
+ internal.pointerDirty.delete(pointerId);
1536
+ processDeferredPointer(event, pointerId);
1537
+ } else if (internal.lastEvent?.current) {
1538
+ processDeferredPointer(internal.lastEvent.current, pointerId);
1539
+ }
1540
+ } else {
1541
+ flushDeferredPointers();
1542
+ if (internal.lastEvent?.current) {
1543
+ events.handlers.onPointerMove(internal.lastEvent.current);
1544
+ }
1545
+ }
1546
+ },
1547
+ flush: () => {
1548
+ const { events, internal } = store.getState();
1549
+ flushDeferredPointers();
1550
+ if (events.updateOnFrame && internal.lastEvent?.current && events.handlers) {
1551
+ events.handlers.onPointerMove(internal.lastEvent.current);
1552
+ }
945
1553
  },
946
1554
  connect: (target) => {
1555
+ if (!target) return;
947
1556
  const { set, events } = store.getState();
948
1557
  events.disconnect?.();
949
1558
  set((state) => ({ events: { ...state.events, connected: target } }));
@@ -967,6 +1576,33 @@ function createPointerEvents(store) {
967
1576
  }
968
1577
  set((state) => ({ events: { ...state.events, connected: void 0 } }));
969
1578
  }
1579
+ },
1580
+ // PREVIEW (A8): the XR pointer registration API may change before stable.
1581
+ registerPointer: (config) => {
1582
+ const pointerId = nextXRPointerId++;
1583
+ xrPointers.set(pointerId, config);
1584
+ const { internal } = store.getState();
1585
+ getPointerState(internal, pointerId);
1586
+ return pointerId;
1587
+ },
1588
+ unregisterPointer: (pointerId) => {
1589
+ xrPointers.delete(pointerId);
1590
+ const { internal } = store.getState();
1591
+ const pointerState = internal.pointerMap.get(pointerId);
1592
+ if (pointerState) {
1593
+ for (const [, hoveredObj] of pointerState.hovered) {
1594
+ const eventObject = hoveredObj.eventObject;
1595
+ const instance = eventObject.__r3f;
1596
+ if (instance?.eventCount) {
1597
+ const handlers = instance.handlers;
1598
+ const data = { ...hoveredObj, intersections: [] };
1599
+ handlers.onPointerOut?.(data);
1600
+ handlers.onPointerLeave?.(data);
1601
+ }
1602
+ }
1603
+ internal.pointerMap.delete(pointerId);
1604
+ }
1605
+ internal.pointerDirty.delete(pointerId);
970
1606
  }
971
1607
  };
972
1608
  }
@@ -1028,6 +1664,14 @@ function notifyAlpha({ message, link }) {
1028
1664
  }
1029
1665
  }
1030
1666
 
1667
+ const INTERNAL_LIB_MARKERS = ["zustand", "setState", "Object.assign"];
1668
+ const INTERNAL_FIBER_MARKERS = ["packages/fiber/src", "packages/fiber/dist", "@react-three/fiber", "@react-three_fiber"];
1669
+ function isInternalRendererAccess(stack, callerDepth = 2) {
1670
+ if (!stack) return false;
1671
+ const caller = stack.split("\n")[callerDepth] ?? "";
1672
+ return INTERNAL_LIB_MARKERS.some((m) => caller.includes(m)) || INTERNAL_FIBER_MARKERS.some((m) => caller.includes(m));
1673
+ }
1674
+
1031
1675
  const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
1032
1676
  const context = globalThis[R3F_CONTEXT] ?? (globalThis[R3F_CONTEXT] = React.createContext(null));
1033
1677
  const createStore = (invalidate, advance) => {
@@ -1057,23 +1701,29 @@ const createStore = (invalidate, advance) => {
1057
1701
  set,
1058
1702
  get,
1059
1703
  // Mock objects that have to be configured
1704
+ // primaryStore is set after store creation (self-reference for primary, primary's store for secondary)
1705
+ primaryStore: null,
1060
1706
  gl: null,
1061
1707
  renderer: null,
1062
1708
  camera: null,
1063
1709
  frustum: new Frustum(),
1064
1710
  autoUpdateFrustum: true,
1065
1711
  raycaster: null,
1066
- events: { priority: 1, enabled: true, connected: false },
1712
+ events: {
1713
+ priority: 1,
1714
+ enabled: true,
1715
+ connected: false,
1716
+ frameTimedRaycasts: true,
1717
+ alwaysFireOnScroll: true,
1718
+ updateOnFrame: false
1719
+ },
1067
1720
  scene: null,
1068
1721
  rootScene: null,
1069
1722
  xr: null,
1070
1723
  inspector: null,
1071
1724
  invalidate: (frames = 1, stackFrames = false) => invalidate(get(), frames, stackFrames),
1072
1725
  advance: (timestamp, runGlobalEffects) => advance(timestamp, runGlobalEffects, get()),
1073
- legacy: false,
1074
- linear: false,
1075
- flat: false,
1076
- textureColorSpace: "srgb",
1726
+ textureColorSpace: SRGBColorSpace,
1077
1727
  isLegacy: false,
1078
1728
  webGPUSupported: false,
1079
1729
  isNative: false,
@@ -1113,10 +1763,40 @@ const createStore = (invalidate, advance) => {
1113
1763
  getCurrentViewport
1114
1764
  },
1115
1765
  setEvents: (events) => set((state2) => ({ ...state2, events: { ...state2.events, ...events } })),
1116
- setSize: (width, height, top = 0, left = 0) => {
1117
- const camera = get().camera;
1118
- const size = { width, height, top, left };
1119
- set((state2) => ({ size, viewport: { ...state2.viewport, ...getCurrentViewport(camera, defaultTarget, size) } }));
1766
+ setSize: (width, height, top, left) => {
1767
+ const state2 = get();
1768
+ if (width === void 0) {
1769
+ set({ _sizeImperative: false });
1770
+ if (state2._sizeProps) {
1771
+ const { width: propW, height: propH } = state2._sizeProps;
1772
+ if (propW !== void 0 || propH !== void 0) {
1773
+ const currentSize = state2.size;
1774
+ const newSize = {
1775
+ width: propW ?? currentSize.width,
1776
+ height: propH ?? currentSize.height,
1777
+ top: currentSize.top,
1778
+ left: currentSize.left
1779
+ };
1780
+ set((s) => ({
1781
+ size: newSize,
1782
+ viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, newSize) }
1783
+ }));
1784
+ getScheduler().invalidate();
1785
+ }
1786
+ }
1787
+ return;
1788
+ }
1789
+ const w = width;
1790
+ const h = height ?? width;
1791
+ const t = top ?? state2.size.top;
1792
+ const l = left ?? state2.size.left;
1793
+ const size = { width: w, height: h, top: t, left: l };
1794
+ set((s) => ({
1795
+ size,
1796
+ viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, size) },
1797
+ _sizeImperative: true
1798
+ }));
1799
+ getScheduler().invalidate();
1120
1800
  },
1121
1801
  setDpr: (dpr) => set((state2) => {
1122
1802
  const resolved = calculateDpr(dpr);
@@ -1124,25 +1804,36 @@ const createStore = (invalidate, advance) => {
1124
1804
  }),
1125
1805
  setFrameloop: (frameloop = "always") => {
1126
1806
  set(() => ({ frameloop }));
1807
+ getScheduler().frameloop = frameloop;
1127
1808
  },
1128
1809
  setError: (error) => set(() => ({ error })),
1129
1810
  error: null,
1130
- //* TSL State (managed via hooks: useUniforms, useNodes, useTextures, usePostProcessing) ==============================
1811
+ //* TSL State (managed via hooks: useUniforms, useNodes, useBuffers, useGPUStorage, useTextures, useRenderPipeline) ==============================
1131
1812
  uniforms: {},
1132
1813
  nodes: {},
1814
+ buffers: {},
1815
+ gpuStorage: {},
1133
1816
  textures: /* @__PURE__ */ new Map(),
1134
- postProcessing: null,
1817
+ _textureRefs: /* @__PURE__ */ new Map(),
1818
+ renderPipeline: null,
1135
1819
  passes: {},
1820
+ _hmrVersion: 0,
1821
+ _sizeImperative: false,
1822
+ _sizeProps: null,
1136
1823
  previousRoot: void 0,
1137
1824
  internal: {
1138
1825
  // Events
1139
1826
  interaction: [],
1140
- hovered: /* @__PURE__ */ new Map(),
1141
1827
  subscribers: [],
1828
+ // Per-pointer state (new unified structure)
1829
+ pointerMap: /* @__PURE__ */ new Map(),
1830
+ pointerDirty: /* @__PURE__ */ new Map(),
1831
+ lastEvent: React.createRef(),
1832
+ // Deprecated but kept for backwards compatibility
1833
+ hovered: /* @__PURE__ */ new Map(),
1142
1834
  initialClick: [0, 0],
1143
1835
  initialHits: [],
1144
1836
  capturedMap: /* @__PURE__ */ new Map(),
1145
- lastEvent: React.createRef(),
1146
1837
  // Visibility tracking (onFramed, onOccluded, onVisible)
1147
1838
  visibilityRegistry: /* @__PURE__ */ new Map(),
1148
1839
  // Occlusion system (WebGPU only)
@@ -1181,8 +1872,7 @@ const createStore = (invalidate, advance) => {
1181
1872
  const currentState = rootStore.getState();
1182
1873
  if (!currentState.isLegacy && currentState.internal.actualRenderer) {
1183
1874
  const stack = new Error().stack || "";
1184
- const isInternalAccess = stack.includes("zustand") || stack.includes("setState") || stack.includes("Object.assign") || stack.includes("react-three-fiber/packages/fiber/src/core");
1185
- if (!isInternalAccess) {
1875
+ if (!isInternalRendererAccess(stack)) {
1186
1876
  const cleanedStack = stack.split("\n").slice(2).join("\n") || "Stack trace unavailable";
1187
1877
  notifyDepreciated({
1188
1878
  heading: "Accessing state.gl in WebGPU mode",
@@ -1225,13 +1915,22 @@ const createStore = (invalidate, advance) => {
1225
1915
  rootStore.subscribe(() => {
1226
1916
  const { camera, size, viewport, set, internal } = rootStore.getState();
1227
1917
  const actualRenderer = internal.actualRenderer;
1918
+ const canvasTarget = internal.canvasTarget;
1228
1919
  if (size.width !== oldSize.width || size.height !== oldSize.height || viewport.dpr !== oldDpr) {
1229
1920
  oldSize = size;
1230
1921
  oldDpr = viewport.dpr;
1231
1922
  updateCamera(camera, size);
1232
- if (viewport.dpr > 0) actualRenderer.setPixelRatio(viewport.dpr);
1233
- const updateStyle = typeof HTMLCanvasElement !== "undefined" && actualRenderer.domElement instanceof HTMLCanvasElement;
1234
- actualRenderer.setSize(size.width, size.height, updateStyle);
1923
+ if (internal.isSecondary && canvasTarget) {
1924
+ if (viewport.dpr > 0) canvasTarget.setPixelRatio(viewport.dpr);
1925
+ canvasTarget.setSize(size.width, size.height, false);
1926
+ } else {
1927
+ if (viewport.dpr > 0) actualRenderer.setPixelRatio(viewport.dpr);
1928
+ actualRenderer.setSize(size.width, size.height, false);
1929
+ if (canvasTarget) {
1930
+ if (viewport.dpr > 0) canvasTarget.setPixelRatio(viewport.dpr);
1931
+ canvasTarget.setSize(size.width, size.height, false);
1932
+ }
1933
+ }
1235
1934
  }
1236
1935
  if (camera !== oldCamera) {
1237
1936
  oldCamera = camera;
@@ -1286,1053 +1985,28 @@ function loadingFn(extensions, onProgress) {
1286
1985
  );
1287
1986
  };
1288
1987
  }
1289
- function useLoader(loader, input, extensions, onProgress) {
1290
- const keys = Array.isArray(input) ? input : [input];
1988
+ function useLoader(loader, input, extensions, onProgress, cacheKey) {
1989
+ const inputs = Array.isArray(input) ? input : [input];
1990
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
1291
1991
  const fn = loadingFn(extensions, onProgress);
1292
- const results = keys.map((key) => suspend(fn, [loader, key], { equal: is.equ }));
1992
+ const results = cacheKeys.map(
1993
+ (key, index) => suspend(() => fn(loader, inputs[index]), [loader, key], { equal: is.equ })
1994
+ );
1293
1995
  return Array.isArray(input) ? results : results[0];
1294
1996
  }
1295
- useLoader.preload = function(loader, input, extensions, onProgress) {
1296
- const keys = Array.isArray(input) ? input : [input];
1297
- keys.forEach((key) => preload(loadingFn(extensions, onProgress), [loader, key]));
1997
+ useLoader.preload = function(loader, input, extensions, onProgress, cacheKey) {
1998
+ const inputs = Array.isArray(input) ? input : [input];
1999
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2000
+ cacheKeys.forEach(
2001
+ (key, index) => preload(() => loadingFn(extensions, onProgress)(loader, inputs[index]), [loader, key])
2002
+ );
1298
2003
  };
1299
- useLoader.clear = function(loader, input) {
1300
- const keys = Array.isArray(input) ? input : [input];
1301
- keys.forEach((key) => clear([loader, key]));
2004
+ useLoader.clear = function(loader, input, cacheKey) {
2005
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2006
+ cacheKeys.forEach((key) => clear([loader, key]));
1302
2007
  };
1303
2008
  useLoader.loader = getLoader;
1304
2009
 
1305
- var __defProp$1 = Object.defineProperty;
1306
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1307
- var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1308
- const DEFAULT_PHASES = ["start", "input", "physics", "update", "render", "finish"];
1309
- class PhaseGraph {
1310
- constructor() {
1311
- /** Ordered list of phase nodes */
1312
- __publicField$1(this, "phases", []);
1313
- /** Quick lookup by name */
1314
- __publicField$1(this, "phaseMap", /* @__PURE__ */ new Map());
1315
- /** Cached ordered names (invalidated on changes) */
1316
- __publicField$1(this, "orderedNamesCache", null);
1317
- this.initializeDefaultPhases();
1318
- }
1319
- //* Initialization --------------------------------
1320
- initializeDefaultPhases() {
1321
- for (const name of DEFAULT_PHASES) {
1322
- const node = { name, isAutoGenerated: false };
1323
- this.phases.push(node);
1324
- this.phaseMap.set(name, node);
1325
- }
1326
- this.invalidateCache();
1327
- }
1328
- //* Public API --------------------------------
1329
- /**
1330
- * Add a named phase to the graph
1331
- * @param name - Phase name (must be unique)
1332
- * @param options - Position options (before or after another phase)
1333
- */
1334
- addPhase(name, options = {}) {
1335
- if (this.phaseMap.has(name)) {
1336
- console.warn(`[useFrame] Phase "${name}" already exists`);
1337
- return;
1338
- }
1339
- const { before, after } = options;
1340
- const node = { name, isAutoGenerated: false };
1341
- let insertIndex = this.phases.length;
1342
- const targetIndex = this.getPhaseIndex(before ?? after);
1343
- if (targetIndex !== -1) insertIndex = before ? targetIndex : targetIndex + 1;
1344
- else {
1345
- const constraintType = before ? "before" : "after";
1346
- console.warn(`[useFrame] Phase "${before ?? after}" not found for '${constraintType}' constraint`);
1347
- }
1348
- this.phases.splice(insertIndex, 0, node);
1349
- this.phaseMap.set(name, node);
1350
- this.invalidateCache();
1351
- }
1352
- /**
1353
- * Get ordered list of phase names
1354
- */
1355
- getOrderedPhases() {
1356
- if (this.orderedNamesCache === null) this.orderedNamesCache = this.phases.map((p) => p.name);
1357
- return this.orderedNamesCache;
1358
- }
1359
- /**
1360
- * Check if a phase exists
1361
- */
1362
- hasPhase(name) {
1363
- return this.phaseMap.has(name);
1364
- }
1365
- /**
1366
- * Get the index of a phase (-1 if not found)
1367
- */
1368
- getPhaseIndex(name) {
1369
- if (!name) return -1;
1370
- return this.phases.findIndex((p) => p.name === name);
1371
- }
1372
- /**
1373
- * Ensure a phase exists, creating an auto-generated one if needed.
1374
- * Used for resolving before/after constraints.
1375
- *
1376
- * @param name - The phase name to ensure exists
1377
- * @returns The phase name (may be auto-generated like 'before:render')
1378
- */
1379
- ensurePhase(name) {
1380
- if (this.phaseMap.has(name)) return name;
1381
- const node = { name, isAutoGenerated: true };
1382
- this.phases.push(node);
1383
- this.phaseMap.set(name, node);
1384
- this.invalidateCache();
1385
- return name;
1386
- }
1387
- /**
1388
- * Resolve where a job with before/after constraints should go.
1389
- * Creates auto-generated phases if needed.
1390
- *
1391
- * @param before - Phase(s) to run before
1392
- * @param after - Phase(s) to run after
1393
- * @returns The resolved phase name
1394
- */
1395
- resolveConstraintPhase(before, after) {
1396
- const beforeArr = before ? Array.isArray(before) ? before : [before] : [];
1397
- const afterArr = after ? Array.isArray(after) ? after : [after] : [];
1398
- if (beforeArr.length > 0) {
1399
- return this.ensureAutoPhase(beforeArr[0], "before", 0);
1400
- }
1401
- if (afterArr.length > 0) {
1402
- return this.ensureAutoPhase(afterArr[0], "after", 1);
1403
- }
1404
- return "update";
1405
- }
1406
- /**
1407
- * Ensure an auto-generated phase exists relative to a target phase.
1408
- * Creates the phase if it doesn't exist, inserting it at the correct position.
1409
- *
1410
- * @param target - The target phase name to position relative to
1411
- * @param prefix - Prefix for auto-generated phase name ('before' or 'after')
1412
- * @param offset - Insertion offset (0 for before, 1 for after)
1413
- * @returns The auto-generated phase name
1414
- */
1415
- ensureAutoPhase(target, prefix, offset) {
1416
- const autoName = `${prefix}:${target}`;
1417
- if (this.phaseMap.has(autoName)) return autoName;
1418
- const node = { name: autoName, isAutoGenerated: true };
1419
- const targetIndex = this.getPhaseIndex(target);
1420
- if (targetIndex !== -1) this.phases.splice(targetIndex + offset, 0, node);
1421
- else this.phases.push(node);
1422
- this.phaseMap.set(autoName, node);
1423
- this.invalidateCache();
1424
- return autoName;
1425
- }
1426
- // Internal --------------------------------
1427
- invalidateCache() {
1428
- this.orderedNamesCache = null;
1429
- }
1430
- }
1431
-
1432
- function rebuildSortedJobs(jobs, phaseGraph) {
1433
- const orderedPhases = phaseGraph.getOrderedPhases();
1434
- const buckets = /* @__PURE__ */ new Map();
1435
- for (const phase of orderedPhases) {
1436
- buckets.set(phase, []);
1437
- }
1438
- for (const job of jobs.values()) {
1439
- if (!job.enabled) continue;
1440
- let bucket = buckets.get(job.phase);
1441
- if (!bucket) {
1442
- bucket = [];
1443
- buckets.set(job.phase, bucket);
1444
- }
1445
- bucket.push(job);
1446
- }
1447
- const sortedBuckets = [];
1448
- for (const phase of orderedPhases) {
1449
- const bucket = buckets.get(phase);
1450
- if (!bucket || bucket.length === 0) continue;
1451
- bucket.sort((a, b) => {
1452
- if (a.priority !== b.priority) return b.priority - a.priority;
1453
- return a.index - b.index;
1454
- });
1455
- sortedBuckets.push(hasCrossJobConstraints(bucket) ? topologicalSort(bucket) : bucket);
1456
- }
1457
- for (const [phase, bucket] of buckets) {
1458
- if (!orderedPhases.includes(phase) && bucket.length > 0) {
1459
- bucket.sort((a, b) => {
1460
- if (a.priority !== b.priority) return b.priority - a.priority;
1461
- return a.index - b.index;
1462
- });
1463
- sortedBuckets.push(bucket);
1464
- }
1465
- }
1466
- return sortedBuckets.flat();
1467
- }
1468
- function hasCrossJobConstraints(bucket) {
1469
- const jobIds = new Set(bucket.map((j) => j.id));
1470
- for (const job of bucket) {
1471
- for (const ref of job.before) {
1472
- if (jobIds.has(ref)) return true;
1473
- }
1474
- for (const ref of job.after) {
1475
- if (jobIds.has(ref)) return true;
1476
- }
1477
- }
1478
- return false;
1479
- }
1480
- function topologicalSort(jobs) {
1481
- const n = jobs.length;
1482
- if (n <= 1) return jobs;
1483
- const jobMap = /* @__PURE__ */ new Map();
1484
- const inDegree = /* @__PURE__ */ new Map();
1485
- const adjacency = /* @__PURE__ */ new Map();
1486
- for (const job of jobs) {
1487
- jobMap.set(job.id, job);
1488
- inDegree.set(job.id, 0);
1489
- adjacency.set(job.id, []);
1490
- }
1491
- for (const job of jobs) {
1492
- for (const ref of job.before) {
1493
- if (jobMap.has(ref)) {
1494
- adjacency.get(job.id).push(ref);
1495
- inDegree.set(ref, inDegree.get(ref) + 1);
1496
- }
1497
- }
1498
- for (const ref of job.after) {
1499
- if (jobMap.has(ref)) {
1500
- adjacency.get(ref).push(job.id);
1501
- inDegree.set(job.id, inDegree.get(job.id) + 1);
1502
- }
1503
- }
1504
- }
1505
- const queue = [];
1506
- for (const job of jobs) {
1507
- if (inDegree.get(job.id) === 0) {
1508
- queue.push(job);
1509
- }
1510
- }
1511
- queue.sort((a, b) => {
1512
- if (a.priority !== b.priority) return b.priority - a.priority;
1513
- return a.index - b.index;
1514
- });
1515
- const result = [];
1516
- while (queue.length > 0) {
1517
- const job = queue.shift();
1518
- result.push(job);
1519
- const neighbors = adjacency.get(job.id) || [];
1520
- for (const neighborId of neighbors) {
1521
- const newDegree = inDegree.get(neighborId) - 1;
1522
- inDegree.set(neighborId, newDegree);
1523
- if (newDegree === 0) {
1524
- const neighbor = jobMap.get(neighborId);
1525
- insertSorted(queue, neighbor);
1526
- }
1527
- }
1528
- }
1529
- if (result.length !== n) {
1530
- console.warn("[useFrame] Circular dependency detected in job constraints");
1531
- const resultIds = new Set(result.map((j) => j.id));
1532
- for (const job of jobs) {
1533
- if (!resultIds.has(job.id)) result.push(job);
1534
- }
1535
- }
1536
- return result;
1537
- }
1538
- function insertSorted(arr, job) {
1539
- let i = 0;
1540
- while (i < arr.length) {
1541
- const cmp = arr[i];
1542
- if (job.priority > cmp.priority || job.priority === cmp.priority && job.index < cmp.index) {
1543
- break;
1544
- }
1545
- i++;
1546
- }
1547
- arr.splice(i, 0, job);
1548
- }
1549
-
1550
- function shouldRun(job, now) {
1551
- if (!job.enabled) return false;
1552
- if (!job.fps) return true;
1553
- const minInterval = 1e3 / job.fps;
1554
- const lastRun = job.lastRun ?? 0;
1555
- const elapsed = now - lastRun;
1556
- if (elapsed < minInterval) return false;
1557
- if (job.drop) {
1558
- job.lastRun = now;
1559
- } else {
1560
- const steps = Math.floor(elapsed / minInterval);
1561
- job.lastRun = lastRun + steps * minInterval;
1562
- if (job.lastRun < now - minInterval) {
1563
- job.lastRun = now;
1564
- }
1565
- }
1566
- return true;
1567
- }
1568
- function resetJobTiming(job) {
1569
- job.lastRun = void 0;
1570
- }
1571
-
1572
- var __defProp = Object.defineProperty;
1573
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1574
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1575
- const hmrData = (() => {
1576
- if (typeof process !== "undefined" && process.env.NODE_ENV === "test") return void 0;
1577
- if (typeof import_meta_hot !== "undefined") return import_meta_hot;
1578
- try {
1579
- return (0, eval)("import.meta.hot");
1580
- } catch {
1581
- return void 0;
1582
- }
1583
- })();
1584
- const _Scheduler = class _Scheduler {
1585
- //* Constructor ================================
1586
- constructor() {
1587
- //* Critical State ================================
1588
- __publicField(this, "roots", /* @__PURE__ */ new Map());
1589
- __publicField(this, "phaseGraph");
1590
- __publicField(this, "loopState", {
1591
- running: false,
1592
- rafHandle: null,
1593
- lastTime: null,
1594
- // null = uninitialized, 0+ = valid timestamp
1595
- frameCount: 0,
1596
- elapsedTime: 0,
1597
- createdAt: performance.now()
1598
- });
1599
- __publicField(this, "stoppedTime", 0);
1600
- //* Private State ================================
1601
- __publicField(this, "nextRootIndex", 0);
1602
- __publicField(this, "globalBeforeJobs", /* @__PURE__ */ new Map());
1603
- __publicField(this, "globalAfterJobs", /* @__PURE__ */ new Map());
1604
- __publicField(this, "nextGlobalIndex", 0);
1605
- __publicField(this, "idleCallbacks", /* @__PURE__ */ new Set());
1606
- __publicField(this, "nextJobIndex", 0);
1607
- __publicField(this, "jobStateListeners", /* @__PURE__ */ new Map());
1608
- __publicField(this, "pendingFrames", 0);
1609
- __publicField(this, "_frameloop", "always");
1610
- //* Independent Mode & Error Handling State ================================
1611
- __publicField(this, "_independent", false);
1612
- __publicField(this, "errorHandler", null);
1613
- __publicField(this, "rootReadyCallbacks", /* @__PURE__ */ new Set());
1614
- //* Core Loop Execution Methods ================================
1615
- /**
1616
- * Main RAF loop callback.
1617
- * Executes frame, handles demand mode, and schedules next frame.
1618
- * @param {number} timestamp - RAF timestamp in milliseconds
1619
- * @returns {void}
1620
- * @private
1621
- */
1622
- __publicField(this, "loop", (timestamp) => {
1623
- if (!this.loopState.running) return;
1624
- this.executeFrame(timestamp);
1625
- if (this._frameloop === "demand") {
1626
- this.pendingFrames = Math.max(0, this.pendingFrames - 1);
1627
- if (this.pendingFrames === 0) {
1628
- this.notifyIdle(timestamp);
1629
- return this.stop();
1630
- }
1631
- }
1632
- this.loopState.rafHandle = requestAnimationFrame(this.loop);
1633
- });
1634
- this.phaseGraph = new PhaseGraph();
1635
- }
1636
- static get instance() {
1637
- return globalThis[_Scheduler.INSTANCE_KEY] ?? null;
1638
- }
1639
- static set instance(value) {
1640
- globalThis[_Scheduler.INSTANCE_KEY] = value;
1641
- }
1642
- /**
1643
- * Get the global scheduler instance (creates if doesn't exist).
1644
- * Uses HMR data to preserve instance across hot reloads.
1645
- * @returns {Scheduler} The singleton scheduler instance
1646
- */
1647
- static get() {
1648
- if (!_Scheduler.instance && hmrData?.data?.scheduler) {
1649
- _Scheduler.instance = hmrData.data.scheduler;
1650
- }
1651
- if (!_Scheduler.instance) {
1652
- _Scheduler.instance = new _Scheduler();
1653
- if (hmrData?.data) {
1654
- hmrData.data.scheduler = _Scheduler.instance;
1655
- }
1656
- }
1657
- return _Scheduler.instance;
1658
- }
1659
- /**
1660
- * Reset the singleton instance. Stops the loop and clears all state.
1661
- * Primarily used for testing to ensure clean state between tests.
1662
- * @returns {void}
1663
- */
1664
- static reset() {
1665
- if (_Scheduler.instance) {
1666
- _Scheduler.instance.stop();
1667
- _Scheduler.instance = null;
1668
- }
1669
- if (hmrData?.data) {
1670
- hmrData.data.scheduler = null;
1671
- }
1672
- }
1673
- //* Getters & Setters ================================
1674
- get phases() {
1675
- return this.phaseGraph.getOrderedPhases();
1676
- }
1677
- get frameloop() {
1678
- return this._frameloop;
1679
- }
1680
- set frameloop(mode) {
1681
- if (this._frameloop === mode) return;
1682
- const wasAlways = this._frameloop === "always";
1683
- this._frameloop = mode;
1684
- if (mode === "always" && !this.loopState.running && this.roots.size > 0) this.start();
1685
- else if (mode !== "always" && wasAlways) this.stop();
1686
- }
1687
- get isRunning() {
1688
- return this.loopState.running;
1689
- }
1690
- get isReady() {
1691
- return this.roots.size > 0;
1692
- }
1693
- get independent() {
1694
- return this._independent;
1695
- }
1696
- set independent(value) {
1697
- this._independent = value;
1698
- if (value) this.ensureDefaultRoot();
1699
- }
1700
- //* Root Management Methods ================================
1701
- /**
1702
- * Register a root (Canvas) with the scheduler.
1703
- * The first root to register starts the RAF loop (if frameloop='always').
1704
- * @param {string} id - Unique identifier for this root
1705
- * @param {RootOptions} [options] - Optional configuration with getState and onError callbacks
1706
- * @returns {() => void} Unsubscribe function to remove this root
1707
- */
1708
- registerRoot(id, options = {}) {
1709
- if (this.roots.has(id)) {
1710
- console.warn(`[Scheduler] Root "${id}" already registered`);
1711
- return () => this.unregisterRoot(id);
1712
- }
1713
- const entry = {
1714
- id,
1715
- getState: options.getState ?? (() => ({})),
1716
- jobs: /* @__PURE__ */ new Map(),
1717
- sortedJobs: [],
1718
- needsRebuild: false
1719
- };
1720
- if (options.onError) {
1721
- this.errorHandler = options.onError;
1722
- }
1723
- this.roots.set(id, entry);
1724
- if (this.roots.size === 1) {
1725
- this.notifyRootReady();
1726
- if (this._frameloop === "always") this.start();
1727
- }
1728
- return () => this.unregisterRoot(id);
1729
- }
1730
- /**
1731
- * Unregister a root from the scheduler.
1732
- * Cleans up all job state listeners for this root's jobs.
1733
- * The last root to unregister stops the RAF loop.
1734
- * @param {string} id - The root ID to unregister
1735
- * @returns {void}
1736
- */
1737
- unregisterRoot(id) {
1738
- const root = this.roots.get(id);
1739
- if (!root) return;
1740
- for (const jobId of root.jobs.keys()) {
1741
- this.jobStateListeners.delete(jobId);
1742
- }
1743
- this.roots.delete(id);
1744
- if (this.roots.size === 0) {
1745
- this.stop();
1746
- this.errorHandler = null;
1747
- }
1748
- }
1749
- /**
1750
- * Subscribe to be notified when a root becomes available.
1751
- * Fires immediately if a root already exists.
1752
- * @param {() => void} callback - Function called when first root registers
1753
- * @returns {() => void} Unsubscribe function
1754
- */
1755
- onRootReady(callback) {
1756
- if (this.roots.size > 0) {
1757
- callback();
1758
- return () => {
1759
- };
1760
- }
1761
- this.rootReadyCallbacks.add(callback);
1762
- return () => this.rootReadyCallbacks.delete(callback);
1763
- }
1764
- /**
1765
- * Notify all registered root-ready callbacks.
1766
- * Called when the first root registers.
1767
- * @returns {void}
1768
- * @private
1769
- */
1770
- notifyRootReady() {
1771
- for (const cb of this.rootReadyCallbacks) {
1772
- try {
1773
- cb();
1774
- } catch (error) {
1775
- console.error("[Scheduler] Error in root-ready callback:", error);
1776
- }
1777
- }
1778
- this.rootReadyCallbacks.clear();
1779
- }
1780
- /**
1781
- * Ensure a default root exists for independent mode.
1782
- * Creates a minimal root with no state provider.
1783
- * @returns {void}
1784
- * @private
1785
- */
1786
- ensureDefaultRoot() {
1787
- if (!this.roots.has("__default__")) {
1788
- this.registerRoot("__default__");
1789
- }
1790
- }
1791
- /**
1792
- * Trigger error handling for job errors.
1793
- * Uses the bound error handler if available, otherwise logs to console.
1794
- * @param {Error} error - The error to handle
1795
- * @returns {void}
1796
- */
1797
- triggerError(error) {
1798
- if (this.errorHandler) this.errorHandler(error);
1799
- else console.error("[Scheduler]", error);
1800
- }
1801
- //* Phase Management Methods ================================
1802
- /**
1803
- * Add a named phase to the scheduler's execution order.
1804
- * Marks all roots for rebuild to incorporate the new phase.
1805
- * @param {string} name - The phase name (e.g., 'physics', 'postprocess')
1806
- * @param {AddPhaseOptions} [options] - Positioning options (before/after other phases)
1807
- * @returns {void}
1808
- * @example
1809
- * scheduler.addPhase('physics', { before: 'update' });
1810
- * scheduler.addPhase('postprocess', { after: 'render' });
1811
- */
1812
- addPhase(name, options) {
1813
- this.phaseGraph.addPhase(name, options);
1814
- for (const root of this.roots.values()) {
1815
- root.needsRebuild = true;
1816
- }
1817
- }
1818
- /**
1819
- * Check if a phase exists in the scheduler.
1820
- * @param {string} name - The phase name to check
1821
- * @returns {boolean} True if the phase exists
1822
- */
1823
- hasPhase(name) {
1824
- return this.phaseGraph.hasPhase(name);
1825
- }
1826
- //* Global Job Registration Methods (Deprecated APIs) ================================
1827
- /**
1828
- * Register a global job that runs once per frame (not per-root).
1829
- * Used internally by deprecated addEffect/addAfterEffect APIs.
1830
- * @param {'before' | 'after'} phase - When to run: 'before' all roots or 'after' all roots
1831
- * @param {string} id - Unique identifier for this global job
1832
- * @param {(timestamp: number) => void} callback - Function called each frame with RAF timestamp
1833
- * @returns {() => void} Unsubscribe function to remove this global job
1834
- * @deprecated Use useFrame with phases instead
1835
- */
1836
- registerGlobal(phase, id, callback) {
1837
- const job = { id, callback };
1838
- if (phase === "before") {
1839
- this.globalBeforeJobs.set(id, job);
1840
- } else {
1841
- this.globalAfterJobs.set(id, job);
1842
- }
1843
- return () => {
1844
- if (phase === "before") this.globalBeforeJobs.delete(id);
1845
- else this.globalAfterJobs.delete(id);
1846
- };
1847
- }
1848
- //* Idle Callback Methods (Deprecated API) ================================
1849
- /**
1850
- * Register an idle callback that fires when the loop stops.
1851
- * Used internally by deprecated addTail API.
1852
- * @param {(timestamp: number) => void} callback - Function called when loop becomes idle
1853
- * @returns {() => void} Unsubscribe function to remove this idle callback
1854
- * @deprecated Use demand mode with invalidate() instead
1855
- */
1856
- onIdle(callback) {
1857
- this.idleCallbacks.add(callback);
1858
- return () => this.idleCallbacks.delete(callback);
1859
- }
1860
- /**
1861
- * Notify all registered idle callbacks.
1862
- * Called when the loop stops in demand mode.
1863
- * @param {number} timestamp - The RAF timestamp when idle occurred
1864
- * @returns {void}
1865
- * @private
1866
- */
1867
- notifyIdle(timestamp) {
1868
- for (const cb of this.idleCallbacks) {
1869
- try {
1870
- cb(timestamp);
1871
- } catch (error) {
1872
- console.error("[Scheduler] Error in idle callback:", error);
1873
- }
1874
- }
1875
- }
1876
- //* Job Registration & Management Methods ================================
1877
- /**
1878
- * Register a job (frame callback) with a specific root.
1879
- * This is the core registration method used by useFrame internally.
1880
- * @param {FrameNextCallback} callback - The function to call each frame
1881
- * @param {JobOptions & { rootId?: string; system?: boolean }} [options] - Job configuration
1882
- * @param {string} [options.rootId] - Target root ID (defaults to first registered root)
1883
- * @param {string} [options.id] - Unique job ID (auto-generated if not provided)
1884
- * @param {string} [options.phase] - Execution phase (defaults to 'update')
1885
- * @param {number} [options.priority] - Priority within phase (higher = earlier, default 0)
1886
- * @param {number} [options.fps] - FPS throttle limit
1887
- * @param {boolean} [options.drop] - Drop frames when behind (default true)
1888
- * @param {boolean} [options.enabled] - Whether job is active (default true)
1889
- * @param {boolean} [options.system] - Internal flag for system jobs (not user-facing)
1890
- * @returns {() => void} Unsubscribe function to remove this job
1891
- */
1892
- register(callback, options = {}) {
1893
- const rootId = options.rootId;
1894
- const root = rootId ? this.roots.get(rootId) : this.roots.values().next().value;
1895
- if (!root) {
1896
- console.warn("[Scheduler] No root registered. Is this inside a Canvas?");
1897
- return () => {
1898
- };
1899
- }
1900
- const id = options.id ?? this.generateJobId();
1901
- let phase = options.phase ?? "update";
1902
- if (!options.phase && (options.before || options.after)) {
1903
- phase = this.phaseGraph.resolveConstraintPhase(options.before, options.after);
1904
- }
1905
- const before = this.normalizeConstraints(options.before);
1906
- const after = this.normalizeConstraints(options.after);
1907
- const job = {
1908
- id,
1909
- callback,
1910
- phase,
1911
- before,
1912
- after,
1913
- priority: options.priority ?? 0,
1914
- index: this.nextJobIndex++,
1915
- fps: options.fps,
1916
- drop: options.drop ?? true,
1917
- enabled: options.enabled ?? true,
1918
- system: options.system ?? false
1919
- };
1920
- if (root.jobs.has(id)) {
1921
- console.warn(`[useFrame] Job with id "${id}" already exists, replacing`);
1922
- }
1923
- root.jobs.set(id, job);
1924
- root.needsRebuild = true;
1925
- return () => this.unregister(id, root.id);
1926
- }
1927
- /**
1928
- * Unregister a job by its ID.
1929
- * Searches all roots if rootId is not provided.
1930
- * @param {string} id - The job ID to unregister
1931
- * @param {string} [rootId] - Optional root ID to search (searches all if not provided)
1932
- * @returns {void}
1933
- */
1934
- unregister(id, rootId) {
1935
- const root = rootId ? this.roots.get(rootId) : Array.from(this.roots.values()).find((r) => r.jobs.has(id));
1936
- if (root?.jobs.delete(id)) {
1937
- root.needsRebuild = true;
1938
- this.jobStateListeners.delete(id);
1939
- }
1940
- }
1941
- /**
1942
- * Update a job's options dynamically.
1943
- * Searches all roots to find the job by ID.
1944
- * Phase/constraint changes trigger a rebuild of the sorted job list.
1945
- * @param {string} id - The job ID to update
1946
- * @param {Partial<JobOptions>} options - The options to update
1947
- * @returns {void}
1948
- */
1949
- updateJob(id, options) {
1950
- let job;
1951
- let root;
1952
- for (const r of this.roots.values()) {
1953
- job = r.jobs.get(id);
1954
- if (job) {
1955
- root = r;
1956
- break;
1957
- }
1958
- }
1959
- if (!job || !root) return;
1960
- if (options.priority !== void 0) job.priority = options.priority;
1961
- if (options.fps !== void 0) job.fps = options.fps;
1962
- if (options.drop !== void 0) job.drop = options.drop;
1963
- if (options.enabled !== void 0) {
1964
- const wasEnabled = job.enabled;
1965
- job.enabled = options.enabled;
1966
- if (!wasEnabled && job.enabled) resetJobTiming(job);
1967
- if (wasEnabled !== job.enabled) root.needsRebuild = true;
1968
- }
1969
- if (options.phase !== void 0 || options.before !== void 0 || options.after !== void 0) {
1970
- if (options.phase) job.phase = options.phase;
1971
- if (options.before !== void 0) job.before = this.normalizeConstraints(options.before);
1972
- if (options.after !== void 0) job.after = this.normalizeConstraints(options.after);
1973
- root.needsRebuild = true;
1974
- }
1975
- }
1976
- //* Job State Management Methods ================================
1977
- /**
1978
- * Check if a job is currently paused (disabled).
1979
- * @param {string} id - The job ID to check
1980
- * @returns {boolean} True if the job exists and is paused
1981
- */
1982
- isJobPaused(id) {
1983
- for (const root of this.roots.values()) {
1984
- const job = root.jobs.get(id);
1985
- if (job) return !job.enabled;
1986
- }
1987
- return false;
1988
- }
1989
- /**
1990
- * Subscribe to state changes for a specific job.
1991
- * Listener is called when job is paused or resumed.
1992
- * @param {string} id - The job ID to subscribe to
1993
- * @param {() => void} listener - Callback invoked on state changes
1994
- * @returns {() => void} Unsubscribe function
1995
- */
1996
- subscribeJobState(id, listener) {
1997
- if (!this.jobStateListeners.has(id)) {
1998
- this.jobStateListeners.set(id, /* @__PURE__ */ new Set());
1999
- }
2000
- this.jobStateListeners.get(id).add(listener);
2001
- return () => {
2002
- this.jobStateListeners.get(id)?.delete(listener);
2003
- if (this.jobStateListeners.get(id)?.size === 0) {
2004
- this.jobStateListeners.delete(id);
2005
- }
2006
- };
2007
- }
2008
- /**
2009
- * Notify all listeners that a job's state has changed.
2010
- * @param {string} id - The job ID that changed
2011
- * @returns {void}
2012
- * @private
2013
- */
2014
- notifyJobStateChange(id) {
2015
- this.jobStateListeners.get(id)?.forEach((listener) => listener());
2016
- }
2017
- /**
2018
- * Pause a job by ID (sets enabled=false).
2019
- * Notifies any subscribed state listeners.
2020
- * @param {string} id - The job ID to pause
2021
- * @returns {void}
2022
- */
2023
- pauseJob(id) {
2024
- this.updateJob(id, { enabled: false });
2025
- this.notifyJobStateChange(id);
2026
- }
2027
- /**
2028
- * Resume a paused job by ID (sets enabled=true).
2029
- * Resets job timing to prevent frame accumulation.
2030
- * Notifies any subscribed state listeners.
2031
- * @param {string} id - The job ID to resume
2032
- * @returns {void}
2033
- */
2034
- resumeJob(id) {
2035
- this.updateJob(id, { enabled: true });
2036
- this.notifyJobStateChange(id);
2037
- }
2038
- //* Frame Loop Control Methods ================================
2039
- /**
2040
- * Start the requestAnimationFrame loop.
2041
- * Resets timing state (elapsedTime, frameCount) on start.
2042
- * No-op if already running.
2043
- * @returns {void}
2044
- */
2045
- start() {
2046
- if (this.loopState.running) return;
2047
- const { elapsedTime, createdAt } = this.loopState;
2048
- let adjustedCreated = 0;
2049
- if (this.stoppedTime > 0) {
2050
- adjustedCreated = createdAt - (performance.now() - this.stoppedTime);
2051
- this.stoppedTime = 0;
2052
- }
2053
- Object.assign(this.loopState, {
2054
- running: true,
2055
- elapsedTime: elapsedTime ?? 0,
2056
- lastTime: performance.now(),
2057
- createdAt: adjustedCreated > 0 ? adjustedCreated : performance.now(),
2058
- frameCount: 0,
2059
- rafHandle: requestAnimationFrame(this.loop)
2060
- });
2061
- }
2062
- /**
2063
- * Stop the requestAnimationFrame loop.
2064
- * Cancels any pending RAF callback.
2065
- * No-op if not running.
2066
- * @returns {void}
2067
- */
2068
- stop() {
2069
- if (!this.loopState.running) return;
2070
- this.loopState.running = false;
2071
- if (this.loopState.rafHandle !== null) {
2072
- cancelAnimationFrame(this.loopState.rafHandle);
2073
- this.loopState.rafHandle = null;
2074
- }
2075
- this.stoppedTime = performance.now();
2076
- }
2077
- /**
2078
- * Request frames to be rendered in demand mode.
2079
- * Accumulates pending frames (capped at 60) and starts the loop if not running.
2080
- * No-op if frameloop is not 'demand'.
2081
- * @param {number} [frames=1] - Number of frames to request
2082
- * @param {boolean} [stackFrames=false] - Whether to add frames to existing pending count
2083
- * - `false` (default): Sets pending frames to the specified value (replaces existing count)
2084
- * - `true`: Adds frames to existing pending count (useful for accumulating invalidations)
2085
- * @returns {void}
2086
- * @example
2087
- * // Request a single frame render
2088
- * scheduler.invalidate();
2089
- *
2090
- * @example
2091
- * // Request 5 frames (e.g., for animations)
2092
- * scheduler.invalidate(5);
2093
- *
2094
- * @example
2095
- * // Set pending frames to exactly 3 (don't stack with existing)
2096
- * scheduler.invalidate(3, false);
2097
- *
2098
- * @example
2099
- * // Add 2 more frames to existing pending count
2100
- * scheduler.invalidate(2, true);
2101
- */
2102
- invalidate(frames = 1, stackFrames = false) {
2103
- if (this._frameloop !== "demand") return;
2104
- const baseFrames = stackFrames ? this.pendingFrames : 0;
2105
- this.pendingFrames = Math.min(60, baseFrames + frames);
2106
- if (!this.loopState.running && this.pendingFrames > 0) this.start();
2107
- }
2108
- /**
2109
- * Reset timing state for deterministic testing.
2110
- * Preserves jobs and roots but resets lastTime, frameCount, elapsedTime, etc.
2111
- * @returns {void}
2112
- */
2113
- resetTiming() {
2114
- this.loopState.lastTime = null;
2115
- this.loopState.frameCount = 0;
2116
- this.loopState.elapsedTime = 0;
2117
- this.loopState.createdAt = performance.now();
2118
- }
2119
- //* Manual Stepping Methods ================================
2120
- /**
2121
- * Manually execute a single frame for all roots.
2122
- * Useful for frameloop='never' mode or testing scenarios.
2123
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2124
- * @returns {void}
2125
- * @example
2126
- * // Manual control mode
2127
- * scheduler.frameloop = 'never';
2128
- * scheduler.step(); // Execute one frame
2129
- */
2130
- step(timestamp) {
2131
- const now = timestamp ?? performance.now();
2132
- this.executeFrame(now);
2133
- }
2134
- /**
2135
- * Manually execute a single job by its ID.
2136
- * Useful for testing individual job callbacks in isolation.
2137
- * @param {string} id - The job ID to step
2138
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2139
- * @returns {void}
2140
- */
2141
- stepJob(id, timestamp) {
2142
- let job;
2143
- let root;
2144
- for (const r of this.roots.values()) {
2145
- job = r.jobs.get(id);
2146
- if (job) {
2147
- root = r;
2148
- break;
2149
- }
2150
- }
2151
- if (!job || !root) {
2152
- console.warn(`[Scheduler] Job "${id}" not found`);
2153
- return;
2154
- }
2155
- const now = timestamp ?? performance.now();
2156
- const deltaMs = this.loopState.lastTime !== null ? now - this.loopState.lastTime : 0;
2157
- const delta = deltaMs / 1e3;
2158
- const elapsed = now - this.loopState.createdAt;
2159
- const providedState = root.getState?.() ?? {};
2160
- const frameState = {
2161
- ...providedState,
2162
- time: now,
2163
- delta,
2164
- elapsed,
2165
- frame: this.loopState.frameCount
2166
- };
2167
- try {
2168
- job.callback(frameState, delta);
2169
- } catch (error) {
2170
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2171
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2172
- }
2173
- }
2174
- /**
2175
- * Execute a single frame across all roots.
2176
- * Order: globalBefore → each root's jobs → globalAfter
2177
- * @param {number} timestamp - RAF timestamp in milliseconds
2178
- * @returns {void}
2179
- * @private
2180
- */
2181
- executeFrame(timestamp) {
2182
- const deltaMs = this.loopState.lastTime !== null ? timestamp - this.loopState.lastTime : 0;
2183
- const delta = deltaMs / 1e3;
2184
- this.loopState.lastTime = timestamp;
2185
- this.loopState.frameCount++;
2186
- this.loopState.elapsedTime += deltaMs;
2187
- this.runGlobalJobs(this.globalBeforeJobs, timestamp);
2188
- for (const root of this.roots.values()) {
2189
- this.tickRoot(root, timestamp, delta);
2190
- }
2191
- this.runGlobalJobs(this.globalAfterJobs, timestamp);
2192
- }
2193
- /**
2194
- * Run all global jobs from a job map.
2195
- * Catches and logs errors without stopping execution.
2196
- * @param {Map<string, GlobalJob>} jobs - The global jobs map to execute
2197
- * @param {number} timestamp - RAF timestamp in milliseconds
2198
- * @returns {void}
2199
- * @private
2200
- */
2201
- runGlobalJobs(jobs, timestamp) {
2202
- for (const job of jobs.values()) {
2203
- try {
2204
- job.callback(timestamp);
2205
- } catch (error) {
2206
- console.error(`[Scheduler] Error in global job "${job.id}":`, error);
2207
- }
2208
- }
2209
- }
2210
- /**
2211
- * Execute all jobs for a single root in sorted order.
2212
- * Rebuilds sorted job list if needed, then dispatches each job.
2213
- * Errors are caught and propagated via triggerError.
2214
- * @param {RootEntry} root - The root entry to tick
2215
- * @param {number} timestamp - RAF timestamp in milliseconds
2216
- * @param {number} delta - Time since last frame in seconds
2217
- * @returns {void}
2218
- * @private
2219
- */
2220
- tickRoot(root, timestamp, delta) {
2221
- if (root.needsRebuild) {
2222
- root.sortedJobs = rebuildSortedJobs(root.jobs, this.phaseGraph);
2223
- root.needsRebuild = false;
2224
- }
2225
- const providedState = root.getState?.() ?? {};
2226
- const frameState = {
2227
- ...providedState,
2228
- time: timestamp,
2229
- delta,
2230
- elapsed: this.loopState.elapsedTime / 1e3,
2231
- // Convert ms to seconds
2232
- frame: this.loopState.frameCount
2233
- };
2234
- for (const job of root.sortedJobs) {
2235
- if (!shouldRun(job, timestamp)) continue;
2236
- try {
2237
- job.callback(frameState, delta);
2238
- } catch (error) {
2239
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2240
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2241
- }
2242
- }
2243
- }
2244
- //* Debug & Inspection Methods ================================
2245
- /**
2246
- * Get the total number of registered jobs across all roots.
2247
- * Includes both per-root jobs and global before/after jobs.
2248
- * @returns {number} Total job count
2249
- */
2250
- getJobCount() {
2251
- let count = 0;
2252
- for (const root of this.roots.values()) {
2253
- count += root.jobs.size;
2254
- }
2255
- return count + this.globalBeforeJobs.size + this.globalAfterJobs.size;
2256
- }
2257
- /**
2258
- * Get all registered job IDs across all roots.
2259
- * Includes both per-root jobs and global before/after jobs.
2260
- * @returns {string[]} Array of all job IDs
2261
- */
2262
- getJobIds() {
2263
- const ids = [];
2264
- for (const root of this.roots.values()) {
2265
- ids.push(...root.jobs.keys());
2266
- }
2267
- ids.push(...this.globalBeforeJobs.keys());
2268
- ids.push(...this.globalAfterJobs.keys());
2269
- return ids;
2270
- }
2271
- /**
2272
- * Get the number of registered roots (Canvas instances).
2273
- * @returns {number} Number of registered roots
2274
- */
2275
- getRootCount() {
2276
- return this.roots.size;
2277
- }
2278
- /**
2279
- * Check if any user (non-system) jobs are registered in a specific phase.
2280
- * Used by the default render job to know if a user has taken over rendering.
2281
- *
2282
- * @param phase The phase to check
2283
- * @param rootId Optional root ID to check (checks all roots if not provided)
2284
- * @returns true if any user jobs exist in the phase
2285
- */
2286
- hasUserJobsInPhase(phase, rootId) {
2287
- const rootsToCheck = rootId ? [this.roots.get(rootId)].filter(Boolean) : Array.from(this.roots.values());
2288
- return rootsToCheck.some((root) => {
2289
- if (!root) return false;
2290
- for (const job of root.jobs.values()) {
2291
- if (job.phase === phase && !job.system && job.enabled) return true;
2292
- }
2293
- return false;
2294
- });
2295
- }
2296
- //* Utility Methods ================================
2297
- /**
2298
- * Generate a unique root ID for automatic root registration.
2299
- * @returns {string} A unique root ID in the format 'root_N'
2300
- */
2301
- generateRootId() {
2302
- return `root_${this.nextRootIndex++}`;
2303
- }
2304
- /**
2305
- * Generate a unique job ID.
2306
- * @returns {string} A unique job ID in the format 'job_N'
2307
- * @private
2308
- */
2309
- generateJobId() {
2310
- return `job_${this.nextJobIndex}`;
2311
- }
2312
- /**
2313
- * Normalize before/after constraints to a Set.
2314
- * Handles undefined, single string, or array inputs.
2315
- * @param {string | string[] | undefined} value - The constraint value(s)
2316
- * @returns {Set<string>} Normalized Set of constraint strings
2317
- * @private
2318
- */
2319
- normalizeConstraints(value) {
2320
- if (!value) return /* @__PURE__ */ new Set();
2321
- if (Array.isArray(value)) return new Set(value);
2322
- return /* @__PURE__ */ new Set([value]);
2323
- }
2324
- };
2325
- //* Static State & Methods (Singleton Usage) ================================
2326
- //* Cross-Bundle Singleton Key ==============================
2327
- // Use Symbol.for() to ensure scheduler is shared across bundle boundaries
2328
- // This prevents issues when mixing imports from @react-three/fiber and @react-three/fiber/webgpu
2329
- __publicField(_Scheduler, "INSTANCE_KEY", Symbol.for("@react-three/fiber.scheduler"));
2330
- let Scheduler = _Scheduler;
2331
- const getScheduler = () => Scheduler.get();
2332
- if (hmrData) {
2333
- hmrData.accept?.();
2334
- }
2335
-
2336
2010
  function useFrame(callback, priorityOrOptions) {
2337
2011
  const store = React.useContext(context);
2338
2012
  const isInsideCanvas = store !== null;
@@ -2405,20 +2079,14 @@ function useFrame(callback, priorityOrOptions) {
2405
2079
  }
2406
2080
  };
2407
2081
  } else {
2408
- const registerOutside = () => {
2409
- return scheduler.register((state, delta) => callbackRef.current?.(state, delta), { id, ...options });
2410
- };
2411
- if (scheduler.independent || scheduler.isReady) {
2412
- return registerOutside();
2413
- }
2414
- let unregisterJob = null;
2415
- const unsubReady = scheduler.onRootReady(() => {
2416
- unregisterJob = registerOutside();
2417
- });
2418
- return () => {
2419
- unsubReady();
2420
- unregisterJob?.();
2421
- };
2082
+ return scheduler.register(
2083
+ (state, delta) => {
2084
+ const frameState = state;
2085
+ if (!frameState.renderer) return;
2086
+ callbackRef.current?.(frameState, delta);
2087
+ },
2088
+ { id, ...options }
2089
+ );
2422
2090
  }
2423
2091
  }, [store, scheduler, id, optionsKey, isLegacyPriority, isInsideCanvas]);
2424
2092
  const isPaused = React.useSyncExternalStore(
@@ -2509,22 +2177,29 @@ function buildFromCache(input, textureCache) {
2509
2177
  function useTexture(input, optionsOrOnLoad) {
2510
2178
  const renderer = useThree((state) => state.internal.actualRenderer);
2511
2179
  const store = useStore();
2512
- const textureCache = useThree((state) => state.textures);
2513
2180
  const options = typeof optionsOrOnLoad === "function" ? { onLoad: optionsOrOnLoad } : optionsOrOnLoad ?? {};
2514
- const { onLoad, cache = false } = options;
2181
+ const { onLoad, cache = true } = options;
2182
+ const onLoadRef = useRef(onLoad);
2183
+ onLoadRef.current = onLoad;
2184
+ const onLoadCalledForRef = useRef(null);
2515
2185
  const urls = useMemo(() => getUrls(input), [input]);
2516
2186
  const cachedResult = useMemo(() => {
2517
2187
  if (!cache) return null;
2518
- if (!allUrlsCached(urls, textureCache)) return null;
2519
- return buildFromCache(input, textureCache);
2520
- }, [cache, urls, textureCache, input]);
2188
+ const textures = store.getState().textures;
2189
+ if (!allUrlsCached(urls, textures)) return null;
2190
+ return buildFromCache(input, textures);
2191
+ }, [cache, urls, input, store]);
2521
2192
  const loadedTextures = useLoader(
2522
2193
  TextureLoader,
2523
2194
  IsObject(input) ? Object.values(input) : input
2524
2195
  );
2196
+ const inputKey = urls.join("\0");
2525
2197
  useLayoutEffect(() => {
2526
- if (!cachedResult) onLoad?.(loadedTextures);
2527
- }, [onLoad, cachedResult, loadedTextures]);
2198
+ if (cachedResult) return;
2199
+ if (onLoadCalledForRef.current === inputKey) return;
2200
+ onLoadCalledForRef.current = inputKey;
2201
+ onLoadRef.current?.(loadedTextures);
2202
+ }, [cachedResult, loadedTextures, inputKey]);
2528
2203
  useEffect(() => {
2529
2204
  if (cachedResult) return;
2530
2205
  if ("initTexture" in renderer) {
@@ -2557,8 +2232,6 @@ function useTexture(input, optionsOrOnLoad) {
2557
2232
  }, [input, loadedTextures, cachedResult]);
2558
2233
  useEffect(() => {
2559
2234
  if (!cache) return;
2560
- if (cachedResult) return;
2561
- const set = store.setState;
2562
2235
  const urlTextureMap = [];
2563
2236
  if (typeof input === "string") {
2564
2237
  urlTextureMap.push([input, mappedTextures]);
@@ -2572,18 +2245,32 @@ function useTexture(input, optionsOrOnLoad) {
2572
2245
  urlTextureMap.push([url, textureRecord[key]]);
2573
2246
  }
2574
2247
  }
2575
- set((state) => {
2576
- const newMap = new Map(state.textures);
2577
- let changed = false;
2248
+ store.setState((state) => {
2249
+ const refs = new Map(state._textureRefs);
2250
+ let textures = state.textures;
2251
+ let added = false;
2578
2252
  for (const [url, texture] of urlTextureMap) {
2579
- if (!newMap.has(url)) {
2580
- newMap.set(url, texture);
2581
- changed = true;
2253
+ if (!textures.has(url)) {
2254
+ if (!added) {
2255
+ textures = new Map(textures);
2256
+ added = true;
2257
+ }
2258
+ textures.set(url, texture);
2582
2259
  }
2260
+ refs.set(url, (refs.get(url) ?? 0) + 1);
2583
2261
  }
2584
- return changed ? { textures: newMap } : state;
2262
+ return added ? { textures, _textureRefs: refs } : { _textureRefs: refs };
2263
+ });
2264
+ return () => store.setState((state) => {
2265
+ const refs = new Map(state._textureRefs);
2266
+ for (const [url] of urlTextureMap) {
2267
+ const next = (refs.get(url) ?? 0) - 1;
2268
+ if (next <= 0) refs.delete(url);
2269
+ else refs.set(url, next);
2270
+ }
2271
+ return { _textureRefs: refs };
2585
2272
  });
2586
- }, [cache, input, mappedTextures, store, cachedResult]);
2273
+ }, [cache, input, mappedTextures, store]);
2587
2274
  return mappedTextures;
2588
2275
  }
2589
2276
  useTexture.preload = (url) => useLoader.preload(TextureLoader, url);
@@ -2599,106 +2286,90 @@ const Texture = ({
2599
2286
  return /* @__PURE__ */ jsx(Fragment, { children: children?.(ret) });
2600
2287
  };
2601
2288
 
2602
- function getTextureValue(entry) {
2603
- if (entry instanceof Texture$1) return entry;
2604
- if (entry && typeof entry === "object" && "value" in entry && entry.value instanceof Texture$1) {
2605
- return entry.value;
2606
- }
2607
- return null;
2608
- }
2609
- function useTextures() {
2289
+ function useTextures(selector) {
2610
2290
  const store = useStore();
2611
- return useMemo(() => {
2612
- const set = store.setState;
2291
+ const registry = useMemo(() => {
2613
2292
  const getState = store.getState;
2614
- const add = (key, value) => {
2615
- set((state) => {
2616
- const newMap = new Map(state.textures);
2617
- newMap.set(key, value);
2618
- return { textures: newMap };
2619
- });
2620
- };
2621
- const addMultiple = (items) => {
2622
- set((state) => {
2623
- const newMap = new Map(state.textures);
2624
- const entries = items instanceof Map ? items.entries() : Object.entries(items);
2625
- for (const [key, value] of entries) {
2626
- newMap.set(key, value);
2627
- }
2628
- return { textures: newMap };
2629
- });
2630
- };
2631
- const remove = (key) => {
2632
- set((state) => {
2633
- const newMap = new Map(state.textures);
2634
- newMap.delete(key);
2635
- return { textures: newMap };
2636
- });
2637
- };
2638
- const removeMultiple = (keys) => {
2639
- set((state) => {
2640
- const newMap = new Map(state.textures);
2641
- for (const key of keys) newMap.delete(key);
2642
- return { textures: newMap };
2643
- });
2644
- };
2645
- const dispose = (key) => {
2646
- const entry = getState().textures.get(key);
2647
- if (entry) {
2648
- const tex = getTextureValue(entry);
2649
- tex?.dispose();
2650
- }
2651
- remove(key);
2652
- };
2653
- const disposeMultiple = (keys) => {
2654
- const textures = getState().textures;
2655
- for (const key of keys) {
2656
- const entry = textures.get(key);
2657
- if (entry) {
2658
- const tex = getTextureValue(entry);
2659
- tex?.dispose();
2660
- }
2661
- }
2662
- removeMultiple(keys);
2663
- };
2664
- const disposeAll = () => {
2665
- const textures = getState().textures;
2666
- for (const entry of textures.values()) {
2667
- const tex = getTextureValue(entry);
2668
- tex?.dispose();
2669
- }
2670
- set({ textures: /* @__PURE__ */ new Map() });
2671
- };
2293
+ const setState = store.setState;
2294
+ const getOne = (key) => getState().textures.get(key);
2672
2295
  return {
2673
- // Getter for the textures Map (reactive via getState)
2674
- get textures() {
2296
+ get all() {
2675
2297
  return getState().textures;
2676
2298
  },
2677
- // Read
2678
- get: (key) => getState().textures.get(key),
2299
+ get(input) {
2300
+ if (typeof input === "string") return getOne(input);
2301
+ if (Array.isArray(input)) return input.map(getOne);
2302
+ const out = {};
2303
+ for (const name in input) out[name] = getOne(input[name]);
2304
+ return out;
2305
+ },
2679
2306
  has: (key) => getState().textures.has(key),
2680
- // Write
2681
- add,
2682
- addMultiple,
2683
- // Remove (cache only)
2684
- remove,
2685
- removeMultiple,
2686
- // Dispose (GPU + cache)
2687
- dispose,
2688
- disposeMultiple,
2689
- disposeAll
2307
+ add(keyOrRecord, texture) {
2308
+ setState((state) => {
2309
+ const textures = new Map(state.textures);
2310
+ if (typeof keyOrRecord === "string") {
2311
+ textures.set(keyOrRecord, texture);
2312
+ } else {
2313
+ for (const key in keyOrRecord) textures.set(key, keyOrRecord[key]);
2314
+ }
2315
+ return { textures };
2316
+ });
2317
+ },
2318
+ dispose(key, options) {
2319
+ const state = getState();
2320
+ const refs = state._textureRefs.get(key) ?? 0;
2321
+ if (refs > 0 && !options?.force) {
2322
+ console.warn(
2323
+ `[useTextures] "${key}" still has ${refs} active reference(s); skipping dispose. Pass { force: true } to override.`
2324
+ );
2325
+ return false;
2326
+ }
2327
+ state.textures.get(key)?.dispose();
2328
+ setState((s) => {
2329
+ const textures = new Map(s.textures);
2330
+ textures.delete(key);
2331
+ const nextRefs = new Map(s._textureRefs);
2332
+ nextRefs.delete(key);
2333
+ return { textures, _textureRefs: nextRefs };
2334
+ });
2335
+ return true;
2336
+ },
2337
+ disposeAll() {
2338
+ for (const texture of getState().textures.values()) texture.dispose();
2339
+ setState({ textures: /* @__PURE__ */ new Map(), _textureRefs: /* @__PURE__ */ new Map() });
2340
+ }
2690
2341
  };
2691
2342
  }, [store]);
2343
+ const subscribe = selector ? () => selector(registry) : (state) => state.textures;
2344
+ const selected = useThree(subscribe);
2345
+ return selector ? selected : registry;
2692
2346
  }
2693
2347
 
2694
- function useRenderTarget(width, height, options) {
2348
+ function useRenderTarget(widthOrOptions, heightOrOptions, options) {
2695
2349
  const isLegacy = useThree((s) => s.isLegacy);
2696
2350
  const size = useThree((s) => s.size);
2351
+ let width;
2352
+ let height;
2353
+ let opts;
2354
+ if (typeof widthOrOptions === "object") {
2355
+ opts = widthOrOptions;
2356
+ } else if (typeof widthOrOptions === "number") {
2357
+ width = widthOrOptions;
2358
+ if (typeof heightOrOptions === "object") {
2359
+ height = widthOrOptions;
2360
+ opts = heightOrOptions;
2361
+ } else if (typeof heightOrOptions === "number") {
2362
+ height = heightOrOptions;
2363
+ opts = options;
2364
+ } else {
2365
+ height = widthOrOptions;
2366
+ }
2367
+ }
2697
2368
  return useMemo(() => {
2698
2369
  const w = width ?? size.width;
2699
2370
  const h = height ?? size.height;
2700
- return new WebGLRenderTarget(w, h, options);
2701
- }, [width, height, size.width, size.height, options, isLegacy]);
2371
+ return new WebGLRenderTarget(w, h, opts);
2372
+ }, [width, height, size.width, size.height, opts, isLegacy]);
2702
2373
  }
2703
2374
 
2704
2375
  function useStore() {
@@ -2748,28 +2419,18 @@ function addTail(callback) {
2748
2419
  function invalidate(state, frames = 1, stackFrames = false) {
2749
2420
  getScheduler().invalidate(frames, stackFrames);
2750
2421
  }
2751
- function advance(timestamp, runGlobalEffects = true, state, frame) {
2422
+ function advance(timestamp) {
2752
2423
  getScheduler().step(timestamp);
2753
2424
  }
2754
2425
 
2755
- const version = "10.0.0-alpha.1";
2426
+ const version = "10.0.0-alpha.3";
2756
2427
  const packageData = {
2757
2428
  version: version};
2758
2429
 
2759
2430
  function Xb(Tt) {
2760
2431
  return Tt && Tt.__esModule && Object.prototype.hasOwnProperty.call(Tt, "default") ? Tt.default : Tt;
2761
2432
  }
2762
- var Rm = { exports: {} }, Og = { exports: {} };
2763
- /**
2764
- * @license React
2765
- * react-reconciler.production.js
2766
- *
2767
- * Copyright (c) Meta Platforms, Inc. and affiliates.
2768
- *
2769
- * This source code is licensed under the MIT license found in the
2770
- * LICENSE file in the root directory of this source tree.
2771
- */
2772
- var _b;
2433
+ var Rm = { exports: {} }, Og = { exports: {} }, _b;
2773
2434
  function Kb() {
2774
2435
  return _b || (_b = 1, (function(Tt) {
2775
2436
  Tt.exports = function(m) {
@@ -3841,7 +3502,6 @@ Error generating stack: ` + l.message + `
3841
3502
  if (J === cl || J === jc) throw J;
3842
3503
  var Ge = Yn(29, J, null, P.mode);
3843
3504
  return Ge.lanes = H, Ge.return = P, Ge;
3844
- } finally {
3845
3505
  }
3846
3506
  };
3847
3507
  }
@@ -4495,7 +4155,6 @@ Error generating stack: ` + l.message + `
4495
4155
  var h = r.lastRenderedState, y = d(h, a);
4496
4156
  if (c.hasEagerState = true, c.eagerState = y, jn(y, h)) return go(t, r, c, 0), Ne === null && Bn(), false;
4497
4157
  } catch {
4498
- } finally {
4499
4158
  }
4500
4159
  if (a = yo(t, r, c, l), a !== null) return nt(a, t, l), ns(a, r, l), true;
4501
4160
  }
@@ -6916,10 +6575,7 @@ Error generating stack: ` + l.message + `
6916
6575
  function vr(t, r) {
6917
6576
  Sf(t, r), (t = t.alternate) && Sf(t, r);
6918
6577
  }
6919
- var ie = {}, Fm = React__default, tt = Tb, Lt = Object.assign, hc = Symbol.for("react.element"), zs = Symbol.for("react.transitional.element"), sa = Symbol.for("react.portal"), $a = Symbol.for("react.fragment"), kf = Symbol.for("react.strict_mode"), Cs = Symbol.for("react.profiler"), mc = Symbol.for("react.consumer"), Io = Symbol.for("react.context"), Zi = Symbol.for("react.forward_ref"), Va = Symbol.for("react.suspense"), Te = Symbol.for("react.suspense_list"), wf = Symbol.for("react.memo"), ua = Symbol.for("react.lazy");
6920
- var gc = Symbol.for("react.activity");
6921
- var $r = Symbol.for("react.memo_cache_sentinel");
6922
- var Pf = Symbol.iterator, xf = Symbol.for("react.client.reference"), ca = Array.isArray, M = Fm.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, Yp = m.rendererVersion, zf = m.rendererPackageName, Cf = m.extraDevToolsConfig, Ts = m.getPublicInstance, Hm = m.getRootHostContext, Xp = m.getChildHostContext, Am = m.prepareForCommit, _s = m.resetAfterCommit, Vr = m.createInstance;
6578
+ var ie = {}, Fm = React__default, tt = Tb, Lt = Object.assign, hc = Symbol.for("react.element"), zs = Symbol.for("react.transitional.element"), sa = Symbol.for("react.portal"), $a = Symbol.for("react.fragment"), kf = Symbol.for("react.strict_mode"), Cs = Symbol.for("react.profiler"), mc = Symbol.for("react.consumer"), Io = Symbol.for("react.context"), Zi = Symbol.for("react.forward_ref"), Va = Symbol.for("react.suspense"), Te = Symbol.for("react.suspense_list"), wf = Symbol.for("react.memo"), ua = Symbol.for("react.lazy"), gc = Symbol.for("react.activity"), $r = Symbol.for("react.memo_cache_sentinel"), Pf = Symbol.iterator, xf = Symbol.for("react.client.reference"), ca = Array.isArray, M = Fm.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, Yp = m.rendererVersion, zf = m.rendererPackageName, Cf = m.extraDevToolsConfig, Ts = m.getPublicInstance, Hm = m.getRootHostContext, Xp = m.getChildHostContext, Am = m.prepareForCommit, _s = m.resetAfterCommit, Vr = m.createInstance;
6923
6579
  m.cloneMutableInstance;
6924
6580
  var yc = m.appendInitialChild, Kp = m.finalizeInitialChildren, Rs = m.shouldSetTextContent, bc = m.createTextInstance;
6925
6581
  m.cloneMutableTextInstance;
@@ -7288,17 +6944,7 @@ No matching component was found for:
7288
6944
  }, Tt.exports.default = Tt.exports, Object.defineProperty(Tt.exports, "__esModule", { value: true });
7289
6945
  })(Og)), Og.exports;
7290
6946
  }
7291
- var Mg = { exports: {} };
7292
- /**
7293
- * @license React
7294
- * react-reconciler.development.js
7295
- *
7296
- * Copyright (c) Meta Platforms, Inc. and affiliates.
7297
- *
7298
- * This source code is licensed under the MIT license found in the
7299
- * LICENSE file in the root directory of this source tree.
7300
- */
7301
- var Rb;
6947
+ var Mg = { exports: {} }, Rb;
7302
6948
  function e0() {
7303
6949
  return Rb || (Rb = 1, (function(Tt) {
7304
6950
  process.env.NODE_ENV !== "production" && (Tt.exports = function(m) {
@@ -13065,10 +12711,7 @@ Check the render method of %s.`, G(di) || "Unknown")), i = zo(n), i.payload = {
13065
12711
  function Ic() {
13066
12712
  return di;
13067
12713
  }
13068
- var le = {}, qm = React__default, St = Tb, ze = Object.assign, Uh = Symbol.for("react.element"), Ho = Symbol.for("react.transitional.element"), Ao = Symbol.for("react.portal"), ol = Symbol.for("react.fragment"), Lc = Symbol.for("react.strict_mode"), Uf = Symbol.for("react.profiler"), ei = Symbol.for("react.consumer"), on = Symbol.for("react.context"), jn = Symbol.for("react.forward_ref"), Nc = Symbol.for("react.suspense"), Bf = Symbol.for("react.suspense_list"), al = Symbol.for("react.memo"), kt = Symbol.for("react.lazy");
13069
- var Ds = Symbol.for("react.activity");
13070
- var Bh = Symbol.for("react.memo_cache_sentinel");
13071
- var ni = Symbol.iterator, il = Symbol.for("react.client.reference"), fn = Array.isArray, x = qm.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, Jt = m.rendererVersion, Zt = m.rendererPackageName, jo = m.extraDevToolsConfig, ot = m.getPublicInstance, Zr = m.getRootHostContext, Dn = m.getChildHostContext, Ws = m.prepareForCommit, pa = m.resetAfterCommit, Fc = m.createInstance;
12714
+ var le = {}, qm = React__default, St = Tb, ze = Object.assign, Uh = Symbol.for("react.element"), Ho = Symbol.for("react.transitional.element"), Ao = Symbol.for("react.portal"), ol = Symbol.for("react.fragment"), Lc = Symbol.for("react.strict_mode"), Uf = Symbol.for("react.profiler"), ei = Symbol.for("react.consumer"), on = Symbol.for("react.context"), jn = Symbol.for("react.forward_ref"), Nc = Symbol.for("react.suspense"), Bf = Symbol.for("react.suspense_list"), al = Symbol.for("react.memo"), kt = Symbol.for("react.lazy"), Ds = Symbol.for("react.activity"), Bh = Symbol.for("react.memo_cache_sentinel"), ni = Symbol.iterator, il = Symbol.for("react.client.reference"), fn = Array.isArray, x = qm.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, Jt = m.rendererVersion, Zt = m.rendererPackageName, jo = m.extraDevToolsConfig, ot = m.getPublicInstance, Zr = m.getRootHostContext, Dn = m.getChildHostContext, Ws = m.prepareForCommit, pa = m.resetAfterCommit, Fc = m.createInstance;
13072
12715
  m.cloneMutableInstance;
13073
12716
  var bn = m.appendInitialChild, Ue = m.finalizeInitialChildren, ue = m.shouldSetTextContent, Do = m.createTextInstance;
13074
12717
  m.cloneMutableTextInstance;
@@ -14036,15 +13679,6 @@ function n0() {
14036
13679
  var t0 = n0();
14037
13680
  const r0 = Xb(t0);
14038
13681
 
14039
- /**
14040
- * @license React
14041
- * react-reconciler-constants.production.js
14042
- *
14043
- * Copyright (c) Meta Platforms, Inc. and affiliates.
14044
- *
14045
- * This source code is licensed under the MIT license found in the
14046
- * LICENSE file in the root directory of this source tree.
14047
- */
14048
13682
  const t = 1, o = 8, r = 32, e = 2;
14049
13683
 
14050
13684
  function createReconciler(config) {
@@ -14071,10 +13705,11 @@ function extend(objects) {
14071
13705
  function validateInstance(type, props) {
14072
13706
  const name = toPascalCase(type);
14073
13707
  const target = catalogue[name];
14074
- if (type !== "primitive" && !target)
13708
+ if (type !== "primitive" && !target) {
14075
13709
  throw new Error(
14076
13710
  `R3F: ${name} is not part of the THREE namespace! Did you forget to extend? See: https://docs.pmnd.rs/react-three-fiber/api/objects#using-3rd-party-objects-declaratively`
14077
13711
  );
13712
+ }
14078
13713
  if (type === "primitive" && !props.object) throw new Error(`R3F: Primitives without 'object' are invalid!`);
14079
13714
  if (props.args !== void 0 && !Array.isArray(props.args)) throw new Error("R3F: The args prop must be an array!");
14080
13715
  }
@@ -14227,6 +13862,7 @@ function swapInstances() {
14227
13862
  }
14228
13863
  }
14229
13864
  if (instance.isHidden) unhideInstance(instance);
13865
+ if (isObject3D(instance.object)) removeInteractivity(findInitialRoot(instance), instance.object);
14230
13866
  if (instance.object.__r3f) delete instance.object.__r3f;
14231
13867
  if (instance.type !== "primitive") disposeOnIdle(instance.object);
14232
13868
  }
@@ -14238,6 +13874,9 @@ function swapInstances() {
14238
13874
  instance.object = instance.props.object ?? new target(...instance.props.args ?? []);
14239
13875
  instance.object.__r3f = instance;
14240
13876
  setFiberRef(fiber, instance.object);
13877
+ delete instance.appliedOnce;
13878
+ instance.eventCount = 0;
13879
+ instance.handlers = {};
14241
13880
  applyProps(instance.object, instance.props);
14242
13881
  if (instance.props.attach) {
14243
13882
  attach(parent, instance);
@@ -14311,8 +13950,22 @@ const reconciler = /* @__PURE__ */ createReconciler({
14311
13950
  const isTailSibling = fiber.sibling === null || (fiber.flags & Update) === NoFlags;
14312
13951
  if (isTailSibling) swapInstances();
14313
13952
  },
14314
- finalizeInitialChildren: () => false,
14315
- commitMount() {
13953
+ finalizeInitialChildren: (instance) => {
13954
+ for (const prop in instance.props) {
13955
+ if (isFromRef(instance.props[prop])) return true;
13956
+ }
13957
+ return false;
13958
+ },
13959
+ commitMount(instance) {
13960
+ const resolved = {};
13961
+ for (const prop in instance.props) {
13962
+ const value = instance.props[prop];
13963
+ if (isFromRef(value)) {
13964
+ const ref = value[FROM_REF];
13965
+ if (ref.current != null) resolved[prop] = ref.current;
13966
+ }
13967
+ }
13968
+ if (Object.keys(resolved).length) applyProps(instance.object, resolved);
14316
13969
  },
14317
13970
  getPublicInstance: (instance) => instance?.object,
14318
13971
  prepareForCommit: () => null,
@@ -14439,11 +14092,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
14439
14092
  cloneMutableTextInstance(textInstance) {
14440
14093
  return textInstance;
14441
14094
  },
14095
+ // React 19.2 added these for root-level view transitions. They only run for hosts that opt into
14096
+ // view transitions by returning a container from cloneRootViewTransitionContainer; R3F renders
14097
+ // into a WebGL/WebGPU canvas, where cloning the root has no meaning, so we never opt in and
14098
+ // React never calls them. They stay as no-ops rather than throws: the host config is shared by
14099
+ // every root, and a throw here would turn a React-internal probe into a hard crash for users.
14100
+ // Guarded by a test asserting a full render + unmount never reaches them.
14442
14101
  cloneRootViewTransitionContainer(_rootContainer) {
14443
- throw new Error("Not implemented.");
14444
14102
  },
14445
14103
  removeRootViewTransitionClone(_rootContainer, _clone) {
14446
- throw new Error("Not implemented.");
14447
14104
  },
14448
14105
  // https://github.com/facebook/react/pull/32465
14449
14106
  createFragmentInstance: (_fiber) => null,
@@ -14525,14 +14182,18 @@ function createRoot(canvas) {
14525
14182
  if (!prevRoot) _roots.set(canvas, { fiber, store });
14526
14183
  let onCreated;
14527
14184
  let lastCamera;
14528
- let lastConfiguredProps = {};
14185
+ const lastConfiguredProps = {};
14529
14186
  let configured = false;
14530
14187
  let pending = null;
14188
+ let rendererSetup = null;
14531
14189
  return {
14532
14190
  async configure(props = {}) {
14533
14191
  let resolve;
14534
14192
  pending = new Promise((_resolve) => resolve = _resolve);
14535
- let {
14193
+ const {
14194
+ id: canvasId,
14195
+ primaryCanvas,
14196
+ scheduler: schedulerConfig,
14536
14197
  gl: glConfig,
14537
14198
  renderer: rendererConfig,
14538
14199
  size: propsSize,
@@ -14540,10 +14201,6 @@ function createRoot(canvas) {
14540
14201
  events,
14541
14202
  onCreated: onCreatedCallback,
14542
14203
  shadows = false,
14543
- linear = false,
14544
- flat = false,
14545
- textureColorSpace = SRGBColorSpace,
14546
- legacy = false,
14547
14204
  orthographic = false,
14548
14205
  frameloop = "always",
14549
14206
  dpr = [1, 2],
@@ -14554,8 +14211,11 @@ function createRoot(canvas) {
14554
14211
  onDragOverMissed,
14555
14212
  onDropMissed,
14556
14213
  autoUpdateFrustum = true,
14557
- occlusion = false
14214
+ occlusion = false,
14215
+ _sizeProps,
14216
+ forceEven
14558
14217
  } = props;
14218
+ const textureColorSpace = is.obj(glConfig) && !is.fun(glConfig) && !isRenderer(glConfig) && glConfig.textureColorSpace || is.obj(rendererConfig) && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && rendererConfig.textureColorSpace || SRGBColorSpace;
14559
14219
  let state = store.getState();
14560
14220
  const defaultGLProps = {
14561
14221
  canvas,
@@ -14568,22 +14228,46 @@ function createRoot(canvas) {
14568
14228
  "WebGPURenderer (renderer prop) is not available in this build. Use @react-three/fiber or @react-three/fiber/webgpu instead."
14569
14229
  );
14570
14230
  }
14571
- (state.isLegacy || glConfig || !R3F_BUILD_WEBGPU);
14231
+ const wantsGL = (state.isLegacy || glConfig || !R3F_BUILD_WEBGPU);
14572
14232
  if (glConfig && rendererConfig) {
14573
14233
  throw new Error("Cannot use both gl and renderer props at the same time");
14574
14234
  }
14575
14235
  let renderer = state.internal.actualRenderer;
14236
+ if (primaryCanvas && !R3F_BUILD_WEBGPU) {
14237
+ throw new Error(
14238
+ "The `primaryCanvas` prop for multi-canvas rendering is only available with WebGPU. Use @react-three/fiber/webgpu instead."
14239
+ );
14240
+ }
14241
+ if (primaryCanvas && wantsGL) {
14242
+ throw new Error(
14243
+ "The `primaryCanvas` prop for multi-canvas rendering cannot be used with WebGL. Remove the `gl` prop or use WebGPU."
14244
+ );
14245
+ }
14576
14246
  if (!state.internal.actualRenderer) {
14577
- renderer = await resolveRenderer(glConfig, defaultGLProps, WebGLRenderer);
14578
- state.internal.actualRenderer = renderer;
14579
- state.set({ isLegacy: true, gl: renderer, renderer });
14247
+ if (!rendererSetup) {
14248
+ rendererSetup = (async () => {
14249
+ {
14250
+ renderer = await resolveRenderer(glConfig, defaultGLProps, WebGLRenderer);
14251
+ state.internal.actualRenderer = renderer;
14252
+ state.set({ isLegacy: true, gl: renderer, renderer, primaryStore: store });
14253
+ }
14254
+ })().catch((err) => {
14255
+ rendererSetup = null;
14256
+ throw err;
14257
+ });
14258
+ }
14259
+ await rendererSetup;
14260
+ state = store.getState();
14261
+ renderer = state.internal.actualRenderer;
14580
14262
  }
14581
14263
  let raycaster = state.raycaster;
14582
14264
  if (!raycaster) state.set({ raycaster: raycaster = new Raycaster() });
14583
14265
  const { params, ...options } = raycastOptions || {};
14584
14266
  if (!is.equ(options, raycaster, shallowLoose)) applyProps(raycaster, { ...options });
14585
- if (!is.equ(params, raycaster.params, shallowLoose))
14267
+ if (!is.equ(params, raycaster.params, shallowLoose)) {
14586
14268
  applyProps(raycaster, { params: { ...raycaster.params, ...params } });
14269
+ }
14270
+ let tempCamera = state.camera;
14587
14271
  if (!state.camera || state.camera === lastCamera && !is.equ(lastCamera, cameraOptions, shallowLoose)) {
14588
14272
  lastCamera = cameraOptions;
14589
14273
  const isCamera = cameraOptions?.isCamera;
@@ -14603,6 +14287,7 @@ function createRoot(canvas) {
14603
14287
  if (!state.camera && !cameraOptions?.rotation) camera.lookAt(0, 0, 0);
14604
14288
  }
14605
14289
  state.set({ camera });
14290
+ tempCamera = camera;
14606
14291
  raycaster.camera = camera;
14607
14292
  }
14608
14293
  if (!state.scene) {
@@ -14620,7 +14305,7 @@ function createRoot(canvas) {
14620
14305
  rootScene: scene,
14621
14306
  internal: { ...prev.internal, container: scene }
14622
14307
  }));
14623
- const camera = state.camera;
14308
+ const camera = tempCamera;
14624
14309
  if (camera && !camera.parent) scene.add(camera);
14625
14310
  }
14626
14311
  if (events && !state.events.handlers) {
@@ -14634,9 +14319,17 @@ function createRoot(canvas) {
14634
14319
  wasEnabled = enabled;
14635
14320
  });
14636
14321
  }
14322
+ if (_sizeProps !== void 0) {
14323
+ state.set({ _sizeProps });
14324
+ }
14325
+ if (forceEven !== void 0 && state.internal.forceEven !== forceEven) {
14326
+ state.set((prev) => ({ internal: { ...prev.internal, forceEven } }));
14327
+ }
14637
14328
  const size = computeInitialSize(canvas, propsSize);
14638
- if (!is.equ(size, state.size, shallowLoose)) {
14329
+ if (!state._sizeImperative && !is.equ(size, state.size, shallowLoose)) {
14330
+ const wasImperative = state._sizeImperative;
14639
14331
  state.setSize(size.width, size.height, size.top, size.left);
14332
+ if (!wasImperative) state.set({ _sizeImperative: false });
14640
14333
  }
14641
14334
  if (dpr !== void 0 && !is.equ(dpr, lastConfiguredProps.dpr, shallowLoose)) {
14642
14335
  state.setDpr(dpr);
@@ -14658,10 +14351,10 @@ function createRoot(canvas) {
14658
14351
  lastConfiguredProps.performance = performance;
14659
14352
  }
14660
14353
  if (!state.xr) {
14661
- const handleXRFrame = (timestamp, frame) => {
14354
+ const handleXRFrame = (timestamp, _frame) => {
14662
14355
  const state2 = store.getState();
14663
14356
  if (state2.frameloop === "never") return;
14664
- advance(timestamp, true);
14357
+ advance(timestamp);
14665
14358
  };
14666
14359
  const actualRenderer = state.internal.actualRenderer;
14667
14360
  const handleSessionChange = () => {
@@ -14673,16 +14366,16 @@ function createRoot(canvas) {
14673
14366
  };
14674
14367
  const xr = {
14675
14368
  connect() {
14676
- const { gl, renderer: renderer2, isLegacy } = store.getState();
14677
- const actualRenderer2 = renderer2 || gl;
14678
- actualRenderer2.xr.addEventListener("sessionstart", handleSessionChange);
14679
- actualRenderer2.xr.addEventListener("sessionend", handleSessionChange);
14369
+ const { gl, renderer: renderer2 } = store.getState();
14370
+ const xrManager = (renderer2 || gl).xr;
14371
+ xrManager.addEventListener("sessionstart", handleSessionChange);
14372
+ xrManager.addEventListener("sessionend", handleSessionChange);
14680
14373
  },
14681
14374
  disconnect() {
14682
- const { gl, renderer: renderer2, isLegacy } = store.getState();
14683
- const actualRenderer2 = renderer2 || gl;
14684
- actualRenderer2.xr.removeEventListener("sessionstart", handleSessionChange);
14685
- actualRenderer2.xr.removeEventListener("sessionend", handleSessionChange);
14375
+ const { gl, renderer: renderer2 } = store.getState();
14376
+ const xrManager = (renderer2 || gl).xr;
14377
+ xrManager.removeEventListener("sessionstart", handleSessionChange);
14378
+ xrManager.removeEventListener("sessionend", handleSessionChange);
14686
14379
  }
14687
14380
  };
14688
14381
  if (typeof renderer.xr?.addEventListener === "function") xr.connect();
@@ -14694,61 +14387,92 @@ function createRoot(canvas) {
14694
14387
  const oldType = renderer.shadowMap.type;
14695
14388
  renderer.shadowMap.enabled = !!shadows;
14696
14389
  if (is.boo(shadows)) {
14697
- renderer.shadowMap.type = PCFSoftShadowMap;
14390
+ renderer.shadowMap.type = PCFShadowMap;
14698
14391
  } else if (is.str(shadows)) {
14392
+ if (shadows === "soft") {
14393
+ notifyDepreciated({
14394
+ heading: 'shadows="soft" is deprecated',
14395
+ body: "Three has depreciated soft and improved basic PCFShadows, we converted for you.",
14396
+ link: "https://github.com/mrdoob/three.js/wiki/Migration-Guide?utm_source=chatgpt.com#181--182"
14397
+ });
14398
+ }
14699
14399
  const types = {
14700
14400
  basic: BasicShadowMap,
14701
14401
  percentage: PCFShadowMap,
14702
- soft: PCFSoftShadowMap,
14402
+ soft: PCFShadowMap,
14703
14403
  variance: VSMShadowMap
14704
14404
  };
14705
- renderer.shadowMap.type = types[shadows] ?? PCFSoftShadowMap;
14405
+ renderer.shadowMap.type = types[shadows] ?? PCFShadowMap;
14706
14406
  } else if (is.obj(shadows)) {
14707
14407
  Object.assign(renderer.shadowMap, shadows);
14708
14408
  }
14709
- if (oldEnabled !== renderer.shadowMap.enabled || oldType !== renderer.shadowMap.type)
14409
+ if (oldEnabled !== renderer.shadowMap.enabled || oldType !== renderer.shadowMap.type) {
14710
14410
  renderer.shadowMap.needsUpdate = true;
14711
- }
14712
- {
14713
- const legacyChanged = legacy !== lastConfiguredProps.legacy;
14714
- const linearChanged = linear !== lastConfiguredProps.linear;
14715
- const flatChanged = flat !== lastConfiguredProps.flat;
14716
- if (legacyChanged) {
14717
- ColorManagement.enabled = !legacy;
14718
- lastConfiguredProps.legacy = legacy;
14719
14411
  }
14720
- if (!configured || linearChanged) {
14721
- renderer.outputColorSpace = linear ? LinearSRGBColorSpace : SRGBColorSpace;
14722
- lastConfiguredProps.linear = linear;
14723
- }
14724
- if (!configured || flatChanged) {
14725
- renderer.toneMapping = flat ? NoToneMapping : ACESFilmicToneMapping;
14726
- lastConfiguredProps.flat = flat;
14727
- }
14728
- if (legacyChanged && state.legacy !== legacy) state.set(() => ({ legacy }));
14729
- if (linearChanged && state.linear !== linear) state.set(() => ({ linear }));
14730
- if (flatChanged && state.flat !== flat) state.set(() => ({ flat }));
14412
+ }
14413
+ if (!configured) {
14414
+ renderer.outputColorSpace = SRGBColorSpace;
14415
+ renderer.toneMapping = ACESFilmicToneMapping;
14731
14416
  }
14732
14417
  if (textureColorSpace !== lastConfiguredProps.textureColorSpace) {
14733
14418
  if (state.textureColorSpace !== textureColorSpace) state.set(() => ({ textureColorSpace }));
14734
14419
  lastConfiguredProps.textureColorSpace = textureColorSpace;
14735
14420
  }
14736
- if (glConfig && !is.fun(glConfig) && !isRenderer(glConfig) && !is.equ(glConfig, renderer, shallowLoose))
14737
- applyProps(renderer, glConfig);
14421
+ const r3fProps = ["textureColorSpace"];
14422
+ const constructorOnlyProps = ["samples", "antialias", "alpha", "canvas", "powerPreference"];
14423
+ const nonApplyProps = [...r3fProps, ...constructorOnlyProps];
14424
+ if (glConfig && !is.fun(glConfig) && !isRenderer(glConfig) && !is.equ(glConfig, renderer, shallowLoose)) {
14425
+ const glProps = {};
14426
+ for (const key in glConfig) {
14427
+ if (!nonApplyProps.includes(key)) glProps[key] = glConfig[key];
14428
+ }
14429
+ applyProps(renderer, glProps);
14430
+ }
14738
14431
  if (rendererConfig && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && state.renderer) {
14739
14432
  const currentRenderer = state.renderer;
14740
14433
  if (!is.equ(rendererConfig, currentRenderer, shallowLoose)) {
14741
- applyProps(currentRenderer, rendererConfig);
14434
+ const rendererProps = {};
14435
+ for (const key in rendererConfig) {
14436
+ if (!nonApplyProps.includes(key)) rendererProps[key] = rendererConfig[key];
14437
+ }
14438
+ applyProps(currentRenderer, rendererProps);
14742
14439
  }
14743
14440
  }
14744
14441
  const scheduler = getScheduler();
14745
14442
  const rootId = state.internal.rootId;
14746
14443
  if (!rootId) {
14747
- const newRootId = scheduler.generateRootId();
14444
+ const newRootId = canvasId || scheduler.generateRootId();
14748
14445
  const unregisterRoot = scheduler.registerRoot(newRootId, {
14749
14446
  getState: () => store.getState(),
14750
14447
  onError: (err) => store.getState().setError(err)
14751
14448
  });
14449
+ const unregisterCanvasTarget = scheduler.register(
14450
+ () => {
14451
+ const state2 = store.getState();
14452
+ if (state2.internal.isMultiCanvas && state2.internal.canvasTarget) {
14453
+ const renderer2 = state2.internal.actualRenderer;
14454
+ renderer2.setCanvasTarget(state2.internal.canvasTarget);
14455
+ }
14456
+ },
14457
+ {
14458
+ id: `${newRootId}_canvasTarget`,
14459
+ rootId: newRootId,
14460
+ phase: "start",
14461
+ system: true
14462
+ }
14463
+ );
14464
+ const unregisterEventsFlush = scheduler.register(
14465
+ () => {
14466
+ const state2 = store.getState();
14467
+ state2.events.flush?.();
14468
+ },
14469
+ {
14470
+ id: `${newRootId}_events`,
14471
+ rootId: newRootId,
14472
+ phase: "input",
14473
+ system: true
14474
+ }
14475
+ );
14752
14476
  const unregisterFrustum = scheduler.register(
14753
14477
  () => {
14754
14478
  const state2 = store.getState();
@@ -14759,7 +14483,7 @@ function createRoot(canvas) {
14759
14483
  {
14760
14484
  id: `${newRootId}_frustum`,
14761
14485
  rootId: newRootId,
14762
- phase: "preRender",
14486
+ before: "render",
14763
14487
  system: true
14764
14488
  }
14765
14489
  );
@@ -14771,7 +14495,7 @@ function createRoot(canvas) {
14771
14495
  {
14772
14496
  id: `${newRootId}_visibility`,
14773
14497
  rootId: newRootId,
14774
- phase: "preRender",
14498
+ before: "render",
14775
14499
  system: true,
14776
14500
  after: `${newRootId}_frustum`
14777
14501
  }
@@ -14783,18 +14507,22 @@ function createRoot(canvas) {
14783
14507
  const userHandlesRender = scheduler.hasUserJobsInPhase("render", newRootId);
14784
14508
  if (userHandlesRender || state2.internal.priority) return;
14785
14509
  try {
14786
- if (state2.postProcessing?.render) state2.postProcessing.render();
14510
+ if (state2.renderPipeline?.render) state2.renderPipeline.render();
14787
14511
  else if (renderer2?.render) renderer2.render(state2.scene, state2.camera);
14788
14512
  } catch (error) {
14789
14513
  state2.setError(error instanceof Error ? error : new Error(String(error)));
14790
14514
  }
14791
14515
  },
14792
14516
  {
14793
- id: `${newRootId}_render`,
14517
+ // Use canvas ID directly as job ID if available, otherwise use generated rootId
14518
+ id: canvasId || `${newRootId}_render`,
14794
14519
  rootId: newRootId,
14795
14520
  phase: "render",
14796
- system: true
14521
+ system: true,
14797
14522
  // Internal flag: this is a system job, not user-controlled
14523
+ // Apply scheduler config for render ordering and rate limiting
14524
+ ...schedulerConfig?.after && { after: schedulerConfig.after },
14525
+ ...schedulerConfig?.fps && { fps: schedulerConfig.fps }
14798
14526
  }
14799
14527
  );
14800
14528
  state.set((state2) => ({
@@ -14803,6 +14531,8 @@ function createRoot(canvas) {
14803
14531
  rootId: newRootId,
14804
14532
  unregisterRoot: () => {
14805
14533
  unregisterRoot();
14534
+ unregisterCanvasTarget();
14535
+ unregisterEventsFlush();
14806
14536
  unregisterFrustum();
14807
14537
  unregisterVisibility();
14808
14538
  unregisterRender();
@@ -14861,15 +14591,24 @@ function unmountComponentAtNode(canvas, callback) {
14861
14591
  const renderer = state.internal.actualRenderer;
14862
14592
  const unregisterRoot = state.internal.unregisterRoot;
14863
14593
  if (unregisterRoot) unregisterRoot();
14594
+ const unregisterPrimary = state.internal.unregisterPrimary;
14595
+ if (unregisterPrimary) unregisterPrimary();
14596
+ const canvasTarget = state.internal.canvasTarget;
14597
+ if (canvasTarget?.dispose) canvasTarget.dispose();
14864
14598
  state.events.disconnect?.();
14865
14599
  cleanupHelperGroup(root.store);
14866
- renderer?.renderLists?.dispose?.();
14867
- renderer?.forceContextLoss?.();
14868
- if (renderer?.xr) state.xr.disconnect();
14600
+ if (state.isLegacy && renderer) {
14601
+ ;
14602
+ renderer.renderLists?.dispose?.();
14603
+ renderer.forceContextLoss?.();
14604
+ }
14605
+ if (!state.internal.isSecondary) {
14606
+ if (renderer?.xr) state.xr.disconnect();
14607
+ }
14869
14608
  dispose(state.scene);
14870
14609
  _roots.delete(canvas);
14871
14610
  if (callback) callback(canvas);
14872
- } catch (e) {
14611
+ } catch {
14873
14612
  }
14874
14613
  }, 500);
14875
14614
  }
@@ -14877,36 +14616,34 @@ function unmountComponentAtNode(canvas, callback) {
14877
14616
  }
14878
14617
  }
14879
14618
  function createPortal(children, container, state) {
14880
- return /* @__PURE__ */ jsx(PortalWrapper, { children, container, state });
14619
+ return /* @__PURE__ */ jsx(Portal, { children, container, state });
14881
14620
  }
14882
- function PortalWrapper({ children, container, state }) {
14621
+ function Portal({ children, container, state }) {
14883
14622
  const isRef = useCallback((obj) => obj && "current" in obj, []);
14884
- const [resolvedContainer, setResolvedContainer] = useState(() => {
14623
+ const [resolvedContainer, _setResolvedContainer] = useState(() => {
14885
14624
  if (isRef(container)) return container.current ?? null;
14886
14625
  return container;
14887
14626
  });
14627
+ const setResolvedContainer = useCallback(
14628
+ (newContainer) => {
14629
+ if (!newContainer || newContainer === resolvedContainer) return;
14630
+ _setResolvedContainer(isRef(newContainer) ? newContainer.current : newContainer);
14631
+ },
14632
+ [resolvedContainer, _setResolvedContainer, isRef]
14633
+ );
14888
14634
  useMemo(() => {
14889
- if (isRef(container)) {
14890
- const current = container.current;
14891
- if (!current) {
14892
- queueMicrotask(() => {
14893
- const updated = container.current;
14894
- if (updated && updated !== resolvedContainer) {
14895
- setResolvedContainer(updated);
14896
- }
14897
- });
14898
- } else if (current !== resolvedContainer) {
14899
- setResolvedContainer(current);
14900
- }
14901
- } else if (container !== resolvedContainer) {
14902
- setResolvedContainer(container);
14635
+ if (isRef(container) && !container.current) {
14636
+ return queueMicrotask(() => {
14637
+ setResolvedContainer(container.current);
14638
+ });
14903
14639
  }
14904
- }, [container, resolvedContainer, isRef]);
14640
+ setResolvedContainer(container);
14641
+ }, [container, isRef, setResolvedContainer]);
14905
14642
  if (!resolvedContainer) return /* @__PURE__ */ jsx(Fragment, {});
14906
14643
  const portalKey = resolvedContainer.uuid ?? `portal-${resolvedContainer.id ?? "unknown"}`;
14907
- return /* @__PURE__ */ jsx(Portal, { children, container: resolvedContainer, state }, portalKey);
14644
+ return /* @__PURE__ */ jsx(PortalInner, { children, container: resolvedContainer, state }, portalKey);
14908
14645
  }
14909
- function Portal({ state = {}, children, container }) {
14646
+ function PortalInner({ state = {}, children, container }) {
14910
14647
  const { events, size, injectScene = true, ...rest } = state;
14911
14648
  const previousRoot = useStore();
14912
14649
  const [raycaster] = useState(() => new Raycaster());
@@ -14927,12 +14664,14 @@ function Portal({ state = {}, children, container }) {
14927
14664
  };
14928
14665
  }, [portalScene, container, injectScene]);
14929
14666
  const inject = useMutableCallback((rootState, injectState) => {
14667
+ const resolvedSize = { ...rootState.size, ...injectState.size, ...size };
14930
14668
  let viewport = void 0;
14931
- if (injectState.camera && size) {
14669
+ if (injectState.camera && (size || injectState.size)) {
14932
14670
  const camera = injectState.camera;
14933
- viewport = rootState.viewport.getCurrentViewport(camera, new Vector3(), size);
14934
- if (camera !== rootState.camera) updateCamera(camera, size);
14671
+ viewport = rootState.viewport.getCurrentViewport(camera, new Vector3(), resolvedSize);
14672
+ if (camera !== rootState.camera) updateCamera(camera, resolvedSize);
14935
14673
  }
14674
+ const set = injectState.set;
14936
14675
  return {
14937
14676
  // The intersect consists of the previous root state
14938
14677
  ...rootState,
@@ -14948,10 +14687,10 @@ function Portal({ state = {}, children, container }) {
14948
14687
  previousRoot,
14949
14688
  // Events, size and viewport can be overridden by the inject layer
14950
14689
  events: { ...rootState.events, ...injectState.events, ...events },
14951
- size: { ...rootState.size, ...size },
14690
+ size: resolvedSize,
14952
14691
  viewport: { ...rootState.viewport, ...viewport },
14953
14692
  // Layers are allowed to override events
14954
- setEvents: (events2) => injectState.set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14693
+ setEvents: (events2) => set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14955
14694
  // Container for child attachment - the portalScene (injected or container itself)
14956
14695
  internal: { ...rootState.internal, ...injectState.internal, container: portalScene }
14957
14696
  };
@@ -14960,9 +14699,13 @@ function Portal({ state = {}, children, container }) {
14960
14699
  const store = createWithEqualityFn((set, get) => ({ ...rest, set, get }));
14961
14700
  const onMutate = (prev) => store.setState((state2) => inject.current(prev, state2));
14962
14701
  onMutate(previousRoot.getState());
14963
- previousRoot.subscribe(onMutate);
14964
14702
  return store;
14965
14703
  }, [previousRoot, container]);
14704
+ useIsomorphicLayoutEffect(() => {
14705
+ const onMutate = (prev) => usePortalStore.setState((state2) => inject.current(prev, state2));
14706
+ const unsubscribe = previousRoot.subscribe(onMutate);
14707
+ return unsubscribe;
14708
+ }, [previousRoot, usePortalStore]);
14966
14709
  return (
14967
14710
  // @ts-ignore, reconciler types are not maintained
14968
14711
  /* @__PURE__ */ jsx(Fragment, { children: reconciler.createPortal(
@@ -14976,21 +14719,72 @@ function flushSync(fn) {
14976
14719
  return reconciler.flushSyncFromReconciler(fn);
14977
14720
  }
14978
14721
 
14722
+ function parseBackground(background) {
14723
+ if (!background) return null;
14724
+ if (typeof background === "object" && !background.isColor) {
14725
+ const { backgroundMap, envMap, files, preset, ...rest } = background;
14726
+ return {
14727
+ ...rest,
14728
+ preset,
14729
+ files: envMap || files,
14730
+ backgroundFiles: backgroundMap,
14731
+ background: true
14732
+ };
14733
+ }
14734
+ if (typeof background === "number") {
14735
+ return { color: background, background: true };
14736
+ }
14737
+ if (typeof background === "string") {
14738
+ if (background in presetsObj) {
14739
+ return { preset: background, background: true };
14740
+ }
14741
+ if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
14742
+ return { files: background, background: true };
14743
+ }
14744
+ return { color: background, background: true };
14745
+ }
14746
+ if (background.isColor) {
14747
+ return { color: background, background: true };
14748
+ }
14749
+ return null;
14750
+ }
14751
+
14752
+ function parseRendererConfig(rendererProp) {
14753
+ const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
14754
+ if (isRendererConfig) {
14755
+ const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
14756
+ return {
14757
+ primaryCanvas: pc,
14758
+ scheduler: sc,
14759
+ renderer: Object.keys(rest).length > 0 ? rest : rendererProp
14760
+ };
14761
+ }
14762
+ return { primaryCanvas: void 0, scheduler: void 0, renderer: rendererProp };
14763
+ }
14764
+
14765
+ function clearHmrCaches(store) {
14766
+ store.setState((state) => ({
14767
+ nodes: {},
14768
+ uniforms: {},
14769
+ buffers: {},
14770
+ gpuStorage: {},
14771
+ _hmrVersion: state._hmrVersion + 1
14772
+ }));
14773
+ }
14774
+
14979
14775
  function CanvasImpl({
14980
14776
  ref,
14981
14777
  children,
14982
14778
  fallback,
14983
14779
  resize,
14984
14780
  style,
14781
+ id,
14985
14782
  gl,
14986
- renderer,
14783
+ renderer: rendererProp,
14987
14784
  events = createPointerEvents,
14988
14785
  eventSource,
14989
14786
  eventPrefix,
14990
14787
  shadows,
14991
- linear,
14992
- flat,
14993
- legacy,
14994
14788
  orthographic,
14995
14789
  frameloop,
14996
14790
  dpr,
@@ -14998,14 +14792,23 @@ function CanvasImpl({
14998
14792
  raycaster,
14999
14793
  camera,
15000
14794
  scene,
14795
+ autoUpdateFrustum,
14796
+ occlusion,
15001
14797
  onPointerMissed,
15002
14798
  onDragOverMissed,
15003
14799
  onDropMissed,
15004
14800
  onCreated,
14801
+ hmr,
14802
+ width,
14803
+ height,
14804
+ background,
14805
+ forceEven,
15005
14806
  ...props
15006
14807
  }) {
14808
+ const { primaryCanvas, scheduler, renderer } = parseRendererConfig(rendererProp);
15007
14809
  React.useMemo(() => extend(THREE), []);
15008
14810
  const Bridge = useBridge();
14811
+ const backgroundProps = React.useMemo(() => parseBackground(background), [background]);
15009
14812
  const hasInitialSizeRef = React.useRef(false);
15010
14813
  const measureConfig = React.useMemo(() => {
15011
14814
  if (!hasInitialSizeRef.current) {
@@ -15022,7 +14825,21 @@ function CanvasImpl({
15022
14825
  };
15023
14826
  }, [resize, hasInitialSizeRef.current]);
15024
14827
  const [containerRef, containerRect] = useMeasure(measureConfig);
15025
- if (!hasInitialSizeRef.current && containerRect.width > 0 && containerRect.height > 0) {
14828
+ const effectiveSize = React.useMemo(() => {
14829
+ let w = width ?? containerRect.width;
14830
+ let h = height ?? containerRect.height;
14831
+ if (forceEven) {
14832
+ w = Math.ceil(w / 2) * 2;
14833
+ h = Math.ceil(h / 2) * 2;
14834
+ }
14835
+ return {
14836
+ width: w,
14837
+ height: h,
14838
+ top: containerRect.top,
14839
+ left: containerRect.left
14840
+ };
14841
+ }, [width, height, containerRect, forceEven]);
14842
+ if (!hasInitialSizeRef.current && effectiveSize.width > 0 && effectiveSize.height > 0) {
15026
14843
  hasInitialSizeRef.current = true;
15027
14844
  }
15028
14845
  const canvasRef = React.useRef(null);
@@ -15033,6 +14850,7 @@ function CanvasImpl({
15033
14850
  const handleDropMissed = useMutableCallback(onDropMissed);
15034
14851
  const [block, setBlock] = React.useState(false);
15035
14852
  const [error, setError] = React.useState(false);
14853
+ const [fallbackVisible, setFallbackVisible] = React.useState(false);
15036
14854
  if (block) throw block;
15037
14855
  if (error) throw error;
15038
14856
  const root = React.useRef(null);
@@ -15040,8 +14858,9 @@ function CanvasImpl({
15040
14858
  const unsubscribeErrorRef = React.useRef(null);
15041
14859
  useIsomorphicLayoutEffect(() => {
15042
14860
  effectActiveRef.current = true;
14861
+ if (fallbackVisible) return;
15043
14862
  const canvas = canvasRef.current;
15044
- if (containerRect.width > 0 && containerRect.height > 0 && canvas) {
14863
+ if (effectiveSize.width > 0 && effectiveSize.height > 0 && canvas) {
15045
14864
  if (!root.current) {
15046
14865
  root.current = createRoot(canvas);
15047
14866
  notifyAlpha({
@@ -15060,22 +14879,27 @@ function CanvasImpl({
15060
14879
  }
15061
14880
  async function run() {
15062
14881
  if (!effectActiveRef.current || !root.current) return;
15063
- await root.current.configure({
14882
+ const configured = await root.current.configure({
14883
+ id,
14884
+ primaryCanvas,
14885
+ scheduler,
15064
14886
  gl,
15065
14887
  renderer,
15066
14888
  scene,
15067
14889
  events,
15068
14890
  shadows,
15069
- linear,
15070
- flat,
15071
- legacy,
15072
14891
  orthographic,
15073
14892
  frameloop,
15074
14893
  dpr,
15075
14894
  performance,
15076
14895
  raycaster,
15077
14896
  camera,
15078
- size: containerRect,
14897
+ autoUpdateFrustum,
14898
+ occlusion,
14899
+ size: effectiveSize,
14900
+ // Store size props for reset functionality
14901
+ _sizeProps: width !== void 0 || height !== void 0 ? { width, height } : null,
14902
+ forceEven,
15079
14903
  // Pass mutable reference to onPointerMissed so it's free to update
15080
14904
  onPointerMissed: (...args) => handlePointerMissed.current?.(...args),
15081
14905
  onDragOverMissed: (...args) => handleDragOverMissed.current?.(...args),
@@ -15096,10 +14920,25 @@ function CanvasImpl({
15096
14920
  }
15097
14921
  onCreated?.(state);
15098
14922
  }
15099
- });
15100
- if (!effectActiveRef.current || !root.current) return;
14923
+ }).then(
14924
+ () => true,
14925
+ // Renderer setup failed (e.g. no WebGL/WebGPU support). The `fallback` prop lives
14926
+ // inside <canvas>, which browsers don't display, so surface it as visible DOM
14927
+ // instead; with no fallback, rethrow to an external error boundary. (#3757)
14928
+ (setupError) => {
14929
+ if (effectActiveRef.current) {
14930
+ if (fallback != null) setFallbackVisible(true);
14931
+ else setError(setupError);
14932
+ }
14933
+ return false;
14934
+ }
14935
+ );
14936
+ if (!configured || !effectActiveRef.current || !root.current) return;
15101
14937
  root.current.render(
15102
- /* @__PURE__ */ jsx(Bridge, { children: /* @__PURE__ */ jsx(ErrorBoundary, { set: setError, children: /* @__PURE__ */ jsx(React.Suspense, { fallback: /* @__PURE__ */ jsx(Block, { set: setBlock }), children: children ?? null }) }) })
14938
+ /* @__PURE__ */ jsx(Bridge, { children: /* @__PURE__ */ jsx(ErrorBoundary, { set: setError, children: /* @__PURE__ */ jsxs(React.Suspense, { fallback: /* @__PURE__ */ jsx(Block, { set: setBlock }), children: [
14939
+ backgroundProps && /* @__PURE__ */ jsx(Environment, { ...backgroundProps }),
14940
+ children ?? null
14941
+ ] }) }) })
15103
14942
  );
15104
14943
  }
15105
14944
  run();
@@ -15121,6 +14960,28 @@ function CanvasImpl({
15121
14960
  };
15122
14961
  }
15123
14962
  }, []);
14963
+ React.useEffect(() => {
14964
+ if (hmr === false) return;
14965
+ const canvas = canvasRef.current;
14966
+ if (!canvas) return;
14967
+ const handleHMR = () => {
14968
+ queueMicrotask(() => {
14969
+ const rootEntry = _roots.get(canvas);
14970
+ if (rootEntry?.store) clearHmrCaches(rootEntry.store);
14971
+ });
14972
+ };
14973
+ if (typeof import.meta !== "undefined" && import.meta.hot) {
14974
+ const hot = import.meta.hot;
14975
+ hot.on("vite:afterUpdate", handleHMR);
14976
+ return () => hot.off?.("vite:afterUpdate", handleHMR);
14977
+ }
14978
+ if (typeof module !== "undefined" && module.hot) {
14979
+ const hot = module.hot;
14980
+ hot.addStatusHandler((status) => {
14981
+ if (status === "idle") handleHMR();
14982
+ });
14983
+ }
14984
+ }, [hmr]);
15124
14985
  const pointerEvents = eventSource ? "none" : "auto";
15125
14986
  return /* @__PURE__ */ jsx(
15126
14987
  "div",
@@ -15135,7 +14996,20 @@ function CanvasImpl({
15135
14996
  ...style
15136
14997
  },
15137
14998
  ...props,
15138
- children: /* @__PURE__ */ jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsx("canvas", { ref: canvasRef, className: "r3f-canvas", style: { display: "block" }, children: fallback }) })
14999
+ children: fallbackVisible ? (
15000
+ // Renderer setup failed: render the fallback as visible DOM. Inside <canvas> (below)
15001
+ // it exists in the tree but browsers never paint it, which is the whole bug (#3757).
15002
+ fallback
15003
+ ) : /* @__PURE__ */ jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsx(
15004
+ "canvas",
15005
+ {
15006
+ ref: canvasRef,
15007
+ id,
15008
+ className: "r3f-canvas",
15009
+ style: { display: "block", width: "100%", height: "100%" },
15010
+ children: fallback
15011
+ }
15012
+ ) })
15139
15013
  }
15140
15014
  );
15141
15015
  }
@@ -15145,4 +15019,4 @@ function Canvas(props) {
15145
15019
 
15146
15020
  extend(THREE);
15147
15021
 
15148
- export { Block, Canvas, ErrorBoundary, IsObject, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, REACT_INTERNAL_PROPS, RESERVED_PROPS, Scheduler, Texture, _roots, act, addAfterEffect, addEffect, addTail, advance, applyProps, attach, buildGraph, calculateDpr, context, createEvents, createPointerEvents, createPortal, createRoot, createStore, detach, diffProps, dispose, createPointerEvents as events, extend, findInitialRoot, flushSync, getInstanceProps, getRootState, getScheduler, getUuidPrefix, hasConstructor, invalidate, invalidateInstance, is, isColorRepresentation, isCopyable, isObject3D, isOrthographicCamera, isRef, isRenderer, isTexture, isVectorLike, prepare, reconciler, removeInteractivity, resolve, unmountComponentAtNode, updateCamera, updateFrustum, useBridge, useFrame, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useMutableCallback, useRenderTarget, useStore, useTexture, useTextures, useThree };
15022
+ export { Block, Canvas, Environment, EnvironmentCube, EnvironmentMap, EnvironmentPortal, ErrorBoundary, FROM_REF, IsObject, ONCE, Portal, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, REACT_INTERNAL_PROPS, RESERVED_PROPS, Texture, _roots, act, addAfterEffect, addEffect, addTail, advance, applyProps, attach, buildGraph, calculateDpr, context, createEvents, createPointerEvents, createPortal, createRoot, createStore, detach, diffProps, dispose, createPointerEvents as events, extend, findInitialRoot, flushSync, fromRef, getInstanceProps, getPrimary, getPrimaryIds, getRootState, getUuidPrefix, hasConstructor, hasPrimary, invalidate, invalidateInstance, is, isColorRepresentation, isCopyable, isFromRef, isObject3D, isOnce, isOrthographicCamera, isRef, isRenderer, isTexture, isVectorLike, once, prepare, presetsObj, reconciler, registerPrimary, removeInteractivity, resolve, unmountComponentAtNode, unregisterPrimary, updateCamera, updateFrustum, useBridge, useEnvironment, useFrame, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useMutableCallback, useRenderTarget, useStore, useTexture, useTextures, useThree, waitForPrimary };