@react-three/fiber 8.0.0-alpha.0 → 8.0.0-beta-04

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.
Files changed (33) hide show
  1. package/CHANGELOG.md +103 -0
  2. package/dist/declarations/src/core/events.d.ts +64 -59
  3. package/dist/declarations/src/core/hooks.d.ts +21 -29
  4. package/dist/declarations/src/core/index.d.ts +31 -0
  5. package/dist/declarations/src/core/loop.d.ts +12 -12
  6. package/dist/declarations/src/core/renderer.d.ts +50 -52
  7. package/dist/declarations/src/core/store.d.ts +117 -106
  8. package/dist/declarations/src/core/utils.d.ts +50 -0
  9. package/dist/declarations/src/index.d.ts +10 -7
  10. package/dist/declarations/src/native/Canvas.d.ts +13 -0
  11. package/dist/declarations/src/native/events.d.ts +5 -0
  12. package/dist/declarations/src/native/hooks.d.ts +9 -0
  13. package/dist/declarations/src/native.d.ts +10 -0
  14. package/dist/declarations/src/three-types.d.ts +309 -320
  15. package/dist/declarations/src/web/Canvas.d.ts +13 -13
  16. package/dist/declarations/src/web/events.d.ts +4 -4
  17. package/dist/index-eb414398.cjs.prod.js +1805 -0
  18. package/dist/index-fccd77b0.esm.js +1750 -0
  19. package/dist/index-ff3eb68b.cjs.dev.js +1805 -0
  20. package/dist/react-three-fiber.cjs.dev.js +108 -1734
  21. package/dist/react-three-fiber.cjs.prod.js +108 -1734
  22. package/dist/react-three-fiber.esm.js +63 -1686
  23. package/native/dist/react-three-fiber-native.cjs.d.ts +1 -0
  24. package/native/dist/react-three-fiber-native.cjs.dev.js +388 -0
  25. package/native/dist/react-three-fiber-native.cjs.js +7 -0
  26. package/native/dist/react-three-fiber-native.cjs.prod.js +388 -0
  27. package/native/dist/react-three-fiber-native.esm.js +336 -0
  28. package/native/package.json +5 -0
  29. package/package.json +19 -8
  30. package/readme.md +10 -10
  31. package/__mocks__/react-use-measure/index.ts +0 -22
  32. package/dist/declarations/src/core/is.d.ts +0 -9
  33. package/dist/declarations/src/web/index.d.ts +0 -30
