sequoia-core 0.1.3

Sequoia GUI framework — core types (geometry, color, events)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
#![forbid(unsafe_code)]

use crate::paint::Color;

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GradientStop {
    pub at: f32,
    pub color: Color,
}

impl GradientStop {
    pub fn new(at: f32, color: Color) -> Self {
        Self { at, color }
    }
}

#[derive(Clone, Debug, Default, PartialEq)]
pub struct GradientStops {
    stops: Vec<GradientStop>,
}

pub const MAX_GRADIENT_STOPS: usize = 4;

impl GradientStops {
    pub fn new(mut stops: Vec<GradientStop>) -> Self {
        for s in &mut stops {
            s.at = if s.at.is_finite() {
                s.at.clamp(0.0, 1.0)
            } else {
                0.0
            };
        }
        stops.sort_by(|a, b| a.at.partial_cmp(&b.at).unwrap_or(std::cmp::Ordering::Equal));

        let mut out: Vec<GradientStop> = Vec::with_capacity(stops.len());
        for s in stops {
            if let Some(last) = out.last_mut()
                && (last.at - s.at).abs() < f32::EPSILON
            {
                *last = s;
                continue;
            }
            out.push(s);
        }
        Self { stops: out }
    }

    pub fn solid(color: Color) -> Self {
        Self {
            stops: vec![GradientStop::new(0.0, color)],
        }
    }

    pub fn two(from: Color, to: Color) -> Self {
        Self::new(vec![
            GradientStop::new(0.0, from),
            GradientStop::new(1.0, to),
        ])
    }

    pub fn is_empty(&self) -> bool {
        self.stops.is_empty()
    }

    pub fn len(&self) -> usize {
        self.stops.len()
    }

    pub fn stops(&self) -> &[GradientStop] {
        &self.stops
    }

    pub fn for_gpu(&self) -> Option<([[f32; 4]; MAX_GRADIENT_STOPS], [f32; 4], u32)> {
        if self.stops.is_empty() || self.stops.len() > MAX_GRADIENT_STOPS {
            return None;
        }
        let mut colors = [[0.0; 4]; MAX_GRADIENT_STOPS];
        let mut pos = [0.0; 4];
        for (i, s) in self.stops.iter().enumerate() {
            let c = s.color.to_linear();
            colors[i] = [c.r, c.g, c.b, c.a];
            pos[i] = s.at;
        }

        if self.stops.len() == 1 {
            for i in 1..MAX_GRADIENT_STOPS {
                colors[i] = colors[0];
                pos[i] = 1.0;
            }
        }
        Some((colors, pos, self.stops.len() as u32))
    }

    pub fn cache_key(&self) -> u64 {
        let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
        let mut mix = |b: u8| {
            hash ^= u64::from(b);
            hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
        };
        for s in &self.stops {
            for b in s.at.to_bits().to_le_bytes() {
                mix(b);
            }
            let (r, g, b, a) = s.color.to_rgba8();
            mix(r);
            mix(g);
            mix(b);
            mix(a);
        }
        hash ^= 0x9e37_79b9_7f4a_7c15;
        hash
    }

    pub fn sample_linear(&self, t: f32) -> [f32; 4] {
        let Some(first) = self.stops.first() else {
            return [0.0, 0.0, 0.0, 0.0];
        };
        if self.stops.len() == 1 || !t.is_finite() {
            let c = first.color.to_linear();
            return [c.r, c.g, c.b, c.a];
        }
        let t = t.clamp(0.0, 1.0);
        if t <= first.at {
            let c = first.color.to_linear();
            return [c.r, c.g, c.b, c.a];
        }
        let last = self.stops[self.stops.len() - 1];
        if t >= last.at {
            let c = last.color.to_linear();
            return [c.r, c.g, c.b, c.a];
        }
        for pair in self.stops.windows(2) {
            let (a, b) = (pair[0], pair[1]);
            if t <= b.at {
                let span = b.at - a.at;
                let k = if span <= f32::EPSILON {
                    0.0
                } else {
                    ((t - a.at) / span).clamp(0.0, 1.0)
                };
                let ca = a.color.to_linear();
                let cb = b.color.to_linear();

                let mix = |x: f32, y: f32| x + (y - x) * k;
                return [
                    mix(ca.r, cb.r),
                    mix(ca.g, cb.g),
                    mix(ca.b, cb.b),
                    mix(ca.a, cb.a),
                ];
            }
        }
        let c = last.color.to_linear();
        [c.r, c.g, c.b, c.a]
    }

    pub fn bake_lut256(&self) -> Vec<u8> {
        let mut out = Vec::with_capacity(256 * 4);
        for i in 0..256 {
            let t = i as f32 / 255.0;
            let [r, g, b, a] = self.sample_linear(t);
            let q = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round() as u8;
            out.push(q(r));
            out.push(q(g));
            out.push(q(b));
            out.push(q(a));
        }
        out
    }
}

