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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -15,6 +15,7 @@ const UltraHDRLoader_js = require('three/examples/jsm/loaders/UltraHDRLoader.js'
15
15
  const gainmapJs = require('@monogrid/gainmap-js');
16
16
  const Tb = require('scheduler');
17
17
  const traditional = require('zustand/traditional');
18
+ const scheduler = require('@pmndrs/scheduler');
18
19
  const suspendReact = require('suspend-react');
19
20
 
20
21
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
@@ -55,10 +56,13 @@ const R3F_BUILD_WEBGPU = true;
55
56
 
56
57
  const THREE = /*#__PURE__*/_mergeNamespaces({
57
58
  __proto__: null,
59
+ CubeRenderTarget: webgpu.CubeRenderTarget,
60
+ CubeRenderTargetCompat: webgpu.CubeRenderTarget,
58
61
  Inspector: Inspector_js.Inspector,
59
62
  R3F_BUILD_LEGACY: R3F_BUILD_LEGACY,
60
63
  R3F_BUILD_WEBGPU: R3F_BUILD_WEBGPU,
61
64
  RenderTargetCompat: webgpu.RenderTarget,
65
+ WebGLCubeRenderTarget: three.WebGLCubeRenderTarget,
62
66
  WebGLRenderTarget: three.WebGLRenderTarget,
63
67
  WebGLRenderer: three.WebGLRenderer
64
68
  }, [webgpu__namespace]);
@@ -332,15 +336,16 @@ function EnvironmentPortal({
332
336
  preset = void 0,
333
337
  extensions
334
338
  }) {
335
- const gl = fiber.useThree((state) => state.gl);
339
+ const renderer = fiber.useThree((state) => state.renderer);
340
+ const isLegacy = fiber.useThree((state) => state.isLegacy);
336
341
  const defaultScene = fiber.useThree((state) => state.scene);
337
342
  const camera = React__namespace.useRef(null);
338
343
  const [virtualScene] = React__namespace.useState(() => new webgpu.Scene());
339
344
  const fbo = React__namespace.useMemo(() => {
340
- const fbo2 = new webgpu.WebGLCubeRenderTarget(resolution);
345
+ const fbo2 = isLegacy ? new three.WebGLCubeRenderTarget(resolution) : new webgpu.CubeRenderTarget(resolution);
341
346
  fbo2.texture.type = webgpu.HalfFloatType;
342
347
  return fbo2;
343
- }, [resolution]);
348
+ }, [resolution, isLegacy]);
344
349
  React__namespace.useEffect(() => {
345
350
  return () => {
346
351
  fbo.dispose();
@@ -348,10 +353,10 @@ function EnvironmentPortal({
348
353
  }, [fbo]);
349
354
  React__namespace.useLayoutEffect(() => {
350
355
  if (frames === 1) {
351
- const autoClear = gl.autoClear;
352
- gl.autoClear = true;
353
- camera.current.update(gl, virtualScene);
354
- gl.autoClear = autoClear;
356
+ const autoClear = renderer.autoClear;
357
+ renderer.autoClear = true;
358
+ camera.current.update(renderer, virtualScene);
359
+ renderer.autoClear = autoClear;
355
360
  }
356
361
  return setEnvProps(background, scene, defaultScene, fbo.texture, {
357
362
  backgroundBlurriness: blur ?? backgroundBlurriness,
@@ -368,7 +373,7 @@ function EnvironmentPortal({
368
373
  defaultScene,
369
374
  background,
370
375
  frames,
371
- gl,
376
+ renderer,
372
377
  blur,
373
378
  backgroundBlurriness,
374
379
  backgroundIntensity,
@@ -379,10 +384,10 @@ function EnvironmentPortal({
379
384
  let count = 1;
380
385
  fiber.useFrame(() => {
381
386
  if (frames === Infinity || count < frames) {
382
- const autoClear = gl.autoClear;
383
- gl.autoClear = true;
384
- camera.current.update(gl, virtualScene);
385
- gl.autoClear = autoClear;
387
+ const autoClear = renderer.autoClear;
388
+ renderer.autoClear = true;
389
+ camera.current.update(renderer, virtualScene);
390
+ renderer.autoClear = autoClear;
386
391
  count++;
387
392
  }
388
393
  });
@@ -446,10 +451,9 @@ function Environment(props) {
446
451
  return props.ground ? /* @__PURE__ */ jsxRuntime.jsx(EnvironmentGround, { ...props }) : props.map ? /* @__PURE__ */ jsxRuntime.jsx(EnvironmentMap, { ...props }) : props.children ? /* @__PURE__ */ jsxRuntime.jsx(EnvironmentPortal, { ...props }) : /* @__PURE__ */ jsxRuntime.jsx(EnvironmentCube, { ...props });
447
452
  }
448
453
 
449
- var __defProp$2 = Object.defineProperty;
450
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
451
- var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
452
- const act = React__namespace["act"];
454
+ var __defProp = Object.defineProperty;
455
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
456
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
453
457
  const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React__namespace.useLayoutEffect : React__namespace.useEffect;
454
458
  function useMutableCallback(fn) {
455
459
  const ref = React__namespace.useRef(fn);
@@ -480,7 +484,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
480
484
  return _a = class extends React__namespace.Component {
481
485
  constructor() {
482
486
  super(...arguments);
483
- __publicField$2(this, "state", { error: false });
487
+ __publicField(this, "state", { error: false });
484
488
  }
485
489
  componentDidCatch(err) {
486
490
  this.props.set(err);
@@ -488,7 +492,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
488
492
  render() {
489
493
  return this.state.error ? null : this.props.children;
490
494
  }
491
- }, __publicField$2(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
495
+ }, __publicField(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
492
496
  })();
493
497
 
494
498
  const is = {
@@ -625,8 +629,7 @@ function prepare(target, root, type, props) {
625
629
  object,
626
630
  eventCount: 0,
627
631
  handlers: {},
628
- isHidden: false,
629
- deferredRefs: []
632
+ isHidden: false
630
633
  };
631
634
  if (object) object.__r3f = instance;
632
635
  }
@@ -783,6 +786,17 @@ function unregisterVisibility(store, object) {
783
786
  internal.visibilityRegistry.delete(object.uuid);
784
787
  internal.occlusionCache.delete(object);
785
788
  }
789
+ function updateVisibilityHandlers(store, object, handlers) {
790
+ const { internal } = store.getState();
791
+ const entry = internal.visibilityRegistry.get(object.uuid);
792
+ if (!entry) return false;
793
+ entry.handlers = handlers;
794
+ if ((handlers.onOccluded || handlers.onVisible) && !internal.occlusionEnabled) {
795
+ object.occlusionTest = true;
796
+ enableOcclusion(store);
797
+ }
798
+ return true;
799
+ }
786
800
  function checkVisibility(state) {
787
801
  const { internal, camera } = state;
788
802
  const registry = internal.visibilityRegistry;
@@ -943,9 +957,9 @@ function diffProps(instance, newProps) {
943
957
  const { root, key } = resolve(instance.object, prop);
944
958
  if (root.constructor && root.constructor.length === 0) {
945
959
  const ctor = getMemoizedPrototype(root);
946
- if (!is.und(ctor)) changedProps[key] = ctor[key];
960
+ if (!is.und(ctor)) changedProps[prop] = ctor[key];
947
961
  } else {
948
- changedProps[key] = 0;
962
+ changedProps[prop] = 0;
949
963
  }
950
964
  }
951
965
  return changedProps;
@@ -970,10 +984,7 @@ function applyProps(object, props) {
970
984
  continue;
971
985
  }
972
986
  if (value === void 0) continue;
973
- if (isFromRef(value)) {
974
- instance?.deferredRefs?.push({ prop, ref: value[FROM_REF] });
975
- continue;
976
- }
987
+ if (isFromRef(value)) continue;
977
988
  if (isOnce(value)) {
978
989
  if (instance?.appliedOnce?.has(prop)) continue;
979
990
  if (instance) {
@@ -1009,6 +1020,19 @@ function applyProps(object, props) {
1009
1020
  } else if (isVectorLike(target) && is.num(value)) {
1010
1021
  if ("setScalar" in target && typeof target.setScalar === "function") target.setScalar(value);
1011
1022
  else target.set(value);
1023
+ } else if (root instanceof webgpu.ShaderMaterial && key === "uniforms" && is.obj(value)) {
1024
+ if (!is.obj(root.uniforms)) root.uniforms = {};
1025
+ const uniforms = root.uniforms;
1026
+ const nextUniforms = value;
1027
+ for (const name in nextUniforms) {
1028
+ const uniform = nextUniforms[name];
1029
+ const targetUniform = uniforms[name];
1030
+ if (targetUniform) Object.assign(targetUniform, uniform);
1031
+ else {
1032
+ const nextUniform = uniform instanceof webgpu.Uniform ? uniform.clone() : new webgpu.Uniform(uniform.value);
1033
+ uniforms[name] = nextUniform;
1034
+ }
1035
+ }
1012
1036
  } else {
1013
1037
  root[key] = value;
1014
1038
  if (key.endsWith("Node") && root.isMaterial) {
@@ -1027,6 +1051,9 @@ function applyProps(object, props) {
1027
1051
  if (instance.eventCount && object2.raycast !== null) {
1028
1052
  rootState.internal.interaction.push(object2);
1029
1053
  }
1054
+ }
1055
+ if (instance?.parent && rootState?.internal && instance.object?.isObject3D) {
1056
+ const object2 = instance.object;
1030
1057
  const root = findInitialRoot(instance);
1031
1058
  const visibilityHandlers = {
1032
1059
  onFramed: instance.handlers.onFramed,
@@ -1034,7 +1061,9 @@ function applyProps(object, props) {
1034
1061
  onVisible: instance.handlers.onVisible
1035
1062
  };
1036
1063
  if (hasVisibilityHandlers(visibilityHandlers)) {
1037
- registerVisibility(root, object2, visibilityHandlers);
1064
+ if (!updateVisibilityHandlers(root, object2, visibilityHandlers)) {
1065
+ registerVisibility(root, object2, visibilityHandlers);
1066
+ }
1038
1067
  } else {
1039
1068
  unregisterVisibility(root, object2);
1040
1069
  }
@@ -1562,6 +1591,7 @@ function createPointerEvents(store) {
1562
1591
  set((state) => ({ events: { ...state.events, connected: void 0 } }));
1563
1592
  }
1564
1593
  },
1594
+ // PREVIEW (A8): the XR pointer registration API may change before stable.
1565
1595
  registerPointer: (config) => {
1566
1596
  const pointerId = nextXRPointerId++;
1567
1597
  xrPointers.set(pointerId, config);
@@ -1648,1036 +1678,11 @@ function notifyAlpha({ message, link }) {
1648
1678
  }
1649
1679
  }
1650
1680
 
1651
- var __defProp$1 = Object.defineProperty;
1652
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1653
- var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1654
- const DEFAULT_PHASES = ["start", "input", "physics", "update", "render", "finish"];
1655
- class PhaseGraph {
1656
- constructor() {
1657
- /** Ordered list of phase nodes */
1658
- __publicField$1(this, "phases", []);
1659
- /** Quick lookup by name */
1660
- __publicField$1(this, "phaseMap", /* @__PURE__ */ new Map());
1661
- /** Cached ordered names (invalidated on changes) */
1662
- __publicField$1(this, "orderedNamesCache", null);
1663
- this.initializeDefaultPhases();
1664
- }
1665
- //* Initialization --------------------------------
1666
- initializeDefaultPhases() {
1667
- for (const name of DEFAULT_PHASES) {
1668
- const node = { name, isAutoGenerated: false };
1669
- this.phases.push(node);
1670
- this.phaseMap.set(name, node);
1671
- }
1672
- this.invalidateCache();
1673
- }
1674
- //* Public API --------------------------------
1675
- /**
1676
- * Add a named phase to the graph
1677
- * @param name - Phase name (must be unique)
1678
- * @param options - Position options (before or after another phase)
1679
- */
1680
- addPhase(name, options = {}) {
1681
- if (this.phaseMap.has(name)) {
1682
- console.warn(`[useFrame] Phase "${name}" already exists`);
1683
- return;
1684
- }
1685
- const { before, after } = options;
1686
- const node = { name, isAutoGenerated: false };
1687
- let insertIndex = this.phases.length;
1688
- const targetIndex = this.getPhaseIndex(before ?? after);
1689
- if (targetIndex !== -1) {
1690
- insertIndex = before ? targetIndex : targetIndex + 1;
1691
- } else {
1692
- const constraintType = before ? "before" : "after";
1693
- console.warn(`[useFrame] Phase "${before ?? after}" not found for '${constraintType}' constraint`);
1694
- }
1695
- this.phases.splice(insertIndex, 0, node);
1696
- this.phaseMap.set(name, node);
1697
- this.invalidateCache();
1698
- }
1699
- /**
1700
- * Get ordered list of phase names
1701
- */
1702
- getOrderedPhases() {
1703
- if (this.orderedNamesCache === null) this.orderedNamesCache = this.phases.map((p) => p.name);
1704
- return this.orderedNamesCache;
1705
- }
1706
- /**
1707
- * Check if a phase exists
1708
- */
1709
- hasPhase(name) {
1710
- return this.phaseMap.has(name);
1711
- }
1712
- /**
1713
- * Get the index of a phase (-1 if not found)
1714
- */
1715
- getPhaseIndex(name) {
1716
- if (!name) return -1;
1717
- return this.phases.findIndex((p) => p.name === name);
1718
- }
1719
- /**
1720
- * Ensure a phase exists, creating an auto-generated one if needed.
1721
- * Used for resolving before/after constraints.
1722
- *
1723
- * @param name - The phase name to ensure exists
1724
- * @returns The phase name (may be auto-generated like 'before:render')
1725
- */
1726
- ensurePhase(name) {
1727
- if (this.phaseMap.has(name)) return name;
1728
- const node = { name, isAutoGenerated: true };
1729
- this.phases.push(node);
1730
- this.phaseMap.set(name, node);
1731
- this.invalidateCache();
1732
- return name;
1733
- }
1734
- /**
1735
- * Resolve where a job with before/after constraints should go.
1736
- * Creates auto-generated phases if needed.
1737
- *
1738
- * @param before - Phase(s) to run before
1739
- * @param after - Phase(s) to run after
1740
- * @returns The resolved phase name
1741
- */
1742
- resolveConstraintPhase(before, after) {
1743
- const beforeArr = before ? Array.isArray(before) ? before : [before] : [];
1744
- const afterArr = after ? Array.isArray(after) ? after : [after] : [];
1745
- if (beforeArr.length > 0) {
1746
- return this.ensureAutoPhase(beforeArr[0], "before", 0);
1747
- }
1748
- if (afterArr.length > 0) {
1749
- return this.ensureAutoPhase(afterArr[0], "after", 1);
1750
- }
1751
- return "update";
1752
- }
1753
- /**
1754
- * Ensure an auto-generated phase exists relative to a target phase.
1755
- * Creates the phase if it doesn't exist, inserting it at the correct position.
1756
- *
1757
- * @param target - The target phase name to position relative to
1758
- * @param prefix - Prefix for auto-generated phase name ('before' or 'after')
1759
- * @param offset - Insertion offset (0 for before, 1 for after)
1760
- * @returns The auto-generated phase name
1761
- */
1762
- ensureAutoPhase(target, prefix, offset) {
1763
- const autoName = `${prefix}:${target}`;
1764
- if (this.phaseMap.has(autoName)) return autoName;
1765
- const node = { name: autoName, isAutoGenerated: true };
1766
- const targetIndex = this.getPhaseIndex(target);
1767
- if (targetIndex !== -1) this.phases.splice(targetIndex + offset, 0, node);
1768
- else this.phases.push(node);
1769
- this.phaseMap.set(autoName, node);
1770
- this.invalidateCache();
1771
- return autoName;
1772
- }
1773
- // Internal --------------------------------
1774
- invalidateCache() {
1775
- this.orderedNamesCache = null;
1776
- }
1777
- }
1778
-
1779
- function rebuildSortedJobs(jobs, phaseGraph) {
1780
- const orderedPhases = phaseGraph.getOrderedPhases();
1781
- const buckets = /* @__PURE__ */ new Map();
1782
- for (const phase of orderedPhases) {
1783
- buckets.set(phase, []);
1784
- }
1785
- for (const job of jobs.values()) {
1786
- if (!job.enabled) continue;
1787
- let bucket = buckets.get(job.phase);
1788
- if (!bucket) {
1789
- bucket = [];
1790
- buckets.set(job.phase, bucket);
1791
- }
1792
- bucket.push(job);
1793
- }
1794
- const sortedBuckets = [];
1795
- for (const phase of orderedPhases) {
1796
- const bucket = buckets.get(phase);
1797
- if (!bucket || bucket.length === 0) continue;
1798
- bucket.sort((a, b) => {
1799
- if (a.priority !== b.priority) return b.priority - a.priority;
1800
- return a.index - b.index;
1801
- });
1802
- sortedBuckets.push(hasCrossJobConstraints(bucket) ? topologicalSort(bucket) : bucket);
1803
- }
1804
- for (const [phase, bucket] of buckets) {
1805
- if (!orderedPhases.includes(phase) && bucket.length > 0) {
1806
- bucket.sort((a, b) => {
1807
- if (a.priority !== b.priority) return b.priority - a.priority;
1808
- return a.index - b.index;
1809
- });
1810
- sortedBuckets.push(bucket);
1811
- }
1812
- }
1813
- return sortedBuckets.flat();
1814
- }
1815
- function hasCrossJobConstraints(bucket) {
1816
- const jobIds = new Set(bucket.map((j) => j.id));
1817
- for (const job of bucket) {
1818
- for (const ref of job.before) {
1819
- if (jobIds.has(ref)) return true;
1820
- }
1821
- for (const ref of job.after) {
1822
- if (jobIds.has(ref)) return true;
1823
- }
1824
- }
1825
- return false;
1826
- }
1827
- function topologicalSort(jobs) {
1828
- const n = jobs.length;
1829
- if (n <= 1) return jobs;
1830
- const jobMap = /* @__PURE__ */ new Map();
1831
- const inDegree = /* @__PURE__ */ new Map();
1832
- const adjacency = /* @__PURE__ */ new Map();
1833
- for (const job of jobs) {
1834
- jobMap.set(job.id, job);
1835
- inDegree.set(job.id, 0);
1836
- adjacency.set(job.id, []);
1837
- }
1838
- for (const job of jobs) {
1839
- for (const ref of job.before) {
1840
- if (jobMap.has(ref)) {
1841
- adjacency.get(job.id).push(ref);
1842
- inDegree.set(ref, inDegree.get(ref) + 1);
1843
- }
1844
- }
1845
- for (const ref of job.after) {
1846
- if (jobMap.has(ref)) {
1847
- adjacency.get(ref).push(job.id);
1848
- inDegree.set(job.id, inDegree.get(job.id) + 1);
1849
- }
1850
- }
1851
- }
1852
- const queue = [];
1853
- for (const job of jobs) {
1854
- if (inDegree.get(job.id) === 0) {
1855
- queue.push(job);
1856
- }
1857
- }
1858
- queue.sort((a, b) => {
1859
- if (a.priority !== b.priority) return b.priority - a.priority;
1860
- return a.index - b.index;
1861
- });
1862
- const result = [];
1863
- while (queue.length > 0) {
1864
- const job = queue.shift();
1865
- result.push(job);
1866
- const neighbors = adjacency.get(job.id) || [];
1867
- for (const neighborId of neighbors) {
1868
- const newDegree = inDegree.get(neighborId) - 1;
1869
- inDegree.set(neighborId, newDegree);
1870
- if (newDegree === 0) {
1871
- const neighbor = jobMap.get(neighborId);
1872
- insertSorted(queue, neighbor);
1873
- }
1874
- }
1875
- }
1876
- if (result.length !== n) {
1877
- console.warn("[useFrame] Circular dependency detected in job constraints");
1878
- const resultIds = new Set(result.map((j) => j.id));
1879
- for (const job of jobs) {
1880
- if (!resultIds.has(job.id)) result.push(job);
1881
- }
1882
- }
1883
- return result;
1884
- }
1885
- function insertSorted(arr, job) {
1886
- let i = 0;
1887
- while (i < arr.length) {
1888
- const cmp = arr[i];
1889
- if (job.priority > cmp.priority || job.priority === cmp.priority && job.index < cmp.index) {
1890
- break;
1891
- }
1892
- i++;
1893
- }
1894
- arr.splice(i, 0, job);
1895
- }
1896
-
1897
- function shouldRun(job, now) {
1898
- if (!job.enabled) return false;
1899
- if (!job.fps) return true;
1900
- const minInterval = 1e3 / job.fps;
1901
- const lastRun = job.lastRun ?? 0;
1902
- const elapsed = now - lastRun;
1903
- if (elapsed < minInterval - 1) return false;
1904
- if (job.drop) {
1905
- job.lastRun = now;
1906
- } else {
1907
- const steps = Math.floor(elapsed / minInterval);
1908
- job.lastRun = lastRun + steps * minInterval;
1909
- if (job.lastRun < now - minInterval) {
1910
- job.lastRun = now;
1911
- }
1912
- }
1913
- return true;
1914
- }
1915
- function resetJobTiming(job) {
1916
- job.lastRun = void 0;
1917
- }
1918
-
1919
- var __defProp = Object.defineProperty;
1920
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1921
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1922
- const hmrData = (() => {
1923
- if (typeof process !== "undefined" && process.env.NODE_ENV === "test") return void 0;
1924
- if (typeof import_meta_hot !== "undefined") return import_meta_hot;
1925
- try {
1926
- return (0, eval)("import.meta.hot");
1927
- } catch {
1928
- return void 0;
1929
- }
1930
- })();
1931
- const _Scheduler = class _Scheduler {
1932
- //* Constructor ================================
1933
- constructor() {
1934
- //* Critical State ================================
1935
- __publicField(this, "roots", /* @__PURE__ */ new Map());
1936
- __publicField(this, "phaseGraph");
1937
- __publicField(this, "loopState", {
1938
- running: false,
1939
- rafHandle: null,
1940
- lastTime: null,
1941
- // null = uninitialized, 0+ = valid timestamp
1942
- frameCount: 0,
1943
- elapsedTime: 0,
1944
- createdAt: performance.now()
1945
- });
1946
- __publicField(this, "stoppedTime", 0);
1947
- //* Private State ================================
1948
- __publicField(this, "nextRootIndex", 0);
1949
- __publicField(this, "globalBeforeJobs", /* @__PURE__ */ new Map());
1950
- __publicField(this, "globalAfterJobs", /* @__PURE__ */ new Map());
1951
- __publicField(this, "nextGlobalIndex", 0);
1952
- __publicField(this, "idleCallbacks", /* @__PURE__ */ new Set());
1953
- __publicField(this, "nextJobIndex", 0);
1954
- __publicField(this, "jobStateListeners", /* @__PURE__ */ new Map());
1955
- __publicField(this, "pendingFrames", 0);
1956
- __publicField(this, "_frameloop", "always");
1957
- //* Independent Mode & Error Handling State ================================
1958
- __publicField(this, "_independent", false);
1959
- __publicField(this, "errorHandler", null);
1960
- __publicField(this, "rootReadyCallbacks", /* @__PURE__ */ new Set());
1961
- //* Core Loop Execution Methods ================================
1962
- /**
1963
- * Main RAF loop callback.
1964
- * Executes frame, handles demand mode, and schedules next frame.
1965
- * @param {number} timestamp - RAF timestamp in milliseconds
1966
- * @returns {void}
1967
- * @private
1968
- */
1969
- __publicField(this, "loop", (timestamp) => {
1970
- if (!this.loopState.running) return;
1971
- this.executeFrame(timestamp);
1972
- if (this._frameloop === "demand") {
1973
- this.pendingFrames = Math.max(0, this.pendingFrames - 1);
1974
- if (this.pendingFrames === 0) {
1975
- this.notifyIdle(timestamp);
1976
- return this.stop();
1977
- }
1978
- }
1979
- this.loopState.rafHandle = requestAnimationFrame(this.loop);
1980
- });
1981
- this.phaseGraph = new PhaseGraph();
1982
- }
1983
- static get instance() {
1984
- return globalThis[_Scheduler.INSTANCE_KEY] ?? null;
1985
- }
1986
- static set instance(value) {
1987
- globalThis[_Scheduler.INSTANCE_KEY] = value;
1988
- }
1989
- /**
1990
- * Get the global scheduler instance (creates if doesn't exist).
1991
- * Uses HMR data to preserve instance across hot reloads.
1992
- * @returns {Scheduler} The singleton scheduler instance
1993
- */
1994
- static get() {
1995
- if (!_Scheduler.instance && hmrData?.data?.scheduler) {
1996
- _Scheduler.instance = hmrData.data.scheduler;
1997
- }
1998
- if (!_Scheduler.instance) {
1999
- _Scheduler.instance = new _Scheduler();
2000
- if (hmrData?.data) {
2001
- hmrData.data.scheduler = _Scheduler.instance;
2002
- }
2003
- }
2004
- return _Scheduler.instance;
2005
- }
2006
- /**
2007
- * Reset the singleton instance. Stops the loop and clears all state.
2008
- * Primarily used for testing to ensure clean state between tests.
2009
- * @returns {void}
2010
- */
2011
- static reset() {
2012
- if (_Scheduler.instance) {
2013
- _Scheduler.instance.stop();
2014
- _Scheduler.instance = null;
2015
- }
2016
- if (hmrData?.data) {
2017
- hmrData.data.scheduler = null;
2018
- }
2019
- }
2020
- //* Getters & Setters ================================
2021
- get phases() {
2022
- return this.phaseGraph.getOrderedPhases();
2023
- }
2024
- get frameloop() {
2025
- return this._frameloop;
2026
- }
2027
- set frameloop(mode) {
2028
- if (this._frameloop === mode) return;
2029
- const wasAlways = this._frameloop === "always";
2030
- this._frameloop = mode;
2031
- if (mode === "always" && !this.loopState.running && this.roots.size > 0) this.start();
2032
- else if (mode !== "always" && wasAlways) this.stop();
2033
- }
2034
- get isRunning() {
2035
- return this.loopState.running;
2036
- }
2037
- get isReady() {
2038
- return this.roots.size > 0;
2039
- }
2040
- get independent() {
2041
- return this._independent;
2042
- }
2043
- set independent(value) {
2044
- this._independent = value;
2045
- if (value) this.ensureDefaultRoot();
2046
- }
2047
- //* Root Management Methods ================================
2048
- /**
2049
- * Register a root (Canvas) with the scheduler.
2050
- * The first root to register starts the RAF loop (if frameloop='always').
2051
- * @param {string} id - Unique identifier for this root
2052
- * @param {RootOptions} [options] - Optional configuration with getState and onError callbacks
2053
- * @returns {() => void} Unsubscribe function to remove this root
2054
- */
2055
- registerRoot(id, options = {}) {
2056
- if (this.roots.has(id)) {
2057
- console.warn(`[Scheduler] Root "${id}" already registered`);
2058
- return () => this.unregisterRoot(id);
2059
- }
2060
- const entry = {
2061
- id,
2062
- getState: options.getState ?? (() => ({})),
2063
- jobs: /* @__PURE__ */ new Map(),
2064
- sortedJobs: [],
2065
- needsRebuild: false
2066
- };
2067
- if (options.onError) {
2068
- this.errorHandler = options.onError;
2069
- }
2070
- this.roots.set(id, entry);
2071
- if (this.roots.size === 1) {
2072
- this.notifyRootReady();
2073
- if (this._frameloop === "always") this.start();
2074
- }
2075
- return () => this.unregisterRoot(id);
2076
- }
2077
- /**
2078
- * Unregister a root from the scheduler.
2079
- * Cleans up all job state listeners for this root's jobs.
2080
- * The last root to unregister stops the RAF loop.
2081
- * @param {string} id - The root ID to unregister
2082
- * @returns {void}
2083
- */
2084
- unregisterRoot(id) {
2085
- const root = this.roots.get(id);
2086
- if (!root) return;
2087
- for (const jobId of root.jobs.keys()) {
2088
- this.jobStateListeners.delete(jobId);
2089
- }
2090
- this.roots.delete(id);
2091
- if (this.roots.size === 0) {
2092
- this.stop();
2093
- this.errorHandler = null;
2094
- }
2095
- }
2096
- /**
2097
- * Subscribe to be notified when a root becomes available.
2098
- * Fires immediately if a root already exists.
2099
- * @param {() => void} callback - Function called when first root registers
2100
- * @returns {() => void} Unsubscribe function
2101
- */
2102
- onRootReady(callback) {
2103
- if (this.roots.size > 0) {
2104
- callback();
2105
- return () => {
2106
- };
2107
- }
2108
- this.rootReadyCallbacks.add(callback);
2109
- return () => this.rootReadyCallbacks.delete(callback);
2110
- }
2111
- /**
2112
- * Notify all registered root-ready callbacks.
2113
- * Called when the first root registers.
2114
- * @returns {void}
2115
- * @private
2116
- */
2117
- notifyRootReady() {
2118
- for (const cb of this.rootReadyCallbacks) {
2119
- try {
2120
- cb();
2121
- } catch (error) {
2122
- console.error("[Scheduler] Error in root-ready callback:", error);
2123
- }
2124
- }
2125
- this.rootReadyCallbacks.clear();
2126
- }
2127
- /**
2128
- * Ensure a default root exists for independent mode.
2129
- * Creates a minimal root with no state provider.
2130
- * @returns {void}
2131
- * @private
2132
- */
2133
- ensureDefaultRoot() {
2134
- if (!this.roots.has("__default__")) {
2135
- this.registerRoot("__default__");
2136
- }
2137
- }
2138
- /**
2139
- * Trigger error handling for job errors.
2140
- * Uses the bound error handler if available, otherwise logs to console.
2141
- * @param {Error} error - The error to handle
2142
- * @returns {void}
2143
- */
2144
- triggerError(error) {
2145
- if (this.errorHandler) this.errorHandler(error);
2146
- else console.error("[Scheduler]", error);
2147
- }
2148
- //* Phase Management Methods ================================
2149
- /**
2150
- * Add a named phase to the scheduler's execution order.
2151
- * Marks all roots for rebuild to incorporate the new phase.
2152
- * @param {string} name - The phase name (e.g., 'physics', 'postprocess')
2153
- * @param {AddPhaseOptions} [options] - Positioning options (before/after other phases)
2154
- * @returns {void}
2155
- * @example
2156
- * scheduler.addPhase('physics', { before: 'update' });
2157
- * scheduler.addPhase('postprocess', { after: 'render' });
2158
- */
2159
- addPhase(name, options) {
2160
- this.phaseGraph.addPhase(name, options);
2161
- for (const root of this.roots.values()) {
2162
- root.needsRebuild = true;
2163
- }
2164
- }
2165
- /**
2166
- * Check if a phase exists in the scheduler.
2167
- * @param {string} name - The phase name to check
2168
- * @returns {boolean} True if the phase exists
2169
- */
2170
- hasPhase(name) {
2171
- return this.phaseGraph.hasPhase(name);
2172
- }
2173
- //* Global Job Registration Methods (Deprecated APIs) ================================
2174
- /**
2175
- * Register a global job that runs once per frame (not per-root).
2176
- * Used internally by deprecated addEffect/addAfterEffect APIs.
2177
- * @param {'before' | 'after'} phase - When to run: 'before' all roots or 'after' all roots
2178
- * @param {string} id - Unique identifier for this global job
2179
- * @param {(timestamp: number) => void} callback - Function called each frame with RAF timestamp
2180
- * @returns {() => void} Unsubscribe function to remove this global job
2181
- * @deprecated Use useFrame with phases instead
2182
- */
2183
- registerGlobal(phase, id, callback) {
2184
- const job = { id, callback };
2185
- if (phase === "before") {
2186
- this.globalBeforeJobs.set(id, job);
2187
- } else {
2188
- this.globalAfterJobs.set(id, job);
2189
- }
2190
- return () => {
2191
- if (phase === "before") this.globalBeforeJobs.delete(id);
2192
- else this.globalAfterJobs.delete(id);
2193
- };
2194
- }
2195
- //* Idle Callback Methods (Deprecated API) ================================
2196
- /**
2197
- * Register an idle callback that fires when the loop stops.
2198
- * Used internally by deprecated addTail API.
2199
- * @param {(timestamp: number) => void} callback - Function called when loop becomes idle
2200
- * @returns {() => void} Unsubscribe function to remove this idle callback
2201
- * @deprecated Use demand mode with invalidate() instead
2202
- */
2203
- onIdle(callback) {
2204
- this.idleCallbacks.add(callback);
2205
- return () => this.idleCallbacks.delete(callback);
2206
- }
2207
- /**
2208
- * Notify all registered idle callbacks.
2209
- * Called when the loop stops in demand mode.
2210
- * @param {number} timestamp - The RAF timestamp when idle occurred
2211
- * @returns {void}
2212
- * @private
2213
- */
2214
- notifyIdle(timestamp) {
2215
- for (const cb of this.idleCallbacks) {
2216
- try {
2217
- cb(timestamp);
2218
- } catch (error) {
2219
- console.error("[Scheduler] Error in idle callback:", error);
2220
- }
2221
- }
2222
- }
2223
- //* Job Registration & Management Methods ================================
2224
- /**
2225
- * Register a job (frame callback) with a specific root.
2226
- * This is the core registration method used by useFrame internally.
2227
- * @param {FrameNextCallback} callback - The function to call each frame
2228
- * @param {JobOptions & { rootId?: string; system?: boolean }} [options] - Job configuration
2229
- * @param {string} [options.rootId] - Target root ID (defaults to first registered root)
2230
- * @param {string} [options.id] - Unique job ID (auto-generated if not provided)
2231
- * @param {string} [options.phase] - Execution phase (defaults to 'update')
2232
- * @param {number} [options.priority] - Priority within phase (higher = earlier, default 0)
2233
- * @param {number} [options.fps] - FPS throttle limit
2234
- * @param {boolean} [options.drop] - Drop frames when behind (default true)
2235
- * @param {boolean} [options.enabled] - Whether job is active (default true)
2236
- * @param {boolean} [options.system] - Internal flag for system jobs (not user-facing)
2237
- * @returns {() => void} Unsubscribe function to remove this job
2238
- */
2239
- register(callback, options = {}) {
2240
- const rootId = options.rootId;
2241
- const root = rootId ? this.roots.get(rootId) : this.roots.values().next().value;
2242
- if (!root) {
2243
- console.warn("[Scheduler] No root registered. Is this inside a Canvas?");
2244
- return () => {
2245
- };
2246
- }
2247
- const id = options.id ?? this.generateJobId();
2248
- let phase = options.phase ?? "update";
2249
- if (!options.phase && (options.before || options.after)) {
2250
- phase = this.phaseGraph.resolveConstraintPhase(options.before, options.after);
2251
- }
2252
- const before = this.normalizeConstraints(options.before);
2253
- const after = this.normalizeConstraints(options.after);
2254
- const job = {
2255
- id,
2256
- callback,
2257
- phase,
2258
- before,
2259
- after,
2260
- priority: options.priority ?? 0,
2261
- index: this.nextJobIndex++,
2262
- fps: options.fps,
2263
- drop: options.drop ?? true,
2264
- enabled: options.enabled ?? true,
2265
- system: options.system ?? false
2266
- };
2267
- if (root.jobs.has(id)) {
2268
- console.warn(`[useFrame] Job with id "${id}" already exists, replacing`);
2269
- }
2270
- root.jobs.set(id, job);
2271
- root.needsRebuild = true;
2272
- return () => this.unregister(id, root.id);
2273
- }
2274
- /**
2275
- * Unregister a job by its ID.
2276
- * Searches all roots if rootId is not provided.
2277
- * @param {string} id - The job ID to unregister
2278
- * @param {string} [rootId] - Optional root ID to search (searches all if not provided)
2279
- * @returns {void}
2280
- */
2281
- unregister(id, rootId) {
2282
- const root = rootId ? this.roots.get(rootId) : Array.from(this.roots.values()).find((r) => r.jobs.has(id));
2283
- if (root?.jobs.delete(id)) {
2284
- root.needsRebuild = true;
2285
- this.jobStateListeners.delete(id);
2286
- }
2287
- }
2288
- /**
2289
- * Update a job's options dynamically.
2290
- * Searches all roots to find the job by ID.
2291
- * Phase/constraint changes trigger a rebuild of the sorted job list.
2292
- * @param {string} id - The job ID to update
2293
- * @param {Partial<JobOptions>} options - The options to update
2294
- * @returns {void}
2295
- */
2296
- updateJob(id, options) {
2297
- let job;
2298
- let root;
2299
- for (const r of this.roots.values()) {
2300
- job = r.jobs.get(id);
2301
- if (job) {
2302
- root = r;
2303
- break;
2304
- }
2305
- }
2306
- if (!job || !root) return;
2307
- if (options.priority !== void 0) job.priority = options.priority;
2308
- if (options.fps !== void 0) job.fps = options.fps;
2309
- if (options.drop !== void 0) job.drop = options.drop;
2310
- if (options.enabled !== void 0) {
2311
- const wasEnabled = job.enabled;
2312
- job.enabled = options.enabled;
2313
- if (!wasEnabled && job.enabled) resetJobTiming(job);
2314
- if (wasEnabled !== job.enabled) root.needsRebuild = true;
2315
- }
2316
- if (options.phase !== void 0 || options.before !== void 0 || options.after !== void 0) {
2317
- if (options.phase) job.phase = options.phase;
2318
- if (options.before !== void 0) job.before = this.normalizeConstraints(options.before);
2319
- if (options.after !== void 0) job.after = this.normalizeConstraints(options.after);
2320
- root.needsRebuild = true;
2321
- }
2322
- }
2323
- //* Job State Management Methods ================================
2324
- /**
2325
- * Check if a job is currently paused (disabled).
2326
- * @param {string} id - The job ID to check
2327
- * @returns {boolean} True if the job exists and is paused
2328
- */
2329
- isJobPaused(id) {
2330
- for (const root of this.roots.values()) {
2331
- const job = root.jobs.get(id);
2332
- if (job) return !job.enabled;
2333
- }
2334
- return false;
2335
- }
2336
- /**
2337
- * Subscribe to state changes for a specific job.
2338
- * Listener is called when job is paused or resumed.
2339
- * @param {string} id - The job ID to subscribe to
2340
- * @param {() => void} listener - Callback invoked on state changes
2341
- * @returns {() => void} Unsubscribe function
2342
- */
2343
- subscribeJobState(id, listener) {
2344
- if (!this.jobStateListeners.has(id)) {
2345
- this.jobStateListeners.set(id, /* @__PURE__ */ new Set());
2346
- }
2347
- this.jobStateListeners.get(id).add(listener);
2348
- return () => {
2349
- this.jobStateListeners.get(id)?.delete(listener);
2350
- if (this.jobStateListeners.get(id)?.size === 0) {
2351
- this.jobStateListeners.delete(id);
2352
- }
2353
- };
2354
- }
2355
- /**
2356
- * Notify all listeners that a job's state has changed.
2357
- * @param {string} id - The job ID that changed
2358
- * @returns {void}
2359
- * @private
2360
- */
2361
- notifyJobStateChange(id) {
2362
- this.jobStateListeners.get(id)?.forEach((listener) => listener());
2363
- }
2364
- /**
2365
- * Pause a job by ID (sets enabled=false).
2366
- * Notifies any subscribed state listeners.
2367
- * @param {string} id - The job ID to pause
2368
- * @returns {void}
2369
- */
2370
- pauseJob(id) {
2371
- this.updateJob(id, { enabled: false });
2372
- this.notifyJobStateChange(id);
2373
- }
2374
- /**
2375
- * Resume a paused job by ID (sets enabled=true).
2376
- * Resets job timing to prevent frame accumulation.
2377
- * Notifies any subscribed state listeners.
2378
- * @param {string} id - The job ID to resume
2379
- * @returns {void}
2380
- */
2381
- resumeJob(id) {
2382
- this.updateJob(id, { enabled: true });
2383
- this.notifyJobStateChange(id);
2384
- }
2385
- //* Frame Loop Control Methods ================================
2386
- /**
2387
- * Start the requestAnimationFrame loop.
2388
- * Resets timing state (elapsedTime, frameCount) on start.
2389
- * No-op if already running.
2390
- * @returns {void}
2391
- */
2392
- start() {
2393
- if (this.loopState.running) return;
2394
- const { elapsedTime, createdAt } = this.loopState;
2395
- let adjustedCreated = 0;
2396
- if (this.stoppedTime > 0) {
2397
- adjustedCreated = createdAt - (performance.now() - this.stoppedTime);
2398
- this.stoppedTime = 0;
2399
- }
2400
- Object.assign(this.loopState, {
2401
- running: true,
2402
- elapsedTime: elapsedTime ?? 0,
2403
- lastTime: performance.now(),
2404
- createdAt: adjustedCreated > 0 ? adjustedCreated : performance.now(),
2405
- frameCount: 0,
2406
- rafHandle: requestAnimationFrame(this.loop)
2407
- });
2408
- }
2409
- /**
2410
- * Stop the requestAnimationFrame loop.
2411
- * Cancels any pending RAF callback.
2412
- * No-op if not running.
2413
- * @returns {void}
2414
- */
2415
- stop() {
2416
- if (!this.loopState.running) return;
2417
- this.loopState.running = false;
2418
- if (this.loopState.rafHandle !== null) {
2419
- cancelAnimationFrame(this.loopState.rafHandle);
2420
- this.loopState.rafHandle = null;
2421
- }
2422
- this.stoppedTime = performance.now();
2423
- }
2424
- /**
2425
- * Request frames to be rendered in demand mode.
2426
- * Accumulates pending frames (capped at 60) and starts the loop if not running.
2427
- * No-op if frameloop is not 'demand'.
2428
- * @param {number} [frames=1] - Number of frames to request
2429
- * @param {boolean} [stackFrames=false] - Whether to add frames to existing pending count
2430
- * - `false` (default): Sets pending frames to the specified value (replaces existing count)
2431
- * - `true`: Adds frames to existing pending count (useful for accumulating invalidations)
2432
- * @returns {void}
2433
- * @example
2434
- * // Request a single frame render
2435
- * scheduler.invalidate();
2436
- *
2437
- * @example
2438
- * // Request 5 frames (e.g., for animations)
2439
- * scheduler.invalidate(5);
2440
- *
2441
- * @example
2442
- * // Set pending frames to exactly 3 (don't stack with existing)
2443
- * scheduler.invalidate(3, false);
2444
- *
2445
- * @example
2446
- * // Add 2 more frames to existing pending count
2447
- * scheduler.invalidate(2, true);
2448
- */
2449
- invalidate(frames = 1, stackFrames = false) {
2450
- if (this._frameloop !== "demand") return;
2451
- const baseFrames = stackFrames ? this.pendingFrames : 0;
2452
- this.pendingFrames = Math.min(60, baseFrames + frames);
2453
- if (!this.loopState.running && this.pendingFrames > 0) this.start();
2454
- }
2455
- /**
2456
- * Reset timing state for deterministic testing.
2457
- * Preserves jobs and roots but resets lastTime, frameCount, elapsedTime, etc.
2458
- * @returns {void}
2459
- */
2460
- resetTiming() {
2461
- this.loopState.lastTime = null;
2462
- this.loopState.frameCount = 0;
2463
- this.loopState.elapsedTime = 0;
2464
- this.loopState.createdAt = performance.now();
2465
- }
2466
- //* Manual Stepping Methods ================================
2467
- /**
2468
- * Manually execute a single frame for all roots.
2469
- * Useful for frameloop='never' mode or testing scenarios.
2470
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2471
- * @returns {void}
2472
- * @example
2473
- * // Manual control mode
2474
- * scheduler.frameloop = 'never';
2475
- * scheduler.step(); // Execute one frame
2476
- */
2477
- step(timestamp) {
2478
- const now = timestamp ?? performance.now();
2479
- this.executeFrame(now);
2480
- }
2481
- /**
2482
- * Manually execute a single job by its ID.
2483
- * Useful for testing individual job callbacks in isolation.
2484
- * @param {string} id - The job ID to step
2485
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2486
- * @returns {void}
2487
- */
2488
- stepJob(id, timestamp) {
2489
- let job;
2490
- let root;
2491
- for (const r of this.roots.values()) {
2492
- job = r.jobs.get(id);
2493
- if (job) {
2494
- root = r;
2495
- break;
2496
- }
2497
- }
2498
- if (!job || !root) {
2499
- console.warn(`[Scheduler] Job "${id}" not found`);
2500
- return;
2501
- }
2502
- const now = timestamp ?? performance.now();
2503
- const deltaMs = this.loopState.lastTime !== null ? now - this.loopState.lastTime : 0;
2504
- const delta = deltaMs / 1e3;
2505
- const elapsed = now - this.loopState.createdAt;
2506
- const providedState = root.getState?.() ?? {};
2507
- const frameState = {
2508
- ...providedState,
2509
- time: now,
2510
- delta,
2511
- elapsed,
2512
- frame: this.loopState.frameCount
2513
- };
2514
- try {
2515
- job.callback(frameState, delta);
2516
- } catch (error) {
2517
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2518
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2519
- }
2520
- }
2521
- /**
2522
- * Execute a single frame across all roots.
2523
- * Order: globalBefore → each root's jobs → globalAfter
2524
- * @param {number} timestamp - RAF timestamp in milliseconds
2525
- * @returns {void}
2526
- * @private
2527
- */
2528
- executeFrame(timestamp) {
2529
- const deltaMs = this.loopState.lastTime !== null ? timestamp - this.loopState.lastTime : 0;
2530
- const delta = deltaMs / 1e3;
2531
- this.loopState.lastTime = timestamp;
2532
- this.loopState.frameCount++;
2533
- this.loopState.elapsedTime += deltaMs;
2534
- this.runGlobalJobs(this.globalBeforeJobs, timestamp);
2535
- for (const root of this.roots.values()) {
2536
- this.tickRoot(root, timestamp, delta);
2537
- }
2538
- this.runGlobalJobs(this.globalAfterJobs, timestamp);
2539
- }
2540
- /**
2541
- * Run all global jobs from a job map.
2542
- * Catches and logs errors without stopping execution.
2543
- * @param {Map<string, GlobalJob>} jobs - The global jobs map to execute
2544
- * @param {number} timestamp - RAF timestamp in milliseconds
2545
- * @returns {void}
2546
- * @private
2547
- */
2548
- runGlobalJobs(jobs, timestamp) {
2549
- for (const job of jobs.values()) {
2550
- try {
2551
- job.callback(timestamp);
2552
- } catch (error) {
2553
- console.error(`[Scheduler] Error in global job "${job.id}":`, error);
2554
- }
2555
- }
2556
- }
2557
- /**
2558
- * Execute all jobs for a single root in sorted order.
2559
- * Rebuilds sorted job list if needed, then dispatches each job.
2560
- * Errors are caught and propagated via triggerError.
2561
- * @param {RootEntry} root - The root entry to tick
2562
- * @param {number} timestamp - RAF timestamp in milliseconds
2563
- * @param {number} delta - Time since last frame in seconds
2564
- * @returns {void}
2565
- * @private
2566
- */
2567
- tickRoot(root, timestamp, delta) {
2568
- if (root.needsRebuild) {
2569
- root.sortedJobs = rebuildSortedJobs(root.jobs, this.phaseGraph);
2570
- root.needsRebuild = false;
2571
- }
2572
- const providedState = root.getState?.() ?? {};
2573
- const frameState = {
2574
- ...providedState,
2575
- time: timestamp,
2576
- delta,
2577
- elapsed: this.loopState.elapsedTime / 1e3,
2578
- // Convert ms to seconds
2579
- frame: this.loopState.frameCount
2580
- };
2581
- for (const job of root.sortedJobs) {
2582
- if (!shouldRun(job, timestamp)) continue;
2583
- try {
2584
- job.callback(frameState, delta);
2585
- } catch (error) {
2586
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2587
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2588
- }
2589
- }
2590
- }
2591
- //* Debug & Inspection Methods ================================
2592
- /**
2593
- * Get the total number of registered jobs across all roots.
2594
- * Includes both per-root jobs and global before/after jobs.
2595
- * @returns {number} Total job count
2596
- */
2597
- getJobCount() {
2598
- let count = 0;
2599
- for (const root of this.roots.values()) {
2600
- count += root.jobs.size;
2601
- }
2602
- return count + this.globalBeforeJobs.size + this.globalAfterJobs.size;
2603
- }
2604
- /**
2605
- * Get all registered job IDs across all roots.
2606
- * Includes both per-root jobs and global before/after jobs.
2607
- * @returns {string[]} Array of all job IDs
2608
- */
2609
- getJobIds() {
2610
- const ids = [];
2611
- for (const root of this.roots.values()) {
2612
- ids.push(...root.jobs.keys());
2613
- }
2614
- ids.push(...this.globalBeforeJobs.keys());
2615
- ids.push(...this.globalAfterJobs.keys());
2616
- return ids;
2617
- }
2618
- /**
2619
- * Get the number of registered roots (Canvas instances).
2620
- * @returns {number} Number of registered roots
2621
- */
2622
- getRootCount() {
2623
- return this.roots.size;
2624
- }
2625
- /**
2626
- * Check if any user (non-system) jobs are registered in a specific phase.
2627
- * Used by the default render job to know if a user has taken over rendering.
2628
- *
2629
- * @param phase The phase to check
2630
- * @param rootId Optional root ID to check (checks all roots if not provided)
2631
- * @returns true if any user jobs exist in the phase
2632
- */
2633
- hasUserJobsInPhase(phase, rootId) {
2634
- const rootsToCheck = rootId ? [this.roots.get(rootId)].filter(Boolean) : Array.from(this.roots.values());
2635
- return rootsToCheck.some((root) => {
2636
- if (!root) return false;
2637
- for (const job of root.jobs.values()) {
2638
- if (job.phase === phase && !job.system && job.enabled) return true;
2639
- }
2640
- return false;
2641
- });
2642
- }
2643
- //* Utility Methods ================================
2644
- /**
2645
- * Generate a unique root ID for automatic root registration.
2646
- * @returns {string} A unique root ID in the format 'root_N'
2647
- */
2648
- generateRootId() {
2649
- return `root_${this.nextRootIndex++}`;
2650
- }
2651
- /**
2652
- * Generate a unique job ID.
2653
- * @returns {string} A unique job ID in the format 'job_N'
2654
- * @private
2655
- */
2656
- generateJobId() {
2657
- return `job_${this.nextJobIndex}`;
2658
- }
2659
- /**
2660
- * Normalize before/after constraints to a Set.
2661
- * Handles undefined, single string, or array inputs.
2662
- * @param {string | string[] | undefined} value - The constraint value(s)
2663
- * @returns {Set<string>} Normalized Set of constraint strings
2664
- * @private
2665
- */
2666
- normalizeConstraints(value) {
2667
- if (!value) return /* @__PURE__ */ new Set();
2668
- if (Array.isArray(value)) return new Set(value);
2669
- return /* @__PURE__ */ new Set([value]);
2670
- }
2671
- };
2672
- //* Static State & Methods (Singleton Usage) ================================
2673
- //* Cross-Bundle Singleton Key ==============================
2674
- // Use Symbol.for() to ensure scheduler is shared across bundle boundaries
2675
- // This prevents issues when mixing imports from @react-three/fiber and @react-three/fiber/webgpu
2676
- __publicField(_Scheduler, "INSTANCE_KEY", Symbol.for("@react-three/fiber.scheduler"));
2677
- let Scheduler = _Scheduler;
2678
- const getScheduler = () => Scheduler.get();
2679
- if (hmrData) {
2680
- hmrData.accept?.();
1681
+ const INTERNAL_LIB_MARKERS = ["zustand", "setState", "Object.assign"];
1682
+ function isInternalRendererAccess(stack, callerDepth = 2) {
1683
+ if (!stack) return false;
1684
+ const caller = stack.split("\n")[callerDepth] ?? "";
1685
+ return INTERNAL_LIB_MARKERS.some((m) => caller.includes(m));
2681
1686
  }
2682
1687
 
2683
1688
  const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
@@ -2789,7 +1794,7 @@ const createStore = (invalidate, advance) => {
2789
1794
  size: newSize,
2790
1795
  viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, newSize) }
2791
1796
  }));
2792
- getScheduler().invalidate();
1797
+ scheduler.getScheduler().invalidate();
2793
1798
  }
2794
1799
  }
2795
1800
  return;
@@ -2804,7 +1809,7 @@ const createStore = (invalidate, advance) => {
2804
1809
  viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, size) },
2805
1810
  _sizeImperative: true
2806
1811
  }));
2807
- getScheduler().invalidate();
1812
+ scheduler.getScheduler().invalidate();
2808
1813
  },
2809
1814
  setDpr: (dpr) => set((state2) => {
2810
1815
  const resolved = calculateDpr(dpr);
@@ -2812,6 +1817,7 @@ const createStore = (invalidate, advance) => {
2812
1817
  }),
2813
1818
  setFrameloop: (frameloop = "always") => {
2814
1819
  set(() => ({ frameloop }));
1820
+ scheduler.getScheduler().frameloop = frameloop;
2815
1821
  },
2816
1822
  setError: (error) => set(() => ({ error })),
2817
1823
  error: null,
@@ -2821,6 +1827,7 @@ const createStore = (invalidate, advance) => {
2821
1827
  buffers: {},
2822
1828
  gpuStorage: {},
2823
1829
  textures: /* @__PURE__ */ new Map(),
1830
+ _textureRefs: /* @__PURE__ */ new Map(),
2824
1831
  renderPipeline: null,
2825
1832
  passes: {},
2826
1833
  _hmrVersion: 0,
@@ -2878,8 +1885,7 @@ const createStore = (invalidate, advance) => {
2878
1885
  const currentState = rootStore.getState();
2879
1886
  if (!currentState.isLegacy && currentState.internal.actualRenderer) {
2880
1887
  const stack = new Error().stack || "";
2881
- const isInternalAccess = stack.includes("zustand") || stack.includes("setState") || stack.includes("Object.assign") || stack.includes("react-three-fiber/packages/fiber/src/core");
2882
- if (!isInternalAccess) {
1888
+ if (!isInternalRendererAccess(stack)) {
2883
1889
  const cleanedStack = stack.split("\n").slice(2).join("\n") || "Stack trace unavailable";
2884
1890
  notifyDepreciated({
2885
1891
  heading: "Accessing state.gl in WebGPU mode",
@@ -2992,26 +1998,32 @@ function loadingFn(extensions, onProgress) {
2992
1998
  );
2993
1999
  };
2994
2000
  }
2995
- function useLoader(loader, input, extensions, onProgress) {
2996
- const keys = Array.isArray(input) ? input : [input];
2001
+ function useLoader(loader, input, extensions, onProgress, cacheKey) {
2002
+ const inputs = Array.isArray(input) ? input : [input];
2003
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2997
2004
  const fn = loadingFn(extensions, onProgress);
2998
- const results = keys.map((key) => suspendReact.suspend(fn, [loader, key], { equal: is.equ }));
2005
+ const results = cacheKeys.map(
2006
+ (key, index) => suspendReact.suspend(() => fn(loader, inputs[index]), [loader, key], { equal: is.equ })
2007
+ );
2999
2008
  return Array.isArray(input) ? results : results[0];
3000
2009
  }
3001
- useLoader.preload = function(loader, input, extensions, onProgress) {
3002
- const keys = Array.isArray(input) ? input : [input];
3003
- keys.forEach((key) => suspendReact.preload(loadingFn(extensions, onProgress), [loader, key]));
2010
+ useLoader.preload = function(loader, input, extensions, onProgress, cacheKey) {
2011
+ const inputs = Array.isArray(input) ? input : [input];
2012
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2013
+ cacheKeys.forEach(
2014
+ (key, index) => suspendReact.preload(() => loadingFn(extensions, onProgress)(loader, inputs[index]), [loader, key])
2015
+ );
3004
2016
  };
3005
- useLoader.clear = function(loader, input) {
3006
- const keys = Array.isArray(input) ? input : [input];
3007
- keys.forEach((key) => suspendReact.clear([loader, key]));
2017
+ useLoader.clear = function(loader, input, cacheKey) {
2018
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2019
+ cacheKeys.forEach((key) => suspendReact.clear([loader, key]));
3008
2020
  };
3009
2021
  useLoader.loader = getLoader;
3010
2022
 
3011
2023
  function useFrame(callback, priorityOrOptions) {
3012
2024
  const store = React__namespace.useContext(context);
3013
2025
  const isInsideCanvas = store !== null;
3014
- const scheduler = getScheduler();
2026
+ const scheduler$1 = scheduler.getScheduler();
3015
2027
  const optionsKey = typeof priorityOrOptions === "number" ? `p:${priorityOrOptions}` : priorityOrOptions ? JSON.stringify({
3016
2028
  id: priorityOrOptions.id,
3017
2029
  phase: priorityOrOptions.phase,
@@ -3059,7 +2071,7 @@ function useFrame(callback, priorityOrOptions) {
3059
2071
  };
3060
2072
  callbackRef.current?.(mergedState, delta);
3061
2073
  };
3062
- const unregister = scheduler.register(wrappedCallback, {
2074
+ const unregister = scheduler$1.register(wrappedCallback, {
3063
2075
  id,
3064
2076
  rootId,
3065
2077
  ...options
@@ -3080,37 +2092,31 @@ function useFrame(callback, priorityOrOptions) {
3080
2092
  }
3081
2093
  };
3082
2094
  } else {
3083
- const registerOutside = () => {
3084
- return scheduler.register((state, delta) => callbackRef.current?.(state, delta), { id, ...options });
3085
- };
3086
- if (scheduler.independent || scheduler.isReady) {
3087
- return registerOutside();
3088
- }
3089
- let unregisterJob = null;
3090
- const unsubReady = scheduler.onRootReady(() => {
3091
- unregisterJob = registerOutside();
3092
- });
3093
- return () => {
3094
- unsubReady();
3095
- unregisterJob?.();
3096
- };
2095
+ return scheduler$1.register(
2096
+ (state, delta) => {
2097
+ const frameState = state;
2098
+ if (!frameState.renderer) return;
2099
+ callbackRef.current?.(frameState, delta);
2100
+ },
2101
+ { id, ...options }
2102
+ );
3097
2103
  }
3098
- }, [store, scheduler, id, optionsKey, isLegacyPriority, isInsideCanvas]);
2104
+ }, [store, scheduler$1, id, optionsKey, isLegacyPriority, isInsideCanvas]);
3099
2105
  const isPaused = React__namespace.useSyncExternalStore(
3100
2106
  // Subscribe function
3101
2107
  React__namespace.useCallback(
3102
2108
  (onStoreChange) => {
3103
- return getScheduler().subscribeJobState(id, onStoreChange);
2109
+ return scheduler.getScheduler().subscribeJobState(id, onStoreChange);
3104
2110
  },
3105
2111
  [id]
3106
2112
  ),
3107
2113
  // getSnapshot function
3108
- React__namespace.useCallback(() => getScheduler().isJobPaused(id), [id]),
2114
+ React__namespace.useCallback(() => scheduler.getScheduler().isJobPaused(id), [id]),
3109
2115
  // getServerSnapshot function (SSR)
3110
2116
  React__namespace.useCallback(() => false, [])
3111
2117
  );
3112
2118
  const controls = React__namespace.useMemo(() => {
3113
- const scheduler2 = getScheduler();
2119
+ const scheduler2 = scheduler.getScheduler();
3114
2120
  return {
3115
2121
  /** The job's unique ID */
3116
2122
  id,
@@ -3125,7 +2131,7 @@ function useFrame(callback, priorityOrOptions) {
3125
2131
  * @param timestamp Optional timestamp (defaults to performance.now())
3126
2132
  */
3127
2133
  step: (timestamp) => {
3128
- getScheduler().stepJob(id, timestamp);
2134
+ scheduler.getScheduler().stepJob(id, timestamp);
3129
2135
  },
3130
2136
  /**
3131
2137
  * Manually step ALL jobs in the scheduler.
@@ -3133,20 +2139,20 @@ function useFrame(callback, priorityOrOptions) {
3133
2139
  * @param timestamp Optional timestamp (defaults to performance.now())
3134
2140
  */
3135
2141
  stepAll: (timestamp) => {
3136
- getScheduler().step(timestamp);
2142
+ scheduler.getScheduler().step(timestamp);
3137
2143
  },
3138
2144
  /**
3139
2145
  * Pause this job (set enabled=false).
3140
2146
  * Job remains registered but won't run.
3141
2147
  */
3142
2148
  pause: () => {
3143
- getScheduler().pauseJob(id);
2149
+ scheduler.getScheduler().pauseJob(id);
3144
2150
  },
3145
2151
  /**
3146
2152
  * Resume this job (set enabled=true).
3147
2153
  */
3148
2154
  resume: () => {
3149
- getScheduler().resumeJob(id);
2155
+ scheduler.getScheduler().resumeJob(id);
3150
2156
  },
3151
2157
  /**
3152
2158
  * Reactive paused state - automatically updates when pause/resume is called.
@@ -3184,18 +2190,18 @@ function buildFromCache(input, textureCache) {
3184
2190
  function useTexture(input, optionsOrOnLoad) {
3185
2191
  const renderer = useThree((state) => state.internal.actualRenderer);
3186
2192
  const store = useStore();
3187
- const textureCache = useThree((state) => state.textures);
3188
2193
  const options = typeof optionsOrOnLoad === "function" ? { onLoad: optionsOrOnLoad } : optionsOrOnLoad ?? {};
3189
- const { onLoad, cache = false } = options;
2194
+ const { onLoad, cache = true } = options;
3190
2195
  const onLoadRef = React.useRef(onLoad);
3191
2196
  onLoadRef.current = onLoad;
3192
2197
  const onLoadCalledForRef = React.useRef(null);
3193
2198
  const urls = React.useMemo(() => getUrls(input), [input]);
3194
2199
  const cachedResult = React.useMemo(() => {
3195
2200
  if (!cache) return null;
3196
- if (!allUrlsCached(urls, textureCache)) return null;
3197
- return buildFromCache(input, textureCache);
3198
- }, [cache, urls, textureCache, input]);
2201
+ const textures = store.getState().textures;
2202
+ if (!allUrlsCached(urls, textures)) return null;
2203
+ return buildFromCache(input, textures);
2204
+ }, [cache, urls, input, store]);
3199
2205
  const loadedTextures = useLoader(
3200
2206
  webgpu.TextureLoader,
3201
2207
  IsObject(input) ? Object.values(input) : input
@@ -3239,8 +2245,6 @@ function useTexture(input, optionsOrOnLoad) {
3239
2245
  }, [input, loadedTextures, cachedResult]);
3240
2246
  React.useEffect(() => {
3241
2247
  if (!cache) return;
3242
- if (cachedResult) return;
3243
- const set = store.setState;
3244
2248
  const urlTextureMap = [];
3245
2249
  if (typeof input === "string") {
3246
2250
  urlTextureMap.push([input, mappedTextures]);
@@ -3254,18 +2258,32 @@ function useTexture(input, optionsOrOnLoad) {
3254
2258
  urlTextureMap.push([url, textureRecord[key]]);
3255
2259
  }
3256
2260
  }
3257
- set((state) => {
3258
- const newMap = new Map(state.textures);
3259
- let changed = false;
2261
+ store.setState((state) => {
2262
+ const refs = new Map(state._textureRefs);
2263
+ let textures = state.textures;
2264
+ let added = false;
3260
2265
  for (const [url, texture] of urlTextureMap) {
3261
- if (!newMap.has(url)) {
3262
- newMap.set(url, texture);
3263
- changed = true;
2266
+ if (!textures.has(url)) {
2267
+ if (!added) {
2268
+ textures = new Map(textures);
2269
+ added = true;
2270
+ }
2271
+ textures.set(url, texture);
3264
2272
  }
2273
+ refs.set(url, (refs.get(url) ?? 0) + 1);
3265
2274
  }
3266
- return changed ? { textures: newMap } : state;
2275
+ return added ? { textures, _textureRefs: refs } : { _textureRefs: refs };
2276
+ });
2277
+ return () => store.setState((state) => {
2278
+ const refs = new Map(state._textureRefs);
2279
+ for (const [url] of urlTextureMap) {
2280
+ const next = (refs.get(url) ?? 0) - 1;
2281
+ if (next <= 0) refs.delete(url);
2282
+ else refs.set(url, next);
2283
+ }
2284
+ return { _textureRefs: refs };
3267
2285
  });
3268
- }, [cache, input, mappedTextures, store, cachedResult]);
2286
+ }, [cache, input, mappedTextures, store]);
3269
2287
  return mappedTextures;
3270
2288
  }
3271
2289
  useTexture.preload = (url) => useLoader.preload(webgpu.TextureLoader, url);
@@ -3281,96 +2299,63 @@ const Texture = ({
3281
2299
  return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: children?.(ret) });
3282
2300
  };
3283
2301
 
3284
- function getTextureValue(entry) {
3285
- if (entry instanceof webgpu.Texture) return entry;
3286
- if (entry && typeof entry === "object" && "value" in entry && entry.value instanceof webgpu.Texture) {
3287
- return entry.value;
3288
- }
3289
- return null;
3290
- }
3291
- function useTextures() {
2302
+ function useTextures(selector) {
3292
2303
  const store = useStore();
3293
- return React.useMemo(() => {
3294
- const set = store.setState;
2304
+ const registry = React.useMemo(() => {
3295
2305
  const getState = store.getState;
3296
- const add = (key, value) => {
3297
- set((state) => {
3298
- const newMap = new Map(state.textures);
3299
- newMap.set(key, value);
3300
- return { textures: newMap };
3301
- });
3302
- };
3303
- const addMultiple = (items) => {
3304
- set((state) => {
3305
- const newMap = new Map(state.textures);
3306
- const entries = items instanceof Map ? items.entries() : Object.entries(items);
3307
- for (const [key, value] of entries) {
3308
- newMap.set(key, value);
3309
- }
3310
- return { textures: newMap };
3311
- });
3312
- };
3313
- const remove = (key) => {
3314
- set((state) => {
3315
- const newMap = new Map(state.textures);
3316
- newMap.delete(key);
3317
- return { textures: newMap };
3318
- });
3319
- };
3320
- const removeMultiple = (keys) => {
3321
- set((state) => {
3322
- const newMap = new Map(state.textures);
3323
- for (const key of keys) newMap.delete(key);
3324
- return { textures: newMap };
3325
- });
3326
- };
3327
- const dispose = (key) => {
3328
- const entry = getState().textures.get(key);
3329
- if (entry) {
3330
- const tex = getTextureValue(entry);
3331
- tex?.dispose();
3332
- }
3333
- remove(key);
3334
- };
3335
- const disposeMultiple = (keys) => {
3336
- const textures = getState().textures;
3337
- for (const key of keys) {
3338
- const entry = textures.get(key);
3339
- if (entry) {
3340
- const tex = getTextureValue(entry);
3341
- tex?.dispose();
3342
- }
3343
- }
3344
- removeMultiple(keys);
3345
- };
3346
- const disposeAll = () => {
3347
- const textures = getState().textures;
3348
- for (const entry of textures.values()) {
3349
- const tex = getTextureValue(entry);
3350
- tex?.dispose();
3351
- }
3352
- set({ textures: /* @__PURE__ */ new Map() });
3353
- };
2306
+ const setState = store.setState;
2307
+ const getOne = (key) => getState().textures.get(key);
3354
2308
  return {
3355
- // Getter for the textures Map (reactive via getState)
3356
- get textures() {
2309
+ get all() {
3357
2310
  return getState().textures;
3358
2311
  },
3359
- // Read
3360
- get: (key) => getState().textures.get(key),
2312
+ get(input) {
2313
+ if (typeof input === "string") return getOne(input);
2314
+ if (Array.isArray(input)) return input.map(getOne);
2315
+ const out = {};
2316
+ for (const name in input) out[name] = getOne(input[name]);
2317
+ return out;
2318
+ },
3361
2319
  has: (key) => getState().textures.has(key),
3362
- // Write
3363
- add,
3364
- addMultiple,
3365
- // Remove (cache only)
3366
- remove,
3367
- removeMultiple,
3368
- // Dispose (GPU + cache)
3369
- dispose,
3370
- disposeMultiple,
3371
- disposeAll
2320
+ add(keyOrRecord, texture) {
2321
+ setState((state) => {
2322
+ const textures = new Map(state.textures);
2323
+ if (typeof keyOrRecord === "string") {
2324
+ textures.set(keyOrRecord, texture);
2325
+ } else {
2326
+ for (const key in keyOrRecord) textures.set(key, keyOrRecord[key]);
2327
+ }
2328
+ return { textures };
2329
+ });
2330
+ },
2331
+ dispose(key, options) {
2332
+ const state = getState();
2333
+ const refs = state._textureRefs.get(key) ?? 0;
2334
+ if (refs > 0 && !options?.force) {
2335
+ console.warn(
2336
+ `[useTextures] "${key}" still has ${refs} active reference(s); skipping dispose. Pass { force: true } to override.`
2337
+ );
2338
+ return false;
2339
+ }
2340
+ state.textures.get(key)?.dispose();
2341
+ setState((s) => {
2342
+ const textures = new Map(s.textures);
2343
+ textures.delete(key);
2344
+ const nextRefs = new Map(s._textureRefs);
2345
+ nextRefs.delete(key);
2346
+ return { textures, _textureRefs: nextRefs };
2347
+ });
2348
+ return true;
2349
+ },
2350
+ disposeAll() {
2351
+ for (const texture of getState().textures.values()) texture.dispose();
2352
+ setState({ textures: /* @__PURE__ */ new Map(), _textureRefs: /* @__PURE__ */ new Map() });
2353
+ }
3372
2354
  };
3373
2355
  }, [store]);
2356
+ const subscribe = selector ? () => selector(registry) : (state) => state.textures;
2357
+ const selected = useThree(subscribe);
2358
+ return selector ? selected : registry;
3374
2359
  }
3375
2360
 
3376
2361
  function useRenderTarget(widthOrOptions, heightOrOptions, options) {
@@ -3427,7 +2412,7 @@ function addEffect(callback) {
3427
2412
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3428
2413
  });
3429
2414
  const id = `legacy_effect_${effectId++}`;
3430
- return getScheduler().registerGlobal("before", id, callback);
2415
+ return scheduler.getScheduler().registerGlobal("before", id, callback);
3431
2416
  }
3432
2417
  function addAfterEffect(callback) {
3433
2418
  notifyDepreciated({
@@ -3436,7 +2421,7 @@ function addAfterEffect(callback) {
3436
2421
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3437
2422
  });
3438
2423
  const id = `legacy_afterEffect_${effectId++}`;
3439
- return getScheduler().registerGlobal("after", id, callback);
2424
+ return scheduler.getScheduler().registerGlobal("after", id, callback);
3440
2425
  }
3441
2426
  function addTail(callback) {
3442
2427
  notifyDepreciated({
@@ -3444,16 +2429,16 @@ function addTail(callback) {
3444
2429
  body: "Use scheduler.onIdle(callback) instead.\naddTail will be removed in a future version.",
3445
2430
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3446
2431
  });
3447
- return getScheduler().onIdle(callback);
2432
+ return scheduler.getScheduler().onIdle(callback);
3448
2433
  }
3449
2434
  function invalidate(state, frames = 1, stackFrames = false) {
3450
- getScheduler().invalidate(frames, stackFrames);
2435
+ scheduler.getScheduler().invalidate(frames, stackFrames);
3451
2436
  }
3452
2437
  function advance(timestamp) {
3453
- getScheduler().step(timestamp);
2438
+ scheduler.getScheduler().step(timestamp);
3454
2439
  }
3455
2440
 
3456
- const version = "10.0.0-alpha.2";
2441
+ const version = "10.0.0-alpha.3";
3457
2442
  const packageData = {
3458
2443
  version: version};
3459
2444
 
@@ -14709,7 +13694,7 @@ function n0() {
14709
13694
  var t0 = n0();
14710
13695
  const r0 = Xb(t0);
14711
13696
 
14712
- const t = 1, o = 8, r = 32, e = 2;
13697
+ const t = 1, o = 8, r = 32, e = 2, i$1 = 268435456;
14713
13698
 
14714
13699
  function createReconciler(config) {
14715
13700
  const reconciler2 = r0(config);
@@ -14874,7 +13859,15 @@ function setFiberRef(fiber, publicInstance) {
14874
13859
  }
14875
13860
  }
14876
13861
  const reconstructed = [];
14877
- function swapInstances() {
13862
+ function flushReconstructedInstances() {
13863
+ if (reconstructed.length === 0) return;
13864
+ try {
13865
+ swapReconstructedInstances();
13866
+ } finally {
13867
+ reconstructed.length = 0;
13868
+ }
13869
+ }
13870
+ function swapReconstructedInstances() {
14878
13871
  for (const [instance] of reconstructed) {
14879
13872
  const parent = instance.parent;
14880
13873
  if (parent) {
@@ -14892,6 +13885,7 @@ function swapInstances() {
14892
13885
  }
14893
13886
  }
14894
13887
  if (instance.isHidden) unhideInstance(instance);
13888
+ if (isObject3D(instance.object)) removeInteractivity(findInitialRoot(instance), instance.object);
14895
13889
  if (instance.object.__r3f) delete instance.object.__r3f;
14896
13890
  if (instance.type !== "primitive") disposeOnIdle(instance.object);
14897
13891
  }
@@ -14904,6 +13898,8 @@ function swapInstances() {
14904
13898
  instance.object.__r3f = instance;
14905
13899
  setFiberRef(fiber, instance.object);
14906
13900
  delete instance.appliedOnce;
13901
+ instance.eventCount = 0;
13902
+ instance.handlers = {};
14907
13903
  applyProps(instance.object, instance.props);
14908
13904
  if (instance.props.attach) {
14909
13905
  attach(parent, instance);
@@ -14920,14 +13916,114 @@ function swapInstances() {
14920
13916
  invalidateInstance(instance);
14921
13917
  }
14922
13918
  }
14923
- reconstructed.length = 0;
14924
13919
  }
14925
13920
  const handleTextInstance = () => {
14926
13921
  };
14927
13922
  const NO_CONTEXT = {};
14928
13923
  let currentUpdatePriority = NoEventPriority;
14929
- const NoFlags = 0;
14930
- const Update = 4;
13924
+ function getEventPriority(type) {
13925
+ switch (type) {
13926
+ case "beforetoggle":
13927
+ case "cancel":
13928
+ case "click":
13929
+ case "close":
13930
+ case "contextmenu":
13931
+ case "copy":
13932
+ case "cut":
13933
+ case "auxclick":
13934
+ case "dblclick":
13935
+ case "dragend":
13936
+ case "dragstart":
13937
+ case "drop":
13938
+ case "focusin":
13939
+ case "focusout":
13940
+ case "input":
13941
+ case "invalid":
13942
+ case "keydown":
13943
+ case "keypress":
13944
+ case "keyup":
13945
+ case "mousedown":
13946
+ case "mouseup":
13947
+ case "paste":
13948
+ case "pause":
13949
+ case "play":
13950
+ case "pointercancel":
13951
+ case "pointerdown":
13952
+ case "pointerup":
13953
+ case "ratechange":
13954
+ case "reset":
13955
+ case "resize":
13956
+ case "seeked":
13957
+ case "submit":
13958
+ case "touchcancel":
13959
+ case "touchend":
13960
+ case "touchstart":
13961
+ case "volumechange":
13962
+ case "change":
13963
+ case "selectionchange":
13964
+ case "compositionstart":
13965
+ case "compositionend":
13966
+ case "compositionupdate":
13967
+ case "beforeinput":
13968
+ case "blur":
13969
+ case "fullscreenchange":
13970
+ case "focus":
13971
+ case "hashchange":
13972
+ case "popstate":
13973
+ case "select":
13974
+ case "selectstart":
13975
+ return e;
13976
+ case "drag":
13977
+ case "dragenter":
13978
+ case "dragexit":
13979
+ case "dragleave":
13980
+ case "dragover":
13981
+ case "mousemove":
13982
+ case "mouseout":
13983
+ case "mouseover":
13984
+ case "pointermove":
13985
+ case "pointerout":
13986
+ case "pointerover":
13987
+ case "scroll":
13988
+ case "touchmove":
13989
+ case "wheel":
13990
+ case "mouseenter":
13991
+ case "mouseleave":
13992
+ case "pointerenter":
13993
+ case "pointerleave":
13994
+ return o;
13995
+ case "message": {
13996
+ switch (Tb.unstable_getCurrentPriorityLevel()) {
13997
+ case Tb.unstable_ImmediatePriority:
13998
+ return e;
13999
+ case Tb.unstable_UserBlockingPriority:
14000
+ return o;
14001
+ case Tb.unstable_NormalPriority:
14002
+ case Tb.unstable_LowPriority:
14003
+ return r;
14004
+ case Tb.unstable_IdlePriority:
14005
+ return i$1;
14006
+ default:
14007
+ return r;
14008
+ }
14009
+ }
14010
+ default:
14011
+ return r;
14012
+ }
14013
+ }
14014
+ function scheduleMicrotask(callback) {
14015
+ if (typeof queueMicrotask === "function") {
14016
+ queueMicrotask(callback);
14017
+ } else if (typeof Promise !== "undefined") {
14018
+ Promise.resolve().then(callback).catch((error) => {
14019
+ setTimeout(() => {
14020
+ throw error;
14021
+ });
14022
+ });
14023
+ } else {
14024
+ setTimeout(callback);
14025
+ }
14026
+ }
14931
14027
  const reconciler = /* @__PURE__ */ createReconciler({
14932
14028
  isPrimaryRenderer: false,
14933
14029
  warnsIfNotActing: false,
@@ -14966,16 +14062,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
14966
14062
  else if (newProps.args?.length !== oldProps.args?.length) reconstruct = true;
14967
14063
  else if (newProps.args?.some((value, index) => value !== oldProps.args?.[index])) reconstruct = true;
14968
14064
  if (reconstruct) {
14969
- reconstructed.push([instance, { ...newProps }, fiber]);
14065
+ reconstructed.push([instance, getInstanceProps(newProps), fiber]);
14970
14066
  } else {
14971
14067
  const changedProps = diffProps(instance, newProps);
14972
- if (Object.keys(changedProps).length) {
14973
- Object.assign(instance.props, changedProps);
14974
- applyProps(instance.object, changedProps);
14975
- }
14068
+ const attach2 = instance.props.attach;
14069
+ instance.props = getInstanceProps(newProps);
14070
+ if (attach2 !== void 0) instance.props.attach = attach2;
14071
+ else delete instance.props.attach;
14072
+ if (Object.keys(changedProps).length) applyProps(instance.object, changedProps);
14976
14073
  }
14977
- const isTailSibling = fiber.sibling === null || (fiber.flags & Update) === NoFlags;
14978
- if (isTailSibling) swapInstances();
14979
14074
  },
14980
14075
  finalizeInitialChildren: (instance) => {
14981
14076
  for (const prop in instance.props) {
@@ -15000,8 +14095,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
15000
14095
  const target = container.getState().internal.container ?? container.getState().scene;
15001
14096
  return prepare(target, container, "", {});
15002
14097
  },
15003
- resetAfterCommit: () => {
15004
- },
14098
+ // Reconstructed instances are swapped once all mutations are committed,
14099
+ // before layout effects run so refs point to the new objects
14100
+ resetAfterCommit: flushReconstructedInstances,
15005
14101
  shouldSetTextContent: () => false,
15006
14102
  clearContainer: () => false,
15007
14103
  hideInstance,
@@ -15009,6 +14105,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
15009
14105
  createTextInstance: handleTextInstance,
15010
14106
  hideTextInstance: handleTextInstance,
15011
14107
  unhideTextInstance: handleTextInstance,
14108
+ // Mirrors react-dom, which flushes discrete work in microtasks
14109
+ supportsMicrotasks: true,
14110
+ scheduleMicrotask,
15012
14111
  scheduleTimeout: typeof setTimeout === "function" ? setTimeout : void 0,
15013
14112
  cancelTimeout: typeof clearTimeout === "function" ? clearTimeout : void 0,
15014
14113
  noTimeout: -1,
@@ -15049,28 +14148,9 @@ const reconciler = /* @__PURE__ */ createReconciler({
15049
14148
  },
15050
14149
  resolveUpdatePriority() {
15051
14150
  if (currentUpdatePriority !== NoEventPriority) return currentUpdatePriority;
15052
- switch (typeof window !== "undefined" && window.event?.type) {
15053
- case "click":
15054
- case "contextmenu":
15055
- case "dblclick":
15056
- case "dragenter":
15057
- case "dragleave":
15058
- case "drop":
15059
- case "pointercancel":
15060
- case "pointerdown":
15061
- case "pointerup":
15062
- return e;
15063
- case "dragover":
15064
- case "pointermove":
15065
- case "pointerout":
15066
- case "pointerover":
15067
- case "pointerenter":
15068
- case "pointerleave":
15069
- case "wheel":
15070
- return o;
15071
- default:
15072
- return r;
15073
- }
14151
+ const eventType = typeof window !== "undefined" ? window.event?.type : void 0;
14152
+ if (eventType === void 0) return r;
14153
+ return getEventPriority(eventType);
15074
14154
  },
15075
14155
  resetFormInstance() {
15076
14156
  },
@@ -15119,11 +14199,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
15119
14199
  cloneMutableTextInstance(textInstance) {
15120
14200
  return textInstance;
15121
14201
  },
14202
+ // React 19.2 added these for root-level view transitions. They only run for hosts that opt into
14203
+ // view transitions by returning a container from cloneRootViewTransitionContainer; R3F renders
14204
+ // into a WebGL/WebGPU canvas, where cloning the root has no meaning, so we never opt in and
14205
+ // React never calls them. They stay as no-ops rather than throws: the host config is shared by
14206
+ // every root, and a throw here would turn a React-internal probe into a hard crash for users.
14207
+ // Guarded by a test asserting a full render + unmount never reaches them.
15122
14208
  cloneRootViewTransitionContainer(_rootContainer) {
15123
- throw new Error("Not implemented.");
15124
14209
  },
15125
14210
  removeRootViewTransitionClone(_rootContainer, _clone) {
15126
- throw new Error("Not implemented.");
15127
14211
  },
15128
14212
  // https://github.com/facebook/react/pull/32465
15129
14213
  createFragmentInstance: (_fiber) => null,
@@ -15208,6 +14292,7 @@ function createRoot(canvas) {
15208
14292
  const lastConfiguredProps = {};
15209
14293
  let configured = false;
15210
14294
  let pending = null;
14295
+ let rendererSetup = null;
15211
14296
  return {
15212
14297
  async configure(props = {}) {
15213
14298
  let resolve;
@@ -15238,7 +14323,7 @@ function createRoot(canvas) {
15238
14323
  forceEven
15239
14324
  } = props;
15240
14325
  const textureColorSpace = is.obj(glConfig) && !is.fun(glConfig) && !isRenderer(glConfig) && glConfig.textureColorSpace || is.obj(rendererConfig) && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && rendererConfig.textureColorSpace || webgpu.SRGBColorSpace;
15241
- const state = store.getState();
14326
+ let state = store.getState();
15242
14327
  const defaultGLProps = {
15243
14328
  canvas,
15244
14329
  powerPreference: "high-performance",
@@ -15266,56 +14351,68 @@ function createRoot(canvas) {
15266
14351
  "The `primaryCanvas` prop for multi-canvas rendering cannot be used with WebGL. Remove the `gl` prop or use WebGPU."
15267
14352
  );
15268
14353
  }
15269
- if (wantsGL && !state.internal.actualRenderer) {
15270
- renderer = await resolveRenderer(glConfig, defaultGLProps, three.WebGLRenderer);
15271
- state.internal.actualRenderer = renderer;
15272
- state.set({ isLegacy: true, gl: renderer, renderer, primaryStore: store });
15273
- } else if (!wantsGL && primaryCanvas && !state.internal.actualRenderer) {
15274
- const primary = await waitForPrimary(primaryCanvas);
15275
- renderer = primary.renderer;
15276
- state.internal.actualRenderer = renderer;
15277
- const canvasTarget = new webgpu.CanvasTarget(canvas);
15278
- primary.store.setState((prev) => ({
15279
- internal: { ...prev.internal, isMultiCanvas: true }
15280
- }));
15281
- state.set((prev) => ({
15282
- webGPUSupported: primary.store.getState().webGPUSupported,
15283
- renderer,
15284
- primaryStore: primary.store,
15285
- internal: {
15286
- ...prev.internal,
15287
- canvasTarget,
15288
- isMultiCanvas: true,
15289
- isSecondary: true,
15290
- targetId: primaryCanvas
15291
- }
15292
- }));
15293
- } else if (!wantsGL && !state.internal.actualRenderer) {
15294
- renderer = await resolveRenderer(rendererConfig, defaultGPUProps, webgpu.WebGPURenderer);
15295
- if (!renderer.hasInitialized?.()) {
15296
- const size2 = computeInitialSize(canvas, propsSize);
15297
- if (size2.width > 0 && size2.height > 0) {
15298
- const pixelRatio = calculateDpr(dpr);
15299
- canvas.width = size2.width * pixelRatio;
15300
- canvas.height = size2.height * pixelRatio;
15301
- }
15302
- await renderer.init();
15303
- }
15304
- const backend = renderer.backend;
15305
- const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
15306
- state.internal.actualRenderer = renderer;
15307
- state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
15308
- if (canvasId && !state.internal.isSecondary) {
15309
- const canvasTarget = new webgpu.CanvasTarget(canvas);
15310
- const unregisterPrimary = registerPrimary(canvasId, renderer, store);
15311
- state.set((prev) => ({
15312
- internal: {
15313
- ...prev.internal,
15314
- canvasTarget,
15315
- unregisterPrimary
14354
+ if (!state.internal.actualRenderer) {
14355
+ if (!rendererSetup) {
14356
+ rendererSetup = (async () => {
14357
+ if (wantsGL) {
14358
+ renderer = await resolveRenderer(glConfig, defaultGLProps, three.WebGLRenderer);
14359
+ state.internal.actualRenderer = renderer;
14360
+ state.set({ isLegacy: true, gl: renderer, renderer, primaryStore: store });
14361
+ } else if (!wantsGL && primaryCanvas) {
14362
+ const primary = await waitForPrimary(primaryCanvas);
14363
+ renderer = primary.renderer;
14364
+ state.internal.actualRenderer = renderer;
14365
+ const canvasTarget = new webgpu.CanvasTarget(canvas);
14366
+ primary.store.setState((prev) => ({
14367
+ internal: { ...prev.internal, isMultiCanvas: true }
14368
+ }));
14369
+ state.set((prev) => ({
14370
+ webGPUSupported: primary.store.getState().webGPUSupported,
14371
+ renderer,
14372
+ primaryStore: primary.store,
14373
+ internal: {
14374
+ ...prev.internal,
14375
+ canvasTarget,
14376
+ isMultiCanvas: true,
14377
+ isSecondary: true,
14378
+ targetId: primaryCanvas
14379
+ }
14380
+ }));
14381
+ } else if (!wantsGL) {
14382
+ renderer = await resolveRenderer(rendererConfig, defaultGPUProps, webgpu.WebGPURenderer);
14383
+ if (!renderer.hasInitialized?.()) {
14384
+ const size2 = computeInitialSize(canvas, propsSize);
14385
+ if (size2.width > 0 && size2.height > 0) {
14386
+ const pixelRatio = calculateDpr(dpr);
14387
+ canvas.width = size2.width * pixelRatio;
14388
+ canvas.height = size2.height * pixelRatio;
14389
+ }
14390
+ await renderer.init();
14391
+ }
14392
+ const backend = renderer.backend;
14393
+ const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
14394
+ state.internal.actualRenderer = renderer;
14395
+ state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
14396
+ if (canvasId && !state.internal.isSecondary) {
14397
+ const canvasTarget = new webgpu.CanvasTarget(canvas);
14398
+ const unregisterPrimary = registerPrimary(canvasId, renderer, store);
14399
+ state.set((prev) => ({
14400
+ internal: {
14401
+ ...prev.internal,
14402
+ canvasTarget,
14403
+ unregisterPrimary
14404
+ }
14405
+ }));
14406
+ }
15316
14407
  }
15317
- }));
14408
+ })().catch((err) => {
14409
+ rendererSetup = null;
14410
+ throw err;
14411
+ });
15318
14412
  }
14413
+ await rendererSetup;
14414
+ state = store.getState();
14415
+ renderer = state.internal.actualRenderer;
15319
14416
  }
15320
14417
  let raycaster = state.raycaster;
15321
14418
  if (!raycaster) state.set({ raycaster: raycaster = new webgpu.Raycaster() });
@@ -15495,15 +14592,15 @@ function createRoot(canvas) {
15495
14592
  applyProps(currentRenderer, rendererProps);
15496
14593
  }
15497
14594
  }
15498
- const scheduler = getScheduler();
14595
+ const scheduler$1 = scheduler.getScheduler();
15499
14596
  const rootId = state.internal.rootId;
15500
14597
  if (!rootId) {
15501
- const newRootId = canvasId || scheduler.generateRootId();
15502
- const unregisterRoot = scheduler.registerRoot(newRootId, {
14598
+ const newRootId = canvasId || scheduler$1.generateRootId();
14599
+ const unregisterRoot = scheduler$1.registerRoot(newRootId, {
15503
14600
  getState: () => store.getState(),
15504
14601
  onError: (err) => store.getState().setError(err)
15505
14602
  });
15506
- const unregisterCanvasTarget = scheduler.register(
14603
+ const unregisterCanvasTarget = scheduler$1.register(
15507
14604
  () => {
15508
14605
  const state2 = store.getState();
15509
14606
  if (state2.internal.isMultiCanvas && state2.internal.canvasTarget) {
@@ -15518,7 +14615,7 @@ function createRoot(canvas) {
15518
14615
  system: true
15519
14616
  }
15520
14617
  );
15521
- const unregisterEventsFlush = scheduler.register(
14618
+ const unregisterEventsFlush = scheduler$1.register(
15522
14619
  () => {
15523
14620
  const state2 = store.getState();
15524
14621
  state2.events.flush?.();
@@ -15530,7 +14627,7 @@ function createRoot(canvas) {
15530
14627
  system: true
15531
14628
  }
15532
14629
  );
15533
- const unregisterFrustum = scheduler.register(
14630
+ const unregisterFrustum = scheduler$1.register(
15534
14631
  () => {
15535
14632
  const state2 = store.getState();
15536
14633
  if (state2.autoUpdateFrustum && state2.camera) {
@@ -15540,11 +14637,11 @@ function createRoot(canvas) {
15540
14637
  {
15541
14638
  id: `${newRootId}_frustum`,
15542
14639
  rootId: newRootId,
15543
- phase: "preRender",
14640
+ before: "render",
15544
14641
  system: true
15545
14642
  }
15546
14643
  );
15547
- const unregisterVisibility = scheduler.register(
14644
+ const unregisterVisibility = scheduler$1.register(
15548
14645
  () => {
15549
14646
  const state2 = store.getState();
15550
14647
  checkVisibility(state2);
@@ -15552,16 +14649,16 @@ function createRoot(canvas) {
15552
14649
  {
15553
14650
  id: `${newRootId}_visibility`,
15554
14651
  rootId: newRootId,
15555
- phase: "preRender",
14652
+ before: "render",
15556
14653
  system: true,
15557
14654
  after: `${newRootId}_frustum`
15558
14655
  }
15559
14656
  );
15560
- const unregisterRender = scheduler.register(
14657
+ const unregisterRender = scheduler$1.register(
15561
14658
  () => {
15562
14659
  const state2 = store.getState();
15563
14660
  const renderer2 = state2.internal.actualRenderer;
15564
- const userHandlesRender = scheduler.hasUserJobsInPhase("render", newRootId);
14661
+ const userHandlesRender = scheduler$1.hasUserJobsInPhase("render", newRootId);
15565
14662
  if (userHandlesRender || state2.internal.priority) return;
15566
14663
  try {
15567
14664
  if (state2.renderPipeline?.render) state2.renderPipeline.render();
@@ -15594,11 +14691,11 @@ function createRoot(canvas) {
15594
14691
  unregisterVisibility();
15595
14692
  unregisterRender();
15596
14693
  },
15597
- scheduler
14694
+ scheduler: scheduler$1
15598
14695
  }
15599
14696
  }));
15600
14697
  }
15601
- scheduler.frameloop = frameloop;
14698
+ scheduler$1.frameloop = frameloop;
15602
14699
  onCreated = onCreatedCallback;
15603
14700
  configured = true;
15604
14701
  resolve();
@@ -15665,7 +14762,8 @@ function unmountComponentAtNode(canvas, callback) {
15665
14762
  dispose(state.scene);
15666
14763
  _roots.delete(canvas);
15667
14764
  if (callback) callback(canvas);
15668
- } catch {
14765
+ } catch (error) {
14766
+ console.warn("[R3F] Error while unmounting root; teardown may be incomplete:", error);
15669
14767
  }
15670
14768
  }, 500);
15671
14769
  }
@@ -15728,6 +14826,7 @@ function PortalInner({ state = {}, children, container }) {
15728
14826
  viewport = rootState.viewport.getCurrentViewport(camera, new webgpu.Vector3(), resolvedSize);
15729
14827
  if (camera !== rootState.camera) updateCamera(camera, resolvedSize);
15730
14828
  }
14829
+ const set = injectState.set;
15731
14830
  return {
15732
14831
  // The intersect consists of the previous root state
15733
14832
  ...rootState,
@@ -15746,7 +14845,7 @@ function PortalInner({ state = {}, children, container }) {
15746
14845
  size: resolvedSize,
15747
14846
  viewport: { ...rootState.viewport, ...viewport },
15748
14847
  // Layers are allowed to override events
15749
- setEvents: (events2) => injectState.set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14848
+ setEvents: (events2) => set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
15750
14849
  // Container for child attachment - the portalScene (injected or container itself)
15751
14850
  internal: { ...rootState.internal, ...injectState.internal, container: portalScene }
15752
14851
  };
@@ -15775,6 +14874,81 @@ function flushSync(fn) {
15775
14874
  return reconciler.flushSyncFromReconciler(fn);
15776
14875
  }
15777
14876
 
14877
+ function parseBackground(background) {
14878
+ if (!background) return null;
14879
+ if (typeof background === "object" && !background.isColor) {
14880
+ const { backgroundMap, envMap, files, preset, ...rest } = background;
14881
+ return {
14882
+ ...rest,
14883
+ preset,
14884
+ files: envMap || files,
14885
+ backgroundFiles: backgroundMap,
14886
+ background: true
14887
+ };
14888
+ }
14889
+ if (typeof background === "number") {
14890
+ return { color: background, background: true };
14891
+ }
14892
+ if (typeof background === "string") {
14893
+ if (background in presetsObj) {
14894
+ return { preset: background, background: true };
14895
+ }
14896
+ if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
14897
+ return { files: background, background: true };
14898
+ }
14899
+ return { color: background, background: true };
14900
+ }
14901
+ if (background.isColor) {
14902
+ return { color: background, background: true };
14903
+ }
14904
+ return null;
14905
+ }
14906
+
14907
+ function parseRendererConfig(rendererProp) {
14908
+ const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
14909
+ if (isRendererConfig) {
14910
+ const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
14911
+ return {
14912
+ primaryCanvas: pc,
14913
+ scheduler: sc,
14914
+ renderer: Object.keys(rest).length > 0 ? rest : rendererProp
14915
+ };
14916
+ }
14917
+ return { primaryCanvas: void 0, scheduler: void 0, renderer: rendererProp };
14918
+ }
14919
+
14920
+ const RESOURCE_KINDS = ["nodes", "uniforms", "buffers", "gpuStorage"];
14921
+ const registries = /* @__PURE__ */ new WeakMap();
14922
+ function getKindRegistry(store, kind) {
14923
+ let registry = registries.get(store);
14924
+ if (!registry) {
14925
+ registry = {
14926
+ nodes: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14927
+ uniforms: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14928
+ buffers: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() },
14929
+ gpuStorage: { valid: /* @__PURE__ */ new Set(), staged: /* @__PURE__ */ new Map() }
14930
+ };
14931
+ registries.set(store, registry);
14932
+ }
14933
+ return registry[kind];
14934
+ }
14935
+ function invalidateResource(store, kind, scopeKey) {
14936
+ const registry = getKindRegistry(store, kind);
14937
+ {
14938
+ registry.valid.clear();
14939
+ registry.staged.clear();
14940
+ }
14941
+ }
14942
+ function invalidateAllResources(store) {
14943
+ for (const kind of RESOURCE_KINDS) invalidateResource(store, kind);
14944
+ }
14945
+
14946
+ function clearHmrCaches(store) {
14947
+ const primary = store.getState().primaryStore ?? store;
14948
+ invalidateAllResources(primary);
14949
+ primary.setState((state) => ({ _hmrVersion: state._hmrVersion + 1 }));
14950
+ }
14951
+
15778
14952
  function CanvasImpl({
15779
14953
  ref,
15780
14954
  children,
@@ -15795,6 +14969,8 @@ function CanvasImpl({
15795
14969
  raycaster,
15796
14970
  camera,
15797
14971
  scene,
14972
+ autoUpdateFrustum,
14973
+ occlusion,
15798
14974
  onPointerMissed,
15799
14975
  onDragOverMissed,
15800
14976
  onDropMissed,
@@ -15806,49 +14982,10 @@ function CanvasImpl({
15806
14982
  forceEven,
15807
14983
  ...props
15808
14984
  }) {
15809
- const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
15810
- let primaryCanvas;
15811
- let scheduler;
15812
- let renderer;
15813
- if (isRendererConfig) {
15814
- const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
15815
- primaryCanvas = pc;
15816
- scheduler = sc;
15817
- renderer = Object.keys(rest).length > 0 ? rest : rendererProp;
15818
- } else {
15819
- renderer = rendererProp;
15820
- }
14985
+ const { primaryCanvas, scheduler, renderer } = parseRendererConfig(rendererProp);
15821
14986
  React__namespace.useMemo(() => extend(THREE), []);
15822
14987
  const Bridge = useBridge();
15823
- const backgroundProps = React__namespace.useMemo(() => {
15824
- if (!background) return null;
15825
- if (typeof background === "object" && !background.isColor) {
15826
- const { backgroundMap, envMap, files, preset, ...rest } = background;
15827
- return {
15828
- ...rest,
15829
- preset,
15830
- files: envMap || files,
15831
- backgroundFiles: backgroundMap,
15832
- background: true
15833
- };
15834
- }
15835
- if (typeof background === "number") {
15836
- return { color: background, background: true };
15837
- }
15838
- if (typeof background === "string") {
15839
- if (background in presetsObj) {
15840
- return { preset: background, background: true };
15841
- }
15842
- if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
15843
- return { files: background, background: true };
15844
- }
15845
- return { color: background, background: true };
15846
- }
15847
- if (background.isColor) {
15848
- return { color: background, background: true };
15849
- }
15850
- return null;
15851
- }, [background]);
14988
+ const backgroundProps = React__namespace.useMemo(() => parseBackground(background), [background]);
15852
14989
  const hasInitialSizeRef = React__namespace.useRef(false);
15853
14990
  const measureConfig = React__namespace.useMemo(() => {
15854
14991
  if (!hasInitialSizeRef.current) {
@@ -15890,6 +15027,7 @@ function CanvasImpl({
15890
15027
  const handleDropMissed = useMutableCallback(onDropMissed);
15891
15028
  const [block, setBlock] = React__namespace.useState(false);
15892
15029
  const [error, setError] = React__namespace.useState(false);
15030
+ const [fallbackVisible, setFallbackVisible] = React__namespace.useState(false);
15893
15031
  if (block) throw block;
15894
15032
  if (error) throw error;
15895
15033
  const root = React__namespace.useRef(null);
@@ -15897,6 +15035,7 @@ function CanvasImpl({
15897
15035
  const unsubscribeErrorRef = React__namespace.useRef(null);
15898
15036
  useIsomorphicLayoutEffect(() => {
15899
15037
  effectActiveRef.current = true;
15038
+ if (fallbackVisible) return;
15900
15039
  const canvas = canvasRef.current;
15901
15040
  if (effectiveSize.width > 0 && effectiveSize.height > 0 && canvas) {
15902
15041
  if (!root.current) {
@@ -15917,7 +15056,7 @@ function CanvasImpl({
15917
15056
  }
15918
15057
  async function run() {
15919
15058
  if (!effectActiveRef.current || !root.current) return;
15920
- await root.current.configure({
15059
+ const configured = await root.current.configure({
15921
15060
  id,
15922
15061
  primaryCanvas,
15923
15062
  scheduler,
@@ -15932,6 +15071,8 @@ function CanvasImpl({
15932
15071
  performance,
15933
15072
  raycaster,
15934
15073
  camera,
15074
+ autoUpdateFrustum,
15075
+ occlusion,
15935
15076
  size: effectiveSize,
15936
15077
  // Store size props for reset functionality
15937
15078
  _sizeProps: width !== void 0 || height !== void 0 ? { width, height } : null,
@@ -15956,8 +15097,20 @@ function CanvasImpl({
15956
15097
  }
15957
15098
  onCreated?.(state);
15958
15099
  }
15959
- });
15960
- if (!effectActiveRef.current || !root.current) return;
15100
+ }).then(
15101
+ () => true,
15102
+ // Renderer setup failed (e.g. no WebGL/WebGPU support). The `fallback` prop lives
15103
+ // inside <canvas>, which browsers don't display, so surface it as visible DOM
15104
+ // instead; with no fallback, rethrow to an external error boundary. (#3757)
15105
+ (setupError) => {
15106
+ if (effectActiveRef.current) {
15107
+ if (fallback != null) setFallbackVisible(true);
15108
+ else setError(setupError);
15109
+ }
15110
+ return false;
15111
+ }
15112
+ );
15113
+ if (!configured || !effectActiveRef.current || !root.current) return;
15961
15114
  root.current.render(
15962
15115
  /* @__PURE__ */ jsxRuntime.jsx(Bridge, { children: /* @__PURE__ */ jsxRuntime.jsx(ErrorBoundary, { set: setError, children: /* @__PURE__ */ jsxRuntime.jsxs(React__namespace.Suspense, { fallback: /* @__PURE__ */ jsxRuntime.jsx(Block, { set: setBlock }), children: [
15963
15116
  backgroundProps && /* @__PURE__ */ jsxRuntime.jsx(Environment, { ...backgroundProps }),
@@ -15991,14 +15144,7 @@ function CanvasImpl({
15991
15144
  const handleHMR = () => {
15992
15145
  queueMicrotask(() => {
15993
15146
  const rootEntry = _roots.get(canvas);
15994
- if (rootEntry?.store) {
15995
- console.log("[R3F] HMR detected \u2014 rebuilding nodes/uniforms");
15996
- rootEntry.store.setState((state) => ({
15997
- nodes: {},
15998
- uniforms: {},
15999
- _hmrVersion: state._hmrVersion + 1
16000
- }));
16001
- }
15147
+ if (rootEntry?.store) clearHmrCaches(rootEntry.store);
16002
15148
  });
16003
15149
  };
16004
15150
  if (typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)) }) !== "undefined" && undefined) {
@@ -16027,7 +15173,11 @@ function CanvasImpl({
16027
15173
  ...style
16028
15174
  },
16029
15175
  ...props,
16030
- children: /* @__PURE__ */ jsxRuntime.jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsxRuntime.jsx(
15176
+ children: fallbackVisible ? (
15177
+ // Renderer setup failed: render the fallback as visible DOM. Inside <canvas> (below)
15178
+ // it exists in the tree but browsers never paint it, which is the whole bug (#3757).
15179
+ fallback
15180
+ ) : /* @__PURE__ */ jsxRuntime.jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsxRuntime.jsx(
16031
15181
  "canvas",
16032
15182
  {
16033
15183
  ref: canvasRef,
@@ -16046,6 +15196,8 @@ function Canvas(props) {
16046
15196
 
16047
15197
  extend(THREE);
16048
15198
 
15199
+ exports.Scheduler = scheduler.Scheduler;
15200
+ exports.getScheduler = scheduler.getScheduler;
16049
15201
  exports.Block = Block;
16050
15202
  exports.Canvas = Canvas;
16051
15203
  exports.Environment = Environment;
@@ -16061,10 +15213,8 @@ exports.R3F_BUILD_LEGACY = R3F_BUILD_LEGACY;
16061
15213
  exports.R3F_BUILD_WEBGPU = R3F_BUILD_WEBGPU;
16062
15214
  exports.REACT_INTERNAL_PROPS = REACT_INTERNAL_PROPS;
16063
15215
  exports.RESERVED_PROPS = RESERVED_PROPS;
16064
- exports.Scheduler = Scheduler;
16065
15216
  exports.Texture = Texture;
16066
15217
  exports._roots = _roots;
16067
- exports.act = act;
16068
15218
  exports.addAfterEffect = addAfterEffect;
16069
15219
  exports.addEffect = addEffect;
16070
15220
  exports.addTail = addTail;
@@ -16091,7 +15241,6 @@ exports.getInstanceProps = getInstanceProps;
16091
15241
  exports.getPrimary = getPrimary;
16092
15242
  exports.getPrimaryIds = getPrimaryIds;
16093
15243
  exports.getRootState = getRootState;
16094
- exports.getScheduler = getScheduler;
16095
15244
  exports.getUuidPrefix = getUuidPrefix;
16096
15245
  exports.hasConstructor = hasConstructor;
16097
15246
  exports.hasPrimary = hasPrimary;