Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@ categories = ["command-line-utilities", "visualization"]
# so excluding them would break the publish verification build.
exclude = [
"demos/",
# dawn and cloudy_day are WIP: reachable by path in a checkout, deliberately not built in, so editing them stays a test: change that cuts no release.
# dawn, cloudy_day and snowfall are WIP: reachable by path in a checkout, deliberately not built in, so editing them stays a test: change that cuts no release.
"scenes/dawn.toml",
"scenes/cloudy_day.toml",
"scenes/snowfall.toml",
"scripts/",
# Bootstraps a binary from GitHub Releases, so it is dead weight to anyone installing from the tarball, and shipping it would make every installer edit cut a release.
"install.sh",
Expand Down
32 changes: 29 additions & 3 deletions benches/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@ use ratatui::layout::Rect;

use celsius::analytic_sky::{self, AnalyticSky};
use celsius::astro;
use celsius::atmosphere::Atmosphere;
use celsius::colorspace::{Oklab, oklab_to_rgb, rgb_u8_to_oklab};
use celsius::lightning::{self, Lightning};
use celsius::noise::Noise;
use celsius::precipitation;
use celsius::snow::{self, FlakeForm, Snowfall};
use celsius::tui::{App, Timeline, draw_frame, write_frame};
use celsius::weather::forecast::Forecast;
use celsius::weather::location::GeoResult;
Expand Down Expand Up @@ -104,14 +106,14 @@ fn bench_render(c: &mut Criterion) {
g.finish();
}

/// `base` with a midday analytic sky attached at crossfade weight `blend`. Turbidity 2.0 is what `turbidity_from_visibility` yields at full visibility.
/// `base` with a midday analytic sky attached at crossfade weight `blend`. Turbidity 2.0 is what `Atmosphere::from_visibility` yields at full visibility.
fn with_analytic(base: &SkyState, blend: f64) -> SkyState {
let mut sky = base.clone();
sky.analytic = Some(AnalyticSky {
sun_alt: 55.0,
sun_az: 180.0,
center_az: 180.0,
turbidity: 2.0,
atmosphere: Atmosphere::from_turbidity(2.0),
blend,
});
sky
Expand Down Expand Up @@ -253,6 +255,22 @@ fn bench_overlay(c: &mut Criterion) {
)
});

// A dendrite is the most expensive form (centre plus four arms) at a heavy-snow count. Unlike the rain pair below, the count is an absolute, so the two sizes measure the per-flake draw against the buffer rather than against a density that grows with it.
let heavy = Snowfall {
form: FlakeForm::Dendrite,
count: 320,
seed: 2749,
drift: 0.02,
opacity: 0.75,
};
g.bench_function("snow_104x50", |b| {
b.iter_batched_ref(
|| base.clone(),
|px| snow::overlay(px, &heavy, 3.0),
BatchSize::SmallInput,
)
});

let stormy = load_scene(scene_path("stormy_afternoon_advancing")).unwrap();
let precip = stormy
.precipitation
Expand All @@ -269,6 +287,14 @@ fn bench_overlay(c: &mut Criterion) {
});

let wide = render(&clear, 320, 100);
g.bench_function("snow_320x100", |b| {
b.iter_batched_ref(
|| wide.clone(),
|px| snow::overlay(px, &heavy, 3.0),
BatchSize::SmallInput,
)
});

