@wildshard/sdk 0.3.0 → 0.3.2

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.
Files changed (61) hide show
  1. package/GUIDE.md +10 -2
  2. package/docs/api/EXPORT-TIERS.md +7 -4
  3. package/lint/export-tiers.json +3 -0
  4. package/lint/host-callbacks.mjs +1 -1
  5. package/package.json +9 -5
  6. package/scripts/bake/template-skins.mjs +6 -3
  7. package/scripts/bake/template-warden.mjs +25 -0
  8. package/scripts/export-ci21-guests.mjs +89 -0
  9. package/scripts/scratch-sweep.mjs +3 -1
  10. package/src/cli/hero/hero.ts +45 -2
  11. package/src/sharddev/as/prelude.ts +67 -0
  12. package/src/sharddev/authorLint.ts +45 -0
  13. package/src/sharddev/bake/compileScript.ts +6 -0
  14. package/src/sharddev/bake/terrain.ts +11 -2
  15. package/src/sharddev/checkProject.ts +7 -18
  16. package/src/sharddev/engineMusic.ts +23 -0
  17. package/src/sharddev/materials.ts +7 -3
  18. package/src/sharddev/project.ts +5 -0
  19. package/src/sharddev/refusals.ts +1 -1
  20. package/src/sharddev/scene/author.ts +116 -11
  21. package/src/sharddev/scene/canvas.ts +2 -3
  22. package/src/sharddev/scene/description.ts +55 -2
  23. package/src/sharddev/scene/lower.ts +144 -29
  24. package/src/sharddev/scene/shard.ts +5 -2
  25. package/src/sharddev/scene/shardfile.ts +385 -72
  26. package/src/sharddev/watch/page.ts +116 -29
  27. package/src/sharddev/watch/pageEntry.ts +38 -2
  28. package/src/sharddev/watch/parity-baseline.json +22 -0
  29. package/src/sharddev/watch/parity.mjs +168 -0
  30. package/src/sharddev/watch/proof.mjs +129 -22
  31. package/src/sharddev/watch/protocol.ts +66 -8
  32. package/src/sharddev/watch/watch.ts +215 -51
  33. package/src/shards/_template/assets/3058c100bc477fd6fe8268f33b53756b8a2556e7e41c58b2216c703ca7b042c6 +1 -0
  34. package/src/shards/_template/assets/8a0440f392737a31cf0926a3c7dc011c320144972882945a5462c893e817d94a +0 -0
  35. package/src/shards/_template/behaviour/door.as +16 -26
  36. package/src/shards/_template/card/landscape.jpg +0 -0
  37. package/src/shards/_template/card/portrait.jpg +0 -0
  38. package/src/shards/_template/card/thumb.jpg +0 -0
  39. package/src/shards/_template/data/clientScripts.json +43 -43
  40. package/src/shards/_template/data/creatures.json +2 -2
  41. package/src/shards/_template/data/look.json +141 -13
  42. package/src/shards/_template/data/rows.json +20 -2
  43. package/src/shards/_template/data/skins.json +32 -0
  44. package/src/shards/_template/data/water.json +18 -0
  45. package/src/shards/_template/generators/product.ts +5 -1
  46. package/src/shards/_template/generators/warden.ts +273 -0
  47. package/src/shards/_template/generators/world.ts +52 -21
  48. package/src/shards/_template/hero.json +6 -6
  49. package/src/shards/authoring-slice/generators/shard.ts +9 -1
  50. package/src/shards/authoring-slice/generators/sky.ts +64 -0
  51. package/src/shards/authoring-slice/generators/template-sky.ts +27 -0
  52. package/src/shards/authoring-slice/generators/textures.ts +59 -0
  53. package/src/shards/authoring-slice/generators/world.ts +108 -5
  54. package/src/shards/mossgate/generators/shard.ts +6 -0
  55. package/src/shards/mossgate/generators/sky.ts +64 -0
  56. package/src/shards/mossgate/generators/textures.ts +249 -0
  57. package/src/shards/mossgate/generators/world.ts +998 -0
  58. package/src/shards/mossgate/shard.config.ts +7 -0
  59. package/scripts/shard-output-report.d.mts +0 -9
  60. package/scripts/shard-output-report.mjs +0 -85
  61. package/scripts/shard-platform-cli.mjs +0 -93
