@umicat/three-sdk 1.16.0 → 1.17.1

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
@@ -40,6 +40,15 @@ middle-mouse pan, F-to-focus, or Studio's comma/period ring-rotate.
40
40
  > each of those arrived. A status line is the first thing anyone reads and the
41
41
  > last thing anyone updates.
42
42
 
43
+ **Multiplayer is in the layer below, and it has rules worth reading before you
44
+ design anything around it** — the room type is always `'lobby'`, and the server
45
+ is authoritative about identity and ownership rather than about your game's
46
+ rules (so shared, contended state has no referee, and secret state is not
47
+ possible yet). It is written up in `@umicat/platform-sdk`'s README, under
48
+ "`rooms`: what the server guarantees, and what it does not". **A 3D game shipped
49
+ the wrong room type because that write-up used to live only in the Phaser SDK's
50
+ guide**, which nothing here points at.
51
+
43
52
  ```
44
53
  @umicat/platform-sdk identity · saves · gameData · rooms · ai · voice · dialogue
45
54
  ▲ (shared with @umicat/phaser-sdk)
@@ -1,3 +1,4 @@
1
+ import { installFoldVariables, placeCanvasInPanel } from '@umicat/platform-sdk/fold/foldVariables.js';
1
2
  // Laying a 3D game across a folded device, NDS-style: the world above the
2
3
  // crease, the controls below it.
3
4
  //
@@ -62,13 +63,17 @@ export function viewportSize(umicat) {
62
63
  */
63
64
  export function installDualScreen(umicat, targets = {}) {
64
65
  let current = null;
66
+ // The CSS custom properties are published by the platform SDK, not here: the
67
+ // variable names are a contract with a game's stylesheet, and the Phaser side
68
+ // needs the same ones. Two definitions of a contract drift.
69
+ const offVars = installFoldVariables(umicat.fold);
65
70
  const applyCanvas = () => {
66
71
  if (!current)
67
72
  return;
68
73
  if (!targets.renderer) {
69
74
  // Box only — the game sizes its own buffer.
70
75
  if (targets.canvas)
71
- placeCanvas(current, targets.canvas);
76
+ placeCanvasInPanel(targets.canvas, current);
72
77
  return;
73
78
  }
74
79
  const size = current.dualScreen && current.top
@@ -79,13 +84,12 @@ export function installDualScreen(umicat, targets = {}) {
79
84
  targets.camera.aspect = size.width / size.height;
80
85
  targets.camera.updateProjectionMatrix();
81
86
  }
82
- placeCanvas(current, targets.renderer.domElement);
87
+ placeCanvasInPanel(targets.renderer.domElement, current);
83
88
  };
84
89
  const onResize = () => { applyCanvas(); requestAnimationFrame(applyCanvas); };
85
90
  window.addEventListener('resize', onResize);
86
91
  const off = umicat.fold.subscribe((layout) => {
87
92
  current = layout;
88
- publishVariables(layout);
89
93
  placeControls(layout);
90
94
  applyCanvas();
91
95
  // A game that drives its own canvas still needs to hear about it. Folding
@@ -95,66 +99,7 @@ export function installDualScreen(umicat, targets = {}) {
95
99
  if (!targets.renderer)
96
100
  window.dispatchEvent(new Event('resize'));
97
101
  });
98
- return () => { window.removeEventListener('resize', onResize); off(); };
99
- }
100
- function publishVariables(layout) {
101
- const root = document.documentElement;
102
- const px = (n) => `${Math.round(n ?? 0)}px`;
103
- const on = layout.dualScreen;
104
- root.style.setProperty('--umicat-top-height', px(on ? layout.top?.height : 0));
105
- root.style.setProperty('--umicat-bottom-top', px(on ? layout.bottom?.y : 0));
106
- root.style.setProperty('--umicat-bottom-height', px(on ? layout.bottom?.height : 0));
107
- root.style.setProperty('--umicat-fold-top', px(on ? layout.division?.y : 0));
108
- root.style.setProperty('--umicat-fold-height', px(on ? layout.division?.height : 0));
109
- // A stylesheet cannot ask the SDK a question, so the state is an attribute.
110
- if (on)
111
- root.dataset.umicatDualScreen = '';
112
- else
113
- delete root.dataset.umicatDualScreen;
114
- }
115
- /**
116
- * Moves the SDK's touch layer into the lower panel.
117
- *
118
- * It is `position:fixed; inset:0` normally — the full window, with the stick
119
- * and buttons pinned near the bottom corners, which is where thumbs are on a
120
- * flat phone. Folded, thumbs are on the lower half and the upper half is
121
- * propped away from them, so "near the bottom of the window" is the wrong place
122
- * twice over: too far to reach, and sitting on top of the world.
123
- *
124
- * Done by moving the LAYER rather than each control, so every control the SDK
125
- * places — and any it grows later — follows for free.
126
- */
127
- /**
128
- * Constrains the canvas's CSS box to the upper panel.
129
- *
130
- * `viewportSize` alone is not enough, and the reason is a three.js argument
131
- * nobody thinks about: `setSize(w, h, false)` — which every template uses —
132
- * sizes the DRAWING BUFFER and deliberately leaves the CSS box alone, because
133
- * normally the canvas is stretched to the window by a stylesheet. Shrink only
134
- * the buffer and the result is the same full-screen picture at a lower
135
- * resolution, which looks like nothing happened at all.
136
- *
137
- * Found by doing exactly that: the fold arrived, the buffer shrank, and the
138
- * screenshot was unchanged.
139
- *
140
- * Defaults to the document's only canvas. A game with several passes its own.
141
- */
142
- function placeCanvas(layout, explicit) {
143
- const canvas = explicit ?? document.querySelector('canvas');
144
- if (!canvas)
145
- return;
146
- if (layout.dualScreen && layout.top) {
147
- Object.assign(canvas.style, {
148
- position: 'fixed',
149
- left: `${layout.top.x}px`,
150
- top: `${layout.top.y}px`,
151
- width: `${layout.top.width}px`,
152
- height: `${layout.top.height}px`,
153
- });
154
- }
155
- else {
156
- Object.assign(canvas.style, { position: '', left: '', top: '', width: '', height: '' });
157
- }
102
+ return () => { window.removeEventListener('resize', onResize); off(); offVars(); };
158
103
  }
159
104
  function placeControls(layout) {
160
105
  const root = document.querySelector(TOUCH_ROOT);
@@ -250,6 +250,99 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
250
250
  // per press.
251
251
  const movementKeysDown = new Set();
252
252
  let shiftHeld = false;
253
+ // ── ADR-051: grid snap ──────────────────────────────────────────────
254
+ //
255
+ // ON by default, step 1. The reference here is Roblox Studio, not Unity:
256
+ // Studio ships Snap to Grid ENABLED at 1 stud, and that is the right
257
+ // default for this audience because the public library's modular kits are
258
+ // built on exactly that module. Measured rather than assumed — Kenney
259
+ // Nature Kit's `cliff_block*` and `ground_*` are 1x1x1 with the origin
260
+ // centred horizontally and the base at y=0, so an INTEGER world position
261
+ // tiles them edge-to-edge with no gap and stacks them with no overlap.
262
+ // Unity's opposite default (off; hold Ctrl to snap) was rejected for the
263
+ // reason the desktop-controls work established the hard way: a capability
264
+ // nobody can find is the same as not having one.
265
+ //
266
+ // The step is ABSOLUTE — the resulting world POSITION is rounded, not the
267
+ // movement. That is what lets a piece already sitting at 0.37 get
268
+ // CORRECTED to 0 the next time it is dragged; delta-snapping would
269
+ // preserve the 0.37 forever, and the visible seam with it.
270
+ let snapEnabled = true;
271
+ let snapStep = 1;
272
+ // 45 degrees, matching Roblox Studio. Multiples of 45 REACH every 90-degree
273
+ // orientation while also permitting diagonals, so it is strictly more
274
+ // reachable than a 90 default at no cost — which is why Studio picked it.
275
+ let snapRotateRad = Math.PI / 4;
276
+ const snap1 = (v) => Math.round(v / snapStep) * snapStep;
277
+ /**
278
+ * Round a WORLD-space position onto the grid. Always called BEFORE the
279
+ * caller converts to parent-local space, so a parented entity lands on the
280
+ * world grid (the one its neighbours tile against) rather than on a grid
281
+ * skewed by its parent's transform.
282
+ *
283
+ * `axes` names ONLY the components this gesture actually varies, and
284
+ * nothing else is touched. That is load-bearing, not tidiness: an X-handle
285
+ * drag that also rounded Y and Z would silently move an entity on two axes
286
+ * the user did not grab, breaking the one contract the axis gizmo exists to
287
+ * provide (`gizmo-3d.test.mjs` asserts exactly that, and passed only
288
+ * because its fixture happened to sit on integers). Unity and Blender both
289
+ * constrain snapping to the dragged axis for the same reason.
290
+ *
291
+ * `bypass` is Alt held during the drag. It is the only modifier left:
292
+ * meta/ctrl at pointerdown means multi-select (ADR-046) and Shift is the
293
+ * fly-speed multiplier. Reading `altKey` off a pointer event is safe on
294
+ * macOS — the "Option is a dead key" trap from the pixel-art work is about
295
+ * Alt+LETTER shortcuts emitting special characters, which this is not.
296
+ */
297
+ const snapWorldPos = (p, bypass, axes) => {
298
+ if (!snapEnabled || bypass)
299
+ return;
300
+ if (axes.includes('x'))
301
+ p.x = snap1(p.x);
302
+ if (axes.includes('y'))
303
+ p.y = snap1(p.y);
304
+ if (axes.includes('z'))
305
+ p.z = snap1(p.z);
306
+ };
307
+ /**
308
+ * The visible grid. A single horizontal XZ plane, deliberately not a
309
+ * volumetric three-axis grid (unreadable in perspective, and no tool draws
310
+ * one) and deliberately only at y=0: with snap on, vertical stacking is
311
+ * self-aligning against the piece BELOW, so the grid's job is to
312
+ * communicate the module size and give horizontal reference — which is
313
+ * also why Roblox gets away with its grid being a texture on the ground
314
+ * baseplate rather than a viewport overlay.
315
+ *
316
+ * Cell count is held constant (not the extent) so a fine step costs the
317
+ * same number of lines as a coarse one — step 0.25 draws a dense 25-unit
318
+ * grid for close work, step 4 a 400-unit one for blocking out.
319
+ */
320
+ let snapGrid = null;
321
+ const SNAP_GRID_CELLS = 100;
322
+ const rebuildSnapGrid = () => {
323
+ if (snapGrid) {
324
+ snapGrid.parent?.remove(snapGrid);
325
+ snapGrid.geometry.dispose();
326
+ snapGrid.material.dispose();
327
+ snapGrid = null;
328
+ }
329
+ if (!scene || !snapEnabled)
330
+ return;
331
+ const grid = new THREE.GridHelper(snapStep * SNAP_GRID_CELLS, SNAP_GRID_CELLS, 0x5a6472, 0x39404a);
332
+ grid.name = '__umicatSnapGrid';
333
+ // Ground in a real scene is routinely a FLAT tile whose top face is
334
+ // exactly y=0 (`ground_grass.glb` measures 1 x 0 x 1), so a grid at
335
+ // y=0 would be coplanar with it and z-fight across the whole floor.
336
+ // Lift it a hair and never write depth, so it reads as a drawn-on
337
+ // overlay instead of geometry competing for the same pixels.
338
+ grid.position.y = 0.002;
339
+ const mat = grid.material;
340
+ mat.transparent = true;
341
+ mat.opacity = 0.5;
342
+ mat.depthWrite = false;
343
+ scene.add(grid);
344
+ snapGrid = grid;
345
+ };
253
346
  // A single persistent marker, repositioned per click — the exact world
254
347
  // point clicked (what "put a torch at the spot I clicked" needs), distinct
255
348
  // from the box below (which entity was hit, not just where).
@@ -432,6 +525,20 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
432
525
  // dropped model's `importScale` means that's almost never true).
433
526
  globalThis.__umicatGizmoAttachedScale =
434
527
  () => gizmo.attached ? { x: gizmo.attached.scale.x, y: gizmo.attached.scale.y, z: gizmo.attached.scale.z } : null;
528
+ // ADR-051 — test-only readback, same posture as the hooks above (never
529
+ // read by umicat-home-ui). `cameraDistance` is here because the grid can
530
+ // break the zoom-to-fit INVISIBLY: folded into the fit box, a 100-unit
531
+ // grid frames 100 units around a 20-unit scene, which reads as "the
532
+ // editor opens zoomed out" rather than as a bug, and no assertion about
533
+ // snapping itself would ever catch it.
534
+ globalThis.__umicatSnapState =
535
+ () => ({
536
+ enabled: snapEnabled,
537
+ step: snapStep,
538
+ rotateDeg: (snapRotateRad * 180) / Math.PI,
539
+ gridPresent: !!(scene && scene.getObjectByName('__umicatSnapGrid')),
540
+ cameraDistance: camera.position.length(),
541
+ });
435
542
  // ADR-046 Phase 3b — test-only: distinguishes "gizmo attached to a REAL
436
543
  // single entity" from "gizmo attached to the shared group pivot" — both
437
544
  // report non-null from `__umicatGizmoAttachedScale` above, so a test
@@ -863,6 +970,13 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
863
970
  if (!grab)
864
971
  return;
865
972
  const newWorldPos = grab.clone().sub(gizmoDrag.grabOffset);
973
+ // ADR-051 — snap in WORLD space, before the parent-local conversion
974
+ // and before the group delta below, and ONLY on the axis being
975
+ // dragged. Snapping the PIVOT and letting members follow by that same
976
+ // delta is what keeps a multi-selection rigid: snapping each member
977
+ // independently would collapse any fractional offsets between them
978
+ // (Unity snaps the active object for the same reason).
979
+ snapWorldPos(newWorldPos, e.altKey, gizmoDrag.axis);
866
980
  if (obj.parent)
867
981
  obj.parent.worldToLocal(newWorldPos);
868
982
  obj.position.copy(newWorldPos);
@@ -945,7 +1059,17 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
945
1059
  if (!hitPoint)
946
1060
  return;
947
1061
  const currentAngle = angleAroundAxis(gizmoDrag.planePoint, gizmoDrag.planeNormal, hitPoint);
948
- const delta = currentAngle - gizmoDrag.startAngle;
1062
+ // ADR-051 — rotation snaps the DELTA, not an absolute orientation,
1063
+ // which is what Unity and Blender both do: "the object's angle about
1064
+ // this world axis" is not well defined for an arbitrary quaternion
1065
+ // without a swing/twist decomposition. Exact for the case that
1066
+ // matters — a freshly placed entity starts at identity, so stepped
1067
+ // deltas land it exactly on multiples. Known limit: an entity already
1068
+ // sitting at an odd angle keeps that offset forever.
1069
+ const rawDelta = currentAngle - gizmoDrag.startAngle;
1070
+ const delta = snapEnabled && !e.altKey
1071
+ ? Math.round(rawDelta / snapRotateRad) * snapRotateRad
1072
+ : rawDelta;
949
1073
  const deltaQuat = new THREE.Quaternion().setFromAxisAngle(gizmoDrag.planeNormal, delta);
950
1074
  const newWorldQuat = deltaQuat.multiply(gizmoDrag.startWorldQuaternion.clone());
951
1075
  obj.quaternion.copy(gizmoDrag.parentWorldQuatInverse.clone().multiply(newWorldQuat));
@@ -1139,6 +1263,11 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
1139
1263
  if (!raycaster.ray.intersectPlane(dragPlane, planePoint))
1140
1264
  return; // looking parallel to the plane
1141
1265
  const newWorldPos = planePoint.sub(dragGrabOffset);
1266
+ // ADR-051 — same grid as the gizmo path. `dragPlane` is horizontal at
1267
+ // the entity's own height, so this gesture varies x and z only; y must
1268
+ // not be rounded here or a piece deliberately parked at y=0.5 would
1269
+ // drop to the floor the first time it was slid sideways.
1270
+ snapWorldPos(newWorldPos, e.altKey, 'xz');
1142
1271
  if (dragEntity.parent)
1143
1272
  dragEntity.parent.worldToLocal(newWorldPos);
1144
1273
  dragEntity.position.copy(newWorldPos);
@@ -1396,6 +1525,23 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
1396
1525
  return onCsgUnion3d(data);
1397
1526
  if (data.type === 'umicat:editor:csgIntersect3d')
1398
1527
  return onCsgIntersect3d(data);
1528
+ // ADR-051 — grid snap settings. Host owns the control and the
1529
+ // persistence; this just applies them. Every field is optional so the
1530
+ // host can push a partial update, and the grid is rebuilt on any change
1531
+ // because its cell size IS the step (the grid is the snap grid, not a
1532
+ // separate decoration).
1533
+ if (data.type === 'umicat:editor:setSnap3d') {
1534
+ const d = data;
1535
+ if (typeof d.enabled === 'boolean')
1536
+ snapEnabled = d.enabled;
1537
+ if (typeof d.step === 'number' && Number.isFinite(d.step) && d.step > 0)
1538
+ snapStep = d.step;
1539
+ if (typeof d.rotateDeg === 'number' && Number.isFinite(d.rotateDeg) && d.rotateDeg > 0) {
1540
+ snapRotateRad = (d.rotateDeg * Math.PI) / 180;
1541
+ }
1542
+ rebuildSnapGrid();
1543
+ return;
1544
+ }
1399
1545
  if (data.type === 'umicat:editor:setGizmoMode3d') {
1400
1546
  const mode = data.mode;
1401
1547
  if (mode === 'move' || mode === 'rotate' || mode === 'scale') {
@@ -2254,6 +2400,11 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
2254
2400
  // ADR-047 — same reasoning as `multiBoxes.clear()` just above: a prior
2255
2401
  // scene's boxes were added to that scene, not this one. Re-seed from
2256
2402
  // the freshly loaded authored data, not carried over.
2403
+ // ADR-051 — a (re)load builds a brand new scene graph, so the previous
2404
+ // grid went with the old one. Same reasoning as the selection
2405
+ // bookkeeping above.
2406
+ snapGrid = null;
2407
+ rebuildSnapGrid();
2257
2408
  negatedBoxes.clear();
2258
2409
  for (const e of sceneData.entities) {
2259
2410
  if (e.negated) {
@@ -2264,7 +2415,18 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
2264
2415
  }
2265
2416
  // Frame the whole scene — auto-fit, since a small template scene and a
2266
2417
  // real level's dozens of entities need wildly different orbit distances.
2267
- const box = new THREE.Box3().setFromObject(scene);
2418
+ // Frame the authored ENTITIES, not `scene` as a whole. ADR-051 adds a
2419
+ // grid helper whose extent is a display choice (step x 100 units) and
2420
+ // has nothing to do with how big the level is — `setFromObject(scene)`
2421
+ // would fold it in and shove the camera back far enough to frame a
2422
+ // 100-unit grid around a 6-unit template. Falls back to the whole scene
2423
+ // when there are no entities at all, which is what the empty-scene case
2424
+ // used to rely on.
2425
+ const box = new THREE.Box3();
2426
+ for (const obj of objectByEntity.values())
2427
+ box.expandByObject(obj, true);
2428
+ if (box.isEmpty())
2429
+ box.setFromObject(scene);
2268
2430
  const size = box.getSize(new THREE.Vector3());
2269
2431
  const center = box.getCenter(new THREE.Vector3());
2270
2432
  const radius = Math.max(size.length() * 0.5, 0.5);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umicat/three-sdk",
3
- "version": "1.16.0",
3
+ "version": "1.17.1",
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",
@@ -13,12 +13,13 @@
13
13
  },
14
14
  "scripts": {
15
15
  "build": "tsc",
16
- "test": "npm run build && npm run build:example && node --test scripts/*.test.mjs",
17
- "build:example": "../umicat-template/node_modules/esbuild/bin/esbuild example/src/main.js --bundle --format=esm --outfile=example/public/game.js --alias:@umicat/three-sdk=./dist/index.js --log-level=warning"
16
+ "test": "npm run build && npm run build:example && npm run build:editor-fixture && node --test scripts/*.test.mjs",
17
+ "build:example": "../umicat-template/node_modules/esbuild/bin/esbuild example/src/main.js --bundle --format=esm --outfile=example/public/game.js --alias:@umicat/three-sdk=./dist/index.js --log-level=warning",
18
+ "build:editor-fixture": "../umicat-template/node_modules/esbuild/bin/esbuild scripts/harness/editor-entry.js --bundle --format=esm --outfile=scripts/harness/editor-fixture/editor-bundle.js --alias:@umicat/three-sdk=./dist/index.js --log-level=warning"
18
19
  },
19
20
  "dependencies": {
20
21
  "@dimforge/rapier3d-compat": "^0.14.0",
21
- "@umicat/platform-sdk": "^0.3.0",
22
+ "@umicat/platform-sdk": "^0.4.0",
22
23
  "three": "0.186.0",
23
24
  "three-bvh-csg": "^0.0.18",
24
25
  "three-mesh-bvh": "^0.9.16"