Skip to main content

sciart_shared/
skyline.rs

1//! An anti-aliased horizon silhouette (a far ridge and an optional conifer forest) shared
2//! by the Earth & Sky scenes. Heights are in degrees above the horizon, so the land keeps
3//! its shape at every size; each pixel column is sub-sampled, so a spruce flank is a soft
4//! slope of partly covered pixels rather than a staircase.
5
6use rand::Rng;
7use sciart_core::timeline::ease;
8
9/// Height samples per pixel column: the silhouette is anti-aliased across as well as
10/// down, so a spruce flank is a soft slope of partly covered pixels, not a staircase.
11pub const SKY_SUB: usize = 4;
12
13/// What stands on the horizon: a far ridge and, optionally, a conifer forest. Heights
14/// are in degrees above the horizon, so the land keeps its shape at every size.
15#[derive(Debug, Clone, Copy)]
16pub struct Terrain {
17    /// Ridge base and relief (deg): `base + relief · noise`.
18    pub ridge: (f64, f64),
19    /// Tree heights (deg), or `None` for bare hills.
20    pub trees: Option<(f64, f64)>,
21    /// Gap between neighbouring spires (deg).
22    pub gap: (f64, f64),
23    /// Chance that a stretch of forest is a clearing.
24    pub clearing: f64,
25}
26
27/// A spruce forest on a low ridge (the tests' reference terrain; scenes set their own).
28#[cfg(any(test, feature = "test-support"))]
29pub const FOREST: Terrain = Terrain {
30    ridge: (0.6, 2.2),
31    trees: Some((1.4, 4.2)),
32    gap: (0.35, 1.6),
33    clearing: 0.2,
34};
35
36/// Spruce tiers: the crown's width runs down each tier like a sawtooth, so a tree reads
37/// as a layered conifer rather than a triangle.
38const TIERS: f64 = 5.0;
39/// Crown half-width at the base, as a fraction of the tree's height.
40const CROWN: f64 = 0.27;
41
42/// An anti-aliased silhouette: silhouette height above the horizon in pixels, at
43/// [`SKY_SUB`] samples per pixel column. Seeded and laid out in `resize`.
44#[derive(Debug, Clone, Default)]
45pub struct Skyline {
46    sub: Vec<f32>,
47}
48
49/// One spire: centre (deg from the left edge), height and base half-width (deg).
50#[derive(Debug, Clone, Copy)]
51struct Spire {
52    at: f64,
53    height: f64,
54    half: f64,
55}
56
57impl Spire {
58    /// Height (deg) of the crown `off` degrees from the trunk, or 0 beyond it: the highest
59    /// point of the tiered crown whose half-width at height `v` (0 = base, 1 = tip) is
60    /// `half · (1 − v) · (0.72 + 0.28 · frac(v · TIERS))`.
61    fn crown(&self, off: f64) -> f64 {
62        let off = off.abs();
63        if off >= self.half {
64            return 0.0;
65        }
66        // Scan down from the tip: the first height whose width reaches `off` is the top.
67        const STEPS: usize = 40;
68        for i in 0..=STEPS {
69            let v = 1.0 - i as f64 / STEPS as f64;
70            let frac = (v * TIERS).fract();
71            if self.half * (1.0 - v) * (0.72 + 0.28 * frac) >= off {
72                return self.height * v;
73            }
74        }
75        0.0
76    }
77}
78
79impl Skyline {
80    /// A silhouette `width` pixels wide at `px_per_deg`, seeded from `rng`.
81    pub fn new(rng: &mut impl Rng, width: usize, px_per_deg: f64, terrain: Terrain) -> Self {
82        let px_per_deg = if px_per_deg.is_finite() && px_per_deg > 0.0 {
83            px_per_deg
84        } else {
85            1.0
86        };
87        let span = width as f64 / px_per_deg;
88        // Two octaves of value noise for the ridge, nodes every 9° and 2.5°.
89        let coarse: Vec<f64> = (0..(span / 9.0) as usize + 3)
90            .map(|_| rng.random_range(0.0..1.0))
91            .collect();
92        let fine: Vec<f64> = (0..(span / 2.5) as usize + 3)
93            .map(|_| rng.random_range(0.0..1.0))
94            .collect();
95        let noise = |nodes: &[f64], x: f64| {
96            let i = (x as usize).min(nodes.len() - 2);
97            ease::lerp(nodes[i], nodes[i + 1], ease::smoothstep(x - i as f64))
98        };
99        let mut spires = Vec::new();
100        if let Some((lo, hi)) = terrain.trees {
101            let mut at = rng.random_range(-1.0..0.5);
102            let mut clearing = 0.0;
103            while at < span + 2.0 {
104                if clearing > 0.0 {
105                    clearing -= 1.0;
106                } else if rng.random_bool(terrain.clearing.clamp(0.0, 1.0) / 6.0) {
107                    clearing = f64::from(rng.random_range(2u8..7));
108                } else {
109                    // Heights skew low: many young trees, a few tall ones.
110                    let u: f64 = rng.random_range(0.0..1.0);
111                    let height = lo + (hi - lo) * u * u;
112                    spires.push(Spire {
113                        at,
114                        height,
115                        half: CROWN * height * rng.random_range(0.8..1.25),
116                    });
117                }
118                at += rng.random_range(terrain.gap.0..terrain.gap.1);
119            }
120        }
121        let sub = (0..width * SKY_SUB)
122            .map(|i| {
123                let deg = (i as f64 + 0.5) / (SKY_SUB as f64 * px_per_deg);
124                let ridge = terrain.ridge.0
125                    + terrain.ridge.1
126                        * (0.7 * noise(&coarse, deg / 9.0) + 0.3 * noise(&fine, deg / 2.5));
127                let trees = spires
128                    .iter()
129                    .filter(|s| (s.at - deg).abs() < s.half)
130                    .map(|s| s.crown(deg - s.at))
131                    .fold(0.0, f64::max);
132                // Trees stand on the ridge's lower slopes: part of each trunk is hidden.
133                (px_per_deg * ridge.max(0.6 * terrain.ridge.0 + trees + 0.4 * ridge)) as f32
134            })
135            .collect();
136        Self { sub }
137    }
138
139    /// Silhouette height (px) above the horizon at continuous pixel column `x`.
140    pub fn height_at(&self, x: f64) -> f64 {
141        if self.sub.is_empty() || !x.is_finite() {
142            return 0.0;
143        }
144        let i = ((x * SKY_SUB as f64).max(0.0) as usize).min(self.sub.len() - 1);
145        f64::from(self.sub[i])
146    }
147
148    /// Share of pixel `(x, y)` (spanning rows `[y, y + 1)`) hidden by the land when the
149    /// horizon lies at pixel row `base`: averaged over the column's sub-samples, each
150    /// covering `clamp(y + 1 − top, 0, 1)` of the pixel.
151    pub fn cover(&self, x: i32, y: i32, base: f64) -> f32 {
152        let Ok(x) = usize::try_from(x) else {
153            return 0.0;
154        };
155        let Some(col) = self.sub.get(x * SKY_SUB..(x + 1) * SKY_SUB) else {
156            return 0.0;
157        };
158        let bottom = y as f32 + 1.0;
159        let sum: f32 = col
160            .iter()
161            .map(|&h| (bottom - (base as f32 - h)).clamp(0.0, 1.0))
162            .sum();
163        sum / SKY_SUB as f32
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170    use sciart_core::SplitMix64;
171
172    #[test]
173    fn skyline_cover_is_soft_and_complete_below_the_horizon() {
174        let mut rng = SplitMix64::new(9);
175        let land = Skyline::new(&mut rng, 100, 2.0, FOREST);
176        for x in 0..100 {
177            assert_eq!(land.cover(x, 60, 50.0), 1.0);
178            assert_eq!(land.cover(x, 20, 50.0), 0.0);
179        }
180        // Some pixels are partly covered: the edge is anti-aliased.
181        let partial = (0..100)
182            .flat_map(|x| (30..50).map(move |y| (x, y)))
183            .filter(|&(x, y)| {
184                let c = land.cover(x, y, 50.0);
185                c > 0.05 && c < 0.95
186            })
187            .count();
188        assert!(partial > 30, "{partial}");
189    }
190}