@umicat/three-sdk 1.16.0 → 1.17.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.
@@ -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,96 @@ 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
+ let snapRotateRad = Math.PI / 2;
273
+ const snap1 = (v) => Math.round(v / snapStep) * snapStep;
274
+ /**
275
+ * Round a WORLD-space position onto the grid. Always called BEFORE the
276
+ * caller converts to parent-local space, so a parented entity lands on the
277
+ * world grid (the one its neighbours tile against) rather than on a grid
278
+ * skewed by its parent's transform.
279
+ *
280
+ * `axes` names ONLY the components this gesture actually varies, and
281
+ * nothing else is touched. That is load-bearing, not tidiness: an X-handle
282
+ * drag that also rounded Y and Z would silently move an entity on two axes
283
+ * the user did not grab, breaking the one contract the axis gizmo exists to
284
+ * provide (`gizmo-3d.test.mjs` asserts exactly that, and passed only
285
+ * because its fixture happened to sit on integers). Unity and Blender both
286
+ * constrain snapping to the dragged axis for the same reason.
287
+ *
288
+ * `bypass` is Alt held during the drag. It is the only modifier left:
289
+ * meta/ctrl at pointerdown means multi-select (ADR-046) and Shift is the
290
+ * fly-speed multiplier. Reading `altKey` off a pointer event is safe on
291
+ * macOS — the "Option is a dead key" trap from the pixel-art work is about
292
+ * Alt+LETTER shortcuts emitting special characters, which this is not.
293
+ */
294
+ const snapWorldPos = (p, bypass, axes) => {
295
+ if (!snapEnabled || bypass)
296
+ return;
297
+ if (axes.includes('x'))
298
+ p.x = snap1(p.x);
299
+ if (axes.includes('y'))
300
+ p.y = snap1(p.y);
301
+ if (axes.includes('z'))
302
+ p.z = snap1(p.z);
303
+ };
304
+ /**
305
+ * The visible grid. A single horizontal XZ plane, deliberately not a
306
+ * volumetric three-axis grid (unreadable in perspective, and no tool draws
307
+ * one) and deliberately only at y=0: with snap on, vertical stacking is
308
+ * self-aligning against the piece BELOW, so the grid's job is to
309
+ * communicate the module size and give horizontal reference — which is
310
+ * also why Roblox gets away with its grid being a texture on the ground
311
+ * baseplate rather than a viewport overlay.
312
+ *
313
+ * Cell count is held constant (not the extent) so a fine step costs the
314
+ * same number of lines as a coarse one — step 0.25 draws a dense 25-unit
315
+ * grid for close work, step 4 a 400-unit one for blocking out.
316
+ */
317
+ let snapGrid = null;
318
+ const SNAP_GRID_CELLS = 100;
319
+ const rebuildSnapGrid = () => {
320
+ if (snapGrid) {
321
+ snapGrid.parent?.remove(snapGrid);
322
+ snapGrid.geometry.dispose();
323
+ snapGrid.material.dispose();
324
+ snapGrid = null;
325
+ }
326
+ if (!scene || !snapEnabled)
327
+ return;
328
+ const grid = new THREE.GridHelper(snapStep * SNAP_GRID_CELLS, SNAP_GRID_CELLS, 0x5a6472, 0x39404a);
329
+ grid.name = '__umicatSnapGrid';
330
+ // Ground in a real scene is routinely a FLAT tile whose top face is
331
+ // exactly y=0 (`ground_grass.glb` measures 1 x 0 x 1), so a grid at
332
+ // y=0 would be coplanar with it and z-fight across the whole floor.
333
+ // Lift it a hair and never write depth, so it reads as a drawn-on
334
+ // overlay instead of geometry competing for the same pixels.
335
+ grid.position.y = 0.002;
336
+ const mat = grid.material;
337
+ mat.transparent = true;
338
+ mat.opacity = 0.5;
339
+ mat.depthWrite = false;
340
+ scene.add(grid);
341
+ snapGrid = grid;
342
+ };
253
343
  // A single persistent marker, repositioned per click — the exact world
