@wildshard/shard-format 0.6.0 → 0.7.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wildshard/shard-format",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "The raw shardfile format: the spec, the validator and a validate CLI. The public, versioned contract every other repo builds on.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -247,6 +247,7 @@
247
247
  "./postGraphDocument": "./src/format/postGraphDocument.ts",
248
248
  "./postGraphLook": "./src/format/postGraphLook.ts",
249
249
  "./postStack": "./src/format/postStack.ts",
250
+ "./look-details": "./src/format/look-details.ts",
250
251
  "./look-light": "./src/format/look-light.ts",
251
252
  "./look-render": "./src/format/look-render.ts",
252
253
  "./pool-surface": "./src/format/pool-surface.ts",
@@ -0,0 +1,133 @@
1
+ /**
2
+ * The binary files behind `look.details` (meta SHARD-SOURCE AP32a), kept binary (engine G649: never base64). Plain
3
+ * arithmetic over bytes, so the same checks run in the browser, the Worker, the cook and Node.
4
+ *
5
+ * - A card mesh file: little-endian, no header: `vertices` × f32 xyz positions, `vertices` × f32 xyz normals, `vertices` ×
6
+ * f32 uv, then `triangles` × three u16 indices. Its length is exactly `32 × vertices + 6 × triangles` bytes.
7
+ * - A mask file: one u8 per region cell, row by row from the low corner.
8
+ * - A heights file: one u16 little-endian per region cell, the same order.
9
+ */
10
+
11
+ /** A layer's card mesh: a binary file (by hash) and its counts. */
12
+ interface LookDetailMesh {
13
+ readonly file: string
14
+ readonly vertices: number
15
+ readonly triangles: number
16
+ }
17
+ /** A layer's three files, as bytes. */
18
+ interface LookDetailFiles {
19
+ readonly mesh: Readonly<Uint8Array>
20
+ readonly mask: Readonly<Uint8Array>
21
+ readonly heights: Readonly<Uint8Array>
22
+ }
23
+ /** The parts of a layer row its files are checked against. */
24
+ interface DetailFileRow {
25
+ readonly id: string
26
+ readonly mesh: LookDetailMesh
27
+ readonly region: { readonly columns: number; readonly rows: number }
28
+ }
29
+ /** A card mesh's attribute views over its file's bytes. */
30
+ interface LookDetailMeshViews {
31
+ readonly positions: Float32Array
32
+ readonly normals: Float32Array
33
+ readonly uvs: Float32Array
34
+ readonly indices: Uint16Array
35
+ }
36
+
37
+ /** At most this many triangles in one layer's card mesh. */
38
+ const DETAIL_MESH_TRIANGLES_MAX = 2000
39
+ /** At most this many vertices in one layer's card mesh. */
40
+ const DETAIL_MESH_VERTICES_MAX = 6000
41
+ const NONE = 0
42
+ const ONE = 1
43
+ const XYZ = 3
44
+ const UV = 2
45
+ const TRIANGLE = 3
46
+ const F32 = 4
47
+ const U16 = 2
48
+
49
+ /** The exact byte length of a card mesh file with these counts. */
50
+ function detailMeshBytes(vertices: number, triangles: number): number {
51
+ return vertices * (XYZ + XYZ + UV) * F32 + triangles * TRIANGLE * U16
52
+ }
53
+
54
+ /** The messages whose condition holds. */
55
+ function faultsOf(checks: readonly (readonly [boolean, string])[]): string[] {
56
+ return checks
57
+ .filter((entry: readonly [boolean, string]): boolean => entry[NONE])
58
+ .map((entry: readonly [boolean, string]): string => entry[ONE])
59
+ }
60
+
61
+ /** A fresh aligned copy of `length` bytes from `offset`. */
62
+ function aligned(
63
+ bytes: Readonly<Uint8Array>,
64
+ offset: number,
65
+ length: number,
66
+ ): ArrayBuffer {
67
+ return bytes.slice(offset, offset + length).buffer
68
+ }
69
+
70
+ /** The card mesh's attribute views (copied, so any byte offset works). */
71
+ function detailMeshViews(
72
+ bytes: Readonly<Uint8Array>,
73
+ mesh: LookDetailMesh,
74
+ ): LookDetailMeshViews {
75
+ const xyz = mesh.vertices * XYZ * F32
76
+ const uv = mesh.vertices * UV * F32
77
+ return {
78
+ indices: new Uint16Array(
79
+ aligned(bytes, xyz + xyz + uv, mesh.triangles * TRIANGLE * U16),
80
+ ),
81
+ normals: new Float32Array(aligned(bytes, xyz, xyz)),
82
+ positions: new Float32Array(aligned(bytes, NONE, xyz)),
83
+ uvs: new Float32Array(aligned(bytes, xyz + xyz, uv)),
84
+ }
85
+ }
86
+
87
+ /** True when any index is `vertices` or more. */
88
+ function indexPast(indices: Readonly<Uint16Array>, vertices: number): boolean {
89
+ return indices.some((index: number): boolean => index >= vertices)
90
+ }
91
+
92
+ /** The faults in one layer's files against its mesh counts and region grid, or none. */
93
+ function detailFileFaults(
94
+ row: DetailFileRow,
95
+ files: LookDetailFiles,
96
+ ): string[] {
97
+ const { id, mesh } = row
98
+ const cells = row.region.columns * row.region.rows
99
+ const meshBytes = detailMeshBytes(mesh.vertices, mesh.triangles)
100
+ const sized = files.mesh.length === meshBytes
101
+ const past =
102
+ sized && indexPast(detailMeshViews(files.mesh, mesh).indices, mesh.vertices)
103
+ return faultsOf([
104
+ [
105
+ !sized,
106
+ `detail ${id}: mesh file holds ${String(files.mesh.length)} bytes, its counts need ${String(meshBytes)}`,
107
+ ],
108
+ [past, `detail ${id}: an index past the last vertex`],
109
+ [
110
+ files.mask.length !== cells,
111
+ `detail ${id}: mask holds ${String(files.mask.length)} bytes, the region has ${String(cells)} cells`,
112
+ ],
113
+ [
114
+ files.heights.length !== cells * U16,
115
+ `detail ${id}: heights hold ${String(files.heights.length)} bytes, the region needs ${String(cells * U16)}`,
116
+ ],
117
+ ])
118
+ }
119
+
120
+ export {
121
+ DETAIL_MESH_TRIANGLES_MAX,
122
+ DETAIL_MESH_VERTICES_MAX,
123
+ detailFileFaults,
124
+ detailMeshBytes,
125
+ detailMeshViews,
126
+ faultsOf,
127
+ }
128
+ export type {
129
+ DetailFileRow,
130
+ LookDetailFiles,
131
+ LookDetailMesh,
132
+ LookDetailMeshViews,
133
+ }
@@ -0,0 +1,255 @@
1
+ /**
2
+ * Detail layers (meta SHARD-SOURCE AP32a): grass, ferns and other small clutter as a card mesh plus a density mask, scattered
3
+ * by the engine in a ring round the camera (its grass-carpet pattern, made general) instead of baked as thousands of instance
4
+ * matrices. Absent: no layers (no default is filled, so older shard files keep their bytes).
5
+ *
6
+ * One `look.details` row:
7
+ * - `id`: unique among the layers; it also seeds the scatter, so the same square metre always grows the same clumps.
8
+ * - `material`: a `look.materials` id (or a family) the cards draw with.
9
+ * - `mesh`: the card: a binary `file` (by hash) and its `vertices` and `triangles` counts (layout in
10
+ * `look-details-bytes.ts`). At most `DETAIL_MESH_TRIANGLES_MAX` triangles.
11
+ * - `region`: the mask's grid: its low `corner` ([x, z] metres), `cell` size, `columns` (along x), `rows` (along z), and
12
+ * the `span` of y its heights cover.
13
+ * - `mask`: a binary file, one u8 per cell, row by row from the low corner: 0 grows nothing, 255 grows `clumps` clumps.
14
+ * - `heights`: a binary file, one u16 per cell: the ground under the cell's centre, `span[0] + h / 65535 × (span[1] -
15
+ * span[0])`.
16
+ * - `clumps`: clumps in a full cell; `scale`, `tilt` (the most a clump leans, radians) and `tint` (two sRGB multipliers a
17
+ * clump's colour is picked between) vary each clump.
18
+ * - `sway`: wind on the cards (`amount` of lean, `rate` in cycles a second); absent: still.
19
+ * - `radius`: metres round the camera that grow the layer on desktop; phones grow half the radius (the engine's rule).
20
+ * - `shadow`: the cards cast shadows.
21
+ *
22
+ * The files stay binary (engine G649). Their sizes are checked against the row where the bytes are at hand
23
+ * (`detailFileFaults`); the shardfile rule checks they are declared binary files with no dependencies.
24
+ */
25
+ import {
26
+ array,
27
+ boolean,
28
+ check,
29
+ exactOptional,
30
+ finite,
31
+ integer,
32
+ maxLength,
33
+ maxValue,
34
+ minValue,
35
+ number,
36
+ pipe,
37
+ regex,
38
+ string,
39
+ strictObject,
40
+ tuple,
41
+ } from 'valibot'
42
+
43
+ import {
44
+ DETAIL_MESH_TRIANGLES_MAX,
45
+ DETAIL_MESH_VERTICES_MAX,
46
+ } from './look-details-bytes.ts'
47
+ import { materialExists } from './materials.ts'
48
+
49
+ import type { LookDetailMesh } from './look-details-bytes.ts'
50
+ import type { GenericSchema } from 'valibot'
51
+
52
+ type Rgb = readonly [number, number, number]
53
+ type Pair = readonly [number, number]
54
+
55
+ /** A layer's mask grid. */
56
+ interface LookDetailRegion {
57
+ readonly corner: Pair
58
+ readonly cell: number
59
+ readonly columns: number
60
+ readonly rows: number
61
+ readonly span: Pair
62
+ }
63
+ /** Wind on a layer's cards. */
64
+ interface LookDetailSway {
65
+ readonly amount: number
66
+ readonly rate: number
67
+ }
68
+ /** One detail layer. */
69
+ interface LookDetail {
70
+ readonly id: string
71
+ readonly material: string
72
+ readonly mesh: LookDetailMesh
73
+ readonly region: LookDetailRegion
74
+ readonly mask: string
75
+ readonly heights: string
76
+ readonly clumps: number
77
+ readonly scale: Pair
78
+ readonly tilt: number
79
+ readonly tint: readonly [Rgb, Rgb]
80
+ readonly sway?: LookDetailSway
81
+ readonly radius: number
82
+ readonly shadow: boolean
83
+ }
84
+ /** A shardfile file entry, as the rule reads it. */
85
+ interface DetailFileEntry {
86
+ readonly hash: string
87
+ readonly kind: string
88
+ readonly dependencies: readonly string[]
89
+ }
90
+
91
+ /** At most this many detail layers in one look. */
92
+ const DETAIL_LAYERS_MAX = 8
93
+ /** At most this many mask columns or rows (512 × 512 cells). */
94
+ const DETAIL_SIDE_MAX = 512
95
+ /** At most this many clumps in a full cell. */
96
+ const DETAIL_CLUMPS_MAX = 64
97
+ const NONE = 0
98
+ const FULL = 1
99
+ const TRIANGLE = 3
100
+ const CELL_MIN = 0.5
101
+ const CELL_MAX = 8
102
+ const SCALE_MIN = 0.05
103
+ const SCALE_MAX = 20
104
+ const RATE_MIN = 0.05
105
+ const RATE_MAX = 10
106
+ const RADIUS_MIN = 4
107
+ const RADIUS_MAX = 200
108
+
109
+ /** The layers whose material names no `look.materials` entry or family. */
110
+ function detailMaterialFaults(
111
+ rows: readonly LookDetail[],
112
+ materials: Readonly<Record<string, unknown>>,
113
+ ): string[] {
114
+ const missing = rows.filter(
115
+ (row: LookDetail): boolean => !materialExists(materials, row.material),
116
+ )
117
+ return missing.map(
118
+ (row: LookDetail): string =>
119
+ `detail ${row.id}: material ${row.material} is not declared`,
120
+ )
121
+ }
122
+
123
+ /** True when `hash` is a declared binary file with no dependencies. */
124
+ function plainBinary(
125
+ files: ReadonlyMap<string, DetailFileEntry>,
126
+ hash: string,
127
+ ): boolean {
128
+ const file = files.get(hash)
129
+ return file?.kind === 'binary' && file.dependencies.length === NONE
130
+ }
131
+
132
+ /** The shardfile rules: every layer's material is declared and its three files are plain binaries. */
133
+ function detailLayerRules(
134
+ rows: readonly LookDetail[] | undefined,
135
+ materials: Readonly<Record<string, unknown>>,
136
+ files: readonly DetailFileEntry[],
137
+ ): string[] {
138
+ const layers = rows ?? []
139
+ const byHash = new Map(
140
+ files.map((file: DetailFileEntry): [string, DetailFileEntry] => [
141
+ file.hash,
142
+ file,
143
+ ]),
144
+ )
145
+ const refs = layers.flatMap((row: LookDetail): string[] => [
146
+ row.mesh.file,
147
+ row.mask,
148
+ row.heights,
149
+ ])
150
+ const errors: string[] = []
151
+ if (detailMaterialFaults(layers, materials).length > NONE) {
152
+ errors.push('declared detail layer material')
153
+ }
154
+ if (!refs.every((hash: string): boolean => plainBinary(byHash, hash))) {
155
+ errors.push('detail layer files are declared binaries with no dependencies')
156
+ }
157
+ return errors
158
+ }
159
+
160
+ /** True when a layer's ranges run low to high and its mesh can index every triangle. */
161
+ function ordered(row: LookDetail): boolean {
162
+ const spans =
163
+ row.region.span[NONE] <= row.region.span[FULL] &&
164
+ row.scale[NONE] <= row.scale[FULL]
165
+ return spans && row.mesh.vertices >= TRIANGLE
166
+ }
167
+ /** True when no two layers share an id. */
168
+ function uniqueIds(rows: readonly LookDetail[]): boolean {
169
+ return (
170
+ new Set(rows.map((row: LookDetail): string => row.id)).size === rows.length
171
+ )
172
+ }
173
+
174
+ function range(low: number, high: number): GenericSchema<number, number> {
175
+ return pipe(number(), finite(), minValue(low), maxValue(high))
176
+ }
177
+ function count(low: number, high: number): GenericSchema<number, number> {
178
+ return pipe(number(), integer(), minValue(low), maxValue(high))
179
+ }
180
+
181
+ const real = pipe(number(), finite())
182
+ const unit = range(NONE, FULL)
183
+ const rgb = tuple([unit, unit, unit])
184
+ const identity = pipe(string(), regex(/^[a-z0-9][a-z0-9._-]{0,63}$/u))
185
+ const hash = pipe(string(), regex(/^[a-f0-9]{64}$/u))
186
+ const side = count(FULL, DETAIL_SIDE_MAX)
187
+ const size = range(SCALE_MIN, SCALE_MAX)
188
+ const pair = tuple([real, real])
189
+ const MeshSchema = strictObject({
190
+ file: hash,
191
+ triangles: count(FULL, DETAIL_MESH_TRIANGLES_MAX),
192
+ vertices: count(FULL, DETAIL_MESH_VERTICES_MAX),
193
+ })
194
+ const RegionSchema = strictObject({
195
+ cell: range(CELL_MIN, CELL_MAX),
196
+ columns: side,
197
+ corner: pair,
198
+ rows: side,
199
+ span: pair,
200
+ })
201
+ const SwaySchema = strictObject({
202
+ amount: unit,
203
+ rate: range(RATE_MIN, RATE_MAX),
204
+ })
205
+ const DetailRowSchema: GenericSchema<LookDetail, LookDetail> = strictObject({
206
+ clumps: count(FULL, DETAIL_CLUMPS_MAX),
207
+ heights: hash,
208
+ id: identity,
209
+ mask: hash,
210
+ material: identity,
211
+ mesh: MeshSchema,
212
+ radius: range(RADIUS_MIN, RADIUS_MAX),
213
+ region: RegionSchema,
214
+ scale: tuple([size, size]),
215
+ shadow: boolean(),
216
+ sway: exactOptional(SwaySchema),
217
+ tilt: unit,
218
+ tint: tuple([rgb, rgb]),
219
+ })
220
+ const LookDetailSchema: GenericSchema<LookDetail, LookDetail> = pipe(
221
+ DetailRowSchema,
222
+ check<LookDetail, string>(
223
+ ordered,
224
+ 'detail layer ranges run low to high and its mesh has a triangle',
225
+ ),
226
+ )
227
+ /** `look.details`: at most `DETAIL_LAYERS_MAX` layers with unique ids. */
228
+ const LookDetailsSchema: GenericSchema<LookDetail[], LookDetail[]> = pipe(
229
+ array(LookDetailSchema),
230
+ maxLength(DETAIL_LAYERS_MAX),
231
+ check<LookDetail[], string>(uniqueIds, 'detail layer ids are unique'),
232
+ )
233
+
234
+ export {
235
+ DETAIL_CLUMPS_MAX,
236
+ DETAIL_LAYERS_MAX,
237
+ DETAIL_SIDE_MAX,
238
+ LookDetailsSchema,
239
+ detailLayerRules,
240
+ detailMaterialFaults,
241
+ }
242
+ export {
243
+ DETAIL_MESH_TRIANGLES_MAX,
244
+ DETAIL_MESH_VERTICES_MAX,
245
+ detailFileFaults,
246
+ detailMeshBytes,
247
+ detailMeshViews,
248
+ } from './look-details-bytes.ts'
249
+ export type {
250
+ DetailFileRow,
251
+ LookDetailFiles,
252
+ LookDetailMesh,
253
+ LookDetailMeshViews,
254
+ } from './look-details-bytes.ts'
255
+ export type { DetailFileEntry, LookDetail, LookDetailRegion, LookDetailSway }
@@ -58,6 +58,8 @@ import type { LookSky, LookSkyInput } from './look-sky.ts';
58
58
  import { LookBloomSchema, LookLightSchema, LookToneSchema } from './look-light.ts';
