1use super::expr::Color;
5use std::fmt::Write as _;
6
7pub fn num(v: f64) -> String {
9 let s = format!("{v:.2}");
10 let s = s.trim_end_matches('0').trim_end_matches('.');
11 if s == "-0" || s.is_empty() { "0".into() } else { s.to_owned() }
12}
13
14pub fn alpha(v: f64) -> String {
17 let s = format!("{v:.4}");
18 let s = s.trim_end_matches('0').trim_end_matches('.');
19 if s.is_empty() || s == "-0" { "0".into() } else { s.to_owned() }
20}
21
22pub fn paint(c: Color, opacity: f64) -> Option<(String, f64)> {
24 let a = c.a as f64 * opacity;
25 if a <= 0.0 {
26 return None;
27 }
28 let ca = c.a.max(1e-9) as f64;
29 let ch = |v: f32| ((v as f64 / ca).clamp(0.0, 1.0) * 255.0).round() as u8;
30 Some((format!("#{:02x}{:02x}{:02x}", ch(c.r), ch(c.g), ch(c.b)), a.min(1.0)))
31}
32
33pub fn path_data(rings: &[Vec<(f64, f64)>], close: bool) -> String {
35 let mut d = String::new();
36 for r in rings {
37 let mut it = r.iter();
38 let Some(&(x, y)) = it.next() else { continue };
39 let _ = write!(d, "M{} {}", num(x), num(y));
40 for &(x, y) in it {
41 let _ = write!(d, "L{} {}", num(x), num(y));
42 }
43 if close {
44 d.push('Z');
45 }
46 }
47 d
48}
49
50pub fn xml_escape(s: &str) -> String {
52 s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """)
53}
54
55pub fn trace_contours(w: usize, h: usize, value: impl Fn(usize, usize) -> f64, threshold: f64) -> Vec<Vec<(f64, f64)>> {
61 let v = |i: i64, j: i64| -> f64 {
62 if i < 0 || j < 0 || i >= w as i64 || j >= h as i64 { 0.0 } else { value(i as usize, j as usize) }
63 };
64 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
67 enum E {
68 H(i64, i64),
69 V(i64, i64),
70 }
71 let point = |e: E| -> (f64, f64) {
72 let (i0, j0, i1, j1) = match e {
73 E::H(i, j) => (i, j, i + 1, j),
74 E::V(i, j) => (i, j, i, j + 1),
75 };
76 let (a, b) = (v(i0, j0), v(i1, j1));
77 let t = if (b - a).abs() < 1e-12 { 0.5 } else { ((threshold - a) / (b - a)).clamp(0.0, 1.0) };
78 let x = i0 as f64 + (i1 - i0) as f64 * t + 0.5;
79 let y = j0 as f64 + (j1 - j0) as f64 * t + 0.5;
80 (x, y)
81 };
82 let mut segs: Vec<(E, E)> = Vec::new();
83 for j in -1..h as i64 {
84 for i in -1..w as i64 {
85 let (a, b, c, d) = (v(i, j), v(i + 1, j), v(i + 1, j + 1), v(i, j + 1)); let idx = (a >= threshold) as u8 | ((b >= threshold) as u8) << 1 | ((c >= threshold) as u8) << 2 | ((d >= threshold) as u8) << 3;
87 let sides = [E::H(i, j), E::V(i + 1, j), E::H(i, j + 1), E::V(i, j)]; let inside = [a >= threshold, b >= threshold, c >= threshold, d >= threshold]; let centre = (a + b + c + d) / 4.0 >= threshold;
90 const T: usize = 0;
91 const R: usize = 1;
92 const B: usize = 2;
93 const L: usize = 3;
94 let mut push = |s1: usize, s2: usize| {
95 let (s1, s2) = orient(s1, s2, inside);
96 segs.push((sides[s1], sides[s2]));
97 };
98 match idx {
99 0 | 15 => {}
100 1 | 14 => push(L, T),
101 2 | 13 => push(T, R),
102 3 | 12 => push(L, R),
103 4 | 11 => push(R, B),
104 6 | 9 => push(T, B),
105 7 | 8 => push(L, B),
106 5 => {
107 if centre {
108 push(L, B);
109 push(T, R);
110 } else {
111 push(L, T);
112 push(R, B);
113 }
114 }
115 10 => {
116 if centre {
117 push(L, T);
118 push(R, B);
119 } else {
120 push(L, B);
121 push(T, R);
122 }
123 }
124 _ => {}
125 }
126 }
127 }
128 let mut starts: std::collections::HashMap<E, Vec<usize>> = std::collections::HashMap::new();
131 for (k, (p, _)) in segs.iter().enumerate() {
132 starts.entry(*p).or_default().push(k);
133 }
134 let mut used = vec![false; segs.len()];
135 let mut rings = Vec::new();
136 for start in 0..segs.len() {
137 if used[start] {
138 continue;
139 }
140 used[start] = true;
141 let (first, mut cur) = segs[start];
142 let mut ring = vec![point(first), point(cur)];
143 while cur != first {
144 let Some(&next) = starts.get(&cur).and_then(|l| l.iter().find(|&&k| !used[k])) else { break };
145 used[next] = true;
146 cur = segs[next].1;
147 ring.push(point(cur));
148 }
149 if ring.len() >= 4 {
150 ring.pop(); rings.push(ring);
152 }
153 }
154 rings
155}
156
157fn orient(s1: usize, s2: usize, inside: [bool; 4]) -> (usize, usize) {
162 const MID: [(f64, f64); 4] = [(0.5, 0.0), (1.0, 0.5), (0.5, 1.0), (0.0, 0.5)];
163 const CORNER: [(f64, f64); 4] = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)];
164 let k = match (s1.min(s2), s1.max(s2)) {
167 (0, 3) => 0,
168 (0, 1) => 1,
169 (1, 2) => 2,
170 (2, 3) => 3,
171 _ => 0,
172 };
173 let (p, q) = (MID[s1], MID[s2]);
174 let (dx, dy) = (q.0 - p.0, q.1 - p.1);
175 let (rx, ry) = (CORNER[k].0 - p.0, CORNER[k].1 - p.1);
176 let left_of_travel = dx * ry - dy * rx < 0.0;
177 if left_of_travel == inside[k] { (s1, s2) } else { (s2, s1) }
178}
179
180pub fn base64(data: &[u8]) -> String {
182 const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
183 let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
184 for chunk in data.chunks(3) {
185 let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)];
186 let n = (b[0] as u32) << 16 | (b[1] as u32) << 8 | b[2] as u32;
187 out.push(T[(n >> 18) as usize & 63] as char);
188 out.push(T[(n >> 12) as usize & 63] as char);
189 out.push(if chunk.len() > 1 { T[(n >> 6) as usize & 63] as char } else { '=' });
190 out.push(if chunk.len() > 2 { T[n as usize & 63] as char } else { '=' });
191 }
192 out
193}
194
195pub fn png_data_uri(w: u32, h: u32, rgba: &[u8]) -> String {
197 let mut buf = Vec::new();
198 let enc = image::codecs::png::PngEncoder::new(&mut buf);
199 use image::ImageEncoder;
200 let _ = enc.write_image(rgba, w, h, image::ExtendedColorType::Rgba8);
201 format!("data:image/png;base64,{}", base64(&buf))
202}
203
204#[cfg(test)]
205mod tests {
206 use super::*;
207
208 #[test]
209 fn contour_of_a_square_blob_is_one_ring() {
210 let (w, h) = (6, 6);
211 let rings = trace_contours(w, h, |i, j| if (2..4).contains(&i) && (2..4).contains(&j) { 1.0 } else { 0.0 }, 0.5);
212 assert_eq!(rings.len(), 1);
213 assert!(rings[0].len() >= 4);
214 }
215
216 fn area(r: &[(f64, f64)]) -> f64 {
218 (0..r.len()).map(|k| {
219 let (a, b) = (r[k], r[(k + 1) % r.len()]);
220 a.0 * b.1 - b.0 * a.1
221 }).sum::<f64>() / 2.0
222 }
223
224 #[test]
225 fn holes_wind_opposite_to_outer_rings() {
226 let rings = trace_contours(8, 8, |i, j| {
228 let on = (1..7).contains(&i) && (1..7).contains(&j);
229 let hole = (3..5).contains(&i) && (3..5).contains(&j);
230 if on && !hole { 1.0 } else { 0.0 }
231 }, 0.5);
232 assert_eq!(rings.len(), 2);
233 let (a0, a1) = (area(&rings[0]), area(&rings[1]));
234 assert!(a0 * a1 < 0.0, "outer and hole must wind oppositely: {a0} {a1}");
235 }
236
237 #[test]
238 fn saddle_blobs_wind_the_same_way() {
239 let rings = trace_contours(4, 4, |i, j| if (i < 2) == (j < 2) { 1.0 } else { 0.0 }, 0.6);
241 assert!(rings.len() >= 2);
242 let signs: Vec<bool> = rings.iter().map(|r| area(r) > 0.0).collect();
243 assert!(signs.iter().all(|&s| s == signs[0]), "{signs:?}");
244 }
245
246 #[test]
247 fn base64_matches_known_values() {
248 assert_eq!(base64(b"Man"), "TWFu");
249 assert_eq!(base64(b"Ma"), "TWE=");
250 assert_eq!(base64(b"M"), "TQ==");
251 }
252}