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

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.
@@ -14,6 +14,7 @@ const UltraHDRLoader_js = require('three/examples/jsm/loaders/UltraHDRLoader.js'
14
14
  const gainmapJs = require('@monogrid/gainmap-js');
15
15
  const Tb = require('scheduler');
16
16
  const traditional = require('zustand/traditional');
17
+ const scheduler = require('@pmndrs/scheduler');
17
18
  const suspendReact = require('suspend-react');
18
19
  const lite = require('dequal/lite');
19
20
  require('zustand/shallow');
@@ -62,13 +63,16 @@ const WebGLRenderer = class WebGLRenderer2 {
62
63
  }
63
64
  };
64
65
  const WebGLRenderTarget = null;
66
+ const WebGLCubeRenderTarget = null;
65
67
 
66
68
  const THREE = /*#__PURE__*/_mergeNamespaces({
67
69
  __proto__: null,
70
+ CubeRenderTargetCompat: webgpu.CubeRenderTarget,
68
71
  Inspector: Inspector_js.Inspector,
69
72
  R3F_BUILD_LEGACY: R3F_BUILD_LEGACY,
70
73
  R3F_BUILD_WEBGPU: R3F_BUILD_WEBGPU,
71
74
  RenderTargetCompat: webgpu.RenderTarget,
75
+ WebGLCubeRenderTarget: WebGLCubeRenderTarget,
72
76
  WebGLRenderTarget: WebGLRenderTarget,
73
77
  WebGLRenderer: WebGLRenderer
74
78
  }, [webgpu__namespace]);
