@octanejs/three 0.1.24 → 0.1.26

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.
@@ -26,9 +26,9 @@ import {
26
26
  } from './store.js';
27
27
  import {
28
28
  createThreeObject,
29
- registerThreeNamespace,
30
29
  resolveThreeConstructor,
31
30
  THREE_RENDERER_ID,
31
+ type ConstructorRepresentation,
32
32
  } from './catalogue.js';
33
33
  import {
34
34
  attachString,
@@ -48,6 +48,10 @@ const THREE_PORTAL_TARGET = Symbol('octane.three.portal-target');
48
48
  const EXTERNAL_PORTAL_TARGET_LEASES = new WeakMap<THREE.Object3D, ExternalTargetLease>();
49
49
  const EMPTY_THREE_EVENTS = new Map<string, UniversalEventListenerDescriptor>();
50
50
  const EMPTY_THREE_CALLBACKS = new Map<string, UniversalListenerDescriptor>();
51
+ const THREE_OBJECT3D_ADD = THREE.Object3D.prototype.add;
52
+ const THREE_OBJECT3D_REMOVE = THREE.Object3D.prototype.remove;
53
+ const THREE_OBJECT3D_REMOVE_FROM_PARENT = THREE.Object3D.prototype.removeFromParent;
54
+ const THREE_OBJECT3D_DISPATCH = THREE.Object3D.prototype.dispatchEvent;
51
55
  const THREE_VECTOR3_FROM_ARRAY = THREE.Vector3.prototype.fromArray;
52
56
 
53
57
  const THREE_EVENT_PRIORITIES: Readonly<Record<string, UniversalEventPriority>> = Object.freeze({
@@ -105,7 +109,7 @@ interface ThreePortalTargetDomain {
105
109
  type PhysicalPlacement =
106
110
  | {
107
111
  readonly kind: 'object3d';
108
- readonly object: THREE.Object3D;
112
+ object: THREE.Object3D;
109
113
  readonly parent: THREE.Object3D;
110
114
  }
111
115
  | {
@@ -170,7 +174,7 @@ interface ThreeDriverState {
170
174
  readonly portalChildren: Map<string | number, number[]>;
171
175
  readonly portalTargets: Map<string | number, ThreePortalTargetDomain>;
172
176
  readonly portalTargetCache: WeakMap<RootStore, WeakMap<THREE.Object3D, ThreePortalTargetDomain>>;
173
- readonly disposalQueue: Array<() => void>;
177
+ readonly disposalQueue: any[];
174
178
  nextPortalTarget: number;
175
179
  disposalScheduled: boolean;
176
180
  }
@@ -291,7 +295,19 @@ export function createThreeContainer(
291
295
  flushDisposals() {
292
296
  state.disposalScheduled = false;
293
297
  const queue = state.disposalQueue.splice(0);
294
- runAll(queue);
298
+ let failed = false;
299
+ let firstError: unknown;
300
+ for (const object of queue) {
301
+ try {
302
+ disposeOwnedNow(object);
303
+ } catch (error) {
304
+ if (!failed) {
305
+ failed = true;
306
+ firstError = error;
307
+ }
308
+ }
309
+ }
310
+ if (failed) throw firstError;
295
311
  },
296
312
  [THREE_DRIVER_STATE]: state,
297
313
  };
@@ -301,7 +317,7 @@ export function createThreeContainer(
301
317
 
302
318
  function enqueueDisposal(container: ThreeHostContainer, object: any): void {
303
319
  const state = container[THREE_DRIVER_STATE];
304
- state.disposalQueue.push(() => disposeOwnedNow(object));
320
+ state.disposalQueue.push(object);
305
321
  if (state.disposalScheduled) return;
306
322
  state.disposalScheduled = true;
307
323
  const schedule = container.environment.scheduleDispose ?? defaultScheduleDispose;
@@ -343,7 +359,6 @@ interface DirectMeshProps extends Readonly<Record<string, unknown>> {
343
359
  function isDirectMeshProps(props: Readonly<Record<string, unknown>>): props is DirectMeshProps {
344
360
  let nextName = 'name';
345
361
  for (const name in props) {
346
- if (!Object.prototype.hasOwnProperty.call(props, name)) continue;
347
362
  if (name !== nextName) return false;
348
363
  nextName = name === 'name' ? 'position' : '';
349
364
  }
@@ -353,6 +368,25 @@ function isDirectMeshProps(props: Readonly<Record<string, unknown>>): props is D
353
368
  return nextName === '' && typeof props.name === 'string' && Array.isArray(position);
354
369
  }
355
370
 
371
+ function canSilentlyMutateRootScene(scene: THREE.Scene, removing = false): boolean {
372
+ const children = scene.children;
373
+ return (
374
+ scene.add === THREE_OBJECT3D_ADD &&
375
+ (!removing || scene.remove === THREE_OBJECT3D_REMOVE) &&
376
+ scene.dispatchEvent === THREE_OBJECT3D_DISPATCH &&
377
+ !Object.hasOwn(scene, '_listeners') &&
378
+ !('_listeners' in Object.getPrototypeOf(scene)) &&
379
+ Array.isArray(children) &&
380
+ Object.getPrototypeOf(children) === Array.prototype &&
381
+ children.push === Array.prototype.push &&
382
+ (!removing ||
383
+ (children.splice === Array.prototype.splice &&
384
+ children.indexOf === Array.prototype.indexOf)) &&
385
+ Object.isExtensible(children) &&
386
+ Object.getOwnPropertyDescriptor(children, 'length')?.writable === true
387
+ );
388
+ }
389
+
356
390
  function prepareDirectLeafMountBatch(
357
391
  container: ThreeHostContainer,
358
392
  batch: UniversalHostBatch,
@@ -392,6 +426,8 @@ function prepareDirectLeafMountBatch(
392
426
  ids.add(create.id);
393
427
  }
394
428
 
429
+ const scene = container.scene;
430
+ let addSilently = canSilentlyMutateRootScene(scene);
395
431
  const staged: ThreeHostInstance[] = [];
396
432
  try {
397
433
  for (let index = 0; index < createCount; index++) {
@@ -409,9 +445,24 @@ function prepareDirectLeafMountBatch(
409
445
  true,
410
446
  ),
411
447
  );
412
- applyThreeProps(object, command.props, undefined, {
413
- colorSpace: container.environment.linear !== true,
414
- });
448
+ if (object.position.fromArray === THREE_VECTOR3_FROM_ARRAY) {
449
+ const props = command.props as DirectMeshProps;
450
+ object.name = props.name;
451
+ object.position.fromArray(props.position);
452
+ } else {
453
+ applyThreeProps(object, command.props, undefined, {
454
+ colorSpace: container.environment.linear !== true,
455
+ });
456
+ }
457
+ if (
458
+ addSilently &&
459
+ (Object.hasOwn(object, '_listeners') ||
460
+ object.dispatchEvent !== THREE_OBJECT3D_DISPATCH ||
461
+ object.removeFromParent !== THREE_OBJECT3D_REMOVE_FROM_PARENT ||
462
+ object.parent !== null)
463
+ ) {
464
+ addSilently = false;
465
+ }
415
466
  }
416
467
  } catch (error) {
417
468
  for (const instance of staged) disposeOwnedNow(instance.object);
@@ -423,6 +474,7 @@ function prepareDirectLeafMountBatch(
423
474
  apply() {
424
475
  if (status !== 'prepared') return;
425
476
  status = 'applied';
477
+ addSilently &&= canSilentlyMutateRootScene(scene);
426
478
  state.directInstances = staged;
427
479
  let failed = false;
428
480
  let firstError: unknown;
@@ -433,11 +485,16 @@ function prepareDirectLeafMountBatch(
433
485
  instance.parent = null;
434
486
  OBJECT_INSTANCES.set(instance.object, instance);
435
487
  try {
436
- container.scene.add(instance.object);
488
+ if (addSilently) {
489
+ instance.object.parent = scene;
490
+ scene.children.push(instance.object);
491
+ } else {
492
+ scene.add(instance.object);
493
+ }
437
494
  instance.physical = {
438
495
  kind: 'object3d',
439
496
  object: instance.object,
440
- parent: container.scene,
497
+ parent: scene,
441
498
  };
442
499
  } catch (error) {
443
500
  if (!failed) {
@@ -464,7 +521,10 @@ function prepareDirectLeafMountBatch(
464
521
  firstError = error;
465
522
  }
466
523
  }
467
- if (failed) throw firstError;
524
+ if (failed) {
525
+ state.directInstances = null;
526
+ throw firstError;
527
+ }
468
528
  },
469
529
  abort() {
470
530
  if (status !== 'prepared') return;
@@ -497,22 +557,25 @@ function prepareUpdateOnlyBatch(
497
557
  if (command.op !== 'update') return null;
498
558
  const instance = instances[index];
499
559
  if (command.id !== instance.id) return null;
500
- const nameDescriptor = Object.getOwnPropertyDescriptor(instance.object, 'name');
501
560
  if (
502
- !instance.directLeaf ||
503
- instance.physical?.kind !== 'object3d' ||
504
- instance.physical.parent !== container.scene ||
505
561
  instance.object.parent !== container.scene ||
506
562
  container.scene.children[index] !== instance.object ||
507
563
  instance.object.visible !== true ||
508
- nameDescriptor === undefined ||
509
- !('value' in nameDescriptor) ||
510
- nameDescriptor.writable !== true ||
511
564
  instance.object.position.fromArray !== THREE_VECTOR3_FROM_ARRAY
512
565
  ) {
513
566
  return null;
514
567
  }
515
568
  if (!isDirectMeshProps(command.props)) return null;
569
+ if ((instance.props as DirectMeshProps).name !== command.props.name) {
570
+ const nameDescriptor = Object.getOwnPropertyDescriptor(instance.object, 'name');
571
+ if (
572
+ nameDescriptor === undefined ||
573
+ !('value' in nameDescriptor) ||
574
+ nameDescriptor.writable !== true
575
+ ) {
576
+ return null;
577
+ }
578
+ }
516
579
  }
517
580
 
518
581
  let status: 'prepared' | 'applied' | 'aborted' = 'prepared';
@@ -565,7 +628,581 @@ function prepareUpdateOnlyBatch(
565
628
  firstError = error;
566
629
  }
567
630
  }
568
- if (failed) throw firstError;
631
+ if (failed) {
632
+ state.directInstances = null;
633
+ throw firstError;
634
+ }
635
+ },
636
+ abort() {
637
+ if (status === 'prepared') status = 'aborted';
638
+ },
639
+ };
640
+ }
641
+
642
+ interface AcceptedFlatBatchResult {
643
+ failed: boolean;
644
+ error: unknown;
645
+ }
646
+
647
+ function retainFlatBatchError(result: AcceptedFlatBatchResult, error: unknown): void {
648
+ if (result.failed) return;
649
+ result.failed = true;
650
+ result.error = error;
651
+ }
652
+
653
+ function finishFlatRootBatch(
654
+ container: ThreeHostContainer,
655
+ batch: UniversalHostBatch,
656
+ result: AcceptedFlatBatchResult,
657
+ ): void {
658
+ if (container.environment.recordCommits !== false) {
659
+ try {
660
+ container.commits.push(batch);
661
+ } catch (error) {
662
+ retainFlatBatchError(result, error);
663
+ }
664
+ }
665
+ try {
666
+ container.environment.invalidate?.();
667
+ } catch (error) {
668
+ retainFlatBatchError(result, error);
669
+ }
670
+ if (result.failed) {
671
+ container[THREE_DRIVER_STATE].directInstances = null;
672
+ throw result.error;
673
+ }
674
+ }
675
+
676
+ /**
677
+ * A flat, callback-free root has no attachment, portal, visibility, or
678
+ * interaction relationships to simulate. Verify the live graph first so public
679
+ * Object3D mutations still fall back to the full synchronizing driver.
680
+ */
681
+ function getFlatRootInstances(container: ThreeHostContainer): readonly ThreeHostInstance[] | null {
682
+ const state = container[THREE_DRIVER_STATE];
683
+ const count = state.rootChildren.length;
684
+ if (
685
+ count === 0 ||
686
+ state.instances.size !== count ||
687
+ state.portalTargets.size !== 0 ||
688
+ state.portalChildren.size !== 0 ||
689
+ container.scene.parent !== null ||
690
+ container.scene.children.length !== count
691
+ ) {
692
+ return null;
693
+ }
694
+
695
+ const store = container.environment.store;
696
+ if (store !== undefined) {
697
+ const interaction = store.getState().internal;
698
+ if (
699
+ interaction.interaction.length !== 0 ||
700
+ interaction.initialHits.length !== 0 ||
701
+ interaction.hovered.size !== 0 ||
702
+ interaction.capturedMap.size !== 0
703
+ ) {
704
+ return null;
705
+ }
706
+ }
707
+
708
+ const direct = state.directInstances;
709
+ if (direct !== null && direct.length !== count) return null;
710
+ if (direct !== null) {
711
+ // This private array is retained only after an entirely successful direct
712
+ // commit. Structural work and accepted faults clear it, so logical maps,
713
+ // ownership, and placement descriptors cannot drift independently. Public
714
+ // Three objects remain mutable and must still be checked every time.
715
+ for (let index = 0; index < count; index++) {
716
+ const instance = direct[index];
717
+ if (
718
+ instance.id !== state.rootChildren[index] ||
719
+ instance.object.parent !== container.scene ||
720
+ instance.object.visible !== true ||
721
+ container.scene.children[index] !== instance.object
722
+ ) {
723
+ return null;
724
+ }
725
+ }
726
+ return direct;
727
+ }
728
+
729
+ const instances = new Array<ThreeHostInstance>(count);
730
+ for (let index = 0; index < count; index++) {
731
+ const instance = state.instances.get(state.rootChildren[index]);
732
+ if (
733
+ instance === undefined ||
734
+ instance.id !== state.rootChildren[index] ||
735
+ instance.parent !== null ||
736
+ instance.children.length !== 0 ||
737
+ !instance.visible ||
738
+ instance.events.size !== 0 ||
739
+ instance.lifecycles.size !== 0 ||
740
+ instance.localCallbacks.size !== 0 ||
741
+ instance.localCleanups.size !== 0 ||
742
+ instance.store !== store ||
743
+ instance.physical?.kind !== 'object3d' ||
744
+ instance.physical.object !== instance.object ||
745
+ instance.physical.parent !== container.scene ||
746
+ instance.object.parent !== container.scene ||
747
+ instance.object.visible !== (instance.props.visible !== false) ||
748
+ container.scene.children[index] !== instance.object
749
+ ) {
750
+ return null;
751
+ }
752
+ instances[index] = instance;
753
+ }
754
+ return instances;
755
+ }
756
+
757
+ function stageFlatRootObject(
758
+ container: ThreeHostContainer,
759
+ Constructor: ConstructorRepresentation,
760
+ props: Readonly<Record<string, unknown>>,
761
+ ): any {
762
+ const args = props.args;
763
+ if (args !== undefined && !Array.isArray(args)) {
764
+ throw new Error('@octanejs/three: The args prop must be an array.');
765
+ }
766
+ const object = new Constructor(...((args as readonly unknown[] | undefined) ?? []));
767
+ try {
768
+ for (const prop in props) {
769
+ if (prop === 'args') continue;
770
+ applyThreeProps(object as object, props, undefined, {
771
+ colorSpace: container.environment.linear !== true,
772
+ });
773
+ break;
774
+ }
775
+ } catch (error) {
776
+ disposeOwnedNow(object);
777
+ throw error;
778
+ }
779
+ return object;
780
+ }
781
+
782
+ /**
783
+ * Recreate root Object3D leaves without cloning the complete logical graph.
784
+ * All replacements are constructed while the transaction remains rejectable;
785
+ * abort disposes only those unpublished replacements.
786
+ */
787
+ function prepareFlatRootRecreationBatch(
788
+ container: ThreeHostContainer,
789
+ batch: UniversalHostBatch,
790
+ ): UniversalPreparedHostBatch | null {
791
+ const state = container[THREE_DRIVER_STATE];
792
+ const count = state.rootChildren.length;
793
+ if (
794
+ count === 0 ||
795
+ batch.commands.length !== count ||
796
+ batch.commands[0]?.op !== 'recreate' ||
797
+ batch.commands[count - 1]?.op !== 'recreate'
798
+ ) {
799
+ return null;
800
+ }
801
+ const instances = getFlatRootInstances(container);
802
+ if (instances === null) return null;
803
+
804
+ const constructors = new Map<string, ConstructorRepresentation>();
805
+ const scene = container.scene;
806
+ const children = scene.children;
807
+ let replaceSilently = canSilentlyMutateRootScene(scene, true);
808
+ let previousConstructorType: string | undefined;
809
+ let previousConstructor: ConstructorRepresentation | undefined;
810
+ for (let index = 0; index < count; index++) {
811
+ const command = batch.commands[index];
812
+ const instance = instances[index];
813
+ if (
814
+ command.op !== 'recreate' ||
815
+ command.id !== instance.id ||
816
+ command.type !== instance.type ||
817
+ !instance.owned ||
818
+ command.props.attach != null
819
+ ) {
820
+ return null;
821
+ }
822
+ let Constructor =
823
+ command.type === previousConstructorType
824
+ ? previousConstructor
825
+ : constructors.get(command.type);
826
+ if (Constructor === undefined) {
827
+ const resolved = resolveThreeConstructor(command.type);
828
+ if (
829
+ resolved === null ||
830
+ (resolved !== THREE.Object3D && !(resolved.prototype instanceof THREE.Object3D))
831
+ ) {
832
+ return null;
833
+ }
834
+ Constructor = resolved;
835
+ constructors.set(command.type, Constructor);
836
+ if (
837
+ '_listeners' in Constructor.prototype ||
838
+ Constructor.prototype.dispatchEvent !== THREE_OBJECT3D_DISPATCH ||
839
+ Constructor.prototype.removeFromParent !== THREE_OBJECT3D_REMOVE_FROM_PARENT
840
+ ) {
841
+ replaceSilently = false;
842
+ }
843
+ }
844
+ previousConstructorType = command.type;
845
+ previousConstructor = Constructor;
846
+ if (instance.object.constructor !== Constructor) return null;
847
+ }
848
+
849
+ const replacements: THREE.Object3D[] = [];
850
+ try {
851
+ for (let index = 0; index < count; index++) {
852
+ const command = batch.commands[index] as Extract<
853
+ UniversalHostCommand,
854
+ { readonly op: 'recreate' }
855
+ >;
856
+ const replacement = stageFlatRootObject(
857
+ container,
858
+ command.type === previousConstructorType
859
+ ? previousConstructor!
860
+ : constructors.get(command.type)!,
861
+ command.props,
862
+ );
863
+ replacements.push(replacement);
864
+ if (!isObject3D(replacement)) {
865
+ throw new Error(`@octanejs/three: Recreate type mismatch for ${command.id}.`);
866
+ }
867
+ }
868
+ } catch (error) {
869
+ for (const replacement of replacements) disposeOwnedNow(replacement);
870
+ throw error;
871
+ }
872
+
873
+ let status: 'prepared' | 'applied' | 'aborted' = 'prepared';
874
+ return {
875
+ apply() {
876
+ if (status !== 'prepared') return;
877
+ status = 'applied';
878
+ replaceSilently &&= scene.children === children && canSilentlyMutateRootScene(scene, true);
879
+ if (replaceSilently) {
880
+ for (const Constructor of constructors.values()) {
881
+ if (
882
+ '_listeners' in Constructor.prototype ||
883
+ Constructor.prototype.dispatchEvent !== THREE_OBJECT3D_DISPATCH ||
884
+ Constructor.prototype.removeFromParent !== THREE_OBJECT3D_REMOVE_FROM_PARENT
885
+ ) {
886
+ replaceSilently = false;
887
+ break;
888
+ }
889
+ }
890
+ }
891
+ const result: AcceptedFlatBatchResult = { failed: false, error: undefined };
892
+
893
+ for (let index = 0; index < count; index++) {
894
+ try {
895
+ const instance = instances[index];
896
+ const previousObject = instance.object as THREE.Object3D;
897
+ const previousProps = instance.props;
898
+ const replacement = replacements[index];
899
+ const command = batch.commands[index] as Extract<
900
+ UniversalHostCommand,
901
+ { readonly op: 'recreate' }
902
+ >;
903
+ if (
904
+ replaceSilently &&
905
+ (Object.hasOwn(previousObject, '_listeners') ||
906
+ Object.hasOwn(replacement, '_listeners') ||
907
+ previousObject.dispatchEvent !== THREE_OBJECT3D_DISPATCH ||
908
+ replacement.dispatchEvent !== THREE_OBJECT3D_DISPATCH ||
909
+ replacement.removeFromParent !== THREE_OBJECT3D_REMOVE_FROM_PARENT ||
910
+ replacement.parent !== null ||
911
+ previousObject.parent !== scene ||
912
+ children[index] !== previousObject)
913
+ ) {
914
+ replaceSilently = false;
915
+ }
916
+ OBJECT_INSTANCES.delete(previousObject);
917
+ instance.object = replacement;
918
+ instance.props = command.props;
919
+ OBJECT_INSTANCES.set(replacement, instance);
920
+ previousObject.visible = previousProps.visible !== false;
921
+ if (state.disposalScheduled) state.disposalQueue.push(previousObject);
922
+ else enqueueDisposal(container, previousObject);
923
+ } catch (error) {
924
+ retainFlatBatchError(result, error);
925
+ }
926
+ }
927
+
928
+ if (replaceSilently && canSilentlyMutateRootScene(scene, true)) {
929
+ for (let index = 0; index < count; index++) {
930
+ try {
931
+ const instance = instances[index];
932
+ const placement = instance.physical as Extract<PhysicalPlacement, { kind: 'object3d' }>;
933
+ placement.object.parent = null;
934
+ instance.object.parent = scene;
935
+ children[index] = instance.object;
936
+ placement.object = instance.object;
937
+ instance.object.visible = instance.props.visible !== false;
938
+ } catch (error) {
939
+ retainFlatBatchError(result, error);
940
+ }
941
+ }
942
+ } else {
943
+ for (let index = 0; index < count; index++) {
944
+ try {
945
+ const placement = instances[index].physical as Extract<
946
+ PhysicalPlacement,
947
+ { kind: 'object3d' }
948
+ >;
949
+ instances[index].physical = null;
950
+ scene.remove(placement.object);
951
+ } catch (error) {
952
+ retainFlatBatchError(result, error);
953
+ }
954
+ }
955
+
956
+ for (let index = 0; index < count; index++) {
957
+ try {
958
+ const instance = instances[index];
959
+ scene.add(instance.object);
960
+ instance.physical = {
961
+ kind: 'object3d',
962
+ object: instance.object,
963
+ parent: scene,
964
+ };
965
+ instance.object.visible = instance.props.visible !== false;
966
+ } catch (error) {
967
+ retainFlatBatchError(result, error);
968
+ }
969
+ }
970
+ }
971
+ finishFlatRootBatch(container, batch, result);
972
+ },
973
+ abort() {
974
+ if (status !== 'prepared') return;
975
+ status = 'aborted';
976
+ for (const replacement of replacements) disposeOwnedNow(replacement);
977
+ },
978
+ };
979
+ }
980
+
981
+ /** Reorder a root-only mesh list in linear time, including ordinary prop updates. */
982
+ function prepareFlatRootReorderBatch(
983
+ container: ThreeHostContainer,
984
+ batch: UniversalHostBatch,
985
+ ): UniversalPreparedHostBatch | null {
986
+ const state = container[THREE_DRIVER_STATE];
987
+ const count = state.rootChildren.length;
988
+ if (
989
+ count < 2 ||
990
+ state.directInstances === null ||
991
+ batch.commands.length === 0 ||
992
+ batch.commands[batch.commands.length - 1]?.op !== 'move'
993
+ ) {
994
+ return null;
995
+ }
996
+ const instances = getFlatRootInstances(container);
997
+ if (instances === null) return null;
998
+ const scene = container.scene;
999
+ const children = scene.children;
1000
+ const reorderSilently = canSilentlyMutateRootScene(scene, true);
1001
+
1002
+ const positions = new Map<number, number>();
1003
+ const previous = new Int32Array(count);
1004
+ const next = new Int32Array(count);
1005
+ for (let index = 0; index < count; index++) {
1006
+ const instance = instances[index];
1007
+ if (!instance.directLeaf) return null;
1008
+ positions.set(instance.id, index);
1009
+ previous[index] = index - 1;
1010
+ next[index] = index + 1 === count ? -1 : index + 1;
1011
+ }
1012
+ let first = 0;
1013
+ let last = count - 1;
1014
+ let updates = 0;
1015
+ const updated = new Set<number>();
1016
+ while (updates < batch.commands.length && batch.commands[updates].op === 'update') {
1017
+ const command = batch.commands[updates] as Extract<
1018
+ UniversalHostCommand,
1019
+ { readonly op: 'update' }
1020
+ >;
1021
+ const position = positions.get(command.id);
1022
+ if (position === undefined || updated.has(command.id)) return null;
1023
+ const instance = instances[position];
1024
+ if (
1025
+ instance.object.position.fromArray !== THREE_VECTOR3_FROM_ARRAY ||
1026
+ !isDirectMeshProps(command.props)
1027
+ ) {
1028
+ return null;
1029
+ }
1030
+ if ((instance.props as DirectMeshProps).name !== command.props.name) {
1031
+ const descriptor = Object.getOwnPropertyDescriptor(instance.object, 'name');
1032
+ if (descriptor === undefined || !('value' in descriptor) || descriptor.writable !== true) {
1033
+ return null;
1034
+ }
1035
+ }
1036
+ updated.add(command.id);
1037
+ updates++;
1038
+ }
1039
+ if (updates === batch.commands.length) return null;
1040
+
1041
+ for (let index = updates; index < batch.commands.length; index++) {
1042
+ const command = batch.commands[index];
1043
+ if (command.op !== 'move' || command.parent !== null) return null;
1044
+ const moved = positions.get(command.id);
1045
+ const before = command.before === null ? -1 : positions.get(command.before);
1046
+ if (moved === undefined || before === undefined || moved === before) return null;
1047
+
1048
+ const preceding = previous[moved];
1049
+ const following = next[moved];
1050
+ if (preceding === -1) first = following;
1051
+ else next[preceding] = following;
1052
+ if (following === -1) last = preceding;
1053
+ else previous[following] = preceding;
1054
+
1055
+ if (before === -1) {
1056
+ previous[moved] = last;
1057
+ next[moved] = -1;
1058
+ if (last === -1) first = moved;
1059
+ else next[last] = moved;
1060
+ last = moved;
1061
+ } else {
1062
+ const beforePrevious = previous[before];
1063
+ previous[moved] = beforePrevious;
1064
+ next[moved] = before;
1065
+ previous[before] = moved;
1066
+ if (beforePrevious === -1) first = moved;
1067
+ else next[beforePrevious] = moved;
1068
+ }
1069
+ }
1070
+
1071
+ const ordered = new Array<ThreeHostInstance>(count);
1072
+ for (let index = 0, position = first; index < count; index++, position = next[position]) {
1073
+ if (position === -1) return null;
1074
+ ordered[index] = instances[position];
1075
+ }
1076
+
1077
+ let status: 'prepared' | 'applied' | 'aborted' = 'prepared';
1078
+ return {
1079
+ apply() {
1080
+ if (status !== 'prepared') return;
1081
+ status = 'applied';
1082
+ const result: AcceptedFlatBatchResult = { failed: false, error: undefined };
1083
+ for (let index = 0; index < updates; index++) {
1084
+ try {
1085
+ const command = batch.commands[index] as Extract<
1086
+ UniversalHostCommand,
1087
+ { readonly op: 'update' }
1088
+ >;
1089
+ const instance = instances[positions.get(command.id)!];
1090
+ const previousProps = instance.props as DirectMeshProps;
1091
+ const nextProps = command.props as DirectMeshProps;
1092
+ instance.props = nextProps;
1093
+ if (previousProps.name !== nextProps.name) instance.object.name = nextProps.name;
1094
+ const previousPosition = previousProps.position;
1095
+ const nextPosition = nextProps.position;
1096
+ if (
1097
+ previousPosition[0] !== nextPosition[0] ||
1098
+ previousPosition[1] !== nextPosition[1] ||
1099
+ previousPosition[2] !== nextPosition[2]
1100
+ ) {
1101
+ instance.object.position.fromArray(nextPosition);
1102
+ }
1103
+ } catch (error) {
1104
+ retainFlatBatchError(result, error);
1105
+ }
1106
+ }
1107
+
1108
+ try {
1109
+ state.directInstances = ordered;
1110
+ for (let index = 0; index < count; index++) {
1111
+ state.rootChildren[index] = ordered[index].id;
1112
+ }
1113
+ } catch (error) {
1114
+ retainFlatBatchError(result, error);
1115
+ }
1116
+ if (
1117
+ reorderSilently &&
1118
+ scene.children === children &&
1119
+ children.length === count &&
1120
+ canSilentlyMutateRootScene(scene, true)
1121
+ ) {
1122
+ try {
1123
+ for (let index = 0; index < count; index++) children[index] = ordered[index].object;
1124
+ } catch (error) {
1125
+ retainFlatBatchError(result, error);
1126
+ }
1127
+ } else {
1128
+ for (const instance of ordered) {
1129
+ try {
1130
+ scene.add(instance.object);
1131
+ } catch (error) {
1132
+ retainFlatBatchError(result, error);
1133
+ }
1134
+ }
1135
+ }
1136
+ finishFlatRootBatch(container, batch, result);
1137
+ },
1138
+ abort() {
1139
+ if (status === 'prepared') status = 'aborted';
1140
+ },
1141
+ };
1142
+ }
1143
+
1144
+ /** Clear a callback-free, root-only Object3D list without a scene-wide clone. */
1145
+ function prepareFlatRootRemovalBatch(
1146
+ container: ThreeHostContainer,
1147
+ batch: UniversalHostBatch,
1148
+ ): UniversalPreparedHostBatch | null {
1149
+ const state = container[THREE_DRIVER_STATE];
1150
+ const count = state.rootChildren.length;
1151
+ if (
1152
+ count === 0 ||
1153
+ batch.commands.length !== count * 2 ||
1154
+ batch.commands[0]?.op !== 'remove' ||
1155
+ batch.commands[batch.commands.length - 1]?.op !== 'destroy'
1156
+ ) {
1157
+ return null;
1158
+ }
1159
+ const instances = getFlatRootInstances(container);
1160
+ if (instances === null) return null;
1161
+ for (let index = 0; index < count; index++) {
1162
+ const remove = batch.commands[index];
1163
+ const destroy = batch.commands[count + index];
1164
+ if (
1165
+ remove.op !== 'remove' ||
1166
+ remove.parent !== null ||
1167
+ remove.id !== instances[index].id ||
1168
+ destroy.op !== 'destroy' ||
1169
+ destroy.id !== remove.id
1170
+ ) {
1171
+ return null;
1172
+ }
1173
+ }
1174
+
1175
+ let status: 'prepared' | 'applied' | 'aborted' = 'prepared';
1176
+ return {
1177
+ apply() {
1178
+ if (status !== 'prepared') return;
1179
+ status = 'applied';
1180
+ const result: AcceptedFlatBatchResult = { failed: false, error: undefined };
1181
+ state.directInstances = null;
1182
+ state.rootChildren.length = 0;
1183
+ for (const instance of instances) {
1184
+ try {
1185
+ instance.physical = null;
1186
+ container.scene.remove(instance.object);
1187
+ } catch (error) {
1188
+ retainFlatBatchError(result, error);
1189
+ }
1190
+ }
1191
+ for (const instance of instances) {
1192
+ try {
1193
+ instance.object.visible = instance.props.visible !== false;
1194
+ if (instance.owned && instance.type !== 'primitive' && instance.props.dispose !== null) {
1195
+ enqueueDisposal(container, instance.object);
1196
+ }
1197
+ OBJECT_INSTANCES.delete(instance.object);
1198
+ instance.store = undefined;
1199
+ instance.parent = undefined;
1200
+ state.instances.delete(instance.id);
1201
+ } catch (error) {
1202
+ retainFlatBatchError(result, error);
1203
+ }
1204
+ }
1205
+ finishFlatRootBatch(container, batch, result);
569
1206
  },
570
1207
  abort() {
571
1208
  if (status === 'prepared') status = 'aborted';
@@ -707,6 +1344,10 @@ function storeForInstance(
707
1344
  portalTargets: ReadonlyMap<string | number, ThreePortalTargetDomain>,
708
1345
  rootStore: RootStore | undefined,
709
1346
  ): RootStore | undefined {
1347
+ const rootChild = instances.get(id);
1348
+ if (rootChild === undefined || rootChild.parent === undefined) return undefined;
1349
+ if (rootChild.parent === null) return rootStore;
1350
+ if (isPortalParent(rootChild.parent)) return portalTargets.get(rootChild.parent.id)?.store;
710
1351
  const seen = new Set<number>();
711
1352
  let currentId = id;
712
1353
  while (true) {
@@ -728,6 +1369,10 @@ function hasLiveRootConnection(
728
1369
  instances: ReadonlyMap<number, LogicalInteractionInstance>,
729
1370
  portalTargets: ReadonlyMap<string | number, ThreePortalTargetDomain>,
730
1371
  ): boolean {
1372
+ const rootChild = instances.get(id);
1373
+ if (rootChild === undefined || !rootChild.visible) return false;
1374
+ if (rootChild.parent === null) return true;
1375
+ if (rootChild.parent === undefined) return false;
731
1376
  const seen = new Set<number>();
732
1377
  let currentId = id;
733
1378
  while (true) {
@@ -1142,7 +1787,10 @@ export function hasThreeEventListeners(object: object, types?: readonly string[]
1142
1787
  const events = OBJECT_INSTANCES.get(object)?.events;
1143
1788
  if (events === undefined) return false;
1144
1789
  if (types === undefined) return events.size > 0;
1145
- return types.some((type) => events.has(type));
1790
+ for (let index = 0; index < types.length; index++) {
1791
+ if (events.has(types[index])) return true;
1792
+ }
1793
+ return false;
1146
1794
  }
1147
1795
 
1148
1796
  /** Return the configured root store that owns a managed Three object. */
@@ -1209,7 +1857,6 @@ export function applyProps<T extends object>(
1209
1857
  export function createThreeDriver(
1210
1858
  renderer = THREE_RENDERER_ID,
1211
1859
  ): UniversalHostDriver<ThreeHostContainer, object> {
1212
- registerThreeNamespace();
1213
1860
  return {
1214
1861
  id: renderer,
1215
1862
  capabilities: {
@@ -1395,6 +2042,12 @@ export function createThreeDriver(
1395
2042
  if (directLeafMount !== null) return directLeafMount;
1396
2043
  const updateOnly = prepareUpdateOnlyBatch(container, batch);
1397
2044
  if (updateOnly !== null) return updateOnly;
2045
+ const flatRecreation = prepareFlatRootRecreationBatch(container, batch);
2046
+ if (flatRecreation !== null) return flatRecreation;
2047
+ const flatReorder = prepareFlatRootReorderBatch(container, batch);
2048
+ if (flatReorder !== null) return flatReorder;
2049
+ const flatRemoval = prepareFlatRootRemovalBatch(container, batch);
2050
+ if (flatRemoval !== null) return flatRemoval;
1398
2051
  const simulation = cloneSimulation(state);
1399
2052
  const rootChildren = [...state.rootChildren];
1400
2053
  const portalChildren = clonePortalChildren(state);
@@ -1847,6 +2500,43 @@ export function createThreeDriver(
1847
2500
  }
1848
2501
  tasks.push(() => container.environment.invalidate?.());
1849
2502
  runAll(tasks);
2503
+
2504
+ // Constructor-only Object3D leaves currently mount through the general
2505
+ // graph because their constructors and scene listeners remain public.
2506
+ // Once that entire mount has succeeded, retain its proven flat layout so
2507
+ // later args reconstruction can use the same private ordering cache as
2508
+ // direct meshes without changing any mount or callback semantics.
2509
+ const createdCount = stagedCreates.size;
2510
+ if (
2511
+ createdCount !== 0 &&
2512
+ createdCount === state.instances.size &&
2513
+ createdCount === state.rootChildren.length &&
2514
+ batch.commands.length === createdCount * 2 &&
2515
+ batch.commands[0]?.op === 'create' &&
2516
+ batch.commands[createdCount]?.op === 'insert'
2517
+ ) {
2518
+ let constructorLeaves = true;
2519
+ for (const { instance } of stagedCreates.values()) {
2520
+ const args = Object.getOwnPropertyDescriptor(instance.props, 'args');
2521
+ if (
2522
+ !isObject3D(instance.object) ||
2523
+ args === undefined ||
2524
+ !('value' in args) ||
2525
+ !Array.isArray(args.value)
2526
+ ) {
2527
+ constructorLeaves = false;
2528
+ break;
2529
+ }
2530
+ for (const prop in instance.props) {
2531
+ if (prop !== 'args') {
2532
+ constructorLeaves = false;
2533
+ break;
2534
+ }
2535
+ }
2536
+ if (!constructorLeaves) break;
2537
+ }
2538
+ if (constructorLeaves) state.directInstances = getFlatRootInstances(container);
2539
+ }
1850
2540
  },
1851
2541
  afterAccept() {
1852
2542
  if (status !== 'applied' || callbacksRan) return;