254
344
  // point clicked (what "put a torch at the spot I clicked" needs), distinct
255
345
  // from the box below (which entity was hit, not just where).
@@ -432,6 +522,20 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
432
522
  // dropped model's `importScale` means that's almost never true).
433
523
  globalThis.__umicatGizmoAttachedScale =
434
524
  () => gizmo.attached ? { x: gizmo.attached.scale.x, y: gizmo.attached.scale.y, z: gizmo.attached.scale.z } : null;
525
+ // ADR-051 — test-only readback, same posture as the hooks above (never
526
+ // read by umicat-home-ui). `cameraDistance` is here because the grid can
527
+ // break the zoom-to-fit INVISIBLY: folded into the fit box, a 100-unit
528
+ // grid frames 100 units around a 20-unit scene, which reads as "the
529
+ // editor opens zoomed out" rather than as a bug, and no assertion about
530
+ // snapping itself would ever catch it.
531
+ globalThis.__umicatSnapState =
532
+ () => ({
533
+ enabled: snapEnabled,
534
+ step: snapStep,
535
+ rotateDeg: (snapRotateRad * 180) / Math.PI,
536
+ gridPresent: !!(scene && scene.getObjectByName('__umicatSnapGrid')),
537
+ cameraDistance: camera.position.length(),
538
+ });
435
539
  // ADR-046 Phase 3b — test-only: distinguishes "gizmo attached to a REAL
436
540
  // single entity" from "gizmo attached to the shared group pivot" — both
437
541
  // report non-null from `__umicatGizmoAttachedScale` above, so a test
@@ -863,6 +967,13 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
863
967
  if (!grab)
864
968
  return;
865
969
  const newWorldPos = grab.clone().sub(gizmoDrag.grabOffset);
970
+ // ADR-051 — snap in WORLD space, before the parent-local conversion
971
+ // and before the group delta below, and ONLY on the axis being
972
+ // dragged. Snapping the PIVOT and letting members follow by that same
973
+ // delta is what keeps a multi-selection rigid: snapping each member
974
+ // independently would collapse any fractional offsets between them
975
+ // (Unity snaps the active object for the same reason).
976
+ snapWorldPos(newWorldPos, e.altKey, gizmoDrag.axis);
866
977
  if (obj.parent)
867
978
  obj.parent.worldToLocal(newWorldPos);
868
979
  obj.position.copy(newWorldPos);
@@ -945,7 +1056,17 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
945
1056
  if (!hitPoint)
946
1057
  return;
947
1058
  const currentAngle = angleAroundAxis(gizmoDrag.planePoint, gizmoDrag.planeNormal, hitPoint);
948
- const delta = currentAngle - gizmoDrag.startAngle;
1059
+ // ADR-051 — rotation snaps the DELTA, not an absolute orientation,
1060
+ // which is what Unity and Blender both do: "the object's angle about
1061
+ // this world axis" is not well defined for an arbitrary quaternion
1062
+ // without a swing/twist decomposition. Exact for the case that
1063
+ // matters — a freshly placed entity starts at identity, so stepped
1064
+ // deltas land it exactly on multiples. Known limit: an entity already
1065
+ // sitting at an odd angle keeps that offset forever.
1066
+ const rawDelta = currentAngle - gizmoDrag.startAngle;
1067
+ const delta = snapEnabled && !e.altKey
1068
+ ? Math.round(rawDelta / snapRotateRad) * snapRotateRad
1069
+ : rawDelta;
949
1070
  const deltaQuat = new THREE.Quaternion().setFromAxisAngle(gizmoDrag.planeNormal, delta);
950
1071
  const newWorldQuat = deltaQuat.multiply(gizmoDrag.startWorldQuaternion.clone());
951
1072
  obj.quaternion.copy(gizmoDrag.parentWorldQuatInverse.clone().multiply(newWorldQuat));
@@ -1139,6 +1260,11 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
1139
1260
  if (!raycaster.ray.intersectPlane(dragPlane, planePoint))
