@umicat/three-sdk 1.6.0 → 1.8.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,5 +1,5 @@
1
1
  import * as THREE from 'three';
2
- import { type Scene3D, type Manifest3D, type Sky3D } from './scene3d.js';
2
+ import { type Scene3D, type Manifest3D, type Entity3D, type Sky3D } from './scene3d.js';
3
3
  import { type WornMap } from './Attachments.js';
4
4
  export interface LoadSceneOptions {
5
5
  /** Base url assets resolve against (the project's asset host). */
@@ -54,6 +54,11 @@ export interface LoadedScene3D {
54
54
  update(dt: number): void;
55
55
  dispose(): void;
56
56
  }
57
+ export declare const MATERIAL_LIBRARY: Record<string, {
58
+ color: string;
59
+ roughness: string;
60
+ }>;
61
+ export declare function makePrimitive(e: Entity3D): THREE.Mesh;
57
62
  /**
58
63
  * Turn scene3d design data into a running three.js scene.
59
64
  *
@@ -1,12 +1,18 @@
1
1
  import * as THREE from 'three';
2
2
  import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
3
3
  import { clone as cloneRigged } from 'three/examples/jsm/utils/SkeletonUtils.js';
4
- import { validateScene, IDENTITY_QUAT, } from './scene3d.js';
4
+ import { validateScene, IDENTITY_QUAT, wedgeVertices, cornerWedgeVertices, defaultColliderForPrimitive, } from './scene3d.js';
5
5
  import { applySkin } from './Skin.js';
6
6
  import { applyAttachments } from './Attachments.js';
7
7
  function toVec(v, d = 0) {
8
8
  return new THREE.Vector3(v?.x ?? d, v?.y ?? d, v?.z ?? d);
9
9
  }
10
+ /** `Rapier.ColliderDesc.convexHull` wants a flat `[x,y,z, x,y,z, ...]` buffer. */
11
+ function flattenPoints(points) {
12
+ const out = new Float32Array(points.length * 3);
13
+ points.forEach((v, i) => { out[i * 3] = v.x; out[i * 3 + 1] = v.y; out[i * 3 + 2] = v.z; });
14
+ return out;
15
+ }
10
16
  /** Does this model deform with bones? Decides which clone it needs. */
11
17
  function isRigged(root) {
12
18
  let rigged = false;
@@ -24,26 +30,219 @@ function applyTransform(obj, e) {
24
30
  else if (t.scale)
25
31
  obj.scale.copy(toVec(t.scale, 1));
26
32
  }
27
- function makePrimitive(e) {
33
+ /**
34
+ * Builds a non-indexed, per-face-normal `BufferGeometry` out of a flat list
35
+ * of CCW-wound triangles (`[A,B,C, A,B,C, ...]`) — the shape a hand-authored
36
+ * low-poly solid (wedge/corner-wedge) needs: NON-indexed specifically so
37
+ * `computeVertexNormals()` yields one flat normal per FACE rather than
38
+ * blending across a shared vertex between two faces at different angles
39
+ * (which would wrongly soften the wedge's sharp ridge edge into a curve).
40
+ *
41
+ * ADR-044 — also assigns a UV per vertex, dominant-axis PLANAR per face
42
+ * (box/sphere/cylinder/plane all already have usable UVs from three.js's
43
+ * own geometry constructors; these two hand-built shapes had none at all
44
+ * before this). Each face is flat by construction, so the face's own
45
+ * normal (computed directly from its 3 points — BEFORE
46
+ * `computeVertexNormals()` blends anything) picks which two of the three
47
+ * local axes to project onto: a face whose normal is mostly ±X reads its
48
+ * UV from (y,z), mostly ±Y from (x,z), mostly ±Z from (x,y). `size` scales
49
+ * the projection so UV spans ~0..1 per face — the SAME convention
50
+ * `BoxGeometry`'s own per-face UVs already use, which is what lets
51
+ * `makePrimitive`'s `texture.repeat` math treat every primitive kind
52
+ * uniformly regardless of which one actually has native UVs.
53
+ */
54
+ function triangleListGeometry(triangles, size) {
55
+ const positions = new Float32Array(triangles.length * 3);
56
+ const uvs = new Float32Array(triangles.length * 2);
57
+ triangles.forEach((v, i) => { positions[i * 3] = v.x; positions[i * 3 + 1] = v.y; positions[i * 3 + 2] = v.z; });
58
+ for (let i = 0; i < triangles.length; i += 3) {
59
+ const a = triangles[i], b = triangles[i + 1], c = triangles[i + 2];
60
+ const ab = new THREE.Vector3(b.x - a.x, b.y - a.y, b.z - a.z);
61
+ const ac = new THREE.Vector3(c.x - a.x, c.y - a.y, c.z - a.z);
62
+ const n = new THREE.Vector3().crossVectors(ab, ac);
63
+ const ax = Math.abs(n.x), ay = Math.abs(n.y), az = Math.abs(n.z);
64
+ for (let k = 0; k < 3; k++) {
65
+ const v = triangles[i + k];
66
+ let u, w;
67
+ if (ax >= ay && ax >= az) {
68
+ u = v.y / size.y;
69
+ w = v.z / size.z;
70
+ }
71
+ else if (ay >= ax && ay >= az) {
72
+ u = v.x / size.x;
73
+ w = v.z / size.z;
74
+ }
75
+ else {
76
+ u = v.x / size.x;
77
+ w = v.y / size.y;
78
+ }
79
+ const idx = i + k;
80
+ uvs[idx * 2] = u + 0.5;
81
+ uvs[idx * 2 + 1] = w + 0.5;
82
+ }
83
+ }
84
+ const geom = new THREE.BufferGeometry();
85
+ geom.setAttribute('position', new THREE.BufferAttribute(positions, 3));
86
+ geom.setAttribute('uv', new THREE.BufferAttribute(uvs, 2));
87
+ geom.computeVertexNormals();
88
+ return geom;
89
+ }
90
+ /** Winding verified by hand (right-hand rule, outward normal per face) —
91
+ * see `scene3d.ts`'s `wedgeVertices` doc comment for the vertex layout. */
92
+ function wedgeGeometry(size) {
93
+ const [v0, v1, v2, v3, v4, v5] = wedgeVertices(size);
94
+ return triangleListGeometry([
95
+ v0, v1, v2, v0, v2, v3, // bottom (-Y)
96
+ v0, v5, v1, v0, v4, v5, // back (-Z)
97
+ v0, v3, v4, // left end cap
98
+ v1, v5, v2, // right end cap
99
+ v3, v2, v4, v2, v5, v4, // slope (hypotenuse)
100
+ ], size);
101
+ }
102
+ /** Winding verified by hand the same way as `wedgeGeometry` — see
103
+ * `scene3d.ts`'s `cornerWedgeVertices` doc comment for the vertex layout. */
104
+ function cornerWedgeGeometry(size) {
105
+ const [v0, v1, v2, v3, v4] = cornerWedgeVertices(size);
106
+ return triangleListGeometry([
107
+ v0, v1, v2, v0, v2, v3, // bottom (-Y)
108
+ v0, v4, v1, // back side
109
+ v1, v4, v2, // right side
110
+ v2, v4, v3, // front side
111
+ v3, v4, v0, // left side
112
+ ], size);
113
+ }
114
+ /**
115
+ * ADR-044 — the built-in Parts material library. A NAME resolves to two
116
+ * CDN-hosted maps (Color + Roughness only — see the ADR's own "game-grade,
117
+ * not showcase-grade" scoping for why Normal/Displacement/AO aren't here),
118
+ * re-hosted (not linked to the source) under the platform-wide, already-
119
+ * public `platform/` S3 prefix (`cdn.umicat.ai/platform/...` — the same
120
+ * prefix `platform/canonical-rig/v1/...` already uses for the Model
121
+ * Editor's auto-rig skeleton; no bucket-policy change was needed). Sourced
122
+ * from ambientCG (CC0), reprocessed to 512×512 JPEG.
123
+ */
124
+ const MATERIAL_BASE = 'https://cdn.umicat.ai/platform/three-sdk-materials';
125
+ export const MATERIAL_LIBRARY = Object.fromEntries(['concrete', 'brick', 'wood', 'metal', 'cardboard', 'rock', 'grass', 'tile'].map((name) => [
126
+ name, { color: `${MATERIAL_BASE}/${name}/color.jpg`, roughness: `${MATERIAL_BASE}/${name}/roughness.jpg` },
127
+ ]));
128
+ /** How many world units one tile of a material's source photo covers —
129
+ * matched loosely to each photo's own real-world scale so e.g. brick
130
+ * courses read as actual brick-sized, not a wall-sized or postage-stamp-
131
+ * sized repeat. Same role `groundRestOffset` plays for placement: a
132
+ * small per-kind constant rather than a universal formula, because there
133
+ * isn't one — these are real photos at real physical scales. */
134
+ const MATERIAL_TILE_UNIT = {
135
+ concrete: 1, brick: 0.5, wood: 1, metal: 1, cardboard: 0.6, rock: 1, grass: 1, tile: 0.5,
136
+ };
137
+ const materialTextures = new Map();
138
+ let materialLoader = null;
139
+ /** Load (and cache) one material-library texture. `colorSpace` distinguishes
140
+ * the Color map (sRGB — it's a photographed colour) from Roughness (a data
141
+ * map — tagging it sRGB would wrongly remap its own numeric values, the
142
+ * same class of mistake `Skin.ts`'s texture loader already guards against
143
+ * for the opposite reason). Unlike `Skin.ts`'s `loadSkinTexture`, `flipY`
144
+ * is left at the `TextureLoader` DEFAULT (`true`) — these primitives use
145
+ * three.js's own standard UV convention (both the native box/sphere/
146
+ * cylinder/plane geometries AND `triangleListGeometry`'s hand-rolled UVs
147
+ * above), not GLTFLoader's inverted one; copying Skin.ts's `flipY=false`
148
+ * here would flip every Parts material upside down. */
149
+ function loadMaterialTexture(url, colorSpace) {
150
+ const key = `${url}|${colorSpace}`;
151
+ const hit = materialTextures.get(key);
152
+ if (hit)
153
+ return hit;
154
+ materialLoader ?? (materialLoader = new THREE.TextureLoader());
155
+ const p = materialLoader.loadAsync(url).then((t) => {
156
+ t.colorSpace = colorSpace;
157
+ t.wrapS = t.wrapT = THREE.RepeatWrapping;
158
+ return t;
159
+ });
160
+ materialTextures.set(key, p);
161
+ // A failed fetch must not be remembered as the answer — same reasoning
162
+ // Skin.ts's cache already documents.
163
+ p.catch(() => materialTextures.delete(key));
164
+ return p;
165
+ }
166
+ /**
167
+ * ADR-044 — how many times a material's texture repeats across a Part,
168
+ * per axis. box/plane/wedge/corner-wedge all use width×depth (the closest
169
+ * single approximation to "looks right" across a shape with several
170
+ * differently-sized faces — a perfect per-face repeat would need a scale
171
+ * baked in per face, not worth it for a blockout tool); cylinder uses
172
+ * diameter×height; sphere uses diameter on both axes (no clean width-vs-
173
+ * depth distinction on a sphere for tiling purposes).
174
+ */
175
+ function materialRepeatFor(kind, size, tileUnit) {
176
+ const u = (n) => Math.max(0.1, n / tileUnit);
177
+ if (kind === 'cylinder')
178
+ return new THREE.Vector2(u(size.x), u(size.y));
179
+ if (kind === 'sphere') {
180
+ const d = u(size.x);
181
+ return new THREE.Vector2(d, d);
182
+ }
183
+ return new THREE.Vector2(u(size.x), u(size.z));
184
+ }
185
+ export function makePrimitive(e) {
28
186
  const p = e.primitive;
29
187
  const s = p.size ?? { x: 1, y: 1, z: 1 };
30
188
  const geom = p.kind === 'box' ? new THREE.BoxGeometry(s.x, s.y, s.z)
31
189
  : p.kind === 'sphere' ? new THREE.SphereGeometry(s.x / 2, 24, 16)
32
190
  : p.kind === 'cylinder' ? new THREE.CylinderGeometry(s.x / 2, s.x / 2, s.y, 24)
33
- // Lay the plane down by rotating the GEOMETRY, not the object. Rotating the
34
- // object is the obvious move and it is wrong: applyTransform sets the
35
- // object's quaternion from the entity's authored rotation straight
36
- // afterwards, silently discarding it — which left every "ground" standing
37
- // upright like a wall. It renders convincingly until the camera crosses to
38
- // the far side, at which point the scene becomes a flat fill and every
39
- // measurement still says the character is dead centre, because it is —
40
- // behind a 40x40 wall.
41
- : new THREE.PlaneGeometry(s.x, s.z).rotateX(-Math.PI / 2);
42
- const mesh = new THREE.Mesh(geom, new THREE.MeshStandardMaterial({
191
+ : p.kind === 'wedge' ? wedgeGeometry(s)
192
+ : p.kind === 'corner-wedge' ? cornerWedgeGeometry(s)
193
+ // Lay the plane down by rotating the GEOMETRY, not the object. Rotating the
194
+ // object is the obvious move and it is wrong: applyTransform sets the
195
+ // object's quaternion from the entity's authored rotation straight
196
+ // afterwards, silently discarding it — which left every "ground" standing
197
+ // upright like a wall. It renders convincingly until the camera crosses to
198
+ // the far side, at which point the scene becomes a flat fill and every
199
+ // measurement still says the character is dead centre, because it is —
200
+ // behind a 40x40 wall.
201
+ : new THREE.PlaneGeometry(s.x, s.z).rotateX(-Math.PI / 2);
202
+ const material = new THREE.MeshStandardMaterial({
43
203
  color: new THREE.Color(p.color ?? '#c8c8c8'), roughness: 0.85,
44
- }));
204
+ // The wedge/corner-wedge faces' winding was verified by hand (no
205
+ // browser available to render and visually confirm it in this pass) —
206
+ // DoubleSide is a pragmatic safety net against a winding mistake
207
+ // making a face invisible from its intended viewing side; it costs a
208
+ // little backface-culling perf on two low-poly shapes, not correctness.
209
+ side: (p.kind === 'wedge' || p.kind === 'corner-wedge') ? THREE.DoubleSide : THREE.FrontSide,
210
+ });
211
+ const mesh = new THREE.Mesh(geom, material);
45
212
  mesh.castShadow = p.kind !== 'plane';
46
213
  mesh.receiveShadow = true;
214
+ // ADR-044 — flat color renders IMMEDIATELY above; a material's textures
215
+ // arrive async and patch the material in place once loaded (same "good
216
+ // default now, real thing when it's ready" shape as every other
217
+ // CDN-texture consumer in this SDK). A missing/renamed material name, or
218
+ // a failed fetch, silently keeps the flat color rather than erroring —
219
+ // this is cosmetic, not a thing worth surfacing as a broken scene.
220
+ const libEntry = p.material ? MATERIAL_LIBRARY[p.material] : undefined;
221
+ if (libEntry) {
222
+ const repeat = materialRepeatFor(p.kind, s, MATERIAL_TILE_UNIT[p.material] ?? 1);
223
+ void Promise.all([
224
+ loadMaterialTexture(libEntry.color, THREE.SRGBColorSpace),
225
+ loadMaterialTexture(libEntry.roughness, THREE.NoColorSpace),
226
+ ]).then(([colorTex, roughTex]) => {
227
+ // Cloned, not assigned directly — the cache shares ONE texture per
228
+ // url across every Part using this material, and `.repeat` is
229
+ // per-INSTANCE (a 1×1 block and a 10×10 platform using the same
230
+ // "brick" material need different repeat counts). Assigning the
231
+ // cached texture directly would make every Part sharing a material
232
+ // fight over the last-set repeat value — the exact "clones share
233
+ // materials" trap `Skin.ts` already documents, one level up (here
234
+ // it's the TEXTURE being shared, not the material).
235
+ const map = colorTex.clone();
236
+ const roughnessMap = roughTex.clone();
237
+ map.repeat.copy(repeat);
238
+ roughnessMap.repeat.copy(repeat);
239
+ map.needsUpdate = true;
240
+ roughnessMap.needsUpdate = true;
241
+ material.map = map;
242
+ material.roughnessMap = roughnessMap;
243
+ material.needsUpdate = true;
244
+ }).catch(() => { });
245
+ }
47
246
  return mesh;
48
247
  }
49
248
  /**
@@ -320,23 +519,30 @@ export async function loadScene3D(scene3d, manifest, opts = {}) {
320
519
  const g = scene3d.gravity ?? { x: 0, y: -9.81, z: 0 };
321
520
  world = new opts.rapier.World(g);
322
521
  for (const e of scene3d.entities) {
323
- if (!e.collider)
522
+ // ADR-043 — a primitive Part gets physics even with no collider
523
+ // explicitly authored (an editor-placed Block should be standable on
524
+ // the moment it's dropped). An explicit collider always wins; this
525
+ // only fills the gap for a primitive entity that has none.
526
+ const collider = e.collider ?? (e.primitive ? defaultColliderForPrimitive(e.primitive) : undefined);
527
+ if (!collider)
324
528
  continue;
325
529
  const R = opts.rapier;
326
530
  const p = e.transform.position;
327
- const off = e.collider.offset ?? { x: 0, y: 0, z: 0 };
328
- const desc = e.collider.body === 'fixed' ? R.RigidBodyDesc.fixed()
329
- : e.collider.body === 'kinematic' ? R.RigidBodyDesc.kinematicPositionBased()
531
+ const off = collider.offset ?? { x: 0, y: 0, z: 0 };
532
+ const desc = collider.body === 'fixed' ? R.RigidBodyDesc.fixed()
533
+ : collider.body === 'kinematic' ? R.RigidBodyDesc.kinematicPositionBased()
330
534
  : R.RigidBodyDesc.dynamic();
331
535
  desc.setTranslation(p.x + off.x, p.y + off.y, p.z + off.z);
332
536
  const q = e.transform.rotation ?? IDENTITY_QUAT;
333
537
  desc.setRotation({ x: q[0], y: q[1], z: q[2], w: q[3] });
334
538
  const body = world.createRigidBody(desc);
335
- const s = e.collider.shape;
539
+ const s = collider.shape;
336
540
  const shape = s.kind === 'box' ? R.ColliderDesc.cuboid(s.halfExtents.x, s.halfExtents.y, s.halfExtents.z)
337
541
  : s.kind === 'sphere' ? R.ColliderDesc.ball(s.radius)
338
542
  : s.kind === 'capsule' ? R.ColliderDesc.capsule(s.halfHeight, s.radius)
339
- : null;
543
+ : s.kind === 'cylinder' ? R.ColliderDesc.cylinder(s.halfHeight, s.radius)
544
+ : s.kind === 'convexHull' ? R.ColliderDesc.convexHull(flattenPoints(s.points))
545
+ : null;
340
546
  if (!shape)
341
547
  throw new Error(`entity '${e.id}': trimesh colliders are not supported yet`);
342
548
  world.createCollider(shape, body);
@@ -1,9 +1,9 @@
1
1
  import * as THREE from 'three';
2
2
  import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
3
- import { loadScene3D, loadModelAsset } from '../SceneLoader3D.js';
3
+ import { loadScene3D, loadModelAsset, makePrimitive } from '../SceneLoader3D.js';
4
4
  import { applySkin } from '../Skin.js';
5
5
  import { applyAttachments } from '../Attachments.js';
6
- import { singleModelManifest } from '../scene3d.js';
6
+ import { singleModelManifest, defaultColliderForPrimitive, groundRestOffset } from '../scene3d.js';
7
7
  import { TransformGizmo3D } from './TransformGizmo3D.js';
8
8
  import { closestPointOnLineToRay, raycastPlane, angleAroundAxis } from './gizmoMath.js';
9
9
  import { loadHud3DScene } from '../hud3d/HudRuntime3D.js';
@@ -393,6 +393,35 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
393
393
  scale: { x: o.scale.x, y: o.scale.y, z: o.scale.z },
394
394
  };
395
395
  };
396
+ // ADR-044 — test-only readback of a Part's live material state: whether
397
+ // its async-loaded textures actually landed (`hasMap`/`hasRoughnessMap`),
398
+ // what repeat they resolved to (proves `materialRepeatFor`'s size-based
399
+ // math reached the live object, not just that SOME texture loaded), and
400
+ // the map's own source url (proves the right material NAME resolved to
401
+ // the right CDN file). No pixel-level visual check is possible without a
402
+ // real screenshot; this is what a test CAN assert without one.
403
+ globalThis.__umicatPrimitiveMaterial =
404
+ (entityId) => {
405
+ const o = objectByEntity.get(entityId);
406
+ if (!o || !(o instanceof THREE.Mesh))
407
+ return null;
408
+ const mat = o.material;
409
+ const geom = o.geometry;
410
+ const posAttr = geom.getAttribute('position');
411
+ const uvAttr = geom.getAttribute('uv');
412
+ return {
413
+ hasMap: !!mat.map,
414
+ hasRoughnessMap: !!mat.roughnessMap,
415
+ mapRepeat: mat.map ? { x: mat.map.repeat.x, y: mat.map.repeat.y } : null,
416
+ mapUrl: mat.map?.source?.data?.currentSrc
417
+ ?? mat.map?.source?.data?.src ?? null,
418
+ vertexCount: posAttr ? posAttr.count : 0,
419
+ // 0 (no uv attribute at all — the pre-ADR-044 state for wedge/
420
+ // corner-wedge) vs a real count, matching position's, is exactly
421
+ // the distinction this exists to prove.
422
+ uvCount: uvAttr ? uvAttr.count : 0,
423
+ };
424
+ };
396
425
  // Test-only — the MAIN camera's current pose, for the desktop camera
397
426
  // controls test suite (left-select/right-look/WASD/QE) to assert against
398
427
  // without hand-deriving projection math — same posture as every other
@@ -801,6 +830,8 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
801
830
  return onPatchEntity3d(data);
802
831
  if (data.type === 'umicat:editor:dropModel3d')
803
832
  return onDropModel3d(data);
833
+ if (data.type === 'umicat:editor:dropPrimitive3d')
834
+ return onDropPrimitive3d(data);
804
835
  if (data.type === 'umicat:editor:deleteEntity3d')
805
836
  return onDeleteEntity3d(data);
806
837
  if (data.type === 'umicat:editor:setGizmoMode3d') {
@@ -885,7 +916,7 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
885
916
  console.warn('[umicat/editor] 3D patch failed:', m.entityId, error);
886
917
  window.parent.postMessage({ type: 'umicat:editor:patchApplied3d', entityId: m.entityId, ok: !error, error }, '*');
887
918
  };
888
- const object = objectByEntity.get(m.entityId);
919
+ let object = objectByEntity.get(m.entityId);
889
920
  if (!object)
890
921
  return done(`no entity '${m.entityId}' in the scene being shown`);
891
922
  if (m.patch?.position !== undefined) {
@@ -937,6 +968,63 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
937
968
  return done(e instanceof Error ? e.message : String(e));
938
969
  }
939
970
  }
971
+ if (m.patch?.primitive !== undefined) {
972
+ // Unlike skin (repaints the existing material in place), a size
973
+ // change means a DIFFERENT geometry — there is no "resize this
974
+ // BoxGeometry" in three.js, so this rebuilds the mesh via the same
975
+ // `makePrimitive` the drop handler and the normal scene load both
976
+ // use, and swaps it in. Color-only patches rebuild too rather than
977
+ // branching (one code path, and rebuilding for a color change is
978
+ // cheap — these are a handful of triangles).
979
+ const authored = sceneData?.entities.find((e) => e.id === m.entityId);
980
+ if (!authored?.primitive)
981
+ return done(`entity '${m.entityId}' is not a primitive Part`);
982
+ // `material: null` (explicit clear) and `material: undefined` (key
983
+ // omitted, don't touch) both arrive through the same patch bag, but
984
+ // the STORED entity only ever has `material` present-with-a-string
985
+ // or absent — `null` is a wire-only sentinel, never written to disk.
986
+ const { material: materialPatch, ...restPatch } = m.patch.primitive;
987
+ const merged = { ...authored.primitive, ...restPatch };
988
+ if (materialPatch === null)
989
+ delete merged.material;
990
+ else if (materialPatch !== undefined)
991
+ merged.material = materialPatch;
992
+ authored.primitive = merged;
993
+ const fresh = makePrimitive(authored);
994
+ fresh.position.copy(object.position);
995
+ fresh.quaternion.copy(object.quaternion);
996
+ fresh.scale.copy(object.scale);
997
+ fresh.castShadow = merged.kind !== 'plane';
998
+ fresh.receiveShadow = true;
999
+ if (object instanceof THREE.Mesh) {
1000
+ object.geometry.dispose();
1001
+ (Array.isArray(object.material) ? object.material : [object.material]).forEach((mat) => {
1002
+ // ADR-044 — `map`/`roughnessMap` on a Parts material are PER-
1003
+ // INSTANCE clones (`makePrimitive`'s own doc comment), never the
1004
+ // shared cached texture — `Material.dispose()` does not reach
1005
+ // into its own maps, so leaving this out would leak one texture
1006
+ // per rebuild (every resize/recolor of a materialed Part).
1007
+ const std = mat;
1008
+ std.map?.dispose();
1009
+ std.roughnessMap?.dispose();
1010
+ mat.dispose();
1011
+ });
1012
+ }
1013
+ scene?.remove(object);
1014
+ scene?.add(fresh);
1015
+ entityByObject.delete(object);
1016
+ entityByObject.set(fresh, m.entityId);
1017
+ 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.
1021
+ if (gizmo.attached === object) {
1022
+ gizmo.detach();
1023
+ gizmo.attach(fresh, camera);
1024
+ selectionBox.setFromObject(fresh);
1025
+ }
1026
+ object = fresh;
1027
+ }
940
1028
  done();
941
1029
  }
942
1030
  /**
@@ -994,6 +1082,52 @@ export async function runEditorDesignPlayer3D(renderer, opts = {}) {
994
1082
  manifest?.models?.push(modelAsset);
995
1083
  done(undefined, { x: object.position.x, y: object.position.y, z: object.position.z });
996
1084
  }
1085
+ /**
1086
+ * ADR-043 — ground-raycast placement for a built-in shape (Roblox-style
1087
+ * "Parts"), deliberately mirroring `onDropModel3d` almost line for line:
1088
+ * same ground-plane raycast, same registration into `entityByObject`/
1089
+ * `objectByEntity`/`scene` so the new object is immediately pickable and
1090
+ * draggable with ZERO changes to `pickEntityAt`/the gizmo (neither cares
1091
+ * how an object got into those maps).
1092
+ *
1093
+ * One real difference from a model drop: a Part needs a COLLIDER to be
1094
+ * useful as a building block, and the host has no way to know what
1095
+ * default this SDK would choose — so unlike `modelDropped3d` (which
1096
+ * never echoes the url back; the host already has it), this ack DOES
1097
+ * echo the derived `collider` so the host can persist the exact same
1098
+ * thing this live object was just given.
1099
+ */
1100
+ function onDropPrimitive3d(m) {
1101
+ const done = (error, position, collider) => {
1102
+ if (error)
1103
+ console.warn('[umicat/editor] 3D primitive drop failed:', m.entityId, error);
1104
+ window.parent.postMessage({ type: 'umicat:editor:primitiveDropped3d', entityId: m.entityId, ok: !error, error, position, collider }, '*');
1105
+ };
1106
+ if (!scene)
1107
+ return done('no scene loaded yet');
1108
+ if (objectByEntity.has(m.entityId))
1109
+ return done(`entity '${m.entityId}' already exists in this scene`);
1110
+ const worldPoint = raycastGroundPlane(m.x, m.y, 0);
1111
+ if (!worldPoint)
1112
+ return done('the drop point does not land on the ground plane (camera is looking edge-on)');
1113
+ // Sit the shape ON the ground rather than straddling it — see
1114
+ // `groundRestOffset`'s own doc comment.
1115
+ const restPosition = { x: worldPoint.x, y: worldPoint.y + groundRestOffset(m.primitive), z: worldPoint.z };
1116
+ const entity = { id: m.entityId, transform: { position: restPosition }, primitive: m.primitive };
1117
+ const object = makePrimitive(entity);
1118
+ object.position.set(restPosition.x, restPosition.y, restPosition.z);
1119
+ object.castShadow = m.primitive.kind !== 'plane';
1120
+ object.receiveShadow = true;
1121
+ scene.add(object);
1122
+ entityByObject.set(object, m.entityId);
1123
+ objectByEntity.set(m.entityId, object);
1124
+ const collider = defaultColliderForPrimitive(m.primitive);
1125
+ entity.collider = collider;
1126
+ // Keep this session's own closure state consistent with what the host
1127
+ // is about to write to disk — see onDropModel3d's matching comment.
1128
+ sceneData?.entities.push(entity);
1129
+ done(undefined, { x: object.position.x, y: object.position.y, z: object.position.z }, collider);
1130
+ }
997
1131
  /**
998
1132
  * Frees a subtree's GPU resources the same way the whole-scene `dispose()`
999
1133
  * in `SceneLoader3D.ts` does (geometry + material + every texture field a
package/dist/scene3d.d.ts CHANGED
@@ -47,6 +47,17 @@ export type ColliderShape = {
47
47
  kind: 'capsule';
48
48
  halfHeight: number;
49
49
  radius: number;
50
+ } | {
51
+ kind: 'cylinder';
52
+ halfHeight: number;
53
+ radius: number;
54
+ }
55
+ /** A convex hull of the given points — the right fit for an irregular
56
+ * solid (ADR-043's wedge/corner-wedge Parts) where Rapier has no native
57
+ * primitive shape of its own. */
58
+ | {
59
+ kind: 'convexHull';
60
+ points: Vec3[];
50
61
  }
51
62
  /** Static geometry only. Never use this for a dynamic body. */
52
63
  | {
@@ -89,11 +100,31 @@ export interface Entity3D {
89
100
  transform: Transform3D;
90
101
  /** Manifest asset id for a glTF model. */
91
102
  modelAssetId?: string;
92
- /** A built-in shape, for blocking out a scene before art exists. */
103
+ /**
104
+ * A built-in shape, for blocking out a scene before art exists — the
105
+ * data this platform's "Parts" editor UI places (ADR-043). `wedge` is a
106
+ * right-angle triangular-prism ramp (the slope rises from the `+z` edge
107
+ * to the `-z` edge); `corner-wedge` is a right pyramid whose apex sits
108
+ * above the `(-x,-z)` bottom corner rather than the centre (Roblox's
109
+ * `CornerWedgePart` shape) — see `wedgeVertices`/`cornerWedgeVertices`
110
+ * for the exact geometry both the renderer and the physics collider are
111
+ * built from.
112
+ */
93
113
  primitive?: {
94
- kind: 'box' | 'sphere' | 'plane' | 'cylinder';
114
+ kind: 'box' | 'sphere' | 'plane' | 'cylinder' | 'wedge' | 'corner-wedge';
95
115
  size?: Vec3;
96
116
  color?: string;
117
+ /**
118
+ * ADR-044 — a NAME from the built-in material library
119
+ * (`MATERIAL_LIBRARY` in `SceneLoader3D.ts`), not a URL: same
120
+ * convention as a model's `skin` (the SDK resolves it, nothing is
121
+ * authored per-scene). Omitted = flat `color` only, today's behavior
122
+ * — every Part authored before this field existed keeps rendering
123
+ * identically. `color` still applies when `material` is set (it
124
+ * tints the material's own color map, same as `MeshStandardMaterial`
125
+ * already does when both `color` and `map` are present).
126
+ */
127
+ material?: string;
97
128
  };
98
129
  collider?: Collider3D;
99
130
  /** Which clip to play on spawn, by SEMANTIC name — see `AnimationMap`. */
@@ -119,6 +150,50 @@ export interface Entity3D {
119
150
  */
120
151
  castShadow?: boolean;
121
152
  }
153
+ /**
154
+ * The 6 distinct vertices of a wedge (a right-angle triangular-prism ramp)
155
+ * sized `size` and centred on the entity's own origin, in the SAME local
156
+ * space `Transform3D.position` places the entity's origin at.
157
+ *
158
+ * Exported as plain data — not hidden inside the renderer — so the
159
+ * RENDERER (`SceneLoader3D.makePrimitive`, 8 triangular faces built from
160
+ * these 6 points) and the PHYSICS COLLIDER (`defaultColliderForPrimitive`,
161
+ * a convex hull of the same 6 points) can never silently disagree about
162
+ * the shape's extent — a renderer/collider mismatch on an irregular solid
163
+ * is exactly the kind of bug that only shows up as "I can walk partway
164
+ * into the ramp."
165
+ *
166
+ * The ramp's slope rises from `z = +size.z/2` (low edge, on the ground)
167
+ * to `z = -size.z/2` (the top ridge) — i.e. standing at `-z` looking
168
+ * toward `+z`, the ramp climbs toward you.
169
+ */
170
+ export declare function wedgeVertices(size: Vec3): Vec3[];
171
+ /**
172
+ * The 5 distinct vertices of a corner wedge — a right pyramid whose apex
173
+ * sits above the `(-x,-z)` bottom corner rather than the centre (Roblox's
174
+ * `CornerWedgePart`), same role as `wedgeVertices` above.
175
+ */
176
+ export declare function cornerWedgeVertices(size: Vec3): Vec3[];
177
+ /**
178
+ * How far ABOVE a ground point a dropped primitive's ORIGIN should sit so
179
+ * its bottom rests exactly on the ground, not half-buried in it (ADR-043 —
180
+ * every primitive is built centred on its own origin, same as three.js's
181
+ * own `BoxGeometry`/`SphereGeometry`/etc., so placing the origin straight
182
+ * at the raycast point would sink half the shape below y=0).
183
+ */
184
+ export declare function groundRestOffset(primitive: NonNullable<Entity3D['primitive']>): number;
185
+ /**
186
+ * The collider an editor-placed primitive gets when nothing was authored
187
+ * explicitly (ADR-043 — a Part is a building block, not a decoration; it
188
+ * should be stood on the moment it's dropped, matching every other 3D
189
+ * editor's default). `body: 'fixed'` — a dropped block behaves like static
190
+ * level geometry (Roblox's own Part default, Anchored), not a physics prop
191
+ * that would fall over or get pushed the instant the game boots.
192
+ *
193
+ * Only ever consulted when `Entity3D.collider` is absent — an explicitly
194
+ * authored collider (hand-written JSON, agent-authored) always wins.
195
+ */
196
+ export declare function defaultColliderForPrimitive(primitive: NonNullable<Entity3D['primitive']>): Collider3D;
122
197
  /**
123
198
  * Semantic clip name → the clip actually inside the model.
124
199
  *
package/dist/scene3d.js CHANGED
@@ -23,6 +23,89 @@
23
23
  * - **Colliders are explicit.** Using a render mesh as a dynamic collider is the
24
24
  * classic way to make a game that is correct and unplayably slow.
25
25
  */
26
+ /**
27
+ * The 6 distinct vertices of a wedge (a right-angle triangular-prism ramp)
28
+ * sized `size` and centred on the entity's own origin, in the SAME local
29
+ * space `Transform3D.position` places the entity's origin at.
30
+ *
31
+ * Exported as plain data — not hidden inside the renderer — so the
32
+ * RENDERER (`SceneLoader3D.makePrimitive`, 8 triangular faces built from
33
+ * these 6 points) and the PHYSICS COLLIDER (`defaultColliderForPrimitive`,
34
+ * a convex hull of the same 6 points) can never silently disagree about
35
+ * the shape's extent — a renderer/collider mismatch on an irregular solid
36
+ * is exactly the kind of bug that only shows up as "I can walk partway
37
+ * into the ramp."
38
+ *
39
+ * The ramp's slope rises from `z = +size.z/2` (low edge, on the ground)
40
+ * to `z = -size.z/2` (the top ridge) — i.e. standing at `-z` looking
41
+ * toward `+z`, the ramp climbs toward you.
42
+ */
43
+ export function wedgeVertices(size) {
44
+ const hw = size.x / 2, hh = size.y / 2, hd = size.z / 2;
45
+ return [
46
+ { x: -hw, y: -hh, z: -hd }, // 0 bottom-back-left
47
+ { x: hw, y: -hh, z: -hd }, // 1 bottom-back-right
48
+ { x: hw, y: -hh, z: hd }, // 2 bottom-front-right
49
+ { x: -hw, y: -hh, z: hd }, // 3 bottom-front-left
50
+ { x: -hw, y: hh, z: -hd }, // 4 top-back-left (ridge)
51
+ { x: hw, y: hh, z: -hd }, // 5 top-back-right (ridge)
52
+ ];
53
+ }
54
+ /**
55
+ * The 5 distinct vertices of a corner wedge — a right pyramid whose apex
56
+ * sits above the `(-x,-z)` bottom corner rather than the centre (Roblox's
57
+ * `CornerWedgePart`), same role as `wedgeVertices` above.
58
+ */
59
+ export function cornerWedgeVertices(size) {
60
+ const hw = size.x / 2, hh = size.y / 2, hd = size.z / 2;
61
+ return [
62
+ { x: -hw, y: -hh, z: -hd }, // 0 bottom-back-left
63
+ { x: hw, y: -hh, z: -hd }, // 1 bottom-back-right
64
+ { x: hw, y: -hh, z: hd }, // 2 bottom-front-right
65
+ { x: -hw, y: -hh, z: hd }, // 3 bottom-front-left
66
+ { x: -hw, y: hh, z: -hd }, // 4 apex, above corner 0
67
+ ];
68
+ }
69
+ /**
70
+ * How far ABOVE a ground point a dropped primitive's ORIGIN should sit so
71
+ * its bottom rests exactly on the ground, not half-buried in it (ADR-043 —
72
+ * every primitive is built centred on its own origin, same as three.js's
73
+ * own `BoxGeometry`/`SphereGeometry`/etc., so placing the origin straight
74
+ * at the raycast point would sink half the shape below y=0).
75
+ */
76
+ export function groundRestOffset(primitive) {
77
+ const s = primitive.size ?? { x: 1, y: 1, z: 1 };
78
+ // A plane is zero-thickness and already flush at its own origin.
79
+ if (primitive.kind === 'plane')
80
+ return 0;
81
+ if (primitive.kind === 'sphere')
82
+ return s.x / 2;
83
+ // box / cylinder / wedge / corner-wedge are all centred on the Y axis
84
+ // the same way (`wedgeVertices`/`cornerWedgeVertices` run -hh..+hh too).
85
+ return s.y / 2;
86
+ }
87
+ /**
88
+ * The collider an editor-placed primitive gets when nothing was authored
89
+ * explicitly (ADR-043 — a Part is a building block, not a decoration; it
90
+ * should be stood on the moment it's dropped, matching every other 3D
91
+ * editor's default). `body: 'fixed'` — a dropped block behaves like static
92
+ * level geometry (Roblox's own Part default, Anchored), not a physics prop
93
+ * that would fall over or get pushed the instant the game boots.
94
+ *
95
+ * Only ever consulted when `Entity3D.collider` is absent — an explicitly
96
+ * authored collider (hand-written JSON, agent-authored) always wins.
97
+ */
98
+ export function defaultColliderForPrimitive(primitive) {
99
+ const s = primitive.size ?? { x: 1, y: 1, z: 1 };
100
+ const shape = primitive.kind === 'box' ? { kind: 'box', halfExtents: { x: s.x / 2, y: s.y / 2, z: s.z / 2 } }
101
+ : primitive.kind === 'sphere' ? { kind: 'sphere', radius: s.x / 2 }
102
+ : primitive.kind === 'cylinder' ? { kind: 'cylinder', halfHeight: s.y / 2, radius: s.x / 2 }
103
+ // A ground/wall sheet with zero thickness has nothing for Rapier to
104
+ // represent — give it a thin slab so it still blocks.
105
+ : primitive.kind === 'plane' ? { kind: 'box', halfExtents: { x: s.x / 2, y: 0.05, z: s.z / 2 } }
106
+ : { kind: 'convexHull', points: primitive.kind === 'wedge' ? wedgeVertices(s) : cornerWedgeVertices(s) };
107
+ return { shape, body: 'fixed' };
108
+ }
26
109
  /**
27
110
  * Order six faces named the way skybox packs name them.
28
111
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umicat/three-sdk",
3
- "version": "1.6.0",
3
+ "version": "1.8.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",