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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as webgpu from 'three/webgpu';
2
- import { RenderTarget, CubeReflectionMapping, EquirectangularReflectionMapping, CubeTextureLoader, Scene, WebGLCubeRenderTarget, HalfFloatType, Color, Frustum, Matrix4, Group, BoxGeometry, MeshBasicNodeMaterial, Mesh, Node, NodeUpdateType, Layers, SRGBColorSpace, RGBAFormat, UnsignedByteType, Vector3, Vector2, TextureLoader, Texture as Texture$1, CanvasTarget, Raycaster, OrthographicCamera, PerspectiveCamera, PCFShadowMap, VSMShadowMap, BasicShadowMap, ACESFilmicToneMapping, WebGPURenderer } from 'three/webgpu';
3
- import { WebGLRenderTarget, WebGLRenderer } from 'three';
2
+ import { CubeRenderTarget, RenderTarget, CubeReflectionMapping, EquirectangularReflectionMapping, CubeTextureLoader, Scene, HalfFloatType, Color, Frustum, Matrix4, Group, BoxGeometry, MeshBasicNodeMaterial, Mesh, Node, NodeUpdateType, Layers, ShaderMaterial, Uniform, SRGBColorSpace, RGBAFormat, UnsignedByteType, Vector3, Vector2, TextureLoader, Texture as Texture$1, CanvasTarget, Raycaster, OrthographicCamera, PerspectiveCamera, PCFShadowMap, VSMShadowMap, BasicShadowMap, ACESFilmicToneMapping, WebGPURenderer } from 'three/webgpu';
3
+ import { WebGLCubeRenderTarget, WebGLRenderTarget, WebGLRenderer } from 'three';
4
4
  import { Inspector } from 'three/addons/inspector/Inspector.js';
5
5
  import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
6
6
  import * as React from 'react';
@@ -15,6 +15,8 @@ import { UltraHDRLoader } from 'three/examples/jsm/loaders/UltraHDRLoader.js';
15
15
  import { GainMapLoader } from '@monogrid/gainmap-js';
16
16
  import Tb, { unstable_scheduleCallback, unstable_IdlePriority } from 'scheduler';
17
17
  import { createWithEqualityFn } from 'zustand/traditional';
18
+ import { getScheduler } from '@pmndrs/scheduler';
19
+ export { Scheduler, getScheduler } from '@pmndrs/scheduler';
18
20
  import { suspend, preload, clear } from 'suspend-react';
19
21
 