1140
1261
  return; // looking parallel to the plane
1141
1262
  const newWorldPos = planePoint.sub(dragGrabOffset);
1263
+ // ADR-051 — same grid as the gizmo path. `dragPlane` is horizontal at
1264
+ // the entity's own height, so this gesture varies x and z only; y must
1265
+ // not be rounded here or a piece deliberately parked at y=0.5 would
1266
+ // drop to the floor the first time it was slid sideways.
1267
+ snapWorldPos(newWorldPos, e.altKey, 'xz');
1142
1268
  if (dragEntity.parent)
1143
1269
  dragEntity.parent.worldToLocal(newWorldPos);
1144
1270
  dragEntity.position.copy(newWorldPos);
@@ -1396,6 +1522,23 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
1396
1522
  return onCsgUnion3d(data);
1397
1523
  if (data.type === 'umicat:editor:csgIntersect3d')
1398
1524
  return onCsgIntersect3d(data);
1525
+ // ADR-051 — grid snap settings. Host owns the control and the
1526
+ // persistence; this just applies them. Every field is optional so the
1527
+ // host can push a partial update, and the grid is rebuilt on any change
1528
+ // because its cell size IS the step (the grid is the snap grid, not a
1529
+ // separate decoration).
1530
+ if (data.type === 'umicat:editor:setSnap3d') {
1531
+ const d = data;
1532
+ if (typeof d.enabled === 'boolean')
1533
+ snapEnabled = d.enabled;
1534
+ if (typeof d.step === 'number' && Number.isFinite(d.step) && d.step > 0)
1535
+ snapStep = d.step;
1536
+ if (typeof d.rotateDeg === 'number' && Number.isFinite(d.rotateDeg) && d.rotateDeg > 0) {
1537
+ snapRotateRad = (d.rotateDeg * Math.PI) / 180;
1538
+ }
1539
+ rebuildSnapGrid();
1540
+ return;
1541
+ }
1399
1542
  if (data.type === 'umicat:editor:setGizmoMode3d') {
1400
1543
  const mode = data.mode;
1401
1544
  if (mode === 'move' || mode === 'rotate' || mode === 'scale') {
@@ -2254,6 +2397,11 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
2254
2397
  // ADR-047 — same reasoning as `multiBoxes.clear()` just above: a prior
2255
2398
  // scene's boxes were added to that scene, not this one. Re-seed from
2256
2399
  // the freshly loaded authored data, not carried over.
2400
+ // ADR-051 — a (re)load builds a brand new scene graph, so the previous
2401
+ // grid went with the old one. Same reasoning as the selection
2402
+ // bookkeeping above.
2403
+ snapGrid = null;
2404
+ rebuildSnapGrid();
2257
2405
  negatedBoxes.clear();
2258
2406
  for (const e of sceneData.entities) {
2259
2407
  if (e.negated) {
@@ -2264,7 +2412,18 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
2264
2412
  }
2265
2413
  // Frame the whole scene — auto-fit, since a small template scene and a
2266
2414
  // real level's dozens of entities need wildly different orbit distances.
2267
- const box = new THREE.Box3().setFromObject(scene);
2415
+ // Frame the authored ENTITIES, not `scene` as a whole. ADR-051 adds a
2416
+ // grid helper whose extent is a display choice (step x 100 units) and
2417
+ // has nothing to do with how big the level is — `setFromObject(scene)`
2418
+ // would fold it in and shove the camera back far enough to frame a
2419
+ // 100-unit grid around a 6-unit template. Falls back to the whole scene
2420
+ // when there are no entities at all, which is what the empty-scene case
2421
+ // used to rely on.
2422
+ const box = new THREE.Box3();
2423
+ for (const obj of objectByEntity.values())
2424
+ box.expandByObject(obj, true);
2425
+ if (box.isEmpty())
2426
+ box.setFromObject(scene);
2268
2427
  const size = box.getSize(new THREE.Vector3());
2269
2428
  const center = box.getCenter(new THREE.Vector3());
2270
2429
  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.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",
@@ -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"