-
Notifications
You must be signed in to change notification settings - Fork 10
/
SvgDoc.cpp
2309 lines (2180 loc) · 101 KB
/
SvgDoc.cpp
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
#define NANOSVG_IMPLEMENTATION
#include "SvgDoc.h"
#include <iostream>
#include <fstream>
#include <iomanip> // std::setprecision
#include <string>
#include <math.h>
#include "Geometry.h"
#include "ConvexHull.h"
#define _USE_MATH_DEFINES
#include <cmath>
using namespace std;
#define SIMPLIFY_POLYGON 1
#define FIXED_BIT 16
#define DEBUG_BEZIER 0
enum ReasonPlacementFailure {
FAIL_OUTSIDE_SHEET = 1,
FAIL_VERTEX_IN_POLYGON = 2,
FAIL_EDGE_INTERSECT = 3
};
//static int DebugPassage = 0;
// Compute the max distance between the bezier curve and a line segment
// Actually return the square of the distance, easier to compute
// The distance is the max between the control points and the segment joining the 2
static double Distance_bezier_segment(double x, double y, NSVGPathElt *Elt)
{
// Compute parameters of the line segment between Start and End
double b = Elt->EndX - x;
double a = y - Elt->EndY;
double c = x * Elt->EndY - Elt->EndX*y;
// Compute distance between first control point and the line segment Start - End
// Distance between point and line is (a * p.x + b * p.y + c)*(a * p.x + b * p.y + c)/(a*a + b*b)
double d1 = a * Elt->BzCtrl1X + b * Elt->BzCtrl1Y + c;
d1 *= d1;
d1 /= a*a + b*b;
// Compute distance between second control point and the line segment Start - End
// Distance between point and line is (a * p.x + b * p.y + c)*(a * p.x + b * p.y + c)/(a*a + b*b)
double d2 = a * Elt->BzCtrl2X + b * Elt->BzCtrl2Y + c;
d2 *= d2;
d2 /= a*a + b*b;
return(fmax(d1, d2));
}
// Break each element of type bezier cubic path into segments
static void SplitBezierCurves(NSVGpath *path, double flat_factor)
{
NSVGPathElt *Elt = path->PathElts;
float x, y;
float xmin, xmax, ymin, ymax;
NSVGpath *dPath = (NSVGpath *) malloc(sizeof(NSVGpath));
path->PolyLine = dPath;
dPath->StartX = path->StartX; // Copy elements
dPath->StartY = path->StartY;
dPath->nElts = path->nElts;
dPath->next = 0;
dPath->PolyLine = dPath;
dPath->ClosePolygon = NULL;
dPath->hasBezier = 0;
dPath->closed = path->closed;
// Copy all elements of path
NSVGPathElt *dElt, *oldElt = 0;
while ( Elt )
{
dElt = (NSVGPathElt *) malloc(sizeof(NSVGPathElt));
*dElt = *Elt;
dElt->next = NULL;
if ( oldElt )
oldElt->next = dElt;
else
path->PolyLine->PathElts = dElt;
oldElt = dElt;
Elt = Elt->next;
}
// Now walk through all path elements to transform bezier curves into line segments
x = path->StartX;
y = path->StartY;
xmin = x;
xmax = x;
ymin = y;
ymax = y;
Elt = path->PolyLine->PathElts;
while ( Elt != NULL )
{
if ( Elt->Type == NSVG_PATH_BEZIER_C )
{
// Break bezier curves into line segments
// For this, split bezier curve into two parts, until parts are nearly line segments
double d_bezier = Distance_bezier_segment(x, y, Elt);
if ( d_bezier <= flat_factor )
{
Elt->Type = NSVG_PATH_LINE; // nearly a line segment, transform type
}
else
{
// split bezier into two parts, then resume processing at the same point.
NSVGPathElt *Elt2 = (NSVGPathElt *) malloc(sizeof(NSVGPathElt)); // Create a new element
// First create the linked list
Elt2->next = Elt->next;
Elt->next = Elt2;
Elt2->Type = NSVG_PATH_BEZIER_C;
// The end point of the second half is the previous end point.
Elt2->EndX = Elt->EndX;
Elt2->EndY = Elt->EndY;
// Now compute new bezier control points.
// First is halfway between start and first control point
float m1x, m1y;
m1x = (x + Elt->BzCtrl1X) / 2;
m1y = (y + Elt->BzCtrl1Y) / 2;
// Temp point, halfway between the 2 two control points
float m2x, m2y;
m2x = (Elt->BzCtrl2X + Elt->BzCtrl1X) / 2;
m2y = (Elt->BzCtrl2Y + Elt->BzCtrl1Y) / 2;
// Then a point halfway between the second control point and the end point
float m3x, m3y;
m3x = (Elt->BzCtrl2X + Elt->EndX) / 2;
m3y = (Elt->BzCtrl2Y + Elt->EndY) / 2;
// Then compute a new point in the middle of m1, m2
float m4x, m4y;
m4x = (m1x + m2x)/2;
m4y = (m1y + m2y)/2;
// Then compute a new point in the middle of m2, m3
float m5x, m5y;
m5x = (m2x + m3x)/2;
m5y = (m2y + m3y)/2;
// And at last compute a new point in the middle of m4, m5
float m6x, m6y;
m6x = (m4x + m5x)/2;
m6y = (m4y + m5y)/2;
// The new control points for the first half are m1 and m4, and it goes up to m6
Elt->EndX = m6x;
Elt->EndY = m6y;
Elt->BzCtrl1X = m1x;
Elt->BzCtrl1Y = m1y;
Elt->BzCtrl2X = m4x;
Elt->BzCtrl2Y = m4y;
// The new control points for the second half are m5 and m3
Elt2->BzCtrl1X = m5x;
Elt2->BzCtrl1Y = m5y;
Elt2->BzCtrl2X = m3x;
Elt2->BzCtrl2Y = m3y;
path->PolyLine->nElts++;
continue; // Restart procrssing of the segment, which is smaller now.
}
}
// Change start point for next, which is end of this one
x = Elt->EndX;
y = Elt->EndY;
xmin = fmin(xmin, x);
xmax = fmax(xmax, x);
ymin = fmin(ymin, y);
ymax = fmax(ymax, y);
// Then next element
Elt = Elt->next;
}
path->PolyLine->bounds[0] = xmin;
path->PolyLine->bounds[1] = ymin;
path->PolyLine->bounds[2] = xmax;
path->PolyLine->bounds[3] = ymax;
}
static void Path2Polygon(Polygon *Poly, NSVGpath *path)
{
struct NSVGPathElt *Elt = path->PathElts;
Point p;
p = Point(path->StartX, path->StartY);
Poly->addVertice(p);
for (int n = 0; n < path->nElts; n++)
{
p = Point(Elt->EndX, Elt->EndY);
Poly->addVertice(p);
Elt = Elt->next;
}
}
// Walk through the polyline and delete vertices if the error is smaller than max_error
void SvgDoc::SimplifyPath(NSVGpath *path, double max_error)
{
NSVGPathElt *Elt, *Elt2, *oldElt = NULL;
float x, y;
float xmin, xmax, ymin, ymax;
// Now walk through all path elements to delete vertices if they are aligned
x = path->StartX;
y = path->StartY;
xmin = x;
xmax = x;
ymin = y;
ymax = y;
Elt = path->PathElts;
while ( Elt != NULL )
{
Elt2 = Elt->next;
if ( Elt2 != NULL )
{
// Build segment x,y --> Elt2->EndX, EndY
// Compute parameters of the line segment between Start and End
double b = Elt2->EndX - x;
double a = y - Elt2->EndY;
double c = x * Elt2->EndY - Elt2->EndX*y;
// Compute distance between Elt->EndX, EndY and the segment
// Distance between point and line is (a * p.x + b * p.y + c)*(a * p.x + b * p.y + c)/(a*a + b*b)
double d1 = a * Elt->EndX + b * Elt->EndY + c;
d1 *= d1;
d1 /= a*a + b*b;
if ( d1 < max_error )
{
// remove Elt
if ( oldElt == NULL)
path->PathElts = Elt2;
else
oldElt->next = Elt2;
path->nElts--;
Elt = Elt2;
continue;
}
else
{
x = Elt->EndX;
y = Elt->EndY;
xmin = fmin(xmin, x);
xmax = fmax(xmax, x);
ymin = fmin(ymin, y);
ymax = fmax(ymax, y);
// Then next element
oldElt = Elt;
Elt = Elt2;
continue;
}
}
break;
}
path->PolyLine->bounds[0] = xmin;
path->PolyLine->bounds[1] = ymin;
path->PolyLine->bounds[2] = xmax;
path->PolyLine->bounds[3] = ymax;
}
// Transform each path into a polyline, if not already the case
// Then simplify path to save some running time
void SvgDoc::TransformPaths(double flat_factor, bool KeepNested)
{
int nShape, nPath;
nShape = 0;
if ( SvgData == NULL ) return;
if ( debug_level > 0 )
{
OutDebug << "Entering TransformPaths\n" << std::flush;
}
for (NSVGshape *shape = SvgData->shapes; shape != NULL; shape = shape->next, nShape++)
{
nPath = 0;
if ( debug_level > 0 )
{
OutDebug << "Shape " << nShape << " id:" << shape->id << " Stroke[" << (int) shape->stroke.type << " " << setw(6) << setfill('0') << std::hex << (shape->stroke.color&0xFFFFFF) << std::dec << "] width:" << shape->strokeWidth << "\n" << std::flush;
}
// Transform each path to a polygon
for (NSVGpath *path = shape->paths; path != NULL; path = path->next, nPath++)
{
snprintf(path->id, 99, "%s_%d", shape->id, nPath);
path->id[99] = 0;
// Walk through the path and delete vertices which have trange coordinates (nan)
// This has been observed in some cases.
// Indeed vertices are very close in these cases, so it is safe to remove vertex with nan coordinates.
// However, this can't be the first one.
int StrangeControlPoints = 0;
int StrangeEndPoints = 0;
NSVGPathElt *Elt = path->PathElts;
NSVGPathElt *PrevElt = NULL;
for (int i = 0; i < path->nElts; i++)
{
int ShouldDelete = 0;
if ( isnan(Elt->EndX) || isnan(Elt->EndY) )
{
StrangeEndPoints++;
ShouldDelete = 1;
}
if ( isnan(Elt->BzCtrl1X) || isnan(Elt->BzCtrl1Y) || isnan(Elt->BzCtrl2X) || isnan(Elt->BzCtrl2Y) )
{
StrangeControlPoints++;
ShouldDelete = 1;
}
if ( ShouldDelete )
{
if ( PrevElt == NULL )
{
if ( debug_level > 0 )OutDebug << "nan encoutered as first element in path, aborting\n";
cerr << "nan encoutered as first element in path, aborting\n";
exit(1);
}
// Remove vertex
path->nElts--;
PrevElt->next = Elt->next;
Elt = Elt->next;
continue;
}
PrevElt = Elt;
Elt = Elt->next;
}
if ( debug_level > 2)
{
OutDebug << "Before Transform path, Shape " << nShape << " Path " << nPath << " with " << path->nElts << " HasBezier:" << path->hasBezier << "\n";
OutDebug << "Path has " << StrangeEndPoints << " StrangeEndPoints and "<< StrangeControlPoints << " StrangeControlPoints (removed)\n";
OutDebug << "Starting point=" << path->StartX << "," << path->StartY << "\n";
OutDebug << " Bounds (" << path->bounds[0] << "," << path->bounds[1] << ") --> (" << path->bounds[2] << "," << path->bounds[3] << "\n";
NSVGPathElt *Elt = path->PathElts;
for (int i = 0; i < path->nElts; i++)
{
OutDebug << " Elt " << i << " type " << Elt->Type << " EndPoint=(" << Elt->EndX << "," << Elt->EndY;
OutDebug << ") Control points (" << Elt->BzCtrl1X << "," << Elt->BzCtrl1Y << ") and (" << Elt->BzCtrl2X << "," << Elt->BzCtrl2Y << ")\n";
Elt = Elt->next;
}
OutDebug << std::flush;
}
if ( path->closed == 0 )
{
if ( debug_level > 0 )
{
OutDebug << "Path is NOT closed, skip !\n";
}
// Path is not closed, do NOT process
continue;
}
// If path has bezier curves, break them in small segments, if not copy data to polyline path
SplitBezierCurves(path, flat_factor*flat_factor);
if ( debug_level > 2 )
{
OutDebug << "After flatening bezier, Shape " << nShape << " Path " << nPath << " with " << path->nElts << " HasBezier:" << path->hasBezier << "\n";
OutDebug << " Start (" << path->PolyLine->StartX << "," << path->PolyLine->StartY << ") Bounds (" << path->bounds[0] << "," << path->bounds[1] << ") --> (" << path->bounds[2] << "," << path->bounds[3] << "\n";
NSVGPathElt *Elt = path->PolyLine->PathElts;
for (int i = 0; i < path->PolyLine->nElts; i++)
{
OutDebug << " Elt " << i << " type " << Elt->Type << " EndPoint=(" << Elt->EndX << "," << Elt->EndY;
OutDebug << ") Control points (" << Elt->BzCtrl1X << "," << Elt->BzCtrl1Y << ") and (" << Elt->BzCtrl2X << "," << Elt->BzCtrl2Y << ")\n";
Elt = Elt->next;
}
}
SimplifyPath(path->PolyLine, flat_factor*flat_factor);
if ( debug_level > 2 )
{
OutDebug << "After Simplification, Shape " << nShape << " Path " << nPath << " with " << path->nElts << " HasBezier:" << path->hasBezier << "\n";
OutDebug << " Start (" << path->PolyLine->StartX << "," << path->PolyLine->StartY << ") Bounds (" << path->bounds[0] << "," << path->bounds[1] << ") --> (" << path->bounds[2] << "," << path->bounds[3] << "\n";
NSVGPathElt *Elt = path->PolyLine->PathElts;
for (int i = 0; i < path->PolyLine->nElts; i++)
{
OutDebug << " Elt " << i << " type " << Elt->Type << " EndPoint=(" << Elt->EndX << "," << Elt->EndY;
OutDebug << ") Control points (" << Elt->BzCtrl1X << "," << Elt->BzCtrl1Y << ") and (" << Elt->BzCtrl2X << "," << Elt->BzCtrl2Y << ")\n";
Elt = Elt->next;
}
}
// Create polygon structure
path->ClosePolygon = new Polygon();
Path2Polygon(path->ClosePolygon, path->PolyLine);
if ( debug_level > 1 )
{
OutDebug << "Adding polygon " << nPath << " new name " << path->id << " with " << path->ClosePolygon->nVertices << " vertices, area:" << path->ClosePolygon->area() << "mm²\n";
}
if ( path->ClosePolygon->isClockWise() )
{
if ( debug_level > 1 )
{
OutDebug << "Polygon is clockwise, make it counter clockwise\n";
}
path->ClosePolygon->Reverse();
}
}
if ( debug_level > 0)
OutDebug << std::flush;
}
if ( KeepNested )
{
nShape = 0;
// Second pass, check if a path is included in an other one
if ( debug_level > 0 )
{
OutDebug << "Transform paths pass 2 : checking if paths are included in other ones\n";
}
for (NSVGshape *shape = SvgData->shapes; shape != NULL; shape = shape->next, nShape++)
{
nPath = 0;
NSVGpath *OldPath = NULL;
NSVGpath *next_path = NULL;
// For each path of the shape, check if it is included in a larger o
for (NSVGpath *path = shape->paths; path != NULL; path = next_path, nPath++)
{
next_path = path->next; // Memorize value, because will be modified if path is removed
if ( RemoveIfIncluded(path, shape, OldPath, nShape, nPath) == 0 )
{
// Not removed, new OldPath now. IF removed, DO NOT change OldPath, as the current entry has been moved
OldPath = path;
}
}
}
}
if ( debug_level > 0 )
{
OutDebug << "End of Transform paths\n" << std::flush;
}
}
// If a path is included in an other one, remove this path for the primary list and move it to the child list of the large path
// Do NOT take into account nested inclusion, there is a single level.
int SvgDoc::RemoveIfIncluded(NSVGpath *Inpath, NSVGshape *Inshape, NSVGpath *OldPath, int nShapeIn, int nPathIn)
{
int nShape = 0;
for (NSVGshape *shape = SvgData->shapes; shape != NULL; shape = shape->next, nShape++)
{
int nPath = 0;
// For each path of the shape, check if the path passed as parameter (Inpath) is included in this one
for (NSVGpath *path = shape->paths; path != NULL; path = path->next, nPath++)
{
if ( path->ClosePolygon != NULL && Inpath->ClosePolygon != NULL )
{
if ( nShapeIn == 0 && nPathIn == 1 && nShape== 0 && nPath == 2 )
{
OutDebug << "Inpath->ClosePolygon->Poly_in_Poly(path->ClosePolygon) returns " << Inpath->ClosePolygon->Poly_in_Poly(path->ClosePolygon) << " \n";
}
if ( Inpath->ClosePolygon->Poly_in_Poly(path->ClosePolygon) )
{
if ( debug_level > 0 )
{
OutDebug << "Shape_" << nShapeIn << "/Path_" << nPathIn << "(" << Inpath->id << ") is included in " << path->id << "\n";
}
// First, remove from primary list
if ( OldPath )
{
OldPath->next = Inpath->next; // Not first in list, change next element of previous one
}
else
{
Inshape->paths = Inpath->next; // First in list for this shape, change head of list
}
// Now move from primary list to child list, insert head of list
Inpath->next = path->child;
path->child = Inpath;
// If Inpath has children, move them to child list
NSVGpath *pCur = Inpath->child;
while ( pCur != NULL )
{
NSVGpath *pNext = pCur->next;
pCur->next = path->child;
path->child = pCur;
pCur = pNext;
}
if ( debug_level > 1 )
{
OutDebug << path->id << " has " << NbChildren(path) << " children\n";
}
return 1;
}
}
else if ( path->ClosePolygon == NULL )
{
OutDebug << " Shape " << nShapeIn << " Shape->ClosePolygon is NULL\n";
}
else
{
OutDebug << " InShape->ClosePolygon is NULL\n";
}
}
}
return 0;
}
void SvgDoc::EnlargePaths(double Diff)
{
int nShape, nPath;
if ( debug_level > 0 )
{
OutDebug << "---------------- Entering EnlargePaths, elapsed time: " << 1000.0*(clock() - StartClock)/CLOCKS_PER_SEC << "ms\n";
}
nShape = 0;
if ( SvgData == NULL ) return;
for (NSVGshape *shape = SvgData->shapes; shape != NULL; shape = shape->next, nShape++)
{
nPath = 0;
// Transform each path to a polygon
for (NSVGpath *path = shape->paths; path != NULL; path = path->next, nPath++)
{
if ( path->ClosePolygon == NULL )
{
OutDebug << path->id << " has no closed polygon, skipping large polygon generation\n";
continue;
}
if ( debug_level > 1 )
{
OutDebug << path->id << " before elarging polygon with " << path->ClosePolygon->nVertices << " vertices and area " << path->ClosePolygon->area() << "mm²\n" << std::flush;
}
path->LargePolygon = path->ClosePolygon->enlarge(Diff);
if ( debug_level > 1 )
{
OutDebug << path->id << " before simplify large polygon with " << path->LargePolygon->nVertices << " vertices and area " << path->LargePolygon->area() << "mm²\n" << std::flush;
}
path->LargePolygon->Simplify(Diff*Diff/5);
if ( debug_level > 1 )
{
OutDebug << path->id << " after simplify large polygon with " << path->LargePolygon->nVertices << " vertices and area " << path->LargePolygon->area() << "mm²\n" << std::flush;
}
}
}
if ( debug_level > 0 )
{
OutDebug << "---------------- Exit EnlargePaths, elapsed time: " << 1000.0*(clock() - StartClock)/CLOCKS_PER_SEC << "ms\n\n\n" << std::flush;
}
}
// For each path with a large polygon, modify this large polygon in order to keep max edge length lower tahn max_length
// This will add vertices to polygons, so it will add some positions which could lead to better opimization.
// But beware, more vertices also mean more execution time !
void SvgDoc::BreakLongerEdges(double max_length, double Diff)
{
int nShape, nPath;
if ( debug_level > 0 )
{
OutDebug << "---------------- Entering BreakLongerEdges, elapsed time: " << 1000.0*(clock() - StartClock)/CLOCKS_PER_SEC << "ms\n";
}
nShape = 0;
if ( SvgData == NULL ) return;
for (NSVGshape *shape = SvgData->shapes; shape != NULL; shape = shape->next, nShape++)
{
nPath = 0;
// Transform each large polygon to add vertices when edges are too long
for (NSVGpath *path = shape->paths; path != NULL; path = path->next, nPath++)
{
if ( path->LargePolygon == NULL )
{
OutDebug << " Shape " << shape->id << " Index " << nShape << " Path " << nPath << " has no large polygon\n";
continue;
}
path->LargePolygon->BreakLongerEdges(max_length, Diff);
if ( debug_level > 1 )
{
OutDebug << " Shape " << shape->id << " Index " << nShape << " Path " << nPath << " Large polygon with " << path->LargePolygon->nVertices << " vertices and area " << path->LargePolygon->area() << "mm²\n";
}
}
}
if ( debug_level > 0 )
{
OutDebug << "---------------- Exit BreakLongerEdges, elapsed time: " << 1000.0*(clock() - StartClock)/CLOCKS_PER_SEC << "ms\n\n\n" << std::flush;
}
}
// Read SVG file and create Image object
SvgDoc::SvgDoc(string &FileName)
{
StartClock = clock();
Name = FileName;
// Load SVG
SvgData = nsvgParseFromFile(FileName.c_str(), "mm", 25.4);
if (SvgData )
{
SheetSizeX = round(SvgData->width * 100) / 100.0;
SheetSizeY = round(SvgData->height * 100) / 100.0;
}
nbTranslation = 0;
nbRotation = 0;
nbCheckAngles = 0;
nbPointInPoly = 0;
nbIntersectPoly = 0;
nbPlacementImpossible = 0;
CacheMiss = 0;
CacheHit_OK = 0;
CacheHit_KO = 0;
}
// Return the number of children for a given path
int SvgDoc::NbChildren(NSVGpath *path)
{
int nb = 0;
for ( NSVGpath *child = path->child; child != NULL; child = child->next)
{
nb++;
}
return nb;
}
SvgDoc::~SvgDoc()
{
if ( OutDebug.is_open() )
OutDebug.close();
}
void SvgDoc::WritePath(ostream &Out, NSVGpath *path, NSVGshape *shape, int iPath)
{
Out << " <path" << endl;
// Line style from SVG file
Out << std::hex;
Out << " style=\"fill:none;stroke:#" << setw(6) << setfill('0') << std::hex << (shape->stroke.color&0xFFFFFF);
Out << std::dec;
Out << ";stroke-width:" << shape->strokeWidth << "\"" << endl;
// Then path itself
Out << " d=\"M " << path->StartX << "," << path->StartY;
NSVGPathElt *Elt = path->PathElts;
for (int i = 0; i < path->nElts; i++)
{
if ( Elt->Type == NSVG_PATH_BEZIER_C )
Out << " C " << Elt->BzCtrl1X << "," << Elt->BzCtrl1Y << "," << Elt->BzCtrl2X << "," << Elt->BzCtrl2Y << "," << Elt->EndX << "," << Elt->EndY;
else
Out << " L " << Elt->EndX << "," << Elt->EndY;
Elt = Elt->next;
}
if ( path->closed == 1 )
{
Out << " z";
}
Out << "\"" << endl;
Out << " id=\"" << shape->id << "_" << iPath << "\"" << endl;
Out << " inkscape:connector-curvature=\"0\" />" << endl;
}
void SvgDoc::WritePlacedPath(ostream &Out, NSVGpath *ref_path, NSVGpath *out_path, NSVGshape *shape, int iPath)
{
Out << " <path" << endl;
// Line style from SVG file
Out << std::hex;
Out << " style=\"fill:none;stroke:#" << setw(6) << setfill('0') << std::hex << (shape->stroke.color&0xFFFFFF);
Out << std::dec;
Out << ";stroke-width:" << shape->strokeWidth << "\"" << endl;
// Get transformation values (rotation and translation) from reference path
double angle = ref_path->PlacedPolygon->getRotation();
Point PtTrans = ref_path->PlacedPolygon->getTranslation();
Point Centroid = ref_path->PlacedPolygon->getCentroid() - PtTrans; // Should get centroid of unplaced polygon
// Then write path
Point Start = Point(out_path->StartX, out_path->StartY);
Start.Transform(angle, Centroid, PtTrans);
Out << " d=\"M " << Start.x << "," << Start.y;
NSVGPathElt *Elt = out_path->PathElts;
for (int i = 0; i < out_path->nElts; i++)
{
if ( Elt->Type == NSVG_PATH_BEZIER_C )
{
Point EltEnd = Point(Elt->EndX, Elt->EndY);
EltEnd.Transform(angle, Centroid, PtTrans);
Point EltBzCtrl1 = Point(Elt->BzCtrl1X, Elt->BzCtrl1Y);
EltBzCtrl1.Transform(angle, Centroid, PtTrans);
Point EltBzCtrl2 = Point(Elt->BzCtrl2X, Elt->BzCtrl2Y);
EltBzCtrl2.Transform(angle, Centroid, PtTrans);
Out << " C " << EltBzCtrl1.x << "," << EltBzCtrl1.y << "," << EltBzCtrl2.x << "," << EltBzCtrl2.y << "," << EltEnd.x << "," << EltEnd.y;
}
else
{
Point EltEnd = Point(Elt->EndX, Elt->EndY);
EltEnd.Transform(angle, Centroid, PtTrans);
Out << " L " << EltEnd.x << "," << EltEnd.y;
}
Elt = Elt->next;
}
if ( out_path->closed == 1 )
{
Out << " z";
}
Out << "\"" << endl;
Out << " id=\"Placed_" << shape->id << "_" << iPath << "\"" << endl;
Out << " inkscape:connector-curvature=\"0\" />" << endl;
}
void SvgDoc::WriteOrginalLayer(ostream& Out)
{
// Then the data, begin with original layer
Out << " <g\n";
Out << " inkscape:label=\"Orginal_Layer\"" << endl;
Out << " inkscape:groupmode=\"layer\"" << endl;
Out << " id=\"Orginal_Layer1\">" << endl;
int nShape = 0;
Out << std::fixed;
Out << std::setprecision(6);
for (NSVGshape *shape = SvgData->shapes; shape != NULL; shape = shape->next, nShape++)
{
// Then for each path in the shape
int iPath = 0;
for (NSVGpath *path = shape->paths; path != NULL; path = path->next, iPath++)
{
WritePath(Out, path, shape, iPath); // Write path itself.
int iChild = 10000 - iPath * 100 - 1;
for ( NSVGpath *path_child = path->child; path_child != NULL; path_child = path_child->next, iChild--)
{
WritePath(Out, path_child, shape, iChild);
}
}
}
Out << " </g>" << endl;
}
// Write the polygon layer to output stream
void SvgDoc::WritePolygonLayer(ostream& Out)
{
// Then the data, begin with original layer
Out << " <g\n";
Out << " inkscape:label=\"Polygon_Layer\"" << endl;
Out << " inkscape:groupmode=\"layer\"" << endl;
Out << " id=\"Polygon_Layer1\">" << endl;
int nShape = 0;
Out << std::fixed;
Out << std::setprecision(6);
for (NSVGshape *shape = SvgData->shapes; shape != NULL; shape = shape->next, nShape++)
{
// Then for each path in the shape
int iPath = 0;
for (NSVGpath *path = shape->paths; path != NULL; path = path->next, iPath++)
{
Polygon *poly_path = path->ClosePolygon;
if ( poly_path == NULL ) continue;
Out << " <path" << endl;
// Line style : cyan
Out << " style=\"fill:none;stroke:#00FFFF;stroke-width:" << shape->strokeWidth << "\"" << endl;
// Then path itself
Out << " d=\"M " << poly_path->GetVertex(0)->x << "," << poly_path->GetVertex(0)->y;
for (int i = 1; i < poly_path->nVertices; i++)
{
Out << " L " << poly_path->GetVertex(i)->x << "," << poly_path->GetVertex(i)->y;
}
if ( path->closed == 1 )
{
Out << " z";
}
Out << "\"" << endl;
Out << " id=\"poly_" << path->id << "\"" << endl;
Out << " inkscape:connector-curvature=\"0\" />" << endl;
}
}
Out << " </g>" << endl;
}
// Write large polygon layer to output stream
void SvgDoc::WriteLargePolygonLayer(ostream& Out)
{
// Then the data, begin with original layer
Out << " <g\n";
Out << " inkscape:label=\"Large_Polygon_Layer\"" << endl;
Out << " inkscape:groupmode=\"layer\"" << endl;
Out << " id=\"LargePolygon_Layer1\">" << endl;
int nShape = 0;
Out << std::fixed;
Out << std::setprecision(6);
for (NSVGshape *shape = SvgData->shapes; shape != NULL; shape = shape->next, nShape++)
{
// Then for each path in the shape
int iPath = 0;
for (NSVGpath *path = shape->paths; path != NULL; path = path->next, iPath++)
{
Polygon *poly_path = path->LargePolygon;
if ( poly_path == NULL ) continue;
Out << " <path" << endl;
// Line style : Blue
Out << " style=\"fill:none;stroke:#0000FF;stroke-width:" << shape->strokeWidth << "\"" << endl;
// Then path itself
Out << " d=\"M " << poly_path->GetVertex(0)->x << "," << poly_path->GetVertex(0)->y;
for (int i = 1; i < poly_path->nVertices; i++)
{
Out << " L " << poly_path->GetVertex(i)->x << "," << poly_path->GetVertex(i)->y;
}
if ( path->closed == 1 )
{
Out << " z";
}
Out << "\"" << endl;
Out << " id=\"Largepoly_" << shape->id << "_" << iPath << "\"" << endl;
Out << " inkscape:connector-curvature=\"0\" />" << endl;
}
}
Out << " </g>" << endl;
}
// Write Hull to output file
void SvgDoc::WriteHullLargePolygonLayer(ostream& Out)
{
// Then the data, begin with original layer
Out << " <g\n";
Out << " inkscape:label=\"Hull_Placed_Layer\"" << endl;
Out << " inkscape:groupmode=\"layer\"" << endl;
Out << " id=\"Hull_Placed_Layer1\">" << endl;
int nShape = 0;
Out << std::fixed;
Out << std::setprecision(6);
for (NSVGshape *shape = SvgData->shapes; shape != NULL; shape = shape->next, nShape++)
{
// Then for each path in the shape
int iPath = 0;
for (NSVGpath *path = shape->paths; path != NULL; path = path->next, iPath++)
{
Polygon *poly_path = path->LargeConvexHull;
if ( poly_path == NULL ) continue;
Out << " <path" << endl;
// Line style : Green
Out << " style=\"fill:none;stroke:#00FF00;stroke-width:" << shape->strokeWidth << "\"" << endl;
// Then path itself
Out << " d=\"M " << poly_path->GetVertex(0)->x << "," << poly_path->GetVertex(0)->y;
for (int i = 1; i < poly_path->nVertices; i++)
{
Out << " L " << poly_path->GetVertex(i)->x << "," << poly_path->GetVertex(i)->y;
}
if ( path->closed == 1 )
{
Out << " z";
}
Out << "\"" << endl;
Out << " id=\"Hull_" << shape->id << "_" << iPath << "\"" << endl;
Out << " inkscape:connector-curvature=\"0\" />" << endl;
}
}
Out << " </g>" << endl;
}
// Write Placed POLYGON layer to output file
void SvgDoc::WritePlacedPolygonLayer(ostream& Out)
{
// Then the data, begin with original layer
Out << " <g\n";
Out << " inkscape:label=\"Placed_Polygon_Layer\"" << endl;
Out << " inkscape:groupmode=\"layer\"" << endl;
Out << " id=\"Placed_Polygon_Layer1\">" << endl;
int nShape = 0;
Out << std::fixed;
Out << std::setprecision(6);
for (NSVGshape *shape = SvgData->shapes; shape != NULL; shape = shape->next, nShape++)
{
// Then for each path in the shape
int iPath = 0;
for (NSVGpath *path = shape->paths; path != NULL; path = path->next, iPath++)
{
Polygon *poly_path = path->PlacedPolygon;
if ( poly_path == NULL ) continue;
Out << " <path" << endl;
// Line style : Magenta
Out << " style=\"fill:none;stroke:#FF00FF;stroke-width:" << shape->strokeWidth << "\"" << endl;
// Then path itself
Out << " d=\"M " << poly_path->GetVertex(0)->x << "," << poly_path->GetVertex(0)->y;
for (int i = 1; i < poly_path->nVertices; i++)
{
Out << " L " << poly_path->GetVertex(i)->x << "," << poly_path->GetVertex(i)->y;
}
if ( path->closed == 1 )
{
Out << " z";
}
Out << "\"" << endl;
Out << " id=\"PP_" << shape->id << "_" << iPath << "\"" << endl;
Out << " inkscape:connector-curvature=\"0\" />" << endl;
}
}
Out << " </g>" << endl;
}
// Write the result to output stream
void SvgDoc::WritePlacedLayer(ostream& Out)
{
Out << " <g\n";
Out << " inkscape:label=\"Placed_Layer\"" << endl;
Out << " inkscape:groupmode=\"layer\"" << endl;
Out << " id=\"Placed_Layer1\">" << endl;
int nShape = 0;
Out << std::fixed;
Out << std::setprecision(6);
for (NSVGshape *shape = SvgData->shapes; shape != NULL; shape = shape->next, nShape++)
{
// Then for each path in the shape
int iPath = 0;
for (NSVGpath *path = shape->paths; path != NULL; path = path->next, iPath++)
{
if ( path->PlacedPolygon == NULL ) continue;
WritePlacedPath(Out, path, path, shape, iPath);
int iChild = 10000 - iPath * 100 - 1;
for ( NSVGpath *path_child = path->child; path_child != NULL; path_child = path_child->next, iChild--)
{
WritePlacedPath(Out, path, path_child, shape, iChild);
}
}
}
Out << " </g>" << endl;
}
// Write SVG header
void SvgDoc::WriteHeader(ostream &Out)
{
Out << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n";
Out << "<!-- Created with CutOptim (http://www.fablab-lannion.org/) -->\n";
Out << "\n";
Out << "<svg\n";
Out << " xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n";
Out << " xmlns:cc=\"http://creativecommons.org/ns#\"\n";
Out << " xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n";
Out << " xmlns:svg=\"http://www.w3.org/2000/svg\"\n";
Out << " xmlns=\"http://www.w3.org/2000/svg\"\n";
Out << " xmlns:sodipodi=\"http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd\"\n";
Out << " xmlns:inkscape=\"http://www.inkscape.org/namespaces/inkscape\"\n";
Out << " width=\"" << round(SheetSizeX) << "mm\"" << endl;
Out << " height=\"" << round(SheetSizeY) << "mm\"\n";
Out << " viewBox=\"0 0 " << round(SheetSizeX) << " " << round(SheetSizeY) << "\"" << endl;
Out << " version=\"1.1\"\n";
Out << " id=\"svg8\"\n";
Out << " sodipodi:docname=\"" << Name << "\">" << endl;
Out << " <defs\n";
Out << " id=\"defs2\" />\n";
Out << " <sodipodi:namedview\n";
Out << " id=\"base\"\n";
Out << " pagecolor=\"#ffffff\"\n";
Out << " bordercolor=\"#666666\"\n";
Out << " borderopacity=\"1.0\"\n";
Out << " inkscape:pageopacity=\"0.0\"\n";
Out << " inkscape:pageshadow=\"2\"\n";
Out << " inkscape:document-units=\"mm\"\n";
Out << " inkscape:current-layer=\"Placed_Layer\"\n";
Out << " showgrid=\"false\"\n";
Out << " inkscape:window-maximized=\"1\" />\n";
Out << " <metadata\n";
Out << " id=\"metadata5\">\n";
Out << " <rdf:RDF>\n";
Out << " <cc:Work\n";
Out << " rdf:about=\"\">\n";
Out << " <dc:format>image/svg+xml</dc:format>\n";
Out << " <dc:type\n";
Out << " rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\" />\n";
Out << " <dc:title></dc:title>\n";
Out << " </cc:Work>\n";
Out << " </rdf:RDF>\n";
Out << " </metadata>\n";
}
void SvgDoc::WriteFile(ostream &Out, int output_layers)
{
WriteHeader(Out);
if ( output_layers & 1 ) // Original layer
WriteOrginalLayer(Out);
if ( output_layers & 2 ) // Close Polygon layer
WritePolygonLayer(Out);
if ( output_layers & 4 ) // Large Polygon layer
WriteLargePolygonLayer(Out);
if ( output_layers & 8 ) // Hull Placed layer
WriteHullLargePolygonLayer(Out);
if ( output_layers & 16 ) // Placed Polygon layer
WritePlacedPolygonLayer(Out);
WritePlacedLayer(Out);
Out << "</svg>" << endl;
}
int SvgDoc::WriteDoc(string &FileName, int FlagFile, int Output_Layers)
{
ofstream Out;
if ( SvgData == NULL ) return(0);
if ( FlagFile )
{
Out.open(FileName.c_str());
if ( !Out.is_open() ) return(0);
WriteFile(Out, Output_Layers);
Out.close();
}
else
WriteFile(cout, Output_Layers);
return 1;
}