59
59
  import { LookVignetteSchema } from './look-render.ts';
60
60
  import type { LookBloom, LookBloomInput, LookLight, LookLightInput, LookTone } from './look-light.ts';
61
+ import { LookDetailsSchema, detailLayerRules } from './look-details.ts';
62
+ import type { LookDetail } from './look-details.ts';
61
63
  import type { LookVignette } from './look-render.ts';
62
64
 
63
65
  const channel = v.pipe(finite, v.minValue(0), v.maxValue(1));
@@ -78,7 +80,7 @@ const rawSchema: v.GenericSchema<ShardfileRowsInput, ShardfileRows> & { readonly
78
80
  map: v.exactOptional(MapSchema),
79
81
  requires: RequiresSchema,
80
82
  budgets: BudgetsSchema,
81
- look: v.strictObject({ families: names, materials: v.optional(MaterialsSchema, {}), familyLooks: v.optional(FamilyLooksSchema, {}), curves: v.exactOptional(MaterialCurvesSchema), samplers: v.exactOptional(TextureSamplersSchema), post: v.exactOptional(PostStackSchema), sky: v.exactOptional(LookSkySchema), light: v.exactOptional(LookLightSchema), grade: lookGrade, clock: v.literal('engine'), day: v.optional(day), dayOverride: v.nullable(channel), keys: v.pipe(v.array(key), v.maxLength(64)) }),
83
+ look: v.strictObject({ families: names, materials: v.optional(MaterialsSchema, {}), familyLooks: v.optional(FamilyLooksSchema, {}), curves: v.exactOptional(MaterialCurvesSchema), samplers: v.exactOptional(TextureSamplersSchema), post: v.exactOptional(PostStackSchema), sky: v.exactOptional(LookSkySchema), light: v.exactOptional(LookLightSchema), details: v.exactOptional(LookDetailsSchema), grade: lookGrade, clock: v.literal('engine'), day: v.optional(day), dayOverride: v.nullable(channel), keys: v.pipe(v.array(key), v.maxLength(64)) }),
82
84
  sim: SimSchema,
83
85
  state: StateSchema,
84
86
  migrations: v.optional(MigrationsSchema, []),
@@ -189,6 +191,7 @@ export interface Shardfile {
189
191
  post?: v.InferOutput<typeof PostStackSchema>;
190
192
  sky?: LookSky;
191
193
  light?: LookLight;
194
+ details?: LookDetail[];
192
195
  grade: { exposure: number; saturation: number; contrast: number; lut: string | null; bloom?: LookBloom; tone?: LookTone; vignette?: LookVignette };
193
196
  clock: 'engine';
194
197
  day?: v.InferOutput<typeof day> | undefined;
@@ -304,6 +307,7 @@ export function shardfileRules(s: Shardfile): string[] {
304
307
  try { validatePropsReferences(s.props, s); } catch { errors.push('declared prop references'); }
305
308
  if (!materialExists(s.look.materials, s.props.family)) errors.push('declared prop material');
306
309
  }
310
+ errors.push(...detailLayerRules(s.look.details, s.look.materials, s.files));
307
311
  if (Math.abs(s.spawn.x) > CHUNK_HALF || Math.abs(s.spawn.z) > CHUNK_HALF || s.spawn.y < -CELL_BELOW || s.spawn.y > CELL_ABOVE) errors.push('player spawn in cell');
308
312
  const conditions = new Set(s.hooks.conditions.map((row) => row.id)), scenes = new Set(s.hooks.scenes.map((row) => row.id));
309
313
  const inputConditions = [...(s.plumbing?.input.flatMap(row => [row.when, row.hiddenWhen]) ?? []), ...s.items.contexts.map(row => row.extra?.hiddenWhen)];
@@ -397,6 +401,7 @@ interface ShardfileRowsInputFields {
397
401
  post?: v.InferInput<typeof PostStackSchema>;
398
402
  sky?: LookSkyInput;
399
403
  light?: LookLightInput;
404
+ details?: LookDetail[];
400
405
  grade: {
401
406
  exposure: v.InferInput<typeof finite>;
402
407
  saturation: v.InferInput<typeof finite>;
@@ -474,6 +479,7 @@ interface ShardfileRowsFields {
474
479
  post?: v.InferOutput<typeof PostStackSchema>;
475
480
  sky?: LookSky;
476
481
  light?: LookLight;
482
+ details?: LookDetail[];
477
483
  grade: {
478
484
  exposure: v.InferOutput<typeof finite>;
479
485
  saturation: v.InferOutput<typeof finite>;