diff --git a/.agents/skills/puppetcontrol/SKILL.md b/.agents/skills/puppetcontrol/SKILL.md index 98f2c4c..d28ce10 100644 --- a/.agents/skills/puppetcontrol/SKILL.md +++ b/.agents/skills/puppetcontrol/SKILL.md @@ -14,15 +14,16 @@ Read repo-root AGENTS.md, docs/TECHNICAL_CONCEPT.md, and docs/CHARACTER_IMPORT.m 5. Stage the proposal using `node dist/cli/index.js character landmarks stage --proposal `. Rev2D validates the isolated candidate and returns a work/overlay.png. **Actually inspect the overlay** before `character landmarks accept --candidate --reviewed`. Accepting replaces avatar.json with a backup and revokes all existing pose approvals. Never auto-pass --reviewed solely because a validator passed. 6. Build using node dist/cli/index.js character build (use --force if prior output exists). Inspect any geometryWarnings, particularly BODY_PIVOT_TOO_LOW and IRIS_LANDMARK_MISSING; these do not replace pixel inspection. Source/landmark/model/texture hashes are recorded in avatar-build.json and scene preflight rejects stale assets. Inspect every returned review/poses.png, turn.png, eyes.png and mouth.png. If incorrect, repair avatar.json and rebuild using --force; this resets the generated manifest and any edited scaffold. 7. To test optional drawn eye/mouth variants on a built actor, request edit masks, locally supply reviewed `variants/.png`, and explicitly import. With reviewed closed+half eye drawings, `character variants import eyes_closed eyes_half --experimental-short-fade --reviewed-art` shortens fade windows but makes poses change faster and may still ghost; it is a visual experiment, never a default or automatic quality fix. The import revokes prior approval and refreshes provenance only after re-rendering review sheets. -8. For a deliberately non-blended eye-art experiment, `character variants import eyes_closed eyes_half --experimental-stepped-eyes --reviewed-art` selects only one complete eye appearance outside tiny threshold windows. It can remove ghosted doubled lashes but creates visible pose pops; do not call it seamless or automatically approve. See `docs/EYE_TRANSITIONS.md` and compare actual frames. -9. Before approving a verified imported rig, run `node dist/cli/index.js character qa blink ` to generate an ordered 25-frame actual eyelid transition contact sheet (`blink-eyes.png` and `blink-full.png`); inspect EyeOpen=0.19 and 0.69 and the real eye artwork seams. The QA report flags motion stalls but never passes visual approval. Also run `character qa blink --timed` for a 36-frame synthetic 30 FPS video and review the actual moving result. Different fade policies may produce identical frames when their transition windows fall between sampled timestamps; see `docs/EYE_TIMING.md`. -10. A successful build intentionally leaves character.json with approved:false. A --force rebuild revokes approval *before* writing model/texture files, even if the rebuild later fails. Only after actual visual QA may an agent/user explicitly run `node dist/cli/index.js character approve --reviewed` (the flag is an acknowledgement, not evidence of review) to record neutral-pose approval. If there are torn eyelids, missing areas, extra contours or identity drift, LEAVE IT UNAPPROVED and report what needs correction. -11. For a reviewed reusable rig, use `node dist/cli/index.js scene new --character --seconds 12 --fps 15` to create a strict editable scene. Reuse the same character file in a second scene without rebuilding artwork. The generated preview-scene.json is also editable. Use node dist/cli/index.js scene validate and scene plan before rendering. Preview PNG frames, inspect key timestamps, then render and inspect the MP4. -12. Within a compatible shared rig, semantic pose events may interpolate through validated parameter presets (the neutral-to-pointing demo uses shoulder and elbow controls). Distinct pose models require explicit scene camera cuts; an authored bridge is NOT implemented. Never silently crossfade meshes or call a body cut a smooth physical transition. -13. For speech, prepare WAV, install Rhubarb separately, and use node dist/cli/index.js audio align --out [--binary ]. For exact-byte continuity, optionally run `audio bind --cues --out ` and include `--binding ` in `scene new`; bound scenes fail validation/render if cue or voice bytes change. A `scene new` voice track requires both `--voice` and the actual `--cues` file; no fabricated speech sync. Reference audio.path, audio.startMs and audio.cuesPath from the scene; review the actual mouth/audio timing. -14. Do not commit private character illustrations, full generated models, user voice recordings or secrets without checking redistribution rights. Demo:avatar generates pinned MIT-licensed sample artwork into ignored .cache. -15. For animation QA, compare real ordered PNGs with `node dist/cli/index.js character qa sequence ... [--region x,y,w,h] [--control-values v0,v1,...] [--cut-after i,j]`. Supply sampled control values when investigating invisible or stalled motion; label known cuts. Inspect the PNGs/video and report possible ghosting even if the motion statistics look normal. The QA report is not an approval. -16. Verified imported rigs and explicitly bound voice tracks are now consumed from fresh per-render copies, hashed against recorded inputs; see `docs/RENDER_INTEGRITY.md`. This is not protection against a malicious same-user process modifying temporary files, nor proof of visual quality. -17. State what actually rendered and which controls remain unsupported. Do not claim a flat PNG is automatically converted into production-quality animation without landmark review. +8. For a compatible imported avatar whose extracted lash warps look unnatural, optionally run `character eyes vectorize --experimental`. This creates a **new provenance-tracked vector eyelid model**, preserves source drawings, revokes existing approval, and renders real 30 FPS blink evidence. It uses the eye-mask vertices for a continuously deforming line, not alpha-switching; styling still needs human review. See `docs/VECTOR_EYELIDS.md`. +9. For a deliberately non-blended eye-art experiment, `character variants import eyes_closed eyes_half --experimental-stepped-eyes --reviewed-art` selects only one complete eye appearance outside tiny threshold windows. It can remove ghosted doubled lashes but creates visible pose pops; do not call it seamless or automatically approve. See `docs/EYE_TRANSITIONS.md` and compare actual frames. +10. Before approving a verified imported rig, run `node dist/cli/index.js character qa blink ` to generate an ordered 25-frame actual eyelid transition contact sheet (`blink-eyes.png` and `blink-full.png`); inspect EyeOpen=0.19 and 0.69 and the real eye artwork seams. The QA report flags motion stalls but never passes visual approval. Also run `character qa blink --timed` for a 36-frame synthetic 30 FPS video and review the actual moving result. Different fade policies may produce identical frames when their transition windows fall between sampled timestamps; see `docs/EYE_TIMING.md`. +11. A successful build intentionally leaves character.json with approved:false. A --force rebuild revokes approval *before* writing model/texture files, even if the rebuild later fails. Only after actual visual QA may an agent/user explicitly run `node dist/cli/index.js character approve --reviewed` (the flag is an acknowledgement, not evidence of review) to record neutral-pose approval. If there are torn eyelids, missing areas, extra contours or identity drift, LEAVE IT UNAPPROVED and report what needs correction. +12. For a reviewed reusable rig, use `node dist/cli/index.js scene new --character --seconds 12 --fps 15` to create a strict editable scene. Reuse the same character file in a second scene without rebuilding artwork. The generated preview-scene.json is also editable. Use node dist/cli/index.js scene validate and scene plan before rendering. Preview PNG frames, inspect key timestamps, then render and inspect the MP4. +13. Within a compatible shared rig, semantic pose events may interpolate through validated parameter presets (the neutral-to-pointing demo uses shoulder and elbow controls). Distinct pose models require explicit scene camera cuts; an authored bridge is NOT implemented. Never silently crossfade meshes or call a body cut a smooth physical transition. +14. For speech, prepare WAV, install Rhubarb separately, and use node dist/cli/index.js audio align --out [--binary ]. For exact-byte continuity, optionally run `audio bind --cues --out ` and include `--binding ` in `scene new`; bound scenes fail validation/render if cue or voice bytes change. A `scene new` voice track requires both `--voice` and the actual `--cues` file; no fabricated speech sync. Reference audio.path, audio.startMs and audio.cuesPath from the scene; review the actual mouth/audio timing. +15. Do not commit private character illustrations, full generated models, user voice recordings or secrets without checking redistribution rights. Demo:avatar generates pinned MIT-licensed sample artwork into ignored .cache. +16. For animation QA, compare real ordered PNGs with `node dist/cli/index.js character qa sequence ... [--region x,y,w,h] [--control-values v0,v1,...] [--cut-after i,j]`. Supply sampled control values when investigating invisible or stalled motion; label known cuts. Inspect the PNGs/video and report possible ghosting even if the motion statistics look normal. The QA report is not an approval. +17. Verified imported rigs and explicitly bound voice tracks are now consumed from fresh per-render copies, hashed against recorded inputs; see `docs/RENDER_INTEGRITY.md`. This is not protection against a malicious same-user process modifying temporary files, nor proof of visual quality. +18. State what actually rendered and which controls remain unsupported. Do not claim a flat PNG is automatically converted into production-quality animation without landmark review. Keep edits small and testable. Run npm run verify and inspect visual evidence for any animation/asset changes. \ No newline at end of file diff --git a/README.md b/README.md index ea5a6e2..ec4cd6a 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,8 @@ The long-term goal: **generate artwork when necessary, animate and reuse it inde - An optional **experimental** short-fade profile for imported half/closed eye drawings; avoids prolonged duplicate lash outlines at the cost of faster pose changes, revokes approval and regenerates review sheets. - Local PNG pixel and ordered-frame QA (full frame or explicit region) reports RGB activity, unexpected transparency, candidate motion jumps and changed-control stalls; these metrics never auto-approve a rig. - Import review can render a 25-frame parameter-sweep contact sheet and a separate **36-frame, 30 FPS synthetic timed-blink MP4** with motion warnings; see [Character Review](docs/CHARACTER_REVIEW.md) and [Time-domain Blink QA](docs/EYE_TIMING.md). The opt-in [stepped-eye experiment](docs/EYE_TRANSITIONS.md) removes sampled opacity ghosting but does not provide a seamless morph. The two modes even produced byte-identical frames in one real-time test. -- Imported flat-image actors start with narrower editable head/gaze motion limits, with consistent vertical look direction and unchanged amplitude for existing layered rigs; see [Look Motion](docs/LOOK_MOTION.md). +- Imported flat-image actors start with narrower editable head/gaze motion limits; see [Look Motion](docs/LOOK_MOTION.md). +- Optional **experimental continuous vector eyelids** replace warped raster lash outlines with thin mask-following Rev2D mesh strips while keeping the iris clipped. This improves one real Hana sample without approval and requires artistic review; see [Vector Eyelids](docs/VECTOR_EYELIDS.md). - Optional SHA-256 Rhubarb cue bindings can detect when audio or mouth-cue bytes are replaced after alignment; a bound scene fails validation/render instead of silently using stale lip sync. - Agent-readable CLI output, tests and CI. @@ -73,6 +74,8 @@ The sample uses Rev2D's own **Hana** rig from the pinned MIT-licensed upstream c [Watch the 30 FPS timed-blink diagnostic](docs/media/hana-timed-blink-30fps.mp4) (1.2 seconds, silent 36-frame unapproved imported art test; not a polished animation). +[Watch the continuous vector-eyelid experiment](docs/media/hana-vector-eyelids-30fps.mp4) (1.2-second 30 FPS diagnostic; less distorted lash geometry on one MIT sample, still requires visual approval). + For the first reproducible **one-character video workflow**, see [First Video](docs/FIRST_VIDEO.md). With an already reviewed rig, run `character approve --reviewed` for provenance-tracked imported characters, then `scene new --character `, `scene validate` and `scene render`. Create another scene with the same character path to reuse its rig, without regenerating artwork. To attach your own voice, use a real WAV and aligned Rhubarb cue JSON; no TTS is implied. Run a custom scene through the CLI: diff --git a/docs/CHARACTER_REVIEW.md b/docs/CHARACTER_REVIEW.md index 54f8e95..f4c777f 100644 --- a/docs/CHARACTER_REVIEW.md +++ b/docs/CHARACTER_REVIEW.md @@ -43,7 +43,15 @@ Another **opt-in, sharp-switch** experiment avoids showing two eyelid drawings s node dist/cli/index.js character variants import avatars/portrait eyes_closed eyes_half --experimental-stepped-eyes --reviewed-art ~~~ -Choose **only one** experimental profile. Every import revokes earlier approval, regenerates review sheets and refreshes fingerprints. See [EYE_TRANSITIONS.md](EYE_TRANSITIONS.md) for the actual rendered comparison and trade-offs. +Choose **only one** experimental sprite-transition profile. Every import revokes earlier approval, regenerates review sheets and refreshes fingerprints. See [EYE_TRANSITIONS.md](EYE_TRANSITIONS.md) for the actual rendered comparison and trade-offs. + +For a genuinely deforming eyelid outline instead of alpha-switching whole-eye pictures, a separate **opt-in vector-rig** experiment is now available after building the imported character: + +~~~powershell +node dist/cli/index.js character eyes vectorize avatars/portrait --experimental +~~~ + +It uses the existing Rev2D eye-white mask to deform upper/lower lashes continuously, keeps the iris clipped, preserves the previous model, writes new fingerprints, and revokes approval. Unlike the sprite transitions it simplifies the painted lashes; visually inspect the resulting video. See [VECTOR_EYELIDS.md](VECTOR_EYELIDS.md). ## 3. Inspect exact blink transition frames diff --git a/docs/EYE_TIMING.md b/docs/EYE_TIMING.md index 9d8abd6..5989418 100644 --- a/docs/EYE_TIMING.md +++ b/docs/EYE_TIMING.md @@ -61,4 +61,4 @@ These experiments live only in ignored `outputs/qa/eye-hybrid-20261107/` and wer 3. Replay real 15/30/60 FPS performance timelines and compare actual frames across several rights-cleared drawing styles. 4. Preserve the original character's linework and colors, and require explicit human review. No code metric alone may mark an avatar approved. -The next engineering target is **quality-controlled intermediate eyelid artwork or a proper eyelid-specific deforming rig**, not another global opacity/fade profile. +The subsequent [experimental vector-eyelid rig](VECTOR_EYELIDS.md) now supplies a genuine Rev2D eye-mask-following deformable upper/lower lash line, with no raster lash warp. It improves one MIT Hana sample but simplifies the original line art; further character styles and artist review remain required. diff --git a/docs/IMPLEMENTATION_PLAN.md b/docs/IMPLEMENTATION_PLAN.md index dcf7701..b8303ac 100644 --- a/docs/IMPLEMENTATION_PLAN.md +++ b/docs/IMPLEMENTATION_PLAN.md @@ -85,6 +85,7 @@ - [x] Add bounded per-character semantic head/eye look amplitudes with conservative imported-PNG starting values, schema validation, compiler tests and real Hana ±yaw/pitch/gaze frame comparisons. This does not establish visual approval. - [x] Test an optional stepped-eye visibility profile that removes sampled double-sprite ghosting at EyeOpen 0.19/0.69 on refined MIT Hana artwork, with a 25-frame A/B render, explicit abrupt-change warnings and local 45-frame end-to-end smoke video. The source remains unapproved; **this trades ghosting for pose popping**, not a seamless morph. - [x] Add a 36-frame, 30 FPS time-domain blink QA export with deterministic synthetic timing, unique Rev2D state caching, and JSON motion warnings. The actual short-fade and stepped 30 FPS frames were SHA-256 identical for this one schedule, showing threshold tuning alone is insufficient. Four mesh/overlay variants failed visual QA and were not integrated. +- [x] Build an opt-in, provenance-verified **continuous vector eyelid** rig: replace distorted raster lash warps with curved vertex strips driven by Rev2D's existing eye mask, preserving iris clipping and source art. Inspect real 9-state, 30 FPS blink and head/gaze sweeps; 90-frame end-to-end H.264 export verified. The Hana experiment remains unapproved and artists may prefer their own lash styling. - [ ] Produce and visually approve high-quality closed/half eye and mouth artwork; demonstrate seamless real rendered transitions across full blink playback and multiple character styles. The local proof drawing stays unapproved. ## First video milestone — reproducible usable slice (2026-11-07) diff --git a/docs/THIRD_PARTY_NOTICES.md b/docs/THIRD_PARTY_NOTICES.md index 863fb54..7cb3f46 100644 --- a/docs/THIRD_PARTY_NOTICES.md +++ b/docs/THIRD_PARTY_NOTICES.md @@ -5,7 +5,7 @@ - Source project: https://github.com/RevStudio/Rev2D - Pinned source commit: f144581cdf1f12d781379c4df90d262b8c2dfa3d - File: examples/hana/hana.r2d.json in Rev2D upstream -- Use: local demo pose-rig generation, attributed sample MP4, the derived eye-transition crop in `docs/media/stepped-eye-before-after.png`, and the 30 FPS diagnostic preview in `docs/media/hana-timed-blink-30fps.mp4`. PuppetControl's own source code does not bundle the original full Hana model/artwork. +- Use: local demo pose-rig generation, attributed sample MP4, the derived eye-transition crop in `docs/media/stepped-eye-before-after.png`, the 30 FPS diagnostic preview in `docs/media/hana-timed-blink-30fps.mp4`, and the derived vector-eyelid comparison + 30 FPS preview in `docs/media/hana-vector-eyelids-comparison.png` and `docs/media/hana-vector-eyelids-30fps.mp4`. PuppetControl's own source code does not bundle the original full Hana model/artwork. - Original license: MIT License, Copyright (c) 2026 RevStudio. ### MIT License (RevStudio) diff --git a/docs/VECTOR_EYELIDS.md b/docs/VECTOR_EYELIDS.md new file mode 100644 index 0000000..c8db2dd --- /dev/null +++ b/docs/VECTOR_EYELIDS.md @@ -0,0 +1,53 @@ +# Experimental continuous vector eyelids + +**Status:** working, opt-in imported-avatar rigging experiment; artist approval **not automatic**. + +A single-image Rev2D import extracts pixels around each upper/lower eyelid and bends those raster layers as the eye closes. On the imported Hana trial this created sharp triangular lashes, pinched eye corners and pale edges. Changing only the opacity fade or smoothing/capping the raster warp moved these artifacts around rather than fixing them. + +## What is different + +The new rig derives four small, smoothly deforming **vector ribbons** from the upper and lower rows of the *existing* Rev2D eye-white mask. Each row provides matching coordinates at `EyeOpen=1` and `EyeOpen=0`; the engine interpolates vertex positions at intermediate openings. A thin filled lash ribbon follows each curve (one upper and one lower per eye). + +- The **existing iris stays clipped** by the original deformable eye-white mask. +- The old extracted upper/lower lash images and their rim layers are hidden in the derived model, not deleted. +- Existing `eyes_closed`/`eyes_half` sprite overlays are hidden and known mesh-hide bindings restored in the **derived** model. Mouth, head, brows and hair logic remain in place. Smiling-eye sprite rigs are rejected for now rather than silently changing expressions. +- The ribbon's black/brown shade comes from the imported eye-layer metadata, with independently verified left/right mapping. +- The original user images, textures and source model remain present and unchanged. + +This is **genuine continuous vertex deformation within Rev2D**, not an alpha crossfade, still-image replacement, or a replacement renderer. It also simplifies lash styling, so it is unsuitable for every drawing. + +## Run it on one already built imported character + +~~~powershell +node dist/cli/index.js character inspect avatars/portrait/character.json +node dist/cli/index.js character eyes vectorize avatars/portrait --experimental +~~~ + +The command requires a single-pose, provenance-verified imported Rev2D character, a compatible eye mask and both upper/lower eye layers. It validates all vertices, closed/open keyforms, both lash colors, source hashes, and the **pinned** Rev2D backend. It refuses unsupported eye topology, malformed masks, stale assets, existing vector ribbons and smile-eye variants. + +It deliberately **revokes previous approval before publishing** the new model. Its unique `*-vector-eyelids-.r2d.json` file is validated and hashed, the manifest is updated to reference it, and the original model and original user artwork are preserved. A successful operation generates a private `outputs/qa/blink-review//blink-timed-30fps.mp4` plus eye/full contact sheets and motion warnings. It returns the exact paths. + +The current mutation is a local, non-transactional pair of file replacements for the model reference and fingerprint record. An interrupted update can temporarily fail verification, **never implicitly approve** an avatar. Restore the previous verified project copy or explicitly rebuild with `character build ... --force` if that happens. Make a backup of your imported project before experimenting. + +Do not combine the derived vector rig with subsequent drawn-eye variant imports without rebuilding the avatar first; Rev2D's upstream variant importer targets its original model filename. + +## Real sample comparison (matching EyeOpen parameters) + +![Native extracted-lash mesh above; derived vector eyelids below, rendered on the same Rev2D Hana image](media/hana-vector-eyelids-comparison.png) + +*Both rows are actual pinned Rev2D rendered pixels from the MIT-licensed Hana illustration. No external image generation or hallucinated frame retouching. Upper row: original mesh with drawn-eye sprites disabled. Lower: experimental vector strips on the identical original eye-white mask.* + +In this single test, the vector strips eliminate the sharp outward triangular lash spike at `EyeOpen=0.3/0.14` and meet along a cleaner closed curve. They do not exactly reproduce the original painted lashes, and a different style or head angle may expose seams. The line weight and tone still require artistic review. + +[Watch the 30 FPS continuous vector eyelid blink](media/hana-vector-eyelids-30fps.mp4) + +A disposable, unapproved imported Hana project successfully generated the model and hash record with `character eyes vectorize`. An **additional separate QA-only copy** was temporarily marked renderable to exercise the standard first-video path; its 3-second 512×640, 30 FPS, 90-frame H.264 output passed FFprobe acceptance. The real imported test source remains `approved:false`. + +## Remaining gates + +1. Inspect frame-by-frame eyelid curves at 0, 0.1, 0.25, 0.5, 0.75, 1, plus head turns and iris extremes. No metric certifies the art. +2. Review on at least two more independent, rights-cleared styles before considering vector eyelids a broadly suitable default. +3. Add artist-configurable upper/lower lash widths, smooth corners and optional hand-authored details. The test uses fixed widths (upper 2.8 px, lower 1.2 px) and source-derived RGB. +4. Test real natural-speaking videos and eye expressions. This only changes the eyelid line; head/neck/pose transition and lip-sync quality remain separate issues. + +**Always use `character approve --reviewed` only after a person has inspected the actual updated rig's generated frames and its original artwork.** The CLI does not approve anything here. diff --git a/docs/media/hana-vector-eyelids-30fps.mp4 b/docs/media/hana-vector-eyelids-30fps.mp4 new file mode 100644 index 0000000..07561fa Binary files /dev/null and b/docs/media/hana-vector-eyelids-30fps.mp4 differ diff --git a/docs/media/hana-vector-eyelids-comparison.png b/docs/media/hana-vector-eyelids-comparison.png new file mode 100644 index 0000000..06d9ec2 Binary files /dev/null and b/docs/media/hana-vector-eyelids-comparison.png differ diff --git a/src/character/eyelid-vector-workflow.ts b/src/character/eyelid-vector-workflow.ts new file mode 100644 index 0000000..0a3ce7e --- /dev/null +++ b/src/character/eyelid-vector-workflow.ts @@ -0,0 +1,147 @@ +/** + * Non-destructive, approval-revoking publication of an experimental vector + * eyelid rig. The previous rig and all user drawings stay intact; the new + * derived model gets its own filename and fresh exact-byte provenance record. + * + * This is an ARTISTIC experiment, not automatic quality approval. + */ +import { randomUUID } from "node:crypto"; +import { readFile, rename, stat, unlink, writeFile } from "node:fs/promises"; +import { join, resolve } from "node:path"; +import { characterSchema } from "../scene/schemas.js"; +import { + AvatarWorkflowError, checkedPath, pinnedRev2D, runRev2D, +} from "./avatar.js"; +import { + createAvatarBuildRecord, revokeAvatarApprovalBeforeBuild, + verifyAvatarBuildRecord, writeAvatarBuildRecord, +} from "./provenance.js"; +import { createBlinkReview } from "./blink-review.js"; +import { vectorizeImportedEyelids } from "./eyelid-vector.js"; + +const MAX_MODEL = 20_000_000; +const MAX_LAYER_METADATA = 5_000_000; +const HEX = /^#[0-9a-f]{6}$/i; + +async function readBoundedJson(filename: string, bytes: number): Promise { + const file = await stat(filename); + if (!file.isFile() || file.size < 2 || file.size > bytes) { + throw new AvatarWorkflowError("VECTOR_EYELIDS_INPUT_INVALID", + "Missing/oversized Rev2D asset (limit " + bytes + " bytes): " + filename); + } + return JSON.parse(await readFile(filename, "utf8")) as unknown; +} +type ObjectLike = Record; +function obj(value: unknown): ObjectLike | null { + return value && typeof value === "object" && !Array.isArray(value) ? value as ObjectLike : null; +} + +export function vectorEyeColorsFromLayers(value: unknown): { eyeR: string; eyeL: string } { + const eyes = obj(obj(value)?.eyes); + const left = obj(obj(eyes?.imageLeft)?.colors)?.lash; + const right = obj(obj(eyes?.imageRight)?.colors)?.lash; + if (typeof left !== "string" || !HEX.test(left) || + typeof right !== "string" || !HEX.test(right)) { + throw new AvatarWorkflowError("VECTOR_EYELIDS_LASH_COLOR_MISSING", + "Imported Rev2D eye layer metadata needs valid lash colors for both eyes"); + } + return { eyeR: left, eyeL: right }; +} + +export async function createVectorEyelidRig( + projectDir: string, + root = process.cwd(), +): Promise> { + const project = await checkedPath(root, resolve(root, projectDir)); + if (!(await stat(project)).isDirectory()) { + throw new AvatarWorkflowError("VECTOR_EYELIDS_PROJECT_REQUIRED", "Expected imported avatar project"); + } + const characterFile = await checkedPath(project, join(project, "character.json")); + const manifest = characterSchema.parse( + await readBoundedJson(characterFile, MAX_MODEL)); + if (!manifest.provenance || manifest.render?.backend !== "rev2d" || + !manifest.render.modelPath || manifest.poseFamilies.length !== 1 || + manifest.poseFamilies[0]?.modelPath !== manifest.render.modelPath) { + throw new AvatarWorkflowError("VECTOR_EYELIDS_IMPORTED_RIG_REQUIRED", + "Requires one imported, provenance-verified Rev2D avatar and one model"); + } + const verified = await verifyAvatarBuildRecord(characterFile, manifest.render.modelPath); + if (!verified.valid) throw new AvatarWorkflowError(verified.code, verified.message); + const modelFile = await checkedPath(project, join(project, manifest.render.modelPath)); + const layersFile = await checkedPath(project, join(project, "textures", "layers.json")); + const [model, layers] = await Promise.all([ + readBoundedJson(modelFile, MAX_MODEL), + readBoundedJson(layersFile, MAX_LAYER_METADATA), + ]); + const colors = vectorEyeColorsFromLayers(layers); + const transformed = vectorizeImportedEyelids(model, colors); + const backend = await pinnedRev2D(root); + const relModel = manifest.id + "-vector-eyelids-" + randomUUID() + ".r2d.json"; + const derivedFile = await checkedPath(project, join(project, relModel)); + const approved = manifest.poseFamilies.some(p => p.approved); + // Critical ordering: revoke before creating/changing any model assets. + await revokeAvatarApprovalBeforeBuild(characterFile); + const derived = characterSchema.parse({ + ...manifest, + poseFamilies: manifest.poseFamilies.map(p => ({ ...p, approved: false, modelPath: relModel })), + render: { ...manifest.render, modelPath: relModel }, + }); + const tempManifest = characterFile + ".next-" + randomUUID(); + try { + await writeFile(derivedFile, JSON.stringify(transformed.model), { flag: "wx" }); + const check = await runRev2D(backend, ["validate", derivedFile], 90_000) as unknown; + if (!Array.isArray(check) || !check.length || + check.some(item => { + const r = obj(item); + return !r || r.ok !== true || typeof r.errors !== "number" || r.errors !== 0; + })) { + throw new AvatarWorkflowError("VECTOR_EYELIDS_REV2D_INVALID", + "Pinned Rev2D did not validate the derived model with zero errors"); + } + const record = await createAvatarBuildRecord(project, relModel); + // The record and manifest switch are intentionally two atomic file + // replacements, not a transaction. An interrupted switch fails closed. + await writeAvatarBuildRecord(project, record); + await writeFile(tempManifest, JSON.stringify(derived, null, 2) + "\n", { flag: "wx" }); + await rename(tempManifest, characterFile); + } catch (cause) { + throw new AvatarWorkflowError("VECTOR_EYELIDS_REVIEW_REQUIRED", + (cause instanceof Error ? cause.message : String(cause)) + + ". The avatar stays unapproved; original rig remains untouched. " + + "A failed publication may leave fingerprints stale until you restore the prior model/record or rebuild."); + } finally { + await unlink(tempManifest).catch(() => undefined); + } + // Real engine renders are necessary to inspect the novel eyelid geometry. + // Do not reverse the successful model/record switch merely because FFmpeg + // or an optional contact-sheet renderer fails. + let review: Record; + try { + const rendered = await createBlinkReview(project, { root, timed: true }); + review = { + video: rendered.timedVideo, + eyes: rendered.eyeSheet, + full: rendered.fullSheet, + report: rendered.reportPath, + }; + } catch (cause) { + review = { + status: "manual-review-render-required", + error: cause instanceof Error ? cause.message : String(cause), + }; + } + return { + valid: true, + status: "visual-review-required", + approved: false, + previousApprovalRevoked: approved, + projectDir: project, + previousModel: manifest.render.modelPath, + newModel: relModel, + newParts: transformed.newPartIds, + hiddenParts: transformed.hiddenPartIds, + restoredEyeOpacityBindings: transformed.changedOpacityBindings, + review, + next: "Inspect the 30fps full-blink video AND the exact EyeOpen sweep. Vector eyelids may simplify original line art. Approval is never automatic.", + }; +} diff --git a/src/character/eyelid-vector.ts b/src/character/eyelid-vector.ts new file mode 100644 index 0000000..a0a90f9 --- /dev/null +++ b/src/character/eyelid-vector.ts @@ -0,0 +1,204 @@ +/** + * Experimental continuous eyelid stroke for an imported Rev2D eye rig. + * + * This does NOT generate/source new artwork: it replaces the extracted upper + * and lower eyelash *texture warps* with two thin deformable ribbons following + * the existing eye-white occlusion mask. The original mask continues to clip + * the iris, so the eye closes without ghosted translucent drawings or a + * duplicate lash generated by warping a large raster crop. + * + * The vector stroke is intentionally simple and may lose original lash + * detail. An author must inspect actual frames before accepting it. + * The workflow is opt-in, provenance-tracked and revokes approval. + */ +import { AvatarWorkflowError } from "./avatar.js"; + +type UnknownObject = Record; +type PointArray = number[]; + +export type VectorEyelidResult = { + model: UnknownObject; + newPartIds: string[]; + hiddenPartIds: string[]; + changedOpacityBindings: string[]; + profile: "experimental-vector-eyelids"; +}; + +function unsupported(message: string): never { + throw new AvatarWorkflowError("VECTOR_EYELIDS_UNSUPPORTED", message); +} +function object(value: unknown): UnknownObject { + if (!value || typeof value !== "object" || Array.isArray(value)) unsupported("Invalid Rev2D structure"); + return value as UnknownObject; +} +function list(value: unknown): UnknownObject[] { + if (!Array.isArray(value) || !value.every(v => v && typeof v === "object" && !Array.isArray(v))) { + unsupported("Missing Rev2D parts or bindings"); + } + return value as UnknownObject[]; +} +function validateColor(color: unknown): string { + if (typeof color !== "string" || !/^#[0-9a-f]{6}$/i.test(color)) { + unsupported("Lash color must be a fully opaque #rrggbb value from this avatar"); + } + return color; +} +function vectorRow(value: unknown): PointArray { + if (!Array.isArray(value) || value.length < 32 || value.length > 512 || + value.length % 4 !== 0 || !value.every(v => typeof v === "number" && Number.isFinite(v))) { + unsupported("Eye-mask geometry must have two finite rows of 8–128 sampled points"); + } + return value as number[]; +} +function faceRibbon(points: PointArray, row: number, count: number, width: number) { + const vertices: number[] = []; + const triangles: number[] = []; + for (let i = 0; i < count; i++) { + const x = points[(row * count + i) * 2]!; + const y = points[(row * count + i) * 2 + 1]!; + // Thin, tapered stroke: keep the corners anchored to the same position + // across states instead of scaling an extracted raster texture. + const weight = Math.sin(Math.PI * i / (count - 1)); + const half = width * (0.12 + 0.88 * Math.sqrt(Math.max(0, weight))) / 2; + vertices.push(x, y - half, x, y + half); + if (i < count - 1) { + const a = 2 * i; + triangles.push(a, a + 1, a + 2, a + 1, a + 3, a + 2); + } + } + return { vertices, triangles }; +} + +/** + * Pure, fail-closed transformation. Valid only for the known single-image + * Rev2D topology; it refuses rigs with smile eye sprites or foreign eye + * bindings instead of silently changing an unrelated or artist-authored rig. + */ +export function vectorizeImportedEyelids( + input: unknown, + colors: { eyeR: string; eyeL: string }, +): VectorEyelidResult { + const candidate = structuredClone(object(input)); + const parts = list(candidate.parts); + const bindings = list(candidate.bindings); + const byPart = new Map(); + const byBinding = new Map(); + for (const part of parts) { + if (typeof part.id !== "string" || byPart.has(part.id)) unsupported("Invalid or duplicate part id"); + byPart.set(part.id, part); + } + for (const binding of bindings) { + if (typeof binding.id !== "string" || byBinding.has(binding.id)) unsupported("Invalid or duplicate binding id"); + byBinding.set(binding.id, binding); + } + if ([...byPart.keys()].some(id => id.includes("_vector_") || /^sprite_eyes_smile_/.test(id)) || + [...byBinding.keys()].some(id => id.includes("_vector_") || /^sprite_eyes_smile_/.test(id))) { + unsupported("Already vectorized, or unsupported smiling eye sprite layout"); + } + + const hidden = new Set(); + const modified = new Set(); + const created: string[] = []; + for (const side of ["eyeR", "eyeL"] as const) { + const white = byPart.get(side + "_white"); + const upper = byPart.get(side + "_upper"); + const lower = byPart.get(side + "_lower"); + const ball = byPart.get(side + "_ball"); + const mask = byBinding.get(side + "Mask"); + const param = side === "eyeR" ? "EyeROpen" : "EyeLOpen"; + if (!white || !upper || !lower || !ball || !mask || + object(white.shape).type !== "mesh" || + object(ball.shape).type !== "image" || + !Array.isArray(ball.mask) || ball.mask.length !== 1 || ball.mask[0] !== side + "_white" || + object(upper.shape).type !== "image" || + object(lower.shape).type !== "image" || + mask.target !== "part:" + side + "_white.shape.vertices" || + !Array.isArray(mask.params) || mask.params.length !== 1 || mask.params[0] !== param) { + unsupported("Missing or incompatible built-in Rev2D mask / upper / lower eye topology for " + side); + } + const maskKeys = list(mask.keys); + if (maskKeys.length !== 2) unsupported("Eye mask must have exactly open/closed vertex keyforms"); + const closedKey = maskKeys.find(k => Array.isArray(k.at) && k.at.length === 1 && k.at[0] === 0); + const openedKey = maskKeys.find(k => Array.isArray(k.at) && k.at.length === 1 && k.at[0] === 1); + if (!closedKey || !openedKey) unsupported("Eye-mask keys must be at EyeOpen=0 and 1"); + const opened = vectorRow(openedKey.value); + const closed = vectorRow(closedKey.value); + const count = opened.length / 4; + if (count !== closed.length / 4 || + JSON.stringify(object(white.shape).vertices) !== JSON.stringify(opened)) { + unsupported("Eye-mask rest vertices must match the open geometry"); + } + for (let index = 1; index < count; index++) { + const x = opened[(index * 2)]!; + const priorX = opened[(index - 1) * 2]!; + if (x <= priorX) unsupported("Eye mask x positions are not strictly increasing"); + } + for (let index = 0; index < count; index++) { + const top = opened[index * 2 + 1]!; + const bottom = opened[(count + index) * 2 + 1]!; + const closeTop = closed[index * 2 + 1]!; + const closeBottom = closed[(count + index) * 2 + 1]!; + if (bottom + 1e-4 < top || Math.abs(closeTop - closeBottom) > 0.5) { + unsupported("Eye mask does not converge cleanly at the closed lid line"); + } + } + const lash = validateColor(colors[side]); + for (const [name, row, thickness, z] of [ + ["upper", 0, 2.8, 24.75], + ["lower", 1, 1.2, 22.8], + ] as const) { + const id = side + "_vector_" + name; + if (byPart.has(id) || byBinding.has(id + "Vertices")) unsupported("Generated vector part id already exists"); + const rest = faceRibbon(opened, row, count, thickness); + const shut = faceRibbon(closed, row, count, thickness); + parts.push({ + id, parent: white.parent, z, + shape: { type: "mesh", ...rest }, + fill: lash, + description: "Experimental continuous vector lash following eye-mask occlusion; requires visual review", + }); + bindings.push({ + id: id + "Vertices", target: "part:" + id + ".shape.vertices", + params: [param], + keys: [{ at: [0], value: shut.vertices }, { at: [1], value: rest.vertices }], + }); + created.push(id); + for (const hiddenId of [side + "_" + name, side + "_" + name + "Rim"]) { + const part = byPart.get(hiddenId); + if (!part) continue; + part.visible = false; + hidden.add(hiddenId); + } + } + } + + // Rev2D's existing full-eye sprites would cover the new line; hide only + // these known image variants (not mouth or general purpose expression art). + for (const [id, part] of byPart) { + if (/^sprite_eyes_(?:closed|half)_image(?:Left|Right)$/.test(id)) { + if (object(part.shape).type !== "image") unsupported("Unknown drawn-eye sprite shape"); + part.visible = false; + hidden.add(id); + } + } + // Restore the underlying eye mask/iris where the now-hidden sprites would + // previously have disabled it. Reject anything outside this exact topology. + for (const [id, binding] of byBinding) { + if (!id.endsWith("UnderSprite")) continue; + if (!/^eye[LR]_(?:white|ball|lower|upper|lowerRim|crease|upperRim)UnderSprite$/.test(id) || + binding.target !== "part:" + id.slice(0, -"UnderSprite".length) + ".opacity") { + unsupported("Unexpected sprite-hide binding " + id); + } + const keys = list(binding.keys); + for (const key of keys) { + if (typeof key.value !== "number" || !Number.isFinite(key.value)) unsupported("Invalid eye hide curve"); + key.value = 1; + } + modified.add(id); + } + return { + model: candidate, newPartIds: created, + hiddenPartIds: [...hidden], changedOpacityBindings: [...modified], + profile: "experimental-vector-eyelids", + }; +} diff --git a/src/cli/index.ts b/src/cli/index.ts index feecc16..aa0433e 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -22,6 +22,7 @@ import { requestDrawnVariants, statusDrawnVariants, importDrawnVariants } from " import { comparePngFiles, parsePixelRegionArgument } from "../character/pixel-qa.js"; import { comparePngSequence } from "../character/frame-sequence-qa.js"; import { createBlinkReview } from "../character/blink-review.js"; +import { createVectorEyelidRig } from "../character/eyelid-vector-workflow.js"; import { DEFAULT_LOOK_LIMITS, IMPORTED_INITIAL_LOOK_LIMITS } from "../scene/look-limits.js"; import { createCueBinding, verifyCueBinding, CueBindingError } from "../audio/cue-provenance.js"; @@ -38,6 +39,7 @@ function usage(): never { " puppetctl character import --out --id \n" + " puppetctl character build [--force]\n" + " puppetctl character approve --reviewed\n" + + " puppetctl character eyes vectorize --experimental\n" + " puppetctl character variants request [variant-id ...]\n" + " puppetctl character variants status \n" + " puppetctl character variants import [--experimental-short-fade|--experimental-stepped-eyes] --reviewed-art\n" + @@ -165,6 +167,13 @@ async function run(): Promise { return; } + if (first === "character" && second === "eyes" && third === "vectorize") { + const [project, flag, ...extra] = process.argv.slice(5); + if (!project || project.startsWith("--") || flag !== "--experimental" || extra.length) usage(); + print(await createVectorEyelidRig(project)); + return; + } + if (first === "character" && second === "variants" && third) { const [project, ...flags] = process.argv.slice(5); if (!project) usage(); diff --git a/tests/eyelid-vector.test.ts b/tests/eyelid-vector.test.ts new file mode 100644 index 0000000..d11e9fd --- /dev/null +++ b/tests/eyelid-vector.test.ts @@ -0,0 +1,119 @@ +import { describe, expect, it } from "vitest"; +import { vectorizeImportedEyelids } from "../src/character/eyelid-vector.js"; +import { vectorEyeColorsFromLayers } from "../src/character/eyelid-vector-workflow.js"; + +const colors = { eyeR: "#2a1828", eyeL: "#2b1829" }; +function fixture() { + const parts: Record[] = []; + const bindings: Record[] = []; + for (const [prefix, control] of [["eyeR", "EyeROpen"], ["eyeL", "EyeLOpen"]]) { + const x = prefix === "eyeR" ? 100 : 240; + const top = Array.from({ length: 10 }, (_, i) => [x + i * 4, 112 - Math.sin(i * Math.PI / 9) * 9]).flat(); + const low = Array.from({ length: 10 }, (_, i) => [x + i * 4, 124 + Math.sin(i * Math.PI / 9) * 7]).flat(); + const open = [...top, ...low]; + const closed = top.flatMap((_, i) => i % 2 === 0 ? [top[i], 119] : []) + .concat(top.flatMap((_, i) => i % 2 === 0 ? [top[i], 119] : [])); + parts.push({ id: prefix + "_white", parent: "faceWarp", + shape: { type: "mesh", vertices: open, triangles: [] } }); + parts.push({ id: prefix + "_ball", mask: [prefix + "_white"], + shape: { type: "image", texture: prefix + "_ball", x, y: 100, w: 50, h: 50 } }); + for (const name of ["upper", "lower", "upperRim", "lowerRim"]) { + parts.push({ id: prefix + "_" + name, visible: true, + shape: { type: "image", texture: prefix + "_" + name, x, y: 100, w: 50, h: 50 } }); + } + parts.push({ id: "sprite_eyes_closed_" + (prefix === "eyeR" ? "imageLeft" : "imageRight"), + visible: true, shape: { type: "image", texture: "closed", x, y: 100, w: 50, h: 50 } }); + bindings.push({ id: prefix + "Mask", target: "part:" + prefix + "_white.shape.vertices", + params: [control], keys: [{ at: [0], value: closed }, { at: [1], value: open }] }); + bindings.push({ id: prefix + "_ballUnderSprite", target: "part:" + prefix + "_ball.opacity", + params: [control], keys: [{ at: [0], value: 0 }, { at: [1], value: 1 }] }); + } + parts.push({ id: "mouth", shape: { type: "rect", x: 1, y: 2, w: 3, h: 4 } }); + bindings.push({ id: "mouthOpen", target: "part:mouth.opacity", params: ["MouthOpen"], + keys: [{ at: [0], value: 0 }, { at: [1], value: 1 }] }); + return { parts, bindings, meta: { width: 512, height: 640 } }; +} + +describe("guarded vector lash ribbons driven by an iris occlusion mask", () => { + it("maps image-left to character-right lash color and rejects missing/unsafe metadata", () => { + expect(vectorEyeColorsFromLayers({ eyes: { + imageLeft: { colors: { lash: "#2a1828" } }, + imageRight: { colors: { lash: "#2b1829" } }, + }})).toEqual(colors); + expect(() => vectorEyeColorsFromLayers({ eyes: { + imageLeft: { colors: { lash: "../../unsafe" } }, + imageRight: { colors: { lash: "#2b1829" } }, + }})).toThrow(/valid lash colors/); + expect(() => vectorEyeColorsFromLayers({})).toThrow(/valid lash colors/); + }); + + it("creates four deformable strips and preserves the source, non-eye controls and textures", () => { + const raw = fixture(); + const original = structuredClone(raw); + const result = vectorizeImportedEyelids(raw, colors); + expect(raw).toEqual(original); + expect(result.newPartIds).toEqual([ + "eyeR_vector_upper", "eyeR_vector_lower", + "eyeL_vector_upper", "eyeL_vector_lower", + ]); + const model = result.model as ReturnType; + expect(model.parts.find(p => p.id === "mouth")).toEqual(original.parts.find(p => p.id === "mouth")); + expect(model.bindings.find(p => p.id === "mouthOpen")).toEqual(original.bindings.find(p => p.id === "mouthOpen")); + const upper = model.parts.find(p => p.id === "eyeR_vector_upper")!; + expect(upper.fill).toBe(colors.eyeR); + expect(upper.shape).toMatchObject({ type: "mesh" }); + const curve = model.bindings.find(p => p.id === "eyeR_vector_upperVertices")!; + expect(curve.keys).toHaveLength(2); + expect(model.parts.find(p => p.id === "eyeR_upper")?.visible).toBe(false); + expect(model.parts.find(p => p.id === "sprite_eyes_closed_imageLeft")?.visible).toBe(false); + expect((model.bindings.find(p => p.id === "eyeR_ballUnderSprite")?.keys as {value: number}[]) + .map(x => x.value)).toEqual([1, 1]); + }); + + it("matches mask top/bottom at closed EyeOpen so upper and lower join", () => { + const model = vectorizeImportedEyelids(fixture(), colors).model as ReturnType; + for (const side of ["eyeR", "eyeL"]) { + const up = model.bindings.find(b => b.id === side + "_vector_upperVertices")!; + const lo = model.bindings.find(b => b.id === side + "_vector_lowerVertices")!; + const a = (up.keys as {value: number[]}[])[0]!.value; + const b = (lo.keys as {value: number[]}[])[0]!.value; + // The two bands share the exact same centerline, at every one of ten x points. + for (let i = 0; i < a.length; i += 4) { + expect((a[i + 1]! + a[i + 3]!) / 2).toBeCloseTo((b[i + 1]! + b[i + 3]!) / 2, 8); + } + } + }); + + it("refuses reapplication, smile sprites, foreign eye hide bindings and missing lower eyelid", () => { + const already = vectorizeImportedEyelids(fixture(), colors); + expect(() => vectorizeImportedEyelids(already.model, colors)) + .toThrow(/already vectorized|Already vectorized/i); + const smile = fixture(); + smile.parts.push({ id: "sprite_eyes_smile_imageLeft", shape: { type: "image" } }); + expect(() => vectorizeImportedEyelids(smile, colors)).toThrow(/smiling eye/i); + const hide = fixture(); + hide.bindings.push({ id: "eyeR_crazyUnderSprite", target: "part:x.opacity", + keys: [{ at: [0], value: 0 }, { at: [1], value: 1 }] }); + expect(() => vectorizeImportedEyelids(hide, colors)).toThrow(/Unexpected sprite-hide/); + const missing = fixture(); + missing.parts = missing.parts.filter(p => p.id !== "eyeL_lower"); + expect(() => vectorizeImportedEyelids(missing, colors)).toThrow(/Missing or incompatible/); + const unclipped = fixture(); + unclipped.parts.find(p => p.id === "eyeR_ball")!.mask = []; + expect(() => vectorizeImportedEyelids(unclipped, colors)).toThrow(/Missing or incompatible/); + }); + + it("rejects a malformed mask and invalid lash palette before output", () => { + const flipped = fixture(); + const mask = flipped.bindings.find(b => b.id === "eyeRMask")!; + const vertices = (mask.keys as { value: number[] }[])[1]!.value; + vertices[2] = vertices[0] - 5; + expect(() => vectorizeImportedEyelids(flipped, colors)).toThrow(/strictly increasing/); + expect(() => vectorizeImportedEyelids(fixture(), { ...colors, eyeR: "transparent" })) + .toThrow(/fully opaque/); + const impossible = fixture(); + const bad = impossible.bindings.find(b => b.id === "eyeLMask")!; + (bad.keys as {value: number[]}[])[0]!.value[1] += 50; + expect(() => vectorizeImportedEyelids(impossible, colors)).toThrow(/converge cleanly/); + }); +});