@wildshard/shard-format 0.39.0 → 0.41.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.39.0",
3
+ "version": "0.41.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": {
@@ -125,6 +125,7 @@
125
125
  "./director": "./src/format/director.ts",
126
126
  "./detail-layer": "./src/format/detail-layer.ts",
127
127
  "./pbr-emissive": "./src/format/pbr-emissive.ts",
128
+ "./pbr-fur": "./src/format/pbr-fur.ts",
128
129
  "./scene-render": "./src/format/scene-render.ts",
129
130
  "./look-sky": "./src/format/look-sky.ts",
130
131
  "./directorDocument": "./src/format/directorDocument.ts",
@@ -348,6 +349,7 @@
348
349
  "./shardSections": "./src/format/shardSections.ts",
349
350
  "./sketch": "./src/format/sketch.ts",
350
351
  "./skinAssets": "./src/format/skinAssets.ts",
352
+ "./skinTextures": "./src/format/skin-textures.ts",
351
353
  "./skinData": "./src/format/skinData.ts",
352
354
  "./skinLayers": "./src/format/skinLayers.ts",
353
355
  "./skins": "./src/format/skins.ts",
@@ -0,0 +1,231 @@
1
+ // ONE-FORMAT CC30a: a body's socket attachments. Each hangs up to four parts on
2
+ // a skeleton socket the way the boss socket rig does (`bossSocketRig.ts`: an
3
+ // `{ id, geometry, material }` part), where `geometry` is a library GLB's hash
4
+ // and `material` a `look.materials` id. `when` shows it while a channel is at
5
+ // `at` or above; `part` hides it once that volume breaks (the volume's
6
+ // `channel`, set to 1 by the break, carries it to every page); `desktop`
7
+ // drops it on the phone tier.
8
+ import {
9
+ array,
10
+ boolean,
11
+ check,
12
+ exactOptional,
13
+ finite,
14
+ maxLength,
15
+ maxValue,
16
+ minLength,
17
+ minValue,
18
+ number,
19
+ pipe,
20
+ regex,
21
+ strictObject,
22
+ string,
23
+ tuple,
24
+ } from 'valibot'
25
+
26
+ import { creatureContract } from './creature-skeletons.ts'
27
+ import { CreatureSocketNameSchema } from './creature-volumes.ts'
28
+ import { materialExists } from './materials.ts'
29
+
30
+ import type { CreatureSkeleton } from './creature-layers.ts'
31
+ import type { CreatureTrail } from './creature-skeletons.ts'
32
+ import type { GenericSchema } from 'valibot'
33
+
34
+ const ZERO = 0
35
+ const ONE = 1
36
+ const MAX_ATTACHMENTS = 8
37
+ const MAX_MESHES = 4
38
+ const MAX_ID = 128
39
+ const MAX_OFFSET = 500
40
+ const id = pipe(string(), regex(/^[a-z][a-zA-Z0-9.:-]*$/u), maxLength(MAX_ID))
41
+ const hash = pipe(string(), regex(/^[0-9a-f]{64}$/u))
42
+ const unit = pipe(number(), finite(), minValue(ZERO), maxValue(ONE))
43
+ const offset = pipe(
44
+ number(),
45
+ finite(),
46
+ minValue(-MAX_OFFSET),
47
+ maxValue(MAX_OFFSET),
48
+ )
49
+
50
+ /** One drawn part: a library GLB's geometry under a `look.materials` material. */
51
+ interface CreatureAttachmentMesh {
52
+ id: string
53
+ geometry: string
54
+ material: string
55
+ }
56
+ interface CreatureAttachment {
57
+ id: string
58
+ /** A socket of the body's skeleton contract, or a bone of a GLB's own rig. */
59
+ socket: string
60
+ meshes: CreatureAttachmentMesh[]
61
+ /** Offset in the socket's local frame. */
62
+ at?: [number, number, number]
63
+ /** Shown while `channel` is at `at` (0.5 when omitted) or above. */
64
+ when?: { channel: string; at?: number }
65
+ /** A body volume with a break `channel`: the attachment hides once it breaks. */
66
+ part?: string
67
+ /** Dropped on the phone tier. */
68
+ desktop?: boolean
69
+ }
70
+
71
+ const mesh = strictObject({ id, geometry: hash, material: id })
72
+ const shownWhen = strictObject({ channel: id, at: exactOptional(unit) })
73
+ const meshList = pipe(array(mesh), minLength(ONE), maxLength(MAX_MESHES))
74
+ const attachment = strictObject({
75
+ id,
76
+ socket: CreatureSocketNameSchema,
77
+ meshes: meshList,
78
+ at: exactOptional(tuple([offset, offset, offset])),
79
+ when: exactOptional(shownWhen),
80
+ part: exactOptional(CreatureSocketNameSchema),
81
+ desktop: exactOptional(boolean()),
82
+ })
83
+ const CreatureAttachmentsSchema: GenericSchema<CreatureAttachment[]> = pipe(
84
+ array(attachment),
85
+ minLength(ONE),
86
+ maxLength(MAX_ATTACHMENTS),
87
+ check<CreatureAttachment[], 'Duplicate creature attachment'>(
88
+ (rows: readonly AttachmentView[]): boolean => {
89
+ const ids = rows.flatMap((row: AttachmentView): readonly string[] => [
90
+ row.id,
91
+ ...row.meshes.map((part: MeshView): string => part.id),
92
+ ])
93
+ return new Set(ids).size === ids.length
94
+ },
95
+ 'Duplicate creature attachment',
96
+ ),
97
+ )
98
+
99
+ /** A read-only view of an attachment, for the checks below. */
100
+ interface AttachmentView {
101
+ readonly id: string
102
+ readonly socket: string
103
+ readonly meshes: readonly MeshView[]
104
+ readonly when?: { readonly channel: string }
105
+ readonly part?: string
106
+ }
107
+ interface MeshView {
108
+ readonly id: string
109
+ readonly geometry: string
110
+ readonly material: string
111
+ }
112
+
113
+ interface AttachedBody {
114
+ readonly skeleton?: CreatureSkeleton
115
+ readonly trail?: CreatureTrail
116
+ readonly channels?: readonly { readonly name: string }[]
117
+ readonly volumes?: readonly {
118
+ readonly part: string
119
+ readonly hp?: number
120
+ readonly channel?: string
121
+ }[]
122
+ readonly attachments?: readonly AttachmentView[]
123
+ }
124
+
125
+ /** A volume's break channel is declared and the volume has hp to break. */
126
+ function volumeChannelsDeclared(body: AttachedBody): boolean {
127
+ const names = new Set(
128
+ (body.channels ?? []).map(
129
+ (row: { readonly name: string }): string => row.name,
130
+ ),
131
+ )
132
+ return (body.volumes ?? []).every(
133
+ (row: { readonly hp?: number; readonly channel?: string }): boolean =>
134
+ row.channel === undefined ||
135
+ (row.hp !== undefined && names.has(row.channel)),
136
+ )
137
+ }
138
+
139
+ /** The sockets a declared skeleton offers; undefined for a GLB's own rig. */
140
+ function socketNames(body: AttachedBody): ReadonlySet<string> | undefined {
141
+ if (body.skeleton === undefined) {
142
+ return undefined
143
+ }
144
+ if (body.skeleton === 'serpent' && body.trail === undefined) {
145
+ return new Set()
146
+ }
147
+ return new Set(
148
+ Object.keys(
149
+ creatureContract({
150
+ skeleton: body.skeleton,
151
+ ...(body.trail === undefined ? {} : { trail: body.trail }),
152
+ }).sockets,
153
+ ),
154
+ )
155
+ }
156
+
157
+ /** Every attachment's socket, `when` channel and `part` volume resolve on its body. */
158
+ function attachmentsResolve(body: AttachedBody): boolean {
159
+ const sockets = socketNames(body)
160
+ const channels = new Set(
161
+ (body.channels ?? []).map(
162
+ (row: { readonly name: string }): string => row.name,
163
+ ),
164
+ )
165
+ const broken = new Set(
166
+ (body.volumes ?? [])
167
+ .filter(
168
+ (row: { readonly channel?: string }): boolean =>
169
+ row.channel !== undefined,
170
+ )
171
+ .map((row: { readonly part: string }): string => row.part),
172
+ )
173
+ return (body.attachments ?? []).every(
174
+ (row: AttachmentView): boolean =>
175
+ (sockets === undefined || sockets.has(row.socket)) &&
176
+ (row.when === undefined || channels.has(row.when.channel)) &&
177
+ (row.part === undefined || broken.has(row.part)),
178
+ )
179
+ }
180
+
181
+ /** Shardfile reference rules: each part draws a library GLB under a declared material. */
182
+ function attachmentFileRules(source: {
183
+ readonly species: readonly {
184
+ readonly body?: { readonly attachments?: readonly AttachmentView[] }
185
+ }[]
186
+ readonly files: readonly { readonly hash: string; readonly kind: string }[]
187
+ readonly library: readonly string[]
188
+ readonly materials: Readonly<Record<string, unknown>>
189
+ }): string[] {
190
+ const glbs = new Set(
191
+ source.files
192
+ .filter((file: { readonly kind: string }): boolean => file.kind === 'glb')
193
+ .map((file: { readonly hash: string }): string => file.hash),
194
+ )
195
+ const library = new Set(source.library)
196
+ const meshes = source.species.flatMap(
197
+ (row: {
198
+ readonly body?: { readonly attachments?: readonly AttachmentView[] }
199
+ }): readonly MeshView[] =>
200
+ (row.body?.attachments ?? []).flatMap(
201
+ (item: AttachmentView): readonly MeshView[] => item.meshes,
202
+ ),
203
+ )
204
+ const errors: string[] = []
205
+ if (
206
+ meshes.some(
207
+ (part: MeshView): boolean =>
208
+ !glbs.has(part.geometry) || !library.has(part.geometry),
209
+ )
210
+ ) {
211
+ errors.push('creature attachment geometry')
212
+ }
213
+ if (
214
+ meshes.some(
215
+ (part: MeshView): boolean =>
216
+ !materialExists(source.materials, part.material),
217
+ )
218
+ ) {
219
+ errors.push('creature attachment material')
220
+ }
221
+ return errors
222
+ }
223
+
224
+ export {
225
+ CreatureAttachmentsSchema,
226
+ MAX_ATTACHMENTS,
227
+ attachmentFileRules,
228
+ attachmentsResolve,
229
+ volumeChannelsDeclared,
230
+ }
231
+ export type { CreatureAttachment, CreatureAttachmentMesh }
@@ -2,6 +2,7 @@ import {
2
2
  check,
3
3
  exactOptional,
4
4
  finite,
5
+ integer,
5
6
  maxLength,
6
7
  maxValue,
7
8
  minValue,
@@ -13,36 +14,81 @@ import {
13
14
  string,
14
15
  } from 'valibot'
15
16
 
16
- import { CREATURE_SKELETONS } from './creature-skeletons.ts'
17
+ import {
18
+ CreatureAttachmentsSchema,
19
+ attachmentsResolve,
20
+ volumeChannelsDeclared,
21
+ } from './creature-attachments.ts'
22
+ import {
23
+ CreatureChannelBindSchema,
24
+ CreatureChannelsSchema,
25
+ CreatureLookSwapSchema,
26
+ channelsDeclared,
27
+ } from './creature-channels.ts'
28
+ import { creatureContract } from './creature-skeletons.ts'
17
29
  import {
18
30
  CreatureVolumesSchema,
19
31
  CreatureLockSchema,
20
32
  MAX_VOLUMES,
21
33
  } from './creature-volumes.ts'
22
34
 
35
+ import type { CreatureAttachment } from './creature-attachments.ts'
36
+ import type {
37
+ CreatureChannel,
38
+ CreatureChannelBind,
39
+ CreatureLookSwap,
40
+ } from './creature-channels.ts'
23
41
  import type { CreatureSkeleton, CreatureSize } from './creature-layers.ts'
42
+ import type { CreatureTrail } from './creature-skeletons.ts'
24
43
  import type { CreatureVolume } from './creature-volumes.ts'
25
44
  import type { GenericSchema } from 'valibot'
26
45
 
27
46
  const ONE = 1
28
47
  const MAX_SCALE = 10
29
48
  const MAX_ID = 128
49
+ const MIN_TRAIL = 3
50
+ /** The head ball plus one volume per segment fit `MAX_VOLUMES`. */
51
+ const MAX_TRAIL = MAX_VOLUMES
52
+ const MAX_SPACING = 10
30
53
  const id = pipe(string(), regex(/^[a-z][a-zA-Z0-9.:-]*$/u), maxLength(MAX_ID))
31
54
  const scalar = pipe(number(), finite())
32
55
  interface CreatureBody {
33
56
  /** Omit for a GLB with its own rig; a kit poser names its contract explicitly. */
34
57
  skeleton?: CreatureSkeleton
58
+ /** A serpent's trail bones (ONE-FORMAT CC23); only a serpent has one. */
59
+ trail?: CreatureTrail
35
60
  size: CreatureSize
36
61
  scale: number
37
62
  look: string
38
63
  volumes?: CreatureVolume[]
39
64
  lock?: string[]
40
65
  hits?: 'rest' | 'clip'
66
+ /** ONE-FORMAT CC28: at most four actor channels, in wire order (animal fields 25 to 28). */
67
+ channels?: CreatureChannel[]
68
+ /** Material tint, emissive and opacity that follow channels. */
69
+ bind?: CreatureChannelBind
70
+ /** A second look drawn while a channel is high. */
71
+ swap?: CreatureLookSwap
72
+ /** ONE-FORMAT CC30a: at most eight parts hung on sockets, shown by channel, hidden by a broken part. */
73
+ attachments?: CreatureAttachment[]
41
74
  }
75
+ const trailCount = pipe(
76
+ number(),
77
+ integer(),
78
+ minValue(MIN_TRAIL),
79
+ maxValue(MAX_TRAIL),
80
+ )
81
+ const trailSpacing = pipe(
82
+ scalar,
83
+ minValue(Number.MIN_VALUE),
84
+ maxValue(MAX_SPACING),
85
+ )
86
+ const trailObject = strictObject({ count: trailCount, spacing: trailSpacing })
42
87
  const bodyObject = strictObject({
43
88
  skeleton: exactOptional(
44
- picklist(['quadruped', 'biped'], 'Unknown creature skeleton'),
89
+ picklist(['quadruped', 'biped', 'serpent'], 'Unknown creature skeleton'),
45
90
  ),
91
+ trail: exactOptional(trailObject),
46
92
  size: picklist(
47
93
  ['tiny', 'small', 'medium', 'large', 'giant'],
48
94
  'Unknown creature size',
@@ -52,6 +98,10 @@ const bodyObject = strictObject({
52
98
  volumes: exactOptional(CreatureVolumesSchema),
53
99
  lock: exactOptional(CreatureLockSchema),
54
100
  hits: exactOptional(picklist(['rest', 'clip'])),
101
+ channels: exactOptional(CreatureChannelsSchema),
102
+ bind: exactOptional(CreatureChannelBindSchema),
103
+ swap: exactOptional(CreatureLookSwapSchema),
104
+ attachments: exactOptional(CreatureAttachmentsSchema),
55
105
  })
56
106
  const CreatureBodySchema: GenericSchema<CreatureBody> = pipe(
57
107
  bodyObject,
@@ -65,15 +115,28 @@ const CreatureBodySchema: GenericSchema<CreatureBody> = pipe(
65
115
  ((body.lock?.length ?? ONE) <= ONE && body.hits !== 'clip'),
66
116
  'Only giants have multiple lock points or clip hits',
67
117
  ),
118
+ check<CreatureBody, 'A serpent has a trail row and only a serpent has one'>(
119
+ (body: {
120
+ readonly skeleton?: CreatureSkeleton
121
+ readonly trail?: CreatureTrail
122
+ }): boolean => (body.skeleton === 'serpent') === (body.trail !== undefined),
123
+ 'A serpent has a trail row and only a serpent has one',
124
+ ),
68
125
  check<CreatureBody, 'Too many resolved creature volumes'>(
69
126
  (body: {
70
127
  readonly skeleton?: CreatureSkeleton
128
+ readonly trail?: CreatureTrail
71
129
  readonly volumes?: readonly { readonly part: string }[]
72
130
  }): boolean => {
131
+ // A serpent without its trail is the check above's refusal
73
132
  const defaults =
74
- body.skeleton === undefined
133
+ body.skeleton === undefined ||
134
+ (body.skeleton === 'serpent' && body.trail === undefined)
75
135
  ? []
76
- : CREATURE_SKELETONS[body.skeleton].volumes
136
+ : creatureContract({
137
+ skeleton: body.skeleton,
138
+ ...(body.trail === undefined ? {} : { trail: body.trail }),
139
+ }).volumes
77
140
  return (
78
141
  new Set(
79
142
  [...defaults, ...(body.volumes ?? [])].map(
@@ -84,6 +147,18 @@ const CreatureBodySchema: GenericSchema<CreatureBody> = pipe(
84
147
  },
85
148
  'Too many resolved creature volumes',
86
149
  ),
150
+ check<CreatureBody, 'A creature binds an undeclared channel'>(
151
+ channelsDeclared,
152
+ 'A creature binds an undeclared channel',
153
+ ),
154
+ check<CreatureBody, 'A part breaks into an undeclared channel'>(
155
+ volumeChannelsDeclared,
156
+ 'A part breaks into an undeclared channel',
157
+ ),
158
+ check<CreatureBody, 'A creature attachment does not resolve'>(
159
+ attachmentsResolve,
160
+ 'A creature attachment does not resolve',
161
+ ),
87
162
  )
88
163
 
89
164
  export { CreatureBodySchema }
@@ -0,0 +1,130 @@
1
+ // ONE-FORMAT CC28: a body's actor channels and the looks bound to them.
2
+ // A creature has at most four channels, each a 0..1 value the server owns
3
+ // (a script's `actorChannel` command sets one) and the wire carries as
4
+ // animal fields 25 to 28 in the body's `channels` order. A page binds the
5
+ // look's material tint, emissive and opacity to channels, and may switch to
6
+ // a second look while a channel is at or above `at` (Q-CC48).
7
+ import {
8
+ array,
9
+ check,
10
+ exactOptional,
11
+ finite,
12
+ maxLength,
13
+ maxValue,
14
+ minLength,
15
+ minValue,
16
+ number,
17
+ pipe,
18
+ regex,
19
+ strictObject,
20
+ string,
21
+ tuple,
22
+ } from 'valibot'
23
+
24
+ import type { GenericSchema } from 'valibot'
25
+
26
+ const ZERO = 0
27
+ const ONE = 1
28
+ const MAX_CHANNELS = 4
29
+ const MAX_ID = 128
30
+ const id = pipe(string(), regex(/^[a-z][a-zA-Z0-9.:-]*$/u), maxLength(MAX_ID))
31
+ const unit = pipe(number(), finite(), minValue(ZERO), maxValue(ONE))
32
+ const colour = tuple([unit, unit, unit])
33
+
34
+ interface CreatureChannel {
35
+ name: string
36
+ /** The value a creature spawns with; 0 when omitted. */
37
+ initial?: number
38
+ }
39
+ /** A material term that follows one channel: the look's colour moves toward `colour` as the channel goes 0 to 1. */
40
+ interface CreatureChannelColour {
41
+ channel: string
42
+ colour: [number, number, number]
43
+ }
44
+ interface CreatureChannelBind {
45
+ tint?: CreatureChannelColour
46
+ emissive?: CreatureChannelColour
47
+ /** The material's opacity is this channel's value. */
48
+ opacity?: string
49
+ }
50
+ /** While `channel` is at or above `at` (0.5 when omitted) the body draws `look` instead of its own. */
51
+ interface CreatureLookSwap {
52
+ channel: string
53
+ look: string
54
+ at?: number
55
+ }
56
+
57
+ const channelRow = strictObject({ name: id, initial: exactOptional(unit) })
58
+ const CreatureChannelsSchema: GenericSchema<CreatureChannel[]> = pipe(
59
+ array(channelRow),
60
+ minLength(ONE),
61
+ maxLength(MAX_CHANNELS),
62
+ check<CreatureChannel[], 'Duplicate creature channel'>(
63
+ (rows: readonly { readonly name: string }[]): boolean =>
64
+ new Set(rows.map((row: { readonly name: string }): string => row.name))
65
+ .size === rows.length,
66
+ 'Duplicate creature channel',
67
+ ),
68
+ )
69
+ const channelColour = strictObject({ channel: id, colour })
70
+ const CreatureChannelBindSchema: GenericSchema<CreatureChannelBind> =
71
+ strictObject({
72
+ tint: exactOptional(channelColour),
73
+ emissive: exactOptional(channelColour),
74
+ opacity: exactOptional(id),
75
+ })
76
+ const CreatureLookSwapSchema: GenericSchema<CreatureLookSwap> = strictObject({
77
+ channel: id,
78
+ look: id,
79
+ at: exactOptional(unit),
80
+ })
81
+
82
+ /** Every channel name a body's `bind` and `swap` read. */
83
+ function boundChannels(body: {
84
+ readonly bind?: {
85
+ readonly tint?: { readonly channel: string }
86
+ readonly emissive?: { readonly channel: string }
87
+ readonly opacity?: string
88
+ }
89
+ readonly swap?: { readonly channel: string }
90
+ }): readonly string[] {
91
+ const { bind, swap } = body
92
+ return [
93
+ ...(bind?.tint === undefined ? [] : [bind.tint.channel]),
94
+ ...(bind?.emissive === undefined ? [] : [bind.emissive.channel]),
95
+ ...(bind?.opacity === undefined ? [] : [bind.opacity]),
96
+ ...(swap === undefined ? [] : [swap.channel]),
97
+ ]
98
+ }
99
+
100
+ /** A body binds only channels it declares. */
101
+ function channelsDeclared(body: {
102
+ readonly channels?: readonly { readonly name: string }[]
103
+ readonly bind?: {
104
+ readonly tint?: { readonly channel: string }
105
+ readonly emissive?: { readonly channel: string }
106
+ readonly opacity?: string
107
+ }
108
+ readonly swap?: { readonly channel: string }
109
+ }): boolean {
110
+ const names = new Set(
111
+ (body.channels ?? []).map(
112
+ (row: { readonly name: string }): string => row.name,
113
+ ),
114
+ )
115
+ return boundChannels(body).every((name: string): boolean => names.has(name))
116
+ }
117
+
118
+ export {
119
+ CreatureChannelBindSchema,
120
+ CreatureChannelsSchema,
121
+ CreatureLookSwapSchema,
122
+ channelsDeclared,
123
+ MAX_CHANNELS,
124
+ }
125
+ export type {
126
+ CreatureChannel,
127
+ CreatureChannelBind,
128
+ CreatureChannelColour,
129
+ CreatureLookSwap,
130
+ }
@@ -48,7 +48,7 @@ type CreatureType =
48
48
  | 'aquatic'
49
49
  | 'critter'
50
50
  | 'aberration'
51
- type CreatureSkeleton = 'quadruped' | 'biped'
51
+ type CreatureSkeleton = 'quadruped' | 'biped' | 'serpent'
52
52
  type CreatureSize = 'tiny' | 'small' | 'medium' | 'large' | 'giant'
53
53
  type CreatureReaction = 'passive' | 'skittish' | 'neutral' | 'aggressive'
54
54
  type CreatureTuningScalar = number | boolean | string
@@ -10,10 +10,11 @@ import {
10
10
  strictObject,
11
11
  } from 'valibot'
12
12
 
13
- import { CREATURE_SKELETONS } from './creature-skeletons.ts'
13
+ import { creatureContract } from './creature-skeletons.ts'
14
14
  import { CreatureSocketNameSchema } from './creature-volumes.ts'
15
15
 
16
16
  import type { CreatureSkeleton } from './creature-layers.ts'
17
+ import type { CreatureTrail } from './creature-skeletons.ts'
17
18
  import type { GenericSchema } from 'valibot'
18
19
 
19
20
  /** The seat socket both kit skeletons name. */
@@ -78,6 +79,7 @@ interface MountedSpecies {
78
79
  readonly flight?: unknown
79
80
  readonly body?: {
80
81
  readonly skeleton?: CreatureSkeleton
82
+ readonly trail?: CreatureTrail
81
83
  readonly volumes?: readonly { readonly part: string }[]
82
84
  }
83
85
  }
@@ -92,7 +94,13 @@ function seatKnown(seat: string, body: MountedSpecies['body']): boolean {
92
94
  // A GLB with its own rig names its sockets in its skin; admission checks the seat there.
93
95
  return (
94
96
  body?.skeleton === undefined ||
95
- Object.hasOwn(CREATURE_SKELETONS[body.skeleton].sockets, seat)
97
+ Object.hasOwn(
98
+ creatureContract({
99
+ skeleton: body.skeleton,
100
+ ...(body.trail === undefined ? {} : { trail: body.trail }),
101
+ }).sockets,
102
+ seat,
103
+ )
96
104
  )
97
105
  }
98
106
 
@@ -1,5 +1,8 @@
1
1
  import type { CreatureSkeleton } from './creature-layers.ts'
2
2
 
3
+ /** The skeletons whose bones never change with the body; a serpent's count comes from its `trail` row. */
4
+ type FixedSkeleton = Exclude<CreatureSkeleton, 'serpent'>
5
+
3
6
  interface SkeletonChain {
4
7
  readonly parent: string
5
8
  readonly bones: readonly string[]
@@ -115,11 +118,76 @@ const BIPED: SkeletonContract = {
115
118
  volumes: [bodyVolume('chest', 'y'), HEAD],
116
119
  clips: CLIPS,
117
120
  }
118
- const CREATURE_SKELETONS: Readonly<Record<CreatureSkeleton, SkeletonContract>> =
119
- {
120
- quadruped: QUADRUPED,
121
- biped: BIPED,
121
+ const CREATURE_SKELETONS: Readonly<Record<FixedSkeleton, SkeletonContract>> = {
122
+ quadruped: QUADRUPED,
123
+ biped: BIPED,
124
+ }
125
+
126
+ /** A serpent's trail row (ONE-FORMAT CC23): `count` bones `spacing` metres apart along the root's path. */
127
+ interface CreatureTrail {
128
+ readonly count: number
129
+ readonly spacing: number
130
+ }
131
+ const SEGMENT_MULTIPLIER = 0.5
132
+ const SEGMENT_RADIUS = 0.6
133
+ const HALF = 2
134
+ /** Trail bone names, head first: `head`, `seg1` … `seg<count-2>`, `tail`. */
135
+ function trailBoneName(index: number, count: number): string {
136
+ if (index === ZERO) {
137
+ return 'head'
122
138
  }
139
+ return index === count - ONE ? 'tail' : `seg${String(index)}`
140
+ }
141
+ function trailBoneNames(count: number): readonly string[] {
142
+ return Array.from(
143
+ { length: count },
144
+ (_unused: unknown, index: number): string => trailBoneName(index, count),
145
+ )
146
+ }
147
+ /**
148
+ * The serpent (ONE-FORMAT CC23): every bone is a trail bone following the head's path, so the chain is the whole
149
+ * body. Sockets `head`, `mouth`, `core` (the middle bone) and `tail`; one capsule per segment at x0.5 and the head
150
+ * ball at x2. Buried segments' volumes are off (the engine's poser); the lock stays on the head.
151
+ */
152
+ function serpentContract(trail: CreatureTrail): SkeletonContract {
153
+ const bones = trailBoneNames(trail.count)
154
+ const core = bones[Math.floor(trail.count / HALF)] ?? 'head'
155
+ const segments = bones.slice(ONE).map((bone: string): SkeletonVolume => ({
156
+ part: bone,
157
+ bone,
158
+ shape: 'capsule',
159
+ radius: SEGMENT_RADIUS,
160
+ halfLength: trail.spacing / HALF,
161
+ axis: 'z',
162
+ multiplier: SEGMENT_MULTIPLIER,
163
+ }))
164
+ return {
165
+ root: 'head',
166
+ chains: { spine: { parent: 'head', bones: bones.slice(ONE) } },
167
+ sockets: {
168
+ head: socket('head'),
169
+ mouth: { bone: 'head', at: [ZERO, ZERO, MOUTH_FORWARD] },
170
+ core: socket(core),
171
+ tail: socket('tail'),
172
+ },
173
+ lock: 'head',
174
+ volumes: [HEAD, ...segments],
175
+ clips: CLIPS,
176
+ }
177
+ }
178
+ /** The one contract a body declares: a fixed skeleton's, or a serpent's built from its trail row. */
179
+ function creatureContract(body: {
180
+ readonly skeleton: CreatureSkeleton
181
+ readonly trail?: CreatureTrail
182
+ }): SkeletonContract {
183
+ if (body.skeleton !== 'serpent') {
184
+ return CREATURE_SKELETONS[body.skeleton]
185
+ }
186
+ if (body.trail === undefined) {
187
+ throw new Error('A serpent needs its trail row')
188
+ }
189
+ return serpentContract(body.trail)
190
+ }
123
191
 
124
192
  /** Importers and posers share this list, rather than inferring a creature kind. */
125
193
  function skeletonBones(
@@ -133,5 +201,19 @@ function skeletonBones(
133
201
  ]
134
202
  }
135
203
 
136
- export { CREATURE_SKELETONS, MIN_VOLUME_RADIUS, skeletonBones }
137
- export type { SkeletonChain, SkeletonSocket, SkeletonVolume, SkeletonContract }
204
+ export {
205
+ CREATURE_SKELETONS,
206
+ MIN_VOLUME_RADIUS,
207
+ creatureContract,
208
+ serpentContract,
209
+ skeletonBones,
210
+ trailBoneNames,
211
+ }
212
+ export type {
213
+ CreatureTrail,
214
+ FixedSkeleton,
215
+ SkeletonChain,
216
+ SkeletonSocket,
217
+ SkeletonVolume,
218
+ SkeletonContract,
219
+ }
@@ -22,6 +22,10 @@ import type { GenericSchema } from 'valibot'
22
22
  /** Bone-local rest offset. The runtime clamps the scaled radius, not the source. */
23
23
  interface CreatureVolume extends SkeletonVolume {
24
24
  at?: [number, number, number]
25
+ /** Part hp (ONE-FORMAT CC31): the part breaks at 0, once; later hits pass to the next volume. */
26
+ hp?: number
27
+ /** ONE-FORMAT CC30a: a body channel this part's break sets to 1, so every page sees it broken. */
28
+ channel?: string
25
29
  }
26
30
  const ZERO = 0
27
31
  const ONE = 1
@@ -29,6 +33,7 @@ const MAX_VOLUMES = 16
29
33
  const MAX_NAME = 128
30
34
  const MAX_EXTENT = 500
31
35
  const MAX_MULTIPLIER = 100
36
+ const MAX_PART_HP = 1_000_000
32
37
  const CreatureSocketNameSchema: GenericSchema<string> = pipe(
33
38
  string(),
34
39
  regex(/^[a-zA-Z][a-zA-Z0-9_.:-]*$/u),
@@ -37,6 +42,12 @@ const CreatureSocketNameSchema: GenericSchema<string> = pipe(
37
42
  const scalar = pipe(number(), finite())
38
43
  const extent = pipe(scalar, minValue(ZERO), maxValue(MAX_EXTENT))
39
44
  const offset = pipe(scalar, minValue(-MAX_EXTENT), maxValue(MAX_EXTENT))
45
+ const partHp = pipe(scalar, minValue(Number.MIN_VALUE), maxValue(MAX_PART_HP))
46
+ const channelName = pipe(
47
+ string(),
48
+ regex(/^[a-z][a-zA-Z0-9.:-]*$/u),
49
+ maxLength(MAX_NAME),
50
+ )
40
51
  const volumeObject = strictObject({
41
52
  part: CreatureSocketNameSchema,
42
53
  bone: CreatureSocketNameSchema,
@@ -46,6 +57,8 @@ const volumeObject = strictObject({
46
57
  axis: picklist(['y', 'z']),
47
58
  multiplier: pipe(scalar, minValue(ZERO), maxValue(MAX_MULTIPLIER)),
48
59
  at: exactOptional(tuple([offset, offset, offset])),
60
+ hp: exactOptional(partHp),
61
+ channel: exactOptional(channelName),
49
62
  })
50
63
  const CreatureVolumeSchema: GenericSchema<CreatureVolume> = pipe(
51
64
  volumeObject,
@@ -14,7 +14,10 @@ import { DiverSchema, OrbitDiverSchema, PatrolDiverSchema, BurstFlyerSchema } fr
14
14
  /** One creature spawn row; input and output differ only in the home they carry. */
15
15
  interface CreatureSpawnRow<Home> { perchBody?: string; group?: string; rank?: 'veteran' | 'elite' | 'champion' | 'legendary'; count?: { per: number; max: number }; when?: { quest?: { id: string; stage: number }; time?: 'day' | 'night'; wave?: { set: string; index: number } }; phaseOffset?: number | undefined; respawn?: number | undefined; home?: Home | undefined; id: string; species: string; variant: string; brain: (string) | null; strike: (string) | null; seed: number; scale: number; at: [number, number, number]; yaw: number; }
16
16
 
17
- const id = v.pipe(v.string(), v.regex(/^[a-z][a-z0-9.:-]*$/u), v.maxLength(128));
17
+ const ID_LENGTH = 128;
18
+ const id = v.pipe(v.string(), v.regex(/^[a-z][a-z0-9.:-]*$/u), v.maxLength(ID_LENGTH));
19
+ /** A species row id may carry capitals (OF11a): the spawn that places it names it the same way. */
20
+ const speciesId = v.pipe(v.string(), v.regex(/^[a-z][a-zA-Z0-9.:-]*$/u), v.maxLength(ID_LENGTH));
18
21
  const finite = v.pipe(v.number(), v.finite());
19
22
  const radius = v.pipe(finite, v.minValue(0), v.maxValue(500));
20
23
  const speed = v.pipe(finite, v.minValue(0), v.maxValue(15));
@@ -82,7 +85,7 @@ const questWhen = v.strictObject({ id, stage });
82
85
  const waveWhen = v.strictObject({ set: id, index: countPart });
83
86
  const timeWhen = v.picklist(['day', 'night'], 'unknown spawn time');
84
87
  const when = v.strictObject({ quest: v.exactOptional(questWhen), time: v.exactOptional(timeWhen), wave: v.exactOptional(waveWhen) }, 'unknown spawn condition');
85
- const spawn = v.strictObject({ perchBody: v.exactOptional(id), group: v.exactOptional(id), rank: v.exactOptional(rank), count: v.exactOptional(count), when: v.exactOptional(when), phaseOffset: v.optional(phase), home: v.optional(CreatureHomeSchema), respawn: v.optional(respawn), id, species: id, variant: id, brain: v.nullable(id), strike: v.nullable(id), seed: v.pipe(finite, v.integer(), v.minValue(0), v.maxValue(0xffffffff)), scale: v.pipe(finite, v.minValue(0.1), v.maxValue(10)), at: v.tuple([coord, coord, coord]), yaw: finite });
88
+ const spawn = v.strictObject({ perchBody: v.exactOptional(id), group: v.exactOptional(id), rank: v.exactOptional(rank), count: v.exactOptional(count), when: v.exactOptional(when), phaseOffset: v.optional(phase), home: v.optional(CreatureHomeSchema), respawn: v.optional(respawn), id, species: speciesId, variant: id, brain: v.nullable(id), strike: v.nullable(id), seed: v.pipe(finite, v.integer(), v.minValue(0), v.maxValue(0xffffffff)), scale: v.pipe(finite, v.minValue(0.1), v.maxValue(10)), at: v.tuple([coord, coord, coord]), yaw: finite });
86
89
  /** Pure-data creature archetypes and stable spawn layouts, expanded before the local sim boots. */
87
90
  export const CreaturesSchema: v.GenericSchema<ShardCreaturesInput, ShardCreatures> = v.pipe(v.strictObject({ perchBodies: v.exactOptional(CreaturePerchBodiesSchema), brains: v.pipe(v.array(v.variant('kind', [brain, SkirmisherSchema, GuardianSchema, PerchHunterSchema, ScriptBrainSchema, RamGrazerSchema, ChallengeGrazerSchema, OrbitDiverSchema, PatrolDiverSchema, BurstFlyerSchema, GrazerSchema, DiverSchema, GuardianPatternsSchema, StalkerSchema])), v.maxLength(64)), groups: v.optional(v.pipe(v.array(GroupBrainSchema), v.maxLength(64)), []), patrols: v.exactOptional(CreaturePatrolsSchema), spawns: v.pipe(v.array(spawn), v.maxLength(10000)) }),
88
91
  v.check((c) => creatureRules(c).length === 0 && patrolsAdmitted(c.patrols ?? [], c.spawns, c.groups), 'creature reference rules'));
@@ -9,6 +9,10 @@ const id = v.pipe(v.string(), v.regex(/^[A-Za-z][A-Za-z0-9.:-]*$/u), v.maxLength
9
9
  const local = v.pipe(v.string(), v.regex(/^[A-Za-z_][A-Za-z0-9_.-]*$/u), v.maxLength(64));
10
10
  const finite = v.pipe(v.number(), v.finite());
11
11
  const positive = v.pipe(finite, v.integer(), v.minValue(1), v.maxValue(0x7fffffff));
12
+ const HIT_TAG_LENGTH = 64;
13
+ const HIT_TAGS = 16;
14
+ const hitTag = v.pipe(v.string(), v.regex(/^[a-z][a-z0-9_-]*(?:\.[a-z0-9_-]+)+$/u), v.maxLength(HIT_TAG_LENGTH));
15
+ const hitTags = v.pipe(v.record(local, hitTag), v.check((value: Readonly<Record<string, string>>): boolean => Object.keys(value).length <= HIT_TAGS, 'at most 16 hit tags'));
12
16
  const aliases = v.pipe(v.record(local, id), v.check(value => Object.keys(value).length <= 256, 'bounded script id map'));
13
17
  const unique = (values: readonly unknown[]): boolean => new Set(values).size === values.length;
14
18
  const readNames: ("x" | "y" | "z" | "yaw" | "hpShare" | "alive" | "field" | "distance" | "nearestPlayer" | "flag" | "timerLeft" | "random" | "actorInZone" | "playersInZone" | "moving" | "strikeState" | "playerFlag" | "spawnGroupAlive" | "bearing" | "bodyX" | "bodyY" | "bodyZ" | "bodyAlive" | "bodyYaw" | "bodyVisible" | "playerIntent" | "actorsInZone" | "playersWithin" | "groundHeight" | "nearestWalkable" | "path" | "radial" | "declaredFloor")[] = [...keys(SCRIPT_V1_READS), ...keys(SCRIPT_V1_LISTS)];
@@ -25,7 +29,8 @@ const rowEntries = {
25
29
  source: v.pipe(v.string(), v.maxLength(256), v.regex(/^behaviour\/(?:[A-Za-z0-9_-][A-Za-z0-9_.-]*\/)*[A-Za-z0-9_-][A-Za-z0-9_.-]*\.as$/u),
26
30
  v.check(value => !value.split('/').includes('generated'), 'authored script source, not generated glue')),
27
31
  sourceHash: v.exactOptional(v.pipe(v.string(), v.regex(/^[a-f0-9]{64}$/u))),
28
- binding: v.union([v.strictObject({ encounter: id }), v.strictObject({ quest: id }), v.strictObject({ zone: id }), v.strictObject({ shard: v.literal(true) }), v.strictObject({ spawnGroup: id })]),
32
+ // CC59: `brain` hooks a script onto a brain-owned creature; the brain keeps its body (no move, strike or stop).
33
+ binding: v.union([v.strictObject({ encounter: id }), v.strictObject({ quest: id }), v.strictObject({ zone: id }), v.strictObject({ shard: v.literal(true) }), v.strictObject({ spawnGroup: id }), v.strictObject({ brain: id })]),
29
34
  pages: v.optional(v.pipe(positive, v.maxValue(4)), 1), onFail: v.picklist(['hold', 'reset', 'skip']),
30
35
  on: v.pipe(v.array(v.picklist(keys(SCRIPT_V1_EVENTS))), v.minLength(1), v.maxLength(23), v.check(values => unique(values), 'unique subscribed events')),
31
36
  tick: v.optional(v.nullable(v.picklist([1, 2, 5, 10])), null),
@@ -36,6 +41,8 @@ const rowEntries = {
36
41
  targets: v.optional(aliases, {}), spawns: v.optional(aliases, {}), signals: v.optional(aliases, {}), facts: v.optional(aliases, {}),
37
42
  rewards: v.optional(aliases, {}), channels: v.optional(aliases, {}), impulses: v.optional(aliases, {}), weather: v.optional(aliases, {}),
38
43
  bodies: v.exactOptional(aliases), colliders: v.exactOptional(aliases),
44
+ // CC59: combat tags a hit event reports as a mask, bit i for the i-th alias in sorted order.
45
+ tags: v.exactOptional(hitTags),
39
46
  timers: v.optional(v.pipe(v.array(local), v.maxLength(64), v.check(values => unique(values), 'unique timer names')), []),
40
47
  stateVersion: positive, state: v.pipe(v.array(state), v.maxLength(16)),
41
48
  params: v.pipe(v.record(local, finite), v.check(value => Object.keys(value).length <= 32, 'bounded script parameters')),
@@ -64,6 +71,11 @@ export function decisionScriptRowRules(script: DecisionScriptRow): string[] {
64
71
  if ('spawnGroup' in script.binding && (Object.keys(script.actors).length === 0 || script.state.some(slot => slot.scope !== 'actor')))
65
72
  errors.push('spawn groups declare members and actor-scoped simulation state');
66
73
  if ((script.tick !== null) !== script.on.includes('tick')) errors.push('tick subscription has a declared 1/2/5/10 Hz rate');
74
+ if ('brain' in script.binding && (!Object.values(script.actors).includes(script.binding.brain)
75
+ || script.commands.some((name): boolean => name === 'move' || name === 'strike' || name === 'stop'))) {
76
+ errors.push('a brain hook names its creature and leaves move, strike and stop to the brain');
77
+ }
78
+ if (script.tags !== undefined && !validNames(Object.keys(script.tags))) { errors.push('unique nonreserved generated binding names'); }
67
79
  if (script.on.some(name => SCRIPT_V1_EVENTS[name] >= 30) || script.commands.some(name => SCRIPT_V1_COMMANDS[name] >= 100)) errors.push('simulation script uses only simulation ops');
68
80
  if (script.side === 'view' && !script.commands.every(isViewCommand)) { errors.push(VIEW_WRITES_GAMEPLAY); }
69
81
  for (const names of [...SCRIPT_V1_REFERENCE_KINDS.map(kind => Object.keys(script[kind] ?? {})), script.timers, script.state.map(slot => slot.name), Object.keys(script.params)]) {
@@ -207,6 +219,8 @@ interface DecisionScriptRowInputFields {
207
219
  shard: true;
208
220
  }) | ({
209
221
  spawnGroup: string;
222
+ }) | ({
223
+ brain: string;
210
224
  });
211
225
  pages?: number | undefined;
212
226
  onFail: 'hold' | 'reset' | 'skip';
@@ -232,6 +246,7 @@ interface DecisionScriptRowInputFields {
232
246
  weather?: Record<string, string> | undefined;
233
247
  bodies?: Record<string, string>;
234
248
  colliders?: Record<string, string>;
249
+ tags?: Record<string, string>;
235
250
  timers?: (string)[] | undefined;
236
251
  stateVersion: number;
237
252
  state: ({
@@ -262,6 +277,8 @@ interface DecisionScriptRowFields {
262
277
  shard: true;
263
278
  }) | ({
264
279
  spawnGroup: string;
280
+ }) | ({
281
+ brain: string;
265
282
  });
266
283
  pages: number;
267
284
  onFail: 'hold' | 'reset' | 'skip';
@@ -287,6 +304,7 @@ interface DecisionScriptRowFields {
287
304
  weather: Record<string, string>;
288
305
  bodies?: Record<string, string>;
289
306
  colliders?: Record<string, string>;
307
+ tags?: Record<string, string>;
290
308
  timers: (string)[];
291
309
  stateVersion: number;
292
310
  state: ({
@@ -7,7 +7,10 @@ const coord = v.pipe(finite, v.minValue(-250), v.maxValue(250));
7
7
  const point = v.tuple([coord, coord, coord]);
8
8
  const positive = v.pipe(finite, v.minValue(0.001), v.maxValue(500));
9
9
  const duration = v.pipe(finite, v.minValue(0), v.maxValue(60));
10
- const phase = v.strictObject({ at: v.pipe(finite, v.minValue(0.001), v.maxValue(1)), name: label, caption: label, speed: v.pipe(finite, v.minValue(0), v.maxValue(15)), stopDistance: v.pipe(finite, v.minValue(0), v.maxValue(50)), turnRate: v.pipe(finite, v.minValue(0), v.maxValue(30)) });
10
+ // ONE-FORMAT CC59: a phase's `adds` are spawn rows that wait out of the world until the fight reaches that phase.
11
+ const MAX_ADDS = 8;
12
+ const adds = v.exactOptional(v.pipe(v.array(id), v.nonEmpty(), v.maxLength(MAX_ADDS)));
13
+ const phase = v.strictObject({ at: v.pipe(finite, v.minValue(0.001), v.maxValue(1)), name: label, caption: label, speed: v.pipe(finite, v.minValue(0), v.maxValue(15)), stopDistance: v.pipe(finite, v.minValue(0), v.maxValue(50)), turnRate: v.pipe(finite, v.minValue(0), v.maxValue(30)), adds });
11
14
  /**
12
15
  * ONE-FORMAT OF34a (J420 (1), Jake 2026-11-18): every boss is three parts. `boss` is the one fight: it `start`s `placed`
13
16
  * (its body stands in the world from load, as before), `spawned` (no body until a player enters the arena) or `resident`
@@ -29,7 +32,11 @@ function bossOnly(row: Readonly<{ kind: 'elite' | 'boss'; start?: (typeof BOSS_S
29
32
  const encounter = v.pipe(v.strictObject({ id, entity: id, kind: v.picklist(['elite', 'boss']), panel: v.nullable(id), name: label, title: label, retry: label,
30
33
  start, capExempt, arena, intro: duration, introShort: duration,
31
34
  respawn: v.strictObject({ at: point, yaw: finite }), phases: v.pipe(v.array(phase), v.minLength(1), v.maxLength(16)) }),
32
- v.check((e) => e.phases[0]?.at === 1 && e.phases.every((p, i) => i === 0 || p.at < (e.phases[i - 1]?.at ?? 0)), 'descending phase thresholds starting at 1'),
35
+ v.check((e): boolean => {
36
+ let last = Number.POSITIVE_INFINITY;
37
+ for (const step of e.phases) { if (!(step.at < last)) { return false; } last = step.at; }
38
+ return e.phases[0]?.at === 1;
39
+ }, 'descending phase thresholds starting at 1'),
33
40
  v.check<ShardEncounters[number], string>(bossOnly, 'Only a boss has a start or capExempt'));
34
41
  /** Elite/boss phase tables with checkpoints/retry, neutral steering data and declared panel references. */
35
42
  export const EncountersSchema: v.GenericSchema<ShardEncountersInput, ShardEncounters> = v.pipe(v.array(encounter), v.maxLength(64), v.check((rows) => new Set(rows.map((e) => e.id)).size === rows.length && new Set(rows.map((e) => e.entity)).size === rows.length, 'unique encounter ids and actors'));
@@ -41,6 +48,11 @@ export function encounterRules(rows: ShardEncounters, entities: readonly string[
41
48
  for (const row of rows) {
42
49
  if (!entities.includes(row.entity)) errors.push('declared encounter actor');
43
50
  if (row.panel !== null && !panels.some((p) => p.id === row.panel && p.encounter === row.id)) errors.push('declared matching boss panel');
51
+ for (const step of row.phases) {
52
+ for (const add of step.adds ?? []) {
53
+ if (add === row.entity || !entities.includes(add)) { errors.push('phase adds name other declared spawns'); }
54
+ }
55
+ }
44
56
  }
45
57
  return [...new Set(errors)];
46
58
  }
@@ -83,5 +95,6 @@ export type ShardEncounters = ({
83
95
  speed: number;
84
96
  stopDistance: number;
85
97
  turnRate: number;
98
+ adds?: string[];
86
99
  })[];
87
100
  })[];
@@ -18,6 +18,8 @@
18
18
  import { detailLayer } from './detail-layer.ts';
19
19
  import type { DetailLayer } from './detail-layer.ts';
20
20
  import { pbrEmissive, pbrEmissiveIntensity } from './pbr-emissive.ts';
21
+ import { pbrRim, pbrSheen } from './pbr-fur.ts';
22
+ import type { PbrSheen } from './pbr-fur.ts';
21
23
  import { emissiveCard, emissiveMotion, surfaceBlend, surfaceDepthOffset, surfaceOpacity, surfaceSway, surfaceSwing, surfaceUvScroll } from './scene-render.ts';
22
24
  import type { CardMotion, SurfaceSway } from './scene-render.ts';
23
25
  import * as v from 'valibot';
@@ -212,7 +214,7 @@ export function measureUv(role: MeasureRole, u: number, up: number, w: number, h
212
214
  }
213
215
 
214
216
  /** One PBR surface: metal / rough with colour, normal and packed ORM maps (occlusion r, roughness g, metalness b). */
215
- export const PbrMaterialSchema: v.StrictObjectSchema<{ readonly family: v.GenericSchema<PbrMaterialParamsInput['family'], PbrMaterialParams['family']>; readonly colour: v.OptionalSchema<v.GenericSchema<Exclude<PbrMaterialParamsInput['colour'], undefined>, PbrMaterialParams['colour']>, MaterialSchemaDefault<Exclude<PbrMaterialParamsInput['colour'], undefined>>>; readonly roughness: v.OptionalSchema<v.GenericSchema<Exclude<PbrMaterialParamsInput['roughness'], undefined>, PbrMaterialParams['roughness']>, MaterialSchemaDefault<Exclude<PbrMaterialParamsInput['roughness'], undefined>>>; readonly metalness: v.OptionalSchema<v.GenericSchema<Exclude<PbrMaterialParamsInput['metalness'], undefined>, PbrMaterialParams['metalness']>, MaterialSchemaDefault<Exclude<PbrMaterialParamsInput['metalness'], undefined>>>; readonly maps: v.OptionalSchema<v.GenericSchema<Exclude<PbrMaterialParamsInput['maps'], undefined>, PbrMaterialParams['maps']>, MaterialSchemaDefault<Exclude<PbrMaterialParamsInput['maps'], undefined>>>; readonly normalScale: v.OptionalSchema<v.GenericSchema<Exclude<PbrMaterialParamsInput['normalScale'], undefined>, PbrMaterialParams['normalScale']>, MaterialSchemaDefault<Exclude<PbrMaterialParamsInput['normalScale'], undefined>>>; readonly occlusion: v.OptionalSchema<v.GenericSchema<Exclude<PbrMaterialParamsInput['occlusion'], undefined>, PbrMaterialParams['occlusion']>, MaterialSchemaDefault<Exclude<PbrMaterialParamsInput['occlusion'], undefined>>>; readonly envStrength: v.OptionalSchema<v.GenericSchema<Exclude<PbrMaterialParamsInput['envStrength'], undefined>, PbrMaterialParams['envStrength']>, MaterialSchemaDefault<Exclude<PbrMaterialParamsInput['envStrength'], undefined>>>; readonly vertexColours: v.OptionalSchema<v.GenericSchema<Exclude<PbrMaterialParamsInput['vertexColours'], undefined>, PbrMaterialParams['vertexColours']>, MaterialSchemaDefault<Exclude<PbrMaterialParamsInput['vertexColours'], undefined>>>; readonly faceted: v.OptionalSchema<v.GenericSchema<Exclude<PbrMaterialParamsInput['faceted'], undefined>, PbrMaterialParams['faceted']>, MaterialSchemaDefault<Exclude<PbrMaterialParamsInput['faceted'], undefined>>>; readonly doubleSided: v.OptionalSchema<v.GenericSchema<Exclude<PbrMaterialParamsInput['doubleSided'], undefined>, PbrMaterialParams['doubleSided']>, MaterialSchemaDefault<Exclude<PbrMaterialParamsInput['doubleSided'], undefined>>>; readonly alphaCutoff: v.OptionalSchema<v.GenericSchema<Exclude<PbrMaterialParamsInput['alphaCutoff'], undefined>, PbrMaterialParams['alphaCutoff']>, MaterialSchemaDefault<Exclude<PbrMaterialParamsInput['alphaCutoff'], undefined>>>; readonly ground: v.OptionalSchema<v.GenericSchema<Exclude<PbrMaterialParamsInput['ground'], undefined>, PbrMaterialParams['ground']>, MaterialSchemaDefault<Exclude<PbrMaterialParamsInput['ground'], undefined>>>; readonly measure: v.OptionalSchema<v.GenericSchema<Exclude<PbrMaterialParamsInput['measure'], undefined>, PbrMaterialParams['measure']>, MaterialSchemaDefault<Exclude<PbrMaterialParamsInput['measure'], undefined>>>; readonly detail: typeof detailLayer; readonly emissive: typeof pbrEmissive; readonly emissiveIntensity: typeof pbrEmissiveIntensity; readonly blend: typeof surfaceBlend; readonly opacity: typeof surfaceOpacity; readonly depthOffset: typeof surfaceDepthOffset; readonly sway: typeof surfaceSway; readonly uvScroll: typeof surfaceUvScroll; readonly swing: typeof surfaceSwing; }, undefined> = v.strictObject({
217
+ export const PbrMaterialSchema: v.StrictObjectSchema<{ readonly family: v.GenericSchema<PbrMaterialParamsInput['family'], PbrMaterialParams['family']>; readonly colour: v.OptionalSchema<v.GenericSchema<Exclude<PbrMaterialParamsInput['colour'], undefined>, PbrMaterialParams['colour']>, MaterialSchemaDefault<Exclude<PbrMaterialParamsInput['colour'], undefined>>>; readonly roughness: v.OptionalSchema<v.GenericSchema<Exclude<PbrMaterialParamsInput['roughness'], undefined>, PbrMaterialParams['roughness']>, MaterialSchemaDefault<Exclude<PbrMaterialParamsInput['roughness'], undefined>>>; readonly metalness: v.OptionalSchema<v.GenericSchema<Exclude<PbrMaterialParamsInput['metalness'], undefined>, PbrMaterialParams['metalness']>, MaterialSchemaDefault<Exclude<PbrMaterialParamsInput['metalness'], undefined>>>; readonly maps: v.OptionalSchema<v.GenericSchema<Exclude<PbrMaterialParamsInput['maps'], undefined>, PbrMaterialParams['maps']>, MaterialSchemaDefault<Exclude<PbrMaterialParamsInput['maps'], undefined>>>; readonly normalScale: v.OptionalSchema<v.GenericSchema<Exclude<PbrMaterialParamsInput['normalScale'], undefined>, PbrMaterialParams['normalScale']>, MaterialSchemaDefault<Exclude<PbrMaterialParamsInput['normalScale'], undefined>>>; readonly occlusion: v.OptionalSchema<v.GenericSchema<Exclude<PbrMaterialParamsInput['occlusion'], undefined>, PbrMaterialParams['occlusion']>, MaterialSchemaDefault<Exclude<PbrMaterialParamsInput['occlusion'], undefined>>>; readonly envStrength: v.OptionalSchema<v.GenericSchema<Exclude<PbrMaterialParamsInput['envStrength'], undefined>, PbrMaterialParams['envStrength']>, MaterialSchemaDefault<Exclude<PbrMaterialParamsInput['envStrength'], undefined>>>; readonly vertexColours: v.OptionalSchema<v.GenericSchema<Exclude<PbrMaterialParamsInput['vertexColours'], undefined>, PbrMaterialParams['vertexColours']>, MaterialSchemaDefault<Exclude<PbrMaterialParamsInput['vertexColours'], undefined>>>; readonly faceted: v.OptionalSchema<v.GenericSchema<Exclude<PbrMaterialParamsInput['faceted'], undefined>, PbrMaterialParams['faceted']>, MaterialSchemaDefault<Exclude<PbrMaterialParamsInput['faceted'], undefined>>>; readonly doubleSided: v.OptionalSchema<v.GenericSchema<Exclude<PbrMaterialParamsInput['doubleSided'], undefined>, PbrMaterialParams['doubleSided']>, MaterialSchemaDefault<Exclude<PbrMaterialParamsInput['doubleSided'], undefined>>>; readonly alphaCutoff: v.OptionalSchema<v.GenericSchema<Exclude<PbrMaterialParamsInput['alphaCutoff'], undefined>, PbrMaterialParams['alphaCutoff']>, MaterialSchemaDefault<Exclude<PbrMaterialParamsInput['alphaCutoff'], undefined>>>; readonly ground: v.OptionalSchema<v.GenericSchema<Exclude<PbrMaterialParamsInput['ground'], undefined>, PbrMaterialParams['ground']>, MaterialSchemaDefault<Exclude<PbrMaterialParamsInput['ground'], undefined>>>; readonly measure: v.OptionalSchema<v.GenericSchema<Exclude<PbrMaterialParamsInput['measure'], undefined>, PbrMaterialParams['measure']>, MaterialSchemaDefault<Exclude<PbrMaterialParamsInput['measure'], undefined>>>; readonly detail: typeof detailLayer; readonly emissive: typeof pbrEmissive; readonly emissiveIntensity: typeof pbrEmissiveIntensity; readonly sheen: typeof pbrSheen; readonly rim: typeof pbrRim; readonly blend: typeof surfaceBlend; readonly opacity: typeof surfaceOpacity; readonly depthOffset: typeof surfaceDepthOffset; readonly sway: typeof surfaceSway; readonly uvScroll: typeof surfaceUvScroll; readonly swing: typeof surfaceSwing; }, undefined> = v.strictObject({
216
218
  family: v.literal('pbr'),
217
219
  /** sRGB, multiplies the colour map */
218
220
  colour: v.optional(srgb, [1, 1, 1]),
@@ -242,6 +244,10 @@ export const PbrMaterialSchema: v.StrictObjectSchema<{ readonly family: v.Generi
242
244
  emissive: pbrEmissive,
243
245
  /** M4.3: the glow's linear gain (HDR); absent = 1 */
244
246
  emissiveIntensity: pbrEmissiveIntensity,
247
+ /** OF27b: a fur's velvet sheen (`amount` of linear `colour` at `roughness`); absent = none */
248
+ sheen: pbrSheen,
249
+ /** OF27b: a fur's backlit rim colour (linear); absent = none */
250
+ rim: pbrRim,
245
251
  /** AP10: 'alpha' draws it see-through after the opaque world (a stencil, a decal); absent = opaque */
246
252
  blend: surfaceBlend,
247
253
  /** AP10: the alpha blend's scale; absent = 1 */
@@ -570,9 +576,9 @@ export interface GroundLayerParamsInput { wind?: [number, number] | undefined; w
570
576
  export interface GroundLayerParams { wind: [number, number]; wavelength: [number, number]; lump: number; depth: [number, number]; relief: [number, number, number]; contrast: { near: number; far: number; window: [number, number]; strength: number; }; fade: [number, number]; slip: [number, number]; flat: [number, number]; patches: { floor: number; near: number; window: [number, number]; }; grain: { map: (string) | null; mean: number; glintMean: number; strength: number; }; macro: [[number, number, number], [number, number, number]]; albedo: number; streaks: { tint: [number, number, number]; amount: number; }; trail: ({ map: string; rect: [number, number, number, number]; ripples: number; tint: [number, number, number]; amount: number; }) | null; keyShadow: ({ map: string; rect: [number, number, number, number]; edge: [number, number]; floor: number; }) | null; terminator: number; crest: { band: [number, number]; gain: number; }; sheen: number; shade: { tint: [number, number, number]; gain: number; lift: [number, number, number]; amount: number; edge: number; floor: [number, number, number]; }; saturation: { flat: number; facing: number; coolTint: [number, number, number]; keep: number; }; away: { from: [number, number]; amount: number; }; pools: ({ low: [number, number, number]; high: [number, number, number]; split: number; radius: number; gain: number; source?: string; }) | null; }
571
577
  export interface MeasureLayerParamsInput { structure?: [number, number, number] | undefined; trim?: [number, number, number] | undefined; floor?: [number, number, number] | undefined; line?: { colour: [number, number, number]; alpha: number; floorAlpha: number; width: number; } | undefined; sub?: { step: number; alpha: number; } | undefined; label?: { colour: [number, number, number]; height: number; } | undefined; lift?: number | undefined; tint?: [number, number, number]; grain?: { amount: [number, number, number]; size: number; }; grid?: [number, number, number]; }
572
578
  export interface MeasureLayerParams { structure: [number, number, number]; trim: [number, number, number]; floor: [number, number, number]; line: { colour: [number, number, number]; alpha: number; floorAlpha: number; width: number; }; sub: { step: number; alpha: number; }; label: { colour: [number, number, number]; height: number; }; lift: number; tint?: [number, number, number]; grain?: { amount: [number, number, number]; size: number; }; grid?: [number, number, number]; }
573
- export interface PbrMaterialParamsInput { family: 'pbr'; colour?: [number, number, number] | undefined; roughness?: number | undefined; metalness?: number | undefined; maps?: { colour: (string) | null; normal: (string) | null; orm: (string) | null; } | undefined; normalScale?: number | undefined; occlusion?: number | undefined; envStrength?: number | undefined; vertexColours?: boolean | undefined; faceted?: boolean | undefined; doubleSided?: boolean | undefined; alphaCutoff?: number | undefined; ground?: (GroundLayerParamsInput) | null | undefined; measure?: (MeasureLayerParamsInput) | null | undefined; detail?: DetailLayer; emissive?: [number, number, number]; emissiveIntensity?: number; blend?: 'opaque' | 'alpha'; opacity?: number; depthOffset?: number; sway?: SurfaceSway; uvScroll?: [number, number]; swing?: true; }
579
+ export interface PbrMaterialParamsInput { family: 'pbr'; colour?: [number, number, number] | undefined; roughness?: number | undefined; metalness?: number | undefined; maps?: { colour: (string) | null; normal: (string) | null; orm: (string) | null; } | undefined; normalScale?: number | undefined; occlusion?: number | undefined; envStrength?: number | undefined; vertexColours?: boolean | undefined; faceted?: boolean | undefined; doubleSided?: boolean | undefined; alphaCutoff?: number | undefined; ground?: (GroundLayerParamsInput) | null | undefined; measure?: (MeasureLayerParamsInput) | null | undefined; detail?: DetailLayer; emissive?: [number, number, number]; emissiveIntensity?: number; sheen?: PbrSheen; rim?: [number, number, number]; blend?: 'opaque' | 'alpha'; opacity?: number; depthOffset?: number; sway?: SurfaceSway; uvScroll?: [number, number]; swing?: true; }
574
580
  // oxlint-disable-next-line typescript/consistent-type-definitions -- Graph admission requires the material alias's implicit dictionary compatibility.
575
- export type PbrMaterialParams = { family: 'pbr'; colour: [number, number, number]; roughness: number; metalness: number; maps: { colour: (string) | null; normal: (string) | null; orm: (string) | null; }; normalScale: number; occlusion: number; envStrength: number; vertexColours: boolean; faceted: boolean; doubleSided: boolean; alphaCutoff: number; ground: (GroundLayerParams) | null; measure: (MeasureLayerParams) | null; detail?: DetailLayer; emissive?: [number, number, number]; emissiveIntensity?: number; blend?: 'opaque' | 'alpha'; opacity?: number; depthOffset?: number; sway?: SurfaceSway; uvScroll?: [number, number]; swing?: true; };
581
+ export type PbrMaterialParams = { family: 'pbr'; colour: [number, number, number]; roughness: number; metalness: number; maps: { colour: (string) | null; normal: (string) | null; orm: (string) | null; }; normalScale: number; occlusion: number; envStrength: number; vertexColours: boolean; faceted: boolean; doubleSided: boolean; alphaCutoff: number; ground: (GroundLayerParams) | null; measure: (MeasureLayerParams) | null; detail?: DetailLayer; emissive?: [number, number, number]; emissiveIntensity?: number; sheen?: PbrSheen; rim?: [number, number, number]; blend?: 'opaque' | 'alpha'; opacity?: number; depthOffset?: number; sway?: SurfaceSway; uvScroll?: [number, number]; swing?: true; };
576
582
  export interface GradeParamsInput { exposure?: number | undefined; gain?: number | undefined; shoulder?: number | undefined; saturation?: number | undefined; shadowTint?: [number, number, number] | undefined; lightTint?: [number, number, number] | undefined; split?: [number, number] | undefined; contrast?: number | undefined; lookSaturation?: number | undefined; }
577
583
  export interface GradeParams { exposure: number; gain: number; shoulder: number; saturation: number; shadowTint: [number, number, number]; lightTint: [number, number, number]; split: [number, number]; contrast: number; lookSaturation: number; }
578
584
  export interface PainterlyLookParamsInput { shade?: [number, number, number] | undefined; rim?: [number, number, number] | undefined; warm?: number | undefined; floor?: number | undefined; wet?: number | undefined; wind?: { direction: [number, number]; strength: number; } | undefined; grade?: (GradeParamsInput) | null | undefined; }
@@ -97,9 +97,10 @@ export const TextureSamplersSchema: v.GenericSchema<TextureSamplersInput, Textur
97
97
  wrap: v.exactOptional(v.picklist(['repeat', 'clamp', 'mirror'])), anisotropy: v.exactOptional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(16))),
98
98
  filter: v.exactOptional(v.picklist(['linear', 'nearest'])), mips: v.exactOptional(v.picklist(['file', 'gpu'])),
99
99
  })), v.check((rows) => Object.keys(rows).length <= 256, 'bounded texture samplers'));
100
- /** Each sampler row names a texture of the look's material catalogue (a graph file's are its row's dependencies). */
101
- export function textureSamplerRules(look: Pick<Shardfile['look'], 'materials' | 'samplers'>, files: readonly { readonly hash: string; readonly dependencies: readonly string[] }[] = []): string[] {
102
- const rows = new Map(files.map((file) => [file.hash, file])), refs = new Set(materialTextureRefs(look.materials));
100
+ /** Each sampler row names a texture of the look's material catalogue (a graph file's are its row's dependencies) or of a skin. */
101
+ export function textureSamplerRules(look: Pick<Shardfile['look'], 'materials' | 'samplers'>, files: readonly { readonly hash: string; readonly dependencies: readonly string[] }[] = [], skinTextures: readonly string[] = []): string[] {
102
+ // OF27b: a skin's material textures (`skinLookTextureRefs`) take a sampler too (the hull book's repeat, anisotropy 4)
103
+ const rows = new Map(files.map((file) => [file.hash, file])), refs = new Set([...materialTextureRefs(look.materials), ...skinTextures]);
103
104
  for (const material of Object.values(look.materials)) if (material.family === 'graph' && 'file' in material) for (const ref of rows.get(material.file)?.dependencies ?? []) refs.add(ref);
104
105
  return Object.keys(look.samplers ?? {}).flatMap((ref) => (refs.has(ref) ? [] : [`samplers ${ref}: not a texture of the look's material catalogue`]));
105
106
  }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * A PBR surface's fur (meta ONE-FORMAT OF27b, the hull-book look as a skin): the velvet sheen and the backlit rim that
3
+ * a rigged hull's coat drew with (engine `AnimalFactory`'s hull material and its fur rim), so a `platform.skin` look
4
+ * draws as the hull book did.
5
+ *
6
+ * - `sheen`: three's `MeshPhysicalMaterial` sheen, `amount` (0..1) of `colour` (linear, a light term) at `roughness`.
7
+ * - `rim`: the backlit Fresnel rim's colour (linear, HDR allowed): strongest looking toward the sun, fading past 10 m.
8
+ *
9
+ * Absent: none, as before (no default is filled, so older shard files keep their bytes). A skin variant may wear its
10
+ * own sheen and rim with its coat (`skin-variants.ts`). Plain data and checks, no three.js.
11
+ */
12
+ import {
13
+ exactOptional,
14
+ finite,
15
+ maxValue,
16
+ minValue,
17
+ number,
18
+ pipe,
19
+ strictObject,
20
+ tuple,
21
+ } from 'valibot'
22
+
23
+ import type { ExactOptionalSchema, GenericSchema } from 'valibot'
24
+
25
+ type Rgb = [number, number, number]
26
+ interface PbrSheen {
27
+ amount: number
28
+ colour: Rgb
29
+ roughness: number
30
+ }
31
+
32
+ const NONE = 0
33
+ const FULL = 1
34
+ const LIGHT_MAX = 16
35
+
36
+ const real = pipe(number(), finite())
37
+ const unit = pipe(real, minValue(NONE), maxValue(FULL))
38
+ const light = pipe(real, minValue(NONE), maxValue(LIGHT_MAX))
39
+ const linear: GenericSchema<Rgb, Rgb> = tuple([light, light, light])
40
+ const PbrSheenSchema: GenericSchema<PbrSheen, PbrSheen> = strictObject({
41
+ amount: unit,
42
+ colour: linear,
43
+ roughness: unit,
44
+ })
45
+ /** The PBR family's optional `sheen` key. */
46
+ const pbrSheen: ExactOptionalSchema<
47
+ GenericSchema<PbrSheen, PbrSheen>,
48
+ undefined
49
+ > = exactOptional(PbrSheenSchema)
50
+ /** The PBR family's optional `rim` key. */
51
+ const pbrRim: ExactOptionalSchema<
52
+ GenericSchema<Rgb, Rgb>,
53
+ undefined
54
+ > = exactOptional(linear)
55
+
56
+ export { PbrSheenSchema, pbrRim, pbrSheen, type PbrSheen }
@@ -20,6 +20,9 @@ const positive = v.pipe(finite, v.minValue(0.000001), v.maxValue(10000000));
20
20
  const nonnegative = v.pipe(finite, v.minValue(0), v.maxValue(10000000));
21
21
  const unit = v.pipe(finite, v.minValue(0), v.maxValue(1));
22
22
  const dimension = v.pipe(positive, v.maxValue(20));
23
+ /** A flyer's bake has no legs (OF11a): legs are nonnegative, the body stays positive. */
24
+ const NO_LEGS = 0;
25
+ const legs = v.union([v.literal(NO_LEGS), dimension]);
23
26
  const duration = v.pipe(positive, v.maxValue(86400));
24
27
  const ordered = v.pipe(v.tuple([positive, positive]), v.check(([a, b]) => a <= b, 'ordered range'));
25
28
  const shape = v.variant('kind', [
@@ -40,7 +43,7 @@ const day = v.strictObject({ id, units: v.literal('hour'), start: hour,
40
43
  sun: v.strictObject({ maxElevation: v.pipe(finite, v.minValue(0), v.maxValue(90)), azimuthOffset: v.pipe(finite, v.minValue(-180), v.maxValue(180)) }),
41
44
  fixed: v.strictObject({ midday: hour, golden: hour, sunset: hour, night: hour }), presets: v.strictObject({ dawn: hour, noon: hour, dusk: hour, night: hour }) });
42
45
  const mods = v.strictObject({ speed: positive, chargeDist: positive, damageTaken: positive, chargeDamage: nonnegative, relentless: v.boolean() });
43
- const dims = v.strictObject({ bodyY: dimension, bodyHalfLen: dimension, bodyRadius: dimension, headRadius: dimension, legLen: dimension,
46
+ const dims = v.strictObject({ bodyY: dimension, bodyHalfLen: dimension, bodyRadius: dimension, headRadius: dimension, legLen: legs,
44
47
  feet: v.pipe(v.array(v.tuple([finite, finite])), v.maxLength(16)), halfWidth: dimension });
45
48
  const variant = v.strictObject({ id, label: text, rarity: v.picklist(['common', 'uncommon', 'rare', 'legendary']), weight: nonnegative, scale: ordered, hp: positive, mods });
46
49
  const flight = v.strictObject({ altitude: v.pipe(finite, v.minValue(-250), v.maxValue(250)),
@@ -99,6 +102,7 @@ function rowRules(rows: ShardRows): string[] {
99
102
  if (!strikeIds.has(ability.use)) { errors.push(`Unknown creature ability: ${ability.use}`); }
100
103
  }
101
104
  if (speciesRow.body !== undefined && !lookIds.has(speciesRow.body.look)) { errors.push(`Unknown creature look: ${speciesRow.body.look}`); }
105
+ if (speciesRow.body?.swap !== undefined && !lookIds.has(speciesRow.body.swap.look)) { errors.push(`Unknown creature look: ${speciesRow.body.swap.look}`); }
102
106
  }
103
107
  for (const l of rows.looks) if (!speciesIds.has(l.species)) errors.push('look species');
104
108
  for (const c of rows.compendiums) {
@@ -1,8 +1,15 @@
1
+ /** ONE-FORMAT CC32: `lockable` [target own actor, 0|1]; `heal` [own actor, hp]; `pull` [player, metres, own actor];
2
+ * `root` [player, seconds]. Additive: a guest that never names them is unchanged. */
3
+ const CREATURE_COMMANDS = { lockable: 23, heal: 24, pull: 25, root: 26, ability: 27, actorChannel: 28 } as const;
4
+ /** ONE-FORMAT CC28: `actorChannel` [own actor, channel index 0..3 in the body's `channels`, value 0..1]. */
5
+ /** ONE-FORMAT CC59: a brain hook hears `part.broken` [actor, volume index]; `ability` [own actor, strike] replaces its
6
+ * brain's next pick. A hit event's last slot is the mask of the row's `tags` the hit carried (bit i: i-th alias). */
7
+ const CREATURE_EVENTS = { 'part.broken': 19 } as const;
1
8
  /** ABI-v1 numeric transport. These ids are shared by admission, generated bindings and the decision host. */
2
- export const SCRIPT_V1_EVENTS: Readonly<{ start: 1; tick: 2; timer: 3; 'zone.enter': 4; 'zone.leave': 5; interact: 6; hit: 7; threshold: 8; death: 9; 'move.done': 10; 'strike.done': 11; flag: 12; signal: 13; 'strike.target': 14; 'player.join': 15; 'player.leave': 16; spawned: 17; stop: 18; field: 30; cue: 31; channel: 32; }> = Object.freeze({
9
+ export const SCRIPT_V1_EVENTS: Readonly<{ start: 1; tick: 2; timer: 3; 'zone.enter': 4; 'zone.leave': 5; interact: 6; hit: 7; threshold: 8; death: 9; 'move.done': 10; 'strike.done': 11; flag: 12; signal: 13; 'strike.target': 14; 'player.join': 15; 'player.leave': 16; spawned: 17; stop: 18; field: 30; cue: 31; channel: 32; } & typeof CREATURE_EVENTS> = Object.freeze({
3
10
  start: 1, tick: 2, timer: 3, 'zone.enter': 4, 'zone.leave': 5, interact: 6, hit: 7, threshold: 8,
4
11
  death: 9, 'move.done': 10, 'strike.done': 11, flag: 12, signal: 13, 'strike.target': 14,
5
- 'player.join': 15, 'player.leave': 16, spawned: 17, stop: 18, field: 30, cue: 31, channel: 32,
12
+ 'player.join': 15, 'player.leave': 16, spawned: 17, stop: 18, ...CREATURE_EVENTS, field: 30, cue: 31, channel: 32,
6
13
  });
7
14
  /** Scalar reads; timer and random are answered by the host's own binding state. */
8
15
  export const SCRIPT_V1_READS: Readonly<{ x: 1; y: 2; z: 3; yaw: 4; hpShare: 5; alive: 6; field: 7; distance: 8; nearestPlayer: 9; flag: 10; timerLeft: 11; random: 12; actorInZone: 13; playersInZone: 14; moving: 15; strikeState: 16; playerFlag: 17; spawnGroupAlive: 18; bearing: 19; bodyX: 20; bodyY: 21; bodyZ: 22; bodyAlive: 23; bodyYaw: 24; bodyVisible: 25; playerIntent: 26; }> = Object.freeze({
@@ -14,11 +21,11 @@ export const SCRIPT_V1_READS: Readonly<{ x: 1; y: 2; z: 3; yaw: 4; hpShare: 5; a
14
21
  /** Bounded list queries. Ground/navigation keep the existing physics query semantics. */
15
22
  export const SCRIPT_V1_LISTS: Readonly<{ actorsInZone: 1; playersWithin: 2; groundHeight: 3; nearestWalkable: 4; path: 5; radial: 6; declaredFloor: 7; }> = Object.freeze({ actorsInZone: 1, playersWithin: 2, groundHeight: 3, nearestWalkable: 4, path: 5, radial: 6, declaredFloor: 7 });
16
23
  /** Command ids; view commands occupy a disjoint range and may not run in a simulation binding. */
17
- export const SCRIPT_V1_COMMANDS: Readonly<{ move: 1; strike: 2; stop: 3; field: 4; spawn: 5; despawn: 6; flag: 7; timer: 8; signal: 9; grant: 10; reward: 11; cue: 12; channel: 13; impulse: 14; encounter: 15; weather: 16; 'body.spawn': 17; 'body.teleport': 18; 'collider.enabled': 19; 'body.place': 20; 'body.visible': 21; 'body.retire': 22; 'view.channel': 100; 'view.clip': 101; 'view.vfx': 102; 'view.sound': 103; 'view.visible': 104; 'view.field': 105; }> = Object.freeze({
24
+ export const SCRIPT_V1_COMMANDS: Readonly<{ move: 1; strike: 2; stop: 3; field: 4; spawn: 5; despawn: 6; flag: 7; timer: 8; signal: 9; grant: 10; reward: 11; cue: 12; channel: 13; impulse: 14; encounter: 15; weather: 16; 'body.spawn': 17; 'body.teleport': 18; 'collider.enabled': 19; 'body.place': 20; 'body.visible': 21; 'body.retire': 22; 'view.channel': 100; 'view.clip': 101; 'view.vfx': 102; 'view.sound': 103; 'view.visible': 104; 'view.field': 105; } & typeof CREATURE_COMMANDS> = Object.freeze({
18
25
  move: 1, strike: 2, stop: 3, field: 4, spawn: 5, despawn: 6, flag: 7, timer: 8,
19
26
  signal: 9, grant: 10, reward: 11, cue: 12, channel: 13, impulse: 14, encounter: 15, weather: 16,
20
27
  'body.spawn': 17, 'body.teleport': 18, 'collider.enabled': 19,
21
- 'body.place': 20, 'body.visible': 21, 'body.retire': 22,
28
+ 'body.place': 20, 'body.visible': 21, 'body.retire': 22, ...CREATURE_COMMANDS,
22
29
  'view.channel': 100, 'view.clip': 101, 'view.vfx': 102, 'view.sound': 103, 'view.visible': 104, 'view.field': 105,
23
30
  });
24
31
  export type ScriptV1EventName = keyof typeof SCRIPT_V1_EVENTS;
@@ -58,6 +58,8 @@ import { AccentSchema } from './accent.ts';
58
58
  import { MapSchema, PresentationSchema } from './presentation.ts';
59
59
  import { MigrationsSchema, migrationRules } from './migrations.ts';
60
60
  import { skinLookRules } from './skinAssets.ts';
61
+ import { skinLookTextureRefs } from './skin-textures.ts';
62
+ import { attachmentFileRules } from './creature-attachments.ts';
61
63
  import { MaterialsSchema, FamilyLooksSchema, MaterialCurvesSchema, TextureSamplersSchema, materialExists, materialTextureRefs, materialGraphRules, materialCurveRules, textureSamplerRules, graphBindingSources } from './materials.ts';
62
64
  import { PostStackSchema, postStackRules } from './postStack.ts';
63
65
  import { LookSkySchema, lookSkyRules } from './look-sky.ts';
@@ -265,7 +267,7 @@ export function shardfileRules(s: Shardfile, sections?: ReadonlyMap<string, unkn
265
267
  errors.push(...stateRules(s.state));
266
268
  if ((s.clientChannels?.length ?? 0) > 0 && !pageOwner && s.runtime?.binds?.includes('clientChannels') !== true) errors.push('native visual channels require their declared page or runtime owner');
267
269
  if (s.runtime?.binds?.includes('state') === true && (s.state.player.length > 0 || s.state.shared.some((field) => field.privacy !== 'host' && !(field.privacy === 'public' && field.type !== 'string' && (s.runtime?.spawns?.bosses.length ?? 0) > 0)))) errors.push('runtime-bound state supports host fields and retained-actor numeric fields');
268
- errors.push(...materialGraphRules(s), ...materialCurveRules(s), ...textureSamplerRules(s.look, s.files), ...postStackRules(s), ...lookSkyRules(s.look.sky?.graph, graphBindingSources(s)));
270
+ errors.push(...materialGraphRules(s), ...materialCurveRules(s), ...textureSamplerRules(s.look, s.files, skinLookTextureRefs(s)), ...postStackRules(s), ...lookSkyRules(s.look.sky?.graph, graphBindingSources(s)));
269
271
  const materialRefs = materialTextureRefs(s.look.materials), libraryClosure = new Set<string>();
270
272
  const libraryPending = [...s.library];
271
273
  while (libraryPending.length > 0) {
@@ -322,7 +324,7 @@ export function shardfileRules(s: Shardfile, sections?: ReadonlyMap<string, unkn
322
324
  if (s.items.rows.some((row) => row.kind === 'tool' && row.action === null) && s.runtime?.binds?.includes('items') !== true) errors.push('native tools require runtime.binds items');
323
325
  if (s.modes !== undefined && (s.modes.traverse.some(row => row.kind !== 'ladder') || (s.modes.ride?.length ?? 0) > 0 || (s.modes.grapple?.length ?? 0) > 0) && !pageOwner && s.runtime?.binds?.includes('modes') !== true) errors.push('traverse modes require their declared page or runtime player phase');
324
326
  if (s.runtime !== null && s.modes?.traverse.some(row => row.kind === 'ladder')) errors.push('ladder traversal requires the data-only player owner');
325
- errors.push(...skinLookRules(s));
327
+ errors.push(...skinLookRules(s), ...attachmentFileRules({ species: s.rows.species, files: s.files, library: s.library, materials: s.look.materials }));
326
328
  errors.push(...clientScriptRules(s));
327
329
  if (s.props !== null) {
328
330
  try { validatePropsReferences(s.props, s); } catch { errors.push('declared prop references'); }
@@ -0,0 +1,53 @@
1
+ // Validator output rows retain the format's mutable public data types.
2
+ /* oxlint-disable typescript/prefer-readonly-parameter-types */
3
+ import { skinLookParameters } from './skin-file.ts'
4
+ /**
5
+ * The textures a shard's skin looks draw (ONE-FORMAT OF27b): each skin, variant and phone skin file's dependencies after
6
+ * its GLB, so a texture sampler row may name them as it names the look's material catalogue textures.
7
+ */
8
+ import { SKIN_LOOK_RECIPE } from './skins.ts'
9
+
10
+ import type { ShardRows } from './rows.ts'
11
+ import type { Shardfile } from './shardSchema.ts'
12
+
13
+ type Source = Readonly<Pick<Shardfile, 'rows' | 'files'>>
14
+ type Look = Readonly<ShardRows['looks'][number]>
15
+ type Files = ReadonlyMap<string, Readonly<Shardfile['files'][number]>>
16
+ /** A skin file's dependencies after its GLB. */
17
+ const AFTER_GLB = 1
18
+
19
+ /** The skin files a skin look names: its skin, its variant table's skins and its phone skin. */
20
+ function lookSkinFiles(look: Look, files: Files): readonly string[] {
21
+ if (look.recipe !== SKIN_LOOK_RECIPE) {
22
+ return []
23
+ }
24
+ try {
25
+ const { skin, variants, phone } = skinLookParameters(look)
26
+ const table =
27
+ variants === undefined ? [] : (files.get(variants)?.dependencies ?? [])
28
+ return [skin, ...table, ...(phone === undefined ? [] : [phone])]
29
+ } catch {
30
+ return []
31
+ }
32
+ }
33
+
34
+ /** Every texture a skin look of `source` names, once each. */
35
+ function skinLookTextureRefs(source: Source): string[] {
36
+ const files: Files = new Map(
37
+ source.files.map(
38
+ (
39
+ file: Readonly<Shardfile['files'][number]>,
40
+ ): [string, Readonly<Shardfile['files'][number]>] => [file.hash, file],
41
+ ),
42
+ )
43
+ const textures = (hash: string): readonly string[] =>
44
+ files.get(hash)?.dependencies.slice(AFTER_GLB) ?? []
45
+ const refs = source.rows.looks.flatMap((look: Look): readonly string[] =>
46
+ lookSkinFiles(look, files).flatMap((hash: string): readonly string[] =>
47
+ textures(hash),
48
+ ),
49
+ )
50
+ return [...new Set(refs)]
51
+ }
52
+
53
+ export { skinLookTextureRefs }
@@ -4,6 +4,7 @@
4
4
  /* oxlint-disable unicorn/no-array-sort */
5
5
  import { parse } from 'valibot'
6
6
 
7
+ import { MaterialsSchema, materialTextureRefs } from './materials.ts'
7
8
  import { parseSkinFile, skinLookParameters } from './skin-file.ts'
8
9
  import { SkinVariantsSchema } from './skins.ts'
9
10
  import { validationSourceBytes } from './validationReceipt.ts'
@@ -26,7 +27,32 @@ interface SkinLookFiles {
26
27
  type Source = Pick<Shardfile, 'rows' | 'files'>
27
28
  type Look = ShardRows['looks'][number]
28
29
  const FIRST = 0
29
- const SINGLE = 1
30
+ const REST = 1
31
+ /** A coat: what a variant or phone skin may wear of its own (OF27b), its maps (a painterly `map`), its fur's sheen and rim, and its glow. */
32
+ const COAT: ReadonlySet<string> = new Set([
33
+ 'map',
34
+ 'maps',
35
+ 'sheen',
36
+ 'rim',
37
+ 'emissive',
38
+ 'emissiveIntensity',
39
+ ])
40
+
41
+ /** A skin file's exact dependencies: its GLB, then its material's textures, sorted and once each (OF27b). */
42
+ function skinFileDependencies(row: SkinRow, binding: SkinBinding): string[] {
43
+ const textures = materialTextureRefs(
44
+ parse(MaterialsSchema, { skin: binding.material }),
45
+ )
46
+ return [row.file, ...[...new Set(textures)].sort()]
47
+ }
48
+
49
+ function sharedMaterial(
50
+ material: Readonly<Record<string, unknown>>,
51
+ ): Record<string, unknown> {
52
+ return Object.fromEntries(
53
+ Object.entries(material).filter(([key]): boolean => !COAT.has(key)),
54
+ )
55
+ }
30
56
 
31
57
  function skinContract({ row, binding }: ResolvedSkinFile): string {
32
58
  return new TextDecoder().decode(
@@ -36,7 +62,7 @@ function skinContract({ row, binding }: ResolvedSkinFile): string {
36
62
  joints: [...(row.rig.joints[FIRST] ?? [])].sort(),
37
63
  clips: [...row.rig.clips].sort(),
38
64
  sockets: [...row.rig.sockets].sort(),
39
- material: binding.material,
65
+ material: sharedMaterial(binding.material),
40
66
  materials: binding.materials ?? {},
41
67
  }),
42
68
  )
@@ -53,10 +79,14 @@ function readSkinFile(
53
79
  throw new Error('skin file missing')
54
80
  }
55
81
  const skin = { hash, ...parseSkinFile(bytes) }
82
+ const expected = skinFileDependencies(skin.row, skin.binding)
83
+ const texture = (ref: string): boolean =>
84
+ ref.startsWith('commons:') || files.get(ref)?.kind === 'ktx2'
56
85
  if (
57
- file.dependencies.length !== SINGLE ||
58
- file.dependencies[FIRST] !== skin.row.file ||
59
- files.get(skin.row.file)?.kind !== 'glb'
86
+ file.dependencies.length !== expected.length ||
87
+ file.dependencies.some((ref, index): boolean => ref !== expected[index]) ||
88
+ files.get(skin.row.file)?.kind !== 'glb' ||
89
+ !expected.slice(REST).every((ref): boolean => texture(ref))
60
90
  ) {
61
91
  throw new Error('skin rig dependency mismatch')
62
92
  }
@@ -232,5 +262,5 @@ function lookSkins(resolved: SkinLookFiles): ResolvedSkinFile[] {
232
262
  ]
233
263
  }
234
264
 
235
- export { lookSkins, resolveSkinLookFiles }
265
+ export { lookSkins, resolveSkinLookFiles, skinFileDependencies }
236
266
  export type { ResolvedSkinFile, SkinLookFiles }
@@ -36,8 +36,11 @@ function skinLookRules(source: Pick<Shardfile, 'rows' | 'files' | 'library'>): s
36
36
  for (const row of source.rows.looks) {
37
37
  if (row.recipe !== SKIN_LOOK_RECIPE) { if (row.animation.recipe === SKIN_CLIPS_RECIPE) {errors.push('skin clips without a skin look');} continue; }
38
38
  let parameters: SkinLookParameters; try { parameters = skinLookParameters(row); } catch { errors.push('skin look parameters'); continue; }
39
- const { skin, variants, phone } = parameters, file = files.get(skin), glb = file?.dependencies.length === 1 ? files.get(file.dependencies[0] ?? '') : undefined;
40
- if (file?.kind !== 'json' || glb?.kind !== 'glb' || !source.library.includes(skin)) {errors.push('skin look file references');}
39
+ const { skin, variants, phone } = parameters, file = files.get(skin), glb = files.get(file?.dependencies[0] ?? '');
40
+ // OF27b: a skin file depends on its GLB, then its material's textures (KTX2 files or commons)
41
+ const textures = file?.dependencies.slice(1) ?? [];
42
+ if (file?.kind !== 'json' || glb?.kind !== 'glb' || !source.library.includes(skin)
43
+ || textures.some((ref): boolean => !ref.startsWith('commons:') && files.get(ref)?.kind !== 'ktx2')) {errors.push('skin look file references');}
41
44
  if (!libraryJson(source.library, kinds, variants)) {errors.push('skin variant table references');}
42
45
  if (!libraryJson(source.library, kinds, phone)) {errors.push('skin phone file references');}
43
46
  }
@@ -104,5 +107,6 @@ function validateSkinAssets(source: Pick<Shardfile, 'rows' | 'files'> & { readon
104
107
  }
105
108
 
106
109
  export { parseSkinFile, skinLookParameters } from './skin-file.ts';
107
- export { resolveSkinLookFiles } from './skin-variants.ts';
110
+ export { resolveSkinLookFiles, skinFileDependencies } from './skin-variants.ts';
108
111
  export { skinLookRules, validateSkinAssets };
112
+ export { skinLookTextureRefs } from './skin-textures.ts';