@@ -342,15 +346,16 @@ function EnvironmentPortal({
342
346
  preset = void 0,
343
347
  extensions
344
348
  }) {
345
- const gl = fiber.useThree((state) => state.gl);
349
+ const renderer = fiber.useThree((state) => state.renderer);
350
+ const isLegacy = fiber.useThree((state) => state.isLegacy);
346
351
  const defaultScene = fiber.useThree((state) => state.scene);
347
352
  const camera = React__namespace.useRef(null);
348
353
  const [virtualScene] = React__namespace.useState(() => new webgpu.Scene());
349
354
  const fbo = React__namespace.useMemo(() => {
350
- const fbo2 = new webgpu.WebGLCubeRenderTarget(resolution);
355
+ const fbo2 = isLegacy ? new WebGLCubeRenderTarget(resolution) : new webgpu.CubeRenderTarget(resolution);
351
356
  fbo2.texture.type = webgpu.HalfFloatType;
352
357
  return fbo2;
353
- }, [resolution]);
358
+ }, [resolution, isLegacy]);
354
359
  React__namespace.useEffect(() => {
355
360
  return () => {
356
361
  fbo.dispose();
@@ -358,10 +363,10 @@ function EnvironmentPortal({
358
363
  }, [fbo]);
359
364
  React__namespace.useLayoutEffect(() => {
360
365
  if (frames === 1) {
361
- const autoClear = gl.autoClear;
362
- gl.autoClear = true;
363
- camera.current.update(gl, virtualScene);
364
- gl.autoClear = autoClear;
366
+ const autoClear = renderer.autoClear;
367
+ renderer.autoClear = true;
368
+ camera.current.update(renderer, virtualScene);
369
+ renderer.autoClear = autoClear;
365
370
  }
366
371
  return setEnvProps(background, scene, defaultScene, fbo.texture, {
367
372
  backgroundBlurriness: blur ?? backgroundBlurriness,
@@ -378,7 +383,7 @@ function EnvironmentPortal({
378
383
  defaultScene,
379
384
  background,
380
385
  frames,
381
- gl,
386
+ renderer,
382
387
  blur,
383
388
  backgroundBlurriness,
384
389
  backgroundIntensity,
@@ -389,10 +394,10 @@ function EnvironmentPortal({
389
394
  let count = 1;
390
395
  fiber.useFrame(() => {
391
396
  if (frames === Infinity || count < frames) {
392
- const autoClear = gl.autoClear;
393
- gl.autoClear = true;
394
- camera.current.update(gl, virtualScene);
395
- gl.autoClear = autoClear;
397
+ const autoClear = renderer.autoClear;
398
+ renderer.autoClear = true;
399
+ camera.current.update(renderer, virtualScene);
400
+ renderer.autoClear = autoClear;
396
401
  count++;
397
402
  }
398
403
  });
@@ -456,9 +461,9 @@ function Environment(props) {
456
461
  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 });
457
462
  }
458
463
 
459
- var __defProp$3 = Object.defineProperty;
460
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
461
- var __publicField$3 = (obj, key, value) => __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
464
+ var __defProp$1 = Object.defineProperty;
465
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
466
+ var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
462
467
  const act = React__namespace["act"];
463
468
  const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React__namespace.useLayoutEffect : React__namespace.useEffect;
464
469
  function useMutableCallback(fn) {
@@ -490,7 +495,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
490
495
  return _a = class extends React__namespace.Component {
491
496
  constructor() {
492
497
  super(...arguments);
493
- __publicField$3(this, "state", { error: false });
498
+ __publicField$1(this, "state", { error: false });
494
499
  }
495
500
  componentDidCatch(err) {
496
501
  this.props.set(err);
@@ -498,7 +503,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
498
503
  render() {
499
504
  return this.state.error ? null : this.props.children;
500
505
  }
501
- }, __publicField$3(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
506
+ }, __publicField$1(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
502
507
  })();
503
508
 
504
509
  const is = {
@@ -635,8 +640,7 @@ function prepare(target, root, type, props) {
635
640
  object,
636
641
  eventCount: 0,
637
642
  handlers: {},
638
- isHidden: false,
639
- deferredRefs: []
643
+ isHidden: false
640
644
  };
641
645
  if (object) object.__r3f = instance;
642
646
  }
@@ -793,6 +797,17 @@ function unregisterVisibility(store, object) {
793
797
  internal.visibilityRegistry.delete(object.uuid);
794
798
  internal.occlusionCache.delete(object);
795
799
  }
800
+ function updateVisibilityHandlers(store, object, handlers) {
801
+ const { internal } = store.getState();
802
+ const entry = internal.visibilityRegistry.get(object.uuid);
803
+ if (!entry) return false;
804
+ entry.handlers = handlers;
805
+ if ((handlers.onOccluded || handlers.onVisible) && !internal.occlusionEnabled) {
806
+ object.occlusionTest = true;
807
+ enableOcclusion(store);
808
+ }
809
+ return true;
810
+ }
796
811
  function checkVisibility(state) {
797
812
  const { internal, camera } = state;
798
813
  const registry = internal.visibilityRegistry;
@@ -980,10 +995,7 @@ function applyProps(object, props) {
980
995
  continue;
981
996
  }
982
997
  if (value === void 0) continue;
983
- if (isFromRef(value)) {
984
- instance?.deferredRefs?.push({ prop, ref: value[FROM_REF] });
985
- continue;
986
- }
998
+ if (isFromRef(value)) continue;
987
999
  if (isOnce(value)) {
988
1000
  if (instance?.appliedOnce?.has(prop)) continue;
989
1001
  if (instance) {
@@ -1019,6 +1031,19 @@ function applyProps(object, props) {
1019
1031
  } else if (isVectorLike(target) && is.num(value)) {
1020
1032
  if ("setScalar" in target && typeof target.setScalar === "function") target.setScalar(value);
1021
1033
  else target.set(value);
1034
+ } else if (root instanceof webgpu.ShaderMaterial && key === "uniforms" && is.obj(value)) {
1035
+ if (!is.obj(root.uniforms)) root.uniforms = {};
1036
+ const uniforms = root.uniforms;
1037
+ const nextUniforms = value;
1038
+ for (const name in nextUniforms) {
1039
+ const uniform = nextUniforms[name];
1040
+ const targetUniform = uniforms[name];
1041
+ if (targetUniform) Object.assign(targetUniform, uniform);
1042
+ else {
1043
+ const nextUniform = uniform instanceof webgpu.Uniform ? uniform.clone() : new webgpu.Uniform(uniform.value);
1044
+ uniforms[name] = nextUniform;
1045
+ }
1046
+ }
1022
1047
  } else {
1023
1048
  root[key] = value;
1024
1049
  if (key.endsWith("Node") && root.isMaterial) {
@@ -1037,6 +1062,9 @@ function applyProps(object, props) {
1037
1062
  if (instance.eventCount && object2.raycast !== null) {
1038
1063
  rootState.internal.interaction.push(object2);
1039
1064
  }
1065
+ }
1066
+ if (instance?.parent && rootState?.internal && instance.object?.isObject3D) {
1067
+ const object2 = instance.object;
1040
1068
  const root = findInitialRoot(instance);
1041
1069
  const visibilityHandlers = {
1042
1070
  onFramed: instance.handlers.onFramed,
@@ -1044,7 +1072,9 @@ function applyProps(object, props) {
1044
1072
  onVisible: instance.handlers.onVisible
1045
1073
  };
1046
1074
  if (hasVisibilityHandlers(visibilityHandlers)) {
1047
- registerVisibility(root, object2, visibilityHandlers);
1075
+ if (!updateVisibilityHandlers(root, object2, visibilityHandlers)) {
1076
+ registerVisibility(root, object2, visibilityHandlers);
1077
+ }
1048
1078
  } else {
1049
1079
  unregisterVisibility(root, object2);
1050
1080
  }
@@ -1572,6 +1602,7 @@ function createPointerEvents(store) {
1572
1602
  set((state) => ({ events: { ...state.events, connected: void 0 } }));
1573
1603
  }
1574
1604
  },
1605
+ // PREVIEW (A8): the XR pointer registration API may change before stable.
1575
1606
  registerPointer: (config) => {
1576
1607
  const pointerId = nextXRPointerId++;
1577
1608
  xrPointers.set(pointerId, config);
@@ -1658,1036 +1689,11 @@ function notifyAlpha({ message, link }) {
1658
1689
  }
1659
1690
  }
1660
1691
 
1661
- var __defProp$2 = Object.defineProperty;
1662
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1663
- var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
1664
- const DEFAULT_PHASES = ["start", "input", "physics", "update", "render", "finish"];
1665
- class PhaseGraph {
1666
- constructor() {
1667
- /** Ordered list of phase nodes */
1668
- __publicField$2(this, "phases", []);
1669
- /** Quick lookup by name */
1670
- __publicField$2(this, "phaseMap", /* @__PURE__ */ new Map());
1671
- /** Cached ordered names (invalidated on changes) */
1672
- __publicField$2(this, "orderedNamesCache", null);
1673
- this.initializeDefaultPhases();
1674
- }
1675
- //* Initialization --------------------------------
1676
- initializeDefaultPhases() {
1677
- for (const name of DEFAULT_PHASES) {
1678
- const node = { name, isAutoGenerated: false };
1679
- this.phases.push(node);
1680
- this.phaseMap.set(name, node);
1681
- }
1682
- this.invalidateCache();
1683
- }
1684
- //* Public API --------------------------------
1685
- /**
1686
- * Add a named phase to the graph
1687
- * @param name - Phase name (must be unique)
1688
- * @param options - Position options (before or after another phase)
1689
- */
1690
- addPhase(name, options = {}) {
1691
- if (this.phaseMap.has(name)) {
1692
- console.warn(`[useFrame] Phase "${name}" already exists`);
1693
- return;
1694
- }
1695
- const { before, after } = options;
1696
- const node = { name, isAutoGenerated: false };
1697
- let insertIndex = this.phases.length;
1698
- const targetIndex = this.getPhaseIndex(before ?? after);
1699
- if (targetIndex !== -1) {
1700
- insertIndex = before ? targetIndex : targetIndex + 1;
1701
- } else {
1702
- const constraintType = before ? "before" : "after";
1703
- console.warn(`[useFrame] Phase "${before ?? after}" not found for '${constraintType}' constraint`);
1704
- }
1705
- this.phases.splice(insertIndex, 0, node);
1706
- this.phaseMap.set(name, node);
1707
- this.invalidateCache();
1708
- }
1709
- /**
1710
- * Get ordered list of phase names
1711
- */
1712
- getOrderedPhases() {
1713
- if (this.orderedNamesCache === null) this.orderedNamesCache = this.phases.map((p) => p.name);
1714
- return this.orderedNamesCache;
1715
- }
1716
- /**
1717
- * Check if a phase exists
1718
- */
1719
- hasPhase(name) {
1720
- return this.phaseMap.has(name);
1721
- }
1722
- /**
1723
- * Get the index of a phase (-1 if not found)
1724
- */
1725
- getPhaseIndex(name) {
1726
- if (!name) return -1;
1727
- return this.phases.findIndex((p) => p.name === name);
1728
- }
1729
- /**
1730
- * Ensure a phase exists, creating an auto-generated one if needed.
1731
- * Used for resolving before/after constraints.
1732
- *
1733
- * @param name - The phase name to ensure exists
1734
- * @returns The phase name (may be auto-generated like 'before:render')
1735
- */
1736
- ensurePhase(name) {
1737
- if (this.phaseMap.has(name)) return name;
1738
- const node = { name, isAutoGenerated: true };
1739
- this.phases.push(node);
1740
- this.phaseMap.set(name, node);
1741
- this.invalidateCache();
1742
- return name;
1743
- }
1744
- /**
1745
- * Resolve where a job with before/after constraints should go.
1746
- * Creates auto-generated phases if needed.
1747
- *
1748
- * @param before - Phase(s) to run before
1749
- * @param after - Phase(s) to run after
1750
- * @returns The resolved phase name
1751
- */
1752
- resolveConstraintPhase(before, after) {
1753
- const beforeArr = before ? Array.isArray(before) ? before : [before] : [];
1754
- const afterArr = after ? Array.isArray(after) ? after : [after] : [];
1755
- if (beforeArr.length > 0) {
1756
- return this.ensureAutoPhase(beforeArr[0], "before", 0);
1757
- }
1758
- if (afterArr.length > 0) {
1759
- return this.ensureAutoPhase(afterArr[0], "after", 1);
1760
- }
1761
- return "update";
1762
- }
1763
- /**
1764
- * Ensure an auto-generated phase exists relative to a target phase.
1765
- * Creates the phase if it doesn't exist, inserting it at the correct position.
1766
- *
1767
- * @param target - The target phase name to position relative to
1768
- * @param prefix - Prefix for auto-generated phase name ('before' or 'after')
1769
- * @param offset - Insertion offset (0 for before, 1 for after)
1770
- * @returns The auto-generated phase name
1771
- */
1772
- ensureAutoPhase(target, prefix, offset) {
1773
- const autoName = `${prefix}:${target}`;
1774
- if (this.phaseMap.has(autoName)) return autoName;
1775
- const node = { name: autoName, isAutoGenerated: true };
1776
- const targetIndex = this.getPhaseIndex(target);
1777
- if (targetIndex !== -1) this.phases.splice(targetIndex + offset, 0, node);
1778
- else this.phases.push(node);
1779
- this.phaseMap.set(autoName, node);
1780
- this.invalidateCache();
1781
- return autoName;
1782
- }
1783
- // Internal --------------------------------
1784
- invalidateCache() {
1785
- this.orderedNamesCache = null;
1786
- }
1787
- }
1788
-
1789
- function rebuildSortedJobs(jobs, phaseGraph) {
1790
- const orderedPhases = phaseGraph.getOrderedPhases();
1791
- const buckets = /* @__PURE__ */ new Map();
1792
- for (const phase of orderedPhases) {
1793
- buckets.set(phase, []);
1794
- }
1795
- for (const job of jobs.values()) {
1796
- if (!job.enabled) continue;
1797
- let bucket = buckets.get(job.phase);
1798
- if (!bucket) {
1799
- bucket = [];
1800
- buckets.set(job.phase, bucket);
1801
- }
1802
- bucket.push(job);
1803
- }
1804
- const sortedBuckets = [];
1805
- for (const phase of orderedPhases) {
1806
- const bucket = buckets.get(phase);
1807
- if (!bucket || bucket.length === 0) continue;
1808
- bucket.sort((a, b) => {
1809
- if (a.priority !== b.priority) return b.priority - a.priority;
1810
- return a.index - b.index;
1811
- });
1812
- sortedBuckets.push(hasCrossJobConstraints(bucket) ? topologicalSort(bucket) : bucket);
1813
- }
1814
- for (const [phase, bucket] of buckets) {
1815
- if (!orderedPhases.includes(phase) && bucket.length > 0) {
1816
- bucket.sort((a, b) => {
1817
- if (a.priority !== b.priority) return b.priority - a.priority;
1818
- return a.index - b.index;
1819
- });
1820
- sortedBuckets.push(bucket);
1821
- }
1822
- }
1823
- return sortedBuckets.flat();
1824
- }
1825
- function hasCrossJobConstraints(bucket) {
1826
- const jobIds = new Set(bucket.map((j) => j.id));
1827
- for (const job of bucket) {
1828
- for (const ref of job.before) {
1829
- if (jobIds.has(ref)) return true;
1830
- }
1831
- for (const ref of job.after) {
1832
- if (jobIds.has(ref)) return true;
1833
- }
1834
- }
1835
- return false;
1836
- }
1837
- function topologicalSort(jobs) {
1838
- const n = jobs.length;
1839
- if (n <= 1) return jobs;
1840
- const jobMap = /* @__PURE__ */ new Map();
1841
- const inDegree = /* @__PURE__ */ new Map();
1842
- const adjacency = /* @__PURE__ */ new Map();
1843
- for (const job of jobs) {
1844
- jobMap.set(job.id, job);
1845
- inDegree.set(job.id, 0);
1846
- adjacency.set(job.id, []);
1847
- }
1848
- for (const job of jobs) {
1849
- for (const ref of job.before) {
1850
- if (jobMap.has(ref)) {
1851
- adjacency.get(job.id).push(ref);
1852
- inDegree.set(ref, inDegree.get(ref) + 1);
1853
- }
1854
- }
1855
- for (const ref of job.after) {
1856
- if (jobMap.has(ref)) {
1857
- adjacency.get(ref).push(job.id);
1858
- inDegree.set(job.id, inDegree.get(job.id) + 1);
1859
- }
1860
- }
1861
- }
1862
- const queue = [];
1863
- for (const job of jobs) {
1864
- if (inDegree.get(job.id) === 0) {
1865
- queue.push(job);
1866
- }
1867
- }
1868
- queue.sort((a, b) => {
1869
- if (a.priority !== b.priority) return b.priority - a.priority;
1870
- return a.index - b.index;
1871
- });
1872
- const result = [];
1873
- while (queue.length > 0) {
1874
- const job = queue.shift();
1875
- result.push(job);
1876
- const neighbors = adjacency.get(job.id) || [];
1877
- for (const neighborId of neighbors) {
1878
- const newDegree = inDegree.get(neighborId) - 1;
1879
- inDegree.set(neighborId, newDegree);
1880
- if (newDegree === 0) {
1881
- const neighbor = jobMap.get(neighborId);
1882
- insertSorted(queue, neighbor);
1883
- }
1884
- }
1885
- }
1886
- if (result.length !== n) {
1887
- console.warn("[useFrame] Circular dependency detected in job constraints");
1888
- const resultIds = new Set(result.map((j) => j.id));
1889
- for (const job of jobs) {
1890
- if (!resultIds.has(job.id)) result.push(job);
1891
- }
1892
- }
1893
- return result;
1894
- }
1895
- function insertSorted(arr, job) {
1896
- let i = 0;
1897
- while (i < arr.length) {
1898
- const cmp = arr[i];
1899
- if (job.priority > cmp.priority || job.priority === cmp.priority && job.index < cmp.index) {
1900
- break;
1901
- }
1902
- i++;
1903
- }
1904
- arr.splice(i, 0, job);
1905
- }
1906
-
1907
- function shouldRun(job, now) {
1908
- if (!job.enabled) return false;
1909
- if (!job.fps) return true;
1910
- const minInterval = 1e3 / job.fps;
1911
- const lastRun = job.lastRun ?? 0;
1912
- const elapsed = now - lastRun;
1913
- if (elapsed < minInterval - 1) return false;
1914
- if (job.drop) {
1915
- job.lastRun = now;
1916
- } else {
1917
- const steps = Math.floor(elapsed / minInterval);
1918
- job.lastRun = lastRun + steps * minInterval;
1919
- if (job.lastRun < now - minInterval) {
1920
- job.lastRun = now;
1921
- }
1922
- }
1923
- return true;
1924
- }
1925
- function resetJobTiming(job) {
1926
- job.lastRun = void 0;
1927
- }
1928
-
1929
- var __defProp$1 = Object.defineProperty;
1930
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1931
- var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1932
- const hmrData = (() => {
1933
- if (typeof process !== "undefined" && process.env.NODE_ENV === "test") return void 0;
1934
- if (typeof import_meta_hot !== "undefined") return import_meta_hot;
1935
- try {
1936
- return (0, eval)("import.meta.hot");
1937
- } catch {
1938
- return void 0;
1939
- }
1940
- })();
1941
- const _Scheduler = class _Scheduler {
1942
- //* Constructor ================================
1943
- constructor() {
1944
- //* Critical State ================================
1945
- __publicField$1(this, "roots", /* @__PURE__ */ new Map());
1946
- __publicField$1(this, "phaseGraph");
1947
- __publicField$1(this, "loopState", {
1948
- running: false,
1949
- rafHandle: null,
1950
- lastTime: null,
1951
- // null = uninitialized, 0+ = valid timestamp
1952
- frameCount: 0,
1953
- elapsedTime: 0,
1954
- createdAt: performance.now()
1955
- });
1956
- __publicField$1(this, "stoppedTime", 0);
1957
- //* Private State ================================
1958
- __publicField$1(this, "nextRootIndex", 0);
1959
- __publicField$1(this, "globalBeforeJobs", /* @__PURE__ */ new Map());
1960
- __publicField$1(this, "globalAfterJobs", /* @__PURE__ */ new Map());
1961
- __publicField$1(this, "nextGlobalIndex", 0);
1962
- __publicField$1(this, "idleCallbacks", /* @__PURE__ */ new Set());
1963
- __publicField$1(this, "nextJobIndex", 0);
1964
- __publicField$1(this, "jobStateListeners", /* @__PURE__ */ new Map());
1965
- __publicField$1(this, "pendingFrames", 0);
1966
- __publicField$1(this, "_frameloop", "always");
1967
- //* Independent Mode & Error Handling State ================================
1968
- __publicField$1(this, "_independent", false);
1969
- __publicField$1(this, "errorHandler", null);
1970
- __publicField$1(this, "rootReadyCallbacks", /* @__PURE__ */ new Set());
1971
- //* Core Loop Execution Methods ================================
1972
- /**
1973
- * Main RAF loop callback.
1974
- * Executes frame, handles demand mode, and schedules next frame.
1975
- * @param {number} timestamp - RAF timestamp in milliseconds
1976
- * @returns {void}
1977
- * @private
1978
- */
1979
- __publicField$1(this, "loop", (timestamp) => {
1980
- if (!this.loopState.running) return;
1981
- this.executeFrame(timestamp);
1982
- if (this._frameloop === "demand") {
1983
- this.pendingFrames = Math.max(0, this.pendingFrames - 1);
1984
- if (this.pendingFrames === 0) {
1985
- this.notifyIdle(timestamp);
1986
- return this.stop();
1987
- }
1988
- }
1989
- this.loopState.rafHandle = requestAnimationFrame(this.loop);
1990
- });
1991
- this.phaseGraph = new PhaseGraph();
1992
- }
1993
- static get instance() {
1994
- return globalThis[_Scheduler.INSTANCE_KEY] ?? null;
1995
- }
1996
- static set instance(value) {
1997
- globalThis[_Scheduler.INSTANCE_KEY] = value;
1998
- }
1999
- /**
2000
- * Get the global scheduler instance (creates if doesn't exist).
2001
- * Uses HMR data to preserve instance across hot reloads.
2002
- * @returns {Scheduler} The singleton scheduler instance
2003
- */
2004
- static get() {
2005
- if (!_Scheduler.instance && hmrData?.data?.scheduler) {
2006
- _Scheduler.instance = hmrData.data.scheduler;
2007
- }
2008
- if (!_Scheduler.instance) {
2009
- _Scheduler.instance = new _Scheduler();
2010
- if (hmrData?.data) {
2011
- hmrData.data.scheduler = _Scheduler.instance;
2012
- }
2013
- }
2014
- return _Scheduler.instance;
2015
- }
2016
- /**
2017
- * Reset the singleton instance. Stops the loop and clears all state.
2018
- * Primarily used for testing to ensure clean state between tests.
2019
- * @returns {void}
2020
- */
2021
- static reset() {
2022
- if (_Scheduler.instance) {
2023
- _Scheduler.instance.stop();
2024
- _Scheduler.instance = null;
2025
- }
2026
- if (hmrData?.data) {
2027
- hmrData.data.scheduler = null;
2028
- }
2029
- }
2030
- //* Getters & Setters ================================
2031
- get phases() {
2032
- return this.phaseGraph.getOrderedPhases();
2033
- }
2034
- get frameloop() {
2035
- return this._frameloop;
2036
- }
2037
- set frameloop(mode) {
2038
- if (this._frameloop === mode) return;
2039
- const wasAlways = this._frameloop === "always";
2040
- this._frameloop = mode;
2041
- if (mode === "always" && !this.loopState.running && this.roots.size > 0) this.start();
2042
- else if (mode !== "always" && wasAlways) this.stop();
2043
- }
2044
- get isRunning() {
2045
- return this.loopState.running;
2046
- }
2047
- get isReady() {
2048
- return this.roots.size > 0;
2049
- }
2050
- get independent() {
2051
- return this._independent;
2052
- }
2053
- set independent(value) {
2054
- this._independent = value;
2055
- if (value) this.ensureDefaultRoot();
2056
- }
2057
- //* Root Management Methods ================================
2058
- /**
2059
- * Register a root (Canvas) with the scheduler.
2060
- * The first root to register starts the RAF loop (if frameloop='always').
2061
- * @param {string} id - Unique identifier for this root
2062
- * @param {RootOptions} [options] - Optional configuration with getState and onError callbacks
2063
- * @returns {() => void} Unsubscribe function to remove this root
2064
- */
2065
- registerRoot(id, options = {}) {
2066
- if (this.roots.has(id)) {
2067
- console.warn(`[Scheduler] Root "${id}" already registered`);
2068
- return () => this.unregisterRoot(id);
2069
- }
2070
- const entry = {
2071
- id,
2072
- getState: options.getState ?? (() => ({})),
2073
- jobs: /* @__PURE__ */ new Map(),
2074
- sortedJobs: [],
2075
- needsRebuild: false
2076
- };
2077
- if (options.onError) {
2078
- this.errorHandler = options.onError;
2079
- }
2080
- this.roots.set(id, entry);
2081
- if (this.roots.size === 1) {
2082
- this.notifyRootReady();
2083
- if (this._frameloop === "always") this.start();
2084
- }
2085
- return () => this.unregisterRoot(id);
2086
- }
2087
- /**
2088
- * Unregister a root from the scheduler.
2089
- * Cleans up all job state listeners for this root's jobs.
2090
- * The last root to unregister stops the RAF loop.
2091
- * @param {string} id - The root ID to unregister
2092
- * @returns {void}
2093
- */
2094
- unregisterRoot(id) {
2095
- const root = this.roots.get(id);
2096
- if (!root) return;
2097
- for (const jobId of root.jobs.keys()) {
2098
- this.jobStateListeners.delete(jobId);
2099
- }
2100
- this.roots.delete(id);
2101
- if (this.roots.size === 0) {
2102
- this.stop();
2103
- this.errorHandler = null;
2104
- }
2105
- }
2106
- /**
2107
- * Subscribe to be notified when a root becomes available.
2108
- * Fires immediately if a root already exists.
2109
- * @param {() => void} callback - Function called when first root registers
2110
- * @returns {() => void} Unsubscribe function
2111
- */
2112
- onRootReady(callback) {
2113
- if (this.roots.size > 0) {
2114
- callback();
2115
- return () => {
2116
- };
2117
- }
2118
- this.rootReadyCallbacks.add(callback);
2119
- return () => this.rootReadyCallbacks.delete(callback);
2120
- }
2121
- /**
2122
- * Notify all registered root-ready callbacks.
2123
- * Called when the first root registers.
2124
- * @returns {void}
2125
- * @private
2126
- */
2127
- notifyRootReady() {
2128
- for (const cb of this.rootReadyCallbacks) {
2129
- try {
2130
- cb();
2131
- } catch (error) {
2132
- console.error("[Scheduler] Error in root-ready callback:", error);
2133
- }
2134
- }
2135
- this.rootReadyCallbacks.clear();
2136
- }
2137
- /**
2138
- * Ensure a default root exists for independent mode.
2139
- * Creates a minimal root with no state provider.
2140
- * @returns {void}
2141
- * @private
2142
- */
2143
- ensureDefaultRoot() {
2144
- if (!this.roots.has("__default__")) {
2145
- this.registerRoot("__default__");
2146
- }
2147
- }
2148
- /**
2149
- * Trigger error handling for job errors.
2150
- * Uses the bound error handler if available, otherwise logs to console.
2151
- * @param {Error} error - The error to handle
2152
- * @returns {void}
2153
- */
2154
- triggerError(error) {
2155
- if (this.errorHandler) this.errorHandler(error);
2156
- else console.error("[Scheduler]", error);
2157
- }
2158
- //* Phase Management Methods ================================
2159
- /**
2160
- * Add a named phase to the scheduler's execution order.
2161
- * Marks all roots for rebuild to incorporate the new phase.
2162
- * @param {string} name - The phase name (e.g., 'physics', 'postprocess')
2163
- * @param {AddPhaseOptions} [options] - Positioning options (before/after other phases)
2164
- * @returns {void}
2165
- * @example
2166
- * scheduler.addPhase('physics', { before: 'update' });
2167
- * scheduler.addPhase('postprocess', { after: 'render' });
2168
- */
2169
- addPhase(name, options) {
2170
- this.phaseGraph.addPhase(name, options);
2171
- for (const root of this.roots.values()) {
2172
- root.needsRebuild = true;
2173
- }
2174
- }
2175
- /**
2176
- * Check if a phase exists in the scheduler.
2177
- * @param {string} name - The phase name to check
2178
- * @returns {boolean} True if the phase exists
2179
- */
2180
- hasPhase(name) {
2181
- return this.phaseGraph.hasPhase(name);
2182
- }
2183
- //* Global Job Registration Methods (Deprecated APIs) ================================
2184
- /**
2185
- * Register a global job that runs once per frame (not per-root).
2186
- * Used internally by deprecated addEffect/addAfterEffect APIs.
2187
- * @param {'before' | 'after'} phase - When to run: 'before' all roots or 'after' all roots
2188
- * @param {string} id - Unique identifier for this global job
2189
- * @param {(timestamp: number) => void} callback - Function called each frame with RAF timestamp
2190
- * @returns {() => void} Unsubscribe function to remove this global job
2191
- * @deprecated Use useFrame with phases instead
2192
- */
2193
- registerGlobal(phase, id, callback) {
2194
- const job = { id, callback };
2195
- if (phase === "before") {
2196
- this.globalBeforeJobs.set(id, job);
2197
- } else {
2198
- this.globalAfterJobs.set(id, job);
2199
- }
2200
- return () => {
2201
- if (phase === "before") this.globalBeforeJobs.delete(id);
2202
- else this.globalAfterJobs.delete(id);
2203
- };
2204
- }
2205
- //* Idle Callback Methods (Deprecated API) ================================
2206
- /**
2207
- * Register an idle callback that fires when the loop stops.
2208
- * Used internally by deprecated addTail API.
2209
- * @param {(timestamp: number) => void} callback - Function called when loop becomes idle
2210
- * @returns {() => void} Unsubscribe function to remove this idle callback
2211
- * @deprecated Use demand mode with invalidate() instead
2212
- */
2213
- onIdle(callback) {
2214
- this.idleCallbacks.add(callback);
2215
- return () => this.idleCallbacks.delete(callback);
2216
- }
2217
- /**
2218
- * Notify all registered idle callbacks.
2219
- * Called when the loop stops in demand mode.
2220
- * @param {number} timestamp - The RAF timestamp when idle occurred
2221
- * @returns {void}
2222
- * @private
2223
- */
2224
- notifyIdle(timestamp) {
2225
- for (const cb of this.idleCallbacks) {
2226
- try {
2227
- cb(timestamp);
2228
- } catch (error) {
2229
- console.error("[Scheduler] Error in idle callback:", error);
2230
- }
2231
- }
2232
- }
2233
- //* Job Registration & Management Methods ================================
2234
- /**
2235
- * Register a job (frame callback) with a specific root.
2236
- * This is the core registration method used by useFrame internally.
2237
- * @param {FrameNextCallback} callback - The function to call each frame
2238
- * @param {JobOptions & { rootId?: string; system?: boolean }} [options] - Job configuration
2239
- * @param {string} [options.rootId] - Target root ID (defaults to first registered root)
2240
- * @param {string} [options.id] - Unique job ID (auto-generated if not provided)
2241
- * @param {string} [options.phase] - Execution phase (defaults to 'update')
2242
- * @param {number} [options.priority] - Priority within phase (higher = earlier, default 0)
2243
- * @param {number} [options.fps] - FPS throttle limit
2244
- * @param {boolean} [options.drop] - Drop frames when behind (default true)
2245
- * @param {boolean} [options.enabled] - Whether job is active (default true)
2246
- * @param {boolean} [options.system] - Internal flag for system jobs (not user-facing)
2247
- * @returns {() => void} Unsubscribe function to remove this job
2248
- */
2249
- register(callback, options = {}) {
2250
- const rootId = options.rootId;
2251
- const root = rootId ? this.roots.get(rootId) : this.roots.values().next().value;
2252
- if (!root) {
2253
- console.warn("[Scheduler] No root registered. Is this inside a Canvas?");
2254
- return () => {
2255
- };
2256
- }
2257
- const id = options.id ?? this.generateJobId();
2258
- let phase = options.phase ?? "update";
2259
- if (!options.phase && (options.before || options.after)) {
2260
- phase = this.phaseGraph.resolveConstraintPhase(options.before, options.after);
2261
- }
2262
- const before = this.normalizeConstraints(options.before);
2263
- const after = this.normalizeConstraints(options.after);
2264
- const job = {
2265
- id,
2266
- callback,
2267
- phase,
2268
- before,
2269
- after,
2270
- priority: options.priority ?? 0,
2271
- index: this.nextJobIndex++,
2272
- fps: options.fps,
2273
- drop: options.drop ?? true,
2274
- enabled: options.enabled ?? true,
2275
- system: options.system ?? false
2276
- };
2277
- if (root.jobs.has(id)) {
2278
- console.warn(`[useFrame] Job with id "${id}" already exists, replacing`);
2279
- }
2280
- root.jobs.set(id, job);
2281
- root.needsRebuild = true;
2282
- return () => this.unregister(id, root.id);
2283
- }
2284
- /**
2285
- * Unregister a job by its ID.
2286
- * Searches all roots if rootId is not provided.
2287
- * @param {string} id - The job ID to unregister
2288
- * @param {string} [rootId] - Optional root ID to search (searches all if not provided)
2289
- * @returns {void}
2290
- */
2291
- unregister(id, rootId) {
2292
- const root = rootId ? this.roots.get(rootId) : Array.from(this.roots.values()).find((r) => r.jobs.has(id));
2293
- if (root?.jobs.delete(id)) {
2294
- root.needsRebuild = true;
2295
- this.jobStateListeners.delete(id);
2296
- }
2297
- }
2298
- /**
2299
- * Update a job's options dynamically.
2300
- * Searches all roots to find the job by ID.
2301
- * Phase/constraint changes trigger a rebuild of the sorted job list.
2302
- * @param {string} id - The job ID to update
2303
- * @param {Partial<JobOptions>} options - The options to update
2304
- * @returns {void}
2305
- */
2306
- updateJob(id, options) {
2307
- let job;
2308
- let root;
2309
- for (const r of this.roots.values()) {
2310
- job = r.jobs.get(id);
2311
- if (job) {
2312
- root = r;
2313
- break;
2314
- }
2315
- }
2316
- if (!job || !root) return;
2317
- if (options.priority !== void 0) job.priority = options.priority;
2318
- if (options.fps !== void 0) job.fps = options.fps;
2319
- if (options.drop !== void 0) job.drop = options.drop;
2320
- if (options.enabled !== void 0) {
2321
- const wasEnabled = job.enabled;
2322
- job.enabled = options.enabled;
2323
- if (!wasEnabled && job.enabled) resetJobTiming(job);
2324
- if (wasEnabled !== job.enabled) root.needsRebuild = true;
2325
- }
2326
- if (options.phase !== void 0 || options.before !== void 0 || options.after !== void 0) {
2327
- if (options.phase) job.phase = options.phase;
2328
- if (options.before !== void 0) job.before = this.normalizeConstraints(options.before);
2329
- if (options.after !== void 0) job.after = this.normalizeConstraints(options.after);
2330
- root.needsRebuild = true;
2331
- }
2332
- }
2333
- //* Job State Management Methods ================================
2334
- /**
2335
- * Check if a job is currently paused (disabled).
2336
- * @param {string} id - The job ID to check
2337
- * @returns {boolean} True if the job exists and is paused
2338
- */
2339
- isJobPaused(id) {
2340
- for (const root of this.roots.values()) {
2341
- const job = root.jobs.get(id);
2342
- if (job) return !job.enabled;
2343
- }
2344
- return false;
2345
- }
2346
- /**
2347
- * Subscribe to state changes for a specific job.
2348
- * Listener is called when job is paused or resumed.
2349
- * @param {string} id - The job ID to subscribe to
2350
- * @param {() => void} listener - Callback invoked on state changes
2351
- * @returns {() => void} Unsubscribe function
2352
- */
2353
- subscribeJobState(id, listener) {
2354
- if (!this.jobStateListeners.has(id)) {
2355
- this.jobStateListeners.set(id, /* @__PURE__ */ new Set());
2356
- }
2357
- this.jobStateListeners.get(id).add(listener);
2358
- return () => {
2359
- this.jobStateListeners.get(id)?.delete(listener);
2360
- if (this.jobStateListeners.get(id)?.size === 0) {
2361
- this.jobStateListeners.delete(id);
2362
- }
2363
- };
2364
- }
2365
- /**
2366
- * Notify all listeners that a job's state has changed.
2367
- * @param {string} id - The job ID that changed
2368
- * @returns {void}
2369
- * @private
2370
- */
2371
- notifyJobStateChange(id) {
2372
- this.jobStateListeners.get(id)?.forEach((listener) => listener());
2373
- }
2374
- /**
2375
- * Pause a job by ID (sets enabled=false).
2376
- * Notifies any subscribed state listeners.
2377
- * @param {string} id - The job ID to pause
2378
- * @returns {void}
2379
- */
2380
- pauseJob(id) {
2381
- this.updateJob(id, { enabled: false });
2382
- this.notifyJobStateChange(id);
2383
- }
2384
- /**
2385
- * Resume a paused job by ID (sets enabled=true).
2386
- * Resets job timing to prevent frame accumulation.
2387
- * Notifies any subscribed state listeners.
2388
- * @param {string} id - The job ID to resume
2389
- * @returns {void}
2390
- */
2391
- resumeJob(id) {
2392
- this.updateJob(id, { enabled: true });
2393
- this.notifyJobStateChange(id);
2394
- }
2395
- //* Frame Loop Control Methods ================================
2396
- /**
2397
- * Start the requestAnimationFrame loop.
2398
- * Resets timing state (elapsedTime, frameCount) on start.
2399
- * No-op if already running.
2400
- * @returns {void}
2401
- */
2402
- start() {
2403
- if (this.loopState.running) return;
2404
- const { elapsedTime, createdAt } = this.loopState;
2405
- let adjustedCreated = 0;
2406
- if (this.stoppedTime > 0) {
2407
- adjustedCreated = createdAt - (performance.now() - this.stoppedTime);
2408
- this.stoppedTime = 0;
2409
- }
2410
- Object.assign(this.loopState, {
2411
- running: true,
2412
- elapsedTime: elapsedTime ?? 0,
2413
- lastTime: performance.now(),
2414
- createdAt: adjustedCreated > 0 ? adjustedCreated : performance.now(),
2415
- frameCount: 0,
2416
- rafHandle: requestAnimationFrame(this.loop)
2417
- });
2418
- }
2419
- /**
2420
- * Stop the requestAnimationFrame loop.
2421
- * Cancels any pending RAF callback.
2422
- * No-op if not running.
2423
- * @returns {void}
2424
- */
2425
- stop() {
2426
- if (!this.loopState.running) return;
2427
- this.loopState.running = false;
2428
- if (this.loopState.rafHandle !== null) {
2429
- cancelAnimationFrame(this.loopState.rafHandle);
2430
- this.loopState.rafHandle = null;
2431
- }
2432
- this.stoppedTime = performance.now();
2433
- }
2434
- /**
2435
- * Request frames to be rendered in demand mode.
2436
- * Accumulates pending frames (capped at 60) and starts the loop if not running.
2437
- * No-op if frameloop is not 'demand'.
2438
- * @param {number} [frames=1] - Number of frames to request
2439
- * @param {boolean} [stackFrames=false] - Whether to add frames to existing pending count
2440
- * - `false` (default): Sets pending frames to the specified value (replaces existing count)
2441
- * - `true`: Adds frames to existing pending count (useful for accumulating invalidations)
2442
- * @returns {void}
2443
- * @example
2444
- * // Request a single frame render
2445
- * scheduler.invalidate();
2446
- *
2447
- * @example
2448
- * // Request 5 frames (e.g., for animations)
2449
- * scheduler.invalidate(5);
2450
- *
2451
- * @example
2452
- * // Set pending frames to exactly 3 (don't stack with existing)
2453
- * scheduler.invalidate(3, false);
2454
- *
2455
- * @example
2456
- * // Add 2 more frames to existing pending count
2457
- * scheduler.invalidate(2, true);
2458
- */
2459
- invalidate(frames = 1, stackFrames = false) {
2460
- if (this._frameloop !== "demand") return;
2461
- const baseFrames = stackFrames ? this.pendingFrames : 0;
2462
- this.pendingFrames = Math.min(60, baseFrames + frames);
2463
- if (!this.loopState.running && this.pendingFrames > 0) this.start();
2464
- }
2465
- /**
2466
- * Reset timing state for deterministic testing.
2467
- * Preserves jobs and roots but resets lastTime, frameCount, elapsedTime, etc.
2468
- * @returns {void}
2469
- */
2470
- resetTiming() {
2471
- this.loopState.lastTime = null;
2472
- this.loopState.frameCount = 0;
2473
- this.loopState.elapsedTime = 0;
2474
- this.loopState.createdAt = performance.now();
2475
- }
2476
- //* Manual Stepping Methods ================================
2477
- /**
2478
- * Manually execute a single frame for all roots.
2479
- * Useful for frameloop='never' mode or testing scenarios.
2480
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2481
- * @returns {void}
2482
- * @example
2483
- * // Manual control mode
2484
- * scheduler.frameloop = 'never';
2485
- * scheduler.step(); // Execute one frame
2486
- */
2487
- step(timestamp) {
2488
- const now = timestamp ?? performance.now();
2489
- this.executeFrame(now);
2490
- }
2491
- /**
2492
- * Manually execute a single job by its ID.
2493
- * Useful for testing individual job callbacks in isolation.
2494
- * @param {string} id - The job ID to step
2495
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2496
- * @returns {void}
2497
- */
2498
- stepJob(id, timestamp) {
2499
- let job;
2500
- let root;
2501
- for (const r of this.roots.values()) {
2502
- job = r.jobs.get(id);
2503
- if (job) {
2504
- root = r;
2505
- break;
2506
- }
2507
- }
2508
- if (!job || !root) {
2509
- console.warn(`[Scheduler] Job "${id}" not found`);
2510
- return;
2511
- }
2512
- const now = timestamp ?? performance.now();
2513
- const deltaMs = this.loopState.lastTime !== null ? now - this.loopState.lastTime : 0;
2514
- const delta = deltaMs / 1e3;
2515
- const elapsed = now - this.loopState.createdAt;
2516
- const providedState = root.getState?.() ?? {};
2517
- const frameState = {
2518
- ...providedState,
2519
- time: now,
2520
- delta,
2521
- elapsed,
2522
- frame: this.loopState.frameCount
2523
- };
2524
- try {
2525
- job.callback(frameState, delta);
2526
- } catch (error) {
2527
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2528
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2529
- }
2530
- }
2531
- /**
2532
- * Execute a single frame across all roots.
2533
- * Order: globalBefore → each root's jobs → globalAfter
2534
- * @param {number} timestamp - RAF timestamp in milliseconds
2535
- * @returns {void}
2536
- * @private
2537
- */
2538
- executeFrame(timestamp) {
2539
- const deltaMs = this.loopState.lastTime !== null ? timestamp - this.loopState.lastTime : 0;
2540
- const delta = deltaMs / 1e3;
2541
- this.loopState.lastTime = timestamp;
2542
- this.loopState.frameCount++;
2543
- this.loopState.elapsedTime += deltaMs;
2544
- this.runGlobalJobs(this.globalBeforeJobs, timestamp);
2545
- for (const root of this.roots.values()) {
2546
- this.tickRoot(root, timestamp, delta);
2547
- }
2548
- this.runGlobalJobs(this.globalAfterJobs, timestamp);
2549
- }
2550
- /**
2551
- * Run all global jobs from a job map.
2552
- * Catches and logs errors without stopping execution.
2553
- * @param {Map<string, GlobalJob>} jobs - The global jobs map to execute
2554
- * @param {number} timestamp - RAF timestamp in milliseconds
2555
- * @returns {void}
2556
- * @private
2557
- */
2558
- runGlobalJobs(jobs, timestamp) {
2559
- for (const job of jobs.values()) {
2560
- try {
2561
- job.callback(timestamp);
2562
- } catch (error) {
2563
- console.error(`[Scheduler] Error in global job "${job.id}":`, error);
2564
- }
2565
- }
2566
- }
2567
- /**
2568
- * Execute all jobs for a single root in sorted order.
2569
- * Rebuilds sorted job list if needed, then dispatches each job.
2570
- * Errors are caught and propagated via triggerError.
2571
- * @param {RootEntry} root - The root entry to tick
2572
- * @param {number} timestamp - RAF timestamp in milliseconds
2573
- * @param {number} delta - Time since last frame in seconds
2574
- * @returns {void}
2575
- * @private
2576
- */
2577
- tickRoot(root, timestamp, delta) {
2578
- if (root.needsRebuild) {
2579
- root.sortedJobs = rebuildSortedJobs(root.jobs, this.phaseGraph);
2580
- root.needsRebuild = false;
2581
- }
2582
- const providedState = root.getState?.() ?? {};
2583
- const frameState = {
2584
- ...providedState,
2585
- time: timestamp,
2586
- delta,
2587
- elapsed: this.loopState.elapsedTime / 1e3,
2588
- // Convert ms to seconds
2589
- frame: this.loopState.frameCount
2590
- };
2591
- for (const job of root.sortedJobs) {
2592
- if (!shouldRun(job, timestamp)) continue;
2593
- try {
2594
- job.callback(frameState, delta);
2595
- } catch (error) {
2596
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2597
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2598
- }
2599
- }
2600
- }
2601
- //* Debug & Inspection Methods ================================
2602
- /**
2603
- * Get the total number of registered jobs across all roots.
2604
- * Includes both per-root jobs and global before/after jobs.
2605
- * @returns {number} Total job count
2606
- */
2607
- getJobCount() {
2608
- let count = 0;
2609
- for (const root of this.roots.values()) {
2610
- count += root.jobs.size;
2611
- }
2612
- return count + this.globalBeforeJobs.size + this.globalAfterJobs.size;
2613
- }
2614
- /**
2615
- * Get all registered job IDs across all roots.
2616
- * Includes both per-root jobs and global before/after jobs.
2617
- * @returns {string[]} Array of all job IDs
2618
- */
2619
- getJobIds() {
2620
- const ids = [];
2621
- for (const root of this.roots.values()) {
2622
- ids.push(...root.jobs.keys());
2623
- }
2624
- ids.push(...this.globalBeforeJobs.keys());
2625
- ids.push(...this.globalAfterJobs.keys());
2626
- return ids;
2627
- }
2628
- /**
2629
- * Get the number of registered roots (Canvas instances).
2630
- * @returns {number} Number of registered roots
2631
- */
2632
- getRootCount() {
2633
- return this.roots.size;
2634
- }
2635
- /**
2636
- * Check if any user (non-system) jobs are registered in a specific phase.
2637
- * Used by the default render job to know if a user has taken over rendering.
2638
- *
2639
- * @param phase The phase to check
2640
- * @param rootId Optional root ID to check (checks all roots if not provided)
2641
- * @returns true if any user jobs exist in the phase
2642
- */
2643
- hasUserJobsInPhase(phase, rootId) {
2644
- const rootsToCheck = rootId ? [this.roots.get(rootId)].filter(Boolean) : Array.from(this.roots.values());
2645
- return rootsToCheck.some((root) => {
2646
- if (!root) return false;
2647
- for (const job of root.jobs.values()) {
2648
- if (job.phase === phase && !job.system && job.enabled) return true;
2649
- }
2650
- return false;
2651
- });
2652
- }
2653
- //* Utility Methods ================================
2654
- /**
2655
- * Generate a unique root ID for automatic root registration.
2656
- * @returns {string} A unique root ID in the format 'root_N'
2657
- */
2658
- generateRootId() {
2659
- return `root_${this.nextRootIndex++}`;
2660
- }
2661
- /**
2662
- * Generate a unique job ID.
2663
- * @returns {string} A unique job ID in the format 'job_N'
2664
- * @private
2665
- */
2666
- generateJobId() {
2667
- return `job_${this.nextJobIndex}`;
2668
- }
2669
- /**
2670
- * Normalize before/after constraints to a Set.
2671
- * Handles undefined, single string, or array inputs.
2672
- * @param {string | string[] | undefined} value - The constraint value(s)
2673
- * @returns {Set<string>} Normalized Set of constraint strings
2674
- * @private
2675
- */
2676
- normalizeConstraints(value) {
2677
- if (!value) return /* @__PURE__ */ new Set();
2678
- if (Array.isArray(value)) return new Set(value);
2679
- return /* @__PURE__ */ new Set([value]);
2680
- }
2681
- };
2682
- //* Static State & Methods (Singleton Usage) ================================
2683
- //* Cross-Bundle Singleton Key ==============================
2684
- // Use Symbol.for() to ensure scheduler is shared across bundle boundaries
2685
- // This prevents issues when mixing imports from @react-three/fiber and @react-three/fiber/webgpu
2686
- __publicField$1(_Scheduler, "INSTANCE_KEY", Symbol.for("@react-three/fiber.scheduler"));
2687
- let Scheduler = _Scheduler;
2688
- const getScheduler = () => Scheduler.get();
2689
- if (hmrData) {
2690
- hmrData.accept?.();
1692
+ const INTERNAL_LIB_MARKERS = ["zustand", "setState", "Object.assign"];
1693
+ function isInternalRendererAccess(stack, callerDepth = 2) {
1694
+ if (!stack) return false;
1695
+ const caller = stack.split("\n")[callerDepth] ?? "";
1696
+ return INTERNAL_LIB_MARKERS.some((m) => caller.includes(m));
2691
1697
  }
2692
1698
 
2693
1699
  const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
@@ -2799,7 +1805,7 @@ const createStore = (invalidate, advance) => {
2799
1805
  size: newSize,
2800
1806
  viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, newSize) }
2801
1807
  }));
2802
- getScheduler().invalidate();
1808
+ scheduler.getScheduler().invalidate();
2803
1809
  }
2804
1810
  }
2805
1811
  return;
@@ -2814,7 +1820,7 @@ const createStore = (invalidate, advance) => {
2814
1820
  viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, size) },
2815
1821
  _sizeImperative: true
2816
1822
  }));
2817
- getScheduler().invalidate();
1823
+ scheduler.getScheduler().invalidate();
2818
1824
  },
2819
1825
  setDpr: (dpr) => set((state2) => {
2820
1826
  const resolved = calculateDpr(dpr);
@@ -2822,6 +1828,7 @@ const createStore = (invalidate, advance) => {
2822
1828
  }),
2823
1829
  setFrameloop: (frameloop = "always") => {
2824
1830
  set(() => ({ frameloop }));
1831
+ scheduler.getScheduler().frameloop = frameloop;
2825
1832
  },
2826
1833
  setError: (error) => set(() => ({ error })),
2827
1834
  error: null,
@@ -2831,6 +1838,7 @@ const createStore = (invalidate, advance) => {
2831
1838
  buffers: {},
2832
1839
  gpuStorage: {},
2833
1840
  textures: /* @__PURE__ */ new Map(),
1841
+ _textureRefs: /* @__PURE__ */ new Map(),
2834
1842
  renderPipeline: null,
2835
1843
  passes: {},
2836
1844
  _hmrVersion: 0,
@@ -2888,8 +1896,7 @@ const createStore = (invalidate, advance) => {
2888
1896
  const currentState = rootStore.getState();
2889
1897
  if (!currentState.isLegacy && currentState.internal.actualRenderer) {
2890
1898
  const stack = new Error().stack || "";
2891
- const isInternalAccess = stack.includes("zustand") || stack.includes("setState") || stack.includes("Object.assign") || stack.includes("react-three-fiber/packages/fiber/src/core");
2892
- if (!isInternalAccess) {
1899
+ if (!isInternalRendererAccess(stack)) {
2893
1900
  const cleanedStack = stack.split("\n").slice(2).join("\n") || "Stack trace unavailable";
2894
1901
  notifyDepreciated({
2895
1902
  heading: "Accessing state.gl in WebGPU mode",
@@ -3002,26 +2009,32 @@ function loadingFn(extensions, onProgress) {
3002
2009
  );
3003
2010
  };
3004
2011
  }
3005
- function useLoader(loader, input, extensions, onProgress) {
3006
- const keys = Array.isArray(input) ? input : [input];
2012
+ function useLoader(loader, input, extensions, onProgress, cacheKey) {
2013
+ const inputs = Array.isArray(input) ? input : [input];
2014
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
3007
2015
  const fn = loadingFn(extensions, onProgress);
3008
- const results = keys.map((key) => suspendReact.suspend(fn, [loader, key], { equal: is.equ }));
2016
+ const results = cacheKeys.map(
2017
+ (key, index) => suspendReact.suspend(() => fn(loader, inputs[index]), [loader, key], { equal: is.equ })
2018
+ );
3009
2019
  return Array.isArray(input) ? results : results[0];
3010
2020
  }
3011
- useLoader.preload = function(loader, input, extensions, onProgress) {
3012
- const keys = Array.isArray(input) ? input : [input];
3013
- keys.forEach((key) => suspendReact.preload(loadingFn(extensions, onProgress), [loader, key]));
2021
+ useLoader.preload = function(loader, input, extensions, onProgress, cacheKey) {
2022
+ const inputs = Array.isArray(input) ? input : [input];
2023
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2024
+ cacheKeys.forEach(
2025
+ (key, index) => suspendReact.preload(() => loadingFn(extensions, onProgress)(loader, inputs[index]), [loader, key])
2026
+ );
3014
2027
  };
3015
- useLoader.clear = function(loader, input) {
3016
- const keys = Array.isArray(input) ? input : [input];
3017
- keys.forEach((key) => suspendReact.clear([loader, key]));
2028
+ useLoader.clear = function(loader, input, cacheKey) {
2029
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2030
+ cacheKeys.forEach((key) => suspendReact.clear([loader, key]));
3018
2031
  };
3019
2032
  useLoader.loader = getLoader;
3020
2033
 
3021
2034
  function useFrame(callback, priorityOrOptions) {
3022
2035
  const store = React__namespace.useContext(context);
3023
2036
  const isInsideCanvas = store !== null;
3024
- const scheduler = getScheduler();
2037
+ const scheduler$1 = scheduler.getScheduler();
3025
2038
  const optionsKey = typeof priorityOrOptions === "number" ? `p:${priorityOrOptions}` : priorityOrOptions ? JSON.stringify({
3026
2039
  id: priorityOrOptions.id,
3027
2040
  phase: priorityOrOptions.phase,
@@ -3069,7 +2082,7 @@ function useFrame(callback, priorityOrOptions) {
3069
2082
  };
3070
2083
  callbackRef.current?.(mergedState, delta);
3071
2084
  };
3072
- const unregister = scheduler.register(wrappedCallback, {
2085
+ const unregister = scheduler$1.register(wrappedCallback, {
3073
2086
  id,
3074
2087
  rootId,
3075
2088
  ...options
@@ -3090,37 +2103,31 @@ function useFrame(callback, priorityOrOptions) {
3090
2103
  }
3091
2104
  };
3092
2105
  } else {
3093
- const registerOutside = () => {
3094
- return scheduler.register((state, delta) => callbackRef.current?.(state, delta), { id, ...options });
3095
- };
3096
- if (scheduler.independent || scheduler.isReady) {
3097
- return registerOutside();
3098
- }
3099
- let unregisterJob = null;
3100
- const unsubReady = scheduler.onRootReady(() => {
3101
- unregisterJob = registerOutside();
3102
- });
3103
- return () => {
3104
- unsubReady();
3105
- unregisterJob?.();
3106
- };
2106
+ return scheduler$1.register(
2107
+ (state, delta) => {
2108
+ const frameState = state;
2109
+ if (!frameState.renderer) return;
2110
+ callbackRef.current?.(frameState, delta);
2111
+ },
2112
+ { id, ...options }
2113
+ );
3107
2114
  }
3108
- }, [store, scheduler, id, optionsKey, isLegacyPriority, isInsideCanvas]);
2115
+ }, [store, scheduler$1, id, optionsKey, isLegacyPriority, isInsideCanvas]);
3109
2116
  const isPaused = React__namespace.useSyncExternalStore(
3110
2117
  // Subscribe function
3111
2118
  React__namespace.useCallback(
3112
2119
  (onStoreChange) => {
3113
- return getScheduler().subscribeJobState(id, onStoreChange);
2120
+ return scheduler.getScheduler().subscribeJobState(id, onStoreChange);
3114
2121
  },
3115
2122
  [id]
3116
2123
  ),
3117
2124
  // getSnapshot function
3118
- React__namespace.useCallback(() => getScheduler().isJobPaused(id), [id]),
2125
+ React__namespace.useCallback(() => scheduler.getScheduler().isJobPaused(id), [id]),
3119
2126
  // getServerSnapshot function (SSR)
3120
2127
  React__namespace.useCallback(() => false, [])
3121
2128
  );
3122
2129
  const controls = React__namespace.useMemo(() => {
3123
- const scheduler2 = getScheduler();
2130
+ const scheduler2 = scheduler.getScheduler();
3124
2131
  return {
3125
2132
  /** The job's unique ID */
3126
2133
  id,
@@ -3135,7 +2142,7 @@ function useFrame(callback, priorityOrOptions) {
3135
2142
  * @param timestamp Optional timestamp (defaults to performance.now())
3136
2143
  */
3137
2144
  step: (timestamp) => {
3138
- getScheduler().stepJob(id, timestamp);
2145
+ scheduler.getScheduler().stepJob(id, timestamp);
3139
2146
  },
3140
2147
  /**
3141
2148
  * Manually step ALL jobs in the scheduler.
@@ -3143,20 +2150,20 @@ function useFrame(callback, priorityOrOptions) {
3143
2150
  * @param timestamp Optional timestamp (defaults to performance.now())
3144
2151
  */
3145
2152
  stepAll: (timestamp) => {
3146
- getScheduler().step(timestamp);
2153
+ scheduler.getScheduler().step(timestamp);
3147
2154
  },
3148
2155
  /**
3149
2156
  * Pause this job (set enabled=false).
3150
2157
  * Job remains registered but won't run.
3151
2158
  */
3152
2159
  pause: () => {
3153
- getScheduler().pauseJob(id);
2160
+ scheduler.getScheduler().pauseJob(id);
3154
2161
  },
3155
2162
  /**
3156
2163
  * Resume this job (set enabled=true).
3157
2164
  */
3158
2165
  resume: () => {
3159
- getScheduler().resumeJob(id);
2166
+ scheduler.getScheduler().resumeJob(id);
3160
2167
  },
3161
2168
  /**
3162
2169
  * Reactive paused state - automatically updates when pause/resume is called.
@@ -3194,18 +2201,18 @@ function buildFromCache(input, textureCache) {
3194
2201
  function useTexture(input, optionsOrOnLoad) {
3195
2202
  const renderer = useThree((state) => state.internal.actualRenderer);
3196
2203
  const store = useStore();
3197
- const textureCache = useThree((state) => state.textures);
3198
2204
  const options = typeof optionsOrOnLoad === "function" ? { onLoad: optionsOrOnLoad } : optionsOrOnLoad ?? {};
3199
- const { onLoad, cache = false } = options;
2205
+ const { onLoad, cache = true } = options;
3200
2206
  const onLoadRef = React.useRef(onLoad);
3201
2207
  onLoadRef.current = onLoad;
3202
2208
  const onLoadCalledForRef = React.useRef(null);
3203
2209
  const urls = React.useMemo(() => getUrls(input), [input]);
3204
2210
  const cachedResult = React.useMemo(() => {
3205
2211
  if (!cache) return null;
3206
- if (!allUrlsCached(urls, textureCache)) return null;
3207
- return buildFromCache(input, textureCache);
3208
- }, [cache, urls, textureCache, input]);
2212
+ const textures = store.getState().textures;
2213
+ if (!allUrlsCached(urls, textures)) return null;
2214
+ return buildFromCache(input, textures);
2215
+ }, [cache, urls, input, store]);
3209
2216
  const loadedTextures = useLoader(
3210
2217
  webgpu.TextureLoader,
3211
2218
  IsObject(input) ? Object.values(input) : input
@@ -3249,8 +2256,6 @@ function useTexture(input, optionsOrOnLoad) {
3249
2256
  }, [input, loadedTextures, cachedResult]);
3250
2257
  React.useEffect(() => {
3251
2258
  if (!cache) return;
3252
- if (cachedResult) return;
3253
- const set = store.setState;
3254
2259
  const urlTextureMap = [];
3255
2260
  if (typeof input === "string") {
3256
2261
  urlTextureMap.push([input, mappedTextures]);
@@ -3264,18 +2269,32 @@ function useTexture(input, optionsOrOnLoad) {
3264
2269
  urlTextureMap.push([url, textureRecord[key]]);
3265
2270
  }
3266
2271
  }
3267
- set((state) => {
3268
- const newMap = new Map(state.textures);
3269
- let changed = false;
2272
+ store.setState((state) => {
2273
+ const refs = new Map(state._textureRefs);
2274
+ let textures = state.textures;
2275
+ let added = false;
3270
2276
  for (const [url, texture] of urlTextureMap) {
3271
- if (!newMap.has(url)) {
3272
- newMap.set(url, texture);
3273
- changed = true;
2277
+ if (!textures.has(url)) {
2278
+ if (!added) {
2279
+ textures = new Map(textures);
2280
+ added = true;
2281
+ }
2282
+ textures.set(url, texture);
3274
2283
  }
2284
+ refs.set(url, (refs.get(url) ?? 0) + 1);
3275
2285
  }
3276
- return changed ? { textures: newMap } : state;
2286
+ return added ? { textures, _textureRefs: refs } : { _textureRefs: refs };
3277
2287
  });
3278
- }, [cache, input, mappedTextures, store, cachedResult]);
2288
+ return () => store.setState((state) => {
2289
+ const refs = new Map(state._textureRefs);
2290
+ for (const [url] of urlTextureMap) {
2291
+ const next = (refs.get(url) ?? 0) - 1;
2292
+ if (next <= 0) refs.delete(url);
2293
+ else refs.set(url, next);
2294
+ }
2295
+ return { _textureRefs: refs };
2296
+ });
2297
+ }, [cache, input, mappedTextures, store]);
3279
2298
  return mappedTextures;
3280
2299
  }
3281
2300
  useTexture.preload = (url) => useLoader.preload(webgpu.TextureLoader, url);
@@ -3291,96 +2310,63 @@ const Texture = ({
3291
2310
  return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: children?.(ret) });
3292
2311
  };
3293
2312
 
3294
- function getTextureValue(entry) {
3295
- if (entry instanceof webgpu.Texture) return entry;
3296
- if (entry && typeof entry === "object" && "value" in entry && entry.value instanceof webgpu.Texture) {
3297
- return entry.value;
3298
- }
3299
- return null;
3300
- }
3301
- function useTextures() {
2313
+ function useTextures(selector) {
3302
2314
  const store = useStore();
3303
- return React.useMemo(() => {
3304
- const set = store.setState;
2315
+ const registry = React.useMemo(() => {
3305
2316
  const getState = store.getState;
3306
- const add = (key, value) => {
3307
- set((state) => {
3308
- const newMap = new Map(state.textures);
3309
- newMap.set(key, value);
3310
- return { textures: newMap };
3311
- });
3312
- };
3313
- const addMultiple = (items) => {
3314
- set((state) => {
3315
- const newMap = new Map(state.textures);
3316
- const entries = items instanceof Map ? items.entries() : Object.entries(items);
3317
- for (const [key, value] of entries) {
3318
- newMap.set(key, value);
3319
- }
3320
- return { textures: newMap };
3321
- });
3322
- };
3323
- const remove = (key) => {
3324
- set((state) => {
3325
- const newMap = new Map(state.textures);
3326
- newMap.delete(key);
3327
- return { textures: newMap };
3328
- });
3329
- };
3330
- const removeMultiple = (keys) => {
3331
- set((state) => {
3332
- const newMap = new Map(state.textures);
3333
- for (const key of keys) newMap.delete(key);
3334
- return { textures: newMap };
3335
- });
3336
- };
3337
- const dispose = (key) => {
3338
- const entry = getState().textures.get(key);
3339
- if (entry) {
3340
- const tex = getTextureValue(entry);
3341
- tex?.dispose();
3342
- }
3343
- remove(key);
3344
- };
3345
- const disposeMultiple = (keys) => {
3346
- const textures = getState().textures;
3347
- for (const key of keys) {
3348
- const entry = textures.get(key);
3349
- if (entry) {
3350
- const tex = getTextureValue(entry);
3351
- tex?.dispose();
3352
- }
3353
- }
3354
- removeMultiple(keys);
3355
- };
3356
- const disposeAll = () => {
3357
- const textures = getState().textures;
3358
- for (const entry of textures.values()) {
3359
- const tex = getTextureValue(entry);
3360
- tex?.dispose();
3361
- }
3362
- set({ textures: /* @__PURE__ */ new Map() });
3363
- };
2317
+ const setState = store.setState;
2318
+ const getOne = (key) => getState().textures.get(key);
3364
2319
  return {
3365
- // Getter for the textures Map (reactive via getState)
3366
- get textures() {
2320
+ get all() {
3367
2321
  return getState().textures;
3368
2322
  },
3369
- // Read
3370
- get: (key) => getState().textures.get(key),
2323
+ get(input) {
2324
+ if (typeof input === "string") return getOne(input);
2325
+ if (Array.isArray(input)) return input.map(getOne);
2326
+ const out = {};
2327
+ for (const name in input) out[name] = getOne(input[name]);
2328
+ return out;
2329
+ },
3371
2330
  has: (key) => getState().textures.has(key),
3372
- // Write
3373
- add,
3374
- addMultiple,
3375
- // Remove (cache only)
3376
- remove,
3377
- removeMultiple,
3378
- // Dispose (GPU + cache)
3379
- dispose,
3380
- disposeMultiple,
3381
- disposeAll
2331
+ add(keyOrRecord, texture) {
2332
+ setState((state) => {
2333
+ const textures = new Map(state.textures);
2334
+ if (typeof keyOrRecord === "string") {
2335
+ textures.set(keyOrRecord, texture);
2336
+ } else {
2337
+ for (const key in keyOrRecord) textures.set(key, keyOrRecord[key]);
2338
+ }
2339
+ return { textures };
2340
+ });
2341
+ },
2342
+ dispose(key, options) {
2343
+ const state = getState();
2344
+ const refs = state._textureRefs.get(key) ?? 0;
2345
+ if (refs > 0 && !options?.force) {
2346
+ console.warn(
2347
+ `[useTextures] "${key}" still has ${refs} active reference(s); skipping dispose. Pass { force: true } to override.`
2348
+ );
2349
+ return false;
2350
+ }
2351
+ state.textures.get(key)?.dispose();
2352
+ setState((s) => {
2353
+ const textures = new Map(s.textures);
2354
+ textures.delete(key);
2355
+ const nextRefs = new Map(s._textureRefs);
2356
+ nextRefs.delete(key);
2357
+ return { textures, _textureRefs: nextRefs };
2358
+ });
2359
+ return true;
2360
+ },
2361
+ disposeAll() {
2362
+ for (const texture of getState().textures.values()) texture.dispose();
2363
+ setState({ textures: /* @__PURE__ */ new Map(), _textureRefs: /* @__PURE__ */ new Map() });
2364
+ }
3382
2365
  };
3383
2366
  }, [store]);
2367
+ const subscribe = selector ? () => selector(registry) : (state) => state.textures;
2368
+ const selected = useThree(subscribe);
2369
+ return selector ? selected : registry;
3384
2370
  }
3385
2371
 
3386
2372
  function useRenderTarget(widthOrOptions, heightOrOptions, options) {
@@ -3435,7 +2421,7 @@ function addEffect(callback) {
3435
2421
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3436
2422
  });
3437
2423
  const id = `legacy_effect_${effectId++}`;
3438
- return getScheduler().registerGlobal("before", id, callback);
2424
+ return scheduler.getScheduler().registerGlobal("before", id, callback);
3439
2425
  }
3440
2426
  function addAfterEffect(callback) {
3441
2427
  notifyDepreciated({
@@ -3444,7 +2430,7 @@ function addAfterEffect(callback) {
3444
2430
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3445
2431
  });
3446
2432
  const id = `legacy_afterEffect_${effectId++}`;
3447
- return getScheduler().registerGlobal("after", id, callback);
2433
+ return scheduler.getScheduler().registerGlobal("after", id, callback);
3448
2434
  }
3449
2435
  function addTail(callback) {
3450
2436
  notifyDepreciated({
@@ -3452,16 +2438,16 @@ function addTail(callback) {
3452
2438
  body: "Use scheduler.onIdle(callback) instead.\naddTail will be removed in a future version.",
3453
2439
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
3454
2440
  });
3455
- return getScheduler().onIdle(callback);
2441
+ return scheduler.getScheduler().onIdle(callback);
3456
2442
  }
3457
2443
  function invalidate(state, frames = 1, stackFrames = false) {
3458
- getScheduler().invalidate(frames, stackFrames);
2444
+ scheduler.getScheduler().invalidate(frames, stackFrames);
3459
2445
  }
3460
2446
  function advance(timestamp) {
3461
- getScheduler().step(timestamp);
2447
+ scheduler.getScheduler().step(timestamp);
3462
2448
  }
3463
2449
 
3464
- const version = "10.0.0-alpha.2";
2450
+ const version = "10.0.0-alpha.3";
3465
2451
  const packageData = {
3466
2452
  version: version};
3467
2453
 
@@ -14900,6 +13886,7 @@ function swapInstances() {
14900
13886
  }
14901
13887
  }
14902
13888
  if (instance.isHidden) unhideInstance(instance);
13889
+ if (isObject3D(instance.object)) removeInteractivity(findInitialRoot(instance), instance.object);
14903
13890
  if (instance.object.__r3f) delete instance.object.__r3f;
14904
13891
  if (instance.type !== "primitive") disposeOnIdle(instance.object);
14905
13892
  }
@@ -14912,6 +13899,8 @@ function swapInstances() {
14912
13899
  instance.object.__r3f = instance;
14913
13900
  setFiberRef(fiber, instance.object);
14914
13901
  delete instance.appliedOnce;
13902
+ instance.eventCount = 0;
13903
+ instance.handlers = {};
14915
13904
  applyProps(instance.object, instance.props);
14916
13905
  if (instance.props.attach) {
14917
13906
  attach(parent, instance);
@@ -15127,11 +14116,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
15127
14116
  cloneMutableTextInstance(textInstance) {
15128
14117
  return textInstance;
15129
14118
  },
14119
+ // React 19.2 added these for root-level view transitions. They only run for hosts that opt into
14120
+ // view transitions by returning a container from cloneRootViewTransitionContainer; R3F renders
14121
+ // into a WebGL/WebGPU canvas, where cloning the root has no meaning, so we never opt in and
14122
+ // React never calls them. They stay as no-ops rather than throws: the host config is shared by
14123
+ // every root, and a throw here would turn a React-internal probe into a hard crash for users.
14124
+ // Guarded by a test asserting a full render + unmount never reaches them.
15130
14125
  cloneRootViewTransitionContainer(_rootContainer) {
15131
- throw new Error("Not implemented.");
15132
14126
  },
15133
14127
  removeRootViewTransitionClone(_rootContainer, _clone) {
15134
- throw new Error("Not implemented.");
15135
14128
  },
15136
14129
  // https://github.com/facebook/react/pull/32465
15137
14130
  createFragmentInstance: (_fiber) => null,
@@ -15216,6 +14209,7 @@ function createRoot(canvas) {
15216
14209
  const lastConfiguredProps = {};
15217
14210
  let configured = false;
15218
14211
  let pending = null;
14212
+ let rendererSetup = null;
15219
14213
  return {
15220
14214
  async configure(props = {}) {
15221
14215
  let resolve;
@@ -15246,7 +14240,7 @@ function createRoot(canvas) {
15246
14240
  forceEven
15247
14241
  } = props;
15248
14242
  const textureColorSpace = is.obj(glConfig) && !is.fun(glConfig) && !isRenderer(glConfig) && glConfig.textureColorSpace || is.obj(rendererConfig) && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && rendererConfig.textureColorSpace || webgpu.SRGBColorSpace;
15249
- const state = store.getState();
14243
+ let state = store.getState();
15250
14244
  const defaultGPUProps = {
15251
14245
  canvas,
15252
14246
  antialias: true
@@ -15260,52 +14254,64 @@ function createRoot(canvas) {
15260
14254
  throw new Error("Cannot use both gl and renderer props at the same time");
15261
14255
  }
15262
14256
  let renderer = state.internal.actualRenderer;
15263
- if (primaryCanvas && !state.internal.actualRenderer) {
15264
- const primary = await waitForPrimary(primaryCanvas);
15265
- renderer = primary.renderer;
15266
- state.internal.actualRenderer = renderer;
15267
- const canvasTarget = new webgpu.CanvasTarget(canvas);
15268
- primary.store.setState((prev) => ({
15269
- internal: { ...prev.internal, isMultiCanvas: true }
15270
- }));
15271
- state.set((prev) => ({
15272
- webGPUSupported: primary.store.getState().webGPUSupported,
15273
- renderer,
15274
- primaryStore: primary.store,
15275
- internal: {
15276
- ...prev.internal,
15277
- canvasTarget,
15278
- isMultiCanvas: true,
15279
- isSecondary: true,
15280
- targetId: primaryCanvas
15281
- }
15282
- }));
15283
- } else if (!state.internal.actualRenderer) {
15284
- renderer = await resolveRenderer(rendererConfig, defaultGPUProps, webgpu.WebGPURenderer);
15285
- if (!renderer.hasInitialized?.()) {
15286
- const size2 = computeInitialSize(canvas, propsSize);
15287
- if (size2.width > 0 && size2.height > 0) {
15288
- const pixelRatio = calculateDpr(dpr);
15289
- canvas.width = size2.width * pixelRatio;
15290
- canvas.height = size2.height * pixelRatio;
15291
- }
15292
- await renderer.init();
15293
- }
15294
- const backend = renderer.backend;
15295
- const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
15296
- state.internal.actualRenderer = renderer;
15297
- state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
15298
- if (canvasId && !state.internal.isSecondary) {
15299
- const canvasTarget = new webgpu.CanvasTarget(canvas);
15300
- const unregisterPrimary = registerPrimary(canvasId, renderer, store);
15301
- state.set((prev) => ({
15302
- internal: {
15303
- ...prev.internal,
15304
- canvasTarget,
15305
- unregisterPrimary
14257
+ if (!state.internal.actualRenderer) {
14258
+ if (!rendererSetup) {
14259
+ rendererSetup = (async () => {
14260
+ if (primaryCanvas) {
14261
+ const primary = await waitForPrimary(primaryCanvas);
14262
+ renderer = primary.renderer;
14263
+ state.internal.actualRenderer = renderer;
14264
+ const canvasTarget = new webgpu.CanvasTarget(canvas);
14265
+ primary.store.setState((prev) => ({
14266
+ internal: { ...prev.internal, isMultiCanvas: true }
14267
+ }));
14268
+ state.set((prev) => ({
14269
+ webGPUSupported: primary.store.getState().webGPUSupported,
14270
+ renderer,
14271
+ primaryStore: primary.store,
14272
+ internal: {
14273
+ ...prev.internal,
14274
+ canvasTarget,
14275
+ isMultiCanvas: true,
14276
+ isSecondary: true,
14277
+ targetId: primaryCanvas
14278
+ }
14279
+ }));
14280
+ } else {
14281
+ renderer = await resolveRenderer(rendererConfig, defaultGPUProps, webgpu.WebGPURenderer);
14282
+ if (!renderer.hasInitialized?.()) {
14283
+ const size2 = computeInitialSize(canvas, propsSize);
14284
+ if (size2.width > 0 && size2.height > 0) {
14285
+ const pixelRatio = calculateDpr(dpr);
14286
+ canvas.width = size2.width * pixelRatio;
14287
+ canvas.height = size2.height * pixelRatio;
14288
+ }
14289
+ await renderer.init();
14290
+ }
14291
+ const backend = renderer.backend;
14292
+ const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
14293
+ state.internal.actualRenderer = renderer;
14294
+ state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
14295
+ if (canvasId && !state.internal.isSecondary) {
14296
+ const canvasTarget = new webgpu.CanvasTarget(canvas);
14297
+ const unregisterPrimary = registerPrimary(canvasId, renderer, store);
14298
+ state.set((prev) => ({
14299
+ internal: {
14300
+ ...prev.internal,
14301
+ canvasTarget,
14302
+ unregisterPrimary
14303
+ }
14304
+ }));
14305
+ }
15306
14306
  }
15307
- }));
14307
+ })().catch((err) => {
14308
+ rendererSetup = null;
14309
+ throw err;
14310
+ });
15308
14311
  }
14312
+ await rendererSetup;
14313
+ state = store.getState();
14314
+ renderer = state.internal.actualRenderer;
15309
14315
  }
15310
14316
  let raycaster = state.raycaster;
15311
14317
  if (!raycaster) state.set({ raycaster: raycaster = new webgpu.Raycaster() });
@@ -15485,15 +14491,15 @@ function createRoot(canvas) {
15485
14491
  applyProps(currentRenderer, rendererProps);
15486
14492
  }
15487
14493
  }
15488
- const scheduler = getScheduler();
14494
+ const scheduler$1 = scheduler.getScheduler();
15489
14495
  const rootId = state.internal.rootId;
15490
14496
  if (!rootId) {
15491
- const newRootId = canvasId || scheduler.generateRootId();
15492
- const unregisterRoot = scheduler.registerRoot(newRootId, {
14497
+ const newRootId = canvasId || scheduler$1.generateRootId();
14498
+ const unregisterRoot = scheduler$1.registerRoot(newRootId, {
15493
14499
  getState: () => store.getState(),
15494
14500
  onError: (err) => store.getState().setError(err)
15495
14501
  });
15496
- const unregisterCanvasTarget = scheduler.register(
14502
+ const unregisterCanvasTarget = scheduler$1.register(
15497
14503
  () => {
15498
14504
  const state2 = store.getState();
15499
14505
  if (state2.internal.isMultiCanvas && state2.internal.canvasTarget) {
@@ -15508,7 +14514,7 @@ function createRoot(canvas) {
15508
14514
  system: true
15509
14515
  }
15510
14516
  );
15511
- const unregisterEventsFlush = scheduler.register(
14517
+ const unregisterEventsFlush = scheduler$1.register(
15512
14518
  () => {
15513
14519
  const state2 = store.getState();
15514
14520
  state2.events.flush?.();
@@ -15520,7 +14526,7 @@ function createRoot(canvas) {
15520
14526
  system: true
15521
14527
  }
15522
14528
  );
15523
- const unregisterFrustum = scheduler.register(
14529
+ const unregisterFrustum = scheduler$1.register(
15524
14530
  () => {
15525
14531
  const state2 = store.getState();
15526
14532
  if (state2.autoUpdateFrustum && state2.camera) {
@@ -15530,11 +14536,11 @@ function createRoot(canvas) {
15530
14536
  {
15531
14537
  id: `${newRootId}_frustum`,
15532
14538
  rootId: newRootId,
15533
- phase: "preRender",
14539
+ before: "render",
15534
14540
  system: true
15535
14541
  }
15536
14542
  );
15537
- const unregisterVisibility = scheduler.register(
14543
+ const unregisterVisibility = scheduler$1.register(
15538
14544
  () => {
15539
14545
  const state2 = store.getState();
15540
14546
  checkVisibility(state2);
@@ -15542,16 +14548,16 @@ function createRoot(canvas) {
15542
14548
  {
15543
14549
  id: `${newRootId}_visibility`,
15544
14550
  rootId: newRootId,
15545
- phase: "preRender",
14551
+ before: "render",
15546
14552
  system: true,
15547
14553
  after: `${newRootId}_frustum`
15548
14554
  }
15549
14555
  );
15550
- const unregisterRender = scheduler.register(
14556
+ const unregisterRender = scheduler$1.register(
15551
14557
  () => {
15552
14558
  const state2 = store.getState();
15553
14559
  const renderer2 = state2.internal.actualRenderer;
15554
- const userHandlesRender = scheduler.hasUserJobsInPhase("render", newRootId);
14560
+ const userHandlesRender = scheduler$1.hasUserJobsInPhase("render", newRootId);
15555
14561
  if (userHandlesRender || state2.internal.priority) return;
15556
14562
  try {
15557
14563
  if (state2.renderPipeline?.render) state2.renderPipeline.render();
@@ -15584,11 +14590,11 @@ function createRoot(canvas) {
15584
14590
  unregisterVisibility();
15585
14591
  unregisterRender();
15586
14592
  },
15587
- scheduler
14593
+ scheduler: scheduler$1
15588
14594
  }
15589
14595
  }));
15590
14596
  }
15591
- scheduler.frameloop = frameloop;
14597
+ scheduler$1.frameloop = frameloop;
15592
14598
  onCreated = onCreatedCallback;
15593
14599
  configured = true;
15594
14600
  resolve();
@@ -15655,7 +14661,8 @@ function unmountComponentAtNode(canvas, callback) {
15655
14661
  dispose(state.scene);
15656
14662
  _roots.delete(canvas);
15657
14663
  if (callback) callback(canvas);
15658
- } catch {
14664
+ } catch (error) {
14665
+ console.warn("[R3F] Error while unmounting root; teardown may be incomplete:", error);
15659
14666
  }
15660
14667
  }, 500);
15661
14668
  }
@@ -15718,6 +14725,7 @@ function PortalInner({ state = {}, children, container }) {
15718
14725
  viewport = rootState.viewport.getCurrentViewport(camera, new webgpu.Vector3(), resolvedSize);
15719
14726
  if (camera !== rootState.camera) updateCamera(camera, resolvedSize);
15720
14727
  }
14728
+ const set = injectState.set;
15721
14729
  return {
15722
14730
  // The intersect consists of the previous root state
15723
14731
  ...rootState,
@@ -15736,7 +14744,7 @@ function PortalInner({ state = {}, children, container }) {
15736
14744
  size: resolvedSize,
15737
14745
  viewport: { ...rootState.viewport, ...viewport },
15738
14746
  // Layers are allowed to override events
15739
- setEvents: (events2) => injectState.set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14747
+ setEvents: (events2) => set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
15740
14748
  // Container for child attachment - the portalScene (injected or container itself)
15741
14749
  internal: { ...rootState.internal, ...injectState.internal, container: portalScene }
15742
14750
  };
@@ -15765,6 +14773,59 @@ function flushSync(fn) {
15765
14773
  return reconciler.flushSyncFromReconciler(fn);
15766
14774
  }
15767
14775
 
14776
+ function parseBackground(background) {
14777
+ if (!background) return null;
14778
+ if (typeof background === "object" && !background.isColor) {
14779
+ const { backgroundMap, envMap, files, preset, ...rest } = background;
14780
+ return {
14781
+ ...rest,
14782
+ preset,
14783
+ files: envMap || files,
14784
+ backgroundFiles: backgroundMap,
14785
+ background: true
14786
+ };
14787
+ }
14788
+ if (typeof background === "number") {
14789
+ return { color: background, background: true };
14790
+ }
14791
+ if (typeof background === "string") {
14792
+ if (background in presetsObj) {
14793
+ return { preset: background, background: true };
14794
+ }
14795
+ if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
14796
+ return { files: background, background: true };
14797
+ }
14798
+ return { color: background, background: true };
14799
+ }
14800
+ if (background.isColor) {
14801
+ return { color: background, background: true };
14802
+ }
14803
+ return null;
14804
+ }
14805
+
14806
+ function parseRendererConfig(rendererProp) {
14807
+ const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
14808
+ if (isRendererConfig) {
14809
+ const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
14810
+ return {
14811
+ primaryCanvas: pc,
14812
+ scheduler: sc,
14813
+ renderer: Object.keys(rest).length > 0 ? rest : rendererProp
14814
+ };
14815
+ }
14816
+ return { primaryCanvas: void 0, scheduler: void 0, renderer: rendererProp };
14817
+ }
14818
+
14819
+ function clearHmrCaches(store) {
14820
+ store.setState((state) => ({
14821
+ nodes: {},
14822
+ uniforms: {},
14823
+ buffers: {},
14824
+ gpuStorage: {},
14825
+ _hmrVersion: state._hmrVersion + 1
14826
+ }));
14827
+ }
14828
+
15768
14829
  function CanvasImpl({
15769
14830
  ref,
15770
14831
  children,
@@ -15785,6 +14846,8 @@ function CanvasImpl({
15785
14846
  raycaster,
15786
14847
  camera,
15787
14848
  scene,
14849
+ autoUpdateFrustum,
14850
+ occlusion,
15788
14851
  onPointerMissed,
15789
14852
  onDragOverMissed,
15790
14853
  onDropMissed,
@@ -15796,49 +14859,10 @@ function CanvasImpl({
15796
14859
  forceEven,
15797
14860
  ...props
15798
14861
  }) {
15799
- const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
15800
- let primaryCanvas;
15801
- let scheduler;
15802
- let renderer;
15803
- if (isRendererConfig) {
15804
- const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
15805
- primaryCanvas = pc;
15806
- scheduler = sc;
15807
- renderer = Object.keys(rest).length > 0 ? rest : rendererProp;
15808
- } else {
15809
- renderer = rendererProp;
15810
- }
14862
+ const { primaryCanvas, scheduler, renderer } = parseRendererConfig(rendererProp);
15811
14863
  React__namespace.useMemo(() => extend(THREE), []);
15812
14864
  const Bridge = useBridge();
15813
- const backgroundProps = React__namespace.useMemo(() => {
15814
- if (!background) return null;
15815
- if (typeof background === "object" && !background.isColor) {
15816
- const { backgroundMap, envMap, files, preset, ...rest } = background;
15817
- return {
15818
- ...rest,
15819
- preset,
15820
- files: envMap || files,
15821
- backgroundFiles: backgroundMap,
15822
- background: true
15823
- };
15824
- }
15825
- if (typeof background === "number") {
15826
- return { color: background, background: true };
15827
- }
15828
- if (typeof background === "string") {
15829
- if (background in presetsObj) {
15830
- return { preset: background, background: true };
15831
- }
15832
- if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
15833
- return { files: background, background: true };
15834
- }
15835
- return { color: background, background: true };
15836
- }
15837
- if (background.isColor) {
15838
- return { color: background, background: true };
15839
- }
15840
- return null;
15841
- }, [background]);
14865
+ const backgroundProps = React__namespace.useMemo(() => parseBackground(background), [background]);
15842
14866
  const hasInitialSizeRef = React__namespace.useRef(false);
15843
14867
  const measureConfig = React__namespace.useMemo(() => {
15844
14868
  if (!hasInitialSizeRef.current) {
@@ -15880,6 +14904,7 @@ function CanvasImpl({
15880
14904
  const handleDropMissed = useMutableCallback(onDropMissed);
15881
14905
  const [block, setBlock] = React__namespace.useState(false);
15882
14906
  const [error, setError] = React__namespace.useState(false);
14907
+ const [fallbackVisible, setFallbackVisible] = React__namespace.useState(false);
15883
14908
  if (block) throw block;
15884
14909
  if (error) throw error;
15885
14910
  const root = React__namespace.useRef(null);
@@ -15887,6 +14912,7 @@ function CanvasImpl({
15887
14912
  const unsubscribeErrorRef = React__namespace.useRef(null);
15888
14913
  useIsomorphicLayoutEffect(() => {
15889
14914
  effectActiveRef.current = true;
14915
+ if (fallbackVisible) return;
15890
14916
  const canvas = canvasRef.current;
15891
14917
  if (effectiveSize.width > 0 && effectiveSize.height > 0 && canvas) {
15892
14918
  if (!root.current) {
@@ -15907,7 +14933,7 @@ function CanvasImpl({
15907
14933
  }
15908
14934
  async function run() {
15909
14935
  if (!effectActiveRef.current || !root.current) return;
15910
- await root.current.configure({
14936
+ const configured = await root.current.configure({
15911
14937
  id,
15912
14938
  primaryCanvas,
15913
14939
  scheduler,
@@ -15922,6 +14948,8 @@ function CanvasImpl({
15922
14948
  performance,
15923
14949
  raycaster,
15924
14950
  camera,
14951
+ autoUpdateFrustum,
14952
+ occlusion,
15925
14953
  size: effectiveSize,
15926
14954
  // Store size props for reset functionality
15927
14955
  _sizeProps: width !== void 0 || height !== void 0 ? { width, height } : null,
@@ -15946,8 +14974,20 @@ function CanvasImpl({
15946
14974
  }
15947
14975
  onCreated?.(state);
15948
14976
  }
15949
- });
15950
- if (!effectActiveRef.current || !root.current) return;
14977
+ }).then(
14978
+ () => true,
14979
+ // Renderer setup failed (e.g. no WebGL/WebGPU support). The `fallback` prop lives
14980
+ // inside <canvas>, which browsers don't display, so surface it as visible DOM
14981
+ // instead; with no fallback, rethrow to an external error boundary. (#3757)
14982
+ (setupError) => {
14983
+ if (effectActiveRef.current) {
14984
+ if (fallback != null) setFallbackVisible(true);
14985
+ else setError(setupError);
14986
+ }
14987
+ return false;
14988
+ }
14989
+ );
14990
+ if (!configured || !effectActiveRef.current || !root.current) return;
15951
14991
  root.current.render(
15952
14992
  /* @__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: [
15953
14993
  backgroundProps && /* @__PURE__ */ jsxRuntime.jsx(Environment, { ...backgroundProps }),
@@ -15981,14 +15021,7 @@ function CanvasImpl({
15981
15021
  const handleHMR = () => {
15982
15022
  queueMicrotask(() => {
15983
15023
  const rootEntry = _roots.get(canvas);
15984
- if (rootEntry?.store) {
15985
- console.log("[R3F] HMR detected \u2014 rebuilding nodes/uniforms");
15986
- rootEntry.store.setState((state) => ({
15987
- nodes: {},
15988
- uniforms: {},
15989
- _hmrVersion: state._hmrVersion + 1
15990
- }));
15991
- }
15024
+ if (rootEntry?.store) clearHmrCaches(rootEntry.store);
15992
15025
  });
15993
15026
  };
15994
15027
  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) {
@@ -16017,7 +15050,11 @@ function CanvasImpl({
16017
15050
  ...style
16018
15051
  },
16019
15052
  ...props,
16020
- children: /* @__PURE__ */ jsxRuntime.jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsxRuntime.jsx(
15053
+ children: fallbackVisible ? (
15054
+ // Renderer setup failed: render the fallback as visible DOM. Inside <canvas> (below)
15055
+ // it exists in the tree but browsers never paint it, which is the whole bug (#3757).
15056
+ fallback
15057
+ ) : /* @__PURE__ */ jsxRuntime.jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsxRuntime.jsx(
16021
15058
  "canvas",
16022
15059
  {
16023
15060
  ref: canvasRef,
@@ -16128,6 +15165,20 @@ function createLazyCreatorState(state) {
16128
15165
  });
16129
15166
  }
16130
15167
 
15168
+ function resolvePrimary(local) {
15169
+ return local.getState().primaryStore ?? local;
15170
+ }
15171
+ function usePrimaryStore() {
15172
+ const local = useStore();
15173
+ const primary = local.getState().primaryStore;
15174
+ return React.useMemo(() => primary ?? local, [primary, local]);
15175
+ }
15176
+ function usePrimaryThree(selector = (state) => state, equalityFn) {
15177
+ const local = useStore();
15178
+ const primary = resolvePrimary(local);
15179
+ return primary(selector, equalityFn);
15180
+ }
15181
+
16131
15182
  function addTexture(set, key, value) {
16132
15183
  set((state) => {
16133
15184
  const newMap = new Map(state.textures);
@@ -16233,7 +15284,7 @@ function useCompareMemoize(value, deep) {
16233
15284
 
16234
15285
  const isUniformNode$1 = (value) => value !== null && typeof value === "object" && "value" in value && "uuid" in value;
16235
15286
  function useUniforms(creatorOrScope, scope) {
16236
- const store = useStore();
15287
+ const store = usePrimaryStore();
16237
15288
  const removeUniforms2 = React.useCallback(
16238
15289
  (names, targetScope) => {
16239
15290
  const nameArray = Array.isArray(names) ? names : [names];
@@ -16303,8 +15354,8 @@ function useUniforms(creatorOrScope, scope) {
16303
15354
  }, [creatorOrScope, store]);
16304
15355
  const memoizedInput = useCompareMemoize(inputForMemoization);
16305
15356
  const isReader = memoizedInput === void 0 || typeof memoizedInput === "string";
16306
- const storeUniforms = useThree((s) => s.uniforms);
16307
- const hmrVersion = useThree((s) => s._hmrVersion);
15357
+ const storeUniforms = usePrimaryThree((s) => s.uniforms);
15358
+ const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
16308
15359
  const readerDep = isReader ? storeUniforms : null;
16309
15360
  const creatorDep = isReader ? null : hmrVersion;
16310
15361
  const uniforms = React.useMemo(() => {
@@ -16365,6 +15416,7 @@ function useUniforms(creatorOrScope, scope) {
16365
15416
  return { ...uniforms, removeUniforms: removeUniforms2, clearUniforms, rebuildUniforms };
16366
15417
  }
16367
15418
  function rebuildAllUniforms(store, scope) {
15419
+ store = store.getState().primaryStore ?? store;
16368
15420
  store.setState((state) => {
16369
15421
  let newUniforms = {};
16370
15422
  if (scope && scope !== "root") {
@@ -16440,6 +15492,7 @@ function isSameThreeType(a, b) {
16440
15492
  return obj_a.isColor && obj_b.isColor || obj_a.isMatrix3 && obj_b.isMatrix3 || obj_a.isMatrix4 && obj_b.isMatrix4 || obj_a.isEuler && obj_b.isEuler || obj_a.isQuaternion && obj_b.isQuaternion;
16441
15493
  }
16442
15494
 
15495
+ const uniformOf = tsl.uniform;
16443
15496
  const isUniformNode = (value) => value !== null && typeof value === "object" && "value" in value && "uuid" in value;
16444
15497
  const isTSLNode$1 = (value) => value !== null && typeof value === "object" && "uuid" in value && "nodeType" in value;
16445
15498
  function useUniform(name, value) {
@@ -16472,11 +15525,11 @@ function useUniform(name, value) {
16472
15525
  }
16473
15526
  let node;
16474
15527
  if (isTSLNode$1(value)) {
16475
- node = tsl.uniform(value);
15528
+ node = uniformOf(value);
16476
15529
  } else if (typeof value === "string") {
16477
15530
  node = tsl.uniform(new webgpu.Color(value));
16478
15531
  } else {
16479
- node = tsl.uniform(value);
15532
+ node = uniformOf(value);
16480
15533
  }
16481
15534
  if (typeof node.setName === "function") {
16482
15535
  node.setName(name);
@@ -16493,7 +15546,7 @@ function useUniform(name, value) {
16493
15546
 
16494
15547
  const isTSLNode = (value) => value !== null && typeof value === "object" && ("uuid" in value || "nodeType" in value);
16495
15548
  function useNodes(creatorOrScope, scope) {
16496
- const store = useStore();
15549
+ const store = usePrimaryStore();
16497
15550
  const removeNodes2 = React.useCallback(
16498
15551
  (names, targetScope) => {
16499
15552
  const nameArray = Array.isArray(names) ? names : [names];
@@ -16550,8 +15603,8 @@ function useNodes(creatorOrScope, scope) {
16550
15603
  [store]
16551
15604
  );
16552
15605
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
16553
- const storeNodes = useThree((s) => s.nodes);
16554
- const hmrVersion = useThree((s) => s._hmrVersion);
15606
+ const storeNodes = usePrimaryThree((s) => s.nodes);
15607
+ const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
16555
15608
  const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
16556
15609
  const readerDep = isReader ? storeNodes : null;
16557
15610
  const creatorDep = isReader ? null : hmrVersion;
@@ -16610,6 +15663,7 @@ function useNodes(creatorOrScope, scope) {
16610
15663
  return { ...nodes, removeNodes: removeNodes2, clearNodes, rebuildNodes };
16611
15664
  }
16612
15665
  function rebuildAllNodes(store, scope) {
15666
+ store = store.getState().primaryStore ?? store;
16613
15667
  store.setState((state) => {
16614
15668
  let newNodes = state.nodes;
16615
15669
  if (scope && scope !== "root") {
@@ -16654,11 +15708,11 @@ function clearRootNodes(set) {
16654
15708
  });
16655
15709
  }
16656
15710
  function useLocalNodes(creator) {
16657
- const store = useStore();
16658
- const uniforms = useThree((s) => s.uniforms);
16659
- const nodes = useThree((s) => s.nodes);
16660
- const textures = useThree((s) => s.textures);
16661
- const hmrVersion = useThree((s) => s._hmrVersion);
15711
+ const store = usePrimaryStore();
15712
+ const uniforms = usePrimaryThree((s) => s.uniforms);
15713
+ const nodes = usePrimaryThree((s) => s.nodes);
15714
+ const textures = usePrimaryThree((s) => s.textures);
15715
+ const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
16662
15716
  return React.useMemo(() => {
16663
15717
  const wrappedState = createLazyCreatorState(store.getState());
16664
15718
  return creator(wrappedState);
@@ -16679,7 +15733,7 @@ const disposeBuffer = (buffer) => {
16679
15733
  }
16680
15734
  };
16681
15735
  function useBuffers(creatorOrScope, scope) {
16682
- const store = useStore();
15736
+ const store = usePrimaryStore();
16683
15737
  const removeBuffers = React.useCallback(
16684
15738
  (names, targetScope) => {
16685
15739
  const nameArray = Array.isArray(names) ? names : [names];
@@ -16750,8 +15804,8 @@ function useBuffers(creatorOrScope, scope) {
16750
15804
  [store, removeBuffers]
16751
15805
  );
16752
15806
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
16753
- const storeBuffers = useThree((s) => s.buffers);
16754
- const hmrVersion = useThree((s) => s._hmrVersion);
15807
+ const storeBuffers = usePrimaryThree((s) => s.buffers);
15808
+ const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
16755
15809
  const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
16756
15810
  const readerDep = isReader ? storeBuffers : null;
16757
15811
  const creatorDep = isReader ? null : hmrVersion;
@@ -16814,6 +15868,7 @@ function useBuffers(creatorOrScope, scope) {
16814
15868
  return { ...buffers, removeBuffers, clearBuffers, rebuildBuffers, disposeBuffers };
16815
15869
  }
16816
15870
  function rebuildAllBuffers(store, scope) {
15871
+ store = store.getState().primaryStore ?? store;
16817
15872
  store.setState((state) => {
16818
15873
  let newBuffers = state.buffers;
16819
15874
  if (scope && scope !== "root") {
@@ -16845,7 +15900,7 @@ const disposeStorage = (storage) => {
16845
15900
  }
16846
15901
  };
16847
15902
  function useGPUStorage(creatorOrScope, scope) {
16848
- const store = useStore();
15903
+ const store = usePrimaryStore();
16849
15904
  const removeStorage = React.useCallback(
16850
15905
  (names, targetScope) => {
16851
15906
  const nameArray = Array.isArray(names) ? names : [names];
@@ -16916,8 +15971,8 @@ function useGPUStorage(creatorOrScope, scope) {
16916
15971
  [store, removeStorage]
16917
15972
  );
16918
15973
  const isReader = creatorOrScope === void 0 || typeof creatorOrScope === "string";
16919
- const storeStorage = useThree((s) => s.gpuStorage);
16920
- const hmrVersion = useThree((s) => s._hmrVersion);
15974
+ const storeStorage = usePrimaryThree((s) => s.gpuStorage);
15975
+ const hmrVersion = usePrimaryThree((s) => s._hmrVersion);
16921
15976
  const scopeDep = typeof creatorOrScope === "string" ? creatorOrScope : scope;
16922
15977
  const readerDep = isReader ? storeStorage : null;
16923
15978
  const creatorDep = isReader ? null : hmrVersion;
@@ -16992,6 +16047,7 @@ function useGPUStorage(creatorOrScope, scope) {
16992
16047
  };
16993
16048
  }
16994
16049
  function rebuildAllStorage(store, scope) {
16050
+ store = store.getState().primaryStore ?? store;
16995
16051
  store.setState((state) => {
16996
16052
  let newStorage = state.gpuStorage;
16997
16053
  if (scope && scope !== "root") {
@@ -17047,12 +16103,12 @@ function useRenderPipeline(mainCB, setupCB) {
17047
16103
  const state = store.getState();
17048
16104
  const set = store.setState;
17049
16105
  try {
17050
- let pp = state.renderPipeline;
16106
+ let pipeline = state.renderPipeline;
17051
16107
  let currentPasses = { ...state.passes };
17052
- let justCreatedPP = false;
17053
- if (!pp) {
17054
- pp = new webgpu.PostProcessing(renderer);
17055
- justCreatedPP = true;
16108
+ let justCreatedPipeline = false;
16109
+ if (!pipeline) {
16110
+ pipeline = new webgpu.RenderPipeline(renderer);
16111
+ justCreatedPipeline = true;
17056
16112
  }
17057
16113
  const cacheValid = scenePassCacheRef.current && scenePassCacheRef.current.sceneUuid === scene.uuid && scenePassCacheRef.current.cameraUuid === camera.uuid;
17058
16114
  let scenePass;
@@ -17063,9 +16119,9 @@ function useRenderPipeline(mainCB, setupCB) {
17063
16119
  scenePassCacheRef.current = { sceneUuid: scene.uuid, cameraUuid: camera.uuid, scenePass };
17064
16120
  }
17065
16121
  currentPasses.scenePass = scenePass;
17066
- if (!pp.outputNode || justCreatedPP) pp.outputNode = scenePass;
17067
- set({ renderPipeline: pp, passes: currentPasses });
17068
- const shouldRunCallbacks = justCreatedPP || !callbacksRanRef.current || !cacheValid;
16122
+ if (!pipeline.outputNode || justCreatedPipeline) pipeline.outputNode = scenePass;
16123
+ set({ renderPipeline: pipeline, passes: currentPasses });
16124
+ const shouldRunCallbacks = justCreatedPipeline || !callbacksRanRef.current || !cacheValid;
17069
16125
  if (shouldRunCallbacks) {
17070
16126
  if (setupCBRef.current) {
17071
16127
  const freshState = store.getState();
@@ -17086,7 +16142,7 @@ function useRenderPipeline(mainCB, setupCB) {
17086
16142
  callbacksRanRef.current = true;
17087
16143
  }
17088
16144
  } catch (error) {
17089
- console.error("[useRenderPipeline] Setup error:", error);
16145
+ console.warn("[useRenderPipeline] Setup failed; the render pipeline was not configured:", error);
17090
16146
  }
17091
16147
  }, [store, renderer, scene, camera, isLegacy, rebuildVersion]);
17092
16148
  const passes = useThree((s) => s.passes);
@@ -17104,6 +16160,8 @@ function useRenderPipeline(mainCB, setupCB) {
17104
16160
 
17105
16161
  extend(THREE);
17106
16162
 
16163
+ exports.Scheduler = scheduler.Scheduler;
16164
+ exports.getScheduler = scheduler.getScheduler;
17107
16165
  exports.Block = Block;
17108
16166
  exports.Canvas = Canvas;
17109
16167
  exports.Environment = Environment;
@@ -17119,7 +16177,6 @@ exports.R3F_BUILD_LEGACY = R3F_BUILD_LEGACY;
17119
16177
  exports.R3F_BUILD_WEBGPU = R3F_BUILD_WEBGPU;
17120
16178
  exports.REACT_INTERNAL_PROPS = REACT_INTERNAL_PROPS;
17121
16179
  exports.RESERVED_PROPS = RESERVED_PROPS;
17122
- exports.Scheduler = Scheduler;
17123
16180
  exports.Texture = Texture;
17124
16181
  exports._roots = _roots;
17125
16182
  exports.act = act;
@@ -17155,7 +16212,6 @@ exports.getInstanceProps = getInstanceProps;
17155
16212
  exports.getPrimary = getPrimary;
17156
16213
  exports.getPrimaryIds = getPrimaryIds;
17157
16214
  exports.getRootState = getRootState;
17158
- exports.getScheduler = getScheduler;
17159
16215
  exports.getUuidPrefix = getUuidPrefix;
17160
16216
  exports.hasConstructor = hasConstructor;
17161
16217
  exports.hasPrimary = hasPrimary;