diff --git a/crates/capri-core/src/avatar.rs b/crates/capri-core/src/avatar.rs new file mode 100644 index 0000000..79098dc --- /dev/null +++ b/crates/capri-core/src/avatar.rs @@ -0,0 +1,303 @@ +//! Sprite catalog (`runtime-sprite-set.json`, schema 2) and the avatar list offered to the model, +//! ported from Capri 1.0.4 `avatar-catalog.mjs`. The character artwork is not bundled: it is read +//! from an existing Capri installation (`settings.avatar_dir`), with a procedural fallback otherwise. +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; + +use anyhow::{bail, Context, Result}; +use serde::Deserialize; +use sha2::{Digest, Sha256}; + +use crate::fsutil; + +/// Frame kinds shown in the framed portrait, plus the wink frames. +const PORTRAIT_KINDS: [&str; 4] = ["expression", "micro_frame", "gaze_frame", "reaction_expression"]; +const WINK_FRAMES: [&str; 2] = ["idle-wink_half", "idle-wink_closed"]; + +#[derive(Deserialize, Clone, Copy, Debug, PartialEq)] +pub struct Point { + pub x: f32, + pub y: f32, +} + +#[derive(Deserialize, Clone, Copy, Debug)] +pub struct Bounds { + pub x: f32, + pub y: f32, + pub width: f32, + pub height: f32, +} + +#[derive(Deserialize, Clone, Copy, Debug)] +pub struct Canvas { + pub width: u32, + pub height: u32, +} + +#[derive(Deserialize, Clone, Debug)] +#[serde(rename_all = "camelCase")] +pub struct Frame { + pub id: String, + #[serde(default = "idle")] + pub pose: String, + pub expression: String, + pub file: String, + #[serde(default = "expression_kind")] + pub kind: String, + #[serde(default = "yes")] + pub can_persist: bool, + #[serde(default)] + pub description: Option, + #[serde(default)] + pub visible_bounds: Option, + #[serde(default)] + pub sha256: Option, +} +fn idle() -> String { + "idle".into() +} +fn expression_kind() -> String { + "expression".into() +} +fn yes() -> bool { + true +} + +#[derive(Deserialize, Clone, Debug)] +pub struct ClipFrame { + pub id: String, + pub ms: u32, +} + +#[derive(Deserialize, Clone, Debug)] +pub struct Clip { + pub id: String, + pub frames: Vec, +} + +#[derive(Deserialize, Clone, Debug)] +#[serde(rename_all = "camelCase")] +struct Action { + id: String, + animation: String, + frame: String, + return_to: String, + description: String, +} + +#[derive(Deserialize, Clone, Copy, Debug)] +#[serde(rename_all = "camelCase")] +pub struct Autonomy { + pub enabled: bool, + pub first_activity_ms: u64, + pub activity_gap_ms: u64, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Manifest { + schema_version: u32, + canvas: Canvas, + #[serde(default)] + default_sprite: Option, + sprites: Vec, + #[serde(default)] + actions: Vec, + #[serde(default)] + clips: Vec, + #[serde(default)] + autonomy: Option, +} + +/// An avatar choice the model may emit as `[avatar:ID]`. +#[derive(Clone, Debug)] +pub struct ModelSprite { + pub id: String, + pub description: String, + /// Frame shown while the reply is visible (the action's frame for an action). + pub frame_id: String, + /// One-shot animation clip for actions such as `wink`. + pub animation: Option, + pub return_to: Option, +} + +#[derive(Clone, Debug)] +pub struct Catalog { + pub dir: PathBuf, + pub canvas: Canvas, + pub default_id: String, + pub frames: Vec, + pub clips: Vec, + pub autonomy: Option, + pub model_sprites: Vec, +} + +const DEFAULT_SET: &str = include_str!("../../../assets/default/sprite-set.json"); +pub const DEFAULT_AVATAR_PNG: &[u8] = include_bytes!("../../../assets/default/avatar.png"); + +impl Catalog { + /// Loads `/runtime-sprite-set.json` (Capri pack) or `/sprite-set.json`, verifying frame hashes. + pub fn load(dir: &Path) -> Result { + let file = ["runtime-sprite-set.json", "sprite-set.json"] + .iter() + .map(|name| dir.join(name)) + .find(|path| path.is_file()) + .with_context(|| format!("No sprite manifest in {}", dir.display()))?; + let bytes = fsutil::read_regular(&file, 4 * 1024 * 1024)?.unwrap_or_default(); + let catalog = Self::parse(dir, &serde_json::from_slice(&bytes)?)?; + for frame in &catalog.frames { + let path = catalog.frame_path(frame); + let bytes = fsutil::read_regular(&path, 32 * 1024 * 1024)? + .with_context(|| format!("Missing sprite {}", path.display()))?; + if let Some(expected) = &frame.sha256 + && hex::encode(Sha256::digest(&bytes)) != *expected { + bail!("Sprite checksum mismatch: {}", frame.id); + } + } + Ok(catalog) + } + + /// The bundled procedural avatar (no character artwork). + pub fn fallback() -> Self { + Self::parse(Path::new(""), &serde_json::from_str(DEFAULT_SET).unwrap()).expect("bundled sprite set") + } + + fn parse(dir: &Path, value: &serde_json::Value) -> Result { + let manifest: Manifest = serde_json::from_value(value.clone())?; + if !(1..=2).contains(&manifest.schema_version) { + bail!("Unsupported sprite manifest version"); + } + let valid_name = |s: &str| { + let mut c = s.chars(); + c.next().is_some_and(|f| f.is_ascii_lowercase()) + && s.len() <= 64 + && s.chars().all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_' || ch == '-') + }; + let mut frames = Vec::new(); + let mut ids = HashSet::new(); + for frame in manifest.sprites { + if frame.kind == "walk_frame" || frame.pose.starts_with("walk") { + continue; // walking frames are marked "excluded" in the manifest + } + if !valid_name(&frame.id) || !ids.insert(frame.id.clone()) || frame.file.contains('/') || frame.file.starts_with('.') { + bail!("Invalid sprite entry {}", frame.id); + } + frames.push(frame); + } + let by_id: HashMap<&str, &Frame> = frames.iter().map(|f| (f.id.as_str(), f)).collect(); + for clip in &manifest.clips { + if clip.frames.iter().any(|f| !by_id.contains_key(f.id.as_str())) { + bail!("Clip {} references a missing frame", clip.id); + } + } + let animated = manifest.schema_version == 2; + let portrait: HashSet<&str> = frames + .iter() + .filter(|f| !animated || (f.pose == "idle" && (PORTRAIT_KINDS.contains(&f.kind.as_str()) || WINK_FRAMES.contains(&f.id.as_str())))) + .map(|f| f.id.as_str()) + .collect(); + let mut model_sprites: Vec = frames + .iter() + .filter(|f| f.can_persist && portrait.contains(f.id.as_str())) + .map(|f| ModelSprite { + id: f.id.clone(), + description: f + .description + .clone() + .unwrap_or_else(|| format!("Expression: {}.", f.expression)) + .chars() + .take(240) + .collect(), + frame_id: f.id.clone(), + animation: None, + return_to: None, + }) + .collect(); + for action in &manifest.actions { + let clip = manifest.clips.iter().find(|c| c.id == action.animation); + let persistent = |id: &str| by_id.get(id).is_some_and(|f| f.can_persist) && portrait.contains(id); + if clip.is_some_and(|c| c.frames.iter().all(|f| portrait.contains(f.id.as_str()))) + && persistent(&action.frame) + && persistent(&action.return_to) + && !ids.contains(&action.id) + { + model_sprites.push(ModelSprite { + id: action.id.clone(), + description: action.description.chars().take(240).collect(), + frame_id: action.frame.clone(), + animation: Some(action.animation.clone()), + return_to: Some(action.return_to.clone()), + }); + } + } + let default_id = manifest.default_sprite.unwrap_or_else(|| "neutral".into()); + if !model_sprites.iter().any(|s| s.id == default_id) { + bail!("Default sprite is missing"); + } + Ok(Self { + dir: dir.to_path_buf(), + canvas: manifest.canvas, + default_id, + frames, + clips: manifest.clips, + autonomy: manifest.autonomy.filter(|_| animated), + model_sprites, + }) + } + + pub fn frame(&self, id: &str) -> Option<&Frame> { + self.frames.iter().find(|f| f.id == id) + } + + pub fn frame_path(&self, frame: &Frame) -> PathBuf { + self.dir.join(&frame.file) + } + + pub fn clip(&self, id: &str) -> Option<&Clip> { + self.clips.iter().find(|c| c.id == id) + } + + pub fn model_sprite(&self, id: &str) -> Option<&ModelSprite> { + self.model_sprites.iter().find(|s| s.id == id) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fallback_catalog() { + let c = Catalog::fallback(); + assert_eq!(c.default_id, "neutral"); + assert_eq!(c.model_sprites.len(), 1); + } + + #[test] + fn portrait_selection_and_actions() { + let manifest = serde_json::json!({ + "schemaVersion": 2, "canvas": {"width": 10, "height": 10}, "defaultSprite": "neutral", + "sprites": [ + {"id":"neutral","pose":"idle","expression":"n","file":"n.png","kind":"expression","canPersist":true,"description":"Calm."}, + {"id":"happy","pose":"idle","expression":"h","file":"h.png","kind":"expression","canPersist":true}, + {"id":"idle-wink_closed","pose":"idle","expression":"w","file":"w.png","kind":"micro_frame","canPersist":false}, + {"id":"idle-wave_a","pose":"idle","expression":"v","file":"v.png","kind":"gesture_frame","canPersist":false}, + {"id":"crouch-neutral","pose":"crouch","expression":"n","file":"c.png","kind":"pose_expression","canPersist":true}, + {"id":"walk-a","pose":"walk_left","expression":"n","file":"x.png","kind":"walk_frame","canPersist":false} + ], + "clips": [ + {"id":"wink","frames":[{"id":"neutral","ms":100},{"id":"idle-wink_closed","ms":100}]}, + {"id":"wave","frames":[{"id":"idle-wave_a","ms":100}]} + ], + "actions": [ + {"id":"wink","animation":"wink","frame":"happy","returnTo":"happy","label":"wink","description":"Wink."}, + {"id":"wave","animation":"wave","frame":"neutral","returnTo":"neutral","label":"wave","description":"Wave."} + ] + }); + let c = Catalog::parse(Path::new("/x"), &manifest).unwrap(); + let ids: Vec<_> = c.model_sprites.iter().map(|s| s.id.as_str()).collect(); + assert_eq!(ids, ["neutral", "happy", "wink"]); + assert_eq!(c.model_sprites[1].description, "Expression: h."); + assert!(c.frame("walk-a").is_none()); + } +}