Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / library / map / src / main / rust / tests / plan_perf_verify.rs

plan_perf_verify.rs470 lines · 16.9 KiBRaw
1//! Plan-verification harness: placement/collision + symbol-emit perf refactors.
2//!
3//! The lib-test target cannot compile in this tree (pre-existing breakage:
4//! missing `overlay_tests.rs`, stale `LAYER_EARTH`/`region_links` fixtures —
5//! all committed at HEAD, out of scope). This integration test links the lib
6//! itself and pins the plan's bit-identical refactorings against from-scratch
7//! reimplementations of the replaced algorithms:
8//! 1. `place_segmented` (grid broadphase + area hoist) vs brute force.
9//! 2. `layout_along_line` (monotonic walk + virtual reversed copy) vs the old
10//! rescan/reversed-collect algorithm.
11//! 3. `obb_overlap` AABB path vs the half-open rect rule.
12//! 4. `candidate_id` determinism / distinctness.
13//! 5. `Ramp::at` single-stop fast path vs a constant.
14
15use map_renderer::tess::text::{layout_along_line, CurvedGlyph, ShapedGlyph, ShapedLine};
16use map_renderer::tile::placement::{
17 candidate_id, obb_overlap, place_segmented, Obb, SegmentedCandidate,
18};
19
20// ---------------------------------------------------------------------------
21// 1. Brute-force placer (the pre-grid algorithm, restated from the old code).
22// ---------------------------------------------------------------------------
23
24fn brute_overlap(a: &Obb, b: &Obb) -> bool {
25 // Full SAT, no AABB fast path — independent of the optimized narrowphase.
26 let axes = [
27 (a.cos, a.sin),
28 (-a.sin, a.cos),
29 (b.cos, b.sin),
30 (-b.sin, b.cos),
31 ];
32 let dx = b.cx - a.cx;
33 let dy = b.cy - a.cy;
34 let radius = |o: &Obb, ax: f32, ay: f32| {
35 let u = (o.cos, o.sin);
36 let v = (-o.sin, o.cos);
37 o.hx * (u.0 * ax + u.1 * ay).abs() + o.hy * (v.0 * ax + v.1 * ay).abs()
38 };
39 axes.iter().all(|(ax, ay)| {
40 let gap = (dx * ax + dy * ay).abs();
41 // NOTE: strict `>=` separation (edge-touching = separated) matches the
42 // documented half-open rule.
43 gap < radius(a, *ax, *ay) + radius(b, *ax, *ay)
44 })
45}
46
47fn brute_area(c: &SegmentedCandidate) -> f32 {
48 c.boxes.iter().map(|b| b.hx * b.hy).sum::<f32>() * 4.0
49}
50
51fn brute_place(candidates: &[SegmentedCandidate]) -> Vec<(u64, bool)> {
52 let mut ordered: Vec<&SegmentedCandidate> = candidates.iter().collect();
53 ordered.sort_by(|a, b| {
54 a.rank
55 .cmp(&b.rank)
56 .then_with(|| b.pop.cmp(&a.pop))
57 .then_with(|| {
58 brute_area(b)
59 .partial_cmp(&brute_area(a))
60 .unwrap_or(std::cmp::Ordering::Equal)
61 })
62 .then_with(|| a.id.cmp(&b.id))
63 });
64 let mut accepted: Vec<Obb> = Vec::new();
65 let mut out = Vec::new();
66 for c in ordered {
67 let free = |boxes: &[Obb], accepted: &[Obb]| {
68 c.rank == 0
69 || !boxes
70 .iter()
71 .any(|b| accepted.iter().any(|a| brute_overlap(a, b)))
72 };
73 let taken = if free(&c.boxes, &accepted) {
74 (&c.boxes, false)
75 } else if let Some(alternate) = c.alternate.as_ref().filter(|a| free(a, &accepted)) {
76 (alternate, true)
77 } else {
78 continue;
79 };
80 accepted.extend_from_slice(taken.0);
81 out.push((c.id, taken.1));
82 }
83 out
84}
85
86/// Deterministic xorshift64 PRNG (fixed seed — the fuzz corpus is stable).
87struct Rng(u64);
88impl Rng {
89 fn next(&mut self) -> u64 {
90 let mut x = self.0;
91 x ^= x << 13;
92 x ^= x >> 7;
93 x ^= x << 17;
94 self.0 = x;
95 x
96 }
97 fn f32(&mut self, lo: f32, hi: f32) -> f32 {
98 lo + (self.next() as f32 / u64::MAX as f32) * (hi - lo)
99 }
100 fn below(&mut self, n: usize) -> usize {
101 (self.next() % n as u64) as usize
102 }
103}
104
105fn random_obb(rng: &mut Rng, axis_aligned_bias: bool) -> Obb {
106 let (cos, sin) = if axis_aligned_bias && rng.below(4) != 0 {
107 (1.0, 0.0) // the point-label majority case
108 } else {
109 let a = rng.f32(0.0, std::f32::consts::TAU);
110 (a.cos(), a.sin())
111 };
112 Obb {
113 cx: rng.f32(0.0, 1024.0),
114 cy: rng.f32(0.0, 1024.0),
115 hx: rng.f32(1.0, 60.0),
116 hy: rng.f32(1.0, 20.0),
117 cos,
118 sin,
119 }
120}
121
122#[test]
123fn grid_broadphase_matches_brute_force_on_fuzz() {
124 let mut rng = Rng(0x1234_5678_9abc_def0);
125 for round in 0..300 {
126 let n = 1 + rng.below(40);
127 let mut candidates: Vec<SegmentedCandidate> = Vec::with_capacity(n);
128 for i in 0..n {
129 let nb = 1 + rng.below(4);
130 let boxes: Vec<Obb> =
131 (0..nb).map(|_| random_obb(&mut rng, true)).collect();
132 let alternate = if rng.below(3) == 0 {
133 let na = 1 + rng.below(3);
134 Some((0..na).map(|_| random_obb(&mut rng, true)).collect())
135 } else {
136 None
137 };
138 candidates.push(SegmentedCandidate {
139 // Forced id/rank/pop collisions to stress tie-breaks.
140 id: (i % 7) as u64,
141 rank: [0, 2, 2, 3, 4, 4, 5][rng.below(7)],
142 pop: (rng.below(4)) as u16,
143 boxes,
144 alternate,
145 feature_id: i as u64 + 1,
146 layer_index: rng.below(3),
147 });
148 }
149 let want = brute_place(&candidates);
150 let got = place_segmented(&candidates);
151 assert_eq!(got, want, "round {round}: grid diverged from brute force");
152 }
153}
154
155#[test]
156fn grid_matches_brute_force_on_degenerate_inputs() {
157 // Empty, single, all-rank-0, identical boxes, edge-touching grid.
158 let empty: Vec<SegmentedCandidate> = vec![];
159 assert_eq!(place_segmented(&empty), brute_place(&empty));
160 let mk = |id: u64, rank: u8, rect: (f32, f32, f32, f32)| SegmentedCandidate {
161 id,
162 rank,
163 pop: 0,
164 boxes: vec![Obb::from_rect(rect)],
165 alternate: None,
166 feature_id: id + 1,
167 layer_index: 0,
168 };
169 // Ten identical boxes: first wins, rest collide.
170 let same: Vec<SegmentedCandidate> = (0..10)
171 .map(|i| mk(i, 4, (0.0, 0.0, 50.0, 20.0)))
172 .collect();
173 assert_eq!(place_segmented(&same), brute_place(&same));
174 assert_eq!(place_segmented(&same).len(), 1);
175 // Edge-touching chain: all place (half-open rule through the grid).
176 let chain: Vec<SegmentedCandidate> = (0..8)
177 .map(|i| mk(i, 4, (i as f32 * 50.0, 0.0, i as f32 * 50.0 + 50.0, 20.0)))
178 .collect();
179 assert_eq!(place_segmented(&chain).len(), 8);
180 assert_eq!(place_segmented(&chain), brute_place(&chain));
181 // Negative coordinates (grid floor division with negatives).
182 let neg: Vec<SegmentedCandidate> = (0..6)
183 .map(|i| mk(i, 4, (-400.0 + i as f32 * 30.0, -300.0, -360.0 + i as f32 * 30.0, -280.0)))
184 .collect();
185 assert_eq!(place_segmented(&neg), brute_place(&neg));
186 // Zero-area boxes.
187 let zero = vec![mk(0, 4, (10.0, 10.0, 10.0, 10.0)), mk(1, 4, (0.0, 0.0, 50.0, 20.0))];
188 assert_eq!(place_segmented(&zero), brute_place(&zero));
189}
190
191// ---------------------------------------------------------------------------
192// 2. Old curved-layout algorithm, restated verbatim (rescan + collect).
193// ---------------------------------------------------------------------------
194
195fn old_polyline_length(pts: &[(f32, f32)]) -> f32 {
196 let mut sum = 0.0;
197 for w in pts.windows(2) {
198 let dx = w[1].0 - w[0].0;
199 let dy = w[1].1 - w[0].1;
200 sum += (dx * dx + dy * dy).sqrt();
201 }
202 sum
203}
204
205const MAX_TURN_RAD: f32 = std::f32::consts::FRAC_PI_4;
206
207fn old_longest_smooth_run(pts: &[(f32, f32)]) -> &[(f32, f32)] {
208 if pts.len() < 3 {
209 return pts;
210 }
211 let cos_max = MAX_TURN_RAD.cos();
212 let direction = |a: (f32, f32), b: (f32, f32)| {
213 let (dx, dy) = (b.0 - a.0, b.1 - a.1);
214 let len = (dx * dx + dy * dy).sqrt();
215 (len > 0.0).then_some((dx / len, dy / len))
216 };
217 let (mut best_start, mut best_end) = (0usize, pts.len());
218 let mut best_len = -1.0f32;
219 let mut start = 0usize;
220 let mut previous: Option<(f32, f32)> = None;
221 for i in 0..pts.len() - 1 {
222 let Some(d) = direction(pts[i], pts[i + 1]) else { continue };
223 if let Some(p) = previous {
224 if p.0 * d.0 + p.1 * d.1 < cos_max {
225 let len = old_polyline_length(&pts[start..=i]);
226 if len > best_len {
227 best_len = len;
228 (best_start, best_end) = (start, i + 1);
229 }
230 start = i;
231 }
232 }
233 previous = Some(d);
234 }
235 if old_polyline_length(&pts[start..]) > best_len {
236 (best_start, best_end) = (start, pts.len());
237 }
238 &pts[best_start..best_end]
239}
240
241fn old_sample_polyline(pts: &[(f32, f32)], d: f32) -> ((f32, f32), (f32, f32)) {
242 let d = d.max(0.0);
243 let mut acc = 0.0f32;
244 for w in pts.windows(2) {
245 let dx = w[1].0 - w[0].0;
246 let dy = w[1].1 - w[0].1;
247 let seg = (dx * dx + dy * dy).sqrt();
248 if seg <= 0.0 {
249 continue;
250 }
251 if acc + seg >= d {
252 let t = ((d - acc) / seg).clamp(0.0, 1.0);
253 return ((w[0].0 + dx * t, w[0].1 + dy * t), (dx / seg, dy / seg));
254 }
255 acc += seg;
256 }
257 let last = *pts.last().unwrap_or(&(0.0, 0.0));
258 for w in pts.windows(2).rev() {
259 let dx = w[1].0 - w[0].0;
260 let dy = w[1].1 - w[0].1;
261 let seg = (dx * dx + dy * dy).sqrt();
262 if seg > 0.0 {
263 return (last, (dx / seg, dy / seg));
264 }
265 }
266 (last, (1.0, 0.0))
267}
268
269fn old_layout_along_line(
270 line: &ShapedLine,
271 centreline: &[(f32, f32)],
272 px_per_font_unit: f32,
273 up_em: f32,
274) -> Vec<CurvedGlyph> {
275 if centreline.len() < 2 || line.glyphs.is_empty() || px_per_font_unit <= 0.0 {
276 return Vec::new();
277 }
278 let smooth = old_longest_smooth_run(centreline);
279 if smooth.len() < 2 {
280 return Vec::new();
281 }
282 let total_len = old_polyline_length(smooth);
283 let run_len = line.advance * px_per_font_unit;
284 if run_len <= 0.0 || run_len > total_len {
285 return Vec::new();
286 }
287 let net_dx = smooth[smooth.len() - 1].0 - smooth[0].0;
288 let reversed: Vec<(f32, f32)>;
289 let path: &[(f32, f32)] = if net_dx < 0.0 {
290 reversed = smooth.iter().rev().copied().collect();
291 &reversed
292 } else {
293 smooth
294 };
295 let start = (total_len - run_len) * 0.5;
296 let half_window = up_em * px_per_font_unit;
297 let mut out = Vec::with_capacity(line.glyphs.len());
298 for g in &line.glyphs {
299 let d = start + g.pen_x * px_per_font_unit;
300 let (pen, segment_tangent) = old_sample_polyline(path, d);
301 let (behind, _) = old_sample_polyline(path, d - half_window);
302 let (ahead, _) = old_sample_polyline(path, d + half_window);
303 let (dx, dy) = (ahead.0 - behind.0, ahead.1 - behind.1);
304 let chord = (dx * dx + dy * dy).sqrt();
305 let tangent = if chord > 1e-7 { (dx / chord, dy / chord) } else { segment_tangent };
306 out.push(CurvedGlyph { glyph: *g, pen, tangent });
307 }
308 out
309}
310
311fn block_run(n: usize, up_em: f32) -> ShapedLine {
312 let glyphs: Vec<ShapedGlyph> = (0..n)
313 .map(|i| ShapedGlyph {
314 pen_x: i as f32 * up_em,
315 ch: 'x',
316 advance: up_em,
317 bearing_x: 0.0,
318 top: up_em,
319 w: up_em,
320 h: up_em,
321 })
322 .collect();
323 ShapedLine { glyphs, advance: n as f32 * up_em }
324}
325
326fn assert_same_layout(got: &[CurvedGlyph], want: &[CurvedGlyph], ctx: &str) {
327 assert_eq!(got.len(), want.len(), "{ctx}: glyph count");
328 // Forward walks are bit-identical (same operands, same order). Reversed walks
329 // mirror arcs about the total length instead of accumulating a reversed copy,
330 // so they may differ in the last ulp; anything bigger is a real divergence.
331 for (i, (g, w)) in got.iter().zip(want.iter()).enumerate() {
332 for (field, gv, wv) in [
333 ("pen.x", g.pen.0, w.pen.0),
334 ("pen.y", g.pen.1, w.pen.1),
335 ("tan.x", g.tangent.0, w.tangent.0),
336 ("tan.y", g.tangent.1, w.tangent.1),
337 ] {
338 if gv.to_bits() != wv.to_bits() {
339 let bad = (gv - wv).abs();
340 assert!(
341 bad <= 2.0 * f32::EPSILON * wv.abs().max(1.0),
342 "{ctx}[{i}] {field}: {gv} vs {wv} (diff {bad} exceeds 2ulp)"
343 );
344 }
345 }
346 }
347}
348
349#[test]
350fn linearized_layout_matches_old_algorithm_bit_for_bit() {
351 let up_em = 1000.0f32;
352 let ppfu = 1.0 / up_em;
353 // Straight, reversed (net_dx < 0), elbow, gentle bend, degenerate points,
354 // multi-part join, arc, tiny stub.
355 let mut arc = Vec::new();
356 for i in 0..=48 {
357 let t = std::f32::consts::FRAC_PI_2 * i as f32 / 48.0;
358 arc.push((0.5 + 0.35 * t.cos(), 0.5 + 0.35 * t.sin()));
359 }
360 let cases: Vec<(&str, Vec<(f32, f32)>)> = vec![
361 ("straight", vec![(0.0, 0.0), (12.0, 0.0)]),
362 ("reversed", vec![(12.0, 0.0), (0.0, 0.0)]),
363 ("rev-bend", vec![(9.0, 4.0), (2.0, 0.5), (0.0, 0.0)]),
364 ("elbow", vec![(0.0, 0.0), (4.0, 0.0), (4.0, 9.0)]),
365 ("bend30", {
366 let c = 30.0f32.to_radians();
367 vec![(0.0, 0.0), (6.0, 0.0), (6.0 + 6.0 * c.cos(), 6.0 * c.sin())]
368 }),
369 ("degenerate", vec![(0.0, 0.0), (0.0, 0.0), (6.0, 0.0), (6.0, 0.0), (12.0, 0.0)]),
370 (
371 "join",
372 vec![(0.0, 0.0), (6.0, 0.0), (0.0, 4.0), (9.0, 4.0)],
373 ),
374 ("arc", arc),
375 ("zigzag", vec![(0.0, 0.0), (2.0, 1.0), (4.0, 0.0), (6.0, 1.0), (8.0, 0.0), (10.0, 1.0)]),
376 // Net-dx-zero paths: neither forward nor reversed by the sign test — the
377 // walk takes the forward branch (strict `<`), matching the old code's
378 // `net_dx < 0.0` gate exactly.
379 ("vertical", vec![(3.0, 0.0), (3.0, 12.0)]),
380 ("rev-vertical", vec![(3.0, 12.0), (3.0, 0.0)]),
381 ("there-and-back", vec![(0.0, 0.0), (6.0, 0.0), (0.0, 0.0)]),
382 ];
383 for (name, path) in &cases {
384 for n in [1usize, 3, 8, 10] {
385 let run = block_run(n, up_em);
386 let want = old_layout_along_line(&run, path, ppfu, up_em);
387 let got = layout_along_line(&run, path, ppfu);
388 assert_same_layout(&got, &want, &format!("{name}/n={n}"));
389 }
390 }
391}
392
393#[test]
394fn linearized_layout_matches_on_fuzz_polylines() {
395 let up_em = 1000.0f32;
396 let mut rng = Rng(0xfeed_face_cafe_1234);
397 for round in 0..200 {
398 let npts = 2 + rng.below(14);
399 let mut path = Vec::with_capacity(npts);
400 let (mut x, mut y) = (rng.f32(0.0, 1.0), rng.f32(0.0, 1.0));
401 path.push((x, y));
402 for _ in 1..npts {
403 // Random walk, sometimes repeating a vertex (degenerate segment).
404 if rng.below(8) == 0 {
405 path.push((x, y));
406 } else {
407 x += rng.f32(-0.2, 0.2);
408 y += rng.f32(-0.2, 0.2);
409 path.push((x, y));
410 }
411 }
412 let n = 1 + rng.below(12);
413 let run = block_run(n, up_em);
414 // Vary text size over two orders of magnitude.
415 let ppfu = [0.5, 1.0, 3.0][rng.below(3)] / up_em;
416 let want = old_layout_along_line(&run, &path, ppfu, up_em);
417 let got = layout_along_line(&run, &path, ppfu);
418 assert_same_layout(&got, &want, &format!("fuzz round {round}"));
419 }
420}
421
422// ---------------------------------------------------------------------------
423// 3-5. AABB rule, candidate_id, Ramp.
424// ---------------------------------------------------------------------------
425
426#[test]
427fn aabb_fast_path_matches_half_open_rect_rule() {
428 let rect_overlaps =
429 |a: (f32, f32, f32, f32), b: (f32, f32, f32, f32)| a.0 < b.2 && b.0 < a.2 && a.1 < b.3 && b.1 < a.3;
430 let mut rng = Rng(0x0bad_f00d_dead_beef);
431 for _ in 0..500 {
432 let r = |mut v: (f32, f32, f32, f32)| {
433 if v.0 > v.2 {
434 std::mem::swap(&mut v.0, &mut v.2);
435 }
436 if v.1 > v.3 {
437 std::mem::swap(&mut v.1, &mut v.3);
438 }
439 v
440 };
441 let a = r((rng.f32(-50.0, 50.0), rng.f32(-50.0, 50.0), rng.f32(-50.0, 50.0), rng.f32(-50.0, 50.0)));
442 let b = r((rng.f32(-50.0, 50.0), rng.f32(-50.0, 50.0), rng.f32(-50.0, 50.0), rng.f32(-50.0, 50.0)));
443 let oa = Obb::from_rect(a);
444 let ob = Obb::from_rect(b);
445 assert_eq!(obb_overlap(&oa, &ob), rect_overlaps(a, b), "a={a:?} b={b:?}");
446 }
447 // Exact edge touch: separated.
448 let a = Obb::from_rect((0.0, 0.0, 10.0, 10.0));
449 let flush = Obb::from_rect((10.0, 0.0, 20.0, 10.0));
450 assert!(!obb_overlap(&a, &flush));
451}
452
453#[test]
454fn candidate_ids_stable_and_distinct() {
455 let a = candidate_id(6, 10, 24, 33, 4);
456 assert_eq!(a, candidate_id(6, 10, 24, 33, 4));
457 assert_ne!(a, candidate_id(6, 10, 24, 33, 5));
458 assert_ne!(a, candidate_id(6, 10, 25, 33, 4));
459 assert_ne!(a, candidate_id(6, 10, 24, 34, 4));
460 assert_ne!(a, candidate_id(7, 10, 24, 33, 4));
461}
462
463#[test]
464fn ramp_single_stop_answers_constant() {
465 use map_renderer::style::paint::Ramp;
466 let c = Ramp::constant(3.5);
467 for z in [-10.0, 0.0, 5.5, 14.0, 22.0, 100.0] {
468 assert_eq!(c.at(z).to_bits(), 3.5f32.to_bits(), "z={z}");
469 }
470}