impl From<Vec<GradientStop>> for GradientStops {
    fn from(v: Vec<GradientStop>) -> Self {
        Self::new(v)
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GradientKind {
    Linear { angle_deg: f32 },
    Radial { radius: f32 },
}

impl GradientKind {
    pub fn horizontal() -> Self {
        Self::Linear { angle_deg: 0.0 }
    }

    pub fn vertical() -> Self {
        Self::Linear { angle_deg: 90.0 }
    }

    pub fn cover() -> Self {
        Self::Radial { radius: 0.0 }
    }

    pub fn direction(self) -> (f32, f32) {
        match self {
            Self::Linear { angle_deg } => {
                let a = if angle_deg.is_finite() {
                    angle_deg.to_radians()
                } else {
                    0.0
                };
                (a.cos(), a.sin())
            }
            Self::Radial { .. } => (0.0, 0.0),
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum Fill {
    Solid(Color),
    Gradient {
        kind: GradientKind,
        stops: GradientStops,
    },
}

impl Fill {
    pub fn solid(color: Color) -> Self {
        Self::Solid(color)
    }

    pub fn linear(stops: impl Into<GradientStops>, angle_deg: f32) -> Self {
        Self::Gradient {
            kind: GradientKind::Linear { angle_deg },
            stops: stops.into(),
        }
    }

    pub fn horizontal(stops: impl Into<GradientStops>) -> Self {
        Self::Gradient {
            kind: GradientKind::horizontal(),
            stops: stops.into(),
        }
    }

    pub fn vertical(stops: impl Into<GradientStops>) -> Self {
        Self::Gradient {
            kind: GradientKind::vertical(),
            stops: stops.into(),
        }
    }

    pub fn radial(stops: impl Into<GradientStops>) -> Self {
        Self::Gradient {
            kind: GradientKind::cover(),
            stops: stops.into(),
        }
    }

    pub fn radial_radius(stops: impl Into<GradientStops>, radius: f32) -> Self {
        let radius = if radius.is_finite() {
            radius.max(0.0)
        } else {
            0.0
        };
        Self::Gradient {
            kind: GradientKind::Radial { radius },
            stops: stops.into(),
        }
    }

    pub fn is_solid(&self) -> bool {
        matches!(self, Self::Solid(_))
    }

    pub fn is_visible(&self) -> bool {
        match self {
            Self::Solid(c) => c.a > 0.0,
            Self::Gradient { stops, .. } => !stops.is_empty(),
        }
    }
}

impl From<Color> for Fill {
    fn from(c: Color) -> Self {
        Self::Solid(c)
    }
}

/// Whether a stroke width is expressed in local coordinates or screen pixels.
///
/// Local widths scale with `Painter::with_transform` (so a 1 px outline gets
/// thicker when a canvas is zoomed in). Screen widths stay constant on screen,
/// which is what selection outlines and drag handles usually want.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum StrokeSpace {
    #[default]
    Local,

    Screen,
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Stroke {
    pub width: f32,
    pub rounded: bool,
    pub space: StrokeSpace,
}

impl Stroke {
    fn sanitize_width(width: f32) -> f32 {
        if width.is_finite() {
            width.max(0.0)
        } else {
            0.0
        }
    }

    pub fn new(width: f32) -> Self {
        Self {
            width: Self::sanitize_width(width),
            rounded: false,
            space: StrokeSpace::Local,
        }
    }

    /// A local-space stroke whose width scales with the painter transform.
    pub fn round(width: f32) -> Self {
        Self {
            width: Self::sanitize_width(width),
            rounded: true,
            space: StrokeSpace::Local,
        }
    }

    /// A stroke whose width is in screen pixels and ignores the transform scale.
    pub fn screen(width: f32) -> Self {
        Self {
            width: Self::sanitize_width(width),
            rounded: false,
            space: StrokeSpace::Screen,
        }
    }

    /// A rounded, screen-space stroke.
    pub fn screen_round(width: f32) -> Self {
        Self {
            width: Self::sanitize_width(width),
            rounded: true,
            space: StrokeSpace::Screen,
        }
    }

    /// Converts this stroke to screen-space pixels.
    pub fn in_screen_space(mut self) -> Self {
        self.space = StrokeSpace::Screen;
        self
    }

    pub fn is_visible(self) -> bool {
        self.width > 0.0
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn stops_sort_and_clamp() {
        let s = GradientStops::new(vec![
            GradientStop::new(1.5, Color::BLUE),
            GradientStop::new(-1.0, Color::RED),
            GradientStop::new(0.5, Color::GREEN),
        ]);
        let ats: Vec<f32> = s.stops().iter().map(|x| x.at).collect();
        assert_eq!(ats, vec![0.0, 0.5, 1.0]);
    }

    #[test]
    fn empty_is_transparent() {
        let s = GradientStops::new(vec![]);
        assert_eq!(s.sample_linear(0.5), [0.0, 0.0, 0.0, 0.0]);
        assert_eq!(s.bake_lut256().len(), 256 * 4);
    }

    #[test]
    fn linear_mid_is_not_dark() {
        let s = GradientStops::two(Color::RED, Color::BLUE);
        let mid = s.sample_linear(0.5);

        assert!((mid[0] - 0.5).abs() < 1e-5, "{mid:?}");
        assert!((mid[2] - 0.5).abs() < 1e-5, "{mid:?}");

        let gray = GradientStops::two(Color::WHITE, Color::BLACK).sample_linear(0.5);
        assert!((gray[0] - 0.5).abs() < 1e-5, "{gray:?}");
    }

    #[test]
    fn lut_roundtrip_ends() {
        let s = GradientStops::two(Color::RED, Color::BLUE);
        let lut = s.bake_lut256();
        assert_eq!(lut.len(), 1024);
        assert_eq!(&lut[0..4], &[255, 0, 0, 255]);
        assert_eq!(&lut[1020..1024], &[0, 0, 255, 255]);
    }

    #[test]
    fn cache_key_stable() {
        let a = GradientStops::two(Color::RED, Color::BLUE).cache_key();
        let b = GradientStops::two(Color::RED, Color::BLUE).cache_key();
        let c = GradientStops::two(Color::BLUE, Color::RED).cache_key();
        assert_eq!(a, b);
        assert_ne!(a, c);
    }
}