@umicat/three-sdk 1.5.0 → 1.6.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.
package/README.md CHANGED
@@ -26,9 +26,14 @@ from its CDN url, no manifest entry required — and a full Roblox/Unity-style
26
26
  `umicat:editor:setGizmoMode3d`, posting `dragEnd3d`/`rotateEnd3d`/`scaleEnd3d`
27
27
  on release — plus **Delete** (`umicat:editor:deleteEntity3d`) and
28
28
  **transform-only undo** (Ctrl/Cmd+Z; the undo stack itself lives on the
29
- host, this player only replays a `patchEntity3d` restore)). What it still
30
- does not have: undo of entity creation/deletion, multi-select, or a local/
31
- global axis toggle (the gizmo is local-space only).
29
+ host, this player only replays a `patchEntity3d` restore)). The desktop
30
+ camera matches Roblox Studio: left-click/drag selects and manipulates
31
+ (entities, the gizmo), right-drag looks around, WASD flies, Q/E move
32
+ straight down/up, Shift speeds up — touch is untouched (still orbit/
33
+ pinch-zoom via `OrbitControls`, which mouse input no longer reaches at
34
+ all). What it still does not have: undo of entity creation/deletion,
35
+ multi-select, a local/global axis toggle (the gizmo is local-space only),
36
+ middle-mouse pan, F-to-focus, or Studio's comma/period ring-rotate.
32
37
 
33
38
  > This paragraph said "seed, not a product — no input system, no character
34
39
  > controller, no audio, and no published package" for ten minor versions after
@@ -154,6 +154,101 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
154
154
  const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.05, 2000);
155
155
  const controls = new OrbitControls(camera, renderer.domElement);
156
156
  controls.enableDamping = true;
