8 fn new() -> Self { Self { seed: 0x1234 } }
9 fn next(&mut self) -> u8 {
10 if (self.seed & 0x8000) != 0 {
11 self.seed = (self.seed & 0x7FFF) * 2 ^ 0x1B2B;
19 #[derive(Default,Clone,Copy,PartialEq,Debug)]
35 fn new(centroid: Pixel) -> Self {
52 fn add_pixel(&mut self, entry: &Entry) {
53 self.sum_r += u64::from(entry.pix.r) * entry.count;
54 self.sum_g += u64::from(entry.pix.g) * entry.count;
55 self.sum_b += u64::from(entry.pix.b) * entry.count;
56 self.count += entry.count;
58 fn add_dist(&mut self, entry: &Entry) {
59 self.dist += u64::from(self.centroid.dist(entry.pix)) * entry.count;
61 fn calc_centroid(&mut self) {
63 self.centroid.r = ((self.sum_r + self.count / 2) / self.count) as u8;
64 self.centroid.g = ((self.sum_g + self.count / 2) / self.count) as u8;
65 self.centroid.b = ((self.sum_b + self.count / 2) / self.count) as u8;
68 fn calc_dist(&mut self) {
70 self.dist = (self.dist + self.count / 2) / self.count;
76 clusters: Vec<Cluster>,
81 pub fn new(initial_pal: &[[u8; 3]; 256]) -> Self {
82 let mut clusters = Vec::with_capacity(256);
84 let pix = Pixel { r: initial_pal[i][0], g: initial_pal[i][1], b: initial_pal[i][2] };
85 let cluster = Cluster::new(pix);
86 clusters.push(cluster);
93 pub fn new_random() -> Self {
94 let mut rng = RNG::new();
95 let mut clusters = Vec::with_capacity(256);
97 let pix = Pixel { r: rng.next(), g: rng.next(), b: rng.next() };
98 let cluster = Cluster::new(pix);
99 clusters.push(cluster);
105 fn sort<F>(arr: &mut [Pixel], idx: F) where F: Fn(&Pixel) -> u8 {
106 let mut dst = vec![Pixel::default(); arr.len()];
107 let mut counts = [0; 256];
108 for pix in arr.iter() {
109 counts[idx(pix) as usize] += 1;
111 let mut last = counts[0];
113 for count in counts.iter_mut().skip(1) {
118 for pix in arr.iter() {
119 let bucket = idx(pix) as usize;
120 dst[counts[bucket]] = *pix;
123 arr.copy_from_slice(dst.as_slice());
125 fn new_split(old_index: usize, entries: &[Entry], indices: &[usize]) -> Option<(Pixel, Pixel)> {
126 let mut max = Pixel { r: 0, g: 0, b: 0 };
127 let mut min = Pixel { r: 255, g: 255, b: 255 };
128 let mut found = false;
129 for (entry, idx) in entries.iter().zip(indices) {
130 if *idx == old_index {
131 max = max.max(entry.pix);
132 min = min.min(entry.pix);
139 let dr = max.r - min.r;
140 let dg = max.g - min.g;
141 let db = max.b - min.b;
142 let cent0 = Pixel { r: min.r + dr / 3, g: min.g + dg / 3, b: min.b + db / 3 };
143 let cent1 = Pixel { r: max.r - dr / 3, g: max.g - dg / 3, b: max.b - db / 3 };
146 fn old_centre(&self, old_index1: usize, old_index2: usize, entries: &[Entry], indices: &[usize]) -> Pixel {
147 let mut max = Pixel { r: 0, g: 0, b: 0 };
148 let mut min = Pixel { r: 255, g: 255, b: 255 };
149 let mut found = false;
150 for (entry, idx) in entries.iter().zip(indices) {
151 if *idx == old_index1 || *idx == old_index2 {
152 max = max.max(entry.pix);
153 min = min.min(entry.pix);
158 max = self.clusters[old_index1].centroid.max(self.clusters[old_index2].centroid);
159 min = self.clusters[old_index1].centroid.min(self.clusters[old_index2].centroid);
161 let dr = max.r - min.r;
162 let dg = max.g - min.g;
163 let db = max.b - min.b;
164 Pixel { r: min.r + dr / 2, g: min.g + dg / 2, b: min.b + db / 2 }
166 fn estimate_old(old_idx0: usize, old_idx1: usize, c: Pixel, entries: &[Entry], indices: &[usize]) -> u64 {
167 let mut clu = Cluster::new(c);
169 for (entry, idx) in entries.iter().zip(indices) {
170 if *idx == old_idx0 || *idx == old_idx1 {
172 count += entry.count;
179 fn estimate_new(c0: Pixel, c1: Pixel, old_idx: usize, entries: &[Entry], indices: &[usize]) -> u64 {
180 let mut clu0 = Cluster::new(c0);
181 let mut clu1 = Cluster::new(c1);
184 for (entry, idx) in entries.iter().zip(indices) {
186 if c0.dist(entry.pix) < c1.dist(entry.pix) {
187 clu0.add_dist(entry);
188 count0 += entry.count;
190 clu1.add_dist(entry);
191 count1 += entry.count;
199 clu0.dist + clu1.dist
201 pub fn quantise(&mut self, src: &[Pixel], dst: &mut [[u8; 3]; 256]) {
205 let mut old_cb: [Pixel; 256] = [Pixel::default(); 256];
206 let mut prev_dist = std::u64::MAX;
207 let mut dist = std::u64::MAX / 2;
208 let mut indices = Vec::with_capacity(src.len());
209 let mut pixels = Vec::with_capacity(src.len());
210 pixels.extend_from_slice(src);
211 Self::sort(pixels.as_mut_slice(), |pix| pix.r);
212 Self::sort(pixels.as_mut_slice(), |pix| pix.g);
213 Self::sort(pixels.as_mut_slice(), |pix| pix.b);
214 let mut entries = Vec::with_capacity(pixels.len() / 2);
215 let mut lastval = pixels[0];
217 for pix in pixels.iter().skip(1) {
221 entries.push(Entry { pix: lastval, count: run });
226 entries.push(Entry { pix: lastval, count: run });
229 let mut low_u: Vec<usize> = Vec::with_capacity(256);
230 let mut high_u: Vec<usize> = Vec::with_capacity(256);
231 let mut rng = RNG::new();
232 let mut iterations = 0usize;
233 let mut do_elbg_step = true;
234 while (iterations < 20) && (dist < prev_dist - prev_dist / 1000) {
237 old_cb[i] = self.clusters[i].centroid;
238 self.clusters[i].reset();
240 // put pixels into the nearest clusters
242 for entry in entries.iter() {
244 let mut bestdist = std::u32::MAX;
245 for (i, cluster) in self.clusters.iter().enumerate() {
246 let dist = entry.pix.dist(cluster.centroid);
255 indices.push(bestidx);
256 self.clusters[bestidx].add_pixel(entry);
259 for cluster in self.clusters.iter_mut() {
260 cluster.calc_centroid();
263 for (idx, entry) in indices.iter().zip(entries.iter()) {
264 self.clusters[*idx].add_dist(entry);
266 for cluster in self.clusters.iter_mut() {
268 dist += cluster.dist;
271 let dmean = dist / 256;
274 let mut used = [false; 256];
275 for (i, cluster) in self.clusters.iter().enumerate() {
276 if cluster.dist < dmean {
278 } else if cluster.dist > dmean * 2 {
285 do_elbg_step = false;
286 for low_idx in low_u.iter() {
287 if high_u.len() == 0 {
290 let high_idx_idx = (rng.next() as usize) % high_u.len();
291 let high_idx = high_u[high_idx_idx];
292 let mut closest_idx = *low_idx;
293 let mut closest_dist = std::u32::MAX;
294 let low_centr = self.clusters[*low_idx].centroid;
295 for i in 0..256 {//low_u.iter() {
296 if i == *low_idx || used[i] {
299 let dist = self.clusters[i].centroid.dist(low_centr);
300 if closest_dist > dist {
305 if closest_idx == *low_idx {
308 let old_dist = self.clusters[*low_idx].dist + self.clusters[closest_idx].dist + self.clusters[high_idx].dist;
309 let old_centr = self.old_centre(*low_idx, closest_idx, entries.as_slice(), indices.as_slice());
310 let ret = Self::new_split(high_idx, entries.as_slice(), indices.as_slice());
314 let (centr0, centr1) = ret.unwrap();
315 let dist_o = if old_dist > self.clusters[high_idx].dist {
316 Self::estimate_old(*low_idx, closest_idx, old_centr, entries.as_slice(), indices.as_slice())
318 let dist_n = Self::estimate_new(centr0, centr1, high_idx, entries.as_slice(), indices.as_slice());
319 if dist_o + dist_n < old_dist {
320 self.clusters[*low_idx ].centroid = old_centr;
321 self.clusters[closest_idx].centroid = centr0;
322 self.clusters[high_idx ].centroid = centr1;
323 used[*low_idx] = true;
324 used[closest_idx] = true;
325 used[high_idx] = true;
326 high_u.remove(high_idx_idx);
333 if dist < prev_dist {
335 old_cb[i] = self.clusters[i].centroid;
339 dst[i][0] = old_cb[i].r;
340 dst[i][1] = old_cb[i].g;
341 dst[i][2] = old_cb[i].b;