@umicat/three-sdk 1.8.0 → 1.10.0

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.
@@ -54,6 +54,7 @@ export interface LoadedScene3D {
54
54
  update(dt: number): void;
55
55
  dispose(): void;
56
56
  }
57
+ export declare function applyTransform(obj: THREE.Object3D, e: Entity3D): void;
57
58
  export declare const MATERIAL_LIBRARY: Record<string, {
58
59
  color: string;
59
60
  roughness: string;
@@ -20,7 +20,7 @@ function isRigged(root) {
20
20
  rigged = true; });
21
21
  return rigged;
22
22
  }
23
- function applyTransform(obj, e) {
23
+ export function applyTransform(obj, e) {
24
24
  const t = e.transform;
25
25
  obj.position.copy(toVec(t.position));
26
26
  const q = t.rotation ?? IDENTITY_QUAT;
@@ -1,6 +1,6 @@
1
1
  import * as THREE from 'three';
2
2
  import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
3
- import { loadScene3D, loadModelAsset, makePrimitive } from '../SceneLoader3D.js';
3
+ import { loadScene3D, loadModelAsset, makePrimitive, applyTransform } from '../SceneLoader3D.js';
4
4
  import { applySkin } from '../Skin.js';
5
5
  import { applyAttachments } from '../Attachments.js';
6
6
  import { singleModelManifest, defaultColliderForPrimitive, groundRestOffset } from '../scene3d.js';
@@ -265,6 +265,19 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
265
265
  selectionBox.visible = false;
266
266
  selectionBox.renderOrder = 998;
267
267
  selectionBox.material.depthTest = false;
268
+ // ADR-046 — multi-select (box-select + ⌘/Ctrl-click). `multiSelected` is
269
+ // now the ONE authoritative source of truth for "what's selected" — the
270
+ // single-select visuals above (`gizmo.attached`/`selectionBox`) are kept
271
+ // IN SYNC with it whenever it holds exactly one entity (every selection
272
+ // change routes through `applySelection` below, which is the only place
273
+ // that writes to any of these), rather than being a second independent
274
+ // notion of selection the way "gizmo attachment IS the selection state"
275
+ // used to read before this existed. `multiBoxes` is an EXTRA per-entity
276
+ // highlight box, used ONLY for the 2+ case — the existing singular
277
+ // `selectionBox` above still owns the 1-entity case unchanged, so a
278
+ // single click never grows a second, redundant box.
279
+ let multiSelected = new Set();
280
+ const multiBoxes = new Map();
268
281
  // The Move/Rotate/Scale transform gizmo — shows (and is only hit-testable)
269
282
  // on the current mode's handles once something is selected. `gizmo.root`
270
283
  // is added to the scene once, at scene-load time, right alongside the
@@ -393,6 +406,20 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
393
406
  scale: { x: o.scale.x, y: o.scale.y, z: o.scale.z },
394
407
  };
395
408
  };
409
+ // ADR-045 — test-only readback of an entity's WORLD position, distinct
410
+ // from `__umicatEntityTransform` above which returns LOCAL (parent-
411
+ // relative) position. Needed because `Object3D.attach()` (reparenting)
412
+ // deliberately CHANGES local position to preserve world position — a
413
+ // test asserting "position unchanged across a reparent" must check
414
+ // world, not local, or it fails on perfectly correct behavior.
415
+ globalThis.__umicatEntityWorldPosition =
416
+ (entityId) => {
417
+ const o = objectByEntity.get(entityId);
418
+ if (!o)
419
+ return null;
420
+ const p = o.getWorldPosition(new THREE.Vector3());
421
+ return { x: p.x, y: p.y, z: p.z };
422
+ };
396
423
  // ADR-044 — test-only readback of a Part's live material state: whether
397
424
  // its async-loaded textures actually landed (`hasMap`/`hasRoughnessMap`),
398
425
  // what repeat they resolved to (proves `materialRepeatFor`'s size-based
@@ -463,6 +490,31 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
463
490
  let lookDragging = false;
464
491
  let lastLookX = 0;
465
492
  let lastLookY = 0;
493
+ // ADR-045 — right-click-NO-drag opens the context menu; right-click-DRAG
494
+ // orbits the camera (the look-drag state just above). Same "orbit-vs-
495
+ // click" distinction `downX`/`downY`/`moved` already draws for the LEFT
496
+ // button, tracked separately because `onPointerDown`'s button===2 branch
497
+ // returns before ever touching those.
498
+ let rightDownX = 0;
499
+ let rightDownY = 0;
500
+ let rightMoved = false;
501
+ // ADR-046 — multi-select gesture state. A left-pointerdown becomes a
502
+ // MARQUEE CANDIDATE whenever (a) ⌘/Ctrl is held — ALWAYS, regardless of
503
+ // what's under the cursor, including the ground/baseplate (see
504
+ // onPointerDown's own comment on why that case specifically matters),
505
+ // or (b) no modifier AND the down point hit nothing at all. Committed
506
+ // to an actual marquee only once the pointer moves past the drag
507
+ // threshold (see `onPointerMove`) — released without moving, it's
508
+ // either a ⌘-click TOGGLE (if it hit something) or a plain miss-click
509
+ // deselect (if not), decided in `onPointerUp`. `pendingClickHit`
510
+ // remembers what the down point hit (if anything) for that decision.
511
+ let marqueeCandidate = false;
512
+ let marqueeActive = false;
513
+ let marqueeAdditive = false; // ⌘/Ctrl held during a marquee → ADD to the existing selection instead of replacing it
514
+ let marqueeStartX = 0;
515
+ let marqueeStartY = 0;
516
+ let modifierHeldAtDown = false;
517
+ let pendingClickHit = null;
466
518
  // Entity drag — Phase 1 of real editing (translate only, ground-plane
