# PETAFAB level creation guide and JSON specification

Reference for JSON level format **2**. Updated 2026-11-14. Requires PETAFAB build 984 or newer for triggers and custom gameplay settings.

This standalone reference contains authoring instructions, field semantics, limits, the complete built-in material palette, the full Spillway example, and the JSON Schema. The schema also accepts legacy format 1; use `"version": 2` for new maps documented here. JSON snippets in the reference illustrate individual fields; the **Complete Spillway example** is a whole playable level.

- [Web guide](https://sebastianaaltonen.com/petafab/modding/)
- [Download this Markdown reference](https://sebastianaaltonen.com/assets/modding/petafab-level-format.md)
- [Spillway source ZIP](https://sebastianaaltonen.com/assets/modding/spillway-source.zip)
- [Blender starter ZIP](https://sebastianaaltonen.com/assets/modding/blender-starter.zip)
- [Blender editing guide](https://sebastianaaltonen.com/assets/modding/blender/README.md)
- [Spillway level.json](https://sebastianaaltonen.com/assets/modding/spillway/level.json)
- [JSON Schema](https://sebastianaaltonen.com/assets/modding/spillway/level.schema.json)

## Create, validate and play a map

In the game, **Workshop → My Levels → New Level → Modding Guide** opens the web instructions in the Steam overlay, or in your default browser when the overlay is unavailable.

1. Extract the Spillway source ZIP into a new folder. Keep `level.json` and `preview.jpg` at the root.
2. In PETAFAB on Steam for Windows or macOS, open **Workshop → My Levels → Play Folder** and select that folder. **Play Local ZIP** can open the ZIP directly.
3. Edit `level.json` as UTF-8 JSON. Start with built-in materials so no external assets or build tools are needed. Preserve required arrays even when empty. Use the schema below for editor completion and validation; the game additionally checks references, geometry fit, texture formats and resource budgets.
4. Save your edits, then press **F5** while playing to reread the current local folder or ZIP, including textures and sky assets, and restart the map. On Mac keyboards, use **Fn + F5** if needed. For ZIPs, replace the selected archive before pressing F5. Ordinary restart uses the already-loaded map.
5. During local play, press **F8** to tune graphics and sun settings. **Save JSON** writes them to the map; wait for **SAVED LOCALLY**. After external edits, press **F5** before saving from F8. Reloading discards unsaved tuning changes.
6. Test the spawn, ammunition, headroom, gate exits, fluid containment, wave progression and victory condition. Custom runs are local and do not earn campaign progress.

If F5 encounters invalid JSON or assets, the current map keeps running and an error appears on screen. Correct the source and press F5 again. This reload shortcut applies to **Play Folder** and **Play Local ZIP** runs; it does not update the published Steam Workshop item.

To use the standalone schema in an editor, save it alongside `level.json` as `level.schema.json` and set `"$schema": "level.schema.json"`. Schema validation does not replace loading and playing the map.

## Build terrain in Blender

The [Blender starter ZIP](https://sebastianaaltonen.com/assets/modding/blender-starter.zip) includes an editable `level.blend`, matching `level.json`, an embedded and standalone Python exporter, this reference, a JSON Schema and a README with a window-cutting exercise. It has been tested with Blender 5.1.0. The scene contains ten terrain brushes and two point lights, with no enemy waves.

1. Extract the ZIP and keep `level.blend` beside `level.json`. Open the scene in Blender and work in **Object Mode**.
2. Duplicate, move and scale objects in **Brushes**. Object names such as `010 add Gate wall` and `020 cut Doorway` select the operation and numeric order. Additions need one material named after a material ID in JSON. Keep the original mesh data names when renaming objects.
3. Save the scene. In the **Scripting** workspace, select **Export Level.py** in the Text Editor and click **Run Script**, or hover over the text and press **Alt+P**. No add-on installation is needed.
4. Open the extracted folder using **Workshop → My Levels → Play Folder**. After each Blender export, press **F5** in game to reload it (on Mac keyboards, **Fn + F5** if needed).
5. Add your own `preview.jpg` under 1 MiB before publishing. The starter does not include a thumbnail.

The exporter supports unmodified cubes, spheres, upright cylinders and cones, plus point lights. Arbitrary meshes, modifiers and torus brushes are not supported by this exporter. Boxes support yaw and local-X pitch; spheres need uniform scale; cylinders and cones need equal X/Y scale. Blender Z up and +Y forward convert to game Y up and +Z forward in metres.

Every export replaces the complete `brushes` and `lights` arrays. Manual changes inside those arrays, including `disableWhenAwayFromTerrain` on a light, must be reapplied after exporting. Other JSON fields are preserved, including material declarations, player spawn, pickups, fluids, waves and saved F8 sun/render settings. The **Guides** player-start marker is only a visual reference; edit `player.position` in JSON to move the actual spawn. Add encounters and other gameplay settings in JSON using the reference below.

## Contents

- Coordinates, top-level fields and brush shapes
- Material allocation and all built-in names
- Fluids, pickups and appearance settings
- Texture channels, AO/emission packing and sky requirements
- Gates, waves, announcements and bosses
- Player and bot health and speed
- Random drop limits, trigger areas and scripted actions
- Publishing and package limits
- Complete built-in surface palette
- Complete Spillway example
- Complete JSON Schema

## Coordinates and terrain

All positions are world-space `[x,y,z]` in metres, **Y up**. Terrain spans X/Z −32…32 and Y 0…32. Custom worlds start empty. All terrain, including floors, comes from the ordered brushes. Spillway explicitly adds a concrete floor with its top at **Y = 4**; sky maps can omit it. Brush extents may cross the field boundary and are clipped. All yaw angles are degrees in [−360, 360]. Zero faces +Z, +90 faces +X. Timing is integer ticks at **120 Hz**.

Use one UTF-8 JSON object, at most 32 MiB. Names are case-sensitive. Unknown or duplicate fields are errors. Object field order is free. The required fields are `version`, `materials`, `player`, `brushes`, `fluids`, `gates`, and `waves`. Empty arrays are valid.

| Field | Contents |
|---|---|
| `version` | Integer `2`. Legacy v1 maps retain their built-in brush names and optional `textures` overrides. Optional `$schema` names a schema for your editor. |
| `player` | `position` is the **lower capsule center**, X/Z −31…31, Y 0.55…30. On a floor whose top is Y = 4, use Y = 4.55. Optional `yaw` and `pitch` default to 0. Pitch is −89…89° (positive looks up). Optional `healthMultiplier` and `speedMultiplier` default to 1; see [player and bot stats](#player-and-bot-stats). Leave standing headroom and a path to the fight. |
| `brushes` | 0–65,536 ordered operations. Each takes `op` (`add` or `subtract`), `shape`, `center`, and a declared `material` ID for additions. Cuts may omit the material. A cut only removes terrain present at that point in the list. |
| `fluids` | Initial liquid particle volumes. Build the tank or channel from brushes. Open or breached vessels spill. |
| `gates` | 0–64 named enemy entrance volumes. |
| `waves` | 0–32 regular waves in encounter order. An empty list with no boss gives free exploration. |
| `music` | Optional integer 1–3 selecting the campaign gameplay track: Construction Yard, Inside the Factory or Rooftop Airstrip. Defaults to 1. |
| `boss` | Optional final encounter. Set `type` to `barrage`, `saw` or `laser` and `position` to the boss body center in world metres. |
| `pickups` | Optional, up to 160 objects (16 per kind) with `kind` and world-center `position`. Supplies fall until supported. The player starts unarmed, so place `ammo` near the start. Normal random drops continue. |
| `dropLimits` | Optional per-kind simultaneous random-drop maximums, 0–16. Explicit values override every hero's normal random limit. Zero disables random drops only; manually placed and trigger-spawned loot remain available. |
| `triggers` | Optional, up to 1024 named area triggers or relays, each with up to 4 actions (4096 total). Action brush lists share a 512-brush budget. |
| `bots` | Optional `healthMultiplier` (0.01–100) and `speedMultiplier` (0–4), both default 1. See [player and bot stats](#player-and-bot-stats). |
| `extraWaves` | Optional, up to 32 named waves started by trigger actions, independent of main-wave progression and victory. |
| `materials` | List all map materials. Each has a unique `id` and either a built-in name or a custom texture pair. |
| `botMaterials`, `skybox`, `sun`, `render`, `lights` | Optional appearance settings, described below. Omitted settings use the Yard defaults. |

**Brush shapes.** A `box` needs `size:[width,height,depth]` (full dimensions, each 0.0625…64) and accepts optional `yaw`, `pitch`, and `rounding` (defaults 0). Positive pitch raises local +Z before yaw. Rounding is a corner radius inside the box, at most half its smallest dimension. A `sphere` needs `radius` (0.0625…32). A vertical `cylinder` needs `radius` (same range) and full `height` (0.0625…64), centered on all three axes. Optional `topRadius` (0…32, default `radius`) tapers the top. Use 0 for a cone. A `torus` takes a centerline `radius` and a circular `tubeRadius` (0.0625 m up to the centerline radius). Its axis starts along +Y. Pitch tilts it toward +Z, then yaw turns it toward +X. The importer rejects terrain above 4,194,304 brush-to-tile references. Many overlapping large brushes consume this budget fastest.

## Material budget

Every level has **32 physical SDF IDs**. Each named material chooses `builtin` (e.g. `steel`, `factory:steel` or `rooftop:steel`) or supplies `color` and `normal` DDS paths. IDs use 1–32 ASCII letters, digits, underscores or hyphens. Brushes refer to these map-local IDs. Built-in aliases can share a physical ID. Custom textures normally receive the lowest available ID after reserving all explicit bindings, referenced built-ins and gameplay IDs.

All accepted built-in names (case-sensitive):

`concrete`, `steel`, `teal`, `hazard`, `corpse`, `pavement`, `ivory`, `trim`, `robot_joint`, `robot_boss`, `robot_visor`, `robot_panel`, `robot_boss_panel`, `foam`, `foam_turquoise`, `foam_pink`, `safety`, `lamp_amber`, `lamp_red`, `rubber`, `graybox`, `bee_yellow`, `bee_black`, `bee_wing`, `porcelain`, `aluminium`, `upholstery`, `foliage`, `bark`, `display`, `lounge_fabric`, `robot_rocketeer`.

An unprefixed name selects the Yard palette. Every name also accepts `yard:`, `factory:` or `rooftop:`; for example, `factory:steel`. The prefix selects a surface palette, not an enemy model.

Four IDs remain reserved for the default surface and foam: `concrete`, `foam`, `foam_turquoise`, `foam_pink`. The wave list adds the union of the corpse materials below. Repeated bots and materials count once.

| Enemy in waves | Default corpse IDs |
|---|---|
| `constructor` (yellow Yard bot) | corpse, ivory, robot_joint, robot_visor |
| `constructor2` (blue Factory bot) | factory:corpse, factory:robot_panel, robot_joint, robot_visor |
| `runner` | bee_yellow (green runner armor), ivory, robot_joint, robot_visor |
| `rocketeer` | robot_rocketeer, robot_joint, robot_visor, aluminium, porcelain, safety |
| `shock_trooper` | robot_rocketeer, robot_joint, robot_visor, aluminium, porcelain, bee_yellow (copper) |

**Independent terrain IDs before allocation:** 28 with no bots, 23 with constructors and runners, 19 with the yellow constructor, runner and both medium bots, or 17 when blue constructors also spawn. To share a finish intentionally, use `botMaterials.<enemy>.<original slot>` to point to a declared material. Use the original slot names `corpse` and `robot_panel` in `botMaterials.constructor2` to override its Factory finishes. Once every bot using an original ID is remapped, that reservation goes away. Optional `slot` pins a declaration to a physical slot by name, changing its appearance for all users of that slot. Referencing a reserved built-in reuses it without consuming another ID.

```json
{
  "materials": [
    {"id":"worn_steel","builtin":"steel"},
    {"id":"paint","color":"textures/paint.dds","normal":"textures/paint_normal.dds","roughness":0.45}
  ],
  "botMaterials": {"constructor":{"robot_joint":"worn_steel"},"runner":{"robot_joint":"worn_steel"}}
}
```

Run `--material-budget FILE` while authoring, even before the DDS files exist. Run `--check-level FILE` to also validate the DDS files. Both report the actual used/free count, each named material and bot surface mapped to its physical ID, and the remaining slot numbers and names. Spillway maps both bots' joints to its steel wall. It uses **11/32** (21 free); with default corpse materials it uses 12/32 (20 free). Tumblebrook uses **31/32** (1 free) with constructors, runners and rocketeers.

**Built-in materials.** An unqualified name uses the Yard palette. Prefix a name with `yard:`, `factory:` or `rooftop:` to select that campaign's complete material, including its texture layer and surface parameters. The four rows below list slots 0–31 in order. Color variants share texture layers. Yard-specific appearances include `graybox` (grate), `bark` (red cable), `upholstery` (yellow cable), and `lounge_fabric` (blue cable).

```text
concrete  steel  teal  hazard  corpse  pavement  ivory  trim
robot_joint  robot_boss  robot_visor  robot_panel  robot_boss_panel  foam  foam_turquoise  foam_pink
safety  lamp_amber  lamp_red  rubber  graybox  bee_yellow  bee_black  bee_wing
porcelain  aluminium  upholstery  foliage  bark  display  lounge_fabric  robot_rocketeer
```

A level using only built-in assets can be shared as a single JSON file. For custom art, cook the DDS files before sharing and preserve their paths relative to the JSON. Run `python tools/package_level.py levels/claybook/level.json --output Tumblebrook.zip` to collect only referenced runtime files. Test the ZIP offline with `--workshop-file Tumblebrook.zip` in the development build. To publish, put a JPEG smaller than 1 MiB named `preview.jpg` beside `level.json` in your work folder. PETAFAB’s [Workshop uploader](steam-workshop.md) accepts the folder directly or a ZIP with both files at its root and cooked DDS files at their referenced paths. Put editable art and author notes in the top-level `source/` directory. The Workshop uploader skips it by default. To play an unpacked map in the Steam build, select its source directory with **Workshop → My Levels → Play Folder**.

**Fluid shapes.** A `cylinder` takes `bottom` (center of its bottom face), `radius`, and `height`. A `pipe` takes `start`, `end` (centerline endpoints at least 0.25 m apart), and `radius`. Radii and cylinder heights are 0.25…32 m. Keep the entire volume inside terrain bounds, including radius around both pipe endpoints. Up to 16 cylinders and 192 pipe segments share 65,536 seed candidates.

Both shapes accept `overpressure` from 0 to 0.25, default 0. For example, `0.08` packs about 8% more particles into the same space before settling. Use the same pressure on adjoining pipe segments so their world-aligned lattices meet. A cylinder can also set `maxParticles` from 1 to 65,536. This counts only positions inside the disk and fills from the bottom, stopping at the cap or the last available position. Uncapped cylinders and pipes budget their bounding lattice before shape and overlap rejection.

### Fluid material and damage

One optional `fluidMaterial` object controls every fluid volume in the map. Omit it for campaign toxic waste.
Custom `color` and `normal` DDS files follow the same format and path rules as surface textures. Supply both together.
An optional linear RGB `tint` multiplies the color (white for custom textures). Roughness defaults to 0.22, metallic and emission to zero.
`fluidDamagePerSecond` is a nonnegative number, default 40. Set it to zero for harmless liquid. Contact still pushes players and enemies.

```json
"fluidMaterial": {"color": "textures/water_color.dds", "normal": "textures/water_normal.dds", "roughness": 0.15},
"fluidDamagePerSecond": 0
```

**Pickup kinds.** `ammo`, `health`, `energy`, `mine`, `grenade`, `foam`, `lure`, `bfg` (Fusion), `black_hole`, `micro_missiles`.

## Appearance

```json
{
  "materials": [{"id":"panel", "color":"textures/panel_color.dds", "normal":"textures/panel_normal.dds", "roughness":0.45, "metallic":0.8}],
  "skybox": {"sky":"sky/dusk_sky.dds", "diffuse":"sky/dusk_diffuse.dds", "specular":"sky/dusk_specular.dds"},
  "sun": {"direction":[0.4,0.8,0.2], "radiance":[6,4,2], "ambient":2},
  "render": {"sky_brightness":1.8, "ambient_multiplier":2.1, "exposure":1.25, "saturation":0.1, "fog_density":0.003, "bloom_strength":0.7},
  "lights": [{"position":[0,6,-3], "radius":8, "radiance":[18,6,2]}]
}
```

- **Textures.** Declare up to 32 named entries within the physical ID budget above. A custom pair occupies one array layer per channel. Each pair tiles once per metre and needs 1024² BC7 sRGB color and BC5 linear DirectX (Y−) tangent normal DDS files, both with 11 mips. Optional `roughness` and `metallic` are uniform numbers per material, 0…1 (defaults 0.8, 0); there are no roughness, metallic, or ORM texture inputs. Linear color alpha packs per-pixel AO and an emission mask. `emission` is a uniform strength, 0…64 (default 0), multiplying that mask; surface RGB supplies the emitted color. There is no separate AO texture path or JSON AO value. Asset paths use forward slashes, stay below the level folder, and end in `.dds`.
- **Color alpha packing.** Before BC7 compression, 8-bit alpha 0…127 encodes AO as `alpha / 127` with zero emission. Values 127 and 128 are neutral (unoccluded, non-emitting). Values 129…255 encode emission as `(alpha - 128) / 127` with texture AO fixed at 1. Independent AO and emission cannot coexist at one texel. Alpha is surface data, not transparency; use 127 or 128 for a neutral surface. Texture AO combines with runtime ambient occlusion.
- **HDR skybox.** Supply all three unsigned BC6H cubemaps. The visible sky is 1024² per face with 11 mips, diffuse irradiance is 16² with one mip, and GGX specular is 256² with seven roughness mips. The same environment lights the scene and supplies reflections.
- **Sun.** `direction` points **toward** the sun at time zero and is normalized on import (components −64…64, nonzero vector). `motion` defaults to `orbit` (a 250-second sun and sky rotation). Use `fixed` for stationary room lighting and reflections. `radiance` is linear RGB, each channel 0…1024. `ambient` scales environment lighting (0…16). All fields are optional. The F8 Sun tab writes `color` (linear RGB 0–1) and `brightness` (0–1024), `azimuth` (−180…180° from +Z toward +X), `elevation` (−90…90°) and `rotationSpeed` (−90…90° per second, zero is stationary). These fields take precedence over the corresponding legacy values.
- **Grading and post.** Every visual tuning slider is available under `render` with the [same keys and limits](https://sebastianaaltonen.com/assets/modding/spillway/level.schema.json). `sky_brightness` controls visible sky intensity. `ambient_multiplier` (0–4) independently controls diffuse and specular environment intensity. Omit it to inherit the sky brightness, matching older maps. `sun.ambient` and `sky_ao_multiplier` also scale indirect surface lighting. Exposure, grading, bloom, height fog, SSAO and SDF AO remain adjustable.
- **Local lights.** 0–1024 unshadowed point lights. Each needs `position` (metres, components −64…64), `radius` (0.125…128 m), and linear RGB `radiance` (0…1024). Gameplay and authored lights share the 1024-light frame limit. Gameplay takes priority, then authored lights fill the remaining slots in file order. Optional `disableWhenAwayFromTerrain: true` turns the light off when terrain is more than 0.5 metres from its position, including at map load. It stays off until the map restarts. Omit it or set it to `false` for an always-on light. Support uses the collision terrain, so place the light clearly within 0.5 metres of a wall, floor or ceiling; actors and fluid do not provide support.

## Preparing custom textures

Convert source images into the DDS textures a PETAFAB level uses. The converter generates mipmaps, packs ambient occlusion and emission, compresses materials, and convolves HDR environment lighting. Maps using built-in materials and skies do not need it.

### Downloads and setup

- [Windows x64 converter — AVX2/FMA CPU](https://sebastianaaltonen.com/assets/modding/PETAFAB-Level-Tools-Windows-x64.zip)
- [Mac converter — Apple silicon, macOS 26 or newer](https://sebastianaaltonen.com/assets/modding/PETAFAB-Level-Tools-macOS-arm64.zip)
- [Sandstone example and source images](https://sebastianaaltonen.com/assets/modding/PETAFAB-Cooker-Example.zip)
- [Complete level specification](https://sebastianaaltonen.com/assets/modding/petafab-level-format.md)

Each download includes `petafab-cook`, this guide and license notices.

Extract the ZIP and open a terminal in the extracted folder. On Windows, run `.\bin\petafab-cook.exe --help` in PowerShell. The Windows executable requires an x64 CPU with AVX2/FMA. On Apple silicon with macOS 26 or newer, extract with Finder/Archive Utility and run `./bin/petafab-cook --help`. The Mac executable is signed and notarized. Both platforms cook assets on the CPU.

The commands below use the Mac executable name. Substitute `.\bin\petafab-cook.exe` in PowerShell.

### Source images

| Input | Format and interpretation |
| --- | --- |
| Albedo | Tileable 1024 × 1024 PNG, 8-bit or 16-bit RGB in sRGB. Alpha is ignored; supply AO and emission separately. |
| Normal | Tileable 1024 × 1024 PNG, 8-bit or 16-bit RGB, linear tangent-space **DirectX (Y−)** normals with positive Z. |
| AO | Tileable 1024 × 1024 PNG, 8-bit or 16-bit linear grayscale: black = fully occluded, white = unoccluded. |
| Emissive mask | Tileable 1024 × 1024 PNG, 8-bit or 16-bit linear grayscale: black = no emission, white = full emission. |
| Height | Optional tileable 1024 × 1024 PNG, 8-bit or 16-bit linear grayscale displacement. White is higher than black. |
| Sky panorama | EXR or Radiance HDR, native 2:1 equirectangular image, from 4096 × 2048 up to 32768 × 16384. Scene-linear RGB with linear sRGB primaries; finite nonnegative radiance up to 64512. |

Material sources must already be 1024 × 1024; the converter rejects other sizes. Each tile covers one metre in the game. Export normal maps, masks and height as data, without an sRGB transfer function. Export skies without a display/view transform or tone mapping. Use PNG for the documented material workflow; EXR/HDR are sky inputs.

EXR input supports scanline and tiled images with full-resolution `R`, `G` and `B` channels in the first image part. Deep EXR images are not supported.

#### DirectX versus OpenGL normals

**Use DirectX (Y−), not OpenGL (Y+).** Red and green store tangent X and Y, encoded from −1…+1 into 0…1; blue must encode positive Z. The converter preserves the imported green-channel direction. For an OpenGL normal map, invert **only green** before cooking: `G = 255 - G` for an 8-bit PNG, or `G = 65535 - G` for 16-bit. Do not flip the image vertically. Normals generated from height already use the required convention.

### Materials from albedo, AO and emission

Supply the source images explicitly:

```sh
./bin/petafab-cook material --name panel --albedo panel.png --normal panel_normal.png --ao panel_ao.png --emission panel_emissive.png --out MyLevel/textures
```

This writes `panel_color.dds` (BC7 sRGB) and `panel_normal.dds` (BC5 linear), both 1024 × 1024 with all 11 mip levels down to 1 × 1. Albedo is filtered in linear light; normal mips are renormalized. AO and emission are filtered separately, then packed into color alpha at each mip. The surface preparation also blends opposite albedo and mask edges for tiling; provide tileable source images and normals.

All inputs except albedo are optional. Without normal or height, the surface gets flat normals. Without AO or height, it is unoccluded. Without an emission mask, it does not emit.

Add an entry to the level's `materials` array:

```json
{
  "id": "panel",
  "color": "textures/panel_color.dds",
  "normal": "textures/panel_normal.dds",
  "roughness": 0.45,
  "metallic": 0.8,
  "emission": 4
}
```

Brushes refer to `"material": "panel"`. Roughness and metallic are uniform numbers from 0 to 1. The emissive mask multiplies the material's HDR emissive color: surface RGB × `emission` strength (0…64, default 0). Set a positive strength for the mask to glow. There are no separate runtime AO, emission, roughness, metallic or ORM texture paths in `level.json`.

#### Optional height workflow

If you have a displacement/height map, the converter can derive both normals and AO from it:

```sh
./bin/petafab-cook material --name stone --albedo stone.png --height stone_height.png --relief 0.008 --out MyLevel/textures
```

`--relief` is the black-to-white height difference in metres: `0.008` means 8 mm (default 0.01; allowed range 0…1). Height adds surface shading detail; it does not change the level's brush geometry. Do not pass `--normal` and `--height` together. Add `--ao stone_ao.png` to override height-derived AO, or `--emission stone_emissive.png` to add emission. A height map is not needed when supplying your own normal and AO maps.

#### Packed color alpha

Color alpha contains ambient occlusion in **[0, 0.5]**: 0 = fully occluded, 0.5 or above = unoccluded. Emission uses **[0.5, 1]**: 0.5 or below = none, 1 = full emission. Emissive texels are unoccluded. The converter handles this packing from separate input maps.

The exact 8-bit encoding before BC7 compression is AO × 127 for non-emitting texels, or 128 + emission × 127 for emitting texels. Alpha 127 and 128 are both neutral. Emission takes precedence where both masks are present; independent AO and emission cannot occupy the same texel. The shader combines texture AO with runtime ambient occlusion.

### HDR skyboxes and lighting

Supply your own EXR or Radiance HDR panorama:

```sh
./bin/petafab-cook sky --name dusk --panorama dusk.exr --out MyLevel/sky
```

The cooker bakes lighting on the CPU. The converter resamples the panorama to cubemap faces, convolves diffuse lighting, prefilters GGX reflections for increasing roughness, and compresses all three cubemaps as unsigned BC6H:

| Output | Face size | Mip levels | Purpose |
| --- | --- | --- | --- |
| `dusk_sky.dds` | 1024 × 1024 | 11 | Visible sky |
| `dusk_diffuse.dds` | 16 × 16 | 1 | Convolved diffuse environment lighting |
| `dusk_specular.dds` | 256 × 256 | 7 (down to 4 × 4) | GGX reflections, roughness 0 through 1 |

Add this top-level field to `level.json`:

```json
"skybox": {
  "sky": "sky/dusk_sky.dds",
  "diffuse": "sky/dusk_diffuse.dds",
  "specular": "sky/dusk_specular.dds"
}
```

All three paths are required. The converter writes DDS files; it does not edit `level.json`. Use the level's `sun` fields for direct sunlight. The environment supplies the sky, indirect illumination and reflections.

### Batch recipes

Keep source images under `MyLevel/source/` with a `cook.json` recipe. Image paths are relative to the recipe; output paths are relative to the `--out` level folder.

```json
{
  "version": 1,
  "materials": [
    {"name": "panel", "albedo": "panel.png", "normal": "panel_normal.png", "ao": "panel_ao.png", "emission": "panel_emissive.png"},
    {"name": "stone", "albedo": "stone.png", "height": "stone_height.png", "relief": 0.008}
  ],
  "sky": {"name": "dusk", "panorama": "dusk.exr"}
}
```

```sh
./bin/petafab-cook build MyLevel/source/cook.json --out MyLevel
```

Omit `sky` for a material-only recipe or `materials` for a sky-only recipe. A recipe accepts up to 32 materials with unique names of 1–64 ASCII letters, digits, underscores or hyphens. Materials require `name` and `albedo`; optional fields are `normal`, `height`, `relief`, `ao` and `emission`, with the same rules as the CLI. The sky entry requires `name` and `panorama`. Recipe version 1 describes the converter job; the game's `level.json` uses version 2.

### Try the example and iterate

Extract the sandstone example download and copy its `example/` folder beside the converter's `bin/` folder. It contains the albedo and height PNGs, recipes, a modified Spillway map, schema and thumbnail.

```sh
./bin/petafab-cook build example/source/cook.json --out example
./bin/petafab-cook package example/level.json --output MyLevel.zip
```

In PETAFAB, choose **Workshop → My Levels → Play Folder** and select `example/`, or use **Play Local ZIP**. After editing and recooking, press **F5** (or **Fn + F5** on Mac keyboards) to reload the local map, textures and sky. For ZIP testing, rebuild the selected archive before reloading.

The optional `example/source/sky.json` recipe expects your own `dusk.exr` beside it. Run `build example/source/sky.json --out example`, then add the `skybox` field shown above to the example level. Package again to include the new files.

The `package` command includes `level.json`, referenced runtime assets and `preview.jpg` (JPEG under 1 MiB). Editable source images are excluded. Keep the source folder yourself and distribute it separately if you want others to edit your assets. A developer build of PETAFAB can validate the finished folder with `petafab --check-level MyLevel/level.json`.

## Gates and waves

The [trigger example](https://sebastianaaltonen.com/assets/modding/triggers/level.json) demonstrates opening a wall, adding terrain, an explosion, a delayed ambush and a repeatable rocket trap.

A gate is an **oriented box**. `floor` is the midpoint of the **bottom edge of its rear face**. `size:[width,height,depth]` gives full dimensions (each 1…16 m). Width extends equally left and right, height extends up, and depth extends forward along `yaw` into the arena. The whole box must fit inside X/Z ±31.75 and Y 0…32. Give it a unique `id` of 1–32 ASCII letters, digits, underscores, or hyphens.

A gate defines spawn lanes. Build a visible frame and provide a traversable floor and exit. Enemies appear just inside the rear face and move along `yaw`. Every gate automatically cuts a blocked lane before spawning and reopens it if terrain changes while an enemy is exiting. Cuts start at the gate’s floor and stay within its width, depth and height. Spawning requires space around live bots, at least 4 m of clearance from the player, and room in the actor pool. Main and extra waves share a limit of 2,011 live bots plus active ragdolls. At capacity, spawning waits for space; remaining bots are not discarded. The total enemy count over a whole map can exceed this simultaneous limit. The importer checks that every assigned enemy fits the gate dimensions.

Each wave has 1–4 `groups`. Each group requires an `enemy` (`constructor`, `constructor2`, `runner`, `rocketeer`, or `shock_trooper`), `count` (1…1000), and either `intervalSeconds` (greater than 0 and up to 600 seconds) or `intervalTicks` (1…72000). Seconds are rounded to the nearest 120 Hz simulation tick, with a one-tick minimum for group intervals. Counts are literal at every difficulty. Groups may use different enemy types within the same wave. They start together, attempt admissions in file order, and track their own quotas. The interval runs from the last **successful** spawn in that group.

Waves select their entrance gates with `"gates": ["west", "east"]`. Groups inherit this selection, or may retain a single `"gate": "west"` override.
A wave without a gate selection must specify `gate` on every group. Each group distributes its **total** count across its selected gates in round-robin order;
blocked gates are skipped for that attempt, and the cursor advances only on a successful spawn. Selecting more gates does not multiply the bot count.
The selection is stored as a 64-bit mask. Instead of `gates`, authors may use a nonzero hexadecimal string such as `"gateMask": "0x8000000000000001"`
for the first and 64th gate. Bit positions follow the level's `gates` array order. Do not use JSON numbers for 64-bit masks, or supply both forms.

Use `"enemy": "constructor"` for the yellow Yard bot or `"enemy": "constructor2"` for the blue Level 2 Factory bot. Both use the same health, movement, self-destruct behavior and wave announcements. To spawn both colors in one wave, give each its own group. This entry in `waves` sends three of each through the named gates:

```json
{"groups": [
  {"gate": "west", "enemy": "constructor",  "count": 3, "intervalSeconds": 0.5},
  {"gate": "east", "enemy": "constructor2", "count": 3, "intervalSeconds": 0.5}
]}
```

A wave becomes eligible once every earlier group has spawned its full quota **and** cumulative defeats reach `afterDefeats`. This optional threshold defaults to the total number of enemies in earlier waves. Set it lower to overlap survivors, or to 0 for an opening wave. Optional `afterSeconds` (0…600, default 0) requires a minimum elapsed time since the previous wave’s last successful admission, or since round start for the first wave. It runs alongside the defeat condition. For example, a wave with `afterSeconds: 10` and `afterDefeats: 67` starts as soon as both are satisfied. Optional `delayTicks` (0…72000, default 0) adds a further wait once those conditions hold.

Optional `afterTrigger: "id"` additionally requires that trigger to have fired. Its first firing remains satisfied for the rest of the round.
Extra-wave enemies do not contribute to `afterDefeats`, boss arrival thresholds or victory. Main waves and the boss retain their existing completion rules.

#### Wave and boss announcements

Each `waves[]` entry and the optional `boss` object accepts an `announcement` string. It selects the HUD banner, alarm and spoken line together. A wave announces once when its first bot enters through a gate. A boss announces on arrival.

| Value | What the player sees and hears |
|---|---|
| `auto` or omitted | Use the first bot’s type or the actual boss type. After the opening wave, a constructor entering a wave with at least 300 constructors triggers the huge-swarm warning. |
| `none` | Skip the banner, alarm and voice for this wave or boss. |
| `constructors` / `constructors_confirmed` | Repair bots approaching, with self-destruct status unknown / confirmed. |
| `runners` / `swarm` | Fast runner bots / huge ground swarm approaching. |
| `rocketeers` / `shock_troopers` | Jetpack rocket bots / shielded shock troopers approaching. |
| `bee_carrier` / `bee_swarm` | One bee carrier / five bee carriers approaching. |
| `barrage` / `saw` / `laser` | Siege bot / saw bot / laser bot approaching. |

Announcements control presentation only. The authored groups and boss type determine what spawns. Boss music starts on actual boss arrival, including when its announcement is `none`.

Set a top-level `boss` to spawn after the last wave has finished spawning. Its optional `afterDefeats` sets the cumulative number of regular defeats required for arrival and defaults to the full enemy count. Optional `afterSeconds` sets the minimum time since the final regular spawn (0…600 seconds, default 0). A boss-only map measures this time from round start. Boss music starts on arrival, and defeating the boss wins even with regular bots still alive. Without a boss, the last regular kill wins.

Place a ground boss about 5.05 m above its intended floor and leave room for its 10 m body. The saw boss uses its authored spawn as its teleport return point. The laser boss can spawn up to 59 m high. Rooftop Airstrip and Tumblebrook use 58 m. Bosses detonate without leaving a corpse and reserve no corpse material slots.

These fields select the Factory track and a laser boss with a silent arrival.

```json
{
  "music": 2,
  "boss": { "type": "laser", "position": [0, 18, 12], "announcement": "none" }
}
```

In Spillway, the west and east gates each admit three constructors at half-second intervals. After all six arrive and four have been defeated, the game waits 180 ticks (1.5 s) and releases two runners from the west. Surviving constructors still count toward victory.

## Player and bot stats

The player object accepts `healthMultiplier` and `speedMultiplier`. The optional top-level `bots` object accepts the same fields:

```json
"player": {"position": [0, 4.55, -16], "healthMultiplier": 2, "speedMultiplier": 1.25},
"bots": {"healthMultiplier": 0.5, "speedMultiplier": 1.5}
```

All multipliers default to 1. Health accepts 0.01–100 and multiplies normal maximum health after hero and difficulty modifiers.
Player healing, regeneration and the health bar use the resulting maximum. Bot health applies to all kinds, including bosses and trigger-spawned waves;
boss health bars and shock-trooper shield thresholds scale with it.
Speed accepts 0–4 and scales player walking or bot pursuit movement (including flight and jet ascent); zero removes that movement intent.
Jump heights, gravity, knockback, player jetpack boosts, attack timing and projectile speeds keep their normal behavior.
The same settings apply to every hero and bot in the map; campaign levels keep their normal stats.

## Drop limits and triggers

`dropLimits` accepts `ammo`, `health`, `energy`, `mine`, `grenade`, `foam`, `lure`, `bfg` (Fusion), `black_hole` and `micro_missiles`.
Omitted kinds keep their normal hero-specific random-drop behavior. For example, `"dropLimits": {"mine": 0, "lure": 1}` disables random mines
and prevents random lure drops while one remains uncollected. Manually placed and trigger-spawned loot ignore these random limits.
Every kind has a hard cap of 16 active pickups, across all sources; storage is preallocated for 160 total. Trigger spawns at the hard cap are skipped,
without queuing a later spawn or blocking subsequent actions. New activations may spawn again after collection frees space.
Authored layouts exceeding 16 of a kind are rejected, and the loot editor prevents excess placement.
Random maximums also supply the existing relative selection weights; they do not limit lifetime drop totals or carried ammunition.

Each trigger requires a unique `id` (1–32 letters, digits, underscores or hyphens) and an ordered `actions` array of up to four entries. Optional `area` is either
`{"shape":"box","center":[x,y,z],"size":[width,height,depth]}` or `{"shape":"sphere","center":[x,y,z],"radius":r}`.
Boxes are axis-aligned. Detection uses living actor capsules. `actors` is `player` (default), `enemy`, or `both` (either can activate it).
An area fires on entry, including when the round starts with an actor inside. `repeat` defaults to false; true rearms when the area becomes empty,
then fires on the next entry. A trigger without an area is a relay activated only by another trigger.
`enabled` defaults to true. An initially disabled trigger ignores area entries and direct activation until an `enableTrigger` action arms it.
If an actor is already inside when enabled, area activation happens on the next simulation tick. Enabling again does not reset one-shot history.
Restart restores each trigger's original enabled state.

Use `delaySeconds` (0–600) or `delayTicks` (0–72000), never both, to delay activation. Leaving after entry does not cancel a scheduled activation.
Each trigger holds one activation; further requests while it is waiting or executing are ignored. Actions execute in file order at 120 Hz.
If a projectile pool is full, that action and subsequent actions wait until space is available, without repeating earlier actions.
All trigger and extra-wave state resets on restart. No actions run in the level preview or after the round ends.

| Action `type` | Fields and behavior |
| --- | --- |
| `brushes` | `brushes`: a nonempty ordered list using the same shapes, materials and `add`/`subtract` operations as the initial terrain. Each list must fit the 4,194,304 brush-to-tile reference budget. Changes update collision and rendering. |
| `explosion` | `position`; optional `radius` (0.0625–32 m, default 3), `damage` (0–100000, default 100), `push` (0–1000, default 30). Damage and push fall off over the radius; either can be zero. Push scales the existing blast impulse, including reduced boss response. Terrain is cut within half the radius. |
| `wave` | `wave`: an ID from `extraWaves`. Optional `gates` or `gateMask` overrides all groups for this activation. Omit it to use the wave’s configured gates. Extra waves contain `id`, `groups`, optional gate selection and `announcement`, using the same groups as main waves. A request while that wave is still spawning is ignored; after its quota has spawned it can be started again, even if survivors remain. |
| `pickup` | `kind`: any pickup kind listed above; `position:[x,y,z]`. Spawns one collectible using normal falling and collection behavior. Ignores `dropLimits`, including zero, for every hero and signature weapon. Skips spawning when 16 of that kind already exist; later actions still execute. |
| `projectile` | `projectile`: `rocket`, `grenade` or `lure`; `position` and `velocity:[x,y,z]` in metres/second. Grenades optionally accept `fuseSeconds` (0–600) or `fuseTicks` (0–72000), never both; default 0.5 seconds. Rockets and grenades are environmental hazards, not player-owned attacks. Velocity is subject to the normal physics limit. |
| `enableTrigger` | `trigger`: another trigger ID to enable. Arms its area or relay without firing it immediately. |
| `trigger` | `trigger`: another enabled trigger ID; optional `delaySeconds` or `delayTicks`, added to the target's own delay. Chaining takes at least one simulation tick, so cyclic links cannot recurse or hang a frame. |

Example actions: `{"type":"enableTrigger","trigger":"ambush_area"}` arms an initially disabled area;
`{"type":"wave","wave":"ambush","gates":["west","east"]}` spawns its bots through selected gates;
`{"type":"trigger","trigger":"ambush","delaySeconds":2}` schedules another trigger. IDs may refer forward in the file; missing references and duplicate IDs are rejected.
Grenade example: `{"type":"projectile","projectile":"grenade","position":[0,8,0],"velocity":[0,5,10],"fuseSeconds":2}`.
The fuse starts when the grenade actually spawns, rounds to the nearest 120 Hz tick, and zero detonates on its first simulation step.
Terrain bounces do not reset it; actor contact still detonates early. The 15 child grenades retain their normal 0.1–1 second fuses.
Loot example: `{"type":"pickup","kind":"bfg","position":[0,8,0]}`. Use multiple actions to spawn several items.
The Blender exporter preserves these JSON fields; author trigger areas and actions in `level.json`.

## Publish and update on Steam Workshop

1. Keep `level.json`, your `preview.jpg` (JPEG, less than 1 MiB), and referenced runtime DDS files in the map folder. Runtime paths use forward slashes and stay inside the folder. For a ZIP, place `level.json` and `preview.jpg` directly at the archive root.
2. Open **Workshop → My Levels → New Level**. Select the folder or ZIP, enter a title and description, and choose any tags or change note.
3. Leave **Skip source/ folder** checked for a playable upload, or uncheck it to include editable assets and author notes.
4. Choose **Read Steam Terms**, accept the terms for the submission, then **Upload New Item**. Keep Steam running until upload finishes.
5. New items start **Private**. Complete any agreement acceptance on the Steam item page, test the published copy, then change visibility to **Public** when ready.
6. To update the same item and retain subscribers, use **Community → Update**, choose the revised folder or ZIP, then **Update Level**. For listing-only edits, clear the selected folder or ZIP to retain existing content and thumbnail.

After uploading, open the installed map and choose **Check for Updates**. The detail panel shows the installed revision’s local date and time and whether the check updated it. Test that installed copy before making the item Public.

Package limits: 128 MiB for the ZIP and expanded contents, at most 128 entries, 32 MiB of JSON, and 69 DDS files. Use ordinary stored or deflated ZIP entries with printable ASCII relative names. Encrypted files, links and duplicate paths are not supported. Include each referenced DDS with matching spelling and case; keep runtime assets outside `source/`.

## Complete built-in surface palette

The names below identify surfaces, not enemy models. Unprefixed names use Yard. Prefix any name with `yard:`, `factory:` or `rooftop:` to choose that palette.

| Name | Yard | Factory | Rooftop |
|---|---|---|---|
| `concrete` | Cast structural concrete | Cast structural concrete | Cast structural concrete |
| `steel` | Brushed structural steel | Perforated metal grille | Brushed structural steel |
| `teal` | Teal machinery panels with inset status lights | Teal machinery panels with inset status lights | Teal machinery panels with inset status lights |
| `hazard` | Safety stripe paint | Safety stripe paint | Safety stripe paint |
| `corpse` | Ceramic-coated robot armor | Ceramic-coated robot armor | Ceramic-coated robot armor |
| `pavement` | Aggregate industrial pavement | Molded insect-robot shell | Extruded cable insulation |
| `ivory` | Painted enamel cladding | Varnished oak wood | Painted enamel cladding |
| `trim` | Worn structural metal trim | Worn structural metal trim | Worn structural metal trim |
| `robot_joint` | Robot joint metal | Robot joint metal | Robot joint metal |
| `robot_boss` | Ceramic-coated robot armor | Ceramic-coated robot armor | Ceramic-coated robot armor |
| `robot_visor` | Robot visor glass | Robot visor glass | Robot visor glass |
| `robot_panel` | Robot inset polymer panels | Painted enamel cladding | Robot inset polymer panels |
| `robot_boss_panel` | Robot inset polymer panels | Robot inset polymer panels | Robot inset polymer panels |
| `foam` | Cured expanding construction foam | Cured expanding construction foam | Cured expanding construction foam |
| `foam_turquoise` | Cured expanding construction foam | Cured expanding construction foam | Cured expanding construction foam |
| `foam_pink` | Cured expanding construction foam | Cured expanding construction foam | Cured expanding construction foam |
| `safety` | Painted enamel cladding | Linear lighting diffuser | Painted enamel cladding |
| `lamp_amber` | Molded translucent lamp lens | Molded translucent lamp lens | Molded translucent lamp lens |
| `lamp_red` | Molded translucent lamp lens | Molded translucent lamp lens | Molded translucent lamp lens |
| `rubber` | Continuous molded rubber skin | Continuous molded rubber skin | Continuous molded rubber skin |
| `graybox` | Perforated metal grille | Fine mineral floor coating | Graphite-coated rooftop casing |
| `bee_yellow` | Molded insect-robot shell | Bare copper fittings | Molded insect-robot shell |
| `bee_black` | Molded insect-robot shell | Molded insect-robot shell | Molded insect-robot shell |
| `bee_wing` | Thin insect-robot wing metal | Dense small-leaf foliage | Thin insect-robot wing metal |
| `porcelain` | Architectural stone flooring | Architectural stone flooring | Architectural stone flooring |
| `aluminium` | Brushed aluminum fittings | Brushed aluminum fittings | Brushed aluminum fittings |
| `upholstery` | Extruded cable insulation | Woven upholstery linen | Extruded cable insulation |
| `foliage` | Dense small-leaf foliage | Dense small-leaf foliage | Extruded cable insulation |
| `bark` | Extruded cable insulation | Tree bark | Anti-slip rooftop decking |
| `display` | Industrial display face | Industrial display face | Riveted rooftop duct alloy |
| `lounge_fabric` | Extruded cable insulation | Woven upholstery linen | Teal machinery panels with inset status lights |
| `robot_rocketeer` | Ceramic-coated robot armor | Ceramic-coated robot armor | Ceramic-coated robot armor |

## Complete Spillway example

Save this as `level.json`. All materials are built in; no custom DDS files are needed.

```json
{
  "$schema": "./level.schema.json",
  "version": 2,
  "fluidDamagePerSecond": 40,
  "materials": [
    {"id": "wall", "builtin": "steel"},
    {"id": "tank", "builtin": "teal"},
    {"id": "gate", "builtin": "hazard"},
    {"id": "plinth", "builtin": "concrete"}
  ],
  "botMaterials": {"constructor": {"robot_joint": "wall"}, "runner": {"robot_joint": "wall"}},
  "player": {"position": [0, 4.55, -11], "yaw": 0},
  "sun": {"direction": [0.4, 0.72, 0.6], "radiance": [5.5, 4.7, 3.9], "ambient": 2},
  "render": {"exposure": 1.15, "contrast": 0.05, "saturation": 0.12, "bloom_strength": 0.65, "fog_density": 0.003},
  "lights": [
    {"position": [-11, 6.5, 0], "radius": 8, "radiance": [20, 4, 0.5]},
    {"position": [11, 6.5, 9], "radius": 8, "radiance": [1, 6, 20]},
    {"position": [8, 7.4, 0], "radius": 5, "radiance": [0.6, 9, 6]}
  ],
  "pickups": [
    {"kind": "ammo", "position": [0, 4.55, -10]},
    {"kind": "grenade", "position": [2, 4.55, -8]}
  ],
  "brushes": [
    {"op": "add", "shape": "box", "center": [0, 0, 0], "size": [64, 8, 64], "material": "plinth"},
    {"op": "add", "shape": "box", "center": [0, 6, 3], "size": [13, 4, 1.5], "material": "wall"},
    {"op": "subtract", "shape": "box", "center": [0, 5.5, 3], "size": [3, 3.5, 3]},
    {"op": "add", "shape": "cylinder", "center": [8, 5.5, 0], "radius": 2.8, "height": 3, "material": "tank"},
    {"op": "subtract", "shape": "cylinder", "center": [8, 6.1, 0], "radius": 2.3, "height": 3.2},
    {"op": "add", "shape": "box", "center": [-12, 6.5, 0], "size": [1, 5, 8], "material": "gate"},
    {"op": "subtract", "shape": "box", "center": [-12, 5.8, 0], "size": [2, 4, 5]},
    {"op": "add", "shape": "box", "center": [12, 6.5, 9], "size": [1, 5, 8], "material": "gate"},
    {"op": "subtract", "shape": "box", "center": [12, 5.8, 9], "size": [2, 4, 5]},
    {"op": "add", "shape": "box", "center": [-5, 4.8, -4], "size": [3, 1.6, 1.4], "yaw": 25, "material": "plinth"}
  ],
  "fluids": [
    {"shape": "cylinder", "bottom": [8, 4.6, 0], "radius": 2, "height": 2}
  ],
  "gates": [
    {"id": "west", "floor": [-12, 4, 0], "size": [4, 4, 4], "yaw": 90},
    {"id": "east", "floor": [12, 4, 9], "size": [4, 4, 4], "yaw": -90}
  ],
  "waves": [
    {"delayTicks": 120, "groups": [
      {"gate": "west", "enemy": "constructor", "count": 3, "intervalTicks": 60},
      {"gate": "east", "enemy": "constructor", "count": 3, "intervalTicks": 60}
    ]},
    {"afterDefeats": 4, "delayTicks": 180, "groups": [
      {"gate": "west", "enemy": "runner", "count": 2, "intervalTicks": 90}
    ]}
  ]
}
```

## Complete JSON Schema

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "Petafab level v1/v2",
  "type": "object",
  "additionalProperties": false,
  "required": ["version", "player", "brushes", "fluids", "gates", "waves"],
  "allOf": [
    {
      "if": {
        "properties": {
          "version": {
            "const": 2
          }
        }
      },
      "then": {
        "required": [
          "materials"
        ],
        "properties": {
          "textures": false,
          "brushes": {
            "items": {
              "if": {
                "properties": {
                  "op": {
                    "const": "add"
                  }
                }
              },
              "then": {
                "required": [
                  "material"
                ]
              }
            }
          },
          "triggers": {
            "items": {
              "properties": {
                "actions": {
                  "items": {
                    "properties": {
                      "brushes": {
                        "items": {
                          "if": {
                            "properties": {
                              "op": {
                                "const": "add"
                              }
                            }
                          },
                          "then": {
                            "required": [
                              "material"
                            ]
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      },
      "else": {
        "properties": {
          "materials": false,
          "botMaterials": false,
          "brushes": {
            "items": {
              "properties": {
                "material": {
                  "$ref": "#/$defs/builtin"
                }
              }
            }
          },
          "triggers": {
            "items": {
              "properties": {
                "actions": {
                  "items": {
                    "properties": {
                      "brushes": {
                        "items": {
                          "properties": {
                            "material": {
                              "$ref": "#/$defs/builtin"
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  ],
  "properties": {
    "$schema": {"type": "string"},
    "version": {"enum": [1, 2]},
    "player": {
      "type": "object", "additionalProperties": false, "required": ["position"],
      "properties": {"position": {"$ref": "#/$defs/playerPosition"}, "yaw": {"$ref": "#/$defs/yaw"}, "pitch": {"type": "number", "minimum": -89, "maximum": 89},
        "healthMultiplier": {"type": "number", "minimum": 0.01, "maximum": 100, "default": 1},
        "speedMultiplier": {"type": "number", "minimum": 0, "maximum": 4, "default": 1}}
    },
    "bots": {"type": "object", "additionalProperties": false, "properties": {
      "healthMultiplier": {"type": "number", "minimum": 0.01, "maximum": 100, "default": 1},
      "speedMultiplier": {"type": "number", "minimum": 0, "maximum": 4, "default": 1}}},
    "brushes": {"type": "array", "maxItems": 65536, "items": {"$ref": "#/$defs/brush"}},
    "fluidDamagePerSecond": {"type": "number", "minimum": 0, "default": 40},
    "fluidMaterial": {
      "type": "object", "additionalProperties": false,
      "dependentRequired": {"color": ["normal"], "normal": ["color"]},
      "properties": {
        "color": {"type": "string", "pattern": "[.]dds$"}, "normal": {"type": "string", "pattern": "[.]dds$"},
        "tint": {"type": "array", "minItems": 3, "maxItems": 3, "items": {"type": "number", "minimum": 0, "maximum": 64}},
        "roughness": {"type": "number", "minimum": 0, "maximum": 1}, "metallic": {"type": "number", "minimum": 0, "maximum": 1},
        "emission": {"type": "number", "minimum": 0, "maximum": 64}
      }
    },
    "fluids": {"type": "array", "maxItems": 208, "items": {"$ref": "#/$defs/fluid"}},
    "gates": {"type": "array", "maxItems": 64, "items": {"$ref": "#/$defs/gate"}},
    "waves": {"type": "array", "maxItems": 32, "items": {"$ref": "#/$defs/wave"}},
    "extraWaves": {"type": "array", "maxItems": 32, "items": {"$ref": "#/$defs/extraWave"}},
    "triggers": {"type": "array", "maxItems": 1024, "items": {"$ref": "#/$defs/trigger"}},
    "dropLimits": {"type": "object", "propertyNames": {"enum": ["ammo", "health", "energy", "mine", "grenade", "foam", "lure", "bfg", "black_hole", "micro_missiles"]},
      "additionalProperties": {"type": "integer", "minimum": 0, "maximum": 16}},
    "music": {"type": "integer", "minimum": 1, "maximum": 3, "default": 1},
    "boss": {"type": "object", "additionalProperties": false, "required": ["type", "position"],
      "properties": {"type": {"enum": ["barrage", "saw", "laser"]}, "position": true, "announcement": {"$ref": "#/$defs/announcement"},
        "afterDefeats": {"type": "integer", "minimum": 0, "description": "Regular defeats required for the boss. Defaults to the total scheduled enemy count."},
        "afterSeconds": {"type": "number", "minimum": 0, "maximum": 600, "default": 0}},
      "if": {"properties": {"type": {"const": "laser"}}},
      "then": {"properties": {"position": {"type": "array", "minItems": 3, "maxItems": 3,
        "prefixItems": [{"$ref": "#/$defs/xz"}, {"type": "number", "minimum": 0, "maximum": 59}, {"$ref": "#/$defs/xz"}]}}},
      "else": {"properties": {"position": {"$ref": "#/$defs/point"}}}},
    "pickups": {"type": "array", "maxItems": 160, "items": {"$ref": "#/$defs/pickup"},
      "allOf": [
        {"contains": {"properties": {"kind": {"const": "ammo"}}, "required": ["kind"]}, "minContains": 0, "maxContains": 16},
        {"contains": {"properties": {"kind": {"const": "health"}}, "required": ["kind"]}, "minContains": 0, "maxContains": 16},
        {"contains": {"properties": {"kind": {"const": "energy"}}, "required": ["kind"]}, "minContains": 0, "maxContains": 16},
        {"contains": {"properties": {"kind": {"const": "mine"}}, "required": ["kind"]}, "minContains": 0, "maxContains": 16},
        {"contains": {"properties": {"kind": {"const": "grenade"}}, "required": ["kind"]}, "minContains": 0, "maxContains": 16},
        {"contains": {"properties": {"kind": {"const": "foam"}}, "required": ["kind"]}, "minContains": 0, "maxContains": 16},
        {"contains": {"properties": {"kind": {"const": "lure"}}, "required": ["kind"]}, "minContains": 0, "maxContains": 16},
        {"contains": {"properties": {"kind": {"const": "bfg"}}, "required": ["kind"]}, "minContains": 0, "maxContains": 16},
        {"contains": {"properties": {"kind": {"const": "black_hole"}}, "required": ["kind"]}, "minContains": 0, "maxContains": 16},
        {"contains": {"properties": {"kind": {"const": "micro_missiles"}}, "required": ["kind"]}, "minContains": 0, "maxContains": 16}
      ]},
    "materials": {"type": "array", "maxItems": 32, "items": {"$ref": "#/$defs/material"}},
    "botMaterials": {"type": "object", "propertyNames": {"enum": ["constructor","constructor2","runner","rocketeer","shock_trooper"]},
      "additionalProperties": {"type": "object", "propertyNames": {"$ref": "#/$defs/builtin"}, "additionalProperties": {"$ref": "#/$defs/id"}}},
    "textures": {"type": "array", "maxItems": 32, "items": {"$ref": "#/$defs/texture"}},
    "skybox": {"type": "object", "additionalProperties": false, "required": ["sky", "diffuse", "specular"],
      "properties": {"sky": {"$ref": "#/$defs/dds"}, "diffuse": {"$ref": "#/$defs/dds"}, "specular": {"$ref": "#/$defs/dds"}}},
    "sun": {"type": "object", "additionalProperties": false, "properties": {
      "direction": {"$ref": "#/$defs/vector"}, "radiance": {"$ref": "#/$defs/radiance"}, "ambient": {"type": "number", "minimum": 0, "maximum": 16},
      "motion": {"enum": ["orbit", "fixed"]},
      "color": {"type":"array","minItems":3,"maxItems":3,"items":{"type":"number","minimum":0,"maximum":1}},
      "brightness": {"type":"number","minimum":0,"maximum":1024}, "azimuth": {"type":"number","minimum":-180,"maximum":180},
      "elevation": {"type":"number","minimum":-90,"maximum":90}, "rotationSpeed": {"type":"number","minimum":-90,"maximum":90}
    }},
    "render": {"$ref": "#/$defs/render"},
    "lights": {"type": "array", "maxItems": 1024, "items": {"type": "object", "additionalProperties": false,
      "required": ["position", "radius", "radiance"], "properties": {
        "position": {"$ref": "#/$defs/vector"}, "radius": {"type": "number", "minimum": 0.125, "maximum": 128}, "radiance": {"$ref": "#/$defs/radiance"},
        "disableWhenAwayFromTerrain": {"type": "boolean", "default": false, "description": "Turn off when terrain is more than 0.5 metres from the light position. Remains off until the map restarts."}
      }}}
  },
  "$defs": {
    "announcement": {"type": "string", "default": "auto", "description": "Selects the arrival banner, alarm and voice together. Use none for a silent arrival.",
      "enum": ["auto", "none", "constructors", "constructors_confirmed", "runners", "swarm", "rocketeers", "shock_troopers",
        "bee_carrier", "bee_swarm", "barrage", "saw", "laser"]},
    "dds": {"type": "string", "pattern": "^(?!/)(?!.*[. ]/)(?!.*//)[^\\\\:*?\"<>|]+[.]dds$"},
    "vector": {"type": "array", "minItems": 3, "maxItems": 3, "items": {"type": "number", "minimum": -64, "maximum": 64}},
    "radiance": {"type": "array", "minItems": 3, "maxItems": 3, "items": {"type": "number", "minimum": 0, "maximum": 1024}},
    "builtin": {"enum": ["concrete", "steel", "teal", "hazard", "corpse", "pavement", "ivory", "trim", "robot_joint", "robot_boss", "robot_visor", "robot_panel", "robot_boss_panel", "foam", "foam_turquoise", "foam_pink", "safety", "lamp_amber", "lamp_red", "rubber", "graybox", "bee_yellow", "bee_black", "bee_wing", "porcelain", "aluminium", "upholstery", "foliage", "bark", "display", "lounge_fabric", "robot_rocketeer"]},
    "builtinMaterial": {"anyOf": [{"$ref": "#/$defs/builtin"}, {"type": "string", "pattern": "^(yard|factory|rooftop):(concrete|steel|teal|hazard|corpse|pavement|ivory|trim|robot_joint|robot_boss|robot_visor|robot_panel|robot_boss_panel|foam|foam_turquoise|foam_pink|safety|lamp_amber|lamp_red|rubber|graybox|bee_yellow|bee_black|bee_wing|porcelain|aluminium|upholstery|foliage|bark|display|lounge_fabric|robot_rocketeer)$"}]},
    "material": {"type": "object", "required": ["id"], "additionalProperties": false,
      "properties": {"id": {"$ref": "#/$defs/id"}, "slot": {"$ref": "#/$defs/builtin"}, "builtin": {"$ref": "#/$defs/builtinMaterial"},
        "color": {"$ref": "#/$defs/dds"}, "normal": {"$ref": "#/$defs/dds"}, "roughness": {"type": "number", "minimum": 0, "maximum": 1},
        "metallic": {"type": "number", "minimum": 0, "maximum": 1}, "emission": {"type": "number", "minimum": 0, "maximum": 64}},
      "if": {"required": ["builtin"]}, "then": {"properties": {"color": false, "normal": false, "roughness": false, "metallic": false, "emission": false}},
      "else": {"required": ["color", "normal"]}},
    "texture": {"type": "object", "additionalProperties": false, "required": ["slot", "color", "normal"], "properties": {
      "slot": {"$ref": "#/$defs/builtin"}, "color": {"$ref": "#/$defs/dds"}, "normal": {"$ref": "#/$defs/dds"},
      "roughness": {"type": "number", "minimum": 0, "maximum": 1}, "metallic": {"type": "number", "minimum": 0, "maximum": 1},
      "emission": {"type": "number", "minimum": 0, "maximum": 64}
    }},
    "render": {
      "type": "object", "additionalProperties": false,
      "properties": {
        "exposure": {"type": "number", "minimum": 0.25, "maximum": 3},
        "brightness": {"type": "number", "minimum": -0.5, "maximum": 0.5},
        "contrast": {"type": "number", "minimum": -0.5, "maximum": 0.5},
        "saturation": {"type": "number", "minimum": -1, "maximum": 1},
        "shadows": {"type": "number", "minimum": -1, "maximum": 1},
        "highlights": {"type": "number", "minimum": -1, "maximum": 1},
        "ssao_radius": {"type": "number", "minimum": 0.1, "maximum": 3},
        "ssao_gain": {"type": "number", "minimum": 0, "maximum": 4},
        "ssao_power": {"type": "number", "minimum": 0.25, "maximum": 3},
        "sdf_power": {"type": "number", "minimum": 0.25, "maximum": 3},
        "ambient_floor": {"type": "number", "minimum": 0, "maximum": 0.5},
        "sky_brightness": {"type": "number", "minimum": 0, "maximum": 4},
        "ambient_multiplier": {"type": "number", "minimum": 0, "maximum": 4},
        "sky_ao_multiplier": {"type": "number", "minimum": 0, "maximum": 4},
        "fog_density": {"type": "number", "minimum": 0, "maximum": 0.05},
        "fog_height_falloff": {"type": "number", "minimum": 0, "maximum": 0.2},
        "fog_reference_height": {"type": "number", "minimum": -16, "maximum": 64},
        "bloom_strength": {"type": "number", "minimum": 0, "maximum": 3},
        "bloom_threshold": {"type": "number", "minimum": 0, "maximum": 8},
        "bloom_knee": {"type": "number", "minimum": 0, "maximum": 4},
        "bloom_downsample_radius": {"type": "number", "minimum": 0, "maximum": 4},
        "bloom_upsample_radius": {"type": "number", "minimum": 0, "maximum": 4}
      }
    },
    "xz": {"type": "number", "minimum": -32, "maximum": 32},
    "point": {
      "type": "array", "minItems": 3, "maxItems": 3,
      "prefixItems": [{"$ref": "#/$defs/xz"}, {"type": "number", "minimum": 0, "maximum": 32}, {"$ref": "#/$defs/xz"}]
    },
    "playerPosition": {
      "type": "array", "minItems": 3, "maxItems": 3,
      "prefixItems": [
        {"type": "number", "minimum": -31, "maximum": 31}, {"type": "number", "minimum": 0.55, "maximum": 30},
        {"type": "number", "minimum": -31, "maximum": 31}
      ]
    },
    "yaw": {"type": "number", "minimum": -360, "maximum": 360},
    "id": {"type": "string", "pattern": "^[A-Za-z0-9_-]{1,32}$"},
    "brush": {
      "type": "object", "additionalProperties": false, "required": ["op", "shape", "center"],
      "properties": {
        "op": {"enum": ["add", "subtract"]}, "shape": {"enum": ["box", "sphere", "cylinder", "torus"]}, "center": {"$ref": "#/$defs/point"},
        "material": {"$ref": "#/$defs/id"},
        "size": {"type": "array", "minItems": 3, "maxItems": 3, "items": {"type": "number", "minimum": 0.0625, "maximum": 64}},
        "yaw": {"$ref": "#/$defs/yaw"}, "radius": {"type": "number", "minimum": 0.0625, "maximum": 32},
        "height": {"type": "number", "minimum": 0.0625, "maximum": 64},
        "rounding": {"type": "number", "minimum": 0, "maximum": 32}, "pitch": {"$ref": "#/$defs/yaw"},
        "tubeRadius": {"type": "number", "minimum": 0.0625, "maximum": 32},
        "topRadius": {"type": "number", "minimum": 0, "maximum": 32}
      },
      "oneOf": [
        {"properties": {"shape": {"const": "torus"}, "size": false, "height": false, "rounding": false, "topRadius": false}, "required": ["radius", "tubeRadius"]},
        {"properties": {"shape": {"const": "box"}, "tubeRadius": false, "radius": false, "height": false, "topRadius": false}, "required": ["size"]},
        {"properties": {"shape": {"const": "sphere"}, "tubeRadius": false, "size": false, "yaw": false, "height": false, "pitch": false, "rounding": false, "topRadius": false}, "required": ["radius"]},
        {"properties": {"shape": {"const": "cylinder"}, "tubeRadius": false, "size": false, "yaw": false, "pitch": false, "rounding": false}, "required": ["radius", "height"]}
      ]
    },
    "fluid": {
      "type": "object", "additionalProperties": false, "required": ["shape", "radius"],
      "properties": {
        "shape": {"enum": ["cylinder", "pipe"]}, "radius": {"type": "number", "minimum": 0.25, "maximum": 32},
        "bottom": {"$ref": "#/$defs/point"}, "height": {"type": "number", "minimum": 0.25, "maximum": 32},
        "start": {"$ref": "#/$defs/point"}, "end": {"$ref": "#/$defs/point"},
        "overpressure": {"type": "number", "minimum": 0, "maximum": 0.25, "default": 0},
        "maxParticles": {"type": "integer", "minimum": 1, "maximum": 65536}
      },
      "oneOf": [
        {"properties": {"shape": {"const": "cylinder"}, "start": false, "end": false}, "required": ["bottom", "height"]},
        {"properties": {"shape": {"const": "pipe"}, "bottom": false, "height": false, "maxParticles": false}, "required": ["start", "end"]}
      ]
    },
    "gate": {
      "type": "object", "additionalProperties": false, "required": ["id", "floor", "size", "yaw"],
      "properties": {
        "id": {"$ref": "#/$defs/id"}, "floor": {"$ref": "#/$defs/point"}, "yaw": {"$ref": "#/$defs/yaw"},
        "obstructions": {"enum": ["wait", "clear"], "deprecated": true, "description": "Ignored. All spawn gates clear blocked lanes automatically."},
        "size": {"type": "array", "minItems": 3, "maxItems": 3, "items": {"type": "number", "minimum": 1, "maximum": 16}}
      }
    },
    "wave": {
      "type": "object", "additionalProperties": false, "required": ["groups"],
      "not": {"required": ["gates", "gateMask"]},
      "if": {"not": {"anyOf": [{"required": ["gates"]}, {"required": ["gateMask"]}]}},
      "then": {"properties": {"groups": {"items": {"required": ["gate"]}}}},
      "properties": {
        "gates": {"$ref": "#/$defs/gateSelection"}, "gateMask": {"$ref": "#/$defs/gateMask"},
        "afterTrigger": {"$ref": "#/$defs/id"},
        "afterDefeats": {"type": "integer", "minimum": 0}, "afterSeconds": {"type": "number", "minimum": 0, "maximum": 600},
        "delayTicks": {"type": "integer", "minimum": 0, "maximum": 72000},
        "announcement": {"$ref": "#/$defs/announcement"},
        "groups": {"type": "array", "minItems": 1, "maxItems": 4, "items": {"$ref": "#/$defs/group"}}
      }
    },
    "extraWave": {
      "type": "object", "additionalProperties": false, "required": ["id", "groups"],
      "not": {"required": ["gates", "gateMask"]},
      "if": {"not": {"anyOf": [{"required": ["gates"]}, {"required": ["gateMask"]}]}},
      "then": {"properties": {"groups": {"items": {"required": ["gate"]}}}},
      "properties": {"id": {"$ref": "#/$defs/id"}, "announcement": {"$ref": "#/$defs/announcement"},
        "gates": {"$ref": "#/$defs/gateSelection"}, "gateMask": {"$ref": "#/$defs/gateMask"},
        "groups": {"type": "array", "minItems": 1, "maxItems": 4, "items": {"$ref": "#/$defs/group"}}}
    },
    "trigger": {
      "type": "object", "additionalProperties": false, "required": ["id", "actions"],
      "not": {"required": ["delayTicks", "delaySeconds"]},
      "dependentRequired": {"actors": ["area"]},
      "properties": {
        "id": {"$ref": "#/$defs/id"}, "area": {"$ref": "#/$defs/triggerArea"},
        "actors": {"enum": ["player", "enemy", "both"]}, "repeat": {"type": "boolean", "default": false},
        "enabled": {"type": "boolean", "default": true},
        "delayTicks": {"type": "integer", "minimum": 0, "maximum": 72000},
        "delaySeconds": {"type": "number", "minimum": 0, "maximum": 600},
        "actions": {"type": "array", "maxItems": 4, "items": {"$ref": "#/$defs/triggerAction"}}
      }
    },
    "triggerArea": {
      "type": "object", "additionalProperties": false, "required": ["shape", "center"],
      "properties": {"shape": {"enum": ["box", "sphere"]}, "center": {"$ref": "#/$defs/triggerPosition"},
        "size": {"type": "array", "minItems": 3, "maxItems": 3, "items": {"type": "number", "minimum": 0.0625, "maximum": 128}},
        "radius": {"type": "number", "minimum": 0.0625, "maximum": 64}},
      "oneOf": [{"properties": {"shape": {"const": "box"}, "radius": false}, "required": ["size"]},
        {"properties": {"shape": {"const": "sphere"}, "size": false}, "required": ["radius"]}]
    },
    "triggerPosition": {
      "type": "array", "minItems": 3, "maxItems": 3,
      "prefixItems": [{"$ref": "#/$defs/xz"}, {"type": "number", "minimum": 0, "maximum": 64}, {"$ref": "#/$defs/xz"}]
    },
    "triggerAction": {
      "oneOf": [
        {"type": "object", "additionalProperties": false, "required": ["type", "brushes"],
          "properties": {"type": {"const": "brushes"}, "brushes": {"type": "array", "minItems": 1, "maxItems": 512, "items": {"$ref": "#/$defs/brush"}}}},
        {"type": "object", "additionalProperties": false, "required": ["type", "position"],
          "properties": {"type": {"const": "explosion"}, "position": {"$ref": "#/$defs/triggerPosition"},
            "radius": {"type": "number", "minimum": 0.0625, "maximum": 32, "default": 3},
            "damage": {"type": "number", "minimum": 0, "maximum": 100000, "default": 100},
            "push": {"type": "number", "minimum": 0, "maximum": 1000, "default": 30}}},
        {"type": "object", "additionalProperties": false, "required": ["type", "wave"],
          "not": {"required": ["gates", "gateMask"]},
          "properties": {"type": {"const": "wave"}, "wave": {"$ref": "#/$defs/id"},
            "gates": {"$ref": "#/$defs/gateSelection"}, "gateMask": {"$ref": "#/$defs/gateMask"}}},
        {"type": "object", "additionalProperties": false, "required": ["type", "trigger"],
          "properties": {"type": {"const": "enableTrigger"}, "trigger": {"$ref": "#/$defs/id"}}},
        {"type": "object", "additionalProperties": false, "required": ["type", "kind", "position"],
          "properties": {"type": {"const": "pickup"}, "kind": {"$ref": "#/$defs/pickup/properties/kind"},
            "position": {"$ref": "#/$defs/triggerPosition"}}},
        {"type": "object", "additionalProperties": false, "required": ["type", "position", "projectile", "velocity"],
          "not": {"required": ["fuseTicks", "fuseSeconds"]},
          "if": {"properties": {"projectile": {"const": "grenade"}}},
          "else": {"not": {"anyOf": [{"required": ["fuseTicks"]}, {"required": ["fuseSeconds"]}]}},
          "properties": {"type": {"const": "projectile"}, "position": {"$ref": "#/$defs/triggerPosition"},
            "projectile": {"enum": ["rocket", "grenade", "lure"]},
            "fuseTicks": {"type": "integer", "minimum": 0, "maximum": 72000},
            "fuseSeconds": {"type": "number", "minimum": 0, "maximum": 600},
            "velocity": {"type": "array", "minItems": 3, "maxItems": 3, "items": {"type": "number", "minimum": -1000, "maximum": 1000}}}},
        {"type": "object", "additionalProperties": false, "required": ["type", "trigger"],
          "not": {"required": ["delayTicks", "delaySeconds"]},
          "properties": {"type": {"const": "trigger"}, "trigger": {"$ref": "#/$defs/id"},
            "delayTicks": {"type": "integer", "minimum": 0, "maximum": 72000}, "delaySeconds": {"type": "number", "minimum": 0, "maximum": 600}}}
      ]
    },
    "gateSelection": {"type": "array", "minItems": 1, "maxItems": 64, "uniqueItems": true, "items": {"$ref": "#/$defs/id"}},
    "gateMask": {"type": "string", "pattern": "^0x[0-9a-fA-F]{1,16}$", "not": {"pattern": "^0x0+$"},
      "description": "Nonzero 64-bit mask; bit 0 selects the first gate in the gates array."},
    "group": {
      "type": "object", "additionalProperties": false, "required": ["enemy", "count"],
      "oneOf": [{"required": ["intervalTicks"]}, {"required": ["intervalSeconds"]}],
      "properties": {
        "gate": {"$ref": "#/$defs/id"}, "enemy": {"enum": ["constructor", "constructor2", "runner", "rocketeer", "shock_trooper"]},
        "count": {"type": "integer", "minimum": 1, "maximum": 1000}, "intervalTicks": {"type": "integer", "minimum": 1, "maximum": 72000},
        "intervalSeconds": {"type": "number", "exclusiveMinimum": 0, "maximum": 600}
      }
    },
    "pickup": {
      "type": "object", "additionalProperties": false, "required": ["kind", "position"],
      "properties": {
        "kind": {"enum": ["ammo", "health", "energy", "mine", "grenade", "foam", "lure", "bfg", "black_hole", "micro_missiles"]},
        "position": {"$ref": "#/$defs/point"}
      }
    }
  }
}
```
