-
Notifications
You must be signed in to change notification settings - Fork 128
/
svg.d
5577 lines (4901 loc) · 176 KB
/
svg.d
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) 2013-14 Mikko Mononen memon@inside.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*
* The SVG parser is based on Anti-Grain Geometry 2.4 SVG example
* Copyright (C) 2002-2004 Maxim Shemanarev (McSeem) (http://www.antigrain.com/)
*
* Arc calculation code based on canvg (https://code.google.com/p/canvg/)
*
* Bounding box calculation based on http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html
*
* Fork developement, feature integration and new bugs:
* Ketmar // Invisible Vector <ketmar@ketmar.no-ip.org>
* Contains code from various contributors.
*/
/**
NanoVega.SVG is a simple stupid SVG parser. The output of the parser is a list of drawing commands.
The library suits well for anything from rendering scalable icons in your editor application to prototyping a game.
NanoVega.SVG supports a wide range of SVG features, but several are be missing. Among the most notable
known missing features: `<use>`, `<text>`, `<def>` for shapes (it does work for gradients), `<script>`, `<style>` (minimal inline style attributes work, but style blocks do not), and animations. Note that `<clipPath>` is new and may be buggy (but anything in here may be buggy!) and the css support is fairly rudimentary.
The shapes in the SVG images are transformed by the viewBox and converted to specified units.
That is, you should get the same looking data as your designed in your favorite app.
NanoVega.SVG can return the paths in few different units. For example if you want to render an image, you may choose
to get the paths in pixels, or if you are feeding the data into a CNC-cutter, you may want to use millimeters.
The units passed to NanoVega.SVG should be one of: 'px', 'pt', 'pc', 'mm', 'cm', 'in'.
DPI (dots-per-inch) controls how the unit conversion is done.
If you don't know or care about the units stuff, "px" and 96 should get you going.
Example Usage:
The easiest way to use it is to rasterize a SVG to a [arsd.color.TrueColorImage], and from there you can work with it
same as any other memory image. For example, to turn a SVG into a png:
---
import arsd.svg;
import arsd.png;
void main() {
// Load
NSVG* image = nsvgParseFromFile("test.svg", "px", 96);
int w = cast(int) image.width;
int h = cast(int) image.height;
NSVGrasterizer rast = nsvgCreateRasterizer();
// Allocate memory for image
auto img = new TrueColorImage(w, h);
// Rasterize
rasterize(rast, image, 0, 0, 1, img.imageData.bytes.ptr, w, h, w*4);
// Delete
image.kill();
writePng("test.png", img);
}
---
You can also dig into the individual commands of the svg without rasterizing it.
Note that this is fairly complicated - svgs have a lot of settings, and even this
example only does the basics.
---
import core.stdc.stdio;
import core.stdc.stdlib;
import arsd.svg;
import arsd.nanovega;
void main() {
// we'll create a NanoVega window to display the image
int w = 800;
int h = 600;
auto window = new NVGWindow(w, h, "SVG Test");
// Load the file and can look at its info
NSVG* image = nsvgParseFromFile("/home/me/svgs/arsd.svg", "px", 96);
printf("size: %f x %f\n", image.width, image.height);
// and then use the data when the window asks us to redraw
// note that is is far from complete; svgs can have shapes, clips, caps, joins...
// we're only doing the bare minimum here.
window.redrawNVGScene = delegate(nvg) {
// clear the screen with white so we can see the images on top of it
nvg.beginPath();
nvg.fillColor = NVGColor.white;
nvg.rect(0, 0, window.width, window.height);
nvg.fill();
nvg.closePath();
image.forEachShape((in ref NSVG.Shape shape) {
if (!shape.visible) return;
nvg.beginPath();
// load the stroke
nvg.strokeWidth = shape.strokeWidth;
debug import std.stdio;
final switch(shape.stroke.type) {
case NSVG.PaintType.None:
// no stroke
break;
case NSVG.PaintType.Color:
with(shape.stroke)
nvg.strokeColor = NVGColor(r, g, b, a);
debug writefln("%08x", shape.fill.color);
break;
case NSVG.PaintType.LinearGradient:
case NSVG.PaintType.RadialGradient:
// FIXME: set the nvg stroke paint to shape.stroke.gradient
}
// load the fill
final switch(shape.fill.type) {
case NSVG.PaintType.None:
// no fill set
break;
case NSVG.PaintType.Color:
with(shape.fill)
nvg.fillColor = NVGColor(r, g, b, a);
break;
case NSVG.PaintType.LinearGradient:
case NSVG.PaintType.RadialGradient:
// FIXME: set the nvg fill paint to shape.stroke.gradient
}
shape.forEachPath((in ref NSVG.Path path) {
// this will issue final `LineTo` for closed pathes
path.forEachCommand!true(delegate (NSVG.Command cmd, const(float)[] args) nothrow @trusted @nogc {
debug writeln(cmd, args);
final switch (cmd) {
case NSVG.Command.MoveTo: nvg.moveTo(args); break;
case NSVG.Command.LineTo: nvg.lineTo(args); break;
case NSVG.Command.QuadTo: nvg.quadTo(args); break;
case NSVG.Command.BezierTo: nvg.bezierTo(args); break;
}
});
});
nvg.fill();
nvg.stroke();
nvg.closePath();
});
};
window.eventLoop(0);
// Delete the image
image.kill();
}
---
TODO: maybe merge https://github.com/memononen/nanosvg/pull/94 too
*/
module arsd.svg;
alias NSVGclipPathIndex = ubyte;
private import core.stdc.math : fabs, fabsf, atan2f, acosf, cosf, sinf, tanf, sqrt, sqrtf, floorf, ceilf, fmodf;
//private import iv.vfs;
version(nanosvg_disable_vfs) {
enum NanoSVGHasIVVFS = false;
} else {
static if (is(typeof((){import iv.vfs;}))) {
enum NanoSVGHasIVVFS = true;
import iv.vfs;
} else {
enum NanoSVGHasIVVFS = false;
}
}
version(aliced) {} else {
private alias usize = size_t;
}
version = nanosvg_crappy_stylesheet_parser;
//version = nanosvg_debug_styles;
//version(rdmd) import iv.strex;
//version = nanosvg_use_beziers; // convert everything to beziers
//version = nanosvg_only_cubic_beziers; // convert everything to cubic beziers
///
public enum NSVGDefaults {
CanvasWidth = 800,
CanvasHeight = 600,
}
// ////////////////////////////////////////////////////////////////////////// //
public alias NSVGrasterizer = NSVGrasterizerS*; ///
public alias NSVGRasterizer = NSVGrasterizer; ///
///
struct NSVG {
@disable this (this);
///
enum Command : int {
MoveTo, ///
LineTo, ///
QuadTo, ///
BezierTo, /// cubic bezier
}
///
enum PaintType : ubyte {
None, ///
Color, ///
LinearGradient, ///
RadialGradient, ///
}
///
enum SpreadType : ubyte {
Pad, ///
Reflect, ///
Repeat, ///
}
///
enum LineJoin : ubyte {
Miter, ///
Round, ///
Bevel, ///
}
///
enum LineCap : ubyte {
Butt, ///
Round, ///
Square, ///
}
///
enum FillRule : ubyte {
NonZero, ///
EvenOdd, ///
}
alias Flags = ubyte; ///
enum : ubyte {
Visible = 0x01, ///
}
///
static struct GradientStop {
uint color; ///
float offset; ///
}
///
static struct Gradient {
float[6] xform; ///
SpreadType spread; ///
float fx, fy; ///
int nstops; ///
GradientStop[0] stops; ///
}
///
static struct Paint {
pure nothrow @safe @nogc:
@disable this (this);
PaintType type; ///
union {
uint color; ///
Gradient* gradient; ///
}
static uint rgb (ubyte r, ubyte g, ubyte b) { pragma(inline, true); return (r|(g<<8)|(b<<16)); } ///
@property const {
bool isNone () { pragma(inline, true); return (type == PaintType.None); } ///
bool isColor () { pragma(inline, true); return (type == PaintType.Color); } ///
// gradient types
bool isLinear () { pragma(inline, true); return (type == PaintType.LinearGradient); } ///
bool isRadial () { pragma(inline, true); return (type == PaintType.RadialGradient); } ///
// color
ubyte r () { pragma(inline, true); return color&0xff; } ///
ubyte g () { pragma(inline, true); return (color>>8)&0xff; } ///
ubyte b () { pragma(inline, true); return (color>>16)&0xff; } ///
ubyte a () { pragma(inline, true); return (color>>24)&0xff; } ///
}
}
///
static struct Path {
@disable this (this);
float* stream; /// Command, args...; Cubic bezier points: x0,y0, [cpx1,cpx1,cpx2,cpy2,x1,y1], ...
int nsflts; /// Total number of floats in stream.
bool closed; /// Flag indicating if shapes should be treated as closed.
float[4] bounds; /// Tight bounding box of the shape [minx,miny,maxx,maxy].
NSVG.Path* next; /// Pointer to next path, or null if last element.
///
@property bool empty () const pure nothrow @safe @nogc { pragma(inline, true); return (nsflts == 0); }
///
float startX () const nothrow @trusted @nogc {
pragma(inline, true);
return (nsflts >= 3 && cast(Command)stream[0] == Command.MoveTo ? stream[1] : float.nan);
}
///
float startY () const nothrow @trusted @nogc {
pragma(inline, true);
return (nsflts >= 3 && cast(Command)stream[0] == Command.MoveTo ? stream[2] : float.nan);
}
///
bool startPoint (float* dx, float* dy) const nothrow @trusted @nogc {
if (nsflts >= 3 && cast(Command)stream[0] == Command.MoveTo) {
if (dx !is null) *dx = stream[1];
if (dy !is null) *dy = stream[2];
return true;
} else {
if (dx !is null) *dx = 0;
if (dy !is null) *dy = 0;
return false;
}
}
///
int countCubics () const nothrow @trusted @nogc {
if (nsflts < 3) return 0;
int res = 0, argc;
for (int pidx = 0; pidx+3 <= nsflts; ) {
final switch (cast(Command)stream[pidx++]) {
case Command.MoveTo: argc = 2; break;
case Command.LineTo: argc = 2; ++res; break;
case Command.QuadTo: argc = 4; ++res; break;
case Command.BezierTo: argc = 6; ++res; break;
}
if (pidx+argc > nsflts) break; // just in case
pidx += argc;
}
return res;
}
///
int countCommands(bool synthesizeCloseCommand=true) () const nothrow @trusted @nogc {
if (nsflts < 3) return 0;
int res = 0, argc;
for (int pidx = 0; pidx+3 <= nsflts; ) {
++res;
final switch (cast(Command)stream[pidx++]) {
case Command.MoveTo: argc = 2; break;
case Command.LineTo: argc = 2; break;
case Command.QuadTo: argc = 4; break;
case Command.BezierTo: argc = 6; break;
}
if (pidx+argc > nsflts) break; // just in case
pidx += argc;
}
static if (synthesizeCloseCommand) { if (closed) ++res; }
return res;
}
/// emits cubic beziers.
/// if `withMoveTo` is `false`, issue 8-arg commands for cubic beziers (i.e. include starting point).
/// if `withMoveTo` is `true`, issue 2-arg command for `moveTo`, and 6-arg command for cubic beziers.
void asCubics(bool withMoveTo=false, DG) (scope DG dg) inout if (__traits(compiles, (){ DG xdg; float[] f; xdg(f); })) {
if (dg is null) return;
if (nsflts < 3) return;
enum HasRes = __traits(compiles, (){ DG xdg; float[] f; bool res = xdg(f); });
float cx = 0, cy = 0;
float[8] cubic = void;
void synthLine (in float cx, in float cy, in float x, in float y) nothrow @trusted @nogc {
immutable float dx = x-cx;
immutable float dy = y-cy;
cubic.ptr[0] = cx;
cubic.ptr[1] = cy;
cubic.ptr[2] = cx+dx/3.0f;
cubic.ptr[3] = cy+dy/3.0f;
cubic.ptr[4] = x-dx/3.0f;
cubic.ptr[5] = y-dy/3.0f;
cubic.ptr[6] = x;
cubic.ptr[7] = y;
}
void synthQuad (in float cx, in float cy, in float x1, in float y1, in float x2, in float y2) nothrow @trusted @nogc {
immutable float cx1 = x1+2.0f/3.0f*(cx-x1);
immutable float cy1 = y1+2.0f/3.0f*(cy-y1);
immutable float cx2 = x2+2.0f/3.0f*(cx-x2);
immutable float cy2 = y2+2.0f/3.0f*(cy-y2);
cubic.ptr[0] = cx;
cubic.ptr[1] = cy;
cubic.ptr[2] = cx1;
cubic.ptr[3] = cy2;
cubic.ptr[4] = cx2;
cubic.ptr[5] = cy2;
cubic.ptr[6] = x2;
cubic.ptr[7] = y2;
}
for (int pidx = 0; pidx+3 <= nsflts; ) {
final switch (cast(Command)stream[pidx++]) {
case Command.MoveTo:
static if (withMoveTo) {
static if (HasRes) { if (dg(stream[pidx+0..pidx+2])) return; } else { dg(stream[pidx+0..pidx+2]); }
}
cx = stream[pidx++];
cy = stream[pidx++];
continue;
case Command.LineTo:
synthLine(cx, cy, stream[pidx+0], stream[pidx+1]);
pidx += 2;
break;
case Command.QuadTo:
synthQuad(cx, cy, stream[pidx+0], stream[pidx+1], stream[pidx+2], stream[pidx+3]);
pidx += 4;
break;
case Command.BezierTo:
cubic.ptr[0] = cx;
cubic.ptr[1] = cy;
cubic.ptr[2..8] = stream[pidx..pidx+6];
pidx += 6;
break;
}
cx = cubic.ptr[6];
cy = cubic.ptr[7];
static if (withMoveTo) {
static if (HasRes) { if (dg(cubic[2..8])) return; } else { dg(cubic[2..8]); }
} else {
static if (HasRes) { if (dg(cubic[])) return; } else { dg(cubic[]); }
}
}
}
/// if `synthesizeCloseCommand` is true, and the path is closed, this emits line to the first point.
void forEachCommand(bool synthesizeCloseCommand=true, DG) (scope DG dg) inout
if (__traits(compiles, (){ DG xdg; Command c; const(float)[] f; xdg(c, f); }))
{
if (dg is null) return;
if (nsflts < 3) return;
enum HasRes = __traits(compiles, (){ DG xdg; Command c; const(float)[] f; bool res = xdg(c, f); });
int argc;
Command cmd;
for (int pidx = 0; pidx+3 <= nsflts; ) {
cmd = cast(Command)stream[pidx++];
final switch (cmd) {
case Command.MoveTo: argc = 2; break;
case Command.LineTo: argc = 2; break;
case Command.QuadTo: argc = 4; break;
case Command.BezierTo: argc = 6; break;
}
if (pidx+argc > nsflts) break; // just in case
static if (HasRes) { if (dg(cmd, stream[pidx..pidx+argc])) return; } else { dg(cmd, stream[pidx..pidx+argc]); }
pidx += argc;
}
static if (synthesizeCloseCommand) {
if (closed && cast(Command)stream[0] == Command.MoveTo) {
static if (HasRes) { if (dg(Command.LineTo, stream[1..3])) return; } else { dg(Command.LineTo, stream[1..3]); }
}
}
}
}
static struct Clip {
NSVGclipPathIndex* index; // Array of clip path indices (of related NSVGimage).
NSVGclipPathIndex count; // Number of clip paths in this set.
}
///
static struct Shape {
@disable this (this);
char[64] id = 0; /// Optional 'id' attr of the shape or its group
NSVG.Paint fill; /// Fill paint
NSVG.Paint stroke; /// Stroke paint
float opacity; /// Opacity of the shape.
float strokeWidth; /// Stroke width (scaled).
float strokeDashOffset; /// Stroke dash offset (scaled).
float[8] strokeDashArray; /// Stroke dash array (scaled).
byte strokeDashCount; /// Number of dash values in dash array.
LineJoin strokeLineJoin; /// Stroke join type.
LineCap strokeLineCap; /// Stroke cap type.
float miterLimit; /// Miter limit
FillRule fillRule; /// Fill rule, see FillRule.
/*Flags*/ubyte flags; /// Logical or of NSVG_FLAGS_* flags
float[4] bounds; /// Tight bounding box of the shape [minx,miny,maxx,maxy].
NSVG.Path* paths; /// Linked list of paths in the image.
NSVG.Clip clip;
NSVG.Shape* next; /// Pointer to next shape, or null if last element.
@property bool visible () const pure nothrow @safe @nogc { pragma(inline, true); return ((flags&Visible) != 0); } ///
/// delegate can accept:
/// NSVG.Path*
/// const(NSVG.Path)*
/// ref NSVG.Path
/// in ref NSVG.Path
/// delegate can return:
/// void
/// bool (true means `stop`)
void forEachPath(DG) (scope DG dg) inout
if (__traits(compiles, (){ DG xdg; NSVG.Path s; xdg(&s); }) ||
__traits(compiles, (){ DG xdg; NSVG.Path s; xdg(s); }))
{
if (dg is null) return;
enum WantPtr = __traits(compiles, (){ DG xdg; NSVG.Path s; xdg(&s); });
static if (WantPtr) {
enum HasRes = __traits(compiles, (){ DG xdg; NSVG.Path s; bool res = xdg(&s); });
} else {
enum HasRes = __traits(compiles, (){ DG xdg; NSVG.Path s; bool res = xdg(s); });
}
static if (__traits(compiles, (){ NSVG.Path* s = this.paths; })) {
alias TP = NSVG.Path*;
} else {
alias TP = const(NSVG.Path)*;
}
for (TP path = paths; path !is null; path = path.next) {
static if (HasRes) {
static if (WantPtr) {
if (dg(path)) return;
} else {
if (dg(*path)) return;
}
} else {
static if (WantPtr) dg(path); else dg(*path);
}
}
}
}
static struct ClipPath {
char[64] id; // Unique id of this clip path (from SVG).
NSVGclipPathIndex index; // Unique internal index of this clip path.
NSVG.Shape* shapes; // Linked list of shapes in this clip path.
NSVG.ClipPath* next; // Pointer to next clip path or NULL.
}
float width; /// Width of the image.
float height; /// Height of the image.
NSVG.Shape* shapes; /// Linked list of shapes in the image.
NSVG.ClipPath* clipPaths; /// Linked list of clip paths in the image.
/// delegate can accept:
/// NSVG.Shape*
/// const(NSVG.Shape)*
/// ref NSVG.Shape
/// in ref NSVG.Shape
/// delegate can return:
/// void
/// bool (true means `stop`)
void forEachShape(DG) (scope DG dg) inout
if (__traits(compiles, (){ DG xdg; NSVG.Shape s; xdg(&s); }) ||
__traits(compiles, (){ DG xdg; NSVG.Shape s; xdg(s); }))
{
if (dg is null) return;
enum WantPtr = __traits(compiles, (){ DG xdg; NSVG.Shape s; xdg(&s); });
static if (WantPtr) {
enum HasRes = __traits(compiles, (){ DG xdg; NSVG.Shape s; bool res = xdg(&s); });
} else {
enum HasRes = __traits(compiles, (){ DG xdg; NSVG.Shape s; bool res = xdg(s); });
}
static if (__traits(compiles, (){ NSVG.Shape* s = this.shapes; })) {
alias TP = NSVG.Shape*;
} else {
alias TP = const(NSVG.Shape)*;
}
for (TP shape = shapes; shape !is null; shape = shape.next) {
static if (HasRes) {
static if (WantPtr) {
if (dg(shape)) return;
} else {
if (dg(*shape)) return;
}
} else {
static if (WantPtr) dg(shape); else dg(*shape);
}
}
}
}
// ////////////////////////////////////////////////////////////////////////// //
private:
nothrow @trusted @nogc {
// ////////////////////////////////////////////////////////////////////////// //
// sscanf replacement: just enough to replace all our cases
int xsscanf(A...) (const(char)[] str, const(char)[] fmt, ref A args) {
int spos;
while (spos < str.length && str.ptr[spos] <= ' ') ++spos;
static int hexdigit() (char c) {
pragma(inline, true);
return
(c >= '0' && c <= '9' ? c-'0' :
c >= 'A' && c <= 'F' ? c-'A'+10 :
c >= 'a' && c <= 'f' ? c-'a'+10 :
-1);
}
bool parseInt(T : ulong) (ref T res) {
res = 0;
debug(xsscanf_int) { import std.stdio; writeln("parseInt00: str=", str[spos..$].quote); }
bool neg = false;
if (spos < str.length && str.ptr[spos] == '+') ++spos;
else if (spos < str.length && str.ptr[spos] == '-') { neg = true; ++spos; }
if (spos >= str.length || str.ptr[spos] < '0' || str.ptr[spos] > '9') return false;
while (spos < str.length && str.ptr[spos] >= '0' && str.ptr[spos] <= '9') res = res*10+str.ptr[spos++]-'0';
debug(xsscanf_int) { import std.stdio; writeln("parseInt10: str=", str[spos..$].quote); }
if (neg) res = -res;
return true;
}
bool parseHex(T : ulong) (ref T res) {
res = 0;
debug(xsscanf_int) { import std.stdio; writeln("parseHex00: str=", str[spos..$].quote); }
if (spos >= str.length || hexdigit(str.ptr[spos]) < 0) return false;
while (spos < str.length) {
auto d = hexdigit(str.ptr[spos]);
if (d < 0) break;
res = res*16+d;
++spos;
}
debug(xsscanf_int) { import std.stdio; writeln("parseHex10: str=", str[spos..$].quote); }
return true;
}
bool parseFloat(T : real) (ref T res) {
res = 0.0;
debug(xsscanf_float) { import std.stdio; writeln("parseFloat00: str=", str[spos..$].quote); }
bool neg = false;
if (spos < str.length && str.ptr[spos] == '+') ++spos;
else if (spos < str.length && str.ptr[spos] == '-') { neg = true; ++spos; }
bool wasChar = false;
// integer part
debug(xsscanf_float) { import std.stdio; writeln("parseFloat01: str=", str[spos..$].quote); }
if (spos < str.length && str.ptr[spos] >= '0' && str.ptr[spos] <= '9') wasChar = true;
while (spos < str.length && str.ptr[spos] >= '0' && str.ptr[spos] <= '9') res = res*10+str.ptr[spos++]-'0';
// fractional part
if (spos < str.length && str.ptr[spos] == '.') {
debug(xsscanf_float) { import std.stdio; writeln("parseFloat02: str=", str[spos..$].quote); }
T div = 1.0/10;
++spos;
if (spos < str.length && str.ptr[spos] >= '0' && str.ptr[spos] <= '9') wasChar = true;
debug(xsscanf_float) { import std.stdio; writeln("parseFloat03: str=", str[spos..$].quote); }
while (spos < str.length && str.ptr[spos] >= '0' && str.ptr[spos] <= '9') {
res += div*(str.ptr[spos++]-'0');
div /= 10.0;
}
debug(xsscanf_float) { import std.stdio; writeln("parseFloat04: str=", str[spos..$].quote); }
debug(xsscanf_float) { import std.stdio; writeln("div=", div, "; res=", res, "; str=", str[spos..$].quote); }
}
// '[Ee][+-]num' part
if (wasChar && spos < str.length && (str.ptr[spos] == 'E' || str.ptr[spos] == 'e')) {
debug(xsscanf_float) { import std.stdio; writeln("parseFloat05: str=", str[spos..$].quote); }
++spos;
bool xneg = false;
if (spos < str.length && str.ptr[spos] == '+') ++spos;
else if (spos < str.length && str.ptr[spos] == '-') { xneg = true; ++spos; }
int n = 0;
if (spos >= str.length || str.ptr[spos] < '0' || str.ptr[spos] > '9') return false; // number expected
debug(xsscanf_float) { import std.stdio; writeln("parseFloat06: str=", str[spos..$].quote); }
while (spos < str.length && str.ptr[spos] >= '0' && str.ptr[spos] <= '9') n = n*10+str.ptr[spos++]-'0';
if (xneg) {
while (n-- > 0) res /= 10;
} else {
while (n-- > 0) res *= 10;
}
debug(xsscanf_float) { import std.stdio; writeln("parseFloat07: str=", str[spos..$].quote); }
}
if (!wasChar) return false;
debug(xsscanf_float) { import std.stdio; writeln("parseFloat10: str=", str[spos..$].quote); }
if (neg) res = -res;
return true;
}
int fpos;
void skipXSpaces () {
if (fpos < fmt.length && fmt.ptr[fpos] <= ' ') {
while (fpos < fmt.length && fmt.ptr[fpos] <= ' ') ++fpos;
while (spos < str.length && str.ptr[spos] <= ' ') ++spos;
}
}
bool parseImpl(T/*, usize dummy*/) (ref T res) {
while (fpos < fmt.length) {
//{ import std.stdio; writeln("spos=", spos, "; fpos=", fpos, "\nfmt=", fmt[fpos..$].quote, "\nstr=", str[spos..$].quote); }
if (fmt.ptr[fpos] <= ' ') {
skipXSpaces();
continue;
}
if (fmt.ptr[fpos] != '%') {
if (spos >= str.length || str.ptr[spos] != fmt.ptr[spos]) return false;
++spos;
++fpos;
continue;
}
if (fmt.length-fpos < 2) return false; // stray percent
fpos += 2;
bool skipAss = false;
if (fmt.ptr[fpos-1] == '*') {
++fpos;
if (fpos >= fmt.length) return false; // stray star
skipAss = true;
}
switch (fmt.ptr[fpos-1]) {
case '%':
if (spos >= str.length || str.ptr[spos] != '%') return false;
++spos;
break;
case 'd':
static if (is(T : ulong)) {
if (skipAss) {
long v;
if (!parseInt!long(v)) return false;
} else {
return parseInt!T(res);
}
} else {
if (!skipAss) assert(0, "invalid type");
long v;
if (!parseInt!long(v)) return false;
}
break;
case 'x':
static if (is(T : ulong)) {
if (skipAss) {
long v;
if (!parseHex!long(v)) return false;
} else {
return parseHex!T(res);
}
} else {
if (!skipAss) assert(0, "invalid type");
ulong v;
if (!parseHex!ulong(v)) return false;
}
break;
case 'f':
static if (is(T == float) || is(T == double) || is(T == real)) {
if (skipAss) {
double v;
if (!parseFloat!double(v)) return false;
} else {
return parseFloat!T(res);
}
} else {
if (!skipAss) assert(0, "invalid type");
double v;
if (!parseFloat!double(v)) return false;
}
break;
case '[':
if (fmt.length-fpos < 1) return false;
auto stp = spos;
while (spos < str.length) {
bool ok = false;
foreach (immutable cidx, char c; fmt[fpos..$]) {
if (cidx != 0) {
if (c == '-') assert(0, "not yet");
if (c == ']') break;
}
if (c == ' ') {
if (str.ptr[spos] <= ' ') { ok = true; break; }
} else {
if (str.ptr[spos] == c) { ok = true; break; }
}
}
//{ import std.stdio; writeln("** spos=", spos, "; fpos=", fpos, "\nfmt=", fmt[fpos..$].quote, "\nstr=", str[spos..$].quote, "\nok: ", ok); }
if (!ok) break; // not a match
++spos; // skip match
}
++fpos;
while (fpos < fmt.length && fmt[fpos] != ']') ++fpos;
if (fpos < fmt.length) ++fpos;
static if (is(T == const(char)[])) {
if (!skipAss) {
res = str[stp..spos];
return true;
}
} else {
if (!skipAss) assert(0, "invalid type");
}
break;
case 's':
auto stp = spos;
while (spos < str.length && str.ptr[spos] > ' ') ++spos;
static if (is(T == const(char)[])) {
if (!skipAss) {
res = str[stp..spos];
return true;
}
} else {
// skip non-spaces
if (!skipAss) assert(0, "invalid type");
}
break;
default: assert(0, "unknown format specifier");
}
}
return false;
}
foreach (usize aidx, immutable T; A) {
//pragma(msg, "aidx=", aidx, "; T=", T);
if (!parseImpl!(T)(args[aidx])) return -(spos+1);
//{ import std.stdio; writeln("@@@ aidx=", aidx+3, "; spos=", spos, "; fpos=", fpos, "\nfmt=", fmt[fpos..$].quote, "\nstr=", str[spos..$].quote); }
}
skipXSpaces();
return (fpos < fmt.length ? -(spos+1) : spos);
}
// ////////////////////////////////////////////////////////////////////////// //
T* xalloc(T) (usize addmem=0) if (!is(T == class)) {
import core.stdc.stdlib : malloc;
if (T.sizeof == 0 && addmem == 0) addmem = 1;
auto res = cast(ubyte*)malloc(T.sizeof+addmem+256);
if (res is null) assert(0, "NanoVega.SVG: out of memory");
res[0..T.sizeof+addmem] = 0;
return cast(T*)res;
}
T* xcalloc(T) (usize count) if (!is(T == class) && !is(T == struct)) {
import core.stdc.stdlib : malloc;
usize sz = T.sizeof*count;
if (sz == 0) sz = 1;
auto res = cast(ubyte*)malloc(sz+256);
if (res is null) assert(0, "NanoVega.SVG: out of memory");
res[0..sz] = 0;
return cast(T*)res;
}
void xfree(T) (ref T* p) {
if (p !is null) {
import core.stdc.stdlib : free;
free(p);
p = null;
}
}
alias AttrList = const(const(char)[])[];
public enum NSVG_PI = 3.14159265358979323846264338327f; ///
enum NSVG_KAPPA90 = 0.5522847493f; // Lenght proportional to radius of a cubic bezier handle for 90deg arcs.
enum NSVG_ALIGN_MIN = 0;
enum NSVG_ALIGN_MID = 1;
enum NSVG_ALIGN_MAX = 2;
enum NSVG_ALIGN_NONE = 0;
enum NSVG_ALIGN_MEET = 1;
enum NSVG_ALIGN_SLICE = 2;
int nsvg__isspace() (char c) { pragma(inline, true); return (c && c <= ' '); } // because
int nsvg__isdigit() (char c) { pragma(inline, true); return (c >= '0' && c <= '9'); }
int nsvg__isnum() (char c) { pragma(inline, true); return ((c >= '0' && c <= '9') || c == '+' || c == '-' || c == '.' || c == 'e' || c == 'E'); }
int nsvg__hexdigit() (char c) {
pragma(inline, true);
return
(c >= '0' && c <= '9' ? c-'0' :
c >= 'A' && c <= 'F' ? c-'A'+10 :
c >= 'a' && c <= 'f' ? c-'a'+10 :
-1);
}
float nsvg__minf() (float a, float b) { pragma(inline, true); return (a < b ? a : b); }
float nsvg__maxf() (float a, float b) { pragma(inline, true); return (a > b ? a : b); }
// Simple XML parser
enum NSVG_XML_TAG = 1;
enum NSVG_XML_CONTENT = 2;
enum NSVG_XML_MAX_ATTRIBS = 256;
void nsvg__parseContent (const(char)[] s, scope void function (void* ud, const(char)[] s) nothrow @nogc contentCb, void* ud) {
// Trim start white spaces
while (s.length && nsvg__isspace(s[0])) s = s[1..$];
if (s.length == 0) return;
//{ import std.stdio; writeln("s=", s.quote); }
if (contentCb !is null) contentCb(ud, s);
}
static void nsvg__parseElement (const(char)[] s,
scope void function (void* ud, const(char)[] el, AttrList attr) nothrow @nogc startelCb,
scope void function (void* ud, const(char)[] el) nothrow @nogc endelCb,
void* ud)
{
const(char)[][NSVG_XML_MAX_ATTRIBS] attr;
int nattr = 0;
const(char)[] name;
int start = 0;
int end = 0;
char quote;
// Skip white space after the '<'
while (s.length && nsvg__isspace(s[0])) s = s[1..$];
// Check if the tag is end tag
if (s.length && s[0] == '/') {
s = s[1..$];
end = 1;
} else {
start = 1;
}
// Skip comments, data and preprocessor stuff.
if (s.length == 0 || s[0] == '?' || s[0] == '!') return;
// Get tag name
//{ import std.stdio; writeln("bs=", s.quote); }
{
usize pos = 0;
while (pos < s.length && !nsvg__isspace(s[pos])) ++pos;
name = s[0..pos];
s = s[pos..$];
}
//{ import std.stdio; writeln("name=", name.quote); }
//{ import std.stdio; writeln("as=", s.quote); }
// Get attribs
while (!end && s.length && attr.length-nattr >= 2) {
// skip white space before the attrib name
while (s.length && nsvg__isspace(s[0])) s = s[1..$];
if (s.length == 0) break;
if (s[0] == '/') { end = 1; break; }
// find end of the attrib name
{
usize pos = 0;
while (pos < s.length && !nsvg__isspace(s[pos]) && s[pos] != '=') ++pos;
attr[nattr++] = s[0..pos];
s = s[pos..$];
}
// skip until the beginning of the value
while (s.length && s[0] != '\"' && s[0] != '\'') s = s[1..$];
if (s.length == 0) break;
// store value and find the end of it
quote = s[0];
s = s[1..$];
{
usize pos = 0;
while (pos < s.length && s[pos] != quote) ++pos;
attr[nattr++] = s[0..pos];
s = s[pos+(pos < s.length ? 1 : 0)..$];
}
//{ import std.stdio; writeln("n=", attr[nattr-2].quote, "\nv=", attr[nattr-1].quote, "\n"); }
}
debug(nanosvg) {
import std.stdio;
writeln("===========================");
foreach (immutable idx, const(char)[] v; attr[0..nattr]) writeln(" #", idx, ": ", v.quote);
}
// Call callbacks.
if (start && startelCb !is null) startelCb(ud, name, attr[0..nattr]);
if (end && endelCb !is null) endelCb(ud, name);
}
void nsvg__parseXML (const(char)[] input,
scope void function (void* ud, const(char)[] el, AttrList attr) nothrow @nogc startelCb,
scope void function (void* ud, const(char)[] el) nothrow @nogc endelCb,
scope void function (void* ud, const(char)[] s) nothrow @nogc contentCb,
void* ud)
{
usize cpos = 0;
int state = NSVG_XML_CONTENT;
while (cpos < input.length) {
if (state == NSVG_XML_CONTENT && input[cpos] == '<') {
if (input.length-cpos >= 9 && input[cpos..cpos+9] == "<![CDATA[") {
cpos += 9;
while (cpos < input.length) {
if (input.length-cpos > 1 && input.ptr[cpos] == ']' && input.ptr[cpos+1] == ']') {
cpos += 2;
while (cpos < input.length && input.ptr[cpos] <= ' ') ++cpos;