467
519
  // constrained). Grabbing on an entity moves it; grabbing empty space/sky
468
520
  // still orbits, same convention as Unity/Blender. Whether THIS gesture is
@@ -481,20 +533,163 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
481
533
  let dragPlane = null;
482
534
  let dragGrabOffset = null; // world-space, plane-point minus object position at grab time
483
535
  /**
484
- * Deselect whatever's selected in WORLD — marker/box hidden, gizmo
485
- * detached, and (new, 2026-10-07) the host told, since a miss-click used
486
- * to deselect visually but post nothing: the host's own `lastPick` kept
487
- * the stale prior selection forever, harmless only while the Inspector's
488
- * visibility was gated on a now-removed "world mode" flag rather than on
489
- * `lastPick` itself. Also called from the HUD click listener below (cross-
490
- * layer deselect — see this file's header comment on why only one of
491
- * World/HUD should ever look selected at once).
536
+ * ADR-046 — the ONE place that changes the world selection. Takes the
537
+ * COMPLETE new selection (not a delta) and does three things: (1) syncs
538
+ * every visual (gizmo/selectionBox for the 1-entity case, `multiBoxes`
539
+ * for 2+, all hidden for 0), (2) tells the host via the new
540
+ * `selectionChanged3d` message (every count, including 0 and 1 — the
541
+ * authoritative "what's selected" signal multi-select-aware features
542
+ * read), and (3) ALSO fires the EXISTING `pickPoint3d` message every
543
+ * time, with `entityId` set only for the exactly-one case and `null`
544
+ * otherwise (0 OR 2+) — "not a single clean pick." This is what keeps
545
+ * the single-entity Scene3DInspector correctly hidden for a 2+
546
+ * selection with ZERO new host-side logic: without firing `null` for
547
+ * the 2+ case too, the host's `lastPick` would stay stale at whatever
548
+ * WAS the lone selection right before a marquee/⌘-click grew it past
549
+ * one, and the Inspector would keep showing that old entity.
550
+ */
551
+ function applySelection(objs, clickPoint) {
552
+ const next = new Set(objs);
553
+ const uniqueObjs = [...next];
554
+ // Drop any extra box no longer in the selection, OR every extra box at
555
+ // all once the count drops to ≤1 (the singular `selectionBox` owns
556
+ // that case; a leftover `multiBoxes` entry would double-highlight).
557
+ for (const [obj, box] of Array.from(multiBoxes)) {
558
+ if (!next.has(obj) || next.size < 2) {
559
+ scene?.remove(box);
560
+ box.geometry.dispose();
561
+ box.material.dispose();
562
+ multiBoxes.delete(obj);
563
+ }
564
+ }
565
+ multiSelected = next;
566
+ if (next.size === 0) {
567
+ marker.visible = false;
568
+ selectionBox.visible = false;
569
+ gizmo.detach();
570
+ }
571
+ else if (next.size === 1) {
572
+ const obj = uniqueObjs[0];
573
+ gizmo.attach(obj, camera);
574
+ selectionBox.setFromObject(obj);
575
+ selectionBox.visible = true;
576
+ // A click carries a real surface point; a programmatic 1-entity
577
+ // selection (⌘-click toggling down to one, a marquee netting
578
+ // exactly one) doesn't — the marker just hides rather than showing
579
+ // a stale or fabricated point.
580
+ if (clickPoint) {
581
+ marker.position.copy(clickPoint);
582
+ marker.visible = true;
583
+ }
584
+ else
585
+ marker.visible = false;
586
+ }
587
+ else {
588
+ gizmo.detach();
589
+ selectionBox.visible = false;
590
+ marker.visible = false;
591
+ for (const obj of uniqueObjs) {
592
+ let box = multiBoxes.get(obj);
593
+ if (!box) {
594
+ box = new THREE.BoxHelper(obj, 0xffd23f);
595
+ box.renderOrder = 998;
596
+ box.material.depthTest = false;
597
+ scene?.add(box);
598
+ multiBoxes.set(obj, box);
599
+ }
600
+ box.setFromObject(obj);
601
+ }
602
+ }
603
+ const entityIds = uniqueObjs.map((o) => entityByObject.get(o)).filter((id) => !!id);
604
+ window.parent.postMessage({ type: 'umicat:editor:selectionChanged3d', entityIds }, '*');
605
+ // ALWAYS fires, not just for 0/1 — a 2+ selection has to post
606
+ // `entityId: null` too, or the host's single-entity `lastPick` would
607
+ // stay stale at whatever WAS the lone selection right before a
608
+ // marquee/⌘-click grew it past one (the Inspector would keep showing
609
+ // the old single entity instead of correctly hiding for a
610
+ // multi-selection).
611
+ {
612
+ const id = next.size === 1 ? (entityByObject.get(uniqueObjs[0]) ?? null) : null;
613
+ let p = clickPoint;
614
+ if (!p && next.size === 1)
615
+ p = uniqueObjs[0].getWorldPosition(new THREE.Vector3());
616
+ window.parent.postMessage({ type: 'umicat:editor:pickPoint3d', x: p?.x ?? 0, y: p?.y ?? 0, z: p?.z ?? 0, entityId: id }, '*');
617
+ }
618
+ }
619
+ /**
620
+ * Deselect whatever's selected in WORLD. Also called from the HUD click
621
+ * listener below (cross-layer deselect — see this file's header comment
622
+ * on why only one of World/HUD should ever look selected at once).
492
623
  */
