feat(frontend): add companion voice mode and expressive avatar

Split the client into two tabs so the user can either write to Jarvis or
talk to it. The companion screen centres the animated avatar and exposes a
large push-to-talk button; the transcript from local Whisper is sent to the
backend as text JSON exactly like a typed message, so the network contract
stays text-only.

Give the avatar a distinct expression per mood (thinking, listening,
speaking, happy, error, idle) and apply one dark, rounded theme so the app
looks consistent everywhere.
This commit is contained in:
BlackAngelTV committed 2026-10-06 19:10:30 +02:00
1 parent b9e23cf975
commit e2457d98da
3 files changed
+830 -123

No files matched your search

+21 -6
View File
@@ -76,6 +76,20 @@ la lecture vocale (case « 🔊 Voix »).
## Fonctionnement
### Deux modes : Chat et Compagnon
Deux onglets en haut de la fenêtre basculent l'affichage :
| Onglet | Contenu |
| --- | --- |
| **💬 Chat** | Barre latérale des projets, bulles de conversation, saisie clavier. |
| **🗣️ Compagnon** | L'avatar (tamagotchi) au centre, l'humeur, les sous-titres du dernier échange et un grand bouton micro *push-to-talk*. |
Le **mode est mémorisé** et rouvert au lancement suivant. Les deux onglets parlent au
même code : un message transcrit par la voix emprunte exactement le même chemin qu'un
message tapé (voir [Voix](#voix-stt--tts-local)). Le mode Compagnon envoie donc lui aussi
le **texte** de la transcription au backend, en JSON, exactement comme le Chat.
### Connexion et cache du token
1. Au lancement, le client lit le token JWT mis en cache (via la persistance d'eframe,
@@ -160,10 +174,11 @@ se replie au lieu de déborder de la fenêtre.
La voix est traitée **entièrement côté client** : rien d'audio ne transite vers le backend.
- **STT** — bouton **push-to-talk** `🎤` dans la barre de saisie : maintiens pour parler,
relâche pour transcrire. Le micro est capturé via `cpal`, rééchantillonné à 16 kHz mono si
besoin, puis transcrit par **whisper.cpp** (`whisper-rs`). Le texte obtenu est placé dans le
champ puis envoyé automatiquement.
- **STT** — bouton **push-to-talk** : dans le mode Chat, le petit bouton `🎤` de la barre
de saisie ; dans le mode Compagnon, le **grand bouton circulaire** sous l'avatar. Maintiens
pour parler, relâche pour transcrire. Le micro est capturé via `cpal`, rééchantillonné à
16 kHz mono si besoin, puis transcrit par **whisper.cpp** (`whisper-rs`). Le texte obtenu
est envoyé automatiquement au backend — même requête JSON qu'un message tapé.
- **TTS** — coche « 🔊 Voix » (ou `JARVIS_SPEAK=1`) : à la fin du streaming, la réponse est
synthétisée par **Piper** (`piper-rs`) et jouée sur le haut-parleur (rééchantillonnage vers
la fréquence du périphérique de sortie).
@@ -196,8 +211,8 @@ src/
config.rs # configuration (variables d'environnement)
model.rs # structs serde partagées avec le backend
api.rs # client HTTP : login, /me, flux SSE (eventsource-stream + CancellationToken)
app.rs # état de l'app, connexion, barre projets, chat egui, persistance
tamagotchi.rs # compagnon animé dont l'humeur suit l'état de l'app
app.rs # état de l'app, connexion, barre projets, chat egui, mode Compagnon, thème
tamagotchi.rs # compagnon animé (petit dans la barre, grand sur l'écran Compagnon)
voice/
mod.rs # module voix
audio.rs # micro (cpal) + lecture haut-parleur + rééchantillonnage
+417 -29
View File
@@ -23,6 +23,17 @@ use crate::voice::engine::{self, VoiceConfig, VoiceEvent, VoiceHandle};
/// Key under which the state is persisted (token, email, model, backend URL).
const STORAGE_KEY: &str = "jarvise-session";
/// Accent colour of the primary actions: tabs, titles and the mic button.
pub const ACCENT: egui::Color32 = egui::Color32::from_rgb(0x5b, 0x8d, 0xff);
/// Softer accent for text that has to stay readable on the dark background.
pub const ACCENT_SOFT: egui::Color32 = egui::Color32::from_rgb(0x9d, 0xbc, 0xff);
/// Colour of the running status line (recording, transcribing…).
const STATUS: egui::Color32 = egui::Color32::from_rgb(0x8a, 0xb4, 0xf8);
/// Colour of error messages.
const ERROR: egui::Color32 = egui::Color32::from_rgb(0xff, 0x6b, 0x6b);
/// Background of the top and bottom strips.
const BAR_FILL: egui::Color32 = egui::Color32::from_rgb(0x16, 0x19, 0x21);
/// Messages sent from background tasks to the UI thread.
enum UiEvent {
/// Login succeeded: a token and the user profile are available.
@@ -85,6 +96,35 @@ struct Persisted {
/// Project reopened on the next run, if it still exists.
#[serde(default)]
project_id: Option<i64>,
/// Reopens the companion screen on the next run.
#[serde(default)]
companion: bool,
}
/// The two faces of the app, switched from the tabs at the top of the window.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Mode {
/// Text conversation: project sidebar, bubbles, keyboard input.
Chat,
/// Voice conversation: the avatar is centred and a big button talks to it.
Companion,
}
impl Mode {
fn label(self) -> &'static str {
match self {
Mode::Chat => "💬 Chat",
Mode::Companion => "🗣️ Compagnon",
}
}
/// One-line explanation shown as a tooltip on each tab.
fn hint(self) -> &'static str {
match self {
Mode::Chat => "Écrire à Jarvis, avec les projets et l'historique",
Mode::Companion => "Parler à Jarvis : l'avatar transcrit ta voix et envoie le texte",
}
}
}
/// Cloneable bridge used by background tasks to talk to the UI: pushes an event
@@ -137,6 +177,7 @@ pub struct JarviseApp {
history_truncated: bool,
// Chat.
mode: Mode,
model: String,
messages: Vec<ChatMessage>,
input: String,
@@ -158,6 +199,10 @@ pub struct JarviseApp {
impl JarviseApp {
pub fn new(cc: &eframe::CreationContext<'_>, config: AppConfig) -> Self {
// A single dark theme, applied once: the app should look the same on
// every desktop rather than follow the OS colours.
apply_theme(&cc.egui_ctx);
let persisted: Persisted = cc
.storage
.and_then(|storage| eframe::get_value(storage, STORAGE_KEY))
@@ -227,6 +272,11 @@ impl JarviseApp {
form_description: String::new(),
context_note: String::new(),
history_truncated: false,
mode: if persisted.companion {
Mode::Companion
} else {
Mode::Chat
},
model,
messages: Vec::new(),
input: String::new(),
@@ -864,19 +914,47 @@ impl JarviseApp {
}
fn chat_screen(&mut self, ui: &mut egui::Ui) {
self.project_panel(ui);
// The project sidebar is a text-mode tool: the companion screen is a
// calm, centred stage for the avatar, so it gets the full width.
if self.mode == Mode::Chat {
self.project_panel(ui);
}
self.top_bar(ui);
match self.mode {
Mode::Chat => {
self.input_bar(ui);
egui::CentralPanel::default().show(ui, |ui| {
chat_area(ui, &self.messages);
});
}
Mode::Companion => {
self.companion_bar(ui);
self.companion_screen(ui);
}
}
}
/// The window's top strip: identity, the two mode tabs, and the session
/// controls (context, model, voice output, account).
fn top_bar(&mut self, ui: &mut egui::Ui) {
egui::Panel::top("top-bar").show(ui, |ui| {
egui::Frame::new()
.fill(BAR_FILL)
.inner_margin(egui::Margin::symmetric(14, 10))
.show(ui, |ui| {
// Shown in the bar so the current context is obvious.
// Shown in the bar so the current context is obvious, even
// when the sidebar is hidden on the companion screen.
let project_label = self
.current_project
.and_then(|id| self.projects.iter().find(|item| item.id == id))
.map(|project| project.name.clone());
let time = ui.input(|i| i.time);
let mood = self.mood();
// Narrow windows drop the least important labels instead of
// letting the bar overflow.
let wide = ui.available_width() > 720.0;
ui.horizontal(|ui| {
let pet = tamagotchi::draw(ui, mood, time);
pet.on_hover_text(mood.tooltip());
@@ -894,32 +972,41 @@ impl JarviseApp {
);
});
ui.add_space(8.0);
ui.separator();
ui.add_space(16.0);
let context = egui::RichText::new(
project_label.clone().unwrap_or_else(|| "Sans projet".to_string()),
)
.strong();
ui.label(context);
ui.separator();
// The two modes, side by side — the app's main switch.
for mode in [Mode::Chat, Mode::Companion] {
let selected = self.mode == mode;
let button = egui::Button::new(
egui::RichText::new(mode.label()).size(15.0).color(if selected {
egui::Color32::WHITE
} else {
egui::Color32::from_gray(190)
}),
)
.fill(if selected {
ACCENT
} else {
egui::Color32::TRANSPARENT
})
.corner_radius(egui::CornerRadius::same(9))
.min_size(egui::vec2(0.0, 34.0));
if ui.add(button).on_hover_text(mode.hint()).clicked() {
self.mode = mode;
}
}
ui.label("Modèle");
ui.add(
egui::TextEdit::singleline(&mut self.model)
.desired_width(140.0)
.hint_text("qwen2.5:3b"),
);
if wide {
ui.add_space(10.0);
ui.separator();
ui.separator();
let speak = ui.add_enabled(
self.voice.tts_ready(),
egui::Checkbox::new(&mut self.speak_replies, "🔊 Voix"),
);
if !self.voice.tts_ready() {
speak.on_disabled_hover_text(
"TTS non configuré : définis PIPER_MODEL et PIPER_CONFIG",
);
// Context in use by the next exchange.
let context = egui::RichText::new(
project_label.clone().unwrap_or_else(|| "Sans projet".to_string()),
)
.strong()
.color(ACCENT_SOFT);
ui.label(context).on_hover_text("Contexte utilisé par Jarvis");
}
ui.with_layout(
@@ -930,7 +1017,8 @@ impl JarviseApp {
}
// In a project the history lives on the backend, so the only way to
// really clear it is the sidebar's « Vider ».
if self.current_project.is_none()
if self.mode == Mode::Chat
&& self.current_project.is_none()
&& ui.button("Effacer")
.on_hover_text("Effacer la conversation affichée")
.clicked()
@@ -943,21 +1031,43 @@ impl JarviseApp {
ui.add_space(4.0);
ui.label(user.display_name());
}
ui.separator();
let speak = ui.add_enabled(
self.voice.tts_ready(),
egui::Checkbox::new(&mut self.speak_replies, "🔊 Voix"),
);
if !self.voice.tts_ready() {
speak.on_disabled_hover_text(
"TTS non configuré : définis PIPER_MODEL et PIPER_CONFIG",
);
}
ui.add(
egui::TextEdit::singleline(&mut self.model)
.desired_width(130.0)
.hint_text("qwen2.5:3b"),
)
.on_hover_text("Modèle Ollama");
},
);
});
});
});
}
/// Bottom strip of the text mode: the compose box and its send button.
fn input_bar(&mut self, ui: &mut egui::Ui) {
egui::Panel::bottom("input-bar").show(ui, |ui| {
egui::Frame::new()
.fill(BAR_FILL)
.inner_margin(egui::Margin::symmetric(14, 10))
.show(ui, |ui| {
if let Some(error) = &self.error {
ui.colored_label(egui::Color32::from_rgb(0xff, 0x6b, 0x6b), error);
ui.colored_label(ERROR, error);
}
if let Some(status) = &self.voice_status {
ui.colored_label(egui::Color32::from_rgb(0x8a, 0xb4, 0xf8), status);
ui.colored_label(STATUS, status);
}
if self.error.is_some() || self.voice_status.is_some() {
ui.add_space(4.0);
@@ -1014,9 +1124,114 @@ impl JarviseApp {
});
});
});
}
/// Bottom strip of the companion screen: the status/error line and a text
/// fallback for when the microphone is not configured.
fn companion_bar(&mut self, ui: &mut egui::Ui) {
egui::Panel::bottom("companion-bar").show(ui, |ui| {
egui::Frame::new()
.fill(BAR_FILL)
.inner_margin(egui::Margin::symmetric(14, 10))
.show(ui, |ui| {
if let Some(error) = &self.error {
ui.colored_label(ERROR, error);
ui.add_space(4.0);
}
ui.horizontal(|ui| {
let button_width = 96.0;
let input_width = (ui.available_width() - button_width - 10.0).max(120.0);
let response = ui.add_sized(
[input_width, 40.0],
egui::TextEdit::singleline(&mut self.input)
.hint_text("Ou écris à Jarvis…"),
);
let submitted = response.has_focus()
&& ui.input(|i| i.key_pressed(egui::Key::Enter) && !i.modifiers.shift);
if self.streaming {
if ui
.add_sized([button_width, 40.0], egui::Button::new("Stopper"))
.clicked()
{
self.stop_stream();
}
} else if ui
.add_sized([button_width, 40.0], egui::Button::new("Envoyer"))
.clicked()
|| submitted
{
self.send_message(ui.ctx());
}
});
});
});
}
/// The companion stage: the avatar in the middle, the mood underneath, the
/// last exchange as subtitles, and the large push-to-talk button. Talking
/// produces a transcript, which is sent to the backend as plain text JSON
/// exactly like a typed message.
fn companion_screen(&mut self, ui: &mut egui::Ui) {
egui::CentralPanel::default().show(ui, |ui| {
chat_area(ui, &self.messages);
let available = ui.available_size();
let time = ui.input(|i| i.time);
let mood = self.mood();
let subtitle_width = (available.x * 0.82).min(640.0);
ui.vertical_centered(|ui| {
ui.add_space((available.y * 0.05).max(6.0));
let diameter = (available.x * 0.30).clamp(120.0, 230.0);
let pet = tamagotchi::draw_sized(ui, mood, time, diameter);
pet.on_hover_text(mood.tooltip());
ui.add_space(10.0);
ui.label(egui::RichText::new(mood.label()).size(20.0).color(ACCENT_SOFT));
ui.add_space(6.0);
if let Some(status) = &self.voice_status {
ui.colored_label(STATUS, status);
} else if !self.voice.stt_ready() {
ui.small("Micro non configuré : définis WHISPER_MODEL pour parler à Jarvis.");
}
ui.add_space((available.y * 0.04).max(6.0));
// Subtitles: what was just said, then Jarvis' live answer.
if let Some(last_user) = self.messages.iter().rev().find(|m| m.is_user()) {
subtitle(ui, "Vous", &last_user.content, subtitle_width, false);
ui.add_space(6.0);
}
let live_reply = self
.messages
.iter()
.rev()
.find(|m| m.role == "assistant" && !m.content.trim().is_empty());
match live_reply {
Some(reply) => subtitle(ui, "Jarvis", &reply.content, subtitle_width, true),
None if self.streaming => subtitle(ui, "Jarvis", "…", subtitle_width, true),
None => {}
}
ui.add_space((available.y * 0.06).max(10.0));
// Push-to-talk: hold to record, release to transcribe + send.
let mic = mic_button(ui, self.recorder.is_some(), self.voice.stt_ready());
let down = mic.is_pointer_button_down_on();
if self.voice.stt_ready() {
if down && self.recorder.is_none() {
self.start_recording();
}
if !down && self.recorder.is_some() {
self.stop_recording();
}
mic.on_hover_text("Maintenir pour parler — relâche pour transcrire et envoyer");
} else {
mic.on_hover_text("STT non configuré : définis WHISPER_MODEL");
}
});
});
}
@@ -1262,11 +1477,130 @@ impl eframe::App for JarviseApp {
model: self.model.clone(),
backend_url: self.backend_url.clone(),
project_id: self.current_project,
companion: self.mode == Mode::Companion,
};
eframe::set_value(storage, STORAGE_KEY, &persisted);
}
}
/// Applies the app's single dark theme: a deep, slightly blue background with
/// rounded widgets, so the interface looks the same on every desktop instead of
/// following the operating system colours.
fn apply_theme(ctx: &egui::Context) {
use egui::{Color32, CornerRadius, Stroke};
let mut visuals = egui::Visuals::dark();
visuals.panel_fill = Color32::from_rgb(0x12, 0x14, 0x1a);
visuals.window_fill = Color32::from_rgb(0x1a, 0x1d, 0x26);
visuals.extreme_bg_color = Color32::from_rgb(0x0d, 0x0f, 0x14);
visuals.faint_bg_color = Color32::from_rgb(0x1e, 0x22, 0x2c);
visuals.hyperlink_color = ACCENT;
visuals.selection.bg_fill = ACCENT.gamma_multiply(0.40);
visuals.window_corner_radius = CornerRadius::same(12);
visuals.menu_corner_radius = CornerRadius::same(10);
for widget in [
&mut visuals.widgets.inactive,
&mut visuals.widgets.hovered,
&mut visuals.widgets.active,
&mut visuals.widgets.open,
] {
widget.corner_radius = CornerRadius::same(9);
}
visuals.widgets.inactive.weak_bg_fill = Color32::from_rgb(0x22, 0x27, 0x33);
visuals.widgets.hovered.weak_bg_fill = Color32::from_rgb(0x2c, 0x33, 0x42);
visuals.widgets.active.weak_bg_fill = ACCENT.gamma_multiply(0.55);
visuals.widgets.hovered.bg_stroke = Stroke::new(1.0, ACCENT.gamma_multiply(0.7));
// Force dark regardless of what the desktop prefers.
ctx.set_theme(egui::ThemePreference::Dark);
ctx.set_visuals(visuals);
}
/// One line of the companion's subtitles: a rounded card holding who spoke and
/// what was said.
fn subtitle(ui: &mut egui::Ui, who: &str, text: &str, width: f32, from_jarvis: bool) {
let fill = if from_jarvis {
egui::Color32::from_rgb(0x1e, 0x22, 0x2c)
} else {
egui::Color32::from_rgb(0x24, 0x2c, 0x3d)
};
egui::Frame::new()
.fill(fill)
.corner_radius(egui::CornerRadius::same(12))
.inner_margin(egui::Margin::symmetric(14, 10))
.show(ui, |ui| {
ui.set_max_width((width - 30.0).max(120.0));
ui.vertical(|ui| {
ui.label(
egui::RichText::new(who)
.size(11.0)
.strong()
.color(ACCENT_SOFT),
);
ui.label(text);
});
});
}
/// A large circular push-to-talk button, painted by hand so it reads as a real
/// button. Returns the response the caller senses pointer state on.
fn mic_button(ui: &mut egui::Ui, active: bool, enabled: bool) -> egui::Response {
let diameter = (ui.available_width() * 0.20).clamp(80.0, 124.0);
let sense = if enabled {
egui::Sense::click()
} else {
egui::Sense::hover()
};
let (rect, response) = ui.allocate_exact_size(egui::Vec2::splat(diameter), sense);
let painter = ui.painter();
let center = rect.center();
let radius = diameter / 2.0;
let base = if active {
egui::Color32::from_rgb(0xe5, 0x54, 0x54)
} else if enabled {
ACCENT
} else {
egui::Color32::from_gray(70)
};
let fill = if response.hovered() && enabled {
base.gamma_multiply(1.12)
} else {
base
};
// Pulsing rings while recording.
if active {
let time = ui.input(|i| i.time) as f32;
for i in 0..2 {
let phase = ((time * 1.6 + i as f32 * 0.5) % 1.0 + 1.0) % 1.0;
painter.circle_stroke(
center,
radius * (1.0 + phase * 0.35),
egui::Stroke::new(2.0, base.gamma_multiply(0.7 * (1.0 - phase))),
);
}
}
painter.circle_filled(center, radius, fill);
painter.circle_stroke(
center,
radius,
egui::Stroke::new(2.0, base.gamma_multiply(0.6)),
);
painter.text(
center,
egui::Align2::CENTER_CENTER,
if active { "⏺" } else { "🎤" },
egui::FontId::proportional(radius * 0.85),
egui::Color32::WHITE,
);
response
}
/// Widest the centred conversation column may become, and the margin kept on
/// its sides when the window is narrower than that.
pub const COLUMN_MAX_WIDTH: f32 = 880.0;
@@ -1391,3 +1725,57 @@ pub fn render_bubble(ui: &mut egui::Ui, message: &ChatMessage) -> egui::Rect {
})
.inner
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn theme_is_dark_and_wears_the_accent() {
let ctx = egui::Context::default();
apply_theme(&ctx);
let visuals = ctx.style_of(egui::Theme::Dark).visuals.clone();
assert!(visuals.dark_mode);
assert_eq!(visuals.panel_fill, egui::Color32::from_rgb(0x12, 0x14, 0x1a));
assert_eq!(visuals.selection.bg_fill, ACCENT.gamma_multiply(0.40));
}
/// The companion screen is a hand-painted stage; a headless pass proves the
/// avatar, the subtitles and the microphone button all lay out cleanly.
#[test]
fn companion_widgets_paint_without_panicking() {
let ctx = egui::Context::default();
ctx.set_fonts(egui::FontDefinitions::default());
let input = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(
egui::Pos2::ZERO,
egui::vec2(900.0, 700.0),
)),
..Default::default()
};
let output = ctx.run_ui(input, |ui| {
egui::CentralPanel::default().show(ui, |ui| {
ui.vertical_centered(|ui| {
let pet = tamagotchi::draw_sized(ui, Mood::Listening, 1.0, 180.0);
assert_eq!(pet.rect.width(), 180.0);
subtitle(ui, "Vous", "Bonjour Jarvis", 600.0, false);
subtitle(ui, "Jarvis", "Bonjour, que puis-je faire ?", 600.0, true);
let mic = mic_button(ui, false, true);
assert!(mic.rect.width() >= 80.0);
});
});
});
// Nothing rasterises the fonts here, so the texture deltas can be dropped.
output.drop_without_applying_deltas();
}
#[test]
fn modes_have_distinct_tabs() {
assert_ne!(Mode::Chat.label(), Mode::Companion.label());
assert!(Mode::Chat.hint().to_lowercase().contains("écrire"));
assert!(Mode::Companion.hint().to_lowercase().contains("parler"));
}
}
+392 -88
View File
@@ -3,11 +3,18 @@
//! It reacts to what the app is doing: idle, listening, thinking, speaking,
//! happy or worried — giving the interface a living, friendly touch without any
//! image asset.
//!
//! Everything is derived from the widget's height, so the very same drawing is
//! used for the 40 pt pet of the top bar and for the large avatar centred in
//! the companion screen.
use std::f32::consts::PI;
use eframe::egui::{self, Color32, Pos2, Sense, Stroke, Vec2};
/// Diameter the companion is drawn at by default (the top-bar pet).
pub const DEFAULT_SIZE: f32 = 40.0;
/// What the companion is expressing right now.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Mood {
@@ -73,67 +80,120 @@ impl Mood {
}
}
/// Draws the companion in the current `ui`, animated with `time` (seconds).
///
/// Returns the widget [`egui::Response`] so callers can attach a tooltip.
/// Draws the companion at the default (top-bar) size.
pub fn draw(ui: &mut egui::Ui, mood: Mood, time: f64) -> egui::Response {
let (rect, response) = ui.allocate_exact_size(Vec2::splat(40.0), Sense::hover());
let painter = ui.painter();
draw_sized(ui, mood, time, DEFAULT_SIZE)
}
/// Draws the companion in the current `ui`, animated with `time` (seconds), on
/// a square of `diameter` points. Returns the widget [`egui::Response`] so
/// callers can attach a tooltip or sense clicks.
pub fn draw_sized(ui: &mut egui::Ui, mood: Mood, time: f64, diameter: f32) -> egui::Response {
let (rect, response) = ui.allocate_exact_size(Vec2::splat(diameter), Sense::hover());
paint(ui.painter(), rect, mood, time as f32);
response
}
/// Paints the companion inside `rect`, without allocating it. Shared with the
/// circular microphone button so the avatar can sit on top of a halo.
pub fn paint(painter: &egui::Painter, rect: egui::Rect, mood: Mood, time: f32) {
let (body, accent) = mood.body_and_accent();
let time = time as f32;
// Gentle vertical bob; a bit livelier when the app is busy.
let bob = (time * 2.2).sin() * if mood == Mood::Idle { 1.0 } else { 1.8 };
let center = Pos2::new(rect.center().x, rect.center().y + 3.0 + bob);
// Every offset below is expressed in "small pet" units and scaled, so the
// 40 pt pet and the large avatar stay visually identical.
let scale = rect.height() / DEFAULT_SIZE;
// Bounce: the happy one hops, the idle one barely breathes.
let bounce = match mood {
Mood::Idle => 1.0,
Mood::Happy => 3.0,
Mood::Listening | Mood::Speaking => 1.6,
_ => 1.8,
};
let bob = (time * 2.2).sin() * bounce * scale;
let center = Pos2::new(rect.center().x, rect.center().y + 3.0 * scale + bob);
let radius = rect.height() * 0.33;
// Ground shadow.
// Ground shadow, tighter when the pet is airborne.
let lift = (bob / scale / 3.0).clamp(0.0, 1.0);
painter.circle_filled(
Pos2::new(center.x, rect.bottom() - 2.5),
radius * 0.7,
Pos2::new(center.x, rect.bottom() - 2.5 * scale),
radius * (0.70 - 0.15 * lift),
Color32::from_black_alpha(70),
);
// Antenna with a glowing tip.
let tip = Pos2::new(center.x, center.y - radius - 6.0);
let tip = Pos2::new(center.x, center.y - radius - 6.0 * scale);
painter.line_segment(
[Pos2::new(center.x, center.y - radius + 2.0), tip],
Stroke::new(1.6, accent),
[Pos2::new(center.x, center.y - radius + 2.0 * scale), tip],
Stroke::new(1.6 * scale, accent),
);
let glow = 1.5 + (time * 3.0).sin() * 0.6;
painter.circle_filled(tip, glow.max(1.0), body);
let glow = (1.5 + (time * 3.0).sin() * 0.6) * scale;
painter.circle_filled(tip, glow.max(scale), body);
// Listening: expanding pulse rings.
if mood == Mood::Listening {
for i in 0..2 {
let phase = ((time * 2.0 + i as f32 * 0.5) % 1.0 + 1.0) % 1.0;
painter.circle_stroke(
center,
radius + 2.0 + phase * 5.0,
Stroke::new(1.4, body.gamma_multiply(0.8 * (1.0 - phase))),
);
// Mood ambience, painted behind the body.
match mood {
Mood::Listening => {
// Expanding rings: the robot pricks up its ears.
for i in 0..2 {
let phase = ((time * 2.0 + i as f32 * 0.5) % 1.0 + 1.0) % 1.0;
painter.circle_stroke(
center,
radius + (2.0 + phase * 5.0) * scale,
Stroke::new(1.4 * scale, body.gamma_multiply(0.8 * (1.0 - phase))),
);
}
}
}
// Thinking: little dots orbiting above the head.
if mood == Mood::Thinking {
for i in 0..3 {
let angle = time * 3.0 + i as f32 * (2.0 * PI / 3.0);
let dot = Pos2::new(
center.x + angle.sin() * (radius + 6.0),
center.y - radius - 7.0 - angle.cos() * 3.0,
);
painter.circle_filled(dot, 2.0, accent);
Mood::Speaking => {
// Sound waves escaping from the little loudspeaker.
let pulse = (time * 5.0).sin().abs();
for i in 0..2 {
let r = radius + (7.0 + i as f32 * 7.0 + pulse * 2.0) * scale;
painter.circle_stroke(
center,
r,
Stroke::new(1.3 * scale, accent.gamma_multiply(0.55 - i as f32 * 0.15)),
);
}
}
Mood::Happy => {
// Hearts floating up: very pleased with itself.
for i in 0..3 {
let phase = ((time * 0.7 + i as f32 * 0.33) % 1.0 + 1.0) % 1.0;
let fade = (1.0 - phase).clamp(0.0, 1.0);
let pos = Pos2::new(
center.x + (i as f32 - 1.0) * radius * 0.85
+ (time * 2.0 + i as f32).sin() * 3.0 * scale,
center.y - radius * 1.1 - phase * radius * 1.7,
);
heart(
painter,
pos,
radius * (0.16 + 0.10 * fade),
Color32::from_rgb(0xf5, 0x6b, 0xa0).gamma_multiply(fade.max(0.2)),
);
}
}
Mood::Error => {
// A halo of dizzy sparks.
for i in 0..3 {
let angle = time * 2.6 + i as f32 * (2.0 * PI / 3.0);
let pos = Pos2::new(
center.x + angle.sin() * (radius + 7.0 * scale),
center.y - radius - 6.0 * scale - angle.cos() * 3.0 * scale,
);
sparkle(painter, pos, 2.4 * scale, Color32::from_rgb(0xff, 0xd1, 0x66));
}
}
_ => {}
}
// Body and outline.
painter.circle_filled(center, radius, body);
painter.circle_stroke(center, radius, Stroke::new(1.5, accent));
painter.circle_stroke(center, radius, Stroke::new(1.5 * scale, accent));
// Cheeks.
let cheek = Color32::from_white_alpha(46);
// Cheeks, more flushed when happy.
let cheek = Color32::from_white_alpha(if mood == Mood::Happy { 92 } else { 46 });
painter.circle_filled(
Pos2::new(center.x - radius * 0.56, center.y + radius * 0.12),
radius * 0.17,
@@ -145,89 +205,333 @@ pub fn draw(ui: &mut egui::Ui, mood: Mood, time: f64) -> egui::Response {
cheek,
);
// Eyes.
draw_eyes(painter, center, radius, mood, time, scale);
draw_mouth(painter, center, radius, mood, time, scale);
draw_props(painter, center, radius, mood, time, scale, body);
}
/// The eyes carry most of the mood.
fn draw_eyes(
painter: &egui::Painter,
center: Pos2,
radius: f32,
mood: Mood,
time: f32,
scale: f32,
) {
let eye_y = center.y - radius * 0.22;
let eye_dx = radius * 0.38;
let blinking = mood == Mood::Idle && (time % 3.2) < 0.12;
let white = Color32::WHITE;
let pupil = Color32::from_rgb(0x1c, 0x1c, 0x24);
if mood == Mood::Error {
// Crossed-out eyes.
for side in [-1.0_f32, 1.0] {
let c = Pos2::new(center.x + side * eye_dx, eye_y);
let d = radius * 0.16;
painter.line_segment(
[Pos2::new(c.x - d, c.y - d), Pos2::new(c.x + d, c.y + d)],
Stroke::new(2.0, Color32::WHITE),
);
painter.line_segment(
[Pos2::new(c.x - d, c.y + d), Pos2::new(c.x + d, c.y - d)],
Stroke::new(2.0, Color32::WHITE),
);
match mood {
Mood::Error => {
// Crossed-out, dazed eyes.
for side in [-1.0_f32, 1.0] {
let c = Pos2::new(center.x + side * eye_dx, eye_y);
let d = radius * 0.16;
painter.line_segment(
[Pos2::new(c.x - d, c.y - d), Pos2::new(c.x + d, c.y + d)],
Stroke::new(2.0 * scale, white),
);
painter.line_segment(
[Pos2::new(c.x - d, c.y + d), Pos2::new(c.x + d, c.y - d)],
Stroke::new(2.0 * scale, white),
);
}
}
} else if blinking {
for side in [-1.0_f32, 1.0] {
let c = Pos2::new(center.x + side * eye_dx, eye_y);
Mood::Happy => {
// Closed upward arcs: ^ ^, the universal "delighted" face.
for side in [-1.0_f32, 1.0] {
arc(
painter,
center.x + side * eye_dx,
eye_y + radius * 0.05,
radius * 0.16,
-radius * 0.16,
Stroke::new(2.2 * scale, white),
);
}
}
Mood::Thinking => {
// One eye squints, both look up: computing very hard.
let squint = Pos2::new(center.x - eye_dx, eye_y);
painter.line_segment(
[
Pos2::new(c.x - radius * 0.14, c.y),
Pos2::new(c.x + radius * 0.14, c.y),
Pos2::new(squint.x - radius * 0.13, squint.y),
Pos2::new(squint.x + radius * 0.13, squint.y),
],
Stroke::new(2.0, Color32::WHITE),
Stroke::new(2.0 * scale, white),
);
let open = Pos2::new(center.x + eye_dx, eye_y);
painter.circle_filled(open, radius * 0.15, white);
painter.circle_filled(
open + Vec2::new(radius * 0.02, -radius * 0.07),
radius * 0.07,
pupil,
);
}
} else {
for side in [-1.0_f32, 1.0] {
painter.circle_filled(
Pos2::new(center.x + side * eye_dx, eye_y),
radius * 0.15,
Color32::WHITE,
);
painter.circle_filled(
Pos2::new(center.x + side * eye_dx + radius * 0.05, eye_y),
radius * 0.07,
Color32::from_rgb(0x1c, 0x1c, 0x24),
);
Mood::Listening => {
// Wide, startled eyes: really paying attention.
for side in [-1.0_f32, 1.0] {
let c = Pos2::new(center.x + side * eye_dx, eye_y);
painter.circle_filled(c, radius * 0.19, white);
painter.circle_filled(c, radius * 0.085, pupil);
}
}
Mood::Speaking => {
// Normal eyes with raised eyebrows.
for side in [-1.0_f32, 1.0] {
let c = Pos2::new(center.x + side * eye_dx, eye_y);
painter.circle_filled(c, radius * 0.15, white);
painter.circle_filled(c + Vec2::new(radius * 0.05, 0.0), radius * 0.07, pupil);
painter.line_segment(
[
Pos2::new(c.x - radius * 0.16, c.y - radius * 0.32),
Pos2::new(c.x + radius * 0.16, c.y - radius * 0.36),
],
Stroke::new(1.4 * scale, white),
);
}
}
Mood::Idle => {
let blinking = (time % 3.2) < 0.12;
for side in [-1.0_f32, 1.0] {
let c = Pos2::new(center.x + side * eye_dx, eye_y);
if blinking {
painter.line_segment(
[
Pos2::new(c.x - radius * 0.14, c.y),
Pos2::new(c.x + radius * 0.14, c.y),
],
Stroke::new(2.0 * scale, white),
);
} else {
painter.circle_filled(c, radius * 0.15, white);
painter.circle_filled(c + Vec2::new(radius * 0.05, 0.0), radius * 0.07, pupil);
}
}
}
}
}
// Mouth.
/// The mouth completes the expression.
fn draw_mouth(
painter: &egui::Painter,
center: Pos2,
radius: f32,
mood: Mood,
time: f32,
scale: f32,
) {
let mouth_y = center.y + radius * 0.34;
let white = Stroke::new(1.8 * scale, Color32::WHITE);
let dark = Color32::from_rgb(0x2a, 0x18, 0x18);
let tongue = Color32::from_rgb(0xf5, 0x8f, 0xb0);
match mood {
Mood::Speaking => {
let open = (time * 12.0).sin().abs();
painter.circle_filled(
Pos2::new(center.x, mouth_y),
radius * (0.10 + 0.12 * open),
Color32::from_rgb(0x2a, 0x18, 0x18),
dark,
);
}
Mood::Happy | Mood::Listening => smile(painter, center.x, mouth_y, radius, false),
Mood::Error => smile(painter, center.x, mouth_y, radius, true),
Mood::Idle | Mood::Thinking => {
Mood::Happy => {
// A big open grin with a hint of tongue.
painter.circle_filled(
Pos2::new(center.x, mouth_y + radius * 0.04),
radius * 0.20,
dark,
);
painter.circle_filled(
Pos2::new(center.x, mouth_y + radius * 0.14),
radius * 0.10,
tongue,
);
}
Mood::Listening => {
// A small, attentive "o".
painter.circle_filled(Pos2::new(center.x, mouth_y), radius * 0.09, dark);
}
Mood::Thinking => {
// Flat mouth, tongue poking out: caught mid-calculation.
painter.line_segment(
[
Pos2::new(center.x - radius * 0.16, mouth_y),
Pos2::new(center.x + radius * 0.16, mouth_y),
],
Stroke::new(1.8, Color32::WHITE),
white,
);
painter.circle_filled(
Pos2::new(center.x + radius * 0.05, mouth_y + radius * 0.13),
radius * 0.09,
tongue,
);
}
Mood::Error => {
// Worried frown.
arc(painter, center.x, mouth_y, radius * 0.30, -radius * 0.28, white);
}
Mood::Idle => {
painter.line_segment(
[
Pos2::new(center.x - radius * 0.16, mouth_y),
Pos2::new(center.x + radius * 0.16, mouth_y),
],
white,
);
}
}
response
}
/// Draws a curved mouth (a smile, or a frown when `inverted`).
fn smile(painter: &egui::Painter, cx: f32, y: f32, radius: f32, inverted: bool) {
let half = radius * 0.45;
let depth = radius * 0.5 * if inverted { -1.0 } else { 1.0 };
let steps = 7;
/// Props that sell the mood: sleep bubbles, a question mark, a quaver, sweat.
fn draw_props(
painter: &egui::Painter,
center: Pos2,
radius: f32,
mood: Mood,
time: f32,
scale: f32,
body: Color32,
) {
match mood {
Mood::Idle => {
// Little "z"s drifting up: the robot naps between requests.
for i in 0..2 {
let phase = ((time * 0.45 + i as f32 * 0.5) % 1.0 + 1.0) % 1.0;
let alpha = ((1.0 - phase) * 200.0) as u8;
let pos = Pos2::new(
center.x + radius * 0.95 + phase * radius * 0.35,
center.y - radius * 0.85 - phase * radius * 1.5,
);
painter.text(
pos,
egui::Align2::CENTER_CENTER,
"z",
egui::FontId::proportional(radius * (0.30 + 0.30 * phase)),
Color32::from_white_alpha(alpha),
);
}
}
Mood::Thinking => {
// A thought bubble with a question mark, and its little trail.
painter.circle_filled(
Pos2::new(center.x + radius * 0.45, center.y - radius * 0.85),
radius * 0.09,
Color32::from_white_alpha(190),
);
painter.circle_filled(
Pos2::new(center.x + radius * 0.62, center.y - radius * 1.02),
radius * 0.13,
Color32::from_white_alpha(210),
);
let bubble = Pos2::new(center.x + radius * 0.95, center.y - radius * 1.25);
painter.circle_filled(bubble, radius * 0.34, Color32::from_rgb(0xf2, 0xf4, 0xff));
painter.text(
bubble,
egui::Align2::CENTER_CENTER,
"?",
egui::FontId::proportional(radius * 0.5),
Color32::from_rgb(0x5b, 0x8d, 0xff),
);
}
Mood::Speaking => {
// A tiny quaver, as if it were singing the answer.
let sway = (time * 6.0).sin() * radius * 0.06;
painter.circle_filled(
Pos2::new(center.x + radius * 0.95, center.y - radius * 0.75 + sway),
radius * 0.09,
body,
);
painter.line_segment(
[
Pos2::new(center.x + radius * 1.02, center.y - radius * 0.75 + sway),
Pos2::new(center.x + radius * 1.02, center.y - radius * 1.25 + sway),
],
Stroke::new(1.8 * scale, body),
);
}
Mood::Error => {
// A bead of sweat on the side of the head.
sweat_drop(
painter,
Pos2::new(center.x + radius * 0.78, center.y - radius * 0.28),
radius * 0.26,
Color32::from_rgb(0x9d, 0xd0, 0xff),
);
}
_ => {}
}
}
/// Draws a symmetric arc from `cx - half` to `cx + half`; a positive amplitude
/// curves it into a smile, a negative one into a frown (or closed happy eyes).
fn arc(painter: &egui::Painter, cx: f32, y: f32, half: f32, amp: f32, stroke: Stroke) {
let steps = 8;
let mut previous = Pos2::new(cx - half, y);
for i in 1..=steps {
let f = i as f32 / steps as f32;
let point = Pos2::new(cx - half + 2.0 * half * f, y + (f * PI).sin() * depth);
painter.line_segment([previous, point], Stroke::new(1.8, Color32::WHITE));
let point = Pos2::new(cx - half + 2.0 * half * f, y + (f * PI).sin() * amp);
painter.line_segment([previous, point], stroke);
previous = point;
}
}
/// A cartoon heart: two lobes and a point.
fn heart(painter: &egui::Painter, center: Pos2, size: f32, color: Color32) {
painter.circle_filled(
Pos2::new(center.x - size * 0.42, center.y - size * 0.18),
size * 0.46,
color,
);
painter.circle_filled(
Pos2::new(center.x + size * 0.42, center.y - size * 0.18),
size * 0.46,
color,
);
painter.add(egui::Shape::convex_polygon(
vec![
Pos2::new(center.x - size * 0.86, center.y - size * 0.02),
Pos2::new(center.x + size * 0.86, center.y - size * 0.02),
Pos2::new(center.x, center.y + size * 0.95),
],
color,
Stroke::NONE,
));
}
/// A four-point sparkle.
fn sparkle(painter: &egui::Painter, center: Pos2, size: f32, color: Color32) {
let stroke = Stroke::new(size * 0.5, color);
painter.line_segment(
[
Pos2::new(center.x - size, center.y),
Pos2::new(center.x + size, center.y),
],
stroke,
);
painter.line_segment(
[
Pos2::new(center.x, center.y - size),
Pos2::new(center.x, center.y + size),
],
stroke,
);
}
/// A teardrop: a round bottom with a pointed top.
fn sweat_drop(painter: &egui::Painter, center: Pos2, size: f32, color: Color32) {
painter.circle_filled(center, size * 0.55, color);
painter.add(egui::Shape::convex_polygon(
vec![
Pos2::new(center.x - size * 0.40, center.y - size * 0.18),
Pos2::new(center.x + size * 0.40, center.y - size * 0.18),
Pos2::new(center.x, center.y - size * 1.05),
],
color,
Stroke::NONE,
));
}