@@ -0,0 +1,1750 @@
1
+ import * as React from 'react';
2
+ import { suspend, preload, clear } from 'suspend-react';
3
+ import * as THREE from 'three';
4
+ import { DefaultEventPriority, ContinuousEventPriority, DiscreteEventPriority, ConcurrentRoot } from 'react-reconciler/constants';
5
+ import create from 'zustand';
6
+ import Reconciler from 'react-reconciler';
7
+ import { unstable_scheduleCallback, unstable_IdlePriority } from 'scheduler';
8
+
9
+ var threeTypes = /*#__PURE__*/Object.freeze({
10
+ __proto__: null
11
+ });
12
+
13
+ const DEFAULT = '__default';
14
+ const isDiffSet = def => def && !!def.memoized && !!def.changes;
15
+ function calculateDpr(dpr) {
16
+ return Array.isArray(dpr) ? Math.min(Math.max(dpr[0], window.devicePixelRatio), dpr[1]) : dpr;
17
+ }
18
+ /**
19
+ * Picks or omits keys from an object
20
+ * `omit` will filter out keys, and otherwise cherry-pick them.
21
+ */
22
+
23
+ function filterKeys(obj, omit, ...keys) {
24
+ const keysToSelect = new Set(keys);
25
+ return Object.entries(obj).reduce((acc, [key, value]) => {
26
+ const shouldInclude = !omit;
27
+
28
+ if (keysToSelect.has(key) === shouldInclude) {
29
+ acc[key] = value;
30
+ }
31
+
32
+ return acc;
33
+ }, {});
34
+ }
35
+ /**
36
+ * Clones an object and cherry-picks keys.
37
+ */
38
+
39
+ const pick = (obj, keys) => filterKeys(obj, false, ...keys);
40
+ /**
41
+ * Clones an object and prunes or omits keys.
42
+ */
43
+
44
+ const omit = (obj, keys) => filterKeys(obj, true, ...keys); // A collection of compare functions
45
+
46
+ const is = {
47
+ obj: a => a === Object(a) && !is.arr(a) && typeof a !== 'function',
48
+ fun: a => typeof a === 'function',
49
+ str: a => typeof a === 'string',
50
+ num: a => typeof a === 'number',
51
+ und: a => a === void 0,
52
+ arr: a => Array.isArray(a),
53
+
54
+ equ(a, b) {
55
+ // Wrong type or one of the two undefined, doesn't match
56
+ if (typeof a !== typeof b || !!a !== !!b) return false; // Atomic, just compare a against b
57
+
58
+ if (is.str(a) || is.num(a) || is.obj(a)) return a === b; // Array, shallow compare first to see if it's a match
59
+
60
+ if (is.arr(a) && a == b) return true; // Last resort, go through keys
61
+
62
+ let i;
63
+
64
+ for (i in a) if (!(i in b)) return false;
65
+
66
+ for (i in b) if (a[i] !== b[i]) return false;
67
+
68
+ return is.und(i) ? a === b : true;
69
+ }
70
+
71
+ }; // Collects nodes and materials from a THREE.Object3D
72
+
73
+ function buildGraph(object) {
74
+ const data = {
75
+ nodes: {},
76
+ materials: {}
77
+ };
78
+
79
+ if (object) {
80
+ object.traverse(obj => {
81
+ if (obj.name) data.nodes[obj.name] = obj;
82
+ if (obj.material && !data.materials[obj.material.name]) data.materials[obj.material.name] = obj.material;
83
+ });
84
+ }
85
+
86
+ return data;
87
+ } // Disposes an object and all its properties
88
+
89
+ function dispose(obj) {
90
+ if (obj.dispose && obj.type !== 'Scene') obj.dispose();
91
+
92
+ for (const p in obj) {
93
+ p.dispose == null ? void 0 : p.dispose();
94
+ delete obj[p];
95
+ }
96
+ } // Each object in the scene carries a small LocalState descriptor
97
+
98
+ function prepare(object, state) {
99
+ const instance = object;
100
+
101
+ if (state != null && state.primitive || !instance.__r3f) {
102
+ instance.__r3f = {
103
+ root: null,
104
+ memoizedProps: {},
105
+ eventCount: 0,
106
+ handlers: {},
107
+ objects: [],
108
+ parent: null,
109
+ ...state
110
+ };
111
+ }
112
+
113
+ return object;
114
+ }
115
+
116
+ function resolve(instance, key) {
117
+ let target = instance;
118
+
119
+ if (key.includes('-')) {
120
+ const entries = key.split('-');
121
+ const last = entries.pop();
122
+ target = entries.reduce((acc, key) => acc[key], instance);
123
+ return {
124
+ target,
125
+ key: last
126
+ };
127
+ } else return {
128
+ target,
129
+ key
130
+ };
131
+ }
132
+
133
+ function attach(parent, child, type) {
134
+ if (is.str(type)) {
135
+ const {
136
+ target,
137
+ key
138
+ } = resolve(parent, type);
139
+ parent.__r3f.previousAttach = target[key];
140
+ target[key] = child;
141
+ } else if (is.arr(type)) {
142
+ const [attach] = type;
143
+ if (is.str(attach)) parent[attach](child);else if (is.fun(attach)) attach(parent, child);
144
+ }
145
+ }
146
+ function detach(parent, child, type) {
147
+ if (is.str(type)) {
148
+ const {
149
+ target,
150
+ key
151
+ } = resolve(parent, type);
152
+ target[key] = parent.__r3f.previousAttach;
153
+ } else if (is.arr(type)) {
154
+ const [, detach] = type;
155
+ if (is.str(detach)) parent[detach](child);else if (is.fun(detach)) detach(parent, child);
156
+ }
157
+ } // Shallow check arrays, but check objects atomically
158
+
159
+ function checkShallow(a, b) {
160
+ if (is.arr(a) && is.equ(a, b)) return true;
161
+ if (a === b) return true;
162
+ return false;
163
+ } // This function prepares a set of changes to be applied to the instance
164
+
165
+
166
+ function diffProps(instance, {
167
+ children: cN,
168
+ key: kN,
169
+ ref: rN,
170
+ ...props
171
+ }, {
172
+ children: cP,
173
+ key: kP,
174
+ ref: rP,
175
+ ...previous
176
+ } = {}, remove = false) {
177
+ var _instance$__r3f;
178
+
179
+ const localState = (_instance$__r3f = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f : {};
180
+ const entries = Object.entries(props);
181
+ const changes = []; // Catch removed props, prepend them so they can be reset or removed
182
+
183
+ if (remove) {
184
+ const previousKeys = Object.keys(previous);
185
+
186
+ for (let i = 0; i < previousKeys.length; i++) {
187
+ if (!props.hasOwnProperty(previousKeys[i])) entries.unshift([previousKeys[i], DEFAULT + 'remove']);
188
+ }
189
+ }
190
+
191
+ entries.forEach(([key, value]) => {
192
+ var _instance$__r3f2;
193
+
194
+ // Bail out on primitive object
195
+ if ((_instance$__r3f2 = instance.__r3f) != null && _instance$__r3f2.primitive && key === 'object') return; // When props match bail out
196
+
197
+ if (checkShallow(value, previous[key])) return; // Collect handlers and bail out
198
+
199
+ if (/^on(Pointer|Click|DoubleClick|ContextMenu|Wheel)/.test(key)) return changes.push([key, value, true, []]); // Split dashed props
200
+
201
+ let entries = [];
202
+ if (key.includes('-')) entries = key.split('-');
203
+ changes.push([key, value, false, entries]);
204
+ });
205
+ const memoized = { ...props
206
+ };
207
+ if (localState.memoizedProps && localState.memoizedProps.args) memoized.args = localState.memoizedProps.args;
208
+ if (localState.memoizedProps && localState.memoizedProps.attach) memoized.attach = localState.memoizedProps.attach;
209
+ return {
210
+ memoized,
211
+ changes
212
+ };
213
+ } // This function applies a set of changes to the instance
214
+
215
+ function applyProps$1(instance, data) {
216
+ var _instance$__r3f3, _root$getState;
217
+
218
+ // Filter equals, events and reserved props
219
+ const localState = (_instance$__r3f3 = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f3 : {};
220
+ const root = localState.root;
221
+ const rootState = (_root$getState = root == null ? void 0 : root.getState == null ? void 0 : root.getState()) != null ? _root$getState : {};
222
+ const {
223
+ memoized,
224
+ changes
225
+ } = isDiffSet(data) ? data : diffProps(instance, data);
226
+ const prevHandlers = localState.eventCount; // Prepare memoized props
227
+
228
+ if (instance.__r3f) instance.__r3f.memoizedProps = memoized;
229
+ changes.forEach(([key, value, isEvent, keys]) => {
230
+ let currentInstance = instance;
231
+ let targetProp = currentInstance[key]; // Revolve dashed props
232
+
233
+ if (keys.length) {
234
+ targetProp = keys.reduce((acc, key) => acc[key], instance); // If the target is atomic, it forces us to switch the root
235
+
236
+ if (!(targetProp && targetProp.set)) {
237
+ const [name, ...reverseEntries] = keys.reverse();
238
+ currentInstance = reverseEntries.reverse().reduce((acc, key) => acc[key], instance);
239
+ key = name;
240
+ }
241
+ } // https://github.com/mrdoob/three.js/issues/21209
242
+ // HMR/fast-refresh relies on the ability to cancel out props, but threejs
243
+ // has no means to do this. Hence we curate a small collection of value-classes
244
+ // with their respective constructor/set arguments
245
+ // For removed props, try to set default values, if possible
246
+
247
+
248
+ if (value === DEFAULT + 'remove') {
249
+ if (targetProp && targetProp.constructor) {
250
+ // use the prop constructor to find the default it should be
251
+ value = new targetProp.constructor(memoized.args);
252
+ } else if (currentInstance.constructor) {
253
+ // create a blank slate of the instance and copy the particular parameter.
254
+ // @ts-ignore
255
+ const defaultClassCall = new currentInstance.constructor(currentInstance.__r3f.memoizedProps.args);
256
+ value = defaultClassCall[targetProp]; // destory the instance
257
+
258
+ if (defaultClassCall.dispose) defaultClassCall.dispose(); // instance does not have constructor, just set it to 0
259
+ } else {
260
+ value = 0;
261
+ }
262
+ } // Deal with pointer events ...
263
+
264
+
265
+ if (isEvent) {
266
+ if (value) localState.handlers[key] = value;else delete localState.handlers[key];
267
+ localState.eventCount = Object.keys(localState.handlers).length;
268
+ } // Special treatment for objects with support for set/copy, and layers
269
+ else if (targetProp && targetProp.set && (targetProp.copy || targetProp instanceof THREE.Layers)) {
270
+ // If value is an array
271
+ if (Array.isArray(value)) {
272
+ if (targetProp.fromArray) targetProp.fromArray(value);else targetProp.set(...value);
273
+ } // Test again target.copy(class) next ...
274
+ else if (targetProp.copy && value && value.constructor && targetProp.constructor.name === value.constructor.name) {
275
+ targetProp.copy(value);
276
+ } // If nothing else fits, just set the single value, ignore undefined
277
+ // https://github.com/pmndrs/react-three-fiber/issues/274
278
+ else if (value !== undefined) {
279
+ const isColor = targetProp instanceof THREE.Color; // Allow setting array scalars
280
+
281
+ if (!isColor && targetProp.setScalar) targetProp.setScalar(value); // Layers have no copy function, we must therefore copy the mask property
282
+ else if (targetProp instanceof THREE.Layers && value instanceof THREE.Layers) targetProp.mask = value.mask; // Otherwise just set ...
283
+ else targetProp.set(value); // Auto-convert sRGB colors, for now ...
284
+ // https://github.com/pmndrs/react-three-fiber/issues/344
285
+
286
+ if (!rootState.linear && isColor) targetProp.convertSRGBToLinear();
287
+ } // Else, just overwrite the value
288
+
289
+ } else {
290
+ currentInstance[key] = value; // Auto-convert sRGB textures, for now ...
291
+ // https://github.com/pmndrs/react-three-fiber/issues/344
292
+
293
+ if (!rootState.linear && currentInstance[key] instanceof THREE.Texture) {
294
+ currentInstance[key].encoding = THREE.sRGBEncoding;
295
+ }
296
+ }
297
+
298
+ invalidateInstance(instance);
299
+ return instance;
300
+ });
301
+
302
+ if (localState.parent && rootState.internal && instance.raycast && prevHandlers !== localState.eventCount) {
303
+ // Pre-emptively remove the instance from the interaction manager
304
+ const index = rootState.internal.interaction.indexOf(instance);
305
+ if (index > -1) rootState.internal.interaction.splice(index, 1); // Add the instance to the interaction manager only when it has handlers
306
+
307
+ if (localState.eventCount) rootState.internal.interaction.push(instance);
308
+ } // Call the update lifecycle when it is being updated, but only when it is part of the scene
309
+
310
+
311
+ if (changes.length && instance.parent) updateInstance(instance);
312
+ }
313
+ function invalidateInstance(instance) {
314
+ var _instance$__r3f4, _instance$__r3f4$root;
315
+
316
+ const state = (_instance$__r3f4 = instance.__r3f) == null ? void 0 : (_instance$__r3f4$root = _instance$__r3f4.root) == null ? void 0 : _instance$__r3f4$root.getState == null ? void 0 : _instance$__r3f4$root.getState();
317
+ if (state && state.internal.frames === 0) state.invalidate();
318
+ }
319
+ function updateInstance(instance) {
320
+ instance.onUpdate == null ? void 0 : instance.onUpdate(instance);
321
+ }
322
+
323
+ function makeId(event) {
324
+ return (event.eventObject || event.object).uuid + '/' + event.index + event.instanceId;
325
+ } // https://github.com/facebook/react/tree/main/packages/react-reconciler#getcurrenteventpriority
326
+ // Gives React a clue as to how import the current interaction is
327
+
328
+
329
+ function getEventPriority() {
330
+ var _window, _window$event;
331
+
332
+ let name = (_window = window) == null ? void 0 : (_window$event = _window.event) == null ? void 0 : _window$event.type;
333
+
334
+ switch (name) {
335
+ case 'click':
336
+ case 'contextmenu':
337
+ case 'dblclick':
338
+ case 'pointercancel':
339
+ case 'pointerdown':
340
+ case 'pointerup':
341
+ return DiscreteEventPriority;
342
+
343
+ case 'pointermove':
344
+ case 'pointerout':
345
+ case 'pointerover':
346
+ case 'pointerenter':
347
+ case 'pointerleave':
348
+ case 'wheel':
349
+ return ContinuousEventPriority;
350
+
351
+ default:
352
+ return DefaultEventPriority;
353
+ }
354
+ }
355
+ /**
356
+ * Release pointer captures.
357
+ * This is called by releasePointerCapture in the API, and when an object is removed.
358
+ */
359
+
360
+ function releaseInternalPointerCapture(capturedMap, obj, captures, pointerId) {
361
+ const captureData = captures.get(obj);
362
+
363
+ if (captureData) {
364
+ captures.delete(obj); // If this was the last capturing object for this pointer
365
+
366
+ if (captures.size === 0) {
367
+ capturedMap.delete(pointerId);
368
+ captureData.target.releasePointerCapture(pointerId);
369
+ }
370
+ }
371
+ }
372
+
373
+ function removeInteractivity(store, object) {
374
+ const {
375
+ internal
376
+ } = store.getState(); // Removes every trace of an object from the data store
377
+
378
+ internal.interaction = internal.interaction.filter(o => o !== object);
379
+ internal.initialHits = internal.initialHits.filter(o => o !== object);
380
+ internal.hovered.forEach((value, key) => {
381
+ if (value.eventObject === object || value.object === object) {
382
+ internal.hovered.delete(key);
383
+ }
384
+ });
385
+ internal.capturedMap.forEach((captures, pointerId) => {
386
+ releaseInternalPointerCapture(internal.capturedMap, object, captures, pointerId);
387
+ });
388
+ }
389
+ function createEvents(store) {
390
+ const temp = new THREE.Vector3();
391
+ /** Sets up defaultRaycaster */
392
+
393
+ function prepareRay(event) {
394
+ var _raycaster$computeOff;
395
+
396
+ const state = store.getState();
397
+ const {
398
+ raycaster,
399
+ mouse,
400
+ camera,
401
+ size
402
+ } = state; // https://github.com/pmndrs/react-three-fiber/pull/782
403
+ // Events trigger outside of canvas when moved
404
+
405
+ const {
406
+ offsetX,
407
+ offsetY
408
+ } = (_raycaster$computeOff = raycaster.computeOffsets == null ? void 0 : raycaster.computeOffsets(event, state)) != null ? _raycaster$computeOff : event;
409
+ const {
410
+ width,
411
+ height
412
+ } = size;
413
+ mouse.set(offsetX / width * 2 - 1, -(offsetY / height) * 2 + 1);
414
+ raycaster.setFromCamera(mouse, camera);
415
+ }
416
+ /** Calculates delta */
417
+
418
+
419
+ function calculateDistance(event) {
420
+ const {
421
+ internal
422
+ } = store.getState();
423
+ const dx = event.offsetX - internal.initialClick[0];
424
+ const dy = event.offsetY - internal.initialClick[1];
425
+ return Math.round(Math.sqrt(dx * dx + dy * dy));
426
+ }
427
+ /** Returns true if an instance has a valid pointer-event registered, this excludes scroll, clicks etc */
428
+
429
+
430
+ function filterPointerEvents(objects) {
431
+ return objects.filter(obj => ['Move', 'Over', 'Enter', 'Out', 'Leave'].some(name => {
432
+ var _r3f;
433
+
434
+ return (_r3f = obj.__r3f) == null ? void 0 : _r3f.handlers['onPointer' + name];
435
+ }));
436
+ }
437
+
438
+ function intersect(filter) {
439
+ const state = store.getState();
440
+ const {
441
+ raycaster,
442
+ internal
443
+ } = state; // Skip event handling when noEvents is set
444
+
445
+ if (!raycaster.enabled) return [];
446
+ const seen = new Set();
447
+ const intersections = []; // Allow callers to eliminate event objects
448
+
449
+ const eventsObjects = filter ? filter(internal.interaction) : internal.interaction; // Intersect known handler objects and filter against duplicates
450
+
451
+ let intersects = raycaster.intersectObjects(eventsObjects, true).filter(item => {
452
+ const id = makeId(item);
453
+ if (seen.has(id)) return false;
454
+ seen.add(id);
455
+ return true;
456
+ }); // https://github.com/mrdoob/three.js/issues/16031
457
+ // Allow custom userland intersect sort order
458
+
459
+ if (raycaster.filter) intersects = raycaster.filter(intersects, state);
460
+
461
+ for (const intersect of intersects) {
462
+ let eventObject = intersect.object; // Bubble event up
463
+
464
+ while (eventObject) {
465
+ var _r3f2;
466
+
467
+ if ((_r3f2 = eventObject.__r3f) != null && _r3f2.eventCount) intersections.push({ ...intersect,
468
+ eventObject
469
+ });
470
+ eventObject = eventObject.parent;
471
+ }
472
+ }
473
+
474
+ return intersections;
475
+ }
476
+ /** Creates filtered intersects and returns an array of positive hits */
477
+
478
+
479
+ function patchIntersects(intersections, event) {
480
+ const {
481
+ internal
482
+ } = store.getState(); // If the interaction is captured, make all capturing targets part of the
483
+ // intersect.
484
+
485
+ if ('pointerId' in event && internal.capturedMap.has(event.pointerId)) {
486
+ for (let captureData of internal.capturedMap.get(event.pointerId).values()) {
487
+ intersections.push(captureData.intersection);
488
+ }
489
+ }
490
+
491
+ return intersections;
492
+ }
493
+ /** Handles intersections by forwarding them to handlers */
494
+
495
+
496
+ function handleIntersects(intersections, event, delta, callback) {
497
+ const {
498
+ raycaster,
499
+ mouse,
500
+ camera,
501
+ internal
502
+ } = store.getState(); // If anything has been found, forward it to the event listeners
503
+
504
+ if (intersections.length) {
505
+ const unprojectedPoint = temp.set(mouse.x, mouse.y, 0).unproject(camera);
506
+ const localState = {
507
+ stopped: false
508
+ };
509
+
510
+ for (const hit of intersections) {
511
+ const hasPointerCapture = id => {
512
+ var _internal$capturedMap, _internal$capturedMap2;
513
+
514
+ return (_internal$capturedMap = (_internal$capturedMap2 = internal.capturedMap.get(id)) == null ? void 0 : _internal$capturedMap2.has(hit.eventObject)) != null ? _internal$capturedMap : false;
515
+ };
516
+
517
+ const setPointerCapture = id => {
518
+ const captureData = {
519
+ intersection: hit,
520
+ target: event.target
521
+ };
522
+
523
+ if (internal.capturedMap.has(id)) {
524
+ // if the pointerId was previously captured, we add the hit to the
525
+ // event capturedMap.
526
+ internal.capturedMap.get(id).set(hit.eventObject, captureData);
527
+ } else {
528
+ // if the pointerId was not previously captured, we create a map
529
+ // containing the hitObject, and the hit. hitObject is used for
530
+ // faster access.
531
+ internal.capturedMap.set(id, new Map([[hit.eventObject, captureData]]));
532
+ } // Call the original event now
533
+ event.target.setPointerCapture(id);
534
+ };
535
+
536
+ const releasePointerCapture = id => {
537
+ const captures = internal.capturedMap.get(id);
538
+
539
+ if (captures) {
540
+ releaseInternalPointerCapture(internal.capturedMap, hit.eventObject, captures, id);
541
+ }
542
+ }; // Add native event props
543
+
544
+
545
+ let extractEventProps = {}; // This iterates over the event's properties including the inherited ones. Native PointerEvents have most of their props as getters which are inherited, but polyfilled PointerEvents have them all as their own properties (i.e. not inherited). We can't use Object.keys() or Object.entries() as they only return "own" properties; nor Object.getPrototypeOf(event) as that *doesn't* return "own" properties, only inherited ones.
546
+
547
+ for (let prop in event) {
548
+ let property = event[prop]; // Only copy over atomics, leave functions alone as these should be
549
+ // called as event.nativeEvent.fn()
550
+
551
+ if (typeof property !== 'function') extractEventProps[prop] = property;
552
+ }
553
+
554
+ let raycastEvent = { ...hit,
555
+ ...extractEventProps,
556
+ spaceX: mouse.x,
557
+ spaceY: mouse.y,
558
+ intersections,
559
+ stopped: localState.stopped,
560
+ delta,
561
+ unprojectedPoint,
562
+ ray: raycaster.ray,
563
+ camera: camera,
564
+ // Hijack stopPropagation, which just sets a flag
565
+ stopPropagation: () => {
566
+ // https://github.com/pmndrs/react-three-fiber/issues/596
567
+ // Events are not allowed to stop propagation if the pointer has been captured
568
+ const capturesForPointer = 'pointerId' in event && internal.capturedMap.get(event.pointerId); // We only authorize stopPropagation...
569
+
570
+ if ( // ...if this pointer hasn't been captured
571
+ !capturesForPointer || // ... or if the hit object is capturing the pointer
572
+ capturesForPointer.has(hit.eventObject)) {
573
+ raycastEvent.stopped = localState.stopped = true; // Propagation is stopped, remove all other hover records
574
+ // An event handler is only allowed to flush other handlers if it is hovered itself
575
+
576
+ if (internal.hovered.size && Array.from(internal.hovered.values()).find(i => i.eventObject === hit.eventObject)) {
577
+ // Objects cannot flush out higher up objects that have already caught the event
578
+ const higher = intersections.slice(0, intersections.indexOf(hit));
579
+ cancelPointer([...higher, hit]);
580
+ }
581
+ }
582
+ },
583
+ // there should be a distinction between target and currentTarget
584
+ target: {
585
+ hasPointerCapture,
586
+ setPointerCapture,
587
+ releasePointerCapture
588
+ },
589
+ currentTarget: {
590
+ hasPointerCapture,
591
+ setPointerCapture,
592
+ releasePointerCapture
593
+ },
594
+ sourceEvent: event,
595
+ // deprecated
596
+ nativeEvent: event
597
+ }; // Call subscribers
598
+
599
+ callback(raycastEvent); // Event bubbling may be interrupted by stopPropagation
600
+
601
+ if (localState.stopped === true) break;
602
+ }
603
+ }
604
+
605
+ return intersections;
606
+ }
607
+
608
+ function cancelPointer(hits) {
609
+ const {
610
+ internal
611
+ } = store.getState();
612
+ Array.from(internal.hovered.values()).forEach(hoveredObj => {
613
+ // When no objects were hit or the the hovered object wasn't found underneath the cursor
614
+ // we call onPointerOut and delete the object from the hovered-elements map
615
+ if (!hits.length || !hits.find(hit => hit.object === hoveredObj.object && hit.index === hoveredObj.index && hit.instanceId === hoveredObj.instanceId)) {
616
+ const eventObject = hoveredObj.eventObject;
617
+ const instance = eventObject.__r3f;
618
+ const handlers = instance == null ? void 0 : instance.handlers;
619
+ internal.hovered.delete(makeId(hoveredObj));
620
+
621
+ if (instance != null && instance.eventCount) {
622
+ // Clear out intersects, they are outdated by now
623
+ const data = { ...hoveredObj,
624
+ intersections: hits || []
625
+ };
626
+ handlers.onPointerOut == null ? void 0 : handlers.onPointerOut(data);
627
+ handlers.onPointerLeave == null ? void 0 : handlers.onPointerLeave(data);
628
+ }
629
+ }
630
+ });
631
+ }
632
+
633
+ const handlePointer = name => {
634
+ // Deal with cancelation
635
+ switch (name) {
636
+ case 'onPointerLeave':
637
+ case 'onPointerCancel':
638
+ return () => cancelPointer([]);
639
+
640
+ case 'onLostPointerCapture':
641
+ return event => {
642
+ const {
643
+ internal
644
+ } = store.getState();
645
+
646
+ if ('pointerId' in event && !internal.capturedMap.has(event.pointerId)) {
647
+ // If the object event interface had onLostPointerCapture, we'd call it here on every
648
+ // object that's getting removed.
649
+ internal.capturedMap.delete(event.pointerId);
650
+ cancelPointer([]);
651
+ }
652
+ };
653
+ } // Any other pointer goes here ...
654
+
655
+
656
+ return event => {
657
+ const {
658
+ onPointerMissed,
659
+ internal
660
+ } = store.getState();
661
+ prepareRay(event);
662
+ internal.lastEvent.current = event; // Get fresh intersects
663
+
664
+ const isPointerMove = name === 'onPointerMove';
665
+ const isClickEvent = name === 'onClick' || name === 'onContextMenu' || name === 'onDoubleClick';
666
+ const filter = isPointerMove ? filterPointerEvents : undefined;
667
+ const hits = patchIntersects(intersect(filter), event);
668
+ const delta = isClickEvent ? calculateDistance(event) : 0; // Save initial coordinates on pointer-down
669
+
670
+ if (name === 'onPointerDown') {
671
+ internal.initialClick = [event.offsetX, event.offsetY];
672
+ internal.initialHits = hits.map(hit => hit.eventObject);
673
+ } // If a click yields no results, pass it back to the user as a miss
674
+ // Missed events have to come first in order to establish user-land side-effect clean up
675
+
676
+
677
+ if (isClickEvent && !hits.length) {
678
+ if (delta <= 2) {
679
+ pointerMissed(event, internal.interaction);
680
+ if (onPointerMissed) onPointerMissed(event);
681
+ }
682
+ } // Take care of unhover
683
+
684
+
685
+ if (isPointerMove) cancelPointer(hits);
686
+ handleIntersects(hits, event, delta, data => {
687
+ const eventObject = data.eventObject;
688
+ const instance = eventObject.__r3f;
689
+ const handlers = instance == null ? void 0 : instance.handlers; // Check presence of handlers
690
+
691
+ if (!(instance != null && instance.eventCount)) return;
692
+
693
+ if (isPointerMove) {
694
+ // Move event ...
695
+ if (handlers.onPointerOver || handlers.onPointerEnter || handlers.onPointerOut || handlers.onPointerLeave) {
696
+ // When enter or out is present take care of hover-state
697
+ const id = makeId(data);
698
+ const hoveredItem = internal.hovered.get(id);
699
+
700
+ if (!hoveredItem) {
701
+ // If the object wasn't previously hovered, book it and call its handler
702
+ internal.hovered.set(id, data);
703
+ handlers.onPointerOver == null ? void 0 : handlers.onPointerOver(data);
704
+ handlers.onPointerEnter == null ? void 0 : handlers.onPointerEnter(data);
705
+ } else if (hoveredItem.stopped) {
706
+ // If the object was previously hovered and stopped, we shouldn't allow other items to proceed
707
+ data.stopPropagation();
708
+ }
709
+ } // Call mouse move
710
+
711
+
712
+ handlers.onPointerMove == null ? void 0 : handlers.onPointerMove(data);
713
+ } else {
714
+ // All other events ...
715
+ const handler = handlers[name];
716
+
717
+ if (handler) {
718
+ // Forward all events back to their respective handlers with the exception of click events,
719
+ // which must use the initial target
720
+ if (!isClickEvent || internal.initialHits.includes(eventObject)) {
721
+ // Missed events have to come first
722
+ pointerMissed(event, internal.interaction.filter(object => !internal.initialHits.includes(object))); // Now call the handler
723
+
724
+ handler(data);
725
+ }
726
+ } else {
727
+ // Trigger onPointerMissed on all elements that have pointer over/out handlers, but not click and weren't hit
728
+ if (isClickEvent && internal.initialHits.includes(eventObject)) {
729
+ pointerMissed(event, internal.interaction.filter(object => !internal.initialHits.includes(object)));
730
+ }
731
+ }
732
+ }
733
+ });
734
+ };
735
+ };
736
+
737
+ function pointerMissed(event, objects) {
738
+ objects.forEach(object => {
739
+ var _r3f3;
740
+
741
+ return (_r3f3 = object.__r3f) == null ? void 0 : _r3f3.handlers.onPointerMissed == null ? void 0 : _r3f3.handlers.onPointerMissed(event);
742
+ });
743
+ }
744
+
745
+ return {
746
+ handlePointer
747
+ };
748
+ }
749
+
750
+ // Type guard to tell a store from a portal
751
+ const isStore = def => def && !!def.getState;
752
+
753
+ const getContainer = (container, child) => {
754
+ var _container$__r3f$root, _container$__r3f;
755
+
756
+ return {
757
+ // If the container is not a root-store then it must be a THREE.Object3D into which part of the
758
+ // scene is portalled into. Now there can be two variants of this, either that object is part of
759
+ // the regular jsx tree, in which case it already has __r3f with a valid root attached, or it lies
760
+ // outside react, in which case we must take the root of the child that is about to be attached to it.
761
+ root: isStore(container) ? container : (_container$__r3f$root = (_container$__r3f = container.__r3f) == null ? void 0 : _container$__r3f.root) != null ? _container$__r3f$root : child.__r3f.root,
762
+ // The container is the eventual target into which objects are mounted, it has to be a THREE.Object3D
763
+ container: isStore(container) ? container.getState().scene : container
764
+ };
765
+ };
766
+
767
+ let catalogue = {};
768
+
769
+ let extend = objects => void (catalogue = { ...catalogue,
770
+ ...objects
771
+ });
772
+
773
+ function createRenderer(roots, getEventPriority) {
774
+ function createInstance(type, {
775
+ args = [],
776
+ attach,
777
+ ...props
778
+ }, root, hostContext, internalInstanceHandle) {
779
+ let name = `${type[0].toUpperCase()}${type.slice(1)}`;
780
+ let instance; // https://github.com/facebook/react/issues/17147
781
+ // Portals do not give us a root, they are themselves treated as a root by the reconciler
782
+ // In order to figure out the actual root we have to climb through fiber internals :(
783
+
784
+ if (!isStore(root) && internalInstanceHandle) {
785
+ const fn = node => {
786
+ if (!node.return) return node.stateNode && node.stateNode.containerInfo;else return fn(node.return);
787
+ };
788
+
789
+ root = fn(internalInstanceHandle);
790
+ } // Assert that by now we have a valid root
791
+
792
+
793
+ if (!root || !isStore(root)) throw `No valid root for ${name}!`; // Auto-attach geometries and materials
794
+
795
+ if (attach === undefined) {
796
+ if (name.endsWith('Geometry')) attach = 'geometry';else if (name.endsWith('Material')) attach = 'material';
797
+ }
798
+
799
+ if (type === 'primitive') {
800
+ if (props.object === undefined) throw `Primitives without 'object' are invalid!`;
801
+ const object = props.object;
802
+ instance = prepare(object, {
803
+ root,
804
+ attach,
805
+ primitive: true
806
+ });
807
+ } else {
808
+ const target = catalogue[name];
809
+
810
+ if (!target) {
811
+ throw `${name} is not part of the THREE namespace! Did you forget to extend? See: https://github.com/pmndrs/react-three-fiber/blob/master/markdown/api.md#using-3rd-party-objects-declaratively`;
812
+ } // Throw if an object or literal was passed for args
813
+
814
+
815
+ if (!Array.isArray(args)) throw 'The args prop must be an array!'; // Instanciate new object, link it to the root
816
+ // Append memoized props with args so it's not forgotten
817
+
818
+ instance = prepare(new target(...args), {
819
+ root,
820
+ attach,
821
+ // TODO: Figure out what this is for
822
+ memoizedProps: {
823
+ args: args.length === 0 ? null : args
824
+ }
825
+ });
826
+ } // It should NOT call onUpdate on object instanciation, because it hasn't been added to the
827
+ // view yet. If the callback relies on references for instance, they won't be ready yet, this is
828
+ // why it passes "true" here
829
+
830
+
831
+ applyProps$1(instance, props);
832
+ return instance;
833
+ }
834
+
835
+ function appendChild(parentInstance, child) {
836
+ let added = false;
837
+
838
+ if (child) {
839
+ // The attach attribute implies that the object attaches itself on the parent
840
+ if (child.__r3f.attach) {
841
+ attach(parentInstance, child, child.__r3f.attach);
842
+ } else if (child.isObject3D && parentInstance.isObject3D) {
843
+ // add in the usual parent-child way
844
+ parentInstance.add(child);
845
+ added = true;
846
+ } // This is for anything that used attach, and for non-Object3Ds that don't get attached to props;
847
+ // that is, anything that's a child in React but not a child in the scenegraph.
848
+
849
+
850
+ if (!added) parentInstance.__r3f.objects.push(child);
851
+ if (!child.__r3f) prepare(child, {});
852
+ child.__r3f.parent = parentInstance;
853
+ updateInstance(child);
854
+ invalidateInstance(child);
855
+ }
856
+ }
857
+
858
+ function insertBefore(parentInstance, child, beforeChild) {
859
+ let added = false;
860
+
861
+ if (child) {
862
+ if (child.__r3f.attach) {
863
+ attach(parentInstance, child, child.__r3f.attach);
864
+ } else if (child.isObject3D && parentInstance.isObject3D) {
865
+ child.parent = parentInstance;
866
+ child.dispatchEvent({
867
+ type: 'added'
868
+ });
869
+ const restSiblings = parentInstance.children.filter(sibling => sibling !== child);
870
+ const index = restSiblings.indexOf(beforeChild);
871
+ parentInstance.children = [...restSiblings.slice(0, index), child, ...restSiblings.slice(index)];
872
+ added = true;
873
+ }
874
+
875
+ if (!added) parentInstance.__r3f.objects.push(child);
876
+ if (!child.__r3f) prepare(child, {});
877
+ child.__r3f.parent = parentInstance;
878
+ updateInstance(child);
879
+ invalidateInstance(child);
880
+ }
881
+ }
882
+
883
+ function removeRecursive(array, parent, dispose = false) {
884
+ if (array) [...array].forEach(child => removeChild(parent, child, dispose));
885
+ }
886
+
887
+ function removeChild(parentInstance, child, dispose) {
888
+ if (child) {
889
+ var _parentInstance$__r3f, _child$__r3f2;
890
+
891
+ // Clear the parent reference
892
+ if (child.__r3f) child.__r3f.parent = null; // Remove child from the parents objects
893
+
894
+ if ((_parentInstance$__r3f = parentInstance.__r3f) != null && _parentInstance$__r3f.objects) parentInstance.__r3f.objects = parentInstance.__r3f.objects.filter(x => x !== child); // Remove attachment
895
+
896
+ if (child.__r3f.attach) {
897
+ detach(parentInstance, child, child.__r3f.attach);
898
+ } else if (child.isObject3D && parentInstance.isObject3D) {
899
+ var _child$__r3f;
900
+
901
+ parentInstance.remove(child); // Remove interactivity
902
+
903
+ if ((_child$__r3f = child.__r3f) != null && _child$__r3f.root) {
904
+ removeInteractivity(child.__r3f.root, child);
905
+ }
906
+ } // Allow objects to bail out of recursive dispose alltogether by passing dispose={null}
907
+ // Never dispose of primitives because their state may be kept outside of React!
908
+ // In order for an object to be able to dispose it has to have
909
+ // - a dispose method,
910
+ // - it cannot be a <primitive object={...} />
911
+ // - it cannot be a THREE.Scene, because three has broken it's own api
912
+ //
913
+ // Since disposal is recursive, we can check the optional dispose arg, which will be undefined
914
+ // when the reconciler calls it, but then carry our own check recursively
915
+
916
+
917
+ const isPrimitive = (_child$__r3f2 = child.__r3f) == null ? void 0 : _child$__r3f2.primitive;
918
+ const shouldDispose = dispose === undefined ? child.dispose !== null && !isPrimitive : dispose; // Remove nested child objects. Primitives should not have objects and children that are
919
+ // attached to them declaratively ...
920
+
921
+ if (!isPrimitive) {
922
+ var _child$__r3f3;
923
+
924
+ removeRecursive((_child$__r3f3 = child.__r3f) == null ? void 0 : _child$__r3f3.objects, child, shouldDispose);
925
+ removeRecursive(child.children, child, shouldDispose);
926
+ } // Remove references
927
+
928
+
929
+ if (child.__r3f) {
930
+ delete child.__r3f.root;
931
+ delete child.__r3f.objects;
932
+ delete child.__r3f.handlers;
933
+ delete child.__r3f.memoizedProps;
934
+ if (!isPrimitive) delete child.__r3f;
935
+ } // Dispose item whenever the reconciler feels like it
936
+
937
+
938
+ if (shouldDispose && child.dispose && child.type !== 'Scene') {
939
+ unstable_scheduleCallback(unstable_IdlePriority, () => {
940
+ try {
941
+ child.dispose();
942
+ } catch (e) {
943
+ /* ... */
944
+ }
945
+ });
946
+ }
947
+
948
+ invalidateInstance(parentInstance);
949
+ }
950
+ }
951
+
952
+ function switchInstance(instance, type, newProps, fiber) {
953
+ var _instance$__r3f;
954
+
955
+ const parent = (_instance$__r3f = instance.__r3f) == null ? void 0 : _instance$__r3f.parent;
956
+ if (!parent) return;
957
+ const newInstance = createInstance(type, newProps, instance.__r3f.root); // https://github.com/pmndrs/react-three-fiber/issues/1348
958
+ // When args change the instance has to be re-constructed, which then
959
+ // forces r3f to re-parent the children and non-scene objects
960
+ // This can not include primitives, which should not have declarative children
961
+
962
+ if (type !== 'primitive' && instance.children) {
963
+ instance.children.forEach(child => appendChild(newInstance, child));
964
+ instance.children = [];
965
+ }
966
+
967
+ instance.__r3f.objects.forEach(child => appendChild(newInstance, child));
968
+
969
+ instance.__r3f.objects = [];
970
+ removeChild(parent, instance);
971
+ appendChild(parent, newInstance) // This evil hack switches the react-internal fiber node
972
+ // https://github.com/facebook/react/issues/14983
973
+ // https://github.com/facebook/react/pull/15021
974
+ ;
975
+ [fiber, fiber.alternate].forEach(fiber => {
976
+ if (fiber !== null) {
977
+ fiber.stateNode = newInstance;
978
+
979
+ if (fiber.ref) {
980
+ if (typeof fiber.ref === 'function') fiber.ref(newInstance);else fiber.ref.current = newInstance;
981
+ }
982
+ }
983
+ });
984
+ }
985
+
986
+ const reconciler = Reconciler({
987
+ appendChildToContainer: (parentInstance, child) => {
988
+ const {
989
+ container,
990
+ root
991
+ } = getContainer(parentInstance, child); // Link current root to the default scene
992
+
993
+ container.__r3f.root = root;
994
+ appendChild(container, child);
995
+ },
996
+ removeChildFromContainer: (parentInstance, child) => removeChild(getContainer(parentInstance, child).container, child),
997
+ insertInContainerBefore: (parentInstance, child, beforeChild) => insertBefore(getContainer(parentInstance, child).container, child, beforeChild),
998
+
999
+ prepareUpdate(instance, type, oldProps, newProps) {
1000
+ if (instance.__r3f.primitive && newProps.object && newProps.object !== instance) {
1001
+ return [true];
1002
+ } else {
1003
+ // This is a data object, let's extract critical information about it
1004
+ const {
1005
+ args: argsNew = [],
1006
+ children: cN,
1007
+ ...restNew
1008
+ } = newProps;
1009
+ const {
1010
+ args: argsOld = [],
1011
+ children: cO,
1012
+ ...restOld
1013
+ } = oldProps; // Throw if an object or literal was passed for args
1014
+
1015
+ if (!Array.isArray(argsNew)) throw 'The args prop must be an array!'; // If it has new props or arguments, then it needs to be re-instanciated
1016
+
1017
+ if (argsNew.some((value, index) => value !== argsOld[index])) return [true]; // Create a diff-set, flag if there are any changes
1018
+
1019
+ const diff = diffProps(instance, restNew, restOld, true);
1020
+ if (diff.changes.length) return [false, diff]; // Otherwise do not touch the instance
1021
+
1022
+ return null;
1023
+ }
1024
+ },
1025
+
1026
+ commitUpdate(instance, [reconstruct, diff], type, oldProps, newProps, fiber) {
1027
+ // Reconstruct when args or <primitive object={...} have changes
1028
+ if (reconstruct) switchInstance(instance, type, newProps, fiber); // Otherwise just overwrite props
1029
+ else applyProps$1(instance, diff);
1030
+ },
1031
+
1032
+ hideInstance(instance) {
1033
+ var _instance$__r3f2;
1034
+
1035
+ // Deatch while the instance is hidden
1036
+ const {
1037
+ attach: type,
1038
+ parent
1039
+ } = (_instance$__r3f2 = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f2 : {};
1040
+ if (type && parent) detach(parent, instance, type);
1041
+ if (instance.isObject3D) instance.visible = false;
1042
+ invalidateInstance(instance);
1043
+ },
1044
+
1045
+ unhideInstance(instance, props) {
1046
+ var _instance$__r3f3;
1047
+
1048
+ // Re-attach when the instance is unhidden
1049
+ const {
1050
+ attach: type,
1051
+ parent
1052
+ } = (_instance$__r3f3 = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f3 : {};
1053
+ if (type && parent) attach(parent, instance, type);
1054
+ if (instance.isObject3D && props.visible == null || props.visible) instance.visible = true;
1055
+ invalidateInstance(instance);
1056
+ },
1057
+
1058
+ createInstance,
1059
+ removeChild,
1060
+ appendChild,
1061
+ appendInitialChild: appendChild,
1062
+ insertBefore,
1063
+ warnsIfNotActing: true,
1064
+ supportsMutation: true,
1065
+ isPrimaryRenderer: false,
1066
+ getCurrentEventPriority: () => getEventPriority ? getEventPriority() : DefaultEventPriority,
1067
+ // @ts-ignore
1068
+ now: is.fun(performance.now) ? performance.now : is.fun(Date.now) ? Date.now : undefined,
1069
+ // @ts-ignore
1070
+ scheduleTimeout: is.fun(setTimeout) ? setTimeout : undefined,
1071
+ // @ts-ignore
1072
+ cancelTimeout: is.fun(clearTimeout) ? clearTimeout : undefined,
1073
+ setTimeout: is.fun(setTimeout) ? setTimeout : undefined,
1074
+ clearTimeout: is.fun(clearTimeout) ? clearTimeout : undefined,
1075
+ noTimeout: -1,
1076
+ hideTextInstance: () => {
1077
+ throw new Error('Text is not allowed in the R3F tree.');
1078
+ },
1079
+ // prettier-ignore
1080
+ getPublicInstance: instance => instance,
1081
+ getRootHostContext: () => null,
1082
+ getChildHostContext: parentHostContext => parentHostContext,
1083
+ createTextInstance: () => {},
1084
+
1085
+ finalizeInitialChildren(instance) {
1086
+ var _instance$__r3f4;
1087
+
1088
+ // https://github.com/facebook/react/issues/20271
1089
+ // Returning true will trigger commitMount
1090
+ const localState = (_instance$__r3f4 = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f4 : {};
1091
+ return !!localState.handlers;
1092
+ },
1093
+
1094
+ commitMount(instance)
1095
+ /*, type, props*/
1096
+ {
1097
+ var _instance$__r3f5;
1098
+
1099
+ // https://github.com/facebook/react/issues/20271
1100
+ // This will make sure events are only added once to the central container
1101
+ const localState = (_instance$__r3f5 = instance == null ? void 0 : instance.__r3f) != null ? _instance$__r3f5 : {};
1102
+
1103
+ if (instance.raycast && localState.handlers && localState.eventCount) {
1104
+ instance.__r3f.root.getState().internal.interaction.push(instance);
1105
+ }
1106
+ },
1107
+
1108
+ shouldDeprioritizeSubtree: () => false,
1109
+ prepareForCommit: () => null,
1110
+ preparePortalMount: containerInfo => prepare(containerInfo),
1111
+ resetAfterCommit: () => {},
1112
+ shouldSetTextContent: () => false,
1113
+ clearContainer: () => false,
1114
+ detachDeletedInstance: () => {}
1115
+ });
1116
+ return {
1117
+ reconciler,
1118
+ applyProps: applyProps$1
1119
+ };
1120
+ }
1121
+
1122
+ const isRenderer = def => !!(def != null && def.render);
1123
+ const isOrthographicCamera = def => def && def.isOrthographicCamera;
1124
+ const context = /*#__PURE__*/React.createContext(null);
1125
+
1126
+ const createStore = (applyProps, invalidate, advance, props) => {
1127
+ const {
1128
+ gl,
1129
+ size,
1130
+ shadows = false,
1131
+ linear = false,
1132
+ flat = false,
1133
+ orthographic = false,
1134
+ frameloop = 'always',
1135
+ dpr = [1, 2],
1136
+ performance,
1137
+ clock = new THREE.Clock(),
1138
+ raycaster: raycastOptions,
1139
+ camera: cameraOptions,
1140
+ onPointerMissed
1141
+ } = props; // Set shadowmap
1142
+
1143
+ if (shadows) {
1144
+ gl.shadowMap.enabled = true;
1145
+ if (typeof shadows === 'object') Object.assign(gl.shadowMap, shadows);else gl.shadowMap.type = THREE.PCFSoftShadowMap;
1146
+ } // Set color preferences
1147
+
1148
+
1149
+ if (linear) gl.outputEncoding = THREE.LinearEncoding;
1150
+ if (flat) gl.toneMapping = THREE.NoToneMapping; // clock.elapsedTime is updated using advance(timestamp)
1151
+
1152
+ if (frameloop === 'never') {
1153
+ clock.stop();
1154
+ clock.elapsedTime = 0;
1155
+ }
1156
+
1157
+ const rootState = create((set, get) => {
1158
+ // Create custom raycaster
1159
+ const raycaster = new THREE.Raycaster();
1160
+ const {
1161
+ params,
1162
+ ...options
1163
+ } = raycastOptions || {};
1164
+ applyProps(raycaster, {
1165
+ enabled: true,
1166
+ ...options,
1167
+ params: { ...raycaster.params,
1168
+ ...params
1169
+ }
1170
+ }); // Create default camera
1171
+
1172
+ const isCamera = cameraOptions instanceof THREE.Camera;
1173
+ const camera = isCamera ? cameraOptions : orthographic ? new THREE.OrthographicCamera(0, 0, 0, 0, 0.1, 1000) : new THREE.PerspectiveCamera(75, 0, 0.1, 1000);
1174
+
1175
+ if (!isCamera) {
1176
+ camera.position.z = 5;
1177
+ if (cameraOptions) applyProps(camera, cameraOptions); // Always look at center by default
1178
+
1179
+ if (!(cameraOptions != null && cameraOptions.rotation)) camera.lookAt(0, 0, 0);
1180
+ }
1181
+
1182
+ const initialDpr = calculateDpr(dpr);
1183
+ const position = new THREE.Vector3();
1184
+ const defaultTarget = new THREE.Vector3();
1185
+ const tempTarget = new THREE.Vector3();
1186
+
1187
+ function getCurrentViewport(camera = get().camera, target = defaultTarget, size = get().size) {
1188
+ const {
1189
+ width,
1190
+ height
1191
+ } = size;
1192
+ const aspect = width / height;
1193
+ if (target instanceof THREE.Vector3) tempTarget.copy(target);else tempTarget.set(...target);
1194
+ const distance = camera.getWorldPosition(position).distanceTo(tempTarget);
1195
+
1196
+ if (isOrthographicCamera(camera)) {
1197
+ return {
1198
+ width: width / camera.zoom,
1199
+ height: height / camera.zoom,
1200
+ factor: 1,
1201
+ distance,
1202
+ aspect
1203
+ };
1204
+ } else {
1205
+ const fov = camera.fov * Math.PI / 180; // convert vertical fov to radians
1206
+
1207
+ const h = 2 * Math.tan(fov / 2) * distance; // visible height
1208
+
1209
+ const w = h * (width / height);
1210
+ return {
1211
+ width: w,
1212
+ height: h,
1213
+ factor: width / w,
1214
+ distance,
1215
+ aspect
1216
+ };
1217
+ }
1218
+ }
1219
+
1220
+ let performanceTimeout = undefined;
1221
+
1222
+ const setPerformanceCurrent = current => set(state => ({
1223
+ performance: { ...state.performance,
1224
+ current
1225
+ }
1226
+ })); // Handle frame behavior in WebXR
1227
+
1228
+
1229
+ const handleXRFrame = timestamp => {
1230
+ const state = get();
1231
+ if (state.frameloop === 'never') return;
1232
+ advance(timestamp, true);
1233
+ }; // Toggle render switching on session
1234
+
1235
+
1236
+ const handleSessionChange = () => {
1237
+ gl.xr.enabled = gl.xr.isPresenting;
1238
+ gl.setAnimationLoop(gl.xr.isPresenting ? handleXRFrame : null); // If exiting session, request frame
1239
+
1240
+ if (!gl.xr.isPresenting) invalidate(get());
1241
+ }; // WebXR session manager
1242
+
1243
+
1244
+ const xr = {
1245
+ connect() {
1246
+ gl.xr.addEventListener('sessionstart', handleSessionChange);
1247
+ gl.xr.addEventListener('sessionend', handleSessionChange);
1248
+ },
1249
+
1250
+ disconnect() {
1251
+ gl.xr.removeEventListener('sessionstart', handleSessionChange);
1252
+ gl.xr.removeEventListener('sessionend', handleSessionChange);
1253
+ }
1254
+
1255
+ }; // Subscribe to WebXR session events
1256
+
1257
+ if (gl.xr) xr.connect();
1258
+ return {
1259
+ gl,
1260
+ set,
1261
+ get,
1262
+ invalidate: () => invalidate(get()),
1263
+ advance: (timestamp, runGlobalEffects) => advance(timestamp, runGlobalEffects, get()),
1264
+ linear,
1265
+ flat,
1266
+ scene: prepare(new THREE.Scene()),
1267
+ camera,
1268
+ controls: null,
1269
+ raycaster,
1270
+ clock,
1271
+ mouse: new THREE.Vector2(),
1272
+ frameloop,
1273
+ onPointerMissed,
1274
+ performance: {
1275
+ current: 1,
1276
+ min: 0.5,
1277
+ max: 1,
1278
+ debounce: 200,
1279
+ ...performance,
1280
+ regress: () => {
1281
+ const state = get(); // Clear timeout
1282
+
1283
+ if (performanceTimeout) clearTimeout(performanceTimeout); // Set lower bound performance
1284
+
1285
+ if (state.performance.current !== state.performance.min) setPerformanceCurrent(state.performance.min); // Go back to upper bound performance after a while unless something regresses meanwhile
1286
+
1287
+ performanceTimeout = setTimeout(() => setPerformanceCurrent(get().performance.max), state.performance.debounce);
1288
+ }
1289
+ },
1290
+ size: {
1291
+ width: 0,
1292
+ height: 0
1293
+ },
1294
+ viewport: {
1295
+ initialDpr,
1296
+ dpr: initialDpr,
1297
+ width: 0,
1298
+ height: 0,
1299
+ aspect: 0,
1300
+ distance: 0,
1301
+ factor: 0,
1302
+ getCurrentViewport
1303
+ },
1304
+ setSize: (width, height) => {
1305
+ const size = {
1306
+ width,
1307
+ height
1308
+ };
1309
+ set(state => ({
1310
+ size,
1311
+ viewport: { ...state.viewport,
1312
+ ...getCurrentViewport(camera, defaultTarget, size)
1313
+ }
1314
+ }));
1315
+ },
1316
+ setDpr: dpr => set(state => ({
1317
+ viewport: { ...state.viewport,
1318
+ dpr: calculateDpr(dpr)
1319
+ }
1320
+ })),
1321
+ setFrameloop: (frameloop = 'always') => set(() => ({
1322
+ frameloop
1323
+ })),
1324
+ events: {
1325
+ connected: false
1326
+ },
1327
+ internal: {
1328
+ active: false,
1329
+ priority: 0,
1330
+ frames: 0,
1331
+ lastProps: props,
1332
+ lastEvent: /*#__PURE__*/React.createRef(),
1333
+ interaction: [],
1334
+ hovered: new Map(),
1335
+ subscribers: [],
1336
+ initialClick: [0, 0],
1337
+ initialHits: [],
1338
+ capturedMap: new Map(),
1339
+ xr,
1340
+ subscribe: (ref, priority = 0) => {
1341
+ set(({
1342
+ internal
1343
+ }) => ({
1344
+ internal: { ...internal,
1345
+ // If this subscription was given a priority, it takes rendering into its own hands
1346
+ // For that reason we switch off automatic rendering and increase the manual flag
1347
+ // As long as this flag is positive there can be no internal rendering at all
1348
+ // because there could be multiple render subscriptions
1349
+ priority: internal.priority + (priority > 0 ? 1 : 0),
1350
+ // Register subscriber and sort layers from lowest to highest, meaning,
1351
+ // highest priority renders last (on top of the other frames)
1352
+ subscribers: [...internal.subscribers, {
1353
+ ref,
1354
+ priority
1355
+ }].sort((a, b) => a.priority - b.priority)
1356
+ }
1357
+ }));
1358
+ return () => {
1359
+ set(({
1360
+ internal
1361
+ }) => ({
1362
+ internal: { ...internal,
1363
+ // Decrease manual flag if this subscription had a priority
1364
+ priority: internal.priority - (priority > 0 ? 1 : 0),
1365
+ // Remove subscriber from list
1366
+ subscribers: internal.subscribers.filter(s => s.ref !== ref)
1367
+ }
1368
+ }));
1369
+ };
1370
+ }
1371
+ }
1372
+ };
1373
+ });
1374
+ const state = rootState.getState(); // Resize camera and renderer on changes to size and pixelratio
1375
+
1376
+ let oldSize = state.size;
1377
+ let oldDpr = state.viewport.dpr;
1378
+ rootState.subscribe(() => {
1379
+ const {
1380
+ camera,
1381
+ size,
1382
+ viewport,
1383
+ internal
1384
+ } = rootState.getState();
1385
+
1386
+ if (size !== oldSize || viewport.dpr !== oldDpr) {
1387
+ // https://github.com/pmndrs/react-three-fiber/issues/92
1388
+ // Do not mess with the camera if it belongs to the user
1389
+ if (!camera.manual && !(internal.lastProps.camera instanceof THREE.Camera)) {
1390
+ if (isOrthographicCamera(camera)) {
1391
+ camera.left = size.width / -2;
1392
+ camera.right = size.width / 2;
1393
+ camera.top = size.height / 2;
1394
+ camera.bottom = size.height / -2;
1395
+ } else {
1396
+ camera.aspect = size.width / size.height;
1397
+ }
1398
+
1399
+ camera.updateProjectionMatrix(); // https://github.com/pmndrs/react-three-fiber/issues/178
1400
+ // Update matrix world since the renderer is a frame late
1401
+
1402
+ camera.updateMatrixWorld();
1403
+ } // Update renderer
1404
+
1405
+
1406
+ gl.setPixelRatio(viewport.dpr);
1407
+ gl.setSize(size.width, size.height);
1408
+ oldSize = size;
1409
+ oldDpr = viewport.dpr;
1410
+ }
1411
+ }); // Update size
1412
+
1413
+ if (size) state.setSize(size.width, size.height); // Invalidate on any change
1414
+
1415
+ rootState.subscribe(state => invalidate(state)); // Return root state
1416
+
1417
+ return rootState;
1418
+ };
1419
+
1420
+ function useStore() {
1421
+ const store = React.useContext(context);
1422
+ if (!store) throw `R3F hooks can only be used within the Canvas component!`;
1423
+ return store;
1424
+ }
1425
+ function useThree(selector = state => state, equalityFn) {
1426
+ return useStore()(selector, equalityFn);
1427
+ }
1428
+ function useFrame(callback, renderPriority = 0) {
1429
+ const subscribe = useStore().getState().internal.subscribe; // Update ref
1430
+
1431
+ const ref = React.useRef(callback);
1432
+ React.useLayoutEffect(() => void (ref.current = callback), [callback]); // Subscribe on mount, unsubscribe on unmount
1433
+
1434
+ React.useLayoutEffect(() => subscribe(ref, renderPriority), [renderPriority, subscribe]);
1435
+ return null;
1436
+ }
1437
+ function useGraph(object) {
1438
+ return React.useMemo(() => buildGraph(object), [object]);
1439
+ }
1440
+
1441
+ function loadingFn(extensions, onProgress) {
1442
+ return function (Proto, ...input) {
1443
+ // Construct new loader and run extensions
1444
+ const loader = new Proto();
1445
+ if (extensions) extensions(loader); // Go through the urls and load them
1446
+
1447
+ return Promise.all(input.map(input => new Promise((res, reject) => loader.load(input, data => {
1448
+ if (data.scene) Object.assign(data, buildGraph(data.scene));
1449
+ res(data);
1450
+ }, onProgress, error => reject(`Could not load ${input}: ${error.message}`)))));
1451
+ };
1452
+ }
1453
+
1454
+ function useLoader(Proto, input, extensions, onProgress) {
1455
+ // Use suspense to load async assets
1456
+ const keys = Array.isArray(input) ? input : [input];
1457
+ const results = suspend(loadingFn(extensions, onProgress), [Proto, ...keys], {
1458
+ equal: is.equ
1459
+ }); // Return the object/s
1460
+
1461
+ return Array.isArray(input) ? results : results[0];
1462
+ }
1463
+
1464
+ useLoader.preload = function (Proto, input, extensions) {
1465
+ const keys = Array.isArray(input) ? input : [input];
1466
+ return preload(loadingFn(extensions), [Proto, ...keys]);
1467
+ };
1468
+
1469
+ useLoader.clear = function (Proto, input) {
1470
+ const keys = Array.isArray(input) ? input : [input];
1471
+ return clear([Proto, ...keys]);
1472
+ };
1473
+
1474
+ function createSubs(callback, subs) {
1475
+ const index = subs.length;
1476
+ subs.push(callback);
1477
+ return () => void subs.splice(index, 1);
1478
+ }
1479
+
1480
+ let i;
1481
+ let globalEffects = [];
1482
+ let globalAfterEffects = [];
1483
+ let globalTailEffects = [];
1484
+ const addEffect = callback => createSubs(callback, globalEffects);
1485
+ const addAfterEffect = callback => createSubs(callback, globalAfterEffects);
1486
+ const addTail = callback => createSubs(callback, globalTailEffects);
1487
+
1488
+ function run(effects, timestamp) {
1489
+ for (i = 0; i < effects.length; i++) effects[i](timestamp);
1490
+ }
1491
+
1492
+ function render$1(timestamp, state) {
1493
+ // Run local effects
1494
+ let delta = state.clock.getDelta(); // In frameloop='never' mode, clock times are updated using the provided timestamp
1495
+
1496
+ if (state.frameloop === 'never' && typeof timestamp === 'number') {
1497
+ delta = timestamp - state.clock.elapsedTime;
1498
+ state.clock.oldTime = state.clock.elapsedTime;
1499
+ state.clock.elapsedTime = timestamp;
1500
+ } // Call subscribers (useFrame)
1501
+
1502
+
1503
+ for (i = 0; i < state.internal.subscribers.length; i++) state.internal.subscribers[i].ref.current(state, delta); // Render content
1504
+
1505
+
1506
+ if (!state.internal.priority && state.gl.render) state.gl.render(state.scene, state.camera); // Decrease frame count
1507
+
1508
+ state.internal.frames = Math.max(0, state.internal.frames - 1);
1509
+ return state.frameloop === 'always' ? 1 : state.internal.frames;
1510
+ }
1511
+
1512
+ function createLoop(roots) {
1513
+ let running = false;
1514
+ let repeat;
1515
+
1516
+ function loop(timestamp) {
1517
+ running = true;
1518
+ repeat = 0; // Run effects
1519
+
1520
+ run(globalEffects, timestamp); // Render all roots
1521
+
1522
+ roots.forEach(root => {
1523
+ var _state$gl$xr;
1524
+
1525
+ const state = root.store.getState(); // If the frameloop is invalidated, do not run another frame
1526
+
1527
+ if (state.internal.active && (state.frameloop === 'always' || state.internal.frames > 0) && !((_state$gl$xr = state.gl.xr) != null && _state$gl$xr.isPresenting)) {
1528
+ repeat += render$1(timestamp, state);
1529
+ }
1530
+ }); // Run after-effects
1531
+
1532
+ run(globalAfterEffects, timestamp); // Keep on looping if anything invalidates the frameloop
1533
+
1534
+ if (repeat > 0) return requestAnimationFrame(loop); // Tail call effects, they are called when rendering stops
1535
+ else run(globalTailEffects, timestamp); // Flag end of operation
1536
+
1537
+ running = false;
1538
+ }
1539
+
1540
+ function invalidate(state) {
1541
+ var _state$gl$xr2;
1542
+
1543
+ if (!state) return roots.forEach(root => invalidate(root.store.getState()));
1544
+ if ((_state$gl$xr2 = state.gl.xr) != null && _state$gl$xr2.isPresenting || !state.internal.active || state.frameloop === 'never') return; // Increase frames, do not go higher than 60
1545
+
1546
+ state.internal.frames = Math.min(60, state.internal.frames + 1); // If the render-loop isn't active, start it
1547
+
1548
+ if (!running) {
1549
+ running = true;
1550
+ requestAnimationFrame(loop);
1551
+ }
1552
+ }
1553
+
1554
+ function advance(timestamp, runGlobalEffects = true, state) {
1555
+ if (runGlobalEffects) run(globalEffects, timestamp);
1556
+ if (!state) roots.forEach(root => render$1(timestamp, root.store.getState()));else render$1(timestamp, state);
1557
+ if (runGlobalEffects) run(globalAfterEffects, timestamp);
1558
+ }
1559
+
1560
+ return {
1561
+ loop,
1562
+ invalidate,
1563
+ advance
1564
+ };
1565
+ }
1566
+
1567
+ const roots = new Map();
1568
+ const {
1569
+ invalidate,
1570
+ advance
1571
+ } = createLoop(roots);
1572
+ const {
1573
+ reconciler,
1574
+ applyProps
1575
+ } = createRenderer(roots, getEventPriority);
1576
+
1577
+ const createRendererInstance = (gl, canvas) => {
1578
+ const customRenderer = typeof gl === 'function' ? gl(canvas) : gl;
1579
+ if (isRenderer(customRenderer)) return customRenderer;
1580
+ const renderer = new THREE.WebGLRenderer({
1581
+ powerPreference: 'high-performance',
1582
+ canvas: canvas,
1583
+ antialias: true,
1584
+ alpha: true,
1585
+ ...gl
1586
+ }); // Set color management
1587
+
1588
+ renderer.outputEncoding = THREE.sRGBEncoding;
1589
+ renderer.toneMapping = THREE.ACESFilmicToneMapping; // Set gl props
1590
+
1591
+ if (gl) applyProps(renderer, gl);
1592
+ return renderer;
1593
+ };
1594
+
1595
+ function createRoot(canvas, config) {
1596
+ return {
1597
+ render: element => {
1598
+ var _store;
1599
+
1600
+ let {
1601
+ gl,
1602
+ size,
1603
+ events,
1604
+ onCreated,
1605
+ ...props
1606
+ } = config || {}; // Allow size to take on container bounds initially
1607
+
1608
+ if (!size) {
1609
+ var _canvas$parentElement, _canvas$parentElement2, _canvas$parentElement3, _canvas$parentElement4;
1610
+
1611
+ size = {
1612
+ width: (_canvas$parentElement = (_canvas$parentElement2 = canvas.parentElement) == null ? void 0 : _canvas$parentElement2.clientWidth) != null ? _canvas$parentElement : 0,
1613
+ height: (_canvas$parentElement3 = (_canvas$parentElement4 = canvas.parentElement) == null ? void 0 : _canvas$parentElement4.clientHeight) != null ? _canvas$parentElement3 : 0
1614
+ };
1615
+ }
1616
+
1617
+ let root = roots.get(canvas);
1618
+ let fiber = root == null ? void 0 : root.fiber;
1619
+ let store = root == null ? void 0 : root.store;
1620
+ let state = (_store = store) == null ? void 0 : _store.getState();
1621
+
1622
+ if (fiber && state) {
1623
+ // When a root was found, see if any fundamental props must be changed or exchanged
1624
+ // Check pixelratio
1625
+ if (props.dpr !== undefined && state.viewport.dpr !== calculateDpr(props.dpr)) state.setDpr(props.dpr); // Check size
1626
+
1627
+ if (state.size.width !== size.width || state.size.height !== size.height) state.setSize(size.width, size.height); // Check frameloop
1628
+
1629
+ if (state.frameloop !== props.frameloop) state.setFrameloop(props.frameloop); // For some props we want to reset the entire root
1630
+ // Changes to the color-space
1631
+
1632
+ const linearChanged = props.linear !== state.internal.lastProps.linear;
1633
+
1634
+ if (linearChanged) {
1635
+ unmountComponentAtNode(canvas);
1636
+ fiber = undefined;
1637
+ }
1638
+ }
1639
+
1640
+ if (!fiber) {
1641
+ // If no root has been found, make one
1642
+ // Create gl
1643
+ const glRenderer = createRendererInstance(gl, canvas); // Create store
1644
+
1645
+ store = createStore(applyProps, invalidate, advance, {
1646
+ gl: glRenderer,
1647
+ size,
1648
+ ...props
1649
+ });
1650
+ const state = store.getState(); // Create renderer
1651
+
1652
+ fiber = reconciler.createContainer(store, ConcurrentRoot, false, null); // Map it
1653
+
1654
+ roots.set(canvas, {
1655
+ fiber,
1656
+ store
1657
+ }); // Store events internally
1658
+
1659
+ if (events) state.set({
1660
+ events: events(store)
1661
+ });
1662
+ }
1663
+
1664
+ if (store && fiber) {
1665
+ reconciler.updateContainer( /*#__PURE__*/React.createElement(Provider, {
1666
+ store: store,
1667
+ element: element,
1668
+ onCreated: onCreated,
1669
+ target: canvas
1670
+ }), fiber, null, () => undefined);
1671
+ return store;
1672
+ } else {
1673
+ throw 'Error creating root!';
1674
+ }
1675
+ },
1676
+ unmount: () => unmountComponentAtNode(canvas)
1677
+ };
1678
+ }
1679
+
1680
+ function render(element, canvas, config = {}) {
1681
+ console.warn('R3F.render is no longer supported in React 18. Use createRoot instead!');
1682
+ return createRoot(canvas, config).render(element);
1683
+ }
1684
+
1685
+ function Provider({
1686
+ store,
1687
+ element,
1688
+ onCreated,
1689
+ target
1690
+ }) {
1691
+ React.useEffect(() => {
1692
+ const state = store.getState(); // Flag the canvas active, rendering will now begin
1693
+
1694
+ state.set(state => ({
1695
+ internal: { ...state.internal,
1696
+ active: true
1697
+ }
1698
+ })); // Connect events
1699
+
1700
+ state.events.connect == null ? void 0 : state.events.connect(target); // Notifiy that init is completed, the scene graph exists, but nothing has yet rendered
1701
+
1702
+ if (onCreated) onCreated(state); // eslint-disable-next-line react-hooks/exhaustive-deps
1703
+ }, []);
1704
+ return /*#__PURE__*/React.createElement(context.Provider, {
1705
+ value: store
1706
+ }, element);
1707
+ }
1708
+
1709
+ function unmountComponentAtNode(canvas, callback) {
1710
+ const root = roots.get(canvas);
1711
+ const fiber = root == null ? void 0 : root.fiber;
1712
+
1713
+ if (fiber) {
1714
+ const state = root == null ? void 0 : root.store.getState();
1715
+ if (state) state.internal.active = false;
1716
+ reconciler.updateContainer(null, fiber, null, () => {
1717
+ if (state) {
1718
+ setTimeout(() => {
1719
+ try {
1720
+ var _state$gl, _state$gl$renderLists, _state$gl2, _state$gl3;
1721
+
1722
+ state.events.disconnect == null ? void 0 : state.events.disconnect();
1723
+ (_state$gl = state.gl) == null ? void 0 : (_state$gl$renderLists = _state$gl.renderLists) == null ? void 0 : _state$gl$renderLists.dispose == null ? void 0 : _state$gl$renderLists.dispose();
1724
+ (_state$gl2 = state.gl) == null ? void 0 : _state$gl2.forceContextLoss == null ? void 0 : _state$gl2.forceContextLoss();
1725
+ if ((_state$gl3 = state.gl) != null && _state$gl3.xr) state.internal.xr.disconnect();
1726
+ dispose(state);
1727
+ roots.delete(canvas);
1728
+ if (callback) callback(canvas);
1729
+ } catch (e) {
1730
+ /* ... */
1731
+ }
1732
+ }, 500);
1733
+ }
1734
+ });
1735
+ }
1736
+ }
1737
+
1738
+ const act = React.unstable_act;
1739
+
1740
+ function createPortal(children, container) {
1741
+ return reconciler.createPortal(children, container, null, null);
1742
+ }
1743
+
1744
+ reconciler.injectIntoDevTools({
1745
+ bundleType: process.env.NODE_ENV === 'production' ? 0 : 1,
1746
+ rendererPackageName: '@react-three/fiber',
1747
+ version: '18.0.0'
1748
+ });
1749
+
1750
+ export { is as A, createRoot as a, useStore as b, createEvents as c, useThree as d, extend as e, useFrame as f, useGraph as g, useLoader as h, context as i, createPortal as j, reconciler as k, applyProps as l, dispose as m, invalidate as n, omit as o, pick as p, advance as q, render as r, addEffect as s, threeTypes as t, unmountComponentAtNode as u, addAfterEffect as v, addTail as w, act as x, roots as y, buildGraph as z };