OXYGENHUB
# eb56c8bc4d0e oxygenhub / crates / backdrop / src / sky.rs
24.0 KiB · Rust · last changed fix(web): a sky's marks spread all the way round each cluster (refs #157) 23 days ago source blame history raw
17ca6cdd Andy McCall ↶ 1
//! Your sky (docs/backgrounds.md §5): the dashboard's scene, its layout
2
//! and its motion, with no browser in it so it is tested natively.
3
//!
4
//! Each repository is a cluster placed by a hash of its name, so a
5
//! viewer's sky is the same on every visit; its events of the last 30 days
6
//! orbit it as marks, brightest when newest, shaped by kind. The cursor
7
//! lights marks near it without moving them, and joins the lit marks of
8
//! one repository in the order they happened.
9
10
use std::f32::consts::TAU;
11
6907a989 Andy McCall ↶ 12
/// The scale of marks and orbits: the sky drawn 40% closer than first
13
/// built (Andy, 2026-10-13).
14
const ZOOM: f32 = 1.4;
17ca6cdd Andy McCall ↶ 15
/// How far the cursor lights marks, in CSS pixels (§4).
6907a989 Andy McCall ↶ 16
pub const LIGHT_RADIUS: f32 = 170.0;
17ca6cdd Andy McCall ↶ 17
/// Seconds a mark takes to light, and to fade.
18
const LIT_IN: f32 = 0.15;
19
const LIT_OUT: f32 = 0.6;
20
/// The fastest a mark drifts, in CSS pixels a second.
21
pub const MAX_SPEED: f32 = 12.0;
22
/// How far each depth layer shifts against the cursor, front to back.
23
const PARALLAX: [f32; 3] = [6.0, 3.0, 1.0];
df5c69cb Andy McCall ↶ 24
/// The longest link: only marks that happened one after another and sit
25
/// near each other are joined, so a busy repository reads as a
26
/// constellation, not a scribble.
6907a989 Andy McCall ↶ 27
const LINK_MAX: f32 = 85.0;
17ca6cdd Andy McCall ↶ 28
/// Links fade when the cursor has rested this long, in seconds.
29
const LINK_REST: f32 = 2.0;
30
/// A resting cursor this near a cluster's core names it, after this long.
6907a989 Andy McCall ↶ 31
const LABEL_NEAR: f32 = 110.0;
17ca6cdd Andy McCall ↶ 32
const LABEL_REST: f32 = 0.4;
33
/// Events older than this many days are not drawn.
34
pub const DAYS: f32 = 30.0;
df5c69cb Andy McCall ↶ 35
/// The most marks one push makes (one a change), and in all.
36
const PER_PUSH: u32 = 40;
37
const MAX_MARKS: usize = 3000;
6907a989 Andy McCall ↶ 38
/// A side margin narrower than this holds no clusters: the sky falls back
39
/// to a ring around the page.
40
const MIN_MARGIN: f32 = 180.0;
41
/// The width a cluster gets in a margin's grid.
42
const CELL: f32 = 260.0;
17ca6cdd Andy McCall ↶ 43
44
/// What a mark stands for, which decides its shape.
45
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46
pub enum Kind {
47
    Push,
48
    Proposal,
49
    Issue,
50
    Release,
df5c69cb Andy McCall ↶ 51
    /// A Flow run.
52
    Run,
17ca6cdd Andy McCall ↶ 53
    /// The repository itself, its cluster's core.
54
    Repo,
55
}
56
57
impl Kind {
df5c69cb Andy McCall ↶ 58
    /// The code the page's data uses: 0 a push's change, 1 a proposal
59
    /// event, 2 an issue event, 3 a release, 4 a Flow run.
17ca6cdd Andy McCall ↶ 60
    pub fn from_code(code: u32) -> Kind {
61
        match code {
62
            1 => Kind::Proposal,
63
            2 => Kind::Issue,
64
            3 => Kind::Release,
df5c69cb Andy McCall ↶ 65
            4 => Kind::Run,
17ca6cdd Andy McCall ↶ 66
            _ => Kind::Push,
67
        }
68
    }
69
70
    /// The shape the fragment shader draws: 0 dot, 1 diamond, 2 ring,
df5c69cb Andy McCall ↶ 71
    /// 3 four-point star, 4 thin ring (a repository), 5 square.
17ca6cdd Andy McCall ↶ 72
    pub fn shape(self) -> f32 {
73
        match self {
74
            Kind::Push => 0.0,
75
            Kind::Proposal => 1.0,
76
            Kind::Issue => 2.0,
77
            Kind::Release => 3.0,
78
            Kind::Repo => 4.0,
df5c69cb Andy McCall ↶ 79
            Kind::Run => 5.0,
17ca6cdd Andy McCall ↶ 80
        }
81
    }
82
83
    /// Its radius in CSS pixels.
84
    fn size(self) -> f32 {
85
        match self {
df5c69cb Andy McCall ↶ 86
            Kind::Push => 2.0,
87
            Kind::Run => 2.2,
17ca6cdd Andy McCall ↶ 88
            Kind::Proposal => 3.2,
89
            Kind::Issue => 3.0,
90
            Kind::Release => 4.2,
91
            Kind::Repo => 6.0,
92
        }
93
    }
94
}
95
96
/// One repository, as the page gives it.
97
#[derive(Clone, Debug)]
98
pub struct Repo {
99
    pub name: String,
100
}
101
102
/// One event, as the page gives it: its repository (an index into the
df5c69cb Andy McCall ↶ 103
/// repositories), its kind, how old it is, and how many marks it makes (a
104
/// push's changes; one otherwise).
17ca6cdd Andy McCall ↶ 105
#[derive(Clone, Copy, Debug)]
106
pub struct Event {
107
    pub repo: usize,
108
    pub kind: Kind,
109
    pub age_days: f32,
df5c69cb Andy McCall ↶ 110
    pub n: u32,
17ca6cdd Andy McCall ↶ 111
}
112
113
/// A repository's place: a fraction of the view, and a depth layer.
114
#[derive(Clone, Debug)]
115
pub struct Cluster {
116
    pub name: String,
117
    pub fx: f32,
118
    pub fy: f32,
119
    pub layer: usize,
120
}
121
122
/// One drawn mark, orbiting its cluster.
123
#[derive(Clone, Debug)]
124
pub struct Mark {
125
    pub cluster: usize,
126
    pub kind: Kind,
127
    /// Its place in its cluster's history, 0 the newest; the core is 0
128
    /// too and has radius 0.
129
    pub order: u32,
130
    pub radius: f32,
131
    pub angle: f32,
132
    /// Radians a second, signed.
133
    pub speed: f32,
134
    /// 1 for today, fading to 0.3 for a month ago.
135
    pub bright: f32,
136
    /// How lit it is now, 0 to 1.
137
    pub lit: f32,
138
}
139
140
/// Straight RGBA, 0 to 1, as the page's tokens give them.
141
pub type Rgba = [f32; 4];
142
143
/// The three backdrop tokens (§3).
144
#[derive(Clone, Copy, Debug, PartialEq)]
145
pub struct Colours {
146
    pub mark: Rgba,
147
    pub lit: Rgba,
148
    pub link: Rgba,
149
}
150
151
/// The scene.
152
pub struct Sky {
153
    pub clusters: Vec<Cluster>,
154
    pub marks: Vec<Mark>,
155
    /// The view, in CSS pixels.
156
    pub w: f32,
157
    pub h: f32,
158
    /// Where the cursor is, if it is over the page.
159
    pub cursor: Option<(f32, f32)>,
160
    /// Seconds since the cursor last moved.
161
    pub rested: f32,
162
    /// Still (reduced motion, or the viewer's choice): no drift, no
163
    /// parallax, and marks light at once.
164
    pub still: bool,
6907a989 Andy McCall ↶ 165
    /// The page's content column, left and right, in CSS pixels: clusters
166
    /// go in the margins beside it, where they can be seen.
167
    avoid: Option<(f32, f32)>,
17ca6cdd Andy McCall ↶ 168
    parallax: [(f32, f32); 3],
169
    link_fade: f32,
170
}
171
eb56c8bc Andy McCall ↶ 172
/// FNV-1a, then splitmix64's finaliser: a small, stable hash, so a
173
/// repository's place never changes. The finaliser spreads every bit:
174
/// FNV alone gives names that differ only at the end (`repo#1`, `repo#2`)
175
/// alike high bits, which drew a cluster's marks as fans at a few angles.
17ca6cdd Andy McCall ↶ 176
pub fn hash(s: &str) -> u64 {
177
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
178
    for b in s.as_bytes() {
179
        h ^= *b as u64;
180
        h = h.wrapping_mul(0x0100_0000_01b3);
181
    }
eb56c8bc Andy McCall ↶ 182
    h = (h ^ (h >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
183
    h = (h ^ (h >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
184
    h ^ (h >> 31)
17ca6cdd Andy McCall ↶ 185
}
186
187
/// A number from 0 to 1 from bits of a hash.
188
fn unit(h: u64, shift: u32) -> f32 {
189
    ((h >> shift) & 0xffff) as f32 / 65536.0
190
}
191
192
impl Sky {
193
    /// The sky of `repos` and their `events` (newest first, as the page
194
    /// lists them), in a view of `w` by `h` CSS pixels.
195
    pub fn new(repos: &[Repo], events: &[Event], w: f32, h: f32, still: bool) -> Sky {
196
        // The most active repositories in front, the quiet ones behind.
197
        let mut activity = vec![0u32; repos.len()];
198
        for e in events {
199
            if e.repo < repos.len() && e.age_days <= DAYS {
200
                activity[e.repo] += 1;
201
            }
202
        }
203
        let mut rank: Vec<usize> = (0..repos.len()).collect();
204
        rank.sort_by_key(|&i| std::cmp::Reverse(activity[i]));
205
        let mut layer = vec![2usize; repos.len()];
206
        for (pos, &i) in rank.iter().enumerate() {
207
            layer[i] = (pos * 3 / repos.len().max(1)).min(2);
208
        }
6907a989 Andy McCall ↶ 209
        let clusters: Vec<Cluster> =
210
            repos.iter().enumerate().map(|(i, r)| Cluster { name: r.name.clone(), fx: 0.5, fy: 0.5, layer: layer[i] }).collect();
17ca6cdd Andy McCall ↶ 211
        let mut marks: Vec<Mark> = Vec::new();
212
        for i in 0..clusters.len() {
213
            marks.push(Mark { cluster: i, kind: Kind::Repo, order: 0, radius: 0.0, angle: 0.0, speed: 0.0, bright: 0.9, lit: 0.0 });
214
        }
df5c69cb Andy McCall ↶ 215
        // Each event's marks: a push is a dot for each change it brought.
216
        let expanded: Vec<Event> = events
217
            .iter()
218
            .filter(|e| e.repo < repos.len() && e.age_days <= DAYS)
219
            .flat_map(|e| std::iter::repeat_n(*e, if e.kind == Kind::Push { e.n.clamp(1, PER_PUSH) as usize } else { 1 }))
220
            .take(MAX_MARKS)
221
            .collect();
222
        // A busy repository gets more lanes, so its marks spread out.
223
        let mut count = vec![0u32; repos.len()];
224
        for e in &expanded {
225
            count[e.repo] += 1;
226
        }
17ca6cdd Andy McCall ↶ 227
        let mut seen = vec![0u32; repos.len()];
df5c69cb Andy McCall ↶ 228
        for e in &expanded {
17ca6cdd Andy McCall ↶ 229
            let k = seen[e.repo];
230
            seen[e.repo] += 1;
df5c69cb Andy McCall ↶ 231
            let lanes = (6 + count[e.repo] / 30).min(14);
17ca6cdd Andy McCall ↶ 232
            let h = hash(&format!("{}#{k}", repos[e.repo].name));
233
            // Each repository turns one way; its marks keep their lanes, so
234
            // two clusters' streams cross without touching.
235
            let dir = if hash(&repos[e.repo].name) & 1 == 0 { 1.0 } else { -1.0 };
6907a989 Andy McCall ↶ 236
            // Lanes close together: each repository a tight knot.
237
            let radius = (16.0 + (k % lanes) as f32 * 6.5 + unit(h, 0) * 4.0) * ZOOM;
17ca6cdd Andy McCall ↶ 238
            let speed = dir * (MAX_SPEED / radius).min(0.25) * (0.5 + 0.5 * unit(h, 16));
239
            marks.push(Mark {
240
                cluster: e.repo,
241
                kind: e.kind,
242
                order: k,
243
                radius,
244
                angle: unit(h, 32) * TAU,
245
                speed,
246
                bright: 1.0 - 0.7 * (e.age_days / DAYS).clamp(0.0, 1.0),
247
                lit: 0.0,
248
            });
249
        }
6907a989 Andy McCall ↶ 250
        let mut sky =
251
            Sky { clusters, marks, w, h, cursor: None, rested: 0.0, still, avoid: None, parallax: [(0.0, 0.0); 3], link_fade: 0.0 };
252
        sky.layout();
253
        sky
17ca6cdd Andy McCall ↶ 254
    }
255
6907a989 Andy McCall ↶ 256
    /// The view is now `w` by `h`, its content column between `avoid`'s
257
    /// left and right.
258
    pub fn resize(&mut self, w: f32, h: f32, avoid: Option<(f32, f32)>) {
17ca6cdd Andy McCall ↶ 259
        self.w = w;
260
        self.h = h;
6907a989 Andy McCall ↶ 261
        self.avoid = avoid;
262
        self.layout();
263
    }
264
265
    /// Place the clusters. In the margins beside the content when both are
266
    /// wide enough: repositories in the order of their names' hashes, split
267
    /// between the sides by their widths, each side a staggered grid from
268
    /// top to bottom, so the sky fills the space the page leaves. Otherwise
269
    /// a ring around the middle. The same repositories in the same view
270
    /// always land in the same places.
271
    fn layout(&mut self) {
272
        let n = self.clusters.len();
273
        let mut order: Vec<usize> = (0..n).collect();
274
        order.sort_by_key(|&i| hash(&self.clusters[i].name));
275
        let margins = self.avoid.and_then(|(x0, x1)| {
276
            let (l, r) = (x0.max(0.0), (self.w - x1).max(0.0));
277
            (l >= MIN_MARGIN && r >= MIN_MARGIN).then_some((l, r, x1))
278
        });
279
        match margins {
280
            Some((l, r, x1)) => {
281
                let left = (((n as f32) * l / (l + r)).round() as usize).min(n);
282
                let (a, b) = order.split_at(left);
283
                self.grid(a, 0.0, l);
284
                self.grid(b, x1, self.w);
285
            }
286
            None => {
287
                for c in &mut self.clusters {
288
                    let h = hash(&c.name);
289
                    let a = unit(h, 0) * TAU;
290
                    let d = 0.25 + 0.3 * unit(h, 16).sqrt();
291
                    c.fx = (0.5 + d * a.cos()).clamp(0.03, 0.97);
292
                    c.fy = (0.5 + 0.9 * d * a.sin()).clamp(0.05, 0.95);
293
                }
294
            }
295
        }
17ca6cdd Andy McCall ↶ 296
    }
297
6907a989 Andy McCall ↶ 298
    /// Lay `ids` out in a staggered grid between `x0` and `x1`.
299
    fn grid(&mut self, ids: &[usize], x0: f32, x1: f32) {
300
        if ids.is_empty() || self.w <= 0.0 || self.h <= 0.0 {
301
            return;
302
        }
303
        let (top, bottom) = (self.h * 0.1, self.h * 0.97);
304
        let width = x1 - x0;
305
        let cols = ((width / CELL) as usize).clamp(1, 3);
306
        let rows = ids.len().div_ceil(cols);
307
        let (cw, ch) = (width / cols as f32, (bottom - top) / rows as f32);
308
        for (j, &i) in ids.iter().enumerate() {
309
            let (col, row) = (j % cols, j / cols);
310
            let h = hash(&self.clusters[i].name);
311
            let stagger = if cols > 1 && row % 2 == 1 { cw * 0.25 } else { 0.0 };
312
            let cx = x0 + (col as f32 + 0.5) * cw + stagger + (unit(h, 0) - 0.5) * 0.3 * cw;
313
            let cy = top + (row as f32 + 0.5) * ch + (unit(h, 16) - 0.5) * 0.3 * ch;
314
            self.clusters[i].fx = cx.clamp(x0 + 24.0, x1 - 24.0) / self.w;
315
            self.clusters[i].fy = cy / self.h;
316
        }
317
    }
318
17ca6cdd Andy McCall ↶ 319
    /// The cursor moved to `(x, y)`, or left the page.
320
    pub fn point(&mut self, at: Option<(f32, f32)>) {
321
        self.cursor = at;
322
        self.rested = 0.0;
323
    }
324
325
    /// Where cluster `c`'s core is now.
326
    pub fn core(&self, c: usize) -> (f32, f32) {
327
        let cl = &self.clusters[c];
328
        let (px, py) = self.parallax[cl.layer];
329
        (cl.fx * self.w + px, cl.fy * self.h + py)
330
    }
331
332
    /// Where mark `m` is now.
333
    pub fn position(&self, m: &Mark) -> (f32, f32) {
334
        let (cx, cy) = self.core(m.cluster);
335
        (cx + m.angle.cos() * m.radius, cy + m.angle.sin() * m.radius)
336
    }
337
338
    /// Move the scene on by `dt` seconds.
339
    pub fn step(&mut self, dt: f32) {
340
        let dt = dt.clamp(0.0, 0.1);
341
        self.rested += dt;
342
        if !self.still {
343
            for m in &mut self.marks {
344
                m.angle = (m.angle + m.speed * dt) % TAU;
345
            }
346
            let ease = 1.0 - (-dt * 4.0).exp();
347
            for (l, p) in self.parallax.iter_mut().enumerate() {
348
                let (tx, ty) = match self.cursor {
349
                    Some((x, y)) if self.w > 0.0 && self.h > 0.0 => {
350
                        (-(x - self.w / 2.0) / (self.w / 2.0) * PARALLAX[l], -(y - self.h / 2.0) / (self.h / 2.0) * PARALLAX[l])
351
                    }
352
                    _ => (0.0, 0.0),
353
                };
354
                p.0 += (tx - p.0) * ease;
355
                p.1 += (ty - p.1) * ease;
356
            }
357
        }
358
        let lit_targets: Vec<f32> = self
359
            .marks
360
            .iter()
361
            .map(|m| match self.cursor {
362
                Some((x, y)) => {
363
                    let (mx, my) = self.position(m);
364
                    if (mx - x).hypot(my - y) <= LIGHT_RADIUS {
365
                        1.0
366
                    } else {
367
                        0.0
368
                    }
369
                }
370
                None => 0.0,
371
            })
372
            .collect();
373
        for (m, target) in self.marks.iter_mut().zip(lit_targets) {
374
            m.lit = if self.still {
375
                target
376
            } else if target > m.lit {
377
                (m.lit + dt / LIT_IN).min(target)
378
            } else {
379
                (m.lit - dt / LIT_OUT).max(target)
380
            };
381
        }
382
        let fade_to = if self.cursor.is_some() && self.rested < LINK_REST { 1.0 } else { 0.0 };
383
        self.link_fade = if self.still {
384
            fade_to
385
        } else if fade_to > self.link_fade {
386
            (self.link_fade + dt / LIT_IN).min(1.0)
387
        } else {
388
            (self.link_fade - dt / LIT_OUT).max(0.0)
389
        };
390
    }
391
392
    /// Whether anything is still changing: a frame is worth drawing.
393
    pub fn busy(&self) -> bool {
394
        !self.still || self.marks.iter().any(|m| m.lit > 0.0 && m.lit < 1.0) || (self.link_fade > 0.0 && self.link_fade < 1.0)
395
    }
396
397
    /// One instance per mark: centre x, y and radius in CSS pixels, its
398
    /// shape, and its colour premultiplied, 8 floats each.
399
    pub fn instances(&self, c: &Colours, out: &mut Vec<f32>) {
400
        out.clear();
401
        for m in &self.marks {
402
            let (x, y) = self.position(m);
403
            let rest = [c.mark[0], c.mark[1], c.mark[2], c.mark[3] * m.bright];
404
            let col = mix(rest, c.lit, m.lit);
6907a989 Andy McCall ↶ 405
            let size = m.kind.size() * ZOOM * (1.0 + 0.35 * m.lit);
17ca6cdd Andy McCall ↶ 406
            out.extend_from_slice(&[x, y, size, m.kind.shape(), col[0] * col[3], col[1] * col[3], col[2] * col[3], col[3]]);
407
        }
408
    }
409
410
    /// The links among lit marks: each repository's lit marks in the order
411
    /// they happened, its core to its newest lit mark. Two vertices a
412
    /// link, x, y and a premultiplied colour each, 6 floats a vertex.
413
    pub fn links(&self, c: &Colours, out: &mut Vec<f32>) {
414
        out.clear();
415
        if self.link_fade <= 0.0 {
416
            return;
417
        }
418
        for ci in 0..self.clusters.len() {
419
            let mut lit: Vec<&Mark> = self.marks.iter().filter(|m| m.cluster == ci && m.lit > 0.05).collect();
420
            lit.sort_by_key(|m| (m.kind != Kind::Repo, m.order));
421
            for pair in lit.windows(2) {
422
                let (a, b) = (self.position(pair[0]), self.position(pair[1]));
df5c69cb Andy McCall ↶ 423
                if (a.0 - b.0).hypot(a.1 - b.1) > LINK_MAX {
17ca6cdd Andy McCall ↶ 424
                    continue;
425
                }
426
                let alpha = c.link[3] * pair[0].lit.min(pair[1].lit) * self.link_fade;
427
                let col = [c.link[0] * alpha, c.link[1] * alpha, c.link[2] * alpha, alpha];
428
                out.extend_from_slice(&[a.0, a.1, col[0], col[1], col[2], col[3], b.0, b.1, col[0], col[1], col[2], col[3]]);
429
            }
430
        }
df5c69cb Andy McCall ↶ 431
    }
432
433
    /// How far a cluster's marks reach from its core.
434
    fn reach(&self, c: usize) -> f32 {
435
        self.marks.iter().filter(|m| m.cluster == c).map(|m| m.radius).fold(0.0, f32::max)
17ca6cdd Andy McCall ↶ 436
    }
437
df5c69cb Andy McCall ↶ 438
    /// The name to show for a resting cursor, and where: centred just
439
    /// above the nearest cluster within reach, clear of its marks.
17ca6cdd Andy McCall ↶ 440
    pub fn label(&self) -> Option<(&str, f32, f32)> {
441
        let (x, y) = self.cursor?;
442
        if self.rested < LABEL_REST {
443
            return None;
444
        }
445
        (0..self.clusters.len())
446
            .map(|i| (i, self.core(i)))
447
            .map(|(i, (cx, cy))| (i, cx, cy, (cx - x).hypot(cy - y)))
448
            .filter(|t| t.3 <= LABEL_NEAR)
449
            .min_by(|a, b| a.3.total_cmp(&b.3))
df5c69cb Andy McCall ↶ 450
            .map(|(i, cx, cy, _)| (self.clusters[i].name.as_str(), cx, cy - self.reach(i) - 10.0))
17ca6cdd Andy McCall ↶ 451
    }
452
}
453
454
fn mix(a: Rgba, b: Rgba, t: f32) -> Rgba {
455
    let t = t.clamp(0.0, 1.0);
456
    [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t, a[3] + (b[3] - a[3]) * t]
457
}
458
459
/// A computed CSS colour: `rgb(r, g, b)`, `rgba(r, g, b, a)` or
460
/// `color(srgb r g b / a)`, as browsers report them.
461
pub fn parse_colour(s: &str) -> Option<Rgba> {
462
    let s = s.trim();
463
    if let Some(inner) = s.strip_prefix("color(srgb").and_then(|r| r.strip_suffix(')')) {
464
        let (rgb, a) = match inner.split_once('/') {
465
            Some((rgb, a)) => (rgb, a.trim().parse().ok()?),
466
            None => (inner, 1.0),
467
        };
468
        let v: Vec<f32> = rgb.split_whitespace().map(|x| x.parse().ok()).collect::<Option<_>>()?;
469
        return (v.len() == 3).then(|| [v[0], v[1], v[2], a]);
470
    }
471
    let inner = s.strip_prefix("rgba(").or_else(|| s.strip_prefix("rgb("))?.strip_suffix(')')?;
472
    let v: Vec<f32> = inner.split([',', ' ', '/']).filter(|x| !x.is_empty()).map(|x| x.trim().parse().ok()).collect::<Option<_>>()?;
473
    match v.len() {
474
        3 => Some([v[0] / 255.0, v[1] / 255.0, v[2] / 255.0, 1.0]),
475
        4 => Some([v[0] / 255.0, v[1] / 255.0, v[2] / 255.0, v[3]]),
476
        _ => None,
477
    }
478
}
479
480
#[cfg(test)]
481
mod tests {
482
    use super::*;
483
484
    fn sky(still: bool) -> Sky {
485
        let repos = vec![Repo { name: "andy/hub".into() }, Repo { name: "andy/oxygen".into() }];
486
        let events = vec![
df5c69cb Andy McCall ↶ 487
            Event { repo: 0, kind: Kind::Push, age_days: 0.0, n: 3 },
488
            Event { repo: 0, kind: Kind::Proposal, age_days: 2.0, n: 1 },
489
            Event { repo: 1, kind: Kind::Release, age_days: 29.0, n: 1 },
490
            Event { repo: 1, kind: Kind::Issue, age_days: 45.0, n: 1 },
17ca6cdd Andy McCall ↶ 491
        ];
492
        Sky::new(&repos, &events, 1600.0, 900.0, still)
493
    }
494
495
    #[test]
496
    fn a_sky_is_the_same_on_every_visit() {
497
        let (a, b) = (sky(false), sky(false));
498
        assert_eq!(a.clusters[0].fx, b.clusters[0].fx);
499
        assert_eq!(a.clusters[1].fy, b.clusters[1].fy);
df5c69cb Andy McCall ↶ 500
        // A core per repository, a dot per change pushed, and one mark per
501
        // other event of the last 30 days.
502
        assert_eq!(a.marks.len(), 2 + 3 + 1 + 1);
17ca6cdd Andy McCall ↶ 503
        assert!(a.marks.iter().all(|m| m.kind != Kind::Issue), "older than 30 days: not drawn");
504
        let newest = a.marks.iter().find(|m| m.kind == Kind::Push).unwrap();
505
        let old = a.marks.iter().find(|m| m.kind == Kind::Release).unwrap();
506
        assert!(newest.bright > old.bright, "newer is brighter");
507
        assert_eq!(a.clusters[0].layer, 0, "the busiest in front");
508
    }
509
510
    #[test]
511
    fn marks_drift_slowly_and_the_cursor_lights_without_pulling() {
512
        let mut s = sky(false);
513
        for m in &s.marks {
514
            assert!(m.speed.abs() * m.radius <= MAX_SPEED + 0.01, "at most 12 px a second");
515
        }
516
        let target = s.position(&s.marks[2]);
517
        let radii: Vec<f32> = s.marks.iter().map(|m| m.radius).collect();
518
        s.point(Some(target));
519
        for _ in 0..30 {
520
            s.step(1.0 / 60.0);
521
        }
522
        assert!(s.marks[2].lit > 0.99, "lit near the cursor");
523
        assert_eq!(radii, s.marks.iter().map(|m| m.radius).collect::<Vec<_>>(), "nothing is pulled");
524
        let mut links = Vec::new();
525
        let colours = Colours { mark: [0.5, 0.5, 0.5, 0.2], lit: [0.0, 0.4, 0.9, 0.7], link: [0.0, 0.4, 0.9, 0.3] };
526
        s.links(&colours, &mut links);
527
        assert!(!links.is_empty() && links.len() % 12 == 0, "lit marks of one repository are joined");
528
        // Resting fades the links; leaving fades the light.
529
        for _ in 0..240 {
530
            s.step(1.0 / 60.0);
531
        }
532
        s.links(&colours, &mut links);
533
        assert!(links.is_empty(), "a resting cursor's links fade");
534
        s.point(None);
535
        for _ in 0..60 {
536
            s.step(1.0 / 60.0);
537
        }
538
        assert!(s.marks.iter().all(|m| m.lit == 0.0));
539
    }
540
541
    #[test]
542
    fn still_means_no_drift_and_instant_light() {
543
        let mut s = sky(true);
544
        let before: Vec<f32> = s.marks.iter().map(|m| m.angle).collect();
545
        let at = s.position(&s.marks[2]);
546
        s.point(Some(at));
547
        s.step(1.0 / 60.0);
548
        assert_eq!(before, s.marks.iter().map(|m| m.angle).collect::<Vec<_>>());
549
        assert_eq!(s.marks[2].lit, 1.0);
550
        assert!(!s.busy(), "nothing left to animate");
551
    }
552
553
    #[test]
554
    fn instances_are_premultiplied_and_a_resting_cursor_names_a_cluster() {
555
        let mut s = sky(false);
556
        let colours = Colours { mark: [1.0, 1.0, 1.0, 0.5], lit: [0.0, 0.0, 1.0, 1.0], link: [0.0, 0.0, 1.0, 0.3] };
557
        let mut inst = Vec::new();
558
        s.instances(&colours, &mut inst);
559
        assert_eq!(inst.len(), s.marks.len() * 8);
560
        let core = &inst[0..8];
561
        assert!((core[4] - core[7]).abs() < 1e-6 && core[7] < 0.5, "premultiplied, dimmed by brightness");
562
        let (cx, cy) = s.core(1);
563
        s.point(Some((cx + 10.0, cy)));
564
        assert!(s.label().is_none(), "not while moving");
565
        for _ in 0..10 {
566
            s.step(0.05);
567
        }
568
        assert_eq!(s.label().map(|l| l.0), Some("andy/oxygen"));
6907a989 Andy McCall ↶ 569
    }
570
571
    #[test]
572
    fn clusters_fill_the_margins_beside_the_content() {
573
        let repos: Vec<Repo> = (0..17).map(|i| Repo { name: format!("owner/repo{i}") }).collect();
574
        let mut s = Sky::new(&repos, &[], 2560.0, 1270.0, false);
575
        s.resize(2560.0, 1270.0, Some((707.0, 1838.0)));
576
        let xs: Vec<f32> = (0..17).map(|i| s.core(i).0).collect();
577
        assert!(xs.iter().all(|&x| x < 707.0 || x > 1838.0), "none behind the content: {xs:?}");
578
        let left = xs.iter().filter(|&&x| x < 707.0).count();
579
        assert!((7..=10).contains(&left), "both sides used: {left} on the left");
580
        let ys: Vec<f32> = (0..17).map(|i| s.core(i).1).collect();
581
        assert!(ys.iter().any(|&y| y < 400.0) && ys.iter().any(|&y| y > 900.0), "top to bottom: {ys:?}");
582
        // The same view lays the same sky out.
583
        let mut again = Sky::new(&repos, &[], 2560.0, 1270.0, false);
584
        again.resize(2560.0, 1270.0, Some((707.0, 1838.0)));
585
        assert_eq!(xs, (0..17).map(|i| again.core(i).0).collect::<Vec<_>>());
586
        // Narrow margins: back to the ring.
587
        s.resize(1200.0, 800.0, Some((100.0, 1100.0)));
588
        assert!((0..17).any(|i| (s.core(i).0 - 600.0).abs() < 400.0));
17ca6cdd Andy McCall ↶ 589
    }
590
591
    #[test]
eb56c8bc Andy McCall ↶ 592
    fn a_clusters_marks_spread_all_the_way_round() {
593
        let repos = vec![Repo { name: "doomsdayone/rstar-api".into() }];
594
        let events: Vec<Event> = (0..200).map(|_| Event { repo: 0, kind: Kind::Issue, age_days: 1.0, n: 1 }).collect();
595
        let s = Sky::new(&repos, &events, 1600.0, 900.0, true);
596
        // Every eighth of the circle holds a fair share of the marks.
597
        let mut octants = [0u32; 8];
598
        for m in s.marks.iter().filter(|m| m.kind == Kind::Issue) {
599
            octants[((m.angle / TAU * 8.0) as usize).min(7)] += 1;
600
        }
601
        assert!(octants.iter().all(|&n| (12..=40).contains(&n)), "{octants:?}");
602
    }
603
604
    #[test]
17ca6cdd Andy McCall ↶ 605
    fn computed_colours_parse() {
606
        assert_eq!(parse_colour("rgb(9, 105, 218)"), Some([9.0 / 255.0, 105.0 / 255.0, 218.0 / 255.0, 1.0]));
607
        assert_eq!(parse_colour("rgba(0, 240, 255, 0.75)").map(|c| c[3]), Some(0.75));
608
        assert_eq!(parse_colour("color(srgb 0 0.5 1 / 0.2)"), Some([0.0, 0.5, 1.0, 0.2]));
609
        assert_eq!(parse_colour("rgb(1 2 3 / 0.5)").map(|c| c[3]), Some(0.5));
610
        assert!(parse_colour("transparent").is_none());
611
    }
612
}