-
Notifications
You must be signed in to change notification settings - Fork 0
/
path.go
1104 lines (1052 loc) · 27.4 KB
/
path.go
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
// Copyright (c) 2018, The Goki Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package svg
import (
"fmt"
"log"
"math"
"strconv"
"strings"
"unicode"
"goki.dev/girl/paint"
"goki.dev/ki/v2"
"goki.dev/mat32/v2"
)
// Path renders SVG data sequences that can render just about anything
type Path struct {
NodeBase
// the path data to render -- path commands and numbers are serialized, with each command specifying the number of floating-point coord data points that follow
Data []PathData `xml:"-" set:"-"`
// string version of the path data
DataStr string `xml:"d"`
}
func (g *Path) SVGName() string { return "path" }
func (g *Path) CopyFieldsFrom(frm any) {
fr := frm.(*Path)
g.NodeBase.CopyFieldsFrom(&fr.NodeBase)
g.Data = make([]PathData, len(fr.Data))
copy(g.Data, fr.Data)
g.DataStr = fr.DataStr
}
func (g *Path) SetPos(pos mat32.Vec2) {
// todo: set first point
}
func (g *Path) SetSize(sz mat32.Vec2) {
// todo: scale bbox
}
// SetData sets the path data to given string, parsing it into an optimized
// form used for rendering
func (g *Path) SetData(data string) error {
g.DataStr = data
var err error
g.Data, err = PathDataParse(data)
if err != nil {
return err
}
err = PathDataValidate(&g.Data, g.Path())
return err
}
func (g *Path) LocalBBox() mat32.Box2 {
bb := PathDataBBox(g.Data)
hlw := 0.5 * g.LocalLineWidth()
bb.Min.SetSubScalar(hlw)
bb.Max.SetAddScalar(hlw)
return bb
}
func (g *Path) Render(sv *SVG) {
sz := len(g.Data)
if sz < 2 {
return
}
vis, pc := g.PushTransform(sv)
if !vis {
return
}
pc.Lock()
PathDataRender(g.Data, pc)
pc.FillStrokeClear()
pc.Unlock()
g.BBoxes(sv)
if mrk := sv.MarkerByName(g, "marker-start"); mrk != nil {
// todo: could look for close-path at end and find angle from there..
stv, ang := PathDataStart(g.Data)
mrk.RenderMarker(sv, stv, ang, g.Paint.StrokeStyle.Width.Dots)
}
if mrk := sv.MarkerByName(g, "marker-end"); mrk != nil {
env, ang := PathDataEnd(g.Data)
mrk.RenderMarker(sv, env, ang, g.Paint.StrokeStyle.Width.Dots)
}
if mrk := sv.MarkerByName(g, "marker-mid"); mrk != nil {
var ptm2, ptm1, pt mat32.Vec2
gotidx := 0
PathDataIterFunc(g.Data, func(idx int, cmd PathCmds, ptIdx int, cp mat32.Vec2, ctrls []mat32.Vec2) bool {
ptm2 = ptm1
ptm1 = pt
pt = cp
if gotidx < 2 {
gotidx++
return true
}
if idx >= sz-3 { // todo: this is approximate...
return false
}
ang := 0.5 * (mat32.Atan2(pt.Y-ptm1.Y, pt.X-ptm1.X) + mat32.Atan2(ptm1.Y-ptm2.Y, ptm1.X-ptm2.X))
mrk.RenderMarker(sv, ptm1, ang, g.Paint.StrokeStyle.Width.Dots)
gotidx++
return true
})
}
g.RenderChildren(sv)
pc.PopTransformLock()
}
// PathCmds are the commands within the path SVG drawing data type
type PathCmds byte //enum: enum
const (
// move pen, abs coords
PcM PathCmds = iota
// move pen, rel coords
Pcm
// lineto, abs
PcL
// lineto, rel
Pcl
// horizontal lineto, abs
PcH
// relative lineto, rel
Pch
// vertical lineto, abs
PcV
// vertical lineto, rel
Pcv
// Bezier curveto, abs
PcC
// Bezier curveto, rel
Pcc
// smooth Bezier curveto, abs
PcS
// smooth Bezier curveto, rel
Pcs
// quadratic Bezier curveto, abs
PcQ
// quadratic Bezier curveto, rel
Pcq
// smooth quadratic Bezier curveto, abs
PcT
// smooth quadratic Bezier curveto, rel
Pct
// elliptical arc, abs
PcA
// elliptical arc, rel
Pca
// close path
PcZ
// close path
Pcz
// error -- invalid command
PcErr
)
// PathData encodes the svg path data, using 32-bit floats which are converted
// into uint32 for path commands, and contain the command as the first 5
// bits, and the remaining 27 bits are the number of data points following the
// path command to interpret as numbers.
type PathData float32
// Cmd decodes path data as a command and a number of subsequent values for that command
func (pd PathData) Cmd() (PathCmds, int) {
iv := uint32(pd)
cmd := PathCmds(iv & 0x1F) // only the lowest 5 bits (31 values) for command
n := int((iv & 0xFFFFFFE0) >> 5) // extract the n from remainder of bits
return cmd, n
}
// EncCmd encodes command and n into PathData
func (pc PathCmds) EncCmd(n int) PathData {
nb := int32(n << 5) // n up-shifted
pd := PathData(int32(pc) | nb)
return pd
}
// PathDataNext gets the next path data point, incrementing the index
func PathDataNext(data []PathData, i *int) float32 {
pd := data[*i]
(*i)++
return float32(pd)
}
// PathDataNextVec gets the next 2 path data points as a vector
func PathDataNextVec(data []PathData, i *int) mat32.Vec2 {
v := mat32.Vec2{}
v.X = float32(data[*i])
(*i)++
v.Y = float32(data[*i])
(*i)++
return v
}
// PathDataNextRel gets the next 2 path data points as a relative vector
// and returns that relative vector added to current point
func PathDataNextRel(data []PathData, i *int, cp mat32.Vec2) mat32.Vec2 {
v := mat32.Vec2{}
v.X = float32(data[*i])
(*i)++
v.Y = float32(data[*i])
(*i)++
return v.Add(cp)
}
// PathDataNextCmd gets the next path data command, incrementing the index -- ++
// not an expression so its clunky
func PathDataNextCmd(data []PathData, i *int) (PathCmds, int) {
pd := data[*i]
(*i)++
return pd.Cmd()
}
func reflectPt(pt, rp mat32.Vec2) mat32.Vec2 {
return pt.MulScalar(2).Sub(rp)
}
// PathDataRender traverses the path data and renders it using paint.
// We assume all the data has been validated and that n's are sufficient, etc
func PathDataRender(data []PathData, pc *paint.Context) {
sz := len(data)
if sz == 0 {
return
}
lastCmd := PcErr
var st, cp, xp, ctrl mat32.Vec2
for i := 0; i < sz; {
cmd, n := PathDataNextCmd(data, &i)
rel := false
switch cmd {
case PcM:
cp = PathDataNextVec(data, &i)
pc.MoveTo(cp.X, cp.Y)
st = cp
for np := 1; np < n/2; np++ {
cp = PathDataNextVec(data, &i)
pc.LineTo(cp.X, cp.Y)
}
case Pcm:
cp = PathDataNextRel(data, &i, cp)
pc.MoveTo(cp.X, cp.Y)
st = cp
for np := 1; np < n/2; np++ {
cp = PathDataNextRel(data, &i, cp)
pc.LineTo(cp.X, cp.Y)
}
case PcL:
for np := 0; np < n/2; np++ {
cp = PathDataNextVec(data, &i)
pc.LineTo(cp.X, cp.Y)
}
case Pcl:
for np := 0; np < n/2; np++ {
cp = PathDataNextRel(data, &i, cp)
pc.LineTo(cp.X, cp.Y)
}
case PcH:
for np := 0; np < n; np++ {
cp.X = PathDataNext(data, &i)
pc.LineTo(cp.X, cp.Y)
}
case Pch:
for np := 0; np < n; np++ {
cp.X += PathDataNext(data, &i)
pc.LineTo(cp.X, cp.Y)
}
case PcV:
for np := 0; np < n; np++ {
cp.Y = PathDataNext(data, &i)
pc.LineTo(cp.X, cp.Y)
}
case Pcv:
for np := 0; np < n; np++ {
cp.Y += PathDataNext(data, &i)
pc.LineTo(cp.X, cp.Y)
}
case PcC:
for np := 0; np < n/6; np++ {
xp = PathDataNextVec(data, &i)
ctrl = PathDataNextVec(data, &i)
cp = PathDataNextVec(data, &i)
pc.CubicTo(xp.X, xp.Y, ctrl.X, ctrl.Y, cp.X, cp.Y)
}
case Pcc:
for np := 0; np < n/6; np++ {
xp = PathDataNextRel(data, &i, cp)
ctrl = PathDataNextRel(data, &i, cp)
cp = PathDataNextRel(data, &i, cp)
pc.CubicTo(xp.X, xp.Y, ctrl.X, ctrl.Y, cp.X, cp.Y)
}
case Pcs:
rel = true
fallthrough
case PcS:
for np := 0; np < n/4; np++ {
switch lastCmd {
case Pcc, PcC, Pcs, PcS:
ctrl = reflectPt(cp, ctrl)
default:
ctrl = cp
}
if rel {
xp = PathDataNextRel(data, &i, cp)
cp = PathDataNextRel(data, &i, cp)
} else {
xp = PathDataNextVec(data, &i)
cp = PathDataNextVec(data, &i)
}
pc.CubicTo(ctrl.X, ctrl.Y, xp.X, xp.Y, cp.X, cp.Y)
lastCmd = cmd
ctrl = xp
}
case PcQ:
for np := 0; np < n/4; np++ {
ctrl = PathDataNextVec(data, &i)
cp = PathDataNextVec(data, &i)
pc.QuadraticTo(ctrl.X, ctrl.Y, cp.X, cp.Y)
}
case Pcq:
for np := 0; np < n/4; np++ {
ctrl = PathDataNextRel(data, &i, cp)
cp = PathDataNextRel(data, &i, cp)
pc.QuadraticTo(ctrl.X, ctrl.Y, cp.X, cp.Y)
}
case Pct:
rel = true
fallthrough
case PcT:
for np := 0; np < n/2; np++ {
switch lastCmd {
case Pcq, PcQ, PcT, Pct:
ctrl = reflectPt(cp, ctrl)
default:
ctrl = cp
}
if rel {
cp = PathDataNextRel(data, &i, cp)
} else {
cp = PathDataNextVec(data, &i)
}
pc.QuadraticTo(ctrl.X, ctrl.Y, cp.X, cp.Y)
lastCmd = cmd
}
case Pca:
rel = true
fallthrough
case PcA:
for np := 0; np < n/7; np++ {
rad := PathDataNextVec(data, &i)
ang := PathDataNext(data, &i)
largeArc := (PathDataNext(data, &i) != 0)
sweep := (PathDataNext(data, &i) != 0)
prv := cp
if rel {
cp = PathDataNextRel(data, &i, cp)
} else {
cp = PathDataNextVec(data, &i)
}
ncx, ncy := paint.FindEllipseCenter(&rad.X, &rad.Y, ang*math.Pi/180, prv.X, prv.Y, cp.X, cp.Y, sweep, largeArc)
cp.X, cp.Y = pc.DrawEllipticalArcPath(ncx, ncy, cp.X, cp.Y, prv.X, prv.Y, rad.X, rad.Y, ang, largeArc, sweep)
}
case PcZ:
fallthrough
case Pcz:
pc.ClosePath()
cp = st
}
lastCmd = cmd
}
}
// PathDataIterFunc traverses the path data and calls given function on each
// coordinate point, passing overall starting index of coords in data stream,
// command, index of the points within that command, and coord values
// (absolute, not relative, regardless of the command type), including
// special control points for path commands that have them (else nil).
// If function returns false (use ki.Break vs. ki.Continue) then
// traversal is aborted.
// For Control points, order is in same order as in standard path stream
// when multiple, e.g., C,S.
// For A: order is: nc, prv, rad, mat32.Vec2{X: ang}, mat32.V2(laf, sf)}
func PathDataIterFunc(data []PathData, fun func(idx int, cmd PathCmds, ptIdx int, cp mat32.Vec2, ctrls []mat32.Vec2) bool) {
sz := len(data)
if sz == 0 {
return
}
lastCmd := PcErr
var st, cp, xp, ctrl, nc mat32.Vec2
for i := 0; i < sz; {
cmd, n := PathDataNextCmd(data, &i)
rel := false
switch cmd {
case PcM:
cp = PathDataNextVec(data, &i)
if !fun(i-2, cmd, 0, cp, nil) {
return
}
st = cp
for np := 1; np < n/2; np++ {
cp = PathDataNextVec(data, &i)
if !fun(i-2, cmd, np, cp, nil) {
return
}
}
case Pcm:
cp = PathDataNextRel(data, &i, cp)
if !fun(i-2, cmd, 0, cp, nil) {
return
}
st = cp
for np := 1; np < n/2; np++ {
cp = PathDataNextRel(data, &i, cp)
if !fun(i-2, cmd, np, cp, nil) {
return
}
}
case PcL:
for np := 0; np < n/2; np++ {
cp = PathDataNextVec(data, &i)
if !fun(i-2, cmd, np, cp, nil) {
return
}
}
case Pcl:
for np := 0; np < n/2; np++ {
cp = PathDataNextRel(data, &i, cp)
if !fun(i-2, cmd, np, cp, nil) {
return
}
}
case PcH:
for np := 0; np < n; np++ {
cp.X = PathDataNext(data, &i)
if !fun(i-1, cmd, np, cp, nil) {
return
}
}
case Pch:
for np := 0; np < n; np++ {
cp.X += PathDataNext(data, &i)
if !fun(i-1, cmd, np, cp, nil) {
return
}
}
case PcV:
for np := 0; np < n; np++ {
cp.Y = PathDataNext(data, &i)
if !fun(i-1, cmd, np, cp, nil) {
return
}
}
case Pcv:
for np := 0; np < n; np++ {
cp.Y += PathDataNext(data, &i)
if !fun(i-1, cmd, np, cp, nil) {
return
}
}
case PcC:
for np := 0; np < n/6; np++ {
xp = PathDataNextVec(data, &i)
ctrl = PathDataNextVec(data, &i)
cp = PathDataNextVec(data, &i)
if !fun(i-2, cmd, np, cp, []mat32.Vec2{xp, ctrl}) {
return
}
}
case Pcc:
for np := 0; np < n/6; np++ {
xp = PathDataNextRel(data, &i, cp)
ctrl = PathDataNextRel(data, &i, cp)
cp = PathDataNextRel(data, &i, cp)
if !fun(i-2, cmd, np, cp, []mat32.Vec2{xp, ctrl}) {
return
}
}
case Pcs:
rel = true
fallthrough
case PcS:
for np := 0; np < n/4; np++ {
switch lastCmd {
case Pcc, PcC, Pcs, PcS:
ctrl = reflectPt(cp, ctrl)
default:
ctrl = cp
}
if rel {
xp = PathDataNextRel(data, &i, cp)
cp = PathDataNextRel(data, &i, cp)
} else {
xp = PathDataNextVec(data, &i)
cp = PathDataNextVec(data, &i)
}
if !fun(i-2, cmd, np, cp, []mat32.Vec2{xp, ctrl}) {
return
}
lastCmd = cmd
ctrl = xp
}
case PcQ:
for np := 0; np < n/4; np++ {
ctrl = PathDataNextVec(data, &i)
cp = PathDataNextVec(data, &i)
if !fun(i-2, cmd, np, cp, []mat32.Vec2{ctrl}) {
return
}
}
case Pcq:
for np := 0; np < n/4; np++ {
ctrl = PathDataNextRel(data, &i, cp)
cp = PathDataNextRel(data, &i, cp)
if !fun(i-2, cmd, np, cp, []mat32.Vec2{ctrl}) {
return
}
}
case Pct:
rel = true
fallthrough
case PcT:
for np := 0; np < n/2; np++ {
switch lastCmd {
case Pcq, PcQ, PcT, Pct:
ctrl = reflectPt(cp, ctrl)
default:
ctrl = cp
}
if rel {
cp = PathDataNextRel(data, &i, cp)
} else {
cp = PathDataNextVec(data, &i)
}
if !fun(i-2, cmd, np, cp, []mat32.Vec2{ctrl}) {
return
}
lastCmd = cmd
}
case Pca:
rel = true
fallthrough
case PcA:
for np := 0; np < n/7; np++ {
rad := PathDataNextVec(data, &i)
ang := PathDataNext(data, &i)
laf := PathDataNext(data, &i)
largeArc := (laf != 0)
sf := PathDataNext(data, &i)
sweep := (sf != 0)
prv := cp
if rel {
cp = PathDataNextRel(data, &i, cp)
} else {
cp = PathDataNextVec(data, &i)
}
nc.X, nc.Y = paint.FindEllipseCenter(&rad.X, &rad.Y, ang*math.Pi/180, prv.X, prv.Y, cp.X, cp.Y, sweep, largeArc)
if !fun(i-2, cmd, np, cp, []mat32.Vec2{nc, prv, rad, {X: ang}, {laf, sf}}) {
return
}
}
case PcZ:
fallthrough
case Pcz:
cp = st
}
lastCmd = cmd
}
}
// PathDataBBox traverses the path data and extracts the local bounding box
func PathDataBBox(data []PathData) mat32.Box2 {
bb := mat32.B2Empty()
PathDataIterFunc(data, func(idx int, cmd PathCmds, ptIdx int, cp mat32.Vec2, ctrls []mat32.Vec2) bool {
bb.ExpandByPoint(cp)
return ki.Continue
})
return bb
}
// PathDataStart gets the starting coords and angle from the path
func PathDataStart(data []PathData) (vec mat32.Vec2, ang float32) {
gotSt := false
PathDataIterFunc(data, func(idx int, cmd PathCmds, ptIdx int, cp mat32.Vec2, ctrls []mat32.Vec2) bool {
if gotSt {
ang = mat32.Atan2(cp.Y-vec.Y, cp.X-vec.X)
return ki.Break
}
vec = cp
gotSt = true
return ki.Continue
})
return
}
// PathDataEnd gets the ending coords and angle from the path
func PathDataEnd(data []PathData) (vec mat32.Vec2, ang float32) {
gotSome := false
PathDataIterFunc(data, func(idx int, cmd PathCmds, ptIdx int, cp mat32.Vec2, ctrls []mat32.Vec2) bool {
if gotSome {
ang = mat32.Atan2(cp.Y-vec.Y, cp.X-vec.X)
}
vec = cp
gotSome = true
return ki.Continue
})
return
}
// PathCmdNMap gives the number of points per each command
var PathCmdNMap = map[PathCmds]int{
PcM: 2,
Pcm: 2,
PcL: 2,
Pcl: 2,
PcH: 1,
Pch: 1,
PcV: 1,
Pcv: 1,
PcC: 6,
Pcc: 6,
PcS: 4,
Pcs: 4,
PcQ: 4,
Pcq: 4,
PcT: 2,
Pct: 2,
PcA: 7,
Pca: 7,
PcZ: 0,
Pcz: 0,
}
// PathCmdIsRel returns true if the path command is relative, false for absolute
func PathCmdIsRel(pc PathCmds) bool {
return pc%2 == 1 // odd ones are relative
}
// PathDataValidate validates the path data and emits error messages on log
func PathDataValidate(data *[]PathData, errstr string) error {
sz := len(*data)
if sz == 0 {
return nil
}
di := 0
fcmd, _ := PathDataNextCmd(*data, &di)
if !(fcmd == Pcm || fcmd == PcM) {
log.Printf("gi.PathDataValidate on %v: doesn't start with M or m -- adding\n", errstr)
ns := make([]PathData, 3, sz+3)
ns[0] = PcM.EncCmd(2)
ns[1], ns[2] = (*data)[1], (*data)[2]
*data = append(ns, *data...)
}
sz = len(*data)
for i := 0; i < sz; {
cmd, n := PathDataNextCmd(*data, &i)
trgn, ok := PathCmdNMap[cmd]
if !ok {
err := fmt.Errorf("gi.PathDataValidate on %v: Path Command not valid: %v", errstr, cmd)
log.Println(err)
return err
}
if (trgn == 0 && n > 0) || (trgn > 0 && n%trgn != 0) {
err := fmt.Errorf("gi.PathDataValidate on %v: Path Command %v has invalid n: %v -- should be: %v", errstr, cmd, n, trgn)
log.Println(err)
return err
}
for np := 0; np < n; np++ {
PathDataNext(*data, &i)
}
}
return nil
}
// PathRuneToCmd maps rune to path command
var PathRuneToCmd = map[rune]PathCmds{
'M': PcM,
'm': Pcm,
'L': PcL,
'l': Pcl,
'H': PcH,
'h': Pch,
'V': PcV,
'v': Pcv,
'C': PcC,
'c': Pcc,
'S': PcS,
's': Pcs,
'Q': PcQ,
'q': Pcq,
'T': PcT,
't': Pct,
'A': PcA,
'a': Pca,
'Z': PcZ,
'z': Pcz,
}
// PathCmdToRune maps command to rune
var PathCmdToRune = map[PathCmds]rune{}
func init() {
for k, v := range PathRuneToCmd {
PathCmdToRune[v] = k
}
}
// PathDecodeCmd decodes rune into corresponding command
func PathDecodeCmd(r rune) PathCmds {
cmd, ok := PathRuneToCmd[r]
if ok {
return cmd
} else {
// log.Printf("gi.PathDecodeCmd unrecognized path command: %v %v\n", string(r), r)
return PcErr
}
}
// PathDataParse parses a string representation of the path data into compiled path data
func PathDataParse(d string) ([]PathData, error) {
var pd []PathData
endi := len(d) - 1
numSt := -1
numGotDec := false // did last number already get a decimal point -- if so, then an additional decimal point now acts as a delimiter -- some crazy paths actually leverage that!
lr := ' '
lstCmd := -1
// first pass: just do the raw parse into commands and numbers
for i, r := range d {
num := unicode.IsNumber(r) || (r == '.' && !numGotDec) || (r == '-' && lr == 'e') || r == 'e'
notn := !num
if i == endi || notn {
if numSt != -1 || (i == endi && !notn) {
if numSt == -1 {
numSt = i
}
nstr := d[numSt:i]
if i == endi && !notn {
nstr = d[numSt : i+1]
}
p, err := strconv.ParseFloat(nstr, 32)
if err != nil {
log.Printf("gi.PathDataParse could not parse string: %v into float\n", nstr)
return nil, err
}
pd = append(pd, PathData(p))
}
if r == '-' || r == '.' {
numSt = i
if r == '.' {
numGotDec = true
} else {
numGotDec = false
}
} else {
numSt = -1
numGotDec = false
if lstCmd != -1 { // update number of args for previous command
lcm, _ := pd[lstCmd].Cmd()
n := (len(pd) - lstCmd) - 1
pd[lstCmd] = lcm.EncCmd(n)
}
if !unicode.IsSpace(r) && r != ',' {
cmd := PathDecodeCmd(r)
if cmd == PcErr {
if i != endi {
err := fmt.Errorf("gi.PathDataParse invalid command rune: %v", r)
log.Println(err)
return nil, err
}
} else {
pc := cmd.EncCmd(0) // encode with 0 length to start
lstCmd = len(pd)
pd = append(pd, pc) // push on
}
}
}
} else if numSt == -1 { // got start of a number
numSt = i
if r == '.' {
numGotDec = true
} else {
numGotDec = false
}
} else { // inside a number
if r == '.' {
numGotDec = true
}
}
lr = r
}
return pd, nil
// todo: add some error checking..
}
// PathDataString returns the string representation of the path data
func PathDataString(data []PathData) string {
sz := len(data)
if sz == 0 {
return ""
}
var sb strings.Builder
var rp, cp, xp, ctrl mat32.Vec2
for i := 0; i < sz; {
cmd, n := PathDataNextCmd(data, &i)
sb.WriteString(fmt.Sprintf("%c ", PathCmdToRune[cmd]))
switch cmd {
case PcM, Pcm:
cp = PathDataNextVec(data, &i)
sb.WriteString(fmt.Sprintf("%g,%g ", cp.X, cp.Y))
for np := 1; np < n/2; np++ {
cp = PathDataNextVec(data, &i)
sb.WriteString(fmt.Sprintf("%g,%g ", cp.X, cp.Y))
}
case PcL, Pcl:
for np := 0; np < n/2; np++ {
rp = PathDataNextVec(data, &i)
sb.WriteString(fmt.Sprintf("%g,%g ", rp.X, rp.Y))
}
case PcH, Pch, PcV, Pcv:
for np := 0; np < n; np++ {
cp.Y = PathDataNext(data, &i)
sb.WriteString(fmt.Sprintf("%g ", cp.Y))
}
case PcC, Pcc:
for np := 0; np < n/6; np++ {
xp = PathDataNextVec(data, &i)
sb.WriteString(fmt.Sprintf("%g,%g ", xp.X, xp.Y))
ctrl = PathDataNextVec(data, &i)
sb.WriteString(fmt.Sprintf("%g,%g ", ctrl.X, ctrl.Y))
cp = PathDataNextVec(data, &i)
sb.WriteString(fmt.Sprintf("%g,%g ", cp.X, cp.Y))
}
case Pcs, PcS:
for np := 0; np < n/4; np++ {
xp = PathDataNextVec(data, &i)
sb.WriteString(fmt.Sprintf("%g,%g ", xp.X, xp.Y))
cp = PathDataNextVec(data, &i)
sb.WriteString(fmt.Sprintf("%g,%g ", cp.X, cp.Y))
}
case PcQ, Pcq:
for np := 0; np < n/4; np++ {
ctrl = PathDataNextVec(data, &i)
sb.WriteString(fmt.Sprintf("%g,%g ", ctrl.X, ctrl.Y))
cp = PathDataNextVec(data, &i)
sb.WriteString(fmt.Sprintf("%g,%g ", cp.X, cp.Y))
}
case PcT, Pct:
for np := 0; np < n/2; np++ {
cp = PathDataNextVec(data, &i)
sb.WriteString(fmt.Sprintf("%g,%g ", cp.X, cp.Y))
}
case PcA, Pca:
for np := 0; np < n/7; np++ {
rad := PathDataNextVec(data, &i)
sb.WriteString(fmt.Sprintf("%g,%g ", rad.X, rad.Y))
ang := PathDataNext(data, &i)
largeArc := PathDataNext(data, &i)
sweep := PathDataNext(data, &i)
sb.WriteString(fmt.Sprintf("%g %g %g ", ang, largeArc, sweep))
cp = PathDataNextVec(data, &i)
sb.WriteString(fmt.Sprintf("%g,%g ", cp.X, cp.Y))
}
case PcZ, Pcz:
}
}
return sb.String()
}
//////////////////////////////////////////////////////////////////////////////////
// Transforms
// ApplyTransform applies the given 2D transform to the geometry of this node
// each node must define this for itself
func (g *Path) ApplyTransform(sv *SVG, xf mat32.Mat2) {
// path may have horiz, vert elements -- only gen soln is to transform
g.Paint.Transform = g.Paint.Transform.Mul(xf)
g.SetProp("transform", g.Paint.Transform.String())
}
// PathDataTransformAbs does the transform of next two data points as absolute coords
func PathDataTransformAbs(data []PathData, i *int, xf mat32.Mat2, lpt mat32.Vec2) mat32.Vec2 {
cp := PathDataNextVec(data, i)
tc := xf.MulVec2AsPtCtr(cp, lpt)
data[*i-2] = PathData(tc.X)
data[*i-1] = PathData(tc.Y)
return tc
}
// PathDataTransformRel does the transform of next two data points as relative coords
// compared to given cp coordinate. returns new *absolute* coordinate
func PathDataTransformRel(data []PathData, i *int, xf mat32.Mat2, cp mat32.Vec2) mat32.Vec2 {
rp := PathDataNextVec(data, i)
tc := xf.MulVec2AsVec(rp)
data[*i-2] = PathData(tc.X)
data[*i-1] = PathData(tc.Y)
return cp.Add(tc) // new abs
}
// ApplyDeltaTransform applies the given 2D delta transforms to the geometry of this node
// relative to given point. Trans translation and point are in top-level coordinates,
// so must be transformed into local coords first.
// Point is upper left corner of selection box that anchors the translation and scaling,
// and for rotation it is the center point around which to rotate
func (g *Path) ApplyDeltaTransform(sv *SVG, trans mat32.Vec2, scale mat32.Vec2, rot float32, pt mat32.Vec2) {
crot := g.Paint.Transform.ExtractRot()
if rot != 0 || crot != 0 {
xf, lpt := g.DeltaTransform(trans, scale, rot, pt, false) // exclude self
g.Paint.Transform = g.Paint.Transform.MulCtr(xf, lpt)
g.SetProp("transform", g.Paint.Transform.String())
} else {
xf, lpt := g.DeltaTransform(trans, scale, rot, pt, true) // include self
g.ApplyTransformImpl(xf, lpt)
g.GradientApplyTransformPt(sv, xf, lpt)
}
}
// ApplyTransformImpl does the implementation of applying a transform to all points
func (g *Path) ApplyTransformImpl(xf mat32.Mat2, lpt mat32.Vec2) {
sz := len(g.Data)
data := g.Data
lastCmd := PcErr
var cp, st mat32.Vec2
var xp, ctrl, rp mat32.Vec2
for i := 0; i < sz; {
cmd, n := PathDataNextCmd(data, &i)
rel := false
switch cmd {
case PcM:
cp = PathDataTransformAbs(data, &i, xf, lpt)
st = cp
for np := 1; np < n/2; np++ {
cp = PathDataTransformAbs(data, &i, xf, lpt)
}
case Pcm:
if i == 1 { // starting
cp = PathDataTransformAbs(data, &i, xf, lpt)
} else {
cp = PathDataTransformRel(data, &i, xf, cp)
}
st = cp
for np := 1; np < n/2; np++ {
cp = PathDataTransformRel(data, &i, xf, cp)
}
case PcL:
for np := 0; np < n/2; np++ {
cp = PathDataTransformAbs(data, &i, xf, lpt)
}
case Pcl:
for np := 0; np < n/2; np++ {
cp = PathDataTransformRel(data, &i, xf, cp)
}
case PcH:
for np := 0; np < n; np++ {
cp.X = PathDataNext(data, &i)
tc := xf.MulVec2AsPtCtr(cp, lpt)
data[i-1] = PathData(tc.X)
}
case Pch:
for np := 0; np < n; np++ {
rp.X = PathDataNext(data, &i)
rp.Y = 0
rp = xf.MulVec2AsVec(rp)
data[i-1] = PathData(rp.X)
cp.SetAdd(rp) // new abs
}
case PcV:
for np := 0; np < n; np++ {
cp.Y = PathDataNext(data, &i)
tc := xf.MulVec2AsPtCtr(cp, lpt)
data[i-1] = PathData(tc.Y)
}
case Pcv:
for np := 0; np < n; np++ {
rp.Y = PathDataNext(data, &i)
rp.X = 0
rp = xf.MulVec2AsVec(rp)
data[i-1] = PathData(rp.Y)
cp.SetAdd(rp) // new abs
}
case PcC:
for np := 0; np < n/6; np++ {
xp = PathDataTransformAbs(data, &i, xf, lpt)
ctrl = PathDataTransformAbs(data, &i, xf, lpt)
cp = PathDataTransformAbs(data, &i, xf, lpt)
}
case Pcc:
for np := 0; np < n/6; np++ {
xp = PathDataTransformRel(data, &i, xf, cp)