Skip to main content

vello_encoding/
ramp_cache.rs

1// Copyright 2022 the Vello Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4use std::collections::HashMap;
5
6use peniko::color::cache_key::CacheKey;
7use peniko::color::{HueDirection, Srgb};
8use peniko::{ColorStop, ColorStops};
9
10const N_SAMPLES: usize = 512;
11const RETAINED_COUNT: usize = 64;
12
13/// Data and dimensions for a set of resolved gradient ramps.
14#[derive(Copy, Clone, Debug, Default)]
15pub struct Ramps<'a> {
16    pub data: &'a [u32],
17    pub width: u32,
18    pub height: u32,
19}
20
21#[derive(Default)]
22pub(crate) struct RampCache {
23    epoch: u64,
24    map: HashMap<CacheKey<ColorStops>, (u32, u64)>,
25    data: Vec<u32>,
26}
27
28impl RampCache {
29    pub(crate) fn maintain(&mut self) {
30        self.epoch += 1;
31        if self.map.len() > RETAINED_COUNT {
32            self.map
33                .retain(|_key, value| value.0 < RETAINED_COUNT as u32);
34            self.data.truncate(RETAINED_COUNT * N_SAMPLES);
35        }
36    }
37
38    pub(crate) fn add(&mut self, stops: &[ColorStop]) -> u32 {
39        if let Some(entry) = self.map.get_mut(&CacheKey(stops.into())) {
40            entry.1 = self.epoch;
41            entry.0
42        } else if self.map.len() < RETAINED_COUNT {
43            let id = (self.data.len() / N_SAMPLES) as u32;
44            self.data.extend(make_ramp(stops));
45            self.map.insert(CacheKey(stops.into()), (id, self.epoch));
46            id
47        } else {
48            let mut reuse = None;
49            for (stops, (id, epoch)) in &self.map {
50                if *epoch + 2 < self.epoch {
51                    reuse = Some((stops.to_owned(), *id));
52                    break;
53                }
54            }
55            if let Some((old_stops, id)) = reuse {
56                self.map.remove(&old_stops);
57                let start = id as usize * N_SAMPLES;
58                for (dst, src) in self.data[start..start + N_SAMPLES]
59                    .iter_mut()
60                    .zip(make_ramp(stops))
61                {
62                    *dst = src;
63                }
64                self.map.insert(CacheKey(stops.into()), (id, self.epoch));
65                id
66            } else {
67                let id = (self.data.len() / N_SAMPLES) as u32;
68                self.data.extend(make_ramp(stops));
69                self.map.insert(CacheKey(stops.into()), (id, self.epoch));
70                id
71            }
72        }
73    }
74
75    pub(crate) fn ramps(&self) -> Ramps<'_> {
76        Ramps {
77            data: &self.data,
78            width: N_SAMPLES as u32,
79            height: (self.data.len() / N_SAMPLES) as u32,
80        }
81    }
82}
83
84fn make_ramp(stops: &[ColorStop]) -> impl Iterator<Item = u32> + '_ {
85    let mut last_u = 0.0;
86    let mut last_c = stops[0].color.to_alpha_color::<Srgb>();
87    let mut this_u = last_u;
88    let mut this_c = last_c;
89    let mut j = 0;
90    (0..N_SAMPLES).map(move |i| {
91        let u = (i as f32) / (N_SAMPLES - 1) as f32;
92        while u > this_u {
93            last_u = this_u;
94            last_c = this_c;
95            if let Some(s) = stops.get(j + 1) {
96                this_u = s.offset;
97                this_c = s.color.to_alpha_color::<Srgb>();
98                j += 1;
99            } else {
100                break;
101            }
102        }
103        let du = this_u - last_u;
104        let c = if du < 1e-9 {
105            this_c
106        } else {
107            last_c.lerp(this_c, (u - last_u) / du, HueDirection::default())
108        };
109        c.premultiply().to_rgba8().to_u32()
110    })
111}