From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [IPv6:2a0f:8001:1:32::40]) by lore.proxmox.com (Postfix) with ESMTPS id E59A31FF0B4 for ; Fri, 27 Nov 2026 17:14:24 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id 61A562180C; Fri, 27 Nov 2026 17:13:32 +0100 (CET) From: Dominik Csapak To: pdm-devel@lists.proxmox.com Subject: [PATCH yew-widget-toolkit 27/38] widget: charts: world map: allow shading the night Date: Fri, 27 Nov 2026 17:12:24 +0100 Message-ID: <20261127161241.3713494-28-d.csapak@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261127161241.3713494-1-d.csapak@proxmox.com> References: <20261127161241.3713494-1-d.csapak@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-SPAM-LEVEL: Spam detection results: 0 AWL 0.250 Adjusted score from AWL reputation of From: address DMARC_MISSING 0.1 Missing DMARC policy KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment (newer systems) RCVD_IN_DNSWL_MED -2.3 Sender listed at https://www.dnswl.org/, medium trust SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record Message-ID-Hash: F4KU7GEGIUQQRU7ZQX7NFTOREXGHYLJB X-Message-ID-Hash: F4KU7GEGIUQQRU7ZQX7NFTOREXGHYLJB X-MailFrom: d.csapak@proxmox.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; loop; banned-address; emergency; member-moderation; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; digests; suspicious-header X-Mailman-Version: 3.3.10 Precedence: list List-Id: Proxmox Datacenter Manager development discussion List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: with the new 'show_night' option, so one can see at a glance where on the world it currently is night. For that, calculate where the sun is in the zenith from the current time. That includes the season, so that for example the area around the north pole stays lit in summer. From there, the altitude of the sun tells how dark it is at each place: nothing is shaded while the sun is above the horizon, and the full shade is reached when it is 12 degrees below it (the end of the nautical twilight). The shade is drawn as an image with one pixel per two degrees that is stretched over the map. That is cheap to draw and keeps the edge of the night soft. Letting a canvas encode the image would be the obvious way, but browsers that protect against fingerprinting, like Firefox with that setting, return garbage when reading back from a canvas unless the user allows it. So encode it here, as PNG without compression, which does not take much code. A timer updates the image once a minute. The option only sets the default, the user can turn the shade on and off with a button in the panel of the map. With the new 'state_id', that choice is remembered in the browser. How dark the shade is, is defined in the style sheet with the new 'pwt-world-map-night' class. Signed-off-by: Dominik Csapak --- src/widget/charts/alpha_image.rs | 117 ++++++++++++++ src/widget/charts/mod.rs | 2 + src/widget/charts/world_map.rs | 252 ++++++++++++++++++++++++++++++- 3 files changed, 366 insertions(+), 5 deletions(-) create mode 100644 src/widget/charts/alpha_image.rs diff --git a/src/widget/charts/alpha_image.rs b/src/widget/charts/alpha_image.rs new file mode 100644 index 0000000..3c4a9f9 --- /dev/null +++ b/src/widget/charts/alpha_image.rs @@ -0,0 +1,117 @@ +//! A minimal PNG encoder for images that only consist of an alpha channel. + +// the biggest block of uncompressed data in a deflate stream +const MAX_BLOCK_SIZE: usize = 0xffff; + +/// Returns a black image with the given opacity for each pixel as data URL. +/// +/// The pixels are given in rows from top to bottom. The image is encoded here instead of letting +/// a canvas do it, as browsers that protect against fingerprinting don't allow reading back from +/// a canvas without asking the user, and return garbage otherwise. +pub(crate) fn alpha_image_data_url(width: usize, height: usize, alpha: &[u8]) -> String { + // `btoa` takes a string with one character per byte + let png: String = alpha_image_png(width, height, alpha) + .into_iter() + .map(char::from) + .collect(); + // it only fails for characters that are not a byte + let png = gloo_utils::window().btoa(&png).unwrap_or_default(); + format!("data:image/png;base64,{png}") +} + +/// Encodes the image as PNG with a palette and without compression. +fn alpha_image_png(width: usize, height: usize, alpha: &[u8]) -> Vec { + debug_assert!(width > 0 && alpha.len() == width * height); + + let mut png = b"\x89PNG\r\n\x1a\n".to_vec(); + + // 8 bits per pixel that are an index into the palette + let mut header = Vec::new(); + header.extend((width as u32).to_be_bytes()); + header.extend((height as u32).to_be_bytes()); + header.extend([8, 3, 0, 0, 0]); + add_chunk(&mut png, b"IHDR", &header); + + // all colors of the palette are black, they only differ in their opacity + add_chunk(&mut png, b"PLTE", &[0; 256 * 3]); + let opacities: Vec = (0..=255).collect(); + add_chunk(&mut png, b"tRNS", &opacities); + + // each row starts with its filter type, which is none + let mut rows = Vec::with_capacity((width + 1) * height); + for row in alpha.chunks(width) { + rows.push(0); + rows.extend(row); + } + + // a zlib stream with blocks that are stored and not compressed + let mut data = vec![0x78, 0x01]; + let mut blocks = rows.chunks(MAX_BLOCK_SIZE).peekable(); + while let Some(block) = blocks.next() { + data.push(blocks.peek().is_none() as u8); + data.extend((block.len() as u16).to_le_bytes()); + data.extend((!(block.len() as u16)).to_le_bytes()); + data.extend(block); + } + data.extend(adler32(&rows).to_be_bytes()); + add_chunk(&mut png, b"IDAT", &data); + + add_chunk(&mut png, b"IEND", &[]); + png +} + +fn add_chunk(png: &mut Vec, kind: &[u8; 4], data: &[u8]) { + png.extend((data.len() as u32).to_be_bytes()); + let start = png.len(); + png.extend(kind); + png.extend(data); + let checksum = crc32(&png[start..]); + png.extend(checksum.to_be_bytes()); +} + +fn crc32(data: &[u8]) -> u32 { + let mut crc = !0u32; + for &byte in data { + crc ^= byte as u32; + for _ in 0..8 { + crc = if crc & 1 == 1 { + (crc >> 1) ^ 0xedb8_8320 + } else { + crc >> 1 + }; + } + } + !crc +} + +fn adler32(data: &[u8]) -> u32 { + let (mut a, mut b) = (1u32, 0u32); + for &byte in data { + a = (a + byte as u32) % 65521; + b = (b + a) % 65521; + } + (b << 16) | a +} + +#[cfg(test)] +mod test { + use super::{adler32, alpha_image_png, crc32}; + + #[test] + fn test_checksums() { + // the checksum of the chunk that ends every PNG + assert_eq!(crc32(b"IEND"), 0xae42_6082); + assert_eq!(adler32(b"Wikipedia"), 0x11e6_0398); + } + + #[test] + fn test_alpha_image() { + // two rows of three pixels + let png = alpha_image_png(3, 2, &[0, 128, 255, 255, 128, 0]); + // signature, header, palette, opacities, data and end, each chunk with 12 bytes around it + let size: usize = 8 + (12 + 13) + (12 + 768) + (12 + 256) + (12 + 2 + 5 + 8 + 4) + 12; + assert_eq!(png.len(), size); + // the signature and the start of the header with the width and the height + assert!(png.starts_with(b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR\0\0\0\x03\0\0\0\x02")); + } +} diff --git a/src/widget/charts/mod.rs b/src/widget/charts/mod.rs index dd254c2..addfccc 100644 --- a/src/widget/charts/mod.rs +++ b/src/widget/charts/mod.rs @@ -1,5 +1,7 @@ //! Chart components +mod alpha_image; + mod map; pub use map::{ Coordinates, Map, MapConnection, MapPoint, MapPointData, PointsRenderArgs, render_info_default, diff --git a/src/widget/charts/world_map.rs b/src/widget/charts/world_map.rs index 2ca00f9..0996d5d 100644 --- a/src/widget/charts/world_map.rs +++ b/src/widget/charts/world_map.rs @@ -5,12 +5,17 @@ use std::rc::Rc; use derivative::Derivative; use geojson::{Feature, GeoJson, Geometry}; +use gloo_timers::callback::Interval; use yew::prelude::*; use yew::virtual_dom::{VComp, VNode}; use crate::prelude::*; +use crate::props::{IntoStorageLocation, StorageLocation}; +use crate::state::PersistentState; use crate::widget::canvas::{Group, Path}; +use crate::widget::charts::alpha_image::alpha_image_data_url; use crate::widget::charts::{Coordinates, Map, MapConnection, MapPoint, MapPointData}; +use crate::widget::{Button, Tooltip}; use pwt_macros::{builder, widget}; // the constant size of the svg viewport. also use to project lon/lat to svg coordinates @@ -29,6 +34,19 @@ const REGION_SIZE: f64 = WIDTH / 12.0; // the distance between the lines of the graticule in degrees const GRATICULE_STEP: usize = 30; +// The size of the image that shades the night, which has one pixel per two degrees. It is +// stretched over the map, which makes the already soft edge of the night even smoother. It shows +// the world twice, to also cover the space to the left and right of the map in a wide container. +const NIGHT_IMAGE_WIDTH: usize = 360; +const NIGHT_IMAGE_HEIGHT: usize = 90; + +// The sine of how far the sun is below the horizon when it is as dark as it gets on the map, in +// between is twilight. 12 degrees are the end of the nautical twilight. +const NIGHT_SIN_DEPTH: f64 = 0.2079; + +// how often the night moves on in milliseconds, the sun does a quarter of a degree per minute +const NIGHT_UPDATE_INTERVAL: u32 = 60_000; + /// Represents a Location in the world using the geographic coordinate system. #[derive(Clone, Copy, PartialEq)] pub struct Location { @@ -99,6 +117,17 @@ pub struct WorldMap { /// The radius for info points. Forwarded to the inner [Map]. info_point_radius: f64, + #[prop_or_default] + #[builder] + /// Shade the part of the world where it currently is night. + /// + /// The user can change that with a button on the map. + show_night: bool, + + #[prop_or_default] + /// Where to remember what the user changed on the map. + state_id: Option, + // the map is big, and it would be compared for every render of the parent otherwise #[derivative(PartialEq(compare_with = "Rc::ptr_eq"))] map_data: Rc, @@ -111,6 +140,17 @@ impl WorldMap { yew::props!(Self { map_data }) } + /// Builder style method to set the persistent state ID. + pub fn state_id(mut self, state_id: impl IntoStorageLocation) -> Self { + self.set_state_id(state_id); + self + } + + /// Method to set the persistent state ID. + pub fn set_state_id(&mut self, state_id: impl IntoStorageLocation) { + self.state_id = state_id.into_storage_location(); + } + /// Set the points of the map. Converts the List into a list of [MapPoint]. pub fn set_points(&mut self, points: impl Into>>) { self.points = points @@ -127,8 +167,17 @@ impl WorldMap { } } +pub enum Msg { + UpdateNight, + ToggleNight, +} + pub struct WorldMapComp { shapes: Rc>, + // what the user chose with the button, if anything + show_night: Option, + // the image that shades the night as data URL, with the timer that updates it + night: Option<(AttrValue, Interval)>, _phantom_data: PhantomData, } @@ -266,6 +315,73 @@ fn graticule() -> String { path } +/// Where on the world the sun is in the zenith. +struct Sun(Location); + +impl Sun { + /// The position of the sun at the given time in milliseconds since the Unix epoch. + /// + /// Uses the low precision formulas of the Astronomical Almanac, which are far more accurate + /// than what one can see on a map of the world. + fn at(time: f64) -> Self { + // days since 2000-01-01 12:00 UTC + let days = time / 86_400_000.0 - 10_957.5; + + let mean_longitude = (280.460 + 0.985_647_4 * days).to_radians(); + let mean_anomaly = (357.528 + 0.985_600_3 * days).to_radians(); + let ecliptic_longitude = mean_longitude + + (1.915 * mean_anomaly.sin() + 0.020 * (2.0 * mean_anomaly).sin()).to_radians(); + let obliquity = (23.439 - 0.000_000_4 * days).to_radians(); + + let declination = (obliquity.sin() * ecliptic_longitude.sin()).asin(); + let right_ascension = + (obliquity.cos() * ecliptic_longitude.sin()).atan2(ecliptic_longitude.cos()); + // how far the earth has turned, as sidereal time of the prime meridian + let rotation = (280.460_618_37 + 360.985_647_366_29 * days).to_radians(); + + let longitude = (right_ascension - rotation).to_degrees(); + Self(Location::new( + (longitude + 180.0).rem_euclid(360.0) - 180.0, + declination.to_degrees(), + )) + } + + /// How dark it is everywhere on the world, from 0 for daylight to 255 for the night. + /// + /// Returns the rows of the night image from north to south, each from west to east. + fn night_shade(&self) -> Vec { + let (sin_declination, cos_declination) = self.0.latitude.to_radians().sin_cos(); + // of the angle between the meridian of each column and the one of the sun + let cos_hour_angle: Vec = (0..NIGHT_IMAGE_WIDTH) + .map(|column| { + let longitude = (column as f64 + 0.5) * 720.0 / NIGHT_IMAGE_WIDTH as f64 - 360.0; + (longitude - self.0.longitude).to_radians().cos() + }) + .collect(); + + let mut shade = Vec::with_capacity(NIGHT_IMAGE_WIDTH * NIGHT_IMAGE_HEIGHT); + for row in 0..NIGHT_IMAGE_HEIGHT { + let latitude = 90.0 - (row as f64 + 0.5) * 180.0 / NIGHT_IMAGE_HEIGHT as f64; + let (sin_latitude, cos_latitude) = latitude.to_radians().sin_cos(); + for cos_hour_angle in &cos_hour_angle { + // of the altitude of the sun above the horizon + let sin_altitude = sin_latitude * sin_declination + + cos_latitude * cos_declination * cos_hour_angle; + let depth = (-sin_altitude / NIGHT_SIN_DEPTH).clamp(0.0, 1.0); + // ease in and out of the twilight + let depth = depth * depth * (3.0 - 2.0 * depth); + shade.push((depth * 255.0).round() as u8); + } + } + shade + } + + /// Renders the shade of the night as black image and returns it as data URL. + fn night_image(&self) -> AttrValue { + alpha_image_data_url(NIGHT_IMAGE_WIDTH, NIGHT_IMAGE_HEIGHT, &self.night_shade()).into() + } +} + /// The background of a [WorldMap]. /// /// The shapes are big, and a [Map] renders a lot while it is panned and zoomed. Comparing them @@ -275,6 +391,7 @@ fn graticule() -> String { struct WorldMapShapes { #[derivative(PartialEq(compare_with = "Rc::ptr_eq"))] shapes: Rc>, + night: Option, } struct WorldMapShapesComp; @@ -308,9 +425,23 @@ impl Component for WorldMapShapesComp { .into() }); + let night = props.night.clone().map(|night| { + html! { + + } + }); + Group::new() .with_child(Path::new().class("pwt-world-map-graticule").d(graticule())) .children(features) + .with_optional_child(night) .into() } } @@ -321,25 +452,89 @@ impl From for VNode { } } +impl WorldMapComp { + fn show_night(&self, ctx: &Context) -> bool { + self.show_night.unwrap_or(ctx.props().show_night) + } + + // The choice of the user is only kept in the storage, so that all maps with the same state ID + // agree on it. + fn load_show_night(&mut self, ctx: &Context) { + self.show_night = match &ctx.props().state_id { + Some(state_id) => *PersistentState::>::new(state_id.clone()), + None => None, + }; + } + + fn update_night(&mut self, ctx: &Context) { + self.night = if self.show_night(ctx) { + let image = Sun::at(js_sys::Date::now()).night_image(); + let timer = match self.night.take() { + Some((_, timer)) => timer, + None => { + let link = ctx.link().clone(); + Interval::new(NIGHT_UPDATE_INTERVAL, move || { + link.send_message(Msg::UpdateNight) + }) + } + }; + Some((image, timer)) + } else { + None + }; + } +} + impl yew::Component for WorldMapComp { - type Message = (); + type Message = Msg; type Properties = WorldMap; fn create(ctx: &Context) -> Self { - Self { + let mut this = Self { shapes: Rc::new(calculate_shapes(&ctx.props().map_data)), + show_night: None, + night: None, _phantom_data: PhantomData::, + }; + this.load_show_night(ctx); + this.update_night(ctx); + this + } + + fn update(&mut self, ctx: &Context, msg: Self::Message) -> bool { + match msg { + Msg::UpdateNight => self.update_night(ctx), + Msg::ToggleNight => { + let show_night = Some(!self.show_night(ctx)); + self.show_night = show_night; + if let Some(state_id) = &ctx.props().state_id { + PersistentState::>::new(state_id.clone()).update(show_night); + } + self.update_night(ctx); + } } + true } fn view(&self, ctx: &Context) -> Html { let props = ctx.props(); let shapes = Rc::clone(&self.shapes); - - Map::new(WorldMapShapes { shapes }) + let night = self.night.as_ref().map(|(image, _)| image.clone()); + + let show_night = self.show_night(ctx); + let night_button = Tooltip::new( + Button::new_icon("fa fa-moon-o") + .pressed(show_night) + .attribute("aria-pressed", show_night.to_string()) + .on_activate(ctx.link().callback(|_| Msg::ToggleNight)), + ) + .tip(tr!("Show where it is night")); + + Map::new(WorldMapShapes { shapes, night }) .with_std_props(&props.std_props) .listeners(&props.listeners) .class("pwt-world-map") + .tools(vec![night_button.into()]) .width(WIDTH) .height(HEIGHT) .max_zoom_level(props.max_zoom_level) @@ -354,6 +549,10 @@ impl yew::Component for WorldMapComp { if !Rc::ptr_eq(&props.map_data, &old_props.map_data) { self.shapes = Rc::new(calculate_shapes(&props.map_data)); } + if props.show_night != old_props.show_night || props.state_id != old_props.state_id { + self.load_show_night(ctx); + self.update_night(ctx); + } true } } @@ -371,7 +570,7 @@ fn project(location: Location) -> Coordinates { mod test { use geojson::{Geometry, Value}; - use super::FeatureShapes; + use super::{FeatureShapes, NIGHT_IMAGE_HEIGHT, NIGHT_IMAGE_WIDTH, Sun}; // a square with the given corner and side length in degrees fn square(longitude: f64, latitude: f64, size: f64) -> Vec> { @@ -421,4 +620,47 @@ mod test { assert_eq!(lines.len(), 2); assert_eq!(lines[0], europe_path); } + + #[test] + fn test_sun() { + let close = |a: f64, b: f64| (a - b).abs() < 0.2; + + // 2026-06-21 12:00 UTC, the day of the solstice. The sun is a bit late then. + let sun = Sun::at(1_782_043_200_000.0); + assert!(close(sun.0.latitude, 23.44), "{}", sun.0.latitude); + assert!(close(sun.0.longitude, 0.46), "{}", sun.0.longitude); + + // 2026-11-03 12:00 UTC, when the sun is the most ahead of the clock + let sun = Sun::at(1_793_707_200_000.0); + assert!(close(sun.0.latitude, -15.1), "{}", sun.0.latitude); + assert!(close(sun.0.longitude, -4.1), "{}", sun.0.longitude); + + // 2026-03-20 14:46 UTC, the equinox + let sun = Sun::at(1_774_017_960_000.0); + assert!(close(sun.0.latitude, 0.0), "{}", sun.0.latitude); + } + + #[test] + fn test_night_shade() { + // noon at the prime meridian at the solstice + let shade = Sun::at(1_782_043_200_000.0).night_shade(); + assert_eq!(shade.len(), NIGHT_IMAGE_WIDTH * NIGHT_IMAGE_HEIGHT); + // the image starts at 360 degrees west and 90 degrees north, with two degrees per pixel + let at = |longitude: i32, latitude: i32| { + let (column, row) = ((longitude + 360) / 2, (90 - latitude) / 2); + shade[row as usize * NIGHT_IMAGE_WIDTH + column as usize] + }; + + // day where the sun is, and at the north pole all around + assert_eq!(at(0, 23), 0); + assert_eq!(at(179, 89), 0); + // night on the other side, and at the south pole all around + assert_eq!(at(-180, -23), 255); + assert_eq!(at(0, -89), 255); + // twilight where the sun just went down + let twilight = at(95, 0); + assert!(twilight > 0 && twilight < 255, "{twilight}"); + // the same once around the world + assert_eq!(at(95 - 360, 0), twilight); + } } -- 2.47.3