@wildshard/sdk 0.2.12 → 0.3.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.
Files changed (72) hide show
  1. package/GUIDE.md +16 -11
  2. package/bin/wildshard.mjs +2 -1
  3. package/docs/api/EXPORT-TIERS.md +12 -3
  4. package/lint/export-tiers.json +9 -0
  5. package/lint/tile-bake-debt.json +26 -1
  6. package/package.json +17 -5
  7. package/scripts/build-shardfiles.mjs +7 -2
  8. package/scripts/preparation-preview.mjs +6 -1
  9. package/scripts/prepare-product.mjs +2 -2
  10. package/scripts/scratch-sweep.mjs +180 -0
  11. package/scripts/wildshard.mjs +1 -1
  12. package/skills/wildshard-mockup-to-model/SKILL.md +5 -3
  13. package/skills/wildshard-upgrade/SKILL.md +4 -4
  14. package/src/cli/help.ts +9 -5
  15. package/src/cli/upload/validate.ts +7 -5
  16. package/src/sharddev/assets.ts +1 -1
  17. package/src/sharddev/bake/compactGlb.ts +1 -1
  18. package/src/sharddev/bake/glbCompression.ts +1 -1
  19. package/src/sharddev/bake/gltfSource.ts +1 -1
  20. package/src/sharddev/bake/placeholders.ts +1 -1
  21. package/src/sharddev/bake/terrain.ts +1 -1
  22. package/src/sharddev/blobBytes.ts +1 -1
  23. package/src/sharddev/blobs.ts +2 -2
  24. package/src/sharddev/cli.ts +17 -4
  25. package/src/sharddev/formatJsonSchema.ts +1 -1
  26. package/src/sharddev/materialGraphFiles.ts +1 -1
  27. package/src/sharddev/newProject.ts +18 -10
  28. package/src/sharddev/outputProduct.ts +2 -2
  29. package/src/sharddev/productOutput.ts +2 -2
  30. package/src/sharddev/project.ts +1 -1
  31. package/src/sharddev/projectMap.ts +1 -1
  32. package/src/sharddev/refusals.ts +4 -2
  33. package/src/sharddev/reportCard.ts +1 -1
  34. package/src/sharddev/scene/author.ts +79 -0
  35. package/src/sharddev/scene/canvas.ts +213 -0
  36. package/src/sharddev/scene/description.ts +170 -0
  37. package/src/sharddev/scene/hash.ts +23 -0
  38. package/src/sharddev/scene/lower.ts +226 -0
  39. package/src/sharddev/scene/shard.ts +38 -0
  40. package/src/sharddev/scene/shardfile.ts +328 -0
  41. package/src/sharddev/threeGate.mjs +14 -0
  42. package/src/sharddev/threePin.mjs +40 -0
  43. package/src/sharddev/watch/page.ts +197 -0
  44. package/src/sharddev/watch/pageEntry.ts +23 -0
  45. package/src/sharddev/watch/proof.mjs +92 -0
  46. package/src/sharddev/watch/protocol.ts +108 -0
  47. package/src/sharddev/watch/socket.ts +57 -0
  48. package/src/sharddev/watch/watch.ts +209 -0
  49. package/src/shards/_template/card/landscape.jpg +0 -0
  50. package/src/shards/_template/card/portrait.jpg +0 -0
  51. package/src/shards/_template/card/thumb.jpg +0 -0
  52. package/src/shards/_template/data/card.json +21 -14
  53. package/src/shards/_template/data/clientScripts.json +27 -27
  54. package/src/shards/_template/data/creatures.json +5 -5
  55. package/src/shards/_template/data/encounters.json +2 -2
  56. package/src/shards/_template/data/layout.json +56 -25
  57. package/src/shards/_template/data/look.json +450 -220
  58. package/src/shards/_template/data/quests.json +2 -2
  59. package/src/shards/_template/data/water.json +131 -4
  60. package/src/shards/_template/generators/landscape.ts +19 -7
  61. package/src/shards/_template/generators/product.ts +7 -5
  62. package/src/shards/_template/generators/templatePropsSource.ts +3 -1
  63. package/src/shards/_template/generators/terrain.ts +28 -4
  64. package/src/shards/_template/generators/weather.ts +128 -0
  65. package/src/shards/_template/generators/world.ts +274 -98
  66. package/src/shards/_template/hero.json +6 -6
  67. package/src/shards/_template/manifest.json +21 -14
  68. package/src/shards/authoring-slice/generators/shard.ts +6 -0
  69. package/src/shards/authoring-slice/generators/textures.ts +173 -0
  70. package/src/shards/authoring-slice/generators/world.ts +415 -0
  71. package/src/shards/authoring-slice/shard.config.ts +7 -0
  72. package/src/shards/_template/assets/f2db05998615ce1cb79ea96be32c168842eb6a2b34ec01feb86d36404603ee54 +0 -0
