@react-three/fiber 8.0.0-alpha-08 → 8.0.0-beta-02

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