From a1d1e769d268d579fd785e52759427845745ea5c Mon Sep 17 00:00:00 2001 From: fkDead Date: Wed, 11 Nov 2026 20:20:48 +0100 Subject: [PATCH] capri-ui: add avatar module --- crates/capri-ui/src/avatar.rs | 516 ++++++++++++++++++++++++++++++++++ 1 file changed, 516 insertions(+) create mode 100644 crates/capri-ui/src/avatar.rs diff --git a/crates/capri-ui/src/avatar.rs b/crates/capri-ui/src/avatar.rs new file mode 100644 index 0000000..671b823 --- /dev/null +++ b/crates/capri-ui/src/avatar.rs @@ -0,0 +1,516 @@ +//! Sprite loading and the framed portrait: persistent expression, blink and speech clips, +//! one-shot action clips, plus the overlays drawn on the live frame. +use std::collections::{HashMap, HashSet}; +use std::path::PathBuf; +use std::sync::mpsc::{channel, Receiver, Sender}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use capri_core::avatar::{Catalog, ClipFrame, DEFAULT_AVATAR_PNG}; +use eframe::egui::{self, epaint::Vertex, Color32, ColorImage, Mesh, Pos2, Rect, Shape, TextureHandle, TextureOptions}; + +use crate::{body, fx, geom}; + +pub const CANVAS: f32 = 1254.0; + +/// Alpha plane of a decoded frame, for tap hit tests (alpha >= 16 is opaque). +pub struct Alpha { + w: usize, + h: usize, + data: Vec, +} + +impl Alpha { + pub fn opaque(&self, u: f32, v: f32) -> bool { + if !(0.0..1.0).contains(&u) || !(0.0..1.0).contains(&v) { + return false; + } + self.data[(v * self.h as f32) as usize * self.w + (u * self.w as f32) as usize] >= 16 + } +} + +pub struct Texture { + pub texture: TextureHandle, + /// White silhouette for the red teleport tint (only when requested). + pub silhouette: Option, + pub alpha: Arc, +} + +type Decoded = (String, ColorImage, Option, Alpha); + +/// Background PNG decoder: frames are requested by id and arrive as textures. +pub struct Loader { + paths: HashMap, + requested: HashSet, + request: Sender<(String, PathBuf)>, + loaded: Receiver, + pub textures: HashMap, +} + +fn decode(path: &std::path::Path, crop: Option<(u32, u32, u32, u32)>, height: u32, silhouette: bool) -> anyhow::Result<(ColorImage, Option, Alpha)> { + let image = if path.as_os_str().is_empty() { image::load_from_memory(DEFAULT_AVATAR_PNG)? } else { image::open(path)? }; + let mut image = image.into_rgba8(); + if let Some((x, y, w, h)) = crop + && x + w <= image.width() + && y + h <= image.height() + { + image = image::imageops::crop_imm(&image, x, y, w, h).to_image(); + } + if image.height() > height { + let width = image.width() * height / image.height(); + image = image::imageops::resize(&image, width, height, image::imageops::FilterType::Triangle); + } + let size = [image.width() as usize, image.height() as usize]; + let alpha = Alpha { w: size[0], h: size[1], data: image.pixels().map(|p| p[3]).collect() }; + let white = silhouette.then(|| ColorImage::from_rgba_unmultiplied(size, &image.pixels().flat_map(|p| [255, 255, 255, p[3]]).collect::>())); + Ok((ColorImage::from_rgba_unmultiplied(size, image.as_raw()), white, alpha)) +} + +impl Loader { + /// `crop` is applied in canvas pixels before scaling to at most `height` pixels. + pub fn new(ctx: egui::Context, paths: HashMap, crop: Option<(u32, u32, u32, u32)>, height: u32, silhouettes: bool) -> Self { + let (request, requests) = channel::<(String, PathBuf)>(); + let (done, loaded) = channel(); + std::thread::Builder::new() + .name("capri-sprites".into()) + .spawn(move || { + for (id, path) in requests { + match decode(&path, crop, height, silhouettes) { + Ok((image, white, alpha)) => { + if done.send((id, image, white, alpha)).is_err() { + break; + } + ctx.request_repaint(); + } + Err(e) => tracing::warn!("sprite {id}: {e:#}"), + } + } + }) + .expect("sprite loader thread"); + Self { paths, requested: HashSet::new(), request, loaded, textures: HashMap::new() } + } + + pub fn want(&mut self, id: &str) { + if let Some(path) = self.paths.get(id) + && self.requested.insert(id.to_string()) + { + let _ = self.request.send((id.to_string(), path.clone())); + } + } + + pub fn has(&self, id: &str) -> bool { + self.paths.contains_key(id) + } + + /// Uploads decoded frames; call once per frame on the UI thread. + pub fn poll(&mut self, ctx: &egui::Context) { + while let Ok((id, image, white, alpha)) = self.loaded.try_recv() { + let texture = ctx.load_texture(format!("sprite-{id}"), image, TextureOptions::LINEAR); + let silhouette = white.map(|w| ctx.load_texture(format!("silhouette-{id}"), w, TextureOptions::LINEAR)); + self.textures.insert(id, Texture { texture, silhouette, alpha: Arc::new(alpha) }); + } + } + + pub fn get(&mut self, id: &str) -> Option<&Texture> { + self.want(id); + self.textures.get(id) + } +} + +struct Clip { + frames: Vec, + start: Instant, + looping: bool, +} + +impl Clip { + fn total(&self) -> Duration { + Duration::from_millis(self.frames.iter().map(|f| f.ms as u64).sum()) + } + + /// Current frame id and time to the next frame, or `None` when a one-shot clip is over. + fn at(&self, now: Instant) -> Option<(&str, Duration)> { + let total = self.total(); + if total.is_zero() { + return None; + } + let mut elapsed = now - self.start; + if self.looping { + elapsed = Duration::from_nanos((elapsed.as_nanos() % total.as_nanos()) as u64); + } else if elapsed >= total { + return None; + } + let mut acc = Duration::ZERO; + for f in &self.frames { + acc += Duration::from_millis(f.ms as u64); + if elapsed < acc { + return Some((&f.id, acc - elapsed)); + } + } + None + } +} + +/// Union of the frames' visible bounds, so every frame is cropped identically. +fn crop_box(catalog: &Catalog) -> Option<(u32, u32, u32, u32)> { + let bounds: Vec<_> = catalog.frames.iter().filter_map(|f| f.visible_bounds).collect(); + if bounds.is_empty() { + return None; + } + let x0 = bounds.iter().map(|b| b.x).fold(f32::MAX, f32::min).max(0.0); + let y0 = bounds.iter().map(|b| b.y).fold(f32::MAX, f32::min).max(0.0); + let x1 = bounds.iter().map(|b| b.x + b.width).fold(0.0, f32::max).min(catalog.canvas.width as f32); + let y1 = bounds.iter().map(|b| b.y + b.height).fold(0.0, f32::max).min(catalog.canvas.height as f32); + Some((x0 as u32, y0 as u32, (x1 - x0) as u32, (y1 - y0) as u32)) +} + +/// What was painted, for hit tests and overlays. +#[derive(Clone)] +pub struct View { + pub frame: String, + pub draw: Rect, + /// Crop box in canvas pixels. + pub crop: Rect, + pub alpha: Arc, + pub lens: Option, +} + +impl View { + pub fn to_screen(&self, x: f32, y: f32) -> Pos2 { + let k = self.draw.width() / self.crop.width(); + Pos2::new(self.draw.min.x + (x - self.crop.min.x) * k, self.draw.min.y + (y - self.crop.min.y) * k) + } + + /// Normalized canvas point under a window point (after the CRT lens). + pub fn to_canvas(&self, p: Pos2) -> (f32, f32) { + let p = self.lens.map_or(p, |l| fx::screen_sample(p, l)); + let k = self.crop.width() / self.draw.width(); + ((self.crop.min.x + (p.x - self.draw.min.x) * k) / CANVAS, (self.crop.min.y + (p.y - self.draw.min.y) * k) / CANVAS) + } + + pub fn opaque(&self, u: f32, v: f32) -> bool { + let x = (u * CANVAS - self.crop.min.x) / self.crop.width(); + let y = (v * CANVAS - self.crop.min.y) / self.crop.height(); + self.alpha.opaque(x, y) + } +} + +/// Per-frame inputs from the shell. +pub struct Paint { + pub crt: bool, + pub glitch: f32, + pub time: f32, + pub reduced: bool, + pub mouth: u8, + pub dance: f32, + pub sleeping: bool, + pub headpat: bool, +} + +pub struct Avatar { + catalog: Arc, + pub loader: Loader, + crop: Option<(u32, u32, u32, u32)>, + expression: String, + action: Option<(Clip, String)>, + ambient: Option<(Clip, &'static str)>, + reaction: Option<(String, Instant)>, + intro: Option<(Clip, bool)>, + speaking: bool, + shown: Option, + pub view: Option, +} + +/// Capri's startup intro pack, next to the sprite folder: `../../intro-v1`. +fn intro_frames(dir: &std::path::Path) -> Option> { + #[derive(serde::Deserialize)] + struct F { + id: String, + file: String, + ms: u32, + sha256: String, + } + #[derive(serde::Deserialize)] + struct M { + frames: Vec, + } + let root = dir.parent()?.parent()?.join("intro-v1"); + let manifest: M = serde_json::from_slice(&capri_core::fsutil::read_regular(&root.join("runtime-intro.json"), 16 * 1024).ok()??).ok()?; + if manifest.frames.len() != 7 || manifest.frames.iter().map(|f| f.ms).sum::() != 3000 { + return None; + } + manifest + .frames + .into_iter() + .map(|f| { + let path = root.join(&f.file); + let bytes = capri_core::fsutil::read_regular(&path, 4 << 20).ok()??; + (f.file.starts_with("PNG/") && !f.file.contains("..") && sha256(&bytes) == f.sha256).then_some((format!("intro-{}", f.id), path, f.ms)) + }) + .collect() +} + +pub fn sha256(bytes: &[u8]) -> String { + use sha2::Digest; + hex::encode(sha2::Sha256::digest(bytes)) +} + +/// Capri install root from the sprite folder (`/assets/capri/sprites/v1`). +pub fn install_root(catalog: &Catalog) -> Option { + if catalog.dir.as_os_str().is_empty() { + return None; + } + Some(catalog.dir.parent()?.parent()?.parent()?.parent()?.to_path_buf()) +} + +impl Avatar { + pub fn new(catalog: Arc, ctx: egui::Context, intro: bool) -> Self { + let crop = crop_box(&catalog); + let mut paths: HashMap = catalog.frames.iter().map(|f| (f.id.clone(), catalog.frame_path(f))).collect(); + let mut intro_clip = None; + if intro && let Some(frames) = intro_frames(&catalog.dir) { + intro_clip = Some((Clip { frames: frames.iter().map(|(id, _, ms)| ClipFrame { id: id.clone(), ms: *ms }).collect(), start: Instant::now(), looping: false }, false)); + paths.extend(frames.into_iter().map(|(id, path, _)| (id, path))); + } + // The headpat face plate is character artwork: read from the Capri install, never copied. + if let Some(root) = install_root(&catalog) { + let face = root.join("assets/default/capri-headpat.png"); + if face.is_file() { + paths.insert("headpat-face".into(), face); + } + } + let loader = Loader::new(ctx, paths, crop, 720, false); + let mut avatar = Self { + expression: catalog.default_id.clone(), + catalog, + loader, + crop, + action: None, + ambient: None, + reaction: None, + intro: intro_clip, + speaking: false, + shown: None, + view: None, + }; + let mut ids: Vec = avatar.intro.iter().flat_map(|(c, _)| c.frames.iter().map(|f| f.id.clone())).collect(); + ids.extend(avatar.catalog.model_sprites.iter().map(|s| s.frame_id.clone())); + for clip in &avatar.catalog.clips { + if ["blink", "speech"].contains(&clip.id.as_str()) || avatar.catalog.model_sprites.iter().any(|s| s.animation.as_deref() == Some(&clip.id)) { + ids.extend(clip.frames.iter().map(|f| f.id.clone())); + } + } + for id in ids { + avatar.loader.want(&id); + } + avatar + } + + pub fn catalog(&self) -> &Arc { + &self.catalog + } + + /// Animated Capri artwork (not the fallback symbol): enables detach, headpat and body parts. + pub fn animated(&self) -> bool { + !self.catalog.dir.as_os_str().is_empty() + } + + /// Applies a model choice: a persistent expression, or an action clip followed by its rest frame. + pub fn set_expression(&mut self, id: &str) { + let Some(sprite) = self.catalog.model_sprite(id).cloned() else { return }; + match (&sprite.animation, self.catalog.clip(sprite.animation.as_deref().unwrap_or(""))) { + (Some(_), Some(clip)) => { + let rest = sprite.return_to.clone().unwrap_or(sprite.frame_id.clone()); + self.action = Some((Clip { frames: clip.frames.clone(), start: Instant::now(), looping: false }, rest)); + } + _ => self.expression = sprite.frame_id, + } + } + + pub fn speaking(&mut self, speaking: bool) { + self.speaking = speaking; + } + + /// Tap reaction frame for 740 ms. + pub fn react(&mut self, tone: &str) { + let id = match tone { + "affectionate" => "happy", + "curious" => "skeptical", + "neutral" => "attentive", + _ => "annoyed", + }; + if self.catalog.frame(id).is_some() { + self.reaction = Some((id.into(), Instant::now())); + } + } + + pub fn intro_playing(&self) -> bool { + self.intro.is_some() + } + + /// Skips the intro (any input, Settings opened, leaving the frame). + pub fn skip_intro(&mut self) { + self.intro = None; + } + + /// Speech and blink clips use the neutral face, so they only play on the default expression. + fn ambient_clip(&self) -> Option<&'static str> { + if self.expression != self.catalog.default_id { + return None; + } + let name = if self.speaking { "speech" } else { "blink" }; + self.catalog.clip(name).map(|_| name) + } + + /// Frame to show now and the time until it changes. + pub fn current(&mut self, now: Instant, sleeping: bool) -> (String, Duration) { + if let Some((intro, armed)) = &mut self.intro { + // The intro waits until every frame is decoded, and gives up after 2.2 s. + if !*armed { + if intro.frames.iter().all(|f| self.loader.textures.contains_key(&f.id)) { + (intro.start, *armed) = (now, true); + } else if intro.start.elapsed() < Duration::from_millis(2200) { + return (self.expression.clone(), Duration::from_millis(50)); + } + } + if *armed && let Some((id, next)) = intro.at(now) { + return (id.to_string(), next); + } + } + self.intro = None; + if sleeping && self.catalog.frame("idle-blink_closed").is_some() { + return ("idle-blink_closed".into(), Duration::from_secs(1)); + } + if let Some((id, at)) = &self.reaction { + if at.elapsed() < Duration::from_millis(740) { + return (id.clone(), Duration::from_millis(740) - at.elapsed()); + } + self.reaction = None; + } + if let Some((clip, rest)) = &self.action { + if let Some((id, next)) = clip.at(now) { + return (id.to_string(), next); + } + self.expression = rest.clone(); + self.action = None; + } + let wanted = self.ambient_clip(); + if self.ambient.as_ref().map(|(_, n)| *n) != wanted { + self.ambient = wanted.and_then(|name| self.catalog.clip(name).map(|c| (Clip { frames: c.frames.clone(), start: now, looping: true }, name))); + } + if let Some((clip, _)) = &self.ambient + && let Some((id, next)) = clip.at(now) + { + return (id.to_string(), next); + } + (self.expression.clone(), Duration::from_secs(1)) + } + + /// Time until the frame changes, for repaint scheduling. + pub fn next_change(&mut self, sleeping: bool) -> Duration { + self.current(Instant::now(), sleeping).1.max(Duration::from_millis(16)) + } + + /// Paints the portrait inside `area` and records the [`View`] for hit tests. + pub fn paint(&mut self, ui: &mut egui::Ui, area: Rect, p: &Paint) { + let ctx = ui.ctx().clone(); + self.loader.poll(&ctx); + let (id, _) = self.current(Instant::now(), p.sleeping); + self.loader.want(&id); + if self.loader.textures.contains_key(&id) { + self.shown = Some(id); + } + // While a frame is still loading, keep showing the previous one. + let Some(frame) = self.shown.clone() else { return }; + let Some(tex) = self.loader.textures.get(&frame) else { return }; + let size = tex.texture.size_vec2(); + let scale = (area.width() / size.x).min(area.height() / size.y); + let draw = Rect::from_min_size(Pos2::new(area.center().x - size.x * scale / 2.0, area.bottom() - size.y * scale), size * scale); + let crop = self.crop.map_or(Rect::from_min_size(Pos2::ZERO, egui::vec2(CANVAS, CANVAS)), |(x, y, w, h)| Rect::from_min_size(Pos2::new(x as f32, y as f32), egui::vec2(w as f32, h as f32))); + let painter = ui.painter_at(area); + let uv = Rect::from_min_max(Pos2::ZERO, Pos2::new(1.0, 1.0)); + let mut lens = None; + if p.dance.abs() > 0.01 { + // TODO: the CRT shader is skipped while dancing because it only draws an axis-aligned quad. + let view = View { frame: frame.clone(), draw, crop, alpha: tex.alpha.clone(), lens: None }; + let pivot = view.to_screen(627.0, 1166.0); + let (s, c) = p.dance.to_radians().sin_cos(); + let rot = |q: Pos2| pivot + egui::vec2((q.x - pivot.x) * c - (q.y - pivot.y) * s, (q.x - pivot.x) * s + (q.y - pivot.y) * c); + let mut mesh = Mesh::with_texture(tex.texture.id()); + for (corner, uvp) in geom::rect_points(draw).into_iter().zip(geom::rect_points(uv)) { + mesh.vertices.push(Vertex { pos: rot(corner), uv: uvp, color: Color32::WHITE }); + } + mesh.indices = vec![0, 1, 2, 0, 2, 3]; + painter.add(Shape::mesh(mesh)); + } else if !(p.crt + && fx::paint_crt(&painter, fx::CrtParams { texture: tex.texture.id(), portrait: area, avatar: draw, time: p.time, glitch: p.glitch, reduced: p.reduced }) + && { + lens = Some(area); + true + }) + { + painter.image(tex.texture.id(), draw, uv, Color32::WHITE); + } + let view = View { frame: frame.clone(), draw, crop, alpha: tex.alpha.clone(), lens }; + if p.headpat && !p.sleeping && self.loader.has("headpat-face") && body::portrait_mouth(&frame).is_some() { + if let Some(face) = self.loader.get("headpat-face") { + let outline: Vec = body::HEADPAT_FACE.iter().map(|&(x, y)| view.to_screen(x, y)).collect(); + geom::image_clipped(&painter, face.texture.id(), draw, &outline, Color32::WHITE); + } + } else if p.mouth > 0 && !p.sleeping && !frame.starts_with("intro-") && let Some((mx, my)) = body::portrait_mouth(&frame) { + mouth_plate(&painter, &view, mx, my, p.mouth); + } + self.view = Some(view); + } +} + +/// Mouth plate on standing frames: dark plate then the opening, `o` by shape. +fn mouth_plate(painter: &egui::Painter, view: &View, mx: f32, my: f32, level: u8) { + let o = [0.0, 7.0, 17.0, 24.0][level.min(3) as usize]; + let pts = |list: &[(f32, f32)]| -> Vec { list.iter().map(|&(x, y)| view.to_screen(mx + x, my + y)).collect() }; + geom::fill(painter, &pts(&[(-36., -12.), (36., -24.), (30., 17.), (4., 29.), (-33., 18.)]), Color32::from_rgb(0x07, 0x08, 0x12)); + geom::fill(painter, &pts(&[(-21., 1.), (22., -12.), (12., o), (-5., o - 2.)]), Color32::from_rgb(0xf9, 0xfa, 0xff)); +} + +/// Pose mouth for reviewed poses; `to_screen` maps canvas px. +pub fn pose_mouth(painter: &egui::Painter, to_screen: impl Fn(f32, f32) -> Pos2, m: [f32; 4], level: u8) { + if level == 0 { + return; + } + let [x, y, angle, width] = m; + let k = width / 34.0; + let (s, c) = angle.sin_cos(); + let map = |list: &[(f32, f32)]| -> Vec { list.iter().map(|&(px, py)| to_screen(x + (px * c - py * s) * k, y + (px * s + py * c) * k)).collect() }; + let (hw, d) = [(10.0, 5.0), (10.0, 5.0), (11.0, 12.0), (16.0, 8.0)][level.min(3) as usize]; + geom::fill(painter, &map(&[(-22., -10.), (22., -9.), (20., 11.), (7., 15.), (-22., 11.)]), Color32::from_rgb(0x08, 0x09, 0x11)); + geom::fill(painter, &map(&[(-hw, -3.), (hw, -5.), (hw * 0.6, d), (-hw * 0.57, d)]), Color32::from_rgb(0x2a, 0x18, 0x28)); + geom::fill(painter, &map(&[(-hw, -3.), (hw, -5.), (hw * 0.56, 1.), (-hw * 0.69, 1.)]), Color32::from_rgb(0xf8, 0xfa, 0xfb)); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn clip_timing() { + let start = Instant::now(); + let frames = vec![ClipFrame { id: "a".into(), ms: 100 }, ClipFrame { id: "b".into(), ms: 50 }]; + let once = Clip { frames: frames.clone(), start, looping: false }; + assert_eq!(once.at(start + Duration::from_millis(10)).unwrap().0, "a"); + assert_eq!(once.at(start + Duration::from_millis(120)).unwrap().0, "b"); + assert!(once.at(start + Duration::from_millis(200)).is_none()); + let looped = Clip { frames, start, looping: true }; + assert_eq!(looped.at(start + Duration::from_millis(160)).unwrap().0, "a"); + } + + #[test] + fn view_mapping_roundtrip() { + let alpha = Arc::new(Alpha { w: 2, h: 2, data: vec![0, 255, 255, 0] }); + let view = View { frame: "neutral".into(), draw: Rect::from_min_size(Pos2::new(10.0, 20.0), egui::vec2(100.0, 200.0)), crop: Rect::from_min_size(Pos2::new(200.0, 100.0), egui::vec2(800.0, 1600.0)), alpha, lens: None }; + let p = view.to_screen(600.0, 900.0); + let (u, v) = view.to_canvas(p); + assert!((u * CANVAS - 600.0).abs() < 1e-3 && (v * CANVAS - 900.0).abs() < 1e-3); + assert!(view.opaque(700.0 / CANVAS, 200.0 / CANVAS), "top-right quadrant is opaque"); + assert!(!view.opaque(300.0 / CANVAS, 200.0 / CANVAS)); + } +}