157
+ // Desktop mouse input is owned entirely by the free-fly controller below
158
+ // (Roblox Studio's scheme: left-select/drag, right-drag-look, WASD/QE fly
159
+ // — see that block's own comment) instead of three.js's stock Unity/
160
+ // Blender-style left-drag-orbit. `controls.enabled` stays true FOREVER —
161
+ // never set false for a mouse reason — because `controls.touches` is
162
+ // deliberately left at its default (ONE: TOUCH.ROTATE, TWO:
163
+ // TOUCH.DOLLY_PAN): touch devices must keep orbiting/pinch-zooming exactly
164
+ // as before. Disabling only the three MOUSE bindings is what makes
165
+ // OrbitControls touch-only — confirmed against the pinned three@0.186.0
166
+ // source, `onMouseDown`'s button→action switch falls through to
167
+ // `default: this.state = STATE.NONE` once each mapping is null, so a
168
+ // mouse button-down is tracked (harmlessly) but never drives rotate/
169
+ // dolly/pan. Wheel is untouched on purpose — it still reaches
170
+ // OrbitControls' own (unmodified) wheel handler, which doesn't gate on
171
+ // `mouseButtons` at all; `syncOrbitTarget()` below is what makes that
172
+ // keep working as a plain forward/back dolly instead of zooming toward a
173
+ // stale point, with zero new wheel code needed.
174
+ controls.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
175
+ // ---- Desktop free-fly camera (Roblox Studio scheme) ---------------------
176
+ //
177
+ // Yaw/pitch state, NOT re-derived from camera.quaternion every frame —
178
+ // storing the two angles (rather than reading them back out of the
179
+ // quaternion each update) is what avoids roll creeping in: each frame
180
+ // rebuilds the quaternion fresh from (pitch, yaw, 0) in Euler order
181
+ // 'YXZ'. That order specifically — yaw applied around WORLD Y outermost,
182
+ // pitch around the camera's OWN, already-yawed local X innermost — is the
183
+ // standard three.js FPS-camera convention (same one PointerLockControls
184
+ // uses): pitching rotates around an axis pitch itself doesn't move, so
185
+ // the camera's local X ("right") stays exactly horizontal no matter how
186
+ // far you look up/down, and roll can never accumulate since nothing ever
187
+ // writes the Euler's Z component.
188
+ let yaw = 0;
189
+ let pitch = 0;
190
+ const PITCH_LIMIT = Math.PI / 2 - 0.001; // just inside straight up/down — avoids the lookAt singularity
191
+ const flyEuler = new THREE.Euler(0, 0, 0, 'YXZ');
192
+ // How far in front of the camera OrbitControls' own `target` is kept at
193
+ // all times — a CONSTANT, seeded once from the scene's auto-frame
194
+ // distance (see the scene-load block below). Not the live distance to
195
+ // anything in the scene; purely the radius of the invisible pivot sphere
196
+ // the free-fly camera drags around with it so OrbitControls' touch/wheel
197
+ // code (which still runs `controls.update()` every frame and derives its
198
+ // own state from `camera.position`/`target`) always sees a sane,
199
+ // camera-relative target instead of a stale or distant one.
200
+ //
201
+ // This isn't just a touch nicety — confirmed against the pinned
202
+ // OrbitControls source, `update()` unconditionally ends with
203
+ // `this.object.lookAt(this.target)` on EVERY call, mouse-disabled or not.
204
+ // Without this, the render loop's own `controls.update()` call would snap
205
+ // the camera back to face a stale `target` every single frame, fighting
206
+ // whatever `applyLookDelta`/WASD just did.
207
+ let orbitDistance = 5;
208
+ // Scaled once per scene load (see below) so a tiny room and a sprawling
209
+ // level don't share one fixed speed — same "proportional to scene
210
+ // radius" convention `camera.near`/`camera.far` already use a few lines
211
+ // below in the scene-load block.
212
+ let flySpeed = 5;
213
+ const SHIFT_MULTIPLIER = 3;
214
+ const LOOK_SENSITIVITY = 0.0025; // radians per pixel of mouse movement
215
+ /**
216
+ * Keeps OrbitControls' own invariant (camera always faces `target`, at a
217
+ * sane distance) intact even though desktop input never goes through any
218
+ * OrbitControls method. Called after every desktop-driven camera change
219
+ * (a look-drag delta, a WASD/QE frame-step) — a no-op when nothing
220
+ * changed (recomputing from an unchanged camera pose reproduces the same
221
+ * target), but it's what keeps a TOUCH gesture that starts the instant
222
+ * after a desktop gesture ends from seeing a target that's still wherever
223
+ * it was left relative to the OLD camera pose.
224
+ */
225
+ function syncOrbitTarget() {
226
+ const forward = new THREE.Vector3(0, 0, -1).applyQuaternion(camera.quaternion);
227
+ controls.target.copy(camera.position).addScaledVector(forward, orbitDistance);
228
+ }
229
+ /**
230
+ * Right-drag look: rotates the camera IN PLACE (yaw/pitch only, position
231
+ * untouched) — a FREE-LOOK, not an orbit, matching Roblox Studio's actual
232
+ * behavior ("dragging the mouse moves the camera view around") rather
233
+ * than three.js's default left-drag orbit-around-target. Seeded from the
234
+ * CURRENT `yaw`/`pitch` each call — those two module-scope variables are
235
+ * the single source of truth once seeded at scene load; re-deriving them
236
+ * from `camera.quaternion` via `Euler.setFromQuaternion` on every call
237
+ * would re-introduce the float drift/roll-creep this design avoids.
238
+ */
239
+ function applyLookDelta(deltaX, deltaY) {
240
+ yaw -= deltaX * LOOK_SENSITIVITY;
241
+ pitch = THREE.MathUtils.clamp(pitch - deltaY * LOOK_SENSITIVITY, -PITCH_LIMIT, PITCH_LIMIT);
242
+ flyEuler.set(pitch, yaw, 0);
243
+ camera.quaternion.setFromEuler(flyEuler);
244
+ syncOrbitTarget();
245
+ }
246
+ // WASD/QE — held-key state, consumed every animation-loop frame with a
247
+ // real delta-time (see the render loop below) rather than acted on at
248
+ // keydown, so holding a key flies continuously instead of nudging once
249
+ // per press.
250
+ const movementKeysDown = new Set();
251
+ let shiftHeld = false;
157
252
  // A single persistent marker, repositioned per click — the exact world
158
253
  // point clicked (what "put a torch at the spot I clicked" needs), distinct
159
254
  // from the box below (which entity was hit, not just where).
@@ -298,6 +393,15 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
298
393
  scale: { x: o.scale.x, y: o.scale.y, z: o.scale.z },
299
394
  };
300
395
  };
396
+ // Test-only — the MAIN camera's current pose, for the desktop camera
397
+ // controls test suite (left-select/right-look/WASD/QE) to assert against
398
+ // without hand-deriving projection math — same posture as every other
399
+ // debug readback in this file.
400
+ globalThis.__umicatCameraPose =
401
+ () => ({
402
+ position: { x: camera.position.x, y: camera.position.y, z: camera.position.z },
403
+ quaternion: [camera.quaternion.x, camera.quaternion.y, camera.quaternion.z, camera.quaternion.w],
404
+ });
301
405
  // Only VISIBLE entity roots are ever raycast against. three.js's
