diff --git a/Cargo.lock b/Cargo.lock index 58eac663..85051bd1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -453,7 +453,7 @@ dependencies = [ [[package]] name = "async-task" version = "4.7.1" -source = "git+https://github.com/zed-industries/async-task.git?rev=015845a19fc31752c02367567d3b8900a406f9da#015845a19fc31752c02367567d3b8900a406f9da" +source = "git+https://github.com/smol-rs/async-task?rev=41fd3359c75e221bd8b187a8ee361aa309c1714c#41fd3359c75e221bd8b187a8ee361aa309c1714c" [[package]] name = "async-trait" @@ -2388,6 +2388,7 @@ dependencies = [ "gpui_util", "image", "itertools 0.14.0", + "js-sys", "log", "naga", "parking_lot", diff --git a/Cargo.toml b/Cargo.toml index 850225ae..d9d9498b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -611,6 +611,7 @@ nonminimal_bool = "allow" [patch.crates-io] async-process = { git = "https://github.com/zed-industries/async-process.git", rev = "0b6d6713570af61806e1e5cb40e0f757cb93fd9d" } -async-task = { git = "https://github.com/zed-industries/async-task.git", rev = "015845a19fc31752c02367567d3b8900a406f9da" } +# Keep the waker identity fix until it is released: https://github.com/smol-rs/async-task/pull/108 +async-task = { git = "https://github.com/smol-rs/async-task", rev = "41fd3359c75e221bd8b187a8ee361aa309c1714c" } calloop = { git = "https://github.com/zed-industries/calloop", rev = "3759371fee14c40066d64777e2a36b6ffcc22590" } khronos-egl = { git = "https://github.com/zed-industries/khronos-egl", rev = "42214b36347b108fd9630ca6254b96dde59e04fe" } diff --git a/crates/gpui/examples/svg_animation.rs b/crates/gpui/examples/svg_animation.rs new file mode 100644 index 00000000..db915065 --- /dev/null +++ b/crates/gpui/examples/svg_animation.rs @@ -0,0 +1,222 @@ +#![cfg_attr(target_family = "wasm", no_main)] + +//! Compares SVGs animated with [`Svg::with_timed_transformation`], which +//! moves them in the already painted scene, against the same SVGs animated by +//! re-rendering with `with_animation`. It shows spinners and pulsing rings. +//! +//! The header counts how many times the view has rendered. With the retained +//! scene the count stays put while the SVGs keep animating; when re-rendering +//! it climbs once per frame. Pass `--rerender` to start in that mode, and +//! `--max-fps ` to cap how often the retained scene is presented. + +#[path = "example_support/fonts.rs"] +mod example_support; + +use std::{cell::Cell, time::Duration}; + +use gpui::{ + Animation, AnimationExt as _, App, Bounds, Context, Easing, TimedTransformation, + Transformation, Window, WindowBounds, WindowOptions, div, ease_out_quint, percentage, + prelude::*, px, rgb, size, svg, +}; +use gpui_platform::application; + +const ARROW_CIRCLE_SVG: &str = concat!( + env!("CARGO_MANIFEST_DIR"), + "/examples/image/arrow_circle.svg" +); + +const RING_SVG: &[u8] = br#""#; + +const SPINNER_COUNT: usize = 100; +const PULSE_COUNT: usize = 100; +const SPIN_PERIOD: Duration = Duration::from_secs(2); +const PULSE_PERIOD: Duration = Duration::from_millis(1750); + +#[derive(Clone, Copy, PartialEq)] +enum Mode { + RetainedScene, + Rerender, +} + +struct SvgAnimationExample { + mode: Mode, + max_fps: Option, + render_count: Cell, +} + +impl SvgAnimationExample { + fn timed(&self, transformation: TimedTransformation) -> TimedTransformation { + match self.max_fps { + Some(max_fps) => transformation.with_max_fps(max_fps), + None => transformation, + } + } + + fn pulse(&self, index: usize) -> impl IntoElement { + let ring = svg().size_4().data(RING_SVG).text_color(rgb(0x16a34a)); + let ring = match self.mode { + Mode::RetainedScene => ring + .with_timed_transformation( + self.timed( + TimedTransformation::new(PULSE_PERIOD) + .from(Transformation::alpha(0.6)) + .to(Transformation::scale(size(1.5, 1.5)).with_alpha(0.)) + .with_scale_easing(Easing::EaseOutQuint), + ), + ) + .into_any_element(), + Mode::Rerender => ring + .with_animation( + ("pulse", index), + Animation::new(PULSE_PERIOD).repeat_synced(), + |svg, delta| { + let scale = 1. + 0.5 * ease_out_quint()(delta); + svg.with_transformation( + Transformation::scale(size(scale, scale)) + .with_alpha(0.6 * (1. - delta)), + ) + }, + ) + .into_any_element(), + }; + div() + .size_6() + .flex() + .items_center() + .justify_center() + .child(div().absolute().size_1p5().rounded_full().bg(rgb(0x16a34a))) + .child(ring) + } + + fn spinner(&self, index: usize) -> impl IntoElement { + let spinner = svg() + .size_6() + .external_path(ARROW_CIRCLE_SVG) + .text_color(rgb(0x3b82f6)); + match self.mode { + Mode::RetainedScene => spinner + .with_timed_transformation(self.timed(TimedTransformation::rotation( + SPIN_PERIOD, + Transformation::default(), + ))) + .into_any_element(), + Mode::Rerender => spinner + .with_animation( + ("spinner", index), + Animation::new(SPIN_PERIOD).repeat_synced(), + |svg, delta| svg.with_transformation(Transformation::rotate(percentage(delta))), + ) + .into_any_element(), + } + } +} + +impl Render for SvgAnimationExample { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + self.render_count.set(self.render_count.get() + 1); + let mode = self.mode; + let mode_label = match mode { + Mode::RetainedScene => "retained scene (with_timed_transformation)", + Mode::Rerender => "re-render (with_animation)", + }; + + div() + .flex() + .flex_col() + .size_full() + .bg(gpui::white()) + .text_color(gpui::black()) + .p_4() + .gap_3() + .child( + div() + .flex() + .flex_row() + .items_center() + .gap_4() + .child( + div() + .id("toggle-mode") + .px_3() + .py_1() + .rounded_md() + .bg(rgb(0xe5e7eb)) + .cursor_pointer() + .child(format!("Mode: {mode_label}")) + .on_click(cx.listener(|this, _, _, cx| { + this.mode = match this.mode { + Mode::RetainedScene => Mode::Rerender, + Mode::Rerender => Mode::RetainedScene, + }; + cx.notify(); + })), + ) + .child(format!("Renders: {}", self.render_count.get())), + ) + .child( + div() + .flex() + .flex_row() + .flex_wrap() + .gap_2() + .children((0..SPINNER_COUNT).map(|index| self.spinner(index))), + ) + .child( + div() + .flex() + .flex_row() + .flex_wrap() + .gap_2() + .children((0..PULSE_COUNT).map(|index| self.pulse(index))), + ) + } +} + +fn run_example() { + application().run(|cx: &mut App| { + if !example_support::load_fonts(cx) { + return; + } + let options = WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds::centered( + None, + size(px(720.), px(480.)), + cx, + ))), + ..Default::default() + }; + cx.open_window(options, |_, cx| { + cx.activate(false); + let mode = if std::env::args().any(|arg| arg == "--rerender") { + Mode::Rerender + } else { + Mode::RetainedScene + }; + let mut arguments = std::env::args(); + let max_fps = arguments + .by_ref() + .find(|argument| argument == "--max-fps") + .and_then(|_| arguments.next()) + .and_then(|max_fps| max_fps.parse().ok()); + cx.new(|_| SvgAnimationExample { + mode, + max_fps, + render_count: Cell::new(0), + }) + }) + .expect("failed to open window"); + }); +} + +#[cfg(not(target_family = "wasm"))] +fn main() { + run_example(); +} + +#[cfg(target_family = "wasm")] +#[wasm_bindgen::prelude::wasm_bindgen(start)] +pub fn start() { + gpui_platform::web_init(); + run_example(); +} diff --git a/crates/gpui/examples/system_notifications.rs b/crates/gpui/examples/system_notifications.rs index faf69191..0deff83d 100644 --- a/crates/gpui/examples/system_notifications.rs +++ b/crates/gpui/examples/system_notifications.rs @@ -63,7 +63,7 @@ impl Render for SystemNotificationExample { ))) .child( button("dismiss", "Dismiss").on_click(cx.listener(|this, _, _, cx| { - cx.dismiss_system_notification(NOTIFICATION_TAG); + cx.dismiss_system_notification(NOTIFICATION_TAG).detach(); this.status = "Dismissed the notification".into(); cx.notify(); })), diff --git a/crates/gpui/src/app.rs b/crates/gpui/src/app.rs index 62ecf2f5..3c78ca5a 100644 --- a/crates/gpui/src/app.rs +++ b/crates/gpui/src/app.rs @@ -2097,8 +2097,11 @@ impl App { /// /// Best-effort: some platforms cannot retract a notification once shown, /// in which case it ages out of the notification center on its own. - pub fn dismiss_system_notification(&self, tag: &str) { - self.platform.dismiss_system_notification(tag); + /// The task completes after the platform calls return, not after any + /// asynchronous work inside the operating system. Dropping it does not + /// cancel dismissal. + pub fn dismiss_system_notification(&self, tag: &str) -> Task<()> { + self.platform.dismiss_system_notification(tag) } /// Registers the handler invoked when the user activates a system diff --git a/crates/gpui/src/app/headless_app_context.rs b/crates/gpui/src/app/headless_app_context.rs index c7f7c913..3eb2ebee 100644 --- a/crates/gpui/src/app/headless_app_context.rs +++ b/crates/gpui/src/app/headless_app_context.rs @@ -13,7 +13,7 @@ use crate::{ Context, Entity, EntityId, ForegroundExecutor, Global, Pixels, PlatformHeadlessRenderer, PlatformTextSystem, Render, Reservation, Size, Task, TestDispatcher, TestPlatform, TextSystem, Window, WindowBounds, WindowHandle, WindowOptions, - app::{GpuiBorrow, GpuiMode}, + app::{GpuiBorrow, GpuiMode, test_context::test_window}, }; use anyhow::Result; use image::RgbaImage; @@ -130,6 +130,15 @@ impl HeadlessAppContext { self.dispatcher.run_until_parked(); } + /// Simulates the window moving to a display with a different scale factor. + pub fn simulate_window_scale_factor_change( + &mut self, + window: AnyWindowHandle, + scale_factor: f32, + ) { + test_window(&self.app, window).simulate_scale_factor_change(scale_factor); + } + /// Advances the simulated clock. pub fn advance_clock(&self, duration: Duration) { self.dispatcher.advance_clock(duration); diff --git a/crates/gpui/src/app/test_context.rs b/crates/gpui/src/app/test_context.rs index beff5ea7..df3cce6f 100644 --- a/crates/gpui/src/app/test_context.rs +++ b/crates/gpui/src/app/test_context.rs @@ -16,6 +16,19 @@ use std::{ cell::RefCell, future::Future, ops::Deref, path::PathBuf, rc::Rc, sync::Arc, time::Duration, }; +pub(crate) fn test_window(app: &AppCell, window: AnyWindowHandle) -> TestWindow { + app.borrow_mut() + .windows + .get_mut(window.id) + .expect("window not found") + .as_deref_mut() + .expect("window is being updated") + .platform_window + .as_test() + .expect("window is not a TestWindow") + .clone() +} + /// A TestAppContext is provided to tests created with `#[gpui::test]`, it provides /// an implementation of `Context` with additional methods that are useful in tests. #[derive(Clone)] @@ -670,17 +683,7 @@ impl TestAppContext { /// Returns the `TestWindow` backing the given handle. pub(crate) fn test_window(&self, window: AnyWindowHandle) -> TestWindow { - self.app - .borrow_mut() - .windows - .get_mut(window.id) - .unwrap() - .as_deref_mut() - .unwrap() - .platform_window - .as_test() - .unwrap() - .clone() + test_window(&self.app, window) } /// Returns a stream of notifications whenever the Entity is updated. @@ -1424,7 +1427,7 @@ mod tests { }] ); - cx.update(|cx| cx.dismiss_system_notification("thread-1")); + cx.update(|cx| cx.dismiss_system_notification("thread-1").detach()); assert!(cx.delivered_system_notifications().is_empty()); assert_eq!(cx.dismissed_system_notifications(), ["thread-1"]); } @@ -1499,7 +1502,7 @@ mod tests { actions: Vec::new(), }); cx.on_system_notification_response(|response, cx| { - cx.dismiss_system_notification(&response.tag); + cx.dismiss_system_notification(&response.tag).detach(); }); }); diff --git a/crates/gpui/src/elements/animation.rs b/crates/gpui/src/elements/animation.rs index 33f7bc19..ddb0b19e 100644 --- a/crates/gpui/src/elements/animation.rs +++ b/crates/gpui/src/elements/animation.rs @@ -511,6 +511,15 @@ mod easing { move |delta| 1.0 - (1.0 - delta).powi(5) } + /// A heartbeat: a strong beat, a weaker one, then a rest. Starts and ends at 0 and peaks at 1. + pub fn heartbeat(delta: f32) -> f32 { + let beat = |center: f32, width: f32, height: f32| { + let x = (delta - center) / width; + height * (-x * x).exp() + }; + beat(0.2, 0.06, 1.0) + beat(0.4, 0.05, 0.58) + } + /// Apply the given easing function, first in the forward direction and then in the reverse direction pub fn bounce(easing: impl Fn(f32) -> f32) -> impl Fn(f32) -> f32 { move |delta| { diff --git a/crates/gpui/src/elements/svg.rs b/crates/gpui/src/elements/svg.rs index e87f0da6..8183abe4 100644 --- a/crates/gpui/src/elements/svg.rs +++ b/crates/gpui/src/elements/svg.rs @@ -1,21 +1,24 @@ use std::{ + f32::consts::TAU, fs, hash::{Hash, Hasher}, path::Path, sync::Arc, + time::Duration, }; use crate::{ App, Asset, Bounds, Element, GlobalElementId, Hitbox, InspectorElementId, InteractiveElement, - Interactivity, LayoutId, Pixels, Point, Radians, SharedString, Size, StyleRefinement, Styled, - TransformationMatrix, Window, point, px, radians, size, + Interactivity, LayoutId, Pixels, Point, Radians, SharedString, Size, SpriteAnimation, + StyleRefinement, Styled, TransformationMatrix, Window, ease_in_out, ease_out_quint, heartbeat, + linear, point, px, quadratic, radians, size, }; use gpui_util::ResultExt; /// An SVG element. pub struct Svg { interactivity: Interactivity, - transformation: Option, + transformation: Option, path: Option, external_path: Option, data: Option>, @@ -64,6 +67,20 @@ impl Svg { /// Transform the SVG element with the given transformation. /// Note that this won't effect the hitbox or layout of the element, only the rendering. pub fn with_transformation(mut self, transformation: Transformation) -> Self { + self.transformation = Some(transformation.into()); + self + } + + /// Continuously animate the SVG between two transformations, phase-locked to the + /// app's shared animation clock like [`crate::Animation::repeat_synced`]. + /// + /// The SVG is painted once. On later frames the window moves it in the scene it + /// already has and presents that again, instead of re-rendering this view. + /// + /// This replaces [`Self::with_transformation`], and like it doesn't affect layout + /// or hit testing. The SVG is still clipped and ordered by the bounds of its + /// starting transformation, so keep its motion close to them. + pub fn with_timed_transformation(mut self, transformation: TimedTransformation) -> Self { self.transformation = Some(transformation); self } @@ -138,23 +155,35 @@ impl Element for Svg { window, cx, |style, window, cx| { - let transformation = self + let center = bounds.center(); + let scale_factor = window.scale_factor(); + let animation = self .transformation - .as_ref() - .map(|transformation| { - transformation.into_matrix(bounds.center(), window.scale_factor()) - }) + .filter(|timed| timed.is_animated() && !cx.reduce_motion()) + .map(|timed| SpriteAnimation::new(timed, center, scale_factor)); + // Without an animation, such as with reduced motion, the SVG is + // drawn at its starting transformation. + let pose = self.transformation.map(|timed| timed.from); + let transformation = pose + .map(|pose| pose.into_matrix(center, scale_factor)) .unwrap_or_default(); + // The scene applies an animated sprite's alpha before each present, + // on top of the color it is inserted with. + let alpha = match animation { + Some(_) => 1., + None => pose.map_or(1., |pose| pose.alpha_factor()), + }; if let Some((data, path)) = self.data.as_ref().zip(self.data_path.as_ref()) { if let Some(color) = style.text.color { window - .paint_svg( + .paint_animated_svg( bounds, path.clone(), Some(&**data), transformation, - color, + animation, + color.opacity(alpha), cx, ) .log_err(); @@ -170,18 +199,27 @@ impl Element for Svg { }; window - .paint_svg( + .paint_animated_svg( bounds, path.clone(), Some(&bytes), transformation, - color, + animation, + color.opacity(alpha), cx, ) .log_err(); } else if let Some((path, color)) = self.path.as_ref().zip(style.text.color) { window - .paint_svg(bounds, path.clone(), None, transformation, color, cx) + .paint_animated_svg( + bounds, + path.clone(), + None, + transformation, + animation, + color.opacity(alpha), + cx, + ) .log_err(); } }, @@ -207,6 +245,7 @@ pub struct Transformation { scale: Size, translate: Point, rotate: Radians, + alpha: f32, } impl Default for Transformation { @@ -215,6 +254,7 @@ impl Default for Transformation { scale: size(1.0, 1.0), translate: point(px(0.0), px(0.0)), rotate: radians(0.0), + alpha: 1.0, } } } @@ -224,17 +264,15 @@ impl Transformation { pub fn scale(scale: Size) -> Self { Self { scale, - translate: point(px(0.0), px(0.0)), - rotate: radians(0.0), + ..Self::default() } } /// Create a new Transformation with the specified translation. pub fn translate(translate: Point) -> Self { Self { - scale: size(1.0, 1.0), translate, - rotate: radians(0.0), + ..Self::default() } } @@ -242,12 +280,30 @@ impl Transformation { pub fn rotate(rotate: impl Into) -> Self { let rotate = rotate.into(); Self { - scale: size(1.0, 1.0), - translate: point(px(0.0), px(0.0)), rotate, + ..Self::default() + } + } + + /// Create a new Transformation that multiplies the SVG's alpha by `alpha`. + pub fn alpha(alpha: f32) -> Self { + Self { + alpha, + ..Self::default() } } + /// Update the alpha factor of this transformation. Unlike an element's + /// opacity, this only applies to the SVG itself. + pub fn with_alpha(mut self, alpha: f32) -> Self { + self.alpha = alpha; + self + } + + pub(crate) fn alpha_factor(&self) -> f32 { + self.alpha + } + /// Update the scaling factor of this transformation. pub fn with_scaling(mut self, scale: Size) -> Self { self.scale = scale; @@ -266,7 +322,11 @@ impl Transformation { self } - fn into_matrix(self, center: Point, scale_factor: f32) -> TransformationMatrix { + pub(crate) fn into_matrix( + self, + center: Point, + scale_factor: f32, + ) -> TransformationMatrix { //Note: if you read this as a sequence of matrix multiplications, start from the bottom TransformationMatrix::unit() .translate(center.scale(scale_factor) + self.translate.scale(scale_factor)) @@ -276,6 +336,201 @@ impl Transformation { } } +/// How a value's rate of change varies over one pass of a [`TimedTransformation`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Easing { + /// A constant rate. + #[default] + Linear, + /// Starts slowly and accelerates. + Quadratic, + /// Starts and ends slowly, and speeds up in the middle. + EaseInOut, + /// Starts quickly and decelerates to a stop. + EaseOutQuint, + /// Two quick beats, a strong one then a weaker one, followed by a rest. + /// Unlike the other easings it ends where it started, so the value + /// reaches `to` at the first beat and is back at `from` by the end. + Heartbeat, +} + +impl Easing { + fn apply(self, delta: f32) -> f32 { + match self { + Easing::Linear => linear(delta), + Easing::Quadratic => quadratic(delta), + Easing::EaseInOut => ease_in_out(delta), + Easing::EaseOutQuint => ease_out_quint()(delta), + Easing::Heartbeat => heartbeat(delta), + } + } +} + +/// A [`Transformation`] that repeatedly moves from one pose to another over a +/// period, for [`Svg::with_timed_transformation`]. +/// +/// Each value of the transformation has its own [`Easing`], so for example an +/// SVG can grow quickly at first while fading at a constant rate. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct TimedTransformation { + period: Duration, + from: Transformation, + to: Transformation, + scale_easing: Easing, + translation_easing: Easing, + rotation_easing: Easing, + alpha_easing: Easing, + alternate: bool, + min_frame_interval: Option, +} + +impl TimedTransformation { + /// Create a timed transformation that repeats every `period`. It animates + /// nothing until [`Self::from`] and [`Self::to`] differ. + pub fn new(period: Duration) -> Self { + Self { + period, + from: Transformation::default(), + to: Transformation::default(), + scale_easing: Easing::Linear, + translation_easing: Easing::Linear, + rotation_easing: Easing::Linear, + alpha_easing: Easing::Linear, + alternate: false, + min_frame_interval: None, + } + } + + /// Create a timed transformation that turns `from` clockwise, one full + /// turn per `period`. + pub fn rotation(period: Duration, from: Transformation) -> Self { + Self::new(period) + .from(from) + .to(from.with_rotation(radians(from.rotate.0 + TAU))) + } + + fn is_animated(&self) -> bool { + !self.period.is_zero() && self.from != self.to + } + + /// Set the transformation at the start of each period. + pub fn from(mut self, transformation: Transformation) -> Self { + self.from = transformation; + self + } + + /// Set the transformation reached at the end of each period. + pub fn to(mut self, transformation: Transformation) -> Self { + self.to = transformation; + self + } + + /// Set the easing of every value. + pub fn with_easing(mut self, easing: Easing) -> Self { + self.scale_easing = easing; + self.translation_easing = easing; + self.rotation_easing = easing; + self.alpha_easing = easing; + self + } + + /// Set the easing of the scale. + pub fn with_scale_easing(mut self, easing: Easing) -> Self { + self.scale_easing = easing; + self + } + + /// Set the easing of the translation. + pub fn with_translation_easing(mut self, easing: Easing) -> Self { + self.translation_easing = easing; + self + } + + /// Set the easing of the rotation. + pub fn with_rotation_easing(mut self, easing: Easing) -> Self { + self.rotation_easing = easing; + self + } + + /// Set the easing of the alpha. + pub fn with_alpha_easing(mut self, easing: Easing) -> Self { + self.alpha_easing = easing; + self + } + + /// Move from the start to the end and back again within each period, + /// instead of jumping back to the start. + pub fn alternate(mut self) -> Self { + self.alternate = true; + self + } + + /// Present at most `max_fps` frames per second while nothing but timed + /// transformations needs a frame. The least restrictive limit in a window + /// wins. Values that are not finite and positive are ignored. + pub fn with_max_fps(mut self, max_fps: f32) -> Self { + if max_fps.is_finite() && max_fps > 0.0 { + self.min_frame_interval = Some(Duration::from_secs_f64(1.0 / max_fps as f64)); + } + self + } + + pub(crate) fn min_frame_interval(&self) -> Option { + self.min_frame_interval + } + + /// The transformation `elapsed` time after the animation clock started. + pub(crate) fn at(&self, elapsed: Duration) -> Transformation { + let period_nanos = self.period.as_nanos(); + if period_nanos == 0 { + return self.from; + } + let mut delta = Duration::from_nanos((elapsed.as_nanos() % period_nanos) as u64) + .as_secs_f32() + / self.period.as_secs_f32(); + if self.alternate { + delta = 1.0 - (2.0 * delta - 1.0).abs(); + } + + let interpolate = + |from: f32, to: f32, easing: Easing| from + (to - from) * easing.apply(delta); + let (from, to) = (self.from, self.to); + Transformation { + scale: size( + interpolate(from.scale.width, to.scale.width, self.scale_easing), + interpolate(from.scale.height, to.scale.height, self.scale_easing), + ), + translate: point( + px(interpolate( + from.translate.x.0, + to.translate.x.0, + self.translation_easing, + )), + px(interpolate( + from.translate.y.0, + to.translate.y.0, + self.translation_easing, + )), + ), + rotate: radians(interpolate( + from.rotate.0, + to.rotate.0, + self.rotation_easing, + )), + alpha: interpolate(from.alpha, to.alpha, self.alpha_easing), + } + } +} + +impl From for TimedTransformation { + /// A timed transformation that stays at `transformation`. + fn from(transformation: Transformation) -> Self { + Self::new(Duration::ZERO) + .from(transformation) + .to(transformation) + } +} + enum SvgAsset {} impl Asset for SvgAsset { @@ -293,3 +548,182 @@ impl Asset for SvgAsset { } } } + +#[cfg(test)] +mod tests { + use std::{cell::Cell, f32::consts::FRAC_PI_2, rc::Rc, time::Duration}; + + use crate::{ + Context, Easing, IntoElement, Render, SpriteAnimationId, Styled, TestAppContext, + TimedTransformation, Transformation, VisualTestContext, Window, div, prelude::*, px, red, + size, svg, + }; + + const SQUARE_SVG: &[u8] = + br#""#; + + struct AnimatedSvgView { + transformation: TimedTransformation, + renders: Rc>, + } + + impl Render for AnimatedSvgView { + fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { + self.renders.set(self.renders.get() + 1); + div().child( + svg() + .data(SQUARE_SVG) + .size(px(16.)) + .text_color(red()) + .with_timed_transformation(self.transformation), + ) + } + } + + struct Pose { + rotation_scale: [[f32; 2]; 2], + center_offset: [f32; 2], + alpha: f32, + } + + /// Opens a window showing `transformation` and returns a function that + /// delivers a frame `advance` later and reports the animated sprite's pose, + /// along with the number of times the view has rendered. + fn animate( + transformation: TimedTransformation, + cx: &mut TestAppContext, + ) -> (impl FnMut(Duration) -> Pose, Rc>) { + let renders = Rc::new(Cell::new(0)); + let (_, cx) = cx.add_window_view({ + let renders = renders.clone(); + move |_, _| AnimatedSvgView { + transformation, + renders, + } + }); + cx.run_until_parked(); + let cx: &mut VisualTestContext = cx; + let pose_after = move |advance: Duration| { + cx.executor().advance_clock(advance); + cx.update(|window, cx| { + window.simulate_next_frame(cx); + window.advance_scene_animations(cx); + let sprite = window + .rendered_frame + .scene + .monochrome_sprites + .iter() + .find(|sprite| sprite.animation != SpriteAnimationId::NONE) + .expect("the SVG should be painted as an animated sprite"); + let center = sprite.bounds.center(); + let [[a, b], [c, d]] = sprite.transformation.rotation_scale; + let [x, y] = sprite.transformation.translation; + Pose { + rotation_scale: sprite.transformation.rotation_scale, + center_offset: [ + a * center.x.0 + b * center.y.0 + x - center.x.0, + c * center.x.0 + d * center.y.0 + y - center.y.0, + ], + alpha: sprite.color.a, + } + }) + }; + (pose_after, renders) + } + + #[crate::test] + fn test_rotation_advances_without_rerendering(cx: &mut TestAppContext) { + let (mut pose_after, renders) = animate( + TimedTransformation::rotation(Duration::from_secs(1), Transformation::default()), + cx, + ); + let renders_before_frames = renders.get(); + + for quarter in 0..4 { + let pose = pose_after(if quarter == 0 { + Duration::ZERO + } else { + Duration::from_millis(250) + }); + let (sin, cos) = (quarter as f32 * FRAC_PI_2).sin_cos(); + let expected = [[cos, -sin], [sin, cos]]; + for (actual, expected) in pose + .rotation_scale + .as_flattened() + .iter() + .zip(expected.as_flattened()) + { + assert!((actual - expected).abs() < 1e-5, "quarter {quarter}"); + } + assert!(pose.center_offset.iter().all(|offset| offset.abs() < 1e-3)); + } + assert_eq!(renders.get(), renders_before_frames); + } + + #[crate::test] + fn test_timed_transformation_eases_each_value_separately(cx: &mut TestAppContext) { + let (mut pose_after, renders) = animate( + TimedTransformation::new(Duration::from_secs(1)) + .from(Transformation::alpha(0.4)) + .to(Transformation::scale(size(1.5, 1.5)).with_alpha(0.)) + .with_scale_easing(Easing::EaseOutQuint), + cx, + ); + let renders_before_frames = renders.get(); + + let pose = pose_after(Duration::ZERO); + assert!((pose.rotation_scale[0][0] - 1.).abs() < 1e-5); + assert!((pose.alpha - 0.4).abs() < 1e-5); + + // Halfway through, the scale has eased most of the way out while the + // alpha has faded exactly half. + let pose = pose_after(Duration::from_millis(500)); + assert!((pose.rotation_scale[0][0] - (1. + 0.5 * (1. - 0.5f32.powi(5)))).abs() < 1e-5); + assert!((pose.alpha - 0.2).abs() < 1e-5); + assert_eq!(renders.get(), renders_before_frames); + } + + #[crate::test] + fn test_heartbeat_returns_to_its_start(cx: &mut TestAppContext) { + let (mut pose_after, _) = animate( + TimedTransformation::new(Duration::from_secs(1)) + .to(Transformation::scale(size(1.12, 1.12))) + .with_scale_easing(Easing::Heartbeat), + cx, + ); + + assert!((pose_after(Duration::ZERO).rotation_scale[0][0] - 1.).abs() < 1e-3); + assert!((pose_after(Duration::from_millis(200)).rotation_scale[0][0] - 1.12).abs() < 1e-3); + // Each call advances the clock further, to 400ms and then 999ms. + let second_beat = pose_after(Duration::from_millis(200)).rotation_scale[0][0]; + assert!(second_beat > 1.05 && second_beat < 1.09); + assert!((pose_after(Duration::from_millis(599)).rotation_scale[0][0] - 1.).abs() < 1e-3); + } + + #[crate::test] + fn test_scene_presents_as_often_as_its_least_capped_animation(cx: &mut TestAppContext) { + let spin = TimedTransformation::rotation(Duration::from_secs(1), Transformation::default()); + let (_, cx) = cx.add_window_view(move |_, _| CappedView { spin }); + cx.run_until_parked(); + cx.update(|window, _| { + assert_eq!( + window.rendered_frame.scene.animation_frame_interval(), + Some(Duration::from_millis(50)) + ); + }); + } + + struct CappedView { + spin: TimedTransformation, + } + + impl Render for CappedView { + fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { + let icon = || svg().data(SQUARE_SVG).size(px(16.)).text_color(red()); + div() + .child(icon().with_timed_transformation(self.spin.with_max_fps(10.))) + .child(icon().with_timed_transformation(self.spin.with_max_fps(20.))) + .child(icon().with_transformation(Transformation::alpha(0.5))) + } + } +} diff --git a/crates/gpui/src/geometry.rs b/crates/gpui/src/geometry.rs index 899db1b3..df59ce8c 100644 --- a/crates/gpui/src/geometry.rs +++ b/crates/gpui/src/geometry.rs @@ -3166,7 +3166,7 @@ impl From for DevicePixels { /// a single logical pixel may correspond to multiple physical pixels. By using `ScaledPixels`, /// dimensions and positions can be specified in a way that scales appropriately across different /// display resolutions. -#[derive(Clone, Copy, Default, Add, AddAssign, Sub, SubAssign, Div, DivAssign, PartialEq)] +#[derive(Clone, Copy, Default, Add, AddAssign, Sub, SubAssign, Neg, Div, DivAssign, PartialEq)] #[repr(transparent)] pub struct ScaledPixels(pub f32); @@ -3320,6 +3320,18 @@ impl MulAssign for ScaledPixels { } } +impl std::iter::Sum for ScaledPixels { + fn sum>(iter: I) -> Self { + iter.fold(Self::default(), |a, b| a + b) + } +} + +impl<'a> std::iter::Sum<&'a ScaledPixels> for ScaledPixels { + fn sum>(iter: I) -> Self { + iter.fold(Self::default(), |a, b| a + *b) + } +} + /// Represents a length in rems, a unit based on the font-size of the window, which can be assigned with [`Window::set_rem_size`][set_rem_size]. /// /// Rems are used for defining lengths that are scalable and consistent across different UI elements. @@ -3804,7 +3816,7 @@ pub const fn relative(fraction: f32) -> DefiniteLength { /// Returns the Golden Ratio, i.e. `~(1.0 + sqrt(5.0)) / 2.0`. pub const fn phi() -> DefiniteLength { - relative(1.618_034) + relative(std::f32::consts::GOLDEN_RATIO) } /// Constructs a `Rems` value representing a length in rems. diff --git a/crates/gpui/src/keymap.rs b/crates/gpui/src/keymap.rs index 6283fe6b..a7a32116 100644 --- a/crates/gpui/src/keymap.rs +++ b/crates/gpui/src/keymap.rs @@ -199,10 +199,10 @@ impl Keymap { let mut pending_bindings = SmallVec::<[(BindingIndex, &KeyBinding); 1]>::new(); for (ix, binding) in keymap_bindings { - let Some(depth) = self.binding_enabled(binding, context_stack) else { + let Some(pending) = binding.match_keystrokes(input) else { continue; }; - let Some(pending) = binding.match_keystrokes(input) else { + let Some(depth) = self.binding_enabled(binding, context_stack) else { continue; }; diff --git a/crates/gpui/src/platform.rs b/crates/gpui/src/platform.rs index ba20bdcd..be3426e9 100644 --- a/crates/gpui/src/platform.rs +++ b/crates/gpui/src/platform.rs @@ -579,8 +579,12 @@ pub trait Platform: 'static { /// /// Best-effort: some platforms cannot retract a notification once shown, /// in which case it ages out of the notification center on its own. - fn dismiss_system_notification(&self, tag: &str) { + /// The task completes after the platform calls return, not after any + /// asynchronous work inside the operating system. Dropping it does not + /// cancel dismissal. + fn dismiss_system_notification(&self, tag: &str) -> Task<()> { _ = tag; + Task::ready(()) } /// Registers the callback invoked when the user activates a system diff --git a/crates/gpui/src/platform/test/platform.rs b/crates/gpui/src/platform/test/platform.rs index 7ea86b55..cd1a60be 100644 --- a/crates/gpui/src/platform/test/platform.rs +++ b/crates/gpui/src/platform/test/platform.rs @@ -1,16 +1,14 @@ -#[cfg(any(test, feature = "test-support"))] -use crate::NoopTextSystem; -#[cfg(any(test, feature = "test-support"))] -use crate::PathPromptOptions; use crate::{ ActivityGuard, AnyWindowHandle, AppLifecyclePhase, BackgroundExecutor, ClipboardItem, - CursorStyle, DevicePixels, DisplayId, DummyKeyboardMapper, ForegroundExecutor, Keymap, - OwnedMenu, Platform, PlatformDisplay, PlatformHeadlessRenderer, PlatformKeyboardLayout, + CursorStyle, DevicePixels, DummyKeyboardMapper, ForegroundExecutor, Keymap, OwnedMenu, + Platform, PlatformDisplay, PlatformHeadlessRenderer, PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTextSystem, PromptButton, ScreenCaptureFrame, ScreenCaptureSource, ScreenCaptureStream, SharedString, SourceMetadata, SystemNotification, SystemNotificationResponse, Task, TestDisplay, TestWindow, ThermalState, WindowAppearance, WindowParams, size, }; +#[cfg(any(test, feature = "test-support"))] +use crate::{DisplayId, NoopTextSystem, PathPromptOptions}; use anyhow::Result; #[cfg(any(test, feature = "test-support"))] use collections::VecDeque; @@ -735,7 +733,7 @@ impl Platform for TestPlatform { system_notifications.shown.push(notification); } - fn dismiss_system_notification(&self, tag: &str) { + fn dismiss_system_notification(&self, tag: &str) -> Task<()> { let mut system_notifications = self.system_notifications.borrow_mut(); system_notifications .delivered @@ -743,6 +741,7 @@ impl Platform for TestPlatform { system_notifications .dismissed .push(SharedString::from(tag.to_string())); + Task::ready(()) } fn on_system_notification_response( diff --git a/crates/gpui/src/profiler.rs b/crates/gpui/src/profiler.rs index d78ccb9d..18e639a3 100644 --- a/crates/gpui/src/profiler.rs +++ b/crates/gpui/src/profiler.rs @@ -741,7 +741,7 @@ pub(crate) struct TraceGuard; #[cfg(any(feature = "bench-support", all(test, feature = "profiler")))] pub(crate) fn trace_scope() -> TraceGuard { - let incremented = TRACE_STATE.fetch_update(Ordering::AcqRel, Ordering::Acquire, |state| { + let incremented = TRACE_STATE.try_update(Ordering::AcqRel, Ordering::Acquire, |state| { (state & TRACE_SCOPE_COUNT_MASK < TRACE_SCOPE_COUNT_MASK).then_some(state + 1) }); assert!(incremented.is_ok(), "too many active profiler trace scopes"); @@ -751,10 +751,9 @@ pub(crate) fn trace_scope() -> TraceGuard { #[cfg(any(feature = "bench-support", all(test, feature = "profiler")))] impl Drop for TraceGuard { fn drop(&mut self) { - let previous_state = - TRACE_STATE.fetch_update(Ordering::AcqRel, Ordering::Acquire, |state| { - (state & TRACE_SCOPE_COUNT_MASK > 0).then_some(state - 1) - }); + let previous_state = TRACE_STATE.try_update(Ordering::AcqRel, Ordering::Acquire, |state| { + (state & TRACE_SCOPE_COUNT_MASK > 0).then_some(state - 1) + }); match previous_state { Ok(1) => clear_trace_buffers(), Ok(_) => {} diff --git a/crates/gpui/src/profiler/journal.rs b/crates/gpui/src/profiler/journal.rs index 28c66b6e..4c810f86 100644 --- a/crates/gpui/src/profiler/journal.rs +++ b/crates/gpui/src/profiler/journal.rs @@ -167,6 +167,8 @@ pub enum FrameSkipReason { ThermalFrameRateLimit, /// Low power mode deferred drawing. LowPowerFrameRateLimit, + /// A scene animation's frame rate cap deferred presenting. + AnimationFrameRateLimit, } /// A completed frame request that returned without drawing a new frame. @@ -442,7 +444,7 @@ impl ForegroundRunnableCounter { fn finished(&self) { let _ = self .0 - .fetch_update(Ordering::AcqRel, Ordering::Acquire, |count| { + .try_update(Ordering::AcqRel, Ordering::Acquire, |count| { count.checked_sub(1) }); } diff --git a/crates/gpui/src/scene.rs b/crates/gpui/src/scene.rs index 87b75a75..e25d4610 100644 --- a/crates/gpui/src/scene.rs +++ b/crates/gpui/src/scene.rs @@ -6,12 +6,14 @@ use serde::{Deserialize, Serialize}; use crate::{ AtlasTextureId, AtlasTile, Background, Bounds, ContentMask, Corners, DevicePixels, Edges, Hsla, - Path, PathTiles, Pixels, Point, Radians, ScaledPixels, ShaderId, Size, bounds_tree::BoundsTree, - point, + Path, PathTiles, Pixels, Point, Radians, ScaledPixels, ShaderId, Size, TimedTransformation, + bounds_tree::BoundsTree, point, }; use collections::FxHashMap; use smallvec::SmallVec; -use std::{collections::VecDeque, fmt::Debug, iter::Peekable, ops::Range, rc::Rc, slice}; +use std::{ + collections::VecDeque, fmt::Debug, iter::Peekable, ops::Range, rc::Rc, slice, time::Duration, +}; #[expect(missing_docs)] pub type DrawOrder = u32; @@ -135,6 +137,7 @@ pub struct Scene { /// so a backdrop blur near those edges reads what lies there instead of nothing. The /// renderer draws the frame this much larger and shows only the window's part of it. pub overscan: Size, + animations: Vec, } #[expect(missing_docs)] @@ -161,6 +164,76 @@ impl Scene { self.polychrome_sprites.clear(); self.surfaces.clear(); self.overscan = Size::default(); + self.animations.clear(); + } + + /// Inserts a sprite that [`Self::advance_animations`] keeps moving. The + /// sprite's color is taken as its color before the animation's alpha. + pub(crate) fn insert_animated_sprite( + &mut self, + mut sprite: MonochromeSprite, + mut animation: SpriteAnimation, + ) { + sprite.animation = SpriteAnimationId(self.animations.len() as u32); + animation.base_color = sprite.color; + if self.try_insert_primitive(sprite.into()) { + self.animations.push(animation); + } + } + + /// Inserts a sprite replayed from a scene whose history matched, with the order it was drawn + /// at there, as [`Self::insert_animated_sprite`] does. + fn keep_animated_sprite( + &mut self, + mut sprite: MonochromeSprite, + mut animation: SpriteAnimation, + ) { + sprite.animation = SpriteAnimationId(self.animations.len() as u32); + animation.base_color = sprite.color; + self.keep_primitive(sprite.into()); + self.animations.push(animation); + } + + /// The sprite and its animation when `primitive` is a sprite this scene animates. Animation + /// ids index the scene they were inserted into, so a replay into another scene inserts the + /// pair again rather than the primitive alone. + fn animated_sprite( + &self, + primitive: &Primitive, + ) -> Option<(MonochromeSprite, SpriteAnimation)> { + let Primitive::MonochromeSprite(sprite) = primitive else { + return None; + }; + let animation = self.animations.get(sprite.animation.0 as usize)?; + Some((*sprite, *animation)) + } + + /// How long the window may wait between presents of this scene while only + /// its animations need a frame: `None` when nothing in it animates, and + /// zero when an animation wants every frame. + pub(crate) fn animation_frame_interval(&self) -> Option { + self.animations + .iter() + .map(|animation| { + animation + .transformation + .min_frame_interval() + .unwrap_or_default() + }) + .min() + } + + /// Moves every animated sprite to its pose at `elapsed` time on the app's + /// synced animation clock, without the scene being rebuilt. + pub(crate) fn advance_animations(&mut self, elapsed: Duration) { + for animation in &self.animations { + let Some(sprite) = self.monochrome_sprites.get_mut(animation.sprite_index) else { + continue; + }; + let pose = animation.transformation.at(elapsed); + sprite.transformation = pose.into_matrix(animation.center, animation.scale_factor); + sprite.color = animation.base_color.opacity(pose.alpha_factor()); + } } pub fn len(&self) -> usize { @@ -352,7 +425,11 @@ impl Scene { for operation in &prev_scene.paint_operations[span.operations.clone()] { match operation { PaintOperation::Primitive(primitive) => { - self.insert_primitive(primitive.clone().faded(fade)) + let primitive = primitive.clone().faded(fade); + match prev_scene.animated_sprite(&primitive) { + Some((sprite, animation)) => self.insert_animated_sprite(sprite, animation), + None => self.insert_primitive(primitive), + } } PaintOperation::StartLayer(_) => { layers += 1; @@ -432,10 +509,14 @@ impl Scene { } pub fn insert_primitive(&mut self, primitive: impl Into) { - let mut primitive = primitive.into(); + self.try_insert_primitive(primitive.into()); + } + + /// Returns whether the primitive was kept, rather than clipped away. + fn try_insert_primitive(&mut self, mut primitive: Primitive) -> bool { let clipped_bounds = primitive.clipped_bounds(); if clipped_bounds.is_empty() { - return; + return false; } let kind = primitive.kind(); @@ -452,6 +533,7 @@ impl Scene { } self.paint_operations .push(PaintOperation::Primitive(primitive)); + true } /// Inserts the pieces of one shape at one order between them, the one the highest piece @@ -475,6 +557,7 @@ impl Scene { /// Inserts a primitive replayed from a scene whose history matched this one's where the /// replay began, with the order it was drawn at there. + #[inline] fn keep_primitive(&mut self, primitive: Primitive) { let index = self.paint_operations.len(); if let Some(layer) = self @@ -582,6 +665,7 @@ impl Scene { .iter() .map(|(index, _)| *index) .peekable(); + let has_animations = !prev_scene.animations.is_empty(); for (index, operation) in (range.start..).zip(&prev_scene.paint_operations[range]) { // A cached view nested in this range may be replayed alone next frame, so the // marks inside it move along with what they mark. @@ -589,10 +673,21 @@ impl Scene { self.mark(); } match operation { - PaintOperation::Primitive(primitive) => match keep { - true => self.keep_primitive(primitive.clone()), - false => self.insert_primitive(primitive.clone()), - }, + PaintOperation::Primitive(primitive) => { + if has_animations + && let Some((sprite, animation)) = prev_scene.animated_sprite(primitive) + { + match keep { + true => self.keep_animated_sprite(sprite, animation), + false => self.insert_animated_sprite(sprite, animation), + } + } else { + match keep { + true => self.keep_primitive(primitive.clone()), + false => self.insert_primitive(primitive.clone()), + } + } + } PaintOperation::StartLayer(key) => match layers_kept { true => self.open_layer(*key), false => self.push_layer(), @@ -630,20 +725,34 @@ impl Scene { log::warn!("scene: a filtered layer was left open"); self.effects[index].end = self.effects[index].start; } - self.shadows.sort_by_key(|shadow| shadow.order); - self.backdrops.sort_by_key(|backdrop| backdrop.order); - self.quads.sort_by_key(|quad| quad.order); - self.shaders - .sort_by_key(|shader| (shader.order, shader.shader)); + let keys = &mut Vec::new(); + sort_in_place(&mut self.shadows, keys, |shadow| (shadow.order, 0)); + sort_in_place(&mut self.backdrops, keys, |backdrop| (backdrop.order, 0)); + sort_in_place(&mut self.quads, keys, |quad| (quad.order, 0)); + sort_in_place(&mut self.shaders, keys, |shader| { + (shader.order, shader.shader.0) + }); self.paths.sort_by_key(|path| path.order); - self.underlines.sort_by_key(|underline| underline.order); - self.monochrome_sprites - .sort_by_key(|sprite| (sprite.order, sprite.tile.texture_id.index)); - self.subpixel_sprites - .sort_by_key(|sprite| (sprite.order, sprite.tile.texture_id.index)); - self.polychrome_sprites - .sort_by_key(|sprite| (sprite.order, sprite.tile.texture_id.index)); + sort_in_place(&mut self.underlines, keys, |underline| (underline.order, 0)); + sort_in_place(&mut self.monochrome_sprites, keys, |sprite| { + (sprite.order, sprite.tile.texture_id.index) + }); + sort_in_place(&mut self.subpixel_sprites, keys, |sprite| { + (sprite.order, sprite.tile.texture_id.index) + }); + sort_in_place(&mut self.polychrome_sprites, keys, |sprite| { + (sprite.order, sprite.tile.texture_id.index) + }); self.surfaces.sort_by_key(|surface| surface.order); + + // Sorting moved the sprites, so animations learn where theirs ended up. + if !self.animations.is_empty() { + for (index, sprite) in self.monochrome_sprites.iter().enumerate() { + if let Some(animation) = self.animations.get_mut(sprite.animation.0 as usize) { + animation.sprite_index = index; + } + } + } } #[cfg_attr( @@ -691,6 +800,62 @@ impl Scene { } } +/// Sorts small `(key, index)` pairs instead of the primitives themselves, then moves each +/// primitive into place once. Primitives are large, so a comparison sort that shuffles them +/// directly spends most of its time copying. Ties keep insertion order, as `sort_by_key` +/// does, because the index is part of what is sorted. +fn sort_in_place( + primitives: &mut [T], + keys: &mut Vec<(u64, u32)>, + key: impl Fn(&T) -> (u32, u32), +) { + if primitives.is_sorted_by_key(&key) { + return; + } + keys.clear(); + keys.extend(primitives.iter().enumerate().map(|(index, primitive)| { + let (major, minor) = key(primitive); + ((major as u64) << 32 | minor as u64, index as u32) + })); + keys.sort_unstable(); + + // `keys[target].1` is the source index for `target`. Follow each cycle of that + // permutation, marking visited slots by pointing them at themselves. + for start in 0..primitives.len() { + if keys[start].1 as usize == start { + continue; + } + let displaced = primitives[start]; + let mut target = start; + loop { + let source = keys[target].1 as usize; + keys[target].1 = target as u32; + if source == start { + primitives[target] = displaced; + break; + } + primitives[target] = primitives[source]; + target = source; + } + } +} + +/// Whether renderers draw opaque quads front to back in a depth pre-pass before the rest. +/// The fork leaves it off, since its offscreen layer, blur and backdrop passes have no depth +/// attachment. With it off a filled quad is painted whole and no shader culls opaque rectangles. +pub const DEPTH_PREPASS: bool = false; + +/// The depth step between consecutive quads in a frame with `quad_count` quads. +pub fn quad_depth_scale(quad_count: usize) -> f32 { + let denominator = (quad_count.min((1 << 24) - 1) + 1).next_power_of_two(); + 1.0 / denominator as f32 +} + +/// Maps a quad's index in [`Scene::quads`] to depth, with greater values closer. +pub fn quad_depth(quad_id: u32, scale: f32) -> f32 { + ((quad_id + 1) as f32 * scale).min(1.0) +} + #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Default)] #[cfg_attr( all( @@ -2567,7 +2732,7 @@ impl Default for TransformationMatrix { #[expect(missing_docs)] pub struct MonochromeSprite { pub order: DrawOrder, - pub pad: u32, + pub animation: SpriteAnimationId, pub tile: AtlasTile, pub bounds: Bounds, pub content_mask: ContentMask, @@ -2575,6 +2740,52 @@ pub struct MonochromeSprite { pub transformation: TransformationMatrix, } +/// Refers to an animation of the scene a sprite is inserted into. +/// +/// A single `u32` so it fits the sprite's existing padding and leaves the +/// instance layout unchanged on every backend; renderers ignore it. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +#[repr(transparent)] +pub struct SpriteAnimationId(u32); + +impl SpriteAnimationId { + /// No animation. + pub const NONE: Self = Self(u32::MAX); +} + +impl Default for SpriteAnimationId { + fn default() -> Self { + Self::NONE + } +} + +/// A [`TimedTransformation`] the window applies to a sprite right before +/// every present, so the scene can be presented again without being redrawn. +#[derive(Copy, Clone, Debug)] +pub(crate) struct SpriteAnimation { + transformation: TimedTransformation, + center: Point, + scale_factor: f32, + base_color: Hsla, + sprite_index: usize, +} + +impl SpriteAnimation { + pub(crate) fn new( + transformation: TimedTransformation, + center: Point, + scale_factor: f32, + ) -> Self { + Self { + transformation, + center, + scale_factor, + base_color: Hsla::default(), + sprite_index: usize::MAX, + } + } +} + impl From for Primitive { fn from(sprite: MonochromeSprite) -> Self { Primitive::MonochromeSprite(sprite) diff --git a/crates/gpui/src/svg_renderer.rs b/crates/gpui/src/svg_renderer.rs index 49f77a17..ce0e2b07 100644 --- a/crates/gpui/src/svg_renderer.rs +++ b/crates/gpui/src/svg_renderer.rs @@ -2,11 +2,14 @@ use crate::{ AssetSource, DevicePixels, IsZero, RenderImage, Result, SharedString, Size, swap_rgba_pa_to_bgra, }; +use collections::HashMap; use image::Frame; +use parking_lot::Mutex; use resvg::tiny_skia::Pixmap; use smallvec::SmallVec; use std::{ hash::Hash, + path::Path, sync::{Arc, LazyLock, OnceLock}, }; @@ -102,6 +105,19 @@ pub struct SvgRenderer { /// scales should retain this value to avoid re-paying the parse cost. pub struct ParsedSvg(usvg::Tree); +/// The font of an SVG `` element, as the values of its presentation attributes. +#[derive(Clone, Copy, Debug)] +pub struct SvgTextFont<'a> { + /// The `font-family` list. + pub family: &'a str, + /// The `font-size`, in pixels. + pub size: f32, + /// The `font-weight`. + pub weight: &'a str, + /// The `font-style`. + pub style: &'a str, +} + /// The size in which to rasterize the SVG. #[derive(Clone, Copy)] pub enum SvgSize { @@ -132,45 +148,64 @@ impl SvgRenderer { // eagerly at construction time. This avoids the expensive deep-clone // of the system font database for code paths that never render SVGs // (e.g. tests). - let enriched_fontdb: Arc>> = Arc::new(OnceLock::new()); + let enriched_fontdb = Arc::new(OnceLock::>::new()); let default_font_resolver = usvg::FontResolver::default_font_selector(); let font_resolver = Box::new({ let asset_source = asset_source.clone(); + let enriched_fontdb = enriched_fontdb.clone(); move |font: &usvg::Font, db: &mut Arc| { + let fontdb = enriched_fontdb.get_or_init(|| { + let mut db = (**SYSTEM_FONT_DB).clone(); + load_bundled_fonts(&*asset_source, &mut db); + fix_generic_font_families(&mut db); + Mutex::new(FontDatabase { + database: Arc::new(db), + owned_faces: HashMap::default(), + remaining_owned_bytes: MAX_OWNED_FONT_BYTES, + fallback_faces: HashMap::default(), + }) + }); if db.is_empty() { - let fontdb = enriched_fontdb.get_or_init(|| { - let mut db = (**SYSTEM_FONT_DB).clone(); - load_bundled_fonts(&*asset_source, &mut db); - fix_generic_font_families(&mut db); - Arc::new(db) - }); - *db = fontdb.clone(); - } - if let Some(id) = default_font_resolver(font, db) { - return Some(id); + *db = fontdb.lock().database.clone(); } - // fontdb doesn't recognize CSS system font keywords like "system-ui" - // or "ui-sans-serif", so fall back to sans-serif before any face. - let sans_query = usvg::fontdb::Query { - families: &[usvg::fontdb::Family::SansSerif], - ..Default::default() - }; - db.query(&sans_query) - .or_else(|| db.faces().next().map(|f| f.id)) + let id = default_font_resolver(font, db).or_else(|| { + // fontdb doesn't recognize CSS system font keywords like "system-ui" + // or "ui-sans-serif", so fall back to sans-serif before any face. + let sans_query = usvg::fontdb::Query { + families: &[usvg::fontdb::Family::SansSerif], + ..Default::default() + }; + db.query(&sans_query) + .or_else(|| db.faces().next().map(|f| f.id)) + })?; + Some(fontdb.lock().owned_face(db, id)) } }); let default_fallback_selection = usvg::FontResolver::default_fallback_selector(); let fallback_selection = Box::new( move |ch: char, fonts: &[usvg::fontdb::ID], db: &mut Arc| { - if is_emoji_presentation(ch) { - if let Some(id) = select_emoji_font(ch, fonts, db.as_ref(), EMOJI_FONT_FAMILIES) - { - return Some(id); + let mut select = |fonts: &[usvg::fontdb::ID]| { + if is_emoji_presentation(ch) { + if let Some(id) = + select_emoji_font(ch, fonts, db.as_ref(), EMOJI_FONT_FAMILIES) + { + return Some(id); + } } - } - default_fallback_selection(ch, fonts, db) + default_fallback_selection(ch, fonts, db) + }; + let Some(fontdb) = enriched_fontdb.get() else { + return select(fonts); + }; + let face = cached_fallback_face(fontdb, ch, fonts, select)?; + let owned_face = fontdb.lock().owned_face(db, face); + Some(if fonts.contains(&owned_face) { + face + } else { + owned_face + }) }, ); let options = usvg::Options { @@ -191,6 +226,29 @@ impl SvgRenderer { usvg::Tree::from_data(bytes, &self.usvg_options).map(ParsedSvg) } + /// Returns the advance of `text` drawn by this renderer as a single line of SVG ``. + pub fn measure_text_width( + &self, + text: &str, + font: &SvgTextFont<'_>, + ) -> Result { + let mut svg = String::from( + r#""#)); + push_xml_escaped(&mut svg, text); + svg.push_str(""); + + let tree = usvg::Tree::from_str(&svg, &self.usvg_options)?; + Ok(underline_width(tree.root())) + } + /// Rasterizes a previously parsed SVG into an image buffer. pub fn render_parsed( &self, @@ -306,6 +364,139 @@ fn rasterize_tree(tree: &usvg::Tree, size: SvgSize) -> Result, + owned_faces: HashMap, + remaining_owned_bytes: u64, + fallback_faces: HashMap<(usvg::fontdb::ID, char), Option>, +} + +impl FontDatabase { + fn owned_face( + &mut self, + db: &mut Arc, + id: usvg::fontdb::ID, + ) -> usvg::fontdb::ID { + let Some(usvg::fontdb::Source::File(path)) = db.face(id).map(|face| face.source.clone()) + else { + return id; + }; + if !self.owned_faces.contains_key(&id) { + self.own_font_file(&path); + } + *db = self.database.clone(); + self.owned_faces.get(&id).copied().unwrap_or(id) + } + + fn own_font_file(&mut self, path: &Path) { + let file_faces = self + .database + .faces() + .filter(|face| { + matches!(&face.source, usvg::fontdb::Source::File(face_path) if face_path == path) + }) + .map(|face| (face.id, face.index)) + .collect::>(); + let remaining_owned_bytes = self.remaining_owned_bytes; + let data = std::fs::metadata(path).and_then(|metadata| { + (metadata.len() <= remaining_owned_bytes) + .then(|| std::fs::read(path)) + .transpose() + }); + let owned_ids = match data { + Ok(Some(data)) if data.len() as u64 <= remaining_owned_bytes => { + let size = data.len() as u64; + let owned_ids = Arc::make_mut(&mut self.database) + .load_font_source(usvg::fontdb::Source::Binary(Arc::new(data))); + if !owned_ids.is_empty() { + self.remaining_owned_bytes -= size; + } + owned_ids + } + Ok(_) => Default::default(), + Err(error) => { + log::warn!("Failed to read font {path:?}: {error}"); + Default::default() + } + }; + for (id, index) in file_faces { + let owned_id = owned_ids + .iter() + .copied() + .find(|owned_id| { + self.database + .face(*owned_id) + .is_some_and(|face| face.index == index) + }) + .unwrap_or(id); + self.owned_faces.insert(id, owned_id); + } + } +} + +const MAX_CACHED_FALLBACK_FACES: usize = 16 * 1024; + +fn cached_fallback_face( + fontdb: &Mutex, + ch: char, + fonts: &[usvg::fontdb::ID], + mut select: impl FnMut(&[usvg::fontdb::ID]) -> Option, +) -> Option { + let Some(base) = fonts.first() else { + return select(fonts); + }; + let key = (*base, ch); + let cached_face = fontdb.lock().fallback_faces.get(&key).copied(); + let face = match cached_face { + Some(face) => face, + None => { + let face = select(&fonts[..1]); + let fallback_faces = &mut fontdb.lock().fallback_faces; + if fallback_faces.len() < MAX_CACHED_FALLBACK_FACES { + fallback_faces.insert(key, face); + } + face + } + }; + match face { + Some(face) if fonts.contains(&face) => select(fonts), + face => face, + } +} + +fn underline_width(group: &usvg::Group) -> f32 { + group.children().iter().fold(0., |width, node| { + width + + match node { + usvg::Node::Text(text) => text + .layouted() + .iter() + .filter_map(|span| span.underline.as_ref()) + .fold(0., |width, underline| { + width + underline.data().bounds().width() + }), + usvg::Node::Group(group) => underline_width(group), + usvg::Node::Path(_) | usvg::Node::Image(_) => 0., + } + }) +} + +fn push_xml_escaped(xml: &mut String, text: &str) { + for character in text.chars() { + match character { + '&' => xml.push_str("&"), + '<' => xml.push_str("<"), + '>' => xml.push_str(">"), + '"' => xml.push_str("""), + '\t' | '\n' | '\r' => xml.push(character), + '\u{0}'..='\u{1f}' | '\u{fffe}' | '\u{ffff}' => {} + _ => xml.push(character), + } + } +} + fn load_bundled_fonts(asset_source: &dyn AssetSource, db: &mut usvg::fontdb::Database) { let font_paths = [ "fonts/ibm-plex-sans/IBMPlexSans-Regular.ttf", @@ -356,6 +547,7 @@ fn fix_generic_font_families(db: &mut usvg::fontdb::Database) { #[cfg(test)] mod tests { use super::*; + use std::{borrow::Cow, cell::Cell}; use usvg::fontdb::{Database, Family, Query}; const IBM_PLEX_REGULAR: &[u8] = @@ -390,6 +582,103 @@ mod tests { Ok(()) } + #[test] + fn measured_text_width_matches_rasterized_advance() -> Result<()> { + let renderer = SvgRenderer::new(Arc::new(BundledFonts)); + let font = SvgTextFont { + family: "IBM Plex Sans", + size: 40., + weight: "normal", + style: "normal", + }; + let frame_width = rasterized_text_width(&renderer, "MM")?; + assert!(frame_width > 0.); + + for text in ["MMMM", " ", " ", "\u{a0}", "\u{200b}", "M\u{200b}"] { + let measured = renderer.measure_text_width(text, &font)?; + let rasterized = rasterized_text_width(&renderer, &format!("M{text}M"))? - frame_width; + assert!( + (measured - rasterized).abs() <= 1., + "{text:?} measured {measured}px, rasterized {rasterized}px" + ); + } + assert_eq!( + renderer.measure_text_width("M\u{200b}", &font)?, + renderer.measure_text_width("M", &font)? + ); + assert!(renderer.measure_text_width("<&\"\u{1}>", &font)? > 0.); + Ok(()) + } + + #[test] + fn owns_font_bytes_within_budget() -> Result<()> { + let font_path = |name| { + std::env::temp_dir().join(format!( + "gpui-svg-renderer-{}-{name}.ttf", + std::process::id() + )) + }; + let (plex_path, lilex_path) = (font_path("plex"), font_path("lilex")); + std::fs::write(&plex_path, IBM_PLEX_REGULAR)?; + std::fs::write(&lilex_path, LILEX_REGULAR)?; + let mut database = Database::new(); + database.load_font_file(&plex_path)?; + database.load_font_file(&lilex_path)?; + let mut fonts = FontDatabase { + database: Arc::new(database), + owned_faces: HashMap::default(), + remaining_owned_bytes: IBM_PLEX_REGULAR.len() as u64, + fallback_faces: HashMap::default(), + }; + let mut db = fonts.database.clone(); + let face_ids = db.faces().map(|face| face.id).collect::>(); + let (plex_id, lilex_id) = (face_ids[0], face_ids[1]); + + let owned_plex_id = fonts.owned_face(&mut db, plex_id); + let owned_lilex_id = fonts.owned_face(&mut db, lilex_id); + std::fs::write(&plex_path, b"changed")?; + let data_len = |id| db.with_face_data(id, |data, _| data.len()); + let data_lens = (data_len(plex_id), data_len(owned_plex_id)); + std::fs::remove_file(&plex_path)?; + std::fs::remove_file(&lilex_path)?; + + assert_eq!(data_lens, (Some(7), Some(IBM_PLEX_REGULAR.len()))); + assert_eq!(owned_lilex_id, lilex_id); + assert_eq!(fonts.remaining_owned_bytes, 0); + assert_eq!(fonts.owned_face(&mut db, plex_id), owned_plex_id); + Ok(()) + } + + #[test] + fn fallback_faces_are_remembered_until_excluded() { + let database = db_with_bundled_fonts(); + let face_ids = database.faces().map(|face| face.id).collect::>(); + let (base, fallback) = (face_ids[0], face_ids[1]); + let fontdb = Mutex::new(FontDatabase { + database: Arc::new(database), + owned_faces: HashMap::default(), + remaining_owned_bytes: 0, + fallback_faces: HashMap::default(), + }); + let selections = Cell::new(0); + let fallback_face = |ch, fonts: &[usvg::fontdb::ID]| { + cached_fallback_face(&fontdb, ch, fonts, |excluded| { + selections.set(selections.get() + 1); + (!excluded.contains(&fallback)).then_some(fallback) + }) + }; + + assert_eq!(fallback_face('x', &[base]), Some(fallback)); + assert_eq!(fallback_face('x', &[base]), Some(fallback)); + assert_eq!(selections.get(), 1); + assert_eq!(fallback_face('x', &[base, fallback]), None); + assert_eq!(selections.get(), 2); + assert_eq!(fallback_face('y', &[base, fallback]), None); + assert_eq!(selections.get(), 4); + assert_eq!(fallback_face('y', &[base]), Some(fallback)); + assert_eq!(selections.get(), 4); + } + fn db_with_bundled_fonts() -> Database { let mut db = Database::new(); db.load_font_data(IBM_PLEX_REGULAR.to_vec()); @@ -522,4 +811,44 @@ mod tests { face.families ); } + + struct BundledFonts; + + impl AssetSource for BundledFonts { + fn load(&self, path: &str) -> Result>> { + Ok(match path { + "fonts/ibm-plex-sans/IBMPlexSans-Regular.ttf" => { + Some(Cow::Borrowed(IBM_PLEX_REGULAR)) + } + "fonts/lilex/Lilex-Regular.ttf" => Some(Cow::Borrowed(LILEX_REGULAR)), + _ => None, + }) + } + + fn list(&self, _path: &str) -> Result> { + Ok(Vec::new()) + } + } + + fn rasterized_text_width(renderer: &SvgRenderer, text: &str) -> Result { + let svg = format!( + r#"{text}"# + ); + let pixmap = renderer.render_pixmap(svg.as_bytes(), SvgSize::ScaleFactor(1.))?; + let width = pixmap.width() as usize; + let inked_columns = (0..width) + .filter(|column| { + pixmap + .pixels() + .iter() + .skip(*column) + .step_by(width) + .any(|pixel| pixel.alpha() > 0) + }) + .collect::>(); + Ok(match (inked_columns.first(), inked_columns.last()) { + (Some(first), Some(last)) => (last - first + 1) as f32, + _ => 0., + }) + } } diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs index 1bb5e967..07034b1e 100644 --- a/crates/gpui/src/window.rs +++ b/crates/gpui/src/window.rs @@ -9,23 +9,23 @@ use crate::taffy::TaffyLayoutEngine; use crate::{ Action, AnyDrag, AnyElement, AnyImageCache, AnyTooltip, AnyView, App, AppContext, Arena, Asset, AsyncWindowContext, AtlasTile, AvailableSpace, Backdrop, Background, BorderStyle, Bounds, - BoxShadow, Capslock, Context, Corners, CursorHideMode, CursorStyle, Decorations, DevicePixels, - DispatchActionListener, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity, - EntityId, EventEmitter, FileDropEvent, Filter, FontId, Global, GlobalElementId, GlyphId, - GpuSpecs, Hsla, InputHandler, InputPreference, IsZero, KeyBinding, KeyContext, KeyDownEvent, - KeyEvent, Keystroke, KeystrokeEvent, LayerFilter, LayoutId, LineLayoutIndex, Modifiers, - ModifiersChangedEvent, MonochromeSprite, MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, - PaintedPath, Path, Pixels, PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, - PlatformWindow, Point, PolychromeSprite, Priority, PromptButton, PromptLevel, Quad, Render, - RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams, Replay, ResizeEdge, - SMOOTH_SVG_SCALE_FACTOR, SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, ScaledPixels, Scene, Shader, - ShaderInstance, ShaderQuad, Shadow, SharedString, Size, SpanId, StrikethroughStyle, Style, - SubpixelSprite, Subscription, SystemWindowTab, SystemWindowTabController, TabStopMap, Task, - TextInputConfiguration, TextInputStateChange, TextRenderingMode, TextStyle, - TextStyleRefinement, ThermalState, TransformationMatrix, Underline, UnderlineStyle, - WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowControls, WindowDecorations, - WindowInsets, WindowOptions, WindowParams, WindowTextSystem, WindowVisibility, point, - prelude::*, px, rems, size, transparent_black, + BoxShadow, Capslock, Context, Corners, CursorHideMode, CursorStyle, DEPTH_PREPASS, Decorations, + DevicePixels, DispatchActionListener, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, + Entity, EntityId, EventEmitter, FileDropEvent, Filter, FontId, Global, GlobalElementId, + GlyphId, GpuSpecs, Hsla, InputHandler, InputPreference, IsZero, KeyBinding, KeyContext, + KeyDownEvent, KeyEvent, Keystroke, KeystrokeEvent, LayerFilter, LayoutId, LineLayoutIndex, + Modifiers, ModifiersChangedEvent, MonochromeSprite, MouseButton, MouseEvent, MouseMoveEvent, + MouseUpEvent, PaintedPath, Path, Pixels, PlatformAtlas, PlatformDisplay, PlatformInput, + PlatformInputHandler, PlatformWindow, Point, PolychromeSprite, Priority, PromptButton, + PromptLevel, Quad, Render, RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams, + Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR, SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, + ScaledPixels, Scene, Shader, ShaderInstance, ShaderQuad, Shadow, SharedString, Size, SpanId, + SpriteAnimation, SpriteAnimationId, StrikethroughStyle, Style, SubpixelSprite, Subscription, + SystemWindowTab, SystemWindowTabController, TabStopMap, Task, TextInputConfiguration, + TextInputStateChange, TextRenderingMode, TextStyle, TextStyleRefinement, ThermalState, + TransformationMatrix, Underline, UnderlineStyle, WindowAppearance, WindowBackgroundAppearance, + WindowBounds, WindowControls, WindowDecorations, WindowInsets, WindowOptions, WindowParams, + WindowTextSystem, WindowVisibility, point, prelude::*, px, rems, size, transparent_black, }; use crate::gestures::{GestureTuning, RecognizedTouchGesture, ScrollCoast, TouchGestureRecognizer}; @@ -1422,6 +1422,9 @@ pub struct Window { last_present: Instant, /// Whether a task is already waiting to free the renderer's idle GPU memory. idle_gpu_release_armed: bool, + /// The rendered scene's [`Scene::animation_frame_interval`]. While it is + /// `Some`, the scene must keep being presented even when nothing is redrawn. + scene_animation_interval: Rc>>, /// Tracks recent input event timestamps to determine if input is arriving at a high rate. /// Used to selectively enable VRR optimization only when input rate exceeds 60fps. pub(crate) input_rate_tracker: Rc>, @@ -1876,6 +1879,7 @@ impl Window { profiler::journal::record_window_visibility(handle.window_id(), visibility); let hovered = Rc::new(Cell::new(platform_window.is_hovered())); let needs_present = Rc::new(Cell::new(false)); + let scene_animation_interval = Rc::new(Cell::new(None::)); let next_frame_callbacks: Rc>> = Default::default(); let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default())); let gesture_tuning = cx @@ -2046,6 +2050,7 @@ impl Window { let invalidator = invalidator.clone(); let active = active.clone(); let needs_present = needs_present.clone(); + let scene_animation_interval = scene_animation_interval.clone(); let next_frame_callbacks = next_frame_callbacks.clone(); let input_rate_tracker = input_rate_tracker.clone(); let mut deferred_force_render = false; @@ -2109,12 +2114,14 @@ impl Window { let high_rate_input = input_rate_tracker.borrow_mut().is_high_rate(); let present_for_input = presents_to_hold_refresh_rate && high_rate_input; let has_next_frame_callbacks = !next_frame_callbacks.borrow().is_empty(); - let has_frame_demand = invalidator.is_dirty() + let has_demand_besides_animation = invalidator.is_dirty() || force_render || has_next_frame_callbacks || request_frame_options.require_presentation || needs_present.get() || present_for_input; + let has_frame_demand = + has_demand_besides_animation || scene_animation_interval.get().is_some(); let should_throttle = !request_frame_options.require_presentation; let inactive_without_high_rate_input = @@ -2130,6 +2137,10 @@ impl Window { thermal_state, power_mode, ); + let animation_frame_interval = scene_animation_interval + .get() + .filter(|interval| !has_demand_besides_animation && !interval.is_zero()); + let min_frame_interval = min_frame_interval.max(animation_frame_interval); let now = Instant::now(); // Idle display-link ticks must neither consume a frame slot nor @@ -2156,7 +2167,11 @@ impl Window { profiler::journal::record_frame_skipped( window_id, Instant::now(), - if inactive_without_high_rate_input + if animation_frame_interval.is_some() + && animation_frame_interval == min_frame_interval + { + profiler::journal::FrameSkipReason::AnimationFrameRateLimit + } else if inactive_without_high_rate_input && inactive_frame_interval == min_frame_interval { profiler::journal::FrameSkipReason::InactiveFrameRateLimit @@ -2196,6 +2211,7 @@ impl Window { let should_draw = invalidator.is_dirty() || force_render; let needs_present = request_frame_options.require_presentation || needs_present.get() + || scene_animation_interval.get().is_some() || present_for_input; if should_draw { measure("frame duration", || { @@ -2217,6 +2233,7 @@ impl Window { draw_start, ); crate::frame_stats::mark_drawn(); + window.advance_scene_animations(cx); window.present(); window.arm_idle_gpu_release(cx); arena_clear_needed.clear(cx); @@ -2232,6 +2249,7 @@ impl Window { } else if needs_present { handle .update(&mut cx, |_, window, cx| { + window.advance_scene_animations(cx); window.present(); window.arm_idle_gpu_release(cx); }) @@ -2245,6 +2263,7 @@ impl Window { .update(&mut cx, |_, window, _| { if window.invalidator.is_dirty() || !window.next_frame_callbacks.borrow().is_empty() + || window.scene_animation_interval.get().is_some() { window.platform_window.schedule_frame(); } @@ -2262,7 +2281,10 @@ impl Window { // after this frame (the window was re-invalidated mid-draw, or // animations scheduled next-frame callbacks), re-arm the frame // source explicitly. - if invalidator.is_dirty() || !next_frame_callbacks.borrow().is_empty() { + if invalidator.is_dirty() + || !next_frame_callbacks.borrow().is_empty() + || scene_animation_interval.get().is_some() + { invalidator.wake_platform(); } #[cfg(feature = "profiler")] @@ -2588,6 +2610,7 @@ impl Window { needs_present, last_present: cx.background_executor().now(), idle_gpu_release_armed: false, + scene_animation_interval, input_rate_tracker, #[cfg(feature = "profiler")] window_profiler: profiler::WindowProfiler::new(handle.window_id())?, @@ -3202,6 +3225,11 @@ impl Window { self.on_next_frame(move |_, cx| cx.notify(entity)); } + pub(crate) fn advance_scene_animations(&mut self, cx: &App) { + let elapsed = cx.background_executor().now() - cx.synced_animation_epoch; + self.rendered_frame.scene.advance_animations(elapsed); + } + /// Runs all callbacks scheduled via [`Self::on_next_frame`], returning how many ran. /// /// Tests have no platform frame loop, so this simulates the delivery of the @@ -4071,6 +4099,8 @@ impl Window { let previous_focus_path = self.rendered_frame.focus_path(); let previous_window_active = self.rendered_frame.window_active; mem::swap(&mut self.rendered_frame, &mut self.next_frame); + self.scene_animation_interval + .set(self.rendered_frame.scene.animation_frame_interval()); self.next_frame.clear(); self.drawn_frames += 1; // A backdrop that reaches past an edge for the first time draws once more with the @@ -5547,6 +5577,13 @@ impl Window { continue; } let hole = (bounds + shadow.offset).dilate(-shadow.spread_radius); + // Keep an empty hole empty rather than letting cover_bounds expand a fractional + // collapsed rect into a 1px hole. + let shape_bounds = if hole.is_empty() { + Bounds::default() + } else { + self.cover_bounds(hole) + }; // Clamp at zero so a large spread can't produce negative radii, which would // break the SDF in the shader. let zero = Pixels::ZERO; @@ -5563,7 +5600,7 @@ impl Window { content_mask, corner_radii: element_corner_radii, color: shadow.color.opacity(opacity), - shape_bounds: self.cover_bounds(hole), + shape_bounds, shape_corner_radii: hole_corner_radii.scale(scale_factor), inset: true.into(), element_corner_smoothing: corner_smoothing, @@ -5574,7 +5611,41 @@ impl Window { } fn largest_border_interior(quad: &Quad) -> Bounds { - // A smoothed corner starts further along each edge than its radius. + let size = quad.bounds.size; + let diagonal = (size.width.0 * size.width.0 + size.height.0 * size.height.0).sqrt(); + if diagonal == 0. { + return Bounds::default(); + } + // The interior's corners sit on the corner arcs. Taking the angle along + // the arc whose tangent is the quad's aspect ratio stays within 1% of + // the largest interior. + let cos = size.height.0 / diagonal; + let sin = size.width.0 / diagonal; + + // A corner's inner border edge is a quarter ellipse around the + // corner's center, with the border widths taken off its radius. + // Smoothed corners offset their outer curve by the wider border on + // both axes in the shader, so use that width for both coordinates + // inside a rounded corner. + let smoothed = quad.corner_smoothing > 0.0; + let corner_inset = |radius: ScaledPixels, width_x: ScaledPixels, width_y: ScaledPixels| { + if smoothed && radius > ScaledPixels(0.0) { + let w = width_x.max(width_y); + let inner = (radius - w).max(ScaledPixels(0.0)); + point( + width_x.max(radius - inner * cos), + width_y.max(radius - inner * sin), + ) + } else { + point( + width_x.max(radius - (radius - width_x) * cos), + width_y.max(radius - (radius - width_y) * sin), + ) + } + }; + + // A smoothed corner starts further along each edge than its radius and bulges past the + // round corner of that reach, so a round corner of the reach bounds it from inside. let reach = 1.0 + SQUIRCLE_REACH * quad.corner_smoothing.clamp(0.0, 1.0); let radii = &Corners { top_left: quad.corner_radii.top_left * reach, @@ -5583,40 +5654,23 @@ impl Window { bottom_left: quad.corner_radii.bottom_left * reach, }; let widths = &quad.border_widths; - let edge_radii = Edges { - top: radii.top_left.max(radii.top_right), - right: radii.top_right.max(radii.bottom_right), - bottom: radii.bottom_left.max(radii.bottom_right), - left: radii.top_left.max(radii.bottom_left), - }; + let top_left = corner_inset(radii.top_left, widths.left, widths.top); + let top_right = corner_inset(radii.top_right, widths.right, widths.top); + let bottom_right = corner_inset(radii.bottom_right, widths.right, widths.bottom); + let bottom_left = corner_inset(radii.bottom_left, widths.left, widths.bottom); let antialias_inset = point(ScaledPixels(1.0), ScaledPixels(1.0)); - let inset_bounds = |top_left_inset, bottom_right_inset| { - Bounds::from_corners( - quad.bounds.origin + top_left_inset + antialias_inset, - quad.bounds.bottom_right() - bottom_right_inset - antialias_inset, - ) - }; - - // Rounded corners need only be excluded on one axis. Either candidate - // is empty of border pixels, so use the larger interior. - let horizontal_band = inset_bounds( - point(widths.left, widths.top.max(edge_radii.top)), - point(widths.right, widths.bottom.max(edge_radii.bottom)), - ); - let vertical_band = inset_bounds( - point(widths.left.max(edge_radii.left), widths.top), - point(widths.right.max(edge_radii.right), widths.bottom), - ); - - let area = |bounds: &Bounds| { - bounds.size.width.0.max(0.) * bounds.size.height.0.max(0.) - }; - if area(&horizontal_band) >= area(&vertical_band) { - horizontal_band - } else { - vertical_band - } + Bounds::from_corners( + quad.bounds.origin + + point(top_left.x.max(bottom_left.x), top_left.y.max(top_right.y)) + + antialias_inset, + quad.bounds.bottom_right() + - point( + top_right.x.max(bottom_right.x), + bottom_left.y.max(bottom_right.y), + ) + - antialias_inset, + ) } /// Paints everything the callback draws into an offscreen layer, applies the given effects, @@ -5872,8 +5926,22 @@ impl Window { corner_smoothing, pad: 0, }; + self.insert_quad(quad); + } + + fn insert_quad(&mut self, quad: Quad) { + let has_background = !quad.background.is_transparent(); + let has_border = + quad.border_widths != Edges::default() && !quad.border_color.is_transparent(); + if !has_background && !has_border { + return; + } - if !quad.background.is_transparent() { + // Splitting a filled quad only lets the depth pre-pass draw its interior, so without the + // pre-pass it goes in whole and only a border-only quad is split around its interior. + let is_rectangle = + quad.border_widths == Edges::default() && quad.corner_radii == Corners::default(); + if has_background && (is_rectangle || !DEPTH_PREPASS) { let strips = self.strips_past_edges(&quad); let scene = &mut self.next_frame.scene; match strips.is_empty() { @@ -5885,16 +5953,49 @@ impl Window { return; } - // Splitting a border-only quad around its empty interior avoids shading - // every transparent pixel inside large outlines. + let plain_border = DEPTH_PREPASS + && quad.corner_radii == Corners::default() + && quad.border_style == BorderStyle::Solid + && (!has_background || quad.border_color.is_opaque()); + + // Splitting off the interior leaves only the strips around it for the + // border and corner shading. let outer_bounds = quad.bounds; - let inner_bounds = Self::largest_border_interior(&quad); + let inner_bounds = if plain_border { + quad.bounds.extend(quad.border_widths.map(|width| -*width)) + } else { + Self::largest_border_interior(&quad) + }; + + // A plain border's strips can be plain rectangles of the border color. + // Otherwise, each strip is the whole quad masked to the strip, so the + // border, corners and gradients are still shaded relative to the full quad. + let strip_quad = if plain_border { + Quad { + background: quad.border_color.into(), + border_widths: Edges::default(), + ..quad + } + } else { + quad + }; if inner_bounds.is_empty() { - self.next_frame.scene.insert_primitive(quad); + self.next_frame.scene.insert_primitive(strip_quad); return; } + if has_background { + self.next_frame.scene.insert_primitive(Quad { + content_mask: ContentMask { + bounds: quad.content_mask.bounds.intersect(&inner_bounds), + }, + border_widths: Edges::default(), + corner_radii: Corners::default(), + ..quad + }); + } + let strips = [ // Top Bounds::from_corners( @@ -5919,15 +6020,12 @@ impl Window { ]; for strip in strips { - let content_mask_bounds = quad.content_mask.bounds.intersect(&strip); - if !content_mask_bounds.is_empty() { - self.next_frame.scene.insert_primitive(Quad { - content_mask: ContentMask { - bounds: content_mask_bounds, - }, - ..quad - }); - } + self.next_frame.scene.insert_primitive(Quad { + content_mask: ContentMask { + bounds: quad.content_mask.bounds.intersect(&strip), + }, + ..strip_quad + }); } } @@ -6083,7 +6181,7 @@ impl Window { } else { self.next_frame.scene.insert_primitive(MonochromeSprite { order: 0, - pad: 0, + animation: SpriteAnimationId::NONE, bounds, content_mask, color: color.opacity(element_opacity), @@ -6190,6 +6288,21 @@ impl Window { transformation: TransformationMatrix, color: Hsla, cx: &App, + ) -> Result<()> { + self.paint_animated_svg(bounds, path, data, transformation, None, color, cx) + } + + /// Like [`Self::paint_svg`], with an `animation` the window applies before every + /// present, so the view isn't re-rendered to advance it. + pub(crate) fn paint_animated_svg( + &mut self, + bounds: Bounds, + path: SharedString, + data: Option<&[u8]>, + transformation: TransformationMatrix, + animation: Option, + color: Hsla, + cx: &App, ) -> Result<()> { self.invalidator.debug_assert_paint(); @@ -6234,15 +6347,22 @@ impl Window { }) .map_size(|size| size.ceil()); - self.next_frame.scene.insert_primitive(MonochromeSprite { + let sprite = MonochromeSprite { order: 0, - pad: 0, + animation: SpriteAnimationId::NONE, bounds: final_bounds, content_mask, color: color.opacity(element_opacity), tile, transformation, - }); + }; + match animation { + Some(animation) => self + .next_frame + .scene + .insert_animated_sprite(sprite, animation), + None => self.next_frame.scene.insert_primitive(sprite), + } Ok(()) } @@ -6384,7 +6504,7 @@ impl Window { frame_index, }; - self.sprite_atlas.remove(¶ms.clone().into()); + self.sprite_atlas.remove(¶ms.into()); } Ok(()) @@ -12124,4 +12244,84 @@ mod inspector_tests { }) .expect("closed inspector has no bookkeeping and no style overrides"); } + + #[test] + fn largest_border_interior_clears_unequal_smoothed_borders() { + let mut quad = Quad { + order: 0, + border_style: BorderStyle::Solid, + bounds: Bounds::new( + point(ScaledPixels(0.0), ScaledPixels(0.0)), + size(ScaledPixels(200.0), ScaledPixels(200.0)), + ), + content_mask: ContentMask { + bounds: Bounds::new( + point(ScaledPixels(0.0), ScaledPixels(0.0)), + size(ScaledPixels(200.0), ScaledPixels(200.0)), + ), + }, + background: crate::Background::default(), + border_color: crate::black(), + corner_radii: Corners::all(ScaledPixels(60.0)), + border_widths: Edges { + top: ScaledPixels(1.0), + right: ScaledPixels(50.0), + bottom: ScaledPixels(1.0), + left: ScaledPixels(50.0), + }, + corner_smoothing: 1.0, + pad: 0, + }; + let interior = Window::largest_border_interior(&quad); + assert!( + !interior.contains(&point(ScaledPixels(64.5), ScaledPixels(29.5))), + "interior cutout {interior:?} must not clip a smoothed corner offset by the wider border" + ); + assert!(interior.origin.y > ScaledPixels(63.0)); + + quad.corner_radii = Corners::all(ScaledPixels(0.0)); + let square_interior = Window::largest_border_interior(&quad); + assert_eq!(square_interior.origin.y, ScaledPixels(2.0)); + assert_eq!(square_interior.origin.x, ScaledPixels(51.0)); + } + + #[gpui::test] + fn test_collapsed_inset_shadow_hole_stays_empty_at_fractional_origin(cx: &mut TestAppContext) { + struct BlankView; + impl Render for BlankView { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + div() + } + } + let window = cx.add_window(|_, _| BlankView); + cx.update_window(window.into(), |_, window, cx| { + window.draw(cx).clear(cx); + window.invalidator.set_phase(DrawPhase::Paint); + let bounds = Bounds::new(point(px(10.5), px(10.5)), size(px(20.0), px(20.0))); + window.paint_inset_shadows( + bounds, + Corners::default(), + 0.0, + &[BoxShadow { + color: crate::black(), + offset: point(px(0.0), px(0.0)), + blur_radius: px(4.0), + spread_radius: px(10.0), + inset: true, + }], + ); + let shadow = window + .next_frame + .scene + .shadows + .last() + .expect("collapsed inset shadow inserted"); + assert!( + shadow.shape_bounds.is_empty(), + "collapsed inset hole at fractional origin must stay empty, got {:?}", + shadow.shape_bounds + ); + }) + .unwrap(); + } } diff --git a/crates/gpui_apple/Cargo.toml b/crates/gpui_apple/Cargo.toml index c319e5c2..81d0bea5 100644 --- a/crates/gpui_apple/Cargo.toml +++ b/crates/gpui_apple/Cargo.toml @@ -57,6 +57,7 @@ objc2-metal = { version = "0.3.2", default-features = false, features = [ "MTLCommandBuffer", "MTLCommandEncoder", "MTLCommandQueue", + "MTLDepthStencil", "MTLDevice", "MTLDrawable", "MTLLibrary", diff --git a/crates/gpui_apple/src/metal_renderer.rs b/crates/gpui_apple/src/metal_renderer.rs index 717fabd6..626eeffe 100644 --- a/crates/gpui_apple/src/metal_renderer.rs +++ b/crates/gpui_apple/src/metal_renderer.rs @@ -3,9 +3,9 @@ use anyhow::{Context as _, Result}; use block2::RcBlock; use collections::FxHashMap; use gpui::{ - AtlasTextureId, BLUR_LEVELS, BlurPasses, Bounds, ContentMask, DevicePixels, GAUSSIAN_REACH, - LayerEffect, PaintSurface, PaintedPath, PrimitiveBatch, Pyramid, ScaledPixels, Scene, ShaderId, - Size, point, size, + AtlasTextureId, BLUR_LEVELS, BlurPasses, Bounds, ContentMask, DEPTH_PREPASS, DevicePixels, + GAUSSIAN_REACH, LayerEffect, PaintSurface, PaintedPath, PrimitiveBatch, Pyramid, ScaledPixels, + Scene, ShaderId, Size, point, quad_depth, quad_depth_scale, size, }; #[cfg(any(test, feature = "bench-support", feature = "test-support"))] use image::RgbaImage; @@ -22,7 +22,8 @@ use objc2_foundation::{NSRange, NSString}; use objc2_metal::MTLCopyAllDevices; use objc2_metal::{ MTLBlendFactor, MTLBlendOperation, MTLBuffer, MTLClearColor, MTLCommandBuffer, - MTLCommandEncoder, MTLCommandQueue, MTLCompileOptions, MTLCreateSystemDefaultDevice, MTLDevice, + MTLCommandEncoder, MTLCommandQueue, MTLCompareFunction, MTLCompileOptions, + MTLCreateSystemDefaultDevice, MTLDepthStencilDescriptor, MTLDepthStencilState, MTLDevice, MTLDrawable, MTLGPUFamily, MTLLibrary, MTLLoadAction, MTLPixelFormat, MTLPrimitiveType, MTLRenderCommandEncoder, MTLRenderPassDescriptor, MTLRenderPipelineDescriptor, MTLRenderPipelineState, MTLResourceOptions, MTLScissorRect, MTLStorageMode, MTLStoreAction, @@ -174,7 +175,6 @@ enum DisplayLinkMode { pub struct MetalRenderer { device: Retained>, layer: Option>, - #[cfg(any(test, feature = "bench-support", feature = "test-support"))] is_apple_gpu: bool, is_unified_memory: bool, presents_with_transaction: bool, @@ -185,6 +185,7 @@ pub struct MetalRenderer { path_tiles_pipeline_state: Retained>, shadows_pipeline_state: Retained>, quads_pipeline_state: Retained>, + opaque_quads_pipeline_state: Retained>, underlines_pipeline_state: Retained>, monochrome_sprites_pipeline_state: Retained>, polychrome_sprites_pipeline_state: Retained>, @@ -203,6 +204,9 @@ pub struct MetalRenderer { /// it. A shader that failed to build is kept as `None`, so it is not built again every frame. custom_pipeline_states: FxHashMap>>>, + depth_write_state: Retained>, + depth_test_state: Retained>, + depth_texture: Option>>, instance_buffer_pool: Arc>, sprite_atlas: Arc, core_video_texture_cache: CFRetained, @@ -354,6 +358,7 @@ impl MetalRenderer { "path_tile_vertex", "path_tile_fragment", MTLPixelFormat::BGRA8Unorm, + true, )?; let shadows_pipeline_state = build_pipeline_state( &device, @@ -362,6 +367,7 @@ impl MetalRenderer { "shadow_vertex", "shadow_fragment", MTLPixelFormat::BGRA8Unorm, + true, )?; let quads_pipeline_state = build_pipeline_state( &device, @@ -370,6 +376,16 @@ impl MetalRenderer { "quad_vertex", "quad_fragment", MTLPixelFormat::BGRA8Unorm, + true, + )?; + let opaque_quads_pipeline_state = build_pipeline_state( + &device, + &library, + "opaque_quads", + "opaque_quad_vertex", + "opaque_quad_fragment", + MTLPixelFormat::BGRA8Unorm, + false, )?; let underlines_pipeline_state = build_pipeline_state( &device, @@ -378,6 +394,7 @@ impl MetalRenderer { "underline_vertex", "underline_fragment", MTLPixelFormat::BGRA8Unorm, + true, )?; let monochrome_sprites_pipeline_state = build_pipeline_state( &device, @@ -386,6 +403,7 @@ impl MetalRenderer { "monochrome_sprite_vertex", "monochrome_sprite_fragment", MTLPixelFormat::BGRA8Unorm, + true, )?; let polychrome_sprites_pipeline_state = build_pipeline_state( &device, @@ -394,6 +412,7 @@ impl MetalRenderer { "polychrome_sprite_vertex", "polychrome_sprite_fragment", MTLPixelFormat::BGRA8Unorm, + true, )?; let surfaces_pipeline_state = build_pipeline_state( &device, @@ -402,6 +421,7 @@ impl MetalRenderer { "surface_vertex", "surface_fragment", MTLPixelFormat::BGRA8Unorm, + true, )?; // A backdrop mixes the blurred copy into what it covers rather than laying it over: @@ -489,6 +509,9 @@ impl MetalRenderer { FilterBlend::Over, )?; + let depth_write_state = build_depth_stencil_state(&device, true)?; + let depth_test_state = build_depth_stencil_state(&device, false)?; + let command_queue = device.newCommandQueue().context("creating command queue")?; let supports_shared_storage = cfg!(target_os = "ios") || is_apple_gpu; #[expect( @@ -514,7 +537,6 @@ impl MetalRenderer { layer, presents_with_transaction: false, display_link_mode: DisplayLinkMode::Detached, - #[cfg(any(test, feature = "bench-support", feature = "test-support"))] is_apple_gpu, is_unified_memory, opaque, @@ -522,6 +544,7 @@ impl MetalRenderer { path_tiles_pipeline_state, shadows_pipeline_state, quads_pipeline_state, + opaque_quads_pipeline_state, underlines_pipeline_state, monochrome_sprites_pipeline_state, polychrome_sprites_pipeline_state, @@ -536,6 +559,9 @@ impl MetalRenderer { composite_pipeline_state, masked_pipeline_state, custom_pipeline_states: FxHashMap::default(), + depth_write_state, + depth_test_state, + depth_texture: None, instance_buffer_pool, sprite_atlas, core_video_texture_cache, @@ -982,10 +1008,14 @@ impl MetalRenderer { true => self.filter_texture(FilterTarget::Frame, viewport_size)?, false => texture.retain(), }; + let depth_texture = DEPTH_PREPASS + .then(|| self.depth_texture_matching(&main_texture)) + .transpose()?; let mut command_encoder = new_command_encoder_for_texture( &command_buffer, &main_texture, + depth_texture.as_deref(), viewport_size, Some(MTLClearColor { red: 0., @@ -994,14 +1024,25 @@ impl MetalRenderer { alpha, }), )?; - // SAFETY: Metal copies the viewport bytes, which match every vertex - // shader's `GlobalInputIndex_ViewportSize` argument. + let depth_scale = quad_depth_scale(scene.quads.len()); + // SAFETY: Metal copies both values, which match every vertex shader's + // `GlobalInputIndex_ViewportSize` and `GlobalInputIndex_DepthScale` arguments. unsafe { command_encoder.setVertexBytes_length_atIndex( ptr::NonNull::from(&viewport_size).cast(), mem::size_of_val(&viewport_size), GlobalInputIndex::ViewportSize as usize, ); + command_encoder.setVertexBytes_length_atIndex( + ptr::NonNull::from(&depth_scale).cast(), + mem::size_of_val(&depth_scale), + GlobalInputIndex::DepthScale as usize, + ); + } + + if DEPTH_PREPASS { + self.draw_opaque_quads(scene.quads.len(), instance_bindings, &command_encoder); + command_encoder.setDepthStencilState(Some(&self.depth_test_state)); } let mut stack: Vec = Vec::new(); @@ -1012,6 +1053,7 @@ impl MetalRenderer { // share the target when everything it draws lands inside it. let mut wiped: Vec> = Vec::new(); + let mut quad_cursor: u32 = 0; let mut path_tile_cursor = 0; for batch in scene.batches() { let wanted = filtered @@ -1059,6 +1101,7 @@ impl MetalRenderer { stack.len(), &main_texture, viewport_size, + depth_scale, )?; } @@ -1076,18 +1119,38 @@ impl MetalRenderer { // margin a blur reads past it, is ever read back, so only that is wiped. command_encoder = new_discarding_command_encoder(&command_buffer, &target, viewport_size)?; - bind_viewport(&command_encoder, viewport_size); + bind_viewport(&command_encoder, viewport_size, depth_scale); self.clear_within(&command_encoder, layer_wipe(layer), viewport_size); stack.push(*index); spans.push(layer.destination_clip()); wiped.push(layer_wipe(layer)); } + // Quad shaders assign each quad its own depth. + // In every other batch type, the depth is fixed to the position of the quad cursor. + if DEPTH_PREPASS { + let (znear, zfar) = if matches!(&batch, PrimitiveBatch::Quads(_)) { + (0.0, 1.0) + } else { + let depth = quad_depth(quad_cursor, depth_scale) as f64; + (depth, depth) + }; + command_encoder.setViewport(MTLViewport { + originX: 0.0, + originY: 0.0, + width: i32::from(viewport_size.width) as f64, + height: i32::from(viewport_size.height) as f64, + znear, + zfar, + }); + } + match batch { PrimitiveBatch::Shadows(range) => { self.draw_shadows(range, instance_bindings, &command_encoder) } PrimitiveBatch::Quads(range) => { + quad_cursor += range.len() as u32; self.draw_quads(range, instance_bindings, &command_encoder) } PrimitiveBatch::Shaders { shader, range } => { @@ -1097,6 +1160,7 @@ impl MetalRenderer { range, instance_bindings, viewport_size, + depth_scale, &command_encoder, ); } @@ -1171,10 +1235,11 @@ impl MetalRenderer { command_encoder = new_command_encoder_for_texture( &command_buffer, &target, + None, viewport_size, None, )?; - bind_viewport(&command_encoder, viewport_size); + bind_viewport(&command_encoder, viewport_size, depth_scale); self.draw_backdrops( range, instance_bindings, @@ -1212,6 +1277,7 @@ impl MetalRenderer { stack.len(), &main_texture, viewport_size, + depth_scale, )?; } @@ -1244,6 +1310,7 @@ impl MetalRenderer { depth: usize, main_texture: &ProtocolObject, viewport_size: Size, + depth_scale: f32, ) -> Result>> { let source = self.filter_texture( FilterTarget::Layer(depth.min(LAYER_DEPTH - 1)), @@ -1267,8 +1334,9 @@ impl MetalRenderer { )?, false => source, }; - let encoder = new_command_encoder_for_texture(command_buffer, &onto, viewport_size, None)?; - bind_viewport(&encoder, viewport_size); + let encoder = + new_command_encoder_for_texture(command_buffer, &onto, None, viewport_size, None)?; + bind_viewport(&encoder, viewport_size, depth_scale); self.composite_layer(&encoder, &blurred, layer, clip, viewport_size); Ok(encoder) } @@ -1344,6 +1412,7 @@ impl MetalRenderer { None => new_command_encoder_for_texture( command_buffer, target, + None, size, Some(MTLClearColor { red: 0., @@ -1637,6 +1706,7 @@ impl MetalRenderer { let encoder = new_command_encoder_for_texture( command_buffer, &target, + None, viewport_size, Some(MTLClearColor { red: 0., @@ -1747,6 +1817,75 @@ impl MetalRenderer { } } + fn depth_texture_matching( + &mut self, + target: &ProtocolObject, + ) -> Result>> { + if let Some(depth_texture) = &self.depth_texture + && depth_texture.width() == target.width() + && depth_texture.height() == target.height() + { + return Ok(depth_texture.clone()); + } + let descriptor = MTLTextureDescriptor::new(); + // SAFETY: The size is the size of an existing render target, which the device supports. + unsafe { + descriptor.setWidth(target.width()); + descriptor.setHeight(target.height()); + } + descriptor.setPixelFormat(MTLPixelFormat::Depth32Float); + descriptor.setUsage(MTLTextureUsage::RenderTarget); + // The depth buffer never leaves its render pass, so Apple GPUs can keep + // it in tile memory without allocating any backing store. + descriptor.setStorageMode(if self.is_apple_gpu { + MTLStorageMode::Memoryless + } else { + MTLStorageMode::Private + }); + let depth_texture = self + .device + .newTextureWithDescriptor(&descriptor) + .context("allocating depth texture")?; + self.depth_texture = Some(depth_texture.clone()); + Ok(depth_texture) + } + + fn draw_opaque_quads( + &self, + quad_count: usize, + instance_bindings: &InstanceBindings, + command_encoder: &ProtocolObject, + ) { + if quad_count == 0 { + return; + } + let quad_count_value = quad_count as u32; + + command_encoder.setRenderPipelineState(&self.opaque_quads_pipeline_state); + command_encoder.setDepthStencilState(Some(&self.depth_write_state)); + // SAFETY: The scene's quads and the copied count match the shader layouts and slots. + // Metal retains the buffer, and writer.finish publishes its writes. + unsafe { + command_encoder.setVertexBuffer_offset_atIndex( + Some(&instance_bindings.quads.buffer), + instance_bindings.quads.offset, + QuadInputIndex::Quads as usize, + ); + command_encoder.setVertexBytes_length_atIndex( + ptr::NonNull::from(&quad_count_value).cast(), + mem::size_of_val(&quad_count_value), + QuadInputIndex::QuadCount as usize, + ); + command_encoder.drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance( + MTLPrimitiveType::TriangleStrip, + 0, + 4, + quad_count, + 0, + ); + } + } + fn draw_path_tiles( &self, tiles: Range, @@ -1887,6 +2026,7 @@ impl MetalRenderer { shaders: Range, instance_bindings: &InstanceBindings, viewport_size: Size, + depth_scale: f32, command_encoder: &ProtocolObject, ) { if shaders.is_empty() { @@ -1954,8 +2094,8 @@ impl MetalRenderer { shaders.start, ); } - // The globals took the slot the viewport is bound at for the whole pass. - bind_viewport(command_encoder, viewport_size); + // The globals and instances took the slots of the viewport and depth scale. + bind_viewport(command_encoder, viewport_size, depth_scale); } fn draw_underlines( @@ -2223,20 +2363,26 @@ fn layer_wipe(layer: LayerEffect) -> Bounds { layer.source_bounds.dilate(margin + ScaledPixels(1.)) } -/// Binds the viewport every primitive shader reads at `GlobalInputIndex::ViewportSize`. A pass -/// starts without it, and the custom shader globals share its slot. +/// Binds the viewport and quad depth scale the primitive shaders read at `GlobalInputIndex`. A +/// pass starts without them, and the custom shader globals and instances share their slots. fn bind_viewport( encoder: &ProtocolObject, viewport_size: Size, + depth_scale: f32, ) { - // SAFETY: Metal copies the viewport bytes, which match every vertex shader's - // `GlobalInputIndex_ViewportSize` argument. + // SAFETY: Metal copies both values, which match every vertex shader's + // `GlobalInputIndex_ViewportSize` and `GlobalInputIndex_DepthScale` arguments. unsafe { encoder.setVertexBytes_length_atIndex( ptr::NonNull::from(&viewport_size).cast(), mem::size_of_val(&viewport_size), GlobalInputIndex::ViewportSize as usize, ); + encoder.setVertexBytes_length_atIndex( + ptr::NonNull::from(&depth_scale).cast(), + mem::size_of_val(&depth_scale), + GlobalInputIndex::DepthScale as usize, + ); } } @@ -2250,8 +2396,6 @@ fn whole_scissor(viewport_size: Size) -> MTLScissorRect { } } -/// Starts a render pass into `texture`. The pass descriptor retains the texture, so it may be a -/// temporary the caller drops before the encoder ends. /// An encoder on `texture` that keeps nothing it held, for a pass that writes everything it later /// reads. fn new_discarding_command_encoder( @@ -2284,9 +2428,13 @@ fn new_discarding_command_encoder( Ok(command_encoder) } +/// Starts a render pass into `texture`, with a depth attachment only when `depth_texture` is given. +/// The pass descriptor retains the textures, so they may be temporaries the caller drops before +/// the encoder ends. fn new_command_encoder_for_texture( command_buffer: &ProtocolObject, texture: &ProtocolObject, + depth_texture: Option<&ProtocolObject>, viewport_size: Size, clear_color: Option, ) -> Result>> { @@ -2306,6 +2454,15 @@ fn new_command_encoder_for_texture( color_attachment.setLoadAction(MTLLoadAction::Load); } + if let Some(depth_texture) = depth_texture { + let depth_attachment = render_pass_descriptor.depthAttachment(); + depth_attachment.setTexture(Some(depth_texture)); + depth_attachment.setLoadAction(MTLLoadAction::Clear); + depth_attachment.setClearDepth(0.0); + // The depth buffer is only needed within this pass. + depth_attachment.setStoreAction(MTLStoreAction::DontCare); + } + let command_encoder = command_buffer .renderCommandEncoderWithDescriptor(&render_pass_descriptor) .context("creating render command encoder")?; @@ -2466,10 +2623,10 @@ const _: () = { #[repr(C)] pub enum FilterInputIndex { - Backdrops = 1, - ViewportSize = 2, - Params = 3, - Source = 4, + Backdrops = 2, + ViewportSize = 3, + Params = 4, + Source = 5, } fn mask_params(layer: LayerEffect, destination_clip: Bounds) -> MaskParams { @@ -2561,6 +2718,7 @@ fn build_pipeline_state( vertex_fn_name: &str, fragment_fn_name: &str, pixel_format: MTLPixelFormat, + blending: bool, ) -> Result>> { let vertex_fn = library .newFunctionWithName(&NSString::from_str(vertex_fn_name)) @@ -2576,13 +2734,16 @@ fn build_pipeline_state( // SAFETY: Index zero is within the pipeline's color attachment array. let color_attachment = unsafe { descriptor.colorAttachments().objectAtIndexedSubscript(0) }; color_attachment.setPixelFormat(pixel_format); - color_attachment.setBlendingEnabled(true); + color_attachment.setBlendingEnabled(blending); color_attachment.setRgbBlendOperation(MTLBlendOperation::Add); color_attachment.setAlphaBlendOperation(MTLBlendOperation::Add); color_attachment.setSourceRGBBlendFactor(MTLBlendFactor::SourceAlpha); color_attachment.setSourceAlphaBlendFactor(MTLBlendFactor::One); color_attachment.setDestinationRGBBlendFactor(MTLBlendFactor::OneMinusSourceAlpha); color_attachment.setDestinationAlphaBlendFactor(MTLBlendFactor::OneMinusSourceAlpha); + if DEPTH_PREPASS { + descriptor.setDepthAttachmentPixelFormat(MTLPixelFormat::Depth32Float); + } device .newRenderPipelineStateWithDescriptor_error(&descriptor) @@ -2646,6 +2807,18 @@ fn build_custom_pipeline_state( .map_err(|error| anyhow::anyhow!("custom shader `{}`: {error}", program.label)) } +fn build_depth_stencil_state( + device: &ProtocolObject, + write_depth: bool, +) -> Result>> { + let descriptor = MTLDepthStencilDescriptor::new(); + descriptor.setDepthCompareFunction(MTLCompareFunction::Greater); + descriptor.setDepthWriteEnabled(write_depth); + device + .newDepthStencilStateWithDescriptor(&descriptor) + .context("creating depth stencil state") +} + #[derive(Clone)] struct InstanceBinding { buffer: Retained>, @@ -2833,43 +3006,45 @@ impl InstanceBufferWriter { #[repr(C)] enum GlobalInputIndex { ViewportSize = 0, + DepthScale = 1, } #[repr(C)] enum ShadowInputIndex { - Shadows = 1, + Shadows = 2, } #[repr(C)] enum QuadInputIndex { - Quads = 1, + Quads = 2, + QuadCount = 3, } #[repr(C)] enum UnderlineInputIndex { - Underlines = 1, + Underlines = 2, } #[repr(C)] enum SpriteInputIndex { - Sprites = 1, - AtlasTextureSize = 2, - AtlasTexture = 3, + Sprites = 2, + AtlasTextureSize = 3, + AtlasTexture = 4, } #[repr(C)] enum SurfaceInputIndex { - Surfaces = 1, - TextureSize = 2, - YTexture = 3, - CbCrTexture = 4, + Surfaces = 2, + TextureSize = 3, + YTexture = 4, + CbCrTexture = 5, } #[repr(C)] enum PathTileInputIndex { - Tiles = 1, - Curves = 2, - Paints = 3, + Tiles = 2, + Curves = 3, + Paints = 4, } #[derive(Clone, Debug, Eq, PartialEq)] diff --git a/crates/gpui_apple/src/shaders.metal b/crates/gpui_apple/src/shaders.metal index d5b1a6df..71bfe59e 100644 --- a/crates/gpui_apple/src/shaders.metal +++ b/crates/gpui_apple/src/shaders.metal @@ -41,10 +41,6 @@ float quad_sdf(float2 point, Bounds_ScaledPixels bounds, float2 corner_shape(float radius, float smoothing, float2 half_size); float superellipse_sdf(float2 point, float radius, float exponent); float quad_sdf_impl(float2 center_to_point, float corner_radius, float corner_exponent); -float gaussian(float x, float sigma); -float2 erf(float2 x); -float blur_along_x(float x, float y, float sigma, float corner, - float2 half_size); float4 over(float4 below, float4 above); float radians(float degrees); @@ -95,18 +91,39 @@ float pixel_coverage(float2 position, Bounds_ScaledPixels bounds) { return overlap.x * overlap.y; } +constant float4 CULLED_POSITION = float4(0., 0., 0., 1.); + +float quad_depth(uint quad_id, float depth_scale) { + return saturate(float(quad_id + 1u) * depth_scale); +} + +// Opaque rectangles are drawn by the opaque pass instead of the quad pass. The fork draws no +// opaque pass (`DEPTH_PREPASS` in scene.rs), so the quad pass keeps every quad. Upstream's test is +// a solid opaque background with neither rounded corners nor a border. +bool is_opaque_rectangle(Quad quad) { + return false; +} + vertex QuadFragmentInput quad_vertex( uint vertex_id [[vertex_id]], uint quad_id [[instance_id]], constant Quad *quads [[buffer(QuadInputIndex_Quads)]], constant Size_DevicePixels *viewport_size - [[buffer(GlobalInputIndex_ViewportSize)]]) { - float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); + [[buffer(GlobalInputIndex_ViewportSize)]], + constant float *depth_scale [[buffer(GlobalInputIndex_DepthScale)]]) { Quad quad = quads[quad_id]; + if (is_opaque_rectangle(quad)) { + QuadFragmentInput culled = {}; + culled.position = CULLED_POSITION; + return culled; + } + + float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); Bounds_ScaledPixels cover = pixel_cover(quad.bounds); ClippedVertex clipped = clip_to_mask(unit_vertex, cover, quad.content_mask.bounds); float4 device_position = to_device_position_impl(clipped.position, viewport_size); + device_position.z = quad_depth(quad_id, *depth_scale); float4 border_color = hsla_to_rgba(quad.border_color); // A quad off the pixel grid covers its edge pixels only in part, which the fragment weighs. bool on_grid = all(float4(cover.origin.x, cover.origin.y, cover.size.width, cover.size.height) == @@ -414,11 +431,8 @@ fragment float4 quad_fragment(QuadFragmentInput input [[stage_in]], } } - // Blend the border on top of the background and then linearly interpolate - // between the two as we slide inside the background. - float4 blended_border = over(background, border_color); - color = mix(background, blended_border, - saturate(antialias_threshold - inner_sdf)); + border_color.a *= saturate(antialias_threshold - inner_sdf); + color = over(background, border_color); } // The distance field knows nothing of how much of the pixel the quad covers, so a quad @@ -476,12 +490,118 @@ float quarter_ellipse_sdf(float2 point, float2 radii) { return unit_circle_sdf * (radii.x + radii.y) * -0.5; } +struct OpaqueQuadFragmentInput { + float4 position [[position]]; + float4 color [[flat]]; +}; + +vertex OpaqueQuadFragmentInput opaque_quad_vertex( + uint vertex_id [[vertex_id]], uint instance_id [[instance_id]], + constant Quad *quads [[buffer(QuadInputIndex_Quads)]], + constant uint *quad_count [[buffer(QuadInputIndex_QuadCount)]], + constant Size_DevicePixels *viewport_size + [[buffer(GlobalInputIndex_ViewportSize)]], + constant float *depth_scale [[buffer(GlobalInputIndex_DepthScale)]]) { + uint quad_id = *quad_count - 1u - instance_id; + Quad quad = quads[quad_id]; + if (!is_opaque_rectangle(quad)) { + return OpaqueQuadFragmentInput{CULLED_POSITION, float4(0.)}; + } + + float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); + ClippedVertex clipped = + clip_to_mask(unit_vertex, quad.bounds, quad.content_mask.bounds); + float4 device_position = + to_device_position_impl(clipped.position, viewport_size); + device_position.z = quad_depth(quad_id, *depth_scale); + return OpaqueQuadFragmentInput{device_position, + hsla_to_rgba(quad.background.solid)}; +} + +fragment float4 opaque_quad_fragment(OpaqueQuadFragmentInput input + [[stage_in]]) { + return input.color; +} + +struct PreparedBlurredRoundedRect { + float4 shape; + float4 r1; + float4 exponent; + float4 scale; +}; + struct ShadowFragmentInput { float4 position [[position]]; float4 color [[flat]]; uint shadow_id [[flat]]; + float4 blur_shape [[flat]]; + float4 blur_r1 [[flat]]; + float4 blur_exponent [[flat]]; + float4 blur_scale [[flat]]; }; +float erf7(float x) { + x = clamp(x, -10., 10.) * (2. / sqrt(M_PI_F)); + float xx = x * x; + x = x + (0.24295 + (0.03395 + 0.0104 * xx) * xx) * (x * xx); + return x / sqrt(1. + x * x); +} + +// Raph Levien's blurred rounded rectangle approximation, whose blur s is sigma * sqrt(2): +// https://raphlinus.github.io/graphics/2020/04/21/blurred-rounded-rects.html +PreparedBlurredRoundedRect prepare_blurred_rounded_rect(float2 size, Corners_ScaledPixels corner_radii, float sigma) { + float min_edge = min(size.x, size.y); + if (min_edge <= 0.) { + return PreparedBlurredRoundedRect{ + float4(0.), float4(0.), float4(2.), float4(0.)}; + } + float s = max(sigma * sqrt(2.), 1e-6); + float s_inv = 1. / s; + float r_max = 0.5 * min_edge; + float4 radii = float4(corner_radii.top_left, corner_radii.top_right, + corner_radii.bottom_right, corner_radii.bottom_left); + float4 r0 = min(sqrt(radii * radii + 1.15 * 1.15 * s * s), r_max); + float4 r1 = min(sqrt(radii * radii + 4. * s * s), r_max); + + float2 half_extent = 0.5 * s_inv * size; + float delta = 1.25 * s * (exp(-half_extent.x * half_extent.x) - exp(-half_extent.y * half_extent.y)); + float2 adjusted_size = float2(size.x + min(delta, 0.), size.y - max(delta, 0.)); + float4 peak = s_inv * 0.5 * (max(adjusted_size.x, adjusted_size.y) - 0.5 * radii); + + PreparedBlurredRoundedRect output; + output.shape = float4(0.5 * adjusted_size, s_inv, min_edge); + output.r1 = r1; + output.exponent = 2. * r1 / r0; + output.scale = 0.5 * float4(erf7(peak.x), erf7(peak.y), erf7(peak.z), erf7(peak.w)); + return output; +} + +float pick_corner(float2 center_to_point, float4 values) { + Corners_ScaledPixels corners = {values.x, values.y, values.z, values.w}; + return pick_corner_radius(center_to_point, corners); +} + +float blurred_rounded_rect(float2 center_to_point, PreparedBlurredRoundedRect prepared) { + float r1 = pick_corner(center_to_point, prepared.r1); + float exponent = pick_corner(center_to_point, prepared.exponent); + float scale = pick_corner(center_to_point, prepared.scale); + float s_inv = prepared.shape.z; + float min_edge = prepared.shape.w; + + float2 p0 = abs(center_to_point) - (prepared.shape.xy - r1); + float2 p1 = max(p0, 0.); + float d_pos; + if (p1.x > 0. && p1.y > 0.) { + d_pos = pow(pow(p1.x, exponent) + pow(p1.y, exponent), 1. / exponent); + } else { + d_pos = p1.x + p1.y; + } + + float d_neg = min(max(p0.x, p0.y), 0.); + float d = d_pos + d_neg - r1; + return scale * (erf7(s_inv * (min_edge + d)) - erf7(s_inv * d)); +} + vertex ShadowFragmentInput shadow_vertex( uint vertex_id [[vertex_id]], uint shadow_id [[instance_id]], constant Shadow *shadows [[buffer(ShadowInputIndex_Shadows)]], @@ -495,11 +615,18 @@ vertex ShadowFragmentInput shadow_vertex( float4 device_position = to_device_position_impl(clipped.position, viewport_size); float4 color = hsla_to_rgba(shadow.color); + PreparedBlurredRoundedRect blur = prepare_blurred_rounded_rect( + float2(shadow.shape_bounds.size.width, shadow.shape_bounds.size.height), + shadow.shape_corner_radii, shadow.blur_radius); return ShadowFragmentInput{ device_position, color, - shadow_id}; + shadow_id, + blur.shape, + blur.r1, + blur.exponent, + blur.scale}; } fragment float4 shadow_fragment(ShadowFragmentInput input [[stage_in]], @@ -507,48 +634,20 @@ fragment float4 shadow_fragment(ShadowFragmentInput input [[stage_in]], [[buffer(ShadowInputIndex_Shadows)]]) { Shadow shadow = shadows[input.shadow_id]; - float2 origin = float2(shadow.shape_bounds.origin.x, shadow.shape_bounds.origin.y); - float2 size = float2(shadow.shape_bounds.size.width, shadow.shape_bounds.size.height); - float2 half_size = size / 2.; - float2 center = origin + half_size; - float2 point = input.position.xy - center; - float corner_radius; - if (point.x < 0.) { - if (point.y < 0.) { - corner_radius = shadow.shape_corner_radii.top_left; - } else { - corner_radius = shadow.shape_corner_radii.bottom_left; - } - } else { - if (point.y < 0.) { - corner_radius = shadow.shape_corner_radii.top_right; - } else { - corner_radius = shadow.shape_corner_radii.bottom_right; - } - } - float alpha; - if (shadow.blur_radius == 0.) { + if (shadow.shape_bounds.size.width <= 0. || shadow.shape_bounds.size.height <= 0.) { + alpha = 0.; + } else if (shadow.blur_radius == 0.) { float distance = quad_sdf(input.position.xy, shadow.shape_bounds, shadow.shape_corner_radii, 0.0); alpha = saturate(0.5 - distance); } else { - // The signal is only non-zero in a limited range, so don't waste samples - float low = point.y - half_size.y; - float high = point.y + half_size.y; - float start = clamp(-3. * shadow.blur_radius, low, high); - float end = clamp(3. * shadow.blur_radius, low, high); - - // Accumulate samples (we can get away with surprisingly few samples) - float step = (end - start) / 4.; - float y = start + step * 0.5; - alpha = 0.; - for (int i = 0; i < 4; i++) { - alpha += blur_along_x(point.x, point.y - y, shadow.blur_radius, - corner_radius, half_size) * - gaussian(y, shadow.blur_radius) * step; - y += step; - } + float2 origin = float2(shadow.shape_bounds.origin.x, shadow.shape_bounds.origin.y); + float2 size = float2(shadow.shape_bounds.size.width, shadow.shape_bounds.size.height); + float2 center = origin + size / 2.; + PreparedBlurredRoundedRect blur = {input.blur_shape, input.blur_r1, + input.blur_exponent, input.blur_scale}; + alpha = blurred_rounded_rect(input.position.xy - center, blur); } if (shadow.inset != 0u) { @@ -1154,30 +1253,6 @@ float quad_sdf_impl(float2 corner_center_to_point, float corner_radius, float co } } -// A standard gaussian function, used for weighting samples -float gaussian(float x, float sigma) { - return exp(-(x * x) / (2. * sigma * sigma)) / (sqrt(2. * M_PI_F) * sigma); -} - -// This approximates the error function, needed for the gaussian integral -float2 erf(float2 x) { - float2 s = sign(x); - float2 a = abs(x); - float2 r1 = 1. + (0.278393 + (0.230389 + (0.000972 + 0.078108 * a) * a) * a) * a; - float2 r2 = r1 * r1; - return s - s / (r2 * r2); -} - -float blur_along_x(float x, float y, float sigma, float corner, - float2 half_size) { - float delta = min(half_size.y - corner - abs(y), 0.); - float curved = - half_size.x - corner + sqrt(max(0., corner * corner - delta * delta)); - float2 integral = - 0.5 + 0.5 * erf((x + float2(-curved, curved)) * (sqrt(0.5) / sigma)); - return integral.y - integral.x; -} - ClippedVertex clip_to_mask(float2 unit_vertex, Bounds_ScaledPixels bounds, Bounds_ScaledPixels mask) { float2 bounds_origin = float2(bounds.origin.x, bounds.origin.y); @@ -1212,12 +1287,10 @@ float4 distance_from_clip_rect_transformed(float2 unit_vertex, Bounds_ScaledPixe } float4 over(float4 below, float4 above) { - float4 result; float alpha = above.a + below.a * (1.0 - above.a); - result.rgb = - (above.rgb * above.a + below.rgb * below.a * (1.0 - above.a)) / alpha; - result.a = alpha; - return result; + float3 premultiplied = + above.rgb * above.a + below.rgb * below.a * (1.0 - above.a); + return float4(premultiplied / (alpha == 0.0 ? 1.0 : alpha), alpha); } PreparedBackground prepare_background(Background background) { diff --git a/crates/gpui_linux/src/linux/platform.rs b/crates/gpui_linux/src/linux/platform.rs index 2ec3f361..dd0f2d6b 100644 --- a/crates/gpui_linux/src/linux/platform.rs +++ b/crates/gpui_linux/src/linux/platform.rs @@ -1009,8 +1009,9 @@ impl Platform for LinuxPlatform { }); } - fn dismiss_system_notification(&self, tag: &str) { + fn dismiss_system_notification(&self, tag: &str) -> Task<()> { self.with_common(|common| common.system_notifications.dismiss(tag)); + Task::ready(()) } fn on_system_notification_response( diff --git a/crates/gpui_linux/src/linux/x11/clipboard.rs b/crates/gpui_linux/src/linux/x11/clipboard.rs index 9835786e..ef6976e8 100644 --- a/crates/gpui_linux/src/linux/x11/clipboard.rs +++ b/crates/gpui_linux/src/linux/x11/clipboard.rs @@ -12,7 +12,7 @@ * The project to which this file belongs is licensed under either of * the Apache 2.0 or the MIT license at the licensee's choice. The terms * and conditions of the chosen license apply to this file. -*/ + */ // More info about using the clipboard on X11: // https://tronche.com/gui/x/icccm/sec-2.html#s-2.6 diff --git a/crates/gpui_macos/src/platform.rs b/crates/gpui_macos/src/platform.rs index 8bf73f14..4d3927f7 100644 --- a/crates/gpui_macos/src/platform.rs +++ b/crates/gpui_macos/src/platform.rs @@ -2,6 +2,7 @@ use crate::{ AppleActivity, AppleDispatcher, BoolExt, MacDisplay, MacKeyboardLayout, MacKeyboardMapper, MacWindow, events::key_to_menu_equivalent, main_thread_marker, ns_string, pasteboard::Pasteboard, renderer, set_active_window_cursor_style, + system_notifications::NotificationCommand, }; use anyhow::{Context as _, anyhow}; use block2::RcBlock; @@ -1128,14 +1129,27 @@ impl Platform for MacPlatform { fn show_system_notification(&self, notification: gpui::SystemNotification) { let mut state = self.0.lock(); - let executor = state.foreground_executor.clone(); - state.system_notifications.show(&executor, notification); + let foreground_executor = state.foreground_executor.clone(); + let background_executor = state.background_executor.clone(); + state + .system_notifications + .send( + &foreground_executor, + &background_executor, + NotificationCommand::Show(notification), + ) + .detach(); } - fn dismiss_system_notification(&self, tag: &str) { + fn dismiss_system_notification(&self, tag: &str) -> Task<()> { let mut state = self.0.lock(); - let executor = state.foreground_executor.clone(); - state.system_notifications.dismiss(&executor, tag); + let foreground_executor = state.foreground_executor.clone(); + let background_executor = state.background_executor.clone(); + state.system_notifications.send( + &foreground_executor, + &background_executor, + NotificationCommand::Dismiss(gpui::SharedString::from(tag.to_owned())), + ) } fn on_system_notification_response( diff --git a/crates/gpui_macos/src/system_notifications.rs b/crates/gpui_macos/src/system_notifications.rs index 4bfd9522..8c1df527 100644 --- a/crates/gpui_macos/src/system_notifications.rs +++ b/crates/gpui_macos/src/system_notifications.rs @@ -4,19 +4,24 @@ //! so nothing can trigger the authorization prompt or the framework's //! not-in-a-bundle abort) until the application posts a notification or //! registers a response callback. +//! +//! Notification-center calls can synchronously wait for the macOS service. +//! A single worker owns the center so those waits never block the UI, while +//! preserving the order of posting and dismissing notifications. -use std::cell::{Cell, RefCell}; +use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; +use std::sync::mpsc::{Sender, channel}; use block2::RcBlock; use futures::StreamExt as _; -use futures::channel::mpsc; +use futures::channel::{mpsc, oneshot}; use gpui::{ - ForegroundExecutor, SharedString, SystemNotification, SystemNotificationAction, - SystemNotificationResponse, Task, + BackgroundExecutor, ForegroundExecutor, SharedString, SystemNotification, + SystemNotificationAction, SystemNotificationResponse, Task, }; -use objc2::rc::Retained; +use objc2::rc::{Retained, autoreleasepool}; use objc2::runtime::{Bool, ProtocolObject}; use objc2::{AnyThread, DefinedClass, define_class, msg_send}; use objc2_foundation::{NSArray, NSBundle, NSError, NSObject, NSObjectProtocol, NSSet, NSString}; @@ -30,10 +35,19 @@ use objc2_user_notifications::{ type ResponseCallback = Rc>>>; +#[cfg_attr(test, derive(Debug, PartialEq, Eq))] +pub(crate) enum NotificationCommand { + Show(SystemNotification), + Dismiss(SharedString), +} + pub(crate) struct SystemNotificationState { initialized: bool, - center: Option, + commands: Option)>>, callback: ResponseCallback, + /// The center's `delegate` property is weak; keeping the delegate retained + /// here keeps response handling alive for the app's lifetime. + _delegate: Option>, _response_task: Option>, } @@ -41,24 +55,35 @@ impl SystemNotificationState { pub(crate) fn new() -> Self { Self { initialized: false, - center: None, + commands: None, callback: Rc::new(RefCell::new(None)), + _delegate: None, _response_task: None, } } - pub(crate) fn show(&mut self, executor: &ForegroundExecutor, notification: SystemNotification) { - self.initialize(executor); - if let Some(center) = &self.center { - center.show(notification); - } - } - - pub(crate) fn dismiss(&mut self, executor: &ForegroundExecutor, tag: &str) { - self.initialize(executor); - if let Some(center) = &self.center { - center.dismiss(tag); + pub(crate) fn send( + &mut self, + foreground_executor: &ForegroundExecutor, + background_executor: &BackgroundExecutor, + command: NotificationCommand, + ) -> Task<()> { + self.initialize(foreground_executor); + let Some(commands) = &self.commands else { + return Task::ready(()); + }; + let (completed, completion) = oneshot::channel(); + if let Err(error) = commands.send((command, completed)) { + log::error!("system notification worker disconnected: {error}"); + return Task::ready(()); } + background_executor.spawn(async move { + if let Err(error) = completion.await { + log::error!( + "system notification worker stopped before completing a command: {error}" + ); + } + }) } pub(crate) fn on_response( @@ -76,11 +101,45 @@ impl SystemNotificationState { } self.initialized = true; + // UserNotifications aborts outside an app bundle. Checking the bundle + // does not contact the notification service. + if NSBundle::mainBundle().bundleIdentifier().is_none() { + log::info!("system notifications disabled: not running from an app bundle"); + return; + } + let (sender, mut receiver) = mpsc::unbounded(); - self.center = NotificationCenter::new(sender); - if self.center.is_none() { + // Install the delegate before returning so a response delivered right + // after registration (e.g. the click that launched the app) has + // somewhere to go. Setting the delegate doesn't wait on the + // notification service, unlike the calls handled by the worker. + let delegate = autoreleasepool(|_| { + let delegate = NotificationResponseDelegate::new(sender); + UNUserNotificationCenter::currentNotificationCenter() + .setDelegate(Some(ProtocolObject::from_ref(&*delegate))); + delegate + }); + self._delegate = Some(delegate); + + let (commands, pending_commands) = channel::<(NotificationCommand, oneshot::Sender<()>)>(); + let worker = std::thread::Builder::new() + .name("system-notifications".into()) + .spawn(move || { + let mut center = autoreleasepool(|_| NotificationCenter::new()); + for (command, completed) in pending_commands { + autoreleasepool(|_| match command { + NotificationCommand::Show(notification) => center.show(notification), + NotificationCommand::Dismiss(tag) => center.dismiss(&tag), + }); + // The caller may stop waiting without cancelling the operation. + _ = completed.send(()); + } + }); + if let Err(error) = worker { + log::error!("failed to start system notification worker: {error}"); return; } + self.commands = Some(commands); // Responses arrive from the delegate on an arbitrary thread; this task // hands them to the registered callback on the main thread. @@ -102,46 +161,28 @@ impl SystemNotificationState { struct NotificationCenter { center: Retained, - /// The center's `delegate` property is weak; keeping the delegate retained - /// here keeps response handling alive for the app's lifetime. - _delegate: Retained, /// The union of every action set registered so far. Categories are shared /// by notifications with identical actions because macOS replaces the /// entire registered set whenever a category is added. - categories: RefCell< + categories: HashMap, (SharedString, Retained)>, - >, - authorization_requested: Cell, + authorization_requested: bool, } impl NotificationCenter { - fn new(sender: mpsc::UnboundedSender) -> Option { - // `UNUserNotificationCenter` raises `NSInternalInconsistencyException` - // ("bundleProxyForCurrentProcess is nil"), aborting the process, when - // the binary isn't part of an app bundle — which is how dev builds run - // via `cargo run`. A bundle identifier is only present when launched - // from a real `.app`, so use it as the guard. - if NSBundle::mainBundle().bundleIdentifier().is_none() { - log::info!("system notifications disabled: not running from an app bundle"); - return None; + fn new() -> Self { + Self { + center: UNUserNotificationCenter::currentNotificationCenter(), + categories: HashMap::new(), + authorization_requested: false, } - - let center = UNUserNotificationCenter::currentNotificationCenter(); - let delegate = NotificationResponseDelegate::new(sender); - center.setDelegate(Some(ProtocolObject::from_ref(&*delegate))); - - Some(Self { - center, - _delegate: delegate, - categories: RefCell::new(HashMap::new()), - authorization_requested: Cell::new(false), - }) } - fn request_authorization(&self) { - if self.authorization_requested.replace(true) { + fn request_authorization(&mut self) { + if self.authorization_requested { return; } + self.authorization_requested = true; let completion = RcBlock::new(|granted: Bool, error: *mut NSError| { // SAFETY: when non-null, `error` is a valid `NSError` for the // duration of the callback. @@ -161,7 +202,7 @@ impl NotificationCenter { ); } - fn show(&self, notification: SystemNotification) { + fn show(&mut self, notification: SystemNotification) { self.request_authorization(); let content = UNMutableNotificationContent::new(); @@ -194,14 +235,15 @@ impl NotificationCenter { .addNotificationRequest_withCompletionHandler(&request, Some(&completion)); } - fn register_category(&self, actions: &[SystemNotificationAction]) -> SharedString { - let mut categories = self.categories.borrow_mut(); - if let Some((identifier, _category)) = categories.get(actions) { + fn register_category(&mut self, actions: &[SystemNotificationAction]) -> SharedString { + if let Some((identifier, _category)) = self.categories.get(actions) { return identifier.clone(); } - let identifier = - SharedString::from(format!("gpui-system-notification-{}", categories.len())); + let identifier = SharedString::from(format!( + "gpui-system-notification-{}", + self.categories.len() + )); let platform_actions: Vec> = actions .iter() .map(|action| { @@ -220,8 +262,10 @@ impl NotificationCenter { UNNotificationCategoryOptions::empty(), ); - categories.insert(actions.to_vec(), (identifier.clone(), category)); - let all: Vec> = categories + self.categories + .insert(actions.to_vec(), (identifier.clone(), category)); + let all: Vec> = self + .categories .values() .map(|(_identifier, category)| category.clone()) .collect(); @@ -307,3 +351,65 @@ impl NotificationResponseDelegate { unsafe { msg_send![super(this), init] } } } + +#[cfg(test)] +mod tests { + use super::*; + use futures::FutureExt as _; + + #[gpui::test] + async fn test_notification_commands_do_not_wait_for_the_service(cx: &mut gpui::TestAppContext) { + let (sender, receiver) = channel(); + let mut state = SystemNotificationState { + initialized: true, + commands: Some(sender), + ..SystemNotificationState::new() + }; + let notification = SystemNotification { + tag: "thread".into(), + title: "Finished".into(), + body: "Ready for input".into(), + actions: vec![], + }; + + // No service consumes commands until after every UI call has returned. + let mut tasks = [ + state.send( + &cx.foreground_executor, + &cx.background_executor, + NotificationCommand::Show(notification.clone()), + ), + state.send( + &cx.foreground_executor, + &cx.background_executor, + NotificationCommand::Dismiss("thread".into()), + ), + state.send( + &cx.foreground_executor, + &cx.background_executor, + NotificationCommand::Show(notification.clone()), + ), + ]; + for task in &mut tasks { + assert!(task.now_or_never().is_none()); + } + + let (commands, completions): (Vec<_>, Vec<_>) = receiver.try_iter().unzip(); + assert_eq!( + commands, + vec![ + NotificationCommand::Show(notification.clone()), + NotificationCommand::Dismiss("thread".into()), + NotificationCommand::Show(notification), + ] + ); + for completed in completions { + completed + .send(()) + .expect("caller is waiting for completion"); + } + for task in tasks { + task.await; + } + } +} diff --git a/crates/gpui_platform/benches/atlas_upload.rs b/crates/gpui_platform/benches/atlas_upload.rs index 8ede1a5b..9ad76e2b 100644 --- a/crates/gpui_platform/benches/atlas_upload.rs +++ b/crates/gpui_platform/benches/atlas_upload.rs @@ -224,7 +224,7 @@ fn tile_scene(tile: AtlasTile) -> Scene { match tile.texture_id.kind { AtlasTextureKind::Monochrome => scene.insert_primitive(MonochromeSprite { order: 0, - pad: 0, + animation: gpui::SpriteAnimationId::NONE, tile, bounds, content_mask, diff --git a/crates/gpui_platform/benches/primitives.rs b/crates/gpui_platform/benches/primitives.rs index a451dbc5..60f296db 100644 --- a/crates/gpui_platform/benches/primitives.rs +++ b/crates/gpui_platform/benches/primitives.rs @@ -297,6 +297,11 @@ fn scene_content_mask() -> ContentMask { } fn build_scene(scene: &mut Scene, rectangles: &[Rectangle]) { + insert_primitives(scene, rectangles); + scene.finish(); +} + +fn insert_primitives(scene: &mut Scene, rectangles: &[Rectangle]) { scene.clear(); let content_mask = scene_content_mask().scale(1.); for (index, rectangle) in rectangles.iter().enumerate() { @@ -345,7 +350,7 @@ fn build_scene(scene: &mut Scene, rectangles: &[Rectangle]) { + point(glyph_size * (glyph as f32 * 0.6), gpui::ScaledPixels(0.)); scene.insert_primitive(gpui::MonochromeSprite { order: 0, - pad: 0, + animation: gpui::SpriteAnimationId::NONE, tile: glyph_tile(index + glyph), bounds: Bounds::new(origin, size(glyph_size * 0.6, glyph_size)), content_mask, @@ -356,7 +361,26 @@ fn build_scene(scene: &mut Scene, rectangles: &[Rectangle]) { } } } - scene.finish(); +} + +fn scene_finish(criterion: &mut criterion::Criterion) { + let mut group = criterion.benchmark_group("Primitives/finish"); + for case in cases() { + let mut fixture = None; + group.bench_function(case.to_string(), |bencher| { + let rectangles = fixture.get_or_insert_with(|| rectangles(&case, 512.)); + bencher.iter_batched_ref( + || { + let mut scene = Scene::default(); + insert_primitives(&mut scene, rectangles); + scene + }, + |scene| scene.finish(), + criterion::BatchSize::LargeInput, + ); + }); + } + group.finish(); } fn scene_ordering(criterion: &mut criterion::Criterion) { @@ -419,6 +443,6 @@ gpui::bench_group!( .warm_up_time(Duration::from_millis(500)) .measurement_time(Duration::from_secs(1)) .sample_size(20); - targets = paint_rectangles, scene_ordering + targets = paint_rectangles, scene_ordering, scene_finish ); gpui::bench_main!(benches); diff --git a/crates/gpui_wgpu/Cargo.toml b/crates/gpui_wgpu/Cargo.toml index df665c6b..877c7300 100644 --- a/crates/gpui_wgpu/Cargo.toml +++ b/crates/gpui_wgpu/Cargo.toml @@ -49,6 +49,7 @@ wgpu = { workspace = true, features = ["std", "metal", "gles", "vulkan", "wgsl", wgpu = { workspace = true, default-features = true } [target.'cfg(target_family = "wasm")'.dependencies] +js-sys.workspace = true web-sys = { workspace = true, features = ["HtmlCanvasElement"] } wgpu = { workspace = true, features = ["webgl"] } diff --git a/crates/gpui_wgpu/src/cosmic_text_system.rs b/crates/gpui_wgpu/src/cosmic_text_system.rs index 8ccb3031..7034253f 100644 --- a/crates/gpui_wgpu/src/cosmic_text_system.rs +++ b/crates/gpui_wgpu/src/cosmic_text_system.rs @@ -424,7 +424,7 @@ impl CosmicTextSystemState { let loaded = self.load_family(fallback_name, features, None, weight, true)?; self.fallback_ids_by_family_cache - .insert(fb_key.clone(), loaded.clone()); + .insert(fb_key, loaded.clone()); loaded }; // a family can hold several static weights, so match the requested diff --git a/crates/gpui_wgpu/src/shaders.wgsl b/crates/gpui_wgpu/src/shaders.wgsl index 064198cf..577b8a30 100644 --- a/crates/gpui_wgpu/src/shaders.wgsl +++ b/crates/gpui_wgpu/src/shaders.wgsl @@ -81,10 +81,12 @@ struct GlobalParams { viewport_size: vec2, path_paint_base: u32, path_curve_base: u32, + depth_scale: f32, + quad_count: u32, + premultiplied_alpha: u32, + pad: u32, } -override PREMULTIPLIED_ALPHA: bool = false; - struct GammaParams { gamma_ratios: vec4, grayscale_enhanced_contrast: f32, @@ -350,29 +352,8 @@ fn oklab_to_linear_srgb(color: vec4) -> vec4 { fn over(below: vec4, above: vec4) -> vec4 { let alpha = above.a + below.a * (1.0 - above.a); - let color = (above.rgb * above.a + below.rgb * below.a * (1.0 - above.a)) / alpha; - return vec4(color, alpha); -} - -// A standard gaussian function, used for weighting samples -fn gaussian(x: f32, sigma: f32) -> f32{ - return exp(-(x * x) / (2.0 * sigma * sigma)) / (sqrt(2.0 * M_PI_F) * sigma); -} - -// This approximates the error function, needed for the gaussian integral -fn erf(v: vec2) -> vec2 { - let s = sign(v); - let a = abs(v); - let r1 = 1.0 + (0.278393 + (0.230389 + (0.000972 + 0.078108 * a) * a) * a) * a; - let r2 = r1 * r1; - return s - s / (r2 * r2); -} - -fn blur_along_x(x: f32, y: f32, sigma: f32, corner: f32, half_size: vec2) -> f32 { - let delta = min(half_size.y - corner - abs(y), 0.0); - let curved = half_size.x - corner + sqrt(max(0.0, corner * corner - delta * delta)); - let integral = 0.5 + 0.5 * erf((x + vec2(-curved, curved)) * (sqrt(0.5) / sigma)); - return integral.y - integral.x; + let premultiplied = above.rgb * above.a + below.rgb * below.a * (1.0 - above.a); + return vec4(premultiplied / select(alpha, 1.0, alpha == 0.0), alpha); } // Selects corner radius based on quadrant. @@ -454,7 +435,7 @@ fn superellipse_sdf(point: vec2, radius: f32, exponent: f32) -> f32 { // target alpha compositing mode. fn blend_color(color: vec4, alpha_factor: f32) -> vec4 { let alpha = color.a * alpha_factor; - let multiplier = select(1.0, alpha, PREMULTIPLIED_ALPHA); + let multiplier = select(1.0, alpha, globals.premultiplied_alpha != 0u); return vec4(color.rgb * multiplier, alpha); } @@ -614,6 +595,19 @@ fn is_shaped(quad: Quad) -> bool { return has_rounded_corners(quad.corner_radii) || has_border(quad.border_widths); } +const CULLED_POSITION: vec4 = vec4(0.0, 0.0, 0.0, 1.0); + +fn quad_depth(quad_id: u32) -> f32 { + return saturate(f32(quad_id + 1u) * globals.depth_scale); +} + +// Opaque rectangles are drawn by the opaque pass instead of the quad pass. The fork draws no +// opaque pass (`DEPTH_PREPASS` in scene.rs), so the quad pass keeps every quad. Upstream's test is +// a solid opaque background with neither rounded corners nor a border. +fn is_opaque_rectangle(quad: Quad) -> bool { + return false; +} + struct QuadVarying { @builtin(position) position: vec4, @location(0) @interpolate(flat) border_color: vec4, @@ -626,13 +620,19 @@ struct QuadVarying { @vertex fn vs_quad(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> QuadVarying { - let unit_vertex = vec2(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u)); let quad = load_quad(instance_id); let cover = pixel_cover(quad.bounds); var out = QuadVarying(); + if (is_opaque_rectangle(quad)) { + out.position = CULLED_POSITION; + return out; + } + + let unit_vertex = vec2(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u)); let clipped = clip_to_mask(unit_vertex, cover, quad.content_mask); out.position = to_device_position_impl(clipped.position); + out.position.z = quad_depth(instance_id); out.border_color = hsla_to_rgba(quad.border_color); // A quad off the pixel grid partly covers the pixels its edges fall through, so only one on @@ -964,11 +964,8 @@ fn fs_quad(input: QuadVarying) -> @location(0) vec4 { } } - // Blend the border on top of the background and then linearly interpolate - // between the two as we slide inside the background. - let blended_border = over(background, border_color); - color = mix(background, blended_border, - saturate(antialias_threshold - inner_sdf)); + border_color.a *= saturate(antialias_threshold - inner_sdf); + color = over(background, border_color); } // The distance field knows nothing of how much of the pixel the quad covers, so a quad @@ -1029,6 +1026,37 @@ fn fmod(a: f32, b: f32) -> f32 { return a - b * trunc(a / b); } +// --- opaque quads --- // + +struct OpaqueQuadVarying { + @builtin(position) position: vec4, + @location(0) @interpolate(flat) color: vec4, +} + +@vertex +fn vs_opaque_quad(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> OpaqueQuadVarying { + let quad_id = globals.quad_count - 1u - instance_id; + let quad = load_quad(quad_id); + + var out = OpaqueQuadVarying(); + if (!is_opaque_rectangle(quad)) { + out.position = CULLED_POSITION; + return out; + } + + let unit_vertex = vec2(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u)); + let clipped = clip_to_mask(unit_vertex, quad.bounds, quad.content_mask); + out.position = to_device_position_impl(clipped.position); + out.position.z = quad_depth(quad_id); + out.color = blend_color(hsla_to_rgba(quad.background.solid), 1.0); + return out; +} + +@fragment +fn fs_opaque_quad(input: OpaqueQuadVarying) -> @location(0) vec4 { + return input.color; +} + // --- shadows --- // struct Shadow { @@ -1057,6 +1085,82 @@ struct ShadowVarying { @builtin(position) position: vec4, @location(0) @interpolate(flat) color: vec4, @location(1) @interpolate(flat) shadow_id: u32, + @location(2) @interpolate(flat) blur_shape: vec4, + @location(3) @interpolate(flat) blur_r1: vec4, + @location(4) @interpolate(flat) blur_exponent: vec4, + @location(5) @interpolate(flat) blur_scale: vec4, +} + +struct PreparedBlurredRoundedRect { + shape: vec4, + r1: vec4, + exponent: vec4, + scale: vec4, +} + +fn erf7(input: f32) -> f32 { + let x = clamp(input, -10.0, 10.0) * (2.0 / sqrt(M_PI_F)); + let xx = x * x; + let y = x + (0.24295 + (0.03395 + 0.0104 * xx) * xx) * (x * xx); + return y / sqrt(1.0 + y * y); +} + +// Raph Levien's blurred rounded rectangle approximation, whose blur s is sigma * sqrt(2): +// https://raphlinus.github.io/graphics/2020/04/21/blurred-rounded-rects.html +fn prepare_blurred_rounded_rect(size: vec2, corner_radii: Corners, sigma: f32) -> PreparedBlurredRoundedRect { + let min_edge = min(size.x, size.y); + if (min_edge <= 0.0) { + var empty: PreparedBlurredRoundedRect; + empty.shape = vec4(0.0); + empty.r1 = vec4(0.0); + empty.exponent = vec4(2.0); + empty.scale = vec4(0.0); + return empty; + } + let s = max(sigma * sqrt(2.0), 1e-6); + let s_inv = 1.0 / s; + let r_max = 0.5 * min_edge; + let radii = vec4(corner_radii.top_left, corner_radii.top_right, + corner_radii.bottom_right, corner_radii.bottom_left); + let r0 = min(sqrt(radii * radii + 1.15 * 1.15 * s * s), vec4(r_max)); + let r1 = min(sqrt(radii * radii + 4.0 * s * s), vec4(r_max)); + + let half_extent = 0.5 * s_inv * size; + let delta = 1.25 * s * (exp(-half_extent.x * half_extent.x) - exp(-half_extent.y * half_extent.y)); + let adjusted_size = vec2(size.x + min(delta, 0.0), size.y - max(delta, 0.0)); + let peak = s_inv * 0.5 * (max(adjusted_size.x, adjusted_size.y) - 0.5 * radii); + + var output: PreparedBlurredRoundedRect; + output.shape = vec4(0.5 * adjusted_size, s_inv, min_edge); + output.r1 = r1; + output.exponent = 2.0 * r1 / r0; + output.scale = 0.5 * vec4(erf7(peak.x), erf7(peak.y), erf7(peak.z), erf7(peak.w)); + return output; +} + +fn pick_corner(center_to_point: vec2, values: vec4) -> f32 { + return pick_corner_radius(center_to_point, Corners(values.x, values.y, values.z, values.w)); +} + +fn blurred_rounded_rect(center_to_point: vec2, prepared: PreparedBlurredRoundedRect) -> f32 { + let r1 = pick_corner(center_to_point, prepared.r1); + let exponent = pick_corner(center_to_point, prepared.exponent); + let scale = pick_corner(center_to_point, prepared.scale); + let s_inv = prepared.shape.z; + let min_edge = prepared.shape.w; + + let p0 = abs(center_to_point) - (prepared.shape.xy - r1); + let p1 = max(p0, vec2(0.0)); + var d_pos: f32; + if (p1.x > 0.0 && p1.y > 0.0) { + d_pos = pow(pow(p1.x, exponent) + pow(p1.y, exponent), 1.0 / exponent); + } else { + d_pos = p1.x + p1.y; + } + + let d_neg = min(max(p0.x, p0.y), 0.0); + let d = d_pos + d_neg - r1; + return scale * (erf7(s_inv * (min_edge + d)) - erf7(s_inv * d)); } @vertex @@ -1069,40 +1173,31 @@ fn vs_shadow(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) ins out.position = to_device_position_impl(clipped.position); out.color = hsla_to_rgba(shadow.color); out.shadow_id = instance_id; + let blur = prepare_blurred_rounded_rect(shadow.shape_bounds.size, shadow.shape_corner_radii, + shadow.blur_radius); + out.blur_shape = blur.shape; + out.blur_r1 = blur.r1; + out.blur_exponent = blur.exponent; + out.blur_scale = blur.scale; return out; } @fragment fn fs_shadow(input: ShadowVarying) -> @location(0) vec4 { let shadow = load_shadow(input.shadow_id); - let half_size = shadow.shape_bounds.size / 2.0; - let center = shadow.shape_bounds.origin + half_size; - let center_to_point = input.position.xy - center; - - let corner_radius = pick_corner_radius(center_to_point, shadow.shape_corner_radii); var alpha: f32; - if (shadow.blur_radius == 0.0) { + if (shadow.shape_bounds.size.x <= 0.0 || shadow.shape_bounds.size.y <= 0.0) { + alpha = 0.0; + } else if (shadow.blur_radius == 0.0) { let distance = quad_sdf(input.position.xy, shadow.shape_bounds, shadow.shape_corner_radii, 0.0); alpha = saturate(0.5 - distance); } else { - // The signal is only non-zero in a limited range, so don't waste samples - let low = center_to_point.y - half_size.y; - let high = center_to_point.y + half_size.y; - let start = clamp(-3.0 * shadow.blur_radius, low, high); - let end = clamp(3.0 * shadow.blur_radius, low, high); - - // Accumulate samples (we can get away with surprisingly few samples) - let step = (end - start) / 4.0; - var y = start + step * 0.5; - alpha = 0.0; - for (var i = 0; i < 4; i += 1) { - let blur = blur_along_x(center_to_point.x, center_to_point.y - y, - shadow.blur_radius, corner_radius, half_size); - alpha += blur * gaussian(y, shadow.blur_radius) * step; - y += step; - } + let center = shadow.shape_bounds.origin + shadow.shape_bounds.size / 2.0; + let blur = PreparedBlurredRoundedRect(input.blur_shape, input.blur_r1, + input.blur_exponent, input.blur_scale); + alpha = blurred_rounded_rect(input.position.xy - center, blur); } if (shadow.inset != 0u) { diff --git a/crates/gpui_wgpu/src/wgpu_context.rs b/crates/gpui_wgpu/src/wgpu_context.rs index 5563a761..37e9a0aa 100644 --- a/crates/gpui_wgpu/src/wgpu_context.rs +++ b/crates/gpui_wgpu/src/wgpu_context.rs @@ -338,6 +338,18 @@ impl WgpuContext { } } + pub fn supports_transient_attachments(&self) -> bool { + #[cfg(target_family = "wasm")] + if self.backend == WgpuBackend::BrowserWebGpu { + // wgpu passes usage bits straight to the browser without knowing + // whether it recognizes this one. + return js_sys::Reflect::get(&js_sys::global(), &"GPUTextureUsage".into()) + .and_then(|usage| js_sys::Reflect::has(&usage, &"TRANSIENT_ATTACHMENT".into())) + .unwrap_or(false); + } + true + } + #[cfg(target_family = "wasm")] pub async fn new_web( canvas: &web_sys::HtmlCanvasElement, diff --git a/crates/gpui_wgpu/src/wgpu_renderer.rs b/crates/gpui_wgpu/src/wgpu_renderer.rs index 1806cfb7..0b279fa9 100644 --- a/crates/gpui_wgpu/src/wgpu_renderer.rs +++ b/crates/gpui_wgpu/src/wgpu_renderer.rs @@ -3,9 +3,9 @@ use anyhow::{Context as _, Result}; use bytemuck::{Pod, Zeroable}; use collections::FxHashMap; use gpui::{ - AtlasTextureId, BLUR_LEVELS, BlurPasses, Bounds, DevicePixels, GAUSSIAN_REACH, GpuSpecs, - LayerEffect, PaintedPath, PrimitiveBatch, Pyramid, ScaledPixels, Scene, ShaderId, Size, - get_gamma_correction_ratios, point, size, + AtlasTextureId, BLUR_LEVELS, BlurPasses, Bounds, DEPTH_PREPASS, DevicePixels, GAUSSIAN_REACH, + GpuSpecs, LayerEffect, PaintedPath, PrimitiveBatch, Pyramid, ScaledPixels, Scene, ShaderId, + Size, get_gamma_correction_ratios, point, quad_depth, quad_depth_scale, size, }; use log::warn; #[cfg(not(target_family = "wasm"))] @@ -77,6 +77,17 @@ struct GlobalParams { viewport_size: [f32; 2], path_paint_base: u32, path_curve_base: u32, + depth_scale: f32, + quad_count: u32, + premultiplied_alpha: u32, + pad: u32, +} + +const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float; + +struct DepthTexture { + texture: wgpu::Texture, + view: wgpu::TextureView, } /// The globals a custom shader's prelude reads, as its `GpuiShaderGlobals` declares them. They @@ -147,6 +158,7 @@ struct WgpuPipelines { /// Composites a layer blurred across only, running the gaussian down on the way. blurred: wgpu::RenderPipeline, quads: wgpu::RenderPipeline, + opaque_quads: wgpu::RenderPipeline, shadows: wgpu::RenderPipeline, path_tiles: wgpu::RenderPipeline, underlines: wgpu::RenderPipeline, @@ -163,6 +175,7 @@ struct WgpuPipelines { /// A pipeline per custom shader, created the first time a frame draws it. A shader that /// failed to compile is kept as `None`, so it is not compiled again every frame. custom: FxHashMap>, + premultiplied_alpha: bool, } /// One frame allocation of instance data, ready to bind. @@ -424,9 +437,6 @@ struct WgpuRendererCore { atlas: Arc, shader_globals_offset: u64, gamma_offset: u64, - /// Whether the pipelines were built for a premultiplied surface, which custom shaders read - /// from their globals. - premultiplied_alpha: bool, instance_data_capacity: u64, max_instance_data_size: u64, instance_data_alignment: u64, @@ -442,7 +452,9 @@ struct WgpuRendererCore { rendering_params: RenderingParameters, is_bgr: bool, dual_source_blending: bool, + transient_attachments: bool, adapter_info: wgpu::AdapterInfo, + depth_texture: Option, /// The format of the frame, which the offscreen filter targets share. target_format: wgpu::TextureFormat, max_texture_size: u32, @@ -1011,10 +1023,6 @@ impl WgpuRendererCore { } else { wgpu::BlendState::ALPHA_BLENDING }; - let compilation_options = wgpu::PipelineCompilationOptions { - constants: &[("PREMULTIPLIED_ALPHA", f64::from(premultiplied_alpha as u8))], - ..Default::default() - }; let color_target = wgpu::ColorTargetState { format: surface_format, @@ -1038,7 +1046,7 @@ impl WgpuRendererCore { texture_layout: Option<&wgpu::BindGroupLayout>, topology: wgpu::PrimitiveTopology, color_targets: &[Option], - sample_count: u32, + depth_write_enabled: bool, module: &wgpu::ShaderModule| { let mut bind_group_layouts = vec![Some(globals_layout), Some(data_layout)]; bind_group_layouts.extend(texture_layout.map(Some)); @@ -1055,13 +1063,13 @@ impl WgpuRendererCore { module, entry_point: Some(vs_entry), buffers: &[], - compilation_options: compilation_options.clone(), + compilation_options: wgpu::PipelineCompilationOptions::default(), }, fragment: Some(wgpu::FragmentState { module, entry_point: Some(fs_entry), targets: color_targets, - compilation_options: compilation_options.clone(), + compilation_options: wgpu::PipelineCompilationOptions::default(), }), primitive: wgpu::PrimitiveState { topology, @@ -1072,12 +1080,14 @@ impl WgpuRendererCore { unclipped_depth: false, conservative: false, }, - depth_stencil: None, - multisample: wgpu::MultisampleState { - count: sample_count, - mask: !0, - alpha_to_coverage_enabled: false, - }, + depth_stencil: DEPTH_PREPASS.then(|| wgpu::DepthStencilState { + format: DEPTH_FORMAT, + depth_write_enabled: Some(depth_write_enabled), + depth_compare: Some(wgpu::CompareFunction::Greater), + stencil: wgpu::StencilState::default(), + bias: wgpu::DepthBiasState::default(), + }), + multisample: wgpu::MultisampleState::default(), multiview_mask: None, cache: None, }) @@ -1130,7 +1140,7 @@ impl WgpuRendererCore { Some(&layouts.texture), wgpu::PrimitiveTopology::TriangleStrip, &[Some(backdrop_punch_target)], - 1, + false, &shader_module, ); @@ -1143,7 +1153,7 @@ impl WgpuRendererCore { Some(&layouts.texture), wgpu::PrimitiveTopology::TriangleStrip, &[Some(backdrop_target)], - 1, + false, &shader_module, ); @@ -1162,7 +1172,7 @@ impl WgpuRendererCore { Some(&layouts.texture), wgpu::PrimitiveTopology::TriangleStrip, &[Some(opaque_target.clone())], - 1, + false, &shader_module, ); @@ -1175,7 +1185,7 @@ impl WgpuRendererCore { Some(&layouts.texture), wgpu::PrimitiveTopology::TriangleStrip, &[Some(opaque_target.clone())], - 1, + false, &shader_module, ); @@ -1188,7 +1198,7 @@ impl WgpuRendererCore { Some(&layouts.texture), wgpu::PrimitiveTopology::TriangleStrip, &[Some(opaque_target.clone())], - 1, + false, &shader_module, ); @@ -1201,7 +1211,7 @@ impl WgpuRendererCore { Some(&layouts.texture), wgpu::PrimitiveTopology::TriangleStrip, &[Some(opaque_target)], - 1, + false, &shader_module, ); @@ -1214,7 +1224,7 @@ impl WgpuRendererCore { Some(&layouts.texture), wgpu::PrimitiveTopology::TriangleStrip, &[Some(premultiplied_target.clone())], - 1, + false, &shader_module, ); @@ -1227,7 +1237,7 @@ impl WgpuRendererCore { Some(&layouts.texture), wgpu::PrimitiveTopology::TriangleStrip, &[Some(premultiplied_target.clone())], - 1, + false, &shader_module, ); @@ -1240,7 +1250,7 @@ impl WgpuRendererCore { Some(&layouts.texture), wgpu::PrimitiveTopology::TriangleStrip, &[Some(premultiplied_target)], - 1, + false, &shader_module, ); @@ -1253,7 +1263,24 @@ impl WgpuRendererCore { None, wgpu::PrimitiveTopology::TriangleStrip, &[Some(color_target.clone())], - 1, + false, + &shader_module, + ); + + let opaque_quads = create_pipeline( + "opaque_quads", + "vs_opaque_quad", + "fs_opaque_quad", + &layouts.globals, + &layouts.instances, + None, + wgpu::PrimitiveTopology::TriangleStrip, + &[Some(wgpu::ColorTargetState { + format: surface_format, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + true, &shader_module, ); @@ -1266,7 +1293,7 @@ impl WgpuRendererCore { None, wgpu::PrimitiveTopology::TriangleStrip, &[Some(color_target.clone())], - 1, + false, &shader_module, ); @@ -1279,7 +1306,7 @@ impl WgpuRendererCore { None, wgpu::PrimitiveTopology::TriangleStrip, &[Some(color_target.clone())], - 1, + false, &shader_module, ); @@ -1292,7 +1319,7 @@ impl WgpuRendererCore { None, wgpu::PrimitiveTopology::TriangleStrip, &[Some(color_target.clone())], - 1, + false, &shader_module, ); @@ -1305,7 +1332,7 @@ impl WgpuRendererCore { Some(&layouts.texture), wgpu::PrimitiveTopology::TriangleStrip, &[Some(color_target.clone())], - 1, + false, &shader_module, ); @@ -1336,7 +1363,7 @@ impl WgpuRendererCore { blend: Some(subpixel_blend), write_mask: wgpu::ColorWrites::COLOR, })], - 1, + false, subpixel_module, )) } else { @@ -1353,7 +1380,7 @@ impl WgpuRendererCore { Some(&layouts.texture), wgpu::PrimitiveTopology::TriangleStrip, &[Some(color_target.clone())], - 1, + false, subpixel_module, ) }); @@ -1367,7 +1394,7 @@ impl WgpuRendererCore { Some(&layouts.texture), wgpu::PrimitiveTopology::TriangleStrip, &[Some(color_target.clone())], - 1, + false, &shader_module, ); @@ -1380,7 +1407,7 @@ impl WgpuRendererCore { None, wgpu::PrimitiveTopology::TriangleStrip, &[Some(color_target.clone())], - 1, + false, &shader_module, ); @@ -1395,6 +1422,7 @@ impl WgpuRendererCore { masked, blurred, quads, + opaque_quads, shadows, path_tiles, underlines, @@ -1405,6 +1433,7 @@ impl WgpuRendererCore { surfaces, custom_target: color_target, custom: FxHashMap::default(), + premultiplied_alpha, } } @@ -2214,7 +2243,6 @@ impl WgpuRendererCore { atlas, shader_globals_offset, gamma_offset, - premultiplied_alpha: alpha_mode == wgpu::CompositeAlphaMode::PreMultiplied, instance_data_capacity, max_instance_data_size, instance_data_alignment, @@ -2226,7 +2254,9 @@ impl WgpuRendererCore { rendering_params, is_bgr: false, dual_source_blending, + transient_attachments: context.supports_transient_attachments(), adapter_info: context.adapter.get_info(), + depth_texture: None, target_format, max_texture_size, } @@ -2241,7 +2271,6 @@ impl WgpuRendererCore { surface_format: wgpu::TextureFormat, alpha_mode: wgpu::CompositeAlphaMode, ) { - self.premultiplied_alpha = alpha_mode == wgpu::CompositeAlphaMode::PreMultiplied; self.resources.pipelines = Self::create_pipelines( &self.resources.device, &self.resources.bind_group_layouts, @@ -2305,7 +2334,7 @@ impl WgpuRendererCore { }; let shader_globals = ShaderGlobals { viewport_size: [frame_size.0 as f32, frame_size.1 as f32], - premultiplied_alpha: self.premultiplied_alpha as u32, + premultiplied_alpha: self.resources.pipelines.premultiplied_alpha as u32, pad: 0, }; self.resources.queue.write_buffer( @@ -2351,10 +2380,15 @@ impl WgpuRendererCore { scene.polychrome_sprites.len(), ) })?; + let depth_scale = quad_depth_scale(scene.quads.len()); let globals = GlobalParams { viewport_size: [self.frame_size.0 as f32, self.frame_size.1 as f32], path_paint_base: instance_bindings.path_tiles.paint_base, path_curve_base: instance_bindings.path_tiles.curve_base, + depth_scale, + quad_count: scene.quads.len() as u32, + premultiplied_alpha: self.resources().pipelines.premultiplied_alpha as u32, + pad: 0, }; self.resources().queue.write_buffer( &self.resources().globals_buffer, @@ -2362,6 +2396,21 @@ impl WgpuRendererCore { bytemuck::bytes_of(&globals), ); self.prepare_texture_bind_groups(scene); + // Without the depth pre-pass the frame takes no depth attachment, as no fork pass does. + let depth_view = match DEPTH_PREPASS { + true => { + let (width, height) = self.frame_size; + self.ensure_depth_texture(size( + DevicePixels(width as i32), + DevicePixels(height as i32), + )); + let depth_texture = self.depth_texture.as_ref(); + Some(depth_texture.context("depth texture missing")?.view.clone()) + } + false => None, + }; + // Quad depths rely on a quad's instance index being its index in `scene.quads`. + debug_assert!(!DEPTH_PREPASS || instance_bindings.quads.first_instance == 0); let mut encoder = self.resources() @@ -2391,11 +2440,29 @@ impl WgpuRendererCore { }, depth_slice: None, })], - depth_stencil_attachment: None, + depth_stencil_attachment: depth_view.as_ref().map(|view| { + wgpu::RenderPassDepthStencilAttachment { + view, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(0.0), + store: wgpu::StoreOp::Discard, + }), + stencil_ops: None, + } + }), ..Default::default() }); pass.set_bind_group(0, &self.resources().globals_bind_group, &[]); + if DEPTH_PREPASS { + self.draw_instances( + &instance_bindings.quads, + &self.resources().pipelines.opaque_quads, + instance_range(0..scene.quads.len()), + &mut pass, + ); + } + // Where the pass in hand is drawing: the frame, or the layer being filled when one // is open. Anything that has to break the pass and resume it has to resume it here, // or its primitives land in the window while the rest of the frame is still being @@ -2406,6 +2473,9 @@ impl WgpuRendererCore { // filter share one target, so a list of separately blurred rows costs one pass, not one // per row. let mut spans: Vec> = Vec::new(); + let viewport_width = self.frame_size.0 as f32; + let viewport_height = self.frame_size.1 as f32; + let mut quad_cursor: u32 = 0; let mut path_tile_cursor = 0; for batch in scene.batches() { let wanted = filtered @@ -2488,13 +2558,36 @@ impl WgpuRendererCore { spans.push(layer.destination_clip()); } + // Quad shaders assign each quad its own depth. + // In every other batch type, the depth is fixed to the position of the quad cursor. + if DEPTH_PREPASS { + let (minimum_depth, maximum_depth) = + if matches!(&batch, PrimitiveBatch::Quads(_)) { + (0.0, 1.0) + } else { + let depth = quad_depth(quad_cursor, depth_scale); + (depth, depth) + }; + pass.set_viewport( + 0.0, + 0.0, + viewport_width, + viewport_height, + minimum_depth, + maximum_depth, + ); + } + match batch { - PrimitiveBatch::Quads(range) => self.draw_instances( - &instance_bindings.quads, - &self.resources().pipelines.quads, - instance_range(range), - &mut pass, - ), + PrimitiveBatch::Quads(range) => { + quad_cursor += range.len() as u32; + self.draw_instances( + &instance_bindings.quads, + &self.resources().pipelines.quads, + instance_range(range), + &mut pass, + ) + } PrimitiveBatch::Shaders { shader, range } => { if let Some(pipeline) = self.custom_pipeline(shader) { // A custom shader reads globals of its own, so the renderer's go @@ -2743,6 +2836,41 @@ impl WgpuRendererCore { Ok((onto, blurred, params, composite)) } + fn ensure_depth_texture(&mut self, size: Size) { + let width = size.width.0 as u32; + let height = size.height.0 as u32; + if let Some(depth_texture) = &self.depth_texture + && depth_texture.texture.width() == width + && depth_texture.texture.height() == height + { + return; + } + let usage = if self.transient_attachments { + wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TRANSIENT_ATTACHMENT + } else { + wgpu::TextureUsages::RENDER_ATTACHMENT + }; + let texture = self + .resources() + .device + .create_texture(&wgpu::TextureDescriptor { + label: Some("depth_texture"), + size: wgpu::Extent3d { + width, + height, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: DEPTH_FORMAT, + usage, + view_formats: &[], + }); + let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); + self.depth_texture = Some(DepthTexture { texture, view }); + } + fn write_instances( &mut self, scene: &Scene, @@ -4402,3 +4530,60 @@ fn render_fixture_cases() -> anyhow::Result<()> { renderer.render_scene_to_image(scene, size) }) } + +#[cfg(all(test, target_os = "linux"))] +#[test] +fn collapsed_inset_shadow_hole_fills_element() -> anyhow::Result<()> { + use gpui::{ + Bounds, ContentMask, Corners, DevicePixels, Hsla, PlatformHeadlessRenderer as _, + ScaledPixels, Scene, Shadow, Size, point, size, + }; + + let mut renderer = crate::WgpuHeadlessRenderer::new()?; + let viewport = Size::new(DevicePixels(64), DevicePixels(64)); + let full = Bounds::new( + point(ScaledPixels(0.0), ScaledPixels(0.0)), + size(ScaledPixels(64.0), ScaledPixels(64.0)), + ); + let element = Bounds::new( + point(ScaledPixels(8.0), ScaledPixels(8.0)), + size(ScaledPixels(48.0), ScaledPixels(48.0)), + ); + let collapsed_hole = Bounds::new( + point(ScaledPixels(32.5), ScaledPixels(32.5)), + size(ScaledPixels(0.0), ScaledPixels(0.0)), + ); + for blur_radius in [8.0, 0.0] { + let mut scene = Scene::default(); + scene.insert_primitive(Shadow { + order: 0, + blur_radius: ScaledPixels(blur_radius), + bounds: element, + content_mask: ContentMask { bounds: full }, + corner_radii: Corners::default(), + color: Hsla { + h: 0.0, + s: 1.0, + l: 0.5, + a: 1.0, + }, + shape_bounds: collapsed_hole, + shape_corner_radii: Corners::default(), + inset: true.into(), + element_corner_smoothing: 0.0, + element_bounds: element, + element_corner_radii: Corners::default(), + }); + scene.finish(); + let image = renderer.render_scene_to_image(&scene, viewport)?; + for (x, y) in [(32, 32), (20, 20), (44, 44)] { + let pixel = image.get_pixel(x, y).0; + assert_eq!( + pixel, + [255, 0, 0, 255], + "collapsed inset shadow (blur={blur_radius}) at ({x},{y}) must fill element" + ); + } + } + Ok(()) +} diff --git a/crates/gpui_windows/Cargo.toml b/crates/gpui_windows/Cargo.toml index 15ab649e..e6a1a45b 100644 --- a/crates/gpui_windows/Cargo.toml +++ b/crates/gpui_windows/Cargo.toml @@ -17,8 +17,6 @@ default = ["gpui/default"] test-support = ["gpui/test-support"] screen-capture = ["gpui/screen-capture", "scap"] -[dependencies] -gpui.workspace = true [target.'cfg(target_os = "windows")'.dependencies] accesskit.workspace = true @@ -28,6 +26,7 @@ collections.workspace = true dunce.workspace = true etagere.workspace = true futures.workspace = true +gpui.workspace = true gpui_util.workspace = true image.workspace = true itertools.workspace = true diff --git a/crates/gpui_windows/build.rs b/crates/gpui_windows/build.rs index 69ae09fa..4dd8056f 100644 --- a/crates/gpui_windows/build.rs +++ b/crates/gpui_windows/build.rs @@ -41,6 +41,7 @@ mod shader_compilation { ("blit", true), ("mask", true), ("quad", true), + ("opaque_quad", true), ("shadow", true), ("path_tile", true), ("underline", true), diff --git a/crates/gpui_windows/src/directx_renderer.rs b/crates/gpui_windows/src/directx_renderer.rs index 649dbfa7..1c2c026e 100644 --- a/crates/gpui_windows/src/directx_renderer.rs +++ b/crates/gpui_windows/src/directx_renderer.rs @@ -74,6 +74,7 @@ pub(crate) struct DirectXRendererDevices { pub(crate) dxgi_factory: IDXGIFactory6, pub(crate) device: ID3D11Device, pub(crate) device_context: ID3D11DeviceContext, + device_context1: Option, dxgi_device: Option, annotation: Option, } @@ -83,6 +84,8 @@ struct DirectXResources { swap_chain: IDXGISwapChain1, render_target: Option, render_target_view: Option, + depth_stencil_texture: Option, + depth_stencil_view: Option, // Offscreen targets the frame blurs and masks through filters: FilterTargets, @@ -284,6 +287,7 @@ struct DirectXRenderPipelines { mask_pipeline: PipelineState, shadow_pipeline: PipelineState, quad_pipeline: PipelineState, + opaque_quad_pipeline: OpaqueQuadPipeline, path_tile_pipeline: PipelineState, path_curves: StructuredBuffer, path_paints: StructuredBuffer, @@ -343,12 +347,14 @@ impl DirectXRendererDevices { Some(device.cast().context("Creating DXGI device")?) }; let annotation = device_context.cast().ok(); + let device_context1 = device_context.cast().ok(); Ok(Self { adapter: adapter.clone(), dxgi_factory: dxgi_factory.clone(), device: device.clone(), device_context: device_context.clone(), + device_context1, dxgi_device, annotation, }) @@ -407,7 +413,7 @@ impl DirectXRenderer { self.atlas.clone() } - fn pre_draw(&self, clear_color: &[f32; 4]) -> Result<()> { + fn pre_draw(&self, clear_color: &[f32; 4], depth_scale: f32) -> Result<()> { let resources = self.resources.as_ref().expect("resources missing"); let device_context = &self .devices @@ -423,7 +429,8 @@ impl DirectXRenderer { grayscale_enhanced_contrast: self.font_info.grayscale_enhanced_contrast, subpixel_enhanced_contrast: self.font_info.subpixel_enhanced_contrast, is_bgr: self.font_info.is_bgr as u32, - _pad: [0; 3], + depth_scale, + _pad: [0; 2], }], )?; unsafe { @@ -434,8 +441,21 @@ impl DirectXRenderer { .context("missing render target view")?, clear_color, ); - device_context - .OMSetRenderTargets(Some(slice::from_ref(&resources.render_target_view)), None); + if DEPTH_PREPASS { + device_context.ClearDepthStencilView( + resources + .depth_stencil_view + .as_ref() + .context("missing depth stencil view")?, + D3D11_CLEAR_DEPTH.0, + 0.0, + 0, + ); + } + device_context.OMSetRenderTargets( + Some(slice::from_ref(&resources.render_target_view)), + resources.depth_stencil_view.as_ref(), + ); device_context.RSSetViewports(Some(slice::from_ref(&resources.viewport))); device_context .VSSetConstantBuffers(0, Some(slice::from_ref(&self.globals.global_params_buffer))); @@ -450,6 +470,13 @@ impl DirectXRenderer { Ok(()) } + fn discard_depth_buffer(&self) -> Option<()> { + let context1 = self.devices.as_ref()?.device_context1.as_ref()?; + let depth_stencil_view = self.resources.as_ref()?.depth_stencil_view.as_ref()?; + unsafe { context1.DiscardView(depth_stencil_view) }; + Some(()) + } + #[inline] /// The handles a filter pass needs, cloned so the pipelines can be borrowed alongside them. fn pipeline_handles( @@ -1080,9 +1107,10 @@ impl DirectXRenderer { .handle_device_lost(&devices.device, &devices.device_context); unsafe { - devices - .device_context - .OMSetRenderTargets(Some(slice::from_ref(&resources.render_target_view)), None); + devices.device_context.OMSetRenderTargets( + Some(slice::from_ref(&resources.render_target_view)), + resources.depth_stencil_view.as_ref(), + ); } self.devices = Some(devices); self.resources = Some(resources); @@ -1120,10 +1148,14 @@ impl DirectXRenderer { background_appearance: WindowBackgroundAppearance, ) -> Result<()> { self.frame_time = Instant::now(); - self.pre_draw(&match background_appearance { - WindowBackgroundAppearance::Opaque => [1.0f32; 4], - _ => [0.0f32; 4], - })?; + let depth_scale = quad_depth_scale(scene.quads.len()); + self.pre_draw( + &match background_appearance { + WindowBackgroundAppearance::Opaque => [1.0f32; 4], + _ => [0.0f32; 4], + }, + depth_scale, + )?; self.upload_scene_buffers(scene)?; // Backdrops read what the frame has drawn so far, which the swap chain cannot be sampled @@ -1152,6 +1184,18 @@ impl DirectXRenderer { .as_ref() .and_then(|devices| devices.annotation.clone()) .filter(|annotation| unsafe { annotation.GetStatus().as_bool() }); + + if DEPTH_PREPASS && !scene.quads.is_empty() { + let _annotation = annotation.as_ref().map(|annotation| { + Annotation::new( + annotation, + HSTRING::from(format!("opaque quads ({})", scene.quads.len())), + ) + }); + self.draw_opaque_quads(scene.quads.len())?; + } + + let mut quad_cursor: u32 = 0; let mut path_tile_cursor = 0; for batch in scene.batches() { let _annotation = annotation @@ -1201,9 +1245,23 @@ impl DirectXRenderer { spans.push(layer.destination_clip()); } + // Quad shaders assign each quad its own depth. + // In every other batch type, the depth is fixed to the position of the quad cursor. + if DEPTH_PREPASS { + if matches!(&batch, PrimitiveBatch::Quads(_)) { + self.set_viewport_depth_range(0.0, 1.0)?; + } else { + let depth = quad_depth(quad_cursor, depth_scale); + self.set_viewport_depth_range(depth, depth)?; + } + } + match batch { PrimitiveBatch::Shadows(range) => self.draw_shadows(range.start, range.len()), - PrimitiveBatch::Quads(range) => self.draw_quads(range.start, range.len()), + PrimitiveBatch::Quads(range) => { + quad_cursor += range.len() as u32; + self.draw_quads(range.start, range.len()) + } PrimitiveBatch::Shaders { shader, range } => { self.draw_custom_shaders(shader, range.start, range.len()) } @@ -1268,6 +1326,7 @@ impl DirectXRenderer { self.blit_frame()?; } + self.discard_depth_buffer(); Ok(()) } @@ -1376,6 +1435,36 @@ impl DirectXRenderer { .context("Failed to build RgbaImage from staging readback") } + fn set_viewport_depth_range(&self, minimum_depth: f32, maximum_depth: f32) -> Result<()> { + let devices = self.devices.as_ref().context("devices missing")?; + let resources = self.resources.as_ref().context("resources missing")?; + // Equal endpoints collapse every shader depth to the same value. + let viewport = D3D11_VIEWPORT { + MinDepth: minimum_depth, + MaxDepth: maximum_depth, + ..resources.viewport + }; + unsafe { + devices + .device_context + .RSSetViewports(Some(slice::from_ref(&viewport))) + }; + Ok(()) + } + + fn draw_opaque_quads(&self, quad_count: usize) -> Result<()> { + let devices = self.devices.as_ref().context("devices missing")?; + self.pipelines.opaque_quad_pipeline.draw( + &devices.device_context, + &self.pipelines.quad_pipeline, + self.globals + .batch_params_buffer + .as_ref() + .context("batch params buffer missing")?, + quad_count as u32, + ) + } + pub(crate) fn resize(&mut self, new_size: Size) -> Result<()> { let width = new_size.width.0.max(1) as u32; let height = new_size.height.0.max(1) as u32; @@ -1412,9 +1501,10 @@ impl DirectXRenderer { resources.recreate_resources(devices, width, height)?; unsafe { - devices - .device_context - .OMSetRenderTargets(Some(slice::from_ref(&resources.render_target_view)), None); + devices.device_context.OMSetRenderTargets( + Some(slice::from_ref(&resources.render_target_view)), + resources.depth_stencil_view.as_ref(), + ); } Ok(()) @@ -1775,8 +1865,13 @@ impl DirectXResources { )? }; - let (render_target, render_target_view, viewport) = - create_resources(devices, &swap_chain, width, height)?; + let ( + render_target, + render_target_view, + depth_stencil_texture, + depth_stencil_view, + viewport, + ) = create_resources(devices, &swap_chain, width, height)?; let filters = FilterTargets::new(width, height); set_rasterizer_state(&devices.device, &devices.device_context)?; @@ -1785,6 +1880,8 @@ impl DirectXResources { filters, render_target: Some(render_target), render_target_view, + depth_stencil_texture, + depth_stencil_view, viewport, }) } @@ -1796,12 +1893,19 @@ impl DirectXResources { width: u32, height: u32, ) -> Result<()> { - let (render_target, render_target_view, viewport) = - create_resources(devices, &self.swap_chain, width, height)?; + let ( + render_target, + render_target_view, + depth_stencil_texture, + depth_stencil_view, + viewport, + ) = create_resources(devices, &self.swap_chain, width, height)?; // The offscreen targets are rebuilt at the new size by the first frame that needs them. self.filters = FilterTargets::new(width, height); self.render_target = Some(render_target); self.render_target_view = render_target_view; + self.depth_stencil_texture = depth_stencil_texture; + self.depth_stencil_view = depth_stencil_view; self.viewport = viewport; Ok(()) } @@ -1924,6 +2028,7 @@ impl DirectXRenderPipelines { 16, create_blend_state(device)?, )?; + let opaque_quad_pipeline = OpaqueQuadPipeline::new(device)?; Ok(Self { backdrop_pipeline, @@ -1936,6 +2041,7 @@ impl DirectXRenderPipelines { mask_pipeline, shadow_pipeline, quad_pipeline, + opaque_quad_pipeline, path_tile_pipeline, path_curves, path_paints, @@ -1997,7 +2103,8 @@ struct GlobalParams { grayscale_enhanced_contrast: f32, subpixel_enhanced_contrast: f32, is_bgr: u32, - _pad: [u32; 3], + depth_scale: f32, + _pad: [u32; 2], } #[derive(Clone, Copy, Debug, Default)] @@ -2095,6 +2202,7 @@ struct PipelineState { fragment: ID3D11PixelShader, instances: StructuredBuffer, blend_state: ID3D11BlendState, + depth_stencil_state: ID3D11DepthStencilState, } impl PipelineState { @@ -2119,6 +2227,7 @@ impl PipelineState { fragment, instances: StructuredBuffer::new(device, label, buffer_size)?, blend_state, + depth_stencil_state: create_depth_stencil_state(device, D3D11_DEPTH_WRITE_MASK_ZERO)?, }) } @@ -2147,6 +2256,7 @@ impl PipelineState { &self.vertex, &self.fragment, &self.blend_state, + &self.depth_stencil_state, ); unsafe { device_context.DrawInstanced(4, instance_count, 0, 0); @@ -2180,6 +2290,7 @@ impl PipelineState { &self.vertex, fragment, blend_state, + &self.depth_stencil_state, ); unsafe { device_context.PSSetSamplers(0, Some(sampler)); @@ -2360,6 +2471,63 @@ impl CustomShaders { } } +/// Draws opaque rectangles ahead of everything else, writing depth so that +/// later passes skip the pixels they cover. +struct OpaqueQuadPipeline { + vertex: ID3D11VertexShader, + fragment: ID3D11PixelShader, + blend_state: ID3D11BlendState, + depth_stencil_state: ID3D11DepthStencilState, +} + +impl OpaqueQuadPipeline { + fn new(device: &ID3D11Device) -> Result { + let vertex = { + let raw_shader = RawShaderBytes::new(ShaderModule::OpaqueQuad, ShaderTarget::Vertex)?; + create_vertex_shader(device, raw_shader.as_bytes())? + }; + let fragment = { + let raw_shader = RawShaderBytes::new(ShaderModule::OpaqueQuad, ShaderTarget::Fragment)?; + create_fragment_shader(device, raw_shader.as_bytes())? + }; + Ok(OpaqueQuadPipeline { + vertex, + fragment, + blend_state: create_opaque_blend_state(device)?, + depth_stencil_state: create_depth_stencil_state(device, D3D11_DEPTH_WRITE_MASK_ALL)?, + }) + } + + /// Draws every quad, last first. The vertex shader drops all but opaque + /// rectangles. + fn draw( + &self, + device_context: &ID3D11DeviceContext, + quad_pipeline: &PipelineState, + batch_params_buffer: &ID3D11Buffer, + quad_count: u32, + ) -> Result<()> { + if quad_count == 0 { + return Ok(()); + } + quad_pipeline.ensure_range(0, quad_count)?; + // Drawing front to back lets the depth test skip pixels that a later + // quad already covers. + update_batch_start(device_context, batch_params_buffer, quad_count - 1)?; + set_pipeline_state( + device_context, + slice::from_ref(&quad_pipeline.instances.view), + D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, + &self.vertex, + &self.fragment, + &self.blend_state, + &self.depth_stencil_state, + ); + unsafe { device_context.DrawInstanced(4, quad_count, 0, 0) }; + Ok(()) + } +} + /// Translates a custom shader to HLSL and compiles both of its stages for shader model 5.0, /// which needs a device of feature level 11 or above. fn compile_custom_pipeline(device: &ID3D11Device, shader: ShaderId) -> Result { @@ -2506,12 +2674,28 @@ fn create_resources( ) -> Result<( ID3D11Texture2D, Option, + Option, + Option, D3D11_VIEWPORT, )> { let (render_target, render_target_view) = create_render_target_and_its_view(swap_chain, &devices.device)?; + let (depth_stencil_texture, depth_stencil_view) = match DEPTH_PREPASS { + true => { + let (texture, view) = + create_depth_stencil_texture_and_view(&devices.device, width, height)?; + (Some(texture), view) + } + false => (None, None), + }; let viewport = set_viewport(&devices.device_context, width as f32, height as f32); - Ok((render_target, render_target_view, viewport)) + Ok(( + render_target, + render_target_view, + depth_stencil_texture, + depth_stencil_view, + viewport, + )) } #[inline] @@ -2539,6 +2723,37 @@ fn set_viewport(device_context: &ID3D11DeviceContext, width: f32, height: f32) - viewport[0] } +#[inline] +fn create_depth_stencil_texture_and_view( + device: &ID3D11Device, + width: u32, + height: u32, +) -> Result<(ID3D11Texture2D, Option)> { + let texture = unsafe { + let mut output = None; + let desc = D3D11_TEXTURE2D_DESC { + Width: width, + Height: height, + MipLevels: 1, + ArraySize: 1, + Format: DXGI_FORMAT_D32_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Usage: D3D11_USAGE_DEFAULT, + BindFlags: D3D11_BIND_DEPTH_STENCIL.0 as u32, + CPUAccessFlags: 0, + MiscFlags: 0, + }; + device.CreateTexture2D(&desc, None, Some(&mut output))?; + output.unwrap() + }; + let mut view = None; + unsafe { device.CreateDepthStencilView(&texture, None, Some(&mut view))? }; + Ok((texture, view)) +} + #[inline] fn set_rasterizer_state(device: &ID3D11Device, device_context: &ID3D11DeviceContext) -> Result<()> { let desc = D3D11_RASTERIZER_DESC { @@ -2695,6 +2910,52 @@ fn create_render_texture(device: &ID3D11Device, width: u32, height: u32) -> Resu }) } +#[inline] +fn create_opaque_blend_state(device: &ID3D11Device) -> Result { + let mut desc = D3D11_BLEND_DESC::default(); + desc.RenderTarget[0].BlendEnable = false.into(); + desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; + desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; + desc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; + desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; + desc.RenderTarget[0].DestBlend = D3D11_BLEND_ZERO; + desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; + desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL.0 as u8; + unsafe { + let mut state = None; + device.CreateBlendState(&desc, Some(&mut state))?; + Ok(state.unwrap()) + } +} + +#[inline] +fn create_depth_stencil_state( + device: &ID3D11Device, + write_mask: D3D11_DEPTH_WRITE_MASK, +) -> Result { + let stencil_op = D3D11_DEPTH_STENCILOP_DESC { + StencilFailOp: D3D11_STENCIL_OP_KEEP, + StencilDepthFailOp: D3D11_STENCIL_OP_KEEP, + StencilPassOp: D3D11_STENCIL_OP_KEEP, + StencilFunc: D3D11_COMPARISON_ALWAYS, + }; + let desc = D3D11_DEPTH_STENCIL_DESC { + DepthEnable: DEPTH_PREPASS.into(), + DepthWriteMask: write_mask, + DepthFunc: D3D11_COMPARISON_GREATER, + StencilEnable: false.into(), + StencilReadMask: D3D11_DEFAULT_STENCIL_READ_MASK as u8, + StencilWriteMask: D3D11_DEFAULT_STENCIL_WRITE_MASK as u8, + FrontFace: stencil_op, + BackFace: stencil_op, + }; + unsafe { + let mut state = None; + device.CreateDepthStencilState(&desc, Some(&mut state))?; + Ok(state.unwrap()) + } +} + #[inline] fn create_blend_state_for_subpixel_rendering(device: &ID3D11Device) -> Result { let mut desc = D3D11_BLEND_DESC::default(); @@ -2859,6 +3120,7 @@ fn set_pipeline_state( vertex_shader: &ID3D11VertexShader, fragment_shader: &ID3D11PixelShader, blend_state: &ID3D11BlendState, + depth_stencil_state: &ID3D11DepthStencilState, ) { unsafe { device_context.VSSetShaderResources(1, Some(buffer_view)); @@ -2867,6 +3129,7 @@ fn set_pipeline_state( device_context.VSSetShader(vertex_shader, None); device_context.PSSetShader(fragment_shader, None); device_context.OMSetBlendState(blend_state, None, 0xFFFFFFFF); + device_context.OMSetDepthStencilState(depth_stencil_state, 0); } } @@ -2905,6 +3168,7 @@ pub(crate) mod shader_resources { Blit, Mask, Quad, + OpaqueQuad, Shadow, Underline, PathTile, @@ -3003,6 +3267,10 @@ pub(crate) mod shader_resources { ShaderTarget::Vertex => QUAD_VERTEX_BYTES, ShaderTarget::Fragment => QUAD_FRAGMENT_BYTES, }, + ShaderModule::OpaqueQuad => match target { + ShaderTarget::Vertex => OPAQUE_QUAD_VERTEX_BYTES, + ShaderTarget::Fragment => OPAQUE_QUAD_FRAGMENT_BYTES, + }, ShaderModule::Shadow => match target { ShaderTarget::Vertex => SHADOW_VERTEX_BYTES, ShaderTarget::Fragment => SHADOW_FRAGMENT_BYTES, @@ -3111,6 +3379,7 @@ pub(crate) mod shader_resources { ShaderModule::Blit => "blit", ShaderModule::Mask => "mask", ShaderModule::Quad => "quad", + ShaderModule::OpaqueQuad => "opaque_quad", ShaderModule::Shadow => "shadow", ShaderModule::Underline => "underline", ShaderModule::PathTile => "path_tile", diff --git a/crates/gpui_windows/src/platform.rs b/crates/gpui_windows/src/platform.rs index 0a9a3c65..6b943e22 100644 --- a/crates/gpui_windows/src/platform.rs +++ b/crates/gpui_windows/src/platform.rs @@ -927,8 +927,9 @@ impl Platform for WindowsPlatform { .log_err(); } - fn dismiss_system_notification(&self, tag: &str) { + fn dismiss_system_notification(&self, tag: &str) -> Task<()> { self.system_notifications.borrow_mut().dismiss(tag); + Task::ready(()) } fn on_system_notification_response( diff --git a/crates/gpui_windows/src/shaders.hlsl b/crates/gpui_windows/src/shaders.hlsl index 56c170c2..3beaaab8 100644 --- a/crates/gpui_windows/src/shaders.hlsl +++ b/crates/gpui_windows/src/shaders.hlsl @@ -6,7 +6,8 @@ cbuffer GlobalParams: register(b0) { float grayscale_enhanced_contrast; float subpixel_enhanced_contrast; uint is_bgr; - uint3 global_pad; + float depth_scale; + uint2 global_pad; }; cbuffer BatchParams: register(b1) { @@ -113,6 +114,12 @@ float4 to_device_position(float2 unit_vertex, Bounds bounds) { return to_device_position_impl(position); } +float quad_depth(uint quad_id) { + return saturate(float(quad_id + 1u) * depth_scale); +} + +static const float4 CULLED_POSITION = float4(0.0, 0.0, 0.0, 1.0); + float4 distance_from_clip_rect_impl(float2 position, Bounds clip_bounds) { float2 tl = position - clip_bounds.origin; float2 br = clip_bounds.origin + clip_bounds.size - position; @@ -262,33 +269,10 @@ float4 oklab_to_srgb(float4 color) { return float4(linear_to_srgb(linear_rgb), color.a); } -// This approximates the error function, needed for the gaussian integral -float2 erf(float2 x) { - float2 s = sign(x); - float2 a = abs(x); - x = 1. + (0.278393 + (0.230389 + 0.078108 * (a * a)) * a) * a; - x *= x; - return s - s / (x * x); -} - -float blur_along_x(float x, float y, float sigma, float corner, float2 half_size) { - float delta = min(half_size.y - corner - abs(y), 0.); - float curved = half_size.x - corner + sqrt(max(0., corner * corner - delta * delta)); - float2 integral = 0.5 + 0.5 * erf((x + float2(-curved, curved)) * (sqrt(0.5) / sigma)); - return integral.y - integral.x; -} - -// A standard gaussian function, used for weighting samples -float gaussian(float x, float sigma) { - return exp(-(x * x) / (2. * sigma * sigma)) / (sqrt(2. * M_PI_F) * sigma); -} - float4 over(float4 below, float4 above) { - float4 result; float alpha = above.a + below.a * (1.0 - above.a); - result.rgb = (above.rgb * above.a + below.rgb * below.a * (1.0 - above.a)) / alpha; - result.a = alpha; - return result; + float3 premultiplied = above.rgb * above.a + below.rgb * below.a * (1.0 - above.a); + return float4(premultiplied / (alpha == 0.0 ? 1.0 : alpha), alpha); } float2 to_tile_position(float2 unit_vertex, AtlasTile tile) { @@ -587,12 +571,26 @@ struct QuadFragmentInput { PreparedBackground background; }; +// Opaque rectangles are drawn by the opaque pass instead of the quad pass. The fork draws no +// opaque pass (`DEPTH_PREPASS` in scene.rs), so the quad pass keeps every quad. Upstream's test is +// a solid opaque background with neither rounded corners nor a border. +bool is_opaque_rectangle(Quad quad) { + return false; +} + StructuredBuffer quads: register(t1); QuadFragmentInput quad_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) { - float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); uint quad_id = batch_start_index + instance_id; Quad quad = quads[quad_id]; + + if (is_opaque_rectangle(quad)) { + QuadFragmentInput culled = (QuadFragmentInput)0; + culled.position = CULLED_POSITION; + return culled; + } + + float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); Bounds cover = pixel_cover(quad.bounds); ClippedVertex vertex = clip_to_mask(unit_vertex, cover, quad.content_mask); float4 device_position = to_device_position_impl(vertex.position); @@ -601,6 +599,7 @@ QuadFragmentInput quad_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_ QuadFragmentInput output; output.position = device_position; + output.position.z = quad_depth(quad_id); output.border_color = border_color; // A quad off the pixel grid partly covers the pixels its edges fall through, so only one on // the grid fills every pixel it draws. @@ -895,11 +894,8 @@ float4 quad_fragment(QuadFragmentInput input): SV_Target { } } - // Blend the border on top of the background and then linearly interpolate - // between the two as we slide inside the background. - float4 blended_border = over(background, border_color); - color = lerp(background, blended_border, - saturate(antialias_threshold - inner_sdf)); + border_color.a *= saturate(antialias_threshold - inner_sdf); + color = over(background, border_color); } // The distance field knows nothing of how much of the pixel the quad covers, so a quad @@ -907,6 +903,41 @@ float4 quad_fragment(QuadFragmentInput input): SV_Target { return color * float4(1.0, 1.0, 1.0, min(coverage, saturate(antialias_threshold - outer_sdf))); } +/* +** +** Opaque quads +** +*/ + +struct OpaqueQuadFragmentInput { + float4 position: SV_Position; + nointerpolation float4 color: COLOR0; +}; + +OpaqueQuadFragmentInput opaque_quad_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) { + uint quad_id = batch_start_index - instance_id; + Quad quad = quads[quad_id]; + + OpaqueQuadFragmentInput output; + if (!is_opaque_rectangle(quad)) { + output.position = CULLED_POSITION; + output.color = float4(0.0, 0.0, 0.0, 0.0); + return output; + } + + float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); + ClippedVertex vertex = clip_to_mask(unit_vertex, quad.bounds, quad.content_mask); + + output.position = to_device_position_impl(vertex.position); + output.position.z = quad_depth(quad_id); + output.color = hsla_to_rgba(quad.background.solid); + return output; +} + +float4 opaque_quad_fragment(OpaqueQuadFragmentInput input): SV_Target { + return input.color; +} + /* ** ** Shadows @@ -935,14 +966,88 @@ struct Shadow { Corners element_corner_radii; }; +struct PreparedBlurredRoundedRect { + nointerpolation float4 shape: TEXCOORD1; + nointerpolation float4 r1: TEXCOORD2; + nointerpolation float4 exponent: TEXCOORD3; + nointerpolation float4 scale: TEXCOORD4; +}; + struct ShadowFragmentInput { nointerpolation uint shadow_id: TEXCOORD0; float4 position: SV_Position; nointerpolation float4 color: COLOR; + PreparedBlurredRoundedRect blur; }; StructuredBuffer shadows: register(t1); +float erf7(float x) { + x = clamp(x, -10., 10.) * (2. / sqrt(M_PI_F)); + float xx = x * x; + x = x + (0.24295 + (0.03395 + 0.0104 * xx) * xx) * (x * xx); + return x / sqrt(1. + x * x); +} + +// Raph Levien's blurred rounded rectangle approximation, whose blur s is sigma * sqrt(2): +// https://raphlinus.github.io/graphics/2020/04/21/blurred-rounded-rects.html +PreparedBlurredRoundedRect prepare_blurred_rounded_rect(float2 size, Corners corner_radii, float sigma) { + float min_edge = min(size.x, size.y); + if (min_edge <= 0.) { + PreparedBlurredRoundedRect empty; + empty.shape = float4(0., 0., 0., 0.); + empty.r1 = float4(0., 0., 0., 0.); + empty.exponent = float4(2., 2., 2., 2.); + empty.scale = float4(0., 0., 0., 0.); + return empty; + } + float s = max(sigma * sqrt(2.), 1e-6); + float s_inv = 1. / s; + float r_max = 0.5 * min_edge; + float4 radii = float4(corner_radii.top_left, corner_radii.top_right, + corner_radii.bottom_right, corner_radii.bottom_left); + float4 r0 = min(sqrt(radii * radii + 1.15 * 1.15 * s * s), r_max); + float4 r1 = min(sqrt(radii * radii + 4. * s * s), r_max); + + float2 half_extent = 0.5 * s_inv * size; + float delta = 1.25 * s * (exp(-half_extent.x * half_extent.x) - exp(-half_extent.y * half_extent.y)); + float2 adjusted_size = float2(size.x + min(delta, 0.), size.y - max(delta, 0.)); + float4 peak = s_inv * 0.5 * (max(adjusted_size.x, adjusted_size.y) - 0.5 * radii); + + PreparedBlurredRoundedRect output; + output.shape = float4(0.5 * adjusted_size, s_inv, min_edge); + output.r1 = r1; + output.exponent = 2. * r1 / r0; + output.scale = 0.5 * float4(erf7(peak.x), erf7(peak.y), erf7(peak.z), erf7(peak.w)); + return output; +} + +float pick_corner(float2 center_to_point, float4 values) { + Corners corners = { values.x, values.y, values.z, values.w }; + return pick_corner_radius(center_to_point, corners); +} + +float blurred_rounded_rect(float2 center_to_point, PreparedBlurredRoundedRect prepared) { + float r1 = pick_corner(center_to_point, prepared.r1); + float exponent = pick_corner(center_to_point, prepared.exponent); + float scale = pick_corner(center_to_point, prepared.scale); + float s_inv = prepared.shape.z; + float min_edge = prepared.shape.w; + + float2 p0 = abs(center_to_point) - (prepared.shape.xy - r1); + float2 p1 = max(p0, 0.); + float d_pos; + [branch] if (p1.x > 0. && p1.y > 0.) { + d_pos = pow(pow(p1.x, exponent) + pow(p1.y, exponent), 1. / exponent); + } else { + d_pos = p1.x + p1.y; + } + + float d_neg = min(max(p0.x, p0.y), 0.); + float d = d_pos + d_neg - r1; + return scale * (erf7(s_inv * (min_edge + d)) - erf7(s_inv * d)); +} + ShadowFragmentInput shadow_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) { float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); uint shadow_id = batch_start_index + instance_id; @@ -956,6 +1061,7 @@ ShadowFragmentInput shadow_vertex(uint vertex_id: SV_VertexID, uint instance_id: output.position = device_position; output.color = color; output.shadow_id = shadow_id; + output.blur = prepare_blurred_rounded_rect(shadow.shape_bounds.size, shadow.shape_corner_radii, shadow.blur_radius); return output; } @@ -963,32 +1069,15 @@ ShadowFragmentInput shadow_vertex(uint vertex_id: SV_VertexID, uint instance_id: float4 shadow_fragment(ShadowFragmentInput input): SV_TARGET { Shadow shadow = shadows[input.shadow_id]; - float2 half_size = shadow.shape_bounds.size / 2.; - float2 center = shadow.shape_bounds.origin + half_size; - float2 point0 = input.position.xy - center; - float corner_radius = pick_corner_radius(point0, shadow.shape_corner_radii); - float alpha; - if (shadow.blur_radius == 0.) { + if (shadow.shape_bounds.size.x <= 0. || shadow.shape_bounds.size.y <= 0.) { + alpha = 0.; + } else if (shadow.blur_radius == 0.) { float distance = quad_sdf(input.position.xy, shadow.shape_bounds, shadow.shape_corner_radii, 0.0); alpha = saturate(0.5 - distance); } else { - // The signal is only non-zero in a limited range, so don't waste samples - float low = point0.y - half_size.y; - float high = point0.y + half_size.y; - float start = clamp(-3. * shadow.blur_radius, low, high); - float end = clamp(3. * shadow.blur_radius, low, high); - - // Accumulate samples (we can get away with surprisingly few samples) - float step = (end - start) / 4.; - float y = start + step * 0.5; - alpha = 0.; - for (int i = 0; i < 4; i++) { - alpha += blur_along_x(point0.x, point0.y - y, shadow.blur_radius, - corner_radius, half_size) * - gaussian(y, shadow.blur_radius) * step; - y += step; - } + float2 center = shadow.shape_bounds.origin + shadow.shape_bounds.size / 2.; + alpha = blurred_rounded_rect(input.position.xy - center, input.blur); } if (shadow.inset != 0u) { diff --git a/crates/zlog/src/filter.rs b/crates/zlog/src/filter.rs index afd1466d..2b0d227f 100644 --- a/crates/zlog/src/filter.rs +++ b/crates/zlog/src/filter.rs @@ -99,6 +99,9 @@ pub fn refresh_from_settings(settings: &HashMap) { level_enabled_max = level_enabled_max.max(level as u8); } } + for (_, level) in &map_new.modules { + level_enabled_max = level_enabled_max.max(*level as u8); + } LEVEL_ENABLED_MAX_CONFIG.store(level_enabled_max, Ordering::Release); { @@ -542,6 +545,17 @@ mod tests { ); } + #[test] + fn test_refresh_from_settings_with_module_filter() { + let settings = [("a::b".to_string(), "trace".to_string())] + .into_iter() + .collect(); + refresh_from_settings(&settings); + let is_enabled = is_scope_enabled(&scope_new(&[""]), Some("a::b"), log::Level::Trace); + refresh_from_settings(&HashMap::default()); + assert!(is_enabled); + } + #[test] fn test_is_enabled_module() { let mut map = scope_map_from_keys(&[("a", "trace")]); diff --git a/crates/ztracing_macro/Cargo.toml b/crates/ztracing_macro/Cargo.toml index 78feebb8..b85bbf2a 100644 --- a/crates/ztracing_macro/Cargo.toml +++ b/crates/ztracing_macro/Cargo.toml @@ -5,6 +5,9 @@ edition.workspace = true publish.workspace = true license = "Apache-2.0" +[lints] +workspace = true + [lib] proc-macro = true test = false