g.bench_function("precip_320x100", |b| {
b.iter_batched_ref(
|| wide.clone(),
Expand Down Expand Up @@ -435,7 +461,7 @@ fn bench_micro(c: &mut Criterion) {
sun_alt: 55.0,
sun_az: 180.0,
center_az: 180.0,
turbidity: 2.0,
atmosphere: Atmosphere::from_turbidity(2.0),
blend: 1.0,
});
// A frame's worth of Perez evaluations, which is what a daytime render pays: `sample` runs once per pixel and roughly triples a clear 104x50 frame. Batched for the same reason as `warped_fbm_5200`, a single call being short enough that the reported number was the harness.
Expand Down
2 changes: 1 addition & 1 deletion justfile
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ scenes := "golden_hour_cumulus blue_hour_calm high_noon_clear moonlit_clear_wint

# Vendored in scenes/ but intentionally NOT locked yet: not pretty enough to bless.
# Render with `just render-wip`, and promote a name into `scenes` once it is good.
wip_scenes := "dawn cloudy_day"
wip_scenes := "dawn cloudy_day snowfall"

default: check

Expand Down
43 changes: 43 additions & 0 deletions scenes/snowfall.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# snowfall
# Hamburg, 15 January at 09:48 local; low winter daylight beneath a flat overcast, air at -1 C in near-saturated cloud.
# Visibility about 1 km, which is WMO 73 moderate-to-heavy continuous snow: the haze here is the falling snow itself, not fog, so it is a soft wash rather than the near-total extinction fog.toml carries.
# Heavy snow under a flat overcast deck. The sky during snowfall is a dull medium grey, not bright white; the brightness people picture is the snow on the ground, not the sky. A medium tone is also what lets the near-white flakes show at all (snow is painted around 242,244,248), and it dodges the engine's cloud palette, which only spans warm cream to cool purple: any deck near the hidden sun picks up an off-genre warm cast. So, no cloud layers. A flat cold gradient plus dense falling snow reads as heavy snowfall far better than a textured and warm-tinged deck would.
# The gradient is darker than it looks like it should be, and the contact sheet is why. Flakes cover about a quarter of the frame and every one of them is near white, so they carry a lot of the tone: the first version of this scene measured brighter than cloudy_day and high_noon_clear both, which made a snowstorm the most luminous sky in the library. It sits between them now. Judge this one beside its siblings rather than alone, because on its own a too-bright version still looks like snow.
# The flake form is not decoration and is not free to choose: at -1 C in dense cloud the Nakaya morphology diagram gives sectored plates, so that is what this scene pins. Its own chrome is the check. A scene claiming -1 C and snowing dendrites would be claiming -15 C weather, and dendrites are the flake everyone pictures, which is exactly why it is the wrong one to reach for here.
# If this breaks, it looks like: flakes clumped in the left third of a wide terminal (frame fractions lost, see rules/reference-size.md), or a sky that reads white rather than grey, at which point the flakes vanish into it and the scene is just fog.

[gradient]
stops = [
{ t = 0.00, rgb = [104, 111, 122] }, # cool dull grey zenith
{ t = 0.35, rgb = [119, 126, 136] },
{ t = 0.65, rgb = [136, 142, 150] },
{ t = 0.88, rgb = [148, 153, 159] },
{ t = 1.00, rgb = [155, 159, 164] }, # lighter toward the snowy murk, still grey
]

[sun]
x_frac = 0.50
y_frac = 1.20
radius = 2.0
visible = false

[haze]
# The murk of falling snow, and the one parameter here that was doing nothing at all. It used to pull toward [180, 184, 189], which is *darker* than the gradient's own horizon stop, so raising its strength from 0.45 to 0.85 moved no pixel by more than 5 of 255 and what it did move it made dimmer. The low visibility was written in the chrome and encoded nowhere. Distance in snow washes pale, so the target has to sit above the horizon stop, not below it.
# onset_t, exponent and strength are the documented mapping from docs/literature/README.md at 1 km visibility, where the formula clamps to 0.85. The colour is the deliberate departure: [188, 180, 168] there is warm aerosol haze in daylight, and snow murk is cool and bright.
rgb = [178, 182, 188]
onset_t = 0.10
strength = 0.85
exponent = 1.6

[snowfall]
form = "sectored_plate"
count = 240 # about 1 cm/h through flake_count, which is heavy but still legible
seed = 2749
drift = -0.02 # NE wind at 11 km/h, of which only the across-view component moves anything
opacity = 0.75

[chrome]
header_left = "celsius"
header_right = "hamburg thu 15 jan 09:48"
footer = "-1 C snow wind ne 11 visibility 1 km"
keys = "m map space pause <- -> scrub q quit"
76 changes: 69 additions & 7 deletions src/analytic_sky.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,26 @@
//! Prototype: an analytic daytime sky (Preetham et al. 1999), the closed-form member of the Hosek-Wilkie family. Sky radiance is computed per pixel from the sun's position and an atmospheric turbidity via the Perez function, so the zenith-to-horizon falloff and the sun-side brightening fall out of one physical model instead of hand-tuned palettes. Daytime only: `build_sky` attaches this only when the sun is above the horizon, and `render` falls back to the gradient otherwise (Preetham's zenith formula is undefined once the solar zenith angle passes 90 degrees).
//!
//! Radiance comes out in kcd/m^2 and spans orders of magnitude between a low sun and a high one, so what reaches a terminal is decided by the exposure rather than by the model. It is a partial adaptation, anchored so that a clear noon renders as it always has while dimmer skies stay dimmer; a full adaptation, which is what this had, flattens every sky to one brightness and throws that range away. See `ADAPTATION`.

use std::f64::consts::PI;

use crate::atmosphere::Atmosphere;
use crate::colorspace::Oklab;

/// Where a sky's own mean luminance is placed on the tone curve.
/// The sky every other sky is exposed relative to: a clear noon, sun 55 degrees up at turbidity 2, which is the sky the gain was originally tuned against by eye. Both numbers are measured from that frame rather than recalled, and the pair is what keeps it rendering exactly as it does today.
///
/// Preetham radiance is in kcd/m^2 and spans orders of magnitude between a low sun and a high one, so a fixed gain can only be correct at one solar elevation. It was tuned against a clear noon zenith, which meant every low sun came out under-exposed and muddy, and that is what forced the crossfade to hand twilight back to a hand-tuned palette. Exposure is now derived per sky from a coarse survey of the frame, and this constant is the target that survey is mapped onto. Its value is the old gain times the mean luminance of the sky it was tuned on, so a clear noon still lands where it always did.
const ADAPT_KEY: f64 = 0.045 * 2.35;
/// These were one constant, `0.045 * 2.35`, and that product is what made the exposure a pure auto-exposure. Dividing a frame's own log-average into a fixed target normalises every sky to the same mean lightness, so the one absolute quantity Preetham computes, radiance in kcd/m^2 spanning orders of magnitude between a low sun and a high one, was surveyed and then divided straight back out. The renderer could not draw a dim sky.
///
/// The factors are also why `2.35` was wrong and could stay wrong. Under full adaptation only the product is observable, so neither number alone had to describe anything; a clear noon measures 12.858 here, and 2.35 is a survey of some frame that stopped existing when the projection went rectilinear in v0.5.0 and the view stopped reaching the zenith. Splitting the product is what makes each factor load-bearing enough to be checked.
const REFERENCE_GAIN: f64 = 0.008_225;
const REFERENCE_LUMINANCE: f64 = 12.858;

/// How much of its own brightness a sky is exposed for, from 0 to 1.
///
/// At 1 the exposure follows the sky exactly and this is the old behaviour, byte for byte. At 0 it is the fixed gain that came before that, which under-exposed every low sun into mud. In between, `1 - ADAPTATION` is the fraction of a stop of real brightness difference that survives to the terminal, which is the only quantity this constant controls.
///
/// Photographic tone reproduction calls the same idea incomplete adaptation, and the reason to want it here is not fidelity for its own sake: a sky that cannot be dim cannot be compared with another sky, which is why every assertion about this model had to be phrased as contrast until now.
const ADAPTATION: f64 = 0.7;

/// How many samples across the frame the luminance survey takes, per axis.
const ADAPT_GRID: u32 = 5;
Expand All @@ -18,7 +31,7 @@ pub struct AnalyticSky {
pub sun_alt: f64,
pub sun_az: f64,
pub center_az: f64,
pub turbidity: f64,
pub atmosphere: Atmosphere,
/// Crossfade weight toward the analytic sky, 0..1. Ramps up from 0 at the horizon to 1 a few degrees above it, so the model fades into the palette through twilight instead of popping in at sunrise. render lerps the palette gradient toward `sample()` by this amount.
pub blend: f64,
}
Expand Down Expand Up @@ -115,7 +128,7 @@ fn dir_from_altaz(alt_deg: f64, az_deg: f64, center_az: f64) -> [f64; 3] {
}

pub fn prepare(sky: &AnalyticSky) -> Prepared {
let t = sky.turbidity;
let t = sky.atmosphere.turbidity;
let theta_sun = (90.0 - sky.sun_alt).to_radians();
let lum = lum_coeffs(t);
let cx = cx_coeffs(t);
Expand Down Expand Up @@ -143,7 +156,16 @@ pub fn prepare(sky: &AnalyticSky) -> Prepared {
}

/// Survey the frame's luminance so the tone curve can be placed against the sky actually being drawn rather than against one remembered clear noon. A coarse grid is enough: this decides an exposure, not a pixel, and it runs once per sky rather than once per pixel.
///
/// What it returns is a partial adaptation rather than a normalisation; see `ADAPTATION`.
fn adapted_exposure(sun: &[f64; 3], lum_z: f64, lum: &Coeffs, denom_lum: f64) -> f64 {
let mean = frame_log_average(sun, lum_z, lum, denom_lum);
// e = g * (Lref / Lbar)^p, so the rendered level scales as (Lbar / Lref)^(1 - p) and a brighter sky arrives brighter. At p = 1 this is a plain normalisation, and at Lbar = Lref it is g whatever p is, which is what holds the reference sky still.
REFERENCE_GAIN * (REFERENCE_LUMINANCE / mean).powf(ADAPTATION)
}

/// The luminance this frame reads as, which is the quantity `REFERENCE_LUMINANCE` is a measurement of.
fn frame_log_average(sun: &[f64; 3], lum_z: f64, lum: &Coeffs, denom_lum: f64) -> f64 {
let mut total = 0.0;
for iy in 0..ADAPT_GRID {
for ix in 0..ADAPT_GRID {
Expand All @@ -157,8 +179,7 @@ fn adapted_exposure(sun: &[f64; 3], lum_z: f64, lum: &Coeffs, denom_lum: f64) ->
total += (sample.max(0.0) + 1e-4).ln();
}
}
let mean = (total / f64::from(ADAPT_GRID * ADAPT_GRID)).exp().max(1e-6);
ADAPT_KEY / mean
(total / f64::from(ADAPT_GRID * ADAPT_GRID)).exp().max(1e-6)
}

impl Prepared {
Expand Down Expand Up @@ -206,3 +227,44 @@ fn lin_rgb_to_oklab(lr: f64, lg: f64, lb: f64) -> Oklab {
b: 0.025_904_037_1 * l + 0.782_771_766_2 * m - 0.808_675_766_0 * s,
}
}

#[cfg(test)]
mod tests {
use super::*;

/// `REFERENCE_LUMINANCE` is a measurement of one specific frame, and a frame is only fixed while the projection is. This is the test the previous constant did not have: `2.35` survived the v0.5.0 move from an orthographic view to a rectilinear one that stops short of the zenith, describing a frame that no longer existed, and nothing could tell because full adaptation made only the product of the two factors observable.
#[test]
fn the_reference_sky_still_reads_as_the_reference_luminance() {
let (alt, turbidity) = (55.0f64, 2.0);
let theta_sun = (90.0 - alt).to_radians();
let lum = lum_coeffs(turbidity);
let measured = frame_log_average(
&dir_from_altaz(alt, 180.0, 180.0),
zenith_luminance(turbidity, theta_sun),
&lum,
perez(1.0, theta_sun, &lum),
);
assert!(
(measured / REFERENCE_LUMINANCE - 1.0).abs() < 1e-3,
"a clear noon now reads as {measured:.4}, not the {REFERENCE_LUMINANCE} the exposure is anchored to; re-measure both constants against the current projection rather than adjusting one"
);
}

/// The anchor is the whole of the compatibility claim: whatever the adaptation exponent is set to, the sky the gain was tuned on must come out at that gain.
#[test]
fn the_anchor_holds_at_any_adaptation() {
let (alt, turbidity) = (55.0f64, 2.0);
let theta_sun = (90.0 - alt).to_radians();
let lum = lum_coeffs(turbidity);
let exposure = adapted_exposure(
&dir_from_altaz(alt, 180.0, 180.0),
zenith_luminance(turbidity, theta_sun),
&lum,
perez(1.0, theta_sun, &lum),
);
assert!(
(exposure / REFERENCE_GAIN - 1.0).abs() < 1e-3,
"the reference sky is exposed at {exposure:.6} rather than {REFERENCE_GAIN}"
);
}
}
43 changes: 43 additions & 0 deletions src/atmosphere.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
//! What the air is doing, held once so every sky model reads the same state instead of each deriving its own.
//!
//! Turbidity and horizon haze are one aerosol loading seen two ways, and both were computed from the same reported visibility in two places on two unrelated curves: turbidity ramps across 2 to 24 km while haze switches off entirely above 12 km. At 13 km the analytic sky is told the air is fairly hazy and the haze layer is told there is none. Both curves are unchanged here; what changes is that they now read one value and that disagreement sits in one type rather than split across two functions.
//!
//! `#[non_exhaustive]` is the reason this type exists at all, rather than a precaution. Turbidity lived on `AnalyticSky`, which is the Preetham parameter block and does not survive the move to Hosek-Wilkie; ground albedo is the next axis (Hosek-Wilkie fits it, Preetham has no place to put it) and aerosol species the one after (no model in the Perez family carries it). Each of those would otherwise break every caller writing a struct literal.

/// The atmospheric state one sky is rendered through.
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct Atmosphere {
/// Horizontal visibility in metres, when a forecast reported one. `None` for a sky whose turbidity was chosen directly, which is every sweep the lab renders.
pub visibility_m: Option<f64>,
/// Preetham turbidity: total optical thickness over its molecular part, so 1 is a pure Rayleigh atmosphere and 2 to 3 is a clear day.
pub turbidity: f64,
}

impl Atmosphere {
/// The live path, where everything follows from what the forecast reported.
#[must_use]
pub fn from_visibility(visibility_m: Option<f64>) -> Self {
Self {
visibility_m,
turbidity: turbidity_from_visibility(visibility_m),
}
}

/// The authored path, for sweeping a model across turbidities that no visibility reading has to justify.
#[must_use]
pub fn from_turbidity(turbidity: f64) -> Self {
Self {
visibility_m: None,
turbidity,
}
}
}

// Open-Meteo visibility tops out near 24 km on clear days and falls to a few km in haze/fog. Map clear -> low turbidity (~2), hazy -> high (~9).
/// Map visibility in metres to the turbidity range used by the analytic sky.
#[must_use]
pub fn turbidity_from_visibility(vis_m: Option<f64>) -> f64 {
let vis_km = vis_m.unwrap_or(24_000.0) / 1000.0;

Check warning on line 41 in src/atmosphere.rs

View workflow job for this annotation

GitHub Actions / surviving mutants in the diff

Missed mutant

replace / with * in turbidity_from_visibility

Check warning on line 41 in src/atmosphere.rs

View workflow job for this annotation

GitHub Actions / surviving mutants in the diff

Missed mutant

replace / with % in turbidity_from_visibility
(2.0 + (24.0 - vis_km.clamp(2.0, 24.0)) / 22.0 * 7.0).clamp(2.0, 9.0)

Check warning on line 42 in src/atmosphere.rs

View workflow job for this annotation

GitHub Actions / surviving mutants in the diff

Missed mutant

replace - with + in turbidity_from_visibility

Check warning on line 42 in src/atmosphere.rs

View workflow job for this annotation

GitHub Actions / surviving mutants in the diff

Missed mutant

replace / with * in turbidity_from_visibility

Check warning on line 42 in src/atmosphere.rs

View workflow job for this annotation

GitHub Actions / surviving mutants in the diff

Missed mutant

replace / with % in turbidity_from_visibility

Check warning on line 42 in src/atmosphere.rs

View workflow job for this annotation

GitHub Actions / surviving mutants in the diff

Missed mutant

replace * with / in turbidity_from_visibility

Check warning on line 42 in src/atmosphere.rs

View workflow job for this annotation

GitHub Actions / surviving mutants in the diff

Missed mutant

replace * with + in turbidity_from_visibility

Check warning on line 42 in src/atmosphere.rs

View workflow job for this annotation

GitHub Actions / surviving mutants in the diff

Missed mutant

replace + with * in turbidity_from_visibility

Check warning on line 42 in src/atmosphere.rs

View workflow job for this annotation

GitHub Actions / surviving mutants in the diff

Missed mutant

replace + with - in turbidity_from_visibility

Check warning on line 42 in src/atmosphere.rs

View workflow job for this annotation

GitHub Actions / surviving mutants in the diff

Missed mutant

replace turbidity_from_visibility -> f64 with 1.0
}
4 changes: 4 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,12 @@
//! Two rules explain most of the design. **All compositing happens in Oklab**, converting to sRGB only at the final pixel write, because linear interpolation in Oklab is what keeps a dawn gradient from banding. And **the PRNG is bit-compatible with CPython's `random.Random`**, so a given seed produces identical noise, stars and precipitation on every platform; the golden-image tests depend on that exactness.
//!
//! Time-varying effects deliberately live *outside* [`render()`]. Lightning, meteors and the easter egg composite onto a rendered buffer from an app clock, so a still image never catches a flash mid-strike and the expensive pixel pipeline stays cacheable across frames.
//!
//! Snow is the exception, and the exception has a reason. A still that catches lightning mid-strike is wrong, but a snowfall scene with no flakes in its PNG is not a scene at all, so [`snow::overlay`] is called by `render()` at `t = 0` and by the TUI on its own clock. One function serves both, which is what makes the still an instant the animation actually passes through.

pub mod analytic_sky;
pub mod astro;
pub mod atmosphere;
pub mod colorspace;
pub mod config;
pub mod gradient;
Expand All @@ -27,6 +30,7 @@ pub mod precipitation;
pub mod raster;
pub mod render;
pub mod scene;
pub mod snow;
pub mod stars;
pub mod terminal;
pub mod tui;
Expand Down
Loading
Loading