# Species Authoring Contract (CONTRACT)

> One species = one self-contained ES module at `demo/src/species/<id>.js`. The engine, skeleton, fur, IK and motion are all reused.
> Goal: make every animal **instantly recognizable** in the 6 QC views, with proportions that do not collapse, feet that do not sink through the ground, and facial features that do not float.

---

## 0. Coordinate system and units

- `+X` = the animal's right side (the model is left-right symmetric), `+Y` = up, `+Z` = forward (the nose points toward +Z).
- Ground is `y = 0`. 1.0 ≈ 0.33 m (cat shoulder height 0.735).
- Head-local coordinates: origin at `spec.head`, divided by `spec.headScale`; the head sculpt, eyes, nose, ears and whiskers are all authored in head-local units.
- All species **share the 27-bone template** (fixed order, see `demo/src/engine/rig.js`), so do not add or remove bones.

## 1. Module shape

```js
import { buildHead, makeEar } from '../engine/head-kit.js';

const spec = { /* proportion source of truth, see §2 */ };
const headLocal = buildHead({ /* §3 */ });

export default {
  id: 'shiba', name: 'Shiba Inu', en: 'Shiba Inu', emoji: '', accent: '#d97706',
  feature: 'curled tail · triangular prick ears · urajiro',
  spec,
  headLocal,                 // (hx, hax, hy, hz) => head-local distance
  bodyParts,                 // optional: generated from spec by default, see §4
  groom, flow,               // fur, see §5
  coatGLSL,                  // coat color, see §6
  coats: [ {id:0, name:'Red', eyeHue:'amber'}, ... ],
  organs: { /* §7 */ },
  paws: { /* §8 */ },
  gait: { /* §9 */ },
  mouthLocal: [0, -0.11, 0.38],
  vertexTint(px, py, pz, nx, ny, nz) { return [1, 1, 1]; },   // optional
  extras({ THREE, species, rig }) { return null; },          // optional: antlers / mane, etc.
};
```

`engine/prepare.js` fills in automatically: `bodyParts`, `headSDF`, `sdf`, `headFocus`, `bones`, `headGate`.
**You do not need to write `sdf`** unless you want to customize body assembly completely.

## 2. `spec` proportion source of truth

Required:

```js
head: { x, y, z }, headScale,        // head center and world scale (head-local unit × headScale)
spine: [ {z, top, bot, rx}, ... ],   // front (+z) to back (-z); z must be monotonic; 6-8 stations
spineEndCap,                          // end-cap depth (cat 0.052, rabbit 0.06)
pectoral: {x,y,z,rx,ry,rz} | null,   // pectoral muscle (optional)
buttock:  {x,y,z,rx,ry,rz} | null,   // gluteal mass
torso: { withers:{y,z,r}, back:{...}, waist:{...}, croup:{...} },  // rig key points (hand-written or from deriveTorso)
neck: { base:{x,y,z}, top:{x,y,z}, rBase, rTop },
frontLeg: { shoulder, elbow, wrist, paw, rShoulder, rElbow, rWrist, rPawX, rPawY, rPawZ },
hindLeg:  { hip, knee, hock, ankle, paw, rHip, rKnee, rHock, rAnkle, rPawX, rPawY, rPawZ },
tail: { cps:[[x,y,z] ×4], rBase, rTip, segments },   // cubic Bezier, base → tip
bounds: { min:[x,y,z], max:[x,y,z] },                // isosurface sampling box (tight to the silhouette is best)
ear: { root:[x,y,z], tip:[x,y,z], r }                // head-local, used for the ear bones
```

Optional: `scapula:{a,b,r}`, `ham:{x,y,z,rx,ry,rz}`, `hockHeel:{...}`, `blend:{...}`, `headFocus`, `headWeightCut`.

> References: `demo/src/species/cat.js` (realistic quadruped), `demo/src/species/rabbit.js` (compact round rump + long ears).

## 3. `head-kit` head sculpt

```js
buildHead({
  cranium:  {x,y,z,rx,ry,rz},
  cheek:    [{x,y,z,rx,ry,rz,k}],   // mirrored; positioned low and set back
  brow:     [{...}],                // brow ridge above the eye
  muzzle:   [{...}],                // muzzle volume (may be stacked)
  bridge:   [{...}],                // nasal bridge
  whiskerPad:[{...}],               // whisker pad (mirrored)
  lip:      [{from:[...],to:[...],r,k}],   // upper-lip roll (mirrored)
  nose:     [{...}],                // nose pad
  chin:     [{...}],
  philtrum: {from,to,r,k},          // philtrum groove (subtract)
  orbit:    {x,y,z,rx,ry,rz,k},     // eye socket (subtract, mirrored)
  lidHood:  [{from,to,r,k}],        // eyelid hood (add back)
  ears:     earFn, earK,
  extra:    (hx,hax,hy,hz)=>d, extraK,   // antlers / tusks / cheek pouches, etc.
})
```

