@wildshard/sdk 0.3.1 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/GUIDE.md +19 -6
- package/bin/wildshard.mjs +4 -0
- package/docs/api/EXPORT-TIERS.md +3 -2
- package/lint/export-tiers.json +1 -0
- package/lint/sdk-plugin.d.mts +2 -0
- package/lint/sdk-plugin.mjs +39 -1
- package/package.json +10 -9
- package/scripts/capture-hero.mjs +48 -18
- package/scripts/ci21-sdk-tail-lint.mjs +95 -0
- package/scripts/keep-copy.mjs +172 -0
- package/scripts/land.mjs +34 -4
- package/scripts/lane-live.mjs +136 -0
- package/scripts/leftovers-report.mjs +47 -0
- package/scripts/lint-dispatch.mjs +5 -0
- package/scripts/music/export-midi.mjs +3 -2
- package/scripts/prepare-product.mjs +3 -2
- package/scripts/scratch-dir.d.mts +3 -0
- package/scripts/scratch-dir.mjs +33 -14
- package/scripts/scratch-sweep.mjs +15 -23
- package/scripts/typecheck.mjs +15 -0
- package/scripts/worktree-reap.mjs +46 -104
- package/scripts/worktree.mjs +35 -13
- package/skills/wildshard/SKILL.md +3 -1
- package/src/cli/content-command.ts +44 -0
- package/src/cli/content.ts +287 -0
- package/src/cli/help.ts +7 -2
- package/src/cli/hero/hero.ts +51 -3
- package/src/cli/hero/scene-card.ts +46 -0
- package/src/cli/hero/stamp.ts +5 -3
- package/src/sharddev/authorManifest.ts +20 -2
- package/src/sharddev/cli.ts +1 -1
- package/src/sharddev/dev.ts +23 -4
- package/src/sharddev/newProject.ts +27 -8
- package/src/sharddev/project.ts +2 -2
- package/src/sharddev/refusals.ts +1 -0
- package/src/sharddev/scene/author.ts +22 -1
- package/src/sharddev/scene/budget.ts +87 -0
- package/src/sharddev/scene/creature.ts +171 -0
- package/src/sharddev/scene/description.ts +41 -0
- package/src/sharddev/scene/lower.ts +127 -3
- package/src/sharddev/scene/shardfile.ts +222 -20
- package/src/sharddev/shardSource.ts +2 -2
- package/src/sharddev/test/diskScriptScenario.ts +4 -2
- package/src/sharddev/test/ownedScratch.ts +14 -0
- package/src/sharddev/test/scriptScenario.ts +18 -13
- package/src/sharddev/tsconfig.json +3 -0
- package/src/sharddev/watch/pageEntry.ts +1 -19
- package/src/sharddev/watch/parity-baseline.json +8 -8
- package/src/sharddev/watch/parity.mjs +24 -0
- package/src/sharddev/watch/watch.ts +10 -2
- package/src/shards/_template/behaviour/boss.as +13 -4
- package/src/shards/_template/behaviour/door.as +8 -3
- package/src/shards/_template/behaviour/hooks.json +35 -0
- package/src/shards/_template/card/landscape.jpg +0 -0
- package/src/shards/_template/card/portrait.jpg +0 -0
- package/src/shards/_template/card/thumb.jpg +0 -0
- package/src/shards/_template/data/bossDecision.json +11 -1
- package/src/shards/_template/data/card.json +49 -1
- package/src/shards/_template/data/clientScripts.json +411 -0
- package/src/shards/_template/data/creatures.json +280 -2
- package/src/shards/_template/data/items.json +1 -1
- package/src/shards/_template/data/layout.json +32 -1
- package/src/shards/_template/data/ledger.json +45 -0
- package/src/shards/_template/data/npcs/hermit.json +72 -0
- package/src/shards/_template/data/quests.json +297 -11
- package/src/shards/_template/data/rows.json +154 -0
- package/src/shards/_template/data/skins.json +14 -0
- package/src/shards/_template/data/targets.json +47 -0
- package/src/shards/_template/data/text.json +4 -1
- package/src/shards/_template/generators/lift.ts +71 -0
- package/src/shards/_template/generators/product.ts +19 -5
- package/src/shards/_template/generators/templatePropsSource.ts +5 -4
- package/src/shards/_template/generators/terrain.ts +10 -2
- package/src/shards/_template/generators/world.ts +42 -7
- package/src/shards/_template/hero.json +6 -6
- package/src/shards/_template/manifest.json +49 -1
- package/src/shards/authoring-slice/generators/shard.ts +2 -1
- package/src/shards/authoring-slice/generators/world.ts +8 -1
- package/tsconfig.author.json +24 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Box3, BufferAttribute, BufferGeometry, Color, Float32BufferAttribute, Matrix3, Matrix4, MeshStandardMaterial, Quaternion, Vector3 } from 'three';
|
|
1
|
+
import { Box3, BufferAttribute, BufferGeometry, Color, DoubleSide, Float32BufferAttribute, FrontSide, Matrix3, Matrix4, MeshStandardMaterial, Quaternion, Vector3 } from 'three';
|
|
2
2
|
import type { PoolSurface } from '@wildshard/format/pool-surface';
|
|
3
3
|
import { parseShardfile, type Shardfile } from '@wildshard/format/shardSchema';
|
|
4
4
|
import { emptyShardfile } from '../author';
|
|
@@ -11,7 +11,10 @@ import { encodeTerrainTile } from '@wildshard/format/terrainTileBytes';
|
|
|
11
11
|
import { bakeRawColourPixels } from '../bake/rawTexture';
|
|
12
12
|
import type { Rgb, SceneCollider, SceneDraw, SceneGeometry, SceneLight, SceneMaterial, SceneMotion, ScenePart, ShardScene } from './description';
|
|
13
13
|
import { SceneRefusalError } from './lower';
|
|
14
|
+
import { budgetReport, partBudgets } from './budget';
|
|
15
|
+
import { coarseGeometry } from '../bake/coarseCopy';
|
|
14
16
|
import { hashOf } from './hash';
|
|
17
|
+
import { detailFileFaults, detailMeshBytes } from '@wildshard/format/look-details';
|
|
15
18
|
|
|
16
19
|
/**
|
|
17
20
|
* AUTHORING-PARITY AP2, AP3, AP4: the shardfile back end. It reads only the scene description and writes the sections an
|
|
@@ -35,7 +38,7 @@ import { hashOf } from './hash';
|
|
|
35
38
|
* `motion`, a mesh's `sway` to its entry's `sway` plus a `_SWAY` channel (metres, growing with the square of the height
|
|
36
39
|
* over the mesh's own bounds), a mesh's `uvScroll` to its entry's `uvScroll`.
|
|
37
40
|
*
|
|
38
|
-
* Phone tile caps are reported, not enforced (J338: this shard may use up to 50 MB)
|
|
41
|
+
* Phone tile caps are reported, not enforced (J338: this shard may use up to 50 MB), as AP9a's per-part table (`budget.ts`).
|
|
39
42
|
*/
|
|
40
43
|
|
|
41
44
|
export interface ShardfileOptions {
|
|
@@ -120,6 +123,28 @@ function mergeDraws(key: string, draws: readonly SceneDraw[], scene: ShardScene,
|
|
|
120
123
|
interface InstancedGroup { key: string; geometry: BufferGeometry; matrices: Matrix4[]; colours: Color[] | null; castShadow: boolean; box: Box3 }
|
|
121
124
|
/** The fewest copies a draw needs to stay instanced (below it the merge is as small). */
|
|
122
125
|
const INSTANCE_MIN = 2, INSTANCE_CAP = 10_000;
|
|
126
|
+
/**
|
|
127
|
+
* AP9c: the coarse (L1) copies the back end writes itself, so no author keeps a hand coarse list. An L1 tile (two by two
|
|
128
|
+
* fine tiles) draws past the fine ring, from about 150 m: its still meshes are simplified toward a quarter of their
|
|
129
|
+
* triangles (half a metre of error for the bounded pass; past 1.5 times the target meshopt's topology-free pass takes over,
|
|
130
|
+
* with no metre bound), and an instanced shape smaller than COARSE_MIN_SIZE across in its own frame (grass, flowers) stays
|
|
131
|
+
* near-only.
|
|
132
|
+
*/
|
|
133
|
+
const COARSE_RATIO = 0.25, COARSE_ERROR = 0.5, COARSE_MIN_SIZE = 2;
|
|
134
|
+
/** A simplified geometry with only the vertices its index still names (the simplifier keeps every vertex). */
|
|
135
|
+
function compacted(source: BufferGeometry): BufferGeometry {
|
|
136
|
+
const index = source.getIndex(); if (index === null) return source;
|
|
137
|
+
const remap = new Map<number, number>(), order: number[] = [], next: number[] = [];
|
|
138
|
+
for (const at of index.array) { let to = remap.get(at); if (to === undefined) { to = order.length; remap.set(at, to); order.push(at); } next.push(to); }
|
|
139
|
+
const out = new BufferGeometry();
|
|
140
|
+
for (const [name, attribute] of Object.entries(source.attributes)) {
|
|
141
|
+
const size = attribute.itemSize, values = new Float32Array(order.length * size);
|
|
142
|
+
order.forEach((from, i) => { for (let c = 0; c < size; c++) values[i * size + c] = attribute.getComponent(from, c); });
|
|
143
|
+
out.setAttribute(name, new BufferAttribute(values, size));
|
|
144
|
+
}
|
|
145
|
+
out.setIndex(next);
|
|
146
|
+
return out;
|
|
147
|
+
}
|
|
123
148
|
|
|
124
149
|
/** A copy the engine's loader can place: translation, rotation and a positive scale, no shear (the loader reads instance
|
|
125
150
|
* TRS rows; an exact `_MATRIX` row loads as the identity there). */
|
|
@@ -224,6 +249,16 @@ function appendCard(key: string, seat: readonly [number, number, number], size:
|
|
|
224
249
|
merge.index.push(base, base + 1, base + 2, base, base + 2, base + 3);
|
|
225
250
|
}
|
|
226
251
|
|
|
252
|
+
/**
|
|
253
|
+
* A tile GLB's material for one entry: white, vertex-coloured, and double-sided when the scene's material is (AP16w). The
|
|
254
|
+
* engine draws a prop mesh with the side its GLB material says, so a crossed grass card left one-sided lost its back faces in
|
|
255
|
+
* build while watch drew them.
|
|
256
|
+
*/
|
|
257
|
+
function glbMaterial(name: string, material: SceneMaterial): MeshStandardMaterial {
|
|
258
|
+
const glb = new MeshStandardMaterial({ color: 0xffffff, vertexColors: true, side: material.side === 'double' ? DoubleSide : FrontSide }); glb.name = name;
|
|
259
|
+
return glb;
|
|
260
|
+
}
|
|
261
|
+
|
|
227
262
|
/** A merge cut into primitives of at most 200,000 vertices, each with its own compact vertex list. */
|
|
228
263
|
/** One entry's merge as GLB primitives: a card's corners and a swaying surface's amplitude ride their own channels (AP11, AP12). */
|
|
229
264
|
function primitivesOf(merge: Merge, entry: Entry, name: string, castShadow: boolean): GlbPrimitive[] {
|
|
@@ -233,14 +268,37 @@ function primitivesOf(merge: Merge, entry: Entry, name: string, castShadow: bool
|
|
|
233
268
|
.setAttribute('uv', new Float32BufferAttribute(chunk.uv, 2)).setAttribute('color', new BufferAttribute(new Float32Array(chunk.colour), 3)).setIndex(chunk.index);
|
|
234
269
|
if (entry.card) geometry.setAttribute('corner', new Float32BufferAttribute(chunk.corner, 2));
|
|
235
270
|
if (swaying) geometry.setAttribute('sway', new Float32BufferAttribute(chunk.sway, 1));
|
|
236
|
-
const material =
|
|
271
|
+
const material = glbMaterial(name, entry.material);
|
|
237
272
|
const primitive: GlbPrimitive = { geometry, material, castShadow: entry.card ? false : castShadow };
|
|
238
273
|
if (entry.card) primitive.customAttributes = { _CORNER: 'corner' }; else if (swaying) primitive.customAttributes = { _SWAY: 'sway' };
|
|
239
274
|
return primitive;
|
|
240
275
|
});
|
|
241
276
|
}
|
|
242
277
|
|
|
243
|
-
/**
|
|
278
|
+
/** A primitive's GLB bytes, near enough to batch by: 44 a vertex (position, normal, uv, colour, one more channel), 4 an index, 76 an instance. */
|
|
279
|
+
function glbBytes(primitive: GlbPrimitive): number {
|
|
280
|
+
return primitive.geometry.getAttribute('position').count * 44 + (primitive.geometry.getIndex()?.count ?? 0) * 4 + (primitive.instances?.length ?? 0) * 76;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** `from`'s vertices and triangles added to `into` (AP16's panels: one merge a material across tiles). */
|
|
284
|
+
function appendMerge(into: Merge, from: Merge): void {
|
|
285
|
+
const base = into.position.length / 3;
|
|
286
|
+
// element by element: a spread of a large merge overflows the call stack
|
|
287
|
+
for (const channel of ['position', 'normal', 'uv', 'colour', 'sway', 'corner'] as const) for (const value of from[channel]) into[channel].push(value);
|
|
288
|
+
for (const at of from.index) into.index.push(at + base);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* AP26: the two server figures a scene shard declares rather than sums. `SIM_CEILING` is the bytes the server reserves for
|
|
293
|
+
* the shard's simulation in each cell it runs (engine `server/game/plugin/simulation.ts`), which shard-format reads as the
|
|
294
|
+
* authoring ceiling `budgets.sim.resident` (`runtimeCost.ts`, scripts at their growth limit): a ceiling, so no sum of
|
|
295
|
+
* critical bytes. It is also the server's `memory`. `SERVER_TICK_MICROS` is the server tick's time a scene shard may spend.
|
|
296
|
+
* Later steps add their own critical bytes on top (behaviour scripts, platform sections, the authored world).
|
|
297
|
+
*/
|
|
298
|
+
export const SIM_CEILING = 16_000_000, SERVER_TICK_MICROS = 5_000;
|
|
299
|
+
|
|
300
|
+
/** AP16: what the library (AP26: or critical) roots cost with their dependencies (format asset admission's `budgets.library`
|
|
301
|
+
* and `budgets.sim` checks). */
|
|
244
302
|
function libraryCost(files: Shardfile['files'], roots: readonly string[]): { resident: number; compressed: number } {
|
|
245
303
|
const byHash = new Map(files.map((f) => [f.hash, f])), seen = new Set<string>(), pending = [...roots];
|
|
246
304
|
let resident = 0, compressed = 0;
|
|
@@ -410,9 +468,8 @@ export function compileShardfile(scene: ShardScene, ctx: ProjectGenerationContex
|
|
|
410
468
|
const { shard, assets, report } = sceneShardfile(scene, options);
|
|
411
469
|
for (const [hash, bytes] of assets) if (ctx.asset(bytes) !== hash) throw new Error('scene: an asset hash differs from the product store');
|
|
412
470
|
if (report.lampsDropped > 0) console.info(`scene: ${report.lampsDropped} point lights past the 16 brightest are not in the shardfile (AP28)`);
|
|
413
|
-
//
|
|
414
|
-
const
|
|
415
|
-
if (over.length > 0) console.info(`scene: ${over.length} tiles are over the phone tile triangle cap (J338; AP9 turns this into a per-part table): ${over.map((t) => `${t.tile} ${t.triangles} tris ${t.draws} draws`).join(', ')}`);
|
|
471
|
+
// AP9a: the per-part budget table, each tier's overruns named by tile and part (reported, J338; AP8: draws are a view's)
|
|
472
|
+
for (const line of budgetReport(partBudgets(scene), report.tiles)) console.info(`scene: ${line}`);
|
|
416
473
|
return Promise.resolve({ shard, output: {} });
|
|
417
474
|
}
|
|
418
475
|
|
|
@@ -434,7 +491,8 @@ export function sceneShardfile(scene: ShardScene, options: ShardfileOptions = {}
|
|
|
434
491
|
// textures (AP2): RGBA8 KTX2, one file per painted raster
|
|
435
492
|
const textureFiles = new Map<string, Shardfile['files'][number]>();
|
|
436
493
|
// only the textures a drawn material or a card samples
|
|
437
|
-
const sampled = new Set(scene.parts.flatMap((part) => [...part.draws.map((d) => d.material), ...part.sprites.map((c) => c.material), ...part.points.map((c) => c.material)]
|
|
494
|
+
const sampled = new Set([...scene.parts.flatMap((part) => [...part.draws.map((d) => d.material), ...part.sprites.map((c) => c.material), ...part.points.map((c) => c.material)]), ...(scene.details ?? []).map((layer) => layer.material)]
|
|
495
|
+
.map((key) => scene.materials[key]?.map).filter((key) => typeof key === 'string'));
|
|
438
496
|
for (const texture of Object.values(scene.textures).filter((t) => sampled.has(t.key))) {
|
|
439
497
|
const bytes = bakeRawColourPixels({ width: texture.width, height: texture.height, pixels: new Uint8ClampedArray(texture.rgba) }, { colourSpace: texture.colourSpace });
|
|
440
498
|
textureFiles.set(texture.key, store(bytes, 'ktx2'));
|
|
@@ -483,8 +541,40 @@ export function sceneShardfile(scene: ShardScene, options: ShardfileOptions = {}
|
|
|
483
541
|
propMaterials[name] = { id: lookId(key), ...(file === undefined ? {} : { colour: { file: file.hash, wrapS: 10497, wrapT: 10497, minFilter: 9987, magFilter: 9729, anisotropy: 4 } }) };
|
|
484
542
|
}
|
|
485
543
|
lookMaterials[GROUND_MATERIAL] = groundEntry(scene);
|
|
544
|
+
// AP32c: detail layers: the card, mask and heights as plain binary files (engine G649: never base64), the card's own look
|
|
545
|
+
// entry (no vertex colours: the cards have none, the engine tints each clump)
|
|
546
|
+
const binary = (bytes: Uint8Array, gpu: number, triangles: number): string => {
|
|
547
|
+
const hash = hashImmutableBytes(bytes);
|
|
548
|
+
if (!assets.has(hash)) { assets.set(hash, bytes); files.push({ hash, kind: 'binary', compressed: bytes.length, decoded: bytes.length, gpu, triangles, draws: triangles > 0 ? 1 : 0, dependencies: [], critical: false }); }
|
|
549
|
+
return hash;
|
|
550
|
+
};
|
|
551
|
+
const detailTextures = new Set<string>();
|
|
552
|
+
const details = (scene.details ?? []).map((layer) => {
|
|
553
|
+
const material = scene.materials[layer.material], geometry = scene.geometries[layer.geometry];
|
|
554
|
+
if (material === undefined || geometry === undefined) throw new SceneRefusalError(layer.path, 'its card did not lower', 'Give world.detail an InstancedMesh with a geometry and a MeshStandardMaterial');
|
|
555
|
+
const look = lookId(`${layer.material}.detail`);
|
|
556
|
+
const entry = materialEntry({ material, motion: null, card: false });
|
|
557
|
+
entry['vertexColours'] = false;
|
|
558
|
+
// AP32d: a textured card's map is its look entry's colour map (a library KTX2, as the tiles' own), its uvs carrying the
|
|
559
|
+
// map's repeat and offset as a tile merge's do
|
|
560
|
+
const map = material.map === null ? undefined : textureFiles.get(material.map);
|
|
561
|
+
if (map !== undefined) { entry['maps'] = { colour: map.hash, normal: null, orm: null }; detailTextures.add(map.hash); }
|
|
562
|
+
lookMaterials[look] = entry;
|
|
563
|
+
const mesh = detailMeshFile(geometry, material), { region } = layer;
|
|
564
|
+
const faults = detailFileFaults({ id: layer.id, mesh: { file: '', vertices: mesh.vertices, triangles: mesh.triangles }, region }, { mesh: mesh.bytes, mask: layer.mask, heights: layer.heights });
|
|
565
|
+
if (faults.length > 0) throw new SceneRefusalError(layer.path, faults.join('; '), 'Report this: the sdk wrote a detail file the format refuses');
|
|
566
|
+
const row: Record<string, unknown> = {
|
|
567
|
+
id: layer.id, material: look, mesh: { file: binary(mesh.bytes, mesh.bytes.length, mesh.triangles), vertices: mesh.vertices, triangles: mesh.triangles },
|
|
568
|
+
region: { corner: [round(region.corner[0], 3), round(region.corner[1], 3)], cell: region.cell, columns: region.columns, rows: region.rows, span: [round(region.span[0], 3), round(region.span[1], 3)] },
|
|
569
|
+
mask: binary(layer.mask, 0, 0), heights: binary(layer.heights, 0, 0), clumps: layer.clumps,
|
|
570
|
+
scale: [round(layer.scale[0], 3), round(layer.scale[1], 3)], tilt: round(clamp01(layer.tilt), 3), tint: [srgb01(layer.tint[0]), srgb01(layer.tint[1])],
|
|
571
|
+
radius: layer.radius, shadow: layer.shadow,
|
|
572
|
+
};
|
|
573
|
+
if (layer.sway !== null) row['sway'] = { amount: round(clamp01(layer.sway.amount), 3), rate: round(layer.sway.rate, 3) };
|
|
574
|
+
return row as { mesh: { file: string }; mask: string; heights: string };
|
|
575
|
+
});
|
|
486
576
|
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] } }));
|
|
487
|
-
const propTiles: { lod: 0; x: number; z: number; file: string }[] = [], tileReport: { tile: string; triangles: number; draws: number; bytes: number }[] = [];
|
|
577
|
+
const propTiles: { lod: 0 | 1; x: number; z: number; file: string }[] = [], tileReport: { tile: string; triangles: number; draws: number; bytes: number }[] = [];
|
|
488
578
|
const addresses = [...new Set([...tiles.keys(), ...instanced.keys()])].sort((a, b) => a.localeCompare(b));
|
|
489
579
|
for (const address of addresses) {
|
|
490
580
|
const merges = tiles.get(address) ?? new Map<string, Merge>();
|
|
@@ -508,10 +598,10 @@ export function sceneShardfile(scene: ShardScene, options: ShardfileOptions = {}
|
|
|
508
598
|
// AP15: the tile's instance groups, at most INSTANCE_CAP copies a node
|
|
509
599
|
for (const group of instanced.get(address) ?? []) {
|
|
510
600
|
const entry = entries.get(group.key), material = entry?.material; if (entry === undefined || material === undefined) continue;
|
|
511
|
-
const
|
|
601
|
+
const groupMaterial = glbMaterial(glbNames.get(group.key) ?? group.key, material);
|
|
512
602
|
for (let from = 0; from < group.matrices.length; from += INSTANCE_CAP) {
|
|
513
603
|
const colours = group.colours?.slice(from, from + INSTANCE_CAP);
|
|
514
|
-
primitives.push({ geometry: group.geometry, material:
|
|
604
|
+
primitives.push({ geometry: group.geometry, material: groupMaterial, castShadow: group.castShadow, instances: group.matrices.slice(from, from + INSTANCE_CAP), ...(colours === undefined ? {} : { instanceColours: colours }) });
|
|
515
605
|
}
|
|
516
606
|
drawn.union(group.box);
|
|
517
607
|
const file = material.map === null ? undefined : textureFiles.get(material.map); if (file !== undefined) dependencies.add(file.hash);
|
|
@@ -520,7 +610,7 @@ export function sceneShardfile(scene: ShardScene, options: ShardfileOptions = {}
|
|
|
520
610
|
// a GLB holds at most 25 MB (shard-format glbCost): batch the primitives into as many files as the tile needs
|
|
521
611
|
const batches: GlbPrimitive[][] = []; let batch: GlbPrimitive[] = [], bytes = 0;
|
|
522
612
|
for (const primitive of primitives) {
|
|
523
|
-
const size =
|
|
613
|
+
const size = glbBytes(primitive);
|
|
524
614
|
if (batch.length > 0 && bytes + size > 18_000_000) { batches.push(batch); batch = []; bytes = 0; }
|
|
525
615
|
batch.push(primitive); bytes += size;
|
|
526
616
|
}
|
|
@@ -547,20 +637,90 @@ export function sceneShardfile(scene: ShardScene, options: ShardfileOptions = {}
|
|
|
547
637
|
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) };
|
|
548
638
|
tileReport.push({ tile: `0/${x}/${z}`, triangles: row.triangles, draws: row.draws, bytes: row.compressed });
|
|
549
639
|
}
|
|
640
|
+
// AP9c: each L1 tile carries a simplified copy of its four fine tiles' still meshes and of their larger instanced shapes;
|
|
641
|
+
// cards and moving entries stay near-only. The engine draws an L1 tile where its fine tiles are not resident.
|
|
642
|
+
const coarseShapes = new Map<BufferGeometry, BufferGeometry>();
|
|
643
|
+
const coarseShape = (geometry: BufferGeometry): BufferGeometry => {
|
|
644
|
+
const found = coarseShapes.get(geometry); if (found !== undefined) return found;
|
|
645
|
+
const simplified = compacted(coarseGeometry(geometry, COARSE_RATIO, COARSE_ERROR, { sloppy: true }));
|
|
646
|
+
// a shape simplified to nothing keeps its own geometry (an empty GLB accessor is refused)
|
|
647
|
+
const made = (simplified.getIndex()?.count ?? 0) === 0 ? geometry : simplified; coarseShapes.set(geometry, made); return made;
|
|
648
|
+
};
|
|
649
|
+
for (let x = 0; x < 4; x++) for (let z = 0; z < 4; z++) {
|
|
650
|
+
const children = [[0, 0], [0, 1], [1, 0], [1, 1]].map(([dx = 0, dz = 0]) => `${String(x * 2 + dx)}/${String(z * 2 + dz)}`);
|
|
651
|
+
const byKey = new Map<string, Merge>();
|
|
652
|
+
for (const child of children) {
|
|
653
|
+
for (const [key, merge] of [...(tiles.get(child) ?? new Map<string, Merge>())].sort(([p], [q]) => p.localeCompare(q))) {
|
|
654
|
+
const entry = entries.get(key); if (entry === undefined || entry.card || entry.motion !== null || merge.position.length === 0) continue;
|
|
655
|
+
const whole = byKey.get(key) ?? emptyMerge(); appendMerge(whole, merge); byKey.set(key, whole);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
const primitives: GlbPrimitive[] = [], dependencies = new Set<string>(), drawn = new Box3();
|
|
659
|
+
for (const [key, merge] of [...byKey].sort(([p], [q]) => p.localeCompare(q))) {
|
|
660
|
+
const entry = entries.get(key); if (entry === undefined) continue;
|
|
661
|
+
for (const primitive of primitivesOf(merge, entry, glbNames.get(key) ?? key, false)) {
|
|
662
|
+
const geometry = compacted(coarseGeometry(primitive.geometry, COARSE_RATIO, COARSE_ERROR, { sloppy: true }));
|
|
663
|
+
if ((geometry.getIndex()?.count ?? 0) === 0) continue;
|
|
664
|
+
primitives.push({ ...primitive, geometry });
|
|
665
|
+
}
|
|
666
|
+
const file = entry.material.map === null ? undefined : textureFiles.get(entry.material.map); if (file !== undefined) dependencies.add(file.hash);
|
|
667
|
+
}
|
|
668
|
+
for (const child of children) for (const group of instanced.get(child) ?? []) {
|
|
669
|
+
const entry = entries.get(group.key); if (entry === undefined) continue;
|
|
670
|
+
group.geometry.computeBoundingBox(); const box = group.geometry.boundingBox;
|
|
671
|
+
if (box === null || box.max.x - box.min.x < COARSE_MIN_SIZE && box.max.y - box.min.y < COARSE_MIN_SIZE && box.max.z - box.min.z < COARSE_MIN_SIZE) continue;
|
|
672
|
+
const geometry = coarseShape(group.geometry), material = glbMaterial(glbNames.get(group.key) ?? group.key, entry.material);
|
|
673
|
+
for (let from = 0; from < group.matrices.length; from += INSTANCE_CAP) {
|
|
674
|
+
const colours = group.colours?.slice(from, from + INSTANCE_CAP);
|
|
675
|
+
primitives.push({ geometry, material, castShadow: false, instances: group.matrices.slice(from, from + INSTANCE_CAP), ...(colours === undefined ? {} : { instanceColours: colours }) });
|
|
676
|
+
}
|
|
677
|
+
drawn.union(group.box);
|
|
678
|
+
const file = entry.material.map === null ? undefined : textureFiles.get(entry.material.map); if (file !== undefined) dependencies.add(file.hash);
|
|
679
|
+
}
|
|
680
|
+
if (primitives.length === 0) continue;
|
|
681
|
+
for (const primitive of primitives) if (primitive.instances === undefined) { primitive.geometry.computeBoundingBox(); if (primitive.geometry.boundingBox !== null) drawn.union(primitive.geometry.boundingBox); }
|
|
682
|
+
const size = primitives.reduce((n, primitive) => n + glbBytes(primitive), 0);
|
|
683
|
+
if (size > 18_000_000) throw new Error(`scene: the generated L1 tile 1/${String(x)}/${String(z)} is ${(size / 1e6).toFixed(1)} MB, over the 18 MB one GLB holds (AP9c)`);
|
|
684
|
+
const row = store(staticGlb(primitives, `scene.l1.${String(x)}.${String(z)}`), 'glb', [...dependencies].sort());
|
|
685
|
+
propTiles.push({ lod: 1, x, z, file: row.hash });
|
|
686
|
+
const tile = shardTiles.find((t) => t.lod === 1 && t.x === x && t.z === z);
|
|
687
|
+
if (tile === undefined) throw new Error(`scene: no terrain tile 1/${String(x)}/${String(z)}`);
|
|
688
|
+
const textures = [...dependencies].map((hash) => files.find((f) => f.hash === hash)).filter((f) => f !== undefined);
|
|
689
|
+
tile.files.push(row.hash, ...textures.map((f) => f.hash).filter((hash) => !tile.files.includes(hash)));
|
|
690
|
+
tile.compressed += row.compressed + textures.reduce((n, f) => n + f.compressed, 0); tile.decoded += row.decoded + textures.reduce((n, f) => n + f.decoded, 0);
|
|
691
|
+
tile.gpu += row.gpu + textures.reduce((n, f) => n + f.gpu, 0); tile.triangles += row.triangles; tile.draws += row.draws;
|
|
692
|
+
if (!drawn.isEmpty()) {
|
|
693
|
+
tile.bounds.min[1] = Math.min(tile.bounds.min[1], drawn.min.y); tile.bounds.max[1] = Math.max(tile.bounds.max[1], drawn.max.y);
|
|
694
|
+
// an instanced copy is whole in its seat's tile, so it may hang over the L1 tile's edge: its draw bounds say so
|
|
695
|
+
if (drawn.min.x < tile.bounds.min[0] || drawn.min.z < tile.bounds.min[2] || drawn.max.x > tile.bounds.max[0] || drawn.max.z > tile.bounds.max[2]) {
|
|
696
|
+
const low = (v: number): number => Math.max(-HALF - OVERHANG, Math.floor(v * 1000) / 1000), high = (v: number): number => Math.min(HALF + OVERHANG, Math.ceil(v * 1000) / 1000);
|
|
697
|
+
tile.drawBounds = { min: [low(Math.min(tile.bounds.min[0], drawn.min.x)), tile.bounds.min[1], low(Math.min(tile.bounds.min[2], drawn.min.z))],
|
|
698
|
+
max: [high(Math.max(tile.bounds.max[0], drawn.max.x)), tile.bounds.max[1], high(Math.max(tile.bounds.max[2], drawn.max.z))] };
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
}
|
|
550
702
|
// panels (AP16): one library GLB each, its texture slots as dependencies
|
|
551
703
|
const panels = panelParts.map(({ id, merges, shadows }) => {
|
|
552
704
|
const primitives: GlbPrimitive[] = [], dependencies = new Set<string>();
|
|
705
|
+
// the panel is one GLB: a material's triangles in every tile it crosses are one merge again, so one draw, not one a tile
|
|
706
|
+
const byKey = new Map<string, Merge>();
|
|
553
707
|
for (const [, tile] of [...merges].sort(([a], [b]) => a.localeCompare(b))) {
|
|
554
|
-
for (const [key, merge] of [...tile].sort(([a], [b]) => a.localeCompare(b))) {
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
708
|
+
for (const [key, merge] of [...tile].sort(([a], [b]) => a.localeCompare(b))) { const whole = byKey.get(key); if (whole === undefined) byKey.set(key, merge); else appendMerge(whole, merge); }
|
|
709
|
+
}
|
|
710
|
+
for (const [key, merge] of [...byKey].sort(([a], [b]) => a.localeCompare(b))) {
|
|
711
|
+
const entry = entries.get(key); if (entry === undefined || merge.position.length === 0) continue;
|
|
712
|
+
primitives.push(...primitivesOf(merge, entry, glbNames.get(key) ?? key, shadows.get(key) ?? true));
|
|
713
|
+
const file = entry.material.map === null ? undefined : textureFiles.get(entry.material.map); if (file !== undefined) dependencies.add(file.hash);
|
|
559
714
|
}
|
|
560
715
|
if (primitives.length === 0) throw new SceneRefusalError(id, 'a panel part draws nothing', 'Give the panel part a visible mesh, or drop its panel option');
|
|
716
|
+
// a panel is one library file (format props `panels[].file`), and a GLB holds at most 25 MB: the tiles' 18 MB batch is
|
|
717
|
+
// not open to it, so a panel past that is refused here, by name, not at admission
|
|
718
|
+
const size = primitives.reduce((n, primitive) => n + glbBytes(primitive), 0);
|
|
719
|
+
if (size > 18_000_000) throw new SceneRefusalError(id, `a panel part's mesh is ${(size / 1e6).toFixed(1)} MB, over the 18 MB a panel GLB holds`, 'Split it into smaller panel parts, or drop detail from its meshes');
|
|
561
720
|
return { id, file: store(staticGlb(primitives, `scene.panel.${id}`), 'glb', [...dependencies].sort()).hash, visible: true };
|
|
562
721
|
});
|
|
563
|
-
|
|
722
|
+
// AP32c: a detail layer's three files load with the shard (the charged library), not per tile
|
|
723
|
+
const library = [...panels.map((panel) => panel.file), ...details.flatMap((row) => [row.mesh.file, row.mask, row.heights]), ...[...detailTextures].sort()];
|
|
564
724
|
// colliders (AP4); a panel part's solids are its panel's one collider (AP16)
|
|
565
725
|
const colliders = scene.parts.filter((part) => part.colliders.length > 0).map((part) => ({ id: part.panel ?? `scene.${part.name}`, panel: part.panel ?? null, initialActive: true, shapes: part.colliders.map(boxRow) }));
|
|
566
726
|
// water (AP4)
|
|
@@ -570,8 +730,9 @@ export function sceneShardfile(scene: ShardScene, options: ShardfileOptions = {}
|
|
|
570
730
|
const [sx, sy, sz] = scene.spawn.position;
|
|
571
731
|
const spawnY = Math.max(sy, (ground?.heightAt(sx, sz) ?? 0) + 1);
|
|
572
732
|
const product = {
|
|
573
|
-
...base, budgets: { ...base.budgets, library: libraryCost(files, library), sim: { resident:
|
|
574
|
-
|
|
733
|
+
...base, budgets: { ...base.budgets, library: libraryCost(files, library), sim: { resident: SIM_CEILING, compressed: libraryCost(files, terrain.critical).compressed } },
|
|
734
|
+
serverBudget: { ...base.serverBudget, tickMicros: SERVER_TICK_MICROS, memory: SIM_CEILING },
|
|
735
|
+
look: { ...sceneLook(scene, lights, lookMaterials), ...(details.length === 0 ? {} : { details }) }, spawn: { x: round(sx, 3), y: round(spawnY, 3), z: round(sz, 3), yaw: round(scene.spawn.yaw, 4) },
|
|
575
736
|
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,
|
|
576
737
|
critical: [...terrain.critical], far: null, library: [...base.library, ...library],
|
|
577
738
|
props: { version: 1, family: 'pbr', overhang: OVERHANG, tiles: propTiles, panels, models: [], far: null, textures: [], colliders, ...(Object.keys(propMaterials).length === 0 ? {} : { materials: propMaterials }) },
|
|
@@ -580,6 +741,7 @@ export function sceneShardfile(scene: ShardScene, options: ShardfileOptions = {}
|
|
|
580
741
|
// oxlint-disable-next-line unicorn/prefer-structured-clone -- JSON wire normalization (signed zero), as product.ts does
|
|
581
742
|
let shard = parseShardfile(JSON.parse(JSON.stringify(product)));
|
|
582
743
|
if (options.extend !== undefined) shard = options.extend(shard);
|
|
744
|
+
shard = withAnchored(shard, scene.anchored);
|
|
583
745
|
return { shard, assets, report: { cards, lampsDropped: Math.max(0, lights.filter((l) => l.kind === 'point').length - 16), tiles: tileReport } };
|
|
584
746
|
}
|
|
585
747
|
|
|
@@ -609,6 +771,46 @@ export function sceneGameplay(identity: ShardScene['identity'], options: Shardfi
|
|
|
609
771
|
return { gameplay, rest };
|
|
610
772
|
}
|
|
611
773
|
|
|
774
|
+
/**
|
|
775
|
+
* AP25: the scene's anchored rows merged into the sections `extend` wrote (`quests.triggers`, `targets.interactions`), after
|
|
776
|
+
* it, so an `extend` that replaces `quests` keeps them. An id `extend` already declares is refused: one place, one row.
|
|
777
|
+
*/
|
|
778
|
+
export function withAnchored<T extends { quests?: unknown; targets?: unknown }>(shard: T, anchored: ShardScene['anchored']): T {
|
|
779
|
+
if (anchored.triggers.length === 0 && anchored.interactions.length === 0) return shard;
|
|
780
|
+
const quests = (shard.quests ?? { flags: [], quests: [], triggers: [], dialogue: [] }) as { flags?: readonly string[]; triggers?: readonly { id: string }[] };
|
|
781
|
+
// a trigger's flag is a quest flag: declare the ones `extend` did not (review SHOULD 4)
|
|
782
|
+
const flags = [...quests.flags ?? []]; for (const t of anchored.triggers) if (!flags.includes(t.flag)) flags.push(t.flag);
|
|
783
|
+
const targets = (shard.targets ?? { panels: [], interactions: [] }) as { interactions?: readonly { id: string }[] };
|
|
784
|
+
const twice = (rows: readonly { id: string }[], added: readonly { id: string }[], what: string): void => {
|
|
785
|
+
const taken = new Set(rows.map((row) => row.id)), clash = added.find((row) => taken.has(row.id));
|
|
786
|
+
if (clash !== undefined) throw new SceneRefusalError(clash.id, `extend declares ${what} ${clash.id} too`, `Declare it once: drop the row from extend, or rename the scene's`);
|
|
787
|
+
};
|
|
788
|
+
twice(quests.triggers ?? [], anchored.triggers, 'trigger'); twice(targets.interactions ?? [], anchored.interactions, 'interaction');
|
|
789
|
+
return {
|
|
790
|
+
...shard,
|
|
791
|
+
...(anchored.triggers.length === 0 ? {} : { quests: { ...quests, flags, triggers: [...quests.triggers ?? [], ...anchored.triggers] } }),
|
|
792
|
+
...(anchored.interactions.length === 0 ? {} : { targets: { ...targets, interactions: [...targets.interactions ?? [], ...anchored.interactions] } }),
|
|
793
|
+
};
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
/**
|
|
797
|
+
* AP32c: a detail card in the format's mesh file layout (`look-details-bytes.ts`): f32 positions, normals and uvs (zero
|
|
798
|
+
* when the card has none), then u16 indices (in order when it has no index).
|
|
799
|
+
*/
|
|
800
|
+
export function detailMeshFile(geometry: SceneGeometry, material?: Pick<SceneMaterial, 'repeat' | 'offset'>): { bytes: Uint8Array; vertices: number; triangles: number } {
|
|
801
|
+
const vertices = geometry.position.length / 3, triangles = geometry.triangles;
|
|
802
|
+
const indices = Uint16Array.from(geometry.index ?? Array.from({ length: triangles * 3 }, (_, i) => i));
|
|
803
|
+
const floats = new Float32Array(vertices * 8);
|
|
804
|
+
floats.set(geometry.position, 0); floats.set(geometry.normal, vertices * 3);
|
|
805
|
+
if (geometry.uv !== null) {
|
|
806
|
+
const [ru, rv] = material?.repeat ?? [1, 1], [ou, ov] = material?.offset ?? [0, 0];
|
|
807
|
+
for (let at = 0; at < vertices; at++) { floats[vertices * 6 + at * 2] = (geometry.uv[at * 2] ?? 0) * ru + ou; floats[vertices * 6 + at * 2 + 1] = (geometry.uv[at * 2 + 1] ?? 0) * rv + ov; }
|
|
808
|
+
}
|
|
809
|
+
const bytes = new Uint8Array(detailMeshBytes(vertices, triangles));
|
|
810
|
+
bytes.set(new Uint8Array(floats.buffer), 0); bytes.set(new Uint8Array(indices.buffer), floats.byteLength);
|
|
811
|
+
return { bytes, vertices, triangles };
|
|
812
|
+
}
|
|
813
|
+
|
|
612
814
|
/** The scene's ground as the terrain bake reads it: the declared height field, or a flat cell. */
|
|
613
815
|
function groundSource(scene: ShardScene): Parameters<typeof bakeTerrain>[0] {
|
|
614
816
|
const ground = scene.ground;
|
|
@@ -43,9 +43,9 @@ export function shardRepoRoot(source: string): string {
|
|
|
43
43
|
const given = resolve(source), parent = dirname(given);
|
|
44
44
|
if (isRepoSource(given)) return parent;
|
|
45
45
|
if (basename(parent) === 'shards' && basename(dirname(parent)) === 'src') return dirname(dirname(parent));
|
|
46
|
-
for (let at =
|
|
46
|
+
for (let at = given; ; at = dirname(at)) {
|
|
47
47
|
if (existsSync(resolve(at, 'package.json')) || existsSync(resolve(at, '.git'))) return at;
|
|
48
|
-
if (dirname(at) === at) return
|
|
48
|
+
if (dirname(at) === at) return given;
|
|
49
49
|
}
|
|
50
50
|
}
|
|
51
51
|
|
|
@@ -28,12 +28,13 @@ export async function readDiskScriptScenario(slug: string, id: string, options:
|
|
|
28
28
|
const rows = decisionScriptsFromSections(sections);
|
|
29
29
|
const row = rows.find(value => value.id === id), ordinal = rows.findIndex(value => value.id === id);
|
|
30
30
|
if (row === undefined) throw new Error(`Missing simulation scenario script ${id}`);
|
|
31
|
+
if (row.side !== 'sim') throw new Error('Scenario script must run on simulation side');
|
|
31
32
|
const moves = parseActorMoves(sections.get('actors/moves') ?? []), targets = sections.get('world/targets');
|
|
32
33
|
const nativePlan = sections.get('sim/runtime-plan');
|
|
33
34
|
const nativeActors = shard.runtime === null && nativePlan !== undefined ? nativeRuntimeActorIds(nativePlan) : [];
|
|
34
35
|
const registries = buildDecisionRegistries(shard, moves, targets === undefined ? undefined : parseWorldTargets(targets), readCreatureStrikes(sections.get('actors/strikes') ?? []), rows, nativeActors);
|
|
35
36
|
const map = decisionBindingMap(row, registries), handles = Object.values(map.ids.actors ?? {});
|
|
36
|
-
const script: DecisionScript = { ...row, ids: map.ids, state: [...row.state], reads: row.reads.filter((name): name is ScriptV1ReadName => Object.hasOwn(SCRIPT_V1_READS, name)),
|
|
37
|
+
const script: DecisionScript = { ...row, side: row.side, ids: map.ids, state: [...row.state], reads: row.reads.filter((name): name is ScriptV1ReadName => Object.hasOwn(SCRIPT_V1_READS, name)),
|
|
37
38
|
lists: row.reads.filter((name): name is ScriptV1ListName => Object.hasOwn(SCRIPT_V1_LISTS, name)) };
|
|
38
39
|
const file = index.files.find(value => value.kind === 'wasm' && value.path === row.module);
|
|
39
40
|
if (file?.name === undefined) throw new Error('Scenario module requires an admitted logical blob name');
|
|
@@ -79,7 +80,8 @@ export async function readDiskScriptScenario(slug: string, id: string, options:
|
|
|
79
80
|
const bindings = 'spawnGroup' in binding ? handles.map((actor, ordinalIndex) => ({ id: ordinalIndex + 1, script: row.id, self: actor, actors: [actor], instance: 0 }))
|
|
80
81
|
: [{ id: ordinal + 1, script: row.id, self, actors: handles, instance: 0 }];
|
|
81
82
|
const primary = bindings[0]; if (primary === undefined) throw new Error('Empty scenario binding');
|
|
82
|
-
|
|
83
|
+
if(Object.keys(options.fields??{}).some(key=>!Object.hasOwn(fieldValues,key)))throw new Error('Unknown scenario shared field');
|
|
84
|
+
const made = createScriptScenario(DecisionHost, { ...options, fields:{...fieldValues,...options.fields},fieldBounds:bounds,actors, spawnGroups, seed: options.seed, script, bytes, binding: primary, bindings });
|
|
83
85
|
const entry = index.sections.find(value => value.name === 'sim/scripts'); if (entry === undefined) throw new Error('Missing scenario section');
|
|
84
86
|
return Object.assign(made, { product: Object.freeze({ slug, script: row.id, sectionHash: entry.hash,
|
|
85
87
|
indexHash: descriptor.indexHash }) });
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// oxlint-disable-next-line import/no-nodejs-modules -- Tests own their bounded repository scratch.
|
|
2
|
+
import { existsSync, mkdtempSync, readdirSync, rmSync } from 'node:fs';
|
|
3
|
+
// oxlint-disable-next-line import/no-nodejs-modules -- Tests never use the system temp directory.
|
|
4
|
+
import { join, resolve } from 'node:path';
|
|
5
|
+
import { scratchDir } from '../../../scripts/scratch-dir.mjs';
|
|
6
|
+
|
|
7
|
+
const task = process.env['WS_LANE_NAME'] ?? `test-dev-${process.pid}`;
|
|
8
|
+
const existed = existsSync(resolve('tmp', task));
|
|
9
|
+
const parent = scratchDir(task, 'SDK dev fixture', { env: { ...process.env, WS_LANE_NAME: task } });
|
|
10
|
+
|
|
11
|
+
export const fixtureRoot = (prefix: string): string => mkdtempSync(join(parent, prefix));
|
|
12
|
+
export function closeFixtures(): void {
|
|
13
|
+
if (!existed && readdirSync(parent).every(name => name === '.owner')) rmSync(parent, { recursive: true });
|
|
14
|
+
}
|
|
@@ -7,6 +7,8 @@ export interface ScenarioActor {
|
|
|
7
7
|
fields?: Readonly<Record<number, number>>; fieldBounds?: Readonly<Record<number, { min: number; max: number; integer?: boolean }>>; moving?: boolean; strikeState?: number; spawn?: number;
|
|
8
8
|
}
|
|
9
9
|
export interface ScenarioWorldInput {
|
|
10
|
+
/** Declared shared field writes use target zero, matching the real DecisionHost ABI. */
|
|
11
|
+
fields?: ScenarioActor['fields']; fieldBounds?: ScenarioActor['fieldBounds'];
|
|
10
12
|
actors?: readonly ScenarioActor[]; players?: readonly ScenarioActor[];
|
|
11
13
|
spawnGroups?: readonly { id: number; members: readonly number[] }[];
|
|
12
14
|
flags?: Readonly<Record<number, boolean>>; playerFlags?: Readonly<Record<number, Readonly<Record<number, boolean>>>>;
|
|
@@ -23,7 +25,7 @@ export interface ScriptScenarioInput extends ScenarioWorldInput {
|
|
|
23
25
|
export interface ScenarioSnapshot { host: DecisionSnapshot; world: ScenarioWorldInput }
|
|
24
26
|
export type ScenarioCommand = readonly (string | number)[];
|
|
25
27
|
/** Disk fixtures name actor aliases or real platform ids; numeric handles must already be registered. */
|
|
26
|
-
export interface DiskScenarioOptions extends Omit<ScenarioWorldInput, 'actors'> {
|
|
28
|
+
export interface DiskScenarioOptions extends Omit<ScenarioWorldInput, 'actors' | 'fieldBounds'> {
|
|
27
29
|
seed: number;
|
|
28
30
|
/** Published output root, defaulting to out/ in the caller's working directory. */
|
|
29
31
|
products?: string;
|
|
@@ -42,11 +44,15 @@ export async function scenario(slug: string, id: string, options: DiskScenarioOp
|
|
|
42
44
|
return readDiskScriptScenario(slug, id, options);
|
|
43
45
|
}
|
|
44
46
|
function finite(values: readonly number[]): void { if (!values.every(Number.isFinite)) throw new Error('Non-finite scenario value'); }
|
|
45
|
-
function
|
|
46
|
-
|
|
47
|
-
|
|
47
|
+
function checkFields(fields:ScenarioActor['fields'],bounds:ScenarioActor['fieldBounds']):void{
|
|
48
|
+
finite(Object.values(fields??{}));
|
|
49
|
+
for (const [key, bound] of Object.entries(bounds ?? {})) {
|
|
50
|
+
finite([bound.min, bound.max]); const value = fields?.[Number(key)];
|
|
48
51
|
if (bound.min > bound.max || value === undefined || value < bound.min || value > bound.max || (bound.integer === true && !Number.isInteger(value))) throw new Error('Invalid scenario field bounds');
|
|
49
52
|
}
|
|
53
|
+
}
|
|
54
|
+
function actorCopy(actor: ScenarioActor): ScenarioActor {
|
|
55
|
+
checkFields(actor.fields,actor.fieldBounds);
|
|
50
56
|
return { ...actor, at: [...actor.at], fields: { ...actor.fields }, fieldBounds: structuredClone(actor.fieldBounds ?? {}) };
|
|
51
57
|
}
|
|
52
58
|
|
|
@@ -119,13 +125,10 @@ export class ScenarioWorld implements DecisionWorld {
|
|
|
119
125
|
return this.actor(id);
|
|
120
126
|
};
|
|
121
127
|
for (const [op, target, a, b] of batch) {
|
|
122
|
-
if
|
|
123
|
-
const
|
|
124
|
-
if (
|
|
125
|
-
|
|
126
|
-
if (actor.fields?.[a] === undefined || !Number.isFinite(b) || (bound !== undefined && (b < bound.min || b > bound.max || (bound.integer === true && !Number.isInteger(b))))) throw new Error('Scenario field declaration or bounds refused');
|
|
127
|
-
}
|
|
128
|
-
}
|
|
128
|
+
if(op===commands.field){
|
|
129
|
+
const value=target===0?this.input:owned(target),bound=value.fieldBounds?.[a];
|
|
130
|
+
if(value.fields?.[a]===undefined||!Number.isFinite(b)||(bound!==undefined&&(b<bound.min||b>bound.max||(bound.integer===true&&!Number.isInteger(b)))))throw new Error('Scenario field declaration or bounds refused');
|
|
131
|
+
}else if([commands.move,commands.stop,commands.strike,commands.despawn].some(value=>value===op))owned(target);
|
|
129
132
|
if ([commands.grant, commands.reward, commands.flag].some(value => value === op) && target !== 0 && !player(target)) throw new Error('Scenario target is not an observed player');
|
|
130
133
|
if ((op === commands.impulse || (op === commands.cue && target !== 0)) && !player(target)) owned(target);
|
|
131
134
|
if (op === commands.flag && b !== 0 && b !== 1) throw new Error('Scenario flag value refused');
|
|
@@ -136,6 +139,7 @@ export class ScenarioWorld implements DecisionWorld {
|
|
|
136
139
|
if (op === commands.flag) this.input = target === 0
|
|
137
140
|
? { ...this.input, flags: { ...this.input.flags, [a]: b === 1 } }
|
|
138
141
|
: { ...this.input, playerFlags: { ...this.input.playerFlags, [target]: { ...this.input.playerFlags?.[target], [a]: b === 1 } } };
|
|
142
|
+
if(op===commands.field&&target===0)this.input={...this.input,fields:{...this.input.fields,[a]:b}};
|
|
139
143
|
const actor = this.actors.get(target); if (actor === undefined) continue;
|
|
140
144
|
if (op === commands.field) this.actors.set(target, { ...actor, fields: { ...actor.fields, [a]: b } });
|
|
141
145
|
if (op === commands.move || op === commands.stop) this.actors.set(target, { ...actor, moving: op === commands.move });
|
|
@@ -151,7 +155,8 @@ export class ScenarioWorld implements DecisionWorld {
|
|
|
151
155
|
return structuredClone({ ...this.input, actors: [...this.actors.values()].filter(actor => !this.players.has(actor.id)), players: [...this.players].map(id => this.actor(id)) });
|
|
152
156
|
}
|
|
153
157
|
restore(input: ScenarioWorldInput): void {
|
|
154
|
-
const copy = structuredClone({ actors: input.actors ?? [], players: input.players ?? [], spawnGroups: input.spawnGroups ?? [], flags: input.flags ?? {}, playerFlags: input.playerFlags ?? {}, zones: input.zones ?? [], lists: input.lists ?? [] }), actors = new Map<number, ScenarioActor>();
|
|
158
|
+
const copy = structuredClone({ actors: input.actors ?? [], players: input.players ?? [], spawnGroups: input.spawnGroups ?? [], flags: input.flags ?? {}, playerFlags: input.playerFlags ?? {}, zones: input.zones ?? [], lists: input.lists ?? [],...(input.fields===undefined?{}:{fields:input.fields}),...(input.fieldBounds===undefined?{}:{fieldBounds:input.fieldBounds}) }), actors = new Map<number, ScenarioActor>();
|
|
159
|
+
checkFields(copy.fields,copy.fieldBounds);
|
|
155
160
|
for (const actor of [...copy.actors, ...copy.players]) {
|
|
156
161
|
if (!Number.isSafeInteger(actor.id) || actor.id <= 0 || actors.has(actor.id)) throw new Error('Invalid or duplicate scenario actor');
|
|
157
162
|
finite([...actor.at, actor.yaw ?? 0, actor.hpShare ?? 1, ...Object.values(actor.fields ?? {})]); actors.set(actor.id, actorCopy(actor));
|
|
@@ -181,7 +186,7 @@ export function scenarioCommand(script: DecisionScript, [op, target, a, b, c]: S
|
|
|
181
186
|
if (op === commands.grant || op === commands.reward) return [op === commands.grant ? 'grant' : 'reward', actor(target), name(op === commands.grant ? 'facts' : 'rewards', a)];
|
|
182
187
|
if (op === commands.impulse) return ['impulse', actor(target), name('impulses', a)];
|
|
183
188
|
if (op === commands.weather) return ['weather', name('weather', a)];
|
|
184
|
-
if (op === commands.encounter) { const verb = ['phase', 'win', 'fail'][a - 1]; if (verb === undefined) throw new Error('Unknown encounter verb'); return ['encounter', verb, b]; }
|
|
189
|
+
if (op === commands.encounter) { const verb = ['phase', 'win', 'fail', 'guard'][a - 1]; if (verb === undefined) throw new Error('Unknown encounter verb'); return ['encounter', verb, b]; }
|
|
185
190
|
const view = Object.entries(commands).find(([key, value]) => key.startsWith('view.') && value === op)?.[0];
|
|
186
191
|
if (view !== undefined) return [view, target, a, b, c];
|
|
187
192
|
throw new Error(`Unknown scenario command ${op}`);
|
|
@@ -21,29 +21,11 @@ const panel = (): HTMLElement => {
|
|
|
21
21
|
held = node;
|
|
22
22
|
return node;
|
|
23
23
|
};
|
|
24
|
-
/**
|
|
25
|
-
* Engine 0.1.21 and earlier give every `game.watchFrames` observer the one system id `harness.walk`. The dev hook's ground
|
|
26
|
-
* sweep takes it at boot, so the first part with a lamp or water threw "Duplicate system id" and never drew. Until the sdk
|
|
27
|
-
* pins an engine whose observers carry their own ids, the page gives each later observer its own (engine-quickfix fix,
|
|
28
|
-
* SHARD-SOURCE AP16). The engine's fields are read loosely: a client without them is left as it is.
|
|
29
|
-
*/
|
|
30
|
-
interface ObserverGame { watchFrames?: unknown; levelScope?: { child?: unknown }; app?: { addSystem?: unknown } }
|
|
31
|
-
let observers = 0;
|
|
32
|
-
const ownObserverIds = (): void => {
|
|
33
|
-
const game = (window as unknown as { __wildshard?: { world?: { game?: ObserverGame } } }).__wildshard?.world?.game;
|
|
34
|
-
if (game === undefined || typeof game.levelScope?.child !== 'function' || typeof game.app?.addSystem !== 'function') return;
|
|
35
|
-
const levelScope = game.levelScope as { child: (name: string) => Scope }, app = game.app as { addSystem: (spec: { id: string; phase: 'update'; run: (dt: number) => void; core: boolean }, scope: Scope) => void };
|
|
36
|
-
game.watchFrames = (run: (dt: number) => void): (() => void) => {
|
|
37
|
-
const owner = levelScope.child('observer');
|
|
38
|
-
app.addSystem({ id: `harness.walk.watch.${String(observers++)}`, phase: 'update', run, core: false }, owner);
|
|
39
|
-
return () => { owner.dispose(); };
|
|
40
|
-
};
|
|
41
|
-
};
|
|
42
24
|
const entry = location.href;
|
|
43
25
|
const timers = new Scope('watch.entry');
|
|
44
26
|
const page = startWatchPage({
|
|
45
27
|
origin: location.origin,
|
|
46
|
-
hook: () =>
|
|
28
|
+
hook: () => window.__wildshardDevHook,
|
|
47
29
|
fetch: (url) => fetch(url, { cache: 'no-store' }),
|
|
48
30
|
socket: (url) => socketOf(new WebSocket(url)),
|
|
49
31
|
frame: (run) => { timers.raf(run); },
|
|
@@ -3,20 +3,20 @@
|
|
|
3
3
|
"source": "src/shards/authoring-slice",
|
|
4
4
|
"cameras": {
|
|
5
5
|
"hut-front": {
|
|
6
|
-
"mean": 2.
|
|
7
|
-
"share": 0.
|
|
6
|
+
"mean": 2.155,
|
|
7
|
+
"share": 0.03402
|
|
8
8
|
},
|
|
9
9
|
"door-lamp": {
|
|
10
|
-
"mean": 4.
|
|
11
|
-
"share": 0.
|
|
10
|
+
"mean": 4.239,
|
|
11
|
+
"share": 0.07664
|
|
12
12
|
},
|
|
13
13
|
"hut-back": {
|
|
14
|
-
"mean": 0.
|
|
15
|
-
"share": 0.
|
|
14
|
+
"mean": 0.471,
|
|
15
|
+
"share": 0.00751
|
|
16
16
|
},
|
|
17
17
|
"pond": {
|
|
18
|
-
"mean": 3.
|
|
19
|
-
"share": 0.
|
|
18
|
+
"mean": 3.499,
|
|
19
|
+
"share": 0.0484
|
|
20
20
|
}
|
|
21
21
|
}
|
|
22
22
|
}
|
|
@@ -66,15 +66,37 @@ async function shoot(browser, url, live, after = []) {
|
|
|
66
66
|
live, { timeout: 180_000, polling: 500 });
|
|
67
67
|
await page.evaluate(() => {
|
|
68
68
|
const w = window.__wildshard.world, camera = w.game.camera;
|
|
69
|
+
const lampUpdates = new WeakMap();
|
|
69
70
|
if (w.animals) w.animals.calm = true;
|
|
70
71
|
// the camera leaves the player (whose body stands where colliders put it, which this test does not compare): each
|
|
71
72
|
// frame it is set to the shot's eye, one field of view, no viewmodel
|
|
72
73
|
w.freeCamera = true;
|
|
73
74
|
w.game.onLate(() => {
|
|
74
75
|
const eye = window.__ap20Eye;
|
|
76
|
+
// Sample this static material fixture at one presentation instant.
|
|
77
|
+
// Capture mode holds the tier's render scale; pause holds scheduled
|
|
78
|
+
// systems. Water and lamp accumulators need their own explicit sample.
|
|
79
|
+
let water = 0, lamps = 0;
|
|
80
|
+
w.game.rootScene.traverse((object) => {
|
|
81
|
+
if (object.name.startsWith('water:') && object.material?.uniforms?.uTime !== undefined) {
|
|
82
|
+
object.material.uniforms.uTime.value = 5; water++;
|
|
83
|
+
}
|
|
84
|
+
if (object.name === 'look-light-lamps' && typeof object.update === 'function') {
|
|
85
|
+
let update = lampUpdates.get(object);
|
|
86
|
+
if (update === undefined) {
|
|
87
|
+
update = object.update.bind(object); lampUpdates.set(object, update);
|
|
88
|
+
// The built look updates after late; watch holds the original
|
|
89
|
+
// callback, so both the property and this late sample are needed.
|
|
90
|
+
object.update = () => { update(5); };
|
|
91
|
+
}
|
|
92
|
+
update(5); lamps++;
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
window.__ap20Phases = { water, lamps };
|
|
75
96
|
for (const child of camera.children) child.visible = false;
|
|
76
97
|
if (Math.abs(camera.fov - 72) > 0.01) { camera.fov = 72; camera.updateProjectionMatrix(); }
|
|
77
98
|
if (eye !== undefined) { camera.position.set(eye[0], eye[1], eye[2]); camera.rotation.set(eye[4], eye[3], 0, 'YXZ'); camera.updateMatrixWorld(true); }
|
|
99
|
+
w.game.app.clock.restore({ version: 1, elapsed: 5, wall: 5, frames: 300, captureFps: 60, paused: true, scale: 1 });
|
|
78
100
|
}, 'ap20.camera');
|
|
79
101
|
});
|
|
80
102
|
// the watch panel's timings and build table change from run to run: they are not the scene
|
|
@@ -86,6 +108,8 @@ async function shoot(browser, url, live, after = []) {
|
|
|
86
108
|
for (const [id, x, z, yaw, pitch] of CAMERAS) {
|
|
87
109
|
await page.evaluate((eye) => { window.__ap20Eye = eye; }, [x, EYE, z, yaw, pitch]);
|
|
88
110
|
await page.waitForTimeout(2500);
|
|
111
|
+
const phases = await page.evaluate(() => window.__ap20Phases);
|
|
112
|
+
if (phases === undefined || phases.water < 1 || phases.lamps < 1) throw new Error('Parity scene lacks its controlled water or lamp presentation');
|
|
89
113
|
frames.push({ id, png: await page.screenshot() });
|
|
90
114
|
}
|
|
91
115
|
sets.push(frames);
|