# Tenant models

A tenant model is a 3D model one tenant uploads for its own twins, beside the
shared library: its own filler, a press the library lacks, its own product. A
twin names it as `tenant/{name}@{version}`, the way it names
`library/{name}@{version}`.

This page describes the result the DigitalTwin API accepts, a way to build it,
and how to upload it with tllt. Nothing here needs simstack or its Blender kit.
Build the GLB with any tools: what matters is the file that comes out.

The rules are those of **contract 1**, the version the API checks today. They
come from the API's own checker, which runs on every commit and answers with the
problems it finds. Where this page and the API disagree, the API wins.

## Before you start

- **Who.** Uploading, committing and deleting need the TilliT `ADMIN` role on the
  tenant. Listing and reading need only sign-in.
- **Where.** The environment's Digital Twin API must have the model routes.
  `tllt --json api GET digital-twin/models/tenant/anything@1` tells you which:
  `404 no model …` means the route exists, `404 no route …` means it doesn't. As of
  November 2026 production has no model routes.
- **Versions are immutable.** A committed version never changes; any change is a
  new version. A deleted version's ref can never be used again.
- **Keep your source.** The API stores the GLB and its metadata only. To change a
  model later, you need whatever built it.

## What you deliver

1. A GLB file, at most **8 MiB**.
2. An upload body:

   ```json
   {"contract": 1, "bytes": 52920, "sidecar": {…}, "rigs": {…}}
   ```

   `bytes` is the file's exact size. `sidecar` is the model's metadata, the same
   object embedded in the GLB. `rigs` gives each moving part's rest position
   ([below](#the-upload-body)).

The name is lowercase letters, digits and dashes, starting with a letter or
digit, at most 64 characters, and no library model's name: `tllt --json twin
models` lists those, and the upload refuses one. A prefix of your own, such as
`acme-press`, keeps clear of them. The version is an integer from 1.

## Space and conventions

- Metres, in glTF's axes: **+Y is up**, and the floor is `y = 0`.
- The origin is the **centre of the footprint, on the floor**: a twin places the
  model there.
- A machine runs along X: its in port toward −X, its out port toward +X.
- **+Z is the front**, where an operator stands: the library's `operator` anchors
  sit on the floor at +Z.
- `footprint` is `[x, z]`: the width along X and the depth along Z.
- "Within 1 mm" in the rules means on each axis.

## The metadata (sidecar)

A JSON object. Unknown keys are refused, and it may be at most 64 KiB.

| Key | Type | Meaning |
| --- | ---- | ------- |
| `units` | `"m"` | Optional; metres is the only unit |
| `kind` | `machine` \| `product` \| `vehicle` \| `person` \| `structure` | Default `machine` |
| `footprint` | `[x, z]`, metres, both > 0 | The floor area; twins lay out by it |
| `ports` | `{name: [x, y, z]}` | Where flows attach. Names match `^[a-z][a-z0-9-]*$`, usually `in` and `out` |
| `anchors` | `{status?, label?, operator?: [x, y, z], changeover?: [[x, y, z], …]}` | Where the status badge floats (above the model), the label sits, an operator stands (on the floor, at +Z), changeover parts go |
| `rig` | `["rig:…", …]` | The names of the moving parts' nodes ([rules](#the-glb)) |
| `behavior` | one of the table below | How the simulator drives it |
| `consumes`, `produces` | string | The product a machine takes in and puts out, matching the twin's product keys, e.g. `bottle`, `carton` |
| `consumesPerUnit` | integer ≥ 1, default 1 | Inputs per cycle |
| `outputEvery` | integer ≥ 1, default 1 | Inputs per output: 12 bottles make a carton |
| `unpacks` | integer ≥ 1 | Parts released from a crate whose identity doesn't say |
| `closeAfterSeconds` | number > 0 | Idle seconds before a pack closes its part-full crate |
| `kits` | boolean | A pack that kits parts of several orders into carts |
| `pitch` | number > 0 | Spacing of products on a conveyor, metres |
| `rings` | array | Only for `rotary` models carrying bottles on rig nodes. Each ring is `{rig, radius, slots, y?, parts: ["shell", "liquid", "cap", "label"], spin?: 1 \| -1}` |

| `behavior` | Fields |
| ---------- | ------ |
| `{"type": "static"}` | Nothing moves |
| `{"type": "rotary"}` | Rig nodes spin as it runs |
| `{"type": "cycle", "unitsPerCycle": n}` | Plays its `cycle` animation once per `unitsPerCycle` units (default 1) of the machine's rate, stretched to fit: the clip's own length doesn't set its speed. A stopped machine holds its pose |
| `{"type": "robot-arm"}` | A robot arm |
| `{"type": "vehicle", "flow": "<flow id>", "roundTrip"?: true}` | Carries a flow's load |
| `{"type": "tank", "level": "<process value>", "full"?: n}` | Fills by a process value, in percent unless `full` gives the full-scale reading |

A simple machine with one moving part:

```json
{
  "kind": "machine",
  "footprint": [2.4, 1.6],
  "ports": {"in": [-1.2, 0.9, 0], "out": [1.2, 0.9, 0]},
  "anchors": {"status": [0, 2.3, 0]},
  "rig": ["rig:ram"],
  "behavior": {"type": "cycle"},
  "consumes": "bottle",
  "produces": "bottle"
}
```

## The GLB

The commit checks every rule below. A `product` skips 5, 6 and 9, and must have
no rig nodes and no contact shadow.

1. **Metadata.** The glTF root's `extras.digitalTwin` holds the sidecar, the same
   object you send as `sidecar`. Both are parsed with defaults filled in, then
   compared.
2. **Part names.** Every node that carries a mesh, other than a `port:` node, has
   a unique name. Keep meshes on nodes without children: compression moves the
   mesh of a node that has children onto a new, unnamed child.
3. **Rig nodes.** Each moving part is a node named `rig:{name}`, no spaces, and
   the set of such nodes is exactly the sidecar's `rig` list. A rig node:
   - carries no mesh itself; its meshes are child nodes that move with it;
   - rests unrotated (identity rotation) and unscaled (scale 1) in its own
     transform;
   - sits where `rigs` says, within 1 mm on each axis, in model space (world
     position);
   - has the nearest `rig:` ancestor that `rigs` names as its `parent`, or none.

   A child node's name that starts with `rig:` and has a space,
   `rig:ram steel`, is not a rig node.
4. **Ports.** One node `port:{name}` per sidecar port, at the port's position
   within 1 mm on each axis, and no other `port:` nodes. Port nodes are empty: no
   mesh.
5. **Contact shadow** (machines, structures, vehicles, people). A node named
   `contact-shadow` whose mesh has one primitive:
   - a flat quad: its bounds between 5 and 20 mm above the floor, and at most 1 mm
     thick;
   - its material unlit (`KHR_materials_unlit`), `alphaMode: "BLEND"`, with a
     base colour texture of at most 512 × 512.
6. **Baked shading (ambient occlusion).** Every primitive whose material isn't
   alpha-blended (and isn't the shadow's):
   - has a material with an occlusion texture on **texture coordinate 1**;
   - has a `TEXCOORD_1` attribute;
   - and all of them share **one** occlusion texture of at most 1024 × 1024.

   Alpha-blended (see-through) materials must have **no** occlusion texture.
7. **Size.** At most 100,000 triangles and 40 primitives, counted over every
   primitive, the shadow included. The file is at most 8 MiB. A tenant's committed
   models total at most 200 MiB, and one twin's tenant models at most 30 MiB.
8. **Compression.** Geometry uses `EXT_meshopt_compression` with
   `KHR_mesh_quantization`, and every texture is `image/webp` (`EXT_texture_webp`):
   no PNG or JPEG remains.
9. **Shape** (machines, vehicles, people with a `footprint`). The mesh nodes,
   without the shadow, span at least 80% of the footprint on X and on Z. Every
   port lies within 0.25 m of those meshes' bounds, and the status anchor within
   0.5 m.
10. **Animation.** Only a `cycle` model animates, with no animation or exactly one
    named `cycle`. That clip:
    - animates only nodes in the sidecar's `rig` list, never mesh nodes;
    - starts at each node's rest pose and ends where it started: within 1 mm on
      each axis, 0.1° and 0.001 of scale;
    - lasts more than 0.1 s.

    Any other model has no animations.
11. **Valid glTF.** The Khronos glTF validator (`npm i gltf-validator`) reports no
    errors. Information messages are fine: meshopt, unused `TEXCOORD_0`, empty
    nodes.

## A way to build it

One route that meets every rule, tested end to end against the API's checker:
the geometry and the shading bake in Blender 5.2's Python API, finished in Node
with glTF-Transform 4.

```bash
npm i @gltf-transform/core @gltf-transform/extensions @gltf-transform/functions meshoptimizer sharp gltf-validator
blender -b --factory-startup --python-exit-code 1 --python build.py   # geometry, bake: raw.glb + ao.png
node finish.mjs raw.glb ao.png sidecar.json model.glb                # occlusion, shadow, metadata, compression
node upload-body.mjs model.glb > upload.json                         # "The upload body" below
```

### 1. Geometry (Blender)

- Model in metres. Blender is +Z up; its glTF exporter turns Blender's
  (x, y, z) into glTF's (x, z, −y). So the floor is Blender's z = 0, and glTF's
  front (+Z) is Blender's −Y.
- Apply rotation and scale to every mesh object.
- Keep meshes as leaf objects: group parts under Empties, never under another
  mesh (rule 2).
- Each moving part is an **Empty** named `rig:{name}` at its pivot, unrotated
  and unscaled, with its meshes parented to it.
- Each port is an **Empty** named `port:{name}`.
- Give mesh objects distinct names. Delete faces that can never be seen, such as
  those against the floor or inside another part: they waste the shading atlas.

### 2. Shading bake (Blender)

- **A second UV map.** Give every opaque mesh a second UV map and make it the
  active map, since Lightmap Pack writes into the active one. With all of them
  selected, pack them into one atlas:
  `bpy.ops.uv.lightmap_pack(PREF_CONTEXT='ALL_FACES', PREF_PACK_IN_ONE=True,
  PREF_NEW_UVLAYER=False, PREF_MARGIN_DIV=0.3)` (about 3 px of margin at
  1024). Then make the first map active again.
- **One image, Non-Color.** Create one image of at most 1024² and set its colour
  space to **Non-Color**. glTF reads occlusion as linear, so an sRGB bake comes
  out at about half strength.
- **The bake target.** In every material, add an Image Texture node holding that
  image, and make it the only selected node and the active one: the bake writes
  there.
- **A floor.** Add a temporary floor plane so the ground darkens the parts near
  it.
- **Bake.** With Cycles, run `bpy.ops.object.bake(type='AO',
  uv_layer='<second map>', target='IMAGE_TEXTURES')`. The world's
  `light_settings.distance` (0.5 to 1 m) sets how far occlusion reaches. Save
  the image as PNG.
- **Moving parts (optional).** Bake the fixed parts with the moving parts hidden
  (`hide_render`). Then bake the moving parts alone into the same image with
  `use_clear=False`, in their working position. That way the bake doesn't paint
  shadows the motion would leave behind.
- **Clean up.** Remove the bake nodes and the floor before exporting.

### 3. Export (Blender)

```python
bpy.ops.export_scene.gltf(filepath='raw.glb', export_format='GLB', export_yup=True,
    export_texcoords=True, export_normals=True, export_animations=True,
    export_animation_mode='ACTIONS', export_force_sampling=True,
    export_cameras=False, export_lights=False)
```

Both UV maps export in order, the second as `TEXCOORD_1`. For a `cycle` model,
keyframe the rig Empties so the action starts and ends at the rest pose, and
name the action `cycle`: its name becomes the clip's. Any other model exports
no animation (`export_animations=False`).

### 4. Finish (Node)

Blender's exporter doesn't write the occlusion, the unlit shadow, the metadata or
the compression the way the checker wants, so this script adds them. Run it with
the sidecar as a JSON file:

```js
// node finish.mjs raw.glb ao.png sidecar.json model.glb
import fs from 'node:fs';
import {NodeIO} from '@gltf-transform/core';
import {ALL_EXTENSIONS, KHRMaterialsUnlit} from '@gltf-transform/extensions';
import {dedup, meshopt, textureCompress} from '@gltf-transform/functions';
import {MeshoptEncoder} from 'meshoptimizer';
import sharp from 'sharp';

const [rawPath, aoPath, sidecarPath, outPath] = process.argv.slice(2);
const sidecar = JSON.parse(fs.readFileSync(sidecarPath, 'utf8'));
await MeshoptEncoder.ready; // writing meshopt needs the encoder registered
const io = new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({'meshopt.encoder': MeshoptEncoder});
const doc = await io.read(rawPath);
const root = doc.getRoot();

// Rule 6: one occlusion texture, on texture coordinate 1, on every opaque material.
const ao = doc.createTexture('ao').setImage(fs.readFileSync(aoPath)).setMimeType('image/png');
for (const material of root.listMaterials()) {
  if (material.getAlphaMode() === 'BLEND') continue;
  material.setOcclusionTexture(ao);
  material.getOcclusionTextureInfo().setTexCoord(1);
}

// Rule 5 (not for products): a quad 10 mm above the floor, dark under the model, clear 0.3 m past its footprint.
if (sidecar.kind !== 'product') {
  const [w, d] = sidecar.footprint ?? [1, 1];
  const half = [w / 2 + 0.3, d / 2 + 0.3];
  const core = [Math.max(w / 2 - 0.1, 0.05), Math.max(d / 2 - 0.1, 0.05)];
  const size = 256;
  const pixels = Buffer.alloc(size * size * 4); // black; only alpha varies
  for (let j = 0; j < size; j++) {
    for (let i = 0; i < size; i++) {
      const x = (((i + 0.5) / size) * 2 - 1) * half[0];
      const z = (((j + 0.5) / size) * 2 - 1) * half[1];
      const out = Math.hypot(Math.max(Math.abs(x) - core[0], 0), Math.max(Math.abs(z) - core[1], 0));
      const t = Math.min(out / 0.35, 1);
      pixels[(j * size + i) * 4 + 3] = Math.round(255 * 0.55 * (1 - t * t * (3 - 2 * t)));
    }
  }
  const image = await sharp(pixels, {raw: {width: size, height: size, channels: 4}}).png().toBuffer();
  const unlit = doc.createExtension(KHRMaterialsUnlit);
  const material = doc
    .createMaterial('contact-shadow')
    .setAlphaMode('BLEND')
    .setBaseColorTexture(doc.createTexture('contact-shadow').setImage(image).setMimeType('image/png'))
    .setExtension('KHR_materials_unlit', unlit.createUnlit());
  const buffer = root.listBuffers()[0];
  const accessor = (type, array) => doc.createAccessor().setBuffer(buffer).setType(type).setArray(array);
  const [hx, hz] = half;
  const y = 0.01;
  const quad = doc
    .createPrimitive()
    .setMaterial(material)
    .setIndices(accessor('SCALAR', new Uint16Array([0, 2, 1, 0, 3, 2]))) // faces +Y
    .setAttribute('POSITION', accessor('VEC3', new Float32Array([-hx, y, -hz, hx, y, -hz, hx, y, hz, -hx, y, hz])))
    .setAttribute('NORMAL', accessor('VEC3', new Float32Array([0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0])))
    .setAttribute('TEXCOORD_0', accessor('VEC2', new Float32Array([0, 0, 1, 0, 1, 1, 0, 1])));
  const node = doc.createNode('contact-shadow').setMesh(doc.createMesh('contact-shadow').addPrimitive(quad));
  root.getDefaultScene().addChild(node);
}

// Rules 1, 6 and 8: the metadata, one shared occlusion texture, compression and WebP.
root.setExtras({digitalTwin: sidecar});
await doc.transform(
  dedup(),
  // 'medium', not the default 'high': 'high' stores animation lossily, and rig keys can drift past 1 mm.
  meshopt({encoder: MeshoptEncoder, level: 'medium'}),
  textureCompress({encoder: sharp, targetFormat: 'webp'}),
);
await io.write(outPath, doc);
```

### 5. Check

Run `gltf-validator` on the result and look over rules 2–10 yourself: node names,
rig and port positions, extensions, texture types and sizes, the triangle count.
The commit runs the full check.

### Without Blender

glTF-Transform alone can build the geometry from boxes and cylinders. Every
primitive then needs `TEXCOORD_0` as well as `TEXCOORD_1`, because the validator
refuses a `TEXCOORD_1` without a `TEXCOORD_0`. Point `TEXCOORD_1` at a small,
uniform occlusion texture. That passes rule 6 but looks flat: real occlusion
needs a bake.

## The upload body

Reading the sidecar and the rig positions back from the finished GLB guarantees
they match it:

```js
// node upload-body.mjs model.glb > upload.json
// npm i @gltf-transform/core @gltf-transform/extensions meshoptimizer (already in the build's npm i)
import fs from 'node:fs';
import {NodeIO, PropertyType} from '@gltf-transform/core';
import {ALL_EXTENSIONS} from '@gltf-transform/extensions';
import {MeshoptDecoder} from 'meshoptimizer';

const file = process.argv[2];
await MeshoptDecoder.ready;
const io = new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({'meshopt.decoder': MeshoptDecoder});
const root = (await io.read(file)).getRoot();
const isRig = (node) => /^rig:\S+$/.test(node.getName());
const parentOf = (node) => node.listParents().find((p) => p.propertyType === PropertyType.NODE) ?? null;
const rigs = {};
for (const node of root.listNodes().filter(isRig)) {
  const m = node.getWorldMatrix();
  let parent = parentOf(node);
  while (parent && !isRig(parent)) parent = parentOf(parent);
  rigs[node.getName()] = {at: [m[12], m[13], m[14]], ...(parent ? {parent: parent.getName()} : {})};
}
const sidecar = root.getExtras().digitalTwin;
process.stdout.write(JSON.stringify({contract: 1, bytes: fs.statSync(file).size, sidecar, rigs}));
```

A top-level rig node has no `parent` key; `null` is refused. A product has
`"rigs": {}`.

## Uploading with tllt

Three calls, the middle one a plain HTTP upload. Name and version go in the path:

```bash
P=my-tenant-stage; M=press@1
node upload-body.mjs press.glb > upload.json

# 1. Stage the upload: answers {uploadId, url, expiresAt}
tllt --json --profile $P api POST digital-twin/models/tenant/$M/upload @upload.json > staged.json
URL=$(jq -r .body.url staged.json); ID=$(jq -r .body.uploadId staged.json)

# 2. Within 15 minutes, send the file's exact bytes with exactly this content type
curl --fail-with-body -X PUT -H 'Content-Type: model/gltf-binary' --data-binary @press.glb "$URL"

# 3. Commit: the API runs the checks above
tllt --json --profile $P api POST digital-twin/models/tenant/$M/commit "{\"uploadId\":\"$ID\"}"
```

- **Success** (`201`, `"ok": true`): `body` is `{ref, metadata}`, e.g.
  `tenant/press@1`.
- **`400`** (`"ok": false`, exit 1): the list is in `error.problems`. A failed
  commit discards the staged file: fix the GLB, then start again at step 1. The
  version stays free.
- **`409`**: the version is already committed, or was deleted. Use a new version.
- **`403`**: the profile's user isn't an ADMIN of the tenant.

The upload call checks the body before anything is staged: the name, version,
contract, `bytes`, the sidecar's shape, and that `rigs` has exactly one entry per
`rig` name.

## Using it in a twin

```bash
tllt --json twin models            # tenant/press@1 is listed beside the library
```

Name it as an asset's `model` (or a product's `model`) in the twin file, then
`tllt twin validate` and `tllt twin push` as usual ([twin.md](twin.md)). To see
how it looks, open the tenant's View at `/digital-twin/`.

`tllt --json api DELETE digital-twin/models/tenant/press@1` retires a version that
no published twin names. Otherwise it answers `409` with the twins that use it.

## Commit problems and what they mean

| Problem | Fix |
| ------- | --- |
| `root extras.digitalTwin differs from the sidecar` | Embed exactly the object you send; read it back from the GLB |
| `its rig nodes are […], the sidecar lists […]` | Name the moving parts' nodes exactly as `rig` lists them |
| `rig:x rests at […], rigs.json puts it at […]` | The message says `rigs.json`; it means the body's `rigs`. Recompute it from the finished GLB |
| `rig:x is rotated at rest` / `is scaled at rest` | Apply the rotation or scale to its meshes, not the rig node |
| `rig:x carries a mesh` | Move the mesh to a child node |
| `port:x is at …` / `it has no port:x node` | Place an empty `port:x` node at the sidecar's position |
| `it has no contact-shadow node with one primitive` | Add the shadow quad (rule 5) |
| `X has no occlusion texture` / `isn't on texture coordinate 1` | Wire the baked image as occlusion with `texCoord: 1` |
| `see-through X has an occlusion texture` | Remove occlusion from alpha-blended materials |
| `its materials use N occlusion textures, not one` | Bake one atlas; run `dedup()` |
| `it doesn't use EXT_meshopt_compression` | Run glTF-Transform's `meshopt()` before writing |
| `texture … is image/png, not image/webp` | Run `textureCompress({targetFormat: 'webp'})` |
| `… triangles, over its budget of 100000` | Simplify (`simplify()` with `MeshoptSimplifier`) or model less detail |
| `its meshes span …, under 80% of its footprint` | Shrink `footprint` to what's drawn, or model to it |
| `it has duplicate part name …` | Name every mesh node distinctly; keep meshes off nodes that have children |
| `clip cycle starts … away from its rest pose` / `doesn't loop` | Key the rest pose first and last; compress with `level: 'medium'` |
| `glTF validator: …` | Fix what the Khronos validator names |