Ear shapes use `makeEar`:

```js
const ears = makeEar({
  base:[x,y,z], tip:[x,y,z], baseR, tipR,
  lean:[dx,dz],                         // lean out/back with height (cat ears)
  rim:{from,to,r0,r1,k},                // helical outer ridge: widens the ear into a "bowl"
  back:{x,y,z,rx,ry,rz,k},              // concave back of the ear (subtract)
  cup:{from,to,r0,r1,k},                // ear-canal hollow (subtract)
  crease:{...}, antiTragus:{...}, pad:{...},
  k: 0.040,                             // blend into the skull
});
```

- Prick ears: `base→tip` up and outward; lop ears: `tip` outward and down; folded ears: tip up first, then forward and down, optionally with an extra `pad`.
- **Ears are the strongest species signature**: spend extra time on them. `rim` gives the ear thickness, `back` turns the back into a bowl, `cup` opens the ear canal.
- Common mistakes: ears that look like thin antennas (`baseR`/`tipR` too small, `back` carved too aggressively); floating ears (`base` not buried in the cranium).

## 4. Body: defaults are fine, or override

`body-kit.js` builds from `spec`: `torso`(loft) / `neck` / `scapula` / `pectoral` / `upperArm` / `foreArm` / `frontPaw` / `thigh` / `ham` / `buttock` / `shin` / `hockHeel` / `meta` / `hindPaw` / `tail[]`.

- When you need extra volume (pig belly, sheep wool, horse withers), export `bodyExtra(x,y,z)`; it is smin-blended into the body.
- When you need a completely different leg shape, export your own `bodyParts(x,y,z,out)`, but you **must return the same keys** (listed above) plus the `tail` array, otherwise skinning breaks.
- The assembly smin radii are overridden through `spec.blend` (defaults = cat). For long-legged animals, increase `hip/shoulder` at the leg-body junction.

## 5. Fur

```js
groom(x,y,z,nx,ny,nz) -> { density, length, weight, zone }
```
- `density` 0..1 (0 = bald, eyes/nose/mouth must be 0); `length` in world units (0.01–0.12); `zone` is a string used by `flow` to split the flow per zone.
- Use world coordinates to decide the body region; use head-local coordinates (`(y-head.y)/headScale` and so on) to decide facial-feature regions.
- Eye socket: `hypot((|x|/hs-ex)/1, (hy-ey)/0.82, (hz-ez)/1) < r` must always give density=0, otherwise the fur smothers the eyes.
- Apply the same ellipsoid gating to the nose tip and the lips.

```js
flow(px,py,pz,nx,ny,nz,info) -> [fx,fy,fz]   // world direction; the engine projects it onto the tangent plane
```
Assign directions by `info.zone`: body back and down, limbs down, ears up, tail along the tail axis, mane along the neck crest.

## 6. Coat GLSL

Must define:

```glsl
vec3 evalCoatColor(vec3 p, float t, float seed, int coatType, vec3 headOff, float headScale, int poseMode)
```

- `p` world position; `t` strand parameter 0 (root) → 1 (tip); `seed` 0..1; `coatType` is an index into your `coats`; `poseMode` is always 1.
- `axH = abs(p.x)/headScale`, `hy=(p.y-headOff.y)/headScale`, `hz=...` are available for face/ear masks.
- **Do not use GLSL ES 3.0 reserved words**: `patch`, `sample`, `filter`, `input`, `output`, `active`, `common`, `partition` and so on. Rename when you hit a compile error.
- Every coat branch must output a full color; finish with `clamp(col, 0.02, 0.98)`.
- Build markings from `smoothstep` plus low-frequency `sin` combinations; avoid high-frequency noise (the fur amplifies it).

## 7. Organs

```js
organs: {
  eye: {
    x,y,z, r, yaw, roll,
    iris: { shape:'slit'|'round'|'horizontal', fibers: 400,
            hues: { amber:{stops:[[0,'#..'],[.4,'#..'],[.85,'#..'],[1,'#..']], ring:'#..'}, ... } },
    rim: { enabled:true, color:0x1a1311 },
    caruncle: { enabled:true, color:0x331917 },
    catchlights: true,
  },
  nose: { y,z, rx,ry,rz,
    nostril: { kind:'comma'|'round', spreadIn, spreadOut, yIn, yOut, radius, depth, aspectX, aspectY },
    philtrum: { width, depth } | false,
    colors: { stops: [[0,'#..'],...] },
  },
  whiskers: { specs:[[ox,oy,oz,len,dyMid,dyEnd,sweep],...], browSpecs, tuftSpecs, radius, ... } | null,
  tongue: { y,z,r } | null,
}
```