302
406
  // Mesh.raycast does NOT check `.visible` on its own (confirmed against the
303
407
  // pinned three source — no such check in Raycaster.js or Object3D.raycast),
@@ -324,6 +428,12 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
324
428
  let downX = 0;
325
429
  let downY = 0;
326
430
  let moved = false;
431
+ // Right-button look-drag state — a separate gesture channel entirely from
432
+ // the left-button select/drag state above; see `applyLookDelta` and the
433
+ // `e.button === 2` branch in the pointer handlers below.
434
+ let lookDragging = false;
435
+ let lastLookX = 0;
436
+ let lastLookY = 0;
327
437
  // Entity drag — Phase 1 of real editing (translate only, ground-plane
328
438
  // constrained). Grabbing on an entity moves it; grabbing empty space/sky
329
439
  // still orbits, same convention as Unity/Blender. Whether THIS gesture is
@@ -450,6 +560,30 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
450
560
  moved = true;
451
561
  };
452
562
  const onPointerDown = (e) => {
563
+ // Right button — camera look-drag, a separate gesture channel entirely
564
+ // from everything below. Hard-returns before touching any select/drag/
565
+ // gizmo state, so a right-click can never be misread as the start of a
566
+ // left gesture.
567
+ if (e.button === 2) {
568
+ lookDragging = true;
569
+ lastLookX = e.clientX;
570
+ lastLookY = e.clientY;
571
+ try {
572
+ renderer.domElement.setPointerCapture(e.pointerId);
573
+ }
574
+ catch {
575
+ // Same posture as every other setPointerCapture call in this file —
576
+ // capture is an enhancement (keeps the look-drag live off-canvas),
577
+ // not a requirement.
578
+ }
579
+ return;
580
+ }
581
+ // Middle button, or anything else: not ours. Left (button 0) covers
582
+ // both a real left-click AND touch's primary contact (also button 0) —
583
+ // this is how touch stays on the exact same path it's always used,
584
+ // unaffected by the Roblox-style desktop remap.
585
+ if (e.button !== 0)
586
+ return;
453
587
  downX = e.clientX;
454
588
  downY = e.clientY;
455
589
  moved = false;
@@ -459,6 +593,15 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
459
593
  raycaster.setFromCamera(ndcFromEvent(e), camera);
460
594
  const gizmoHit = gizmo.hitTest(raycaster);
461
595
  if (gizmoHit && beginGizmoDrag(gizmoHit, e)) {
596
+ // `controls.enabled` toggling is a TOUCH-only concern now — mouse
597
+ // can't reach OrbitControls regardless, since all three of its
598
+ // mouse bindings are null (see `controls.mouseButtons` above). But
599
+ // `onPointerDown`/`Move`/`Up` have no `pointerType` check and never
600
+ // have, so a touch tap/drag on a gizmo handle or entity body runs
601
+ // through this exact same code — and `controls.touches` is
602
+ // deliberately left reactive. Without this toggle, a touch-drag on
603
+ // an entity would simultaneously manipulate it AND orbit the
604
+ // camera via OrbitControls' own touch handling.
462
605
  controls.enabled = false;
463
606
  try {
464
607
  renderer.domElement.setPointerCapture(e.pointerId);
@@ -470,22 +613,25 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
470
613
  }
471
614
  }
472
615
  const hit = pickEntityAt(e);
616
+ // Empty space: a left-drag here is a no-op now (Roblox scheme — rotate
617
+ // lives on the right button; OrbitControls' LEFT binding is null, so
618
+ // there's nothing left to fall through to). Reserved for a future
619
+ // marquee-select, not built yet.
473
620
  if (!hit)
474
- return; // empty space — let OrbitControls own this gesture
621
+ return;
475
622
  const objectPos = hit.entityRoot.getWorldPosition(new THREE.Vector3());
476
623
  const plane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -objectPos.y);
477
624
  const planePoint = new THREE.Vector3();
478
625
  // Looking exactly parallel to the ground has no plane intersection —
479
626
  // vanishingly rare for this camera (auto-framed, always angled down at
