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 = 12;
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 => "Crescent & peaks",
1387        1 => "Sunset horizon",
1388        2 => "Faceted ring",
1389        3 if buddy => "Clawd by starlight",
1390        3 => "Paper lantern",
1391        4 => "Spiral nebula",
1392        5 => "Ringed planet",
1393        6 => "Lighthouse beam",
1394        7 => "Torii & harvest moon",
1395        8 => "Great wave",
1396        9 => "Jellyfish bloom",
1397        10 => "Aurora pines",
1398        _ => "Origami crane",
1399    };
1400
1401    for y in 0..h {
1402        let ny = f64::from(y) / f64::from(h);
1403        for x in 0..w {
1404            let nx = f64::from(x) / f64::from(w);
1405            let [r, g, b, a] = match which {
1406                0 => opaque(sample_crescent_peaks(nx, ny)),
1407                1 => opaque(sample_sunset(nx, ny)),
1408                2 => opaque(sample_torus(nx, ny)),
1409                3 if buddy => opaque(sample_clawd_card(nx, ny)),
1410                3 => opaque(sample_paper_lantern(nx, ny)),
1411                4 => opaque(sample_nebula(nx, ny)),
1412                5 => opaque(sample_ringed_planet(nx, ny)),
1413                6 => opaque(sample_lighthouse(nx, ny)),
1414                7 => opaque(sample_torii_moon(nx, ny)),
1415                8 => opaque(sample_great_wave(nx, ny)),
1416                9 => opaque(sample_jellyfish(nx, ny)),
1417                10 => opaque(sample_aurora_pines(nx, ny)),
1418                _ => sample_origami_crane(nx, ny),
1419            };
1420            let o = ((y * w + x) * 4) as usize;
1421            px[o] = r;
1422            px[o + 1] = g;
1423            px[o + 2] = b;
1424            px[o + 3] = a;
1425        }
1426    }
1427    (
1428        title,
1429        RgbaImage {
1430            width: w,
1431            height: h,
1432            pixels: px,
1433        },
1434    )
1435}
1436
1437#[inline]
1438fn opaque(rgb: [u8; 3]) -> [u8; 4] {
1439    [rgb[0], rgb[1], rgb[2], 255]
1440}
1441
1442fn star_spark(nx: f64, ny: f64, seed: u32) -> u8 {
1443    let gx = (nx * 90.0) as u32;
1444    let gy = (ny * 60.0) as u32;
1445    let fx = (nx * 90.0).fract() - 0.5;
1446    let fy = (ny * 60.0).fract() - 0.5;
1447    let mut h = gx
1448        .wrapping_mul(0x9E37_79B9)
1449        .wrapping_add(gy.wrapping_mul(0x85EB_CA6B))
1450        .wrapping_add(seed.wrapping_mul(0xC2B2_AE35));
1451    h ^= h >> 15;
1452    h = h.wrapping_mul(0x2C1B_3C6D);
1453    h ^= h >> 12;
1454    if !h.is_multiple_of(97) {
1455        return 0;
1456    }
1457    let d = (fx * fx + fy * fy).sqrt();
1458    if d < 0.34 {
1459        ((1.0 - d / 0.34) * (150.0 + f64::from(h % 95))) as u8
1460    } else {
1461        0
1462    }
1463}
1464
1465fn sample_crescent_peaks(nx: f64, ny: f64) -> [u8; 3] {
1466    // Sky gradient + crescent moon + twin alpine ridges + lake reflection.
1467    let water_y = 0.72;
1468    let (ux, uy, mir) = if ny > water_y {
1469        let ripple = ((ny - water_y) * 190.0).sin() * 0.008;
1470        (
1471            (nx + ripple).clamp(0.0, 1.0),
1472            (water_y - (ny - water_y) * 0.88).clamp(0.0, water_y),
1473            true,
1474        )
1475    } else {
1476        (nx, ny, false)
1477    };
1478
1479    // Crescent moon at (0.66, 0.27)
1480    let dx = (ux - 0.66) * 1.5;
1481    let dy = uy - 0.27;
1482    let d_outer = (dx * dx + dy * dy).sqrt();
1483    let d_cut = ((dx - 0.065) * (dx - 0.065) + (dy + 0.025) * (dy + 0.025)).sqrt();
1484
1485    let ridge_far = 0.56
1486        - 0.19 * (1.0 - ((ux - 0.28).abs() * 3.4).min(1.0))
1487        - 0.14 * (1.0 - ((ux - 0.74).abs() * 3.8).min(1.0))
1488        + 0.02 * (ux * 38.0).sin();
1489    let ridge_near =
1490        0.68 - 0.26 * (1.0 - ((ux - 0.42).abs() * 2.8).min(1.0)) - 0.03 * (ux * 29.0).cos();
1491
1492    let mut rgb = if uy > ridge_near {
1493        let slope = if ux < 0.42 { 0.52 } else { 0.88 };
1494        let v = (52.0 + slope * 78.0 * (1.0 - (uy - ridge_near) * 1.9).clamp(0.2, 1.0)) as u8;
1495        [v.saturating_sub(12), v, v.saturating_add(18)]
1496    } else if uy > ridge_far {
1497        let v = (34.0 + (0.72 - uy) * 95.0) as u8;
1498        [v.saturating_sub(8), v, v.saturating_add(24)]
1499    } else if d_outer < 0.145 && d_cut > 0.125 {
1500        [250, 240, 206]
1501    } else {
1502        let glow = (1.0 - (d_outer / 0.28).min(1.0)).powi(3) * 26.0;
1503        let base = 6.0 + uy * 18.0 + glow;
1504        [
1505            base as u8,
1506            (base * 1.08) as u8,
1507            (base * 1.35).min(255.0) as u8,
1508        ]
1509    };
1510    if mir {
1511        rgb = [
1512            (u16::from(rgb[0]) * 6 / 10) as u8,
1513            (u16::from(rgb[1]) * 7 / 10) as u8,
1514            (u16::from(rgb[2]) * 8 / 10) as u8,
1515        ];
1516    }
1517    rgb
1518}
1519
1520fn sample_sunset(nx: f64, ny: f64) -> [u8; 3] {
1521    let horizon = 0.62;
1522    let dx = (nx - 0.5) * 1.5;
1523    let dy = ny - 0.44;
1524    let d = (dx * dx + dy * dy).sqrt();
1525    if ny < horizon {
1526        if d < 0.24 {
1527            // Striped retro sun
1528            let band = ((ny - 0.34) * 55.0) as i32;
1529            if ny > 0.38 && band % 3 == 0 {
1530                return [38, 18, 52];
1531            }
1532            let t = ((ny - 0.20) / 0.30).clamp(0.0, 1.0);
1533            return [252, (225.0 - t * 115.0) as u8, (95.0 + t * 45.0) as u8];
1534        }
1535        let hill = horizon - 0.08 * (nx * 9.0).sin().abs() - 0.04 * (nx * 21.0 + 1.0).sin().abs();
1536        if ny > hill {
1537            return [24, 16, 36];
1538        }
1539        let t = (ny / horizon).clamp(0.0, 1.0);
1540        [
1541            (28.0 + t * 140.0) as u8,
1542            (20.0 + t * 62.0) as u8,
1543            (58.0 + t * 55.0) as u8,
1544        ]
1545    } else {
1546        let depth = (ny - horizon) / (1.0 - horizon);
1547        let sun_col = (1.0 - ((nx - 0.5).abs() * (3.2 + depth * 3.0)).min(1.0)).max(0.0);
1548        let wave = ((depth * 85.0 + nx * 18.0).sin() * 0.5 + 0.5) * sun_col;
1549        [
1550            (22.0 + wave * 220.0) as u8,
1551            (18.0 + wave * 120.0) as u8,
1552            (44.0 + wave * 65.0 + (1.0 - depth) * 28.0) as u8,
1553        ]
1554    }
1555}
1556
1557fn sample_torus(nx: f64, ny: f64) -> [u8; 3] {
1558    let u = (nx - 0.5) * 2.4;
1559    let v = (ny - 0.5) * 1.65;
1560    // Tilted 3D ring normal approximation
1561    let r = (u * u + (v * 1.28) * (v * 1.28)).sqrt();
1562    let major = 0.62;
1563    let minor = 0.25;
1564    let dr = r - major;
1565    let inside = minor * minor - dr * dr;
1566    if inside <= 0.0 {
1567        let vignette = (1.0 - (r * 0.6).min(1.0)) * 22.0;
1568        return [
1569            vignette as u8,
1570            (vignette * 1.05) as u8,
1571            (vignette * 1.25) as u8,
1572        ];
1573    }
1574    let nz = inside.sqrt() / minor;
1575    let inv_r = if r > 1e-4 { 1.0 / r } else { 0.0 };
1576    let nx3 = (dr / minor) * (u * inv_r);
1577    let ny3 = (dr / minor) * (v * 1.28 * inv_r);
1578    let diff = (-0.52 * nx3 - 0.58 * ny3 + 0.62 * nz).max(0.06);
1579    let spec = diff.powi(6) * 0.55;
1580    let l = (diff * 0.85 + spec).clamp(0.0, 1.0);
1581    [
1582        (30.0 + l * 220.0) as u8,
1583        (38.0 + l * 198.0) as u8,
1584        (54.0 + l * 175.0) as u8,
1585    ]
1586}
1587
1588fn sample_clawd_card(nx: f64, ny: f64) -> [u8; 3] {
1589    // 3D-shaded pixel Clawd beside a crackling campfire under a starry sky.
1590    let gx = (nx * 60.0).floor() as i32 - 30;
1591    let gy = (ny * 40.0).floor() as i32 - 20;
1592    let cx = -6;
1593    let cy = 2;
1594    let lx = gx - cx;
1595    let ly = gy - cy;
1596
1597    let corner_clip = lx.abs() == 8 && ly == -6;
1598    let in_body = (-8..=8).contains(&lx) && (-6..=3).contains(&ly) && !corner_clip;
1599    let in_arms = ((-11..=-9).contains(&lx) || (9..=11).contains(&lx)) && (-2..=1).contains(&ly);
1600    let in_legs = ([-7, -6, -3, -2, 2, 3, 6, 7].contains(&lx)) && (4..=7).contains(&ly);
1601    let in_eyes = ([-4, -3, 3, 4].contains(&lx)) && (-3..=-2).contains(&ly);
1602
1603    if in_eyes {
1604        return [14, 12, 16];
1605    }
1606    if in_body || in_arms {
1607        // Warm directional firelight from the campfire on the right (+lx) plus top rim light.
1608        let fire_lit = ((f64::from(lx + 11) / 22.0) * 0.65
1609            + (1.0 - f64::from(ly + 6) / 11.0) * 0.35)
1610            .clamp(0.0, 1.0);
1611        return [
1612            (132.0 + fire_lit * 120.0) as u8,
1613            (62.0 + fire_lit * 108.0) as u8,
1614            (48.0 + fire_lit * 72.0) as u8,
1615        ];
1616    }
1617    if in_legs {
1618        let lit = if lx > 0 { 28 } else { 0 };
1619        return [156 + lit, 76 + lit / 2, 58];
1620    }
1621
1622    // Campfire at (0.68, 0.73)
1623    let fx = (nx - 0.68) * 1.5;
1624    let fy = 0.74 - ny;
1625    if (-0.025..=0.018).contains(&fy) && fx.abs() < 0.085 {
1626        return [96, 56, 36]; // crossed logs
1627    }
1628    if (0.0..=0.19).contains(&fy) {
1629        let sway = (fy * 34.0).sin() * 0.012;
1630        let half_w = 0.068 * (1.0 - (fy / 0.19).powf(0.85));
1631        let df = (fx - sway).abs();
1632        if df < half_w {
1633            let core = (1.0 - df / half_w.max(1e-4)) * (1.0 - fy / 0.22);
1634            return [
1635                255,
1636                (125.0 + core * 125.0).min(255.0) as u8,
1637                (40.0 + core * 165.0).min(255.0) as u8,
1638            ];
1639        }
1640    }
1641
1642    // Terraced mossy ledge lit around the fire
1643    let ground = 0.74 + 0.025 * (nx * 9.0 - 1.2).cos();
1644    if ny >= ground {
1645        let fire_dist = ((nx - 0.68).abs() * 2.1 + (ny - ground) * 2.6).min(1.0);
1646        let warm = (1.0 - fire_dist).powi(2);
1647        return [
1648            (32.0 + warm * 145.0) as u8,
1649            (38.0 + warm * 92.0) as u8,
1650            (46.0 + warm * 38.0) as u8,
1651        ];
1652    }
1653
1654    let d_fire = (((nx - 0.68) * 1.4).powi(2) + (ny - 0.68).powi(2)).sqrt();
1655    let ember_halo = (1.0 - (d_fire / 0.26).min(1.0)).powi(3) * 28.0;
1656    let s = star_spark(nx, ny, 41);
1657    [
1658        (8.0 + ember_halo) as u8 | s,
1659        (10.0 + ember_halo * 0.6) as u8 | s,
1660        (16.0 + ember_halo * 0.3) as u8 | s,
1661    ]
1662}
1663
1664fn sample_paper_lantern(nx: f64, ny: f64) -> [u8; 3] {
1665    // Glowing ribbed chochin lantern hanging from a pine branch.
1666    let branch_y = 0.11 + 0.08 * (1.0 - nx).powi(2);
1667    if nx > 0.34 && (ny - branch_y).abs() < 0.013 {
1668        return [78, 56, 42];
1669    }
1670    // Pine needle clusters near upper-right
1671    let nd = (((nx - 0.76) * 1.4).powi(2) + (ny - 0.16).powi(2)).sqrt();
1672    if nd < 0.13 && ((nx - 0.76).atan2(ny - 0.16) * 14.0).cos() > 0.25 {
1673        let shade = (1.0 - nd / 0.13) * 75.0;
1674        return [28 + shade as u8 / 2, 58 + shade as u8, 48 + shade as u8 / 2];
1675    }
1676    // Hanging cord
1677    if (0.14..=0.25).contains(&ny) && (nx - 0.50).abs() < 0.006 {
1678        return [140, 118, 86];
1679    }
1680
1681    let dx = (nx - 0.50) * 1.5;
1682    let dy = (ny - 0.50) / 0.25;
1683    if dy.abs() <= 1.0 {
1684        let half_w = 0.245 * (1.0 - 0.36 * dy * dy).max(0.0).sqrt();
1685        if dx.abs() <= half_w {
1686            if dy.abs() > 0.89 {
1687                let rim = 1.0 - (dx.abs() / half_w.max(1e-4)) * 0.55;
1688                return [(78.0 * rim) as u8, (52.0 * rim) as u8, (36.0 * rim) as u8];
1689            }
1690            let u_x = dx / half_w.max(1e-4);
1691            let core = (1.0 - (u_x * u_x * 0.72 + dy * dy * 0.58)).clamp(0.0, 1.0);
1692            let rib = ((dy + 1.0) * 5.0 * std::f64::consts::PI).cos().abs();
1693            let rib_dim = if rib > 0.93 { 0.48 } else { 1.0 };
1694            return [
1695                ((165.0 + core * 90.0) * rib_dim) as u8,
1696                ((58.0 + core * 182.0) * rib_dim) as u8,
1697                ((28.0 + core * 148.0) * rib_dim) as u8,
1698            ];
1699        }
1700    }
1701
1702    // Silk tassel below bottom rim
1703    if (0.75..=0.91).contains(&ny) {
1704        let spread = 0.012 + (ny - 0.75) * 0.11;
1705        if (nx - 0.50).abs() < spread {
1706            let strand = (((nx - 0.50) / spread) * 9.0).cos().abs();
1707            let fade = 1.0 - (ny - 0.75) / 0.18;
1708            let v = (0.45 + 0.55 * strand) * fade;
1709            return [(215.0 * v) as u8, (82.0 * v) as u8, (44.0 * v) as u8];
1710        }
1711    }
1712
1713    let r_halo = (dx * dx + (ny - 0.50).powi(2)).sqrt();
1714    let halo = (1.0 - (r_halo / 0.40).min(1.0)).powi(4) * 30.0;
1715    let s = star_spark(nx, ny, 73);
1716    [
1717        (8.0 + halo) as u8 | s,
1718        (9.0 + halo * 0.55) as u8 | s,
1719        (15.0 + halo * 0.25) as u8 | s,
1720    ]
1721}
1722
1723fn sample_nebula(nx: f64, ny: f64) -> [u8; 3] {
1724    // Tilted grand two-armed spiral galaxy (Andromeda-style foreshortened disc).
1725    let u = (nx - 0.5) * 1.45;
1726    let v = ny - 0.5;
1727    let (sin_t, cos_t) = (-0.28_f64).sin_cos();
1728    let dx = (u * cos_t - v * sin_t) * 0.92;
1729    let dy = (u * sin_t + v * cos_t) * 1.85;
1730    let r = (dx * dx + dy * dy).sqrt();
1731    let a = dy.atan2(dx);
1732    let arm = ((2.0 * a - r * 9.5).cos() * 0.5 + 0.5).powi(3);
1733    let core = (1.0 - (r / 0.34).min(1.0)).powi(2);
1734    let env = (1.0 - (r / 0.78).min(1.0)).powf(1.5);
1735    let disc = (1.0 - (r / 0.62).min(1.0)).powi(2) * 0.24;
1736    let lum = (core * 0.96 + arm * env * 0.84 + disc).clamp(0.0, 1.0);
1737    let s = star_spark(nx, ny, 19);
1738    let cyan_mix = (r / 0.62).clamp(0.0, 1.0);
1739    [
1740        ((8.0 + lum * (250.0 - cyan_mix * 95.0)) as u8).max(s),
1741        ((10.0 + lum * (192.0 + cyan_mix * 42.0)) as u8).max(s),
1742        ((16.0 + lum * 242.0) as u8).max(s),
1743    ]
1744}
1745
1746fn sample_ringed_planet(nx: f64, ny: f64) -> [u8; 3] {
1747    // Tilted banded gas giant with wide dark inner ring gap, Cassini division, and ring shadow.
1748    let u = (nx - 0.5) * 1.5;
1749    let v = ny - 0.5;
1750    let (sin_t, cos_t) = 0.26_f64.sin_cos();
1751    let ru = u * cos_t - v * sin_t;
1752    let rv = u * sin_t + v * cos_t;
1753
1754    let rp = 0.215;
1755    let d2 = ru * ru + rv * rv;
1756    let on_planet = d2 < rp * rp;
1757
1758    // Foreshortened ring ellipse with a wide empty gap (0.215..0.345) so both ring handles frame dark space.
1759    let ring_r = (ru * ru + (rv * 3.1) * (rv * 3.1)).sqrt();
1760    let in_ring = (0.345..=0.645).contains(&ring_r) && !(0.490..=0.528).contains(&ring_r);
1761    let front_ring = in_ring && rv > 0.0;
1762    let back_ring = in_ring && rv <= 0.0;
1763
1764    let ring_rgb = |rr: f64, shadowed: bool| -> [u8; 3] {
1765        let fine = 0.84 + 0.16 * ((rr - 0.345) * 85.0).sin();
1766        let outer_dim = if rr > 0.528 { 0.80 } else { 1.0 };
1767        let sh = if shadowed { 0.20 } else { 1.0 };
1768        let l = (fine * outer_dim * sh).clamp(0.0, 1.0);
1769        [
1770            (28.0 + l * 214.0) as u8,
1771            (32.0 + l * 214.0) as u8,
1772            (40.0 + l * 208.0) as u8,
1773        ]
1774    };
1775
1776    if front_ring {
1777        return ring_rgb(ring_r, false);
1778    }
1779    if on_planet {
1780        let nz = ((rp * rp - d2).max(0.0)).sqrt() / rp;
1781        let nx3 = ru / rp;
1782        let ny3 = rv / rp;
1783        let mut diff = (-0.48 * nx3 - 0.42 * ny3 + 0.77 * nz).clamp(0.22, 1.0);
1784        // Crisp dark shadow right behind/under the front ring band
1785        let proj_r = (ru * ru + ((rv - 0.032) * 3.1).powi(2)).sqrt();
1786        if rv > 0.0 && (0.345..=0.645).contains(&proj_r) {
1787            diff *= 0.16;
1788        }
1789        let band = 0.80 + 0.20 * (ny3 * 16.0).cos();
1790        let l = (diff * band).clamp(0.0, 1.0);
1791        return [
1792            (28.0 + l * 224.0) as u8,
1793            (20.0 + l * 146.0) as u8,
1794            (18.0 + l * 88.0) as u8,
1795        ];
1796    }
1797    if back_ring {
1798        let shadowed = ru > 0.06 && rv.abs() < rp * 0.55;
1799        return ring_rgb(ring_r, shadowed);
1800    }
1801
1802    let s = star_spark(nx, ny, 108);
1803    [7 | s, 9 | s, 15 | s]
1804}
1805
1806fn sample_lighthouse(nx: f64, ny: f64) -> [u8; 3] {
1807    // Striped coastal lighthouse on a rocky headland with sweeping searchlights.
1808    let sea_y = 0.75;
1809    if ny >= sea_y {
1810        let depth = (ny - sea_y) / (1.0 - sea_y);
1811        let surf_zone = (0.10..=0.46).contains(&nx)
1812            && ny < sea_y + 0.052 * (1.0 - (nx - 0.28).abs() * 4.2).max(0.0);
1813        if surf_zone {
1814            let foam = 0.72 + 0.28 * (nx * 110.0 + ny * 90.0).sin();
1815            let v = (182.0 + foam * 70.0) as u8;
1816            return [v.saturating_sub(10), v, v];
1817        }
1818        let tower_ref = (1.0 - ((nx - 0.28).abs() * 7.5).min(1.0)) * (1.0 - depth * 0.65);
1819        let beam_ref = ((nx - 0.28).max(0.0) * 1.5).min(1.0) * (1.0 - depth * 0.75) * 0.62;
1820        let ripple = (depth * 95.0 + nx * 24.0).sin() * 0.5 + 0.5;
1821        let glint = (tower_ref * 0.90 + beam_ref * 0.75) * (0.25 + 0.75 * ripple);
1822        return [
1823            (14.0 + glint * 222.0) as u8,
1824            (20.0 + glint * 202.0) as u8,
1825            (34.0 + glint * 158.0) as u8,
1826        ];
1827    }
1828
1829    // Sun-kissed rocky headland on the left
1830    let cliff_top = 0.62 + (nx - 0.27).powi(2) * 2.4 + 0.014 * (nx * 40.0).sin();
1831    if nx < 0.47 && ny >= cliff_top {
1832        let slope_lit = if nx >= 0.26 { 0.95 } else { 0.58 };
1833        let ridge = (1.0 - ((ny - cliff_top) * 5.0).min(1.0)) * 0.35;
1834        let crag = 0.78 + 0.22 * (nx * 65.0 + ny * 35.0).cos();
1835        let v = (48.0 + (slope_lit * crag + ridge) * 86.0).min(175.0) as u8;
1836        return [v, v.saturating_sub(4), v.saturating_add(14)];
1837    }
1838
1839    // Lighthouse tower at nx = 0.28, ny in 0.26..=0.65
1840    let tx = nx - 0.28;
1841    if (0.26..=0.65).contains(&ny) {
1842        let half_w = 0.028 + (ny - 0.26) * 0.056;
1843        if tx.abs() <= half_w {
1844            let cyl = (0.48 + 0.52 * ((tx / half_w.max(1e-4)) * 0.5 + 0.5)).clamp(0.42, 1.0);
1845            let stripe = ((ny - 0.26) * 19.0).floor() as i32 % 2 == 0;
1846            return if stripe {
1847                [
1848                    (252.0 * cyl) as u8,
1849                    (246.0 * cyl) as u8,
1850                    (234.0 * cyl) as u8,
1851                ]
1852            } else {
1853                [(242.0 * cyl) as u8, (96.0 * cyl) as u8, (74.0 * cyl) as u8]
1854            };
1855        }
1856    }
1857    // Gallery deck, blazing lantern room & cupola dome
1858    if (0.25..0.265).contains(&ny) && tx.abs() <= 0.038 {
1859        return [165, 170, 182];
1860    }
1861    if (0.195..0.25).contains(&ny) && tx.abs() <= 0.030 {
1862        if ny < 0.220 {
1863            if tx.abs() <= 0.028 * (1.0 - (0.220 - ny) / 0.026).max(0.0) {
1864                return [112, 120, 138];
1865            }
1866        } else {
1867            return [255, 252, 224];
1868        }
1869    }
1870
1871    // Sweeping searchlight beams from (0.28, 0.236)
1872    let bx = (nx - 0.28) * 1.5;
1873    let by = ny - 0.236;
1874    let dist = (bx * bx + by * by).sqrt();
1875    let mut beam = 0.0_f64;
1876    if bx > 0.0 {
1877        let center_y = 0.045 * bx;
1878        let half_cone = 0.020 + bx * 0.165;
1879        let perp = (by - center_y).abs();
1880        if perp < half_cone {
1881            let cross = (1.0 - (perp / half_cone).powi(2)).powf(1.2);
1882            let fade = (1.0 - (bx / 1.18).min(1.0)).powf(0.68);
1883            beam = beam.max(cross * fade * 0.94);
1884        }
1885    } else {
1886        let ax = -bx;
1887        let center_y = 0.025 * ax;
1888        let half_cone = 0.016 + ax * 0.145;
1889        let perp = (by - center_y).abs();
1890        if perp < half_cone {
1891            let cross = (1.0 - (perp / half_cone).powi(2)).powf(1.3);
1892            let fade = (1.0 - (ax / 0.52).min(1.0)).powf(0.8);
1893            beam = beam.max(cross * fade * 0.68);
1894        }
1895    }
1896    let lamp_glow = (1.0 - (dist / 0.16).min(1.0)).powi(3) * 0.90;
1897    let l = (beam + lamp_glow).clamp(0.0, 1.0);
1898    let s = if l < 0.08 { star_spark(nx, ny, 55) } else { 0 };
1899    [
1900        ((8.0 + l * 246.0) as u8).max(s),
1901        ((10.0 + l * 232.0) as u8).max(s),
1902        ((18.0 + l * 176.0) as u8).max(s),
1903    ]
1904}
1905
1906fn sample_torii_moon(nx: f64, ny: f64) -> [u8; 3] {
1907    // Traditional floating Torii gate silhouetted against a giant harvest moon.
1908    let water_y = 0.75;
1909    let (ux, uy, mir) = if ny > water_y {
1910        let ripple = ((ny - water_y) * 210.0).sin() * 0.010;
1911        (
1912            (nx + ripple).clamp(0.0, 1.0),
1913            (water_y - (ny - water_y) * 0.92).clamp(0.0, water_y),
1914            true,
1915        )
1916    } else {
1917        (nx, ny, false)
1918    };
1919
1920    // Torii geometry centred at ux = 0.50
1921    let cx = ux - 0.50;
1922    let kasagi_y = 0.305 - 0.42 * cx * cx;
1923    let on_kasagi = cx.abs() < 0.265 && (uy - kasagi_y).abs() < 0.017;
1924    let on_shimaki = cx.abs() < 0.240 && (uy - (kasagi_y + 0.022)).abs() < 0.010;
1925    let on_nuki = cx.abs() < 0.225 && (uy - 0.415).abs() < 0.014;
1926    let on_plaque = cx.abs() < 0.018 && (kasagi_y + 0.02..=0.415).contains(&uy);
1927    let pillar_x = 0.142 + (uy - 0.31).max(0.0) * 0.028;
1928    let on_pillar = (0.31..=water_y).contains(&uy) && (cx.abs() - pillar_x).abs() < 0.017;
1929    let on_foot = (water_y - 0.03..=water_y).contains(&uy) && (cx.abs() - pillar_x).abs() < 0.024;
1930
1931    let mut rgb = if on_kasagi || on_shimaki || on_nuki || on_plaque || on_pillar || on_foot {
1932        // Dark lacquer crimson so it cuts a sharp silhouette across the bright moon,
1933        // while keeping rich vermilion colour in Photo mode.
1934        if on_kasagi && uy < kasagi_y {
1935            [28, 18, 22]
1936        } else {
1937            [62, 18, 20]
1938        }
1939    } else {
1940        // Distant misty island hills along the waterline
1941        let hill = water_y
1942            - 0.055 * (1.0 - ((ux - 0.18).abs() * 4.2).min(1.0))
1943            - 0.045 * (1.0 - ((ux - 0.83).abs() * 4.6).min(1.0))
1944            - 0.012;
1945        if uy > hill {
1946            [22, 18, 28]
1947        } else {
1948            // Giant harvest moon centred at (0.50, 0.44)
1949            let mdx = (ux - 0.50) * 1.5;
1950            let mdy = uy - 0.44;
1951            let mr = (mdx * mdx + mdy * mdy).sqrt();
1952            if mr < 0.305 {
1953                let edge_soft = ((0.305 - mr) / 0.015).clamp(0.0, 1.0);
1954                // Subtle lunar mare texture so interior has rich ASCII tonal detail
1955                let mare =
1956                    0.86 + 0.14 * (mdx * 15.0 + mdy * 9.0).sin() * (mdx * 8.0 - mdy * 13.0).cos();
1957                let vert = ((uy - 0.14) / 0.58).clamp(0.0, 1.0);
1958                let r = (254.0 * mare * edge_soft) as u8;
1959                let g = ((236.0 - vert * 78.0) * mare * edge_soft) as u8;
1960                let b = ((168.0 - vert * 96.0) * mare * edge_soft) as u8;
1961                [r, g, b]
1962            } else {
1963                let glow = (1.0 - ((mr - 0.305) / 0.18).clamp(0.0, 1.0)).powi(3) * 28.0;
1964                let s = if mr > 0.38 { star_spark(ux, uy, 88) } else { 0 };
1965                [
1966                    ((10.0 + glow * 1.2) as u8).max(s),
1967                    ((9.0 + glow * 0.65) as u8).max(s),
1968                    ((16.0 + glow * 0.45) as u8).max(s),
1969                ]
1970            }
1971        }
1972    };
1973
1974    if mir {
1975        rgb = [
1976            (u16::from(rgb[0]) * 65 / 100) as u8,
1977            (u16::from(rgb[1]) * 62 / 100) as u8,
1978            (u16::from(rgb[2]) * 72 / 100) as u8,
1979        ];
1980    }
1981    rgb
1982}
1983
1984fn sample_great_wave(nx: f64, ny: f64) -> [u8; 3] {
1985    // Curling Prussian-blue & turquoise wave with white foam crest and distant snow peak.
1986    // Foreground swell at bottom
1987    let swell_y = 0.83 + 0.045 * (nx * 7.5 - 0.8).sin();
1988    if ny > swell_y {
1989        let crest = (ny - swell_y) < 0.024;
1990        if crest {
1991            return [236, 244, 250];
1992        }
1993        let d = ((ny - swell_y) / 0.18).clamp(0.0, 1.0);
1994        return [
1995            (24.0 + (1.0 - d) * 48.0) as u8,
1996            (58.0 + (1.0 - d) * 76.0) as u8,
1997            (108.0 + (1.0 - d) * 72.0) as u8,
1998        ];
1999    }
2000
2001    // Main arching wave outer curve + inner curling hollow around (0.55, 0.49)
2002    let outer_top = if nx < 0.56 {
2003        0.18 + ((0.48 - nx).max(0.0) * 1.32).powi(2) + ((nx - 0.48).max(0.0) * 1.6).powi(2)
2004    } else {
2005        1.2 // past the overhanging lip
2006    };
2007    let hdx = (nx - 0.54) * 1.42;
2008    let hdy = ny - 0.50;
2009    let hr = (hdx * hdx + hdy * hdy).sqrt();
2010    let in_hollow = hr < 0.235 && !(nx < 0.42 && ny > 0.54);
2011
2012    // Overhanging white foam claws & spray around the curling lip
2013    let lip_dx = (nx - 0.56) * 1.4;
2014    let lip_dy = ny - 0.27;
2015    let lip_r = (lip_dx * lip_dx + lip_dy * lip_dy).sqrt();
2016    let claw_angle = lip_dy.atan2(lip_dx);
2017    let in_claws = lip_r < 0.165
2018        && (-0.4..=2.3).contains(&claw_angle)
2019        && ((claw_angle * 7.0 + lip_r * 22.0).sin() > 0.08 || lip_r < 0.075);
2020
2021    if in_claws {
2022        return [246, 250, 255];
2023    }
2024
2025    let in_main_wave =
2026        (ny >= outer_top && !in_hollow && nx < 0.64) || (ny >= 0.72 + 0.04 * (nx * 5.0).cos());
2027    if in_main_wave {
2028        let near_crest = (ny - outer_top).abs() < 0.048 && nx > 0.16 && nx < 0.58;
2029        let inner_rim = (hr - 0.235).abs() < 0.032 && ny < 0.52 && nx > 0.36;
2030        if near_crest || inner_rim {
2031            return [242, 248, 254];
2032        }
2033        // Translucent turquoise near top, deep Prussian blue in trough, pale striations
2034        let height_u = (1.0 - ((ny - 0.20) / 0.62).clamp(0.0, 1.0)).powf(1.2);
2035        let streak = ((nx * 28.0 + ny * 19.0).sin() * 0.5 + 0.5).powi(3) * 0.28;
2036        let u = (height_u * 0.78 + streak).clamp(0.0, 1.0);
2037        return [
2038            (22.0 + u * 86.0) as u8,
2039            (46.0 + u * 146.0) as u8,
2040            (96.0 + u * 128.0) as u8,
2041        ];
2042    }
2043
2044    // Distant snow-capped volcanic cone on the right horizon
2045    let fuji_dx = (nx - 0.76).abs();
2046    let fuji_top = 0.57 + fuji_dx.powf(0.82) * 1.05;
2047    if fuji_dx > 0.018 && ny >= fuji_top && ny <= 0.76 {
2048        let snow_line = 0.635 + 0.015 * (nx * 45.0).sin();
2049        return if ny < snow_line {
2050            [240, 244, 252]
2051        } else {
2052            [56, 74, 114]
2053        };
2054    }
2055    if fuji_dx <= 0.018 && (0.585..=0.76).contains(&ny) {
2056        return if ny < 0.64 {
2057            [244, 248, 254]
2058        } else {
2059            [56, 74, 114]
2060        };
2061    }
2062
2063    // Clean dramatic twilight sky so wave foam and snow cap pop sharply
2064    [10, 13, 22]
2065}
2066
2067fn sample_jellyfish(nx: f64, ny: f64) -> [u8; 3] {
2068    // Bioluminescent jellyfish drifting diagonally in deep abyssal water.
2069    let u = (nx - 0.56) * 1.5;
2070    let v = ny - 0.34;
2071    let (sin_a, cos_a) = 0.42_f64.sin_cos();
2072    let ru = u * cos_a - v * sin_a;
2073    let rv = u * sin_a + v * cos_a;
2074
2075    // Scalloped bell dome in rv: -0.22..=0.06
2076    let scallop = 0.055 + 0.018 * (ru * 38.0).cos();
2077    if rv >= -0.23 && rv <= scallop {
2078        let t = ((rv + 0.23) / 0.29).clamp(0.0, 1.0);
2079        let half_w = 0.27 * (1.0 - (1.0 - t).powf(2.1)).max(0.0).sqrt();
2080        if ru.abs() <= half_w {
2081            let ux = ru / half_w.max(1e-4);
2082            let rim = ux.abs().powi(3);
2083            let margin = ((rv - (scallop - 0.035)) / 0.035).clamp(0.0, 1.0);
2084            let canal = ((ux * std::f64::consts::PI * 3.5).cos().abs()).powi(8) * 0.55;
2085            let inner_pink = (1.0 - ux.abs()) * (1.0 - (t - 0.55).abs() * 2.2).max(0.0);
2086            let glow =
2087                (0.34 + rim * 0.62 + margin * 0.48 + canal + inner_pink * 0.45).clamp(0.0, 1.0);
2088            return [
2089                (38.0 + inner_pink * 205.0 + rim * 65.0).min(255.0) as u8,
2090                (65.0 + glow * 178.0 - inner_pink * 55.0).clamp(0.0, 255.0) as u8,
2091                (125.0 + glow * 130.0).min(255.0) as u8,
2092            ];
2093        }
2094    }
2095
2096    // Trailing ruffled oral arms & slender outer tentacles in rv: 0.03..=0.64
2097    if (0.03..=0.64).contains(&rv) {
2098        let fade = (1.0 - (rv - 0.03) / 0.62).clamp(0.0, 1.0);
2099        let mut best_pink = 0.0_f64;
2100        for (offset, freq, phase) in [(-0.052, 16.0, 0.4), (0.0, 13.5, 2.1), (0.052, 15.0, 4.0)] {
2101            let center = offset + (rv * freq + phase).sin() * 0.040 * (0.4 + 0.6 * (1.0 - fade));
2102            let w = 0.028 * fade.sqrt().max(0.35);
2103            let d = (ru - center).abs();
2104            if d < w {
2105                best_pink = best_pink.max((1.0 - d / w).powf(0.7) * fade.powf(0.45));
2106            }
2107        }
2108        let mut best_cyan = 0.0_f64;
2109        for (offset, freq, phase) in [
2110            (-0.18, 11.0, 0.0),
2111            (-0.11, 13.0, 1.5),
2112            (0.11, 12.5, 3.1),
2113            (0.18, 10.5, 4.7),
2114        ] {
2115            let center = offset + (rv * freq + phase).sin() * 0.034;
2116            let w = 0.015;
2117            let d = (ru - center).abs();
2118            if d < w {
2119                best_cyan = best_cyan.max((1.0 - d / w).powf(0.75) * fade.powf(0.42));
2120            }
2121        }
2122        if best_pink > 0.02 || best_cyan > 0.02 {
2123            let r = (36.0 + best_pink * 218.0 + best_cyan * 65.0).min(255.0) as u8;
2124            let g = (48.0 + best_pink * 125.0 + best_cyan * 206.0).min(255.0) as u8;
2125            let b = (82.0 + best_pink * 172.0 + best_cyan * 173.0).min(255.0) as u8;
2126            return [r, g, b];
2127        }
2128    }
2129
2130    let sp = star_spark(nx, ny, 204);
2131    [6 | (sp / 3), 9 | ((u16::from(sp) * 3 / 4) as u8), 16 | sp]
2132}
2133
2134fn sample_aurora_pines(nx: f64, ny: f64) -> [u8; 3] {
2135    // Boreal spruce forest silhouetted directly in front of glowing northern lights.
2136    let lake_y = 0.78;
2137    let (ux, uy, mir) = if ny > lake_y {
2138        let ripple = ((ny - lake_y) * 195.0).sin() * 0.014;
2139        (
2140            (nx + ripple).clamp(0.0, 1.0),
2141            (lake_y - (ny - lake_y) * 1.15).clamp(0.0, lake_y),
2142            true,
2143        )
2144    } else {
2145        (nx, ny, false)
2146    };
2147
2148    // Jagged boreal spruce silhouettes cutting into the glowing horizon curtain
2149    let trees: [(f64, f64, f64); 10] = [
2150        (0.06, 0.50, 0.072),
2151        (0.16, 0.40, 0.084),
2152        (0.27, 0.54, 0.064),
2153        (0.37, 0.60, 0.056),
2154        (0.48, 0.64, 0.052),
2155        (0.59, 0.58, 0.060),
2156        (0.70, 0.46, 0.078),
2157        (0.82, 0.37, 0.090),
2158        (0.93, 0.49, 0.074),
2159        (0.21, 0.62, 0.055),
2160    ];
2161    for (tx, apex, span) in trees {
2162        if uy >= apex && uy <= lake_y {
2163            let h_frac = (uy - apex) / (lake_y - apex);
2164            let tier = 0.68 + 0.32 * ((uy - apex) * 54.0).fract();
2165            let half_w = span * h_frac.powf(0.84) * tier;
2166            if (ux - tx).abs() <= half_w {
2167                return [8, 13, 15];
2168            }
2169        }
2170    }
2171    if uy > 0.755 {
2172        return [10, 16, 18];
2173    }
2174
2175    // Two sweeping aurora curtains reaching down to the lake horizon behind every spruce tree
2176    let c1_base = 0.76 + 0.02 * (ux * 5.2 - 0.6).sin();
2177    let c2_base = 0.42 + 0.08 * (ux * 6.4 + 1.8).sin();
2178    let rays1 = 0.78 + 0.22 * (ux * 76.0 + uy * 6.0).sin();
2179    let rays2 = 0.70 + 0.30 * (ux * 64.0 - uy * 5.0 + 1.4).cos();
2180
2181    let a1 = if uy <= lake_y {
2182        let up = (c1_base - uy).max(0.0);
2183        (-up * 3.6).exp() * rays1
2184    } else {
2185        0.0
2186    };
2187    let a2 = if uy <= c2_base + 0.03 {
2188        let up = (c2_base - uy).max(0.0);
2189        let bot = ((c2_base + 0.03 - uy) / 0.03).clamp(0.0, 1.0);
2190        (-up * 5.8).exp() * bot * rays2 * 0.88
2191    } else {
2192        0.0
2193    };
2194
2195    let alt = ((c1_base - uy).max(0.0) / 0.42).clamp(0.0, 1.0);
2196    let intensity = (a1 * 0.95 + a2 * 0.85).clamp(0.0, 1.0);
2197    let s = if intensity < 0.10 && !mir {
2198        star_spark(ux, uy, 311)
2199    } else {
2200        0
2201    };
2202    let mut rgb = [
2203        ((7.0 + intensity * (52.0 + alt * 165.0)) as u8).max(s),
2204        ((9.0 + intensity * (250.0 - alt * 120.0)) as u8).max(s),
2205        ((16.0 + intensity * (150.0 + alt * 96.0)) as u8).max(s),
2206    ];
2207    if mir {
2208        rgb = [
2209            (u16::from(rgb[0]) * 72 / 100) as u8,
2210            (u16::from(rgb[1]) * 78 / 100) as u8,
2211            (u16::from(rgb[2]) * 82 / 100) as u8,
2212        ];
2213    }
2214    rgb
2215}
2216
2217fn in_tri(p: (f64, f64), a: (f64, f64), b: (f64, f64), c: (f64, f64)) -> bool {
2218    let cross = |o: (f64, f64), u: (f64, f64), v: (f64, f64)| {
2219        (u.0 - o.0) * (v.1 - o.1) - (u.1 - o.1) * (v.0 - o.0)
2220    };
2221    let d1 = cross(p, a, b);
2222    let d2 = cross(p, b, c);
2223    let d3 = cross(p, c, a);
2224    let has_neg = (d1 < 0.0) || (d2 < 0.0) || (d3 < 0.0);
2225    let has_pos = (d1 > 0.0) || (d2 > 0.0) || (d3 > 0.0);
2226    !(has_neg && has_pos)
2227}
2228
2229fn sample_origami_crane(nx: f64, ny: f64) -> [u8; 4] {
2230    // Geometric folded paper crane with distinct per-facet shading and alpha cutout.
2231    let p = ((nx - 0.50) * 1.5, ny - 0.48);
2232
2233    // Painter's order from back to front so overlapping folds have crisp crease lines:
2234    let mut out: Option<[u8; 3]> = None;
2235
2236    // 1. Far wing (back right)
2237    if in_tri(p, (-0.06, 0.00), (0.36, -0.38), (0.16, 0.06)) {
2238        out = Some([112, 128, 162]);
2239    }
2240    // 2. Tail spire (right)
2241    if in_tri(p, (0.10, 0.07), (0.46, -0.22), (0.24, 0.16)) {
2242        out = Some([154, 144, 148]);
2243    }
2244    // 3. Lower belly fold
2245    if in_tri(p, (-0.22, 0.13), (0.24, 0.16), (0.01, 0.29)) {
2246        out = Some([84, 80, 92]);
2247    }
2248    // 4. Central folded body diamond
2249    if in_tri(p, (-0.22, 0.13), (0.02, -0.10), (0.24, 0.16)) {
2250        out = Some([192, 184, 176]);
2251    }
2252    // 5. Neck spire (left)
2253    if in_tri(p, (-0.11, 0.09), (-0.33, -0.30), (-0.22, 0.13)) {
2254        out = Some([228, 212, 194]);
2255    }
2256    // 6. Folded head / beak tip
2257    if in_tri(p, (-0.33, -0.30), (-0.48, -0.19), (-0.29, -0.20)) {
2258        out = Some([244, 142, 102]);
2259    }
2260    // 7. Foreground main wing (sweeping upper-left to body crease)
2261    if in_tri(p, (-0.17, 0.04), (0.18, 0.06), (-0.07, -0.41)) {
2262        let lift = ((-0.04 - p.1) / 0.38).clamp(0.0, 1.0);
2263        out = Some([
2264            (216.0 + lift * 38.0) as u8,
2265            (204.0 + lift * 42.0) as u8,
2266            (190.0 + lift * 46.0) as u8,
2267        ]);
2268    }
2269
2270    match out {
2271        Some([r, g, b]) => [r, g, b, 255],
2272        None => [0, 0, 0, 0],
2273    }
2274}
2275
2276#[cfg(test)]
2277mod tests {
2278    use super::*;
2279    use crate::clock::Clock;
2280
2281    fn split_gradient() -> RgbaImage {
2282        let (w, h) = (80, 48);
2283        let mut px = Vec::with_capacity((w * h * 4) as usize);
2284        for y in 0..h {
2285            for x in 0..w {
2286                let v = (x * 255 / (w - 1)) as u8;
2287                let r = v;
2288                let g = (y * 255 / (h - 1)) as u8;
2289                let b = 255 - v;
2290                px.extend_from_slice(&[r, g, b, 255]);
2291            }
2292        }
2293        RgbaImage::new(w, h, px).unwrap()
2294    }
2295
2296    #[test]
2297    fn dark_and_light_polarities_invert_character_weights() {
2298        let src = split_gradient();
2299        let mut cfg = AsciiConfig {
2300            columns: 40,
2301            color_mode: AsciiColorMode::Black,
2302            ..AsciiConfig::default()
2303        };
2304        let on_black = convert_standalone(&src, &cfg, Theme::Dark);
2305        let last = (on_black.cols * on_black.rows - 1) as usize;
2306        assert_eq!(on_black.chars[0], ' ');
2307        assert_eq!(on_black.chars[last], '@');
2308
2309        cfg.color_mode = AsciiColorMode::White;
2310        let on_white = convert_standalone(&src, &cfg, Theme::Light);
2311        assert_eq!(on_white.chars[0], '@');
2312        assert_eq!(on_white.chars[last], ' ');
2313    }
2314
2315    #[test]
2316    fn braille_and_custom_ramps_produce_expected_characters() {
2317        let src = split_gradient();
2318        let braille_cfg = AsciiConfig {
2319            columns: 32,
2320            ramp: RampPreset::Braille,
2321            ..AsciiConfig::default()
2322        };
2323        let braille = convert_standalone(&src, &braille_cfg, Theme::Dark);
2324        assert!(
2325            braille
2326                .chars
2327                .iter()
2328                .any(|&c| ('\u{2801}'..='\u{28FF}').contains(&c))
2329        );
2330
2331        let custom_cfg = AsciiConfig {
2332            columns: 32,
2333            ramp: RampPreset::Custom,
2334            custom_ramp: "#. ".into(),
2335            ..AsciiConfig::default()
2336        };
2337        let custom = convert_standalone(&src, &custom_cfg, Theme::Dark);
2338        assert!(custom.chars.iter().all(|c| ['#', '.', ' '].contains(c)));
2339    }
2340
2341    #[test]
2342    fn none_background_exports_transparent_rgba_png_in_light_and_dark_ink() {
2343        let src = split_gradient();
2344        let cfg = AsciiConfig {
2345            columns: 30,
2346            color_mode: AsciiColorMode::None,
2347            ..AsciiConfig::default()
2348        };
2349        let art_dark = convert_standalone(&src, &cfg, Theme::Dark);
2350        let (w, h, rgba_light_ink) = render_rgba(&art_dark, &cfg, Theme::Dark, 12, true);
2351        assert_eq!(
2352            rgba_light_ink[3], 0,
2353            "top-left margin pixel must be transparent"
2354        );
2355        let light_ink_px = rgba_light_ink
2356            .as_chunks::<4>()
2357            .0
2358            .iter()
2359            .find(|p| p[3] > 200)
2360            .expect("opaque light-ink pixel");
2361        assert!(
2362            light_ink_px[0] > 200,
2363            "Theme::Dark None mode should render light ink"
2364        );
2365
2366        let art_light = convert_standalone(&src, &cfg, Theme::Light);
2367        let (_, _, rgba_dark_ink) = render_rgba(&art_light, &cfg, Theme::Light, 12, true);
2368        let dark_ink_px = rgba_dark_ink
2369            .as_chunks::<4>()
2370            .0
2371            .iter()
2372            .find(|p| p[3] > 200)
2373            .expect("opaque dark-ink pixel");
2374        assert!(
2375            dark_ink_px[0] < 40,
2376            "Theme::Light None mode should render dark ink"
2377        );
2378
2379        let png = encode_rgba_png(w, h, &rgba_light_ink).unwrap();
2380        assert!(png.starts_with(b"\x89PNG"));
2381    }
2382
2383    #[test]
2384    fn custom_ramp_sanitizes_unmapped_unicode_and_weather_scale_uses_scene_grid() {
2385        // Emoji, control chars, and duplicate characters are stripped or deduplicated,
2386        // falling back cleanly if nothing renderable was typed.
2387        let fallback = RampPreset::Custom.heavy_to_light("🚀🎉\n\t   ");
2388        assert_eq!(fallback.last(), Some(&' '));
2389        assert!(fallback.len() >= 2);
2390        assert!(
2391            fallback
2392                .iter()
2393                .take(fallback.len() - 1)
2394                .all(|&c| GlyphAtlas::can_render_char(c))
2395        );
2396
2397        let deduped = RampPreset::Custom.heavy_to_light("@@@###...🚀 ");
2398        assert_eq!(deduped, vec!['@', '#', '.', ' ']);
2399
2400        // Extreme aspect ratio (400x1) and low column count (30 cols) do not panic
2401        // and keep `SceneGraph.grid` at standard monitor particle resolution.
2402        let wide = RgbaImage::new(400, 1, vec![220; 400 * 4]).unwrap();
2403        let cfg = AsciiConfig {
2404            columns: 30,
2405            weather: "snow".into(),
2406            ..AsciiConfig::default()
2407        };
2408        assert!(cfg.has_live_weather());
2409        let pkg = build_photo_package(&wide, &cfg, 1920, 1080, 99).unwrap();
2410        let g = pkg.graph(Theme::Dark).unwrap();
2411        let expected = clairlune_scene::grid_spec(1920, 1080);
2412        assert_eq!(
2413            (g.grid.cell_w, g.grid.cell_h),
2414            (expected.cell_w, expected.cell_h)
2415        );
2416    }
2417
2418    #[test]
2419    fn all_inspire_samples_have_crisp_silhouettes_and_tonal_range() {
2420        let cfg = AsciiConfig {
2421            columns: 80,
2422            ..AsciiConfig::default()
2423        };
2424        for buddy in [false, true] {
2425            let mut seen_titles = std::collections::HashSet::new();
2426            for idx in 0..INSPIRE_COUNT {
2427                let (title, img) = inspire_sample(idx, buddy);
2428                assert!(seen_titles.insert(title), "duplicate title {title}");
2429                assert_eq!((img.width, img.height), (360, 240));
2430                let art = convert_standalone(&img, &cfg, Theme::Dark);
2431                let total = art.chars.len();
2432                let non_space = art.chars.iter().filter(|&&c| c != ' ').count();
2433                let unique_ink: std::collections::HashSet<char> =
2434                    art.chars.iter().copied().filter(|&c| c != ' ').collect();
2435                assert!(
2436                    non_space > total / 10 && non_space < total * 9 / 10,
2437                    "{title} (buddy={buddy}) coverage {non_space}/{total} should keep a clean silhouette"
2438                );
2439                assert!(
2440                    unique_ink.len() >= 5,
2441                    "{title} (buddy={buddy}) should use >= 5 tonal levels, got {:?}",
2442                    unique_ink
2443                );
2444            }
2445        }
2446    }
2447
2448    #[test]
2449    fn photo_packages_save_load_and_animate_weather_in_palette_and_photo_modes() {
2450        let (_, src) = inspire_sample(0, true);
2451        let dir = std::env::temp_dir().join(format!("clairlune-img2ascii-{}", std::process::id()));
2452        let _ = std::fs::remove_dir_all(&dir);
2453
2454        for (idx, mode) in [
2455            AsciiColorMode::Palette("nord".into()),
2456            AsciiColorMode::Photo,
2457            AsciiColorMode::Black,
2458        ]
2459        .into_iter()
2460        .enumerate()
2461        {
2462            let cfg = AsciiConfig {
2463                columns: 80,
2464                ramp: RampPreset::Detailed,
2465                color_mode: mode,
2466                weather: "snow".into(),
2467                ..AsciiConfig::default()
2468            };
2469            let pkg = build_photo_package(&src, &cfg, 640, 360, 12345).unwrap();
2470            let sub = dir.join(format!("mode-{idx}"));
2471            pkg.save(&sub).unwrap();
2472            let loaded = ScenePackage::load(&sub).unwrap();
2473            let theme = loaded.themes()[0];
2474            let (still, pal) = loaded.still(theme, false).unwrap();
2475            assert_eq!((still.width, still.height), (640, 360));
2476            assert!(pal.len() <= 255);
2477
2478            let mut inc = loaded.incremental(theme).unwrap();
2479            let dirty = loaded
2480                .advance(&mut inc, theme, false, 1500, Clock::Smooth)
2481                .unwrap();
2482            assert!(!dirty.is_empty(), "snow weather should animate frames");
2483        }
2484
2485        let _ = std::fs::remove_dir_all(&dir);
2486    }
2487}