# Making a creature for first steps

first steps (https://first-steps-1122.algovivo.com) takes a 3D creature, a tetrahedral mesh with muscles, and shows it walking toward a moving
target within a minute of the upload. There is nothing to train first: the creature gets a random brain, and a planner
steers it every few steps. This guide is for you or an AI agent making one over the REST API.

## The short version

1. Write the creature as JSON (format below), or start from the quadruped script at the end and change it.
2. `POST https://first-steps-1122.algovivo.com/api/creatures/check` with `{"data": ...}`. It needs no sign-in, saves nothing, and answers with what is
   wrong and how to fix it. Repeat until `"ok": true`.
3. `POST https://first-steps-1122.algovivo.com/api/creatures` with `{"name": "...", "data": ..., "frame": ...}` and
   `Authorization: Bearer <token>` (make a token under https://first-steps-1122.algovivo.com/account). The answer has the creature's `id` and `url`.
4. Open the `url` in a browser to watch it walk, or poll `GET https://first-steps-1122.algovivo.com/api/creatures/{id}` until `walk.status` is `done`
   (or `failed`, with `walk.error`). `walk.summary` says how many of the 4 targets it reached and how often it fell.

```sh
curl -s -X POST https://first-steps-1122.algovivo.com/api/creatures/check -H 'content-type: application/json' --data @creature.json
curl -s -X POST https://first-steps-1122.algovivo.com/api/creatures -H 'content-type: application/json' -H "authorization: Bearer $TOKEN" --data @creature.json
```

## The format

```json
{
  "name": "my creature",
  "data": {
    "cells":   [{"pos": [x, y, z]}, ...],
    "tets":    [[a, b, c, d], ...],
    "muscles": [[a, b], ...]
  },
  "frame": {"center": i, "forward": j, "up": k}
}
```

- **cells**: the mesh's vertices. `y` is up, `x` is forward, `z` is sideways. The floor is at whatever height the
  lowest vertex is; the body is placed on it, centered, before it walks.
- **tets**: tetrahedra, four vertex ids each (0-based, into `cells`). Every vertex must be in some tet, and the tets
  must form one piece, joined through shared faces (a shared face means the same three vertex ids).
- **muscles**: pairs of vertex ids. Each must be an edge of some tet; the simulator drops any that is not. A muscle
  contracts and relaxes as the brain says. Make plenty of them: more than half of the edges, through the legs and
  the body, is typical.
- **frame** (optional): three vertex ids that define the creature's own axes. `center` near the middle of the body,
  `forward` in front of it at about the same height, `up` above it. The brain sees the world in this frame, and the
  course's targets are placed by it (the first one is straight ahead along center→forward). Left out, the server picks
  center, forward and up among the vertices on the midplane `z = 0`.

Leave out any brain: the server gives a random one with one output per muscle.

## The rules the check applies

Errors refuse the body; warnings are only advice. Every error and warning comes in `issues` with a `code`, the `ids`
it is about and a `fix`.

- Size: at most 400 vertices, 2000 tets and 2400 muscles, and at most 4 across on any axis. Bodies about 1 to 2
  across walk best.
- Tets right side out: `(b - a) · ((c - a) × (d - a)) > 0`. Swap two ids of a tet that is inside out.
- Tets not too flat: quality at least 0.1 (1 is a regular tet, 0 a flat one), and no more than 10% of them under 0.2.
  Evenly spaced vertices make good tets; long thin ones and nearly flat slivers make the simulation unstable.
- Surface edges at most 0.7 long, ideally about 0.3. Edges and muscles at least 0.02.
- The frame's three vertices apart and not in a line, with `up` not below `center` (a body whose up is below its center
  counts as fallen).

An upload that fails the check is answered with status 422 and the same report in `detail`:

```json
{"detail": {"message": "the body fails the mesh check (1 error): ...", "ok": false,
            "errors": ["..."], "warnings": [], "stats": {...},
            "issues": [{"level": "error", "code": "sliver", "message": "...", "fix": "...", "ids": [12]}]}}
```

## What makes a good walker

- Legs or limbs that reach the floor, a few tets thick, with muscles along them.
- A body wider than it is tall tips over less. Very tall, thin bodies fall a lot.
- Left-right symmetry (mirror in `z`) usually helps.
- Start from the quadruped below and change one thing at a time: the outline, the leg lengths, the width.

## A quadruped to start from

This script (no libraries) builds a quadruped like jb-g: a side outline of 15 points copied into 5 slices across the
body, the outer slices narrower and keeping only the lower body, and four legs pushed down from the outer slices. It
prints the upload's JSON: `python3 quadruped.py > creature.json`. The knobs are at the top: the outline, the triangles,
`slices`, `depth`, `side`, `frontLen`, `rearLen`, `taper`. Its output passes the check and reaches all 4 targets.

```python
# a quadruped like jb-g: a 2D side outline (cells and triangles) copied into 5 slices across the body, the outer
# slices narrower and keeping only the lower body, and four legs grown down from the outer slabs. no libraries.
#   python3 quadruped.py > quadruped.json
import json, math

# the side outline: x forward, y up, about 1.4 long and 1.2 tall
outline = [[0.52, 0.36], [-0.24, 0.17], [0.34, 0.09], [-0.34, -0.18], [-0.26, 0.63], [0.2, 0.59], [0.27, -0.27],
           [-0.59, 0.11], [0.09, 0.33], [0.68, -0.19], [0.39, -0.52], [-0.69, -0.27], [-0.44, -0.54], [0.0, -0.07],
           [-0.03, -0.47]]
triangles = [[9, 2, 0], [7, 3, 1], [13, 3, 1], [13, 8, 1], [9, 6, 2], [13, 6, 2], [13, 8, 2], [11, 7, 3], [12, 11, 3],
             [14, 12, 3], [14, 13, 3], [10, 9, 6], [14, 10, 6], [14, 13, 6], [7, 4, 1], [8, 4, 1], [8, 2, 0], [8, 5, 0],
             [8, 5, 4]]
# the triangles the two outer slabs keep: the lower body, so the back is narrower than the belly
outer = [i for i, t in enumerate(triangles) if not {0, 4, 5, 8} & set(t)]
frontLeg, rearLeg = (10, 9), (12, 11)  # the bottom edges the legs grow from
slices, depth, side = 5, 1.1, 0.75  # slices across (odd), body width, outer slices' scale
frontLen, rearLen, taper = 0.3, 0.35, 1.2  # leg lengths, foot size relative to the hip
frame2d = {"center": 13, "forward": 9, "up": 8}  # on the midplane

n = len(outline)
cx, cy = (sum(p[k] for p in outline) / n for k in (0, 1))
pos = []
for s in range(slices):
    t = abs(s - (slices - 1) / 2) / ((slices - 1) / 2)
    scale = 1 + (side - 1) * t
    z = -depth / 2 + depth * s / (slices - 1)
    pos += [[cx + (x - cx) * scale, cy + (y - cy) * scale, z] for x, y in outline]
at = lambda i, s: i + s * n

def vol(t):
    a, b, c, d = (pos[i] for i in t)
    u, v, w = ([q[k] - a[k] for k in range(3)] for q in (b, c, d))
    return u[0] * (v[1] * w[2] - v[2] * w[1]) - u[1] * (v[0] * w[2] - v[2] * w[0]) + u[2] * (v[0] * w[1] - v[1] * w[0])

def prism(bottom, top):
    # a triangular prism as 3 tets, its vertices taken in a fixed order so neighbors split shared faces alike
    return [[bottom[0], bottom[1], bottom[2], top[0]], [bottom[1], bottom[2], top[0], top[1]], [bottom[2], top[0], top[1], top[2]]]

tets = []
slabs = slices - 1
for s in range(slabs):
    for i, tri in enumerate(triangles):
        if s in (0, slabs - 1) and i not in outer:
            continue
        order = sorted(tri) if s < slabs / 2 else sorted(tri, reverse=True)
        tets += prism([at(v, s) for v in order], [at(v, s + 1) for v in order])

edges = {frozenset((t[a], t[b])) for t in tets for a in range(4) for b in range(a + 1, 4)}

def leg(a, b, s, length):
    # the quad the edge spans across slab s, pushed straight down; split along the diagonal the body already has there
    quad = [at(a, s), at(b, s), at(b, s + 1), at(a, s + 1)]
    mx, mz = sum(pos[v][0] for v in quad) / 4, sum(pos[v][2] for v in quad) / 4
    foot = []
    for v in quad:
        pos.append([mx + (pos[v][0] - mx) * taper, pos[v][1] - length, mz + (pos[v][2] - mz) * taper])
        foot.append(len(pos) - 1)
    k = 0 if frozenset((quad[0], quad[2])) in edges else 1
    for tri in ([0, 1, 2], [0, 2, 3]) if k == 0 else ([0, 1, 3], [1, 2, 3]):
        order = sorted(tri, key=lambda j: quad[j])
        tets.extend(prism([foot[j] for j in order], [quad[j] for j in order]))

for s in (0, slabs - 1):
    leg(*frontLeg, s, frontLen)
    leg(*rearLeg, s, rearLen)
tets = [t if vol(t) > 0 else [t[1], t[0], t[2], t[3]] for t in tets]

# drop the vertices no tet uses (the outer slices' back) and number the rest from 0
used = sorted({v for t in tets for v in t})
new = {v: i for i, v in enumerate(used)}
tets = [[new[v] for v in t] for t in tets]
edges = {frozenset(e) for t in tets for e in ((t[0], t[1]), (t[0], t[2]), (t[0], t[3]), (t[1], t[2]), (t[1], t[3]), (t[2], t[3]))}
# muscles: every edge of the outline's triangles on every slice, every link between slices, and the legs' edges
want = {frozenset((at(a, s), at(b, s))) for s in range(slices) for tri in triangles for a, b in ((tri[0], tri[1]), (tri[1], tri[2]), (tri[0], tri[2]))}
want |= {frozenset((at(i, s), at(i, s + 1))) for s in range(slabs) for i in range(n)}
want = {frozenset(new[v] for v in e) for e in want if all(v in new for v in e)}
legs = {frozenset(e) for e in edges if any(v >= len(used) - 16 for v in e)}
muscles = sorted(sorted(e) for e in (want & edges) | legs)
mid = (slices - 1) // 2
frame = {k: new[at(v, mid)] for k, v in frame2d.items()}
print(json.dumps({"name": "quadruped", "data": {"cells": [{"pos": [round(x, 4) for x in pos[v]]} for v in used],
                                                "tets": tets, "muscles": muscles}, "frame": frame}))
```