@@ -1,11 +1,14 @@
1
1
  import {
2
- AdditiveBlending, AmbientLight, BackSide, Box3, DataTexture, DirectionalLight, DoubleSide, Fog, FogExp2, Group, HemisphereLight, InstancedMesh, Line, Matrix4,
3
- Mesh, MeshBasicMaterial, MeshStandardMaterial, type Object3D, PointLight, Points, Quaternion, Scene, SpotLight, Sprite, SpriteMaterial, Vector3,
4
- type BufferAttribute, type BufferGeometry, type Color, type InterleavedBufferAttribute, type Material, type Texture,
2
+ AdditiveBlending, AmbientLight, BackSide, Box3, DataTexture, DirectionalLight, DoubleSide, Fog, FrontSide, FogExp2, Group, HemisphereLight, InstancedMesh, Line, Matrix4,
3
+ Mesh, MeshBasicMaterial, MeshStandardMaterial, type Object3D, PointLight, Points, PointsMaterial, Quaternion, Scene, SpotLight, Sprite, SpriteMaterial, Vector3,
4
+ type BufferAttribute, type BufferGeometry, Color, type InterleavedBufferAttribute, Material, ShaderMaterial, type Texture,
5
5
  } from 'three';
6
- import { isSolid, paintedPixels, Water, type ShardWorld } from './author';
6
+ import { vec3 } from 'three/tsl';
7
+ import { GraphMaterial, graph, isCatalogueMaterial, meshMap, type GraphValue } from '../materials';
8
+ import { LOOK_SKY_BUDGET } from '@wildshard/format/look-sky';
9
+ import { isSolid, motionOf, paintedPixels, Water, type ShardWorld } from './author';
7
10
  import type {
8
- Rgb, SceneCollider, SceneDraw, SceneGeometry, SceneGround, SceneLight, SceneLook, SceneMaterial, ScenePart, ScenePost, SceneSprite, SceneTexture,
11
+ Rgb, SceneCollider, SceneDraw, SceneSky, SceneGeometry, SceneGround, SceneLight, SceneLook, SceneMaterial, SceneMotion, ScenePart, ScenePoints, ScenePost, SceneSprite, SceneTexture,
9
12
  SceneWater, ShardIdentityInput, ShardScene, Vec3,
10
13
  } from './description';
11
14
  import { ContentHash, hashOf } from './hash';
@@ -17,6 +20,10 @@ import { ContentHash, hashOf } from './hash';
17
20
  */
18
21
 
19
22
  /** A refusal: the object's path and the fix. */
23
+ /** ss4d: whether a graph material entry samples the mesh's own map (a `meshMap` node in its graph). */
24
+ const readsMeshMap = (entry: object): boolean =>
25
+ Object.values((entry as { graph?: { nodes?: Record<string, { op?: string }> } }).graph?.nodes ?? {}).some((node) => node.op === 'meshMap');
26
+
20
27
  export class SceneRefusalError extends Error {
21
28
  constructor(path: string, problem: string, fix: string) { super(`scene: ${path}: ${problem}. ${fix}`); this.name = 'SceneRefusalError'; }
22
29
  }
@@ -52,6 +59,8 @@ function lowerGeometry(geometry: BufferGeometry, path: string, tables: Tables):
52
59
  return key;
53
60
  }
54
61
 
62
+ /** A painted array's texture key per colour space (an array is never written after it is painted). */
63
+ const PIXEL_KEYS = new WeakMap<Uint8Array, Partial<Record<'srgb' | 'linear', string>>>();
55
64
  function lowerTexture(texture: Texture, path: string, tables: Tables): string {
56
65
  const known = tables.textureKeys.get(texture); if (known !== undefined) return known;
57
66
  let pixels = paintedPixels(texture.source);
@@ -61,21 +70,59 @@ function lowerTexture(texture: Texture, path: string, tables: Tables): string {
61
70
  }
62
71
  if (pixels === undefined) throw new SceneRefusalError(path, `texture ${texture.name || texture.constructor.name} has no pixels at compile time`, 'Paint it with paint(width, height, fn) from @wildshard/sdk/scene/shard (a CanvasTexture needs a browser), or hand in an RGBA8 DataTexture');
63
72
  const colourSpace = texture.colorSpace === 'srgb' ? 'srgb' : 'linear';
64
- const key = `t${hashOf((h) => { h.numbers([pixels.width, pixels.height]).text(colourSpace).bytes(pixels.rgba); })}`;
73
+ // AP17: a watched revision's memoised paint hands back the same pixel array, so its hash is kept by that array
74
+ const cached = PIXEL_KEYS.get(pixels.rgba)?.[colourSpace], { rgba, width, height } = pixels;
75
+ const key = cached ?? `t${hashOf((h) => { h.numbers([width, height]).text(colourSpace).bytes(rgba); })}`;
76
+ if (cached === undefined) PIXEL_KEYS.set(rgba, { ...PIXEL_KEYS.get(rgba), [colourSpace]: key });
65
77
  if (!tables.textures.has(key)) tables.textures.set(key, { key, width: pixels.width, height: pixels.height, rgba: pixels.rgba, colourSpace });
66
78
  tables.textureKeys.set(texture, key);
67
79
  return key;
68
80
  }
69
81
 
