@react-three/fiber 10.0.0-canary.2c50459 → 10.0.0-canary.9806389

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -15,7 +15,6 @@ const UltraHDRLoader_js = require('three/examples/jsm/loaders/UltraHDRLoader.js'
15
15
  const gainmapJs = require('@monogrid/gainmap-js');
16
16
  const Tb = require('scheduler');
17
17
  const traditional = require('zustand/traditional');
18
- const scheduler = require('@pmndrs/scheduler');
19
18
  const suspendReact = require('suspend-react');
20
19
 
21
20
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
@@ -447,9 +446,9 @@ function Environment(props) {
447
446
  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 });
448
447
  }
449
448
 
450
- var __defProp = Object.defineProperty;
451
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
452
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
449
+ var __defProp$2 = Object.defineProperty;
450
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
451
+ var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
453
452
  const act = React__namespace["act"];
454
453
  const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React__namespace.useLayoutEffect : React__namespace.useEffect;
455
454
  function useMutableCallback(fn) {
@@ -481,7 +480,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
481
480
  return _a = class extends React__namespace.Component {
482
481
  constructor() {
483
482
  super(...arguments);
484
- __publicField(this, "state", { error: false });
483
+ __publicField$2(this, "state", { error: false });
485
484
  }
486
485
  componentDidCatch(err) {
487
486
  this.props.set(err);
@@ -489,7 +488,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
489
488
  render() {
490
489
  return this.state.error ? null : this.props.children;
491
490
  }
492
- }, __publicField(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
491
+ }, __publicField$2(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
493
492
  })();
494
493
 
495
494
  const is = {
@@ -1649,6 +1648,1038 @@ function notifyAlpha({ message, link }) {
1649
1648
  }
1650
1649
  }
1651
1650
 
1651
+ var __defProp$1 = Object.defineProperty;
1652
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1653
+ var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1654
+ const DEFAULT_PHASES = ["start", "input", "physics", "update", "render", "finish"];
1655
+ class PhaseGraph {
1656
+ constructor() {
1657
+ /** Ordered list of phase nodes */
1658
+ __publicField$1(this, "phases", []);
1659
+ /** Quick lookup by name */
1660
+ __publicField$1(this, "phaseMap", /* @__PURE__ */ new Map());
1661
+ /** Cached ordered names (invalidated on changes) */
1662
+ __publicField$1(this, "orderedNamesCache", null);
1663
+ this.initializeDefaultPhases();
1664
+ }
1665
+ //* Initialization --------------------------------
1666
+ initializeDefaultPhases() {
1667
+ for (const name of DEFAULT_PHASES) {
1668
+ const node = { name, isAutoGenerated: false };
1669
+ this.phases.push(node);
1670
+ this.phaseMap.set(name, node);
1671
+ }
1672
+ this.invalidateCache();
1673
+ }
1674
+ //* Public API --------------------------------
1675
+ /**
1676
+ * Add a named phase to the graph
1677
+ * @param name - Phase name (must be unique)
1678
+ * @param options - Position options (before or after another phase)
1679
+ */
1680
+ addPhase(name, options = {}) {
1681
+ if (this.phaseMap.has(name)) {
1682
+ console.warn(`[useFrame] Phase "${name}" already exists`);
1683
+ return;
1684
+ }
1685
+ const { before, after } = options;
1686
+ const node = { name, isAutoGenerated: false };
1687
+ let insertIndex = this.phases.length;
1688
+ const targetIndex = this.getPhaseIndex(before ?? after);
1689
+ if (targetIndex !== -1) {
1690
+ insertIndex = before ? targetIndex : targetIndex + 1;
1691
+ } else {
1692
+ const constraintType = before ? "before" : "after";
1693
+ console.warn(`[useFrame] Phase "${before ?? after}" not found for '${constraintType}' constraint`);
1694
+ }
1695
+ this.phases.splice(insertIndex, 0, node);
1696
+ this.phaseMap.set(name, node);
1697
+ this.invalidateCache();
1698
+ }
1699
+ /**
1700
+ * Get ordered list of phase names
1701
+ */
1702
+ getOrderedPhases() {
1703
+ if (this.orderedNamesCache === null) this.orderedNamesCache = this.phases.map((p) => p.name);
1704
+ return this.orderedNamesCache;
1705
+ }
1706
+ /**
1707
+ * Check if a phase exists
1708
+ */
1709
+ hasPhase(name) {
1710
+ return this.phaseMap.has(name);
1711
+ }
1712
+ /**
1713
+ * Get the index of a phase (-1 if not found)
1714
+ */
1715
+ getPhaseIndex(name) {
1716
+ if (!name) return -1;
1717
+ return this.phases.findIndex((p) => p.name === name);
1718
+ }
1719
+ /**
1720
+ * Ensure a phase exists, creating an auto-generated one if needed.
1721
+ * Used for resolving before/after constraints.
1722
+ *
1723
+ * @param name - The phase name to ensure exists
1724
+ * @returns The phase name (may be auto-generated like 'before:render')
1725
+ */
1726
+ ensurePhase(name) {
1727
+ if (this.phaseMap.has(name)) return name;
1728
+ const node = { name, isAutoGenerated: true };
1729
+ this.phases.push(node);
1730
+ this.phaseMap.set(name, node);
1731
+ this.invalidateCache();
1732
+ return name;
1733
+ }
1734
+ /**
1735
+ * Resolve where a job with before/after constraints should go.
1736
+ * Creates auto-generated phases if needed.
1737
+ *
1738
+ * @param before - Phase(s) to run before
1739
+ * @param after - Phase(s) to run after
1740
+ * @returns The resolved phase name
1741
+ */
1742
+ resolveConstraintPhase(before, after) {
1743
+ const beforeArr = before ? Array.isArray(before) ? before : [before] : [];
1744
+ const afterArr = after ? Array.isArray(after) ? after : [after] : [];
1745
+ if (beforeArr.length > 0) {
1746
+ return this.ensureAutoPhase(beforeArr[0], "before", 0);
1747
+ }
1748
+ if (afterArr.length > 0) {
1749
+ return this.ensureAutoPhase(afterArr[0], "after", 1);
1750
+ }
1751
+ return "update";
1752
+ }
1753
+ /**
1754
+ * Ensure an auto-generated phase exists relative to a target phase.
1755
+ * Creates the phase if it doesn't exist, inserting it at the correct position.
1756
+ *
1757
+ * @param target - The target phase name to position relative to
1758
+ * @param prefix - Prefix for auto-generated phase name ('before' or 'after')
1759
+ * @param offset - Insertion offset (0 for before, 1 for after)
1760
+ * @returns The auto-generated phase name
1761
+ */
1762
+ ensureAutoPhase(target, prefix, offset) {
1763
+ const autoName = `${prefix}:${target}`;
1764
+ if (this.phaseMap.has(autoName)) return autoName;
1765
+ const node = { name: autoName, isAutoGenerated: true };
1766
+ const targetIndex = this.getPhaseIndex(target);
1767
+ if (targetIndex !== -1) this.phases.splice(targetIndex + offset, 0, node);
1768
+ else this.phases.push(node);
1769
+ this.phaseMap.set(autoName, node);
1770
+ this.invalidateCache();
1771
+ return autoName;
1772
+ }
1773
+ // Internal --------------------------------
1774
+ invalidateCache() {
1775
+ this.orderedNamesCache = null;
1776
+ }
1777
+ }
1778
+
1779
+ function rebuildSortedJobs(jobs, phaseGraph) {
1780
+ const orderedPhases = phaseGraph.getOrderedPhases();
1781
+ const buckets = /* @__PURE__ */ new Map();
1782
+ for (const phase of orderedPhases) {
1783
+ buckets.set(phase, []);
1784
+ }
1785
+ for (const job of jobs.values()) {
1786
+ if (!job.enabled) continue;
1787
+ let bucket = buckets.get(job.phase);
1788
+ if (!bucket) {
1789
+ bucket = [];
1790
+ buckets.set(job.phase, bucket);
1791
+ }
1792
+ bucket.push(job);
1793
+ }
1794
+ const sortedBuckets = [];
1795
+ for (const phase of orderedPhases) {
1796
+ const bucket = buckets.get(phase);
1797
+ if (!bucket || bucket.length === 0) continue;
1798
+ bucket.sort((a, b) => {
1799
+ if (a.priority !== b.priority) return b.priority - a.priority;
1800
+ return a.index - b.index;
1801
+ });
1802
+ sortedBuckets.push(hasCrossJobConstraints(bucket) ? topologicalSort(bucket) : bucket);
1803
+ }
1804
+ for (const [phase, bucket] of buckets) {
1805
+ if (!orderedPhases.includes(phase) && bucket.length > 0) {
1806
+ bucket.sort((a, b) => {
1807
+ if (a.priority !== b.priority) return b.priority - a.priority;
1808
+ return a.index - b.index;
1809
+ });
1810
+ sortedBuckets.push(bucket);
1811
+ }
1812
+ }
1813
+ return sortedBuckets.flat();
1814
+ }
1815
+ function hasCrossJobConstraints(bucket) {
1816
+ const jobIds = new Set(bucket.map((j) => j.id));
1817
+ for (const job of bucket) {
1818
+ for (const ref of job.before) {
1819
+ if (jobIds.has(ref)) return true;
1820
+ }
1821
+ for (const ref of job.after) {
1822
+ if (jobIds.has(ref)) return true;
1823
+ }
1824
+ }
1825
+ return false;
1826
+ }
1827
+ function topologicalSort(jobs) {
1828
+ const n = jobs.length;
1829
+ if (n <= 1) return jobs;
1830
+ const jobMap = /* @__PURE__ */ new Map();
1831
+ const inDegree = /* @__PURE__ */ new Map();
1832
+ const adjacency = /* @__PURE__ */ new Map();
1833
+ for (const job of jobs) {
1834
+ jobMap.set(job.id, job);
1835
+ inDegree.set(job.id, 0);
1836
+ adjacency.set(job.id, []);
1837
+ }
1838
+ for (const job of jobs) {
1839
+ for (const ref of job.before) {
1840
+ if (jobMap.has(ref)) {
1841
+ adjacency.get(job.id).push(ref);
1842
+ inDegree.set(ref, inDegree.get(ref) + 1);
1843
+ }
1844
+ }
1845
+ for (const ref of job.after) {
1846
+ if (jobMap.has(ref)) {
1847
+ adjacency.get(ref).push(job.id);
1848
+ inDegree.set(job.id, inDegree.get(job.id) + 1);
1849
+ }
1850
+ }
1851
+ }
1852
+ const queue = [];
1853
+ for (const job of jobs) {
1854
+ if (inDegree.get(job.id) === 0) {
1855
+ queue.push(job);
1856
+ }
1857
+ }
1858
+ queue.sort((a, b) => {
1859
+ if (a.priority !== b.priority) return b.priority - a.priority;
1860
+ return a.index - b.index;
1861
+ });
1862
+ const result = [];
1863
+ while (queue.length > 0) {
1864
+ const job = queue.shift();
1865
+ result.push(job);
1866
+ const neighbors = adjacency.get(job.id) || [];
1867
+ for (const neighborId of neighbors) {
1868
+ const newDegree = inDegree.get(neighborId) - 1;
1869
+ inDegree.set(neighborId, newDegree);
1870
+ if (newDegree === 0) {
1871
+ const neighbor = jobMap.get(neighborId);
1872
+ insertSorted(queue, neighbor);
1873
+ }
1874
+ }
1875
+ }
1876
+ if (result.length !== n) {
1877
+ console.warn("[useFrame] Circular dependency detected in job constraints");
1878
+ const resultIds = new Set(result.map((j) => j.id));
1879
+ for (const job of jobs) {
1880
+ if (!resultIds.has(job.id)) result.push(job);
1881
+ }
1882
+ }
1883
+ return result;
1884
+ }
1885
+ function insertSorted(arr, job) {
1886
+ let i = 0;
1887
+ while (i < arr.length) {
1888
+ const cmp = arr[i];
1889
+ if (job.priority > cmp.priority || job.priority === cmp.priority && job.index < cmp.index) {
1890
+ break;
1891
+ }
1892
+ i++;
1893
+ }
1894
+ arr.splice(i, 0, job);
1895
+ }
1896
+
1897
+ function shouldRun(job, now) {
1898
+ if (!job.enabled) return false;
1899
+ if (!job.fps) return true;
1900
+ const minInterval = 1e3 / job.fps;
1901
+ const lastRun = job.lastRun ?? 0;
1902
+ const elapsed = now - lastRun;
1903
+ if (elapsed < minInterval - 1) return false;
1904
+ if (job.drop) {
1905
+ job.lastRun = now;
1906
+ } else {
1907
+ const steps = Math.floor(elapsed / minInterval);
1908
+ job.lastRun = lastRun + steps * minInterval;
1909
+ if (job.lastRun < now - minInterval) {
1910
+ job.lastRun = now;
1911
+ }
1912
+ }
1913
+ return true;
1914
+ }
1915
+ function resetJobTiming(job) {
1916
+ job.lastRun = void 0;
1917
+ }
1918
+
1919
+ var __defProp = Object.defineProperty;
1920
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1921
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1922
+ const hmrData = (() => {
1923
+ if (typeof process !== "undefined" && process.env.NODE_ENV === "test") return void 0;
1924
+ if (typeof import_meta_hot !== "undefined") return import_meta_hot;
1925
+ try {
1926
+ return (0, eval)("import.meta.hot");
1927
+ } catch {
1928
+ return void 0;
1929
+ }
1930
+ })();
1931
+ const _Scheduler = class _Scheduler {
1932
+ //* Constructor ================================
1933
+ constructor() {
1934
+ //* Critical State ================================
1935
+ __publicField(this, "roots", /* @__PURE__ */ new Map());
1936
+ __publicField(this, "phaseGraph");
1937
+ __publicField(this, "loopState", {
1938
+ running: false,
1939
+ rafHandle: null,
1940
+ lastTime: null,
1941
+ // null = uninitialized, 0+ = valid timestamp
1942
+ frameCount: 0,
1943
+ elapsedTime: 0,
1944
+ createdAt: performance.now()
1945
+ });
1946
+ __publicField(this, "stoppedTime", 0);
1947
+ //* Private State ================================
1948
+ __publicField(this, "nextRootIndex", 0);
1949
+ __publicField(this, "globalBeforeJobs", /* @__PURE__ */ new Map());
1950
+ __publicField(this, "globalAfterJobs", /* @__PURE__ */ new Map());
1951
+ __publicField(this, "nextGlobalIndex", 0);
1952
+ __publicField(this, "idleCallbacks", /* @__PURE__ */ new Set());
1953
+ __publicField(this, "nextJobIndex", 0);
1954
+ __publicField(this, "jobStateListeners", /* @__PURE__ */ new Map());
1955
+ __publicField(this, "pendingFrames", 0);
1956
+ __publicField(this, "_frameloop", "always");
1957
+ //* Independent Mode & Error Handling State ================================
1958
+ __publicField(this, "_independent", false);
1959
+ __publicField(this, "errorHandler", null);
1960
+ __publicField(this, "rootReadyCallbacks", /* @__PURE__ */ new Set());
1961
+ //* Core Loop Execution Methods ================================
1962
+ /**
1963
+ * Main RAF loop callback.
1964
+ * Executes frame, handles demand mode, and schedules next frame.
1965
+ * @param {number} timestamp - RAF timestamp in milliseconds
1966
+ * @returns {void}
1967
+ * @private
1968
+ */
1969
+ __publicField(this, "loop", (timestamp) => {
1970
+ if (!this.loopState.running) return;
1971
+ this.executeFrame(timestamp);
1972
+ if (this._frameloop === "demand") {
1973
+ this.pendingFrames = Math.max(0, this.pendingFrames - 1);
1974
+ if (this.pendingFrames === 0) {
1975
+ this.notifyIdle(timestamp);
1976
+ return this.stop();
1977
+ }
1978
+ }
1979
+ this.loopState.rafHandle = requestAnimationFrame(this.loop);
1980
+ });
1981
+ this.phaseGraph = new PhaseGraph();
1982
+ }
1983
+ static get instance() {
1984
+ return globalThis[_Scheduler.INSTANCE_KEY] ?? null;
1985
+ }
1986
+ static set instance(value) {
1987
+ globalThis[_Scheduler.INSTANCE_KEY] = value;
1988
+ }
1989
+ /**
1990
+ * Get the global scheduler instance (creates if doesn't exist).
1991
+ * Uses HMR data to preserve instance across hot reloads.
1992
+ * @returns {Scheduler} The singleton scheduler instance
1993
+ */
1994
+ static get() {
1995
+ if (!_Scheduler.instance && hmrData?.data?.scheduler) {
1996
+ _Scheduler.instance = hmrData.data.scheduler;
1997
+ }
1998
+ if (!_Scheduler.instance) {
1999
+ _Scheduler.instance = new _Scheduler();
2000
+ if (hmrData?.data) {
2001
+ hmrData.data.scheduler = _Scheduler.instance;
2002
+ }
2003
+ }
2004
+ return _Scheduler.instance;
2005
+ }
2006
+ /**
2007
+ * Reset the singleton instance. Stops the loop and clears all state.
2008
+ * Primarily used for testing to ensure clean state between tests.
2009
+ * @returns {void}
2010
+ */
2011
+ static reset() {
2012
+ if (_Scheduler.instance) {
2013
+ _Scheduler.instance.stop();
2014
+ _Scheduler.instance = null;
2015
+ }
2016
+ if (hmrData?.data) {
2017
+ hmrData.data.scheduler = null;
2018
+ }
2019
+ }
2020
+ //* Getters & Setters ================================
2021
+ get phases() {
2022
+ return this.phaseGraph.getOrderedPhases();
2023
+ }
2024
+ get frameloop() {
2025
+ return this._frameloop;
2026
+ }
2027
+ set frameloop(mode) {
2028
+ if (this._frameloop === mode) return;
2029
+ const wasAlways = this._frameloop === "always";
2030
+ this._frameloop = mode;
2031
+ if (mode === "always" && !this.loopState.running && this.roots.size > 0) this.start();
2032
+ else if (mode !== "always" && wasAlways) this.stop();
2033
+ }
2034
+ get isRunning() {
2035
+ return this.loopState.running;
2036
+ }
2037
+ get isReady() {
2038
+ return this.roots.size > 0;
2039
+ }
2040
+ get independent() {
2041
+ return this._independent;
2042
+ }
2043
+ set independent(value) {
2044
+ this._independent = value;
2045
+ if (value) this.ensureDefaultRoot();
2046
+ }
2047
+ //* Root Management Methods ================================
2048
+ /**
2049
+ * Register a root (Canvas) with the scheduler.
2050
+ * The first root to register starts the RAF loop (if frameloop='always').
2051
+ * @param {string} id - Unique identifier for this root
2052
+ * @param {RootOptions} [options] - Optional configuration with getState and onError callbacks
2053
+ * @returns {() => void} Unsubscribe function to remove this root
2054
+ */
2055
+ registerRoot(id, options = {}) {
2056
+ if (this.roots.has(id)) {
2057
+ console.warn(`[Scheduler] Root "${id}" already registered`);
2058
+ return () => this.unregisterRoot(id);
2059
+ }
2060
+ const entry = {
2061
+ id,
2062
+ getState: options.getState ?? (() => ({})),
2063
+ jobs: /* @__PURE__ */ new Map(),
2064
+ sortedJobs: [],
2065
+ needsRebuild: false
2066
+ };
2067
+ if (options.onError) {
2068
+ this.errorHandler = options.onError;
2069
+ }
2070
+ this.roots.set(id, entry);
2071
+ if (this.roots.size === 1) {
2072
+ this.notifyRootReady();
2073
+ if (this._frameloop === "always") this.start();
2074
+ }
2075
+ return () => this.unregisterRoot(id);
2076
+ }
2077
+ /**
2078
+ * Unregister a root from the scheduler.
2079
+ * Cleans up all job state listeners for this root's jobs.
2080
+ * The last root to unregister stops the RAF loop.
2081
+ * @param {string} id - The root ID to unregister
2082
+ * @returns {void}
2083
+ */
2084
+ unregisterRoot(id) {
2085
+ const root = this.roots.get(id);
2086
+ if (!root) return;
2087
+ for (const jobId of root.jobs.keys()) {
2088
+ this.jobStateListeners.delete(jobId);
2089
+ }
2090
+ this.roots.delete(id);
2091
+ if (this.roots.size === 0) {
2092
+ this.stop();
2093
+ this.errorHandler = null;
2094
+ }
2095
+ }
2096
+ /**
2097
+ * Subscribe to be notified when a root becomes available.
2098
+ * Fires immediately if a root already exists.
2099
+ * @param {() => void} callback - Function called when first root registers
2100
+ * @returns {() => void} Unsubscribe function
2101
+ */
2102
+ onRootReady(callback) {
2103
+ if (this.roots.size > 0) {
2104
+ callback();
2105
+ return () => {
2106
+ };
2107
+ }
2108
+ this.rootReadyCallbacks.add(callback);
2109
+ return () => this.rootReadyCallbacks.delete(callback);
2110
+ }
2111
+ /**
2112
+ * Notify all registered root-ready callbacks.
2113
+ * Called when the first root registers.
2114
+ * @returns {void}
2115
+ * @private
2116
+ */
2117
+ notifyRootReady() {
2118
+ for (const cb of this.rootReadyCallbacks) {
2119
+ try {
2120
+ cb();
2121
+ } catch (error) {
2122
+ console.error("[Scheduler] Error in root-ready callback:", error);
2123
+ }
2124
+ }
2125
+ this.rootReadyCallbacks.clear();
2126
+ }
2127
+ /**
2128
+ * Ensure a default root exists for independent mode.
2129
+ * Creates a minimal root with no state provider.
2130
+ * @returns {void}
2131
+ * @private
2132
+ */
2133
+ ensureDefaultRoot() {
2134
+ if (!this.roots.has("__default__")) {
2135
+ this.registerRoot("__default__");
2136
+ }
2137
+ }
2138
+ /**
2139
+ * Trigger error handling for job errors.
2140
+ * Uses the bound error handler if available, otherwise logs to console.
2141
+ * @param {Error} error - The error to handle
2142
+ * @returns {void}
2143
+ */
2144
+ triggerError(error) {
2145
+ if (this.errorHandler) this.errorHandler(error);
2146
+ else console.error("[Scheduler]", error);
2147
+ }
2148
+ //* Phase Management Methods ================================
2149
+ /**
2150
+ * Add a named phase to the scheduler's execution order.
2151
+ * Marks all roots for rebuild to incorporate the new phase.
2152
+ * @param {string} name - The phase name (e.g., 'physics', 'postprocess')
2153
+ * @param {AddPhaseOptions} [options] - Positioning options (before/after other phases)
2154
+ * @returns {void}
2155
+ * @example
2156
+ * scheduler.addPhase('physics', { before: 'update' });
2157
+ * scheduler.addPhase('postprocess', { after: 'render' });
2158
+ */
2159
+ addPhase(name, options) {
2160
+ this.phaseGraph.addPhase(name, options);
2161
+ for (const root of this.roots.values()) {
2162
+ root.needsRebuild = true;
2163
+ }
2164
+ }
2165
+ /**
2166
+ * Check if a phase exists in the scheduler.
2167
+ * @param {string} name - The phase name to check
2168
+ * @returns {boolean} True if the phase exists
2169
+ */
2170
+ hasPhase(name) {
2171
+ return this.phaseGraph.hasPhase(name);
2172
+ }
2173
+ //* Global Job Registration Methods (Deprecated APIs) ================================
2174
+ /**
2175
+ * Register a global job that runs once per frame (not per-root).
2176
+ * Used internally by deprecated addEffect/addAfterEffect APIs.
2177
+ * @param {'before' | 'after'} phase - When to run: 'before' all roots or 'after' all roots
2178
+ * @param {string} id - Unique identifier for this global job
2179
+ * @param {(timestamp: number) => void} callback - Function called each frame with RAF timestamp
2180
+ * @returns {() => void} Unsubscribe function to remove this global job
2181
+ * @deprecated Use useFrame with phases instead
2182
+ */
2183
+ registerGlobal(phase, id, callback) {
2184
+ const job = { id, callback };
2185
+ if (phase === "before") {
2186
+ this.globalBeforeJobs.set(id, job);
2187
+ } else {
2188
+ this.globalAfterJobs.set(id, job);
2189
+ }
2190
+ return () => {
2191
+ if (phase === "before") this.globalBeforeJobs.delete(id);
2192
+ else this.globalAfterJobs.delete(id);
2193
+ };
2194
+ }
2195
+ //* Idle Callback Methods (Deprecated API) ================================
2196
+ /**
2197
+ * Register an idle callback that fires when the loop stops.
2198
+ * Used internally by deprecated addTail API.
2199
+ * @param {(timestamp: number) => void} callback - Function called when loop becomes idle
2200
+ * @returns {() => void} Unsubscribe function to remove this idle callback
2201
+ * @deprecated Use demand mode with invalidate() instead
2202
+ */
2203
+ onIdle(callback) {
2204
+ this.idleCallbacks.add(callback);
2205
+ return () => this.idleCallbacks.delete(callback);
2206
+ }
2207
+ /**
2208
+ * Notify all registered idle callbacks.
2209
+ * Called when the loop stops in demand mode.
2210
+ * @param {number} timestamp - The RAF timestamp when idle occurred
2211
+ * @returns {void}
2212
+ * @private
2213
+ */
2214
+ notifyIdle(timestamp) {
2215
+ for (const cb of this.idleCallbacks) {
2216
+ try {
2217
+ cb(timestamp);
2218
+ } catch (error) {
2219
+ console.error("[Scheduler] Error in idle callback:", error);
2220
+ }
2221
+ }
2222
+ }
2223
+ //* Job Registration & Management Methods ================================
2224
+ /**
2225
+ * Register a job (frame callback) with a specific root.
2226
+ * This is the core registration method used by useFrame internally.
2227
+ * @param {FrameNextCallback} callback - The function to call each frame
2228
+ * @param {JobOptions & { rootId?: string; system?: boolean }} [options] - Job configuration
2229
+ * @param {string} [options.rootId] - Target root ID (defaults to first registered root)
2230
+ * @param {string} [options.id] - Unique job ID (auto-generated if not provided)
2231
+ * @param {string} [options.phase] - Execution phase (defaults to 'update')
2232
+ * @param {number} [options.priority] - Priority within phase (higher = earlier, default 0)
2233
+ * @param {number} [options.fps] - FPS throttle limit
2234
+ * @param {boolean} [options.drop] - Drop frames when behind (default true)
2235
+ * @param {boolean} [options.enabled] - Whether job is active (default true)
2236
+ * @param {boolean} [options.system] - Internal flag for system jobs (not user-facing)
2237
+ * @returns {() => void} Unsubscribe function to remove this job
2238
+ */
2239
+ register(callback, options = {}) {
2240
+ const rootId = options.rootId;
2241
+ const root = rootId ? this.roots.get(rootId) : this.roots.values().next().value;
2242
+ if (!root) {
2243
+ console.warn("[Scheduler] No root registered. Is this inside a Canvas?");
2244
+ return () => {
2245
+ };
2246
+ }
2247
+ const id = options.id ?? this.generateJobId();
2248
+ let phase = options.phase ?? "update";
2249
+ if (!options.phase && (options.before || options.after)) {
2250
+ phase = this.phaseGraph.resolveConstraintPhase(options.before, options.after);
2251
+ }
2252
+ const before = this.normalizeConstraints(options.before);
2253
+ const after = this.normalizeConstraints(options.after);
2254
+ const job = {
2255
+ id,
2256
+ callback,
2257
+ phase,
2258
+ before,
2259
+ after,
2260
+ priority: options.priority ?? 0,
2261
+ index: this.nextJobIndex++,
2262
+ fps: options.fps,
2263
+ drop: options.drop ?? true,
2264
+ enabled: options.enabled ?? true,
2265
+ system: options.system ?? false
2266
+ };
2267
+ if (root.jobs.has(id)) {
2268
+ console.warn(`[useFrame] Job with id "${id}" already exists, replacing`);
2269
+ }
2270
+ root.jobs.set(id, job);
2271
+ root.needsRebuild = true;
2272
+ return () => this.unregister(id, root.id);
2273
+ }
2274
+ /**
2275
+ * Unregister a job by its ID.
2276
+ * Searches all roots if rootId is not provided.
2277
+ * @param {string} id - The job ID to unregister
2278
+ * @param {string} [rootId] - Optional root ID to search (searches all if not provided)
2279
+ * @returns {void}
2280
+ */
2281
+ unregister(id, rootId) {
2282
+ const root = rootId ? this.roots.get(rootId) : Array.from(this.roots.values()).find((r) => r.jobs.has(id));
2283
+ if (root?.jobs.delete(id)) {
2284
+ root.needsRebuild = true;
2285
+ this.jobStateListeners.delete(id);
2286
+ }
2287
+ }
2288
+ /**
2289
+ * Update a job's options dynamically.
2290
+ * Searches all roots to find the job by ID.
2291
+ * Phase/constraint changes trigger a rebuild of the sorted job list.
2292
+ * @param {string} id - The job ID to update
2293
+ * @param {Partial<JobOptions>} options - The options to update
2294
+ * @returns {void}
2295
+ */
2296
+ updateJob(id, options) {
2297
+ let job;
2298
+ let root;
2299
+ for (const r of this.roots.values()) {
2300
+ job = r.jobs.get(id);
2301
+ if (job) {
2302
+ root = r;
2303
+ break;
2304
+ }
2305
+ }
2306
+ if (!job || !root) return;
2307
+ if (options.priority !== void 0) job.priority = options.priority;
2308
+ if (options.fps !== void 0) job.fps = options.fps;
2309
+ if (options.drop !== void 0) job.drop = options.drop;
2310
+ if (options.enabled !== void 0) {
2311
+ const wasEnabled = job.enabled;
2312
+ job.enabled = options.enabled;
2313
+ if (!wasEnabled && job.enabled) resetJobTiming(job);
2314
+ if (wasEnabled !== job.enabled) root.needsRebuild = true;
2315
+ }
2316
+ if (options.phase !== void 0 || options.before !== void 0 || options.after !== void 0) {
2317
+ if (options.phase) job.phase = options.phase;
2318
+ if (options.before !== void 0) job.before = this.normalizeConstraints(options.before);
2319
+ if (options.after !== void 0) job.after = this.normalizeConstraints(options.after);
2320
+ root.needsRebuild = true;
2321
+ }
2322
+ }
2323
+ //* Job State Management Methods ================================
2324
+ /**
2325
+ * Check if a job is currently paused (disabled).
2326
+ * @param {string} id - The job ID to check
2327
+ * @returns {boolean} True if the job exists and is paused
2328
+ */
2329
+ isJobPaused(id) {
2330
+ for (const root of this.roots.values()) {
2331
+ const job = root.jobs.get(id);
2332
+ if (job) return !job.enabled;
2333
+ }
2334
+ return false;
2335
+ }
2336
+ /**
2337
+ * Subscribe to state changes for a specific job.
2338
+ * Listener is called when job is paused or resumed.
2339
+ * @param {string} id - The job ID to subscribe to
2340
+ * @param {() => void} listener - Callback invoked on state changes
2341
+ * @returns {() => void} Unsubscribe function
2342
+ */
2343
+ subscribeJobState(id, listener) {
2344
+ if (!this.jobStateListeners.has(id)) {
2345
+ this.jobStateListeners.set(id, /* @__PURE__ */ new Set());
2346
+ }
2347
+ this.jobStateListeners.get(id).add(listener);
2348
+ return () => {
2349
+ this.jobStateListeners.get(id)?.delete(listener);
2350
+ if (this.jobStateListeners.get(id)?.size === 0) {
2351
+ this.jobStateListeners.delete(id);
2352
+ }
2353
+ };
2354
+ }
2355
+ /**
2356
+ * Notify all listeners that a job's state has changed.
2357
+ * @param {string} id - The job ID that changed
2358
+ * @returns {void}
2359
+ * @private
2360
+ */
2361
+ notifyJobStateChange(id) {
2362
+ this.jobStateListeners.get(id)?.forEach((listener) => listener());
2363
+ }
2364
+ /**
2365
+ * Pause a job by ID (sets enabled=false).
2366
+ * Notifies any subscribed state listeners.
2367
+ * @param {string} id - The job ID to pause
2368
+ * @returns {void}
2369
+ */
2370
+ pauseJob(id) {
2371
+ this.updateJob(id, { enabled: false });
2372
+ this.notifyJobStateChange(id);
2373
+ }
2374
+ /**
2375
+ * Resume a paused job by ID (sets enabled=true).
2376
+ * Resets job timing to prevent frame accumulation.
2377
+ * Notifies any subscribed state listeners.
2378
+ * @param {string} id - The job ID to resume
2379
+ * @returns {void}
2380
+ */
2381
+ resumeJob(id) {
2382
+ this.updateJob(id, { enabled: true });
2383
+ this.notifyJobStateChange(id);
2384
+ }
2385
+ //* Frame Loop Control Methods ================================
2386
+ /**
2387
+ * Start the requestAnimationFrame loop.
2388
+ * Resets timing state (elapsedTime, frameCount) on start.
2389
+ * No-op if already running.
2390
+ * @returns {void}
2391
+ */
2392
+ start() {
2393
+ if (this.loopState.running) return;
2394
+ const { elapsedTime, createdAt } = this.loopState;
2395
+ let adjustedCreated = 0;
2396
+ if (this.stoppedTime > 0) {
2397
+ adjustedCreated = createdAt - (performance.now() - this.stoppedTime);
2398
+ this.stoppedTime = 0;
2399
+ }
2400
+ Object.assign(this.loopState, {
2401
+ running: true,
2402
+ elapsedTime: elapsedTime ?? 0,
2403
+ lastTime: performance.now(),
2404
+ createdAt: adjustedCreated > 0 ? adjustedCreated : performance.now(),
2405
+ frameCount: 0,
2406
+ rafHandle: requestAnimationFrame(this.loop)
2407
+ });
2408
+ }
2409
+ /**
2410
+ * Stop the requestAnimationFrame loop.
2411
+ * Cancels any pending RAF callback.
2412
+ * No-op if not running.
2413
+ * @returns {void}
2414
+ */
2415
+ stop() {
2416
+ if (!this.loopState.running) return;
2417
+ this.loopState.running = false;
2418
+ if (this.loopState.rafHandle !== null) {
2419
+ cancelAnimationFrame(this.loopState.rafHandle);
2420
+ this.loopState.rafHandle = null;
2421
+ }
2422
+ this.stoppedTime = performance.now();
2423
+ }
2424
+ /**
2425
+ * Request frames to be rendered in demand mode.
2426
+ * Accumulates pending frames (capped at 60) and starts the loop if not running.
2427
+ * No-op if frameloop is not 'demand'.
2428
+ * @param {number} [frames=1] - Number of frames to request
2429
+ * @param {boolean} [stackFrames=false] - Whether to add frames to existing pending count
2430
+ * - `false` (default): Sets pending frames to the specified value (replaces existing count)
2431
+ * - `true`: Adds frames to existing pending count (useful for accumulating invalidations)
2432
+ * @returns {void}
2433
+ * @example
2434
+ * // Request a single frame render
2435
+ * scheduler.invalidate();
2436
+ *
2437
+ * @example
2438
+ * // Request 5 frames (e.g., for animations)
2439
+ * scheduler.invalidate(5);
2440
+ *
2441
+ * @example
2442
+ * // Set pending frames to exactly 3 (don't stack with existing)
2443
+ * scheduler.invalidate(3, false);
2444
+ *
2445
+ * @example
2446
+ * // Add 2 more frames to existing pending count
2447
+ * scheduler.invalidate(2, true);
2448
+ */
2449
+ invalidate(frames = 1, stackFrames = false) {
2450
+ if (this._frameloop !== "demand") return;
2451
+ const baseFrames = stackFrames ? this.pendingFrames : 0;
2452
+ this.pendingFrames = Math.min(60, baseFrames + frames);
2453
+ if (!this.loopState.running && this.pendingFrames > 0) this.start();
2454
+ }
2455
+ /**
2456
+ * Reset timing state for deterministic testing.
2457
+ * Preserves jobs and roots but resets lastTime, frameCount, elapsedTime, etc.
2458
+ * @returns {void}
2459
+ */
2460
+ resetTiming() {
2461
+ this.loopState.lastTime = null;
2462
+ this.loopState.frameCount = 0;
2463
+ this.loopState.elapsedTime = 0;
2464
+ this.loopState.createdAt = performance.now();
2465
+ }
2466
+ //* Manual Stepping Methods ================================
2467
+ /**
2468
+ * Manually execute a single frame for all roots.
2469
+ * Useful for frameloop='never' mode or testing scenarios.
2470
+ * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2471
+ * @returns {void}
2472
+ * @example
2473
+ * // Manual control mode
2474
+ * scheduler.frameloop = 'never';
2475
+ * scheduler.step(); // Execute one frame
2476
+ */
2477
+ step(timestamp) {
2478
+ const now = timestamp ?? performance.now();
2479
+ this.executeFrame(now);
2480
+ }
2481
+ /**
2482
+ * Manually execute a single job by its ID.
2483
+ * Useful for testing individual job callbacks in isolation.
2484
+ * @param {string} id - The job ID to step
2485
+ * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2486
+ * @returns {void}
2487
+ */
2488
+ stepJob(id, timestamp) {
2489
+ let job;
2490
+ let root;
2491
+ for (const r of this.roots.values()) {
2492
+ job = r.jobs.get(id);
2493
+ if (job) {
2494
+ root = r;
2495
+ break;
2496
+ }
2497
+ }
2498
+ if (!job || !root) {
2499
+ console.warn(`[Scheduler] Job "${id}" not found`);
2500
+ return;
2501
+ }
2502
+ const now = timestamp ?? performance.now();
2503
+ const deltaMs = this.loopState.lastTime !== null ? now - this.loopState.lastTime : 0;
2504
+ const delta = deltaMs / 1e3;
2505
+ const elapsed = now - this.loopState.createdAt;
2506
+ const providedState = root.getState?.() ?? {};
2507
+ const frameState = {
2508
+ ...providedState,
2509
+ time: now,
2510
+ delta,
2511
+ elapsed,
2512
+ frame: this.loopState.frameCount
2513
+ };
2514
+ try {
2515
+ job.callback(frameState, delta);
2516
+ } catch (error) {
2517
+ console.error(`[Scheduler] Error in job "${job.id}":`, error);
2518
+ this.triggerError(error instanceof Error ? error : new Error(String(error)));
2519
+ }
2520
+ }
2521
+ /**
2522
+ * Execute a single frame across all roots.
2523
+ * Order: globalBefore → each root's jobs → globalAfter
2524
+ * @param {number} timestamp - RAF timestamp in milliseconds
2525
+ * @returns {void}
2526
+ * @private
2527
+ */
2528
+ executeFrame(timestamp) {
2529
+ const deltaMs = this.loopState.lastTime !== null ? timestamp - this.loopState.lastTime : 0;
2530
+ const delta = deltaMs / 1e3;
2531
+ this.loopState.lastTime = timestamp;
2532
+ this.loopState.frameCount++;
2533
+ this.loopState.elapsedTime += deltaMs;
2534
+ this.runGlobalJobs(this.globalBeforeJobs, timestamp);
2535
+ for (const root of this.roots.values()) {
2536
+ this.tickRoot(root, timestamp, delta);
2537
+ }
2538
+ this.runGlobalJobs(this.globalAfterJobs, timestamp);
2539
+ }
2540
+ /**
2541
+ * Run all global jobs from a job map.
2542
+ * Catches and logs errors without stopping execution.
2543
+ * @param {Map<string, GlobalJob>} jobs - The global jobs map to execute
2544
+ * @param {number} timestamp - RAF timestamp in milliseconds
2545
+ * @returns {void}
2546
+ * @private
2547
+ */
2548
+ runGlobalJobs(jobs, timestamp) {
2549
+ for (const job of jobs.values()) {
2550
+ try {
2551
+ job.callback(timestamp);
2552
+ } catch (error) {
2553
+ console.error(`[Scheduler] Error in global job "${job.id}":`, error);
2554
+ }
2555
+ }
2556
+ }
2557
+ /**
2558
+ * Execute all jobs for a single root in sorted order.
2559
+ * Rebuilds sorted job list if needed, then dispatches each job.
2560
+ * Errors are caught and propagated via triggerError.
2561
+ * @param {RootEntry} root - The root entry to tick
2562
+ * @param {number} timestamp - RAF timestamp in milliseconds
2563
+ * @param {number} delta - Time since last frame in seconds
2564
+ * @returns {void}
2565
+ * @private
2566
+ */
2567
+ tickRoot(root, timestamp, delta) {
2568
+ if (root.needsRebuild) {
2569
+ root.sortedJobs = rebuildSortedJobs(root.jobs, this.phaseGraph);
2570
+ root.needsRebuild = false;
2571
+ }
2572
+ const providedState = root.getState?.() ?? {};
2573
+ const frameState = {
2574
+ ...providedState,
2575
+ time: timestamp,
2576
+ delta,
2577
+ elapsed: this.loopState.elapsedTime / 1e3,
2578
+ // Convert ms to seconds
2579
+ frame: this.loopState.frameCount
2580
+ };
2581
+ for (const job of root.sortedJobs) {
2582
+ if (!shouldRun(job, timestamp)) continue;
2583
+ try {
2584
+ job.callback(frameState, delta);
2585
+ } catch (error) {
2586
+ console.error(`[Scheduler] Error in job "${job.id}":`, error);
2587
+ this.triggerError(error instanceof Error ? error : new Error(String(error)));
2588
+ }
2589
+ }
2590
+ }
2591
+ //* Debug & Inspection Methods ================================
2592
+ /**
2593
+ * Get the total number of registered jobs across all roots.
2594
+ * Includes both per-root jobs and global before/after jobs.
2595
+ * @returns {number} Total job count
2596
+ */
2597
+ getJobCount() {
2598
+ let count = 0;
2599
+ for (const root of this.roots.values()) {
2600
+ count += root.jobs.size;
2601
+ }
2602
+ return count + this.globalBeforeJobs.size + this.globalAfterJobs.size;
2603
+ }
2604
+ /**
2605
+ * Get all registered job IDs across all roots.
2606
+ * Includes both per-root jobs and global before/after jobs.
2607
+ * @returns {string[]} Array of all job IDs
2608
+ */
2609
+ getJobIds() {
2610
+ const ids = [];
2611
+ for (const root of this.roots.values()) {
2612
+ ids.push(...root.jobs.keys());
2613
+ }
2614
+ ids.push(...this.globalBeforeJobs.keys());
2615
+ ids.push(...this.globalAfterJobs.keys());
2616
+ return ids;
2617
+ }
2618
+ /**
2619
+ * Get the number of registered roots (Canvas instances).
2620
+ * @returns {number} Number of registered roots
2621
+ */
2622
+ getRootCount() {
2623
+ return this.roots.size;
2624
+ }
2625
+ /**
2626
+ * Check if any user (non-system) jobs are registered in a specific phase.
2627
+ * Used by the default render job to know if a user has taken over rendering.
2628
+ *
2629
+ * @param phase The phase to check
2630
+ * @param rootId Optional root ID to check (checks all roots if not provided)
2631
+ * @returns true if any user jobs exist in the phase
2632
+ */
2633
+ hasUserJobsInPhase(phase, rootId) {
2634
+ const rootsToCheck = rootId ? [this.roots.get(rootId)].filter(Boolean) : Array.from(this.roots.values());
2635
+ return rootsToCheck.some((root) => {
2636
+ if (!root) return false;
2637
+ for (const job of root.jobs.values()) {
2638
+ if (job.phase === phase && !job.system && job.enabled) return true;
2639
+ }
2640
+ return false;
2641
+ });
2642
+ }
2643
+ //* Utility Methods ================================
2644
+ /**
2645
+ * Generate a unique root ID for automatic root registration.
2646
+ * @returns {string} A unique root ID in the format 'root_N'
2647
+ */
2648
+ generateRootId() {
2649
+ return `root_${this.nextRootIndex++}`;
2650
+ }
2651
+ /**
2652
+ * Generate a unique job ID.
2653
+ * @returns {string} A unique job ID in the format 'job_N'
2654
+ * @private
2655
+ */
2656
+ generateJobId() {
2657
+ return `job_${this.nextJobIndex}`;
2658
+ }
2659
+ /**
2660
+ * Normalize before/after constraints to a Set.
2661
+ * Handles undefined, single string, or array inputs.
2662
+ * @param {string | string[] | undefined} value - The constraint value(s)
2663
+ * @returns {Set<string>} Normalized Set of constraint strings
2664
+ * @private
2665
+ */
2666
+ normalizeConstraints(value) {
2667
+ if (!value) return /* @__PURE__ */ new Set();
2668
+ if (Array.isArray(value)) return new Set(value);
2669
+ return /* @__PURE__ */ new Set([value]);
2670
+ }
2671
+ };
2672
+ //* Static State & Methods (Singleton Usage) ================================
2673
+ //* Cross-Bundle Singleton Key ==============================
2674
+ // Use Symbol.for() to ensure scheduler is shared across bundle boundaries
2675
+ // This prevents issues when mixing imports from @react-three/fiber and @react-three/fiber/webgpu
2676
+ __publicField(_Scheduler, "INSTANCE_KEY", Symbol.for("@react-three/fiber.scheduler"));
2677
+ let Scheduler = _Scheduler;
2678
+ const getScheduler = () => Scheduler.get();
2679
+ if (hmrData) {
2680
+ hmrData.accept?.();
2681
+ }
2682
+
1652
2683
  const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
1653
2684
  const context = globalThis[R3F_CONTEXT] ?? (globalThis[R3F_CONTEXT] = React__namespace.createContext(null));
1654
2685
  const createStore = (invalidate, advance) => {
@@ -1758,7 +2789,7 @@ const createStore = (invalidate, advance) => {
1758
2789
  size: newSize,
1759
2790
  viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, newSize) }
1760
2791
  }));
