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