1use cranpose_ui_graphics::{Color, CornerRadii, GraphicsLayer, Rect, RoundedCornerShape};
7
8use crate::layer_transform::layer_uniform_scale;
9
10const MIN_LAYER_SHADOW_SCALE: f32 = 0.1;
11const AMBIENT_SHADOW_ALPHA: f32 = 0.039;
15const SPOT_SHADOW_ALPHA: f32 = 0.19;
16const LIGHT_Y: f32 = 0.0;
18const LIGHT_Z: f32 = 500.0;
19const LIGHT_RADIUS: f32 = 800.0;
20const LIGHT_Z_REFERENCE: f32 = 450.0;
23const MAX_AMBIENT_REACH_PIXELS: f32 = 150.0;
26const FALLOFF_TEXELS: f32 = 128.0;
29const FALLOFF_FLOOR: f32 = 0.018;
30
31#[derive(Clone, Copy, Debug, PartialEq)]
34pub struct ShadowLight {
35 pub x: f32,
36 pub y: f32,
37 pub z: f32,
38 pub radius: f32,
39 pub pixels_per_unit: f32,
42}
43
44impl ShadowLight {
45 pub fn for_window(width: f32, height: f32, units_per_dp: f32, pixels_per_unit: f32) -> Self {
50 let units_per_dp = units_per_dp.max(f32::EPSILON);
51 let window_dp = width.min(height).max(0.0) / units_per_dp;
52 let adjustment = (window_dp / LIGHT_Z_REFERENCE + 2.0) / 3.0;
53 Self {
54 x: width / 2.0,
55 y: LIGHT_Y * units_per_dp,
56 z: LIGHT_Z * units_per_dp * adjustment,
57 radius: LIGHT_RADIUS * units_per_dp,
58 pixels_per_unit,
59 }
60 }
61
62 pub fn in_space(self, origin_x: f32, origin_y: f32, scale: f32) -> Self {
65 let scale = scale.max(MIN_LAYER_SHADOW_SCALE);
66 Self {
67 x: (self.x - origin_x) / scale,
68 y: (self.y - origin_y) / scale,
69 z: self.z / scale,
70 radius: self.radius / scale,
71 pixels_per_unit: self.pixels_per_unit * scale,
72 }
73 }
74}
75
76#[derive(Clone, Copy, Debug, PartialEq)]
83pub struct ShadowRRect {
84 pub bounds: Rect,
86 pub radii: [f32; 4],
89 pub umbra_inset: f32,
91 pub distance_correction: f32,
93 pub hole: Option<ShadowHole>,
95}
96
97#[derive(Clone, Copy, Debug, PartialEq)]
100pub struct ShadowHole {
101 pub inset: f32,
102 pub radius: f32,
103}
104
105impl ShadowRRect {
106 fn new(outer: Rect, radii: [f32; 4], blur: f32, inset_width: f32) -> Option<Self> {
110 let half_side = 0.5 * outer.width.min(outer.height);
111 if half_side <= 0.0 || blur <= 0.0 {
112 return None;
113 }
114 let largest = radii.into_iter().fold(0.0, f32::max);
115 let circle = (outer.width - outer.height).abs() <= f32::EPSILON * outer.width
116 && largest >= half_side;
117 let (umbra_inset, hole) = if circle {
118 let inner = half_side - inset_width;
119 let hole = (inner > 0.0).then_some(ShadowHole {
120 inset: inset_width,
121 radius: inner,
122 });
123 (half_side, hole)
124 } else {
125 let umbra = largest.max(blur);
126 let hole = (inset_width <= half_side).then(|| ShadowHole {
127 inset: inset_width.max(umbra.min(half_side)),
128 radius: 0.0,
129 });
130 (umbra.min(half_side), hole)
131 };
132 Some(Self {
133 bounds: outer,
134 radii: if circle { [half_side; 4] } else { radii },
135 umbra_inset,
136 distance_correction: umbra_inset / blur,
137 hole: hole.filter(|hole| hole.inset < half_side),
138 })
139 }
140
141 pub fn scaled(self, scale: f32) -> Self {
143 Self {
144 bounds: Rect {
145 x: self.bounds.x * scale,
146 y: self.bounds.y * scale,
147 width: self.bounds.width * scale,
148 height: self.bounds.height * scale,
149 },
150 radii: self.radii.map(|radius| radius * scale),
151 umbra_inset: self.umbra_inset * scale,
152 distance_correction: self.distance_correction,
153 hole: self.hole.map(|hole| ShadowHole {
154 inset: hole.inset * scale,
155 radius: hole.radius * scale,
156 }),
157 }
158 }
159
160 pub fn translated(self, dx: f32, dy: f32) -> Self {
162 Self {
163 bounds: self.bounds.translate(dx, dy),
164 ..self
165 }
166 }
167
168 pub fn hole_rect(&self) -> Option<Rect> {
170 self.hole.map(|hole| Rect {
171 x: self.bounds.x + hole.inset,
172 y: self.bounds.y + hole.inset,
173 width: self.bounds.width - 2.0 * hole.inset,
174 height: self.bounds.height - 2.0 * hole.inset,
175 })
176 }
177
178 pub fn coverage(&self, x: f32, y: f32) -> f32 {
182 let bounds = self.bounds;
183 let right_edge = bounds.x + bounds.width;
184 let bottom_edge = bounds.y + bounds.height;
185 if x < bounds.x || y < bounds.y || x >= right_edge || y >= bottom_edge {
186 return 0.0;
187 }
188 if let (Some(hole), Some(rect)) = (self.hole, self.hole_rect())
189 && rounded_rect_contains(rect, hole.radius, x, y)
190 {
191 return 0.0;
192 }
193 let umbra = self.umbra_inset;
194 let left = bounds.x + umbra - x;
195 let right = x - (right_edge - umbra);
196 let top = bounds.y + umbra - y;
197 let bottom = y - (bottom_edge - umbra);
198 let corner = match (left > right, top > bottom) {
199 (true, true) => 0,
200 (false, true) => 1,
201 (false, false) => 2,
202 (true, false) => 3,
203 };
204 let offset = fan_offset(
205 left.max(right).max(0.0),
206 top.max(bottom).max(0.0),
207 umbra,
208 self.radii[corner],
209 );
210 shadow_falloff(self.distance_correction * (1.0 - offset))
211 }
212}
213
214fn rounded_rect_contains(rect: Rect, radius: f32, x: f32, y: f32) -> bool {
215 let half_width = 0.5 * rect.width;
216 let half_height = 0.5 * rect.height;
217 let dx = (x - rect.x - half_width).abs() - (half_width - radius);
218 let dy = (y - rect.y - half_height).abs() - (half_height - radius);
219 let outside = (dx.max(0.0).powi(2) + dy.max(0.0).powi(2)).sqrt();
220 outside + dx.max(dy).min(0.0) - radius < 0.0
221}
222
223pub fn fan_offset(along: f32, across: f32, umbra: f32, radius: f32) -> f32 {
230 let (a, b) = if along >= across {
231 (along, across)
232 } else {
233 (across, along)
234 };
235 if a <= 0.0 || umbra <= 0.0 {
236 return 0.0;
237 }
238 let length = (2.0 * (radius * radius + umbra * umbra)).sqrt();
239 let outer = [(radius - umbra) / length, (-radius - umbra) / length];
240 let straight = umbra - radius;
241 let [x, y] = if b * umbra <= a * straight {
242 let toward_curve = if straight > 0.0 { b / straight } else { 0.0 };
243 let toward_edge = a / umbra - toward_curve;
244 [
245 toward_curve * outer[0],
246 -toward_edge + toward_curve * outer[1],
247 ]
248 } else {
249 let diagonal = umbra / (std::f32::consts::SQRT_2 * (radius - umbra) - radius);
250 let toward_curve = (a - b) / radius;
251 let toward_corner = a / umbra - toward_curve;
252 [
253 toward_curve * outer[0] + toward_corner * diagonal,
254 toward_curve * outer[1] + toward_corner * diagonal,
255 ]
256 };
257 (x * x + y * y).sqrt()
258}
259
260pub fn shadow_falloff(x: f32) -> f32 {
263 let texel = ((x * FALLOFF_TEXELS - 0.5) / (FALLOFF_TEXELS - 1.0)).clamp(0.0, 1.0);
264 let distance = 1.0 - texel;
265 ((-4.0 * distance * distance).exp() - FALLOFF_FLOOR).max(0.0)
266}
267
268#[derive(Clone, Copy, Debug, Default, PartialEq)]
269pub struct LayerShadowGeometry {
270 pub ambient: Option<(ShadowRRect, Color)>,
271 pub spot: Option<(ShadowRRect, Color)>,
272}
273
274impl LayerShadowGeometry {
275 pub fn passes(&self) -> impl Iterator<Item = (ShadowRRect, Color)> {
277 self.ambient.into_iter().chain(self.spot)
278 }
279}
280
281fn outset(rect: Rect, amount: f32) -> Rect {
282 Rect {
283 x: rect.x - amount,
284 y: rect.y - amount,
285 width: rect.width + amount * 2.0,
286 height: rect.height + amount * 2.0,
287 }
288}
289
290fn corner_radii(radii: CornerRadii) -> [f32; 4] {
291 [
292 radii.top_left,
293 radii.top_right,
294 radii.bottom_right,
295 radii.bottom_left,
296 ]
297}
298
299fn pass_color(color: Color, share: f32, caster_alpha: f32) -> Option<Color> {
304 let share_byte = (share * 255.0).floor();
305 let color_byte = (color.a().clamp(0.0, 1.0) * 255.0).round();
306 let byte = (color_byte * share_byte / 255.0 * caster_alpha).floor();
307 (byte > 0.0).then(|| Color(color.r(), color.g(), color.b(), byte / 255.0))
308}
309
310fn caster_occludes(layer: &GraphicsLayer) -> bool {
313 layer.alpha >= 1.0
314 && layer.rotation_x.abs() <= f32::EPSILON
315 && layer.rotation_y.abs() <= f32::EPSILON
316 && layer.rotation_z.abs() <= f32::EPSILON
317}
318
319fn spot_stray(caster: Rect, spot: Rect, caster_radius: f32, spot_radius: f32) -> f32 {
323 if caster_radius <= 0.0 {
324 return (spot.x - caster.x)
325 .abs()
326 .max((spot.y - caster.y).abs())
327 .max((spot.x + spot.width - caster.x - caster.width).abs())
328 .max((spot.y + spot.height - caster.y - caster.height).abs());
329 }
330 let grown = spot_radius - caster_radius;
331 let upper = [spot.x - caster.x + grown, spot.y - caster.y + grown];
332 let lower = [
333 spot.x + spot.width - caster.x - caster.width - grown,
334 spot.y + spot.height - caster.y - caster.height - grown,
335 ];
336 let length = |[x, y]: [f32; 2]| x * x + y * y;
337 length(upper).max(length(lower)).sqrt() + grown
338}
339
340pub fn layer_shadow_geometry(
344 layer: &GraphicsLayer,
345 transformed_bounds: Rect,
346 caster: Option<RoundedCornerShape>,
347 light: ShadowLight,
348) -> LayerShadowGeometry {
349 if layer.shadow_elevation <= 0.0 {
350 return LayerShadowGeometry::default();
351 }
352
353 let scale = layer_uniform_scale(layer).max(MIN_LAYER_SHADOW_SCALE);
354 let height = layer.shadow_elevation * scale;
355 let caster_alpha = layer.alpha.clamp(0.0, 1.0);
356 let radii = caster.map_or([0.0; 4], |shape| corner_radii(shape.radii()));
357 let occludes = caster_occludes(layer);
358 let pixels_per_unit = light.pixels_per_unit.max(f32::EPSILON);
359
360 let reach = (height * 0.5).min(MAX_AMBIENT_REACH_PIXELS / pixels_per_unit);
363 let ambient_outer = outset(transformed_bounds, reach);
364 let ambient = pass_color(
365 layer.ambient_shadow_color,
366 AMBIENT_SHADOW_ALPHA,
367 caster_alpha,
368 )
369 .and_then(|color| {
370 let blur = reach * (1.0 + height * pixels_per_unit / 128.0);
371 let inset = if occludes { reach } else { ambient_outer.width };
372 ShadowRRect::new(ambient_outer, radii.map(|r| r + reach), blur, inset)
373 .map(|shadow| (shadow, color))
374 });
375
376 let depth = light.z - height;
380 let z_ratio = if depth > f32::EPSILON {
381 (height / depth).clamp(0.0, 0.95)
382 } else {
383 0.95
384 };
385 let spot_scale = 1.0 + z_ratio;
386 let spot_blur = light.radius * z_ratio;
387 let projected = Rect {
388 x: transformed_bounds.x + z_ratio * (transformed_bounds.x - light.x),
389 y: transformed_bounds.y + z_ratio * (transformed_bounds.y - light.y),
390 width: transformed_bounds.width * spot_scale,
391 height: transformed_bounds.height * spot_scale,
392 };
393 let spot =
394 pass_color(layer.spot_shadow_color, SPOT_SHADOW_ALPHA, caster_alpha).and_then(|color| {
395 let caster_radius = radii.into_iter().fold(0.0, f32::max);
396 let inset = spot_blur
397 + if occludes {
398 spot_blur.max(spot_stray(
399 transformed_bounds,
400 projected,
401 caster_radius,
402 caster_radius * spot_scale,
403 ))
404 } else {
405 projected.width
406 };
407 ShadowRRect::new(
408 outset(projected, spot_blur),
409 radii.map(|r| r * spot_scale + spot_blur),
410 2.0 * spot_blur,
411 inset,
412 )
413 .map(|shadow| (shadow, color))
414 });
415
416 LayerShadowGeometry { ambient, spot }
417}
418
419#[cfg(test)]
420#[path = "tests/layer_shadow_tests.rs"]
421mod tests;