- Eyes must **sit inside the orbit**: align `eye.z` with the head sculpt's `orbit.z`, with a radius of about 0.7 of the orbit.
- The nose is a separate mesh; `nose.z` must land 0.01–0.03 (head-local units) outside the front surface of the muzzle — neither floating nor buried.
- Whiskers follow the `specs` list; shorten `len` for long-muzzled animals and lengthen it for short-muzzled ones.

## 8. Feet

```js
paws: {
  style: 'paw' | 'hoof' | 'cloven',
  toeCount: 4, scale: 1.0,
  color, padColor, tufts: true, tuftCount: 260,
  front: { x, z, yaw }, hind: { x, z, yaw },   // optional, defaults to spec's paw
}
```

- Cat / dog / fox / rabbit / panda / hamster use `paw`; the horse uses `hoof`; pig / deer / sheep use `cloven`.
- Hoofed species must also narrow the SDF foot tip into a column (smaller `rPawX/rPawZ`, larger `rPawY`), otherwise the hoof floats on top of a fleshy pad.

## 9. Gait

```js
gait: {
  walk: { period, stride, duty, liftFront, liftHind, pelvisDrop, bob, roll, ... },
  run:  { period, strideFront, strideHind, liftFront, liftHind, pelvisDrop, bounce },
  groom:{ speed },
}
```
- Longer legs → larger `stride` and `period`; smaller animals → shorter cycle.
- Hopping species (rabbit) can push `run.strideHind` close to `strideFront` and increase `pelvisDrop`.

## 10. QC workflow (mandatory)

Start a static server at the repository root (`python -m http.server 8099`). From `demo/`:

```bash
# Numeric health check (NaN / negative samples / head center)
node tools/sdf-probe.mjs <id>

# 6-view QC (check the clay silhouette first, then the full coat)
node tools/shot.mjs <id>-clay "s=<id>&stage=clay&res=80"
node tools/shot.mjs <id>-full "s=<id>&stage=full&fur=80000&res=80"
```

Then inspect `demo/qc/<id>-clay.png` / `demo/qc/<id>-full.png` with `read_image`, and iterate at least 3 rounds.
The released QC captures are stored as WebP (`demo/qc/<id>-clay.webp` / `demo/qc/<id>-full.webp`).

Criteria:

1. **Silhouette**: the species is identifiable without color (ears / muzzle / tail / legs / body mass).
2. **Proportions**: head-to-body ratio, leg length, neck length and tail length are harmonious; feet touch the ground without sinking (`METRICS.footMinY` should be ≥ 0).
3. **Features**: eyes inside the orbits, nose at the tip of the muzzle, ears not floating; no fur poking through around the mouth.
4. **Fur**: does not smear the face, no bald patches, no hedgehog spikes.
5. **Numbers**: `METRICS.nan=0`, `tris>8000`.

## 11. Troubleshooting

| Symptom | Cause / fix |
|---|---|
| `verts=0, tris=0` | SDF is all NaN: `roundCone` `r1` not supplied, negative `sqrt`, division by zero; locate it with `sdf-probe` |
| Shader compile failure | GLSL reserved word (`patch` etc.); or a missing `evalCoatColor` |
| Eye turns into a grey-white ball | wrong iris UV ratio / cornea reflection too strong; tune `iris` and `r` |
| Nose floats | `nose.z` too far forward; align it with the head sculpt's `nose` ellipsoid |
| Legs tear away from the body | `spec.torso` key points too far from the spine; tune `blend.hip/shoulder` |
| Feet sink through the ground | `frontLeg.paw.y`/`hindLeg.paw.y` too small; `paws` `footY` defaults to 0.002 |
| Ear base splits open | `makeEar` `k` too small / `base` not buried in the cranium |

## 12. Prohibitions

- Do not modify `demo/src/engine/*`, other people's files under `demo/src/species/`, `demo/tools/*`, or `demo/index.html`.
- Do not import `three` inside a species file (`THREE` is a global variable, used only in `extras`).
- Do not add dependencies, external textures or models.
- Keep a single species file at or below 450 lines; beyond that, split it with `bodyExtra` / `extras`.
