use std::{
cell::{Cell, RefCell},
sync::OnceLock,
};
use cranpose_ui::{Modifier, current_density};
use cranpose_ui_graphics::{
Color, GLASS_ACTIVITY_UNIFORM, GLASS_ADAPTIVE_FROST_UNIFORM, GLASS_ADAPTIVE_TONE_UNIFORM,
GLASS_BLUR_RADIUS_UNIFORM, GLASS_DISPERSION_UNIFORM, GLASS_EDGE_REFRACTION_REACH_UNIFORM,
GLASS_EDGE_RETURN_DEPTH_UNIFORM, GLASS_EDGE_SPECTRUM_UNIFORM, GLASS_EFFECT_DENSITY_UNIFORM,
GLASS_FACE_LIGHTING_OFF_UNIFORM, GLASS_FACE_RESPONSE_UNIFORM, GLASS_FOLD_DEPTH_UNIFORM,
GLASS_INNER_SHADOW_UNIFORM, GLASS_KEY_FILL_UNIFORM, GLASS_LAYER_CLIPPED_UNIFORM,
GLASS_LAYERED_RETURN_UNIFORM, GLASS_LIGHT_DIRECTION_UNIFORM, GLASS_MENISCUS_ABSORPTION_UNIFORM,
GLASS_OPTICAL_PROJECTION_UNIFORM, GLASS_OPTICAL_ZOOM_ANCHOR_UNIFORM,
GLASS_OPTICAL_ZOOM_UNIFORM, GLASS_PHYSICAL_REFRACTION_DEPTH_ENABLED_UNIFORM,
GLASS_PHYSICAL_REFRACTION_DEPTH_UNIFORM, GLASS_REFRACTION_CURVE_UNIFORM,
GLASS_REFRACTION_MODE_UNIFORM, GLASS_RESTING_EDGE_SHARPNESS_UNIFORM,
GLASS_RESTING_TINT_UNIFORM, GLASS_TOUCH_RADIUS_UNIFORM, GLASS_TRANSMISSION_REFRACTION_UNIFORM,
GraphicsLayer, LIQUID_GLASS_WGSL, LayerShape, PlaceholderShape, Rect, RenderEffect,
RoundedCornerShape, RuntimeShader, TileMode, liquid_glass_placeholder,
liquid_glass_runtime_effect, specialize_liquid_glass,
};
use crate::{appearance::GlassTintAmount, theme::LiquidColors};
thread_local! {
static GLASS_LIGHT_RETURN: Cell<(f32, f32)> = const { Cell::new((0.0, 1.0)) };
}
pub fn set_glass_light_direction(direction: (f32, f32)) {
GLASS_LIGHT_RETURN.with(|cell| cell.set(direction));
}
pub fn glass_light_direction() -> (f32, f32) {
GLASS_LIGHT_RETURN.with(Cell::get)
}
const CAPSULE_CLIP_RADIUS: f32 = 1.0e6;
const CAPSULE_SHADER_RADIUS: f32 = -1.0;
const WCKSRD_OPTICAL_BLUR_RADIUS_PX: f32 = 2.0;
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub enum LiquidShape {
#[default]
Capsule,
RoundedRect(f32),
Circle,
}
impl LiquidShape {
pub fn clip_shape(&self) -> RoundedCornerShape {
match self {
LiquidShape::Capsule | LiquidShape::Circle => {
RoundedCornerShape::uniform(CAPSULE_CLIP_RADIUS)
}
LiquidShape::RoundedRect(radius) => RoundedCornerShape::uniform(*radius),
}
}
pub fn layer_shape(&self) -> LayerShape {
LayerShape::Rounded(self.clip_shape())
}
fn shader_radius_px(&self, density: f32) -> f32 {
match self {
LiquidShape::Capsule | LiquidShape::Circle => CAPSULE_SHADER_RADIUS,
LiquidShape::RoundedRect(radius) => radius * density,
}
}
fn radius_dp(&self) -> f32 {
match self {
LiquidShape::Capsule | LiquidShape::Circle => f32::MAX,
LiquidShape::RoundedRect(radius) => *radius,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum GlassVariant {
#[default]
Regular,
Clear,
Lens,
}
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub enum GlassRefraction {
#[default]
Radial,
Surface {
reach_dp: f32,
},
EdgeLens {
reach_dp: f32,
},
LayeredSurface {
reach_dp: f32,
return_reach_dp: f32,
return_depth_dp: f32,
},
}
impl GlassRefraction {
fn shader_parameters(self) -> (f32, f32) {
match self {
Self::Radial => (0.0, 0.0),
Self::Surface { reach_dp } => (1.0, finite_nonnegative(reach_dp)),
Self::EdgeLens { reach_dp } => (2.0, finite_nonnegative(reach_dp)),
Self::LayeredSurface { reach_dp, .. } => (3.0, finite_nonnegative(reach_dp)),
}
}
}
fn finite_nonnegative(reach_dp: f32) -> f32 {
if reach_dp.is_finite() {
reach_dp.max(0.0)
} else {
0.0
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GlassShadow {
pub color: Color,
pub radius: f32,
pub offset_y: f32,
pub spread: f32,
}
impl GlassShadow {
pub fn new(color: Color, radius: f32, offset_y: f32, spread: f32) -> Self {
Self {
color,
radius: radius.max(0.0),
offset_y,
spread,
}
}
fn uniforms(self) -> Option<[f32; 8]> {
let values = [
self.color.r(),
self.color.g(),
self.color.b(),
self.color.a(),
self.radius,
self.offset_y,
self.spread,
1.0,
];
(values.iter().all(|value| value.is_finite())
&& self.radius >= 0.0
&& (0.0..=1.0).contains(&self.color.a()))
.then_some(values)
}
}
#[derive(Clone, Debug, PartialEq, Default)]
pub struct GlassDynamics {
pub contact_lighting: bool,
pub refraction: Option<GlassRefraction>,
pub shadow: Option<GlassShadow>,
pub ring_shadow: Option<(GlassShadow, f32)>,
pub edge_return_depth_dp: Option<f32>,
pub optical_projection: Option<(f32, f32)>,
pub activity: Option<f32>,
pub resting_tint: Option<Color>,
pub highlight_boost: f32,
pub saturation_boost: f32,
pub tint_alpha_multiplier: Option<f32>,
pub tint_crossfade: Option<(Color, f32)>,
pub morph: Option<GlassMorph>,
pub touch: Option<(f32, f32, f32)>,
pub touch_radius_dp: Option<f32>,
pub press_depth: Option<f32>,
}
impl GlassDynamics {
fn projection(&self) -> (f32, f32) {
self.optical_projection
.filter(|(x, y)| x.is_finite() && y.is_finite() && *x > 0.0 && *y > 0.0)
.unwrap_or((1.0, 1.0))
}
pub fn touched_up(
mut self,
press: f32,
finger: Option<(f32, f32)>,
center: (f32, f32),
) -> Self {
let press = press.clamp(0.0, 1.0);
if press <= 0.0 {
return self;
}
self.highlight_boost += 0.85 * press;
self.saturation_boost += 0.45 * press;
let (fx, fy) = finger.unwrap_or(center);
let carried = self.touch.map_or(0.0, |(_, _, i)| i);
self.touch = Some((fx, fy, (carried + press).clamp(0.0, 1.0)));
self
}
}
fn foreground_is_dark(foreground: Color) -> bool {
let foreground_luma =
0.2126 * foreground.r() + 0.7152 * foreground.g() + 0.0722 * foreground.b();
foreground_luma < 0.5
}
fn shown_tint(tint: Color, crossfade: Option<(Color, f32)>) -> Color {
let Some((previous, progress)) = crossfade.filter(|(_, progress)| progress.is_finite()) else {
return tint;
};
let progress = progress.clamp(0.0, 1.0);
let mix = |from: f32, to: f32| from + (to - from) * progress;
Color(
mix(previous.0, tint.0),
mix(previous.1, tint.1),
mix(previous.2, tint.2),
mix(previous.3, tint.3),
)
}
fn boost_tint_saturation(tint: Color, boost: f32) -> Color {
if boost.abs() <= f32::EPSILON {
return tint;
}
let luma = 0.2126 * tint.r() + 0.7152 * tint.g() + 0.0722 * tint.b();
let saturation = (1.0 + boost).max(0.0);
Color::rgba(
(luma + (tint.r() - luma) * saturation).clamp(0.0, 1.0),
(luma + (tint.g() - luma) * saturation).clamp(0.0, 1.0),
(luma + (tint.b() - luma) * saturation).clamp(0.0, 1.0),
tint.a(),
)
}
pub(crate) fn neutral_surface_tint(foreground: Color, light_alpha: f32, dark_alpha: f32) -> Color {
if foreground_is_dark(foreground) {
Color::BLACK.with_alpha(light_alpha.clamp(0.0, 1.0))
} else {
Color::WHITE.with_alpha(dark_alpha.clamp(0.0, 1.0))
}
}
#[derive(Clone, Debug, PartialEq, Default)]
pub struct GlassMorph {
pub node_size: (f32, f32),
pub primary: (f32, f32, f32, f32, f32),
pub shapes: Vec<(f32, f32, f32, f32, f32)>,
pub glue: f32,
pub wobble_amplitude: f32,
pub wobble_phase: f32,
pub bulge_amplitude: f32,
pub bulge_direction: f32,
pub ellipse_blend: f32,
pub capsule_smoothing_dp: f32,
pub deformation: Option<GlassDeformation>,
pub zoom_anchor: (f32, f32),
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GlassDeformation {
axis: (f32, f32),
along: f32,
}
impl GlassDeformation {
pub fn incompressible(axis: (f32, f32), along: f32) -> Self {
let length = (axis.0 * axis.0 + axis.1 * axis.1).sqrt();
let axis = if length > f32::EPSILON {
(axis.0 / length, axis.1 / length)
} else {
(1.0, 0.0)
};
Self {
axis,
along: along.max(f32::EPSILON),
}
}
pub fn axis(self) -> (f32, f32) {
self.axis
}
pub fn along(self) -> f32 {
self.along
}
pub fn across(self) -> f32 {
1.0 / self.along
}
}
impl GlassMorph {
pub const MAX_SHAPES: usize = 8;
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GlassContourHighlight {
pub height_dp: f32,
pub offset_dp: f32,
pub amount: f32,
pub color_bias: f32,
pub angle_radians: f32,
pub spread_radians: f32,
}
impl GlassContourHighlight {
fn uniforms(self) -> Option<[f32; 6]> {
let values = [
self.height_dp,
self.offset_dp,
self.amount,
self.color_bias,
self.angle_radians,
self.spread_radians,
];
(values.iter().all(|value| value.is_finite())
&& self.height_dp > 0.0
&& self.spread_radians > 0.0)
.then_some(values)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GlassSpecularHighlight {
pub height_dp: f32,
pub angle_radians: f32,
pub spread_radians: f32,
pub curvature: f32,
pub diffuse_amount: f32,
pub diffuse_height_dp: f32,
pub diffuse_spread_radians: f32,
pub saturation: f32,
pub luma_gain: f32,
pub color_bias: f32,
}
impl GlassSpecularHighlight {
fn uniforms(self) -> Option<[f32; 10]> {
let values = [
self.height_dp,
self.angle_radians,
self.spread_radians,
self.curvature,
self.diffuse_amount,
self.diffuse_height_dp,
self.diffuse_spread_radians,
self.saturation,
self.luma_gain,
self.color_bias,
];
(values.iter().all(|value| value.is_finite())
&& self.height_dp > 0.0
&& self.spread_radians > 0.0
&& self.curvature > 0.0
&& self.diffuse_height_dp > 0.0
&& self.diffuse_spread_radians > 0.0)
.then_some(values)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GlassKeyFill {
pub height_dp: f32,
pub curvature: f32,
pub angle_radians: f32,
pub saturation: f32,
pub luma_gain: f32,
pub offset: f32,
pub scale_with_surface: bool,
}
impl GlassKeyFill {
fn uniforms(self) -> Option<[f32; 7]> {
let values = [
self.height_dp,
self.curvature,
self.angle_radians,
self.saturation,
self.luma_gain,
self.offset,
f32::from(self.scale_with_surface),
];
(values.iter().all(|value| value.is_finite())
&& self.height_dp > 0.0
&& self.curvature > 0.0)
.then_some(values)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GlassSpectrum {
pub angle_radians: f32,
pub step_dp: f32,
pub vertical_scale: f32,
pub opacity_near: f32,
pub opacity_far: f32,
pub fade_depth_dp: f32,
pub extent_dp: f32,
}
impl GlassSpectrum {
fn uniforms(self) -> Option<[f32; 8]> {
let values = [
self.angle_radians,
self.step_dp,
self.vertical_scale,
self.opacity_near,
self.opacity_far,
self.fade_depth_dp,
self.extent_dp,
1.0,
];
(values.iter().all(|value| value.is_finite())
&& self.vertical_scale >= 0.0
&& (0.0..=1.0).contains(&self.opacity_near)
&& (0.0..=1.0).contains(&self.opacity_far)
&& self.fade_depth_dp >= 0.0
&& self.extent_dp >= 0.0)
.then_some(values)
}
fn capture_reach(self) -> f32 {
self.step_dp.abs() * 3.0 * self.vertical_scale.max(1.0)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GlassFaceResponse {
pub gain: f32,
pub start_dp: f32,
pub end_dp: f32,
pub illumination: f32,
}
impl GlassFaceResponse {
fn uniforms(self) -> Option<[f32; 4]> {
let values = [
1.0 - self.gain,
self.start_dp,
self.end_dp,
self.illumination,
];
(values.iter().all(|value| value.is_finite())
&& (0.0..=1.0).contains(&self.gain)
&& self.start_dp >= 0.0
&& self.end_dp >= self.start_dp)
.then_some(values)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GlassFaceTone {
pub black: f32,
pub white: f32,
pub saturation: f32,
pub max_luminance: f32,
}
impl GlassFaceTone {
fn uniforms(self) -> Option<[f32; 5]> {
let values = [
self.black,
self.white,
self.saturation,
self.max_luminance,
1.0,
];
(values.iter().all(|value| value.is_finite())
&& (0.0..=1.0).contains(&self.black)
&& self.white > self.black
&& self.saturation >= 0.0
&& (0.0..=1.0).contains(&self.max_luminance))
.then_some(values)
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Glass {
pub face_tone: Option<GlassFaceTone>,
pub variant: GlassVariant,
pub shape: LiquidShape,
pub tint: Option<Color>,
pub tint_transmission: Option<f32>,
pub tint_amount: Option<GlassTintAmount>,
pub pane_blur_radius: f32,
pub blur_radius: Option<f32>,
pub backdrop_blur: Option<(f32, f32)>,
pub saturation: Option<f32>,
pub refraction_depth: f32,
pub refraction_depth_dp: Option<f32>,
pub refraction: GlassRefraction,
pub refraction_curve: f32,
pub dispersion: f32,
pub edge_spectrum: Option<GlassSpectrum>,
pub transmission_refraction: f32,
pub meniscus_absorption: f32,
pub fold_depth: f32,
pub optical_zoom: f32,
pub rim_reflection: f32,
pub ink_recolor: Option<(Color, f32)>,
pub highlight: f32,
pub face_lighting: bool,
pub key_fill: Option<GlassKeyFill>,
pub contour_highlight: Option<GlassContourHighlight>,
pub specular_highlight: Option<GlassSpecularHighlight>,
pub face_response: Option<GlassFaceResponse>,
pub inner_shadow: Option<GlassShadow>,
pub lift: Option<f32>,
pub contrast: Option<f32>,
pub shadow: bool,
pub shadow_style: Option<GlassShadow>,
pub clip: bool,
pub foreground: Option<Color>,
pub adaptive_frost: f32,
pub adaptive_tone: bool,
pub resting_edge_sharpness: f32,
}
impl Glass {
pub fn regular() -> Self {
Self {
variant: GlassVariant::Regular,
face_tone: None,
shape: LiquidShape::Capsule,
tint: None,
tint_transmission: None,
tint_amount: None,
pane_blur_radius: 8.0,
blur_radius: None,
backdrop_blur: None,
saturation: None,
refraction_depth: 0.0,
refraction_depth_dp: None,
refraction: GlassRefraction::Radial,
refraction_curve: 0.25,
dispersion: 0.0,
edge_spectrum: None,
transmission_refraction: 0.0,
meniscus_absorption: 1.0,
fold_depth: 0.0,
optical_zoom: 1.0,
rim_reflection: 1.0,
ink_recolor: None,
highlight: 0.9,
face_lighting: true,
key_fill: None,
contour_highlight: None,
specular_highlight: None,
face_response: None,
inner_shadow: None,
lift: None,
contrast: None,
shadow: true,
shadow_style: None,
clip: true,
foreground: None,
adaptive_frost: 0.65,
adaptive_tone: false,
resting_edge_sharpness: 0.0,
}
}
pub fn clear() -> Self {
Self {
variant: GlassVariant::Clear,
..Self::regular()
}
}
pub fn lens() -> Self {
Self {
variant: GlassVariant::Lens,
tint: Some(Color::rgba(1.0, 1.0, 1.0, 0.07)),
refraction_depth: 0.34,
refraction_curve: 1.0,
dispersion: 0.30,
transmission_refraction: 1.0,
highlight: 1.15,
adaptive_frost: 0.0,
..Self::regular()
}
}
pub fn face_lighting(mut self, enabled: bool) -> Self {
self.face_lighting = enabled;
self
}
pub fn resting_edge_sharpness(mut self, sharpness: f32) -> Self {
self.resting_edge_sharpness = sharpness;
self
}
pub fn key_fill(mut self, lighting: GlassKeyFill) -> Self {
self.key_fill = Some(lighting);
self
}
pub fn face_response(mut self, response: GlassFaceResponse) -> Self {
self.face_response = Some(response);
self
}
pub fn inner_shadow(mut self, shadow: GlassShadow) -> Self {
self.inner_shadow = shadow.uniforms().map(|_| shadow);
self
}
pub fn shape(mut self, shape: LiquidShape) -> Self {
self.shape = shape;
self
}
pub fn tint(mut self, tint: Color) -> Self {
self.tint = Some(tint);
self
}
pub fn transmission_tint(mut self, tint: Color, black: f32) -> Self {
if black.is_finite() {
self.tint = Some(tint);
self.tint_transmission = Some(black.clamp(0.0, 1.0));
}
self
}
pub fn blur_radius(mut self, radius_dp: f32) -> Self {
self.blur_radius = Some(radius_dp);
self
}
pub fn saturation(mut self, saturation: f32) -> Self {
self.saturation = Some(saturation);
self
}
pub fn refraction_depth(mut self, fraction: f32) -> Self {
self.refraction_depth = fraction.clamp(0.0, 2.0);
self.refraction_depth_dp = None;
self
}
pub fn refraction_depth_dp(mut self, depth_dp: f32) -> Self {
self.refraction_depth_dp = Some(depth_dp.max(0.0));
self
}
pub fn surface_refraction(mut self, reach_dp: f32) -> Self {
self.refraction = GlassRefraction::Surface {
reach_dp: finite_nonnegative(reach_dp),
};
self
}
pub fn edge_spectrum(mut self, spectrum: GlassSpectrum) -> Self {
self.edge_spectrum = spectrum.uniforms().map(|_| spectrum);
self
}
pub fn edge_refraction(mut self, reach_dp: f32) -> Self {
self.refraction = GlassRefraction::EdgeLens {
reach_dp: finite_nonnegative(reach_dp),
};
self
}
pub fn refraction_curve(mut self, curve: f32) -> Self {
self.refraction_curve = curve.clamp(0.05, 1.0);
self
}
pub fn dispersion(mut self, strength: f32) -> Self {
self.dispersion = strength.clamp(0.0, 1.0);
self
}
pub fn transmission_refraction(mut self, strength: f32) -> Self {
self.transmission_refraction = strength.clamp(0.0, 1.0);
self
}
pub fn meniscus_absorption(mut self, strength: f32) -> Self {
self.meniscus_absorption = strength.clamp(0.0, 1.0);
self
}
pub fn fold_depth(mut self, depth_dp: f32) -> Self {
self.fold_depth = depth_dp.max(0.0);
self
}
pub fn optical_zoom(mut self, zoom: f32) -> Self {
self.optical_zoom = zoom.max(1.0);
self
}
pub fn rim_reflection(mut self, reflectivity: f32) -> Self {
self.rim_reflection = reflectivity.clamp(0.0, 2.0);
self
}
pub fn ink_recolor(mut self, color: Color, strength: f32) -> Self {
self.ink_recolor = Some((color, strength.clamp(0.0, 1.0)));
self
}
pub fn highlight(mut self, highlight: f32) -> Self {
self.highlight = highlight;
self
}
pub fn lift(mut self, lift: f32) -> Self {
self.lift = Some(lift);
self
}
pub fn contrast(mut self, contrast: f32) -> Self {
self.contrast = Some(contrast.max(0.05));
self
}
pub fn adaptive_frost(mut self, foreground: Color, strength: f32) -> Self {
self.foreground = Some(foreground);
self.adaptive_frost = strength.clamp(0.0, 1.0);
self
}
pub fn adaptive_tone(mut self, foreground: Color) -> Self {
self.face_tone = None;
self.foreground = Some(foreground);
self.adaptive_tone = true;
self.adaptive_frost = 0.0;
self
}
pub fn face_tone(mut self, tone: GlassFaceTone) -> Self {
self.face_tone = tone.uniforms().map(|_| tone);
self.adaptive_tone = false;
self.adaptive_frost = 0.0;
self
}
pub fn shadow(mut self, shadow: bool) -> Self {
self.shadow = shadow;
self
}
pub fn shadow_style(mut self, shadow: GlassShadow) -> Self {
self.shadow_style = Some(shadow);
self
}
pub fn no_clip(mut self) -> Self {
self.clip = false;
self
}
pub fn tint_amount(mut self, amount: GlassTintAmount) -> Self {
self.tint_amount = Some(amount);
self
}
pub fn pane_blur_radius(mut self, radius: f32) -> Self {
if radius.is_finite() && radius >= 0.0 {
self.pane_blur_radius = radius;
}
self
}
pub fn backdrop_blur(mut self, radius_dp: f32, opacity: f32) -> Self {
self.backdrop_blur = (radius_dp.is_finite() && opacity.is_finite())
.then_some((radius_dp.max(0.0), opacity.clamp(0.0, 1.0)));
self
}
fn default_blur_radius(&self) -> f32 {
match self.variant {
GlassVariant::Regular => 8.0,
GlassVariant::Clear => 3.0,
GlassVariant::Lens => 0.0,
}
}
fn default_saturation(&self) -> f32 {
match self.variant {
GlassVariant::Regular => 1.5,
GlassVariant::Clear => 1.25,
GlassVariant::Lens => 1.0,
}
}
pub fn backdrop_effect(
&self,
colors: &LiquidColors,
density: f32,
dynamics: GlassDynamics,
) -> RenderEffect {
self.resolve(colors).backdrop_effect(density, dynamics)
}
fn preferred_foreground(&self, colors: &LiquidColors) -> Color {
self.foreground
.filter(|color| {
[color.r(), color.g(), color.b(), color.a()]
.iter()
.all(|value| value.is_finite())
})
.unwrap_or(colors.label)
}
pub(crate) fn resolve(&self, colors: &LiquidColors) -> ResolvedGlass {
let lift = self.lift.unwrap_or(match (self.variant, colors.is_dark) {
(GlassVariant::Regular, false) => 0.42,
(GlassVariant::Regular, true) => -0.38,
(GlassVariant::Clear, false) => 0.12,
(GlassVariant::Clear, true) => -0.12,
(GlassVariant::Lens, false) => 0.10,
(GlassVariant::Lens, true) => -0.08,
});
let foreground = self.preferred_foreground(colors);
let shadow = self.shadow_style.unwrap_or_else(|| {
GlassShadow::new(
Color::BLACK.with_alpha(match (self.variant, colors.is_dark) {
(GlassVariant::Lens, false) => 0.14,
(GlassVariant::Lens, true) => 0.28,
(_, false) => 0.16,
(_, true) => 0.5,
}),
if self.variant == GlassVariant::Lens {
10.0
} else {
22.0
},
if self.variant == GlassVariant::Lens {
3.0
} else {
8.0
},
if self.variant == GlassVariant::Lens {
-6.0
} else {
-2.0
},
)
});
ResolvedGlass {
face_tone: self.face_tone,
shape: self.shape,
tint: self.tint.unwrap_or(colors.glass_tint),
tint_transmission: self.tint_transmission,
tint_amount: self.tint_amount,
pane_blur_radius: self.pane_blur_radius,
backdrop_blur: self.backdrop_blur,
blur_radius_dp: self
.blur_radius
.unwrap_or_else(|| self.default_blur_radius()),
saturation: self.saturation.unwrap_or_else(|| self.default_saturation()),
refraction_depth: self.refraction_depth,
refraction_depth_dp: self.refraction_depth_dp,
refraction: self.refraction,
refraction_curve: self.refraction_curve,
dispersion: self.dispersion,
edge_spectrum: self.edge_spectrum,
transmission_refraction: self.transmission_refraction,
meniscus_absorption: self.meniscus_absorption,
fold_depth: self.fold_depth,
optical_zoom: self.optical_zoom,
rim_reflection: self.rim_reflection,
ink_recolor: self.ink_recolor,
highlight: self.highlight,
face_lighting: self.face_lighting,
key_fill: self.key_fill,
contour_highlight: self.contour_highlight,
specular_highlight: self.specular_highlight,
face_response: self.face_response,
inner_shadow: self.inner_shadow,
lift,
contrast: self.contrast.unwrap_or(match self.variant {
GlassVariant::Lens => 1.0,
_ => 1.03,
}),
shadow: self.shadow,
clip: self.clip,
foreground_luma: 0.2126 * foreground.r()
+ 0.7152 * foreground.g()
+ 0.0722 * foreground.b(),
adaptive_frost: self.adaptive_frost,
adaptive_tone: self.adaptive_tone,
resting_edge_sharpness: finite_nonnegative(self.resting_edge_sharpness).min(1.0),
rim_style: if self.variant == GlassVariant::Lens {
1.0
} else {
0.0
},
shadow_color: shadow.color,
shadow_radius: shadow.radius,
shadow_offset_y: shadow.offset_y,
shadow_spread: shadow.spread,
}
}
}
impl Default for Glass {
fn default() -> Self {
Self::regular()
}
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct ResolvedGlass {
specular_highlight: Option<GlassSpecularHighlight>,
face_tone: Option<GlassFaceTone>,
resting_edge_sharpness: f32,
pub shape: LiquidShape,
pub tint: Color,
tint_transmission: Option<f32>,
tint_amount: Option<GlassTintAmount>,
pane_blur_radius: f32,
backdrop_blur: Option<(f32, f32)>,
pub blur_radius_dp: f32,
pub saturation: f32,
pub refraction_depth: f32,
pub refraction_depth_dp: Option<f32>,
pub refraction: GlassRefraction,
pub refraction_curve: f32,
pub dispersion: f32,
pub edge_spectrum: Option<GlassSpectrum>,
pub transmission_refraction: f32,
pub meniscus_absorption: f32,
pub fold_depth: f32,
pub optical_zoom: f32,
pub rim_reflection: f32,
pub ink_recolor: Option<(Color, f32)>,
pub highlight: f32,
pub face_lighting: bool,
pub key_fill: Option<GlassKeyFill>,
pub contour_highlight: Option<GlassContourHighlight>,
pub face_response: Option<GlassFaceResponse>,
pub lift: f32,
pub inner_shadow: Option<GlassShadow>,
pub contrast: f32,
pub shadow: bool,
pub clip: bool,
pub rim_style: f32,
pub foreground_luma: f32,
pub adaptive_frost: f32,
pub adaptive_tone: bool,
pub shadow_color: Color,
pub shadow_radius: f32,
pub shadow_offset_y: f32,
pub shadow_spread: f32,
}
fn set_edge_return_depth(shader: &mut RuntimeShader, depth: Option<f32>) {
if let Some(depth) = depth.filter(|depth| depth.is_finite() && *depth >= 0.0) {
shader.set_float2(GLASS_EDGE_RETURN_DEPTH_UNIFORM, depth, 1.0);
}
}
impl ResolvedGlass {
fn placeholder_shape(&self, morph: Option<&GlassMorph>) -> PlaceholderShape {
let Some(morph) = morph else {
return PlaceholderShape {
bounds: Rect {
x: 0.0,
y: 0.0,
width: 1.0,
height: 1.0,
},
corner_radius: self.shape.radius_dp(),
};
};
let (node_width, node_height) = morph.node_size;
let (node_width, node_height) =
(node_width.max(f32::EPSILON), node_height.max(f32::EPSILON));
let added = morph.shapes.iter().filter(|&&(.., radius)| radius > -1.5);
let (left, top, right, bottom) = std::iter::once(&morph.primary).chain(added).fold(
(f32::MAX, f32::MAX, f32::MIN, f32::MIN),
|(left, top, right, bottom), &(center_x, center_y, width, height, _)| {
(
left.min(center_x - width * 0.5),
top.min(center_y - height * 0.5),
right.max(center_x + width * 0.5),
bottom.max(center_y + height * 0.5),
)
},
);
let (.., radius) = morph.primary;
PlaceholderShape {
bounds: Rect {
x: left / node_width,
y: top / node_height,
width: (right - left) / node_width,
height: (bottom - top) / node_height,
},
corner_radius: if radius < 0.0 { f32::MAX } else { radius },
}
}
pub(crate) fn without_transparency(mut self, colors: &LiquidColors) -> Self {
self.tint = colors.surface;
self.tint_transmission = None;
self.tint_amount = None;
self.backdrop_blur = None;
self.face_tone = None;
self.contour_highlight = None;
self.specular_highlight = None;
self.adaptive_tone = false;
self.blur_radius_dp = 0.0;
self.saturation = 1.0;
self.refraction_depth = 0.0;
self.refraction_depth_dp = None;
self.dispersion = 0.0;
self.edge_spectrum = None;
self.transmission_refraction = 0.0;
self.meniscus_absorption = 0.0;
self.rim_reflection = 0.0;
self.adaptive_frost = 0.0;
self
}
fn clips_in_shader(&self) -> bool {
self.key_fill.and_then(GlassKeyFill::uniforms).is_some()
}
pub(crate) fn backdrop_effect(&self, density: f32, dynamics: GlassDynamics) -> RenderEffect {
self.runtime_effect(density, &dynamics, false)
}
fn blur_radii(&self, density: f32, activity: f32, content_mask: bool) -> (f32, f32) {
if content_mask || self.tint_amount.is_some() {
return (0.0, 0.0);
}
let radius = self.blur_radius_dp * density * activity;
if radius > WCKSRD_OPTICAL_BLUR_RADIUS_PX {
(0.0, radius)
} else {
(radius, 0.0)
}
}
fn runtime_effect(
&self,
density: f32,
dynamics: &GlassDynamics,
content_mask: bool,
) -> RenderEffect {
self.runtime_effect_with_content(density, dynamics, content_mask, false)
}
fn set_refraction_uniforms(
&self,
shader: &mut RuntimeShader,
dynamics: &GlassDynamics,
activity: f32,
) -> (f32, f32, f32) {
let press_depth = dynamics.press_depth.unwrap_or(1.0).clamp(0.0, 1.0);
shader.set_float(9, self.refraction_depth * activity * press_depth);
let refraction = dynamics.refraction.unwrap_or(self.refraction);
let (refraction_mode, refraction_reach) = refraction.shader_parameters();
let refraction_weight = if matches!(refraction, GlassRefraction::LayeredSurface { .. }) {
1.0
} else {
activity * press_depth
};
shader.set_float(GLASS_REFRACTION_MODE_UNIFORM, refraction_mode);
if let GlassRefraction::LayeredSurface {
return_reach_dp,
return_depth_dp,
..
} = refraction
{
shader.set_float2(
GLASS_LAYERED_RETURN_UNIFORM,
finite_nonnegative(return_reach_dp),
finite_nonnegative(return_depth_dp),
);
}
set_edge_return_depth(shader, dynamics.edge_return_depth_dp);
shader.set_float(
GLASS_EDGE_REFRACTION_REACH_UNIFORM,
refraction_reach * refraction_weight,
);
shader.set_float(
GLASS_PHYSICAL_REFRACTION_DEPTH_UNIFORM,
self.refraction_depth_dp.unwrap_or(0.0) * refraction_weight,
);
shader.set_float(
GLASS_PHYSICAL_REFRACTION_DEPTH_ENABLED_UNIFORM,
if self.refraction_depth_dp.is_some() {
1.0
} else {
0.0
},
);
shader.set_float(
GLASS_REFRACTION_CURVE_UNIFORM,
self.refraction_curve * activity,
);
shader.set_float(
GLASS_DISPERSION_UNIFORM,
self.dispersion * activity * press_depth,
);
let spectrum_reach = self.set_spectrum_uniforms(shader);
shader.set_float(
GLASS_TRANSMISSION_REFRACTION_UNIFORM,
self.transmission_refraction * if refraction_mode > 2.5 { 1.0 } else { activity },
);
shader.set_float(
GLASS_MENISCUS_ABSORPTION_UNIFORM,
self.meniscus_absorption * press_depth,
);
shader.set_float(
GLASS_FOLD_DEPTH_UNIFORM,
self.fold_depth.max(0.0) * press_depth,
);
(refraction_mode, refraction_reach, spectrum_reach)
}
fn set_shadow_uniforms(
&self,
shader: &mut RuntimeShader,
dynamics: &GlassDynamics,
activity: f32,
) -> (f32, f32) {
let dynamic_shadow = !self.clip && self.shadow;
let shadow = dynamics
.shadow
.filter(|shadow| shadow.uniforms().is_some())
.unwrap_or_else(|| {
GlassShadow::new(
self.shadow_color
.with_alpha(self.shadow_color.a() * 0.55 * activity),
self.shadow_radius,
self.shadow_offset_y,
self.shadow_spread,
)
});
shader.set_float(
102,
if dynamic_shadow {
shadow.color.a()
} else {
0.0
},
);
shader.set_float(103, shadow.radius);
shader.set_float(104, shadow.offset_y);
shader.set_float(105, shadow.spread);
shader.set_float4(
cranpose_ui_graphics::GLASS_SHADOW_COLOR_UNIFORM,
shadow.color.r(),
shadow.color.g(),
shadow.color.b(),
0.0,
);
let ring_shadow = dynamics.ring_shadow.filter(|(ring, width)| {
ring.color.a() > 0.0 && ring.uniforms().is_some() && width.is_finite() && *width > 0.0
});
if let Some((ring, width)) = ring_shadow {
shader.set_float4(
cranpose_ui_graphics::GLASS_RING_SHADOW_UNIFORM,
ring.color.r(),
ring.color.g(),
ring.color.b(),
ring.color.a(),
);
shader.set_float4(
cranpose_ui_graphics::GLASS_RING_SHADOW_UNIFORM + 4,
ring.radius,
ring.offset_y,
width,
1.0,
);
shader.set_float(
cranpose_ui_graphics::GLASS_RING_SHADOW_UNIFORM + 8,
ring.spread,
);
}
let ring_reach = ring_shadow.map_or(0.0, |(ring, width)| {
3.0 * ring.radius + ring.offset_y.abs() + width * 0.5 + ring.spread.abs()
});
let contour_reach = self
.contour_highlight
.and_then(GlassContourHighlight::uniforms)
.filter(|values| values[2] > 0.0 && activity > 0.0)
.map_or(0.0, |values| (-values[1]).max(0.0));
shader.set_output_padding(ring_reach.max(contour_reach));
let visible_shadow = dynamic_shadow && shadow.color.a() > 0.0;
let shadow_reach = if visible_shadow {
shadow.radius + shadow.offset_y.abs() + shadow.spread.max(0.0)
} else {
0.0
}
.max(ring_reach)
.max(contour_reach);
let offset = if visible_shadow || ring_shadow.is_some() {
shadow
.offset_y
.abs()
.max(ring_shadow.map_or(0.0, |(ring, _)| ring.offset_y.abs()))
} else {
0.0
};
(shadow_reach, offset)
}
fn runtime_effect_with_content(
&self,
density: f32,
dynamics: &GlassDynamics,
content_mask: bool,
separate_content: bool,
) -> RenderEffect {
let density = density.max(f32::EPSILON);
let activity = dynamics
.activity
.filter(|value| value.is_finite())
.unwrap_or(1.0)
.clamp(0.0, 1.0);
static SHADER: OnceLock<RuntimeShader> = OnceLock::new();
let mut shader = SHADER
.get_or_init(|| {
let mut shader = RuntimeShader::new(LIQUID_GLASS_WGSL);
shader.set_float(GLASS_ACTIVITY_UNIFORM, 1.0);
shader.set_float2(GLASS_OPTICAL_ZOOM_ANCHOR_UNIFORM, 0.0, 0.0);
specialize_liquid_glass(&mut shader);
shader
})
.clone();
if let Some(morph) = dynamics.morph.as_ref() {
set_morph_uniforms(&mut shader, morph, activity);
} else {
shader.set_float2(0, 0.0, 0.0);
shader.set_float(6, self.shape.shader_radius_px(density));
}
let projection = dynamics.projection();
shader.set_float2(GLASS_OPTICAL_PROJECTION_UNIFORM, projection.0, projection.1);
let (refraction_mode, refraction_reach, spectrum_reach) =
self.set_refraction_uniforms(&mut shader, dynamics, activity);
shader.set_float(
GLASS_OPTICAL_ZOOM_UNIFORM,
1.0 + (self.optical_zoom - 1.0).max(0.0) * activity,
);
let zoom_anchor = dynamics
.morph
.as_ref()
.map_or((0.0, 0.0), |morph| morph.zoom_anchor);
shader.set_float2(
GLASS_OPTICAL_ZOOM_ANCHOR_UNIFORM,
zoom_anchor.0,
zoom_anchor.1,
);
shader.set_float(121, self.rim_reflection.max(0.001));
let (ink_color, ink_strength) = self
.ink_recolor
.map_or((Color::TRANSPARENT, 0.0), |(color, strength)| {
(color, strength * activity)
});
shader.set_float(124, ink_color.r());
shader.set_float(125, ink_color.g());
shader.set_float(126, ink_color.b());
shader.set_float(127, ink_strength);
let (light_x, light_y) = glass_light_direction();
shader.set_float(GLASS_LIGHT_DIRECTION_UNIFORM, light_x);
shader.set_float(GLASS_LIGHT_DIRECTION_UNIFORM + 1, light_y);
self.set_lighting_uniforms(&mut shader, dynamics);
shader.set_float(GLASS_EFFECT_DENSITY_UNIFORM, density);
shader.set_float(
11,
(self.highlight + dynamics.highlight_boost).clamp(0.0, 2.0) * activity,
);
let dynamic_tint = boost_tint_saturation(self.tint, dynamics.saturation_boost);
let dynamic_tint_alpha = (dynamic_tint.a()
* dynamics
.tint_alpha_multiplier
.unwrap_or(1.0)
.clamp(0.0, 2.0)
* activity)
.clamp(0.0, 1.0);
shader.set_float4(
14,
dynamic_tint.r(),
dynamic_tint.g(),
dynamic_tint.b(),
dynamic_tint_alpha,
);
if let Some((color, progress)) = dynamics.tint_crossfade.filter(|(_, p)| p.is_finite()) {
let index = cranpose_ui_graphics::liquid_glass::GLASS_TINT_CROSSFADE_UNIFORM;
shader.set_float(index, 1.0 + progress.clamp(0.0, 1.0));
shader.set_float4(index + 1, color.r(), color.g(), color.b(), color.a());
}
let saturation = (self.saturation + dynamics.saturation_boost).max(0.0);
shader.set_float(18, 1.0 + (saturation - 1.0) * activity);
shader.set_float(20, self.lift * activity);
shader.set_float(21, 0.5 * activity);
shader.set_float2(22, 0.0, 1.0);
shader.set_float(24, 1.0 + (self.contrast - 1.0) * activity);
shader.set_float(28, self.rim_style * activity);
let (wcksrd_blur_radius, gaussian_blur_radius) =
self.blur_radii(density, activity, content_mask);
shader.set_float(GLASS_BLUR_RADIUS_UNIFORM, wcksrd_blur_radius);
shader.set_float(GLASS_ACTIVITY_UNIFORM, activity);
shader.set_float(
GLASS_RESTING_EDGE_SHARPNESS_UNIFORM,
self.resting_edge_sharpness,
);
let resting_tint = dynamics.resting_tint.unwrap_or(Color::TRANSPARENT);
shader.set_float4(
GLASS_RESTING_TINT_UNIFORM,
resting_tint.r(),
resting_tint.g(),
resting_tint.b(),
resting_tint.a(),
);
shader.set_float(112, if content_mask { 1.0 } else { 0.0 });
shader.set_float(GLASS_ADAPTIVE_FROST_UNIFORM, self.adaptive_frost * activity);
shader.set_float(97, self.foreground_luma);
shader.set_float(GLASS_ADAPTIVE_TONE_UNIFORM, f32::from(self.adaptive_tone));
self.set_backdrop_uniforms(&mut shader, density, content_mask);
shader.set_float(
cranpose_ui_graphics::GLASS_FOREGROUND_CONTENT_UNIFORM,
f32::from(separate_content),
);
let (shadow_reach, shadow_offset) = if content_mask {
(0.0, 0.0)
} else {
self.set_shadow_uniforms(&mut shader, dynamics, activity)
};
let morph_pad = dynamics.morph.as_ref().map_or(0.0, |morph| {
let (px, py, pw, ph, _) = morph.primary;
let (left, top) = (px - pw * 0.5, py - ph * 0.5);
let (right, bottom) = (px + pw * 0.5, py + ph * 0.5);
let mut shape_reach = 0.0f32;
for (sx, sy, sw, sh, _) in &morph.shapes {
let reach_x = ((sx + sw * 0.5) - right)
.max(left - (sx - sw * 0.5))
.max(0.0);
let reach_y = ((sy + sh * 0.5) - bottom)
.max(top - (sy - sh * 0.5))
.max(0.0);
shape_reach = shape_reach.max(reach_x.max(reach_y));
}
let glue_pad = if morph.shapes.is_empty() {
0.0
} else {
morph.glue * 2.0
};
morph.wobble_amplitude * 2.0 + morph.bulge_amplitude + shape_reach + glue_pad
});
shader.set_input_padding(if content_mask {
0.0
} else {
(self.input_padding()
+ if refraction_mode > 2.5 {
refraction_reach + spectrum_reach
} else if refraction_mode >= 1.5 {
refraction_reach * (26.5 / 9.0) + spectrum_reach
} else {
refraction_reach
}
+ morph_pad
+ wcksrd_blur_radius / density)
* projection.0.max(projection.1).max(1.0)
});
if let Some(morph) = dynamics.morph.as_ref() {
let support =
morph_output_support(morph, activity, morph_pad, shadow_reach, shadow_offset);
let (cx, cy, _, _, _) = morph.primary;
let support = Rect {
x: cx + (support.x - cx) * projection.0,
y: cy + (support.y - cy) * projection.1,
width: support.width * projection.0,
height: support.height * projection.1,
};
let (node_w, node_h) = morph.node_size;
let overhang = (-support.x)
.max(-support.y)
.max(support.x + support.width - node_w)
.max(support.y + support.height - node_h)
.max(0.0);
shader.set_output_padding((morph_pad + shadow_reach + 4.0).max(overhang));
shader.set_output_support(Some(support));
}
shader.set_placeholder(Some(liquid_glass_placeholder(
shown_tint(
Color(
dynamic_tint.r(),
dynamic_tint.g(),
dynamic_tint.b(),
dynamic_tint_alpha,
),
dynamics.tint_crossfade,
),
Some(self.placeholder_shape(dynamics.morph.as_ref())),
)));
let optical_effect = liquid_glass_runtime_effect(shader);
if gaussian_blur_radius > f32::EPSILON {
RenderEffect::blur_with_edge_treatment(gaussian_blur_radius, TileMode::Mirror)
.then(optical_effect)
} else {
optical_effect
}
}
fn set_backdrop_uniforms(&self, shader: &mut RuntimeShader, density: f32, content_mask: bool) {
if let Some(values) = self.face_tone.and_then(GlassFaceTone::uniforms) {
for (index, value) in values.into_iter().enumerate() {
shader.set_float(cranpose_ui_graphics::GLASS_FACE_TONE_UNIFORM + index, value);
}
}
if let Some(amount) = self.tint_amount {
shader.set_float(
cranpose_ui_graphics::GLASS_PANE_BLEND_UNIFORM,
self.pane_blur_radius * density,
);
shader.set_float(
cranpose_ui_graphics::GLASS_PANE_BLEND_UNIFORM + 1,
amount.percent() / 100.0,
);
}
if !content_mask && let Some((radius, opacity)) = self.backdrop_blur {
shader.set_float2(
cranpose_ui_graphics::GLASS_BACKDROP_BLUR_UNIFORM,
radius * density,
opacity,
);
}
}
fn set_spectrum_uniforms(&self, shader: &mut RuntimeShader) -> f32 {
let spectrum = self
.edge_spectrum
.and_then(|spectrum| spectrum.uniforms().map(|values| (spectrum, values)));
if let Some((spectrum, values)) = spectrum {
for (index, value) in values.into_iter().enumerate() {
shader.set_float(GLASS_EDGE_SPECTRUM_UNIFORM + index, value);
}
spectrum.capture_reach()
} else {
40.787 * self.dispersion
}
}
fn set_lighting_uniforms(&self, shader: &mut RuntimeShader, dynamics: &GlassDynamics) {
if let Some(values) = self
.specular_highlight
.and_then(GlassSpecularHighlight::uniforms)
{
for (index, value) in values.into_iter().enumerate() {
shader.set_float(
cranpose_ui_graphics::GLASS_SPECULAR_HIGHLIGHT_UNIFORM + index,
value,
);
}
}
shader.set_float(
cranpose_ui_graphics::GLASS_CONTACT_LIGHT_UNIFORM,
f32::from(dynamics.contact_lighting),
);
if let Some(black) = self.tint_transmission.filter(|value| value.is_finite()) {
shader.set_float2(
cranpose_ui_graphics::GLASS_TINT_TRANSMISSION_UNIFORM,
black.clamp(0.0, 1.0),
1.0,
);
}
let (touch_x, touch_y, touch_intensity) = dynamics.touch.unwrap_or((0.0, 0.0, 0.0));
shader.set_float(118, touch_x);
shader.set_float(119, touch_y);
shader.set_float(120, touch_intensity.clamp(0.0, 1.0));
shader.set_float(
GLASS_FACE_LIGHTING_OFF_UNIFORM,
f32::from(!self.face_lighting),
);
shader.set_float(
GLASS_TOUCH_RADIUS_UNIFORM,
dynamics
.touch_radius_dp
.filter(|radius| radius.is_finite() && *radius > 0.0)
.unwrap_or(58.0),
);
shader.set_float(
GLASS_LAYER_CLIPPED_UNIFORM,
f32::from(self.clip && !self.clips_in_shader()),
);
if let Some(values) = self.key_fill.and_then(GlassKeyFill::uniforms) {
for (index, value) in values.into_iter().enumerate() {
shader.set_float(GLASS_KEY_FILL_UNIFORM + index, value);
}
}
if let Some(values) = self.face_response.and_then(GlassFaceResponse::uniforms) {
for (index, value) in values.into_iter().enumerate() {
shader.set_float(GLASS_FACE_RESPONSE_UNIFORM + index, value);
}
}
if let Some(values) = self
.contour_highlight
.and_then(GlassContourHighlight::uniforms)
{
for (index, value) in values.into_iter().enumerate() {
shader.set_float(
cranpose_ui_graphics::GLASS_CONTOUR_HIGHLIGHT_UNIFORM + index,
value,
);
}
}
if let Some(values) = self.inner_shadow.and_then(GlassShadow::uniforms) {
for (index, value) in values.into_iter().enumerate() {
shader.set_float(GLASS_INNER_SHADOW_UNIFORM + index, value);
}
}
}
fn input_padding(&self) -> f32 {
2.0
}
}
pub trait LiquidModifierExt {
fn glass_effect(self, glass: Glass) -> Modifier;
fn glass_effect_with(
self,
glass: Glass,
dynamics: impl Fn() -> GlassDynamics + 'static,
) -> Modifier;
}
impl LiquidModifierExt for Modifier {
fn glass_effect(self, glass: Glass) -> Modifier {
self.glass_effect_with(glass, GlassDynamics::default)
}
fn glass_effect_with(
self,
glass: Glass,
dynamics: impl Fn() -> GlassDynamics + 'static,
) -> Modifier {
let colors = crate::theme::liquid_colors();
let options = cranpose_services::local_accessibility_options().current();
let resolved = if options.reduce_transparency {
glass.resolve(&colors).without_transparency(&colors)
} else {
glass.resolve(&colors)
};
let shape = resolved.shape;
let mut modifier = self;
if resolved.shadow && resolved.clip {
let shadow_color = resolved.shadow_color;
let (radius, offset_y, spread) = (
resolved.shadow_radius,
resolved.shadow_offset_y,
resolved.shadow_spread,
);
modifier = modifier.drop_shadow(shape.layer_shape(), move |scope| {
scope.radius = radius;
scope.spread = spread;
scope.offset.y = offset_y;
scope.color = shadow_color;
scope.cutout = true;
});
}
let layer = cached_glass_layer(resolved);
modifier.graphics_layer(move || layer(current_density(), dynamics()))
}
}
struct CachedGlassLayer<T> {
density: u32,
light: [u32; 2],
dynamics: GlassDynamics,
value: T,
}
fn cached_glass_layer(resolved: ResolvedGlass) -> impl Fn(f32, GlassDynamics) -> GraphicsLayer {
cached_glass_layers(resolved, false, std::convert::identity)
}
pub(crate) fn cached_glass_content_layers(
resolved: ResolvedGlass,
) -> impl Fn(f32, GlassDynamics) -> [GraphicsLayer; 2] {
cached_glass_layers(resolved, true, |mut layer| {
let Some(RenderEffect::Chain { first, second }) = layer.backdrop_effect.take() else {
panic!("content layers require a sequential edge lens");
};
layer.backdrop_effect = Some((*second).clone());
[
GraphicsLayer {
backdrop_effect: Some((*first).clone()),
..Default::default()
},
layer,
]
})
}
fn cached_glass_layers<T: Clone>(
resolved: ResolvedGlass,
separate_content: bool,
assemble: impl Fn(GraphicsLayer) -> T,
) -> impl Fn(f32, GlassDynamics) -> T {
let cached = RefCell::new(None::<CachedGlassLayer<T>>);
move |density, dynamics| {
let direction = glass_light_direction();
let light = [direction.0, direction.1].map(f32::to_bits);
let mut cached = cached.borrow_mut();
if let Some(previous) = &*cached
&& previous.density == density.to_bits()
&& previous.light == light
&& glass_dynamics_match(&previous.dynamics, &dynamics)
{
return previous.value.clone();
}
let render_effect = ((!resolved.clip && dynamics.morph.is_some())
|| (resolved.clip && resolved.clips_in_shader()))
.then(|| resolved.runtime_effect(density, &dynamics, true));
let layer = GraphicsLayer {
backdrop_effect: Some(resolved.runtime_effect_with_content(
density,
&dynamics,
false,
separate_content,
)),
render_effect,
shape: resolved.shape.layer_shape(),
clip: resolved.clip && !resolved.clips_in_shader(),
..Default::default()
};
let value = assemble(layer);
*cached = Some(CachedGlassLayer {
density: density.to_bits(),
light,
dynamics,
value: value.clone(),
});
value
}
}
fn glass_dynamics_match(a: &GlassDynamics, b: &GlassDynamics) -> bool {
let bits = |d: &GlassDynamics| {
let GlassDynamics {
contact_lighting,
refraction,
shadow,
ring_shadow,
edge_return_depth_dp,
optical_projection,
activity,
resting_tint,
highlight_boost,
saturation_boost,
tint_alpha_multiplier,
tint_crossfade,
morph: _,
touch,
touch_radius_dp,
press_depth,
} = d;
(
(
*contact_lighting,
ring_shadow.map(|(ring, width)| (shadow_bits(ring), width.to_bits())),
tint_crossfade.map(|(Color(r, g, b, a), p)| [r, g, b, a, p].map(f32::to_bits)),
),
refraction.map(|refraction| {
match refraction {
GlassRefraction::Radial => [0.0, 0.0, 0.0, 0.0],
GlassRefraction::Surface { reach_dp } => [1.0, reach_dp, 0.0, 0.0],
GlassRefraction::EdgeLens { reach_dp } => [2.0, reach_dp, 0.0, 0.0],
GlassRefraction::LayeredSurface {
reach_dp,
return_reach_dp,
return_depth_dp,
} => [3.0, reach_dp, return_reach_dp, return_depth_dp],
}
.map(f32::to_bits)
}),
shadow.map(shadow_bits),
edge_return_depth_dp.map(f32::to_bits),
optical_projection.map(|(x, y)| [x, y].map(f32::to_bits)),
activity.map(f32::to_bits),
resting_tint.map(|Color(r, g, b, a)| [r, g, b, a].map(f32::to_bits)),
[*highlight_boost, *saturation_boost].map(f32::to_bits),
tint_alpha_multiplier.map(f32::to_bits),
touch.map(|(x, y, strength)| [x, y, strength].map(f32::to_bits)),
press_depth.map(f32::to_bits),
touch_radius_dp.map(f32::to_bits),
)
};
bits(a) == bits(b)
&& match (&a.morph, &b.morph) {
(None, None) => true,
(Some(a), Some(b)) => glass_morphs_match(a, b),
_ => false,
}
}
fn shadow_bits(shadow: GlassShadow) -> [u32; 7] {
[
shadow.color.r(),
shadow.color.g(),
shadow.color.b(),
shadow.color.a(),
shadow.radius,
shadow.offset_y,
shadow.spread,
]
.map(f32::to_bits)
}
fn glass_morphs_match(a: &GlassMorph, b: &GlassMorph) -> bool {
let shape_bits =
|&(x, y, w, h, r): &(f32, f32, f32, f32, f32)| [x, y, w, h, r].map(f32::to_bits);
let bits = |m: &GlassMorph| {
let GlassMorph {
node_size,
primary,
shapes: _,
glue,
wobble_amplitude,
wobble_phase,
bulge_amplitude,
bulge_direction,
ellipse_blend,
capsule_smoothing_dp,
deformation,
zoom_anchor,
} = m;
(
[
node_size.0,
node_size.1,
*glue,
*wobble_amplitude,
*wobble_phase,
*bulge_amplitude,
*bulge_direction,
*ellipse_blend,
*capsule_smoothing_dp,
zoom_anchor.0,
zoom_anchor.1,
]
.map(f32::to_bits),
shape_bits(primary),
deformation
.map(|GlassDeformation { axis, along }| [axis.0, axis.1, along].map(f32::to_bits)),
)
};
bits(a) == bits(b)
&& a.shapes
.iter()
.map(shape_bits)
.eq(b.shapes.iter().map(shape_bits))
}
fn morph_output_support(
morph: &GlassMorph,
activity: f32,
morph_pad: f32,
shadow_reach: f32,
shadow_offset: f32,
) -> Rect {
let (px, py, pw, ph, _) = morph.primary;
let (along, (ax, ay)) = morph.deformation.map_or((1.0, (1.0, 0.0)), |deformation| {
(
1.0 + (deformation.along() - 1.0) * activity,
deformation.axis(),
)
});
let across = 1.0 / along;
let smallest_strain = along.min(across);
let reach = (morph_pad + shadow_reach + 4.0) / smallest_strain;
let rows = [
(
(along * ax * ax + across * ay * ay).abs(),
((along - across) * ax * ay).abs(),
),
(
((along - across) * ax * ay).abs(),
(along * ay * ay + across * ax * ax).abs(),
),
];
let half = (pw * 0.5 + reach, ph * 0.5 + reach);
let extent_x = rows[0].0 * half.0 + rows[0].1 * half.1;
let extent_y = rows[1].0 * half.0 + rows[1].1 * half.1;
let (mut left, mut top) = (px - extent_x, py - extent_y);
let (mut right, mut bottom) = (px + extent_x, py + extent_y);
for (sx, sy, sw, sh, _) in &morph.shapes {
left = left.min(sx - sw * 0.5 - reach);
top = top.min(sy - sh * 0.5 - reach);
right = right.max(sx + sw * 0.5 + reach);
bottom = bottom.max(sy + sh * 0.5 + reach);
}
Rect {
x: left,
y: top - shadow_offset,
width: right - left,
height: bottom - top + 2.0 * shadow_offset,
}
}
fn set_morph_uniforms(shader: &mut RuntimeShader, morph: &GlassMorph, activity: f32) {
let (node_w, node_h) = morph.node_size;
let (cx, cy, w, h, radius) = morph.primary;
shader.set_float2(0, node_w.max(1.0), node_h.max(1.0));
shader.set_float2(2, cx, cy);
shader.set_float2(4, w, h);
shader.set_float(6, radius);
let count = morph.shapes.len().min(GlassMorph::MAX_SHAPES);
shader.set_float(30, count as f32);
for (index, (sx, sy, sw, sh, sr)) in morph.shapes.iter().take(count).enumerate() {
let base = 36 + index * 5;
shader.set_float(base, *sx);
shader.set_float(base + 1, *sy);
shader.set_float(base + 2, *sw);
shader.set_float(base + 3, *sh);
shader.set_float(base + 4, *sr);
}
shader.set_float(31, morph.glue);
shader.set_float(32, morph.wobble_amplitude * activity);
shader.set_float(33, morph.wobble_phase);
shader.set_float(26, morph.bulge_amplitude * activity);
shader.set_float(27, morph.bulge_direction);
shader.set_float(110, morph.ellipse_blend.clamp(0.0, 1.0) * activity);
shader.set_float(
cranpose_ui_graphics::liquid_glass::GLASS_CAPSULE_SMOOTHING_UNIFORM,
if morph.capsule_smoothing_dp.is_finite() {
morph.capsule_smoothing_dp.max(0.0) * activity
} else {
0.0
},
);
if let Some(deformation) = morph.deformation {
let axis = deformation.axis();
let along = 1.0 + (deformation.along() - 1.0) * activity;
shader.set_float2(106, axis.0, axis.1);
shader.set_float(108, along);
shader.set_float(109, 1.0 / along);
} else {
shader.set_float2(106, 1.0, 0.0);
shader.set_float2(108, 1.0, 1.0);
}
}
#[cfg(test)]
#[path = "tests/material_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "tests/material_transparency_tests.rs"]
mod transparency_tests;