493
624
  function clearWorldSelection() {
494
- marker.visible = false;
495
- selectionBox.visible = false;
496
- gizmo.detach();
497
- window.parent.postMessage({ type: 'umicat:editor:pickPoint3d', x: 0, y: 0, z: 0, entityId: null }, '*');
625
+ applySelection([]);
626
+ }
627
+ // ADR-046 — box-select. A plain `<div>` overlay (NOT a 3D object — this
628
+ // is pure screen-space UI, same reasoning a 2D editor's marquee would
629
+ // use), created lazily on first use and reused for the life of this
630
+ // player. `position: fixed` in viewport pixels matches `e.clientX/Y`
631
+ // directly — no coordinate conversion needed, since this editor's canvas
632
+ // already fills the viewport.
633
+ let marqueeEl = null;
634
+ function ensureMarqueeEl() {
635
+ if (marqueeEl)
636
+ return marqueeEl;
637
+ const el = document.createElement('div');
638
+ el.style.position = 'fixed';
639
+ el.style.border = '1px solid #4da3ff';
640
+ el.style.background = 'rgba(77,163,255,0.15)';
641
+ el.style.pointerEvents = 'none';
642
+ el.style.zIndex = '9999';
643
+ el.style.display = 'none';
644
+ document.body.appendChild(el);
645
+ marqueeEl = el;
646
+ return el;
647
+ }
648
+ function updateMarqueeRect(x1, y1, x2, y2) {
649
+ const el = ensureMarqueeEl();
650
+ el.style.display = 'block';
651
+ el.style.left = `${Math.min(x1, x2)}px`;
652
+ el.style.top = `${Math.min(y1, y2)}px`;
653
+ el.style.width = `${Math.abs(x2 - x1)}px`;
654
+ el.style.height = `${Math.abs(y2 - y1)}px`;
655
+ }
656
+ function hideMarqueeRect() {
657
+ if (marqueeEl)
658
+ marqueeEl.style.display = 'none';
659
+ }
660
+ /**
661
+ * ADR-046 — which entities a marquee rect nets. Tests each entity's
662
+ * WORLD-POSITION (its origin/pivot), projected to screen, for plain
663
+ * CONTAINMENT in the rect — not a full bounding-box/overlap test. This
664
+ * is a deliberate v1 simplification: a Part's pivot sitting inside the
665
+ * dragged rectangle is an unambiguous, easy-to-predict rule ("drag
666
+ * around the things you want"), whereas a full AABB-overlap test would
667
+ * also select anything merely GRAZED by the rect's edge — arguably more
668
+ * "correct" for a large or partially-covered mesh, but a materially
669
+ * bigger and more failure-prone computation (8-corner projection,
670
+ * near-plane clipping per corner) for a benefit that doesn't matter for
671
+ * the small, discrete Parts this feature is built around. Worth
672
+ * revisiting if real use shows pivot-containment missing things people
673
+ * expected to net.
674
+ */
675
+ function selectEntitiesInScreenRect(x1, y1, x2, y2) {
676
+ const left = Math.min(x1, x2);
677
+ const right = Math.max(x1, x2);
678
+ const top = Math.min(y1, y2);
679
+ const bottom = Math.max(y1, y2);
680
+ const worldPos = new THREE.Vector3();
681
+ const camSpace = new THREE.Vector3();
682
+ const hits = [];
683
+ for (const obj of objectByEntity.values()) {
684
+ obj.getWorldPosition(worldPos);
685
+ camSpace.copy(worldPos).applyMatrix4(camera.matrixWorldInverse);
686
+ if (camSpace.z > -camera.near)
687
+ continue; // behind the camera (or inside the near clip) — not actually visible, don't net it
688
+ const screen = worldToClientXY(worldPos);
689
+ if (screen.x >= left && screen.x <= right && screen.y >= top && screen.y <= bottom)
690
+ hits.push(obj);
691
+ }
692
+ return hits;
498
693
  }
499
694
  let gizmoDrag = null;