82
+ interface NodeSlots { readonly isNodeMaterial?: boolean; readonly isMeshBasicNodeMaterial?: boolean; readonly map?: Texture | null; readonly [slot: string]: unknown }
83
+ const isNodeMaterial = (material: Material): boolean => Reflect.get(material, 'isNodeMaterial') === true;
84
+ /** AP13: a three.js node material (`MeshStandardNodeMaterial`, `MeshBasicNodeMaterial`) as one material graph: its TSL slots
85
+ * go through `graph()`, its plain numbers stand where a slot is empty. A slot the graph has no stage for is refused. */
86
+ function nodeMaterialGraph(material: Material, path: string): GraphMaterial {
87
+ const m = material as Material & NodeSlots & { color?: Color; emissive?: Color; roughness?: number; metalness?: number };
88
+ for (const slot of ['positionNode', 'normalNode', 'outputNode', 'fragmentNode', 'vertexNode', 'castShadowNode', 'receivedShadowNode', 'aoNode', 'lightsNode', 'envNode']) {
89
+ if (m[slot] !== null && m[slot] !== undefined) throw new SceneRefusalError(path, `its ${slot} has no graph stage`, 'Use colorNode, emissiveNode, roughnessNode, metalnessNode and opacityNode, or write the whole surface with graph() in a GraphMaterial');
90
+ }
91
+ const value = (node: unknown, fallback: GraphValue): GraphValue => (node === null || node === undefined ? fallback : node as GraphValue);
92
+ const c = m.color ?? new Color(1, 1, 1), e = m.emissive ?? new Color(0, 0, 0);
93
+ const unlit = m.isMeshBasicNodeMaterial === true;
94
+ // ss4d: a node material's own `map` (three draws map x color when colorNode is empty) is the mesh's colour map: the
95
+ // graph reads it as `meshMap`, the shard binds the lowered texture to it (props.materials `colour`)
96
+ const mapped = m.map !== null && m.map !== undefined, empty = (slot: string): boolean => m[slot] === null || m[slot] === undefined;
97
+ const cutsOrBlends = material.transparent || material.alphaTest > 0;
98
+ const surface = {
99
+ colour: value(m['colorNode'], mapped ? meshMap.rgb.mul(vec3(c.r, c.g, c.b)) : [c.r, c.g, c.b]),
100
+ ...(unlit ? {} : { emissive: value(m['emissiveNode'], [e.r, e.g, e.b]), roughness: value(m['roughnessNode'], m.roughness ?? 1), metalness: value(m['metalnessNode'], m.metalness ?? 0) }),
101
+ ...(!empty('opacityNode') ? { alpha: value(m['opacityNode'], 1) } : mapped && empty('colorNode') && cutsOrBlends ? { alpha: meshMap.a.mul(material.opacity) } : {}),
102
+ ...(material.alphaTest > 0 ? { alphaCutoff: material.alphaTest } : {}),
103
+ };
104
+ return new GraphMaterial(graph({ model: unlit ? 'unlit' : 'standard', doubleSided: material.side === DoubleSide, surface }));
105
+ }
106
+
70
107
  function lowerMaterial(material: Material, path: string, tables: Tables): string {
71
108
  const known = tables.materialKeys.get(material); if (known !== undefined) return known;
109
+ // AP13: shaders are TSL; raw GLSL never reaches a shard file
110
+ if (material instanceof ShaderMaterial) throw new SceneRefusalError(path, `a ${material.type} is raw GLSL`, 'Write the shader in TSL and draw it with new GraphMaterial(graph({ surface: { colour } })) from @wildshard/sdk/materials');
111
+ const catalogue = isCatalogueMaterial(material) ? material.toMaterialEntry() : isNodeMaterial(material) ? nodeMaterialGraph(material, path).toMaterialEntry() : null;
112
+ if (catalogue === null && material.onBeforeCompile !== Material.prototype.onBeforeCompile) throw new SceneRefusalError(path, 'its onBeforeCompile patches GLSL', 'Write the change in TSL as a GraphMaterial (graph() from @wildshard/sdk/materials), or declare it with animate() if it is motion');
72
113
  let kind: SceneMaterial['kind'];
73
114
  if (material instanceof MeshStandardMaterial) kind = 'standard';
74
115
  else if (material instanceof MeshBasicMaterial) kind = 'basic';
75
116
  else if (material instanceof SpriteMaterial) kind = 'sprite';
76
- else throw new SceneRefusalError(path, `${material.type} has no lowering yet`, 'Use MeshStandardMaterial or MeshBasicMaterial; node (TSL) materials arrive with AP13');
77
- const m = material as MeshStandardMaterial & MeshBasicMaterial & SpriteMaterial;
78
- const map = m.map === null || m.map === undefined ? null : lowerTexture(m.map, path, tables);
117
+ else if (material instanceof PointsMaterial) kind = 'points';
118
+ else if (catalogue !== null) kind = 'standard';
119
+ else throw new SceneRefusalError(path, `${material.type} has no lowering yet`, 'Use MeshStandardMaterial, MeshBasicMaterial, a node material or a GraphMaterial (TSL through graph())');
120
+ if (material instanceof PointsMaterial && !material.sizeAttenuation) throw new SceneRefusalError(path, 'a Points cloud sized in pixels has no lowering', 'Leave sizeAttenuation on: a point is a card `size` metres across');
121
+ const m = material as MeshStandardMaterial & MeshBasicMaterial & SpriteMaterial & PointsMaterial;
122
+ // ss4d: a graph draws only what it samples: a map reaches the shard (its props.materials `colour`) only when the graph
123
+ // reads the mesh map (a node material's colorNode replaces its map, as in three)
124
+ const sampled = catalogue === null || (catalogue as { family?: string }).family !== 'graph' || readsMeshMap(catalogue);
125
+ const map = m.map === null || m.map === undefined || !sampled ? null : lowerTexture(m.map, path, tables);
79
126
  const standard = material instanceof MeshStandardMaterial;
80
127
  const fields: Omit<SceneMaterial, 'key' | 'name'> = {
81
128
  kind, colour: rgb(m.color), roughness: standard ? m.roughness : 1, metalness: standard ? m.metalness : 0,
@@ -84,6 +131,9 @@ function lowerMaterial(material: Material, path: string, tables: Tables): string
84
131
  alphaTest: material.alphaTest, side: material.side === DoubleSide ? 'double' : material.side === BackSide ? 'back' : 'front',
85
132
  vertexColours: material.vertexColors, transparent: material.transparent, opacity: material.opacity,
86
133
  blending: material.blending === AdditiveBlending ? 'additive' : 'normal', depthWrite: material.depthWrite, fog: m.fog !== false,
134
+ polygonOffset: material.polygonOffset ? material.polygonOffsetFactor : 0,
135
+ pointSize: material instanceof PointsMaterial ? material.size : 0,
136
+ entry: catalogue,
87
137
  };
88
138
  const key = `m${hashOf((h) => h.json(fields))}`;
89
139
  if (!tables.materials.has(key)) tables.materials.set(key, { key, name: material.name === '' ? key : material.name, ...fields });
@@ -109,8 +159,31 @@ function colliderOf(path: string, matrix: Matrix4, box: Box3): SceneCollider {
109
159
  return { path, kind: 'cuboid', centre: v3(world), half: [Math.abs(size.x * scale.x) / 2, Math.abs(size.y * scale.y) / 2, Math.abs(size.z * scale.z) / 2], rotation: [rotation.x, rotation.y, rotation.z, rotation.w] };
110
160
  }
111
161
 
112
- function lowerPart(root: Object3D, tables: Tables): ScenePart {
113
- const draws: SceneDraw[] = [], sprites: SceneSprite[] = [], lights: SceneLight[] = [], colliders: SceneCollider[] = [], water: SceneWater[] = [];
162
+ const CARD_MOTIONS: ReadonlySet<string> = new Set(['pulse', 'drift', 'rise']), MESH_MOTIONS: ReadonlySet<string> = new Set(['sway', 'uvScroll']), LIGHT_MOTIONS: ReadonlySet<string> = new Set(['flicker']);
163
+ /** The motion `object` takes (AP12): one declared on it must fit what it is (else a refusal by path); one declared on a
164
+ * group reaches only the objects it fits (a fire's group pulses its cards and flickers its light). */
165
+ function fitMotion(object: Object3D, root: Object3D, path: string, kinds: ReadonlySet<string>, what: string): SceneMotion | null {
166
+ const own = motionOf(object, object);
167
+ if (own !== null && !kinds.has(own.kind)) throw new SceneRefusalError(path, `${own.kind} does not move a ${what}`, 'flicker moves a PointLight; pulse, drift and rise move a Sprite or Points; sway and uvScroll move a mesh. spin and bob need moving parts: an engine row after M2');
168
+ if (own !== null) return own;
169
+ const inherited = object.parent === null || object === root ? null : motionOf(object.parent, root);
170
+ return inherited !== null && kinds.has(inherited.kind) ? inherited : null;
171
+ }
172
+
173
+ /**
174
+ * ss4d: a graph material (TSL, a node material, a catalogue entry) is its own whole surface: the engine draws its graph
175
+ * and nothing of the scene's card or motion rows, so a card or a declared motion on one would be dropped. Refused by
176
+ * path, never dropped: a card is a SpriteMaterial or a PointsMaterial; a graph moves in its own `vertex.offset` stage.
177
+ */
178
+ function refuseGraphMotion(path: string, key: string, tables: Tables, what: string): void {
179
+ if (tables.materials.get(key)?.entry === null) return;
180
+ throw new SceneRefusalError(path, what === 'card' ? 'a graph material has no card (a camera-facing quad)' : `a graph material does not take a declared ${what}`,
181
+ what === 'card' ? 'Draw a Sprite or Points with a SpriteMaterial or PointsMaterial (its map, colour and blending), or a plain Mesh with the graph'
182
+ : 'Move it in the graph: vertex: { offset } over graphInputs.windTime (sway) or a uv over time (uvScroll), or draw it with a MeshStandardMaterial');
183
+ }
184
+
185
+ function lowerPart(root: Object3D, tables: Tables, panel?: string): ScenePart {
186
+ const draws: SceneDraw[] = [], sprites: SceneSprite[] = [], lights: SceneLight[] = [], colliders: SceneCollider[] = [], water: SceneWater[] = [], points: ScenePoints[] = [];
114
187
  const visit = (object: Object3D): void => {
115
188
  const path = pathOf(object, root);
116
189
  if (!object.visible) {
@@ -120,12 +193,12 @@ function lowerPart(root: Object3D, tables: Tables): ScenePart {
120
193
  }
121
194
  if (object instanceof Water) {
122
195
  // the format holds at most 64 outline points: 48 evenly spaced along the shape
123
- const points = object.shape.getSpacedPoints(48).slice(0, 48).map((p) => new Vector3(p.x, p.y, 0).applyMatrix4(object.matrixWorld));
196
+ const outline = object.shape.getSpacedPoints(48).slice(0, 48).map((p) => new Vector3(p.x, p.y, 0).applyMatrix4(object.matrixWorld));
124
197
  const geometry = object.geometry, position = geometry.getAttribute('position'), index = geometry.getIndex(), n = index?.count ?? position.count;
125
198
  const triangles = new Float32Array(n * 3);
126
199
  for (let i = 0; i < n; i++) { const p = new Vector3().fromBufferAttribute(position, index?.getX(i) ?? i).applyMatrix4(object.matrixWorld); triangles.set([p.x, p.y, p.z], i * 3); }
127
200
  const level = new Vector3().setFromMatrixPosition(object.matrixWorld).y;
128
- water.push({ path, outline: points.map((p) => [p.x, p.z] as const), level, tint: rgb(object.material.color), reflect: object.reflect, triangles });
201
+ water.push({ path, outline: outline.map((p) => [p.x, p.z] as const), level, tint: rgb(object.material.color), reflect: object.reflect, triangles });
129
202
  return;
130
203
  }
131
204
  if (object instanceof Mesh) {
@@ -143,36 +216,54 @@ function lowerPart(root: Object3D, tables: Tables): ScenePart {
143
216
  } else if (isSolid(object)) {
144
217
  object.geometry.computeBoundingBox(); colliders.push(colliderOf(path, object.matrixWorld, object.geometry.boundingBox ?? new Box3()));
145
218
  }
146
- draws.push({ path, geometry, material, matrix: [...object.matrixWorld.elements], instances, castShadow: object.castShadow, receiveShadow: object.receiveShadow });
219
+ const motion = fitMotion(object, root, path, MESH_MOTIONS, 'mesh');
220
+ if (motion !== null) refuseGraphMotion(path, material, tables, motion.kind);
221
+ draws.push({ path, geometry, material, matrix: [...object.matrixWorld.elements], instances, castShadow: object.castShadow, receiveShadow: object.receiveShadow, motion });
147
222
  } else if (object instanceof Sprite) {
148
223
  const material = lowerMaterial(object.material, path, tables), scale = new Vector3().setFromMatrixScale(object.matrixWorld);
149
- sprites.push({ path, material, position: v3(new Vector3().setFromMatrixPosition(object.matrixWorld)), scale: [scale.x, scale.y], center: [object.center.x, object.center.y] });
224
+ refuseGraphMotion(path, material, tables, 'card');
225
+ sprites.push({ path, material, position: v3(new Vector3().setFromMatrixPosition(object.matrixWorld)), scale: [scale.x, scale.y], center: [object.center.x, object.center.y], motion: fitMotion(object, root, path, CARD_MOTIONS, 'Sprite') });
150
226
  } else if (object instanceof PointLight || object instanceof DirectionalLight || object instanceof HemisphereLight || object instanceof AmbientLight) {
151
227
  const position = v3(new Vector3().setFromMatrixPosition(object.matrixWorld));
152
228
  const kind: SceneLight['kind'] = object instanceof PointLight ? 'point' : object instanceof DirectionalLight ? 'directional' : object instanceof HemisphereLight ? 'hemisphere' : 'ambient';
153
229
  lights.push({ path, kind, colour: rgb(object.color), groundColour: object instanceof HemisphereLight ? rgb(object.groundColor) : null, intensity: object.intensity,
154
230
  distance: object instanceof PointLight ? object.distance : 0, decay: object instanceof PointLight ? object.decay : 0, position,
155
- target: object instanceof DirectionalLight ? v3(object.target.getWorldPosition(new Vector3())) : null, castShadow: object.castShadow });
231
+ target: object instanceof DirectionalLight ? v3(object.target.getWorldPosition(new Vector3())) : null, castShadow: object.castShadow,
232
+ motion: object instanceof PointLight ? fitMotion(object, root, path, LIGHT_MOTIONS, 'light') : null });
156
233
  } else if (object instanceof SpotLight) {
157
234
  throw new SceneRefusalError(path, 'SpotLight has no lowering yet', 'Use a PointLight; spot lamps are an engine row after M1');
158
- } else if (object instanceof Points || object instanceof Line) {
159
- throw new SceneRefusalError(path, `${object.type} has no lowering yet`, 'Motes and lines arrive with AP11; leave them out of the part until then');
235
+ } else if (object instanceof Points) {
236
+ // AP11: each point a camera-facing card; the cloud keeps its own motion (drift, rise)
237
+ if (Array.isArray(object.material)) throw new SceneRefusalError(path, 'it has several materials', 'Give a Points cloud one PointsMaterial');
238
+ const material = lowerMaterial(object.material, path, tables), position = object.geometry.getAttribute('position');
239
+ refuseGraphMotion(path, material, tables, 'card');
240
+ if (position === undefined) throw new SceneRefusalError(path, 'its geometry has no position', 'Give the cloud a position attribute');
241
+ const seats = new Float32Array(position.count * 3), p = new Vector3();
242
+ for (let i = 0; i < position.count; i++) { p.fromBufferAttribute(position, i).applyMatrix4(object.matrixWorld); seats.set([p.x, p.y, p.z], i * 3); }
243
+ points.push({ path, material, positions: seats, motion: fitMotion(object, root, path, CARD_MOTIONS, 'Points cloud') });
244
+ } else if (object instanceof Line) {
245
+ throw new SceneRefusalError(path, `${object.type} has no lowering yet`, 'Draw a line as a thin mesh (a TubeGeometry)');
160
246
  } else if (isSolid(object)) {
161
247
  colliders.push(colliderOf(path, new Matrix4(), new Box3().setFromObject(object))); // a solid group is one world box; its meshes still draw
162
248
  }
163
249
  for (const child of object.children) visit(child);
164
250
  };
165
251
  visit(root);
166
- const materials = [...new Set([...draws.map((d) => d.material), ...sprites.map((s) => s.material)])];
252
+ const materials = [...new Set([...draws.map((d) => d.material), ...sprites.map((s) => s.material), ...points.map((c) => c.material)])];
167
253
  const textures = [...new Set(materials.map((key) => tables.materials.get(key)?.map).filter((key): key is string => typeof key === 'string'))];
168
254
  const geometries = [...new Set(draws.map((d) => d.geometry))];
169
- const hash = new ContentHash().text(root.name);
255
+ const hash = new ContentHash().text(root.name).text(panel ?? '');
256
+ // AP16: a panel is meshes and solids, the things a state row can hide; anything else would stay when it hides
257
+ if (panel !== undefined && sprites.length + points.length + lights.length + water.length > 0) throw new SceneRefusalError(root.name, 'a panel part holds meshes and solids only (its sprites, points, lights and water would not hide with it)', 'Put them in a part of their own');
258
+ // a panel is a library model, which carries no tile motion: a moving mesh would stand still
259
+ if (panel !== undefined && draws.some((d) => d.motion !== null)) throw new SceneRefusalError(root.name, 'a panel part cannot move (sway, flicker, pulse or uvScroll)', 'Put the moving meshes in a part of their own');
170
260
  for (const draw of draws) {
171
- hash.text(draw.geometry).text(draw.material).numbers(draw.matrix).numbers([draw.castShadow ? 1 : 0, draw.receiveShadow ? 1 : 0]);
261
+ hash.text(draw.geometry).text(draw.material).numbers(draw.matrix).numbers([draw.castShadow ? 1 : 0, draw.receiveShadow ? 1 : 0]).json(draw.motion);
172
262
  if (draw.instances !== null) { hash.bytes(draw.instances.matrices); if (draw.instances.colours !== null) hash.bytes(draw.instances.colours); }
173
263
  }
174
264
  hash.json(sprites).json(lights).json(colliders).json(water.map((w) => ({ ...w, triangles: [...w.triangles] })));
175
- return { name: root.name, hash: hash.hex(), draws, sprites, lights, colliders, water, materials, textures, geometries };
265
+ for (const cloud of points) hash.text(cloud.material).bytes(cloud.positions).json(cloud.motion);
266
+ return { name: root.name, hash: hash.hex(), ...(panel === undefined ? {} : { panel }), draws, sprites, points, lights, colliders, water, materials, textures, geometries };
176
267
  }
177
268
 
178
269
  function groundHash(heightAt: (x: number, z: number) => number, colourAt: SceneGround['colourAt']): string {
@@ -185,17 +276,41 @@ const DEFAULT_POST: ScenePost = { tone: 'aces', exposure: 1, bloom: null, vignet
185
276
 
186
277
  /** Run the author's build on a fresh scene and read it. Parts come in authored order; `scene` holds anything outside one. */
187
278
  export function lowerShard(identity: ShardIdentityInput, build: (world: ShardWorld) => void): ShardScene {
188
- const scene = new Scene(), parts: Group[] = [];
279
+ const scene = new Scene(), parts: Group[] = [], panels = new Map<Object3D, string>();
280
+ let sky: SceneSky | null = null;
189
281
  let ground: SceneGround | null = null, post: ScenePost | null = null, spawn: ShardScene['spawn'] = { position: [0, 0, 0], yaw: 0 };
190
282
  const world: ShardWorld = {
191
283
  scene,
192
- part: (name, fill) => {
284
+ part: (name, fill, options = {}) => {
193
285
  if (!/^[a-z][a-z0-9-]{0,63}$/u.test(name)) throw new SceneRefusalError(name, 'a part name must be kebab-case', 'Name it like `hut` or `pond-lamps`');
194
286
  if (name === 'scene' || parts.some((p) => p.name === name)) throw new SceneRefusalError(name, 'two parts share this name', 'Give every world.part its own name');
195
- const group = new Group(); group.name = name; parts.push(group); scene.add(group); fill(group); return group;
287
+ const { panel } = options;
288
+ // AP16: the format's panel id (props `id`), one part each, at most 64 (props.panels)
289
+ // a panel's collider takes its id, so it may not look like a part's collider (`scene.<part>`)
290
+ if (panel !== undefined && (!/^[a-z][a-z0-9.-]{0,127}$/u.test(panel) || panel.startsWith('scene.'))) throw new SceneRefusalError(name, `panel id ${panel} is not a shardfile id`, 'Name it like `brasscap.gate`: lower case, digits, dots and dashes');
291
+ if (panel !== undefined && [...panels.values()].includes(panel)) throw new SceneRefusalError(name, `two parts are panel ${panel}`, 'Give every panel part its own id');
292
+ if (panel !== undefined && panels.size >= 64) throw new SceneRefusalError(name, 'a shard has at most 64 panels', 'Merge panels that hide together');
293
+ const group = new Group(); group.name = name; parts.push(group); scene.add(group);
294
+ if (panel !== undefined) panels.set(group, panel);
295
+ fill(group); return group;
296
+ },
297
+ ground: (heightAt, options = {}) => {
298
+ // ss4d: the ground is a lit PBR surface (the cleanroom's ground mesh material), never the format's default toon
299
+ const m = options.material;
300
+ if (m !== undefined && !(m instanceof MeshStandardMaterial)) throw new SceneRefusalError('ground', `a ${(m as { type?: string }).type ?? 'material'} ground has no lowering`, 'Give world.ground a MeshStandardMaterial');
301
+ // the shard's ground takes colour, roughness, metalness and detail only: anything else is refused, never dropped
302
+ if (m?.map !== null && m?.map !== undefined) throw new SceneRefusalError('ground', 'a ground map has no lowering (the terrain has no uvs)', 'Say its grain with world.ground(h, { detail }), the PBR detail layer');
303
+ if (m !== undefined && (m.emissive.getHex() !== 0 || m.transparent || m.side !== FrontSide)) throw new SceneRefusalError('ground', 'a ground material is opaque, one-sided and unlit by itself', 'Leave emissive black, transparent off and side FrontSide on the ground material');
304
+ const surface = { colour: m === undefined ? [1, 1, 1] as Rgb : rgb(m.color), roughness: m?.roughness ?? 1, metalness: m?.metalness ?? 0, detail: options.detail ?? null };
305
+ ground = { heightAt, colourAt: options.colourAt ?? null, surface, hash: groundHash(heightAt, options.colourAt ?? null) };
196
306
  },
197
- ground: (heightAt, options = {}) => { ground = { heightAt, colourAt: options.colourAt ?? null, hash: groundHash(heightAt, options.colourAt ?? null) }; },
198
307
  post: (settings) => { post = { ...DEFAULT_POST, ...post, ...settings }; },
308
+ // AP14: the sky compiles at once, so a graph outside the vocabulary or the sky's budget is refused at its line
309
+ sky: (colour, options = {}) => {
310
+ const env = options.environment;
311
+ sky = { graph: graph({ kind: 'material', model: 'unlit', surface: { colour } }, { budget: LOOK_SKY_BUDGET }),
312
+ environment: env === undefined ? null : { intensity: env.intensity, ground: [env.ground[0], env.ground[1], env.ground[2]] } };
313
+ },
199
314
  spawn: (x, y, z, yaw = 0) => { spawn = { position: [x, y, z], yaw }; },
200
315
  };
201
316
  build(world);
@@ -206,13 +321,13 @@ export function lowerShard(identity: ShardIdentityInput, build: (world: ShardWor
206
321
  const roots = loose.children.length > 0 ? [...parts, loose] : parts;
207
322
  scene.add(loose); scene.updateMatrixWorld(true);
208
323
  const tables: Tables = { materials: new Map(), textures: new Map(), geometries: new Map(), geometryKeys: new WeakMap(), materialKeys: new WeakMap(), textureKeys: new WeakMap() };
209
- const lowered = roots.map((root) => lowerPart(root, tables));
324
+ const lowered = roots.map((root) => lowerPart(root, tables, panels.get(root)));
210
325
  const fog: SceneLook['fog'] = scene.fog instanceof FogExp2 ? { kind: 'exp2', colour: rgb(scene.fog.color), density: scene.fog.density }
211
326
  : scene.fog instanceof Fog ? { kind: 'linear', colour: rgb(scene.fog.color), near: scene.fog.near, far: scene.fog.far } : null;
212
327
  const background = scene.background !== null && typeof scene.background === 'object' && 'isColor' in scene.background ? rgb(scene.background as Color) : null;
213
328
  return {
214
329
  identity, parts: lowered, materials: Object.fromEntries(tables.materials), textures: Object.fromEntries(tables.textures),
215
- geometries: Object.fromEntries(tables.geometries), look: { fog, background, post }, ground, spawn,
330
+ geometries: Object.fromEntries(tables.geometries), look: { fog, background, post, sky }, ground, spawn,
216
331
  };
217
332
  }
218
333
 
@@ -221,6 +336,6 @@ export function sceneSummary(shard: ShardScene): { part: string; draws: number;
221
336
  return shard.parts.map((part) => ({
222
337
  part: part.name, draws: part.draws.length, instances: part.draws.reduce((n, d) => n + (d.instances?.count ?? 0), 0),
223
338
  triangles: part.draws.reduce((n, d) => n + (shard.geometries[d.geometry]?.triangles ?? 0) * (d.instances?.count ?? 1), 0),
224
- sprites: part.sprites.length, lights: part.lights.length, colliders: part.colliders.length, water: part.water.length, materials: part.materials.length, textures: part.textures.length,
339
+ sprites: part.sprites.length + part.points.reduce((n, c) => n + c.positions.length / 3, 0), lights: part.lights.length, colliders: part.colliders.length, water: part.water.length, materials: part.materials.length, textures: part.textures.length,
225
340
  }));
226
341
  }
@@ -17,7 +17,7 @@ import type { ProjectGenerationContext, GeneratedProject } from '../projectGener
17
17
  import type { ShardWorld } from './author';
18
18
  import type { ShardIdentityInput, ShardScene } from './description';
19
19
  import { lowerShard } from './lower';
20
- import { compileShardfile, type ShardfileOptions } from './shardfile';
20
+ import { compileShardfile, sceneGameplay, type ShardfileOptions } from './shardfile';
21
21
  import { liveShell } from '../watch/protocol';
22
22
 
23
23
 
@@ -27,6 +27,9 @@ export interface SceneShard {
27
27
  /** Run the author's build once on a fresh scene and read it (compile time only). */
28
28
  readonly describe: () => ShardScene;
29
29
  readonly identity: ShardIdentityInput;
30
+ /** AP19: the gameplay sections `options.extend` declares (`wildshard watch` restarts the page's simulation on a change) and
31
+ * the rest of what it adds (a change there is a new shell) */
32
+ readonly gameplay: () => ReturnType<typeof sceneGameplay>;
30
33
  }
31
34
 
32
35
  /** Declare a shard as a three.js scene. The build function runs at compile time only, never in a page or on a server. */
@@ -34,5 +37,5 @@ export function defineShard(identity: ShardIdentityInput, build: (world: ShardWo
34
37
  const describe = (): ShardScene => lowerShard(identity, build);
35
38
  // `wildshard watch` builds the page's shell only: the dev scene host draws the parts (SHARD-SOURCE AP6)
36
39
  const generate = (ctx: ProjectGenerationContext): Promise<GeneratedProject> => compileShardfile(process.env['WILDSHARD_SCENE_LIVE'] === '1' ? liveShell(describe()) : describe(), ctx, options);
37
- return Object.assign(generate, { describe, identity });
40
+ return Object.assign(generate, { describe, identity, gameplay: () => sceneGameplay(identity, options) });
38
41
  }