20
22
  function _mergeNamespaces(n, m) {
@@ -34,10 +36,13 @@ const R3F_BUILD_WEBGPU = true;
34
36
 
35
37
  const THREE = /*#__PURE__*/_mergeNamespaces({
36
38
  __proto__: null,
39
+ CubeRenderTarget: CubeRenderTarget,
40
+ CubeRenderTargetCompat: CubeRenderTarget,
37
41
  Inspector: Inspector,
38
42
  R3F_BUILD_LEGACY: R3F_BUILD_LEGACY,
39
43
  R3F_BUILD_WEBGPU: R3F_BUILD_WEBGPU,
40
44
  RenderTargetCompat: RenderTarget,
45
+ WebGLCubeRenderTarget: WebGLCubeRenderTarget,
41
46
  WebGLRenderTarget: WebGLRenderTarget,
42
47
  WebGLRenderer: WebGLRenderer
43
48
  }, [webgpu]);
@@ -311,15 +316,16 @@ function EnvironmentPortal({
311
316
  preset = void 0,
312
317
  extensions
313
318
  }) {
314
- const gl = useThree$1((state) => state.gl);
319
+ const renderer = useThree$1((state) => state.renderer);
320
+ const isLegacy = useThree$1((state) => state.isLegacy);
315
321
  const defaultScene = useThree$1((state) => state.scene);
316
322
  const camera = React.useRef(null);
317
323
  const [virtualScene] = React.useState(() => new Scene());
318
324
  const fbo = React.useMemo(() => {
319
- const fbo2 = new WebGLCubeRenderTarget(resolution);
325
+ const fbo2 = isLegacy ? new WebGLCubeRenderTarget(resolution) : new CubeRenderTarget(resolution);
320
326
  fbo2.texture.type = HalfFloatType;
321
327
  return fbo2;
322
- }, [resolution]);
328
+ }, [resolution, isLegacy]);
323
329
  React.useEffect(() => {
324
330
  return () => {
325
331
  fbo.dispose();
@@ -327,10 +333,10 @@ function EnvironmentPortal({
327
333
  }, [fbo]);
328
334
  React.useLayoutEffect(() => {
329
335
  if (frames === 1) {
330
- const autoClear = gl.autoClear;
331
- gl.autoClear = true;
332
- camera.current.update(gl, virtualScene);
333
- gl.autoClear = autoClear;
336
+ const autoClear = renderer.autoClear;
337
+ renderer.autoClear = true;
338
+ camera.current.update(renderer, virtualScene);
339
+ renderer.autoClear = autoClear;
334
340
  }
335
341
  return setEnvProps(background, scene, defaultScene, fbo.texture, {
336
342
  backgroundBlurriness: blur ?? backgroundBlurriness,
@@ -347,7 +353,7 @@ function EnvironmentPortal({
347
353
  defaultScene,
348
354
  background,
349
355
  frames,
350
- gl,
356
+ renderer,
351
357
  blur,
352
358
  backgroundBlurriness,
353
359
  backgroundIntensity,
@@ -358,10 +364,10 @@ function EnvironmentPortal({
358
364
  let count = 1;
359
365
  useFrame$1(() => {
360
366
  if (frames === Infinity || count < frames) {
361
- const autoClear = gl.autoClear;
362
- gl.autoClear = true;
363
- camera.current.update(gl, virtualScene);
364
- gl.autoClear = autoClear;
367
+ const autoClear = renderer.autoClear;
368
+ renderer.autoClear = true;
369
+ camera.current.update(renderer, virtualScene);
370
+ renderer.autoClear = autoClear;
365
371
  count++;
366
372
  }
367
373
  });
@@ -425,9 +431,9 @@ function Environment(props) {
425
431
  return props.ground ? /* @__PURE__ */ jsx(EnvironmentGround, { ...props }) : props.map ? /* @__PURE__ */ jsx(EnvironmentMap, { ...props }) : props.children ? /* @__PURE__ */ jsx(EnvironmentPortal, { ...props }) : /* @__PURE__ */ jsx(EnvironmentCube, { ...props });
426
432
  }
427
433
 
428
- var __defProp$2 = Object.defineProperty;
429
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
430
- var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
434
+ var __defProp = Object.defineProperty;
435
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
436
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
431
437
  const act = React["act"];
432
438
  const useIsomorphicLayoutEffect = /* @__PURE__ */ (() => typeof window !== "undefined" && (window.document?.createElement || window.navigator?.product === "ReactNative"))() ? React.useLayoutEffect : React.useEffect;
433
439
  function useMutableCallback(fn) {
@@ -459,7 +465,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
459
465
  return _a = class extends React.Component {
460
466
  constructor() {
461
467
  super(...arguments);
462
- __publicField$2(this, "state", { error: false });
468
+ __publicField(this, "state", { error: false });
463
469
  }
464
470
  componentDidCatch(err) {
465
471
  this.props.set(err);
@@ -467,7 +473,7 @@ const ErrorBoundary = /* @__PURE__ */ (() => {
467
473
  render() {
468
474
  return this.state.error ? null : this.props.children;
469
475
  }
470
- }, __publicField$2(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
476
+ }, __publicField(_a, "getDerivedStateFromError", () => ({ error: true })), _a;
471
477
  })();
472
478
 
473
479
  const is = {
@@ -604,8 +610,7 @@ function prepare(target, root, type, props) {
604
610
  object,
605
611
  eventCount: 0,
606
612
  handlers: {},
607
- isHidden: false,
608
- deferredRefs: []
613
+ isHidden: false
609
614
  };
610
615
  if (object) object.__r3f = instance;
611
616
  }
@@ -762,6 +767,17 @@ function unregisterVisibility(store, object) {
762
767
  internal.visibilityRegistry.delete(object.uuid);
763
768
  internal.occlusionCache.delete(object);
764
769
  }
770
+ function updateVisibilityHandlers(store, object, handlers) {
771
+ const { internal } = store.getState();
772
+ const entry = internal.visibilityRegistry.get(object.uuid);
773
+ if (!entry) return false;
774
+ entry.handlers = handlers;
775
+ if ((handlers.onOccluded || handlers.onVisible) && !internal.occlusionEnabled) {
776
+ object.occlusionTest = true;
777
+ enableOcclusion(store);
778
+ }
779
+ return true;
780
+ }
765
781
  function checkVisibility(state) {
766
782
  const { internal, camera } = state;
767
783
  const registry = internal.visibilityRegistry;
@@ -949,10 +965,7 @@ function applyProps(object, props) {
949
965
  continue;
950
966
  }
951
967
  if (value === void 0) continue;
952
- if (isFromRef(value)) {
953
- instance?.deferredRefs?.push({ prop, ref: value[FROM_REF] });
954
- continue;
955
- }
968
+ if (isFromRef(value)) continue;
956
969
  if (isOnce(value)) {
957
970
  if (instance?.appliedOnce?.has(prop)) continue;
958
971
  if (instance) {
@@ -988,6 +1001,19 @@ function applyProps(object, props) {
988
1001
  } else if (isVectorLike(target) && is.num(value)) {
989
1002
  if ("setScalar" in target && typeof target.setScalar === "function") target.setScalar(value);
990
1003
  else target.set(value);
1004
+ } else if (root instanceof ShaderMaterial && key === "uniforms" && is.obj(value)) {
1005
+ if (!is.obj(root.uniforms)) root.uniforms = {};
1006
+ const uniforms = root.uniforms;
1007
+ const nextUniforms = value;
1008
+ for (const name in nextUniforms) {
1009
+ const uniform = nextUniforms[name];
1010
+ const targetUniform = uniforms[name];
1011
+ if (targetUniform) Object.assign(targetUniform, uniform);
1012
+ else {
1013
+ const nextUniform = uniform instanceof Uniform ? uniform.clone() : new Uniform(uniform.value);
1014
+ uniforms[name] = nextUniform;
1015
+ }
1016
+ }
991
1017
  } else {
992
1018
  root[key] = value;
993
1019
  if (key.endsWith("Node") && root.isMaterial) {
@@ -1006,6 +1032,9 @@ function applyProps(object, props) {
1006
1032
  if (instance.eventCount && object2.raycast !== null) {
1007
1033
  rootState.internal.interaction.push(object2);
1008
1034
  }
1035
+ }
1036
+ if (instance?.parent && rootState?.internal && instance.object?.isObject3D) {
1037
+ const object2 = instance.object;
1009
1038
  const root = findInitialRoot(instance);
1010
1039
  const visibilityHandlers = {
1011
1040
  onFramed: instance.handlers.onFramed,
@@ -1013,7 +1042,9 @@ function applyProps(object, props) {
1013
1042
  onVisible: instance.handlers.onVisible
1014
1043
  };
1015
1044
  if (hasVisibilityHandlers(visibilityHandlers)) {
1016
- registerVisibility(root, object2, visibilityHandlers);
1045
+ if (!updateVisibilityHandlers(root, object2, visibilityHandlers)) {
1046
+ registerVisibility(root, object2, visibilityHandlers);
1047
+ }
1017
1048
  } else {
1018
1049
  unregisterVisibility(root, object2);
1019
1050
  }
@@ -1541,6 +1572,7 @@ function createPointerEvents(store) {
1541
1572
  set((state) => ({ events: { ...state.events, connected: void 0 } }));
1542
1573
  }
1543
1574
  },
1575
+ // PREVIEW (A8): the XR pointer registration API may change before stable.
1544
1576
  registerPointer: (config) => {
1545
1577
  const pointerId = nextXRPointerId++;
1546
1578
  xrPointers.set(pointerId, config);
@@ -1627,1036 +1659,11 @@ function notifyAlpha({ message, link }) {
1627
1659
  }
1628
1660
  }
1629
1661
 
1630
- var __defProp$1 = Object.defineProperty;
1631
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1632
- var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1633
- const DEFAULT_PHASES = ["start", "input", "physics", "update", "render", "finish"];
1634
- class PhaseGraph {
1635
- constructor() {
1636
- /** Ordered list of phase nodes */
1637
- __publicField$1(this, "phases", []);
1638
- /** Quick lookup by name */
1639
- __publicField$1(this, "phaseMap", /* @__PURE__ */ new Map());
1640
- /** Cached ordered names (invalidated on changes) */
1641
- __publicField$1(this, "orderedNamesCache", null);
1642
- this.initializeDefaultPhases();
1643
- }
1644
- //* Initialization --------------------------------
1645
- initializeDefaultPhases() {
1646
- for (const name of DEFAULT_PHASES) {
1647
- const node = { name, isAutoGenerated: false };
1648
- this.phases.push(node);
1649
- this.phaseMap.set(name, node);
1650
- }
1651
- this.invalidateCache();
1652
- }
1653
- //* Public API --------------------------------
1654
- /**
1655
- * Add a named phase to the graph
1656
- * @param name - Phase name (must be unique)
1657
- * @param options - Position options (before or after another phase)
1658
- */
1659
- addPhase(name, options = {}) {
1660
- if (this.phaseMap.has(name)) {
1661
- console.warn(`[useFrame] Phase "${name}" already exists`);
1662
- return;
1663
- }
1664
- const { before, after } = options;
1665
- const node = { name, isAutoGenerated: false };
1666
- let insertIndex = this.phases.length;
1667
- const targetIndex = this.getPhaseIndex(before ?? after);
1668
- if (targetIndex !== -1) {
1669
- insertIndex = before ? targetIndex : targetIndex + 1;
1670
- } else {
1671
- const constraintType = before ? "before" : "after";
1672
- console.warn(`[useFrame] Phase "${before ?? after}" not found for '${constraintType}' constraint`);
1673
- }
1674
- this.phases.splice(insertIndex, 0, node);
1675
- this.phaseMap.set(name, node);
1676
- this.invalidateCache();
1677
- }
1678
- /**
1679
- * Get ordered list of phase names
1680
- */
1681
- getOrderedPhases() {
1682
- if (this.orderedNamesCache === null) this.orderedNamesCache = this.phases.map((p) => p.name);
1683
- return this.orderedNamesCache;
1684
- }
1685
- /**
1686
- * Check if a phase exists
1687
- */
1688
- hasPhase(name) {
1689
- return this.phaseMap.has(name);
1690
- }
1691
- /**
1692
- * Get the index of a phase (-1 if not found)
1693
- */
1694
- getPhaseIndex(name) {
1695
- if (!name) return -1;
1696
- return this.phases.findIndex((p) => p.name === name);
1697
- }
1698
- /**
1699
- * Ensure a phase exists, creating an auto-generated one if needed.
1700
- * Used for resolving before/after constraints.
1701
- *
1702
- * @param name - The phase name to ensure exists
1703
- * @returns The phase name (may be auto-generated like 'before:render')
1704
- */
1705
- ensurePhase(name) {
1706
- if (this.phaseMap.has(name)) return name;
1707
- const node = { name, isAutoGenerated: true };
1708
- this.phases.push(node);
1709
- this.phaseMap.set(name, node);
1710
- this.invalidateCache();
1711
- return name;
1712
- }
1713
- /**
1714
- * Resolve where a job with before/after constraints should go.
1715
- * Creates auto-generated phases if needed.
1716
- *
1717
- * @param before - Phase(s) to run before
1718
- * @param after - Phase(s) to run after
1719
- * @returns The resolved phase name
1720
- */
1721
- resolveConstraintPhase(before, after) {
1722
- const beforeArr = before ? Array.isArray(before) ? before : [before] : [];
1723
- const afterArr = after ? Array.isArray(after) ? after : [after] : [];
1724
- if (beforeArr.length > 0) {
1725
- return this.ensureAutoPhase(beforeArr[0], "before", 0);
1726
- }
1727
- if (afterArr.length > 0) {
1728
- return this.ensureAutoPhase(afterArr[0], "after", 1);
1729
- }
1730
- return "update";
1731
- }
1732
- /**
1733
- * Ensure an auto-generated phase exists relative to a target phase.
1734
- * Creates the phase if it doesn't exist, inserting it at the correct position.
1735
- *
1736
- * @param target - The target phase name to position relative to
1737
- * @param prefix - Prefix for auto-generated phase name ('before' or 'after')
1738
- * @param offset - Insertion offset (0 for before, 1 for after)
1739
- * @returns The auto-generated phase name
1740
- */
1741
- ensureAutoPhase(target, prefix, offset) {
1742
- const autoName = `${prefix}:${target}`;
1743
- if (this.phaseMap.has(autoName)) return autoName;
1744
- const node = { name: autoName, isAutoGenerated: true };
1745
- const targetIndex = this.getPhaseIndex(target);
1746
- if (targetIndex !== -1) this.phases.splice(targetIndex + offset, 0, node);
1747
- else this.phases.push(node);
1748
- this.phaseMap.set(autoName, node);
1749
- this.invalidateCache();
1750
- return autoName;
1751
- }
1752
- // Internal --------------------------------
1753
- invalidateCache() {
1754
- this.orderedNamesCache = null;
1755
- }
1756
- }
1757
-
1758
- function rebuildSortedJobs(jobs, phaseGraph) {
1759
- const orderedPhases = phaseGraph.getOrderedPhases();
1760
- const buckets = /* @__PURE__ */ new Map();
1761
- for (const phase of orderedPhases) {
1762
- buckets.set(phase, []);
1763
- }
1764
- for (const job of jobs.values()) {
1765
- if (!job.enabled) continue;
1766
- let bucket = buckets.get(job.phase);
1767
- if (!bucket) {
1768
- bucket = [];
1769
- buckets.set(job.phase, bucket);
1770
- }
1771
- bucket.push(job);
1772
- }
1773
- const sortedBuckets = [];
1774
- for (const phase of orderedPhases) {
1775
- const bucket = buckets.get(phase);
1776
- if (!bucket || bucket.length === 0) continue;
1777
- bucket.sort((a, b) => {
1778
- if (a.priority !== b.priority) return b.priority - a.priority;
1779
- return a.index - b.index;
1780
- });
1781
- sortedBuckets.push(hasCrossJobConstraints(bucket) ? topologicalSort(bucket) : bucket);
1782
- }
1783
- for (const [phase, bucket] of buckets) {
1784
- if (!orderedPhases.includes(phase) && bucket.length > 0) {
1785
- bucket.sort((a, b) => {
1786
- if (a.priority !== b.priority) return b.priority - a.priority;
1787
- return a.index - b.index;
1788
- });
1789
- sortedBuckets.push(bucket);
1790
- }
1791
- }
1792
- return sortedBuckets.flat();
1793
- }
1794
- function hasCrossJobConstraints(bucket) {
1795
- const jobIds = new Set(bucket.map((j) => j.id));
1796
- for (const job of bucket) {
1797
- for (const ref of job.before) {
1798
- if (jobIds.has(ref)) return true;
1799
- }
1800
- for (const ref of job.after) {
1801
- if (jobIds.has(ref)) return true;
1802
- }
1803
- }
1804
- return false;
1805
- }
1806
- function topologicalSort(jobs) {
1807
- const n = jobs.length;
1808
- if (n <= 1) return jobs;
1809
- const jobMap = /* @__PURE__ */ new Map();
1810
- const inDegree = /* @__PURE__ */ new Map();
1811
- const adjacency = /* @__PURE__ */ new Map();
1812
- for (const job of jobs) {
1813
- jobMap.set(job.id, job);
1814
- inDegree.set(job.id, 0);
1815
- adjacency.set(job.id, []);
1816
- }
1817
- for (const job of jobs) {
1818
- for (const ref of job.before) {
1819
- if (jobMap.has(ref)) {
1820
- adjacency.get(job.id).push(ref);
1821
- inDegree.set(ref, inDegree.get(ref) + 1);
1822
- }
1823
- }
1824
- for (const ref of job.after) {
1825
- if (jobMap.has(ref)) {
1826
- adjacency.get(ref).push(job.id);
1827
- inDegree.set(job.id, inDegree.get(job.id) + 1);
1828
- }
1829
- }
1830
- }
1831
- const queue = [];
1832
- for (const job of jobs) {
1833
- if (inDegree.get(job.id) === 0) {
1834
- queue.push(job);
1835
- }
1836
- }
1837
- queue.sort((a, b) => {
1838
- if (a.priority !== b.priority) return b.priority - a.priority;
1839
- return a.index - b.index;
1840
- });
1841
- const result = [];
1842
- while (queue.length > 0) {
1843
- const job = queue.shift();
1844
- result.push(job);
1845
- const neighbors = adjacency.get(job.id) || [];
1846
- for (const neighborId of neighbors) {
1847
- const newDegree = inDegree.get(neighborId) - 1;
1848
- inDegree.set(neighborId, newDegree);
1849
- if (newDegree === 0) {
1850
- const neighbor = jobMap.get(neighborId);
1851
- insertSorted(queue, neighbor);
1852
- }
1853
- }
1854
- }
1855
- if (result.length !== n) {
1856
- console.warn("[useFrame] Circular dependency detected in job constraints");
1857
- const resultIds = new Set(result.map((j) => j.id));
1858
- for (const job of jobs) {
1859
- if (!resultIds.has(job.id)) result.push(job);
1860
- }
1861
- }
1862
- return result;
1863
- }
1864
- function insertSorted(arr, job) {
1865
- let i = 0;
1866
- while (i < arr.length) {
1867
- const cmp = arr[i];
1868
- if (job.priority > cmp.priority || job.priority === cmp.priority && job.index < cmp.index) {
1869
- break;
1870
- }
1871
- i++;
1872
- }
1873
- arr.splice(i, 0, job);
1874
- }
1875
-
1876
- function shouldRun(job, now) {
1877
- if (!job.enabled) return false;
1878
- if (!job.fps) return true;
1879
- const minInterval = 1e3 / job.fps;
1880
- const lastRun = job.lastRun ?? 0;
1881
- const elapsed = now - lastRun;
1882
- if (elapsed < minInterval - 1) return false;
1883
- if (job.drop) {
1884
- job.lastRun = now;
1885
- } else {
1886
- const steps = Math.floor(elapsed / minInterval);
1887
- job.lastRun = lastRun + steps * minInterval;
1888
- if (job.lastRun < now - minInterval) {
1889
- job.lastRun = now;
1890
- }
1891
- }
1892
- return true;
1893
- }
1894
- function resetJobTiming(job) {
1895
- job.lastRun = void 0;
1896
- }
1897
-
1898
- var __defProp = Object.defineProperty;
1899
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1900
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1901
- const hmrData = (() => {
1902
- if (typeof process !== "undefined" && process.env.NODE_ENV === "test") return void 0;
1903
- if (typeof import_meta_hot !== "undefined") return import_meta_hot;
1904
- try {
1905
- return (0, eval)("import.meta.hot");
1906
- } catch {
1907
- return void 0;
1908
- }
1909
- })();
1910
- const _Scheduler = class _Scheduler {
1911
- //* Constructor ================================
1912
- constructor() {
1913
- //* Critical State ================================
1914
- __publicField(this, "roots", /* @__PURE__ */ new Map());
1915
- __publicField(this, "phaseGraph");
1916
- __publicField(this, "loopState", {
1917
- running: false,
1918
- rafHandle: null,
1919
- lastTime: null,
1920
- // null = uninitialized, 0+ = valid timestamp
1921
- frameCount: 0,
1922
- elapsedTime: 0,
1923
- createdAt: performance.now()
1924
- });
1925
- __publicField(this, "stoppedTime", 0);
1926
- //* Private State ================================
1927
- __publicField(this, "nextRootIndex", 0);
1928
- __publicField(this, "globalBeforeJobs", /* @__PURE__ */ new Map());
1929
- __publicField(this, "globalAfterJobs", /* @__PURE__ */ new Map());
1930
- __publicField(this, "nextGlobalIndex", 0);
1931
- __publicField(this, "idleCallbacks", /* @__PURE__ */ new Set());
1932
- __publicField(this, "nextJobIndex", 0);
1933
- __publicField(this, "jobStateListeners", /* @__PURE__ */ new Map());
1934
- __publicField(this, "pendingFrames", 0);
1935
- __publicField(this, "_frameloop", "always");
1936
- //* Independent Mode & Error Handling State ================================
1937
- __publicField(this, "_independent", false);
1938
- __publicField(this, "errorHandler", null);
1939
- __publicField(this, "rootReadyCallbacks", /* @__PURE__ */ new Set());
1940
- //* Core Loop Execution Methods ================================
1941
- /**
1942
- * Main RAF loop callback.
1943
- * Executes frame, handles demand mode, and schedules next frame.
1944
- * @param {number} timestamp - RAF timestamp in milliseconds
1945
- * @returns {void}
1946
- * @private
1947
- */
1948
- __publicField(this, "loop", (timestamp) => {
1949
- if (!this.loopState.running) return;
1950
- this.executeFrame(timestamp);
1951
- if (this._frameloop === "demand") {
1952
- this.pendingFrames = Math.max(0, this.pendingFrames - 1);
1953
- if (this.pendingFrames === 0) {
1954
- this.notifyIdle(timestamp);
1955
- return this.stop();
1956
- }
1957
- }
1958
- this.loopState.rafHandle = requestAnimationFrame(this.loop);
1959
- });
1960
- this.phaseGraph = new PhaseGraph();
1961
- }
1962
- static get instance() {
1963
- return globalThis[_Scheduler.INSTANCE_KEY] ?? null;
1964
- }
1965
- static set instance(value) {
1966
- globalThis[_Scheduler.INSTANCE_KEY] = value;
1967
- }
1968
- /**
1969
- * Get the global scheduler instance (creates if doesn't exist).
1970
- * Uses HMR data to preserve instance across hot reloads.
1971
- * @returns {Scheduler} The singleton scheduler instance
1972
- */
1973
- static get() {
1974
- if (!_Scheduler.instance && hmrData?.data?.scheduler) {
1975
- _Scheduler.instance = hmrData.data.scheduler;
1976
- }
1977
- if (!_Scheduler.instance) {
1978
- _Scheduler.instance = new _Scheduler();
1979
- if (hmrData?.data) {
1980
- hmrData.data.scheduler = _Scheduler.instance;
1981
- }
1982
- }
1983
- return _Scheduler.instance;
1984
- }
1985
- /**
1986
- * Reset the singleton instance. Stops the loop and clears all state.
1987
- * Primarily used for testing to ensure clean state between tests.
1988
- * @returns {void}
1989
- */
1990
- static reset() {
1991
- if (_Scheduler.instance) {
1992
- _Scheduler.instance.stop();
1993
- _Scheduler.instance = null;
1994
- }
1995
- if (hmrData?.data) {
1996
- hmrData.data.scheduler = null;
1997
- }
1998
- }
1999
- //* Getters & Setters ================================
2000
- get phases() {
2001
- return this.phaseGraph.getOrderedPhases();
2002
- }
2003
- get frameloop() {
2004
- return this._frameloop;
2005
- }
2006
- set frameloop(mode) {
2007
- if (this._frameloop === mode) return;
2008
- const wasAlways = this._frameloop === "always";
2009
- this._frameloop = mode;
2010
- if (mode === "always" && !this.loopState.running && this.roots.size > 0) this.start();
2011
- else if (mode !== "always" && wasAlways) this.stop();
2012
- }
2013
- get isRunning() {
2014
- return this.loopState.running;
2015
- }
2016
- get isReady() {
2017
- return this.roots.size > 0;
2018
- }
2019
- get independent() {
2020
- return this._independent;
2021
- }
2022
- set independent(value) {
2023
- this._independent = value;
2024
- if (value) this.ensureDefaultRoot();
2025
- }
2026
- //* Root Management Methods ================================
2027
- /**
2028
- * Register a root (Canvas) with the scheduler.
2029
- * The first root to register starts the RAF loop (if frameloop='always').
2030
- * @param {string} id - Unique identifier for this root
2031
- * @param {RootOptions} [options] - Optional configuration with getState and onError callbacks
2032
- * @returns {() => void} Unsubscribe function to remove this root
2033
- */
2034
- registerRoot(id, options = {}) {
2035
- if (this.roots.has(id)) {
2036
- console.warn(`[Scheduler] Root "${id}" already registered`);
2037
- return () => this.unregisterRoot(id);
2038
- }
2039
- const entry = {
2040
- id,
2041
- getState: options.getState ?? (() => ({})),
2042
- jobs: /* @__PURE__ */ new Map(),
2043
- sortedJobs: [],
2044
- needsRebuild: false
2045
- };
2046
- if (options.onError) {
2047
- this.errorHandler = options.onError;
2048
- }
2049
- this.roots.set(id, entry);
2050
- if (this.roots.size === 1) {
2051
- this.notifyRootReady();
2052
- if (this._frameloop === "always") this.start();
2053
- }
2054
- return () => this.unregisterRoot(id);
2055
- }
2056
- /**
2057
- * Unregister a root from the scheduler.
2058
- * Cleans up all job state listeners for this root's jobs.
2059
- * The last root to unregister stops the RAF loop.
2060
- * @param {string} id - The root ID to unregister
2061
- * @returns {void}
2062
- */
2063
- unregisterRoot(id) {
2064
- const root = this.roots.get(id);
2065
- if (!root) return;
2066
- for (const jobId of root.jobs.keys()) {
2067
- this.jobStateListeners.delete(jobId);
2068
- }
2069
- this.roots.delete(id);
2070
- if (this.roots.size === 0) {
2071
- this.stop();
2072
- this.errorHandler = null;
2073
- }
2074
- }
2075
- /**
2076
- * Subscribe to be notified when a root becomes available.
2077
- * Fires immediately if a root already exists.
2078
- * @param {() => void} callback - Function called when first root registers
2079
- * @returns {() => void} Unsubscribe function
2080
- */
2081
- onRootReady(callback) {
2082
- if (this.roots.size > 0) {
2083
- callback();
2084
- return () => {
2085
- };
2086
- }
2087
- this.rootReadyCallbacks.add(callback);
2088
- return () => this.rootReadyCallbacks.delete(callback);
2089
- }
2090
- /**
2091
- * Notify all registered root-ready callbacks.
2092
- * Called when the first root registers.
2093
- * @returns {void}
2094
- * @private
2095
- */
2096
- notifyRootReady() {
2097
- for (const cb of this.rootReadyCallbacks) {
2098
- try {
2099
- cb();
2100
- } catch (error) {
2101
- console.error("[Scheduler] Error in root-ready callback:", error);
2102
- }
2103
- }
2104
- this.rootReadyCallbacks.clear();
2105
- }
2106
- /**
2107
- * Ensure a default root exists for independent mode.
2108
- * Creates a minimal root with no state provider.
2109
- * @returns {void}
2110
- * @private
2111
- */
2112
- ensureDefaultRoot() {
2113
- if (!this.roots.has("__default__")) {
2114
- this.registerRoot("__default__");
2115
- }
2116
- }
2117
- /**
2118
- * Trigger error handling for job errors.
2119
- * Uses the bound error handler if available, otherwise logs to console.
2120
- * @param {Error} error - The error to handle
2121
- * @returns {void}
2122
- */
2123
- triggerError(error) {
2124
- if (this.errorHandler) this.errorHandler(error);
2125
- else console.error("[Scheduler]", error);
2126
- }
2127
- //* Phase Management Methods ================================
2128
- /**
2129
- * Add a named phase to the scheduler's execution order.
2130
- * Marks all roots for rebuild to incorporate the new phase.
2131
- * @param {string} name - The phase name (e.g., 'physics', 'postprocess')
2132
- * @param {AddPhaseOptions} [options] - Positioning options (before/after other phases)
2133
- * @returns {void}
2134
- * @example
2135
- * scheduler.addPhase('physics', { before: 'update' });
2136
- * scheduler.addPhase('postprocess', { after: 'render' });
2137
- */
2138
- addPhase(name, options) {
2139
- this.phaseGraph.addPhase(name, options);
2140
- for (const root of this.roots.values()) {
2141
- root.needsRebuild = true;
2142
- }
2143
- }
2144
- /**
2145
- * Check if a phase exists in the scheduler.
2146
- * @param {string} name - The phase name to check
2147
- * @returns {boolean} True if the phase exists
2148
- */
2149
- hasPhase(name) {
2150
- return this.phaseGraph.hasPhase(name);
2151
- }
2152
- //* Global Job Registration Methods (Deprecated APIs) ================================
2153
- /**
2154
- * Register a global job that runs once per frame (not per-root).
2155
- * Used internally by deprecated addEffect/addAfterEffect APIs.
2156
- * @param {'before' | 'after'} phase - When to run: 'before' all roots or 'after' all roots
2157
- * @param {string} id - Unique identifier for this global job
2158
- * @param {(timestamp: number) => void} callback - Function called each frame with RAF timestamp
2159
- * @returns {() => void} Unsubscribe function to remove this global job
2160
- * @deprecated Use useFrame with phases instead
2161
- */
2162
- registerGlobal(phase, id, callback) {
2163
- const job = { id, callback };
2164
- if (phase === "before") {
2165
- this.globalBeforeJobs.set(id, job);
2166
- } else {
2167
- this.globalAfterJobs.set(id, job);
2168
- }
2169
- return () => {
2170
- if (phase === "before") this.globalBeforeJobs.delete(id);
2171
- else this.globalAfterJobs.delete(id);
2172
- };
2173
- }
2174
- //* Idle Callback Methods (Deprecated API) ================================
2175
- /**
2176
- * Register an idle callback that fires when the loop stops.
2177
- * Used internally by deprecated addTail API.
2178
- * @param {(timestamp: number) => void} callback - Function called when loop becomes idle
2179
- * @returns {() => void} Unsubscribe function to remove this idle callback
2180
- * @deprecated Use demand mode with invalidate() instead
2181
- */
2182
- onIdle(callback) {
2183
- this.idleCallbacks.add(callback);
2184
- return () => this.idleCallbacks.delete(callback);
2185
- }
2186
- /**
2187
- * Notify all registered idle callbacks.
2188
- * Called when the loop stops in demand mode.
2189
- * @param {number} timestamp - The RAF timestamp when idle occurred
2190
- * @returns {void}
2191
- * @private
2192
- */
2193
- notifyIdle(timestamp) {
2194
- for (const cb of this.idleCallbacks) {
2195
- try {
2196
- cb(timestamp);
2197
- } catch (error) {
2198
- console.error("[Scheduler] Error in idle callback:", error);
2199
- }
2200
- }
2201
- }
2202
- //* Job Registration & Management Methods ================================
2203
- /**
2204
- * Register a job (frame callback) with a specific root.
2205
- * This is the core registration method used by useFrame internally.
2206
- * @param {FrameNextCallback} callback - The function to call each frame
2207
- * @param {JobOptions & { rootId?: string; system?: boolean }} [options] - Job configuration
2208
- * @param {string} [options.rootId] - Target root ID (defaults to first registered root)
2209
- * @param {string} [options.id] - Unique job ID (auto-generated if not provided)
2210
- * @param {string} [options.phase] - Execution phase (defaults to 'update')
2211
- * @param {number} [options.priority] - Priority within phase (higher = earlier, default 0)
2212
- * @param {number} [options.fps] - FPS throttle limit
2213
- * @param {boolean} [options.drop] - Drop frames when behind (default true)
2214
- * @param {boolean} [options.enabled] - Whether job is active (default true)
2215
- * @param {boolean} [options.system] - Internal flag for system jobs (not user-facing)
2216
- * @returns {() => void} Unsubscribe function to remove this job
2217
- */
2218
- register(callback, options = {}) {
2219
- const rootId = options.rootId;
2220
- const root = rootId ? this.roots.get(rootId) : this.roots.values().next().value;
2221
- if (!root) {
2222
- console.warn("[Scheduler] No root registered. Is this inside a Canvas?");
2223
- return () => {
2224
- };
2225
- }
2226
- const id = options.id ?? this.generateJobId();
2227
- let phase = options.phase ?? "update";
2228
- if (!options.phase && (options.before || options.after)) {
2229
- phase = this.phaseGraph.resolveConstraintPhase(options.before, options.after);
2230
- }
2231
- const before = this.normalizeConstraints(options.before);
2232
- const after = this.normalizeConstraints(options.after);
2233
- const job = {
2234
- id,
2235
- callback,
2236
- phase,
2237
- before,
2238
- after,
2239
- priority: options.priority ?? 0,
2240
- index: this.nextJobIndex++,
2241
- fps: options.fps,
2242
- drop: options.drop ?? true,
2243
- enabled: options.enabled ?? true,
2244
- system: options.system ?? false
2245
- };
2246
- if (root.jobs.has(id)) {
2247
- console.warn(`[useFrame] Job with id "${id}" already exists, replacing`);
2248
- }
2249
- root.jobs.set(id, job);
2250
- root.needsRebuild = true;
2251
- return () => this.unregister(id, root.id);
2252
- }
2253
- /**
2254
- * Unregister a job by its ID.
2255
- * Searches all roots if rootId is not provided.
2256
- * @param {string} id - The job ID to unregister
2257
- * @param {string} [rootId] - Optional root ID to search (searches all if not provided)
2258
- * @returns {void}
2259
- */
2260
- unregister(id, rootId) {
2261
- const root = rootId ? this.roots.get(rootId) : Array.from(this.roots.values()).find((r) => r.jobs.has(id));
2262
- if (root?.jobs.delete(id)) {
2263
- root.needsRebuild = true;
2264
- this.jobStateListeners.delete(id);
2265
- }
2266
- }
2267
- /**
2268
- * Update a job's options dynamically.
2269
- * Searches all roots to find the job by ID.
2270
- * Phase/constraint changes trigger a rebuild of the sorted job list.
2271
- * @param {string} id - The job ID to update
2272
- * @param {Partial<JobOptions>} options - The options to update
2273
- * @returns {void}
2274
- */
2275
- updateJob(id, options) {
2276
- let job;
2277
- let root;
2278
- for (const r of this.roots.values()) {
2279
- job = r.jobs.get(id);
2280
- if (job) {
2281
- root = r;
2282
- break;
2283
- }
2284
- }
2285
- if (!job || !root) return;
2286
- if (options.priority !== void 0) job.priority = options.priority;
2287
- if (options.fps !== void 0) job.fps = options.fps;
2288
- if (options.drop !== void 0) job.drop = options.drop;
2289
- if (options.enabled !== void 0) {
2290
- const wasEnabled = job.enabled;
2291
- job.enabled = options.enabled;
2292
- if (!wasEnabled && job.enabled) resetJobTiming(job);
2293
- if (wasEnabled !== job.enabled) root.needsRebuild = true;
2294
- }
2295
- if (options.phase !== void 0 || options.before !== void 0 || options.after !== void 0) {
2296
- if (options.phase) job.phase = options.phase;
2297
- if (options.before !== void 0) job.before = this.normalizeConstraints(options.before);
2298
- if (options.after !== void 0) job.after = this.normalizeConstraints(options.after);
2299
- root.needsRebuild = true;
2300
- }
2301
- }
2302
- //* Job State Management Methods ================================
2303
- /**
2304
- * Check if a job is currently paused (disabled).
2305
- * @param {string} id - The job ID to check
2306
- * @returns {boolean} True if the job exists and is paused
2307
- */
2308
- isJobPaused(id) {
2309
- for (const root of this.roots.values()) {
2310
- const job = root.jobs.get(id);
2311
- if (job) return !job.enabled;
2312
- }
2313
- return false;
2314
- }
2315
- /**
2316
- * Subscribe to state changes for a specific job.
2317
- * Listener is called when job is paused or resumed.
2318
- * @param {string} id - The job ID to subscribe to
2319
- * @param {() => void} listener - Callback invoked on state changes
2320
- * @returns {() => void} Unsubscribe function
2321
- */
2322
- subscribeJobState(id, listener) {
2323
- if (!this.jobStateListeners.has(id)) {
2324
- this.jobStateListeners.set(id, /* @__PURE__ */ new Set());
2325
- }
2326
- this.jobStateListeners.get(id).add(listener);
2327
- return () => {
2328
- this.jobStateListeners.get(id)?.delete(listener);
2329
- if (this.jobStateListeners.get(id)?.size === 0) {
2330
- this.jobStateListeners.delete(id);
2331
- }
2332
- };
2333
- }
2334
- /**
2335
- * Notify all listeners that a job's state has changed.
2336
- * @param {string} id - The job ID that changed
2337
- * @returns {void}
2338
- * @private
2339
- */
2340
- notifyJobStateChange(id) {
2341
- this.jobStateListeners.get(id)?.forEach((listener) => listener());
2342
- }
2343
- /**
2344
- * Pause a job by ID (sets enabled=false).
2345
- * Notifies any subscribed state listeners.
2346
- * @param {string} id - The job ID to pause
2347
- * @returns {void}
2348
- */
2349
- pauseJob(id) {
2350
- this.updateJob(id, { enabled: false });
2351
- this.notifyJobStateChange(id);
2352
- }
2353
- /**
2354
- * Resume a paused job by ID (sets enabled=true).
2355
- * Resets job timing to prevent frame accumulation.
2356
- * Notifies any subscribed state listeners.
2357
- * @param {string} id - The job ID to resume
2358
- * @returns {void}
2359
- */
2360
- resumeJob(id) {
2361
- this.updateJob(id, { enabled: true });
2362
- this.notifyJobStateChange(id);
2363
- }
2364
- //* Frame Loop Control Methods ================================
2365
- /**
2366
- * Start the requestAnimationFrame loop.
2367
- * Resets timing state (elapsedTime, frameCount) on start.
2368
- * No-op if already running.
2369
- * @returns {void}
2370
- */
2371
- start() {
2372
- if (this.loopState.running) return;
2373
- const { elapsedTime, createdAt } = this.loopState;
2374
- let adjustedCreated = 0;
2375
- if (this.stoppedTime > 0) {
2376
- adjustedCreated = createdAt - (performance.now() - this.stoppedTime);
2377
- this.stoppedTime = 0;
2378
- }
2379
- Object.assign(this.loopState, {
2380
- running: true,
2381
- elapsedTime: elapsedTime ?? 0,
2382
- lastTime: performance.now(),
2383
- createdAt: adjustedCreated > 0 ? adjustedCreated : performance.now(),
2384
- frameCount: 0,
2385
- rafHandle: requestAnimationFrame(this.loop)
2386
- });
2387
- }
2388
- /**
2389
- * Stop the requestAnimationFrame loop.
2390
- * Cancels any pending RAF callback.
2391
- * No-op if not running.
2392
- * @returns {void}
2393
- */
2394
- stop() {
2395
- if (!this.loopState.running) return;
2396
- this.loopState.running = false;
2397
- if (this.loopState.rafHandle !== null) {
2398
- cancelAnimationFrame(this.loopState.rafHandle);
2399
- this.loopState.rafHandle = null;
2400
- }
2401
- this.stoppedTime = performance.now();
2402
- }
2403
- /**
2404
- * Request frames to be rendered in demand mode.
2405
- * Accumulates pending frames (capped at 60) and starts the loop if not running.
2406
- * No-op if frameloop is not 'demand'.
2407
- * @param {number} [frames=1] - Number of frames to request
2408
- * @param {boolean} [stackFrames=false] - Whether to add frames to existing pending count
2409
- * - `false` (default): Sets pending frames to the specified value (replaces existing count)
2410
- * - `true`: Adds frames to existing pending count (useful for accumulating invalidations)
2411
- * @returns {void}
2412
- * @example
2413
- * // Request a single frame render
2414
- * scheduler.invalidate();
2415
- *
2416
- * @example
2417
- * // Request 5 frames (e.g., for animations)
2418
- * scheduler.invalidate(5);
2419
- *
2420
- * @example
2421
- * // Set pending frames to exactly 3 (don't stack with existing)
2422
- * scheduler.invalidate(3, false);
2423
- *
2424
- * @example
2425
- * // Add 2 more frames to existing pending count
2426
- * scheduler.invalidate(2, true);
2427
- */
2428
- invalidate(frames = 1, stackFrames = false) {
2429
- if (this._frameloop !== "demand") return;
2430
- const baseFrames = stackFrames ? this.pendingFrames : 0;
2431
- this.pendingFrames = Math.min(60, baseFrames + frames);
2432
- if (!this.loopState.running && this.pendingFrames > 0) this.start();
2433
- }
2434
- /**
2435
- * Reset timing state for deterministic testing.
2436
- * Preserves jobs and roots but resets lastTime, frameCount, elapsedTime, etc.
2437
- * @returns {void}
2438
- */
2439
- resetTiming() {
2440
- this.loopState.lastTime = null;
2441
- this.loopState.frameCount = 0;
2442
- this.loopState.elapsedTime = 0;
2443
- this.loopState.createdAt = performance.now();
2444
- }
2445
- //* Manual Stepping Methods ================================
2446
- /**
2447
- * Manually execute a single frame for all roots.
2448
- * Useful for frameloop='never' mode or testing scenarios.
2449
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2450
- * @returns {void}
2451
- * @example
2452
- * // Manual control mode
2453
- * scheduler.frameloop = 'never';
2454
- * scheduler.step(); // Execute one frame
2455
- */
2456
- step(timestamp) {
2457
- const now = timestamp ?? performance.now();
2458
- this.executeFrame(now);
2459
- }
2460
- /**
2461
- * Manually execute a single job by its ID.
2462
- * Useful for testing individual job callbacks in isolation.
2463
- * @param {string} id - The job ID to step
2464
- * @param {number} [timestamp] - Optional timestamp (defaults to performance.now())
2465
- * @returns {void}
2466
- */
2467
- stepJob(id, timestamp) {
2468
- let job;
2469
- let root;
2470
- for (const r of this.roots.values()) {
2471
- job = r.jobs.get(id);
2472
- if (job) {
2473
- root = r;
2474
- break;
2475
- }
2476
- }
2477
- if (!job || !root) {
2478
- console.warn(`[Scheduler] Job "${id}" not found`);
2479
- return;
2480
- }
2481
- const now = timestamp ?? performance.now();
2482
- const deltaMs = this.loopState.lastTime !== null ? now - this.loopState.lastTime : 0;
2483
- const delta = deltaMs / 1e3;
2484
- const elapsed = now - this.loopState.createdAt;
2485
- const providedState = root.getState?.() ?? {};
2486
- const frameState = {
2487
- ...providedState,
2488
- time: now,
2489
- delta,
2490
- elapsed,
2491
- frame: this.loopState.frameCount
2492
- };
2493
- try {
2494
- job.callback(frameState, delta);
2495
- } catch (error) {
2496
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2497
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2498
- }
2499
- }
2500
- /**
2501
- * Execute a single frame across all roots.
2502
- * Order: globalBefore → each root's jobs → globalAfter
2503
- * @param {number} timestamp - RAF timestamp in milliseconds
2504
- * @returns {void}
2505
- * @private
2506
- */
2507
- executeFrame(timestamp) {
2508
- const deltaMs = this.loopState.lastTime !== null ? timestamp - this.loopState.lastTime : 0;
2509
- const delta = deltaMs / 1e3;
2510
- this.loopState.lastTime = timestamp;
2511
- this.loopState.frameCount++;
2512
- this.loopState.elapsedTime += deltaMs;
2513
- this.runGlobalJobs(this.globalBeforeJobs, timestamp);
2514
- for (const root of this.roots.values()) {
2515
- this.tickRoot(root, timestamp, delta);
2516
- }
2517
- this.runGlobalJobs(this.globalAfterJobs, timestamp);
2518
- }
2519
- /**
2520
- * Run all global jobs from a job map.
2521
- * Catches and logs errors without stopping execution.
2522
- * @param {Map<string, GlobalJob>} jobs - The global jobs map to execute
2523
- * @param {number} timestamp - RAF timestamp in milliseconds
2524
- * @returns {void}
2525
- * @private
2526
- */
2527
- runGlobalJobs(jobs, timestamp) {
2528
- for (const job of jobs.values()) {
2529
- try {
2530
- job.callback(timestamp);
2531
- } catch (error) {
2532
- console.error(`[Scheduler] Error in global job "${job.id}":`, error);
2533
- }
2534
- }
2535
- }
2536
- /**
2537
- * Execute all jobs for a single root in sorted order.
2538
- * Rebuilds sorted job list if needed, then dispatches each job.
2539
- * Errors are caught and propagated via triggerError.
2540
- * @param {RootEntry} root - The root entry to tick
2541
- * @param {number} timestamp - RAF timestamp in milliseconds
2542
- * @param {number} delta - Time since last frame in seconds
2543
- * @returns {void}
2544
- * @private
2545
- */
2546
- tickRoot(root, timestamp, delta) {
2547
- if (root.needsRebuild) {
2548
- root.sortedJobs = rebuildSortedJobs(root.jobs, this.phaseGraph);
2549
- root.needsRebuild = false;
2550
- }
2551
- const providedState = root.getState?.() ?? {};
2552
- const frameState = {
2553
- ...providedState,
2554
- time: timestamp,
2555
- delta,
2556
- elapsed: this.loopState.elapsedTime / 1e3,
2557
- // Convert ms to seconds
2558
- frame: this.loopState.frameCount
2559
- };
2560
- for (const job of root.sortedJobs) {
2561
- if (!shouldRun(job, timestamp)) continue;
2562
- try {
2563
- job.callback(frameState, delta);
2564
- } catch (error) {
2565
- console.error(`[Scheduler] Error in job "${job.id}":`, error);
2566
- this.triggerError(error instanceof Error ? error : new Error(String(error)));
2567
- }
2568
- }
2569
- }
2570
- //* Debug & Inspection Methods ================================
2571
- /**
2572
- * Get the total number of registered jobs across all roots.
2573
- * Includes both per-root jobs and global before/after jobs.
2574
- * @returns {number} Total job count
2575
- */
2576
- getJobCount() {
2577
- let count = 0;
2578
- for (const root of this.roots.values()) {
2579
- count += root.jobs.size;
2580
- }
2581
- return count + this.globalBeforeJobs.size + this.globalAfterJobs.size;
2582
- }
2583
- /**
2584
- * Get all registered job IDs across all roots.
2585
- * Includes both per-root jobs and global before/after jobs.
2586
- * @returns {string[]} Array of all job IDs
2587
- */
2588
- getJobIds() {
2589
- const ids = [];
2590
- for (const root of this.roots.values()) {
2591
- ids.push(...root.jobs.keys());
2592
- }
2593
- ids.push(...this.globalBeforeJobs.keys());
2594
- ids.push(...this.globalAfterJobs.keys());
2595
- return ids;
2596
- }
2597
- /**
2598
- * Get the number of registered roots (Canvas instances).
2599
- * @returns {number} Number of registered roots
2600
- */
2601
- getRootCount() {
2602
- return this.roots.size;
2603
- }
2604
- /**
2605
- * Check if any user (non-system) jobs are registered in a specific phase.
2606
- * Used by the default render job to know if a user has taken over rendering.
2607
- *
2608
- * @param phase The phase to check
2609
- * @param rootId Optional root ID to check (checks all roots if not provided)
2610
- * @returns true if any user jobs exist in the phase
2611
- */
2612
- hasUserJobsInPhase(phase, rootId) {
2613
- const rootsToCheck = rootId ? [this.roots.get(rootId)].filter(Boolean) : Array.from(this.roots.values());
2614
- return rootsToCheck.some((root) => {
2615
- if (!root) return false;
2616
- for (const job of root.jobs.values()) {
2617
- if (job.phase === phase && !job.system && job.enabled) return true;
2618
- }
2619
- return false;
2620
- });
2621
- }
2622
- //* Utility Methods ================================
2623
- /**
2624
- * Generate a unique root ID for automatic root registration.
2625
- * @returns {string} A unique root ID in the format 'root_N'
2626
- */
2627
- generateRootId() {
2628
- return `root_${this.nextRootIndex++}`;
2629
- }
2630
- /**
2631
- * Generate a unique job ID.
2632
- * @returns {string} A unique job ID in the format 'job_N'
2633
- * @private
2634
- */
2635
- generateJobId() {
2636
- return `job_${this.nextJobIndex}`;
2637
- }
2638
- /**
2639
- * Normalize before/after constraints to a Set.
2640
- * Handles undefined, single string, or array inputs.
2641
- * @param {string | string[] | undefined} value - The constraint value(s)
2642
- * @returns {Set<string>} Normalized Set of constraint strings
2643
- * @private
2644
- */
2645
- normalizeConstraints(value) {
2646
- if (!value) return /* @__PURE__ */ new Set();
2647
- if (Array.isArray(value)) return new Set(value);
2648
- return /* @__PURE__ */ new Set([value]);
2649
- }
2650
- };
2651
- //* Static State & Methods (Singleton Usage) ================================
2652
- //* Cross-Bundle Singleton Key ==============================
2653
- // Use Symbol.for() to ensure scheduler is shared across bundle boundaries
2654
- // This prevents issues when mixing imports from @react-three/fiber and @react-three/fiber/webgpu
2655
- __publicField(_Scheduler, "INSTANCE_KEY", Symbol.for("@react-three/fiber.scheduler"));
2656
- let Scheduler = _Scheduler;
2657
- const getScheduler = () => Scheduler.get();
2658
- if (hmrData) {
2659
- hmrData.accept?.();
1662
+ const INTERNAL_LIB_MARKERS = ["zustand", "setState", "Object.assign"];
1663
+ function isInternalRendererAccess(stack, callerDepth = 2) {
1664
+ if (!stack) return false;
1665
+ const caller = stack.split("\n")[callerDepth] ?? "";
1666
+ return INTERNAL_LIB_MARKERS.some((m) => caller.includes(m));
2660
1667
  }
2661
1668
 
2662
1669
  const R3F_CONTEXT = Symbol.for("@react-three/fiber.context");
@@ -2791,6 +1798,7 @@ const createStore = (invalidate, advance) => {
2791
1798
  }),
2792
1799
  setFrameloop: (frameloop = "always") => {
2793
1800
  set(() => ({ frameloop }));
1801
+ getScheduler().frameloop = frameloop;
2794
1802
  },
2795
1803
  setError: (error) => set(() => ({ error })),
2796
1804
  error: null,
@@ -2800,6 +1808,7 @@ const createStore = (invalidate, advance) => {
2800
1808
  buffers: {},
2801
1809
  gpuStorage: {},
2802
1810
  textures: /* @__PURE__ */ new Map(),
1811
+ _textureRefs: /* @__PURE__ */ new Map(),
2803
1812
  renderPipeline: null,
2804
1813
  passes: {},
2805
1814
  _hmrVersion: 0,
@@ -2857,8 +1866,7 @@ const createStore = (invalidate, advance) => {
2857
1866
  const currentState = rootStore.getState();
2858
1867
  if (!currentState.isLegacy && currentState.internal.actualRenderer) {
2859
1868
  const stack = new Error().stack || "";
2860
- const isInternalAccess = stack.includes("zustand") || stack.includes("setState") || stack.includes("Object.assign") || stack.includes("react-three-fiber/packages/fiber/src/core");
2861
- if (!isInternalAccess) {
1869
+ if (!isInternalRendererAccess(stack)) {
2862
1870
  const cleanedStack = stack.split("\n").slice(2).join("\n") || "Stack trace unavailable";
2863
1871
  notifyDepreciated({
2864
1872
  heading: "Accessing state.gl in WebGPU mode",
@@ -2971,19 +1979,25 @@ function loadingFn(extensions, onProgress) {
2971
1979
  );
2972
1980
  };
2973
1981
  }
2974
- function useLoader(loader, input, extensions, onProgress) {
2975
- const keys = Array.isArray(input) ? input : [input];
1982
+ function useLoader(loader, input, extensions, onProgress, cacheKey) {
1983
+ const inputs = Array.isArray(input) ? input : [input];
1984
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2976
1985
  const fn = loadingFn(extensions, onProgress);
2977
- const results = keys.map((key) => suspend(fn, [loader, key], { equal: is.equ }));
1986
+ const results = cacheKeys.map(
1987
+ (key, index) => suspend(() => fn(loader, inputs[index]), [loader, key], { equal: is.equ })
1988
+ );
2978
1989
  return Array.isArray(input) ? results : results[0];
2979
1990
  }
2980
- useLoader.preload = function(loader, input, extensions, onProgress) {
2981
- const keys = Array.isArray(input) ? input : [input];
2982
- keys.forEach((key) => preload(loadingFn(extensions, onProgress), [loader, key]));
1991
+ useLoader.preload = function(loader, input, extensions, onProgress, cacheKey) {
1992
+ const inputs = Array.isArray(input) ? input : [input];
1993
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
1994
+ cacheKeys.forEach(
1995
+ (key, index) => preload(() => loadingFn(extensions, onProgress)(loader, inputs[index]), [loader, key])
1996
+ );
2983
1997
  };
2984
- useLoader.clear = function(loader, input) {
2985
- const keys = Array.isArray(input) ? input : [input];
2986
- keys.forEach((key) => clear([loader, key]));
1998
+ useLoader.clear = function(loader, input, cacheKey) {
1999
+ const cacheKeys = Array.isArray(cacheKey ?? input) ? cacheKey ?? input : [cacheKey ?? input];
2000
+ cacheKeys.forEach((key) => clear([loader, key]));
2987
2001
  };
2988
2002
  useLoader.loader = getLoader;
2989
2003
 
@@ -3059,20 +2073,14 @@ function useFrame(callback, priorityOrOptions) {
3059
2073
  }
3060
2074
  };
3061
2075
  } else {
3062
- const registerOutside = () => {
3063
- return scheduler.register((state, delta) => callbackRef.current?.(state, delta), { id, ...options });
3064
- };
3065
- if (scheduler.independent || scheduler.isReady) {
3066
- return registerOutside();
3067
- }
3068
- let unregisterJob = null;
3069
- const unsubReady = scheduler.onRootReady(() => {
3070
- unregisterJob = registerOutside();
3071
- });
3072
- return () => {
3073
- unsubReady();
3074
- unregisterJob?.();
3075
- };
2076
+ return scheduler.register(
2077
+ (state, delta) => {
2078
+ const frameState = state;
2079
+ if (!frameState.renderer) return;
2080
+ callbackRef.current?.(frameState, delta);
2081
+ },
2082
+ { id, ...options }
2083
+ );
3076
2084
  }
3077
2085
  }, [store, scheduler, id, optionsKey, isLegacyPriority, isInsideCanvas]);
3078
2086
  const isPaused = React.useSyncExternalStore(
@@ -3163,18 +2171,18 @@ function buildFromCache(input, textureCache) {
3163
2171
  function useTexture(input, optionsOrOnLoad) {
3164
2172
  const renderer = useThree((state) => state.internal.actualRenderer);
3165
2173
  const store = useStore();
3166
- const textureCache = useThree((state) => state.textures);
3167
2174
  const options = typeof optionsOrOnLoad === "function" ? { onLoad: optionsOrOnLoad } : optionsOrOnLoad ?? {};
3168
- const { onLoad, cache = false } = options;
2175
+ const { onLoad, cache = true } = options;
3169
2176
  const onLoadRef = useRef(onLoad);
3170
2177
  onLoadRef.current = onLoad;
3171
2178
  const onLoadCalledForRef = useRef(null);
3172
2179
  const urls = useMemo(() => getUrls(input), [input]);
3173
2180
  const cachedResult = useMemo(() => {
3174
2181
  if (!cache) return null;
3175
- if (!allUrlsCached(urls, textureCache)) return null;
3176
- return buildFromCache(input, textureCache);
3177
- }, [cache, urls, textureCache, input]);
2182
+ const textures = store.getState().textures;
2183
+ if (!allUrlsCached(urls, textures)) return null;
2184
+ return buildFromCache(input, textures);
2185
+ }, [cache, urls, input, store]);
3178
2186
  const loadedTextures = useLoader(
3179
2187
  TextureLoader,
3180
2188
  IsObject(input) ? Object.values(input) : input
@@ -3218,8 +2226,6 @@ function useTexture(input, optionsOrOnLoad) {
3218
2226
  }, [input, loadedTextures, cachedResult]);
3219
2227
  useEffect(() => {
3220
2228
  if (!cache) return;
3221
- if (cachedResult) return;
3222
- const set = store.setState;
3223
2229
  const urlTextureMap = [];
3224
2230
  if (typeof input === "string") {
3225
2231
  urlTextureMap.push([input, mappedTextures]);
@@ -3233,18 +2239,32 @@ function useTexture(input, optionsOrOnLoad) {
3233
2239
  urlTextureMap.push([url, textureRecord[key]]);
3234
2240
  }
3235
2241
  }
3236
- set((state) => {
3237
- const newMap = new Map(state.textures);
3238
- let changed = false;
2242
+ store.setState((state) => {
2243
+ const refs = new Map(state._textureRefs);
2244
+ let textures = state.textures;
2245
+ let added = false;
3239
2246
  for (const [url, texture] of urlTextureMap) {
3240
- if (!newMap.has(url)) {
3241
- newMap.set(url, texture);
3242
- changed = true;
2247
+ if (!textures.has(url)) {
2248
+ if (!added) {
2249
+ textures = new Map(textures);
2250
+ added = true;
2251
+ }
2252
+ textures.set(url, texture);
3243
2253
  }
2254
+ refs.set(url, (refs.get(url) ?? 0) + 1);
3244
2255
  }
3245
- return changed ? { textures: newMap } : state;
2256
+ return added ? { textures, _textureRefs: refs } : { _textureRefs: refs };
3246
2257
  });
3247
- }, [cache, input, mappedTextures, store, cachedResult]);
2258
+ return () => store.setState((state) => {
2259
+ const refs = new Map(state._textureRefs);
2260
+ for (const [url] of urlTextureMap) {
2261
+ const next = (refs.get(url) ?? 0) - 1;
2262
+ if (next <= 0) refs.delete(url);
2263
+ else refs.set(url, next);
2264
+ }
2265
+ return { _textureRefs: refs };
2266
+ });
2267
+ }, [cache, input, mappedTextures, store]);
3248
2268
  return mappedTextures;
3249
2269
  }
3250
2270
  useTexture.preload = (url) => useLoader.preload(TextureLoader, url);
@@ -3260,96 +2280,63 @@ const Texture = ({
3260
2280
  return /* @__PURE__ */ jsx(Fragment, { children: children?.(ret) });
3261
2281
  };
3262
2282
 
3263
- function getTextureValue(entry) {
3264
- if (entry instanceof Texture$1) return entry;
3265
- if (entry && typeof entry === "object" && "value" in entry && entry.value instanceof Texture$1) {
3266
- return entry.value;
3267
- }
3268
- return null;
3269
- }
3270
- function useTextures() {
2283
+ function useTextures(selector) {
3271
2284
  const store = useStore();
3272
- return useMemo(() => {
3273
- const set = store.setState;
2285
+ const registry = useMemo(() => {
3274
2286
  const getState = store.getState;
3275
- const add = (key, value) => {
3276
- set((state) => {
3277
- const newMap = new Map(state.textures);
3278
- newMap.set(key, value);
3279
- return { textures: newMap };
3280
- });
3281
- };
3282
- const addMultiple = (items) => {
3283
- set((state) => {
3284
- const newMap = new Map(state.textures);
3285
- const entries = items instanceof Map ? items.entries() : Object.entries(items);
3286
- for (const [key, value] of entries) {
3287
- newMap.set(key, value);
3288
- }
3289
- return { textures: newMap };
3290
- });
3291
- };
3292
- const remove = (key) => {
3293
- set((state) => {
3294
- const newMap = new Map(state.textures);
3295
- newMap.delete(key);
3296
- return { textures: newMap };
3297
- });
3298
- };
3299
- const removeMultiple = (keys) => {
3300
- set((state) => {
3301
- const newMap = new Map(state.textures);
3302
- for (const key of keys) newMap.delete(key);
3303
- return { textures: newMap };
3304
- });
3305
- };
3306
- const dispose = (key) => {
3307
- const entry = getState().textures.get(key);
3308
- if (entry) {
3309
- const tex = getTextureValue(entry);
3310
- tex?.dispose();
3311
- }
3312
- remove(key);
3313
- };
3314
- const disposeMultiple = (keys) => {
3315
- const textures = getState().textures;
3316
- for (const key of keys) {
3317
- const entry = textures.get(key);
3318
- if (entry) {
3319
- const tex = getTextureValue(entry);
3320
- tex?.dispose();
3321
- }
3322
- }
3323
- removeMultiple(keys);
3324
- };
3325
- const disposeAll = () => {
3326
- const textures = getState().textures;
3327
- for (const entry of textures.values()) {
3328
- const tex = getTextureValue(entry);
3329
- tex?.dispose();
3330
- }
3331
- set({ textures: /* @__PURE__ */ new Map() });
3332
- };
2287
+ const setState = store.setState;
2288
+ const getOne = (key) => getState().textures.get(key);
3333
2289
  return {
3334
- // Getter for the textures Map (reactive via getState)
3335
- get textures() {
2290
+ get all() {
3336
2291
  return getState().textures;
3337
2292
  },
3338
- // Read
3339
- get: (key) => getState().textures.get(key),
2293
+ get(input) {
2294
+ if (typeof input === "string") return getOne(input);
2295
+ if (Array.isArray(input)) return input.map(getOne);
2296
+ const out = {};
2297
+ for (const name in input) out[name] = getOne(input[name]);
2298
+ return out;
2299
+ },
3340
2300
  has: (key) => getState().textures.has(key),
3341
- // Write
3342
- add,
3343
- addMultiple,
3344
- // Remove (cache only)
3345
- remove,
3346
- removeMultiple,
3347
- // Dispose (GPU + cache)
3348
- dispose,
3349
- disposeMultiple,
3350
- disposeAll
2301
+ add(keyOrRecord, texture) {
2302
+ setState((state) => {
2303
+ const textures = new Map(state.textures);
2304
+ if (typeof keyOrRecord === "string") {
2305
+ textures.set(keyOrRecord, texture);
2306
+ } else {
2307
+ for (const key in keyOrRecord) textures.set(key, keyOrRecord[key]);
2308
+ }
2309
+ return { textures };
2310
+ });
2311
+ },
2312
+ dispose(key, options) {
2313
+ const state = getState();
2314
+ const refs = state._textureRefs.get(key) ?? 0;
2315
+ if (refs > 0 && !options?.force) {
2316
+ console.warn(
2317
+ `[useTextures] "${key}" still has ${refs} active reference(s); skipping dispose. Pass { force: true } to override.`
2318
+ );
2319
+ return false;
2320
+ }
2321
+ state.textures.get(key)?.dispose();
2322
+ setState((s) => {
2323
+ const textures = new Map(s.textures);
2324
+ textures.delete(key);
2325
+ const nextRefs = new Map(s._textureRefs);
2326
+ nextRefs.delete(key);
2327
+ return { textures, _textureRefs: nextRefs };
2328
+ });
2329
+ return true;
2330
+ },
2331
+ disposeAll() {
2332
+ for (const texture of getState().textures.values()) texture.dispose();
2333
+ setState({ textures: /* @__PURE__ */ new Map(), _textureRefs: /* @__PURE__ */ new Map() });
2334
+ }
3351
2335
  };
3352
2336
  }, [store]);
2337
+ const subscribe = selector ? () => selector(registry) : (state) => state.textures;
2338
+ const selected = useThree(subscribe);
2339
+ return selector ? selected : registry;
3353
2340
  }
3354
2341
 
3355
2342
  function useRenderTarget(widthOrOptions, heightOrOptions, options) {
@@ -3432,7 +2419,7 @@ function advance(timestamp) {
3432
2419
  getScheduler().step(timestamp);
3433
2420
  }
3434
2421
 
3435
- const version = "10.0.0-alpha.2";
2422
+ const version = "10.0.0-alpha.3";
3436
2423
  const packageData = {
3437
2424
  version: version};
3438
2425
 
@@ -14871,6 +13858,7 @@ function swapInstances() {
14871
13858
  }
14872
13859
  }
14873
13860
  if (instance.isHidden) unhideInstance(instance);
13861
+ if (isObject3D(instance.object)) removeInteractivity(findInitialRoot(instance), instance.object);
14874
13862
  if (instance.object.__r3f) delete instance.object.__r3f;
14875
13863
  if (instance.type !== "primitive") disposeOnIdle(instance.object);
14876
13864
  }
@@ -14883,6 +13871,8 @@ function swapInstances() {
14883
13871
  instance.object.__r3f = instance;
14884
13872
  setFiberRef(fiber, instance.object);
14885
13873
  delete instance.appliedOnce;
13874
+ instance.eventCount = 0;
13875
+ instance.handlers = {};
14886
13876
  applyProps(instance.object, instance.props);
14887
13877
  if (instance.props.attach) {
14888
13878
  attach(parent, instance);
@@ -15098,11 +14088,15 @@ const reconciler = /* @__PURE__ */ createReconciler({
15098
14088
  cloneMutableTextInstance(textInstance) {
15099
14089
  return textInstance;
15100
14090
  },
14091
+ // React 19.2 added these for root-level view transitions. They only run for hosts that opt into
14092
+ // view transitions by returning a container from cloneRootViewTransitionContainer; R3F renders
14093
+ // into a WebGL/WebGPU canvas, where cloning the root has no meaning, so we never opt in and
14094
+ // React never calls them. They stay as no-ops rather than throws: the host config is shared by
14095
+ // every root, and a throw here would turn a React-internal probe into a hard crash for users.
14096
+ // Guarded by a test asserting a full render + unmount never reaches them.
15101
14097
  cloneRootViewTransitionContainer(_rootContainer) {
15102
- throw new Error("Not implemented.");
15103
14098
  },
15104
14099
  removeRootViewTransitionClone(_rootContainer, _clone) {
15105
- throw new Error("Not implemented.");
15106
14100
  },
15107
14101
  // https://github.com/facebook/react/pull/32465
15108
14102
  createFragmentInstance: (_fiber) => null,
@@ -15187,6 +14181,7 @@ function createRoot(canvas) {
15187
14181
  const lastConfiguredProps = {};
15188
14182
  let configured = false;
15189
14183
  let pending = null;
14184
+ let rendererSetup = null;
15190
14185
  return {
15191
14186
  async configure(props = {}) {
15192
14187
  let resolve;
@@ -15217,7 +14212,7 @@ function createRoot(canvas) {
15217
14212
  forceEven
15218
14213
  } = props;
15219
14214
  const textureColorSpace = is.obj(glConfig) && !is.fun(glConfig) && !isRenderer(glConfig) && glConfig.textureColorSpace || is.obj(rendererConfig) && !is.fun(rendererConfig) && !isRenderer(rendererConfig) && rendererConfig.textureColorSpace || SRGBColorSpace;
15220
- const state = store.getState();
14215
+ let state = store.getState();
15221
14216
  const defaultGLProps = {
15222
14217
  canvas,
15223
14218
  powerPreference: "high-performance",
@@ -15245,56 +14240,68 @@ function createRoot(canvas) {
15245
14240
  "The `primaryCanvas` prop for multi-canvas rendering cannot be used with WebGL. Remove the `gl` prop or use WebGPU."
15246
14241
  );
15247
14242
  }
15248
- if (wantsGL && !state.internal.actualRenderer) {
15249
- renderer = await resolveRenderer(glConfig, defaultGLProps, WebGLRenderer);
15250
- state.internal.actualRenderer = renderer;
15251
- state.set({ isLegacy: true, gl: renderer, renderer, primaryStore: store });
15252
- } else if (!wantsGL && primaryCanvas && !state.internal.actualRenderer) {
15253
- const primary = await waitForPrimary(primaryCanvas);
15254
- renderer = primary.renderer;
15255
- state.internal.actualRenderer = renderer;
15256
- const canvasTarget = new CanvasTarget(canvas);
15257
- primary.store.setState((prev) => ({
15258
- internal: { ...prev.internal, isMultiCanvas: true }
15259
- }));
15260
- state.set((prev) => ({
15261
- webGPUSupported: primary.store.getState().webGPUSupported,
15262
- renderer,
15263
- primaryStore: primary.store,
15264
- internal: {
15265
- ...prev.internal,
15266
- canvasTarget,
15267
- isMultiCanvas: true,
15268
- isSecondary: true,
15269
- targetId: primaryCanvas
15270
- }
15271
- }));
15272
- } else if (!wantsGL && !state.internal.actualRenderer) {
15273
- renderer = await resolveRenderer(rendererConfig, defaultGPUProps, WebGPURenderer);
15274
- if (!renderer.hasInitialized?.()) {
15275
- const size2 = computeInitialSize(canvas, propsSize);
15276
- if (size2.width > 0 && size2.height > 0) {
15277
- const pixelRatio = calculateDpr(dpr);
15278
- canvas.width = size2.width * pixelRatio;
15279
- canvas.height = size2.height * pixelRatio;
15280
- }
15281
- await renderer.init();
15282
- }
15283
- const backend = renderer.backend;
15284
- const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
15285
- state.internal.actualRenderer = renderer;
15286
- state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
15287
- if (canvasId && !state.internal.isSecondary) {
15288
- const canvasTarget = new CanvasTarget(canvas);
15289
- const unregisterPrimary = registerPrimary(canvasId, renderer, store);
15290
- state.set((prev) => ({
15291
- internal: {
15292
- ...prev.internal,
15293
- canvasTarget,
15294
- unregisterPrimary
14243
+ if (!state.internal.actualRenderer) {
14244
+ if (!rendererSetup) {
14245
+ rendererSetup = (async () => {
14246
+ if (wantsGL) {
14247
+ renderer = await resolveRenderer(glConfig, defaultGLProps, WebGLRenderer);
14248
+ state.internal.actualRenderer = renderer;
14249
+ state.set({ isLegacy: true, gl: renderer, renderer, primaryStore: store });
14250
+ } else if (!wantsGL && primaryCanvas) {
14251
+ const primary = await waitForPrimary(primaryCanvas);
14252
+ renderer = primary.renderer;
14253
+ state.internal.actualRenderer = renderer;
14254
+ const canvasTarget = new CanvasTarget(canvas);
14255
+ primary.store.setState((prev) => ({
14256
+ internal: { ...prev.internal, isMultiCanvas: true }
14257
+ }));
14258
+ state.set((prev) => ({
14259
+ webGPUSupported: primary.store.getState().webGPUSupported,
14260
+ renderer,
14261
+ primaryStore: primary.store,
14262
+ internal: {
14263
+ ...prev.internal,
14264
+ canvasTarget,
14265
+ isMultiCanvas: true,
14266
+ isSecondary: true,
14267
+ targetId: primaryCanvas
14268
+ }
14269
+ }));
14270
+ } else if (!wantsGL) {
14271
+ renderer = await resolveRenderer(rendererConfig, defaultGPUProps, WebGPURenderer);
14272
+ if (!renderer.hasInitialized?.()) {
14273
+ const size2 = computeInitialSize(canvas, propsSize);
14274
+ if (size2.width > 0 && size2.height > 0) {
14275
+ const pixelRatio = calculateDpr(dpr);
14276
+ canvas.width = size2.width * pixelRatio;
14277
+ canvas.height = size2.height * pixelRatio;
14278
+ }
14279
+ await renderer.init();
14280
+ }
14281
+ const backend = renderer.backend;
14282
+ const isWebGPUBackend = backend && "isWebGPUBackend" in backend;
14283
+ state.internal.actualRenderer = renderer;
14284
+ state.set({ webGPUSupported: isWebGPUBackend, renderer, primaryStore: store });
14285
+ if (canvasId && !state.internal.isSecondary) {
14286
+ const canvasTarget = new CanvasTarget(canvas);
14287
+ const unregisterPrimary = registerPrimary(canvasId, renderer, store);
14288
+ state.set((prev) => ({
14289
+ internal: {
14290
+ ...prev.internal,
14291
+ canvasTarget,
14292
+ unregisterPrimary
14293
+ }
14294
+ }));
14295
+ }
15295
14296
  }
15296
- }));
14297
+ })().catch((err) => {
14298
+ rendererSetup = null;
14299
+ throw err;
14300
+ });
15297
14301
  }
14302
+ await rendererSetup;
14303
+ state = store.getState();
14304
+ renderer = state.internal.actualRenderer;
15298
14305
  }
15299
14306
  let raycaster = state.raycaster;
15300
14307
  if (!raycaster) state.set({ raycaster: raycaster = new Raycaster() });
@@ -15519,7 +14526,7 @@ function createRoot(canvas) {
15519
14526
  {
15520
14527
  id: `${newRootId}_frustum`,
15521
14528
  rootId: newRootId,
15522
- phase: "preRender",
14529
+ before: "render",
15523
14530
  system: true
15524
14531
  }
15525
14532
  );
@@ -15531,7 +14538,7 @@ function createRoot(canvas) {
15531
14538
  {
15532
14539
  id: `${newRootId}_visibility`,
15533
14540
  rootId: newRootId,
15534
- phase: "preRender",
14541
+ before: "render",
15535
14542
  system: true,
15536
14543
  after: `${newRootId}_frustum`
15537
14544
  }
@@ -15644,7 +14651,8 @@ function unmountComponentAtNode(canvas, callback) {
15644
14651
  dispose(state.scene);
15645
14652
  _roots.delete(canvas);
15646
14653
  if (callback) callback(canvas);
15647
- } catch {
14654
+ } catch (error) {
14655
+ console.warn("[R3F] Error while unmounting root; teardown may be incomplete:", error);
15648
14656
  }
15649
14657
  }, 500);
15650
14658
  }
@@ -15707,6 +14715,7 @@ function PortalInner({ state = {}, children, container }) {
15707
14715
  viewport = rootState.viewport.getCurrentViewport(camera, new Vector3(), resolvedSize);
15708
14716
  if (camera !== rootState.camera) updateCamera(camera, resolvedSize);
15709
14717
  }
14718
+ const set = injectState.set;
15710
14719
  return {
15711
14720
  // The intersect consists of the previous root state
15712
14721
  ...rootState,
@@ -15725,7 +14734,7 @@ function PortalInner({ state = {}, children, container }) {
15725
14734
  size: resolvedSize,
15726
14735
  viewport: { ...rootState.viewport, ...viewport },
15727
14736
  // Layers are allowed to override events
15728
- setEvents: (events2) => injectState.set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
14737
+ setEvents: (events2) => set((state2) => ({ ...state2, events: { ...state2.events, ...events2 } })),
15729
14738
  // Container for child attachment - the portalScene (injected or container itself)
15730
14739
  internal: { ...rootState.internal, ...injectState.internal, container: portalScene }
15731
14740
  };
@@ -15754,6 +14763,59 @@ function flushSync(fn) {
15754
14763
  return reconciler.flushSyncFromReconciler(fn);
15755
14764
  }
15756
14765
 
14766
+ function parseBackground(background) {
14767
+ if (!background) return null;
14768
+ if (typeof background === "object" && !background.isColor) {
14769
+ const { backgroundMap, envMap, files, preset, ...rest } = background;
14770
+ return {
14771
+ ...rest,
14772
+ preset,
14773
+ files: envMap || files,
14774
+ backgroundFiles: backgroundMap,
14775
+ background: true
14776
+ };
14777
+ }
14778
+ if (typeof background === "number") {
14779
+ return { color: background, background: true };
14780
+ }
14781
+ if (typeof background === "string") {
14782
+ if (background in presetsObj) {
14783
+ return { preset: background, background: true };
14784
+ }
14785
+ if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
14786
+ return { files: background, background: true };
14787
+ }
14788
+ return { color: background, background: true };
14789
+ }
14790
+ if (background.isColor) {
14791
+ return { color: background, background: true };
14792
+ }
14793
+ return null;
14794
+ }
14795
+
14796
+ function parseRendererConfig(rendererProp) {
14797
+ const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
14798
+ if (isRendererConfig) {
14799
+ const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
14800
+ return {
14801
+ primaryCanvas: pc,
14802
+ scheduler: sc,
14803
+ renderer: Object.keys(rest).length > 0 ? rest : rendererProp
14804
+ };
14805
+ }
14806
+ return { primaryCanvas: void 0, scheduler: void 0, renderer: rendererProp };
14807
+ }
14808
+
14809
+ function clearHmrCaches(store) {
14810
+ store.setState((state) => ({
14811
+ nodes: {},
14812
+ uniforms: {},
14813
+ buffers: {},
14814
+ gpuStorage: {},
14815
+ _hmrVersion: state._hmrVersion + 1
14816
+ }));
14817
+ }
14818
+
15757
14819
  function CanvasImpl({
15758
14820
  ref,
15759
14821
  children,
@@ -15774,6 +14836,8 @@ function CanvasImpl({
15774
14836
  raycaster,
15775
14837
  camera,
15776
14838
  scene,
14839
+ autoUpdateFrustum,
14840
+ occlusion,
15777
14841
  onPointerMissed,
15778
14842
  onDragOverMissed,
15779
14843
  onDropMissed,
@@ -15785,49 +14849,10 @@ function CanvasImpl({
15785
14849
  forceEven,
15786
14850
  ...props
15787
14851
  }) {
15788
- const isRendererConfig = typeof rendererProp === "object" && rendererProp !== null && !("render" in rendererProp) && ("primaryCanvas" in rendererProp || "scheduler" in rendererProp);
15789
- let primaryCanvas;
15790
- let scheduler;
15791
- let renderer;
15792
- if (isRendererConfig) {
15793
- const { primaryCanvas: pc, scheduler: sc, ...rest } = rendererProp;
15794
- primaryCanvas = pc;
15795
- scheduler = sc;
15796
- renderer = Object.keys(rest).length > 0 ? rest : rendererProp;
15797
- } else {
15798
- renderer = rendererProp;
15799
- }
14852
+ const { primaryCanvas, scheduler, renderer } = parseRendererConfig(rendererProp);
15800
14853
  React.useMemo(() => extend(THREE), []);
15801
14854
  const Bridge = useBridge();
15802
- const backgroundProps = React.useMemo(() => {
15803
- if (!background) return null;
15804
- if (typeof background === "object" && !background.isColor) {
15805
- const { backgroundMap, envMap, files, preset, ...rest } = background;
15806
- return {
15807
- ...rest,
15808
- preset,
15809
- files: envMap || files,
15810
- backgroundFiles: backgroundMap,
15811
- background: true
15812
- };
15813
- }
15814
- if (typeof background === "number") {
15815
- return { color: background, background: true };
15816
- }
15817
- if (typeof background === "string") {
15818
- if (background in presetsObj) {
15819
- return { preset: background, background: true };
15820
- }
15821
- if (/^(https?:\/\/|\/|\.\/|\.\.\/)|\\.(hdr|exr|jpg|jpeg|png|webp|gif)$/i.test(background)) {
15822
- return { files: background, background: true };
15823
- }
15824
- return { color: background, background: true };
15825
- }
15826
- if (background.isColor) {
15827
- return { color: background, background: true };
15828
- }
15829
- return null;
15830
- }, [background]);
14855
+ const backgroundProps = React.useMemo(() => parseBackground(background), [background]);
15831
14856
  const hasInitialSizeRef = React.useRef(false);
15832
14857
  const measureConfig = React.useMemo(() => {
15833
14858
  if (!hasInitialSizeRef.current) {
@@ -15869,6 +14894,7 @@ function CanvasImpl({
15869
14894
  const handleDropMissed = useMutableCallback(onDropMissed);
15870
14895
  const [block, setBlock] = React.useState(false);
15871
14896
  const [error, setError] = React.useState(false);
14897
+ const [fallbackVisible, setFallbackVisible] = React.useState(false);
15872
14898
  if (block) throw block;
15873
14899
  if (error) throw error;
15874
14900
  const root = React.useRef(null);
@@ -15876,6 +14902,7 @@ function CanvasImpl({
15876
14902
  const unsubscribeErrorRef = React.useRef(null);
15877
14903
  useIsomorphicLayoutEffect(() => {
15878
14904
  effectActiveRef.current = true;
14905
+ if (fallbackVisible) return;
15879
14906
  const canvas = canvasRef.current;
15880
14907
  if (effectiveSize.width > 0 && effectiveSize.height > 0 && canvas) {
15881
14908
  if (!root.current) {
@@ -15896,7 +14923,7 @@ function CanvasImpl({
15896
14923
  }
15897
14924
  async function run() {
15898
14925
  if (!effectActiveRef.current || !root.current) return;
15899
- await root.current.configure({
14926
+ const configured = await root.current.configure({
15900
14927
  id,
15901
14928
  primaryCanvas,
15902
14929
  scheduler,
@@ -15911,6 +14938,8 @@ function CanvasImpl({
15911
14938
  performance,
15912
14939
  raycaster,
15913
14940
  camera,
14941
+ autoUpdateFrustum,
14942
+ occlusion,
15914
14943
  size: effectiveSize,
15915
14944
  // Store size props for reset functionality
15916
14945
  _sizeProps: width !== void 0 || height !== void 0 ? { width, height } : null,
@@ -15935,8 +14964,20 @@ function CanvasImpl({
15935
14964
  }
15936
14965
  onCreated?.(state);
15937
14966
  }
15938
- });
15939
- if (!effectActiveRef.current || !root.current) return;
14967
+ }).then(
14968
+ () => true,
14969
+ // Renderer setup failed (e.g. no WebGL/WebGPU support). The `fallback` prop lives
14970
+ // inside <canvas>, which browsers don't display, so surface it as visible DOM
14971
+ // instead; with no fallback, rethrow to an external error boundary. (#3757)
14972
+ (setupError) => {
14973
+ if (effectActiveRef.current) {
14974
+ if (fallback != null) setFallbackVisible(true);
14975
+ else setError(setupError);
14976
+ }
14977
+ return false;
14978
+ }
14979
+ );
14980
+ if (!configured || !effectActiveRef.current || !root.current) return;
15940
14981
  root.current.render(
15941
14982
  /* @__PURE__ */ jsx(Bridge, { children: /* @__PURE__ */ jsx(ErrorBoundary, { set: setError, children: /* @__PURE__ */ jsxs(React.Suspense, { fallback: /* @__PURE__ */ jsx(Block, { set: setBlock }), children: [
15942
14983
  backgroundProps && /* @__PURE__ */ jsx(Environment, { ...backgroundProps }),
@@ -15970,14 +15011,7 @@ function CanvasImpl({
15970
15011
  const handleHMR = () => {
15971
15012
  queueMicrotask(() => {
15972
15013
  const rootEntry = _roots.get(canvas);
15973
- if (rootEntry?.store) {
15974
- console.log("[R3F] HMR detected \u2014 rebuilding nodes/uniforms");
15975
- rootEntry.store.setState((state) => ({
15976
- nodes: {},
15977
- uniforms: {},
15978
- _hmrVersion: state._hmrVersion + 1
15979
- }));
15980
- }
15014
+ if (rootEntry?.store) clearHmrCaches(rootEntry.store);
15981
15015
  });
15982
15016
  };
15983
15017
  if (typeof import.meta !== "undefined" && import.meta.hot) {
@@ -16006,7 +15040,11 @@ function CanvasImpl({
16006
15040
  ...style
16007
15041
  },
16008
15042
  ...props,
16009
- children: /* @__PURE__ */ jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsx(
15043
+ children: fallbackVisible ? (
15044
+ // Renderer setup failed: render the fallback as visible DOM. Inside <canvas> (below)
15045
+ // it exists in the tree but browsers never paint it, which is the whole bug (#3757).
15046
+ fallback
15047
+ ) : /* @__PURE__ */ jsx("div", { ref: containerRef, className: "r3f-canvas-container", style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsx(
16010
15048
  "canvas",
16011
15049
  {
16012
15050
  ref: canvasRef,
@@ -16025,4 +15063,4 @@ function Canvas(props) {
16025
15063
 
16026
15064
  extend(THREE);
16027
15065
 
16028
- export { Block, Canvas, Environment, EnvironmentCube, EnvironmentMap, EnvironmentPortal, ErrorBoundary, FROM_REF, IsObject, ONCE, Portal, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, REACT_INTERNAL_PROPS, RESERVED_PROPS, Scheduler, Texture, _roots, act, addAfterEffect, addEffect, addTail, advance, applyProps, attach, buildGraph, calculateDpr, context, createEvents, createPointerEvents, createPortal, createRoot, createStore, detach, diffProps, dispose, createPointerEvents as events, extend, findInitialRoot, flushSync, fromRef, getInstanceProps, getPrimary, getPrimaryIds, getRootState, getScheduler, getUuidPrefix, hasConstructor, hasPrimary, invalidate, invalidateInstance, is, isColorRepresentation, isCopyable, isFromRef, isObject3D, isOnce, isOrthographicCamera, isRef, isRenderer, isTexture, isVectorLike, once, prepare, presetsObj, reconciler, registerPrimary, removeInteractivity, resolve, unmountComponentAtNode, unregisterPrimary, updateCamera, updateFrustum, useBridge, useEnvironment, useFrame, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useMutableCallback, useRenderTarget, useStore, useTexture, useTextures, useThree, waitForPrimary };
15066
+ export { Block, Canvas, Environment, EnvironmentCube, EnvironmentMap, EnvironmentPortal, ErrorBoundary, FROM_REF, IsObject, ONCE, Portal, R3F_BUILD_LEGACY, R3F_BUILD_WEBGPU, REACT_INTERNAL_PROPS, RESERVED_PROPS, Texture, _roots, act, addAfterEffect, addEffect, addTail, advance, applyProps, attach, buildGraph, calculateDpr, context, createEvents, createPointerEvents, createPortal, createRoot, createStore, detach, diffProps, dispose, createPointerEvents as events, extend, findInitialRoot, flushSync, fromRef, getInstanceProps, getPrimary, getPrimaryIds, getRootState, getUuidPrefix, hasConstructor, hasPrimary, invalidate, invalidateInstance, is, isColorRepresentation, isCopyable, isFromRef, isObject3D, isOnce, isOrthographicCamera, isRef, isRenderer, isTexture, isVectorLike, once, prepare, presetsObj, reconciler, registerPrimary, removeInteractivity, resolve, unmountComponentAtNode, unregisterPrimary, updateCamera, updateFrustum, useBridge, useEnvironment, useFrame, useGraph, useInstanceHandle, useIsomorphicLayoutEffect, useLoader, useMutableCallback, useRenderTarget, useStore, useTexture, useTextures, useThree, waitForPrimary };