@@ -0,0 +1,328 @@
1
+ import { BufferAttribute, BufferGeometry, Float32BufferAttribute, Matrix3, Matrix4, MeshStandardMaterial, Quaternion, Vector3 } from 'three';
2
+ import { parseShardfile, type Shardfile } from '@wildshard/format/shardSchema';
3
+ import { emptyShardfile } from '../author';
4
+ import { parseGlb, parseKtx2 } from '../assets';
5
+ import { hashImmutableBytes } from '../immutable';
6
+ import type { GeneratedProject, ProjectGenerationContext } from '../projectGeneration';
7
+ import { staticGlb, type GlbPrimitive } from '../bake/glb';
8
+ import { bakeTerrain } from '../bake/terrain';
9
+ import { bakeRawColourPixels } from '../bake/rawTexture';
10
+ import type { Rgb, SceneCollider, SceneDraw, SceneGeometry, SceneLight, SceneMaterial, ScenePart, ShardScene } from './description';
11
+
12
+ /**
13
+ * AUTHORING-PARITY AP2, AP3, AP4: the shardfile back end. It reads only the scene description and writes the sections an
14
+ * author types by hand today:
15
+ *
16
+ * - **static parts** (AP2): every `Mesh` and `InstancedMesh`, merged per material per 62.5 m tile (instances expanded, their
17
+ * colours in the vertex colours, the map's repeat and offset in the uvs), one named GLB material per scene material, a
18
+ * generated `look.materials` entry and `props.materials` binding for each, painted textures as RGBA8 KTX2 slots;
19
+ * - **light and look** (AP3): `PointLight`s to `look.light.lamps` (the 16 brightest), the brightest `DirectionalLight` to
20
+ * the sun key, a `HemisphereLight` to the ambient key, `scene.fog`, `world.post`;
21
+ * - **ground, colliders, water** (AP4): `world.ground(heightAt)` to the terrain bake, `solid(mesh)` to collider boxes, each
22
+ * `Water` to a `water[]` pool row whose outline is its own geometry's.
23
+ *
24
+ * Phone tile caps are reported, not enforced (J338: this shard may use up to 50 MB): AP9 turns them into a per-part table.
25
+ * Sprites have no shardfile lowering until AP11 and are reported, never silently dropped.
26
+ */
27
+
28
+ export interface ShardfileOptions {
29
+ /** extra rows merged into the generated shardfile (manifest, card, quests...) */
30
+ readonly extend?: (shard: Shardfile) => Shardfile;
31
+ }
32
+
33
+ const TILE = 62.5, HALF = 250;
34
+ const glbName = (material: SceneMaterial, taken: Map<string, string>): string => {
35
+ const wanted = material.name.replaceAll(/[^\w.-]/gu, '-').slice(0, 96) || material.key;
36
+ const owner = taken.get(wanted);
37
+ const name = owner === undefined || owner === material.key ? wanted : `${wanted}-${material.key}`;
38
+ taken.set(name, material.key); return name;
39
+ };
40
+ const lookId = (material: SceneMaterial): string => `scene.${material.key}`;
41
+ const luminance = ([r, g, b]: Rgb): number => 0.2126 * r + 0.7152 * g + 0.0722 * b;
42
+ const clamp01 = (value: number): number => Math.min(1, Math.max(0, value));
43
+ const round = (value: number, digits = 4): number => { const k = 10 ** digits; const out = Math.round(value * k) / k; return out === 0 ? 0 : out; };
44
+ const rgb01 = (colour: Rgb): [number, number, number] => [round(clamp01(colour[0])), round(clamp01(colour[1])), round(clamp01(colour[2]))];
45
+
46
+ /** One tile's growing merge for one material: world-space vertices and an index (a copy inside one tile keeps its
47
+ * own index; a triangle cut at a tile seam adds its clipped corners). */
48
+ interface Merge { position: number[]; normal: number[]; uv: number[]; colour: number[]; index: number[] }
49
+
50
+ /** The tiles a world box touches, by L0 address. */
51
+ const tileOf = (value: number): number => Math.min(7, Math.max(0, Math.floor((value + HALF) / TILE)));
52
+
53
+ interface Vertex { p: Vector3; n: Vector3; u: number; v: number; c: Vector3 }
54
+ function clipToTile(triangle: readonly Vertex[], x: number, z: number): Vertex[] {
55
+ const x0 = -HALF + x * TILE, z0 = -HALF + z * TILE;
56
+ let polygon = [...triangle];
57
+ for (const [axis, limit, direction] of [['x', x0, 1], ['x', x0 + TILE, -1], ['z', z0, 1], ['z', z0 + TILE, -1]] as const) {
58
+ const input = polygon; polygon = [];
59
+ for (let i = 0; i < input.length; i++) {
60
+ const a = input[i], b = input[(i + 1) % input.length]; if (a === undefined || b === undefined) continue;
61
+ const da = (a.p[axis] - limit) * direction, db = (b.p[axis] - limit) * direction;
62
+ if (da >= 0) polygon.push(a);
63
+ if ((da < 0) !== (db < 0)) { const t = da / (da - db); polygon.push({ p: a.p.clone().lerp(b.p, t), n: a.n.clone().lerp(b.n, t).normalize(), u: a.u + (b.u - a.u) * t, v: a.v + (b.v - a.v) * t, c: a.c.clone().lerp(b.c, t) }); }
64
+ }
65
+ }
66
+ return polygon;
67
+ }
68
+
69
+ /** Expand every draw of one material into per-tile world triangles. */
70
+ function mergeDraws(draws: readonly SceneDraw[], scene: ShardScene, tiles: Map<string, Map<string, Merge>>): void {
71
+ const p = new Vector3(), n = new Vector3(), world = new Matrix4(), local = new Matrix4(), normalMatrix = new Matrix3();
72
+ for (const draw of draws) {
73
+ const geometry = scene.geometries[draw.geometry], material = scene.materials[draw.material];
74
+ if (geometry === undefined || material === undefined) continue;
75
+ const base = new Matrix4().fromArray(draw.matrix), copies = draw.instances?.count ?? 1;
76
+ for (let copy = 0; copy < copies; copy++) {
77
+ world.copy(base); if (draw.instances !== null) world.multiply(local.fromArray(draw.instances.matrices, copy * 16));
78
+ normalMatrix.getNormalMatrix(world);
79
+ const flip = world.determinant() < 0;
80
+ const tint = draw.instances?.colours ? new Vector3(draw.instances.colours[copy * 3] ?? 1, draw.instances.colours[copy * 3 + 1] ?? 1, draw.instances.colours[copy * 3 + 2] ?? 1) : new Vector3(1, 1, 1);
81
+ appendCopy(geometry, material, world, normalMatrix, flip, tint, draw.material, tiles, p, n);
82
+ }
83
+ }
84
+ }
85
+
86
+ function appendCopy(geometry: SceneGeometry, material: SceneMaterial, world: Matrix4, normalMatrix: Matrix3, flip: boolean, tint: Vector3, key: string, tiles: Map<string, Map<string, Merge>>, p: Vector3, n: Vector3): void {
87
+ const count = geometry.index?.length ?? geometry.position.length / 3;
88
+ const vertex = (at: number): Vertex => ({ // world-space corner
89
+ p: p.fromArray(geometry.position, at * 3).applyMatrix4(world).clone(),
90
+ n: n.fromArray(geometry.normal, at * 3).applyMatrix3(normalMatrix).normalize().clone(),
91
+ u: (geometry.uv?.[at * 2] ?? 0) * material.repeat[0] + material.offset[0], v: (geometry.uv?.[at * 2 + 1] ?? 0) * material.repeat[1] + material.offset[1],
92
+ c: (material.vertexColours && geometry.colour !== null ? new Vector3().fromArray(geometry.colour, at * 3) : new Vector3(1, 1, 1)).multiply(tint),
93
+ });
94
+ const mergeOf = (tile: string): Merge => {
95
+ const merges = tiles.get(tile) ?? new Map<string, Merge>(); tiles.set(tile, merges);
96
+ const merge = merges.get(key) ?? { position: [], normal: [], uv: [], colour: [], index: [] }; merges.set(key, merge);
97
+ return merge;
98
+ };
99
+ const push = (merge: Merge, corner: Vertex): number => {
100
+ merge.position.push(corner.p.x, corner.p.y, corner.p.z); merge.normal.push(corner.n.x, corner.n.y, corner.n.z);
101
+ merge.uv.push(corner.u, corner.v); merge.colour.push(corner.c.x, corner.c.y, corner.c.z);
102
+ return merge.position.length / 3 - 1;
103
+ };
104
+ const vertexCount = geometry.position.length / 3, corners = Array.from({ length: vertexCount }, (_, at) => vertex(at));
105
+ const xs = corners.map((c) => tileOf(c.p.x)), zs = corners.map((c) => tileOf(c.p.z));
106
+ const order = (i: number): [number, number, number] => {
107
+ const a = geometry.index?.[i] ?? i, b = geometry.index?.[i + 1] ?? i + 1, c = geometry.index?.[i + 2] ?? i + 2;
108
+ return flip ? [a, c, b] : [a, b, c];
109
+ };
110
+ if (xs.every((x) => x === xs[0]) && zs.every((z) => z === zs[0])) {
111
+ // the whole copy is in one tile: its vertices once, its index offset
112
+ const merge = mergeOf(`${xs[0] ?? 0}/${zs[0] ?? 0}`), base = merge.position.length / 3;
113
+ for (const corner of corners) push(merge, corner);
114
+ for (let i = 0; i < count; i += 3) merge.index.push(...order(i).map((at) => at + base));
115
+ return;
116
+ }
117
+ for (let i = 0; i < count; i += 3) {
118
+ const ids = order(i), triangle = ids.map((at) => corners[at]).filter((c) => c !== undefined);
119
+ const txs = ids.map((at) => xs[at] ?? 0), tzs = ids.map((at) => zs[at] ?? 0);
120
+ for (let x = Math.min(...txs); x <= Math.max(...txs); x++) for (let z = Math.min(...tzs); z <= Math.max(...tzs); z++) {
121
+ const polygon = txs.every((value) => value === x) && tzs.every((value) => value === z) ? triangle : clipToTile(triangle, x, z);
122
+ if (polygon.length < 3) continue;
123
+ const merge = mergeOf(`${x}/${z}`), at = polygon.map((corner) => push(merge, corner));
124
+ for (let k = 1; k + 1 < at.length; k++) merge.index.push(at[0] ?? 0, at[k] ?? 0, at[k + 1] ?? 0);
125
+ }
126
+ }
127
+ }
128
+
129
+ /** A merge cut into primitives of at most 200,000 vertices, each with its own compact vertex list. */
130
+ function chunks(merge: Merge, limit = 200_000): Merge[] {
131
+ if (merge.position.length / 3 <= limit) return [merge];
132
+ const out: Merge[] = []; let current: Merge | null = null, remap = new Map<number, number>();
133
+ for (let i = 0; i < merge.index.length; i += 3) {
134
+ if (current === null || current.position.length / 3 + 3 > limit) { current = { position: [], normal: [], uv: [], colour: [], index: [] }; out.push(current); remap = new Map(); }
135
+ for (let k = 0; k < 3; k++) {
136
+ const from = merge.index[i + k] ?? 0; let to = remap.get(from);
137
+ if (to === undefined) {
138
+ to = current.position.length / 3; remap.set(from, to);
139
+ current.position.push(...merge.position.slice(from * 3, from * 3 + 3)); current.normal.push(...merge.normal.slice(from * 3, from * 3 + 3));
140
+ current.uv.push(...merge.uv.slice(from * 2, from * 2 + 2)); current.colour.push(...merge.colour.slice(from * 3, from * 3 + 3));
141
+ }
142
+ current.index.push(to);
143
+ }
144
+ }
145
+ return out;
146
+ }
147
+
148
+ /** A collider box row: yaw-only rotations keep their yaw; any other tilt becomes its world bounding box. */
149
+ function boxRow(collider: SceneCollider): { kind: 'box'; x: number; y: number; z: number; hx: number; hy: number; hz: number; yaw?: number } {
150
+ const q = new Quaternion(...collider.rotation), up = new Vector3(0, 1, 0).applyQuaternion(q);
151
+ const [x, y, z] = collider.centre.map((value) => round(value, 3)) as [number, number, number];
152
+ if (up.y > 0.9999) {
153
+ const forward = new Vector3(1, 0, 0).applyQuaternion(q), yaw = round(Math.atan2(-forward.z, forward.x), 4);
154
+ return { kind: 'box', x, y, z, hx: round(collider.half[0], 3), hy: round(collider.half[1], 3), hz: round(collider.half[2], 3), ...(yaw === 0 ? {} : { yaw }) };
155
+ }
156
+ const half = new Vector3(...collider.half), extent = new Vector3();
157
+ // world AABB of the oriented box: sum of |R| * half per axis
158
+ const m = new Matrix4().makeRotationFromQuaternion(q).elements;
159
+ extent.set(
160
+ Math.abs(m[0] ?? 0) * half.x + Math.abs(m[4] ?? 0) * half.y + Math.abs(m[8] ?? 0) * half.z,
161
+ Math.abs(m[1] ?? 0) * half.x + Math.abs(m[5] ?? 0) * half.y + Math.abs(m[9] ?? 0) * half.z,
162
+ Math.abs(m[2] ?? 0) * half.x + Math.abs(m[6] ?? 0) * half.y + Math.abs(m[10] ?? 0) * half.z);
163
+ return { kind: 'box', x, y, z, hx: round(extent.x, 3), hy: round(extent.y, 3), hz: round(extent.z, 3) };
164
+ }
165
+
166
+ /** Point lights as the look's lamp rows (`look.light.lamps`): what a baked shard and a watched part (the dev hook) both draw. */
167
+ export function lampRows(lights: readonly SceneLight[]): { at: [number, number, number]; colour: [number, number, number]; intensity: number; distance: number }[] {
168
+ return lights.filter((l) => l.kind === 'point').map((l) => ({ at: l.position.map((v) => round(v, 3)) as [number, number, number], colour: rgb01(l.colour), intensity: round(Math.min(100, l.intensity), 3), distance: round(Math.min(50, Math.max(0.1, l.distance === 0 ? 50 : l.distance)), 3) }));
169
+ }
170
+
171
+ /** A part's `Water` surfaces as the shardfile's water rows (AP4): the outline is the Water's own geometry. */
172
+ export function waterRows(part: ScenePart): { id: string; kind: 'pool'; level: number; shape: { kind: 'polygon'; points: [number, number][] } }[] {
173
+ return part.water.map((w, i) => ({
174
+ id: `scene.${part.name}.water${i === 0 ? '' : `-${i}`}`, kind: 'pool', level: round(w.level, 3),
175
+ shape: { kind: 'polygon', points: w.outline.map(([px, pz]) => [round(px, 3), round(pz, 3)]) },
176
+ // shard-format 0.4.10 has no water surface fields; tint and planar reflection ride TEMPLATES-CLEANROOM M4.6's format
177
+ }));
178
+ }
179
+
180
+ /** The look a scene declares (AP3), over the format's day-key model fixed at one time of day. */
181
+ export function sceneLook(scene: ShardScene, lights: readonly SceneLight[], materials: Record<string, unknown>): Shardfile['look'] {
182
+ const directional = lights.filter((l) => l.kind === 'directional').sort((a, b) => b.intensity - a.intensity);
183
+ const sun = directional[0], hemisphere = lights.find((l) => l.kind === 'hemisphere'), ambient = lights.find((l) => l.kind === 'ambient');
184
+ const lamps = lights.filter((l) => l.kind === 'point').sort((a, b) => b.intensity - a.intensity).slice(0, 16);
185
+ // the sun's heading and height from its position over its target
186
+ const toSun = sun === undefined ? new Vector3(0.3, 1, 0.4) : new Vector3(...sun.position).sub(new Vector3(...sun.target ?? [0, 0, 0]));
187
+ toSun.normalize();
188
+ const elevation = Math.asin(clamp01(toSun.y)) * 180 / Math.PI, azimuth = Math.atan2(toSun.x, -toSun.z) * 180 / Math.PI;
189
+ const fog = scene.look.fog, post = scene.look.post;
190
+ const skyColour: Rgb = hemisphere?.colour ?? ambient?.colour ?? [0.5, 0.5, 0.6], groundColour: Rgb = hemisphere?.groundColour ?? skyColour;
191
+ const fogColour: Rgb = fog?.colour ?? scene.look.background ?? skyColour;
192
+ return {
193
+ families: ['pbr', 'emissive'], materials: materials as Shardfile['look']['materials'],
194
+ grade: { exposure: round(Math.log2(post?.exposure ?? 1), 3), saturation: 1, contrast: 1, lut: null,
195
+ ...(post?.bloom === null || post?.bloom === undefined ? {} : { bloom: { intensity: round(Math.min(4, post.bloom.strength * 1.5), 3), threshold: round(post.bloom.threshold, 3) } }),
196
+ ...(post?.tone === 'neutral' ? { tone: 'neutral' } : {}) },
197
+ clock: 'engine', day: { minutes: 12, start: 0.5, maxElevation: round(Math.max(5, elevation), 2), azimuth: round(azimuth, 2) }, dayOverride: 0.5,
198
+ keys: [{ time: 0, sky: { zenith: rgb01(skyColour), horizon: rgb01(fogColour) },
199
+ fog: fog?.kind === 'linear' ? { colour: rgb01(fog.colour), density: 0, near: fog.near, far: fog.far } : { colour: rgb01(fogColour), density: round(fog?.kind === 'exp2' ? fog.density : 0, 5) },
200
+ sun: { colour: rgb01(sun?.colour ?? [1, 1, 1]), intensity: round(sun?.intensity ?? 0, 3) },
201
+ ambient: { sky: rgb01(skyColour), ground: rgb01(groundColour), intensity: round((hemisphere?.intensity ?? ambient?.intensity ?? 0.5) * Math.PI, 3) } }],
202
+ light: lamps.length === 0 ? {} : { lamps: lampRows(lamps) },
203
+ } as Shardfile['look'];
204
+ }
205
+
206
+ /** A look.materials entry for one scene material (AP2): pbr for lit surfaces, emissive for glowing or unlit ones. */
207
+ function materialEntry(material: SceneMaterial): Record<string, unknown> {
208
+ const glow = luminance(material.emissive) * material.emissiveIntensity;
209
+ if (material.kind === 'basic' || glow > 0.5) {
210
+ const colour = material.kind === 'basic' ? material.colour : material.emissive;
211
+ return { family: 'emissive', colour: rgb01(colour), intensity: round(Math.min(10, material.kind === 'basic' ? 1 : material.emissiveIntensity), 3), vertexColours: true, ...(material.side === 'double' ? { doubleSided: true } : {}) };
212
+ }
213
+ // AP10 adds sorted transparency; until then a transparent surface is cut at a low alpha, as a decal mostly is
214
+ const cutoff = material.alphaTest > 0 ? material.alphaTest : material.transparent && material.map !== null ? 0.3 : 0;
215
+ return { family: 'pbr', colour: rgb01(material.colour), roughness: round(clamp01(material.roughness), 3), metalness: round(clamp01(material.metalness), 3), vertexColours: true,
216
+ ...(material.side === 'double' ? { doubleSided: true } : {}), ...(cutoff > 0 ? { alphaCutoff: round(cutoff, 3) } : {}) };
217
+ }
218
+
219
+ /** What the shardfile back end did not write, for the build log (never silent). */
220
+ export interface ShardfileReport { readonly sprites: number; readonly lampsDropped: number; readonly tiles: readonly { tile: string; triangles: number; draws: number; bytes: number }[] }
221
+
222
+ /** The shardfile back end: the description in, a generated project out. Runs at compile time. */
223
+ export function compileShardfile(scene: ShardScene, ctx: ProjectGenerationContext, options: ShardfileOptions = {}): Promise<GeneratedProject> {
224
+ const { shard, assets, report } = sceneShardfile(scene, options);
225
+ for (const [hash, bytes] of assets) if (ctx.asset(bytes) !== hash) throw new Error('scene: an asset hash differs from the product store');
226
+ if (report.sprites > 0) console.info(`scene: ${report.sprites} sprites are drawn by watch only until AP11 (billboards)`);
227
+ if (report.lampsDropped > 0) console.info(`scene: ${report.lampsDropped} point lights past the 16 brightest are not in the shardfile (AP28)`);
228
+ const over = report.tiles.filter((t) => t.triangles > 40_000 || t.draws > 8);
229
+ if (over.length > 0) console.info(`scene: ${over.length} tiles are over the phone tile caps (J338; AP9 turns this into a per-part table): ${over.map((t) => `${t.tile} ${t.triangles} tris ${t.draws} draws`).join(', ')}`);
230
+ return Promise.resolve({ shard, output: {} });
231
+ }
232
+
233
+ /** The pure half of the back end: shardfile rows and asset bytes by hash. */
234
+ export function sceneShardfile(scene: ShardScene, options: ShardfileOptions = {}): { shard: Shardfile; assets: Map<string, Uint8Array>; report: ShardfileReport } {
235
+ const assets = new Map<string, Uint8Array>(), files: Shardfile['files'] = [];
236
+ const store = (bytes: Uint8Array, kind: 'glb' | 'ktx2', dependencies: string[] = []): Shardfile['files'][number] => {
237
+ const hash = hashImmutableBytes(bytes), cost = kind === 'glb' ? parseGlb(bytes) : parseKtx2(bytes);
238
+ const row = { hash, kind, compressed: bytes.length, ...cost, dependencies, critical: false };
239
+ if (!assets.has(hash)) { assets.set(hash, bytes); files.push(row); }
240
+ return files.find((f) => f.hash === hash) ?? row;
241
+ };
242
+ // ground (AP4): the declared height field, or a flat cell
243
+ const ground = scene.ground;
244
+ const terrain = bakeTerrain({ heightAt: ground?.heightAt ?? (() => 0), colourAt: (x, z) => ground?.colourAt?.(x, z) ?? [0.3, 0.36, 0.2] });
245
+ for (const [hash, bytes] of terrain.assets) assets.set(hash, bytes);
246
+ files.push(...terrain.files);
247
+
248
+ // textures (AP2): RGBA8 KTX2, one file per painted raster
249
+ const textureFiles = new Map<string, Shardfile['files'][number]>();
250
+ // only the textures a drawn material samples: a sprite's (AP11) would be an orphan file
251
+ const sampled = new Set(scene.parts.flatMap((part) => part.draws.map((d) => scene.materials[d.material]?.map)).filter((key) => typeof key === 'string'));
252
+ for (const texture of Object.values(scene.textures).filter((t) => sampled.has(t.key))) {
253
+ const bytes = bakeRawColourPixels({ width: texture.width, height: texture.height, pixels: new Uint8ClampedArray(texture.rgba) }, { colourSpace: texture.colourSpace });
254
+ textureFiles.set(texture.key, store(bytes, 'ktx2'));
255
+ }
256
+ // static parts (AP2): merged per material per tile
257
+ const draws = scene.parts.flatMap((part) => part.draws), byMaterial = new Map<string, SceneDraw[]>();
258
+ for (const draw of draws) { const list = byMaterial.get(draw.material) ?? []; list.push(draw); byMaterial.set(draw.material, list); }
259
+ const tiles = new Map<string, Map<string, Merge>>();
260
+ for (const list of byMaterial.values()) mergeDraws(list, scene, tiles);
261
+ const names = new Map<string, string>(), used = [...byMaterial.keys()].flatMap((key) => { const m = scene.materials[key]; return m === undefined ? [] : [m]; });
262
+ const glbNames = new Map(used.map((m) => [m.key, glbName(m, names)]));
263
+ const casts = new Map<string, boolean>(); for (const draw of draws) casts.set(draw.material, (casts.get(draw.material) ?? false) || draw.castShadow);
264
+ const lookMaterials: Record<string, unknown> = {}, propMaterials: Record<string, unknown> = {};
265
+ for (const material of used) {
266
+ const name = glbNames.get(material.key) ?? material.key, file = material.map === null ? undefined : textureFiles.get(material.map);
267
+ lookMaterials[lookId(material)] = materialEntry(material);
268
+ propMaterials[name] = { id: lookId(material), ...(file === undefined ? {} : { colour: { file: file.hash, wrapS: 10497, wrapT: 10497, minFilter: 9987, magFilter: 9729, anisotropy: 4 } }) };
269
+ }
270
+ const shardTiles = terrain.tiles.map((t) => ({ ...t, files: [...t.files], bounds: { min: [...t.bounds.min] as [number, number, number], max: [...t.bounds.max] as [number, number, number] } }));
271
+ const propTiles: { lod: 0; x: number; z: number; file: string }[] = [], tileReport: { tile: string; triangles: number; draws: number; bytes: number }[] = [];
272
+ for (const [address, merges] of [...tiles].sort(([a], [b]) => a.localeCompare(b))) {
273
+ const [x = 0, z = 0] = address.split('/').map(Number);
274
+ const primitives: GlbPrimitive[] = [], dependencies = new Set<string>();
275
+ for (const [key, merge] of [...merges].sort(([p], [q]) => p.localeCompare(q))) {
276
+ const material = scene.materials[key]; if (material === undefined || merge.position.length === 0) continue;
277
+ for (const chunk of chunks(merge)) {
278
+ const geometry = new BufferGeometry().setAttribute('position', new Float32BufferAttribute(chunk.position, 3)).setAttribute('normal', new Float32BufferAttribute(chunk.normal, 3))
279
+ .setAttribute('uv', new Float32BufferAttribute(chunk.uv, 2)).setAttribute('color', new BufferAttribute(new Float32Array(chunk.colour), 3)).setIndex(chunk.index);
280
+ const glbMaterial = new MeshStandardMaterial({ color: 0xffffff, vertexColors: true }); glbMaterial.name = glbNames.get(key) ?? key;
281
+ primitives.push({ geometry, material: glbMaterial, castShadow: casts.get(key) ?? true });
282
+ }
283
+ const file = material.map === null ? undefined : textureFiles.get(material.map); if (file !== undefined) dependencies.add(file.hash);
284
+ }
285
+ if (primitives.length === 0) continue;
286
+ // a GLB holds at most 25 MB (shard-format glbCost): batch the primitives into as many files as the tile needs
287
+ const batches: GlbPrimitive[][] = []; let batch: GlbPrimitive[] = [], bytes = 0;
288
+ for (const primitive of primitives) {
289
+ const size = primitive.geometry.getAttribute('position').count * 44 + (primitive.geometry.getIndex()?.count ?? 0) * 4;
290
+ if (batch.length > 0 && bytes + size > 18_000_000) { batches.push(batch); batch = []; bytes = 0; }
291
+ batch.push(primitive); bytes += size;
292
+ }
293
+ batches.push(batch);
294
+ const rows = batches.map((list, i) => store(staticGlb(list, batches.length === 1 ? `scene.${x}.${z}` : `scene.${x}.${z}.${i}`), 'glb', [...dependencies].sort()));
295
+ const [first, ...more] = rows; if (first === undefined) continue;
296
+ propTiles.push({ lod: 0, x, z, file: first.hash, ...(more.length === 0 ? {} : { additionalFiles: more.map((r) => r.hash) }) });
297
+ const tile = shardTiles.find((t) => t.lod === 0 && t.x === x && t.z === z);
298
+ if (tile === undefined) throw new Error(`scene: no terrain tile 0/${x}/${z}`);
299
+ const textures = [...dependencies].map((hash) => files.find((f) => f.hash === hash)).filter((f) => f !== undefined);
300
+ tile.files.push(...rows.map((r) => r.hash), ...textures.map((f) => f.hash).filter((hash) => !tile.files.includes(hash)));
301
+ const sum = (pick: (f: Shardfile['files'][number]) => number): number => rows.reduce((n, f) => n + pick(f), 0) + textures.reduce((n, f) => n + pick(f), 0);
302
+ tile.compressed += sum((f) => f.compressed); tile.decoded += sum((f) => f.decoded); tile.gpu += sum((f) => f.gpu);
303
+ tile.triangles += rows.reduce((n, f) => n + f.triangles, 0); tile.draws += rows.reduce((n, f) => n + f.draws, 0);
304
+ for (const primitive of primitives) { primitive.geometry.computeBoundingBox(); const box = primitive.geometry.boundingBox; if (box === null) continue; tile.bounds.min[1] = Math.min(tile.bounds.min[1], box.min.y); tile.bounds.max[1] = Math.max(tile.bounds.max[1], box.max.y); }
305
+ const row = { triangles: rows.reduce((n, f) => n + f.triangles, 0), draws: rows.reduce((n, f) => n + f.draws, 0), compressed: rows.reduce((n, f) => n + f.compressed, 0) };
306
+ tileReport.push({ tile: `0/${x}/${z}`, triangles: row.triangles, draws: row.draws, bytes: row.compressed });
307
+ }
308
+ // colliders (AP4)
309
+ const colliders = scene.parts.filter((part) => part.colliders.length > 0).map((part) => ({ id: `scene.${part.name}`, panel: null, initialActive: true, shapes: part.colliders.map(boxRow) }));
310
+ // water (AP4)
311
+ const water = scene.parts.flatMap(waterRows);
312
+ const lights = scene.parts.flatMap((part) => part.lights);
313
+ const base = emptyShardfile({ slug: scene.identity.slug, name: scene.identity.name, author: scene.identity.author ?? 'Wildshard', revision: scene.identity.revision ?? 1, seed: scene.identity.seed ?? 1 });
314
+ const [sx, sy, sz] = scene.spawn.position;
315
+ const spawnY = Math.max(sy, (ground?.heightAt(sx, sz) ?? 0) + 1);
316
+ const product = {
317
+ ...base, budgets: { ...base.budgets, sim: { resident: 16_000_000, compressed: 1_000_000 } }, serverBudget: { ...base.serverBudget, tickMicros: 5_000, memory: 16_000_000 },
318
+ look: sceneLook(scene, lights, lookMaterials), spawn: { x: round(sx, 3), y: round(spawnY, 3), z: round(sz, 3), yaw: round(scene.spawn.yaw, 4) },
319
+ terrain: { ...terrain.terrain, shadow: { cast: true, receive: true }, follow: 5 }, tiles: shardTiles, files: files.sort((a, b) => a.hash.localeCompare(b.hash)), edge: terrain.edge,
320
+ critical: [...terrain.critical], far: null,
321
+ props: { version: 1, family: 'pbr', tiles: propTiles, panels: [], models: [], far: null, textures: [], colliders, ...(Object.keys(propMaterials).length === 0 ? {} : { materials: propMaterials }) },
322
+ ...(water.length === 0 ? {} : { water }),
323
+ };
324
+ // oxlint-disable-next-line unicorn/prefer-structured-clone -- JSON wire normalization (signed zero), as product.ts does
325
+ let shard = parseShardfile(JSON.parse(JSON.stringify(product)));
326
+ if (options.extend !== undefined) shard = options.extend(shard);
327
+ return { shard, assets, report: { sprites: scene.parts.reduce((n, p) => n + p.sprites.length, 0), lampsDropped: Math.max(0, lights.filter((l) => l.kind === 'point').length - 16), tiles: tileReport } };
328
+ }
@@ -0,0 +1,14 @@
1
+ // SA8: the first import of bin/wildshard.mjs. It refuses a run whose `three` is not the sdk's pin (threePin.mjs), except help and --version.
2
+ import { threeRefusal } from './threePin.mjs';
3
+
4
+ // Help and --version print without it: the refusal sends authors to --version for the pinned chain.
5
+ const args = process.argv.slice(2);
6
+ const passes = args[0] === 'help' || args[0] === '--version' || args.some(arg => arg === '--help' || arg === '-h');
7
+ if (!passes) {
8
+ const refusal = threeRefusal(new URL('../../package.json', import.meta.url));
9
+ if (refusal !== undefined) {
10
+ process.stderr.write(`wildshard: ${refusal}\n`);
11
+ // oxlint-disable-next-line unicorn/no-process-exit -- Stop before any other module loads; a throw would print a stack to authors.
12
+ process.exit(1);
13
+ }
14
+ }
@@ -0,0 +1,40 @@
1
+ // SHARD-AUTHORING SA8 (J317): `three` is a peer of the sdk, pinned exact. Every `wildshard` (and `sharddev`) run checks,
2
+ // before anything else loads (threeGate.mjs), that the `three` this sdk would import is the version it pins, and refuses
3
+ // naming both. Engine still lists its own `three` until it takes it as a peer too, so the copy engine resolves is checked
4
+ // as well: two copies at different versions would otherwise pass. Plain JS with Node built-ins only: bin/wildshard.mjs
5
+ // imports it first, ahead of the type-stripping hook.
6
+ // oxlint-disable-next-line import/no-nodejs-modules -- Read the sdk, engine and three package.json files, as Node finds them.
7
+ import { existsSync, readFileSync, realpathSync } from 'node:fs';
8
+ // oxlint-disable-next-line import/no-nodejs-modules -- The node_modules folders Node resolves a package from.
9
+ import { createRequire } from 'node:module';
10
+ // oxlint-disable-next-line import/no-nodejs-modules -- Join a node_modules folder and a package.json.
11
+ import { join } from 'node:path';
12
+ // oxlint-disable-next-line import/no-nodejs-modules -- Resolve from a package.json's real path.
13
+ import { pathToFileURL } from 'node:url';
14
+
15
+ const FIX = (pin) => `fix: pnpm add three@${pin} --save-exact (GUIDE.md#three-version)`;
16
+
17
+ /** The package.json of `name` as Node would find it from the file at `from` (a URL), at its real path, if any. */
18
+ function found(from, name) {
19
+ const folders = createRequire(from).resolve.paths(name) ?? [];
20
+ const file = folders.map(folder => join(folder, name, 'package.json')).find(candidate => existsSync(candidate));
21
+ return file === undefined ? undefined : realpathSync(file);
22
+ }
23
+
24
+ /** The refusal for the `three` an sdk at `sdkPackageUrl` (its package.json's URL) resolves, or that the engine it
25
+ * resolves resolves, or undefined when both are the pinned one. The lookup walks the folders Node's resolver would. */
26
+ export function threeRefusal(sdkPackageUrl) {
27
+ const sdk = JSON.parse(readFileSync(new URL(sdkPackageUrl), 'utf8'));
28
+ const pin = sdk.peerDependencies?.three;
29
+ if (typeof pin !== 'string') return undefined;
30
+ const name = `${sdk.name ?? '@wildshard/sdk'} ${sdk.version ?? ''}`.trim();
31
+ const own = found(sdkPackageUrl, 'three');
32
+ if (own === undefined) return `[three-version] three is not installed, and ${name} needs three ${pin} exactly. ${FIX(pin)}`;
33
+ const installed = JSON.parse(readFileSync(own, 'utf8')).version;
34
+ if (installed !== pin) return `[three-version] three ${installed} is installed, but ${name} needs three ${pin} exactly. ${FIX(pin)}`;
35
+ const engine = found(sdkPackageUrl, '@wildshard/engine');
36
+ const engines = engine === undefined ? undefined : found(pathToFileURL(engine), 'three');
37
+ const second = engines === undefined ? undefined : JSON.parse(readFileSync(engines, 'utf8')).version;
38
+ return second === undefined || second === pin ? undefined
39
+ : `[three-version] @wildshard/engine loads three ${second}, but ${name} needs three ${pin} exactly. ${FIX(pin)}`;
40
+ }
@@ -0,0 +1,197 @@
1
+ import { Scope } from '@wildshard/engine/app/scope';
2
+ import { DEV_HOOK_VERSION, DEV_SCENE_PATH, WATCH_SOCKET, WATCH_WIRE, decodeGeometry, type WatchPart, type WatchState } from './protocol';
3
+
4
+ /**
5
+ * SHARD-SOURCE AP5 (J347): the page script `wildshard watch` injects into the page it serves (`pageEntry.ts`, bundled at
6
+ * start). It owns the page's half of watch: the socket, the fetches, a cache of decoded geometry and rasters, one scope
7
+ * per part and the swap order, and drives engine's dev hook (`window.__wildshardDevHook`, five calls). Per revision:
8
+ *
9
+ * 1. the look's day keys, if they changed (`setLook`; a look the page can't take live reloads it)
10
+ * 2. every changed part is fetched and decoded first, so a slow fetch never leaves half a revision on screen
11
+ * 3. each one swaps in (`addPart` or `replacePart`, then `swapColliders`), and only then its old scope goes
12
+ * 4. parts no longer in the scene go (`removePart`, `swapColliders(name, [])`)
13
+ *
14
+ * `window.__wsDevScene` reports what landed and the first frame after it, for `proof.mjs`'s timing.
15
+ */
16
+ export interface DevHookLike {
17
+ readonly version: number;
18
+ addPart: (name: string, part: unknown) => void;
19
+ replacePart: (name: string, part: unknown) => void;
20
+ removePart: (name: string) => void;
21
+ setLook: (look: { readonly keys: readonly unknown[] }) => boolean;
22
+ swapColliders: (name: string, boxes: readonly unknown[]) => void;
23
+ }
24
+
25
+ export interface SocketLike { onmessage: ((event: { data: unknown }) => void) | null; onclose: (() => void) | null; close: () => void }
26
+
27
+ export interface WatchPageEnv {
28
+ /** the watch server's origin, `http://127.0.0.1:<port>` */
29
+ readonly origin: string;
30
+ readonly hook: () => DevHookLike | undefined;
31
+ readonly fetch: (url: string) => Promise<{ ok: boolean; status: number; json: () => Promise<unknown>; arrayBuffer: () => Promise<ArrayBuffer> }>;
32
+ readonly socket: (url: string) => SocketLike;
33
+ /** the page's next frame (`requestAnimationFrame`) */
34
+ readonly frame: (run: () => void) => void;
35
+ readonly wait: (ms: number, run: () => void) => void;
36
+ readonly reload: () => void;
37
+ readonly now: () => number;
38
+ readonly log: (message: string) => void;
39
+ /** the shell this page booted from (`window.__wsShell`, written into the page per shell); a state for another reloads */
40
+ readonly shell?: () => number | null;
41
+ }
42
+
43
+ export interface WatchPageReport {
44
+ revision: number;
45
+ /** the last revision whose parts all landed, and the wall clock (ms) of the first frame after it */
46
+ framedRevision: number;
47
+ framedAt: number;
48
+ /** frames since the script started: it only grows, swap or no swap */
49
+ frames: number;
50
+ /** the page's own failure: a part the hook refused, a fetch, a message it couldn't read */
51
+ error: string | null;
52
+ /** the watch server's: the source failed to bundle or describe (the page keeps the last good revision) */
53
+ serverError: string | null;
54
+ /** every part swapped in, in order (`name@hash`) */
55
+ readonly applied: string[];
56
+ }
57
+
58
+ interface Held<T> { readonly value: T; users: number }
59
+ interface LivePart { readonly hash: string; readonly scope: Scope }
60
+
61
+ /** How long the script waits for the engine to boot and install its hook. */
62
+ const HOOK_WAIT_MS = 180_000;
63
+
64
+ export function startWatchPage(env: WatchPageEnv): { readonly report: WatchPageReport; readonly stop: () => void } {
65
+ const scope = new Scope('watch.page');
66
+ const report: WatchPageReport = { revision: 0, framedRevision: 0, framedAt: 0, frames: 0, error: null, serverError: null, applied: [] };
67
+ const parts = new Map<string, LivePart>(), geometries = new Map<string, Held<ReturnType<typeof decodeGeometry>>>(), textures = new Map<string, Held<Uint8Array>>();
68
+ let hook: DevHookLike | null = null, shell: number | null = env.shell?.() ?? null, look: string | null = null, socket: SocketLike | null = null;
69
+ let pendingFrame: number | null = null;
70
+
71
+ const tick = (): void => {
72
+ if (scope.disposed) return;
73
+ report.frames++;
74
+ if (pendingFrame !== null) { report.framedRevision = pendingFrame; report.framedAt = env.now(); pendingFrame = null; }
75
+ env.frame(tick);
76
+ };
77
+ env.frame(tick);
78
+
79
+ const fail = (message: string): void => { report.error = message; env.log(`wildshard watch: ${message}`); };
80
+ const get = async (path: string): Promise<{ json: () => Promise<unknown>; arrayBuffer: () => Promise<ArrayBuffer> }> => {
81
+ const response = await env.fetch(`${env.origin}${DEV_SCENE_PATH}${path}`);
82
+ if (!response.ok) throw new Error(`${path} answered ${response.status}`);
83
+ return response;
84
+ };
85
+ /** Take one use of a cached asset for `owner`; it is let go when `owner` is disposed. */
86
+ const hold = <T>(map: Map<string, Held<T>>, key: string, owner: Scope): T => {
87
+ const held = map.get(key);
88
+ if (held === undefined) throw new Error(`asset ${key} was not fetched`);
89
+ held.users++;
90
+ owner.onDispose(() => { if (--held.users === 0) map.delete(key); });
91
+ return held.value;
92
+ };
93
+
94
+ const sync = async (state: WatchState, first: boolean): Promise<void> => {
95
+ const live = hook;
96
+ if (live === null) return;
97
+ report.serverError = state.error;
98
+ if (state.error !== null) env.log(`wildshard watch: ${state.error}`);
99
+ if (state.look.hash !== look) {
100
+ if (!live.setLook({ keys: state.look.keys })) {
101
+ if (!first) { env.log('wildshard watch: this look change needs a reload'); env.reload(); return; }
102
+ fail('the page\'s look can\'t take day keys live: look edits will reload the page');
103
+ }
104
+ look = state.look.hash;
105
+ }
106
+ // fetch and decode every changed part before any swaps in
107
+ const changed = state.parts.filter((part) => parts.get(part.name)?.hash !== part.hash);
108
+ const fetched = await Promise.all(changed.map(async ({ name }) => await (await get(`part/${encodeURIComponent(name)}`)).json() as WatchPart));
109
+ const fresh = new Map<string, Promise<void>>();
110
+ for (const part of fetched) {
111
+ for (const key of part.geometries) if (!geometries.has(key) && !fresh.has(`g:${key}`)) fresh.set(`g:${key}`, (async () => { const bytes = await (await get(`geometry/${key}`)).arrayBuffer(); geometries.set(key, { value: decodeGeometry(key, bytes), users: 0 }); })());
112
+ for (const t of part.textures) if (!textures.has(t.key) && !fresh.has(`t:${t.key}`)) fresh.set(`t:${t.key}`, (async () => { const bytes = await (await get(`texture/${t.key}`)).arrayBuffer(); textures.set(t.key, { value: new Uint8Array(bytes), users: 0 }); })());
113
+ }
114
+ await Promise.all(fresh.values());
115
+ if (scope.disposed) return;
116
+ let landed = true;
117
+ for (const part of fetched) {
118
+ const owner = scope.child(`watch.part.${part.name}@${part.hash}`), old = parts.get(part.name);
119
+ try {
120
+ const devPart = { materials: part.materials, sprites: part.sprites, lamps: part.lamps, water: part.water, draws: part.draws,
121
+ geometries: part.geometries.map((key) => hold(geometries, key, owner)),
122
+ textures: part.textures.map((t) => ({ ...t, rgba: hold(textures, t.key, owner) })) };
123
+ if (old === undefined) live.addPart(part.name, devPart); else live.replacePart(part.name, devPart);
124
+ } catch (cause) {
125
+ // the hook keeps the old part drawn; this revision's copy lets its assets go
126
+ owner.dispose(); landed = false;
127
+ fail(`part ${part.name}: ${cause instanceof Error ? cause.message : String(cause)}`);
128
+ continue;
129
+ }
130
+ // the new part is drawn: record it before anything else can throw, so the next revision replaces it
131
+ parts.set(part.name, { hash: part.hash, scope: owner });
132
+ report.applied.push(`${part.name}@${part.hash}`);
133
+ old?.scope.dispose();
134
+ try { live.swapColliders(part.name, part.colliders); }
135
+ catch (cause) { landed = false; fail(`part ${part.name} colliders: ${cause instanceof Error ? cause.message : String(cause)}`); }
136
+ }
137
+ const names = new Set(state.parts.map((part) => part.name));
138
+ for (const [name, part] of parts) {
139
+ if (names.has(name)) continue;
140
+ live.removePart(name); live.swapColliders(name, []);
141
+ parts.delete(name); part.scope.dispose();
142
+ }
143
+ report.revision = state.revision;
144
+ // the timing counts a revision only once all its parts landed
145
+ if (landed) pendingFrame = state.revision;
146
+ };
147
+
148
+ // one sync at a time; a revision announced while one runs waits, and only the newest one runs
149
+ let running = false, next: WatchState | null = null, synced = 0;
150
+ const drain = async (): Promise<void> => {
151
+ running = true;
152
+ while (next !== null && !scope.disposed) {
153
+ const state = next; next = null;
154
+ try { await sync(state, synced++ === 0); } catch (cause) { fail(cause instanceof Error ? cause.message : String(cause)); }
155
+ }
156
+ running = false;
157
+ };
158
+ const receive = (data: unknown): void => {
159
+ let state: WatchState;
160
+ try { state = JSON.parse(String(data)) as WatchState; }
161
+ catch { fail('the watch server sent a message this page can\'t read'); return; }
162
+ if (state.wire !== WATCH_WIRE) { env.log(`wildshard watch: the server speaks wire ${state.wire}, this page ${WATCH_WIRE}; reloading`); env.reload(); return; }
163
+ if (shell !== null && state.shell !== shell) { env.log('wildshard watch: the ground, spawn or grade changed; reloading'); env.reload(); return; }
164
+ shell = state.shell; next = state;
165
+ if (!running) void drain();
166
+ };
167
+ const connect = (): void => {
168
+ if (scope.disposed) return;
169
+ const opened = env.socket(`${env.origin.replace(/^http/u, 'ws')}${WATCH_SOCKET}`);
170
+ socket = opened;
171
+ opened.onmessage = (event) => { receive(event.data); };
172
+ opened.onclose = () => { if (socket === opened && !scope.disposed) env.wait(1000, connect); };
173
+ };
174
+
175
+ const started = env.now();
176
+ const find = (): void => {
177
+ if (scope.disposed) return;
178
+ const found = env.hook();
179
+ if (found === undefined) {
180
+ if (env.now() - started > HOOK_WAIT_MS) { fail('the page never installed engine\'s dev hook: is this a devserver client?'); return; }
181
+ env.wait(250, find); return;
182
+ }
183
+ if (found.version !== DEV_HOOK_VERSION) { fail(`the page's dev hook is v${found.version}, this sdk drives v${DEV_HOOK_VERSION}: move the sdk and its engine pin together`); return; }
184
+ hook = found;
185
+ connect();
186
+ };
187
+ find();
188
+ return { report, stop: () => { scope.dispose(); const open = socket; socket = null; open?.close(); } };
189
+ }
190
+
191
+ /** A platform WebSocket as the page script's `SocketLike` (the browser's, or Node's in a test). */
192
+ export function socketOf(open: WebSocket): SocketLike {
193
+ const socket: SocketLike = { onmessage: null, onclose: null, close: () => { open.close(); } };
194
+ open.onmessage = (event) => { socket.onmessage?.({ data: event.data }); };
195
+ open.onclose = () => { socket.onclose?.(); };
196
+ return socket;
197
+ }
@@ -0,0 +1,23 @@
1
+ import { Scope } from '@wildshard/engine/app/scope';
2
+ import { installBrowserScopeEnvironment } from '@wildshard/engine/app/view/scopeEnvironment';
3
+ import { socketOf, startWatchPage, type DevHookLike, type WatchPageReport } from './page';
4
+
5
+ // SHARD-SOURCE AP5: the browser entry `wildshard watch` bundles and injects into the page it serves (watch.ts `pageScript`).
6
+ // It is its own bundle beside the engine's, so it installs its own copy of the browser scope environment (frames, timers).
7
+ declare global { interface Window { __wildshardDevHook?: DevHookLike; __wsDevScene?: WatchPageReport; __wsShell?: number } }
8
+
9
+ installBrowserScopeEnvironment();
10
+ const timers = new Scope('watch.entry');
11
+ const page = startWatchPage({
12
+ origin: location.origin,
13
+ hook: () => window.__wildshardDevHook,
14
+ fetch: (url) => fetch(url, { cache: 'no-store' }),
15
+ socket: (url) => socketOf(new WebSocket(url)),
16
+ frame: (run) => { timers.raf(run); },
17
+ wait: (ms, run) => { timers.timeout(ms, run); },
18
+ reload: () => { location.reload(); },
19
+ now: () => Date.now(),
20
+ log: (message) => { console.error(message); },
21
+ shell: () => window.__wsShell ?? null,
22
+ });
23
+ window.__wsDevScene = page.report;