500
695
  const beginGizmoDrag = (hit, e) => {
@@ -597,6 +792,9 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
597
792
  lookDragging = true;
598
793
  lastLookX = e.clientX;
599
794
  lastLookY = e.clientY;
795
+ rightDownX = e.clientX;
796
+ rightDownY = e.clientY;
797
+ rightMoved = false;
600
798
  try {
601
799
  renderer.domElement.setPointerCapture(e.pointerId);
602
800
  }
@@ -618,7 +816,13 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
618
816
  moved = false;
619
817
  if (!scene)
620
818
  return;
621
- if (gizmo.attached) {
819
+ // ADR-046 — ⌘/Ctrl held: never starts ANY drag (gizmo, single-entity,
820
+ // OR gizmo-hit-test) — the modifier means "I'm multi-selecting," and
821
+ // deciding what that click actually DOES (toggle one entity, or start
822
+ // a marquee-ADD) has to wait for release, so a ⌘-drag that moved the
823
+ // pointer doesn't get misread as a toggle (see onPointerUp).
824
+ modifierHeldAtDown = e.metaKey || e.ctrlKey;
825
+ if (!modifierHeldAtDown && gizmo.attached) {
622
826
  raycaster.setFromCamera(ndcFromEvent(e), camera);
623
827
  const gizmoHit = gizmo.hitTest(raycaster);
624
828
  if (gizmoHit && beginGizmoDrag(gizmoHit, e)) {
@@ -642,12 +846,46 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
642
846
  }
643
847
  }
644
848
  const hit = pickEntityAt(e);
645
- // Empty space: a left-drag here is a no-op now (Roblox scheme — rotate
646
- // lives on the right button; OrbitControls' LEFT binding is null, so
647
- // there's nothing left to fall through to). Reserved for a future
648
- // marquee-select, not built yet.
649
- if (!hit)
849
+ if (modifierHeldAtDown) {
850
+ // ⌘/Ctrl held — ALWAYS a selection gesture: toggle-on-click (decided
851
+ // on release, below, if the pointer never moved) or marquee-ADD on
852
+ // drag, regardless of what's under the cursor. Deliberately NOT
853
+ // gated on `!hit` the way the non-modifier marquee below is — a
854
+ // baseplate-style scene's ground is itself a real, registered
855
+ // `Entity3D` (see `template-3d-baseplate` — the SAME plane primitive
856
+ // this fixture's own "ground" entity uses) that can cover the ENTIRE
857
+ // viewport, leaving no truly empty pixel to start a plain marquee
858
+ // from. The modifier is what makes box-select reachable on such a
859
+ // scene at all — the alternative (treating it as a no-op) would
860
+ // make Phase 3a's whole feature unreachable there.
861
+ pendingClickHit = hit;
862
+ marqueeCandidate = true;
863
+ marqueeAdditive = true;
864
+ marqueeStartX = e.clientX;
865
+ marqueeStartY = e.clientY;
866
+ try {
867
+ renderer.domElement.setPointerCapture(e.pointerId);
868
+ }
869
+ catch { /* enhancement only */ }
870
+ return;
871
+ }
872
+ if (!hit) {
873
+ // Empty space, no modifier — might become a marquee that REPLACES
874
+ // the selection; committed only once the pointer actually moves
875
+ // (see onPointerMove). A plain miss-click (no movement) still just
876
+ // deselects, same as before marquee-select existed.
877
+ marqueeCandidate = true;
878
+ marqueeAdditive = false;
879
+ marqueeStartX = e.clientX;
880
+ marqueeStartY = e.clientY;
881
+ try {
882
+ renderer.domElement.setPointerCapture(e.pointerId);
883
+ }
884
+ catch { /* enhancement only */ }
650
885
  return;
886
+ }
887
+ marqueeCandidate = false;
888
+ pendingClickHit = null;
651
889
  const objectPos = hit.entityRoot.getWorldPosition(new THREE.Vector3());
652
890
  const plane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -objectPos.y);
653
891
  const planePoint = new THREE.Vector3();
@@ -675,6 +913,8 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
675
913
  };
