1use crate::int32::div_u64_by_u32;
11use core::mem::MaybeUninit;
12
13#[derive(Copy, Clone, Debug, Eq, PartialEq)]
19pub enum ClipTraversal {
20 PreviousToCurrent,
22 CurrentToNext,
24}
25
26#[inline(always)]
34pub fn crossing_fraction_q12_i32(first_distance: i32, second_distance: i32) -> i32 {
35 ratio_q12_i32(first_distance, first_distance.wrapping_sub(second_distance))
36}
37
38#[inline(always)]
47pub fn crossing_fraction_q16_i32(first_distance: i32, second_distance: i32) -> u32 {
48 let difference_positive = first_distance > second_distance;
51 if first_distance == second_distance {
52 return 1 << 16;
53 }
54 if (first_distance >= 0) != difference_positive {
55 return 0;
56 }
57 let numerator = first_distance.unsigned_abs();
58 let denominator = first_distance.abs_diff(second_distance);
59 let magnitude = if numerator < (1 << 16) {
60 (numerator << 16) / denominator
61 } else {
62 if (numerator >> 16) >= denominator {
66 return 1 << 16;
67 }
68 div_u64_by_u32(numerator >> 16, numerator << 16, denominator)
69 };
70 magnitude.min(1 << 16)
71}
72
73#[inline(always)]
80pub fn lerp_q16_i32_exact(first: i32, second: i32, fraction_q16: u32) -> i32 {
81 let delta = second.wrapping_sub(first);
82 debug_assert!(delta.unsigned_abs() < (1 << 23));
83 let high = (fraction_q16 >> 8) as i32;
84 let low = (fraction_q16 & 0xff) as i32;
85 first.wrapping_add(
89 (delta
90 .wrapping_mul(high)
91 .wrapping_add((delta.wrapping_mul(low)) >> 8))
92 >> 8,
93 )
94}
95
96#[inline(always)]
102pub fn lerp_q12_i32(first: i32, second: i32, fraction: i32) -> i32 {
103 let delta = second.wrapping_sub(first);
104 first.wrapping_add(delta.wrapping_mul(fraction) >> 12)
105}
106
107#[inline(always)]
110pub fn lerp_q12_i32_rounded(first: i32, second: i32, fraction: i32) -> i32 {
111 first.wrapping_add(
112 (second
113 .wrapping_sub(first)
114 .wrapping_mul(fraction)
115 .wrapping_add(1 << 11))
116 >> 12,
117 )
118}
119
120#[inline(always)]
122pub fn lerp_q12_i32_wide(first: i32, second: i32, fraction: i32) -> i32 {
123 let delta = second.wrapping_sub(first);
124 first
125 .wrapping_add((delta / 4096).wrapping_mul(fraction))
126 .wrapping_add(((delta % 4096).wrapping_mul(fraction)) >> 12)
127}
128
129#[inline(always)]
135pub fn ratio_q12_i32(numerator: i32, denominator: i32) -> i32 {
136 if denominator == 0 || (numerator < 0) != (denominator < 0) {
137 return 0;
138 }
139 let mut numerator = numerator.unsigned_abs();
140 let mut denominator = denominator.unsigned_abs();
141 while numerator > (i32::MAX as u32 >> 12) {
142 numerator = (numerator + 1) >> 1;
143 denominator = (denominator + 1) >> 1;
144 }
145 if denominator == 0 {
146 return 0;
147 }
148 ((numerator << 12) / denominator).min(4096) as i32
149}
150
151pub trait AttributedClipPlane<Vertex> {
157 type Distance: Copy;
159
160 fn distance(&self, source_index: usize, vertex: &Vertex) -> Self::Distance;
162
163 fn inside(&self, distance: Self::Distance) -> bool;
165
166 fn intersection(
168 &self,
169 first_index: usize,
170 first: &Vertex,
171 first_distance: Self::Distance,
172 second_index: usize,
173 second: &Vertex,
174 second_distance: Self::Distance,
175 ) -> Vertex;
176}
177
178#[derive(Clone, Copy, Debug, PartialEq, Eq)]
181pub struct ClipOverflow;
182
183impl core::fmt::Display for ClipOverflow {
184 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
185 f.write_str("clip output does not fit the destination")
186 }
187}
188
189#[inline(always)]
202pub fn clip_to_plane<Vertex: Copy, Plane: AttributedClipPlane<Vertex>>(
203 source: &[Vertex],
204 destination: &mut [Vertex],
205 plane: &Plane,
206 traversal: ClipTraversal,
207) -> Result<usize, ClipOverflow> {
208 unsafe {
213 clip_convex_plane_raw::<_, _, true>(
214 source,
215 destination.as_mut_ptr(),
216 destination.len(),
217 plane,
218 traversal,
219 )
220 }
221 .map_err(|_| ClipOverflow)
222}
223
224#[inline(always)]
234pub unsafe fn clip_to_plane_unchecked<Vertex: Copy, Plane: AttributedClipPlane<Vertex>>(
235 source: &[Vertex],
236 destination: &mut [Vertex],
237 plane: &Plane,
238 traversal: ClipTraversal,
239) -> usize {
240 match unsafe {
245 clip_convex_plane_raw::<_, _, false>(
246 source,
247 destination.as_mut_ptr(),
248 destination.len(),
249 plane,
250 traversal,
251 )
252 } {
253 Ok(written) | Err(written) => written,
254 }
255}
256
257#[deprecated(
268 note = "use the safe `clip_to_plane` (checked) or `clip_to_plane_unchecked` (proven capacity)"
269)]
270#[inline(always)]
271pub unsafe fn clip_convex_plane<
272 Vertex: Copy,
273 Plane: AttributedClipPlane<Vertex>,
274 const CHECK_CAPACITY: bool,
275>(
276 source: &[Vertex],
277 destination: &mut [Vertex],
278 plane: &Plane,
279 traversal: ClipTraversal,
280) -> usize {
281 match unsafe {
286 clip_convex_plane_raw::<_, _, CHECK_CAPACITY>(
287 source,
288 destination.as_mut_ptr(),
289 destination.len(),
290 plane,
291 traversal,
292 )
293 } {
294 Ok(written) | Err(written) => written,
295 }
296}
297
298#[inline(always)]
306pub fn clip_to_plane_uninit<Vertex: Copy, Plane: AttributedClipPlane<Vertex>>(
307 source: &[Vertex],
308 destination: &mut [MaybeUninit<Vertex>],
309 plane: &Plane,
310 traversal: ClipTraversal,
311) -> Result<usize, ClipOverflow> {
312 unsafe {
317 clip_convex_plane_raw::<_, _, true>(
318 source,
319 destination.as_mut_ptr().cast::<Vertex>(),
320 destination.len(),
321 plane,
322 traversal,
323 )
324 }
325 .map_err(|_| ClipOverflow)
326}
327
328#[inline(always)]
335pub unsafe fn clip_to_plane_uninit_unchecked<Vertex: Copy, Plane: AttributedClipPlane<Vertex>>(
336 source: &[Vertex],
337 destination: &mut [MaybeUninit<Vertex>],
338 plane: &Plane,
339 traversal: ClipTraversal,
340) -> usize {
341 match unsafe {
344 clip_convex_plane_raw::<_, _, false>(
345 source,
346 destination.as_mut_ptr().cast::<Vertex>(),
347 destination.len(),
348 plane,
349 traversal,
350 )
351 } {
352 Ok(written) | Err(written) => written,
353 }
354}
355
356#[deprecated(
363 note = "use the safe `clip_to_plane_uninit` (checked) or `clip_to_plane_uninit_unchecked` (proven capacity)"
364)]
365#[inline(always)]
366pub unsafe fn clip_convex_plane_uninit<
367 Vertex: Copy,
368 Plane: AttributedClipPlane<Vertex>,
369 const CHECK_CAPACITY: bool,
370>(
371 source: &[Vertex],
372 destination: &mut [MaybeUninit<Vertex>],
373 plane: &Plane,
374 traversal: ClipTraversal,
375) -> usize {
376 match unsafe {
382 clip_convex_plane_raw::<_, _, CHECK_CAPACITY>(
383 source,
384 destination.as_mut_ptr().cast::<Vertex>(),
385 destination.len(),
386 plane,
387 traversal,
388 )
389 } {
390 Ok(written) | Err(written) => written,
391 }
392}
393
394#[inline(always)]
398unsafe fn clip_convex_plane_raw<
399 Vertex: Copy,
400 Plane: AttributedClipPlane<Vertex>,
401 const CHECK_CAPACITY: bool,
402>(
403 source: &[Vertex],
404 destination: *mut Vertex,
405 destination_len: usize,
406 plane: &Plane,
407 traversal: ClipTraversal,
408) -> Result<usize, usize> {
409 if source.is_empty() {
410 return Ok(0);
411 }
412 if !CHECK_CAPACITY {
413 debug_assert!(destination_len >= source.len().saturating_add(1));
414 }
415
416 #[inline(always)]
417 unsafe fn emit<Vertex: Copy, const CHECK_CAPACITY: bool>(
418 destination: *mut Vertex,
419 destination_len: usize,
420 written: &mut usize,
421 vertex: Vertex,
422 ) -> bool {
423 if CHECK_CAPACITY && *written >= destination_len {
424 return false;
425 }
426 debug_assert!(*written < destination_len);
427 unsafe { destination.add(*written).write(vertex) };
432 *written += 1;
433 true
434 }
435
436 let mut written = 0usize;
437 match traversal {
438 ClipTraversal::PreviousToCurrent => {
439 let mut previous_index = source.len() - 1;
440 let mut previous = unsafe { source.get_unchecked(previous_index) };
449 let mut previous_distance = plane.distance(previous_index, previous);
450 let mut current_index = 0usize;
451 while current_index < source.len() {
452 let current = unsafe { source.get_unchecked(current_index) };
454 let current_distance = plane.distance(current_index, current);
455 let current_inside = plane.inside(current_distance);
456 if current_inside != plane.inside(previous_distance) {
457 if unsafe {
461 !emit::<Vertex, CHECK_CAPACITY>(
462 destination,
463 destination_len,
464 &mut written,
465 plane.intersection(
466 previous_index,
467 previous,
468 previous_distance,
469 current_index,
470 current,
471 current_distance,
472 ),
473 )
474 } {
475 return Err(written);
476 }
477 }
478 if current_inside
479 && unsafe {
482 !emit::<Vertex, CHECK_CAPACITY>(
483 destination,
484 destination_len,
485 &mut written,
486 *current,
487 )
488 }
489 {
490 return Err(written);
491 }
492 previous_index = current_index;
493 previous = current;
494 previous_distance = current_distance;
495 current_index += 1;
496 }
497 }
498 ClipTraversal::CurrentToNext => {
499 let mut current_index = 0usize;
500 while current_index < source.len() {
501 let next_index = if current_index + 1 == source.len() {
502 0
503 } else {
504 current_index + 1
505 };
506 let current = unsafe { source.get_unchecked(current_index) };
508 let next = unsafe { source.get_unchecked(next_index) };
511 let current_distance = plane.distance(current_index, current);
512 let next_distance = plane.distance(next_index, next);
513 let current_inside = plane.inside(current_distance);
514 if current_inside
515 && unsafe {
518 !emit::<Vertex, CHECK_CAPACITY>(
519 destination,
520 destination_len,
521 &mut written,
522 *current,
523 )
524 }
525 {
526 return Err(written);
527 }
528 if current_inside != plane.inside(next_distance) {
529 if unsafe {
533 !emit::<Vertex, CHECK_CAPACITY>(
534 destination,
535 destination_len,
536 &mut written,
537 plane.intersection(
538 current_index,
539 current,
540 current_distance,
541 next_index,
542 next,
543 next_distance,
544 ),
545 )
546 } {
547 return Err(written);
548 }
549 }
550 current_index += 1;
551 }
552 }
553 }
554 Ok(written)
555}
556
557#[cfg(test)]
558mod tests {
559 use super::*;
560
561 #[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
562 struct Vertex(i32, i32);
563
564 struct Plane<'a>(Option<&'a [i32]>);
565
566 impl AttributedClipPlane<Vertex> for Plane<'_> {
567 type Distance = i32;
568
569 fn distance(&self, index: usize, vertex: &Vertex) -> i32 {
570 self.0.map_or(vertex.0, |distances| distances[index])
571 }
572
573 fn inside(&self, distance: i32) -> bool {
574 distance >= 0
575 }
576
577 fn intersection(
578 &self,
579 _: usize,
580 first: &Vertex,
581 first_distance: i32,
582 _: usize,
583 second: &Vertex,
584 second_distance: i32,
585 ) -> Vertex {
586 Vertex(
587 0,
588 first.1
589 + (second.1 - first.1) * first_distance / (first_distance - second_distance),
590 )
591 }
592 }
593
594 fn clip<const CHECK: bool>(
595 source: &[Vertex],
596 traversal: ClipTraversal,
597 ) -> ([Vertex; 8], usize) {
598 let mut output = [Vertex::default(); 8];
599 assert!(2 * source.len() <= output.len());
600 let count = if CHECK {
601 clip_to_plane(source, &mut output, &Plane(None), traversal).expect("fits")
602 } else {
603 unsafe { clip_to_plane_unchecked(source, &mut output, &Plane(None), traversal) }
606 };
607 (output, count)
608 }
609
610 #[test]
611 fn traversal_preserves_each_historical_fan_start() {
612 let source = [Vertex(-2, 0), Vertex(2, 40), Vertex(2, 80)];
613 let (previous, previous_count) = clip::<true>(&source, ClipTraversal::PreviousToCurrent);
614 assert_eq!(previous_count, 4);
615 assert_eq!(
616 &previous[..previous_count],
617 &[Vertex(0, 40), Vertex(0, 20), source[1], source[2]]
618 );
619 let (current, current_count) = clip::<false>(&source, ClipTraversal::CurrentToNext);
620 assert_eq!(current_count, 4);
621 assert_eq!(
622 ¤t[..current_count],
623 &[Vertex(0, 20), source[1], source[2], Vertex(0, 40)]
624 );
625 }
626
627 #[test]
628 fn cached_distance_domain_is_authoritative() {
629 let source = [Vertex(100, 0), Vertex(100, 40), Vertex(100, 80)];
630 let mut output = [Vertex::default(); 4];
631 let count = clip_to_plane(
632 &source,
633 &mut output,
634 &Plane(Some(&[-2, 2, 2])),
635 ClipTraversal::CurrentToNext,
636 );
637 assert_eq!(count, Ok(4));
638 assert_eq!(output, [Vertex(0, 20), source[1], source[2], Vertex(0, 40)]);
639 }
640
641 #[test]
645 fn non_convex_input_overflows_len_plus_one_but_fits_twice_len() {
646 let zigzag = [Vertex(1, 0), Vertex(-1, 10), Vertex(1, 20), Vertex(-1, 30)];
647 for traversal in [
648 ClipTraversal::PreviousToCurrent,
649 ClipTraversal::CurrentToNext,
650 ] {
651 let mut tight = [Vertex::default(); 5];
652 assert_eq!(
653 clip_to_plane(&zigzag, &mut tight, &Plane(None), traversal),
654 Err(ClipOverflow)
655 );
656 let mut roomy = [Vertex::default(); 8];
657 assert_eq!(
658 clip_to_plane(&zigzag, &mut roomy, &Plane(None), traversal),
659 Ok(6)
660 );
661 let mut uninit = [MaybeUninit::<Vertex>::uninit(); 5];
662 assert_eq!(
663 clip_to_plane_uninit(&zigzag, &mut uninit, &Plane(None), traversal),
664 Err(ClipOverflow)
665 );
666 }
667 }
668
669 #[allow(deprecated)]
672 #[test]
673 fn deprecated_forwarders_keep_partial_counts() {
674 let zigzag = [Vertex(1, 0), Vertex(-1, 10), Vertex(1, 20), Vertex(-1, 30)];
675 let mut tight = [Vertex::default(); 5];
676 let count = unsafe {
678 clip_convex_plane::<_, _, true>(
679 &zigzag,
680 &mut tight,
681 &Plane(None),
682 ClipTraversal::PreviousToCurrent,
683 )
684 };
685 assert_eq!(count, 5);
686 }
687
688 #[test]
689 fn canonical_q12_crossing_is_direction_independent() {
690 let interpolate =
691 |mut first: i32, mut second: i32, mut first_distance: i32, mut second_distance: i32| {
692 if second < first {
693 core::mem::swap(&mut first, &mut second);
694 core::mem::swap(&mut first_distance, &mut second_distance);
695 }
696 lerp_q12_i32(
697 first,
698 second,
699 crossing_fraction_q12_i32(first_distance, second_distance),
700 )
701 };
702 assert_eq!(interpolate(10, 110, 7, -3), 79);
703 assert_eq!(interpolate(110, 10, -3, 7), 79);
704 }
705
706 #[test]
707 fn measured_numeric_policies_keep_their_rounding_contracts() {
708 let q12 = crossing_fraction_q12_i32(7, -3);
709 assert_eq!(lerp_q12_i32(10, 110, q12), 79);
710 assert_eq!(lerp_q12_i32_rounded(10, 110, q12), 80);
711
712 let q16 = crossing_fraction_q16_i32(7, -3);
713 assert_eq!(lerp_q16_i32_exact(10, 110, q16), 79);
714 }
715
716 #[test]
717 fn all_inside_and_all_outside_are_stable() {
718 let inside = [Vertex(1, 1), Vertex(2, 2), Vertex(3, 3)];
719 let outside = [Vertex(-1, 1), Vertex(-2, 2), Vertex(-3, 3)];
720 let (inside_output, inside_count) = clip::<true>(&inside, ClipTraversal::PreviousToCurrent);
721 assert_eq!(inside_count, inside.len());
722 assert_eq!(&inside_output[..inside_count], &inside);
723 let (_, outside_count) = clip::<true>(&outside, ClipTraversal::PreviousToCurrent);
724 assert_eq!(outside_count, 0);
725 }
726
727 fn crossing_fraction_q16_i64(first: i64, second: i64) -> i64 {
729 ((first << 16) / first.wrapping_sub(second)).clamp(0, 1 << 16)
730 }
731
732 fn lerp_q16_i64(first: i32, second: i32, fraction: i64) -> i32 {
733 (first as i64 + ((second.wrapping_sub(first) as i64).wrapping_mul(fraction) >> 16)) as i32
734 }
735
736 #[test]
737 #[cfg_attr(
738 miri,
739 ignore = "exhaustive sweep, minutes under Miri; make test runs it natively"
740 )]
741 fn q16_crossing_and_lerp_match_the_wide_oracles() {
742 let mut state = 0x9e37_79b9_7f4a_7c15u64;
743 let mut next = || {
744 state ^= state << 13;
745 state ^= state >> 7;
746 state ^= state << 17;
747 state
748 };
749 for iteration in 0..100_000u32 {
750 let span: i32 = if iteration % 3 == 0 {
751 i32::MAX
752 } else {
753 1 << 24
754 };
755 let first = (next() as i32) % span;
756 let second = (next() as i32) % span;
757 if first == second {
758 continue;
759 }
760 let expected = crossing_fraction_q16_i64(i64::from(first), i64::from(second));
761 let actual = crossing_fraction_q16_i32(first, second);
762 assert_eq!(i64::from(actual), expected, "first {first} second {second}");
763 let a = (next() as i32) % (1 << 22);
764 let b = (next() as i32) % (1 << 22);
765 assert_eq!(
766 lerp_q16_i32_exact(a, b, actual),
767 lerp_q16_i64(a, b, expected),
768 "lerp {a} {b} fraction {actual}"
769 );
770 }
771 }
772
773 fn by_value_reference(
776 source: &[Vertex],
777 destination: &mut [Vertex],
778 plane: &Plane<'_>,
779 traversal: ClipTraversal,
780 ) -> usize {
781 let mut written = 0;
782 let mut emit = |v: Vertex| {
783 destination[written] = v;
784 written += 1;
785 };
786 match traversal {
787 ClipTraversal::PreviousToCurrent => {
788 let mut previous_index = source.len() - 1;
789 let mut previous = source[previous_index];
790 let mut previous_distance = plane.distance(previous_index, &previous);
791 for (current_index, ¤t) in source.iter().enumerate() {
792 let current_distance = plane.distance(current_index, ¤t);
793 let inside = plane.inside(current_distance);
794 if inside != plane.inside(previous_distance) {
795 emit(plane.intersection(
796 previous_index,
797 &previous,
798 previous_distance,
799 current_index,
800 ¤t,
801 current_distance,
802 ));
803 }
804 if inside {
805 emit(current);
806 }
807 previous_index = current_index;
808 previous = current;
809 previous_distance = current_distance;
810 }
811 }
812 ClipTraversal::CurrentToNext => {
813 for current_index in 0..source.len() {
814 let next_index = (current_index + 1) % source.len();
815 let (current, next) = (source[current_index], source[next_index]);
816 let current_distance = plane.distance(current_index, ¤t);
817 let next_distance = plane.distance(next_index, &next);
818 let inside = plane.inside(current_distance);
819 if inside {
820 emit(current);
821 }
822 if inside != plane.inside(next_distance) {
823 emit(plane.intersection(
824 current_index,
825 ¤t,
826 current_distance,
827 next_index,
828 &next,
829 next_distance,
830 ));
831 }
832 }
833 }
834 }
835 written
836 }
837
838 #[test]
839 fn reading_vertices_in_place_clips_exactly_as_copying_them_did() {
840 let mut state = 0x9e37_79b9_7f4a_7c15u64;
841 let mut next = || {
842 state ^= state << 13;
843 state ^= state >> 7;
844 state ^= state << 17;
845 state
846 };
847 for _ in 0..20_000 {
848 let len = 1 + (next() % 8) as usize;
849 let mut source = [Vertex::default(); 8];
850 for v in &mut source[..len] {
851 *v = Vertex((next() as i32) % 1000, (next() as i32) % 1000);
852 }
853 let source = &source[..len];
854 for traversal in [
855 ClipTraversal::PreviousToCurrent,
856 ClipTraversal::CurrentToNext,
857 ] {
858 let mut want = [Vertex::default(); 16];
859 let want_len = by_value_reference(source, &mut want, &Plane(None), traversal);
860 let mut got = [Vertex::default(); 16];
861 let got_len =
862 clip_to_plane(source, &mut got, &Plane(None), traversal).expect("2 * len fits");
863 assert_eq!((got_len, &got[..got_len]), (want_len, &want[..want_len]));
864 let mut unchecked = [Vertex::default(); 16];
865 let unchecked_len = unsafe {
867 clip_to_plane_unchecked(source, &mut unchecked, &Plane(None), traversal)
868 };
869 assert_eq!(&unchecked[..unchecked_len], &want[..want_len]);
870 }
871 }
872 }
873}