KiCad PCB EDA Suite
Loading...
Searching...
No Matches
SVG_plotter.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 2020 Jean-Pierre Charras, jp.charras at wanadoo.fr
5 * Copyright (C) 1992-2023 KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, you may find one here:
19 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
20 * or you may search the http://www.gnu.org website for the version 2 license,
21 * or you may write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 */
24
25/* Some info on basic items SVG format, used here:
26 * The root element of all SVG files is the <svg> element.
27 *
28 * The <g> element is used to group SVG shapes together.
29 * Once grouped you can transform the whole group of shapes as if it was a single shape.
30 * This is an advantage compared to a nested <svg> element
31 * which cannot be the target of transformation by itself.
32 *
33 * The <rect> element represents a rectangle.
34 * Using this element you can draw rectangles of various width, height,
35 * with different stroke (outline) and fill colors, with sharp or rounded corners etc.
36 *
37 * <svg xmlns="http://www.w3.org/2000/svg"
38 * xmlns:xlink="http://www.w3.org/1999/xlink">
39 *
40 * <rect x="10" y="10" height="100" width="100"
41 * style="stroke:#006600; fill: #00cc00"/>
42 *
43 * </svg>
44 *
45 * The <circle> element is used to draw circles.
46 * <circle cx="40" cy="40" r="24" style="stroke:#006600; fill:#00cc00"/>
47 *
48 * The <ellipse> element is used to draw ellipses.
49 * An ellipse is a circle that does not have equal height and width.
50 * Its radius in the x and y directions are different, in other words.
51 * <ellipse cx="40" cy="40" rx="30" ry="15"
52 * style="stroke:#006600; fill:#00cc00"/>
53 *
54 * The <line> element is used to draw lines.
55 *
56 * <line x1="0" y1="10" x2="0" y2="100" style="stroke:#006600;"/>
57 * <line x1="10" y1="10" x2="100" y2="100" style="stroke:#006600;"/>
58 *
59 * The <polyline> element is used to draw multiple connected lines
60 * Here is a simple example:
61 *
62 * <polyline points="0,0 30,0 15,30" style="stroke:#006600;"/>
63 *
64 * The <polygon> element is used to draw with multiple (3 or more) sides / edges.
65 * Here is a simple example:
66 *
67 * <polygon points="0,0 50,0 25,50" style="stroke:#660000; fill:#cc3333;"/>
68 *
69 * The <path> element is used to draw advanced shapes combined from lines and arcs,
70 * with or without fill.
71 * It is probably the most advanced and versatile SVG shape of them all.
72 * It is probably also the hardest element to master.
73 * <path d="M50,50
74 * A30,30 0 0,1 35,20
75 * L100,100
76 * M110,110
77 * L100,0"
78 * style="stroke:#660000; fill:none;"/>
79 *
80 * Draw an elliptic arc: it is one of basic path command:
81 * <path d="M(startx,starty) A(radiusx,radiusy)
82 * rotation-axe-x
83 * flag_arc_large,flag_sweep endx,endy">
84 * flag_arc_large: 0 = small arc > 180 deg, 1 = large arc > 180 deg
85 * flag_sweep : 0 = CCW, 1 = CW
86 * The center of ellipse is automatically calculated.
87 */
88
89#include <core/base64.h>
90#include <eda_shape.h>
91#include <string_utils.h>
92#include <font/font.h>
93#include <macros.h>
94#include <trigo.h>
95
96#include <cstdint>
97#include <wx/mstream.h>
98
100
101// Note:
102// During tests, we (JPC) found issues when the coordinates used 6 digits in mantissa
103// especially for stroke-width using very small (but not null) values < 0.00001 mm
104// So to avoid this king of issue, we are using 4 digits in mantissa
105// The resolution (m_precision ) is 0.1 micron, that looks enougt for a SVG file
106
112static wxString XmlEsc( const wxString& aStr, bool isAttribute = false )
113{
114 wxString escaped;
115
116 escaped.reserve( aStr.length() );
117
118 for( wxString::const_iterator it = aStr.begin(); it != aStr.end(); ++it )
119 {
120 const wxChar c = *it;
121
122 switch( c )
123 {
124 case wxS( '<' ):
125 escaped.append( wxS( "&lt;" ) );
126 break;
127 case wxS( '>' ):
128 escaped.append( wxS( "&gt;" ) );
129 break;
130 case wxS( '&' ):
131 escaped.append( wxS( "&amp;" ) );
132 break;
133 case wxS( '\r' ):
134 escaped.append( wxS( "&#xD;" ) );
135 break;
136 default:
137 if( isAttribute )
138 {
139 switch( c )
140 {
141 case wxS( '"' ):
142 escaped.append( wxS( "&quot;" ) );
143 break;
144 case wxS( '\t' ):
145 escaped.append( wxS( "&#x9;" ) );
146 break;
147 case wxS( '\n' ):
148 escaped.append( wxS( "&#xA;" ));
149 break;
150 default:
151 escaped.append(c);
152 }
153 }
154 else
155 {
156 escaped.append(c);
157 }
158 }
159 }
160
161 return escaped;
162}
163
164
166{
167 m_graphics_changed = true;
168 SetTextMode( PLOT_TEXT_MODE::STROKE );
169 m_fillMode = FILL_T::NO_FILL; // or FILLED_SHAPE or FILLED_WITH_BG_BODYCOLOR
170 m_pen_rgb_color = 0; // current color value (black)
171 m_brush_rgb_color = 0; // current color value (black)
172 m_brush_alpha = 1.0;
173 m_dashed = PLOT_DASH_TYPE::SOLID;
174 m_precision = 4; // default: 4 digits in mantissa.
175}
176
177
178void SVG_PLOTTER::SetViewport( const VECTOR2I& aOffset, double aIusPerDecimil,
179 double aScale, bool aMirror )
180{
181 m_plotMirror = aMirror;
182 m_yaxisReversed = true; // unlike other plotters, SVG has Y axis reversed
183 m_plotOffset = aOffset;
184 m_plotScale = aScale;
185 m_IUsPerDecimil = aIusPerDecimil;
186
187 // Compute the paper size in IUs. for historical reasons the page size is in mils
189 m_paperSize.x *= 10.0 * aIusPerDecimil;
190 m_paperSize.y *= 10.0 * aIusPerDecimil;
191
192 // gives now a default value to iuPerDeviceUnit (because the units of the caller is now known)
193 double iusPerMM = m_IUsPerDecimil / 2.54 * 1000;
194 m_iuPerDeviceUnit = 1 / iusPerMM;
195
197}
198
199
200void SVG_PLOTTER::SetSvgCoordinatesFormat( unsigned aPrecision )
201{
202 // Only number of digits in mantissa are adjustable.
203 // SVG units are always mm
204 m_precision = aPrecision;
205}
206
207
209{
210 if( m_fillMode != fill )
211 {
212 m_graphics_changed = true;
213 m_fillMode = fill;
214 }
215}
216
217
218void SVG_PLOTTER::setSVGPlotStyle( int aLineWidth, bool aIsGroup, const std::string& aExtraStyle )
219{
220 if( aIsGroup )
221 fputs( "</g>\n<g ", m_outputFile );
222
223 // output the background fill color
224 fprintf( m_outputFile, "style=\"fill:#%6.6lX; ", m_brush_rgb_color );
225
226 switch( m_fillMode )
227 {
228 case FILL_T::NO_FILL:
229 fputs( "fill-opacity:0.0; ", m_outputFile );
230 break;
231
232 case FILL_T::FILLED_SHAPE:
233 case FILL_T::FILLED_WITH_BG_BODYCOLOR:
234 case FILL_T::FILLED_WITH_COLOR:
235 fprintf( m_outputFile, "fill-opacity:%.*f; ", m_precision, m_brush_alpha );
236 break;
237 }
238
239 double pen_w = userToDeviceSize( aLineWidth );
240
241 if( pen_w < 0.0 ) // Ensure pen width validity
242 pen_w = 0.0;
243
244 // Fix a strange issue found in Inkscape: aWidth < 100 nm create issues on degrouping objects
245 // So we use only 4 digits in mantissa for stroke-width.
246 // TODO: perhaps used only 3 or 4 digits in mantissa for all values in mm, because some
247 // issues were previously reported reported when using nm as integer units
248
249 fprintf( m_outputFile, "\nstroke:#%6.6lX; stroke-width:%.*f; stroke-opacity:1; \n",
251 fputs( "stroke-linecap:round; stroke-linejoin:round;", m_outputFile );
252
253 //set any extra attributes for non-solid lines
254 switch( m_dashed )
255 {
256 case PLOT_DASH_TYPE::DASH:
257 fprintf( m_outputFile, "stroke-dasharray:%.*f,%.*f;",
258 m_precision, GetDashMarkLenIU( aLineWidth ),
259 m_precision, GetDashGapLenIU( aLineWidth ) );
260 break;
261
262 case PLOT_DASH_TYPE::DOT:
263 fprintf( m_outputFile, "stroke-dasharray:%f,%f;",
264 GetDotMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ) );
265 break;
266
267 case PLOT_DASH_TYPE::DASHDOT:
268 fprintf( m_outputFile, "stroke-dasharray:%f,%f,%f,%f;",
269 GetDashMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ),
270 GetDotMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ) );
271 break;
272
273 case PLOT_DASH_TYPE::DASHDOTDOT:
274 fprintf( m_outputFile, "stroke-dasharray:%f,%f,%f,%f,%f,%f;",
275 GetDashMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ),
276 GetDotMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ),
277 GetDotMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ) );
278 break;
279
280 case PLOT_DASH_TYPE::DEFAULT:
281 case PLOT_DASH_TYPE::SOLID:
282 default:
283 //do nothing
284 break;
285 }
286
287 if( aExtraStyle.length() )
288 fputs( aExtraStyle.c_str(), m_outputFile );
289
290 fputs( "\"", m_outputFile );
291
292 if( aIsGroup )
293 {
294 fputs( ">", m_outputFile );
295 m_graphics_changed = false;
296 }
297
298 fputs( "\n", m_outputFile );
299}
300
301
302void SVG_PLOTTER::SetCurrentLineWidth( int aWidth, void* aData )
303{
304 if( aWidth == DO_NOT_SET_LINE_WIDTH )
305 return;
306 else if( aWidth == USE_DEFAULT_LINE_WIDTH )
308
309 // Note: aWidth == 0 is fine: used for filled shapes with no outline thickness
310
311 wxASSERT_MSG( aWidth >= 0, "Plotter called to set negative pen width" );
312
313 if( aWidth != m_currentPenWidth )
314 {
315 m_graphics_changed = true;
316 m_currentPenWidth = aWidth;
317 }
318}
319
320
321void SVG_PLOTTER::StartBlock( void* aData )
322{
323 // We can't use <g></g> for blocks because we're already using it for graphics context, and
324 // our graphics context handling is lazy (ie: it leaves the last group open until the context
325 // changes).
326}
327
328
329void SVG_PLOTTER::EndBlock( void* aData )
330{
331}
332
333
334void SVG_PLOTTER::emitSetRGBColor( double r, double g, double b, double a )
335{
336 int red = (int) ( 255.0 * r );
337 int green = (int) ( 255.0 * g );
338 int blue = (int) ( 255.0 * b );
339 long rgb_color = (red << 16) | (green << 8) | blue;
340
341 if( m_pen_rgb_color != rgb_color )
342 {
343 m_graphics_changed = true;
344 m_pen_rgb_color = rgb_color;
345
346 // Currently, use the same color for brush and pen (i.e. to draw and fill a contour).
347 m_brush_rgb_color = rgb_color;
348 m_brush_alpha = a;
349 }
350}
351
352
353void SVG_PLOTTER::SetDash( int aLineWidth, PLOT_DASH_TYPE aLineStyle )
354{
355 if( m_dashed != aLineStyle )
356 {
357 m_graphics_changed = true;
358 m_dashed = aLineStyle;
359 }
360}
361
362
363void SVG_PLOTTER::Rect( const VECTOR2I& p1, const VECTOR2I& p2, FILL_T fill, int width )
364{
365 BOX2I rect( p1, VECTOR2I( p2.x - p1.x, p2.y - p1.y ) );
366 rect.Normalize();
367
368 VECTOR2D org_dev = userToDeviceCoordinates( rect.GetOrigin() );
369 VECTOR2D end_dev = userToDeviceCoordinates( rect.GetEnd() );
370 VECTOR2D size_dev = end_dev - org_dev;
371
372 // Ensure size of rect in device coordinates is > 0
373 // I don't know if this is a SVG issue or a Inkscape issue, but
374 // Inkscape has problems with negative or null values for width and/or height, so avoid them
375 BOX2D rect_dev( org_dev, size_dev );
376 rect_dev.Normalize();
377
378 setFillMode( fill );
379 SetCurrentLineWidth( width );
380
383
384 // Rectangles having a 0 size value for height or width are just not drawn on Inkscape,
385 // so use a line when happens.
386 if( rect_dev.GetSize().x == 0.0 || rect_dev.GetSize().y == 0.0 ) // Draw a line
387 {
388 fprintf( m_outputFile,
389 "<line x1=\"%.*f\" y1=\"%.*f\" x2=\"%.*f\" y2=\"%.*f\" />\n",
390 m_precision, rect_dev.GetPosition().x, m_precision, rect_dev.GetPosition().y,
391 m_precision, rect_dev.GetEnd().x, m_precision, rect_dev.GetEnd().y );
392 }
393 else
394 {
395 fprintf( m_outputFile,
396 "<rect x=\"%f\" y=\"%f\" width=\"%f\" height=\"%f\" rx=\"%f\" />\n",
397 rect_dev.GetPosition().x, rect_dev.GetPosition().y,
398 rect_dev.GetSize().x, rect_dev.GetSize().y,
399 0.0 /* radius of rounded corners */ );
400 }
401}
402
403
404void SVG_PLOTTER::Circle( const VECTOR2I& pos, int diametre, FILL_T fill, int width )
405{
406 VECTOR2D pos_dev = userToDeviceCoordinates( pos );
407 double radius = userToDeviceSize( diametre / 2.0 );
408
409 setFillMode( fill );
410 SetCurrentLineWidth( width );
411
414
415 // If diameter is less than width, switch to filled mode
416 if( fill == FILL_T::NO_FILL && diametre < width )
417 {
418 setFillMode( FILL_T::FILLED_SHAPE );
420
421 radius = userToDeviceSize( ( diametre / 2.0 ) + ( width / 2.0 ) );
422 }
423
424 fprintf( m_outputFile,
425 "<circle cx=\"%.*f\" cy=\"%.*f\" r=\"%.*f\" /> \n",
426 m_precision, pos_dev.x, m_precision, pos_dev.y, m_precision, radius );
427}
428
429
430void SVG_PLOTTER::Arc( const VECTOR2D& aCenter, const EDA_ANGLE& aStartAngle,
431 const EDA_ANGLE& aAngle, double aRadius, FILL_T aFill, int aWidth )
432{
433 /* Draws an arc of a circle, centered on (xc,yc), with starting point (x1, y1) and ending
434 * at (x2, y2). The current pen is used for the outline and the current brush for filling
435 * the shape.
436 *
437 * The arc is drawn in an anticlockwise direction from the start point to the end point.
438 */
439
440 if( aRadius <= 0 )
441 {
442 Circle( aCenter, aWidth, FILL_T::FILLED_SHAPE, 0 );
443 return;
444 }
445
446 EDA_ANGLE startAngle = -aStartAngle;
447 EDA_ANGLE endAngle = startAngle - aAngle;
448
449 if( endAngle < startAngle )
450 std::swap( startAngle, endAngle );
451
452 // Calculate start point.
453 VECTOR2D centre_device = userToDeviceCoordinates( aCenter );
454 double radius_device = userToDeviceSize( aRadius );
455
456 if( m_plotMirror )
457 {
459 {
460 std::swap( startAngle, endAngle );
461 startAngle = ANGLE_180 - startAngle;
462 endAngle = ANGLE_180 - endAngle;
463 }
464 else
465 {
466 startAngle = -startAngle;
467 endAngle = -endAngle;
468 }
469 }
470
471 VECTOR2D start;
472 start.x = radius_device;
473 RotatePoint( start, startAngle );
474 VECTOR2D end;
475 end.x = radius_device;
476 RotatePoint( end, endAngle );
477 start += centre_device;
478 end += centre_device;
479
480 double theta1 = startAngle.AsRadians();
481
482 if( theta1 < 0 )
483 theta1 = theta1 + M_PI * 2;
484
485 double theta2 = endAngle.AsRadians();
486
487 if( theta2 < 0 )
488 theta2 = theta2 + M_PI * 2;
489
490 if( theta2 < theta1 )
491 theta2 = theta2 + M_PI * 2;
492
493 int flg_arc = 0; // flag for large or small arc. 0 means less than 180 degrees
494
495 if( fabs( theta2 - theta1 ) > M_PI )
496 flg_arc = 1;
497
498 int flg_sweep = 0; // flag for sweep always 0
499
500 // Draw a single arc: an arc is one of 3 curve commands (2 other are 2 bezier curves)
501 // params are start point, radius1, radius2, X axe rotation,
502 // flag arc size (0 = small arc > 180 deg, 1 = large arc > 180 deg),
503 // sweep arc ( 0 = CCW, 1 = CW),
504 // end point
505 if( aFill != FILL_T::NO_FILL )
506 {
507 // Filled arcs (in Eeschema) consist of the pie wedge and a stroke only on the arc
508 // This needs to be drawn in two steps.
509 setFillMode( aFill );
511
514
515 fprintf( m_outputFile, "<path d=\"M%.*f %.*f A%.*f %.*f 0.0 %d %d %.*f %.*f L %.*f %.*f Z\" />\n",
516 m_precision, start.x, m_precision, start.y,
517 m_precision, radius_device, m_precision, radius_device,
518 flg_arc, flg_sweep,
519 m_precision, end.x, m_precision, end.y,
520 m_precision, centre_device.x, m_precision, centre_device.y );
521 }
522
523 setFillMode( FILL_T::NO_FILL );
524 SetCurrentLineWidth( aWidth );
525
528
529 fprintf( m_outputFile, "<path d=\"M%.*f %.*f A%.*f %.*f 0.0 %d %d %.*f %.*f\" />\n",
530 m_precision, start.x, m_precision, start.y,
531 m_precision, radius_device, m_precision, radius_device,
532 flg_arc, flg_sweep,
533 m_precision, end.x, m_precision, end.y );
534}
535
536
537void SVG_PLOTTER::BezierCurve( const VECTOR2I& aStart, const VECTOR2I& aControl1,
538 const VECTOR2I& aControl2, const VECTOR2I& aEnd,
539 int aTolerance, int aLineThickness )
540{
541#if 1
542 setFillMode( FILL_T::NO_FILL );
543 SetCurrentLineWidth( aLineThickness );
544
547
548 VECTOR2D start = userToDeviceCoordinates( aStart );
549 VECTOR2D ctrl1 = userToDeviceCoordinates( aControl1 );
550 VECTOR2D ctrl2 = userToDeviceCoordinates( aControl2 );
551 VECTOR2D end = userToDeviceCoordinates( aEnd );
552
553 // Generate a cubic curve: start point and 3 other control points.
554 fprintf( m_outputFile, "<path d=\"M%.*f,%.*f C%.*f,%.*f %.*f,%.*f %.*f,%.*f\" />\n",
555 m_precision, start.x, m_precision, start.y,
556 m_precision, ctrl1.x, m_precision, ctrl1.y,
557 m_precision, ctrl2.x, m_precision, ctrl2.y,
558 m_precision, end.x, m_precision, end.y );
559#else
560 PLOTTER::BezierCurve( aStart, aControl1, aControl2, aEnd, aTolerance, aLineThickness );
561#endif
562}
563
564
565void SVG_PLOTTER::PlotPoly( const std::vector<VECTOR2I>& aCornerList, FILL_T aFill,
566 int aWidth, void* aData )
567{
568 if( aCornerList.size() <= 1 )
569 return;
570
571 setFillMode( aFill );
572 SetCurrentLineWidth( aWidth );
573 fprintf( m_outputFile, "<path ");
574
575 switch( aFill )
576 {
577 case FILL_T::NO_FILL:
578 setSVGPlotStyle( aWidth, false, "fill:none" );
579 break;
580
581 case FILL_T::FILLED_WITH_BG_BODYCOLOR:
582 case FILL_T::FILLED_SHAPE:
583 case FILL_T::FILLED_WITH_COLOR:
584 setSVGPlotStyle( aWidth, false, "fill-rule:evenodd;" );
585 break;
586 }
587
588 VECTOR2D pos = userToDeviceCoordinates( aCornerList[0] );
589 fprintf( m_outputFile, "d=\"M %.*f,%.*f\n", m_precision, pos.x, m_precision, pos.y );
590
591 for( unsigned ii = 1; ii < aCornerList.size() - 1; ii++ )
592 {
593 pos = userToDeviceCoordinates( aCornerList[ii] );
594 fprintf( m_outputFile, "%.*f,%.*f\n", m_precision, pos.x, m_precision, pos.y );
595 }
596
597 // If the corner list ends where it begins, then close the poly
598 if( aCornerList.front() == aCornerList.back() )
599 {
600 fprintf( m_outputFile, "Z\" /> \n" );
601 }
602 else
603 {
604 pos = userToDeviceCoordinates( aCornerList.back() );
605 fprintf( m_outputFile, "%.*f,%.*f\n\" /> \n", m_precision, pos.x, m_precision, pos.y );
606 }
607}
608
609
610void SVG_PLOTTER::PlotImage( const wxImage& aImage, const VECTOR2I& aPos, double aScaleFactor )
611{
612 VECTOR2I pix_size( aImage.GetWidth(), aImage.GetHeight() );
613
614 // Requested size (in IUs)
615 VECTOR2D drawsize( aScaleFactor * pix_size.x, aScaleFactor * pix_size.y );
616
617 // calculate the bitmap start position
618 VECTOR2I start( aPos.x - drawsize.x / 2, aPos.y - drawsize.y / 2 );
619
620 // Rectangles having a 0 size value for height or width are just not drawn on Inkscape,
621 // so use a line when happens.
622 if( drawsize.x == 0.0 || drawsize.y == 0.0 ) // Draw a line
623 {
624 PLOTTER::PlotImage( aImage, aPos, aScaleFactor );
625 }
626 else
627 {
628 wxMemoryOutputStream img_stream;
629
630 if( m_colorMode )
631 {
632 aImage.SaveFile( img_stream, wxBITMAP_TYPE_PNG );
633 }
634 else // Plot in B&W
635 {
636 wxImage image = aImage.ConvertToGreyscale();
637 image.SaveFile( img_stream, wxBITMAP_TYPE_PNG );
638 }
639 size_t input_len = img_stream.GetOutputStreamBuffer()->GetBufferSize();
640 std::vector<uint8_t> buffer( input_len );
641 std::vector<uint8_t> encoded;
642
643 img_stream.CopyTo( buffer.data(), buffer.size() );
644 base64::encode( buffer, encoded );
645
646 fprintf( m_outputFile,
647 "<image x=\"%f\" y=\"%f\" xlink:href=\"data:image/png;base64,",
648 userToDeviceSize( start.x ), userToDeviceSize( start.y ) );
649
650 for( size_t i = 0; i < encoded.size(); i++ )
651 {
652 fprintf( m_outputFile, "%c", static_cast<char>( encoded[i] ) );
653
654 if( ( i % 64 ) == 63 )
655 fprintf( m_outputFile, "\n" );
656 }
657
658 fprintf( m_outputFile, "\"\npreserveAspectRatio=\"none\" width=\"%.*f\" height=\"%.*f\" />",
659 m_precision, userToDeviceSize( drawsize.x ), m_precision, userToDeviceSize( drawsize.y ) );
660 }
661}
662
663
664void SVG_PLOTTER::PenTo( const VECTOR2I& pos, char plume )
665{
666 if( plume == 'Z' )
667 {
668 if( m_penState != 'Z' )
669 {
670 fputs( "\" />\n", m_outputFile );
671 m_penState = 'Z';
672 m_penLastpos.x = -1;
673 m_penLastpos.y = -1;
674 }
675
676 return;
677 }
678
679 if( m_penState == 'Z' ) // here plume = 'D' or 'U'
680 {
681 VECTOR2D pos_dev = userToDeviceCoordinates( pos );
682
683 // Ensure we do not use a fill mode when moving the pen,
684 // in SVG mode (i;e. we are plotting only basic lines, not a filled area
685 if( m_fillMode != FILL_T::NO_FILL )
686 setFillMode( FILL_T::NO_FILL );
687
690
691 fprintf( m_outputFile, "<path d=\"M%.*f %.*f\n",
692 m_precision, pos_dev.x,
693 m_precision, pos_dev.y );
694 }
695 else if( m_penState != plume || pos != m_penLastpos )
696 {
699
700 VECTOR2D pos_dev = userToDeviceCoordinates( pos );
701
702 fprintf( m_outputFile, "L%.*f %.*f\n",
703 m_precision, pos_dev.x,
704 m_precision, pos_dev.y );
705 }
706
707 m_penState = plume;
708 m_penLastpos = pos;
709}
710
711
712bool SVG_PLOTTER::StartPlot( const wxString& aPageNumber )
713{
714 wxASSERT( m_outputFile );
715
716 static const char* header[] =
717 {
718 "<?xml version=\"1.0\" standalone=\"no\"?>\n",
719 " <!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \n",
720 " \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"> \n",
721 "<svg\n"
722 " xmlns:svg=\"http://www.w3.org/2000/svg\"\n"
723 " xmlns=\"http://www.w3.org/2000/svg\"\n",
724 " xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n",
725 " version=\"1.1\"\n",
726 nullptr
727 };
728
729 // Write header.
730 for( int ii = 0; header[ii] != nullptr; ii++ )
731 {
732 fputs( header[ii], m_outputFile );
733 }
734
735 // Write viewport pos and size
736 VECTOR2D origin; // TODO set to actual value
737 fprintf( m_outputFile, " width=\"%.*fmm\" height=\"%.*fmm\" viewBox=\"%.*f %.*f %.*f %.*f\">\n",
738 m_precision, (double) m_paperSize.x / m_IUsPerDecimil * 2.54 / 1000,
739 m_precision, (double) m_paperSize.y / m_IUsPerDecimil * 2.54 / 1000,
740 m_precision, origin.x, m_precision, origin.y,
743
744 // Write title
745 char date_buf[250];
746 time_t ltime = time( nullptr );
747 strftime( date_buf, 250, "%Y/%m/%d %H:%M:%S", localtime( &ltime ) );
748
749 fprintf( m_outputFile,
750 "<title>SVG Image created as %s date %s </title>\n",
751 TO_UTF8( XmlEsc( wxFileName( m_filename ).GetFullName() ) ), date_buf );
752
753 // End of header
754 fprintf( m_outputFile, " <desc>Image generated by %s </desc>\n",
755 TO_UTF8( XmlEsc( m_creator ) ) );
756
757 // output the pen and brush color (RVB values in hex) and opacity
758 double opacity = 1.0; // 0.0 (transparent to 1.0 (solid)
759 fprintf( m_outputFile,
760 "<g style=\"fill:#%6.6lX; fill-opacity:%.*f;stroke:#%6.6lX; stroke-opacity:%.*f;\n",
762
763 // output the pen cap and line joint
764 fputs( "stroke-linecap:round; stroke-linejoin:round;\"\n", m_outputFile );
765 fputs( " transform=\"translate(0 0) scale(1 1)\">\n", m_outputFile );
766 return true;
767}
768
769
771{
772 fputs( "</g> \n</svg>\n", m_outputFile );
773 fclose( m_outputFile );
774 m_outputFile = nullptr;
775
776 return true;
777}
778
779
780void SVG_PLOTTER::Text( const VECTOR2I& aPos,
781 const COLOR4D& aColor,
782 const wxString& aText,
783 const EDA_ANGLE& aOrient,
784 const VECTOR2I& aSize,
785 enum GR_TEXT_H_ALIGN_T aH_justify,
786 enum GR_TEXT_V_ALIGN_T aV_justify,
787 int aWidth,
788 bool aItalic,
789 bool aBold,
790 bool aMultilineAllowed,
791 KIFONT::FONT* aFont,
792 const KIFONT::METRICS& aFontMetrics,
793 void* aData )
794{
795 setFillMode( FILL_T::NO_FILL );
796 SetColor( aColor );
797 SetCurrentLineWidth( aWidth );
798
801
802 VECTOR2I text_pos = aPos;
803 const char* hjust = "start";
804
805 switch( aH_justify )
806 {
807 case GR_TEXT_H_ALIGN_CENTER: hjust = "middle"; break;
808 case GR_TEXT_H_ALIGN_RIGHT: hjust = "end"; break;
809 case GR_TEXT_H_ALIGN_LEFT: hjust = "start"; break;
810 }
811
812 switch( aV_justify )
813 {
814 case GR_TEXT_V_ALIGN_CENTER: text_pos.y += aSize.y / 2; break;
815 case GR_TEXT_V_ALIGN_TOP: text_pos.y += aSize.y; break;
816 case GR_TEXT_V_ALIGN_BOTTOM: break;
817 }
818
819 VECTOR2I text_size;
820
821 // aSize.x or aSize.y is < 0 for mirrored texts.
822 // The actual text size value is the absolute value
823 text_size.x = std::abs( GRTextWidth( aText, aFont, aSize, aWidth, aBold, aItalic, aFontMetrics ) );
824 text_size.y = std::abs( aSize.x * 4/3 ); // Hershey font height to em size conversion
825 VECTOR2D anchor_pos_dev = userToDeviceCoordinates( aPos );
826 VECTOR2D text_pos_dev = userToDeviceCoordinates( text_pos );
827 VECTOR2D sz_dev = userToDeviceSize( text_size );
828
829 if( !aOrient.IsZero() )
830 {
831 fprintf( m_outputFile, "<g transform=\"rotate(%f %.*f %.*f)\">\n",
832 m_plotMirror ? aOrient.AsDegrees() : -aOrient.AsDegrees(), m_precision,
833 anchor_pos_dev.x, m_precision, anchor_pos_dev.y );
834 }
835
836 fprintf( m_outputFile, "<text x=\"%.*f\" y=\"%.*f\"\n",
837 m_precision, text_pos_dev.x, m_precision, text_pos_dev.y );
838
840 if( m_plotMirror != ( aSize.x < 0 ) )
841 fprintf( m_outputFile, "transform=\"scale(-1 1) translate(%f 0)\"\n", -2 * text_pos_dev.x );
842
843 fprintf( m_outputFile,
844 "textLength=\"%.*f\" font-size=\"%.*f\" lengthAdjust=\"spacingAndGlyphs\"\n"
845 "text-anchor=\"%s\" opacity=\"0\">%s</text>\n",
846 m_precision, sz_dev.x, m_precision, sz_dev.y, hjust, TO_UTF8( XmlEsc( aText ) ) );
847
848 if( !aOrient.IsZero() )
849 fputs( "</g>\n", m_outputFile );
850
851 fprintf( m_outputFile, "<g class=\"stroked-text\"><desc>%s</desc>\n",
852 TO_UTF8( XmlEsc( aText ) ) );
853
854 PLOTTER::Text( aPos, aColor, aText, aOrient, aSize, aH_justify, aV_justify, aWidth, aItalic,
855 aBold, aMultilineAllowed, aFont, aFontMetrics );
856
857 fputs( "</g>", m_outputFile );
858}
859
860
862 const COLOR4D& aColor,
863 const wxString& aText,
864 const TEXT_ATTRIBUTES& aAttributes,
865 KIFONT::FONT* aFont,
866 const KIFONT::METRICS& aFontMetrics,
867 void* aData )
868{
869 VECTOR2I size = aAttributes.m_Size;
870
871 if( aAttributes.m_Mirrored )
872 size.x = -size.x;
873
874 SVG_PLOTTER::Text( aPos, aColor, aText, aAttributes.m_Angle, size, aAttributes.m_Halign,
875 aAttributes.m_Valign, aAttributes.m_StrokeWidth, aAttributes.m_Italic,
876 aAttributes.m_Bold, aAttributes.m_Multiline, aFont, aFontMetrics, aData );
877}
static wxString XmlEsc(const wxString &aStr, bool isAttribute=false)
Translates '<' to "<", '>' to ">" and so on, according to the spec: http://www.w3....
BOX2< Vec > & Normalize()
Ensure that the height and width are positive.
Definition: box2.h:120
const Vec & GetPosition() const
Definition: box2.h:185
const Vec & GetOrigin() const
Definition: box2.h:184
const Vec GetEnd() const
Definition: box2.h:186
const Vec & GetSize() const
Definition: box2.h:180
double AsDegrees() const
Definition: eda_angle.h:149
bool IsZero() const
Definition: eda_angle.h:169
double AsRadians() const
Definition: eda_angle.h:153
FONT is an abstract base class for both outline and stroke fonts.
Definition: font.h:130
A color representation with 4 components: red, green, blue, alpha.
Definition: color4d.h:104
int GetDefaultPenWidth() const
const VECTOR2I & GetSizeMils() const
Definition: page_info.h:134
double GetDotMarkLenIU(int aLineWidth) const
Definition: plotter.cpp:131
virtual void PlotImage(const wxImage &aImage, const VECTOR2I &aPos, double aScaleFactor)
Only PostScript plotters can plot bitmaps.
Definition: plotter.cpp:259
double GetDashGapLenIU(int aLineWidth) const
Definition: plotter.cpp:143
bool m_mirrorIsHorizontal
Definition: plotter.h:649
PAGE_INFO m_pageInfo
Definition: plotter.h:665
bool m_plotMirror
Definition: plotter.h:647
static const int USE_DEFAULT_LINE_WIDTH
Definition: plotter.h:108
virtual void BezierCurve(const VECTOR2I &aStart, const VECTOR2I &aControl1, const VECTOR2I &aControl2, const VECTOR2I &aEnd, int aTolerance, int aLineThickness=USE_DEFAULT_LINE_WIDTH)
Generic fallback: Cubic Bezier curve rendered as a polyline In KiCad the bezier curves have 4 control...
Definition: plotter.cpp:229
bool m_yaxisReversed
Definition: plotter.h:650
double m_iuPerDeviceUnit
Definition: plotter.h:644
VECTOR2I m_plotOffset
Definition: plotter.h:646
VECTOR2I m_penLastpos
Definition: plotter.h:660
virtual VECTOR2D userToDeviceCoordinates(const VECTOR2I &aCoordinate)
Modify coordinates according to the orientation, scale factor, and offsets trace.
Definition: plotter.cpp:90
VECTOR2I m_paperSize
Definition: plotter.h:666
virtual VECTOR2D userToDeviceSize(const VECTOR2I &size)
Modify size according to the plotter scale factors (VECTOR2I version, returns a VECTOR2D).
Definition: plotter.cpp:115
char m_penState
Definition: plotter.h:659
wxString m_creator
Definition: plotter.h:662
int m_currentPenWidth
Definition: plotter.h:658
double m_plotScale
Plot scale - chosen by the user (even implicitly with 'fit in a4')
Definition: plotter.h:636
FILE * m_outputFile
Output file.
Definition: plotter.h:653
static const int DO_NOT_SET_LINE_WIDTH
Definition: plotter.h:107
RENDER_SETTINGS * m_renderSettings
Definition: plotter.h:670
virtual void Text(const VECTOR2I &aPos, const COLOR4D &aColor, const wxString &aText, const EDA_ANGLE &aOrient, const VECTOR2I &aSize, enum GR_TEXT_H_ALIGN_T aH_justify, enum GR_TEXT_V_ALIGN_T aV_justify, int aPenWidth, bool aItalic, bool aBold, bool aMultilineAllowed, KIFONT::FONT *aFont, const KIFONT::METRICS &aFontMetrics, void *aData=nullptr)
Draw text with the plotter.
Definition: plotter.cpp:691
double m_IUsPerDecimil
Definition: plotter.h:642
virtual int GetCurrentLineWidth() const
Definition: plotter.h:147
bool m_colorMode
Definition: plotter.h:656
double GetDashMarkLenIU(int aLineWidth) const
Definition: plotter.cpp:137
wxString m_filename
Definition: plotter.h:663
virtual void SetColor(const COLOR4D &color) override
The SetColor implementation is split with the subclasses: the PSLIKE computes the rgb values,...
Definition: PS_plotter.cpp:63
virtual void SetTextMode(PLOT_TEXT_MODE mode) override
PS and PDF fully implement native text (for the Latin-1 subset)
virtual void emitSetRGBColor(double r, double g, double b, double a) override
Initialize m_pen_rgb_color from reduced values r, g ,b ( reduced values are 0.0 to 1....
virtual void PlotImage(const wxImage &aImage, const VECTOR2I &aPos, double aScaleFactor) override
PostScript-likes at the moment are the only plot engines supporting bitmaps.
unsigned m_precision
virtual bool StartPlot(const wxString &aPageNumber) override
Create SVG file header.
virtual void EndBlock(void *aData) override
Calling this function allows one to define the end of a group of drawing items the group is started b...
virtual void PlotPoly(const std::vector< VECTOR2I > &aCornerList, FILL_T aFill, int aWidth=USE_DEFAULT_LINE_WIDTH, void *aData=nullptr) override
Draw a polygon ( filled or not ).
virtual void SetViewport(const VECTOR2I &aOffset, double aIusPerDecimil, double aScale, bool aMirror) override
Set the plot offset and scaling for the current plot.
virtual void BezierCurve(const VECTOR2I &aStart, const VECTOR2I &aControl1, const VECTOR2I &aControl2, const VECTOR2I &aEnd, int aTolerance, int aLineThickness=USE_DEFAULT_LINE_WIDTH) override
Generic fallback: Cubic Bezier curve rendered as a polyline In KiCad the bezier curves have 4 control...
virtual void SetDash(int aLineWidth, PLOT_DASH_TYPE aLineStyle) override
SVG supports dashed lines.
virtual void Text(const VECTOR2I &aPos, const COLOR4D &aColor, const wxString &aText, const EDA_ANGLE &aOrient, const VECTOR2I &aSize, enum GR_TEXT_H_ALIGN_T aH_justify, enum GR_TEXT_V_ALIGN_T aV_justify, int aWidth, bool aItalic, bool aBold, bool aMultilineAllowed, KIFONT::FONT *aFont, const KIFONT::METRICS &aFontMetrics, void *aData=nullptr) override
Draw text with the plotter.
double m_brush_alpha
virtual void Rect(const VECTOR2I &p1, const VECTOR2I &p2, FILL_T fill, int width=USE_DEFAULT_LINE_WIDTH) override
virtual void SetSvgCoordinatesFormat(unsigned aPrecision) override
Select SVG coordinate precision (number of digits needed for 1 mm ) (SVG plotter uses always metric u...
virtual bool EndPlot() override
void setSVGPlotStyle(int aLineWidth, bool aIsGroup=true, const std::string &aExtraStyle={})
Output the string which define pen and brush color, shape, transparency.
virtual void PlotText(const VECTOR2I &aPos, const COLOR4D &aColor, const wxString &aText, const TEXT_ATTRIBUTES &aAttributes, KIFONT::FONT *aFont, const KIFONT::METRICS &aFontMetrics, void *aData=nullptr) override
virtual void PenTo(const VECTOR2I &pos, char plume) override
Moveto/lineto primitive, moves the 'pen' to the specified direction.
long m_brush_rgb_color
virtual void Circle(const VECTOR2I &pos, int diametre, FILL_T fill, int width=USE_DEFAULT_LINE_WIDTH) override
bool m_graphics_changed
PLOT_DASH_TYPE m_dashed
virtual void StartBlock(void *aData) override
Calling this function allows one to define the beginning of a group of drawing items (used in SVG for...
void setFillMode(FILL_T fill)
Prepare parameters for setSVGPlotStyle()
virtual void Arc(const VECTOR2D &aCenter, const EDA_ANGLE &aStartAngle, const EDA_ANGLE &aAngle, double aRadius, FILL_T aFill, int aWidth=USE_DEFAULT_LINE_WIDTH) override
virtual void SetCurrentLineWidth(int width, void *aData=nullptr) override
Set the current line width (in IUs) for the next plot.
GR_TEXT_H_ALIGN_T m_Halign
GR_TEXT_V_ALIGN_T m_Valign
static constexpr EDA_ANGLE & ANGLE_180
Definition: eda_angle.h:441
FILL_T
Definition: eda_shape.h:55
int GRTextWidth(const wxString &aText, KIFONT::FONT *aFont, const VECTOR2I &aSize, int aThickness, bool aBold, bool aItalic, const KIFONT::METRICS &aFontMetrics)
Definition: gr_text.cpp:113
This file contains miscellaneous commonly used macros and functions.
void encode(const std::vector< uint8_t > &aInput, std::vector< uint8_t > &aOutput)
Definition: base64.cpp:76
EDA_ANGLE abs(const EDA_ANGLE &aAngle)
Definition: eda_angle.h:426
Plotting engines similar to ps (PostScript, Gerber, svg)
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
Definition: string_utils.h:378
PLOT_DASH_TYPE
Dashed line types.
Definition: stroke_params.h:48
GR_TEXT_H_ALIGN_T
@ GR_TEXT_H_ALIGN_CENTER
@ GR_TEXT_H_ALIGN_RIGHT
@ GR_TEXT_H_ALIGN_LEFT
GR_TEXT_V_ALIGN_T
@ GR_TEXT_V_ALIGN_BOTTOM
@ GR_TEXT_V_ALIGN_CENTER
@ GR_TEXT_V_ALIGN_TOP
void RotatePoint(int *pX, int *pY, const EDA_ANGLE &aAngle)
Definition: trigo.cpp:183
VECTOR2< int > VECTOR2I
Definition: vector2d.h:588