@react-three/fiber 10.0.0-canary.c3fa45d → 10.0.0-canary.ca63ccd

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import * as webgpu from 'three/webgpu';
2
- import { RenderTarget, CubeReflectionMapping, EquirectangularReflectionMapping, CubeTextureLoader, Scene, WebGLCubeRenderTarget, HalfFloatType, Color, Frustum, Matrix4, Group, BoxGeometry, MeshBasicNodeMaterial, Mesh, Node, NodeUpdateType, Layers, SRGBColorSpace, RGBAFormat, UnsignedByteType, Vector3, Vector2, TextureLoader, Texture as Texture$1, CanvasTarget, Raycaster, OrthographicCamera, PerspectiveCamera, PCFShadowMap, VSMShadowMap, BasicShadowMap, ACESFilmicToneMapping, WebGPURenderer, Vector4, PostProcessing } from 'three/webgpu';
2
+ import { CubeRenderTarget, RenderTarget, CubeReflectionMapping, EquirectangularReflectionMapping, CubeTextureLoader, Scene, HalfFloatType, Color, Frustum, Matrix4, Group, BoxGeometry, MeshBasicNodeMaterial, Mesh, Node, NodeUpdateType, Layers, ShaderMaterial, Uniform, SRGBColorSpace, RGBAFormat, UnsignedByteType, Vector3, Vector2, TextureLoader, Texture as Texture$1, CanvasTarget, Raycaster, OrthographicCamera, PerspectiveCamera, PCFShadowMap, VSMShadowMap, BasicShadowMap, ACESFilmicToneMapping, WebGPURenderer, Vector4, RenderPipeline } from 'three/webgpu';
3
3
  import { Inspector } from 'three/addons/inspector/Inspector.js';
4
4
  import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
5
5
  import * as React from 'react';
@@ -14,6 +14,8 @@ import { UltraHDRLoader } from 'three/examples/jsm/loaders/UltraHDRLoader.js';
14
14
  import { GainMapLoader } from '@monogrid/gainmap-js';
15
15
  import Tb, { unstable_scheduleCallback, unstable_IdlePriority } from 'scheduler';
16
16
  import { createWithEqualityFn } from 'zustand/traditional';
17
+ import { getScheduler } from '@pmndrs/scheduler';
18
+ export { Scheduler, getScheduler } from '@pmndrs/scheduler';
17
19
  import { suspend, preload, clear } from 'suspend-react';
18
20
  import { dequal } from 'dequal/lite';
19
21
  import 'zustand/shallow';
@@ -41,13 +43,16 @@ const WebGLRenderer = class WebGLRenderer2 {
41
43
  }
42
44
  };
43
45
  const WebGLRenderTarget = null;
46
+ const WebGLCubeRenderTarget = null;
44
47
 
45
48
  const THREE = /*#__PURE__*/_mergeNamespaces({
46
49
  __proto__: null,
50
+ CubeRenderTargetCompat: CubeRenderTarget,
47
51
  Inspector: Inspector,
48
52
  R3F_BUILD_LEGACY: R3F_BUILD_LEGACY,
49
53
  R3F_BUILD_WEBGPU: R3F_BUILD_WEBGPU,
50
54
  RenderTargetCompat: RenderTarget,
55
+ WebGLCubeRenderTarget: WebGLCubeRenderTarget,
51
56
  WebGLRenderTarget: WebGLRenderTarget,
52
57
  WebGLRenderer: WebGLRenderer
53
58
  }, [webgpu]);
