anime-eye-mapping

Community@xinsong854/anime-eye-mapping
Community skill — not reviewed. It was shared by 安诺涅 and has not been checked by Neta. Read SKILL.md below before letting an agent use it.
Installation
npx -y @neta-art/neta-search-cli@latest skills add @xinsong854/anime-eye-mapping
Summary

Make a drawn character's eyes look around, follow your cursor or phone tilt, or turn into a candy ball.

  • Starts from one picture of your character and turns the drawn eye into a round eyeball. Their own iris colour, rings and highlights stay exactly as drawn.
  • Comes as a web page where the eyes follow the cursor or the phone's tilt, or as a still strip of three looks: left, center, right.
  • Can slide one steady eyeball across a montage of different characters, or make an eye into a glass candy or sphere.
  • Includes a drag-and-adjust aligner to nudge the eye points by hand and preview the three looks live, if the automatic fit is off.
  • Works best with a clear, open-eyed character at high resolution. Closed eyes, glasses, heavy bangs or sharp side profiles need extra care.
SKILL.md
# 动漫眼睛:对准、拉成正圆、做成会动的球

Read this file fully before writing any file or generating anything. The numbers below are measured, not guessed; change one only with a QA run that shows the change is better.

**Reply in the user's language** (Chinese to a Chinese user). Every string the user sees in the deliverable — buttons, warnings, the aligner's readouts — follows the user's language too.

**What this skill is for.** A drawn eye is an ellipse in perspective, partly hidden by lids, with its own colour layers. To make it *move* — follow a cursor, follow the gyroscope, slide across a montage, turn into a candy — you must first turn that ellipse into a **round, complete eyeball texture**. This skill does that by *copying* the drawing (never repainting it), so the character keeps their exact iris colour, rings, highlights and pupil, and no two characters end up looking the same.

## Deliver — what the user gets, and how it reaches them

