Files
os/crates/sf-ui/src/glass.rs
2026-10-25 14:11:49 +01:00

387 lines
14 KiB
Rust

//! The Liquid Glass layer for a Slint window: install it once, then tell it
//! each frame which panels to draw (usually the `[GlassRect]` arrays your
//! .slint file exports), and set the backdrop (palette, picture, video).
//!
//! ```ignore
//! sf_ui::init()?; // before creating the window
//! let ui = App::new()?;
//! ui.sf_ui_setup(); // from sf_ui::glue!(App)
//! let glass = sf_ui::Glass::install(&ui, |ui, panels| {
//! panels.extend(ui.get_glass().iter());
//! })?;
//! glass.set_palette(sf_ui::Palette::from_hex(["#ffb27a", "#8a3d12", "#120805"]));
//! ui.run()?;
//! ```
use std::cell::RefCell;
use std::rc::Rc;
use std::time::Instant;
use slint::{ComponentHandle, Rgba8Pixel, SharedPixelBuffer};
use crate::render::{Frame, GlassRenderer, ImageDraw, ImageId, Nv12Frame, Panel, Quality, VideoDraw};
use crate::Palette;
/// Time constant of palette and brightness changes (seconds).
const EASE: f32 = 0.35;
/// Crossfade time of pictures and video (seconds).
const FADE: f32 = 0.45;
/// A picture for the backdrop (artwork behind a details page, a hero...).
/// Glass panels refract and frost it like the gradient.
#[derive(Clone)]
pub struct Backdrop {
pixels: SharedPixelBuffer<Rgba8Pixel>,
dim: f32,
fade_left: f32,
fade_bottom: f32,
align: [f32; 2],
sharp: bool,
}
impl Backdrop {
/// Defaults: slightly dimmed, darker towards the left and bottom (room
/// for titles), sharp, cropped around the centre.
pub fn new(pixels: SharedPixelBuffer<Rgba8Pixel>) -> Backdrop {
Backdrop { pixels, dim: 0.12, fade_left: 0.75, fade_bottom: 0.6, align: [0.5, 0.35], sharp: true }
}
/// Darkens the whole picture: 0 = as is, 1 = black.
pub fn dim(mut self, v: f32) -> Self {
self.dim = v.clamp(0.0, 1.0);
self
}
/// Darkening towards the left edge, 0..1.
pub fn fade_left(mut self, v: f32) -> Self {
self.fade_left = v.clamp(0.0, 1.0);
self
}
/// Darkening towards the bottom edge, 0..1.
pub fn fade_bottom(mut self, v: f32) -> Self {
self.fade_bottom = v.clamp(0.0, 1.0);
self
}
/// Which part stays visible when cropped (0..1 per axis, 0.5 = centre).
pub fn align(mut self, x: f32, y: f32) -> Self {
self.align = [x.clamp(0.0, 1.0), y.clamp(0.0, 1.0)];
self
}
/// Soft: only the blurred low-resolution copy shows (a frosted wallpaper).
pub fn soft(mut self) -> Self {
self.sharp = false;
self
}
}
/// Where video frames come from (see `sf_ui::video::Player`, or your own
/// decoder). Called once per rendered frame on the UI thread.
pub trait VideoSource {
/// The newest frame since the last call, if any.
fn take_frame(&self) -> Option<Box<dyn Nv12Frame + '_>>;
}
/// Collects the glass panels of one frame, in logical pixels (the units of
/// your .slint file). Draw order is push order: later panels lie on top.
pub struct Panels {
scale: f32,
out: Vec<Panel>,
}
impl Panels {
/// One panel (logical px).
pub fn push(&mut self, panel: impl Into<Panel>) {
let p = panel.into();
if p.alpha > 0.002 && p.w > 0.0 && p.h > 0.0 {
self.out.push(p.scaled(self.scale));
}
}
/// Many panels, e.g. `panels.extend(ui.get_glass().iter())`.
pub fn extend<T: Into<Panel>>(&mut self, panels: impl IntoIterator<Item = T>) {
for p in panels {
self.push(p);
}
}
}
struct Slot {
backdrop: Backdrop,
id: Option<ImageId>,
alpha: f32,
target: f32,
}
struct State {
palette: [f32; 9],
palette_target: [f32; 9],
brightness: f32,
brightness_target: f32,
images: Vec<Slot>,
free: Vec<ImageId>,
video: Option<Rc<dyn VideoSource>>,
video_alpha: f32,
video_on: bool,
clear_video: bool,
light: f32,
zoom: f32,
last: f32,
quality: Quality,
}
/// Handle to an installed glass layer (cheap to clone).
#[derive(Clone)]
pub struct Glass {
state: Rc<RefCell<State>>,
}
impl Glass {
/// Draws the glass layer under `ui`'s window. `panels` runs before every
/// frame and adds that frame's panels. The backdrop animates, so frames
/// keep coming (vsync-limited).
///
/// Call [`crate::init`] before creating the window: the layer needs the
/// OpenGL (FemtoVG) renderer.
pub fn install<C: ComponentHandle + 'static>(
ui: &C,
mut panels: impl FnMut(&C, &mut Panels) + 'static,
) -> anyhow::Result<Glass> {
let neutral = Palette::NEUTRAL.to_floats();
let state = Rc::new(RefCell::new(State {
palette: neutral,
palette_target: neutral,
brightness: 1.0,
brightness_target: 1.0,
images: Vec::new(),
free: Vec::new(),
video: None,
video_alpha: 0.0,
video_on: false,
clear_video: false,
light: 0.0,
zoom: 1.0,
last: 0.0,
quality: Quality::Full,
}));
let glass = Glass { state: state.clone() };
let snapshot = crate::dev::setup(ui);
let renderer: Rc<RefCell<Option<GlassRenderer>>> = Rc::default();
let start = Instant::now();
let weak = ui.as_weak();
ui.window()
.set_rendering_notifier(move |rs, api| match rs {
slint::RenderingState::RenderingSetup => {
let slint::GraphicsAPI::NativeOpenGL { get_proc_address } = api else {
log::error!("sf-ui: the glass layer needs OpenGL (call sf_ui::init() first)");
return;
};
let gl = unsafe { glow::Context::from_loader_function_cstr(|s| get_proc_address(s)) };
match unsafe { GlassRenderer::new(gl) } {
Ok(r) => *renderer.borrow_mut() = Some(r),
Err(e) => log::error!("sf-ui: glass layer disabled: {e:#}"),
}
}
slint::RenderingState::BeforeRendering => {
let mut guard = renderer.borrow_mut();
let (Some(ui), Some(r)) = (weak.upgrade(), guard.as_mut()) else { return };
let time = start.elapsed().as_secs_f32();
let size = ui.window().size();
let scale = ui.window().scale_factor();
let mut list = Panels { scale, out: Vec::new() };
panels(&ui, &mut list);
let mut st = state.borrow_mut();
let dt = (time - st.last).clamp(0.0, 0.25);
st.last = time;
st.step(dt);
// SAFETY: the rendering notifier runs with the GL context current.
unsafe { st.sync_images(r) };
if std::mem::take(&mut st.clear_video) {
r.clear_video();
}
let draws: Vec<ImageDraw> = st
.images
.iter()
.filter_map(|s| {
Some(ImageDraw {
image: s.id?,
alpha: s.alpha,
dim: s.backdrop.dim,
fade_left: s.backdrop.fade_left,
fade_bottom: s.backdrop.fade_bottom,
align: s.backdrop.align,
sharp: s.backdrop.sharp,
})
})
.collect();
let video = st.video.clone();
let frame_box = video.as_ref().and_then(|v| v.take_frame());
let angle = -2.25 + 0.10 * (time * 0.35).sin() + st.light;
let frame = Frame {
width: size.width,
height: size.height,
scale,
time,
palette: st.palette,
brightness: st.brightness,
light: [angle.cos(), angle.sin()],
zoom: st.zoom,
images: &draws,
video: (st.video_alpha > 0.002 || frame_box.is_some())
.then(|| VideoDraw { frame: frame_box.as_deref(), alpha: st.video_alpha }),
rects: list.out,
quality: st.quality,
};
drop(st);
// SAFETY: as above.
unsafe { r.render(&frame) };
}
slint::RenderingState::AfterRendering => {
let Some(ui) = weak.upgrade() else { return };
if snapshot.due.get() {
if let (Some(path), Some(r)) = (snapshot.path.borrow_mut().take(), renderer.borrow().as_ref()) {
let size = ui.window().size();
// SAFETY: after Slint rendered, context current.
let px = unsafe { r.read_pixels(size.width, size.height) };
match crate::dev::save_png(&path, size.width, size.height, &px) {
Ok(()) => log::info!("sf-ui: snapshot {}", path.display()),
Err(e) => log::error!("sf-ui: snapshot {}: {e:#}", path.display()),
}
let _ = slint::quit_event_loop();
}
}
ui.window().request_redraw();
}
slint::RenderingState::RenderingTeardown => {
if let Some(mut r) = renderer.borrow_mut().take() {
unsafe { r.destroy() };
}
// Textures died with the context: upload again if it comes back.
for s in state.borrow_mut().images.iter_mut() {
s.id = None;
}
}
_ => {}
})
.map_err(|e| anyhow::anyhow!("sf-ui: rendering notifier: {e:?}"))?;
Ok(glass)
}
/// The backdrop gradient's colours; eases over from the current ones.
pub fn set_palette(&self, palette: Palette) {
self.state.borrow_mut().palette_target = palette.to_floats();
}
/// Backdrop brightness, 0..1 (1 = full). Lower it to calm the backdrop
/// behind dense content.
pub fn set_brightness(&self, v: f32) {
self.state.borrow_mut().brightness_target = v.clamp(0.0, 1.0);
}
/// A picture over the gradient (crossfades from the previous one), or
/// `None` to fade back to the gradient.
pub fn set_backdrop(&self, backdrop: Option<Backdrop>) {
let mut st = self.state.borrow_mut();
match backdrop {
Some(b) => {
// Already showing this very picture: keep it.
if let Some(last) = st.images.last_mut() {
if last.backdrop.pixels.as_bytes().as_ptr() == b.pixels.as_bytes().as_ptr() {
last.backdrop = b;
last.target = 1.0;
return;
}
}
st.images.push(Slot { backdrop: b, id: None, alpha: 0.0, target: 1.0 });
}
None => {
for s in st.images.iter_mut() {
s.target = 0.0;
}
}
}
}
/// Video as the backdrop (glass refracts the film), or `None` to fade it
/// out. The source is polled once per frame.
pub fn set_video(&self, source: Option<Rc<dyn VideoSource>>) {
let mut st = self.state.borrow_mut();
st.video_on = source.is_some();
if source.is_some() {
st.video = source;
st.clear_video = true;
}
}
/// Turns the key light (radians, small values like ±0.3), e.g. to follow
/// the focus across the screen.
pub fn set_light(&self, offset: f32) {
self.state.borrow_mut().light = offset;
}
/// How much of the glass effect to draw ([`Quality::Light`] or
/// [`Quality::Flat`] on weaker hardware).
pub fn set_quality(&self, q: Quality) {
self.state.borrow_mut().quality = q;
}
/// Zooms the backdrop gradient (1 = none).
pub fn set_zoom(&self, zoom: f32) {
self.state.borrow_mut().zoom = zoom.max(0.1);
}
}
impl State {
fn step(&mut self, dt: f32) {
let k = 1.0 - (-dt / EASE).exp();
for (c, t) in self.palette.iter_mut().zip(self.palette_target) {
*c += (t - *c) * k;
}
self.brightness += (self.brightness_target - self.brightness) * k;
let fade = dt / FADE;
for s in self.images.iter_mut() {
s.alpha = if s.target > s.alpha { (s.alpha + fade).min(s.target) } else { (s.alpha - fade).max(s.target) };
}
// A picture fully covered by a newer, opaque one is no longer needed;
// faded-out ones neither.
let covered = self.images.iter().rposition(|s| s.alpha >= 0.999).unwrap_or(0);
let mut i = 0;
self.images.retain(|s| {
let keep = i >= covered && !(s.target == 0.0 && s.alpha <= 0.0);
i += 1;
if !keep {
if let Some(id) = s.id {
self.free.push(id);
}
}
keep
});
let target = if self.video_on { 1.0 } else { 0.0 };
self.video_alpha = if target > self.video_alpha {
(self.video_alpha + dt / 0.3).min(1.0)
} else {
(self.video_alpha - dt / 0.3).max(0.0)
};
if !self.video_on && self.video_alpha <= 0.0 {
self.video = None;
}
}
unsafe fn sync_images(&mut self, r: &mut GlassRenderer) {
for id in self.free.drain(..) {
unsafe { r.free_image(id) };
}
for s in self.images.iter_mut().filter(|s| s.id.is_none()) {
let px = &s.backdrop.pixels;
match unsafe { r.upload_image(px.width(), px.height(), px.as_bytes()) } {
Ok(id) => s.id = Some(id),
Err(e) => {
log::warn!("sf-ui: backdrop picture: {e:#}");
s.target = 0.0;
s.alpha = 0.0;
}
}
}
}
}