Skip to main content

gpui/
corner_shape.rs

1use crate::{Bounds, Corners, Point};
2#[cfg(feature = "schemars")]
3use schemars::JsonSchema;
4use serde::{Deserialize, Serialize};
5
6/// CSS `corner-shape`: the superellipse parameter `K` of `superellipse(K)` (css-borders-4 §3.7).
7/// The corner is `x^(2^K) + y^(2^K) = 1`, mirrored about the corner when `K` is negative.
8#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
9#[cfg_attr(feature = "schemars", derive(JsonSchema))]
10pub struct CornerShape(pub f32);
11
12impl Default for CornerShape {
13    fn default() -> Self {
14        Self::ROUND
15    }
16}
17
18impl CornerShape {
19    /// `round`, `superellipse(1)`.
20    pub const ROUND: Self = Self(1.);
21    /// `squircle`, `superellipse(2)`.
22    pub const SQUIRCLE: Self = Self(2.);
23    /// `square`, `superellipse(infinity)`.
24    pub const SQUARE: Self = Self(f32::INFINITY);
25    /// `bevel`, `superellipse(0)`.
26    pub const BEVEL: Self = Self(0.);
27    /// `scoop`, `superellipse(-1)`.
28    pub const SCOOP: Self = Self(-1.);
29    /// `notch`, `superellipse(-infinity)`.
30    pub const NOTCH: Self = Self(f32::NEG_INFINITY);
31
32    /// Whether this is `round`, the shape `border-radius` alone draws.
33    pub fn is_round(self) -> bool {
34        self.0 == 1.
35    }
36
37    /// The normalized superellipse half corner (§3.9.6): where the curve crosses the corner's
38    /// diagonal, from 0 (`notch`) through 0.5 (`bevel`) to 1 (`square`).
39    pub fn half_corner(self) -> f32 {
40        let k = self.0;
41        if k.is_nan() {
42            return Self::ROUND.half_corner();
43        }
44        if k == f32::INFINITY {
45            return 1.;
46        }
47        if k == f32::NEG_INFINITY {
48            return 0.;
49        }
50        let convex = 0.5f32.powf(1. / 2f32.powf(k.abs()));
51        if k < 0. { 1. - convex } else { convex }
52    }
53
54    /// The shape whose [`CornerShape::half_corner`] is `value`.
55    pub fn from_half_corner(value: f32) -> Self {
56        let value = value.clamp(0., 1.);
57        if value == 0. {
58            return Self::NOTCH;
59        }
60        if value == 1. {
61            return Self::SQUARE;
62        }
63        if value == 0.5 {
64            return Self::BEVEL;
65        }
66        let convex = if value < 0.5 { 1. - value } else { value };
67        let k = (0.5f32.ln() / convex.ln()).log2();
68        Self(if value < 0.5 { -k } else { k })
69    }
70
71    /// CSS interpolation: the half corner moves linearly (§3.9.6).
72    pub fn interpolate(self, to: Self, t: f32) -> Self {
73        if t <= 0. {
74            return self;
75        }
76        if t >= 1. {
77            return to;
78        }
79        let (a, b) = (self.half_corner(), to.half_corner());
80        Self::from_half_corner(a + (b - a) * t)
81    }
82}
83
84const SHAPE_BITS: u32 = 0xfff;
85const SHAPE_STEPS: f32 = 4094.;
86const INSET_BITS: u32 = 0x3ff;
87const INSET_STEPS_PER_PIXEL: f32 = 4.;
88
89/// The corner shapes of a primitive as the shaders read them. Each corner's word holds the
90/// shape's half corner in its low 12 bits, 0 for `round`, then two 10-bit insets in quarter
91/// pixels: the corner is the inner edge of a border that wide on the box `bounds` is inside.
92#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
93#[repr(C)]
94pub struct CornerShapes {
95    /// The top left corner.
96    pub top_left: u32,
97    /// The top right corner.
98    pub top_right: u32,
99    /// The bottom right corner.
100    pub bottom_right: u32,
101    /// The bottom left corner.
102    pub bottom_left: u32,
103}
104
105fn shape_code(shape: CornerShape) -> u32 {
106    if shape.is_round() {
107        return 0;
108    }
109    1 + (shape.half_corner() * SHAPE_STEPS).round() as u32
110}
111
112fn inset_code(inset: f32) -> u32 {
113    ((inset.max(0.) * INSET_STEPS_PER_PIXEL).round() as u32).min(INSET_BITS)
114}
115
116impl CornerShapes {
117    /// Each corner's shape, without insets.
118    pub fn new(shapes: &Corners<CornerShape>) -> Self {
119        Self {
120            top_left: shape_code(shapes.top_left),
121            top_right: shape_code(shapes.top_right),
122            bottom_right: shape_code(shapes.bottom_right),
123            bottom_left: shape_code(shapes.bottom_left),
124        }
125    }
126
127    /// Whether every corner is round, the shape the shaders draw without these.
128    pub fn is_round(&self) -> bool {
129        self.words().iter().all(|word| word & SHAPE_BITS == 0)
130    }
131
132    fn words(&self) -> [u32; 4] {
133        [
134            self.top_left,
135            self.top_right,
136            self.bottom_right,
137            self.bottom_left,
138        ]
139    }
140
141    fn from_words([top_left, top_right, bottom_right, bottom_left]: [u32; 4]) -> Self {
142        Self {
143            top_left,
144            top_right,
145            bottom_right,
146            bottom_left,
147        }
148    }
149
150    /// The shapes as the inner edge of a border `insets` wide on each axis, per corner
151    /// (x: the left or right border, y: the top or bottom one). A round corner takes none.
152    pub fn with_insets(self, insets: Corners<(f32, f32)>) -> Self {
153        let insets = [
154            insets.top_left,
155            insets.top_right,
156            insets.bottom_right,
157            insets.bottom_left,
158        ];
159        let mut words = self.words();
160        for (word, (x, y)) in words.iter_mut().zip(insets) {
161            let shape = *word & SHAPE_BITS;
162            *word = if shape == 0 {
163                0
164            } else {
165                shape | inset_code(x) << 12 | inset_code(y) << 22
166            };
167        }
168        Self::from_words(words)
169    }
170
171    /// The same shapes without insets.
172    pub fn without_insets(self) -> Self {
173        Self::from_words(self.words().map(|word| word & SHAPE_BITS))
174    }
175
176    /// The insets scaled, as a content mask is scaled to device pixels.
177    pub fn scale(self, factor: f32) -> Self {
178        Self::from_words(self.words().map(|word| {
179            let shape = word & SHAPE_BITS;
180            if shape == 0 {
181                return 0;
182            }
183            let (x, y) = word_insets(word);
184            shape | inset_code(x * factor) << 12 | inset_code(y * factor) << 22
185        }))
186    }
187
188    /// The shapes in [`Corners`] order, with each corner's insets.
189    pub fn corners(&self) -> Corners<u32> {
190        Corners {
191            top_left: self.top_left,
192            top_right: self.top_right,
193            bottom_right: self.bottom_right,
194            bottom_left: self.bottom_left,
195        }
196    }
197}
198
199fn word_insets(word: u32) -> (f32, f32) {
200    (
201        ((word >> 12) & INSET_BITS) as f32 / INSET_STEPS_PER_PIXEL,
202        ((word >> 22) & INSET_BITS) as f32 / INSET_STEPS_PER_PIXEL,
203    )
204}
205
206/// How far `q` is outside the curve of a shaped corner of radius `r`, negative inside: `q` runs
207/// inward from the box's corner along both edges, and `inset` is the border on the edge the
208/// curve ends on (x: the left or right border). Mirrors `shaped_corner_piece` in the shaders.
209pub(crate) fn corner_piece_sdf(q: [f32; 2], r: f32, word: u32, inset: [f32; 2]) -> f32 {
210    let code = word & SHAPE_BITS;
211    if code == 0 || code == SHAPE_BITS || r <= 0. {
212        return f32::MIN;
213    }
214    let h = (code - 1) as f32 / SHAPE_STEPS;
215    let convex = h >= 0.5;
216    let (mut a, mut b) = ([r, 0.], [0., r]);
217    if inset[0] > 0. || inset[1] > 0. {
218        let cp =
219            ((1. + std::f32::consts::SQRT_2) * h - std::f32::consts::FRAC_1_SQRT_2).clamp(0., 1.);
220        let d = (inset[0] - inset[1]).clamp(-r, r);
221        if h <= 0.5 && d.abs() >= r {
222            return f32::MIN;
223        }
224        let mut start = cp;
225        if d != 0. {
226            let s = (2. * r * r - d * d).sqrt();
227            let bevel = (s - d) / (2. * s);
228            start = if convex {
229                1. - (1. - bevel) * 2. * (1. - cp)
230            } else {
231                bevel * 2. * cp
232            };
233        }
234        let end = 2. * cp - start;
235        let normal = |x: f32, y: f32| {
236            let length = (x * x + y * y).sqrt().max(1e-6);
237            [x / length, y / length]
238        };
239        let na = normal(1. - start, start);
240        let nb = normal(end, 1. - end);
241        a = [a[0] + na[0] * inset[1], a[1] + na[1] * inset[1]];
242        b = [b[0] + nb[0] * inset[0], b[1] + nb[1] * inset[0]];
243    }
244    let axes = [a[0] - b[0], b[1] - a[1]];
245    if axes[0] <= 0. || axes[1] <= 0. {
246        return f32::MIN;
247    }
248    let hc = if convex { h } else { 1. - h };
249    let n = -std::f32::consts::LN_2 / hc.ln().min(-1e-4);
250    let uv = if convex {
251        [(a[0] - q[0]) / axes[0], (b[1] - q[1]) / axes[1]]
252    } else {
253        [(q[0] - b[0]) / axes[0], (q[1] - a[1]) / axes[1]]
254    }
255    .map(|v| v.max(0.));
256    let m = uv[0].max(uv[1]);
257    if m <= 0. {
258        let depth = axes[0].min(axes[1]);
259        return if convex { -depth } else { depth };
260    }
261    let spow = |x: f32, e: f32| if x <= 0. { 0. } else { (e * x.log2()).exp2() };
262    let l = m * spow(spow(uv[0] / m, n) + spow(uv[1] / m, n), 1. / n);
263    let slope = |v: f32| if n > 1.0001 { spow(v / l, n - 1.) } else { 1. };
264    let g = [slope(uv[0]) / axes[0], slope(uv[1]) / axes[1]];
265    let distance = (l - 1.) / (g[0] * g[0] + g[1] * g[1]).sqrt().max(1e-6);
266    if convex { distance } else { -distance }
267}
268
269/// The signed distance from `point` to a box with shaped corners, negative inside. A corner whose
270/// shape is round is gpui's rounded corner.
271pub(crate) fn shaped_rect_sdf<P>(
272    point: Point<P>,
273    bounds: &Bounds<P>,
274    radii: &Corners<P>,
275    shapes: &CornerShapes,
276) -> f32
277where
278    P: Clone + Copy + std::fmt::Debug + Default + PartialEq + Into<f64>,
279{
280    let f = |v: P| -> f32 { Into::<f64>::into(v) as f32 };
281    let half = [f(bounds.size.width) / 2., f(bounds.size.height) / 2.];
282    let to_point = [
283        f(point.x) - f(bounds.origin.x) - half[0],
284        f(point.y) - f(bounds.origin.y) - half[1],
285    ];
286    let (r, word) = match (to_point[0] < 0., to_point[1] < 0.) {
287        (true, true) => (f(radii.top_left), shapes.top_left),
288        (false, true) => (f(radii.top_right), shapes.top_right),
289        (false, false) => (f(radii.bottom_right), shapes.bottom_right),
290        (true, false) => (f(radii.bottom_left), shapes.bottom_left),
291    };
292    let corner_to_point = [to_point[0].abs() - half[0], to_point[1].abs() - half[1]];
293    if word & SHAPE_BITS == 0 {
294        let c = [corner_to_point[0] + r, corner_to_point[1] + r];
295        if r == 0. {
296            return c[0].max(c[1]);
297        }
298        let outside = (c[0].max(0.).powi(2) + c[1].max(0.).powi(2)).sqrt();
299        return outside + c[0].max(c[1]).min(0.) - r;
300    }
301    let (ix, iy) = word_insets(word);
302    let q = [ix - corner_to_point[0], iy - corner_to_point[1]];
303    let rect = corner_to_point[0].max(corner_to_point[1]);
304    rect.max(corner_piece_sdf(q, r, word, [ix, iy]))
305}
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310    use crate::{Pixels, point, px, size};
311
312    fn all<T: Clone + std::fmt::Debug + Default + PartialEq>(value: T) -> Corners<T> {
313        Corners {
314            top_left: value.clone(),
315            top_right: value.clone(),
316            bottom_right: value.clone(),
317            bottom_left: value,
318        }
319    }
320
321    fn close(a: f32, b: f32, tolerance: f32) {
322        assert!(
323            (a - b).abs() <= tolerance,
324            "{a} is not within {tolerance} of {b}"
325        );
326    }
327
328    #[test]
329    fn keywords_map_to_their_half_corners_and_back() {
330        let cases = [
331            (CornerShape::NOTCH, 0.),
332            (CornerShape::SCOOP, 1. - std::f32::consts::FRAC_1_SQRT_2),
333            (CornerShape::BEVEL, 0.5),
334            (CornerShape::ROUND, std::f32::consts::FRAC_1_SQRT_2),
335            (CornerShape::SQUIRCLE, 0.5f32.powf(0.25)),
336            (CornerShape::SQUARE, 1.),
337        ];
338        for (shape, half) in cases {
339            close(shape.half_corner(), half, 1e-6);
340            let back = CornerShape::from_half_corner(half);
341            assert!(
342                back.0 == shape.0 || (back.0 - shape.0).abs() < 1e-4,
343                "{back:?} for {shape:?}"
344            );
345        }
346    }
347
348    #[test]
349    fn interpolation_moves_the_half_corner_linearly() {
350        let mid = CornerShape::BEVEL.interpolate(CornerShape::SQUARE, 0.5);
351        close(mid.half_corner(), 0.75, 1e-6);
352        let mid = CornerShape::SCOOP.interpolate(CornerShape::ROUND, 0.5);
353        close(mid.0, 0., 1e-5);
354        assert_eq!(
355            CornerShape::NOTCH.interpolate(CornerShape::SQUARE, 0.5),
356            CornerShape::BEVEL
357        );
358        assert_eq!(
359            CornerShape::ROUND.interpolate(CornerShape::SCOOP, 1.),
360            CornerShape::SCOOP
361        );
362    }
363
364    #[test]
365    fn round_corners_encode_as_zero() {
366        let shapes = CornerShapes::new(&all(CornerShape::ROUND)).with_insets(all((4., 4.)));
367        assert_eq!(shapes, CornerShapes::default());
368        let bevel = CornerShapes::new(&all(CornerShape::BEVEL));
369        assert!(!bevel.is_round());
370        let inset = bevel.with_insets(all((2.5, 7.))).scale(2.);
371        assert_eq!(word_insets(inset.top_left), (5., 14.));
372        assert_eq!(inset.without_insets(), bevel);
373    }
374
375    fn sdf(x: f32, y: f32, shape: CornerShape, inset: f32) -> f32 {
376        let bounds = Bounds::new(
377            point(px(inset), px(inset)),
378            size(px(100. - 2. * inset), px(100. - 2. * inset)),
379        );
380        let shapes = CornerShapes::new(&all(shape)).with_insets(all((inset, inset)));
381        shaped_rect_sdf::<Pixels>(
382            point(px(x), px(y)),
383            &bounds,
384            &Corners::all(px(40.)),
385            &shapes,
386        )
387    }
388
389    #[test]
390    fn each_shape_puts_its_curve_through_its_half_corner() {
391        let diagonal = |shape: CornerShape| {
392            let along = 40. * (1. - shape.half_corner());
393            sdf(along, along, shape, 0.)
394        };
395        for shape in [
396            CornerShape::SCOOP,
397            CornerShape::BEVEL,
398            CornerShape::SQUIRCLE,
399            CornerShape(3.),
400            CornerShape(-2.5),
401        ] {
402            close(diagonal(shape), 0., 0.05);
403        }
404        close(
405            sdf(10., 10., CornerShape::BEVEL, 0.),
406            20. / std::f32::consts::SQRT_2,
407            1e-3,
408        );
409        close(sdf(0., 0., CornerShape::SCOOP, 0.), 40., 1e-3);
410        close(sdf(28.28427, 28.28427, CornerShape::SCOOP, 0.), 0., 0.01);
411        assert!(sdf(39., 39., CornerShape::NOTCH, 0.) > 0.);
412        assert!(sdf(41., 20., CornerShape::NOTCH, 0.) < 0.);
413        assert!(sdf(1., 1., CornerShape::SQUARE, 0.) < 0.);
414    }
415
416    #[test]
417    fn an_inset_corner_stays_a_border_width_from_the_outer_curve() {
418        for shape in [
419            CornerShape::BEVEL,
420            CornerShape::SCOOP,
421            CornerShape::SQUIRCLE,
422            CornerShape(-0.5),
423            CornerShape(0.5),
424        ] {
425            let along = 40. * (1. - shape.half_corner());
426            let step = 6. / std::f32::consts::SQRT_2;
427            let at = sdf(along + step, along + step, shape, 6.);
428            assert!(at.abs() < 1.5, "{shape:?}: {at}");
429        }
430        close(sdf(46., 6., CornerShape::SCOOP, 6.), 0., 0.3);
431    }
432}