1761
- scheduler.getScheduler().invalidate();
2792
+ getScheduler().invalidate();
1762
2793
  }
1763
2794
  }
1764
2795
  return;
@@ -1773,7 +2804,7 @@ const createStore = (invalidate, advance) => {
1773
2804
  viewport: { ...s.viewport, ...getCurrentViewport(state2.camera, defaultTarget, size) },
1774
2805
  _sizeImperative: true
1775
2806
  }));
1776
- scheduler.getScheduler().invalidate();
2807
+ getScheduler().invalidate();
1777
2808
  },
1778
2809
  setDpr: (dpr) => set((state2) => {
1779
2810
  const resolved = calculateDpr(dpr);
@@ -1981,7 +3012,7 @@ useLoader.loader = getLoader;
1981
3012
  function useFrame(callback, priorityOrOptions) {
1982
3013
  const store = React__namespace.useContext(context);
1983
3014
  const isInsideCanvas = store !== null;
1984
- const scheduler$1 = scheduler.getScheduler();
3015
+ const scheduler = getScheduler();
1985
3016
  const optionsKey = typeof priorityOrOptions === "number" ? `p:${priorityOrOptions}` : priorityOrOptions ? JSON.stringify({
1986
3017
  id: priorityOrOptions.id,
1987
3018
  phase: priorityOrOptions.phase,
@@ -2029,7 +3060,7 @@ function useFrame(callback, priorityOrOptions) {
2029
3060
  };
2030
3061
  callbackRef.current?.(mergedState, delta);
2031
3062
  };
2032
- const unregister = scheduler$1.register(wrappedCallback, {
3063
+ const unregister = scheduler.register(wrappedCallback, {
2033
3064
  id,
2034
3065
  rootId,
2035
3066
  ...options
@@ -2050,31 +3081,37 @@ function useFrame(callback, priorityOrOptions) {
2050
3081
  }
2051
3082
  };
2052
3083
  } else {
2053
- return scheduler$1.register(
2054
- (state, delta) => {
2055
- const frameState = state;
2056
- if (!frameState.renderer) return;
2057
- callbackRef.current?.(frameState, delta);
2058
- },
2059
- { id, ...options }
2060
- );
3084
+ const registerOutside = () => {
3085
+ return scheduler.register((state, delta) => callbackRef.current?.(state, delta), { id, ...options });
3086
+ };
3087
+ if (scheduler.independent || scheduler.isReady) {
3088
+ return registerOutside();
3089
+ }
3090
+ let unregisterJob = null;
3091
+ const unsubReady = scheduler.onRootReady(() => {
3092
+ unregisterJob = registerOutside();
3093
+ });
3094
+ return () => {
3095
+ unsubReady();
3096
+ unregisterJob?.();
3097
+ };
2061
3098
  }
2062
- }, [store, scheduler$1, id, optionsKey, isLegacyPriority, isInsideCanvas]);
3099
+ }, [store, scheduler, id, optionsKey, isLegacyPriority, isInsideCanvas]);
2063
3100
  const isPaused = React__namespace.useSyncExternalStore(
2064
3101
  // Subscribe function
2065
3102
  React__namespace.useCallback(
2066
3103
  (onStoreChange) => {
2067
- return scheduler.getScheduler().subscribeJobState(id, onStoreChange);
3104
+ return getScheduler().subscribeJobState(id, onStoreChange);
2068
3105
  },
2069
3106
  [id]
2070
3107
  ),
2071
3108
  // getSnapshot function
2072
- React__namespace.useCallback(() => scheduler.getScheduler().isJobPaused(id), [id]),
3109
+ React__namespace.useCallback(() => getScheduler().isJobPaused(id), [id]),
2073
3110
  // getServerSnapshot function (SSR)
2074
3111
  React__namespace.useCallback(() => false, [])
2075
3112
  );
2076
3113
  const controls = React__namespace.useMemo(() => {
2077
- const scheduler2 = scheduler.getScheduler();
3114
+ const scheduler2 = getScheduler();
2078
3115
  return {
2079
3116
  /** The job's unique ID */
2080
3117
  id,
@@ -2089,7 +3126,7 @@ function useFrame(callback, priorityOrOptions) {
2089
3126
  * @param timestamp Optional timestamp (defaults to performance.now())
2090
3127
  */
2091
3128
  step: (timestamp) => {
2092
- scheduler.getScheduler().stepJob(id, timestamp);
3129
+ getScheduler().stepJob(id, timestamp);
2093
3130
  },
2094
3131
  /**
2095
3132
  * Manually step ALL jobs in the scheduler.
@@ -2097,20 +3134,20 @@ function useFrame(callback, priorityOrOptions) {
2097
3134
  * @param timestamp Optional timestamp (defaults to performance.now())
2098
3135
  */
2099
3136
  stepAll: (timestamp) => {
2100
- scheduler.getScheduler().step(timestamp);
3137
+ getScheduler().step(timestamp);
2101
3138
  },
2102
3139
  /**
2103
3140
  * Pause this job (set enabled=false).
2104
3141
  * Job remains registered but won't run.
2105
3142
  */
2106
3143
  pause: () => {
2107
- scheduler.getScheduler().pauseJob(id);
3144
+ getScheduler().pauseJob(id);
2108
3145
  },
2109
3146
  /**
2110
3147
  * Resume this job (set enabled=true).
2111
3148
  */
2112
3149
  resume: () => {
2113
- scheduler.getScheduler().resumeJob(id);
3150
+ getScheduler().resumeJob(id);
2114
3151
  },
2115
3152
  /**
2116
3153
  * Reactive paused state - automatically updates when pause/resume is called.
@@ -2370,7 +3407,7 @@ function addEffect(callback) {
2370
3407
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
2371
3408
  });
2372
3409
  const id = `legacy_effect_${effectId++}`;
2373
- return scheduler.getScheduler().registerGlobal("before", id, callback);
3410
+ return getScheduler().registerGlobal("before", id, callback);
2374
3411
  }
2375
3412
  function addAfterEffect(callback) {
2376
3413
  notifyDepreciated({
@@ -2379,7 +3416,7 @@ function addAfterEffect(callback) {
2379
3416
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
2380
3417
  });
2381
3418
  const id = `legacy_afterEffect_${effectId++}`;
2382
- return scheduler.getScheduler().registerGlobal("after", id, callback);
3419
+ return getScheduler().registerGlobal("after", id, callback);
2383
3420
  }
2384
3421
  function addTail(callback) {
2385
3422
  notifyDepreciated({
@@ -2387,13 +3424,13 @@ function addTail(callback) {
2387
3424
  body: "Use scheduler.onIdle(callback) instead.\naddTail will be removed in a future version.",
2388
3425
  link: "https://docs.pmnd.rs/react-three-fiber/api/hooks#useframe"
2389
3426
  });
2390
- return scheduler.getScheduler().onIdle(callback);
3427
+ return getScheduler().onIdle(callback);
2391
3428
  }
2392
3429
  function invalidate(state, frames = 1, stackFrames = false) {
2393
- scheduler.getScheduler().invalidate(frames, stackFrames);
3430
+ getScheduler().invalidate(frames, stackFrames);
2394
3431
  }
2395
3432
  function advance(timestamp) {
2396
- scheduler.getScheduler().step(timestamp);
3433
+ getScheduler().step(timestamp);
2397
3434
  }
2398
3435
 
2399
3436
  const version = "10.0.0-alpha.2";
@@ -14438,15 +15475,15 @@ function createRoot(canvas) {
14438
15475
  applyProps(currentRenderer, rendererProps);
14439
15476
  }
14440
15477
  }
14441
- const scheduler$1 = scheduler.getScheduler();
15478
+ const scheduler = getScheduler();
14442
15479
  const rootId = state.internal.rootId;
14443
15480
  if (!rootId) {
14444
- const newRootId = canvasId || scheduler$1.generateRootId();
14445
- const unregisterRoot = scheduler$1.registerRoot(newRootId, {
15481
+ const newRootId = canvasId || scheduler.generateRootId();
15482
+ const unregisterRoot = scheduler.registerRoot(newRootId, {
14446
15483
  getState: () => store.getState(),
14447
15484
  onError: (err) => store.getState().setError(err)
14448
15485
  });
14449
- const unregisterCanvasTarget = scheduler$1.register(
15486
+ const unregisterCanvasTarget = scheduler.register(
14450
15487
  () => {
14451
15488
  const state2 = store.getState();
14452
15489
  if (state2.internal.isMultiCanvas && state2.internal.canvasTarget) {
@@ -14461,7 +15498,7 @@ function createRoot(canvas) {
14461
15498
  system: true
14462
15499
  }
14463
15500
  );
14464
- const unregisterEventsFlush = scheduler$1.register(
15501
+ const unregisterEventsFlush = scheduler.register(
14465
15502
  () => {
14466
15503
  const state2 = store.getState();
14467
15504
  state2.events.flush?.();
@@ -14473,7 +15510,7 @@ function createRoot(canvas) {
14473
15510
  system: true
14474
15511
  }
14475
15512
  );
14476
- const unregisterFrustum = scheduler$1.register(
15513
+ const unregisterFrustum = scheduler.register(
14477
15514
  () => {
14478
15515
  const state2 = store.getState();
14479
15516
  if (state2.autoUpdateFrustum && state2.camera) {
@@ -14487,7 +15524,7 @@ function createRoot(canvas) {
14487
15524
  system: true
14488
15525
  }
14489
15526
  );
14490
- const unregisterVisibility = scheduler$1.register(
15527
+ const unregisterVisibility = scheduler.register(
14491
15528
  () => {
14492
15529
  const state2 = store.getState();
14493
15530
  checkVisibility(state2);
@@ -14500,11 +15537,11 @@ function createRoot(canvas) {
14500
15537
  after: `${newRootId}_frustum`
14501
15538
  }
14502
15539
  );
14503
- const unregisterRender = scheduler$1.register(
15540
+ const unregisterRender = scheduler.register(
14504
15541
  () => {
14505
15542
  const state2 = store.getState();
14506
15543
  const renderer2 = state2.internal.actualRenderer;
14507
- const userHandlesRender = scheduler$1.hasUserJobsInPhase("render", newRootId);
15544
+ const userHandlesRender = scheduler.hasUserJobsInPhase("render", newRootId);
14508
15545
  if (userHandlesRender || state2.internal.priority) return;
14509
15546
  try {
14510
15547
  if (state2.renderPipeline?.render) state2.renderPipeline.render();
@@ -14537,11 +15574,11 @@ function createRoot(canvas) {
14537
15574
  unregisterVisibility();
14538
15575
  unregisterRender();
14539
15576
  },
14540
- scheduler: scheduler$1
15577
+ scheduler
14541
15578
  }
14542
15579
  }));
14543
15580
  }
14544
- scheduler$1.frameloop = frameloop;
15581
+ scheduler.frameloop = frameloop;
14545
15582
  onCreated = onCreatedCallback;
14546
15583
  configured = true;
14547
15584
  resolve();
@@ -14998,8 +16035,6 @@ function Canvas(props) {
14998
16035
 
14999
16036
  extend(THREE);
15000
16037
 
15001
- exports.Scheduler = scheduler.Scheduler;
15002
- exports.getScheduler = scheduler.getScheduler;
15003
16038
  exports.Block = Block;
15004
16039
  exports.Canvas = Canvas;
15005
16040
  exports.Environment = Environment;
@@ -15015,6 +16050,7 @@ exports.R3F_BUILD_LEGACY = R3F_BUILD_LEGACY;
15015
16050
  exports.R3F_BUILD_WEBGPU = R3F_BUILD_WEBGPU;
15016
16051
  exports.REACT_INTERNAL_PROPS = REACT_INTERNAL_PROPS;
15017
16052
  exports.RESERVED_PROPS = RESERVED_PROPS;
16053
+ exports.Scheduler = Scheduler;
15018
16054
  exports.Texture = Texture;
15019
16055
  exports._roots = _roots;
15020
16056
  exports.act = act;
@@ -15044,6 +16080,7 @@ exports.getInstanceProps = getInstanceProps;
15044
16080
  exports.getPrimary = getPrimary;
15045
16081
  exports.getPrimaryIds = getPrimaryIds;
15046
16082
  exports.getRootState = getRootState;
16083
+ exports.getScheduler = getScheduler;
15047
16084
  exports.getUuidPrefix = getUuidPrefix;
15048
16085
  exports.hasConstructor = hasConstructor;
15049
16086
  exports.hasPrimary = hasPrimary;