Skip to main content

clairlune_render/
img2ascii.rs

1//! Image-to-ASCII conversion and custom ASCII wallpaper packaging.
2//!
3//! Converts an arbitrary RGBA image into:
4//! - plain multi-line ASCII/Unicode text (`.txt` / clipboard),
5//! - an anti-aliased RGBA image (including transparent background when asked),
6//! - a genuine [`ScenePackage`] (with both light and dark themes when using a
7//!   Clairlune palette or photo colours, plus optional live weather particles),
8//!   playable natively in Still, Live, Library, Archive, Timeline and GIF export.
9
10use crate::IndexedImage;
11use crate::atlas::GlyphAtlas;
12use crate::package::{CustomTheme, ScenePackage};
13use crate::palette::{IndexedPalette, SPRITE_BASE, TRANSPARENT_INDEX, ink_level};
14use crate::sign::SIGNATURE;
15use clairlune_scene::graph::{ADVANCE_RATIO, FONT_TO_CELL, GridSpec, Lighting, SceneGraph};
16use clairlune_scene::particles::{
17    CALM_PACE, Emitter, EmitterKind, LOOP_MS, WeatherKind, ember_set, hero_time, weather_set,
18};
19use clairlune_scene::recipe::{Composition, PalettePick};
20use clairlune_scene::{
21    Aspect, GENERATOR_VERSION, PaletteFamily, Rgb, SceneRecipe, Theme, TimeOfDay,
22};
23use serde::{Deserialize, Serialize};
24use std::collections::HashMap;
25
26/// Archetype marker stored on custom image-to-ASCII recipes.
27pub const PHOTO_ARCHETYPE: &str = "photo";
28
29/// Decoded RGBA8 source image, row-major (`width * height * 4` bytes).
30#[derive(Clone, Debug, PartialEq, Eq)]
31pub struct RgbaImage {
32    pub width: u32,
33    pub height: u32,
34    pub pixels: Vec<u8>,
35}
36
37impl RgbaImage {
38    pub fn new(width: u32, height: u32, pixels: Vec<u8>) -> Result<Self, String> {
39        let want = (width as usize)
40            .checked_mul(height as usize)
41            .and_then(|n| n.checked_mul(4))
42            .ok_or_else(|| "image dimensions overflow".to_string())?;
43        if width == 0 || height == 0 || pixels.len() != want {
44            return Err(format!(
45                "invalid RGBA image buffer ({} bytes for {width}x{height})",
46                pixels.len()
47            ));
48        }
49        Ok(Self {
50            width,
51            height,
52            pixels,
53        })
54    }
55
56    /// Downscales the image if its longest side exceeds `max_side`, keeping
57    /// saved archive/library copies compact while preserving full ASCII detail.
58    pub fn capped(&self, max_side: u32) -> Self {
59        let longest = self.width.max(self.height);
60        if longest <= max_side || max_side == 0 {
61            return self.clone();
62        }
63        let nw = ((u64::from(self.width) * u64::from(max_side)) / u64::from(longest)).max(1) as u32;
64        let nh =
65            ((u64::from(self.height) * u64::from(max_side)) / u64::from(longest)).max(1) as u32;
66        let mut out = vec![0u8; (nw * nh * 4) as usize];
67        for y in 0..nh {
68            let y0 = f64::from(y) * f64::from(self.height) / f64::from(nh);
69            let y1 = f64::from(y + 1) * f64::from(self.height) / f64::from(nh);
70            for x in 0..nw {
71                let x0 = f64::from(x) * f64::from(self.width) / f64::from(nw);
72                let x1 = f64::from(x + 1) * f64::from(self.width) / f64::from(nw);
73                let s = sample_box(self, x0, y0, x1, y1);
74                let idx = ((y * nw + x) * 4) as usize;
75                out[idx..idx + 4].copy_from_slice(&[s.r, s.g, s.b, s.a]);
76            }
77        }
78        Self {
79            width: nw,
80            height: nh,
81            pixels: out,
82        }
83    }
84}
85
86/// Line-height / character aspect ratio for standalone `.txt` and PNG output.
87#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
88#[serde(rename_all = "snake_case")]
89pub enum RowDensity {
90    /// Matches Clairlune's JetBrains Mono cell geometry (`0.54`).
91    #[default]
92    Auto,
93    /// Tighter terminal spacing (`0.45`).
94    Compact,
95    /// Classic 1:2 terminal cell (`0.50`).
96    Standard,
97    /// Looser editor/prose line spacing (`0.62`).
98    Tall,
99}
100
101impl RowDensity {
102    /// Width-to-height ratio of one character cell.
103    pub fn cell_aspect(self) -> f64 {
104        match self {
105            RowDensity::Auto => ADVANCE_RATIO * FONT_TO_CELL,
106            RowDensity::Compact => 0.45,
107            RowDensity::Standard => 0.50,
108            RowDensity::Tall => 0.62,
109        }
110    }
111}
112
113/// Character ramp ordered from heaviest ink to lightest (`' '` last in the UI).
114#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
115#[serde(rename_all = "snake_case")]
116pub enum RampPreset {
117    #[default]
118    Standard,
119    Detailed,
120    Dither,
121    Braille,
122    Blocks,
123    Lines,
124    Kana,
125    Shapes,
126    Hex,
127    Custom,
128}
129
130impl RampPreset {
131    pub const ALL: [RampPreset; 10] = [
132        RampPreset::Standard,
133        RampPreset::Detailed,
134        RampPreset::Dither,
135        RampPreset::Braille,
136        RampPreset::Blocks,
137        RampPreset::Lines,
138        RampPreset::Kana,
139        RampPreset::Shapes,
140        RampPreset::Hex,
141        RampPreset::Custom,
142    ];
143
144    pub fn label(self) -> &'static str {
145        match self {
146            RampPreset::Standard => "Standard, 10 levels",
147            RampPreset::Detailed => "Detailed, 70 levels",
148            RampPreset::Dither => "Dithered, 7 levels",
149            RampPreset::Braille => "Braille, 2×4 dots",
150            RampPreset::Blocks => "Blocks, 5 levels",
151            RampPreset::Lines => "Box lines, 8 levels",
152            RampPreset::Kana => "Katakana, 10 levels",
153            RampPreset::Shapes => "Geometric shapes, 9 levels",
154            RampPreset::Hex => "Hex digits, 9 levels",
155            RampPreset::Custom => "Custom ramp",
156        }
157    }
158
159    /// Characters ordered heaviest to lightest (as shown in the UI).
160    pub fn heavy_to_light(self, custom: &str) -> Vec<char> {
161        let s = match self {
162            RampPreset::Standard => "@%#*+=-:. ",
163            RampPreset::Detailed => {
164                "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/|()1{}[]?-_+~<>i!lI;:,\"^`'. "
165            }
166            RampPreset::Dither => "■●━▪•· ",
167            RampPreset::Braille => "⣿⣷⣯⣟⡿⢿⣻⣽⣾⣶⣦⣤⣄⣀⡀ ",
168            RampPreset::Blocks => "█▓▒░ ",
169            RampPreset::Lines => "╬╋╪┼═─· ",
170            RampPreset::Kana => "ヰモムヌメミニー・ ",
171            RampPreset::Shapes => "■●◆▪▫○◦· ",
172            RampPreset::Hex => "8BECF731 ",
173            RampPreset::Custom => {
174                let mut chars: Vec<char> = Vec::new();
175                for ch in custom.chars() {
176                    if ch != ' '
177                        && !ch.is_control()
178                        && GlyphAtlas::can_render_char(ch)
179                        && !chars.contains(&ch)
180                    {
181                        chars.push(ch);
182                        if chars.len() >= 250 {
183                            break;
184                        }
185                    }
186                }
187                if chars.is_empty() {
188                    chars = "@%#*+=-:.".chars().collect();
189                }
190                chars.push(' ');
191                return chars;
192            }
193        };
194        s.chars().collect()
195    }
196
197    /// Characters ordered lightest (`' '`) to heaviest (for density indexing).
198    pub fn light_to_heavy(self, custom: &str) -> Vec<char> {
199        let mut v = self.heavy_to_light(custom);
200        v.reverse();
201        v
202    }
203
204    /// Matching Clairlune letter set for ambient weather particles.
205    pub fn weather_letters(self) -> &'static str {
206        match self {
207            RampPreset::Braille => "braille",
208            RampPreset::Blocks => "blocks",
209            RampPreset::Lines => "lines",
210            RampPreset::Kana => "kana",
211            RampPreset::Shapes => "shapes",
212            RampPreset::Hex => "hex",
213            _ => "text",
214        }
215    }
216}
217
218/// How the converted ASCII art is coloured and backed.
219#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
220#[serde(tag = "kind", content = "palette", rename_all = "snake_case")]
221pub enum AsciiColorMode {
222    /// One of Clairlune's 12 palettes (both light and dark themes).
223    Palette(String),
224    /// Pure black background (`#000000`) with white characters.
225    Black,
226    /// Pure white background (`#FFFFFF`) with black characters.
227    White,
228    /// Transparent background on PNG export; dark polarity by default.
229    None,
230    /// Each character takes its colour from the source image.
231    Photo,
232}
233
234impl Default for AsciiColorMode {
235    fn default() -> Self {
236        AsciiColorMode::Palette("classic".into())
237    }
238}
239
240/// How an image fits a monitor whose aspect ratio differs from the image's.
241#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
242#[serde(rename_all = "snake_case")]
243pub enum FitMode {
244    Cover,
245    #[default]
246    Contain,
247}
248
249/// Full user-configurable settings for an image-to-ASCII conversion.
250#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
251pub struct AsciiConfig {
252    /// Number of columns across (`20..=320`).
253    pub columns: u32,
254    #[serde(default)]
255    pub row_density: RowDensity,
256    #[serde(default)]
257    pub ramp: RampPreset,
258    #[serde(default = "default_custom_ramp")]
259    pub custom_ramp: String,
260    /// Contrast percentage (`50..=250`; `100` is neutral, `120` is crisp).
261    pub contrast: i32,
262    /// Brightness shift (`-100..=100`; `0` is neutral).
263    pub brightness: i32,
264    /// Invert light/dark polarity.
265    #[serde(default)]
266    pub invert: bool,
267    #[serde(default)]
268    pub color_mode: AsciiColorMode,
269    /// Optional ambient weather id (`"none"`, `"snow"`, `"fireflies"`, ...).
270    #[serde(default = "none_weather")]
271    pub weather: String,
272    #[serde(default)]
273    pub fit: FitMode,
274}
275
276fn default_custom_ramp() -> String {
277    "@%#*+=-:. ".into()
278}
279
280fn none_weather() -> String {
281    "none".into()
282}
283
284impl Default for AsciiConfig {
285    fn default() -> Self {
286        Self {
287            columns: 110,
288            row_density: RowDensity::Auto,
289            ramp: RampPreset::Standard,
290            custom_ramp: default_custom_ramp(),
291            contrast: 120,
292            brightness: 0,
293            invert: false,
294            color_mode: AsciiColorMode::Palette("classic".into()),
295            weather: none_weather(),
296            fit: FitMode::Contain,
297        }
298    }
299}
300
301impl AsciiConfig {
302    /// Whether `theme` uses dark-background polarity (characters represent light)
303    /// before applying `self.invert`.
304    pub fn dark_canvas(&self, theme: Theme) -> bool {
305        match &self.color_mode {
306            AsciiColorMode::Black => true,
307            AsciiColorMode::White => false,
308            AsciiColorMode::Palette(_) | AsciiColorMode::Photo | AsciiColorMode::None => {
309                theme == Theme::Dark
310            }
311        }
312    }
313
314    /// Whether `self.weather` resolves to an animated particle emitter.
315    pub fn has_live_weather(&self) -> bool {
316        WeatherKind::from_id(&self.weather).is_some()
317    }
318}
319
320/// Converted character grid with per-cell colour, opacity and plain text.
321#[derive(Clone, Debug)]
322pub struct AsciiArt {
323    pub cols: u32,
324    pub rows: u32,
325    pub chars: Vec<char>,
326    pub colors: Vec<[u8; 3]>,
327    /// Sampled source alpha (`0..=255`) per cell.
328    pub alphas: Vec<u8>,
329    /// Multi-line text (`\n`-separated rows, trailing spaces trimmed on empty right margins
330    /// kept uniform as exact `cols` characters per row so alignment never shifts).
331    pub text: String,
332}
333
334#[derive(Clone, Copy, Default)]
335struct Sample {
336    r: u8,
337    g: u8,
338    b: u8,
339    a: u8,
340}
341
342/// Exact area-weighted box average over `[x0, x1] x [y0, y1]` in source pixel space.
343fn sample_box(src: &RgbaImage, x0: f64, y0: f64, x1: f64, y1: f64) -> Sample {
344    let w = src.width as i32;
345    let h = src.height as i32;
346    let x0 = x0.clamp(0.0, f64::from(src.width));
347    let y0 = y0.clamp(0.0, f64::from(src.height));
348    let x1 = x1.clamp(x0, f64::from(src.width));
349    let y1 = y1.clamp(y0, f64::from(src.height));
350    let ix0 = (x0.floor() as i32).clamp(0, w - 1);
351    let iy0 = (y0.floor() as i32).clamp(0, h - 1);
352    let ix1 = (x1.ceil() as i32).clamp(ix0 + 1, w);
353    let iy1 = (y1.ceil() as i32).clamp(iy0 + 1, h);
354
355    let mut wr = 0.0;
356    let mut wg = 0.0;
357    let mut wb = 0.0;
358    let mut wa = 0.0;
359    let mut w_rgb = 0.0;
360    let mut w_tot = 0.0;
361
362    for py in iy0..iy1 {
363        let oy = (f64::from(py + 1).min(y1) - f64::from(py).max(y0)).max(0.0);
364        if oy <= 0.0 {
365            continue;
366        }
367        for px in ix0..ix1 {
368            let ox = (f64::from(px + 1).min(x1) - f64::from(px).max(x0)).max(0.0);
369            let area = ox * oy;
370            if area <= 0.0 {
371                continue;
372            }
373            let idx = ((py as u32 * src.width + px as u32) * 4) as usize;
374            let r = f64::from(src.pixels[idx]);
375            let g = f64::from(src.pixels[idx + 1]);
376            let b = f64::from(src.pixels[idx + 2]);
377            let a = f64::from(src.pixels[idx + 3]);
378            let alpha_w = area * (a / 255.0);
379            wr += r * alpha_w;
380            wg += g * alpha_w;
381            wb += b * alpha_w;
382            w_rgb += alpha_w;
383            wa += a * area;
384            w_tot += area;
385        }
386    }
387    if w_tot <= 0.0 {
388        return Sample::default();
389    }
390    let a = (wa / w_tot).round().clamp(0.0, 255.0) as u8;
391    if w_rgb <= 1e-6 {
392        return Sample {
393            r: 0,
394            g: 0,
395            b: 0,
396            a,
397        };
398    }
399    Sample {
400        r: (wr / w_rgb).round().clamp(0.0, 255.0) as u8,
401        g: (wg / w_rgb).round().clamp(0.0, 255.0) as u8,
402        b: (wb / w_rgb).round().clamp(0.0, 255.0) as u8,
403        a,
404    }
405}
406
407/// Applies brightness (`-100..=100`), contrast (`50..=250`), alpha compositing
408/// over the canvas polarity, and optional inversion to produce ink density in `0..=1`.
409fn ink_density(s: Sample, config: &AsciiConfig, dark_canvas: bool) -> f64 {
410    if s.a < 16 {
411        return 0.0;
412    }
413    let alpha = f64::from(s.a) / 255.0;
414    let bg_luma = if dark_canvas { 0.0 } else { 1.0 };
415    let raw_luma =
416        (0.2126 * f64::from(s.r) + 0.7152 * f64::from(s.g) + 0.0722 * f64::from(s.b)) / 255.0;
417    let luma = raw_luma * alpha + bg_luma * (1.0 - alpha);
418    let bright = luma + f64::from(config.brightness.clamp(-100, 100)) / 180.0;
419    let contrast = f64::from(config.contrast.clamp(40, 300)) / 100.0;
420    let adjusted = ((bright - 0.5) * contrast + 0.5).clamp(0.0, 1.0);
421    let polarity = if dark_canvas {
422        adjusted
423    } else {
424        1.0 - adjusted
425    };
426    if config.invert {
427        1.0 - polarity
428    } else {
429        polarity
430    }
431}
432
433/// Converts `src` using its natural aspect ratio (for the Studio preview, `.txt`
434/// export and standalone PNG export).
435pub fn convert_standalone(src: &RgbaImage, config: &AsciiConfig, theme: Theme) -> AsciiArt {
436    let cols = config.columns.clamp(20, 320);
437    let img_aspect = f64::from(src.height) / f64::from(src.width.max(1));
438    let rows = ((f64::from(cols) * img_aspect * config.row_density.cell_aspect()).round() as u32)
439        .clamp(8, 320);
440    convert_grid(src, config, theme, cols, rows, None)
441}
442
443/// Converts `src` onto a fixed `(cols, rows)` wallpaper grid, cropping (`Cover`)
444/// or centring (`Contain`) according to `config.fit` and cell pixel aspect `cell_w / cell_h`.
445pub fn convert_for_grid(
446    src: &RgbaImage,
447    config: &AsciiConfig,
448    theme: Theme,
449    cols: u32,
450    rows: u32,
451    cell_w: u32,
452    cell_h: u32,
453) -> AsciiArt {
454    let grid_px_w = f64::from(cols * cell_w.max(1));
455    let grid_px_h = f64::from(rows * cell_h.max(1));
456    convert_grid(src, config, theme, cols, rows, Some((grid_px_w, grid_px_h)))
457}
458
459fn convert_grid(
460    src: &RgbaImage,
461    config: &AsciiConfig,
462    theme: Theme,
463    cols: u32,
464    rows: u32,
465    screen_px: Option<(f64, f64)>,
466) -> AsciiArt {
467    let dark_canvas = config.dark_canvas(theme);
468    let ramp = config.ramp.light_to_heavy(&config.custom_ramp);
469    let n = (cols * rows) as usize;
470    let mut chars = vec![' '; n];
471    let mut colors = vec![[0u8; 3]; n];
472    let mut alphas = vec![0u8; n];
473
474    let sw = f64::from(src.width);
475    let sh = f64::from(src.height);
476
477    // Map cell coordinates [0..cols] x [0..rows] into source pixel space.
478    // Either full source (standalone), Cover crop, or Contain letterbox.
479    let (crop_x, crop_y, crop_w, crop_h, dst_x0, dst_y0, dst_w, dst_h) = match screen_px {
480        None => (0.0, 0.0, sw, sh, 0.0, 0.0, f64::from(cols), f64::from(rows)),
481        Some((gw, gh)) => {
482            let src_ratio = sw / sh.max(1.0);
483            let dst_ratio = gw / gh.max(1.0);
484            match config.fit {
485                FitMode::Cover => {
486                    if src_ratio > dst_ratio {
487                        let cw = sh * dst_ratio;
488                        (
489                            (sw - cw) * 0.5,
490                            0.0,
491                            cw,
492                            sh,
493                            0.0,
494                            0.0,
495                            f64::from(cols),
496                            f64::from(rows),
497                        )
498                    } else {
499                        let ch = sw / dst_ratio;
500                        (
501                            0.0,
502                            (sh - ch) * 0.5,
503                            sw,
504                            ch,
505                            0.0,
506                            0.0,
507                            f64::from(cols),
508                            f64::from(rows),
509                        )
510                    }
511                }
512                FitMode::Contain => {
513                    if src_ratio > dst_ratio {
514                        let dh = (f64::from(rows) * (dst_ratio / src_ratio)).max(1.0);
515                        (
516                            0.0,
517                            0.0,
518                            sw,
519                            sh,
520                            0.0,
521                            (f64::from(rows) - dh).max(0.0) * 0.5,
522                            f64::from(cols),
523                            dh,
524                        )
525                    } else {
526                        let dw = (f64::from(cols) * (src_ratio / dst_ratio)).max(1.0);
527                        (
528                            0.0,
529                            0.0,
530                            sw,
531                            sh,
532                            (f64::from(cols) - dw).max(0.0) * 0.5,
533                            0.0,
534                            dw,
535                            f64::from(rows),
536                        )
537                    }
538                }
539            }
540        }
541    };
542
543    let canvas_bg = resolve_family(&config.color_mode, theme).bg_center;
544    const BAYER_2X4: [[f64; 2]; 4] = [[-0.07, 0.02], [0.05, -0.04], [-0.02, 0.07], [0.04, -0.05]];
545    const BRAILLE_BITS: [[u8; 2]; 4] = [[0, 3], [1, 4], [2, 5], [6, 7]];
546
547    for row in 0..rows {
548        let ry0 = f64::from(row);
549        let ry1 = f64::from(row + 1);
550        if ry1 <= dst_y0 || ry0 >= dst_y0 + dst_h {
551            continue;
552        }
553        let u_y0 = ((ry0 - dst_y0) / dst_h).clamp(0.0, 1.0);
554        let u_y1 = ((ry1 - dst_y0) / dst_h).clamp(0.0, 1.0);
555        let sy0 = crop_y + u_y0 * crop_h;
556        let sy1 = crop_y + u_y1 * crop_h;
557
558        for col in 0..cols {
559            let cx0 = f64::from(col);
560            let cx1 = f64::from(col + 1);
561            if cx1 <= dst_x0 || cx0 >= dst_x0 + dst_w {
562                continue;
563            }
564            let u_x0 = ((cx0 - dst_x0) / dst_w).clamp(0.0, 1.0);
565            let u_x1 = ((cx1 - dst_x0) / dst_w).clamp(0.0, 1.0);
566            let sx0 = crop_x + u_x0 * crop_w;
567            let sx1 = crop_x + u_x1 * crop_w;
568
569            let idx = (row * cols + col) as usize;
570            let cell_sample = sample_box(src, sx0, sy0, sx1, sy1);
571            if cell_sample.a == 0 {
572                continue;
573            }
574            let composited = if cell_sample.a < 255 {
575                let t = f64::from(cell_sample.a) / 255.0;
576                let mixed = canvas_bg.mix(
577                    Rgb {
578                        r: cell_sample.r,
579                        g: cell_sample.g,
580                        b: cell_sample.b,
581                    },
582                    t,
583                );
584                Sample {
585                    r: mixed.r,
586                    g: mixed.g,
587                    b: mixed.b,
588                    a: cell_sample.a,
589                }
590            } else {
591                cell_sample
592            };
593            colors[idx] = readable_photo_rgb(composited, dark_canvas);
594
595            if config.ramp == RampPreset::Braille {
596                // 2x4 sub-cell braille sampling for sharp edges and stippled gradients.
597                let mut mask = 0u8;
598                let mut sum = 0.0;
599                let mut max_sub_a = cell_sample.a;
600                for (dy, bit_row) in BRAILLE_BITS.iter().enumerate() {
601                    let by0 = sy0 + (sy1 - sy0) * (dy as f64 / 4.0);
602                    let by1 = sy0 + (sy1 - sy0) * ((dy + 1) as f64 / 4.0);
603                    for (dx, &bit) in bit_row.iter().enumerate() {
604                        let bx0 = sx0 + (sx1 - sx0) * (dx as f64 / 2.0);
605                        let bx1 = sx0 + (sx1 - sx0) * ((dx + 1) as f64 / 2.0);
606                        let sub = sample_box(src, bx0, by0, bx1, by1);
607                        max_sub_a = max_sub_a.max(sub.a);
608                        let d = ink_density(sub, config, dark_canvas);
609                        sum += d;
610                        if d + BAYER_2X4[dy][dx] >= 0.34 {
611                            mask |= 1 << bit;
612                        }
613                    }
614                }
615                if max_sub_a < 16 {
616                    continue;
617                }
618                alphas[idx] = if mask != 0 { max_sub_a } else { cell_sample.a };
619                if mask == 0 && sum / 8.0 > 0.14 {
620                    mask = 1 << 6;
621                    alphas[idx] = max_sub_a;
622                }
623                chars[idx] = if mask == 0 {
624                    ' '
625                } else {
626                    char::from_u32(0x2800 + u32::from(mask)).unwrap_or(' ')
627                };
628            } else {
629                if cell_sample.a < 16 {
630                    continue;
631                }
632                alphas[idx] = cell_sample.a;
633                let d = ink_density(cell_sample, config, dark_canvas);
634                let max_i = ramp.len().saturating_sub(1);
635                let ri = (d * max_i as f64).round().clamp(0.0, max_i as f64) as usize;
636                chars[idx] = ramp[ri];
637            }
638        }
639    }
640
641    let mut text = String::with_capacity(((cols + 1) * rows) as usize);
642    for r in 0..rows {
643        if r > 0 {
644            text.push('\n');
645        }
646        let start = (r * cols) as usize;
647        let line: String = chars[start..start + cols as usize].iter().collect();
648        text.push_str(line.trim_end_matches(' '));
649    }
650
651    AsciiArt {
652        cols,
653        rows,
654        chars,
655        colors,
656        alphas,
657        text,
658    }
659}
660
661/// Ensures photo-coloured glyphs keep legible contrast against the chosen canvas.
662fn readable_photo_rgb(s: Sample, dark_canvas: bool) -> [u8; 3] {
663    let luma = (u32::from(s.r) * 2126 + u32::from(s.g) * 7152 + u32::from(s.b) * 722) / 10_000;
664    if dark_canvas && luma < 48 {
665        let lift = (48 - luma) as u8;
666        [
667            s.r.saturating_add(lift),
668            s.g.saturating_add(lift),
669            s.b.saturating_add(lift),
670        ]
671    } else if !dark_canvas && luma > 212 {
672        let drop = (luma - 212) as u8;
673        [
674            s.r.saturating_sub(drop),
675            s.g.saturating_sub(drop),
676            s.b.saturating_sub(drop),
677        ]
678    } else {
679        [s.r, s.g, s.b]
680    }
681}
682
683/// Resolves the `PaletteFamily` for a `(color_mode, theme)` pair.
684pub fn resolve_family(mode: &AsciiColorMode, theme: Theme) -> PaletteFamily {
685    match mode {
686        AsciiColorMode::Palette(set) => clairlune_scene::palette::families_in(set, theme)
687            .next()
688            .copied()
689            .or_else(|| {
690                clairlune_scene::palette::families_for(theme)
691                    .next()
692                    .copied()
693            })
694            .expect("classic palette exists"),
695        AsciiColorMode::Black => PaletteFamily {
696            id: "ascii_black",
697            set: "classic",
698            theme: Theme::Dark,
699            bg_edge: Rgb::hex(0x000000),
700            bg_center: Rgb::hex(0x000000),
701            ink: Rgb::hex(0xF2F2F2),
702            accent: Rgb::hex(0xFF9646),
703            ember: Rgb::hex(0xFFB066),
704            glow_strength: 0.14,
705            tint_strength: 0.50,
706        },
707        AsciiColorMode::White => PaletteFamily {
708            id: "ascii_white",
709            set: "classic",
710            theme: Theme::Light,
711            bg_edge: Rgb::hex(0xFFFFFF),
712            bg_center: Rgb::hex(0xFFFFFF),
713            ink: Rgb::hex(0x141414),
714            accent: Rgb::hex(0xD9652B),
715            ember: Rgb::hex(0xCF5320),
716            glow_strength: 0.10,
717            tint_strength: 0.45,
718        },
719        AsciiColorMode::None => match theme {
720            Theme::Dark => PaletteFamily {
721                id: "ascii_black",
722                set: "classic",
723                theme: Theme::Dark,
724                bg_edge: Rgb::hex(0x000000),
725                bg_center: Rgb::hex(0x000000),
726                ink: Rgb::hex(0xF2F2F2),
727                accent: Rgb::hex(0xFF9646),
728                ember: Rgb::hex(0xFFB066),
729                glow_strength: 0.14,
730                tint_strength: 0.50,
731            },
732            Theme::Light => PaletteFamily {
733                id: "ascii_white",
734                set: "classic",
735                theme: Theme::Light,
736                bg_edge: Rgb::hex(0xFFFFFF),
737                bg_center: Rgb::hex(0xFFFFFF),
738                ink: Rgb::hex(0x141414),
739                accent: Rgb::hex(0xD9652B),
740                ember: Rgb::hex(0xCF5320),
741                glow_strength: 0.10,
742                tint_strength: 0.45,
743            },
744        },
745        AsciiColorMode::Photo => match theme {
746            Theme::Dark => PaletteFamily {
747                id: "photo_dark",
748                set: "classic",
749                theme: Theme::Dark,
750                bg_edge: Rgb::hex(0x0B0C10),
751                bg_center: Rgb::hex(0x13151C),
752                ink: Rgb::hex(0xE9E5D7),
753                accent: Rgb::hex(0xFF9646),
754                ember: Rgb::hex(0xFFA65C),
755                glow_strength: 0.16,
756                tint_strength: 0.55,
757            },
758            Theme::Light => PaletteFamily {
759                id: "photo_light",
760                set: "classic",
761                theme: Theme::Light,
762                bg_edge: Rgb::hex(0xEAE6DC),
763                bg_center: Rgb::hex(0xF6F3EC),
764                ink: Rgb::hex(0x1C1A17),
765                accent: Rgb::hex(0xD9652B),
766                ember: Rgb::hex(0xCF5320),
767                glow_strength: 0.10,
768                tint_strength: 0.50,
769            },
770        },
771    }
772}
773
774/// Rasterizes every unique character in `chars` in chunks of `<= 200` glyphs,
775/// returning `(per_cell_glyph_id, contiguous_masks)` with `0` reserved for `' '`.
776fn rasterize_unique_chars(
777    chars: &[char],
778    cell_w: u32,
779    cell_h: u32,
780    font_px: f64,
781) -> (Vec<u16>, Vec<u8>) {
782    let mut unique: Vec<char> = vec![' '];
783    let mut map: HashMap<char, u16> = HashMap::new();
784    map.insert(' ', 0);
785    let mut ids = Vec::with_capacity(chars.len());
786    for &c in chars {
787        let id = if let Some(&id) = map.get(&c) {
788            id
789        } else {
790            let id = unique.len() as u16;
791            unique.push(c);
792            map.insert(c, id);
793            id
794        };
795        ids.push(id);
796    }
797    let cell_len = (cell_w * cell_h) as usize;
798    let mut all_masks = vec![0u8; unique.len() * cell_len];
799    for (chunk_idx, chunk) in unique.chunks(200).enumerate() {
800        let atlas = GlyphAtlas::for_char_set(chunk, cell_w, cell_h, font_px);
801        for (local_i, _) in chunk.iter().enumerate() {
802            let global_i = chunk_idx * 200 + local_i;
803            all_masks[global_i * cell_len..(global_i + 1) * cell_len]
804                .copy_from_slice(atlas.mask(local_i as u8));
805        }
806    }
807    (ids, all_masks)
808}
809
810/// Renders `art` to an RGBA8 image (`width, height, pixels`), supporting
811/// transparent backgrounds (`AsciiColorMode::None`), photo colours, palettes,
812/// and optional corner signature on opaque exports.
813pub fn render_rgba(
814    art: &AsciiArt,
815    config: &AsciiConfig,
816    theme: Theme,
817    cell_h: u32,
818    sign: bool,
819) -> (u32, u32, Vec<u8>) {
820    let cell_h = cell_h.max(8);
821    let cell_w = ((f64::from(cell_h) * FONT_TO_CELL * ADVANCE_RATIO).round() as u32).max(4);
822    let transparent = config.color_mode == AsciiColorMode::None;
823    let pad_x = cell_w * 2;
824    let pad_y = cell_h;
825    let sig_pad_bottom = if sign && !transparent {
826        cell_h.max(16) + 8
827    } else {
828        0
829    };
830    let width = art.cols * cell_w + pad_x * 2;
831    let height = art.rows * cell_h + pad_y * 2 + sig_pad_bottom;
832
833    let family = resolve_family(&config.color_mode, theme);
834    let lighting = Lighting {
835        vignette_cx: f64::from(width) * 0.5,
836        vignette_cy: f64::from(height) * 0.5,
837        vignette_rx: f64::from(width) * 0.78,
838        vignette_ry: f64::from(height) * 0.78,
839        glow: None,
840    };
841
842    let mut rgba = vec![0u8; (width * height * 4) as usize];
843    if !transparent {
844        let flat = matches!(
845            config.color_mode,
846            AsciiColorMode::Black | AsciiColorMode::White
847        );
848        for y in 0..height {
849            let rt = lighting.row_terms(y);
850            for x in 0..width {
851                let bg = if flat {
852                    family.bg_center
853                } else {
854                    let b = lighting.band_in_row(&rt, x).min(3);
855                    family.bg_edge.mix(family.bg_center, f64::from(b) / 3.0)
856                };
857                let o = ((y * width + x) * 4) as usize;
858                rgba[o] = bg.r;
859                rgba[o + 1] = bg.g;
860                rgba[o + 2] = bg.b;
861                rgba[o + 3] = 255;
862            }
863        }
864    }
865
866    let font_px = f64::from(cell_h) * FONT_TO_CELL;
867    let (glyph_ids, all_masks) = rasterize_unique_chars(&art.chars, cell_w, cell_h, font_px);
868    let cell_len = (cell_w * cell_h) as usize;
869
870    for row in 0..art.rows {
871        for col in 0..art.cols {
872            let ci = (row * art.cols + col) as usize;
873            let gid = glyph_ids[ci] as usize;
874            if gid == 0 {
875                continue;
876            }
877            let mask = &all_masks[gid * cell_len..(gid + 1) * cell_len];
878            let ink = if config.color_mode == AsciiColorMode::Photo {
879                let [r, g, b] = art.colors[ci];
880                Rgb { r, g, b }
881            } else {
882                family.ink
883            };
884            let x0 = pad_x + col * cell_w;
885            let y0 = pad_y + row * cell_h;
886            for my in 0..cell_h {
887                for mx in 0..cell_w {
888                    let a = mask[(my * cell_w + mx) as usize];
889                    if a == 0 {
890                        continue;
891                    }
892                    let o = (((y0 + my) * width + (x0 + mx)) * 4) as usize;
893                    if transparent {
894                        let scaled_a =
895                            ((u16::from(a) * u16::from(art.alphas[ci]) + 127) / 255) as u8;
896                        if scaled_a == 0 {
897                            continue;
898                        }
899                        rgba[o] = ink.r;
900                        rgba[o + 1] = ink.g;
901                        rgba[o + 2] = ink.b;
902                        rgba[o + 3] = scaled_a;
903                    } else {
904                        let t = f64::from(a) / 255.0;
905                        let cur = Rgb {
906                            r: rgba[o],
907                            g: rgba[o + 1],
908                            b: rgba[o + 2],
909                        };
910                        let m = cur.mix(ink, t);
911                        rgba[o] = m.r;
912                        rgba[o + 1] = m.g;
913                        rgba[o + 2] = m.b;
914                        rgba[o + 3] = 255;
915                    }
916                }
917            }
918        }
919    }
920
921    if sign && !transparent {
922        stamp_rgba_signature(&mut rgba, width, height, family.ink);
923    }
924
925    (width, height, rgba)
926}
927
928fn stamp_rgba_signature(rgba: &mut [u8], width: u32, height: u32, ink: Rgb) {
929    let spec = clairlune_scene::grid_spec(width, height);
930    let chars: Vec<char> = SIGNATURE.chars().collect();
931    let n = chars.len() as u32;
932    if spec.cols < 2 * (n + 3) || spec.rows < 6 {
933        return;
934    }
935    let Ok(atlas) = GlyphAtlas::with_chars(
936        crate::atlas::FONT_DATA,
937        &chars,
938        spec.cell_w,
939        spec.cell_h,
940        spec.font_px,
941    ) else {
942        return;
943    };
944    let x0 = spec.origin_x + (spec.cols - n - 2) * spec.cell_w;
945    let y0 = spec.origin_y + (spec.rows - 2) * spec.cell_h;
946    for c in 0..n {
947        let mask = atlas.mask(c as u8);
948        for my in 0..spec.cell_h {
949            for mx in 0..spec.cell_w {
950                let a = mask[(my * spec.cell_w + mx) as usize];
951                if a == 0 {
952                    continue;
953                }
954                let px = x0 + c * spec.cell_w + mx;
955                let py = y0 + my;
956                if px >= width || py >= height {
957                    continue;
958                }
959                let o = ((py * width + px) * 4) as usize;
960                let cur = Rgb {
961                    r: rgba[o],
962                    g: rgba[o + 1],
963                    b: rgba[o + 2],
964                };
965                let m = cur.mix(ink, (f64::from(a) / 255.0) * 0.65);
966                rgba[o] = m.r;
967                rgba[o + 1] = m.g;
968                rgba[o + 2] = m.b;
969            }
970        }
971    }
972}
973
974/// Encodes an RGBA8 image buffer as a PNG.
975pub fn encode_rgba_png(width: u32, height: u32, rgba: &[u8]) -> Result<Vec<u8>, String> {
976    let mut out = Vec::new();
977    {
978        let mut enc = png::Encoder::new(&mut out, width, height);
979        enc.set_color(png::ColorType::Rgba);
980        enc.set_depth(png::BitDepth::Eight);
981        let mut writer = enc.write_header().map_err(|e| e.to_string())?;
982        writer.write_image_data(rgba).map_err(|e| e.to_string())?;
983    }
984    Ok(out)
985}
986
987/// Builds a frozen [`ScenePackage`] at `(width, height)` for a user image,
988/// complete with both themes (unless fixed to Black or White) and optional
989/// live weather particles.
990pub fn build_photo_package(
991    src: &RgbaImage,
992    config: &AsciiConfig,
993    width: u32,
994    height: u32,
995    seed: u64,
996) -> Result<ScenePackage, String> {
997    if width < 160 || height < 90 {
998        return Err(format!("{width}x{height} is too small (minimum 160x90)"));
999    }
1000
1001    let wanted_cols = config.columns.clamp(24, 320);
1002    let max_cell_w = (width / wanted_cols).max(3);
1003    let cell_h_from_cols =
1004        ((f64::from(max_cell_w) / (ADVANCE_RATIO * FONT_TO_CELL)).round() as u32).max(6);
1005    let font_px = f64::from(cell_h_from_cols) * FONT_TO_CELL;
1006    let cell_w = ((font_px * ADVANCE_RATIO).round() as u32)
1007        .clamp(3, width)
1008        .min(max_cell_w);
1009    let cell_h = cell_h_from_cols.min(height);
1010    let cols = (width / cell_w).max(1);
1011    let rows = (height / cell_h).max(1);
1012    let ascii_grid = GridSpec {
1013        cols,
1014        rows,
1015        cell_w,
1016        cell_h,
1017        origin_x: (width - cols * cell_w) / 2,
1018        origin_y: (height - rows * cell_h) / 2,
1019        font_px,
1020    };
1021    // Weather particles use the screen's standard scene grid so snowflakes/rain
1022    // stay crisp regardless of how wide or narrow `config.columns` is set.
1023    let scene_grid = clairlune_scene::grid_spec(width, height);
1024
1025    let themes_to_build: &[Theme] = match config.color_mode {
1026        AsciiColorMode::Black => &[Theme::Dark],
1027        AsciiColorMode::White => &[Theme::Light],
1028        AsciiColorMode::Palette(_) | AsciiColorMode::None | AsciiColorMode::Photo => {
1029            &[Theme::Dark, Theme::Light]
1030        }
1031    };
1032
1033    let letters = config.ramp.weather_letters();
1034    let weather_atlas = GlyphAtlas::for_letters(&scene_grid, letters);
1035    let embers = ember_set(seed, CALM_PACE);
1036    let t_hero_ms = hero_time(&embers);
1037    let aspect = f64::from(width) / f64::from(height);
1038    let unit = f64::from(width.min(height));
1039
1040    let mut emitters = Vec::new();
1041    if let Some(kind) = WeatherKind::from_id(&config.weather) {
1042        emitters.push(Emitter {
1043            kind: EmitterKind::Weather(kind),
1044            origin_x: 0.0,
1045            origin_y: 0.0,
1046            unit,
1047            intensity: 1.0,
1048            embers: Vec::new(),
1049            drops: weather_set(kind, seed, aspect, CALM_PACE),
1050            size: (f64::from(width), f64::from(height)),
1051            pace: CALM_PACE,
1052        });
1053    }
1054
1055    let mut custom_themes = Vec::with_capacity(themes_to_build.len());
1056    for &theme in themes_to_build {
1057        let tod = match theme {
1058            Theme::Dark => TimeOfDay::Night,
1059            Theme::Light => TimeOfDay::Morning,
1060        };
1061        let family = resolve_family(&config.color_mode, theme);
1062        let art = convert_for_grid(src, config, theme, cols, rows, cell_w, cell_h);
1063        let lighting = Lighting {
1064            vignette_cx: f64::from(width) * 0.5,
1065            vignette_cy: f64::from(height) * 0.5,
1066            vignette_rx: f64::from(width) * 0.78,
1067            vignette_ry: f64::from(height) * 0.78,
1068            glow: None,
1069        };
1070
1071        let graph = SceneGraph {
1072            width,
1073            height,
1074            theme,
1075            tod,
1076            buddy: false,
1077            seed,
1078            family,
1079            grid: scene_grid,
1080            cells: Vec::new(),
1081            lighting,
1082            activity: None,
1083            props: Vec::new(),
1084            unattended: Vec::new(),
1085            character: None,
1086            emitters: emitters.clone(),
1087            ground_y: height as i32,
1088            t_hero_ms,
1089            loop_ms: LOOP_MS,
1090            pace: CALM_PACE,
1091            generator: GENERATOR_VERSION,
1092            letters: if letters == "text" {
1093                String::new()
1094            } else {
1095                letters.to_string()
1096            },
1097            water: None,
1098            journey: None,
1099            zoom: 1.0,
1100        };
1101
1102        let (background, palette) = bake_ascii_theme(&art, config, &graph, &ascii_grid);
1103        custom_themes.push(CustomTheme {
1104            theme,
1105            graph,
1106            palette,
1107            atlas: weather_atlas.clone(),
1108            background,
1109            hero_ms: t_hero_ms,
1110        });
1111    }
1112
1113    let (light_family, dark_family) = match &config.color_mode {
1114        AsciiColorMode::Palette(set) => {
1115            let l = clairlune_scene::palette::families_in(set, Theme::Light)
1116                .next()
1117                .map_or("paper_day", |f| f.id);
1118            let d = clairlune_scene::palette::families_in(set, Theme::Dark)
1119                .next()
1120                .map_or("ember_night", |f| f.id);
1121            (l.to_string(), d.to_string())
1122        }
1123        _ => ("paper_day".to_string(), "ember_night".to_string()),
1124    };
1125
1126    let recipe = SceneRecipe {
1127        generator_version: GENERATOR_VERSION,
1128        seed,
1129        aspect: Aspect::from_size(width, height),
1130        content_ctx_hash: format!("{seed:016x}"),
1131        activity: None,
1132        archetype: PHOTO_ARCHETYPE.into(),
1133        light_tod: themes_to_build
1134            .contains(&Theme::Light)
1135            .then_some(TimeOfDay::Morning),
1136        dark_tod: themes_to_build
1137            .contains(&Theme::Dark)
1138            .then_some(TimeOfDay::Night),
1139        platform: "none".into(),
1140        props: Vec::new(),
1141        weather: config.weather.clone(),
1142        composition: Composition {
1143            horizon_pm: 800,
1144            focus_x_pm: 500,
1145            gap_pm: 500,
1146            shape_pow_pm: 1000,
1147            platform_margin_pm: 0,
1148            cliff_layers: 0,
1149            prop_left: false,
1150            motion_speed_cc: 0,
1151            pace_half_pm: 0,
1152            fly_lift_pm: 0,
1153            journey_ms: 0,
1154            journey_pace_c: 0,
1155            landmark: String::new(),
1156        },
1157        palette: PalettePick {
1158            light: light_family,
1159            dark: dark_family,
1160        },
1161        look: "line".into(),
1162        contrast: "normal".into(),
1163        zoom: "close".into(),
1164        letters: letters.into(),
1165    };
1166
1167    ScenePackage::from_custom(recipe, width, height, custom_themes).map_err(|e| e.to_string())
1168}
1169
1170fn bake_ascii_theme(
1171    art: &AsciiArt,
1172    config: &AsciiConfig,
1173    graph: &SceneGraph,
1174    g: &GridSpec,
1175) -> (IndexedImage, IndexedPalette) {
1176    let mut img = IndexedImage::new(graph.width, graph.height);
1177    let w = graph.width as usize;
1178    let flat_bg = matches!(
1179        config.color_mode,
1180        AsciiColorMode::Black | AsciiColorMode::White | AsciiColorMode::None
1181    );
1182    if flat_bg {
1183        img.pixels.fill(3); // uniform bg_center band
1184    } else {
1185        for (y, row) in img.pixels.chunks_exact_mut(w).enumerate() {
1186            graph.lighting.fill_row(y as u32, row);
1187        }
1188    }
1189
1190    let (cw, ch) = (g.cell_w as usize, g.cell_h as usize);
1191    let cell_len = cw * ch;
1192    let (glyph_ids, all_masks) = rasterize_unique_chars(&art.chars, g.cell_w, g.cell_h, g.font_px);
1193
1194    if config.color_mode == AsciiColorMode::Photo {
1195        let (palette, cell_slots) = build_photo_palette(graph, art);
1196        for row in 0..g.rows {
1197            for col in 0..g.cols {
1198                let ci = (row * g.cols + col) as usize;
1199                let gid = glyph_ids[ci] as usize;
1200                if gid == 0 {
1201                    continue;
1202                }
1203                let base_slot = cell_slots[ci];
1204                let mask = &all_masks[gid * cell_len..(gid + 1) * cell_len];
1205                let x0 = g.origin_x as usize + col as usize * cw;
1206                let y0 = g.origin_y as usize + row as usize * ch;
1207                for my in 0..ch {
1208                    let line = (y0 + my) * w + x0;
1209                    for mx in 0..cw {
1210                        let a = mask[my * cw + mx];
1211                        // 3 anti-aliasing levels per quantized colour: faint, medium, full.
1212                        let step = if a < 48 {
1213                            continue;
1214                        } else if a < 128 {
1215                            0
1216                        } else if a < 205 {
1217                            1
1218                        } else {
1219                            2
1220                        };
1221                        img.pixels[line + mx] = base_slot + step;
1222                    }
1223                }
1224            }
1225        }
1226        return (img, palette);
1227    }
1228
1229    let palette = IndexedPalette::for_graph(graph);
1230    for row in 0..g.rows {
1231        for col in 0..g.cols {
1232            let ci = (row * g.cols + col) as usize;
1233            let gid = glyph_ids[ci] as usize;
1234            if gid == 0 {
1235                continue;
1236            }
1237            let mask = &all_masks[gid * cell_len..(gid + 1) * cell_len];
1238            let x0 = g.origin_x as usize + col as usize * cw;
1239            let y0 = g.origin_y as usize + row as usize * ch;
1240            for my in 0..ch {
1241                let line = (y0 + my) * w + x0;
1242                for mx in 0..cw {
1243                    let a = mask[my * cw + mx];
1244                    if a == 0 {
1245                        continue;
1246                    }
1247                    let level = ink_level(a, 255);
1248                    if level > 0 {
1249                        let band = img.pixels[line + mx];
1250                        img.pixels[line + mx] = IndexedPalette::ink(band, level);
1251                    }
1252                }
1253            }
1254        }
1255    }
1256    (img, palette)
1257}
1258
1259/// Builds an `IndexedPalette` whose `0..104` entries keep standard background,
1260/// ink and ember ramps (for vignette, live weather and signatures) and whose
1261/// `104..248` entries hold up to 48 median-cut photo colours × 3 AA blend steps.
1262fn build_photo_palette(graph: &SceneGraph, art: &AsciiArt) -> (IndexedPalette, Vec<u8>) {
1263    let base = IndexedPalette::for_graph(graph);
1264    let mut colors = base.colors()[..SPRITE_BASE as usize].to_vec();
1265
1266    let active: Vec<[u8; 3]> = art
1267        .chars
1268        .iter()
1269        .zip(&art.colors)
1270        .filter(|(ch, _)| **ch != ' ')
1271        .map(|(_, &rgb)| rgb)
1272        .collect();
1273
1274    let centroids = median_cut(&active, 48);
1275    let bg = graph.family.bg_center;
1276    for &[r, g, b] in &centroids {
1277        let target = Rgb { r, g, b };
1278        for t in [0.38, 0.70, 1.0] {
1279            colors.push(bg.mix(target, t));
1280        }
1281    }
1282    debug_assert!(colors.len() < TRANSPARENT_INDEX as usize);
1283
1284    let cell_slots = art
1285        .colors
1286        .iter()
1287        .map(|rgb| {
1288            let best = centroids
1289                .iter()
1290                .enumerate()
1291                .min_by_key(|(_, c)| color_dist2(*rgb, **c))
1292                .map_or(0, |(i, _)| i);
1293            SPRITE_BASE + (best as u8) * 3
1294        })
1295        .collect();
1296
1297    (IndexedPalette::from_colors(colors), cell_slots)
1298}
1299
1300fn color_dist2(a: [u8; 3], b: [u8; 3]) -> u32 {
1301    let dr = i32::from(a[0]) - i32::from(b[0]);
1302    let dg = i32::from(a[1]) - i32::from(b[1]);
1303    let db = i32::from(a[2]) - i32::from(b[2]);
1304    (dr * dr * 2 + dg * dg * 4 + db * db) as u32
1305}
1306
1307/// Deterministic median-cut colour quantizer producing `1..=max_colors` RGB centroids.
1308fn median_cut(samples: &[[u8; 3]], max_colors: usize) -> Vec<[u8; 3]> {
1309    if samples.is_empty() {
1310        return vec![[220, 220, 220]];
1311    }
1312    let mut buckets: Vec<Vec<[u8; 3]>> = vec![samples.to_vec()];
1313    while buckets.len() < max_colors {
1314        let Some((split_idx, axis)) = buckets
1315            .iter()
1316            .enumerate()
1317            .filter(|(_, b)| b.len() >= 2)
1318            .filter_map(|(i, b)| {
1319                let (mut rmin, mut rmax) = (255u8, 0u8);
1320                let (mut gmin, mut gmax) = (255u8, 0u8);
1321                let (mut bmin, mut bmax) = (255u8, 0u8);
1322                for c in b {
1323                    rmin = rmin.min(c[0]);
1324                    rmax = rmax.max(c[0]);
1325                    gmin = gmin.min(c[1]);
1326                    gmax = gmax.max(c[1]);
1327                    bmin = bmin.min(c[2]);
1328                    bmax = bmax.max(c[2]);
1329                }
1330                let ranges = [rmax - rmin, gmax - gmin, bmax - bmin];
1331                let (axis, &span) = ranges.iter().enumerate().max_by_key(|(_, s)| *s)?;
1332                (span > 0).then_some((i, axis, u32::from(span) * (b.len() as u32).ilog2().max(1)))
1333            })
1334            .max_by_key(|&(_, _, score)| score)
1335            .map(|(i, axis, _)| (i, axis))
1336        else {
1337            break;
1338        };
1339
1340        let mut bucket = buckets.swap_remove(split_idx);
1341        bucket.sort_by_key(|c| (c[axis], c[0], c[1], c[2]));
1342        let mut mid = bucket.len() / 2;
1343        let min_v = bucket[0][axis];
1344        let max_v = bucket[bucket.len() - 1][axis];
1345        if bucket[0][axis] == bucket[mid][axis] || bucket[mid - 1][axis] == max_v {
1346            let thr = ((u16::from(min_v) + u16::from(max_v)) / 2) as u8;
1347            mid = bucket
1348                .partition_point(|c| c[axis] <= thr)
1349                .clamp(1, bucket.len() - 1);
1350        }
1351        let right = bucket.split_off(mid);
1352        buckets.push(bucket);
1353        buckets.push(right);
1354    }
1355
1356    buckets
1357        .into_iter()
1358        .filter(|b| !b.is_empty())
1359        .map(|b| {
1360            let n = b.len() as u64;
1361            let (sr, sg, sb) = b.iter().fold((0u64, 0u64, 0u64), |(r, g, bl), c| {
1362                (
1363                    r + u64::from(c[0]),
1364                    g + u64::from(c[1]),
1365                    bl + u64::from(c[2]),
1366                )
1367            });
1368            [
1369                ((sr + n / 2) / n) as u8,
1370                ((sg + n / 2) / n) as u8,
1371                ((sb + n / 2) / n) as u8,
1372            ]
1373        })
1374        .collect()
1375}
1376
1377/// Number of built-in procedural showcase images for the Studio's Inspire button.
1378pub const INSPIRE_COUNT: usize = 4;
1379
1380/// Generates one of the built-in showcase images (`360 x 240` RGBA) in pure Rust.
1381pub fn inspire_sample(index: usize, buddy: bool) -> (&'static str, RgbaImage) {
1382    let (w, h) = (360u32, 240u32);
1383    let mut px = vec![0u8; (w * h * 4) as usize];
1384    let which = index % INSPIRE_COUNT;
1385    let title = match which {
1386        0 => "Sample 1 · Crescent & peaks",
1387        1 => "Sample 2 · Sunset horizon",
1388        2 => "Sample 3 · Faceted ring",
1389        _ if buddy => "Sample 4 · Clawd by starlight",
1390        _ => "Sample 4 · Spiral nebula",
1391    };
1392
1393    for y in 0..h {
1394        let ny = f64::from(y) / f64::from(h);
1395        for x in 0..w {
1396            let nx = f64::from(x) / f64::from(w);
1397            let [r, g, b] = match which {
1398                0 => sample_crescent_peaks(nx, ny),
1399                1 => sample_sunset(nx, ny),
1400                2 => sample_torus(nx, ny),
1401                _ if buddy => sample_clawd_card(nx, ny),
1402                _ => sample_nebula(nx, ny),
1403            };
1404            let o = ((y * w + x) * 4) as usize;
1405            px[o] = r;
1406            px[o + 1] = g;
1407            px[o + 2] = b;
1408            px[o + 3] = 255;
1409        }
1410    }
1411    (
1412        title,
1413        RgbaImage {
1414            width: w,
1415            height: h,
1416            pixels: px,
1417        },
1418    )
1419}
1420
1421fn sample_crescent_peaks(nx: f64, ny: f64) -> [u8; 3] {
1422    // Sky gradient + crescent moon + twin alpine ridges + lake reflection.
1423    let water_y = 0.72;
1424    let (ux, uy, mir) = if ny > water_y {
1425        let ripple = ((ny - water_y) * 190.0).sin() * 0.008;
1426        (
1427            (nx + ripple).clamp(0.0, 1.0),
1428            (water_y - (ny - water_y) * 0.88).clamp(0.0, water_y),
1429            true,
1430        )
1431    } else {
1432        (nx, ny, false)
1433    };
1434
1435    // Crescent moon at (0.66, 0.27)
1436    let dx = (ux - 0.66) * 1.5;
1437    let dy = uy - 0.27;
1438    let d_outer = (dx * dx + dy * dy).sqrt();
1439    let d_cut = ((dx - 0.065) * (dx - 0.065) + (dy + 0.025) * (dy + 0.025)).sqrt();
1440
1441    let ridge_far = 0.56
1442        - 0.19 * (1.0 - ((ux - 0.28).abs() * 3.4).min(1.0))
1443        - 0.14 * (1.0 - ((ux - 0.74).abs() * 3.8).min(1.0))
1444        + 0.02 * (ux * 38.0).sin();
1445    let ridge_near =
1446        0.68 - 0.26 * (1.0 - ((ux - 0.42).abs() * 2.8).min(1.0)) - 0.03 * (ux * 29.0).cos();
1447
1448    let mut rgb = if uy > ridge_near {
1449        let slope = if ux < 0.42 { 0.52 } else { 0.88 };
1450        let v = (52.0 + slope * 78.0 * (1.0 - (uy - ridge_near) * 1.9).clamp(0.2, 1.0)) as u8;
1451        [v.saturating_sub(12), v, v.saturating_add(18)]
1452    } else if uy > ridge_far {
1453        let v = (34.0 + (0.72 - uy) * 95.0) as u8;
1454        [v.saturating_sub(8), v, v.saturating_add(24)]
1455    } else if d_outer < 0.145 && d_cut > 0.125 {
1456        [250, 240, 206]
1457    } else {
1458        let glow = (1.0 - (d_outer / 0.28).min(1.0)).powi(3) * 26.0;
1459        let base = 6.0 + uy * 18.0 + glow;
1460        [
1461            base as u8,
1462            (base * 1.08) as u8,
1463            (base * 1.35).min(255.0) as u8,
1464        ]
1465    };
1466    if mir {
1467        rgb = [
1468            (u16::from(rgb[0]) * 6 / 10) as u8,
1469            (u16::from(rgb[1]) * 7 / 10) as u8,
1470            (u16::from(rgb[2]) * 8 / 10) as u8,
1471        ];
1472    }
1473    rgb
1474}
1475
1476fn sample_sunset(nx: f64, ny: f64) -> [u8; 3] {
1477    let horizon = 0.62;
1478    let dx = (nx - 0.5) * 1.5;
1479    let dy = ny - 0.44;
1480    let d = (dx * dx + dy * dy).sqrt();
1481    if ny < horizon {
1482        if d < 0.24 {
1483            // Striped retro sun
1484            let band = ((ny - 0.34) * 55.0) as i32;
1485            if ny > 0.38 && band % 3 == 0 {
1486                return [38, 18, 52];
1487            }
1488            let t = ((ny - 0.20) / 0.30).clamp(0.0, 1.0);
1489            return [252, (225.0 - t * 115.0) as u8, (95.0 + t * 45.0) as u8];
1490        }
1491        let hill = horizon - 0.08 * (nx * 9.0).sin().abs() - 0.04 * (nx * 21.0 + 1.0).sin().abs();
1492        if ny > hill {
1493            return [24, 16, 36];
1494        }
1495        let t = (ny / horizon).clamp(0.0, 1.0);
1496        [
1497            (28.0 + t * 140.0) as u8,
1498            (20.0 + t * 62.0) as u8,
1499            (58.0 + t * 55.0) as u8,
1500        ]
1501    } else {
1502        let depth = (ny - horizon) / (1.0 - horizon);
1503        let sun_col = (1.0 - ((nx - 0.5).abs() * (3.2 + depth * 3.0)).min(1.0)).max(0.0);
1504        let wave = ((depth * 85.0 + nx * 18.0).sin() * 0.5 + 0.5) * sun_col;
1505        [
1506            (22.0 + wave * 220.0) as u8,
1507            (18.0 + wave * 120.0) as u8,
1508            (44.0 + wave * 65.0 + (1.0 - depth) * 28.0) as u8,
1509        ]
1510    }
1511}
1512
1513fn sample_torus(nx: f64, ny: f64) -> [u8; 3] {
1514    let u = (nx - 0.5) * 2.4;
1515    let v = (ny - 0.5) * 1.65;
1516    // Tilted 3D ring normal approximation
1517    let r = (u * u + (v * 1.28) * (v * 1.28)).sqrt();
1518    let major = 0.62;
1519    let minor = 0.25;
1520    let dr = r - major;
1521    let inside = minor * minor - dr * dr;
1522    if inside <= 0.0 {
1523        let vignette = (1.0 - (r * 0.6).min(1.0)) * 22.0;
1524        return [
1525            vignette as u8,
1526            (vignette * 1.05) as u8,
1527            (vignette * 1.25) as u8,
1528        ];
1529    }
1530    let nz = inside.sqrt() / minor;
1531    let inv_r = if r > 1e-4 { 1.0 / r } else { 0.0 };
1532    let nx3 = (dr / minor) * (u * inv_r);
1533    let ny3 = (dr / minor) * (v * 1.28 * inv_r);
1534    let diff = (-0.52 * nx3 - 0.58 * ny3 + 0.62 * nz).max(0.06);
1535    let spec = diff.powi(6) * 0.55;
1536    let l = (diff * 0.85 + spec).clamp(0.0, 1.0);
1537    [
1538        (30.0 + l * 220.0) as u8,
1539        (38.0 + l * 198.0) as u8,
1540        (54.0 + l * 175.0) as u8,
1541    ]
1542}
1543
1544fn sample_clawd_card(nx: f64, ny: f64) -> [u8; 3] {
1545    // Pixel-art Clawd silhouette centred over a warm campfire halo.
1546    let gx = (nx * 45.0).floor() as i32 - 22;
1547    let gy = (ny * 30.0).floor() as i32 - 15;
1548    // Body [-7..=7, -5..=2], arms [-9..-7] & [8..10] at [-2..=1], legs at [-6,-5], [-2,-1], [1,2], [5,6] at [3..=5]
1549    let in_body = (-7..=7).contains(&gx) && (-5..=2).contains(&gy);
1550    let in_arms = ((-9..=-8).contains(&gx) || (8..=9).contains(&gx)) && (-2..=1).contains(&gy);
1551    let in_legs = ([-6, -5, -2, -1, 2, 3, 5, 6].contains(&gx)) && (3..=5).contains(&gy);
1552    let in_eyes = ([-4, -3, 3, 4].contains(&gx)) && gy == -2;
1553
1554    if in_eyes {
1555        return [24, 18, 16];
1556    }
1557    if in_body || in_arms {
1558        let top = if gy <= -4 { 24 } else { 0 };
1559        return [226u8.saturating_add(top), 132u8.saturating_add(top / 2), 98];
1560    }
1561    if in_legs {
1562        return [184, 94, 69];
1563    }
1564    if gy == 6 && (-14..=14).contains(&gx) {
1565        return [120, 112, 98];
1566    }
1567    let d = ((nx - 0.5) * (nx - 0.5) * 1.6 + (ny - 0.52) * (ny - 0.52)).sqrt();
1568    let glow = (1.0 - (d / 0.55).min(1.0)).powi(2);
1569    [
1570        (10.0 + glow * 85.0) as u8,
1571        (12.0 + glow * 48.0) as u8,
1572        (18.0 + glow * 28.0) as u8,
1573    ]
1574}
1575
1576fn sample_nebula(nx: f64, ny: f64) -> [u8; 3] {
1577    let dx = (nx - 0.5) * 1.6;
1578    let dy = ny - 0.5;
1579    let r = (dx * dx + dy * dy).sqrt();
1580    let a = dy.atan2(dx);
1581    let arm = ((2.0 * a - r * 11.0).cos() * 0.5 + 0.5).powi(3);
1582    let core = (1.0 - (r / 0.55).min(1.0)).powi(2);
1583    let v = (core * 0.85 + arm * (1.0 - (r / 0.72).min(1.0)) * 0.75).clamp(0.0, 1.0);
1584    [
1585        (12.0 + v * 235.0) as u8,
1586        (14.0 + v * 195.0) as u8,
1587        (24.0 + v * 240.0) as u8,
1588    ]
1589}
1590
1591#[cfg(test)]
1592mod tests {
1593    use super::*;
1594    use crate::clock::Clock;
1595
1596    fn split_gradient() -> RgbaImage {
1597        let (w, h) = (80, 48);
1598        let mut px = Vec::with_capacity((w * h * 4) as usize);
1599        for y in 0..h {
1600            for x in 0..w {
1601                let v = (x * 255 / (w - 1)) as u8;
1602                let r = v;
1603                let g = (y * 255 / (h - 1)) as u8;
1604                let b = 255 - v;
1605                px.extend_from_slice(&[r, g, b, 255]);
1606            }
1607        }
1608        RgbaImage::new(w, h, px).unwrap()
1609    }
1610
1611    #[test]
1612    fn dark_and_light_polarities_invert_character_weights() {
1613        let src = split_gradient();
1614        let mut cfg = AsciiConfig {
1615            columns: 40,
1616            color_mode: AsciiColorMode::Black,
1617            ..AsciiConfig::default()
1618        };
1619        let on_black = convert_standalone(&src, &cfg, Theme::Dark);
1620        let last = (on_black.cols * on_black.rows - 1) as usize;
1621        assert_eq!(on_black.chars[0], ' ');
1622        assert_eq!(on_black.chars[last], '@');
1623
1624        cfg.color_mode = AsciiColorMode::White;
1625        let on_white = convert_standalone(&src, &cfg, Theme::Light);
1626        assert_eq!(on_white.chars[0], '@');
1627        assert_eq!(on_white.chars[last], ' ');
1628    }
1629
1630    #[test]
1631    fn braille_and_custom_ramps_produce_expected_characters() {
1632        let src = split_gradient();
1633        let braille_cfg = AsciiConfig {
1634            columns: 32,
1635            ramp: RampPreset::Braille,
1636            ..AsciiConfig::default()
1637        };
1638        let braille = convert_standalone(&src, &braille_cfg, Theme::Dark);
1639        assert!(
1640            braille
1641                .chars
1642                .iter()
1643                .any(|&c| ('\u{2801}'..='\u{28FF}').contains(&c))
1644        );
1645
1646        let custom_cfg = AsciiConfig {
1647            columns: 32,
1648            ramp: RampPreset::Custom,
1649            custom_ramp: "#. ".into(),
1650            ..AsciiConfig::default()
1651        };
1652        let custom = convert_standalone(&src, &custom_cfg, Theme::Dark);
1653        assert!(custom.chars.iter().all(|c| ['#', '.', ' '].contains(c)));
1654    }
1655
1656    #[test]
1657    fn none_background_exports_transparent_rgba_png_in_light_and_dark_ink() {
1658        let src = split_gradient();
1659        let cfg = AsciiConfig {
1660            columns: 30,
1661            color_mode: AsciiColorMode::None,
1662            ..AsciiConfig::default()
1663        };
1664        let art_dark = convert_standalone(&src, &cfg, Theme::Dark);
1665        let (w, h, rgba_light_ink) = render_rgba(&art_dark, &cfg, Theme::Dark, 12, true);
1666        assert_eq!(
1667            rgba_light_ink[3], 0,
1668            "top-left margin pixel must be transparent"
1669        );
1670        let light_ink_px = rgba_light_ink
1671            .as_chunks::<4>()
1672            .0
1673            .iter()
1674            .find(|p| p[3] > 200)
1675            .expect("opaque light-ink pixel");
1676        assert!(
1677            light_ink_px[0] > 200,
1678            "Theme::Dark None mode should render light ink"
1679        );
1680
1681        let art_light = convert_standalone(&src, &cfg, Theme::Light);
1682        let (_, _, rgba_dark_ink) = render_rgba(&art_light, &cfg, Theme::Light, 12, true);
1683        let dark_ink_px = rgba_dark_ink
1684            .as_chunks::<4>()
1685            .0
1686            .iter()
1687            .find(|p| p[3] > 200)
1688            .expect("opaque dark-ink pixel");
1689        assert!(
1690            dark_ink_px[0] < 40,
1691            "Theme::Light None mode should render dark ink"
1692        );
1693
1694        let png = encode_rgba_png(w, h, &rgba_light_ink).unwrap();
1695        assert!(png.starts_with(b"\x89PNG"));
1696    }
1697
1698    #[test]
1699    fn custom_ramp_sanitizes_unmapped_unicode_and_weather_scale_uses_scene_grid() {
1700        // Emoji, control chars, and duplicate characters are stripped or deduplicated,
1701        // falling back cleanly if nothing renderable was typed.
1702        let fallback = RampPreset::Custom.heavy_to_light("🚀🎉\n\t   ");
1703        assert_eq!(fallback.last(), Some(&' '));
1704        assert!(fallback.len() >= 2);
1705        assert!(
1706            fallback
1707                .iter()
1708                .take(fallback.len() - 1)
1709                .all(|&c| GlyphAtlas::can_render_char(c))
1710        );
1711
1712        let deduped = RampPreset::Custom.heavy_to_light("@@@###...🚀 ");
1713        assert_eq!(deduped, vec!['@', '#', '.', ' ']);
1714
1715        // Extreme aspect ratio (400x1) and low column count (30 cols) do not panic
1716        // and keep `SceneGraph.grid` at standard monitor particle resolution.
1717        let wide = RgbaImage::new(400, 1, vec![220; 400 * 4]).unwrap();
1718        let cfg = AsciiConfig {
1719            columns: 30,
1720            weather: "snow".into(),
1721            ..AsciiConfig::default()
1722        };
1723        assert!(cfg.has_live_weather());
1724        let pkg = build_photo_package(&wide, &cfg, 1920, 1080, 99).unwrap();
1725        let g = pkg.graph(Theme::Dark).unwrap();
1726        let expected = clairlune_scene::grid_spec(1920, 1080);
1727        assert_eq!(
1728            (g.grid.cell_w, g.grid.cell_h),
1729            (expected.cell_w, expected.cell_h)
1730        );
1731    }
1732
1733    #[test]
1734    fn photo_packages_save_load_and_animate_weather_in_palette_and_photo_modes() {
1735        let (_, src) = inspire_sample(0, true);
1736        let dir = std::env::temp_dir().join(format!("clairlune-img2ascii-{}", std::process::id()));
1737        let _ = std::fs::remove_dir_all(&dir);
1738
1739        for (idx, mode) in [
1740            AsciiColorMode::Palette("nord".into()),
1741            AsciiColorMode::Photo,
1742            AsciiColorMode::Black,
1743        ]
1744        .into_iter()
1745        .enumerate()
1746        {
1747            let cfg = AsciiConfig {
1748                columns: 80,
1749                ramp: RampPreset::Detailed,
1750                color_mode: mode,
1751                weather: "snow".into(),
1752                ..AsciiConfig::default()
1753            };
1754            let pkg = build_photo_package(&src, &cfg, 640, 360, 12345).unwrap();
1755            let sub = dir.join(format!("mode-{idx}"));
1756            pkg.save(&sub).unwrap();
1757            let loaded = ScenePackage::load(&sub).unwrap();
1758            let theme = loaded.themes()[0];
1759            let (still, pal) = loaded.still(theme, false).unwrap();
1760            assert_eq!((still.width, still.height), (640, 360));
1761            assert!(pal.len() <= 255);
1762
1763            let mut inc = loaded.incremental(theme).unwrap();
1764            let dirty = loaded
1765                .advance(&mut inc, theme, false, 1500, Clock::Smooth)
1766                .unwrap();
1767            assert!(!dirty.is_empty(), "snow weather should animate frames");
1768        }
1769
1770        let _ = std::fs::remove_dir_all(&dir);
1771    }
1772}