-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathclean-shape.lisp
More file actions
2846 lines (2771 loc) · 133 KB
/
clean-shape.lisp
File metadata and controls
2846 lines (2771 loc) · 133 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#++
(ql:quickload '(sdf))
(defpackage #:sdf/cleaner
(:use :cl)
(:local-nicknames (#:a #:alexandria-2)
(#:b #:sdf/base)
(#:rb #:sdf/rb)
(#:q #:sdf/f+f-pqueue)
(#:dq #:sdf/df-pqueue))
(:import-from #:sdf/base
#:*check*
#:ebreak))
(in-package #:sdf/cleaner)
;; debugging vars, used by vis and test code in clean-scratch
(defvar *shapes* ())
(defvar *error-shapes* ())
;; rb-tree sorting uses a unique ID field to ensure a stable
;; ordering. Id generation isn't thread safe for now, so bind locally
;; if that matters
(defvar *id* 0)
(defclass intersect-edge ()
;; wrapper for a curve or segment in sweepline rb tree.
((edge :initarg :edge :reader edge)
;; valid T range for active edge, top first (so might be 1-0), and
;; might be partial range if a curve was split at an extreme
(t1 :initarg :t1 :accessor t1)
(t2 :initarg :t2 :accessor t2)
;; +1 if upwards or edge, -1 if downwards edge
(winding-sign :reader winding-sign)
;; winding number to right of edge while in sweepline rb tree
(winding-number :initform nil :accessor winding-number)
(previous-winding-number :initform nil :accessor previous-winding-number)
;; true if edge is (currently) a transition to or from 0 winding
;; (can't be updated or detected automatically because it needs to
;; account for join point of 2 adjacent segments, where both need
;; to be on boundary but we can't add both when calculating winding
;; number (actually might not care about that case anymore, but
;; still gets modified to account for stacked edges canceling out))
(on-boundary :initform nil :accessor on-boundary)
;; to decide how to connect edges at an intersection, we need to
;; know which side (if any) of edge was inside or outside the final
;; shape before the edge reached the intersection. We can't just
;; look at values before updating them while looking at
;; intersection, since a previous intersection on same line might
;; have caused it to be updated already. Instead, we store a value
;; from some previous Y value, and use that.
;;
;; for now, storing a list of (y win boundary wout). probably
;; should replace with separate slots at some point?
(previous-windings :initform nil :accessor previous-windings)
;; store point of any y extrema so we can use that directly when
;; calculating X for that Y value
(split-point :initarg :split-point :reader split-point :initform nil)
;; store coordinates of point with maximum Y value, so we can use
;; it to decide if this edge contributes to winding #.
(y-max :reader y-max :initform nil)
;; cached X value for sorting, calculated at specified Y
(x)
;; cached T value for sorting, calculated at specified Y
(at)
;; X component of tangent for sorting, calculated at specific y
(tangent-x :initform nil)
;; cached curvature for sorting, calculated at specific y
(curvature :initform nil)
(y :initform nil :reader y)
;; fixnum used to order rb-tree nodes that would otherwise sort as
;; same value
(id :reader id)
;; ref back to rb tree node, so we don't have to FIND to delete it
(%node :initform nil :accessor %node)))
(defmethod initialize-instance :after ((o intersect-edge) &key)
(incf *id*)
(when (> *id* most-positive-fixnum)
(setf *id* most-negative-fixnum))
;; since we split at y extrema, and t1/t2 are ordered by increasing
;; Y, winding sign can be calculated directly from those
(assert (/= (t1 o) (t2 o)))
(when (slot-boundp o 'winding-sign)
(assert (= (winding-sign o) (signum (- (t1 o) (t2 o))))))
(setf (slot-value o 'winding-sign) (signum (- (t1 o) (t2 o))))
(let ((e (edge o)))
;; find y value of last endpoint
;; todo: add a flag to edge to indicate an endpoint is split, and
;; use the split-point directly in that case instead of evaluating
;; and then comparing to split point
(let* ((p1 (b::eval-at (edge o) (t1 o)))
(p2 (b::eval-at (edge o) (t2 o)))
(max (max (b::vy p1) (b::vy p2))))
(setf (slot-value o 'y-max) max)
;; use Y from split point if available
(when (and (split-point o)
(< (abs (- (b::vy (split-point o))
max))
(* 128 (b::%bcs-eps (edge o)))))
(setf (slot-value o 'y-max) (b::vy (split-point o)))))
;; tangent/curvature of segment doesn't change, so set it once on init
(when (typep e 'b::segment)
(let* ((x1 (b::s-dx1 e))
(x2 (b::s-dx2 e))
(y1 (b::s-dy1 e))
(y2 (b::s-dy2 e))
(dx (- x2 x1))
(dy (- y2 y1))
(l (sqrt (+ (expt dx 2) (expt dy 2))))
(s (signum (- (t2 o) (t1 o)))))
(setf (slot-value o 'tangent-x) (* s (/ dx l)))
(setf (slot-value o 'curvature) 0d0))))
(setf (slot-value o 'id) *id*))
(defun maybe-winding-sign (n)
;; don't count this edge if it is at the endpoint with highest Y
;; value.
(if (= (y n) (y-max n))
0
(winding-sign n)))
(defmethod (setf winding-number) :before (n (o intersect-edge))
(setf (previous-winding-number o) (winding-number o)))
(defclass horizontal-intersect-edge (intersect-edge)
;; store right endpoint of horizontal edges so we don't have to
;; calculate it from EDGE every time
((x2 :initarg :x2 :reader x2)))
(defmethod initialize-instance :after ((o horizontal-intersect-edge) &key x)
;; not usually called since we make horizontal edges with
;; change-class
(setf (slot-value o 'y) (y-max o))
(setf (slot-value o 'x) x)
(setf (slot-value o 'winding-sign) 0))
(defmethod update-instance-for-different-class
:after (p (o horizontal-intersect-edge) &key x)
(setf (slot-value o 'y) (y-max o))
(setf (slot-value o 'x) x)
(setf (slot-value o 'winding-sign) 0))
(defun %x-at (node y tmin tmax split-point &key (errorp t))
(declare (type double-float tmin tmax))
(when (> tmin tmax)
(rotatef tmin tmax))
(flet ((x (n at)
(let ((1-at (- 1 at)))
(+ (* (b::b2-dx1 n)
(expt 1-at 2))
(* (b::b2-dxc n)
(* 2 at 1-at))
(* (b::b2-dx2 n)
(expt at 2))))))
(let ((n node))
(cond
(n
(etypecase n
(b::point
(cond
((= (b::p-dy n) y)
(values (b::p-dx n) 0d0))
(t (when errorp
(error "calculating X value for point on strip at wrong value?~%expected y=~s, got ~s (~s)"
y (b::p-dy n) (b::p-ry n))))))
(b::segment
(let ((y1 (b::s-dy1 n))
(y2 (b::s-dy2 n)))
(cond
((= y1 y2)
(let ((x1 (b::s-dx1 n))
(x2 (b::s-dx2 n)))
(if (< x1 x2)
(values x1 0)
(values x2 1))))
((or (<= y1 y y2) (<= y2 y y1))
(let* ((at (/ (- y y1) (- y2 y1)))
(x1 (b::s-dx1 n))
(x2 (b::s-dx2 n)))
(when (or (< at 0) (> at 1))
(ebreak "bat at ~s?" at))
(values (+ x1 (* (- x2 x1) at))
at)))
(t
(when errorp
(error "calculating X value for Y outside valid range of segment?~% y = ~s,~% expected ~s - ~s (~s - ~s)"
y y1 y2 (b::s-ry1 n) (b::s-ry2 n)))))))
(b::bezier2
(multiple-value-bind (t1 t2) (b::%b2-find-t (b::b2-dy1 n)
(b::b2-dyc n)
(b::b2-dy2 n)
y)
(cond
((and split-point (< (abs (- (b::vy split-point) y))
(b::%bcs-eps n)))
(values (b::vx split-point)
(if (< 0 tmin 1) tmin tmax)))
((not t1)
(when errorp
(error "calculating X value for Y that doesn't intersect curve?")))
((not t2)
(if (<= tmin t1 tmax)
(values (x n t1) t1)
(let ((p1 (b::eval-at/b2/fast n t1))
(e1 (b::eval-at/b2/fast n tmin))
(e2 (b::eval-at/b2/fast n tmax))
(eps (* 4 (b::%bcs-eps n))))
(cond
((b::~ (b::vy p1) (b::vy e1) eps)
(values (b::vx e1) tmin))
((b::~ (b::vy p1) (b::vy e2) eps)
(values (b::vx e2) tmax))
(t (when errorp
(error "calculating X value for Y outside valid range of curve?~% y=~s (~s, ~s, ~s)~% t = ~s (~s - ~s)~%"
y
(b::b2-dy1 n)
(b::b2-dyc n)
(b::b2-dy2 n)
t1 tmin tmax)))))))
((<= tmin t1 tmax)
(if (<= tmin t2 tmax)
(if errorp
(error "found 2 X values for Y in curve?~% y=~s~% t = ~s, ~s (~s - ~s)~% x= ~s, ~s~%"
y
t1 t2 tmin tmax
(x n t1) (x n t2))
(ebreak "found 2 X values for Y in curve?~% y=~s~% t = ~s, ~s (~s - ~s)~% x= ~s, ~s~%"
y
t1 t2 tmin tmax
(x n t1) (x n t2)))
(values (x n t1) t1)))
((<= tmin t2 tmax)
(values (x n t2) t2))
(t
(when errorp
(error "calculating X value for Y outside valid range of curve?~% y=~s (~s, ~s, ~s)~% t = ~s, ~s (~s - ~s)~% split ~s (~s)"
y
(b::b2-dy1 n)
(b::b2-dyc n)
(b::b2-dy2 n)
t1 t2 tmin tmax
split-point (when split-point
(abs (- (b::vy split-point) y)))))))))))
(t
(when errorp
(error "tried to calculate X of empty contour-strip?~%")))))))
(defun df (x) (coerce x 'double-float))
(defun update-cached (strip y)
(assert y)
(unless (and (y strip) (= (y strip) y))
(let ((e (edge strip)))
(when (typep e 'b::bezier2)
;; we only need sorting info when we have 2 points at same X,
;; which should be rare, so just clear it here and recalculate
;; if used.
(setf (slot-value strip 'tangent-x) nil)
(setf (slot-value strip 'curvature) nil))
(setf (values (slot-value strip 'x)
(slot-value strip 'at))
(%x-at e y (df (t1 strip)) (df (t2 strip))
(split-point strip) :errorp t)))
(setf (slot-value strip 'y) y)))
(defun %update-cached* (strip y x at &optional force)
(assert y)
(when (and *check* (not force) (y strip) (= (y strip) y))
(assert (< (abs (- (slot-value strip 'at) at))
(b::%bcs-eps (edge strip))))
(assert (= (slot-value strip 'x) x)))
(when (or force (not (and (y strip) (= (y strip) y))))
(let ((e (edge strip)))
(when (typep e 'b::bezier2)
;; we only need sorting info when we have 2 points at same X,
;; which should be rare, so just clear it here and recalculate
;; if used.
(setf (slot-value strip 'tangent-x) nil)
(setf (slot-value strip 'curvature) nil))
(setf (slot-value strip 'x) x
(slot-value strip 'at) at))
(setf (slot-value strip 'y) y)))
(defun x-at (strip y)
(update-cached strip y)
(slot-value strip 'x))
(defun t-at (strip y)
(update-cached strip y)
(slot-value strip 'at))
(defun %tangent-x-at (strip y)
;; derivative at point, projected onto X axis
(update-cached strip y)
(cond
((slot-value strip 'tangent-x) ;; return directly if set
)
(t
;; (we never clear ANGLE slot for SEGMENTs, so this is only
;; called for BEZIER2s)
(let* ((e (edge strip))
(at (slot-value strip 'at))
(x1 (b::b2-dx1 e))
(y1 (b::b2-dy1 e))
(xc (b::b2-dxc e))
(yc (b::b2-dyc e))
(x2 (b::b2-dx2 e))
(y2 (b::b2-dy2 e))
;; dx/dt,dy/dt. Should be *2, but we normalize it so can
;; factor it out
(x3 (- xc x1))
(y3 (- yc y1))
(x4 (- x2 xc))
(y4 (- y2 yc))
(dx (a:lerp at x3 x4))
(dy (a:lerp at y3 y4))
(l (sqrt (+ (expt dx 2) (expt dy 2))))
(s (signum (- (t2 strip) (t1 strip)))))
(assert (not (zerop l)))
(setf (slot-value strip 'tangent-x)
(* s (/ dx l)))))))
(defun %curvature-at (strip y)
;; not sure if this should be calculated as a 2nd value of
;; TANGENT-X-AT or not. For now, assuming this will be much more
;; rarely used, so better to duplicate some calculations here.
(update-cached strip y)
(cond
((slot-value strip 'curvature) ;; return directly if set
)
(t
;; (we never clear DERIVATIVE slot for SEGMENTs, so this is only
;; called for BEZIER2s)
(let* ((e (edge strip))
(x1 (b::b2-dx1 e))
(y1 (b::b2-dy1 e))
(xc (b::b2-dxc e))
(yc (b::b2-dyc e))
(x2 (b::b2-dx2 e))
(y2 (b::b2-dy2 e))
(at (slot-value strip 'at)))
;; flip end points to match direction we care about
(when (< (t2 strip) (t1 strip))
(rotatef x1 x2)
(rotatef y1 y2)
(setf at (- 1 at)))
(let* (;; coefficients of 1st derivative, = linear bezier
(x3 (* 2 (- xc x1)))
(y3 (* 2 (- yc y1)))
(x4 (* 2 (- x2 xc)))
(y4 (* 2 (- y2 yc)))
;; 1st derivative with respect to t
(dx (a:lerp at x3 x4))
(dy (a:lerp at y3 y4))
;; 2nd derivative with respect to t
(d2x (- x4 x3))
(d2y (- y4 y3))
;; curvature
(k (- (/ (- (* dx d2y)
(* dy d2x))
(expt (+ (expt dx 2)
(expt dy 2))
3/2)))))
(setf (slot-value strip 'curvature) k))))))
(defun %curvature-derivative-at (strip y)
;; possibly should be calculated with curvature, but seems to be
;; very rare, so separate for now and not cached
(typecase (edge strip)
(b::segment
0d0)
(b::bezier2
(update-cached strip y)
(let* ((e (edge strip))
(x1 (b::b2-dx1 e))
(y1 (b::b2-dy1 e))
(xc (b::b2-dxc e))
(yc (b::b2-dyc e))
(x2 (b::b2-dx2 e))
(y2 (b::b2-dy2 e))
(at (slot-value strip 'at)))
;; flip end points to match direction we care about
(when (< (t2 strip) (t1 strip))
(rotatef x1 x2)
(rotatef y1 y2)
(setf at (- 1 at)))
(let* (;; coefficients of 1st derivative, = linear bezier
(x3 (* 2 (- xc x1)))
(y3 (* 2 (- yc y1)))
(x4 (* 2 (- x2 xc)))
(y4 (* 2 (- y2 yc)))
;; 1st derivative with respect to t
(dx (a:lerp at x3 x4))
(dy (a:lerp at y3 y4))
;; 2nd derivative with respect to t
(d2x (- x4 x3))
(d2y (- y4 y3))
;;; see https://www.wolframalpha.com/input?i=%28x%27%28t%29y%27%27%28t%29-y%27%28t%29x%27%27%28t%29%29%2F%28%28%28x%27%28t%29%29%5E2%2B%28y%27%28t%29%29%5E2%29%5E%283%2F2%29%29'
;;;; (2(x′² + y′²)(y‴x′ - x‴y′) + 6(x″y′ - x′y″) (x′x″ + y′y″))/(2(x′² + y′²)^(5/2))
;;;;
;;;; if y‴=x‴=0, then k′=(3(x″y′ - x′y″)(x′x″ + y′y″))/((x′² + y′²)^(5/2))
;;;<selwynning> unless you are careful to differentiate with respect to arc
;;; length
;;;<selwynning> the arc length itself is related to the curvature though
;;;<selwynning> so it might be possible to get a useful expression for that
;;;<selwynning> ok, so you've worked out dκ/dt
;;;<selwynning> what you want is dκ/ds
;;;<selwynning> where s is arc length
;;;<selwynning> so multiply that by dt/ds
;;;<selwynning> which is 1/sqrt(x' ^2 + y' ^2)
;; derivative of curvature with respect to arc length
(dkds (/ (* 3
(- (* d2x dy) (* dx d2y))
(+ (* dx d2x) (* dy d2y)))
(expt (+ (expt dx 2) (expt dy 2)) 3))))
dkds)))))
(defmethod is-extreme ((p b::point) shape)
(labels ((prev-y ()
(let ((prev (b::prev shape p)))
(etypecase prev
(b::segment
(b::s-ry1 prev))
(b::bezier2
(if (= (b::b2-ryc prev) (b::p-ry p))
(b::b2-ry1 prev)
(b::b2-ryc prev))))))
(next-y ()
(let ((next (b::next shape p)))
(etypecase next
(b::segment
(b::s-ry2 next))
(b::bezier2
(if (= (b::b2-ryc next) (b::p-ry p))
(b::b2-ry2 next)
(b::b2-ryc next)))))))
(let ((ym (b::p-ry p))
(yp (prev-y))
(yn (next-y)))
(cond
((and (< ym yp) (< ym yn)) 1)
((and (> ym yp) (> ym yn)) -1)
((and (= ym yp) (= ym yn))
(error "shouldn't happen1?"))
(t nil)))))
(defmethod is-extreme ((s b::segment) shape)
;; a horizontal segment might count as an extreme, will pick an
;; endpoint when splitting
(when (= (b::s-ry1 s) (b::s-ry2 s))
(labels ((prev-y ()
(let ((prev (b::prev2 shape s)))
(etypecase prev
(b::segment
(b::s-ry1 prev))
(b::bezier2
(if (= (b::b2-ryc prev) (b::s-ry1 s))
(b::b2-ry1 prev)
(b::b2-ryc prev))))))
(next-y ()
(let ((next (b::next2 shape s)))
(etypecase next
(b::segment
(b::s-ry2 next))
(b::bezier2
(if (= (b::b2-ryc next) (b::s-ry1 s))
(b::b2-ry2 next)
(b::b2-ryc next)))))))
(let ((ym (b::s-ry1 s))
(yp (prev-y))
(yn (next-y)))
(cond
((and (< ym yp) (< ym yn)) 1)
((and (> ym yp) (> ym yn)) -1)
((or (= ym yp) (= ym yn))
(error "shouldn't happen?(horizontal segment with same y adjacent)"))
(t nil))))))
(defmethod is-extreme ((b b::bezier2) shape)
;; only an extreme if control point is above or below both end
;; points
(let ((ym (b::b2-ryc b))
(yp (b::b2-ry1 b))
(yn (b::b2-ry2 b)))
(cond
((and (< ym yp) (< ym yn)) 1)
((and (> ym yp) (> ym yn)) -1)
((and (= ym yp) (= ym yn))
(error "shouldn't happen?(flat bezier)"))
(t nil))))
(defclass sweep-event ()
((y :initarg :y :reader y)
(x :initarg :x :reader x)))
(defclass start-event (sweep-event)
((start :initarg :start :Reader start)
(at :initarg :at :reader at)))
(defclass horizontal-event (sweep-event)
;; start of a horizontal edge
((edge :initarg :edge :reader edge)
;; right endpoint of edge
(x2 :initarg :x2 :reader x2)))
(defclass end-event (sweep-event)
((end :initarg :end :Reader end)
(at :initarg :at :reader at)))
;; since contours are continuous, we usually add and remove an edge at
;; the same time
;;; todo: use this and optimize for that case
#++
(defclass add-remove-event (start-event end-event)
())
;; future intersection
(defclass intersect-event (sweep-event)
((left :initarg :left :accessor left)
(at1 :initarg :at1 :reader at1)
(right :initarg :right :accessor right)
(at2 :initarg :at2 :reader at2)))
(defclass horizontal-intersect-event (sweep-event)
;; EDGE intersects currently active horizontal span(s)
((edge :initarg :edge :accessor edge)
(at :initarg :at :reader at)))
(defun make-events-1 (q shape contour)
(labels ((f (x) (coerce x 'double-float))
(split-b (b)
(let* ((v1 (b::p-rv (b::b2-p1 b)))
(vc (b::p-rv (b::b2-c1 b)))
(v2 (b::p-rv (b::b2-p2 b)))
(y1 (b::vy v1))
(yc (b::vy vc))
(y2 (b::vy v2)))
;; sort endpoints so we get same results for regardless
;; of curve direction
(labels ((d (a b) (when (/= a b) (signum (- a b))))
(p (a b) (or (d (b::vx a) (b::vx b))
(d (b::vy a) (b::vy b)))))
;; return T of extreme point on curve
(let ((s (p v1 v2)))
(cond
((or (not s) (plusp s))
(let* ((yc-y1 (- yc y1))
(at (/ yc-y1 (- yc-y1 (- y2 yc)))))
(values at (b::eval-at/b2/fast b at))))
(t
(rotatef y1 y2)
(let* ((yc-y1 (- yc y1))
(at1 (/ yc-y1 (- yc-y1 (- y2 yc))))
(p (b::%eval-at/b2/fast (b::b2-dp2 b)
(b::b2-dc1 b)
(b::b2-dp1 b)
at1)))
(values (- 1 at1) p))))))))
(add-pair (up e x1 y1 at1 x2 y2 at2)
(if up
(progn
(assert (< y1 y2))
(q:enqueue q (make-instance 'start-event
:x x1 :y y1
:at at1
:start e)
(f y1) (f x1))
(q:enqueue q (make-instance 'end-event
:x x2 :y y2
:at at2
:end e)
(f y2) (f x2)))
(progn
(assert (< y2 y1))
(q:enqueue q (make-instance 'end-event
:x x1 :y y1
:at at1
:end e)
(f y1) (f x1))
(q:enqueue q (make-instance 'start-event
:x x2 :y y2
:at at2
:start e)
(f y2) (f x2)))))
(make-edge (&rest args)
(apply #'make-instance 'intersect-edge args)))
(loop for c = contour then n
for n = (b::next shape c)
do (etypecase c
(b::point nil)
(b::segment
(let* ((x1 (b::s-rx1 c))
(y1 (b::s-ry1 c))
(x2 (b::s-rx2 c))
(y2 (b::s-ry2 c))
(up (< y1 y2))
(e (make-edge :edge c
:t1 (if up 0d0 1d0)
:t2 (if up 1d0 0d0))))
(if (= y1 y2)
(let ((lx (min x1 x2))
(rx (max x1 x2)))
(change-class e 'horizontal-intersect-edge
:x lx :x2 rx)
(q:enqueue q (make-instance 'horizontal-event
:x lx
:X2 rx
:y y1
:edge e)
(f y1) (f lx)))
(add-pair up e x1 y1 0d0 x2 y2 1d0))))
(b::bezier2
(let* ((x1 (b::b2-rx1 c))
(y1 (b::b2-ry1 c))
(x2 (b::b2-rx2 c))
(y2 (b::b2-ry2 c)))
(if (is-extreme c shape)
;; contains an extreme Y value, split and add
;; as 2 pieces
(multiple-value-bind (at p)
(split-b c)
(let* ((at (float at 1d0))
(xe (b::vx p))
(ye (b::vy p))
(up (> ye y1)))
(assert (eql up (> ye y2)))
(add-pair up (make-edge :edge c
:split-point p
:t1 (if up 0d0 at)
:t2 (if up at 0d0))
x1 y1 0d0 xe ye at)
(add-pair up (make-edge :edge c
:split-point p
:t1 (if up 1d0 at)
:t2 (if up at 1d0))
x2 y2 1d0 xe ye at)))
;; normal, just add directly
(let* ((up (< y1 y2))
(e (make-edge :edge c
:t1 (if up 0d0 1d0)
:t2 (if up 1d0 0d0))))
(assert (/= y1 y2))
(add-pair up e x1 y1 0d0 x2 y2 1d0))))))
until (eql n contour))))
(defun make-events (shape)
(let ((q (q:make-queue))
(*id* 0))
(loop for c across (b::contours shape)
do (make-events-1 q shape c))
q))
(defun %sort-rb/a (a b y)
(assert (not (eql a b)))
(assert (< (abs (- (x-at a y) (x-at b y)))
(* 16384 double-float-epsilon)))
;; at intersections, sort by angle
(let ((a1 (%tangent-x-at a y))
(a2 (%tangent-x-at b y))
;; this should possibly be much larger epsilon (more than
;; would usually be needed for just FP noise). At small
;; angles, the curves are nearly tangent and intersection code
;; probably didn't converge to a very precise intersection. In
;; that case, there might actually be 0,1 or 2 intersections
;; included in this event, and "correct" comparison of angles
;; might not give the answer we want.
;; In particular, an angle/derivative test might correctly report
;; either result if there are 2 intersections too close to
;; resolve, depending on where we test the angle relative to those
;; intersections. Even 1 intersection (or near miss) might get
;; either result correctly, if there is an inflection in one or
;; both curves near the tested point.
;; todo: test more nearly-tangent curves and see if this needs
;; to be increased, and if so by how much.
(tangent-epsilon (* 32 double-float-epsilon)))
;; actually, possibly to be fully correct it should always check
;; both derivatives, or look for inflections near test point, or
;; check for a future intersection near the one being tested. not
;; sure if an intersection near an inflection of a very pointy
;; curve might be off enough to get the wrong answer?
(if (< (abs (- a1 a2)) tangent-epsilon)
;; if (nearly) tangent, sort by curvature
(let ((d1 (%curvature-at a y))
(d2 (%curvature-at b y)))
(or (< d1 d2)
(and (= d1 d2)
;; if curvature is the same, check derivative of
;; curvature with respect to s
(let ((dk1 (%curvature-derivative-at a y))
(dk2 (%curvature-derivative-at b y)))
(or (> dk1 dk2)
(and (= dk1 dk2)
;; or if it seems to be on same
;; curve, sort by ID
(or (< (id a) (id b)))))))))
;; otherwise just by tangent
(< a1 a2))))
(defun %eql/a (a b y)
;; return true if %sort-rb/a would have returned comparison based on
;; ID (used to filter potential overlapped edges)
(let ((a1 (%tangent-x-at a y))
(a2 (%tangent-x-at b y))
(ea (edge a))
(eb (edge b))
(tangent-epsilon (* 32 double-float-epsilon)))
(and (< (abs (- a1 a2)) tangent-epsilon)
(or (and (typep ea 'b::segment) (typep eb 'b::segment))
(and (= (%curvature-at a y) (%curvature-at b y))
(progn
;; if we have same curvature between a segment and
;; bezier something is broken
(assert (and (typep ea 'b::bezier2) (typep eb 'b::bezier2)))
(let ((a1 (b::b2-p1 ea))
(ac (b::b2-c1 ea))
(a2 (b::b2-p2 ea))
(b1 (b::b2-p1 eb))
(bc (b::b2-c1 eb))
(b2 (b::b2-p2 eb)))
(if (and (b::point= ac bc)
;; same curve regardless of which direction
;; it is going
(or (and (b::point= a1 b1) (b::point= a2 b2))
(and (b::point= a2 b1) (b::point= a1 b2))))
t
(if (/= (%curvature-derivative-at a y)
(%curvature-derivative-at b y))
nil
(sdf/quadratic-intersect/int::same-parabola-p
(edge a) (edge b)
(b::%bcs-eps (edge a))))))))))))
(defun %sort-rb (a b y)
(if (and (eql (edge a) (edge b)))
;; if we are comparing 2 parts of a b2, just sort by X at
;; endpoint closest to current Y (we only split at y extrema, so
;; should always have an X for both at that value)
(progn
(let* ((y2 (if (< (abs (- (b::b2-dy1 (edge a)) y))
(abs (- (b::b2-dy2 (edge b)) y)))
(b::b2-dy1 (edge a))
(b::b2-dy2 (edge a))))
(x1 (%x-at (edge a) y2 (t1 a) (t2 a)
(split-point a) :errorp t))
(x2 (%x-at (edge b) y2 (t1 b) (t2 b)
(split-point b) :errorp t)))
(assert (/= x1 x2)) ;; shouldn't be able to split at an endpoint
(< x1 x2)))
;; otherwise sort by current X (we set both X values to value
;; from calculated intersection and mostly call the angle sort
;; directly in that case, so we should usually have exactly =
;; values here. If not, we probably either missed an
;; intersection or should be merging nearby events better (or
;; quantizing them to a coarser grid, etc)
(let ((x1 (x-at a y))
(x2 (x-at b y)))
(or (< x1 x2)
(and (= x1 x2)
;; or if at intersection, sort by tangent/curvature/id
(%sort-rb/a a b y))))))
(defclass sweep ()
((rb :reader rb :initarg :rb)
(%set-y :reader %set-y :initarg :set-y)
;; priority queue of currently active horizontal edges, ordered by
;; X value of right end point
(horizontal-edges :accessor horizontal-edges :initform (dq:make-queue))
;; highest X value of edges in horizontal edges, for which we have
;; already calculated future intersection events (so any new
;; horizontal edge with lower X doesn't need to check for them, and
;; those with higher X can start there) Should be NIL when
;; HORIZONTAL-EDGES is empty.
(horizontal-edge-max :accessor horizontal-edge-max :initform nil)
;; state used for reconstructing contours
(contour-index :initform (make-hash-table) :reader contour-index)
;; contour-vertex -> boolean indicating contour in contour index is a 'hole'
(contour-direction-flags :initform (make-hash-table)
:reader contour-direction-flags)
(finished-contours :initform nil :accessor finished-contours)
;; store original shape so we can check connectivity of original
;; edges while sweeping
(shape :initarg :shape :reader shape)
;; if winding #s changed after a previous event, store first node
;; that needs updated here, so next event (or start of next sweep)
;; can propagate it
(winding-changed :initform nil :accessor winding-changed)
;; debug stuff
(dbg-added :accessor dbg-added :initform nil)
(dbg-ordering :reader dbg-ordering
:initform (list (make-hash-table) (make-hash-table)))
(dbg-events :accessor dbg-events :initform nil)))
(defmethod set-y ((sweep sweep) y)
(funcall (%set-y sweep) y))
(defun make-sweep (&optional sweep)
(declare (ignore sweep))
(let ((y nil))
(flet ((sort-func (a b)
(%sort-rb a b y))
(set-y (new-y)
(setf y new-y)))
(make-instance 'sweep
:shape nil
:rb (rb:make-tree :key-func #'identity
:sort-func #'sort-func)
:set-y #'set-y))))
(defun nl (n)
(labels ((i (x)
(if (and x (= x (floor x))) (floor x) x))
(li (&rest r)
(mapcar #'i r)))
(etypecase n
(symbol n)
(cons (mapcar 'nl n))
(horizontal-event (list :horiz (x n) '- (x2 n) (y n) (nl (edge n))))
(horizontal-intersect-event (list :horiz-int (x n) (y n) (nl (edge n))))
(start-event (list :add (x n) (y n) (nl (start n))))
(end-event (list :del (x n) (y n)(nl (end n))))
(intersect-event (list :intersect (x n) (y n)
:left (nl (left n))
:right (nl (right n))))
(intersect-edge (list (nl (edge n)) (i (t1 n)) (i (t2 n))
(format nil "+~a~@[(~a)~]=~a"
(i (winding-sign n))
(when (and (y n)
(/= (winding-sign n)
(maybe-winding-sign n)))
(i (maybe-winding-sign n)))
(i (winding-number n)))
(if (on-boundary n) :! :x)))
(b::point (list (b::p-dx n) (b::p-dy n)))
(b::segment (list (li (b::s-dx1 n) (b::s-dy1 n))
(li (b::s-dx2 n) (b::s-dy2 n))))
(b::bezier2 (list (li (b::b2-dx1 n) (b::b2-dy1 n))
(li (b::b2-dxc n) (b::b2-dyc n))
(li (b::b2-dx2 n) (b::b2-dy2 n)))))))
(defun pn (n) (format t "pn~s " (nl n)))
(defun ri (x) (if (and x (= x (floor x))) (floor x) x))
;; don't know control point of a b2 in final contour until we see both
;; endpoints, so store some extra data wile reconstructing contour
(defclass usc-contour-bezier2 (b::es-contour-bezier2)
((t1 :initarg :t1 :reader t1)
(t2 :initarg :t2 :reader t2)
(edge :initarg :edge :Reader edge)))
;; mostly just for debugging, track which edge it goes with
(defclass usc-contour-segment (b::es-contour-segment)
((edge :initarg :edge :Reader edge)))
(defun update-sweep-contours (sweep
intersect-in intersect-out
x y
winding-in-left winding-in-right
winding-out-left winding-out-right
horizontals
&key verbose)
(when verbose
(format t "~&---------------~%update: (~s <> ~s) | (~s <> ~s) @ ~s, ~s~%"
(ri winding-in-left) (ri winding-in-right)
(ri winding-out-left) (ri winding-out-right)
(ri x) (ri y)))
(labels ((widest-horizontal (horizontals)
(when horizontals
(loop with h = (car horizontals)
with x2 = (x2 h)
for i in (cdr horizontals)
when (> (x2 i) x2)
do (setf x2 (x2 i) h i)
finally (return h)))))
(let* ((ci (contour-index sweep))
(h-in (third (gethash :horizontal ci)))
(h-out (widest-horizontal horizontals))
;; we have to be careful about ordering, since we might try
;; to add and remove and edge that continues through the
;; intersection, so those need to be in the right
;; order. Also, we update some values in the contour index
;; when joining contours, so that also needs to be in the
;; right order. To do this, we store a list of updates to
;; do later after deciding what needs done.
;;
(to-add nil)
(to-remove nil)
;; hash table of nodes that were added this update, so
;; splicing knows not to update them even if it saw the
;; other half of the edge
#++(modified (make-hash-table))
;; not used?
(deferred-updates nil))
(declare (ignorable to-add to-remove deferred-updates))
(labels ((key (e)
(if (typep e 'horizontal-intersect-edge)
:horizontal
e))
(%activate (e)
(when verbose
(format t " +~s~% (~s ~s)~%"
(nl (fourth e))
(third e) (b::enl (second e))))
(assert (not (gethash (car e) ci)))
(setf (gethash (car e) ci) (cdr e)))
(%deactivate (e)
(when verbose
(format t " -~s~%" (nl e)))
(assert (gethash e ci))
(remhash e ci))
(finish-updates ()
(when (and verbose (or to-remove to-add deferred-updates))
(format t "running deferred updates: remove ~s, add ~s defer ~s~%"
(length to-remove) (length to-add)
(length deferred-updates)))
(loop for (f . a) in (shiftf deferred-updates nil)
do (apply f a))
(map 'nil #'%deactivate (shiftf to-remove nil))
(map 'nil #'%activate (shiftf to-add nil)))
(activate (e &key defer)
(if defer
(push e to-add)
(%activate e)))
(deactivate (e &key defer)
(if defer
(push e to-remove)
(%deactivate e)))
(point (&optional (x x) (y y))
(make-instance 'b::es-contour-vertex
:point (b::make-point x y)))
(new-node (e)
(etypecase (edge e)
(b::segment
(make-instance 'usc-contour-segment
:edge e))
(b::bezier2
(make-instance 'usc-contour-bezier2
:t1 (t-at e y) :edge e))))
(finish-node (n e)
(when verbose
(format t "finish node ~s~% n= ~s~%"
(nl e) (nl (edge n))))
(etypecase n
(usc-contour-segment
(assert (eql (edge n) e)
nil "~s~% /=~% ~s" (nl (edge n)) (nl e))
(assert (typep (edge e) 'b::segment)))
(usc-contour-bezier2
(assert (eql (edge n) e)
nil "~s~% /=~% ~s" (nl (edge n)) (nl e))
(assert (typep (edge e) 'b::bezier2))
(let* ((t1 (t1 n))
(t2 (t-at e y))
(b (edge e))
(c (b::%%trim-b2-p1 b t1 t2)))
(setf (slot-value n 't2) t2
(slot-value n 'b::control-point)
(b::make-point (b::vx c) (b::vy c)))))))
(splice (l r mask)
;; splice nodes so L is shared by nodes being joined,
;; and R points to other sides of contours
(when verbose
(format t "splice ~2,'0b @~%" mask)
(format t " lp ~s~%" (b::enl (b::eprev l)))
(format t " l ~s~%" (b::enl l))
(format t " ln ~s~%" (b::enl (b::enext l)))
(format t " rp ~s~%" (b::enl (b::eprev r)))
(format t " r ~s~%" (b::enl r))
(format t " rn ~s~%" (b::enl (b::enext r))))
(ecase mask
(#b00 ;; l to l
(b::%reverse-contour r)
(setf (gethash r (contour-direction-flags sweep))
(not (gethash r (contour-direction-flags sweep))))
(rotatef (b::enext (b::eprev r))
(b::enext (b::eprev l)))
(rotatef (b::eprev r)
(b::eprev l)))
(#b01 ;; r to l
(rotatef (b::eprev (b::enext l))
(b::eprev (b::enext r)))
(rotatef (b::enext l)
(b::enext r)))