Skip to main content

sciart_core/
ink.rs

1//! Semantic inks (CORE-R8), ink levels (CORE-R66), the colormap-field helpers
2//! (CORE-R46, CORE-R56, ADR-0011) and the phase, blackbody and named-ramp roles
3//! (CORE-R78..R80, ADR-0015).
4
5use std::f64::consts::TAU;
6
7/// What a cell *means*; themes turn roles into colors (ADR-0004, CORE-R8).
8#[non_exhaustive]
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10pub enum Role {
11    Background,
12    Dim,
13    Star,
14    Sun,
15    Planet,
16    Particle,
17    Wave,
18    Hot,
19    Cold,
20    Structure,
21    Accent,
22    Text,
23    /// Sequential scalar field: level 0 = low, 255 = high (CORE-R46). Build with [`seq`].
24    Seq,
25    /// Signed scalar field: level 128 = zero, 0 = most negative, 255 = most positive
26    /// (CORE-R46). Build with [`div`].
27    Div,
28    /// Cyclic field: level is a phase angle, one turn over 256 levels, so 255 sits next
29    /// to 0 (CORE-R78). Build with [`phase`].
30    Phase,
31    /// Temperature on a log scale, 1000 K at level 0 to 30 000 K at 255, drawn in the
32    /// colour of a blackbody (CORE-R79). Build with [`blackbody`].
33    Blackbody,
34    /// Sequential field in a named ramp: level 0 = low, 255 = high (CORE-R80). Build with
35    /// [`ramp()`].
36    Ramp(Ramp),
37}
38
39/// A named sequential ramp for [`Role::Ramp`] (CORE-R80, ADR-0015): one hue family each,
40/// near-black at level 0 and pale at 255, so field scenes keep their own identity under
41/// one theme. Named palettes are false colour; SPEC-002 says so where a scene uses one.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
43pub enum Ramp {
44    /// Oxblood → scarlet → orange → pale gold: glowing matter, fire, plumes, growth age.
45    Ember,
46    /// Navy → teal-blue → cyan → white: cold gas, frost, Cherenkov and young-star blue.
47    Ice,
48    /// Wine → crimson → violet → azure: BZ ferroin (red, reduced) to ferriin (blue).
49    Ferroin,
50    /// Crimson → rose → pale pink: emission nebulae (Hα 656 nm), prominences.
51    HAlpha,
52    /// Deep teal → emerald → lime-white: auroral O I 557.7 nm, fluorescence.
53    Aurora,
54    /// Indigo → violet → lavender-white: discharges, lightning, synchrotron glow.
55    Plasma,
56    /// Near-black → neutral grey → pale warm white: unresolved starlight, the nearly
57    /// colourless integrated light of an old stellar population.
58    Starlight,
59    /// Near-black olive → chrome yellow → pale lemon: the plasmodium of *Physarum
60    /// polycephalum*, sulfur and pollen yellows (a yellow that is not Ember's orange).
61    Sulfur,
62    /// Deep ultramarine → cobalt blue → pale silver-blue: cobalt glass and pigments, a
63    /// cool precipitate (M12, `liesegang_rings`), a blue that is not Ice's cyan.
64    Cobalt,
65    /// Wine-rose → eosin rose-pink → pale pink-lilac: the eosin of a histology stain, for
66    /// patterns that read as tissue (M12, `gray_scott`), a rose that is neither Ferroin's
67    /// plum, Plasma's violet nor HAlpha's crimson.
68    Eosin,
69    /// Dark sienna → rust → tan → cream: the ammonia-cloud belts and zones of Jupiter-family
70    /// planets and Saturn's butterscotch (M13), an earth tone far softer than Ember's fire.
71    Sienna,
72    /// Near-black → grey → cyan → green → yellow → orange → pale rose-white: a meteorological
73    /// infrared enhancement curve (M13, `hurricane`) — warm surfaces stay grey, colder cloud
74    /// tops step through colour, the coldest overshooting tops are palest.
75    Infrared,
76}
77
78impl Ramp {
79    /// Every ramp, in declaration order.
80    pub const ALL: [Ramp; 12] = [
81        Ramp::Ember,
82        Ramp::Ice,
83        Ramp::Ferroin,
84        Ramp::HAlpha,
85        Ramp::Aurora,
86        Ramp::Plasma,
87        Ramp::Starlight,
88        Ramp::Sulfur,
89        Ramp::Cobalt,
90        Ramp::Eosin,
91        Ramp::Sienna,
92        Ramp::Infrared,
93    ];
94
95    /// A unique lower-case name.
96    pub const fn name(self) -> &'static str {
97        match self {
98            Ramp::Ember => "ember",
99            Ramp::Ice => "ice",
100            Ramp::Ferroin => "ferroin",
101            Ramp::HAlpha => "halpha",
102            Ramp::Aurora => "aurora",
103            Ramp::Plasma => "plasma",
104            Ramp::Starlight => "starlight",
105            Ramp::Sulfur => "sulfur",
106            Ramp::Cobalt => "cobalt",
107            Ramp::Eosin => "eosin",
108            Ramp::Sienna => "sienna",
109            Ramp::Infrared => "infrared",
110        }
111    }
112}
113
114/// Semantic style of a cell: a role plus an intensity `0..=255`.
115#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
116pub struct Ink {
117    pub role: Role,
118    pub level: u8,
119}
120
121impl Ink {
122    pub const BLANK: Ink = Ink::new(Role::Background, 0);
123
124    pub const fn new(role: Role, level: u8) -> Self {
125        Self { role, level }
126    }
127}
128
129impl Default for Ink {
130    fn default() -> Self {
131        Self::BLANK
132    }
133}
134
135/// Levels below this should not be drawn (CORE-R66): every theme keeps level 0 visible
136/// (a dim ink is still a glyph), so a fade must end by removing ink, not by dimming it to
137/// nothing. Compare the real-valued level before converting it with [`level`].
138pub const MIN_VISIBLE_LEVEL: f64 = 12.0;
139
140/// An ink level from a real value: rounded to the nearest integer and clamped to
141/// `0..=255`; NaN ⇒ 0 (CORE-R66).
142#[inline]
143pub fn level(v: f64) -> u8 {
144    // `clamp` keeps NaN, and the saturating `as u8` maps it to 0.
145    v.round().clamp(0.0, 255.0) as u8
146}
147
148/// A [`Role::Seq`] ink for `v ∈ [0, 1]`: 0 ⇒ level 0, 1 ⇒ 255; clamped, NaN ⇒ 0
149/// (CORE-R46).
150#[inline]
151pub fn seq(v: f64) -> Ink {
152    // `clamp` keeps NaN, and a saturating `as u8` maps NaN to 0: the low end.
153    Ink::new(Role::Seq, (v.clamp(0.0, 1.0) * 255.0).round() as u8)
154}
155
156/// A [`Role::Ramp`] ink for `v ∈ [0, 1]` in `ramp`, mapped exactly like [`seq`] and read
157/// back with [`seq_value`] (CORE-R80).
158#[inline]
159pub fn ramp(ramp: Ramp, v: f64) -> Ink {
160    Ink::new(Role::Ramp(ramp), seq(v).level)
161}
162
163/// A [`Role::Phase`] ink for an angle in radians, wrapped onto one turn:
164/// `round(frac(a / 2π) · 256) mod 256`; NaN or ±∞ ⇒ level 0 (CORE-R78).
165#[inline]
166pub fn phase(radians: f64) -> Ink {
167    let turns = radians / TAU;
168    let frac = if turns.is_finite() {
169        turns - turns.floor()
170    } else {
171        0.0
172    };
173    // `frac ∈ [0, 1]` (it can round up to exactly 1), so the product is in [0, 256] and
174    // the wrap folds 256 onto 0.
175    Ink::new(Role::Phase, ((frac * 256.0).round() as u32 % 256) as u8)
176}
177
178/// The angle in `[0, 2π)` a [`Role::Phase`] level stands for, `level · 2π / 256`: the
179/// exact inverse of [`phase`] on its levels (CORE-R78). Reads `level` whatever the role.
180#[inline]
181pub fn phase_value(ink: Ink) -> f64 {
182    f64::from(ink.level) * TAU / 256.0
183}
184
185/// Temperature at [`Role::Blackbody`] level 0 (CORE-R79).
186pub const BLACKBODY_MIN_K: f64 = 1000.0;
187/// Temperature at [`Role::Blackbody`] level 255 (CORE-R79).
188pub const BLACKBODY_MAX_K: f64 = 30_000.0;
189
190/// A [`Role::Blackbody`] ink for a temperature in kelvin: level `255 · ln(T / 1000) / ln 30`,
191/// rounded and clamped; NaN ⇒ level 0 (CORE-R79). The log scale spends about half the
192/// levels on the red-to-white part, where the colour changes fastest.
193#[inline]
194pub fn blackbody(kelvin: f64) -> Ink {
195    let t = (kelvin / BLACKBODY_MIN_K).ln() / (BLACKBODY_MAX_K / BLACKBODY_MIN_K).ln();
196    // `ln` of a non-positive ratio is −∞ or NaN: both land on level 0 via `level`.
197    Ink::new(Role::Blackbody, level(t * 255.0))
198}
199
200/// The temperature in kelvin a [`Role::Blackbody`] level stands for,
201/// `1000 · 30^(level / 255)`: the inverse of [`blackbody`] on its levels (CORE-R79). Reads
202/// `level` whatever the role.
203#[inline]
204pub fn blackbody_kelvin(ink: Ink) -> f64 {
205    BLACKBODY_MIN_K * (BLACKBODY_MAX_K / BLACKBODY_MIN_K).powf(f64::from(ink.level) / 255.0)
206}
207
208/// A temperature drawn from a spectral-class mix (CORE-R88): `classes` holds
209/// `(cumulative fraction, lowest K, highest K)` rows in increasing fraction; a uniform `u`
210/// picks the first row with `u < fraction` (the last row past the end) and `v ∈ [0, 1]`
211/// places the temperature within it, `lo + (hi − lo)·v`. NaN for an empty table.
212#[inline]
213pub fn class_kelvin(classes: &[(f64, f64, f64)], u: f64, v: f64) -> f64 {
214    let Some(&last) = classes.last() else {
215        return f64::NAN;
216    };
217    let (_, lo, hi) = classes
218        .iter()
219        .copied()
220        .find(|&(cum, _, _)| u < cum)
221        .unwrap_or(last);
222    lo + (hi - lo) * v
223}
224
225/// A [`Role::Div`] ink for `v ∈ [−1, 1]`: −1 ⇒ 0, 0 ⇒ 128, 1 ⇒ 255; clamped, NaN ⇒ 128
226/// (CORE-R46).
227///
228/// The two halves have different slopes (128 levels below zero, 127 above) so that
229/// both ends of the range and an exact zero are representable.
230#[inline]
231pub fn div(v: f64) -> Ink {
232    let v = if v.is_nan() { 0.0 } else { v.clamp(-1.0, 1.0) };
233    let half = if v < 0.0 { 128.0 } else { 127.0 };
234    Ink::new(Role::Div, (128.0 + v * half).round() as u8)
235}
236
237/// The value `v ∈ [0, 1]` a [`Role::Seq`] level stands for: `level / 255`, the exact
238/// inverse of [`seq`] on its levels (CORE-R56). Reads `level` whatever the role.
239#[inline]
240pub fn seq_value(ink: Ink) -> f64 {
241    f64::from(ink.level) / 255.0
242}
243
244/// The value `v ∈ [−1, 1]` a [`Role::Div`] level stands for, the exact inverse of
245/// [`div`] on its levels (same two slopes either side of 128) (CORE-R56). Reads `level`
246/// whatever the role.
247#[inline]
248pub fn div_value(ink: Ink) -> f64 {
249    let d = f64::from(ink.level) - 128.0;
250    if d < 0.0 { d / 128.0 } else { d / 127.0 }
251}
252
253/// A cheap `tanh`-like squash onto `[−1, 1]` for mapping unbounded fields to colour
254/// (CORE-R56): the Padé approximant `x(27 + x²) / (27 + 9x²)`, which is odd, monotone
255/// (its derivative is `9(x² − 9)² / (27 + 9x²)² ≥ 0`), meets ±1 with zero slope at
256/// `|x| = 3`, and is exactly ±1 beyond. No libm call, so it is bit-reproducible across
257/// platforms; NaN ⇒ 0.
258#[inline]
259pub fn soft_clip(x: f64) -> f64 {
260    if x.is_nan() {
261        0.0
262    } else if x >= 3.0 {
263        1.0
264    } else if x <= -3.0 {
265        -1.0
266    } else {
267        let x2 = x * x;
268        (x * (27.0 + x2) / (27.0 + 9.0 * x2)).clamp(-1.0, 1.0)
269    }
270}