# BattleSpades Weapon Package (BSWP) — format 1.0.0

Open, versioned package format for custom weapons and cosmetics in Ace of
Spades: Battle Builder revival clients (BattleSpades). One package holds the
voxel models, a skeleton of attachment points (hand grips, muzzle, sights,
ejection port, sockets), first- and third-person hold transforms, the sight or
scope, muzzle flash, keyframe animations, timed sounds, colours and previews.

| | |
|---|---|
| Format id | `battlespades.weapon-package` |
| Current version | `1.0.0` (semver; this document) |
| File extension | `.bswp` (ZIP) — or an unpacked folder with the same layout |
| Media type | `application/vnd.battlespades.weapon-package+zip` |
| JSON Schema | [`/schemas/bswp-1.schema.json`](https://www.aosplay.net/schemas/bswp-1.schema.json) (draft-07), source `src/lib/creator/package/manifest.schema.json` |
| Reference implementation | `src/lib/creator/package/` (TypeScript: types, validator, migrations, pack/unpack, audio inspection, stock defaults) |
| Public page | `/creators/package-format` |
| Licence of this spec | CC-BY-4.0 — anyone may implement readers and writers |

The key words MUST, SHOULD and MAY are used as in RFC 2119.

## 1. Container

```
my-rifle.bswp  (ZIP, or a folder)
├── manifest.json          required, UTF-8 JSON, ≤ 256 KB
├── models/body.kv6        KV6 voxel parts
├── models/scope.kv6
├── sounds/fire-1.ogg      Ogg Vorbis/Opus or PCM/float WAV
├── sounds/bolt-rack.ogg
├── textures/scope-overlay.png
└── previews/thumbnail.png
```

* `manifest.json` is at the root. Readers MUST also accept a ZIP whose single
  top-level folder contains `manifest.json` (a zipped package folder).
* Every payload file MUST be listed in `manifest.files` with its `sha256`,
  `bytes` and `media_type`. Readers MUST reject files whose size or hash does
  not match and MUST ignore unlisted archive entries (with a warning).
* Paths are lowercase, relative, `[a-z0-9_./-]`, never contain `..`, ≤ 160
  characters. Allowed types: `.kv6` `model/x-kv6`, `.ogg` `audio/ogg`, `.wav`
  `audio/wav`, `.png` `image/png`, `.webp` `image/webp`, `.json`, `.txt`.
* Readers MUST check uncompressed sizes from the ZIP central directory before
  inflating (zip-bomb guard). Writers SHOULD store `manifest.json` first, use
  fixed timestamps and store (not deflate) Ogg/PNG/WebP so exports are
  byte-reproducible (the reference writer is deterministic).
* Nothing in a package is executable. Scripts are not part of the format.

### Limits

| Item | Reader limit | Community submission limit |
|---|---|---|
| Package | 16 MB | 3 MB (fits Vercel's ~4.5 MB request body as base64) |
| Files | 96 | — |
| Model parts / KV6 part size | 16 / 2 MB, ≤ 256 voxels per axis, ≤ 60,000 voxels | same |
| Attachment points | 64 | — |
| Sound samples | 48, ≤ 1 MB, ≤ 10 s (≤ 20 s when `loop: true`) | 24, ≤ 512 KB each, ≤ 2 MB total |
| Clips / tracks per clip / keys per track / cues per clip | 48 / 24 / 256 / 64 | — |
| Images | 1 MB, ≤ 2048 px | — |

## 2. Coordinate conventions

* **KV6 space** — voxel coordinates of one model part: X across, **Y forward
  (toward the muzzle)**, Z down; the same axes as `models.load_model` and the
  native client. Integer values are voxel centres; `.5` values are faces.
  Skeleton points and `authored_offset` use KV6 space.
* **View space** — the retail tool space of `Tool.initial_position` and
  `arms_position_offset` (world units, before `Character.draw_fps`' 180° yaw
  and `(-0.4, -0.55, 0.9)` offset). Hold transforms and animation position
  keys use view space; rotations are degrees `[pitch(X), yaw(Y), roll(Z)]`.
* Display mapping is `(x, y, z)_kv6 → (x, -z, y)_GL`, as in
  `aoslib.draw.DisplayList.draw`.

## 3. Manifest

```jsonc
{
  "$schema": "https://www.aosplay.net/schemas/bswp-1.schema.json",
  "format": "battlespades.weapon-package",
  "format_version": "1.0.0",
  "kind": "weapon",                         // or "cosmetic"
  "id": "kiril.copperhead-rifle",           // [a-z0-9._-]{3,100}; namespaced by author
  "version": "1.2.0",                       // the package's own semver
  "name": "Copperhead Rifle",
  "description": "…",
  "authors": [{ "name": "Kiril", "url": "https://…", "role": "creator" }],
  "license": "CC-BY-4.0",                   // SPDX id or a short permission note
  "credits": [{ "name": "Ace of Spades (original game)", "role": "original model and defaults" }],
  "target": { "tool_id": 60, "tool": "ASSAULT_RIFLE", "base_template": "assaultrifle" },
  "compatibility": { "client": ">=0.2.0", "protocol": 168, "requires": ["sounds.custom", "skeleton.points"], "fallback": "retail" },
  "files": [{ "path": "models/body.kv6", "sha256": "…", "bytes": 4872, "media_type": "model/x-kv6" }],
  "models": [ … ], "skeleton": { … }, "sight": { … }, "hold": { … },
  "muzzle_flash": { … }, "animations": [ … ], "sounds": [ … ],
  "colors": { … }, "previews": [ … ],
  "extensions": { "myvendor.recoil": { … } }
}
```

* **`target`** — weapons MUST give the Protocol 168 `tool_id` (0–64) whose
  visuals and audio they replace; damage, spread, ammo, range, hitboxes and
  timing ALWAYS stay server-authoritative (packages are cosmetic). Cosmetics
  MUST give a `slot` (`character.<part>`, `tombstone`, `hat`, `back`, …).
  `base_template` names the Skin Studio template the package derives from.
* **`compatibility.requires`** lists capabilities without which the package
  cannot render correctly: `models.multipart`, `models.custom_geometry`,
  `skeleton.points`, `sight.iron`, `sight.overlay`, `animation.keyframes`,
  `sounds.custom`, `sounds.timeline`, `muzzle_flash.custom`, `colors.team`.
  A reader lacking one MUST use `fallback` (`retail` = stock visuals/audio for
  that tool, `hide` = do not equip) instead of rendering partially.

### 3.1 `models[]`

```json
{ "id": "body", "file": "models/body.kv6", "role": "body", "views": ["first_person", "third_person"],
  "authored_offset": { "first_person": [0, 0, 0], "third_person": [10, -26, 4] }, "team_color": true }
{ "id": "sight", "ref": "retail:kv6/assaultRifle_sight.kv6", "role": "sight", "views": ["sight"] }
{ "id": "scope", "file": "models/scope.kv6", "role": "scope", "views": ["first_person", "third_person"], "parent": "body", "socket": "socket.scope" }
```

* Exactly one of `file` (inside the package) or `ref`. Refs point at assets a
  client already has: `retail:<asset path>` (original game) or
  `cosmetics:<stem>` (installed cosmetics). Refs let stock packages reference
  original assets without redistributing them.
* The first part is the primary body. Parts are drawn in array order; for
  multi-part tools (minigun body + barrel, rocket turret) the index matches
  the retail `model`/`view_model` list.
* `role`: `body barrel magazine stock grip sight scope pin casing tracer
  muzzle_flash attachment accessory hand` (extensible). `views`: `first_person`,
  `third_person`, `sight` (drawn by `Character.draw_sight` while aiming),
  `world` (casings, tracers).
* `authored_offset` is the `models.load_model` offset per view (KV6 units).
* `socket` attaches the part's pivot to a socket point of `parent`.
* `team_color: true` — the part uses the reserved team-material colours
  `#000000 #400040 #800080 #c000c0`, recoloured to the owner's team
  (×0.7/×1/×1.3). Other parts MUST NOT contain them.

### 3.2 `skeleton` — bones and attachment points

```json
{ "space": "kv6", "points": [
  { "id": "grip.right", "type": "hand_grip", "hand": "right", "part": "body", "position": [2, 15, 9.5], "rotation": [0, 0, 0] },
  { "id": "grip.left",  "type": "hand_grip", "hand": "left",  "part": "body", "position": [2, 32, 7.5] },
  { "id": "muzzle", "type": "muzzle", "part": "body", "position": [2, 51.5, 5] },
  { "id": "sight.rear", "type": "sight", "part": "body", "position": [2, 11, 2.5] },
  { "id": "sight.front", "type": "sight", "part": "body", "position": [2, 43, 2.5] },
  { "id": "eject", "type": "ejection", "part": "body", "position": [3.5, 23, 7.25] },
  { "id": "socket.scope", "type": "socket", "part": "body", "position": [2, 27, 2.5], "accepts": ["scope"] }
] }
```

Well-known ids: `grip.right` (trigger hand), `grip.left` (support hand),
`muzzle`, `sight.rear`, `sight.front`, `eject`, `socket.scope`,
`socket.barrel`, `socket.grip`, `socket.magazine`. Other ids and the `custom`
type are allowed. `source` records provenance: `authored`, `retail`, or
`estimated` (a geometric guess the creator has not confirmed).

Runtimes use hand grips to place first-/third-person hands (IK targets),
`muzzle` for the flash/tracer origin when `muzzle_flash.anchor` is
`muzzle_point`, `eject` for casings, and sockets for attachments.

### 3.3 `sight`

* `mode: "retail"` — keep the base tool's optic: `sight_position` (retail
  `Weapon.sight_pos`), `sight_part` (the retail sight KV6), `pin_scale`,
  `zoom_factor`, `zoom_sensitivity_factor`.
* `mode: "iron"` — aim along the `sight.rear` → `sight.front` line; the eye
  sits `eye_distance` (0.2–4) behind the rear sight. The front sight MUST be
  ≥ 1 voxel ahead (+Y). This is the same frame as the client's
  `sight_tag_position` used by `weapon-presentation.json` today.
* `mode: "scope"` — zoom plus an optional `overlay` (`file` PNG/WebP with a
  transparent centre, `fit` `contain|cover`, `tint`, `hide_view_model`).

### 3.4 `hold` — first- and third-person transforms

```json
"hold": {
  "first_person": { "initial_position": [0, 0.2, 0], "initial_orientation": [0, 0, 0],
                    "arms_position_offset": [-0.1, -0.08, -0.1], "view_model_size": 0.035,
                    "parts": [{ "part": "barrel", "position": [0, -0.3, 1.1], "orientation": [0, 0, 0] }] },
  "third_person": { "model_size": 0.04, "initial_position": [0, 0, 0], "initial_orientation": [0, 0, 0] }
}
```

Exactly the retail `Tool.__init__` values: `initial_position`/`initial_orientation`
(main character for first person, remote character for third person),
`arms_position_offset`, `view_model_size` (`Character.view_weapon.size`) and
`model_size`. `parts` overrides the pose of individual parts (minigun barrel,
rocket turret). The client composes these exactly as `Character.draw_fps` /
`Character.draw` do.

### 3.5 `muzzle_flash`

`enabled`, `view_offset` / `zoomed_view_offset` (null = draw at the eye, as the
retail snipers do) / `third_person_offset`, `scale`, `third_person_scale`,
`duration` (s), optional `color`, optional flash model `part`, and `anchor`
(`retail_offset` or `muzzle_point`).

### 3.6 `animations[]` — clips, keyframes and timed cues

```json
{ "id": "reload", "event": "reload", "duration": 0.9, "base": "retail", "loop": false,
  "tracks": [{ "target": "weapon", "property": "rotation",
               "keys": [{ "t": 0, "value": [0, 0, 0] }, { "t": 0.3, "value": [-25, 0, 10], "ease": "ease_out" }, { "t": 0.9, "value": [0, 0, 0] }] }],
  "cues": [{ "t": 0,    "sounds": ["mag-out"] },
           { "t": 0.45, "sounds": ["mag-in-1", "mag-in-2"], "pick": "random", "gain": 0.9, "pitch": [-0.5, 0.5] },
           { "t": 0.6,  "emit": "custom.mag-drop" }] }
```

* A clip plays when its `event` fires. Events: `pullout` (tool raised; retail
  0.5 s, `switch` sound), `fire` (each accepted shot), `fire_loop` (sustained
  automatic fire, `loop: true`), `fire_tail`, `dry_fire`, `reload` (one reload
  cycle — per shell for `clip_reload` weapons), `reload_end` (final cycle
  completed), `zoom_in`, `zoom_out`, `melee`, `melee_hit_block`,
  `melee_hit_player`, `throw_pin`, `throw_release`, `spin_loop`,
  `tool_loop_start`, `tool_loop`, `tool_loop_stop`, `tool_extra`, `inspect`,
  and `custom.*` (fired by a cue's `emit` or future scripting).
* The clip timeline is presentation only: gameplay timing (fire interval,
  reload time) stays server-authoritative. A clip longer than the gameplay
  action is cut off when the next action starts.
* `tracks` are **additive** to the hold pose. `target` is `weapon`, `arms` or
  `part:<id>`; `property` `position` (view units) or `rotation` (degrees).
  Keys have strictly increasing `t` within `[0, duration]`; `ease`
  (`linear step ease_in ease_out ease_in_out`) shapes the segment leaving the
  key. `base: "retail"` keeps the stock procedural motion (`AnimWeaponShoot`,
  `AnimUseSpade`, …) underneath; `base: "none"` replaces it.
* `cues` fire at `t` seconds after the event: `sounds` are variant sample ids
  chosen by `pick` (`cycle` default, or `random`); `gain` 0–2 relative to the
  stock cue level (retail `Tool.play_sound` volume 0.5 = gain 1); `pitch`
  `[min, max]` random semitones (retail `Character.play_sound` slots 3/4);
  `positional` (default true; the local player hears first-person cues
  head-relative, as retail does); `emit` a presentation event
  (`muzzle_flash`, `eject_casing`, `tracer`, `camera_kick`, `custom.*`).

### 3.7 `sounds[]`

```json
{ "id": "bolt-rack", "file": "sounds/bolt-rack.ogg", "duration_ms": 420, "sample_rate": 44100, "channels": 1,
  "peak_dbfs": -2.1, "rms_dbfs": -19.4, "suggested_gain": 0.98, "credit": "recorded by …" }
{ "id": "shotgunshoot", "ref": "retail:shotgunshoot" }
```

* Exactly one of `file` or `ref`. Custom audio MUST be Ogg (Vorbis/Opus) or
  PCM/float WAV, 8–96 kHz, mono or stereo. **Mono is strongly recommended**:
  OpenAL only spatialises mono buffers.
* Metadata fields are informational and are re-measured by tools. The studio's
  loudness hint targets ≈ −18 dBFS RMS with peaks ≤ −1 dBFS.

### 3.8 `colors`, `previews`, `extensions`

`colors.team_placeholders` documents the reserved team materials; `palette`
lists up to 64 `#rrggbb` colours. `previews` are PNG/WebP images of kind
`thumbnail`, `first_person`, `third_person` or `turntable`. `extensions` holds
namespaced vendor data (`"vendor.feature": {…}`).

## 4. Forward compatibility and versioning

1. `format_version` is semver. A reader for 1.y MUST accept any 1.x manifest.
   A newer minor loads with a warning; features it does not know are ignored.
2. Unknown properties — at the top level, inside any object, and in
   `extensions` — MUST be preserved verbatim on load/save. The reference
   implementation never strips fields.
3. Extensible vocabularies (part roles, views, point types, events, emits,
   eases, capabilities) are open: an unknown value is a warning and only that
   entry is skipped. Closed enums (`kind`, `sight.mode`, `property`,
   `fallback`) are errors.
4. A different major version MUST be refused with a clear message, never
   guessed at. Breaking changes require a new major version and a migration.
5. Upgrades are ordered, pure, recorded steps (`MIGRATION_STEPS` in
   `migrate.ts`); a loader reports which ran. Steps are append-only.
6. Packages carry their own `version`; clients SHOULD prefer the highest
   package version for an `id` and MUST NOT mix files between versions.

### Legacy inputs

* **`weapon-presentation.json` (schema_version 1)** — the client's current
  sight/sound tuning file (`assets/client/cosmetics`) upgrades with
  `migrateLegacyPresentation()`: sight tags become `sight.rear`/`sight.front`
  points with `mode: "iron"`, `fire_samples` a `fire` clip cue, `cues.reload`
  a `reload` clip, `cues.raise` a `pullout` clip; the original row is kept
  under `extensions["aosrevival.legacy-presentation"]`.
* **Bare KV6 / Skin Studio drafts** — become a package around the stock
  manifest of their template (`manifestForTemplate`).

## 5. Stock defaults (reproducing retail)

`stockWeaponManifest(tool_id)` builds a package for every retail tool from
`src/lib/creator/package/retail-tools.json`, which
`scripts/generate-retail-weapon-defaults.mjs` generates from the native client:

* `weapon_catalog.generated.cpp` (parsed mechanically): model parts and
  `load_model` offsets, sight/pin/casing/tracer models, `shoot`/`reload`/
  `reload_done` sounds and pitch ranges, method-body cues (`empty`, loops,
  tails, melee, throw), `RetailUseTuning` (shoot interval, reload time, zoom,
  `model_size`, `view_model_size`, `sight_pos`, `pin_scale`, team colour,
  `clip_reload`).
* `retail_view_model.cpp` — `retail_tool_hold()` (initial position/orientation
  for main and remote characters, arms offset) and `retail_view_muzzle_flash()`;
  `retail_character_pose.cpp` — third-person muzzle attachments;
  `retail_inventory.hpp` — `pullout_seconds = 0.5`.

These come from the retail `aoslib/weapons/*.py` class attributes and
`character.pyd`. `runtimeView(stockWeaponManifest(id))` equals
`retailRuntimeView(id)` for every tool (tested), so exporting a stock weapon and
loading it reproduces stock behaviour. Run
`node scripts/generate-retail-weapon-defaults.mjs ../BattleSpadesClient --check`
after client catalogue changes.

## 6. Loading packages in the native client (implementation notes)

The BattleSpadesClient does not load `.bswp` yet. It already has the pieces:
`WeaponDefinition` (models, sounds), `retail_tool_hold`,
`evaluate_weapon_view_model`, `retail_view_muzzle_flash`,
`load_weapon_presentations()` / `sight_tag_position()` and the OpenAL weapon
cue groups. A loader needs to:

1. Unzip (e.g. miniz), check sizes before inflating, verify `files` SHA-256,
   parse `manifest.json` (nlohmann/json), refuse other majors, keep unknown
   fields when re-saving.
2. Resolve `retail:` refs against the asset tree and `cosmetics:` refs against
   `assets/client/cosmetics`; load `file` KV6 parts with the existing KV6
   loader, applying `authored_offset`.
3. Override per tool: `first_person_models`/`third_person_models`, sight model
   or iron-sight frame (`sight_tag_position` with `sight.rear/front`), the
   `RetailToolHold` (initial pose, per-part pose, arms offset), `view_model_size`,
   `model_size`, and the muzzle-flash tables — leaving every gameplay value
   untouched.
4. Map clips to existing hooks: `WeaponActionKind` (fire, reload_started,
   reload_completed with the final-cycle flag → `reload_end`, dry fire),
   the 0.5 s pullout, zoom toggles, melee/throw paths. Schedule cues relative
   to the event, decode Ogg into OpenAL buffers (mono → positional), apply
   `gain` × retail 0.5, random pitch `2^(semitones/12)`, and `pick`.
5. Add keyframe tracks on top of `evaluate_retail_tool_animation` (or instead
   of it when `base: "none"`), and use `grip.*` points as hand IK targets
   instead of the fixed arm anchors.
6. Replicate only the package `id`/`version`/`sha256` over the cosmetic
   channel; clients without the package or a required capability use
   `fallback`.

## 7. Community submissions and moderation

Skin Studio's Advanced mode submits packages to `POST /api/creator/submit-package`
(registered accounts, rate-limited, ≤ 3 MB). The server re-validates the
archive, every KV6, every sound header/duration and the submission limits,
diffs the body part against the original template like a plain KV6 submission,
and stores a canonical re-pack (`migrations/0017_creator_packages.sql`).
Reviewers play each custom sound in `/manage/creators` and must confirm the
audio check (no hate speech, no copyrighted music, no clipped/deafening audio,
appropriate for the event) before approval. Approved packages download from
`/api/creator/package/{id}`.
