-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathPShapeSVG.java
More file actions
2004 lines (1660 loc) · 63.8 KB
/
PShapeSVG.java
File metadata and controls
2004 lines (1660 loc) · 63.8 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
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2012-15 The Processing Foundation
Copyright (c) 2006-12 Ben Fry and Casey Reas
Copyright (c) 2004-06 Michael Chang
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 2.1 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package processing.core;
import static java.awt.Font.BOLD;
import static java.awt.Font.ITALIC;
import static java.awt.Font.PLAIN;
import processing.data.*;
// TODO replace these with PMatrix2D
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.util.Map;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This class is not part of the Processing API and should not be used
* directly. Instead, use loadShape() and methods like it, which will make
* use of this class. Using this class directly will cause your code to break
* when combined with future versions of Processing.
* <p>
* SVG stands for Scalable Vector Graphics, a portable graphics format.
* It is a vector format so it allows for "infinite" resolution and relatively
* small file sizes. Most modern media software can view SVG files, including
* Adobe products, Firefox, etc. Illustrator and Inkscape can edit SVG files.
* View the SVG specification <A HREF="http://www.w3.org/TR/SVG">here</A>.
* <p>
* We have no intention of turning this into a full-featured SVG library.
* The goal of this project is a basic shape importer that originally was small
* enough to be included with applets, meaning that its download size should be
* in the neighborhood of 25-30 Kb. Though we're far less limited nowadays on
* size constraints, we remain extremely limited in terms of time, and do not
* have volunteers who are available to maintain a larger SVG library.
* <p>
* For more sophisticated import/export, consider the
* <A HREF="http://xmlgraphics.apache.org/batik/">Batik</A>
* library from the Apache Software Foundation.
* <p>
* Batik is used in the SVG Export library in Processing 3, however using it
* for full SVG import is still a considerable amount of work. Wiring it to
* Java2D wouldn't be too bad, but using it with OpenGL, JavaFX, and features
* like begin/endRecord() and begin/endRaw() would be considerable effort.
* <p>
* Future improvements to this library may focus on this properly supporting
* a specific subset of SVG, for instance the simpler SVG profiles known as
* <A HREF="http://www.w3.org/TR/SVGMobile/">SVG Tiny or Basic</A>,
* although we still would not support the interactivity options.
*
* <p> <hr noshade> <p>
*
* A minimal example program using SVG:
* (assuming a working moo.svg is in your data folder)
*
* <PRE>
* PShape moo;
*
* void setup() {
* size(400, 400);
* moo = loadShape("moo.svg");
* }
* void draw() {
* background(255);
* shape(moo, mouseX, mouseY);
* }
* </PRE>
*/
public class PShapeSVG extends PShape {
XML element;
/// Values between 0 and 1.
protected float opacity;
float strokeOpacity;
float fillOpacity;
/** Width of containing SVG (used for percentages). */
protected float svgWidth;
/** Height of containing SVG (used for percentages). */
protected float svgHeight;
/** √((w² + h²)/2) of containing SVG (used for percentages). */
protected float svgSizeXY;
protected Gradient strokeGradient;
String strokeName; // id of another object, gradients only?
protected Gradient fillGradient;
String fillName; // id of another object
/**
* Initializes a new SVG object from the given XML object.
*/
public PShapeSVG(XML svg) {
this(null, svg, true);
if (!svg.getName().equals("svg")) {
if (svg.getName().toLowerCase().equals("html")) {
// Common case is that files aren't downloaded properly
throw new RuntimeException("This appears to be a web page, not an SVG file.");
} else {
throw new RuntimeException("The root node is not <svg>, it's <" + svg.getName() + ">");
}
}
}
protected PShapeSVG(PShapeSVG parent, XML properties, boolean parseKids) {
setParent(parent);
// Need to get width/height in early.
if (properties.getName().equals("svg")) {
String unitWidth = properties.getString("width");
String unitHeight = properties.getString("height");
// Can't handle width/height as percentages easily. I'm just going
// to put in 100 as a dummy value, beacuse this means that it will
// come out as a reasonable value.
if (unitWidth != null) width = parseUnitSize(unitWidth, 100);
if (unitHeight != null) height = parseUnitSize(unitHeight, 100);
String viewBoxStr = properties.getString("viewBox");
if (viewBoxStr != null) {
float[] viewBox = PApplet.parseFloat(PApplet.splitTokens(viewBoxStr));
if (unitWidth == null || unitHeight == null) {
// Not proper parsing of the viewBox, but will cover us for cases where
// the width and height of the object is not specified.
width = viewBox[2];
height = viewBox[3];
} else {
// http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute
// TODO: preserveAspectRatio.
if (matrix == null) matrix = new PMatrix2D();
matrix.scale(width/viewBox[2], height/viewBox[3]);
matrix.translate(-viewBox[0], -viewBox[1]);
}
}
// Negative size is illegal.
if (width < 0 || height < 0)
throw new RuntimeException("<svg>: width (" + width +
") and height (" + height + ") must not be negative.");
// It's technically valid to have width or height == 0. Not specified at
// all is what to test for.
if ((unitWidth == null || unitHeight == null) && viewBoxStr == null) {
//throw new RuntimeException("width/height not specified");
PGraphics.showWarning("The width and/or height is not " +
"readable in the <svg> tag of this file.");
// For the spec, the default is 100% and 100%. For purposes
// here, insert a dummy value because this is prolly just a
// font or something for which the w/h doesn't matter.
width = 1;
height = 1;
}
svgWidth = width;
svgHeight = height;
svgSizeXY = PApplet.sqrt((svgWidth*svgWidth + svgHeight*svgHeight)/2.0f);
}
element = properties;
name = properties.getString("id");
// @#$(* adobe illustrator mangles names of objects when re-saving
if (name != null) {
while (true) {
String[] m = PApplet.match(name, "_x([A-Za-z0-9]{2})_");
if (m == null) break;
char repair = (char) PApplet.unhex(m[1]);
name = name.replace(m[0], "" + repair);
}
}
String displayStr = properties.getString("display", "inline");
visible = !displayStr.equals("none");
String transformStr = properties.getString("transform");
if (transformStr != null) {
if (matrix == null) {
matrix = parseTransform(transformStr);
} else {
matrix.preApply(parseTransform(transformStr));
}
}
if (parseKids) {
parseColors(properties);
parseChildren(properties);
}
}
// Broken out so that subclasses can copy any additional variables
// (i.e. fillGradientPaint and strokeGradientPaint)
protected void setParent(PShapeSVG parent) {
// Need to set this so that findChild() works.
// Otherwise 'parent' is null until addChild() is called later.
this.parent = parent;
if (parent == null) {
// set values to their defaults according to the SVG spec
stroke = false;
strokeColor = 0xff000000;
strokeWeight = 1;
strokeCap = PConstants.SQUARE; // equivalent to BUTT in svg spec
strokeJoin = PConstants.MITER;
strokeGradient = null;
// strokeGradientPaint = null;
strokeName = null;
fill = true;
fillColor = 0xff000000;
fillGradient = null;
// fillGradientPaint = null;
fillName = null;
//hasTransform = false;
//transformation = null; //new float[] { 1, 0, 0, 1, 0, 0 };
// svgWidth, svgHeight, and svgXYSize done below.
strokeOpacity = 1;
fillOpacity = 1;
opacity = 1;
} else {
stroke = parent.stroke;
strokeColor = parent.strokeColor;
strokeWeight = parent.strokeWeight;
strokeCap = parent.strokeCap;
strokeJoin = parent.strokeJoin;
strokeGradient = parent.strokeGradient;
// strokeGradientPaint = parent.strokeGradientPaint;
strokeName = parent.strokeName;
fill = parent.fill;
fillColor = parent.fillColor;
fillGradient = parent.fillGradient;
// fillGradientPaint = parent.fillGradientPaint;
fillName = parent.fillName;
svgWidth = parent.svgWidth;
svgHeight = parent.svgHeight;
svgSizeXY = parent.svgSizeXY;
opacity = parent.opacity;
}
// The rect and ellipse modes are set to CORNER since it is the expected
// mode for svg shapes.
rectMode = CORNER;
ellipseMode = CORNER;
}
/** Factory method for subclasses. */
protected PShapeSVG createShape(PShapeSVG parent, XML properties, boolean parseKids) {
return new PShapeSVG(parent, properties, parseKids);
}
protected void parseChildren(XML graphics) {
XML[] elements = graphics.getChildren();
children = new PShape[elements.length];
childCount = 0;
for (XML elem : elements) {
PShape kid = parseChild(elem);
if (kid != null) addChild(kid);
}
children = (PShape[]) PApplet.subset(children, 0, childCount);
}
/**
* Parse a child XML element.
* Override this method to add parsing for more SVG elements.
*/
protected PShape parseChild(XML elem) {
// System.err.println("parsing child in pshape " + elem.getName());
String name = elem.getName();
PShapeSVG shape = null;
if (name == null) {
// just some whitespace that can be ignored (hopefully)
} else if (name.equals("g")) {
shape = createShape(this, elem, true);
} else if (name.equals("defs")) {
// generally this will contain gradient info, so may
// as well just throw it into a group element for parsing
shape = createShape(this, elem, true);
} else if (name.equals("line")) {
shape = createShape(this, elem, true);
shape.parseLine();
} else if (name.equals("circle")) {
shape = createShape(this, elem, true);
shape.parseEllipse(true);
} else if (name.equals("ellipse")) {
shape = createShape(this, elem, true);
shape.parseEllipse(false);
} else if (name.equals("rect")) {
shape = createShape(this, elem, true);
shape.parseRect();
} else if (name.equals("image")) {
shape = createShape(this, elem, true);
shape.parseImage();
} else if (name.equals("polygon")) {
shape = createShape(this, elem, true);
shape.parsePoly(true);
} else if (name.equals("polyline")) {
shape = createShape(this, elem, true);
shape.parsePoly(false);
} else if (name.equals("path")) {
shape = createShape(this, elem, true);
shape.parsePath();
} else if (name.equals("radialGradient")) {
return new RadialGradient(this, elem);
} else if (name.equals("linearGradient")) {
return new LinearGradient(this, elem);
} else if (name.equals("font")) {
return new Font(this, elem);
// } else if (name.equals("font-face")) {
// return new FontFace(this, elem);
// } else if (name.equals("glyph") || name.equals("missing-glyph")) {
// return new FontGlyph(this, elem);
} else if (name.equals("text")) { // || name.equals("font")) {
return new Text(this, elem);
} else if (name.equals("tspan")) {
return new LineOfText(this, elem);
} else if (name.equals("filter")) {
PGraphics.showWarning("Filters are not supported.");
} else if (name.equals("mask")) {
PGraphics.showWarning("Masks are not supported.");
} else if (name.equals("pattern")) {
PGraphics.showWarning("Patterns are not supported.");
} else if (name.equals("stop")) {
// stop tag is handled by gradient parser, so don't warn about it
} else if (name.equals("sodipodi:namedview")) {
// these are always in Inkscape files, the warnings get tedious
} else if (name.equals("metadata")
|| name.equals("title") || name.equals("desc")) {
// fontforge just stuffs <metadata> in as a comment.
// All harmless stuff, irrelevant to rendering.
return null;
} else if (!name.startsWith("#")) {
PGraphics.showWarning("Ignoring <" + name + "> tag.");
// new Exception().printStackTrace();
}
return shape;
}
protected void parseLine() {
kind = LINE;
family = PRIMITIVE;
params = new float[] {
getFloatWithUnit(element, "x1", svgWidth),
getFloatWithUnit(element, "y1", svgHeight),
getFloatWithUnit(element, "x2", svgWidth),
getFloatWithUnit(element, "y2", svgHeight)
};
}
/**
* Handles parsing ellipse and circle tags.
* @param circle true if this is a circle and not an ellipse
*/
protected void parseEllipse(boolean circle) {
kind = ELLIPSE;
family = PRIMITIVE;
params = new float[4];
params[0] = getFloatWithUnit(element, "cx", svgWidth);
params[1] = getFloatWithUnit(element, "cy", svgHeight);
float rx, ry;
if (circle) {
rx = ry = getFloatWithUnit(element, "r", svgSizeXY);
} else {
rx = getFloatWithUnit(element, "rx", svgWidth);
ry = getFloatWithUnit(element, "ry", svgHeight);
}
params[0] -= rx;
params[1] -= ry;
params[2] = rx*2;
params[3] = ry*2;
}
protected void parseRect() {
kind = RECT;
family = PRIMITIVE;
params = new float[] {
getFloatWithUnit(element, "x", svgWidth),
getFloatWithUnit(element, "y", svgHeight),
getFloatWithUnit(element, "width", svgWidth),
getFloatWithUnit(element, "height", svgHeight)
};
}
protected void parseImage() {
kind = RECT;
textureMode = NORMAL;
family = PRIMITIVE;
params = new float[] {
getFloatWithUnit(element, "x", svgWidth),
getFloatWithUnit(element, "y", svgHeight),
getFloatWithUnit(element, "width", svgWidth),
getFloatWithUnit(element, "height", svgHeight)
};
this.imagePath = element.getString("xlink:href");
}
/**
* Parse a polyline or polygon from an SVG file.
* Syntax defined at http://www.w3.org/TR/SVG/shapes.html#PointsBNF
* @param close true if shape is closed (polygon), false if not (polyline)
*/
protected void parsePoly(boolean close) {
family = PATH;
this.close = close;
String pointsAttr = element.getString("points");
if (pointsAttr != null) {
Pattern pattern = Pattern.compile("([+-]?[\\d]+(\\.[\\d]+)?([eE][+-][\\d]+)?)(,?\\s*)([+-]?[\\d]+(\\.[\\d]+)?([eE][+-][\\d]+)?)");
Matcher matcher = pattern.matcher(pointsAttr);
vertexCount = 0;
while (matcher.find()) {
vertexCount++;
}
matcher.reset();
vertices = new float[vertexCount][2];
for (int i = 0; i < vertexCount; i++) {
matcher.find();
vertices[i][X] = Float.parseFloat(matcher.group(1));
vertices[i][Y] = Float.parseFloat(matcher.group(5));
}
// String[] pointsBuffer = PApplet.splitTokens(pointsAttr);
// vertexCount = pointsBuffer.length;
// vertices = new float[vertexCount][2];
// for (int i = 0; i < vertexCount; i++) {
// String pb[] = PApplet.splitTokens(pointsBuffer[i], ", \t\r\n");
// vertices[i][X] = Float.parseFloat(pb[0]);
// vertices[i][Y] = Float.parseFloat(pb[1]);
// }
}
}
protected void parsePath() {
family = PATH;
kind = 0;
String pathData = element.getString("d");
if (pathData == null || PApplet.trim(pathData).length() == 0) {
return;
}
char[] pathDataChars = pathData.toCharArray();
StringBuilder pathBuffer = new StringBuilder();
boolean lastSeparate = false;
for (int i = 0; i < pathDataChars.length; i++) {
char c = pathDataChars[i];
boolean separate = false;
if (c == 'M' || c == 'm' ||
c == 'L' || c == 'l' ||
c == 'H' || c == 'h' ||
c == 'V' || c == 'v' ||
c == 'C' || c == 'c' || // beziers
c == 'S' || c == 's' ||
c == 'Q' || c == 'q' || // quadratic beziers
c == 'T' || c == 't' ||
c == 'A' || c == 'a' || // elliptical arc
c == 'Z' || c == 'z' || // closepath
c == ',') {
separate = true;
if (i != 0) {
pathBuffer.append("|");
}
}
if (c == 'Z' || c == 'z') {
separate = false;
}
if (c == '-' && !lastSeparate) {
// allow for 'e' notation in numbers, e.g. 2.10e-9
// http://dev.processing.org/bugs/show_bug.cgi?id=1408
if (i == 0 || pathDataChars[i-1] != 'e') {
pathBuffer.append("|");
}
}
if (c != ',') {
pathBuffer.append(c); //"" + pathDataBuffer.charAt(i));
}
if (separate && c != ',' && c != '-') {
pathBuffer.append("|");
}
lastSeparate = separate;
}
// use whitespace constant to get rid of extra spaces and CR or LF
String[] pathTokens =
PApplet.splitTokens(pathBuffer.toString(), "|" + WHITESPACE);
vertices = new float[pathTokens.length][2];
vertexCodes = new int[pathTokens.length];
float cx = 0;
float cy = 0;
int i = 0;
char implicitCommand = '\0';
// char prevCommand = '\0';
boolean prevCurve = false;
float ctrlX, ctrlY;
// store values for closepath so that relative coords work properly
float movetoX = 0;
float movetoY = 0;
while (i < pathTokens.length) {
char c = pathTokens[i].charAt(0);
if (((c >= '0' && c <= '9') || (c == '-')) && implicitCommand != '\0') {
c = implicitCommand;
i--;
} else {
implicitCommand = c;
}
switch (c) {
case 'M': // M - move to (absolute)
cx = PApplet.parseFloat(pathTokens[i + 1]);
cy = PApplet.parseFloat(pathTokens[i + 2]);
movetoX = cx;
movetoY = cy;
parsePathMoveto(cx, cy);
implicitCommand = 'L';
i += 3;
break;
case 'm': // m - move to (relative)
cx = cx + PApplet.parseFloat(pathTokens[i + 1]);
cy = cy + PApplet.parseFloat(pathTokens[i + 2]);
movetoX = cx;
movetoY = cy;
parsePathMoveto(cx, cy);
implicitCommand = 'l';
i += 3;
break;
case 'L':
cx = PApplet.parseFloat(pathTokens[i + 1]);
cy = PApplet.parseFloat(pathTokens[i + 2]);
parsePathLineto(cx, cy);
i += 3;
break;
case 'l':
cx = cx + PApplet.parseFloat(pathTokens[i + 1]);
cy = cy + PApplet.parseFloat(pathTokens[i + 2]);
parsePathLineto(cx, cy);
i += 3;
break;
// horizontal lineto absolute
case 'H':
cx = PApplet.parseFloat(pathTokens[i + 1]);
parsePathLineto(cx, cy);
i += 2;
break;
// horizontal lineto relative
case 'h':
cx = cx + PApplet.parseFloat(pathTokens[i + 1]);
parsePathLineto(cx, cy);
i += 2;
break;
case 'V':
cy = PApplet.parseFloat(pathTokens[i + 1]);
parsePathLineto(cx, cy);
i += 2;
break;
case 'v':
cy = cy + PApplet.parseFloat(pathTokens[i + 1]);
parsePathLineto(cx, cy);
i += 2;
break;
// C - curve to (absolute)
case 'C': {
float ctrlX1 = PApplet.parseFloat(pathTokens[i + 1]);
float ctrlY1 = PApplet.parseFloat(pathTokens[i + 2]);
float ctrlX2 = PApplet.parseFloat(pathTokens[i + 3]);
float ctrlY2 = PApplet.parseFloat(pathTokens[i + 4]);
float endX = PApplet.parseFloat(pathTokens[i + 5]);
float endY = PApplet.parseFloat(pathTokens[i + 6]);
parsePathCurveto(ctrlX1, ctrlY1, ctrlX2, ctrlY2, endX, endY);
cx = endX;
cy = endY;
i += 7;
prevCurve = true;
}
break;
// c - curve to (relative)
case 'c': {
float ctrlX1 = cx + PApplet.parseFloat(pathTokens[i + 1]);
float ctrlY1 = cy + PApplet.parseFloat(pathTokens[i + 2]);
float ctrlX2 = cx + PApplet.parseFloat(pathTokens[i + 3]);
float ctrlY2 = cy + PApplet.parseFloat(pathTokens[i + 4]);
float endX = cx + PApplet.parseFloat(pathTokens[i + 5]);
float endY = cy + PApplet.parseFloat(pathTokens[i + 6]);
parsePathCurveto(ctrlX1, ctrlY1, ctrlX2, ctrlY2, endX, endY);
cx = endX;
cy = endY;
i += 7;
prevCurve = true;
}
break;
// S - curve to shorthand (absolute)
// Draws a cubic Bézier curve from the current point to (x,y). The first
// control point is assumed to be the reflection of the second control
// point on the previous command relative to the current point.
// (x2,y2) is the second control point (i.e., the control point
// at the end of the curve). S (uppercase) indicates that absolute
// coordinates will follow; s (lowercase) indicates that relative
// coordinates will follow. Multiple sets of coordinates may be specified
// to draw a polybézier. At the end of the command, the new current point
// becomes the final (x,y) coordinate pair used in the polybézier.
case 'S': {
// (If there is no previous command or if the previous command was not
// an C, c, S or s, assume the first control point is coincident with
// the current point.)
if (!prevCurve) {
ctrlX = cx;
ctrlY = cy;
} else {
float ppx = vertices[vertexCount-2][X];
float ppy = vertices[vertexCount-2][Y];
float px = vertices[vertexCount-1][X];
float py = vertices[vertexCount-1][Y];
ctrlX = px + (px - ppx);
ctrlY = py + (py - ppy);
}
float ctrlX2 = PApplet.parseFloat(pathTokens[i + 1]);
float ctrlY2 = PApplet.parseFloat(pathTokens[i + 2]);
float endX = PApplet.parseFloat(pathTokens[i + 3]);
float endY = PApplet.parseFloat(pathTokens[i + 4]);
parsePathCurveto(ctrlX, ctrlY, ctrlX2, ctrlY2, endX, endY);
cx = endX;
cy = endY;
i += 5;
prevCurve = true;
}
break;
// s - curve to shorthand (relative)
case 's': {
if (!prevCurve) {
ctrlX = cx;
ctrlY = cy;
} else {
float ppx = vertices[vertexCount-2][X];
float ppy = vertices[vertexCount-2][Y];
float px = vertices[vertexCount-1][X];
float py = vertices[vertexCount-1][Y];
ctrlX = px + (px - ppx);
ctrlY = py + (py - ppy);
}
float ctrlX2 = cx + PApplet.parseFloat(pathTokens[i + 1]);
float ctrlY2 = cy + PApplet.parseFloat(pathTokens[i + 2]);
float endX = cx + PApplet.parseFloat(pathTokens[i + 3]);
float endY = cy + PApplet.parseFloat(pathTokens[i + 4]);
parsePathCurveto(ctrlX, ctrlY, ctrlX2, ctrlY2, endX, endY);
cx = endX;
cy = endY;
i += 5;
prevCurve = true;
}
break;
// Q - quadratic curve to (absolute)
// Draws a quadratic Bézier curve from the current point to (x,y) using
// (x1,y1) as the control point. Q (uppercase) indicates that absolute
// coordinates will follow; q (lowercase) indicates that relative
// coordinates will follow. Multiple sets of coordinates may be specified
// to draw a polybézier. At the end of the command, the new current point
// becomes the final (x,y) coordinate pair used in the polybézier.
case 'Q': {
ctrlX = PApplet.parseFloat(pathTokens[i + 1]);
ctrlY = PApplet.parseFloat(pathTokens[i + 2]);
float endX = PApplet.parseFloat(pathTokens[i + 3]);
float endY = PApplet.parseFloat(pathTokens[i + 4]);
//parsePathQuadto(cx, cy, ctrlX, ctrlY, endX, endY);
parsePathQuadto(ctrlX, ctrlY, endX, endY);
cx = endX;
cy = endY;
i += 5;
prevCurve = true;
}
break;
// q - quadratic curve to (relative)
case 'q': {
ctrlX = cx + PApplet.parseFloat(pathTokens[i + 1]);
ctrlY = cy + PApplet.parseFloat(pathTokens[i + 2]);
float endX = cx + PApplet.parseFloat(pathTokens[i + 3]);
float endY = cy + PApplet.parseFloat(pathTokens[i + 4]);
//parsePathQuadto(cx, cy, ctrlX, ctrlY, endX, endY);
parsePathQuadto(ctrlX, ctrlY, endX, endY);
cx = endX;
cy = endY;
i += 5;
prevCurve = true;
}
break;
// T - quadratic curveto shorthand (absolute)
// The control point is assumed to be the reflection of the control
// point on the previous command relative to the current point.
case 'T': {
// If there is no previous command or if the previous command was
// not a Q, q, T or t, assume the control point is coincident
// with the current point.
if (!prevCurve) {
ctrlX = cx;
ctrlY = cy;
} else {
float ppx = vertices[vertexCount-2][X];
float ppy = vertices[vertexCount-2][Y];
float px = vertices[vertexCount-1][X];
float py = vertices[vertexCount-1][Y];
ctrlX = px + (px - ppx);
ctrlY = py + (py - ppy);
}
float endX = PApplet.parseFloat(pathTokens[i + 1]);
float endY = PApplet.parseFloat(pathTokens[i + 2]);
//parsePathQuadto(cx, cy, ctrlX, ctrlY, endX, endY);
parsePathQuadto(ctrlX, ctrlY, endX, endY);
cx = endX;
cy = endY;
i += 3;
prevCurve = true;
}
break;
// t - quadratic curveto shorthand (relative)
case 't': {
if (!prevCurve) {
ctrlX = cx;
ctrlY = cy;
} else {
float ppx = vertices[vertexCount-2][X];
float ppy = vertices[vertexCount-2][Y];
float px = vertices[vertexCount-1][X];
float py = vertices[vertexCount-1][Y];
ctrlX = px + (px - ppx);
ctrlY = py + (py - ppy);
}
float endX = cx + PApplet.parseFloat(pathTokens[i + 1]);
float endY = cy + PApplet.parseFloat(pathTokens[i + 2]);
//parsePathQuadto(cx, cy, ctrlX, ctrlY, endX, endY);
parsePathQuadto(ctrlX, ctrlY, endX, endY);
cx = endX;
cy = endY;
i += 3;
prevCurve = true;
}
break;
// A - elliptical arc to (absolute)
case 'A': {
float rx = PApplet.parseFloat(pathTokens[i + 1]);
float ry = PApplet.parseFloat(pathTokens[i + 2]);
float angle = PApplet.parseFloat(pathTokens[i + 3]);
boolean fa = PApplet.parseFloat(pathTokens[i + 4]) != 0;
boolean fs = PApplet.parseFloat(pathTokens[i + 5]) != 0;
float endX = PApplet.parseFloat(pathTokens[i + 6]);
float endY = PApplet.parseFloat(pathTokens[i + 7]);
parsePathArcto(cx, cy, rx, ry, angle, fa, fs, endX, endY);
cx = endX;
cy = endY;
i += 8;
prevCurve = true;
}
break;
// a - elliptical arc to (relative)
case 'a': {
float rx = PApplet.parseFloat(pathTokens[i + 1]);
float ry = PApplet.parseFloat(pathTokens[i + 2]);
float angle = PApplet.parseFloat(pathTokens[i + 3]);
boolean fa = PApplet.parseFloat(pathTokens[i + 4]) != 0;
boolean fs = PApplet.parseFloat(pathTokens[i + 5]) != 0;
float endX = cx + PApplet.parseFloat(pathTokens[i + 6]);
float endY = cy + PApplet.parseFloat(pathTokens[i + 7]);
parsePathArcto(cx, cy, rx, ry, angle, fa, fs, endX, endY);
cx = endX;
cy = endY;
i += 8;
prevCurve = true;
}
break;
case 'Z':
case 'z':
// since closing the path, the 'current' point needs
// to return back to the last moveto location.
// http://code.google.com/p/processing/issues/detail?id=1058
cx = movetoX;
cy = movetoY;
close = true;
i++;
break;
default:
String parsed =
PApplet.join(PApplet.subset(pathTokens, 0, i), ",");
String unparsed =
PApplet.join(PApplet.subset(pathTokens, i), ",");
System.err.println("parsed: " + parsed);
System.err.println("unparsed: " + unparsed);
throw new RuntimeException("shape command not handled: " + pathTokens[i]);
}
// prevCommand = c;
}
}
// private void parsePathCheck(int num) {
// if (vertexCount + num-1 >= vertices.length) {
// //vertices = (float[][]) PApplet.expand(vertices);
// float[][] temp = new float[vertexCount << 1][2];
// System.arraycopy(vertices, 0, temp, 0, vertexCount);
// vertices = temp;
// }
// }
private void parsePathVertex(float x, float y) {
if (vertexCount == vertices.length) {
//vertices = (float[][]) PApplet.expand(vertices);
float[][] temp = new float[vertexCount << 1][2];
System.arraycopy(vertices, 0, temp, 0, vertexCount);
vertices = temp;
}
vertices[vertexCount][X] = x;
vertices[vertexCount][Y] = y;
vertexCount++;
}
private void parsePathCode(int what) {
if (vertexCodeCount == vertexCodes.length) {
vertexCodes = PApplet.expand(vertexCodes);
}
vertexCodes[vertexCodeCount++] = what;
}
private void parsePathMoveto(float px, float py) {
if (vertexCount > 0) {
parsePathCode(BREAK);
}
parsePathCode(VERTEX);
parsePathVertex(px, py);
}
private void parsePathLineto(float px, float py) {
parsePathCode(VERTEX);
parsePathVertex(px, py);
}
private void parsePathCurveto(float x1, float y1,
float x2, float y2,
float x3, float y3) {
parsePathCode(BEZIER_VERTEX);
parsePathVertex(x1, y1);
parsePathVertex(x2, y2);
parsePathVertex(x3, y3);
}
// private void parsePathQuadto(float x1, float y1,
// float cx, float cy,
// float x2, float y2) {
// //System.out.println("quadto: " + x1 + "," + y1 + " " + cx + "," + cy + " " + x2 + "," + y2);
//// parsePathCode(BEZIER_VERTEX);
// parsePathCode(QUAD_BEZIER_VERTEX);
// // x1/y1 already covered by last moveto, lineto, or curveto
//
// parsePathVertex(x1 + ((cx-x1)*2/3.0f), y1 + ((cy-y1)*2/3.0f));
// parsePathVertex(x2 + ((cx-x2)*2/3.0f), y2 + ((cy-y2)*2/3.0f));
// parsePathVertex(x2, y2);
// }
private void parsePathQuadto(float cx, float cy,
float x2, float y2) {
//System.out.println("quadto: " + x1 + "," + y1 + " " + cx + "," + cy + " " + x2 + "," + y2);
// parsePathCode(BEZIER_VERTEX);
parsePathCode(QUADRATIC_VERTEX);
// x1/y1 already covered by last moveto, lineto, or curveto
parsePathVertex(cx, cy);
parsePathVertex(x2, y2);
}
// Approximates elliptical arc by several bezier segments.
// Meets SVG standard requirements from:
// http://www.w3.org/TR/SVG/paths.html#PathDataEllipticalArcCommands
// http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
// Based on arc to bezier curve equations from:
// http://www.spaceroots.org/documents/ellipse/node22.html
private void parsePathArcto(float x1, float y1,
float rx, float ry,
float angle,
boolean fa, boolean fs,
float x2, float y2) {
if (x1 == x2 && y1 == y2) return;
if (rx == 0 || ry == 0) { parsePathLineto(x2, y2); return; }
rx = PApplet.abs(rx); ry = PApplet.abs(ry);
float phi = PApplet.radians(((angle % 360) + 360) % 360);
float cosPhi = PApplet.cos(phi), sinPhi = PApplet.sin(phi);
float x1r = ( cosPhi * (x1 - x2) + sinPhi * (y1 - y2)) / 2;
float y1r = (-sinPhi * (x1 - x2) + cosPhi * (y1 - y2)) / 2;
float cxr, cyr;
{
float A = (x1r*x1r) / (rx*rx) + (y1r*y1r) / (ry*ry);
if (A > 1) {
// No solution, scale ellipse up according to SVG standard
float sqrtA = PApplet.sqrt(A);
rx *= sqrtA; cxr = 0;
ry *= sqrtA; cyr = 0;
} else {
float k = ((fa == fs) ? -1f : 1f) *
PApplet.sqrt((rx*rx * ry*ry) / ((rx*rx * y1r*y1r) + (ry*ry * x1r*x1r)) - 1f);
cxr = k * rx * y1r / ry;
cyr = -k * ry * x1r / rx;