480
- // the scene) but cheap to guard: fall through to orbit rather than
481
- // start a drag from a garbage grab offset.
627
+ // the scene) but cheap to guard against a garbage grab offset.
482
628
  if (!raycaster.ray.intersectPlane(plane, planePoint))
483
629
  return;
484
630
  dragEntity = hit.entityRoot;
485
631
  dragEntityId = hit.entityId;
486
632
  dragPlane = plane;
487
633
  dragGrabOffset = planePoint.sub(objectPos);
488
- controls.enabled = false;
634
+ controls.enabled = false; // touch-only concern now — see the gizmo-drag site's comment above
489
635
  try {
490
636
  renderer.domElement.setPointerCapture(e.pointerId);
491
637
  }
@@ -499,6 +645,19 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
499
645
  }
500
646
  };
501
647
  const onPointerMove = (e) => {
648
+ if (lookDragging) {
649
+ applyLookDelta(e.clientX - lastLookX, e.clientY - lastLookY);
650
+ lastLookX = e.clientX;
651
+ lastLookY = e.clientY;
652
+ return;
653
+ }
654
+ // Defensive: a right-drag that started off-canvas (so this handler
655
+ // never saw its pointerdown) shouldn't be misread as a left gesture.
656
+ // `buttons` (not `button`) is the live bitmask of currently-held
657
+ // buttons — needed because a pointermove with no button transition
658
+ // reports `button === -1`.
659
+ if (e.buttons === 2)
660
+ return;
502
661
  if (Math.abs(e.clientX - downX) > 4 || Math.abs(e.clientY - downY) > 4)
503
662
  moved = true;
504
663
  if (gizmoDrag) {
@@ -519,6 +678,18 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
519
678
  selectionBox.setFromObject(dragEntity);
520
679
  };
521
680
  const onPointerUp = (e) => {
681
+ if (lookDragging && e.button === 2) {
682
+ lookDragging = false;
683
+ try {
684
+ renderer.domElement.releasePointerCapture(e.pointerId);
685
+ }
686
+ catch {
687
+ // Already released, or never captured.
688
+ }
689
+ return;
690
+ }
691
+ if (e.button !== 0)
692
+ return;
522
693
  try {
523
694
  renderer.domElement.releasePointerCapture(e.pointerId);
524
695
  }
@@ -591,6 +762,13 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
591
762
  renderer.domElement.addEventListener('pointerdown', onPointerDown);
592
763
  renderer.domElement.addEventListener('pointermove', onPointerMove);
593
764
  renderer.domElement.addEventListener('pointerup', onPointerUp);
765
+ // Right-click is now a real camera gesture (look-drag) — the native
766
+ // context menu popping up mid-drag would be disruptive. Not strictly
767
+ // load-bearing today (OrbitControls' own `onContextMenu` already calls
768
+ // `preventDefault()` whenever `controls.enabled !== false`, and `enabled`
769
+ // stays permanently true now — see its own comment above), but this
770
+ // shouldn't be left as an implicit dependency on that internal detail.
771
+ renderer.domElement.addEventListener('contextmenu', (e) => e.preventDefault());
594
772
  /**
595
773
  * Host→iframe messages. `patchEntity3d` (0.18.0) was the first — everything
596
774
  * before it went one way: the player reported picks and drags, and the
@@ -933,10 +1111,72 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
933
1111
  window.parent.postMessage({ type: 'umicat:editor:requestUndo3d' }, '*');
934
1112
  }
935
1113
  });
1114
+ // WASD/QE fly-camera + Shift speed boost — held-STATE, not a discrete
1115
+ // action, so this is a separate keydown/keyup PAIR rather than folded
1116
+ // into the action listener above (which only ever needs keydown). Same
1117
+ // focused-input guard as that listener, for the same reason it states
1118
+ // there — "costs nothing," even though nothing focusable exists in this
1119
+ // iframe today.
1120
+ const MOVEMENT_KEYS = new Set(['w', 'a', 's', 'd', 'q', 'e']);
1121
+ window.addEventListener('keydown', (e) => {
1122
+ const target = e.target;
1123
+ if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable))
1124
+ return;
1125
+ if (e.key === 'Shift') {
1126
+ shiftHeld = true;
1127
+ return;
1128
+ }
1129
+ const key = e.key.toLowerCase();
1130
+ if (MOVEMENT_KEYS.has(key))
1131
+ movementKeysDown.add(key);
1132
+ });
1133
+ window.addEventListener('keyup', (e) => {
1134
+ if (e.key === 'Shift') {
1135
+ shiftHeld = false;
1136
+ return;
1137
+ }
1138
+ movementKeysDown.delete(e.key.toLowerCase());
1139
+ });
936
1140
  // Design mode skips physics and animation entirely (loadScene3D's own
937
1141
  // designMode flag) — there are no mixers to advance and no Rapier world to
938
- // step, so the loop only ever needs to render.
1142
+ // step, so the loop only ever needs to render (plus, now, the WASD/QE
1143
+ // fly-camera frame-step below).
1144
+ const flyClock = new THREE.Clock();
939
1145
  renderer.setAnimationLoop(() => {
1146
+ // Clamped so a backgrounded tab's first frame back (an arbitrarily
1147
+ // large real-world gap) doesn't teleport the camera.
1148
+ const dt = Math.min(flyClock.getDelta(), 0.1);
1149
+ if (movementKeysDown.size > 0) {
1150
+ // Forward/right are horizontal-projected so looking down and
1151
+ // pressing W doesn't dive into the ground — Q/E (below) are the only
1152
+ // vertical axis. `right` isn't explicitly re-projected: under Euler
1153
+ // order 'YXZ', pitch rotates around the camera's own local X, which
1154
+ // pitch itself never moves, so local X stays horizontal by
1155
+ // construction — the `.y = 0; normalize()` here is cheap, defensive
1156
+ // insurance against float drift, not load-bearing math.
1157
+ const speed = flySpeed * (shiftHeld ? SHIFT_MULTIPLIER : 1) * dt;
1158
+ const forward = new THREE.Vector3(0, 0, -1).applyQuaternion(camera.quaternion);
1159
+ forward.y = 0;
1160
+ if (forward.lengthSq() > 1e-8)
1161
+ forward.normalize();
1162
+ const right = new THREE.Vector3(1, 0, 0).applyQuaternion(camera.quaternion);
1163
+ right.y = 0;
1164
+ if (right.lengthSq() > 1e-8)
1165
+ right.normalize();
1166
+ if (movementKeysDown.has('w'))
1167
+ camera.position.addScaledVector(forward, speed);
1168
+ if (movementKeysDown.has('s'))
1169
+ camera.position.addScaledVector(forward, -speed);
1170
+ if (movementKeysDown.has('d'))
1171
+ camera.position.addScaledVector(right, speed);
1172
+ if (movementKeysDown.has('a'))
1173
+ camera.position.addScaledVector(right, -speed);
1174
+ if (movementKeysDown.has('e'))
1175
+ camera.position.y += speed; // straight world-Y, independent of look direction
1176
+ if (movementKeysDown.has('q'))
1177
+ camera.position.y -= speed;
1178
+ syncOrbitTarget();
1179
+ }
940
1180
  controls.update();
941
1181
  if (!scene)
942
1182
  return;
@@ -1013,7 +1253,19 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
1013
1253
  camera.near = Math.max(radius / 100, 0.01);
1014
1254
  camera.far = radius * 20;
1015
1255
  camera.updateProjectionMatrix();
1016
- controls.update();
1256
+ controls.update(); // still the simplest way to get camera.quaternion pointed at `center` — ends in object.lookAt(target)
1257
+ // Seed the free-fly controller's own state from the orientation
1258
+ // `controls.update()` just computed, instead of leaving OrbitControls
1259
+ // to keep deriving it forever (it won't — mouse can't drive it
1260
+ // anymore). `Euler.setFromQuaternion` with order 'YXZ' against a pure,
1261
+ // no-roll lookAt orientation decomposes exactly back into
1262
+ // (pitch, yaw, ~0): both constructions ultimately build "rotate to
1263
+ // face `center`, roll locked to zero, up = world Y."
1264
+ flyEuler.setFromQuaternion(camera.quaternion);
1265
+ pitch = THREE.MathUtils.clamp(flyEuler.x, -PITCH_LIMIT, PITCH_LIMIT);
1266
+ yaw = flyEuler.y;
1267
+ orbitDistance = camera.position.distanceTo(center);
1268
+ flySpeed = Math.max(radius * 0.6, 2); // proportional to scene scale, same convention camera.near/far use just above
1017
1269
  window.parent.postMessage({ type: 'umicat:editor:scene3dLoaded', sceneId }, '*');
1018
1270
  }
1019
1271
  catch (e) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umicat/three-sdk",
3
- "version": "1.5.0",
3
+ "version": "1.6.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",