返回 CodeWhale
ambient_life.rs
根目录 / crates / tui / src / tui / ambient_life.rs
1 //! Ambient ocean life for the underwater transcript field.
2 //!
3 //! The ocean itself (fish school, far shoal, visiting jellyfish, marine snow,
4 //! bubbles and a distant whale) is `codewhale_ratatui::Habitat`, the one
5 //! implementation the kit and the Engine share. This module only adapts the
6 //! Engine's facts to it: the ambient clock, the activity ink, the life
7 //! presence, the semantic surfaces it must leave alone, and the kit theme for
8 //! the painted water. It also owns the completion whale cameo, which draws the
9 //! Engine's pet simulation and so stays here.
10 //!
11 //! Whether life runs at all is decided by
12 //! `underwater::ambient_life_motion_enabled` (Underwater theme, full motion,
13 //! no attention hold, transcript at the tail, truecolor or 256 colours). Under
14 //! reduced motion `presence` is 0 and nothing is painted.
15 //! The habitat never changes the water's own colour, so a frame changes only
16 //! the cells a creature moves through.
17 //!
18 //! Known limits: life needs the kit paint theme, which exists only for the
19 //! painted dark Underwater ground with probed terminal capabilities; without
20 //! it the water is drawn still.
21
22 use codewhale_ratatui::Paint as _;
23 use ratatui::{buffer::Buffer, layout::Rect, style::Color, text::Line};
24 use unicode_width::UnicodeWidthChar;
25
26 use crate::tui::ocean::{self, OceanColumn};
27
28 #[path = "ambient_life/pet_cameo.rs"]
29 mod pet_cameo;
30 #[path = "ambient_life/pet_sim.rs"]
31 pub mod pet_sim;
32 #[path = "ambient_life/pet_widget.rs"]
33 pub mod pet_widget;
34
35 /// Smallest field that earns ambient life. Keep in sync with
36 /// [`crate::tui::ocean::AMBIENT_MIN_WIDTH`].
37 pub const AMBIENT_MIN_WIDTH: u16 = crate::tui::ocean::AMBIENT_MIN_WIDTH;
38 pub const AMBIENT_MIN_HEIGHT: u16 = crate::tui::ocean::AMBIENT_MIN_HEIGHT;
39
40 /// Per-frame render budget counters. `marks_built` splits exactly into
41 /// `marks_painted + marks_skipped_text + marks_clipped`. `cells_written`
42 /// counts individual cell writes: a multi-cell glyph counts each of its
43 /// cells, and two overlapping marks count the shared cell once per write.
44 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
45 pub struct AmbientFrameStats {
46 pub marks_built: u32,
47 pub marks_painted: u32,
48 pub marks_skipped_text: u32,
49 pub marks_clipped: u32,
50 pub cells_written: u32,
51 }
52
53 /// Optional whale cameo trigger (e.g. successful turn completion).
54 #[derive(Debug, Clone, Copy, Default)]
55 pub struct WhaleCameo {
56 pub elapsed_ms: Option<u128>,
57 /// Anchor column within the field (composer / center).
58 pub anchor_x: u16,
59 pub anchor_y: u16,
60 }
61
62 /// How the ambient scene is shaped by live agent activity. The underwater
63 /// used to be phase-agnostic: same fish, same pace, whether the agent was
64 /// thinking, running tools, or orchestrating sub-agents. Each treatment is a
65 /// bounded parameter shift — never a second scene graph.
66 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
67 pub enum AmbientActivity {
68 #[default]
69 Baseline,
70 Reasoning,
71 /// Read-shaped exploration: quieter than generic tool work, brighter
72 /// than hidden reasoning — skimming, not digging.
73 Reading,
74 Tools,
75 Subagents,
76 Verifying,
77 }
78
79 impl AmbientActivity {
80 #[must_use]
81 pub fn from_kind(kind: crate::tui::underwater::LiveActivityKind) -> Self {
82 match kind {
83 crate::tui::underwater::LiveActivityKind::Reasoning => Self::Reasoning,
84 crate::tui::underwater::LiveActivityKind::Reading => Self::Reading,
85 crate::tui::underwater::LiveActivityKind::UsingTool => Self::Tools,
86 crate::tui::underwater::LiveActivityKind::UsingSubagents => Self::Subagents,
87 crate::tui::underwater::LiveActivityKind::Verifying => Self::Verifying,
88 _ => Self::Baseline,
89 }
90 }
91 }
92
93 /// Paint the ocean and the completion cameo into open water in `area`.
94 ///
95 /// Returns the cameo's budget counters for tests and debug tooling.
96 #[allow(clippy::too_many_arguments)]
97 pub fn render_ambient_life(
98 area: Rect,
99 buf: &mut Buffer,
100 theme: &codewhale_ratatui::Theme,
101 ink: Color,
102 lines: &[Line<'static>],
103 elapsed_ms: u128,
104 presence: f32,
105 whale: WhaleCameo,
106 activity: AmbientActivity,
107 protected: &[Rect],
108 ) -> AmbientFrameStats {
109 let mut stats = AmbientFrameStats::default();
110 if area.width < AMBIENT_MIN_WIDTH
111 || area.height < AMBIENT_MIN_HEIGHT
112 || !presence.is_finite()
113 || presence <= 0.0
114 {
115 return stats;
116 }
117 let mut protected_rows = protected.to_vec();
118 let text_right = area.right().saturating_sub(1);
119 for y in area.top()..area.bottom() {
120 let has_text = (area.left()..text_right)
121 .any(|x| buf[(x, y)].symbol().chars().any(|ch| !ch.is_whitespace()));
122 if has_text {
123 protected_rows.push(Rect::new(area.x, y, area.width, 1));
124 }
125 }
126 let elapsed = std::time::Duration::from_millis(u64::try_from(elapsed_ms).unwrap_or(u64::MAX));
127 codewhale_ratatui::Habitat::new(elapsed, codewhale_ratatui::MotionMode::Full)
128 .ink(Some(ink))
129 .presence(presence)
130 .protected(protected_rows)
131 .paint(area, buf, theme);
132 pet_cameo::paint(area, buf, ink, lines, presence, whale, activity, &mut stats);
133 stats
134 }
135
136 /// Rows of clear air the composition keeps on each side of every line it
137 /// writes. One row is enough: it is the difference between a fish swimming
138 /// *behind* a block of text and a fish surfacing in the gap between two of its
139 /// lines, which is what the 80×24 frame showed between the caption and the
140 /// invitation.
141 const TEXT_CLEARANCE_ROWS: u16 = 1;
142
143 /// Columns of clear water kept on each side of every line of text, so life
144 /// never brushes the end of a sentence.
145 const TEXT_CLEARANCE_COLS: usize = 2;
146
147 /// True when the horizontal span at `(x, y)` — and the same span on every row
148 /// within [`TEXT_CLEARANCE_ROWS`] — carries no rendered text.
149 /// [`TEXT_CLEARANCE_COLS`] of horizontal air is reserved on both sides so life
150 /// never touches the prose, while short left-aligned transcript lines still
151 /// leave real water to their right.
152 #[must_use]
153 fn is_open_water(lines: &[Line<'_>], x: u16, y: u16, width: u16) -> bool {
154 let first = usize::from(y.saturating_sub(TEXT_CLEARANCE_ROWS));
155 let last = usize::from(y.saturating_add(TEXT_CLEARANCE_ROWS));
156 !(first..=last).any(|row| {
157 lines
158 .get(row)
159 .and_then(occupied_text_bounds)
160 .is_some_and(|(start, end)| span_touches_text(x, width, start, end))
161 })
162 }
163
164 #[must_use]
165 fn span_touches_text(x: u16, width: u16, start: usize, end: usize) -> bool {
166 usize::from(x) < end.saturating_add(TEXT_CLEARANCE_COLS)
167 && usize::from(x).saturating_add(usize::from(width))
168 > start.saturating_sub(TEXT_CLEARANCE_COLS)
169 }
170
171 /// Width-only occupied-text measurement (no per-line String allocation).
172 #[must_use]
173 pub fn occupied_text_bounds(line: &Line<'_>) -> Option<(usize, usize)> {
174 if line.spans.is_empty() {
175 return None;
176 }
177 let mut total = 0usize;
178 let mut leading = 0usize;
179 let mut seen_non_ws = false;
180 let mut trailing_run = 0usize;
181
182 for span in &line.spans {
183 for ch in span.content.chars() {
184 let w = UnicodeWidthChar::width(ch).unwrap_or(0);
185 total = total.saturating_add(w);
186 if ch.is_whitespace() {
187 if !seen_non_ws {
188 leading = leading.saturating_add(w);
189 } else {
190 trailing_run = trailing_run.saturating_add(w);
191 }
192 } else {
193 seen_non_ws = true;
194 trailing_run = 0;
195 }
196 }
197 }
198 if !seen_non_ws {
199 return None;
200 }
201 Some((leading, total.saturating_sub(trailing_run)))
202 }
203
204 /// Cached ocean row colors invalidated only when phase/dimensions/palette/breath tick.
205 /// Shared across widgets that paint the same [`OceanColumn`] within a frame.
206 #[derive(Debug, Clone, Default)]
207 pub struct OceanRampCache {
208 colors: Vec<Color>,
209 height: u16,
210 top: u16,
211 elapsed_bucket: u128,
212 phase_tag: u8,
213 ramp_fingerprint: u64,
214 }
215
216 impl OceanRampCache {
217 /// Return a per-row color ramp, recomputing only when inputs change.
218 pub fn colors_for(
219 &mut self,
220 column: &OceanColumn,
221 height: u16,
222 top: u16,
223 elapsed_ms: u128,
224 phase_tag: u8,
225 ramp_fingerprint: u64,
226 ) -> &[Color] {
227 // The breath and completion fade are continuous. Bucket at a 60 FPS
228 // floor so Ghostty's smooth-motion lane is not quantized back to the
229 // old 80 ms atmosphere cadence; slower terminals still call this only
230 // when they actually draw.
231 let bucket = elapsed_ms / 16;
232 if self.colors.len() == usize::from(height)
233 && self.height == height
234 && self.top == top
235 && self.elapsed_bucket == bucket
236 && self.phase_tag == phase_tag
237 && self.ramp_fingerprint == ramp_fingerprint
238 {
239 return &self.colors;
240 }
241 self.colors.clear();
242 self.colors.reserve(usize::from(height));
243 for local_y in 0..height {
244 self.colors
245 .push(column.color_at_y(top.saturating_add(local_y)));
246 }
247 self.height = height;
248 self.top = top;
249 self.elapsed_bucket = bucket;
250 self.phase_tag = phase_tag;
251 self.ramp_fingerprint = ramp_fingerprint;
252 &self.colors
253 }
254 }
255
256 thread_local! {
257 static FRAME_RAMP: std::cell::RefCell<OceanRampCache> =
258 const { std::cell::RefCell::new(OceanRampCache {
259 colors: Vec::new(),
260 height: 0,
261 top: 0,
262 elapsed_bucket: 0,
263 phase_tag: 0,
264 ramp_fingerprint: 0,
265 }) };
266 }
267
268 /// Process-local per-frame ocean ramp shared by the chat field and other
269 /// widgets that paint the same column.
270 #[must_use]
271 pub fn frame_ocean_ramp(
272 column: &OceanColumn,
273 height: u16,
274 top: u16,
275 elapsed_ms: u128,
276 phase_tag: u8,
277 ramp_fingerprint: u64,
278 ) -> Vec<Color> {
279 FRAME_RAMP.with(|cache| {
280 cache
281 .borrow_mut()
282 .colors_for(column, height, top, elapsed_ms, phase_tag, ramp_fingerprint)
283 .to_vec()
284 })
285 }
286
287 #[cfg(test)]
288 #[path = "ambient_life/tests.rs"]
289 mod tests;
290
290 lines RUST