676
914
  const onPointerMove = (e) => {
677
915
  if (lookDragging) {
916
+ if (Math.abs(e.clientX - rightDownX) > 4 || Math.abs(e.clientY - rightDownY) > 4)
917
+ rightMoved = true;
678
918
  applyLookDelta(e.clientX - lastLookX, e.clientY - lastLookY);
679
919
  lastLookX = e.clientX;
680
920
  lastLookY = e.clientY;
@@ -689,6 +929,16 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
689
929
  return;
690
930
  if (Math.abs(e.clientX - downX) > 4 || Math.abs(e.clientY - downY) > 4)
691
931
  moved = true;
932
+ if (marqueeCandidate) {
933
+ // Not yet committed to a marquee until the pointer actually moves —
934
+ // a plain miss-click (released with `moved` still false) stays a
935
+ // deselect, decided in onPointerUp.
936
+ if (!moved)
937
+ return;
938
+ marqueeActive = true;
939
+ updateMarqueeRect(marqueeStartX, marqueeStartY, e.clientX, e.clientY);
940
+ return;
941
+ }
692
942
  if (gizmoDrag) {
693
943
  raycaster.setFromCamera(ndcFromEvent(e), camera);
694
944
  updateGizmoDrag(e);
@@ -715,6 +965,36 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
715
965
  catch {
716
966
  // Already released, or never captured.
717
967
  }
968
+ // ADR-045 — a right-click that didn't rotate the camera opens the
969
+ // context menu. Same hit-test + selection side effects a left click
970
+ // already runs (marker/selectionBox/gizmo + `pickPoint3d`) — Roblox
971
+ // itself selects-on-right-click too, so right-clicking an unselected
972
+ // Part both selects it AND opens its menu in one action, rather than
973
+ // requiring a left-click first. Empty space still deselects, but
974
+ // still posts the menu message (with `entityId: null`) — the host
975
+ // decides whether an empty-space menu is worth showing (e.g. Paste).
976
+ if (!scene || rightMoved)
977
+ return;
978
+ const hit = pickEntityAt(e);
979
+ if (!hit) {
980
+ clearWorldSelection();
981
+ if (hudSelectedId)
982
+ selectHudEntity(null);
983
+ window.parent.postMessage({ type: 'umicat:editor:contextMenu3d', entityId: null, clientX: e.clientX, clientY: e.clientY }, '*');
984
+ return;
985
+ }
986
+ if (hudSelectedId)
987
+ selectHudEntity(null);
988
+ // ADR-046 — right-clicking an entity that's ALREADY part of a
989
+ // multi-selection keeps the WHOLE selection, so the menu acts on all
990
+ // of them (explorer-style: right-clicking one of several selected
991
+ // items doesn't collapse the selection to one). Right-clicking
992
+ // anything else collapses to just that one, same as a plain
993
+ // left-click already does.
994
+ if (!(multiSelected.size >= 2 && multiSelected.has(hit.entityRoot))) {
995
+ applySelection([hit.entityRoot], hit.point);
996
+ }
997
+ window.parent.postMessage({ type: 'umicat:editor:contextMenu3d', entityId: hit.entityId, clientX: e.clientX, clientY: e.clientY }, '*');
718
998
  return;
719
999
  }
720
1000
  if (e.button !== 0)
@@ -761,10 +1041,60 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
761
1041
  dragPlane = null;
762
1042
  dragGrabOffset = null;
763
1043
  controls.enabled = true;
1044
+ // ADR-046 — marquee/toggle finalize. Reachable whenever the
1045
+ // pointerdown either hit empty space (no modifier) OR had the
1046
+ // modifier held at all (see onPointerDown — both set
1047
+ // `marqueeCandidate`). Three outcomes, by what actually happened:
1048
+ // (1) it became an active drag → marquee select/add; (2) modifier
1049
+ // held, no drag → toggle whatever was under the cursor at down (can
1050
+ // be nothing, if that was empty space too); (3) no modifier, no drag
1051
+ // → plain miss-click deselect, exactly as before marquee existed.
1052
+ if (marqueeCandidate) {
1053
+ marqueeCandidate = false;
1054
+ if (marqueeActive) {
1055
+ marqueeActive = false;
1056
+ hideMarqueeRect();
1057
+ const hits = selectEntitiesInScreenRect(marqueeStartX, marqueeStartY, e.clientX, e.clientY);
1058
+ if (marqueeAdditive) {
1059
+ const next = new Set(multiSelected);
1060
+ for (const h of hits)
1061
+ next.add(h);
1062
+ applySelection([...next]);
1063
+ }
1064
+ else {
1065
+ applySelection(hits);
1066
+ }
1067
+ if (hudSelectedId)
1068
+ selectHudEntity(null);
1069
+ }
1070
+ else if (modifierHeldAtDown && pendingClickHit) {
1071
+ const obj = pendingClickHit.entityRoot;
1072
+ const next = new Set(multiSelected);
1073
+ if (next.has(obj))
1074
+ next.delete(obj);
1075
+ else
1076
+ next.add(obj);
1077
+ applySelection([...next], pendingClickHit.point);
1078
+ if (hudSelectedId)
1079
+ selectHudEntity(null);
1080
+ }
1081
+ else if (!modifierHeldAtDown && scene) {
1082
+ clearWorldSelection();
1083
+ if (hudSelectedId)
1084
+ selectHudEntity(null);
1085
+ }
1086
+ // The remaining case — modifier held, no drag, no hit (⌘-click on
1087
+ // truly empty space) — is intentionally a no-op: nothing to toggle,
1088
+ // and the modifier means "don't blow away my selection" anyway.
1089
+ modifierHeldAtDown = false;
1090
+ pendingClickHit = null;
1091
+ return;
1092
+ }
764
1093
  if (moved || !scene)
765
1094
  return;
766
- // A plain click (no drag) — the existing read-a-coordinate behavior,
767
- // plus attaching/detaching the transform gizmo to match selection.
1095
+ // A plain click (no drag, no modifier) — collapses the selection to
1096
+ // just the clicked entity (or clears it), same as every pre-multi-
1097
+ // select click already did.
768
1098
  const hit = pickEntityAt(e);
769
1099
  if (!hit) {
770
1100
  // Clicked empty space with nothing grabbed — deselect. Previously a
@@ -777,16 +1107,7 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
777
1107
  }
778
1108
  if (hudSelectedId)
779
1109
  selectHudEntity(null); // cross-layer deselect
780
- marker.position.copy(hit.point);
781
- marker.visible = true;
782
- // Frame the whole entity the click landed on, not just the point on its
783
- // surface — `setFromObject` walks the root's full subtree, so a
784
- // multi-mesh entity (a model with separate parts) gets one box around
785
- // all of it, matching what "entityId" actually refers to.
786
- selectionBox.setFromObject(hit.entityRoot);
787
- selectionBox.visible = true;
788
- gizmo.attach(hit.entityRoot, camera);
789
- window.parent.postMessage({ type: 'umicat:editor:pickPoint3d', x: hit.point.x, y: hit.point.y, z: hit.point.z, entityId: hit.entityId }, '*');
1110
+ applySelection([hit.entityRoot], hit.point);
790
1111
  };
791
1112
  renderer.domElement.addEventListener('pointerdown', onPointerDown);
792
1113
  renderer.domElement.addEventListener('pointermove', onPointerMove);
@@ -832,6 +1153,8 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
832
1153
  return onDropModel3d(data);
833
1154
  if (data.type === 'umicat:editor:dropPrimitive3d')
834
1155
  return onDropPrimitive3d(data);
1156
+ if (data.type === 'umicat:editor:createEntity3d')
1157
+ return onCreateEntity3d(data);
835
1158
  if (data.type === 'umicat:editor:deleteEntity3d')
836
1159
  return onDeleteEntity3d(data);
837
1160
  if (data.type === 'umicat:editor:setGizmoMode3d') {
@@ -935,6 +1258,26 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
935
1258
  // explicit refresh here, same as a live drag already does.
936
1259
  selectionBox.setFromObject(object);
937
1260
  }
1261
+ if (m.patch?.parent !== undefined) {
1262
+ // ADR-045 Phase 2 — reparent. `Object3D.attach` (standard three.js
1263
+ // API) moves `object` under the new parent AND recomputes its local
1264
+ // transform so its WORLD position/rotation/scale is unchanged —
1265
+ // grouping an entity must not visually move it. `null` means attach
1266
+ // to the scene root.
1267
+ const newParentObject = m.patch.parent === null ? scene : objectByEntity.get(m.patch.parent);
1268
+ if (!newParentObject)
1269
+ return done(`no parent entity '${m.patch.parent}' in the scene being shown`);
1270
+ newParentObject.attach(object);
1271
+ const authored = sceneData?.entities.find((en) => en.id === m.entityId);
1272
+ if (authored) {
1273
+ if (m.patch.parent === null)
1274
+ delete authored.parent;
1275
+ else
1276
+ authored.parent = m.patch.parent;
1277
+ }
1278
+ if (gizmo.attached === object)
1279
+ selectionBox.setFromObject(object);
1280
+ }
938
1281
  if (m.patch?.attachments !== undefined) {
939
1282
  const authored = sceneData?.entities.find((e) => e.id === m.entityId);
940
1283
  const asset = manifest?.models?.find((x) => x.id === authored?.modelAssetId);
@@ -1015,14 +1358,26 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
1015
1358
  entityByObject.delete(object);
1016
1359
  entityByObject.set(fresh, m.entityId);
1017
1360
  objectByEntity.set(m.entityId, fresh);
1018
- // Same "gizmo attachment IS the selection state" convention the
1019
- // position/rotation/scale branch above already relies on — there is
1020
- // no separate "currently selected" variable to update.
1361
+ // Same object-instance swap the position/rotation/scale branch
1362
+ // above already handles for the single-select visuals — `object`
1363
+ // itself is being replaced, so anything keyed by the OLD instance
1364
+ // (gizmo attachment, AND now `multiSelected`/`multiBoxes` — ADR-046)
1365
+ // has to move to `fresh` or it silently points at a disposed object.
1021
1366
  if (gizmo.attached === object) {
1022
1367
  gizmo.detach();
1023
1368
  gizmo.attach(fresh, camera);
1024
1369
  selectionBox.setFromObject(fresh);
1025
1370
  }
1371
+ if (multiSelected.has(object)) {
1372
+ multiSelected.delete(object);
1373
+ multiSelected.add(fresh);
1374
+ const box = multiBoxes.get(object);
1375
+ if (box) {
1376
+ multiBoxes.delete(object);
1377
+ multiBoxes.set(fresh, box);
1378
+ box.setFromObject(fresh);
1379
+ }
1380
+ }
1026
1381
  object = fresh;
1027
1382
  }
1028
1383
  done();
@@ -1128,6 +1483,101 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
1128
1483
  sceneData?.entities.push(entity);
1129
1484
  done(undefined, { x: object.position.x, y: object.position.y, z: object.position.z }, collider);
1130
1485
  }