| Kind | What it is | How it is handed over |
|---|---|---|
| **web work** | a page (or minitool) where the eyes move | `neta work init` (or use the work's existing folder) → build `site/` → `neta work publish web <work> --from <dir>`; then hand over the **public URL** on its own line through the interaction-components skill |
| **minitool package** | a zip for 小红书, if the work is one | run the work folder's own `build_minitool.mjs`, then the usual upload / preview / submit flow |
| **image** | aligned eyeball, 3-look strip (`l / c / r`), or a frame sequence | save under the work's folder and give the file as a link |
| **json points** | `{mesh, sock}` for reuse | save next to the page and inline the path in the reply |

Say which kind it is before starting. A page is not delivered until it loads with the eyes animating in it; a strip is not delivered until you have looked at the three looks (the ball must sit in the socket in all three).

## Ask first — only when it changes what gets built

- **Which character / which image** (and whether the original resolution is available). Counts as given when the user names a work, an attached file, or a path that exists.
- **What the eyes must do** — follow the cursor, follow the phone's tilt, slide across several characters, become an object (candy / orb), or just be aligned and exported. Counts as given when the request names one of these, or says "you decide" (then pick the one the page already suggests).
- **Where it lives** — an existing work to repair, or a new one. Counts as given when the user names the work; a new one otherwise.

All given → build straight to delivery, no questions. Missing the image → ask once, in one line, and stop.

## 1. The whole pipeline

```
image ──► face detect (optional) ──► iris ellipse ──► eye socket ──► prep ──► draw / animate / export
          eye-detect.js                eye-mesh.js      eye-ball.js    (ball, clean, shade, face-with-hole)
```

1. **Find the eye.** `scripts/eye-detect.js` (animeface-2009, MIT, weights in `scripts/animeface.png`) gives `{z, w, reye, leye, nose, mouth, chin}` per face. `reye[0..1]` / `leye[0..1]` are the **eye centres**, `[2..3]` half sizes. Keep faces with `z ≥ 0.5`, take the biggest, and start from the eye with the larger box. If no face: ask the user to click the pupil — the rest of the pipeline works the same.
2. **Fit the iris.** `EY.eyestyle.autoMesh(img, {x, y, r, k, a, rough}, tight)` → `{px, py, a, b[8]}`: pupil centre, the "up" direction, and 8 rim points on the iris edge.
3. **Find the socket.** `EY.eyes.autoSocket(img, mesh)` → 12 control points of the visible eye opening (inside the lid line, **including the lashes**).
4. **Prepare layers.** `EY.eyes.prep({img, mesh, sock})` → `R = {ball, clean, shade, src, poly, white, f, hidden, ...}`. `hidden` = how much of the iris was under a lid (filled by mirroring).
5. **Draw.** `EY.eyes.draw(ctx, {R}, {ax, ay, Rs, look, persp, sphere, flip})`.

Load order in a page:

```html
<script src="scripts/eye-mesh.js"></script>   <!-- EY.eyestyle -->
<script src="scripts/eye-ball.js"></script>   <!-- EY.eyes -->
<script src="scripts/eye-detect.js"></script> <!-- GY.face, optional, needs http:// for the weights png -->
```

Both scripts are plain Canvas 2D, no network, no model, Chrome 61-safe. `tools/align.html` is the human-in-the-loop aligner (drag points, lasso, live 3-look preview, copies the json). `tools/qa.mjs` is the self-check.

## 2. Aligning one eye (the part users fight with)

### Iris (`autoMesh`)
- **Seed radius must be the iris radius, not the pupil.** The walk is clamped to `0.72–1.32 × seed` (`0.80–1.22` when the guess is trusted), so a seed at the pupil can never reach the rim. In the aligner, the seed is what the user drags out; from a face box it is `max(eyeW, eyeH) * 0.62`.
- The centre is refined by **mean shift** over "iris-like" pixels (not skin, not sclera, not pure-black lash), capped at **0.12 r** for a user-clicked centre and **0.45 r** for a face-box centre (`sel.rough`). Without the cap, a half-closed eye drags the centre into the visible half and everything after is wrong.
- The **circle search** (outer ring brighter than inner, 30th percentile + median over the lower 240°) runs **only when `sel.rough`**: it fixes a face box that lands on the upper lid, but on a clicked centre it happily locks onto the lash line and reports a radius half the real one. Candidates are validated (outside brighter by > 4 L, inside not mostly lash) before being accepted.
- The rim walk is 16 directions from `0.6 r` outward, step `0.025 r`, stopping on: a dark line (`L` 22 below the local iris, or < 30), 2 consecutive sclera/skin samples, or 3 consecutive steps with `ΔE > thr`. **`thr = max(16, spread × 2.2, 0.4 × ΔE(iris, [email protected]–1.45 r))`** — the third term is what stops a pale or banded iris from stopping at its own inner ring (that bug made pale eyes come out at 0.72 r).
- Then median + smooth over the 16 radii; the 8 published points are every other one. Pupil centre = centroid of the darkest 10% inside the middle 45% circle, moved **half** way, and `sel` is updated with it (the rim points are built around `sel`; forgetting this offsets the whole circle — a real bug that showed as 48 px on one side and 78 px on the other).
- User fix-ups, in order of usefulness: **drag one rim point**, then `贴到虹膜边` again (re-fits from the current effective radius), then `大小/倾斜/朝上` sliders, then a fresh circle.

### Socket (`autoSocket`)
- 24 directions from the iris centre; step `0.03 r`. Start just inside the iris rim (`0.84–0.97 r`) and walk out.
- `lineThr = clamp(min(surroundingL − 26, 62), 18, 62)` — derived from the median luminance of a ring at `3.3 r`, so grey-lined pale art still registers a line while dark hair does not.
- **Skip the iris's own rim**: a dark run that starts before `1.06 r` and ends before `1.2 r`, in the side/lower directions, is the iris outline, not the socket.
- The lash is a band, not a line: after the line, keep walking while it stays dark (tolerance `lineThr + 12`, gap ≤ 2 steps), and stop at its **outer** edge, capped at `+0.5 r` above / `+0.35 r` below. This is why the socket encloses the lashes — see the layering rule below.
- Sclera that fades into skin: sample the **cheek** colour at `2.4–3.4 r` below the eye and require 2 consecutive samples brighter/greyer than skin before believing it.
- Directions that never met a line are **interpolated from their neighbours and clamped to 1.12 ×** the interpolation — never trusted at face value.
- **Half-closed / squinting eyes** (lid covering > ~35%): the outward walk starts *on the skin*. The code detects this (the start sample looks like skin) and walks **inward** looking for the lid line; the socket then follows the lid, and the covered iris is filled by mirroring. Before that fix, a half-closed eye got a socket that reached up into the forehead, `hidden` read 0% and the ball showed skin at its centre.
- Mask edges are pulled in by 1.5 px so the anti-aliased eye line is not eaten.

### Parameters that matter (all in `r` = mean iris radius)

| Thing | Value | Why |
|---|---|---|
| crop around the eye | `x ± 9 r`, `y −12 r … +12 r` | lashes and brow shading stay in frame |
| upscale | iris radius to ≥ 72 px, ≤ 4×, longest side ≤ 1600, in 2× steps | one big jump blurs; 2× steps + unsharp keep the rings |
| eyeball texture | 640² disc, sampled at `0.95 r` | 0.95 keeps sclera out of the rim |
| hidden iris | mirrored across the eye's horizontal axis, else the ring average | a half-lidded eye needs a whole ball |
| sclera colour | top/bottom medians of the brightest half inside the socket | one flat colour looks dead; two values give the lid shadow something to grade |
| lash layer | from the socket edge inward, dark & connected, depth ≤ `0.5 r` | lashes must sit **in front of** the ball |
| draw order | sclera → **ball** → lid shadow (multiply) → face (with a hole) | the ball must be behind the lashes and in front of the sclera |

## 3. What the layers are for

- **`ball`** — the round eyeball. Centre = pupil. Generate it once per eye; it does not move with the face.
- **`clean`** — the sclera with the iris removed, flat-filled from the sampled colour. It **follows the face transform**, so it stretches with perspective and squashes when the eye narrows.
- **`shade`** — the upper-lid shadow as a multiply layer, clipped to the socket. It follows the face, so the ball always sits under the lid's shadow.
- **`src`** — the face crop with the socket **cut out** (`alpha × (1 − mask × (1 − lash))`). The lashes and the eye line stay.
- **`sock` polygon** — used for clipping, for the hole, and for `lookOffset` (how far the pupil may travel so it still shows ≥ half).

**Why cut the socket instead of drawing the eye on top?** Because you would have to paint sclera, lids and lashes yourself, and the eye immediately looks pasted on. Cutting a hole keeps every drawn pixel of the lash, eye corner and lid, and the ball shows through like a real eye behind a mask.

**Perspective correction (`faceMatrix`).** The face is scaled along the eye's own left-right and up-down axes so the iris ellipse becomes a circle — `k = 0.8` means 80% of the way to circular, and the aspect ratio is clamped to 1.35 so a 3/4 view does not explode. Area is preserved (mean radius = `Rs`). Without this, a tilted face shows an oval eyeball.

**Looking around.** `lookOffset(R, dir)` moves the anchor by `reach − 0.5 × irisRadius` along `dir`, clamped to `0.3–0.95 r` (vertical ≤ `0.55 r`). Then either the **ball** moves (pupil tracking inside a still face) or the **face** moves the other way (the eyeball-sliding illusion: pin the ball to a fixed screen point so only the face slides past it).

**Sphere shading.** `shadeBall` darkens the rim (`0.5 × strength`), adds a soft upper-left glow and one small specular. Keep the highlight *on the ball*, not baked from the drawing — the drawing's own highlight is already in the texture and two highlights kill the joke.

## 4. Recipes

- **Eyes that follow the cursor / gyroscope**: keep one `R` per eye, call `draw` each frame with `look = lookOffset(R, dir)`; the face stays put and only the ball slides. Blend by 0.25 of the offset so it reads as attention, not as a googly eye.
- **Eyeball sliding across a montage** (one ball, many faces): draw `sclera` + ball at a **fixed screen anchor**, then the face translated so `mesh.px + look` lands on that anchor. Hard-cut between faces, keep the ball still; the illusion lives in the pan. Full recipe and the measured camera numbers: `reference/recipes.md`.
- **Eye as a glass candy / orb** (`EY.eyestyle.makeTex` → circular texture, then sample it inside a sphere by radius-from-centred-axis): see `reference/eyeball-sphere.md`.
- **Sprite / still export**: `draw` three times with `look = l, c, r` into one strip — that is the whole "looking left/right/up/down" sheet.

## 5. QA — run this, do not eyeball it

```bash
node tools/qa.mjs        # 6 synthetic eyes, 58 checks, writes tools/qa-report.json + tools/qa-report.png
```

The fixtures are drawn in code (skin, lid, lash, banded iris, pupil, highlight) so nothing copyrighted is involved and the truth values are exact. Pass criteria, all enforced by the script:

| Check | Threshold |
|---|---|
| iris centre | ≤ 25% of the iris radius (≤ 30% when a lid covers it) |
| iris radius | within 20% |
| rim fit | median error ≤ 16% |
| one ring of the warped texture keeps one colour | max channel sum diff < 40 / 765 (proves the ellipse was actually circularised) |
| socket | median error ≤ 16%, at most 3 of 12 points > 20% off |
| half-lidded | top of socket follows the lid; `hidden` between 8% and 80% |
| ball centre | is the pupil (L < 70), even when 24% of the iris is hidden |
| ball edge | alpha 255 all the way out (no mipmap dark fringe) |
| drawn frame | ball lands on the anchor; canvas fully opaque |
| face-box centring | a centre 45% off is pulled back to ≤ 25% |

Current result: **58/58**, ≈ 9 s for all six fixtures in headless software rendering (≈ 0.6–2.1 s per `prep` there; a desktop Chrome is several times faster, a 4× throttled phone 2–4× slower — for a live page, `prep({fast:true})` while dragging and the full pass on release).

If a real image fails, do not loosen a threshold: fix the seed radius, drag the rim points, or use `tools/align.html` and read the two numbers it shows (`hidden`, upscale) to decide.

## 6. Known limits (say these out loud instead of shipping a broken eye)

- **Closed eye** — no iris to find. Animate eyelids instead, or ask for an open-eye frame.
- **Profile / 3/4 beyond ~45°** — the far eye is a sliver; fit it by hand or leave it still.
- **Glasses** — the frame crosses the socket; the lash walk may stop on it. Drag the socket points in by hand.
- **Heavy bangs over one eye** — the visible part is too small; `hidden` > 55% and the mirrored texture looks wrong. Show a warning (the aligner does) and let the user reposition.
- **Face detect on pale, backlit or heavy-filter art** — `eye-detect.js` already stretches levels before detecting; if `z < 0.5`, fall back to a click. Full-body art can have a bow or a hand detected as a face — always let the user re-pick.
- **Very small eyes** (< 26 px radius) — usable but soft; prefer the original resolution over a screenshot.

## 7. Out of scope / protected files

- **Never** edit or delete: the world's `world/` materials, `WORLD.md` (name, genre, visual style, slug), `.neta/`, other works' `site/`, or this skill's installed copy under `.agents/skills/` (fix things by re-running the tool, not by patching scripts at runtime).
- Do not restyle or rebuild an existing work that merely *contains* eyes; this skill only adds or repairs the eye pipeline the user asked for.
- Do not repaint the eye "to look better" — the rule is copy, circularise, clarify. If the user wants a colour change, use the texture's own palette (hue/sat/bright in `makeTex`), never a hand-drawn replacement.
- Do not add extra deliverables (promo videos, extra sprite sheets) that were not asked for.

## 8. Licence

`scripts/eye-detect.js` is a JS port of **animeface-2009** by nagadomi, MIT — the copyright notice is inside the file and must stay. `scripts/animeface.png` is that model's weights (1.28 MB, half precision, CRC-checked). Everything else here is original.