@@ -321,15 +326,16 @@ function EnvironmentPortal({
321
326
  preset = void 0,
322
327
  extensions
323
328
  }) {
324
- const gl = useThree$1((state) => state.gl);
329
+ const renderer = useThree$1((state) => state.renderer);
330
+ const isLegacy = useThree$1((state) => state.isLegacy);
325
331
  const defaultScene = useThree$1((state) => state.scene);
326
332
  const camera = React.useRef(null);
327
333
  const [virtualScene] = React.useState(() => new Scene());
328
334
  const fbo = React.useMemo(() => {
329
- const fbo2 = new WebGLCubeRenderTarget(resolution);
335
+ const fbo2 = isLegacy ? new WebGLCubeRenderTarget(resolution) : new CubeRenderTarget(resolution);
330
336
  fbo2.texture.type = HalfFloatType;
331
337
  return fbo2;
332
- }, [resolution]);
338
+ }, [resolution, isLegacy]);
333
339
  React.useEffect(() => {
334
340
  return () => {
335
341
  fbo.dispose();
@@ -337,10 +343,10 @@ function EnvironmentPortal({
337
343
  }, [fbo]);
338
344
  React.useLayoutEffect(() => {
339
345
  if (frames === 1) {
340
- const autoClear = gl.autoClear;
341
- gl.autoClear = true;
342
- camera.current.update(gl, virtualScene);
343
- gl.autoClear = autoClear;
346
+ const autoClear = renderer.autoClear;
347
+ renderer.autoClear = true;
348
+ camera.current.update(renderer, virtualScene);
349
+ renderer.autoClear = autoClear;
344
350
  }
345
351
  return setEnvProps(background, scene, defaultScene, fbo.texture, {
346
352
  backgroundBlurriness: blur ?? backgroundBlurriness,
@@ -357,7 +363,7 @@ function EnvironmentPortal({
357
363
  defaultScene,
358
364
  background,
359
365
  frames,
360
- gl,
366
+ renderer,
361
367
  blur,
362
368
  backgroundBlurriness,
363
369
  backgroundIntensity,
@@ -368,10 +374,10 @@ function EnvironmentPortal({
368
374
  let count = 1;
369
375
  useFrame$1(() => {
370
376
  if (frames === Infinity || count < frames) {
371
- const autoClear = gl.autoClear;
372
- gl.autoClear = true;
373
- camera.current.update(gl, virtualScene);
374
- gl.autoClear = autoClear;
377
+ const autoClear = renderer.autoClear;
378
+ renderer.autoClear = true;
379
+ camera.current.update(renderer, virtualScene);
380
+ renderer.autoClear = autoClear;
375
381
  count++;
376
382
  }
377
383
  });
@@ -435,9 +441,9 @@ function Environment(props) {
435
441
  return props.ground ? /* @__PURE__ */ jsx(EnvironmentGround, { ...props }) : props.map ? /* @__PURE__ */ jsx(EnvironmentMap, { ...props }) : props.children ? /* @__PURE__ */ jsx(EnvironmentPortal, { ...props }) : /* @__PURE__ */ jsx(EnvironmentCube, { ...props });
436
442
  }
437
443
 
438
- var __defProp$3 = Object.defineProperty;
439
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
440
- var __publicField$3 = (obj, key, value) => __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
444
+ var __defProp$1 = Object.defineProperty;
445
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
446
+ var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
441
447
  const act = React["act"];
442
448
  const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React.useLayoutEffect : React.useEffect;
443
449
  function useMutableCallback(fn) {
@@ -469,7 +475,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
469
475
  return _a = class extends React.Component {
470
476
  constructor() {
471
477
  super(...arguments);
472
- __publicField$3(this, "state", { error: false });
478
+ __publicField$1(this, "state", { error: false });
473
479
  }
474
480
  componentDidCatch(err) {
475
481
  this.props.set(err);
@@ -477,7 +483,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
477
483
  render() {
478
484
  return this.state.error ? null : this.props.children;
479
485
  }
480
- }, __publicField$3(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
486
+ }, __publicField$1(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
481
487
  })();
482
488
 
483
489
  const is = {
@@ -614,8 +620,7 @@ function prepare(target, root, type, props) {
614
620
  object,
615
621
  eventCount: 0,
616
622
  handlers: {},
617
- isHidden: false,
618
- deferredRefs: []
623
+ isHidden: false
619
624
  };
620
625
  if (object) object.__r3f = instance;
621
626
  }
@@ -772,6 +777,17 @@ function unregisterVisibility(store, object) {
772
777
  internal.visibilityRegistry.delete(object.uuid);
773
778
  internal.occlusionCache.delete(object);
774
779
  }
780
+ function updateVisibilityHandlers(store, object, handlers) {
781
+ const { internal } = store.getState();
782
+ const entry = internal.visibilityRegistry.get(object.uuid);
783
+ if (!entry) return false;
784
+ entry.handlers = handlers;
785
+ if ((handlers.onOccluded || handlers.onVisible) && !internal.occlusionEnabled) {
786
+ object.occlusionTest = true;
787
+ enableOcclusion(store);
788
+ }
789
+ return true;
790
+ }
775
791
  function checkVisibility(state) {
776
792
  const { internal, camera } = state;
777
793
  const registry = internal.visibilityRegistry;
@@ -959,10 +975,7 @@ function applyProps(object, props) {
959
975
  continue;
960
976
  }
961
977
  if (value === void 0) continue;
962
- if (isFromRef(value)) {
963
- instance?.deferredRefs?.push({ prop, ref: value[FROM_REF] });
964
- continue;
965
- }
978
+ if (isFromRef(value)) continue;
966
979
  if (isOnce(value)) {
967
980
  if (instance?.appliedOnce?.has(prop)) continue;
968
981
  if (instance) {
@@ -998,6 +1011,19 @@ function applyProps(object, props) {
998
1011
  } else if (isVectorLike(target) && is.num(value)) {
999
1012
  if ("setScalar" in target && typeof target.setScalar === "function") target.setScalar(value);
1000
1013
  else target.set(value);
1014
+ } else if (root instanceof ShaderMaterial && key === "uniforms" && is.obj(value)) {
1015
+ if (!is.obj(root.uniforms)) root.uniforms = {};
1016
+ const uniforms = root.uniforms;
1017
+ const nextUniforms = value;
1018
+ for (const name in nextUniforms) {
1019
+ const uniform = nextUniforms[name];
1020
+ const targetUniform = uniforms[name];
1021
+ if (targetUniform) Object.assign(targetUniform, uniform);
1022
+ else {
1023
+ const nextUniform = uniform instanceof Uniform ? uniform.clone() : new Uniform(uniform.value);
1024
+ uniforms[name] = nextUniform;
1025
+ }
1026
+ }
1001
1027
  } else {
1002
1028
  root[key] = value;
1003
1029
  if (key.endsWith("Node") && root.isMaterial) {
@@ -1016,6 +1042,9 @@ function applyProps(object, props) {
1016
1042
  if (instance.eventCount && object2.raycast !== null) {
1017
1043
  rootState.internal.interaction.push(object2);
1018
1044
  }
1045
+ }
1046
+ if (instance?.parent && rootState?.internal && instance.object?.isObject3D) {
1047
+ const object2 = instance.object;
1019
1048
  const root = findInitialRoot(instance);
1020
1049
  const visibilityHandlers = {
1021
1050
  onFramed: instance.handlers.onFramed,
@@ -1023,7 +1052,9 @@ function applyProps(object, props) {
1023
1052
  onVisible: instance.handlers.onVisible
1024
1053
  };
1025
1054
  if (hasVisibilityHandlers(visibilityHandlers)) {
1026
- registerVisibility(root, object2, visibilityHandlers);
1055
+ if (!updateVisibilityHandlers(root, object2, visibilityHandlers)) {
1056
+ registerVisibility(root, object2, visibilityHandlers);
1057
+ }
1027
1058
  } else {
1028
1059
  unregisterVisibility(root, object2);
1029
1060
  }
@@ -1551,6 +1582,7 @@ function createPointerEvents(store) {
1551
1582
  set((state) => ({ events: { ...state.events, connected: void 0 } }));
1552
1583
  }
1553
1584
  },
1585
+ // PREVIEW (A8): the XR pointer registration API may change before stable.
1554
1586
  registerPointer: (config) => {
1555
1587
  const pointerId = nextXRPointerId++;
1556
1588
  xrPointers.set(pointerId, config);
@@ -1637,1036 +1669,11 @@ function notifyAlpha({ message, link }) {
1637
1669
  }
1638
1670
  }
1639
1671
 
1640
- var __defProp$2 = Object.defineProperty;
1641
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1642
- var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
1643
- const DEFAULT_PHASES = ["start", "input", "physics", "update", "render", "finish"];
1644
- class PhaseGraph {
1645
- constructor() {
1646
- /** Ordered list of phase nodes */
1647
- __publicField$2(this, "phases", []);
1648
- /** Quick lookup by name */
1649
- __publicField$2(this, "phaseMap", /* @__PURE__ */ new Map());
1650
- /** Cached ordered names (invalidated on changes) */
1651
- __publicField$2(this, "orderedNamesCache", null);
1652
- this.initializeDefaultPhases();
1653
- }
1654
- //* Initialization --------------------------------
1655
- initializeDefaultPhases() {
1656
- for (const name of DEFAULT_PHASES) {
1657
- const node = { name, isAutoGenerated: false };
1658
- this.phases.push(node);
1659
- this.phaseMap.set(name, node);
1660
- }
1661
- this.invalidateCache();
1662
- }
1663
- //* Public API --------------------------------
1664
- /**
1665
- * Add a named phase to the graph
1666
- * @param name - Phase name (must be unique)
1667
- * @param options - Position options (before or after another phase)
1668
- */
1669
- addPhase(name, options = {}) {
1670
- if (this.phaseMap.has(name)) {
1671
- console.warn(`[useFrame] Phase "${name}" already exists`);
1672
- return;
1673
- }
1674
- const { before, after } = options;
1675
- const node = { name, isAutoGenerated: false };
1676
- let insertIndex = this.phases.length;
1677
- const targetIndex = this.getPhaseIndex(before ?? after);
1678
- if (targetIndex !== -1) {
1679
- insertIndex = before ? targetIndex : targetIndex + 1;
1680
- } else {
1681
- const constraintType = before ? "before" : "after";
1682
- console.warn(`[useFrame] Phase "${before ?? after}" not found for '${constraintType}' constraint`);
1683
- }
1684
- this.phases.splice(insertIndex, 0, node);
1685
- this.phaseMap.set(name, node);
1686
- this.invalidateCache();
1687
- }
1688
- /**
1689
- * Get ordered list of phase names
1690
- */
1691
- getOrderedPhases() {
1692
- if (this.orderedNamesCache === null) this.orderedNamesCache = this.phases.map((p) => p.name);
1693
- return this.orderedNamesCache;
1694
- }
1695
- /**
1696
- * Check if a phase exists
1697
- */
1698
- hasPhase(name) {
1699
- return this.phaseMap.has(name);
1700
- }
1701
- /**
1702
- * Get the index of a phase (-1 if not found)
1703
- */
1704
- getPhaseIndex(name) {
1705
- if (!name) return -1;
1706
- return this.phases.findIndex((p) => p.name === name);
1707
- }
1708
- /**
1709
- * Ensure a phase exists, creating an auto-generated one if needed.
1710
- * Used for resolving before/after constraints.
1711
- *
1712
- * @param name - The phase name to ensure exists
1713
- * @returns The phase name (may be auto-generated like 'before:render')
1714
- */
1715
- ensurePhase(name) {
1716
- if (this.phaseMap.has(name)) return name;
1717
- const node = { name, isAutoGenerated: true };
1718
- this.phases.push(node);
1719
- this.phaseMap.set(name, node);
1720
- this.invalidateCache();
1721
- return name;
1722
- }
1723
- /**
1724
- * Resolve where a job with before/after constraints should go.
1725
- * Creates auto-generated phases if needed.
1726
- *
1727
- * @param before - Phase(s) to run before
1728
- * @param after - Phase(s) to run after
1729
- * @returns The resolved phase name
1730
- */
1731
- resolveConstraintPhase(before, after) {
1732
- const beforeArr = before ? Array.isArray(before) ? before : [before] : [];
1733
- const afterArr = after ? Array.isArray(after) ? after : [after] : [];
1734
- if (beforeArr.length > 0) {
1735
- return this.ensureAutoPhase(beforeArr[0], "before", 0);
1736
- }
1737
- if (afterArr.length > 0) {
1738
- return this.ensureAutoPhase(afterArr[0], "after", 1);
1739
- }
1740
- return "update";
1741
- }
1742
- /**
1743
- * Ensure an auto-generated phase exists relative to a target phase.
1744
- * Creates the phase if it doesn't exist, inserting it at the correct position.
1745
- *
1746
- * @param target - The target phase name to position relative to
1747
- * @param prefix - Prefix for auto-generated phase name ('before' or 'after')
1748
- * @param offset - Insertion offset (0 for before, 1 for after)
1749
- * @returns The auto-generated phase name
1750
- */
1751
- ensureAutoPhase(target, prefix, offset) {
1752
- const autoName = `${prefix}:${target}`;
1753
- if (this.phaseMap.has(autoName)) return autoName;
1754
- const node = { name: autoName, isAutoGenerated: true };
1755
- const targetIndex = this.getPhaseIndex(target);
1756
- if (targetIndex !== -1) this.phases.splice(targetIndex + offset, 0, node);
1757
- else this.phases.push(node);
1758
- this.phaseMap.set(autoName, node);
1759
- this.invalidateCache();
1760
- return autoName;
1761
- }
1762
- // Internal --------------------------------
1763
- invalidateCache() {
1764
- this.orderedNamesCache = null;
1765
- }
1766
- }
1767
-
1768
- function rebuildSortedJobs(jobs, phaseGraph) {
1769
- const orderedPhases = phaseGraph.getOrderedPhases();
1770
- const buckets = /* @__PURE__ */ new Map();
1771
- for (const phase of orderedPhases) {
1772
- buckets.set(phase, []);
1773
- }
1774
- for (const job of jobs.values()) {
1775
- if (!job.enabled) continue;
1776
- let bucket = buckets.get(job.phase);
1777
- if (!bucket) {
1778
- bucket = [];
1779
- buckets.set(job.phase, bucket);
1780
- }
1781
- bucket.push(job);
1782
- }
1783
- const sortedBuckets = [];
1784
- for (const phase of orderedPhases) {
1785
- const bucket = buckets.get(phase);
1786
- if (!bucket || bucket.length === 0) continue;
1787
- bucket.sort((a, b) => {
1788
- if (a.priority !== b.priority) return b.priority - a.priority;
1789
- return a.index - b.index;
1790
- });
1791
- sortedBuckets.push(hasCrossJobConstraints(bucket) ? topologicalSort(bucket) : bucket);
1792
- }
1793
- for (const [phase, bucket] of buckets) {
1794
- if (!orderedPhases.includes(phase) && bucket.length > 0) {
1795
- bucket.sort((a, b) => {
1796
- if (a.priority !== b.priority) return b.priority - a.priority;
1797
- return a.index - b.index;
1798
- });
1799
- sortedBuckets.push(bucket);
1800
- }
1801
- }
1802
- return sortedBuckets.flat();
1803
- }
1804
- function hasCrossJobConstraints(bucket) {
1805
- const jobIds = new Set(bucket.map((j) => j.id));
1806
- for (const job of bucket) {
1807
- for (const ref of job.before) {
1808
- if (jobIds.has(ref)) return true;
1809
- }
1810
- for (const ref of job.after) {
1811
- if (jobIds.has(ref)) return true;
1812
- }
1813
- }
1814
- return false;
1815
- }
1816
- function topologicalSort(jobs) {
1817
- const n = jobs.length;
1818
- if (n <= 1) return jobs;
1819
- const jobMap = /* @__PURE__ */ new Map();
1820
- const inDegree = /* @__PURE__ */ new Map();
1821
- const adjacency = /* @__PURE__ */ new Map();
1822
- for (const job of jobs) {
1823
- jobMap.set(job.id, job);
1824
- inDegree.set(job.id, 0);
1825
- adjacency.set(job.id, []);
1826
- }
1827
- for (const job of jobs) {
1828
- for (const ref of job.before) {
1829
- if (jobMap.has(ref)) {
1830
- adjacency.get(job.id).push(ref);
1831
- inDegree.set(ref, inDegree.get(ref) + 1);
1832
- }
1833
- }
1834
- for (const ref of job.after) {
1835
- if (jobMap.has(ref)) {
1836
- adjacency.get(ref).push(job.id);
1837
- inDegree.set(job.id, inDegree.get(job.id) + 1);
1838
- }
1839
- }
1840
- }
1841
- const queue = [];
1842
- for (const job of jobs) {
1843
- if (inDegree.get(job.id) === 0) {
1844
- queue.push(job);
1845
- }
1846
- }
1847
- queue.sort((a, b) => {
1848
- if (a.priority !== b.priority) return b.priority - a.priority;
1849
- return a.index - b.index;
1850
- });
1851
- const result = [];
1852
- while (queue.length > 0) {
1853
- const job = queue.shift();
1854
- result.push(job);
1855
- const neighbors = adjacency.get(job.id) || [];
1856
- for (const neighborId of neighbors) {
1857
- const newDegree = inDegree.get(neighborId) - 1;
1858
- inDegree.set(neighborId, newDegree);
1859
- if (newDegree === 0) {
1860
- const neighbor = jobMap.get(neighborId);
1861
- insertSorted(queue, neighbor);
1862
- }
1863
- }
1864
- }
1865
- if (result.length !== n) {
1866
- console.warn("[useFrame] Circular dependency detected in job constraints");
1867
- const resultIds = new Set(result.map((j) => j.id));
1868
- for (const job of jobs) {
1869
- if (!resultIds.has(job.id)) result.push(job);
1870
- }
1871
- }
1872
- return result;
1873
- }
1874
- function insertSorted(arr, job) {
1875
- let i = 0;
1876
- while (i < arr.length) {
1877
- const cmp = arr[i];
1878
- if (job.priority > cmp.priority || job.priority === cmp.priority && job.index < cmp.index) {
1879
- break;
1880
- }
1881
- i++;
1882
- }
1883
- arr.splice(i, 0, job);
1884
- }
1885
-
1886
- function shouldRun(job, now) {
1887
- if (!job.enabled) return false;
1888
- if (!job.fps) return true;
1889
- const minInterval = 1e3 / job.fps;
1890
- const lastRun = job.lastRun ?? 0;
1891
- const elapsed = now - lastRun;
1892
- if (elapsed < minInterval - 1) return false;
1893
- if (job.drop) {
1894
- job.lastRun = now;
1895
- } else {
1896
- const steps = Math.floor(elapsed / minInterval);
1897
- job.lastRun = lastRun + steps * minInterval;
1898
- if (job.lastRun < now - minInterval) {
1899
- job.lastRun = now;
1900
- }
1901
- }
1902
- return true;
1903
- }
1904
- function resetJobTiming(job) {
1905
- job.lastRun = void 0;
1906
- }
1907
-
1908
- var __defProp$1 = Object.defineProperty;
1909
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1910
- var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1911
- const hmrData = (() => {
1912
- if (typeof process !== "undefined" && process.env.NODE_ENV === "test") return void 0;
1913
- if (typeof import_meta_hot !== "undefined") return import_meta_hot;
1914
- try {
1915
- return (0, eval)("import.meta.hot");
1916
- } catch {
1917
- return void 0;
1918
- }
1919
- })();
1920
- const _Scheduler = class _Scheduler {
1921
- //* Constructor ================================
1922
- constructor() {
1923
- //* Critical State ================================
1924
- __publicField$1(this, "roots", /* @__PURE__ */ new Map());
1925
- __publicField$1(this, "phaseGraph");
1926
- __publicField$1(this, "loopState", {
1927
- running: false,
1928
- rafHandle: null,
1929
- lastTime: null,
1930
- // null = uninitialized, 0+ = valid timestamp
1931
- frameCount: 0,
1932
- elapsedTime: 0,
1933
- createdAt: performance.now()
1934
- });
1935
- __publicField$1(this, "stoppedTime", 0);
1936
- //* Private State ================================
1937
- __publicField$1(this, "nextRootIndex", 0);
1938
- __publicField$1(this, "globalBeforeJobs", /* @__PURE__ */ new Map());
1939
- __publicField$1(this, "globalAfterJobs", /* @__PURE__ */ new Map());
1940
- __publicField$1(this, "nextGlobalIndex", 0);
1941
- __publicField$1(this, "idleCallbacks", /* @__PURE__ */ new Set());
1942
- __publicField$1(this, "nextJobIndex", 0);
1943
- __publicField$1(this, "jobStateListeners", /* @__PURE__ */ new Map());
1944
- __publicField$1(this, "pendingFrames", 0);
1945
- __publicField$1(this, "_frameloop", "always");
1946
- //* Independent Mode & Error Handling State ================================
1947
- __publicField$1(this, "_independent", false);
1948
- __publicField$1(this, "errorHandler", null);
1949
- __publicField$1(this, "rootReadyCallbacks", /* @__PURE__ */ new Set());
1950
- //* Core Loop Execution Methods ================================
1951
- /**
1952
- * Main RAF loop callback.
1953
- * Executes frame, handles demand mode, and schedules next frame.
1954
- * @param {number} timestamp - RAF timestamp in milliseconds
1955
- * @returns {void}
1956
- * @private
1957
- */
1958
- __publicField$1(this, "loop", (timestamp) => {
1959
- if (!this.loopState.running) return;
1960
- this.executeFrame(timestamp);
1961
- if (this._frameloop === "demand") {
1962
- this.pendingFrames = Math.max(0, this.pendingFrames - 1);
1963
- if (this.pendingFrames === 0) {
1964
- this.notifyIdle(timestamp);
1965
- return this.stop();
1966
- }
1967
- }
1968
- this.loopState.rafHandle = requestAnimationFrame(this.loop);
1969
- });
1970
- this.phaseGraph = new PhaseGraph();
1971
- }
1972
- static get instance() {
1973
- return globalThis[_Scheduler.INSTANCE_KEY] ?? null;
1974
- }
1975
- static set instance(value) {
1976
- globalThis[_Scheduler.INSTANCE_KEY] = value;
1977
- }
1978
- /**
1979
- * Get the global scheduler instance (creates if doesn't exist).
1980
- * Uses HMR data to preserve instance across hot reloads.
1981
- * @returns {Scheduler} The singleton scheduler instance
1982
- */
1983
- static get() {
1984
- if (!_Scheduler.instance && hmrData?.data?.scheduler) {
1985
- _Scheduler.instance = hmrData.data.scheduler;
1986
- }
1987
- if (!_Scheduler.instance) {
1988
- _Scheduler.instance = new _Scheduler();
1989
- if (hmrData?.data) {
1990
- hmrData.data.scheduler = _Scheduler.instance;
1991
- }
1992
- }
1993
- return _Scheduler.instance;
1994
- }
1995
- /**
1996
- * Reset the singleton instance. Stops the loop and clears all state.
1997
- * Primarily used for testing to ensure clean state between tests.
1998
- * @returns {void}
1999
- */
2000
- static reset() {
2001
- if (_Scheduler.instance) {
2002
- _Scheduler.instance.stop();
2003
- _Scheduler.instance = null;
2004
- }
2005
- if (hmrData?.data) {
2006
- hmrData.data.scheduler = null;
2007
- }
2008
- }
2009
- //* Getters & Setters ================================
2010
- get phases() {
2011
- return this.phaseGraph.getOrderedPhases();
2012
- }
2013
- get frameloop() {
2014
- return this._frameloop;
2015
- }
2016
- set frameloop(mode) {
2017
- if (this._frameloop === mode) return;
2018
- const wasAlways = this._frameloop === "always";
2019
- this._frameloop = mode;
2020
- if (mode === "always" && !this.loopState.running && this.roots.size > 0) this.start();
2021
- else if (mode !== "always" && wasAlways) this.stop();
2022
- }
2023
- get isRunning() {
2024
- return this.loopState.running;
2025
- }
2026
- get isReady() {
2027
- return this.roots.size > 0;
2028
- }
2029
- get independent() {
2030
- return this._independent;
2031
- }
2032
- set independent(value) {
2033
- this._independent = value;
2034
- if (value) this.ensureDefaultRoot();
2035
- }
2036
- //* Root Management Methods ================================
2037
- /**
2038
- * Register a root (Canvas) with the scheduler.
2039
- * The first root to register starts the RAF loop (if frameloop='always').
2040
- * @param {string} id - Unique identifier for this root
2041
- * @param {RootOptions} [options] - Optional configuration with getState and onError callbacks
2042
- * @returns {() => void} Unsubscribe function to remove this root
2043
- */
2044
- registerRoot(id, options = {}) {
2045
- if (this.roots.has(id)) {
2046
- console.warn(`[Scheduler] Root "${id}" already registered`);
2047
- return () => this.unregisterRoot(id);
2048
- }
2049
- const entry = {
2050
- id,
2051
- getState: options.getState ?? (() => ({})),
2052
- jobs: /* @__PURE__ */ new Map(),
2053
- sortedJobs: [],
2054
- needsRebuild: false
2055
- };
2056
- if (options.onError) {
2057
- this.errorHandler = options.onError;
2058
- }
2059
- this.roots.set(id, entry);
2060
- if (this.roots.size === 1) {
2061
- this.notifyRootReady();
2062
- if (this._frameloop === "always") this.start();
2063
- }
2064
- return () => this.unregisterRoot(id);
2065
- }
2066
- /**
2067
- * Unregister a root from the scheduler.
2068
- * Cleans up all job state listeners for this root's jobs.
2069
- * The last root to unregister stops the RAF loop.
2070
- * @param {string} id - The root ID to unregister
2071
- * @returns {void}
2072
- */
2073
- unregisterRoot(id) {
2074
- const root = this.roots.get(id);
2075
- if (!root) return;
2076
- for (const jobId of root.jobs.keys()) {
2077
- this.jobStateListeners.delete(jobId);
2078
- }
2079
- this.roots.delete(id);
2080
- if (this.roots.size === 0) {
2081
- this.stop();
2082
- this.errorHandler = null;
2083
- }
2084
- }
2085
- /**
2086
- * Subscribe to be notified when a root becomes available.
2087
- * Fires immediately if a root already exists.
2088
- * @param {() => void} callback - Function called when first root registers
2089
- * @returns {() => void} Unsubscribe function
2090
- */
2091
- onRootReady(callback) {
2092
- if (this.roots.size > 0) {
2093
- callback();
2094
- return () => {
2095
- };
2096
- }
2097
- this.rootReadyCallbacks.add(callback);
2098
- return () => this.rootReadyCallbacks.delete(callback);
2099
- }
2100
- /**
2101
- * Notify all registered root-ready callbacks.
2102
- * Called when the first root registers.
2103
- * @returns {void}
2104
- * @private
2105
- */
2106
- notifyRootReady() {
2107
- for (const cb of this.rootReadyCallbacks) {
2108
- try {
2109
- cb();
2110
- } catch (error) {
2111
- console.error("[Scheduler] Error in root-ready callback:", error);
2112
- }
2113
- }
2114
- this.rootReadyCallbacks.clear();
2115
- }
2116
- /**
2117
- * Ensure a default root exists for independent mode.
2118
- * Creates a minimal root with no state provider.
2119
- * @returns {void}
2120
- * @private
2121
- */
2122
- ensureDefaultRoot() {
2123
- if (!this.roots.has("__default__")) {
2124
- this.registerRoot("__default__");
2125
- }
2126
- }
2127
- /**
2128
- * Trigger error handling for job errors.
2129
- * Uses the bound error handler if available, otherwise logs to console.
2130
- * @param {Error} error - The error to handle
2131
- * @returns {void}
2132
- */
2133
- triggerError(error) {
2134
- if (this.errorHandler) this.errorHandler(error);
2135
- else console.error("[Scheduler]", error);
2136
- }
2137
- //* Phase Management Methods ================================
2138
- /**
2139
- * Add a named phase to the scheduler's execution order.
2140
- * Marks all roots for rebuild to incorporate the new phase.
2141
- * @param {string} name - The phase name (e.g., 'physics', 'postprocess')
2142
- * @param {AddPhaseOptions} [options] - Positioning options (before/after other phases)
2143
- * @returns {void}
2144
- * @example
2145
- * scheduler.addPhase('physics', { before: 'update' });
2146
- * scheduler.addPhase('postprocess', { after: 'render' });
2147
- */
2148
- addPhase(name, options) {
2149
- this.phaseGraph.addPhase(name, options);
2150
- for (const root of this.roots.values()) {
2151
- root.needsRebuild = true;
2152
- }
2153
- }
2154
- /**
2155
- * Check if a phase exists in the scheduler.
2156
- * @param {string} name - The phase name to check
2157
- * @returns {boolean} True if the phase exists
2158
- */
2159
- hasPhase(name) {
2160
- return this.phaseGraph.hasPhase(name);
2161
- }
2162
- //* Global Job Registration Methods (Deprecated APIs) ================================
2163
- /**
2164
- * Register a global job that runs once per frame (not per-root).
2165
- * Used internally by deprecated addEffect/addAfterEffect APIs.
2166
- * @param {'before' | 'after'} phase - When to run: 'before' all roots or 'after' all roots
2167
- * @param {string} id - Unique identifier for this global job
2168
- * @param {(timestamp: number) => void} callback - Function called each frame with RAF timestamp
2169
- * @returns {() => void} Unsubscribe function to remove this global job
2170
- * @deprecated Use useFrame with phases instead
2171
- */
2172
- registerGlobal(phase, id, callback) {
2173
- const job = { id, callback };
2174
- if (phase === "before") {
2175
- this.globalBeforeJobs.set(id, job);
2176
- } else {
2177
- this.globalAfterJobs.set(id, job);
2178
- }
2179
- return () => {
2180
- if (phase === "before") this.globalBeforeJobs.delete(id);
2181
- else this.globalAfterJobs.delete(id);
2182
- };
2183
- }
2184
- //* Idle Callback Methods (Deprecated API) ================================
2185
- /**
2186
- * Register an idle callback that fires when the loop stops.
2187
- * Used internally by deprecated addTail API.
2188
- * @param {(timestamp: number) => void} callback - Function called when loop becomes idle
2189
- * @returns {() => void} Unsubscribe function to remove this idle callback
2190
- * @deprecated Use demand mode with invalidate() instead
2191
- */
2192
- onIdle(callback) {
2193
- this.idleCallbacks.add(callback);
2194
- return () => this.idleCallbacks.delete(callback);
2195
- }
2196
- /**
2197
- * Notify all registered idle callbacks.
2198
- * Called when the loop stops in demand mode.
2199
- * @param {number} timestamp - The RAF timestamp when idle occurred
2200
- * @returns {void}
2201
- * @private
2202
- */
2203
- notifyIdle(timestamp) {
2204
- for (const cb of this.idleCallbacks) {
2205
- try {
2206
- cb(timestamp);
2207
- } catch (error) {
2208
- console.error("[Scheduler] Error in idle callback:", error);
2209
- }
2210
- }
2211
- }
2212
- //* Job Registration & Management Methods ================================
2213
- /**
2214
- * Register a job (frame callback) with a specific root.
2215
- * This is the core registration method used by useFrame internally.
2216
- * @param {FrameNextCallback} callback - The function to call each frame
2217
- * @param {JobOptions & { rootId?: string; system?: boolean }} [options] - Job configuration
2218
- * @param {string} [options.rootId] - Target root ID (defaults to first registered root)
2219
- * @param {string} [options.id] - Unique job ID (auto-generated if not provided)
2220
- * @param {string} [options.phase] - Execution phase (defaults to 'update')
2221
- * @param {number} [options.priority] - Priority within phase (higher = earlier, default 0)
2222
- * @param {number} [options.fps] - FPS throttle limit
2223
- * @param {boolean} [options.drop] - Drop frames when behind (default true)
2224
- * @param {boolean} [options.enabled] - Whether job is active (default true)
2225
- * @param {boolean} [options.system] - Internal flag for system jobs (not user-facing)
2226
- * @returns {() => void} Unsubscribe function to remove this job
2227
- */
2228
- register(callback, options = {}) {
2229
- const rootId = options.rootId;
2230
- const root = rootId ? this.roots.get(rootId) : this.roots.values().next().value;
2231
- if (!root) {
2232
- console.warn("[Scheduler] No root registered. Is this inside a Canvas?");
2233
- return () => {
2234
- };
2235
- }
2236
- const id = options.id ?? this.generateJobId();
2237
- let phase = options.phase ?? "update";
2238
- if (!options.phase && (options.before || options.after)) {
2239
- phase = this.phaseGraph.resolveConstraintPhase(options.before, options.after);
2240
- }
2241
- const before = this.normalizeConstraints(options.before);
2242
- const after = this.normalizeConstraints(options.after);
2243
- const job = {
2244
- id,
2245
- callback,
2246
- phase,
2247
- before,
2248
- after,
2249
- priority: options.priority ?? 0,
2250
- index: this.nextJobIndex++,
2251
- fps: options.fps,
2252
- drop: options.drop ?? true,
2253
- enabled: options.enabled ?? true,
2254
- system: options.system ?? false
2255
- };
2256
- if (root.jobs.has(id)) {
2257
- console.warn(`[useFrame] Job with id "${id}" already exists, replacing`);
2258
- }
2259
- root.jobs.set(id, job);
2260
- root.needsRebuild = true;
2261
- return () => this.unregister(id, root.id);
2262
- }
2263
- /**
2264
- * Unregister a job by its ID.
2265
- * Searches all roots if rootId is not provided.
2266
- * @param {string} id - The job ID to unregister
2267
- * @param {string} [rootId] - Optional root ID to search (searches all if not provided)
2268
- * @returns {void}
2269
- */
2270
- unregister(id, rootId) {
2271
- const root = rootId ? this.roots.get(rootId) : Array.from(this.roots.values()).find((r) => r.jobs.has(id));
2272
- if (root?.jobs.delete(id)) {
2273
- root.needsRebuild = true;
2274
- this.jobStateListeners.delete(id);
2275
- }
2276
- }
2277
- /**
2278
- * Update a job's options dynamically.
2279
- * Searches all roots to find the job by ID.
2280
- * Phase/constraint changes trigger a rebuild of the sorted job list.
2281
- * @param {string} id - The job ID to update
2282
- * @param {Partial<JobOptions>} options - The options to update
2283
- * @returns {void}
2284
- */
2285
- updateJob(id, options) {
2286
- let job;
2287
- let root;
2288
- for (const r of this.roots.values()) {
2289
- job = r.jobs.get(id);
2290
- if (job) {
2291
- root = r;
2292
- break;
2293
- }
2294
- }
2295
- if (!job || !root) return;
2296
- if (options.priority !== void 0) job.priority = options.priority;
2297
- if (options.fps !== void 0) job.fps = options.fps;
2298
- if (options.drop !== void 0) job.drop = options.drop;
2299
- if (options.enabled !== void 0) {
2300
- const wasEnabled = job.enabled;
2301
- job.enabled = options.enabled;
2302
- if (!wasEnabled && job.enabled) resetJobTiming(job);
2303
- if (wasEnabled !== job.enabled) root.needsRebuild = true;
2304
- }
2305
- if (options.phase !== void 0 || options.before !== void 0 || options.after !== void 0) {
2306
- if (options.phase) job.phase = options.phase;
2307
- if (options.before !== void 0) job.before = this.normalizeConstraints(options.before);
2308
- if (options.after !== void 0) job.after = this.normalizeConstraints(options.after);
2309
- root.needsRebuild = true;
2310
- }
2311
- }
2312
- //* Job State Management Methods ================================
2313
- /**
2314
- * Check if a job is currently paused (disabled).
2315
- * @param {string} id - The job ID to check
2316
- * @returns {boolean} True if the job exists and is paused
2317
- */
2318
- isJobPaused(id) {
2319
- for (const root of this.roots.values()) {
2320
- const job = root.jobs.get(id);
2321
- if (job) return !job.enabled;
2322
- }
2323
- return false;
2324
- }
2325
- /**
2326
- * Subscribe to state changes for a specific job.
2327
- * Listener is called when job is paused or resumed.
2328
- * @param {string} id - The job ID to subscribe to
2329
- * @param {() => void} listener - Callback invoked on state changes
2330
- * @returns {() => void} Unsubscribe function
2331
- */
2332
- subscribeJobState(id, listener) {
2333
- if (!this.jobStateListeners.has(id)) {
2334
- this.jobStateListeners.set(id, /* @__PURE__ */ new Set());
2335
- }
2336
- this.jobStateListeners.get(id).add(listener);
2337
- return () => {
2338
- this.jobStateListeners.get(id)?.delete(listener);
2339
- if (this.jobStateListeners.get(id)?.size === 0) {
2340
- this.jobStateListeners.delete(id);
2341
- }
2342
- };
2343
- }
2344
- /**
2345
- * Notify all listeners that a job's state has changed.
2346
- * @param {string} id - The job ID that changed
2347
- * @returns {void}
2348
- * @private
2349
- */
2350
- notifyJobStateChange(id) {
2351
- this.jobStateListeners.get(id)?.forEach((listener) => listener());
2352
- }
2353
- /**
2354
- * Pause a job by ID (sets enabled=false).
2355
- * Notifies any subscribed state listeners.
2356
- * @param {string} id - The job ID to pause
2357
- * @returns {void}
2358
- */
2359
- pauseJob(id) {
2360
- this.updateJob(id, { enabled: false });
2361
- this.notifyJobStateChange(id);
2362
- }
2363
- /**
2364
- * Resume a paused job by ID (sets enabled=true).
2365
- * Resets job timing to prevent frame accumulation.
2366
- * Notifies any subscribed state listeners.
2367
- * @param {string} id - The job ID to resume
2368
- * @returns {void}
2369
- */
2370
- resumeJob(id) {
2371
- this.updateJob(id, { enabled: true });
2372
- this.notifyJobStateChange(id);
2373
- }
2374
- //* Frame Loop Control Methods ================================
2375
- /**
2376
- * Start the requestAnimationFrame loop.
2377
- * Resets timing state (elapsedTime, frameCount) on start.
2378
- * No-op if already running.
2379
- * @returns {void}
2380
- */
2381
- start() {
2382
- if (this.loopState.running) return;
2383
- const { elapsedTime, createdAt } = this.loopState;
2384
- let adjustedCreated = 0;
2385
- if (this.stoppedTime > 0) {
2386
- adjustedCreated = createdAt - (performance.now() - this.stoppedTime);
2387
- this.stoppedTime = 0;
2388
- }
2389
- Object.assign(this.loopState, {
2390
- running: true,
2391
- elapsedTime: elapsedTime ?? 0,
2392
- lastTime: performance.now(),
2393
- createdAt: adjustedCreated > 0 ? adjustedCreated : performance.now(),
2394
- frameCount: 0,
2395
- rafHandle: requestAnimationFrame(this.loop)
2396
- });
2397
- }
2398
- /**
2399
- * Stop the requestAnimationFrame loop.
2400
- * Cancels any pending RAF callback.
2401
- * No-op if not running.
2402
- * @returns {void}
2403
- */
2404
- stop() {
2405
- if (!this.loopState.running) return;
2406
- this.loopState.running = false;
2407
- if (this.loopState.rafHandle !== null) {
2408
- cancelAnimationFrame(this.loopState.rafHandle);
2409
- this.loopState.rafHandle = null;
2410
- }
2411
- this.stoppedTime = performance.now();
2412
- }
2413
- /**
2414
- * Request frames to be rendered in demand mode.
2415
- * Accumulates pending frames (capped at 60) and starts the loop if not running.
2416
- * No-op if frameloop is not 'demand'.
2417
- * @param {number} [frames=1] - Number of frames to request
2418
- * @param {boolean} [stackFrames=false] - Whether to add frames to existing pending count
2419
- * - `false` (default): Sets pending frames to the specified value (replaces existing count)
2420
- * - `true`: Adds frames to existing pending count (useful for accumulating invalidations)
2421
- * @returns {void}
2422
- * @example
2423
- * // Request a single frame render
2424
- * scheduler.invalidate();
2425
- *
2426
- * @example
2427
- * // Request 5 frames (e.g., for animations)
2428
- * scheduler.invalidate(5);
2429
- *
2430
- * @example
2431
- * // Set pending frames to exactly 3 (don't stack with existing)
2432
- * scheduler.invalidate(3, false);
2433
- *
2434
- * @example
2435
- * // Add 2 more frames to existing pending count
2436
- * scheduler.invalidate(2, true);
2437
- */
2438
- invalidate(frames = 1, stackFrames = false) {
2439
- if (this._frameloop !== "demand") return;
2440
- const baseFrames = stackFrames ? this.pendingFrames : 0;
2441
- this.pendingFrames = Math.min(60, baseFrames + frames);
2442
- if (!this.loopState.running && this.pendingFrames > 0) this.start();
2443
- }
2444
- /**
2445
- * Reset timing state for deterministic testing.
2446
- * Preserves jobs and roots but resets lastTime, frameCount, elapsedTime, etc.
2447
- * @returns {void}
2448
- */
2449
- resetTiming() {
2450
- this.loopState.lastTime = null;
2451
- this.loopState.frameCount = 0;
2452
- this.loopState.elapsedTime = 0;
2453
- this.loopState.createdAt = performance.now();
2454
- }
2455
- //* Manual Stepping Methods ================================
2456
- /**
2457
- * Manually execute a single frame for all roots.
2458
- * Useful for frameloop='never' mode or testing scenarios.
2459
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2460
- * @returns {void}
2461
- * @example
2462
- * // Manual control mode
2463
- * scheduler.frameloop = 'never';
2464
- * scheduler.step(); // Execute one frame
2465
- */
2466
- step(timestamp) {
2467
- const now = timestamp ?? performance.now();
2468
- this.executeFrame(now);
2469
- }
2470
- /**
2471
- * Manually execute a single job by its ID.
2472
- * Useful for testing individual job callbacks in isolation.
2473
- * @param {string} id - The job ID to step
2474
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2475
- * @returns {void}
2476
- */
2477
- stepJob(id, timestamp) {
2478
- let job;
2479
- let root;
2480
- for (const r of this.roots.values()) {
2481
- job = r.jobs.get(id);
2482
- if (job) {
2483
- root = r;
2484
- break;
2485
- }
2486
- }
2487
- if (!job || !root) {
2488
- console.warn(`[Scheduler] Job "${id}" not found`);
2489
- return;
2490
- }
2491
- const now = timestamp ?? performance.now();
2492
- const deltaMs = this.loopState.lastTime !== null ? now - this.loopState.lastTime : 0;
2493
- const delta = deltaMs / 1e3;
2494
- const elapsed = now - this.loopState.createdAt;
2495
- const providedState = root.getState?.() ?? {};
2496
- const frameState = {
2497
- ...providedState,
2498
- time: now,
2499
- delta,
2500
- elapsed,
2501
- frame: this.loopState.frameCount
2502
- };
2503
- try {
2504
- job.callback(frameState, delta);
2505
- } catch (error) {
2506
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2507
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2508
- }
2509
- }
2510
- /**
2511
- * Execute a single frame across all roots.
2512
- * Order: globalBefore → each root's jobs → globalAfter
2513
- * @param {number} timestamp - RAF timestamp in milliseconds
2514
- * @returns {void}
2515
- * @private
2516
- */
2517
- executeFrame(timestamp) {
2518
- const deltaMs = this.loopState.lastTime !== null ? timestamp - this.loopState.lastTime : 0;
2519
- const delta = deltaMs / 1e3;
2520
- this.loopState.lastTime = timestamp;
2521
- this.loopState.frameCount++;
2522
- this.loopState.elapsedTime += deltaMs;
2523
- this.runGlobalJobs(this.globalBeforeJobs, timestamp);
2524
- for (const root of this.roots.values()) {
2525
- this.tickRoot(root, timestamp, delta);
2526
- }
2527
- this.runGlobalJobs(this.globalAfterJobs, timestamp);
2528
- }
2529
- /**
2530
- * Run all global jobs from a job map.
2531
- * Catches and logs errors without stopping execution.
2532
- * @param {Map<string, GlobalJob>} jobs - The global jobs map to execute
2533
- * @param {number} timestamp - RAF timestamp in milliseconds
2534
- * @returns {void}
2535
- * @private
2536
- */
2537
- runGlobalJobs(jobs, timestamp) {
2538
- for (const job of jobs.values()) {
2539
- try {
2540
- job.callback(timestamp);
2541
- } catch (error) {
2542
- console.error(`[Scheduler] Error in global job "${job.id}":`, error);
2543
- }
2544
- }
2545
- }
2546
- /**
2547
- * Execute all jobs for a single root in sorted order.
2548
- * Rebuilds sorted job list if needed, then dispatches each job.
2549
- * Errors are caught and propagated via triggerError.
2550
- * @param {RootEntry} root - The root entry to tick
2551
- * @param {number} timestamp - RAF timestamp in milliseconds
2552
- * @param {number} delta - Time since last frame in seconds
2553
- * @returns {void}
2554
- * @private
2555
- */
2556
- tickRoot(root, timestamp, delta) {
2557
- if (root.needsRebuild) {
2558
- root.sortedJobs = rebuildSortedJobs(root.jobs, this.phaseGraph);
2559
- root.needsRebuild = false;
2560
- }
2561
- const providedState = root.getState?.() ?? {};
2562
- const frameState = {
2563
- ...providedState,
2564
- time: timestamp,
2565
- delta,
2566
- elapsed: this.loopState.elapsedTime / 1e3,
2567
- // Convert ms to seconds
2568
- frame: this.loopState.frameCount
2569
- };
2570
- for (const job of root.sortedJobs) {
2571
- if (!shouldRun(job, timestamp)) continue;
2572
- try {
2573
- job.callback(frameState, delta);
2574
- } catch (error) {
2575
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2576
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2577
- }
2578
- }
2579
- }
2580
- //* Debug & Inspection Methods ================================
2581
- /**
2582
- * Get the total number of registered jobs across all roots.
2583
- * Includes both per-root jobs and global before/after jobs.
2584
- * @returns {number} Total job count
2585
- */
2586
- getJobCount() {
2587
- let count = 0;
2588
- for (const root of this.roots.values()) {
2589
- count += root.jobs.size;
2590
- }
2591
- return count + this.globalBeforeJobs.size + this.globalAfterJobs.size;
2592
- }
2593
- /**
2594
- * Get all registered job IDs across all roots.
2595
- * Includes both per-root jobs and global before/after jobs.
2596
- * @returns {string[]} Array of all job IDs
2597
- */
2598
- getJobIds() {
2599
- const ids = [];
2600
- for (const root of this.roots.values()) {
2601
- ids.push(...root.jobs.keys());
2602
- }
2603
- ids.push(...this.globalBeforeJobs.keys());
2604
- ids.push(...this.globalAfterJobs.keys());
2605
- return ids;
2606
- }
2607
- /**
2608
- * Get the number of registered roots (Canvas instances).
2609
- * @returns {number} Number of registered roots
2610
- */
2611
- getRootCount() {
2612
- return this.roots.size;
2613
- }
2614
- /**
2615
- * Check if any user (non-system) jobs are registered in a specific phase.
2616
- * Used by the default render job to know if a user has taken over rendering.
2617
- *
2618
- * @param phase The phase to check
2619
- * @param rootId Optional root ID to check (checks all roots if not provided)
2620
- * @returns true if any user jobs exist in the phase
2621
- */
2622
- hasUserJobsInPhase(phase, rootId) {
2623
- const rootsToCheck = rootId ? [this.roots.get(rootId)].filter(Boolean) : Array.from(this.roots.values());
2624
- return rootsToCheck.some((root) => {
2625
- if (!root) return false;
2626
- for (const job of root.jobs.values()) {
2627
- if (job.phase === phase && !job.system && job.enabled) return true;
2628
- }
2629
- return false;
2630
- });
2631
- }
2632
- //* Utility Methods ================================
2633
- /**
2634
- * Generate a unique root ID for automatic root registration.
2635
- * @returns {string} A unique root ID in the format 'root_N'
2636
- */
2637
- generateRootId() {
2638
- return `root_${this.nextRootIndex++}`;
2639
- }
2640
- /**
2641
- * Generate a unique job ID.
2642
- * @returns {string} A unique job ID in the format 'job_N'
2643
- * @private
2644
- */
2645
- generateJobId() {
2646
- return `job_${this.nextJobIndex}`;
2647
- }
2648
- /**
2649
- * Normalize before/after constraints to a Set.
2650
- * Handles undefined, single string, or array inputs.
2651
- * @param {string | string[] | undefined} value - The constraint value(s)
2652
- * @returns {Set<string>} Normalized Set of constraint strings
2653
- * @private
2654
- */
2655
- normalizeConstraints(value) {
2656
- if (!value) return /* @__PURE__ */ new Set();
2657
- if (Array.isArray(value)) return new Set(value);
2658
- return /* @__PURE__ */ new Set([value]);
2659
- }
2660
- };
2661
- //* Static State & Methods (Singleton Usage) ================================
2662
- //* Cross-Bundle Singleton Key ==============================
2663
- // Use Symbol.for() to ensure scheduler is shared across bundle boundaries
2664
- // This prevents issues when mixing imports from @react-three/fiber and @react-three/fiber/webgpu
2665
- __publicField$1(_Scheduler, "INSTANCE_KEY", Symbol.for("@react-three/fiber.scheduler"));
2666
- let Scheduler = _Scheduler;
2667
- const getScheduler = () => Scheduler.get();
2668
- if (hmrData) {
2669
- hmrData.accept?.();
1672
+ const INTERNAL_LIB_MARKERS = ["zustand", "setState", "Object.assign"];
1673
+ function isInternalRendererAccess(stack, callerDepth = 2) {
1674
+ if (!stack) return false;
1675
+ const caller = stack.split("\n")[callerDepth] ?? "";
1676
+ return INTERNAL_LIB_MARKERS.some((m) => caller.includes(m));
2670
1677
  }
2671
1678
 
2672
1679
  const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
@@ -2801,6 +1808,7 @@ const createStore = (invalidate, advance) => {
2801
1808
  }),
2802
1809
  setFrameloop: (frameloop = "always") => {
2803
1810
  set(() => ({ frameloop }));
1811
+ getScheduler().frameloop = frameloop;
2804
1812
  },
2805
1813
  setError: (error) => set(() => ({ error })),
2806
1814
  error: null,
@@ -2810,6 +1818,7 @@ const createStore = (invalidate, advance) => {
2810
1818
  buffers: {},
2811
1819
  gpuStorage: {},
2812
1820
  textures: /* @__PURE__ */ new Map(),
1821
+ _textureRefs: /* @__PURE__ */ new Map(),
2813
1822
  renderPipeline: null,
2814
1823
  passes: {},
2815
1824
  _hmrVersion: 0,
@@ -2867,8 +1876,7 @@ const createStore = (invalidate, advance) => {
2867
1876
  const currentState = rootStore.getState();
2868
1877
  if (!currentState.isLegacy && currentState.internal.actualRenderer) {
2869
1878
  const stack = new Error().stack || "";
2870
- const isInternalAccess = stack.includes("zustand") || stack.includes("setState") || stack.includes("Object.assign") || stack.includes("react-three-fiber/packages/fiber/src/core");
2871
- if (!isInternalAccess) {
1879
+ if (!isInternalRendererAccess(stack)) {
2872
1880
  const cleanedStack = stack.split("\n").slice(2).join("\n") || "Stack trace unavailable";
2873
1881
  notifyDepreciated({
2874
1882
  heading: "Accessing state.gl in WebGPU mode",
@@ -2981,19 +1989,25 @@ function loadingFn(extensions, onProgress) {
2981
1989
  );
2982
1990
  };
2983
1991
  }
2984
- function useLoader(loader, input, extensions, onProgress) {
2985
- const keys = Array.isArray(input) ? input : [input];
1992
+ function useLoader(loader, input, extensions, onProgress, cacheKey) {
1993
+ const inputs = Array.isArray(input) ? input : [input];
1994
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2986
1995
  const fn = loadingFn(extensions, onProgress);
2987
- const results = keys.map((key) => suspend(fn, [loader, key], { equal: is.equ }));
1996
+ const results = cacheKeys.map(
1997
+ (key, index) => suspend(() => fn(loader, inputs[index]), [loader, key], { equal: is.equ })
1998
+ );
2988
1999
  return Array.isArray(input) ? results : results[0];
2989
2000
  }
2990
- useLoader.preload = function(loader, input, extensions, onProgress) {
2991
- const keys = Array.isArray(input) ? input : [input];
2992
- keys.forEach((key) => preload(loadingFn(extensions, onProgress), [loader, key]));
2001
+ useLoader.preload = function(loader, input, extensions, onProgress, cacheKey) {
2002
+ const inputs = Array.isArray(input) ? input : [input];
2003
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2004
+ cacheKeys.forEach(
2005
+ (key, index) => preload(() => loadingFn(extensions, onProgress)(loader, inputs[index]), [loader, key])
2006
+ );
2993
2007
  };
2994
- useLoader.clear = function(loader, input) {
2995
- const keys = Array.isArray(input) ? input : [input];
2996
- keys.forEach((key) => clear([loader, key]));
2008
+ useLoader.clear = function(loader, input, cacheKey) {
2009
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2010
+ cacheKeys.forEach((key) => clear([loader, key]));
2997
2011
  };
2998
2012
  useLoader.loader = getLoader;
2999
2013
 
@@ -3069,20 +2083,14 @@ function useFrame(callback, priorityOrOptions) {
3069
2083
  }
3070
2084
  };
3071
2085
  } else {
3072
- const registerOutside = () => {
3073
- return scheduler.register((state, delta) => callbackRef.current?.(state, delta), { id, ...options });
3074
- };
3075
- if (scheduler.independent || scheduler.isReady) {
3076
- return registerOutside();
3077
- }
3078
- let unregisterJob = null;
3079
- const unsubReady = scheduler.onRootReady(() => {
3080
- unregisterJob = registerOutside();
3081
- });
3082
- return () => {
3083
- unsubReady();
3084
- unregisterJob?.();
3085
- };
2086
+ return scheduler.register(
2087
+ (state, delta) => {
2088
+ const frameState = state;
2089
+ if (!frameState.renderer) return;
2090
+ callbackRef.current?.(frameState, delta);
2091
+ },
2092
+ { id, ...options }
2093
+ );
3086
2094
  }
3087
2095
  }, [store, scheduler, id, optionsKey, isLegacyPriority, isInsideCanvas]);
3088
2096
  const isPaused = React.useSyncExternalStore(
@@ -3173,18 +2181,18 @@ function buildFromCache(input, textureCache) {
3173
2181
  function useTexture(input, optionsOrOnLoad) {
3174
2182
  const renderer = useThree((state) => state.internal.actualRenderer);
3175
2183
  const store = useStore();
3176
- const textureCache = useThree((state) => state.textures);
3177
2184
  const options = typeof optionsOrOnLoad === "function" ? { onLoad: optionsOrOnLoad } : optionsOrOnLoad ?? {};
3178
- const { onLoad, cache = false } = options;
2185
+ const { onLoad, cache = true } = options;
3179
2186
  const onLoadRef = useRef(onLoad);
3180
2187
  onLoadRef.current = onLoad;
3181
2188
  const onLoadCalledForRef = useRef(null);
3182
2189
  const urls = useMemo(() => getUrls(input), [input]);
3183
2190
  const cachedResult = useMemo(() => {
3184
2191
  if (!cache) return null;
3185
- if (!allUrlsCached(urls, textureCache)) return null;
3186
- return buildFromCache(input, textureCache);
3187
- }, [cache, urls, textureCache, input]);
2192
+ const textures = store.getState().textures;
2193
+ if (!allUrlsCached(urls, textures)) return null;
2194
+ return buildFromCache(input, textures);
2195
+ }, [cache, urls, input, store]);
3188
2196
  const loadedTextures = useLoader(
3189
2197
  TextureLoader,
3190
2198
  IsObject(input) ? Object.values(input) : input
@@ -3228,8 +2236,6 @@ function useTexture(input, optionsOrOnLoad) {
3228
2236
  }, [input, loadedTextures, cachedResult]);
3229
2237
  useEffect(() => {
3230
2238
  if (!cache) return;
3231
- if (cachedResult) return;
3232
- const set = store.setState;
3233
2239
  const urlTextureMap = [];
3234
2240
  if (typeof input === "string") {
3235
2241
  urlTextureMap.push([input, mappedTextures]);
@@ -3243,18 +2249,32 @@ function useTexture(input, optionsOrOnLoad) {
3243
2249
  urlTextureMap.push([url, textureRecord[key]]);
3244
2250
  }
3245
2251
  }
3246
- set((state) => {
3247
- const newMap = new Map(state.textures);
3248
- let changed = false;
2252
+ store.setState((state) => {
2253
+ const refs = new Map(state._textureRefs);
2254
+ let textures = state.textures;
2255
+ let added = false;
3249
2256
  for (const [url, texture] of urlTextureMap) {
3250
- if (!newMap.has(url)) {
3251
- newMap.set(url, texture);
3252
- changed = true;
2257
+ if (!textures.has(url)) {
2258
+ if (!added) {
2259
+ textures = new Map(textures);
2260
+ added = true;
2261
+ }
2262
+ textures.set(url, texture);
3253
2263
  }
2264
+ refs.set(url, (refs.get(url) ?? 0) + 1);
3254
2265
  }
3255
- return changed ? { textures: newMap } : state;
2266
+ return added ? { textures, _textureRefs: refs } : { _textureRefs: refs };
3256
2267
  });
3257
- }, [cache, input, mappedTextures, store, cachedResult]);
2268
+ return () => store.setState((state) => {
2269
+ const refs = new Map(state._textureRefs);
2270
+ for (const [url] of urlTextureMap) {
2271
+ const next = (refs.get(url) ?? 0) - 1;
2272
+ if (next <= 0) refs.delete(url);
2273
+ else refs.set(url, next);
2274
+ }
2275
+ return { _textureRefs: refs };
2276
+ });
2277
+ }, [cache, input, mappedTextures, store]);
3258
2278
  return mappedTextures;
3259
2279
  }
3260
2280
  useTexture.preload = (url) => useLoader.preload(TextureLoader, url);
@@ -3270,96 +2290,63 @@ const Texture = ({
3270
2290
  return /* @__PURE__ */ jsx(Fragment, { children: children?.(ret) });
3271
2291
  };
3272
2292
 
3273
- function getTextureValue(entry) {
3274
- if (entry instanceof Texture$1) return entry;
3275
- if (entry && typeof entry === "object" && "value" in entry && entry.value instanceof Texture$1) {
3276
- return entry.value;
3277
- }
3278
- return null;
3279
- }
3280
- function useTextures() {
2293
+ function useTextures(selector) {
3281
2294
  const store = useStore();
3282
- return useMemo(() => {
3283
- const set = store.setState;
2295
+ const registry = useMemo(() => {
3284
2296
  const getState = store.getState;
3285
- const add = (key, value) => {
3286
- set((state) => {
3287
- const newMap = new Map(state.textures);
3288
- newMap.set(key, value);
3289
- return { textures: newMap };
3290
- });
3291
- };
3292
- const addMultiple = (items) => {
3293
- set((state) => {
3294
- const newMap = new Map(state.textures);
3295
- const entries = items instanceof Map ? items.entries() : Object.entries(items);
3296
- for (const [key, value] of entries) {
3297
- newMap.set(key, value);
3298
- }
3299
- return { textures: newMap };
3300
- });
3301
- };
3302
- const remove = (key) => {
3303
- set((state) => {
3304
- const newMap = new Map(state.textures);
3305
- newMap.delete(key);
3306
- return { textures: newMap };
3307
- });
3308
- };
3309
- const removeMultiple = (keys) => {
3310
- set((state) => {
3311
- const newMap = new Map(state.textures);
3312
- for (const key of keys) newMap.delete(key);
3313
- return { textures: newMap };
3314
- });
3315
- };
3316
- const dispose = (key) => {
3317
- const entry = getState().textures.get(key);
3318
- if (entry) {
3319
- const tex = getTextureValue(entry);
3320
- tex?.dispose();
3321
- }
3322
- remove(key);
3323
- };
3324
- const disposeMultiple = (keys) => {
3325
- const textures = getState().textures;
3326
- for (const key of keys) {
3327
- const entry = textures.get(key);
3328
- if (entry) {
3329
- const tex = getTextureValue(entry);
3330
- tex?.dispose();
3331
- }
3332
- }
3333
- removeMultiple(keys);
3334
- };
3335
- const disposeAll = () => {
3336
- const textures = getState().textures;
3337
- for (const entry of textures.values()) {
3338
- const tex = getTextureValue(entry);
3339
- tex?.dispose();
3340
- }
3341
- set({ textures: /* @__PURE__ */ new Map() });
3342
- };
2297
+ const setState = store.setState;
2298
+ const getOne = (key) => getState().textures.get(key);
3343
2299
  return {
3344
- // Getter for the textures Map (reactive via getState)
3345
- get textures() {
2300
+ get all() {
3346
2301
  return getState().textures;
3347
2302
  },
3348
- // Read
3349
- get: (key) => getState().textures.get(key),
2303
+ get(input) {
2304
+ if (typeof input === "string") return getOne(input);
2305
+ if (Array.isArray(input)) return input.map(getOne);
2306
+ const out = {};
2307
+ for (const name in input) out[name] = getOne(input[name]);
2308
+ return out;
2309
+ },
3350
2310
  has: (key) => getState().textures.has(key),
3351
- // Write
3352
- add,
3353
- addMultiple,
3354
- // Remove (cache only)
3355
- remove,
3356
- removeMultiple,
3357
- // Dispose (GPU + cache)
3358
- dispose,
3359
- disposeMultiple,
3360
- disposeAll
2311
+ add(keyOrRecord, texture) {
2312
+ setState((state) => {
2313
+ const textures = new Map(state.textures);
2314
+ if (typeof keyOrRecord === "string") {
2315
+ textures.set(keyOrRecord, texture);
2316
+ } else {
2317
+ for (const key in keyOrRecord) textures.set(key, keyOrRecord[key]);
2318
+ }
2319
+ return { textures };
2320
+ });
2321
+ },
2322
+ dispose(key, options) {
2323
+ const state = getState();
2324
+ const refs = state._textureRefs.get(key) ?? 0;
2325
+ if (refs > 0 && !options?.force) {
2326
+ console.warn(
2327
+ `[useTextures] "${key}" still has ${refs} active reference(s); skipping dispose. Pass { force: true } to override.`
2328
+ );
2329
+ return false;
2330
+ }
2331
+ state.textures.get(key)?.dispose();
2332
+ setState((s) => {
2333
+ const textures = new Map(s.textures);
2334
+ textures.delete(key);
2335
+ const nextRefs = new Map(s._textureRefs);
2336
+ nextRefs.delete(key);
2337
+ return { textures, _textureRefs: nextRefs };
2338
+ });
2339
+ return true;
2340
+ },
2341
+ disposeAll() {
2342
+ for (const texture of getState().textures.values()) texture.dispose();
2343
+ setState({ textures: /* @__PURE__ */ new Map(), _textureRefs: /* @__PURE__ */ new Map() });
2344
+ }
3361
2345
  };
3362
2346
  }, [store]);
2347
+ const subscribe = selector ? () => selector(registry) : (state) => state.textures;
2348
+ const selected = useThree(subscribe);
2349
+ return selector ? selected : registry;
3363
2350
  }
3364
2351
 
3365
2352
  function useRenderTarget(widthOrOptions, heightOrOptions, options) {
@@ -3440,7 +2427,7 @@ function advance(timestamp) {
3440
2427
  getScheduler().step(timestamp);
3441
2428
  }
3442
2429
 
3443
- const version = "10.0.0-alpha.2";
2430
+ const version = "10.0.0-alpha.3";
3444
2431
  const packageData = {
3445
2432
  version: version};
3446
2433
 
@@ -14879,6 +13866,7 @@ function swapInstances() {
14879
13866
  }
14880
13867
  }
14881
13868
  if (instance.isHidden) unhideInstance(instance);
13869
+ if (isObject3D(instance.object)) removeInteractivity(findInitialRoot(instance), instance.object);
14882
13870
  if (instance.object.__r3f) delete instance.object.__r3f;
14883
13871
  if (instance.type !== "primitive") disposeOnIdle(instance.object);
14884
13872
  }
@@ -14891,6 +13879,8 @@ function swapInstances() {
14891
13879
  instance.object.__r3f = instance;
14892
13880
  setFiberRef(fiber, instance.object);
14893
13881
  delete instance.appliedOnce;
13882
+ instance.eventCount = 0;
13883
+ instance.handlers = {};
14894
13884
  applyProps(instance.object, instance.props);
14895
13885
  if (instance.props.attach) {
14896
13886
  attach(parent, instance);
@@ -15106,11 +14096,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
15106
14096
  cloneMutableTextInstance(textInstance) {
15107
14097
  return textInstance;
15108
14098
  },
14099
+ // React 19.2 added these for root-level view transitions. They only run for hosts that opt into
14100
+ // view transitions by returning a container from cloneRootViewTransitionContainer; R3F renders
14101
+ // into a WebGL/WebGPU canvas, where cloning the root has no meaning, so we never opt in and
14102
+ // React never calls them. They stay as no-ops rather than throws: the host config is shared by
14103
+ // every root, and a throw here would turn a React-internal probe into a hard crash for users.
14104
+ // Guarded by a test asserting a full render + unmount never reaches them.
15109
14105
  cloneRootViewTransitionContainer(_rootContainer) {
15110
- throw new Error("Not implemented.");
15111
14106
  },
15112
14107
  removeRootViewTransitionClone(_rootContainer, _clone) {
15113
- throw new Error("Not implemented.");
15114
14108
  },
15115
14109
  // https://github.com/facebook/react/pull/32465
15116
14110
  createFragmentInstance: (_fiber) => null,
@@ -15195,6 +14189,7 @@ function createRoot(canvas) {
15195
14189
  const lastConfiguredProps = {};
15196
14190
  let configured = false;
15197
14191
  let pending = null;
14192
+ let rendererSetup = null;
15198
14193
  return {
15199
14194
  async configure(props = {}) {
15200
14195
  let resolve;
@@ -15225,7 +14220,7 @@ function createRoot(canvas) {
15225
14220
  forceEven
15226
14221
  } = props;
15227
14222
  const textureColorSpace = is.obj(glConfig) && !is.fun(glConfig) && !isRenderer(glConfig) && glConfig.textureColorSpace || is.obj(rendererConfig) && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && rendererConfig.textureColorSpace || SRGBColorSpace;
15228
- const state = store.getState();
14223
+ let state = store.getState();
15229
14224
  const defaultGPUProps = {
15230
14225
  canvas,
15231
14226
  antialias: true
@@ -15239,52 +14234,64 @@ function createRoot(canvas) {
15239
14234
  throw new Error("Cannot use both gl and renderer props at the same time");
15240
14235
  }
15241
14236
  let renderer = state.internal.actualRenderer;
15242
- if (primaryCanvas && !state.internal.actualRenderer) {
15243
- const primary = await waitForPrimary(primaryCanvas);
15244
- renderer = primary.renderer;
15245
- state.internal.actualRenderer = renderer;
15246
- const canvasTarget = new CanvasTarget(canvas);
15247
- primary.store.setState((prev) => ({
15248
- internal: { ...prev.internal, isMultiCanvas: true }
15249
- }));
15250
- state.set((prev) => ({
15251
- webGPUSupported: primary.store.getState().webGPUSupported,
15252
- renderer,
15253
- primaryStore: primary.store,
15254
- internal: {
15255
- ...prev.internal,
15256
- canvasTarget,
15257
- isMultiCanvas: true,
15258
- isSecondary: true,
15259
- targetId: primaryCanvas
15260
- }
15261
- }));
15262
- } else if (!state.internal.actualRenderer) {
15263
- renderer = await resolveRenderer(rendererConfig, defaultGPUProps, WebGPURenderer);
15264
- if (!renderer.hasInitialized?.()) {
15265
- const size2 = computeInitialSize(canvas, propsSize);
15266
- if (size2.width > 0 && size2.height > 0) {
15267
- const pixelRatio = calculateDpr(dpr);
15268
- canvas.width = size2.width * pixelRatio;
15269
- canvas.height = size2.height * pixelRatio;
15270
- }
15271
- await renderer.init();
15272
- }
15273
- const backend = renderer.backend;
15274
- const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
15275
- state.internal.actualRenderer = renderer;
15276
- state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
15277
- if (canvasId && !state.internal.isSecondary) {
15278
- const canvasTarget = new CanvasTarget(canvas);
15279
- const unregisterPrimary = registerPrimary(canvasId, renderer, store);
15280
- state.set((prev) => ({
15281
- internal: {
15282
- ...prev.internal,
15283
- canvasTarget,
15284
- unregisterPrimary
14237
+ if (!state.internal.actualRenderer) {
14238
+ if (!rendererSetup) {
14239
+ rendererSetup = (async () => {
14240
+ if (primaryCanvas) {
14241
+ const primary = await waitForPrimary(primaryCanvas);
14242
+ renderer = primary.renderer;
14243
+ state.internal.actualRenderer = renderer;
14244
+ const canvasTarget = new CanvasTarget(canvas);
14245
+ primary.store.setState((prev) => ({
14246
+ internal: { ...prev.internal, isMultiCanvas: true }
14247
+ }));
14248
+ state.set((prev) => ({
14249
+ webGPUSupported: primary.store.getState().webGPUSupported,
14250
+ renderer,
14251
+ primaryStore: primary.store,
14252
+ internal: {
14253
+ ...prev.internal,
14254
+ canvasTarget,
14255
+ isMultiCanvas: true,
14256
+ isSecondary: true,
14257
+ targetId: primaryCanvas
14258
+ }
14259
+ }));
14260
+ } else {
14261
+ renderer = await resolveRenderer(rendererConfig, defaultGPUProps, WebGPURenderer);
14262
+ if (!renderer.hasInitialized?.()) {
14263
+ const size2 = computeInitialSize(canvas, propsSize);
14264
+ if (size2.width > 0 && size2.height > 0) {
14265
+ const pixelRatio = calculateDpr(dpr);
14266
+ canvas.width = size2.width * pixelRatio;
14267
+ canvas.height = size2.height * pixelRatio;
14268
+ }
14269
+ await renderer.init();
14270
+ }
14271
+ const backend = renderer.backend;
14272
+ const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
14273
+ state.internal.actualRenderer = renderer;
14274
+ state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
14275
+ if (canvasId && !state.internal.isSecondary) {
14276
+ const canvasTarget = new CanvasTarget(canvas);
14277
+ const unregisterPrimary = registerPrimary(canvasId, renderer, store);
14278
+ state.set((prev) => ({
14279
+ internal: {
14280
+ ...prev.internal,
14281
+ canvasTarget,
14282
+ unregisterPrimary
14283
+ }
14284
+ }));
14285
+ }
15285
14286
  }
15286
- }));
14287
+ })().catch((err) => {
14288
+ rendererSetup = null;
14289
+ throw err;
14290
+ });
15287
14291
  }
14292
+ await rendererSetup;
14293
+ state = store.getState();
14294
+ renderer = state.internal.actualRenderer;
15288
14295
  }
15289
14296
  let raycaster = state.raycaster;
15290
14297
  if (!raycaster) state.set({ raycaster: raycaster = new Raycaster() });
@@ -15509,7 +14516,7 @@ function createRoot(canvas) {
15509
14516
  {
15510
14517
  id: `${newRootId}_frustum`,
15511
14518
  rootId: newRootId,
15512
- phase: "preRender",
14519
+ before: "render",
15513
14520
  system: true
15514
14521
  }
15515
14522
  );
@@ -15521,7 +14528,7 @@ function createRoot(canvas) {
15521
14528
  {
15522
14529
  id: `${newRootId}_visibility`,
15523
14530
  rootId: newRootId,
15524
- phase: "preRender",
14531
+ before: "render",
15525
14532
  system: true,
15526
14533
  after: `${newRootId}_frustum`
15527
14534
  }
@@ -15634,7 +14641,8 @@ function unmountComponentAtNode(canvas, callback) {
15634
14641
  dispose(state.scene);
15635
14642
  _roots.delete(canvas);
15636
14643
  if (callback) callback(canvas);
15637
- } catch {
14644
+ } catch (error) {
14645
+ console.warn("[R3F] Error while unmounting root; teardown may be incomplete:", error);
15638
14646
  }
15639
14647
  }, 500);
15640
14648
  }
@@ -15697,6 +14705,7 @@ function PortalInner({ state = {}, children, container }) {
15697
14705
  viewport = rootState.viewport.getCurrentViewport(camera, new Vector3(), resolvedSize);
15698
14706
  if (camera !== rootState.camera) updateCamera(camera, resolvedSize);
15699
14707
  }
14708
+ const set = injectState.set;
15700
14709
  return {
15701
14710
  // The intersect consists of the previous root state
15702
14711
  ...rootState,
@@ -15715,7 +14724,7 @@ function PortalInner({ state = {}, children, container }) {
15715
14724
  size: resolvedSize,
15716
14725
  viewport: { ...rootState.viewport, ...viewport },
15717
14726
  // Layers are allowed to override events
15718
- setEvents: (events2) => injectState.set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14727
+ setEvents: (events2) => set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
15719
14728
  // Container for child attachment - the portalScene (injected or container itself)
15720
14729
  internal: { ...rootState.internal, ...injectState.internal, container: portalScene }
15721
14730
  };
@@ -15744,6 +14753,59 @@ function flushSync(fn) {
15744
14753
  return reconciler.flushSyncFromReconciler(fn);
15745
14754
  }
15746
14755
 
14756
+ function parseBackground(background) {
14757
+ if (!background) return null;
14758
+ if (typeof background === "object" && !background.isColor) {
14759
+ const { backgroundMap, envMap, files, preset, ...rest } = background;
14760
+ return {
14761
+ ...rest,
14762
+ preset,
14763
+ files: envMap || files,
14764
+ backgroundFiles: backgroundMap,
14765
+ background: true
14766
+ };
14767
+ }
14768
+ if (typeof background === "number") {
14769
+ return { color: background, background: true };
14770
+ }
14771
+ if (typeof background === "string") {
14772
+ if (background in presetsObj) {
14773
+ return { preset: background, background: true };
14774
+ }
14775
+ if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
14776
+ return { files: background, background: true };
14777
+ }
14778
+ return { color: background, background: true };
14779
+ }
14780
+ if (background.isColor) {
14781
+ return { color: background, background: true };
14782
+ }
14783
+ return null;
14784
+ }
14785
+
14786
+ function parseRendererConfig(rendererProp) {
14787
+ const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
14788
+ if (isRendererConfig) {
14789
+ const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
14790
+ return {
14791
+ primaryCanvas: pc,
14792
+ scheduler: sc,
14793
+ renderer: Object.keys(rest).length > 0 ? rest : rendererProp
14794
+ };
14795
+ }
14796
+ return { primaryCanvas: void 0, scheduler: void 0, renderer: rendererProp };
14797
+ }
14798
+
14799
+ function clearHmrCaches(store) {
14800
+ store.setState((state) => ({
14801
+ nodes: {},
14802
+ uniforms: {},
14803
+ buffers: {},
14804
+ gpuStorage: {},
14805
+ _hmrVersion: state._hmrVersion + 1
14806
+ }));
14807
+ }
14808
+
15747
14809
  function CanvasImpl({
15748
14810
  ref,
15749
14811
  children,
@@ -15764,6 +14826,8 @@ function CanvasImpl({
15764
14826
  raycaster,
15765
14827
  camera,
15766
14828
  scene,
14829
+ autoUpdateFrustum,
14830
+ occlusion,
15767
14831
  onPointerMissed,
15768
14832
  onDragOverMissed,
15769
14833
  onDropMissed,
@@ -15775,49 +14839,10 @@ function CanvasImpl({
15775
14839
  forceEven,
15776
14840
  ...props
15777
14841
  }) {
15778
- const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
15779
- let primaryCanvas;
15780
- let scheduler;
15781
- let renderer;
15782
- if (isRendererConfig) {
15783
- const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
15784
- primaryCanvas = pc;
15785
- scheduler = sc;
15786
- renderer = Object.keys(rest).length > 0 ? rest : rendererProp;
15787
- } else {
15788
- renderer = rendererProp;
15789
- }
14842
+ const { primaryCanvas, scheduler, renderer } = parseRendererConfig(rendererProp);
15790
14843
  React.useMemo(() => extend(THREE), []);
15791
14844
  const Bridge = useBridge();
15792
- const backgroundProps = React.useMemo(() => {
15793
- if (!background) return null;
15794
- if (typeof background === "object" && !background.isColor) {
15795
- const { backgroundMap, envMap, files, preset, ...rest } = background;
15796
- return {
15797
- ...rest,
15798
- preset,
15799
- files: envMap || files,
15800
- backgroundFiles: backgroundMap,
15801
- background: true
15802
- };
15803
- }
15804
- if (typeof background === "number") {
15805
- return { color: background, background: true };
15806
- }
15807
- if (typeof background === "string") {
15808
- if (background in presetsObj) {
15809
- return { preset: background, background: true };
15810
- }
15811
- if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
15812
- return { files: background, background: true };
15813
- }
15814
- return { color: background, background: true };
15815
- }
15816
- if (background.isColor) {
15817
- return { color: background, background: true };
15818
- }
15819
- return null;
15820
- }, [background]);
14845
+ const backgroundProps = React.useMemo(() => parseBackground(background), [background]);
15821
14846
  const hasInitialSizeRef = React.useRef(false);
15822
14847
  const measureConfig = React.useMemo(() => {
15823
14848
  if (!hasInitialSizeRef.current) {
@@ -15859,6 +14884,7 @@ function CanvasImpl({
15859
14884
  const handleDropMissed = useMutableCallback(onDropMissed);
15860
14885
  const [block, setBlock] = React.useState(false);
15861
14886
  const [error, setError] = React.useState(false);
14887
+ const [fallbackVisible, setFallbackVisible] = React.useState(false);
15862
14888
  if (block) throw block;
15863
14889
  if (error) throw error;
15864
14890
  const root = React.useRef(null);
@@ -15866,6 +14892,7 @@ function CanvasImpl({
15866
14892
  const unsubscribeErrorRef = React.useRef(null);
15867
14893
  useIsomorphicLayoutEffect(() => {
15868
14894
  effectActiveRef.current = true;
14895
+ if (fallbackVisible) return;
15869
14896
  const canvas = canvasRef.current;
15870
14897
  if (effectiveSize.width > 0 && effectiveSize.height > 0 && canvas) {
15871
14898
  if (!root.current) {
@@ -15886,7 +14913,7 @@ function CanvasImpl({
15886
14913
  }
15887
14914
  async function run() {
15888
14915
  if (!effectActiveRef.current || !root.current) return;
15889
- await root.current.configure({
14916
+ const configured = await root.current.configure({
15890
14917
  id,
15891
14918
  primaryCanvas,
15892
14919
  scheduler,
@@ -15901,6 +14928,8 @@ function CanvasImpl({
15901
14928
  performance,
15902
14929
  raycaster,
15903
14930
  camera,
14931
+ autoUpdateFrustum,
14932
+ occlusion,
15904
14933
  size: effectiveSize,
15905
14934
  // Store size props for reset functionality
15906
14935
  _sizeProps: width !== void 0 || height !== void 0 ? { width, height } : null,
@@ -15925,8 +14954,20 @@ function CanvasImpl({
15925
14954
  }
15926
14955
  onCreated?.(state);
15927
14956
  }
15928
- });
15929
- if (!effectActiveRef.current || !root.current) return;
14957
+ }).then(
14958
+ () => true,
14959
+ // Renderer setup failed (e.g. no WebGL/WebGPU support). The `fallback` prop lives
14960
+ // inside <canvas>, which browsers don't display, so surface it as visible DOM
14961
+ // instead; with no fallback, rethrow to an external error boundary. (#3757)
14962
+ (setupError) => {
14963
+ if (effectActiveRef.current) {
14964
+ if (fallback != null) setFallbackVisible(true);
14965
+ else setError(setupError);
14966
+ }
14967
+ return false;
14968
+ }
14969
+ );
14970
+ if (!configured || !effectActiveRef.current || !root.current) return;
15930
14971
  root.current.render(
15931
14972
  /* @__PURE__ */ jsx(Bridge, { children: /* @__PURE__ */ jsx(ErrorBoundary, { set: setError, children: /* @__PURE__ */ jsxs(React.Suspense, { fallback: /* @__PURE__ */ jsx(Block, { set: setBlock }), children: [
15932
14973
  backgroundProps && /* @__PURE__ */ jsx(Environment, { ...backgroundProps }),
@@ -15960,14 +15001,7 @@ function CanvasImpl({
15960
15001
  const handleHMR = () => {
15961
15002
  queueMicrotask(() => {
15962
15003
  const rootEntry = _roots.get(canvas);
15963
- if (rootEntry?.store) {
15964
- console.log("[R3F] HMR detected \u2014 rebuilding nodes/uniforms");
15965
- rootEntry.store.setState((state) => ({
15966
- nodes: {},
15967
- uniforms: {},
15968
- _hmrVersion: state._hmrVersion + 1
15969
- }));
15970
- }
15004
+ if (rootEntry?.store) clearHmrCaches(rootEntry.store);
15971
15005
  });
15972
15006
  };
15973
15007
  if (typeof import.meta !== "undefined" && import.meta.hot) {
@@ -15996,7 +15030,11 @@ function CanvasImpl({
15996
15030
  ...style
15997
15031
  },
15998
15032
  ...props,
15999
- children: /* @__PURE__ */ jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsx(
15033
+ children: fallbackVisible ? (
15034
+ // Renderer setup failed: render the fallback as visible DOM. Inside <canvas> (below)
15035
+ // it exists in the tree but browsers never paint it, which is the whole bug (#3757).
15036
+ fallback
15037
+ ) : /* @__PURE__ */ jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsx(
16000
15038
  "canvas",
16001
15039
  {
16002
15040
  ref: canvasRef,
@@ -16107,6 +15145,20 @@ function createLazyCreatorState(state) {
16107
15145
  });
16108
15146
  }
16109
15147
 
15148
+ function resolvePrimary(local) {
15149
+ return local.getState().primaryStore ?? local;
15150
+ }
15151
+ function usePrimaryStore() {
15152
+ const local = useStore();
15153
+ const primary = local.getState().primaryStore;
15154
+ return useMemo(() => primary ?? local, [primary, local]);
15155
+ }
15156
+ function usePrimaryThree(selector = (state) => state, equalityFn) {
15157
+ const local = useStore();
15158
+ const primary = resolvePrimary(local);
15159
+ return primary(selector, equalityFn);
15160
+ }
15161
+
16110
15162
  function addTexture(set, key, value) {
16111
15163
  set((state) => {
16112
15164
  const newMap = new Map(state.textures);
@@ -16212,7 +15264,7 @@ function useCompareMemoize(value, deep) {
16212
15264
 
16213
15265
  const isUniformNode$1 = (value) => value !== null && typeof value === "object" && "value" in value && "uuid" in value;
16214
15266
  function useUniforms(creatorOrScope, scope) {
16215
- const store = useStore();
15267
+ const store = usePrimaryStore();
16216
15268
  const removeUniforms2 = useCallback(
16217
15269
  (names, targetScope) => {
16218
15270
  const nameArray = Array.isArray(names) ? names : [names];
@@ -16282,8 +15334,8 @@ function useUniforms(creatorOrScope, scope) {
16282
15334
  }, [creatorOrScope, store]);
16283
15335
  const memoizedInput = useCompareMemoize(inputForMemoization);
16284
15336
  const isReader = memoizedInput === void 0 || typeof memoizedInput === "string";
16285
- const storeUniforms = useThree((s) => s.uniforms);
16286
- const hmrVersion = useThree((s) => s._hmrVersion);
15337
+ const storeUniforms = usePrimaryThree((s) => s.uniforms);
15338
+ const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
16287
15339
  const readerDep = isReader ? storeUniforms : null;
16288
15340
  const creatorDep = isReader ? null : hmrVersion;
16289
15341
  const uniforms = useMemo(() => {
@@ -16344,6 +15396,7 @@ function useUniforms(creatorOrScope, scope) {
16344
15396
  return { ...uniforms, removeUniforms: removeUniforms2, clearUniforms, rebuildUniforms };
16345
15397
  }
16346
15398
  function rebuildAllUniforms(store, scope) {
15399
+ store = store.getState().primaryStore ?? store;
16347
15400
  store.setState((state) => {
16348
15401
  let newUniforms = {};
16349
15402
  if (scope && scope !== "root") {
@@ -16419,6 +15472,7 @@ function isSameThreeType(a, b) {
16419
15472
  return obj_a.isColor && obj_b.isColor || obj_a.isMatrix3 && obj_b.isMatrix3 || obj_a.isMatrix4 && obj_b.isMatrix4 || obj_a.isEuler && obj_b.isEuler || obj_a.isQuaternion && obj_b.isQuaternion;
16420
15473
  }
16421
15474
 
15475
+ const uniformOf = uniform;
16422
15476
  const isUniformNode = (value) => value !== null && typeof value === "object" && "value" in value && "uuid" in value;
16423
15477
  const isTSLNode$1 = (value) => value !== null && typeof value === "object" && "uuid" in value && "nodeType" in value;
16424
15478
  function useUniform(name, value) {
@@ -16451,11 +15505,11 @@ function useUniform(name, value) {
16451
15505
  }
16452
15506
  let node;
16453
15507
  if (isTSLNode$1(value)) {
16454
- node = uniform(value);
15508
+ node = uniformOf(value);
16455
15509
  } else if (typeof value === "string") {
16456
15510
  node = uniform(new Color(value));
16457
15511
  } else {
16458
- node = uniform(value);
15512
+ node = uniformOf(value);
16459
15513
  }
16460
15514
  if (typeof node.setName === "function") {
16461
15515
  node.setName(name);
@@ -16472,7 +15526,7 @@ function useUniform(name, value) {
16472
15526
 
16473
15527
  const isTSLNode = (value) => value !== null && typeof value === "object" && ("uuid" in value || "nodeType" in value);
16474
15528
  function useNodes(creatorOrScope, scope) {
16475
- const store = useStore();
15529
+ const store = usePrimaryStore();
16476
15530
  const removeNodes2 = useCallback(
16477
15531
  (names, targetScope) => {
16478
15532
  const nameArray = Array.isArray(names) ? names : [names];
@@ -16529,8 +15583,8 @@ function useNodes(creatorOrScope, scope) {
16529
15583
  [store]
16530
15584
  );
16531
15585
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
16532
- const storeNodes = useThree((s) => s.nodes);
16533
- const hmrVersion = useThree((s) => s._hmrVersion);
15586
+ const storeNodes = usePrimaryThree((s) => s.nodes);
15587
+ const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
16534
15588
  const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
16535
15589
  const readerDep = isReader ? storeNodes : null;
16536
15590
  const creatorDep = isReader ? null : hmrVersion;
@@ -16589,6 +15643,7 @@ function useNodes(creatorOrScope, scope) {
16589
15643
  return { ...nodes, removeNodes: removeNodes2, clearNodes, rebuildNodes };
16590
15644
  }
16591
15645
  function rebuildAllNodes(store, scope) {
15646
+ store = store.getState().primaryStore ?? store;
16592
15647
  store.setState((state) => {
16593
15648
  let newNodes = state.nodes;
16594
15649
  if (scope && scope !== "root") {
@@ -16633,11 +15688,11 @@ function clearRootNodes(set) {
16633
15688
  });
16634
15689
  }
16635
15690
  function useLocalNodes(creator) {
16636
- const store = useStore();
16637
- const uniforms = useThree((s) => s.uniforms);
16638
- const nodes = useThree((s) => s.nodes);
16639
- const textures = useThree((s) => s.textures);
16640
- const hmrVersion = useThree((s) => s._hmrVersion);
15691
+ const store = usePrimaryStore();
15692
+ const uniforms = usePrimaryThree((s) => s.uniforms);
15693
+ const nodes = usePrimaryThree((s) => s.nodes);
15694
+ const textures = usePrimaryThree((s) => s.textures);
15695
+ const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
16641
15696
  return useMemo(() => {
16642
15697
  const wrappedState = createLazyCreatorState(store.getState());
16643
15698
  return creator(wrappedState);
@@ -16658,7 +15713,7 @@ const disposeBuffer = (buffer) => {
16658
15713
  }
16659
15714
  };
16660
15715
  function useBuffers(creatorOrScope, scope) {
16661
- const store = useStore();
15716
+ const store = usePrimaryStore();
16662
15717
  const removeBuffers = useCallback(
16663
15718
  (names, targetScope) => {
16664
15719
  const nameArray = Array.isArray(names) ? names : [names];
@@ -16729,8 +15784,8 @@ function useBuffers(creatorOrScope, scope) {
16729
15784
  [store, removeBuffers]
16730
15785
  );
16731
15786
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
16732
- const storeBuffers = useThree((s) => s.buffers);
16733
- const hmrVersion = useThree((s) => s._hmrVersion);
15787
+ const storeBuffers = usePrimaryThree((s) => s.buffers);
15788
+ const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
16734
15789
  const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
16735
15790
  const readerDep = isReader ? storeBuffers : null;
16736
15791
  const creatorDep = isReader ? null : hmrVersion;
@@ -16793,6 +15848,7 @@ function useBuffers(creatorOrScope, scope) {
16793
15848
  return { ...buffers, removeBuffers, clearBuffers, rebuildBuffers, disposeBuffers };
16794
15849
  }
16795
15850
  function rebuildAllBuffers(store, scope) {
15851
+ store = store.getState().primaryStore ?? store;
16796
15852
  store.setState((state) => {
16797
15853
  let newBuffers = state.buffers;
16798
15854
  if (scope && scope !== "root") {
@@ -16824,7 +15880,7 @@ const disposeStorage = (storage) => {
16824
15880
  }
16825
15881
  };
16826
15882
  function useGPUStorage(creatorOrScope, scope) {
16827
- const store = useStore();
15883
+ const store = usePrimaryStore();
16828
15884
  const removeStorage = useCallback(
16829
15885
  (names, targetScope) => {
16830
15886
  const nameArray = Array.isArray(names) ? names : [names];
@@ -16895,8 +15951,8 @@ function useGPUStorage(creatorOrScope, scope) {
16895
15951
  [store, removeStorage]
16896
15952
  );
16897
15953
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
16898
- const storeStorage = useThree((s) => s.gpuStorage);
16899
- const hmrVersion = useThree((s) => s._hmrVersion);
15954
+ const storeStorage = usePrimaryThree((s) => s.gpuStorage);
15955
+ const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
16900
15956
  const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
16901
15957
  const readerDep = isReader ? storeStorage : null;
16902
15958
  const creatorDep = isReader ? null : hmrVersion;
@@ -16971,6 +16027,7 @@ function useGPUStorage(creatorOrScope, scope) {
16971
16027
  };
16972
16028
  }
16973
16029
  function rebuildAllStorage(store, scope) {
16030
+ store = store.getState().primaryStore ?? store;
16974
16031
  store.setState((state) => {
16975
16032
  let newStorage = state.gpuStorage;
16976
16033
  if (scope && scope !== "root") {
@@ -17026,12 +16083,12 @@ function useRenderPipeline(mainCB, setupCB) {
17026
16083
  const state = store.getState();
17027
16084
  const set = store.setState;
17028
16085
  try {
17029
- let pp = state.renderPipeline;
16086
+ let pipeline = state.renderPipeline;
17030
16087
  let currentPasses = { ...state.passes };
17031
- let justCreatedPP = false;
17032
- if (!pp) {
17033
- pp = new PostProcessing(renderer);
17034
- justCreatedPP = true;
16088
+ let justCreatedPipeline = false;
16089
+ if (!pipeline) {
16090
+ pipeline = new RenderPipeline(renderer);
16091
+ justCreatedPipeline = true;
17035
16092
  }
17036
16093
  const cacheValid = scenePassCacheRef.current && scenePassCacheRef.current.sceneUuid === scene.uuid && scenePassCacheRef.current.cameraUuid === camera.uuid;
17037
16094
  let scenePass;
@@ -17042,9 +16099,9 @@ function useRenderPipeline(mainCB, setupCB) {
17042
16099
  scenePassCacheRef.current = { sceneUuid: scene.uuid, cameraUuid: camera.uuid, scenePass };
17043
16100
  }
17044
16101
  currentPasses.scenePass = scenePass;
17045
- if (!pp.outputNode || justCreatedPP) pp.outputNode = scenePass;
17046
- set({ renderPipeline: pp, passes: currentPasses });
17047
- const shouldRunCallbacks = justCreatedPP || !callbacksRanRef.current || !cacheValid;
16102
+ if (!pipeline.outputNode || justCreatedPipeline) pipeline.outputNode = scenePass;
16103
+ set({ renderPipeline: pipeline, passes: currentPasses });
16104
+ const shouldRunCallbacks = justCreatedPipeline || !callbacksRanRef.current || !cacheValid;
17048
16105
  if (shouldRunCallbacks) {
17049
16106
  if (setupCBRef.current) {
17050
16107
  const freshState = store.getState();
@@ -17065,7 +16122,7 @@ function useRenderPipeline(mainCB, setupCB) {
17065
16122
  callbacksRanRef.current = true;
17066
16123
  }
17067
16124
  } catch (error) {
17068
- console.error("[useRenderPipeline] Setup error:", error);
16125
+ console.warn("[useRenderPipeline] Setup failed; the render pipeline was not configured:", error);
17069
16126
  }
17070
16127
  }, [store, renderer, scene, camera, isLegacy, rebuildVersion]);
17071
16128
  const passes = useThree((s) => s.passes);
@@ -17083,4 +16140,4 @@ function useRenderPipeline(mainCB, setupCB) {
17083
16140
 
17084
16141
  extend(THREE);
17085
16142
 
17086
- export { Block, Canvas, Environment, EnvironmentCube, EnvironmentMap, EnvironmentPortal, ErrorBoundary, FROM_REF, IsObject, ONCE, Portal, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, REACT_INTERNAL_PROPS, RESERVED_PROPS, Scheduler, Texture, _roots, act, addAfterEffect, addEffect, addTail, advance, applyProps, attach, buildGraph, calculateDpr, clearNodeScope, clearRootNodes, clearRootUniforms, clearScope, context, createEvents, createPointerEvents, createPortal, createRoot, createScopedStore, createStore, createTextureOperations, detach, diffProps, dispose, createPointerEvents as events, extend, findInitialRoot, flushSync, fromRef, getInstanceProps, getPrimary, getPrimaryIds, getRootState, getScheduler, getUuidPrefix, hasConstructor, hasPrimary, invalidate, invalidateInstance, is, isColorRepresentation, isCopyable, isFromRef, isObject3D, isOnce, isOrthographicCamera, isRef, isRenderer, isTexture, isVectorLike, once, prepare, presetsObj, rebuildAllBuffers, rebuildAllNodes, rebuildAllStorage, rebuildAllUniforms, reconciler, registerPrimary, removeInteractivity, removeNodes, removeUniforms, resolve, unmountComponentAtNode, unregisterPrimary, updateCamera, updateFrustum, useBridge, useBuffers, useEnvironment, useFrame, useGPUStorage, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useLocalNodes, useMutableCallback, useNodes, useRenderPipeline, useRenderTarget, useStore, useTexture, useTextures, useThree, useUniform, useUniforms, waitForPrimary };
16143
+ 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, clearNodeScope, clearRootNodes, clearRootUniforms, clearScope, context, createEvents, createPointerEvents, createPortal, createRoot, createScopedStore, createStore, createTextureOperations, detach, diffProps, dispose, createPointerEvents as events, extend, findInitialRoot, flushSync, fromRef, getInstanceProps, getPrimary, getPrimaryIds, getRootState, getUuidPrefix, hasConstructor, hasPrimary, invalidate, invalidateInstance, is, isColorRepresentation, isCopyable, isFromRef, isObject3D, isOnce, isOrthographicCamera, isRef, isRenderer, isTexture, isVectorLike, once, prepare, presetsObj, rebuildAllBuffers, rebuildAllNodes, rebuildAllStorage, rebuildAllUniforms, reconciler, registerPrimary, removeInteractivity, removeNodes, removeUniforms, resolve, unmountComponentAtNode, unregisterPrimary, updateCamera, updateFrustum, useBridge, useBuffers, useEnvironment, useFrame, useGPUStorage, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useLocalNodes, useMutableCallback, useNodes, useRenderPipeline, useRenderTarget, useStore, useTexture, useTextures, useThree, useUniform, useUniforms, waitForPrimary };