1486
+ /**
1487
+ * ADR-045 — spawn a COMPLETE, host-supplied entity at its OWN authored
1488
+ * transform. The generic counterpart to `dropModel3d`/`dropPrimitive3d`
1489
+ * (both raycast-based: host sends a screen pixel, SDK finds where it
1490
+ * lands on the ground) — Paste/Duplicate need the opposite: place at an
1491
+ * EXPLICIT position (the original's, or a small offset from it), never
1492
+ * a raycast. Registers into the same `entityByObject`/`objectByEntity`/
1493
+ * `scene`/`sceneData` as every other creation path, so the result is
1494
+ * immediately pickable/draggable with zero changes to `pickEntityAt` or
1495
+ * the gizmo.
1496
+ *
1497
+ * Reuses `applyTransform` (position AND rotation AND scale — unlike a
1498
+ * fresh drop, a copy must preserve the ORIGINAL's full transform, not
1499
+ * just land at a ground point with identity rotation/scale) and, for a
1500
+ * model entity carrying a `skin`/`attachments`, best-effort re-applies
1501
+ * them too (logged, not fatal — a cosmetic miss on a re-skin must not
1502
+ * block the entity from existing at all, unlike a direct user-initiated
1503
+ * patch where failing loudly is correct).
1504
+ */
1505
+ async function onCreateEntity3d(m) {
1506
+ const e = m.entity;
1507
+ const done = (error) => {
1508
+ if (error)
1509
+ console.warn('[umicat/editor] 3D entity create failed:', e.id, error);
1510
+ window.parent.postMessage({ type: 'umicat:editor:entityCreated3d', entityId: e.id, ok: !error, error }, '*');
1511
+ };
1512
+ if (!scene)
1513
+ return done('no scene loaded yet');
1514
+ if (objectByEntity.has(e.id))
1515
+ return done(`entity '${e.id}' already exists in this scene`);
1516
+ let object;
1517
+ if (e.modelAssetId) {
1518
+ const asset = manifest?.models?.find((x) => x.id === e.modelAssetId);
1519
+ if (!asset)
1520
+ return done(`entity references model '${e.modelAssetId}', which the manifest does not define`);
1521
+ try {
1522
+ const loaded = await loadModelAsset(singleModelManifest(asset), e.modelAssetId, { assetBase: '' });
1523
+ object = loaded.object;
1524
+ }
1525
+ catch (err) {
1526
+ return done(err instanceof Error ? err.message : String(err));
1527
+ }
1528
+ object.traverse((n) => { n.castShadow = e.castShadow !== false; n.receiveShadow = true; });
1529
+ if (e.skin) {
1530
+ const path = asset.skins?.[e.skin];
1531
+ if (path) {
1532
+ try {
1533
+ await applySkin(object, path, { assetBase: '' });
1534
+ }
1535
+ catch (err) {
1536
+ console.warn('[umicat/editor] re-skin on create failed (kept base texture):', e.id, err);
1537
+ }
1538
+ }
1539
+ }
1540
+ if (e.attachments?.length) {
1541
+ try {
1542
+ const worn_ = await applyAttachments(object, asset, manifest, e.attachments, { assetBase: '', label: e.id });
1543
+ worn.set(e.id, worn_);
1544
+ }
1545
+ catch (err) {
1546
+ console.warn('[umicat/editor] re-attaching props on create failed (created bare):', e.id, err);
1547
+ }
1548
+ }
1549
+ }
1550
+ else if (e.primitive) {
1551
+ object = makePrimitive(e);
1552
+ object.castShadow = e.primitive.kind !== 'plane';
1553
+ object.receiveShadow = true;
1554
+ }
1555
+ else {
1556
+ // Neither model nor primitive — an empty transform/pivot node.
1557
+ // ADR-045 Phase 2's "Group as Model" container is exactly this.
1558
+ object = new THREE.Group();
1559
+ }
1560
+ applyTransform(object, e);
1561
+ // Honor an authored `parent` the same way `loadScene3D`'s own spawn loop
1562
+ // does — a pasted copy of a grouped entity carries its `parent` field
1563
+ // along (Copy reads the full entity JSON verbatim), and the authored
1564
+ // `transform` on such an entity is PARENT-LOCAL, not world. Defaulting
1565
+ // to `scene.add` here would silently place it at scene root with its
1566
+ // local offset misread as a world position — right on screen until the
1567
+ // next load, which WOULD honor `parent` and jump it.
1568
+ let parentObject = scene;
1569
+ if (e.parent) {
1570
+ const resolved = objectByEntity.get(e.parent);
1571
+ if (!resolved)
1572
+ return done(`entity references parent '${e.parent}', which does not exist in this scene`);
1573
+ parentObject = resolved;
1574
+ }
1575
+ parentObject.add(object);
1576
+ entityByObject.set(object, e.id);
1577
+ objectByEntity.set(e.id, object);
1578
+ sceneData?.entities.push(e);
1579
+ done();
1580
+ }
1131
1581
  /**
1132
1582
  * Frees a subtree's GPU resources the same way the whole-scene `dispose()`
1133
1583
  * in `SceneLoader3D.ts` does (geometry + material + every texture field a
@@ -1187,10 +1637,13 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
1187
1637
  }
1188
1638
  if (gizmoDrag && gizmo.attached === object)
1189
1639
  gizmoDrag = null;
1190
- if (gizmo.attached === object) {
1191
- gizmo.detach();
1192
- marker.visible = false;
1193
- selectionBox.visible = false;
1640
+ // ADR-046 — if the deleted entity was selected (single OR part of a
1641
+ // multi-selection), route the shrunk selection back through
1642
+ // `applySelection` rather than hand-rolling the gizmo/box cleanup here
1643
+ // — that's the one place all of it (including re-attaching the gizmo
1644
+ // if this drops a 2-selection down to 1) already lives.
1645
+ if (gizmo.attached === object || multiSelected.has(object)) {
1646
+ applySelection([...multiSelected].filter((o) => o !== object));
1194
1647
  }
1195
1648
  scene?.remove(object);
1196
1649
  disposeObjectTree(object);
@@ -1233,17 +1686,43 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
1233
1686
  const target = e.target;
1234
1687
  if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable))
1235
1688
  return;
1236
- if (e.key === 'Delete' && gizmo.attached) {
1237
- const entityId = entityByObject.get(gizmo.attached);
1238
- if (entityId) {
1239
- e.preventDefault();
1689
+ // ADR-046 — these all now read `multiSelected` (the authoritative
1690
+ // selection set), not `gizmo.attached` — the gizmo is DETACHED
1691
+ // whenever 2+ entities are selected (no shared-pivot gizmo yet, Phase
1692
+ // 3b), so reading `gizmo.attached` alone would silently do nothing
1693
+ // for a multi-selection. `gizmo.attached` is always a MEMBER of
1694
+ // `multiSelected` when exactly one entity is selected (the invariant
1695
+ // `applySelection` maintains), so this is a pure generalization, not a
1696
+ // behavior change for the single-select case.
1697
+ const selectedIds = () => [...multiSelected].map((o) => entityByObject.get(o)).filter((id) => !!id);
1698
+ if (e.key === 'Delete' && multiSelected.size > 0) {
1699
+ e.preventDefault();
1700
+ for (const entityId of selectedIds())
1240
1701
  void onDeleteEntity3d({ entityId });
1241
- }
1242
1702
  }
1243
1703
  else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'z') {
1244
1704
  e.preventDefault();
1245
1705
  window.parent.postMessage({ type: 'umicat:editor:requestUndo3d' }, '*');
1246
1706
  }
1707
+ else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'c' && multiSelected.size > 0) {
1708
+ // ADR-045 — same "ask, don't act" shape as Undo above: the CLIPBOARD
1709
+ // lives on the host (Copy is a pure read of the host's own scene
1710
+ // copy), so this player can't act on it locally the way Delete does.
1711
+ e.preventDefault();
1712
+ window.parent.postMessage({ type: 'umicat:editor:requestCopy3d', entityIds: selectedIds() }, '*');
1713
+ }
1714
+ else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'x' && multiSelected.size > 0) {
1715
+ e.preventDefault();
1716
+ window.parent.postMessage({ type: 'umicat:editor:requestCut3d', entityIds: selectedIds() }, '*');
1717
+ }
1718
+ else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'v') {
1719
+ e.preventDefault();
1720
+ window.parent.postMessage({ type: 'umicat:editor:requestPaste3d' }, '*');
1721
+ }
1722
+ else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'd' && multiSelected.size > 0) {
1723
+ e.preventDefault();
1724
+ window.parent.postMessage({ type: 'umicat:editor:requestDuplicate3d', entityIds: selectedIds() }, '*');
1725
+ }
1247
1726
  });
1248
1727
  // WASD/QE fly-camera + Shift speed boost — held-STATE, not a discrete
1249
1728
  // action, so this is a separate keydown/keyup PAIR rather than folded
@@ -1376,6 +1855,13 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
1376
1855
  selectionBox.visible = false;
1377
1856
  scene.add(selectionBox);
1378
1857
  scene.add(gizmo.root);
1858
+ // ADR-046 — a (re)load tears down the whole scene graph; any
1859
+ // multi-select boxes from a PRIOR scene were added to that scene, not
1860
+ // this one, and the objects they tracked are gone. No disposal loop
1861
+ // needed here (nothing in the new scene references them) — just drop
1862
+ // the stale bookkeeping.
1863
+ multiSelected = new Set();
1864
+ multiBoxes.clear();
1379
1865
  // Frame the whole scene — auto-fit, since a small template scene and a
1380
1866
  // real level's dozens of entities need wildly different orbit distances.
1381
1867
  const box = new THREE.Box3().setFromObject(scene);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umicat/three-sdk",
3
- "version": "1.8.0",
3
+ "version": "1.10.0",
4
4
  "description": "Three.js runtime for Umicat games: the scene3d design format, its loader with physics, a kinematic character controller, and the Umicat platform via @umicat/platform-sdk.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",