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-2024 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 with alpha(black)
172 m_brush_alpha = 1.0;
173 m_dashed = LINE_STYLE::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 fputs( "style=\"", m_outputFile );
224
225 if( m_fillMode == FILL_T::NO_FILL )
226 {
227 fputs( "fill:none; ", m_outputFile );
228 }
229 else
230 {
231 // output the background fill color
232 fprintf( m_outputFile, "fill:#%6.6lX; ", m_brush_rgb_color );
233
234 switch( m_fillMode )
235 {
236 case FILL_T::FILLED_SHAPE:
237 case FILL_T::FILLED_WITH_BG_BODYCOLOR:
238 case FILL_T::FILLED_WITH_COLOR:
239 fprintf( m_outputFile, "fill-opacity:%.*f; ", m_precision, m_brush_alpha );
240 break;
241 default: break;
242 }
243 }
244
245 double pen_w = userToDeviceSize( aLineWidth );
246
247 if( pen_w <= 0 )
248 {
249 fputs( "stroke:none;", m_outputFile );
250 }
251 else
252 {
253 // Fix a strange issue found in Inkscape: aWidth < 100 nm create issues on degrouping objects
254 // So we use only 4 digits in mantissa for stroke-width.
255 // TODO: perhaps used only 3 or 4 digits in mantissa for all values in mm, because some
256 // issues were previously reported reported when using nm as integer units
257
258 fprintf( m_outputFile, "\nstroke:#%6.6lX; stroke-width:%.*f; stroke-opacity:1; \n",
260 fputs( "stroke-linecap:round; stroke-linejoin:round;", m_outputFile );
261
262 //set any extra attributes for non-solid lines
263 switch( m_dashed )
264 {
265 case LINE_STYLE::DASH:
266 fprintf( m_outputFile, "stroke-dasharray:%.*f,%.*f;", m_precision,
267 GetDashMarkLenIU( aLineWidth ), m_precision, GetDashGapLenIU( aLineWidth ) );
268 break;
269
270 case LINE_STYLE::DOT:
271 fprintf( m_outputFile, "stroke-dasharray:%f,%f;", GetDotMarkLenIU( aLineWidth ),
272 GetDashGapLenIU( aLineWidth ) );
273 break;
274
275 case LINE_STYLE::DASHDOT:
276 fprintf( m_outputFile, "stroke-dasharray:%f,%f,%f,%f;", GetDashMarkLenIU( aLineWidth ),
277 GetDashGapLenIU( aLineWidth ), GetDotMarkLenIU( aLineWidth ),
278 GetDashGapLenIU( aLineWidth ) );
279 break;
280
281 case LINE_STYLE::DASHDOTDOT:
282 fprintf( m_outputFile, "stroke-dasharray:%f,%f,%f,%f,%f,%f;",
283 GetDashMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ),
284 GetDotMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ),
285 GetDotMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ) );
286 break;
287
288 case LINE_STYLE::DEFAULT:
289 case LINE_STYLE::SOLID:
290 default:
291 //do nothing
292 break;
293 }
294 }
295
296 if( aExtraStyle.length() )
297 fputs( aExtraStyle.c_str(), m_outputFile );
298
299 fputs( "\"", m_outputFile );
300
301 if( aIsGroup )
302 {
303 fputs( ">", m_outputFile );
304 m_graphics_changed = false;
305 }
306
307 fputs( "\n", m_outputFile );
308}
309
310
311void SVG_PLOTTER::SetCurrentLineWidth( int aWidth, void* aData )
312{
313 if( aWidth == DO_NOT_SET_LINE_WIDTH )
314 return;
315 else if( aWidth == USE_DEFAULT_LINE_WIDTH )
317
318 // Note: aWidth == 0 is fine: used for filled shapes with no outline thickness
319
320 wxASSERT_MSG( aWidth >= 0, "Plotter called to set negative pen width" );
321
322 if( aWidth != m_currentPenWidth )
323 {
324 m_graphics_changed = true;
325 m_currentPenWidth = aWidth;
326 }
327}
328
329
330void SVG_PLOTTER::StartBlock( void* aData )
331{
332 // We can't use <g></g> for blocks because we're already using it for graphics context, and
333 // our graphics context handling is lazy (ie: it leaves the last group open until the context
334 // changes).
335}
336
337
338void SVG_PLOTTER::EndBlock( void* aData )
339{
340}
341
342
343void SVG_PLOTTER::emitSetRGBColor( double r, double g, double b, double a )
344{
345 int red = (int) ( 255.0 * r );
346 int green = (int) ( 255.0 * g );
347 int blue = (int) ( 255.0 * b );
348 long rgb_color = (red << 16) | (green << 8) | blue;
349
350 if( m_pen_rgb_color != rgb_color || m_brush_alpha != a )
351 {
352 m_graphics_changed = true;
353 m_pen_rgb_color = rgb_color;
354
355 // Currently, use the same color for brush and pen (i.e. to draw and fill a contour).
356 m_brush_rgb_color = rgb_color;
357 m_brush_alpha = a;
358 }
359}
360
361
362void SVG_PLOTTER::SetDash( int aLineWidth, LINE_STYLE aLineStyle )
363{
364 if( m_dashed != aLineStyle )
365 {
366 m_graphics_changed = true;
367 m_dashed = aLineStyle;
368 }
369}
370
371
372void SVG_PLOTTER::Rect( const VECTOR2I& p1, const VECTOR2I& p2, FILL_T fill, int width )
373{
374 BOX2I rect( p1, VECTOR2I( p2.x - p1.x, p2.y - p1.y ) );
375 rect.Normalize();
376
377 VECTOR2D org_dev = userToDeviceCoordinates( rect.GetOrigin() );
378 VECTOR2D end_dev = userToDeviceCoordinates( rect.GetEnd() );
379 VECTOR2D size_dev = end_dev - org_dev;
380
381 // Ensure size of rect in device coordinates is > 0
382 // I don't know if this is a SVG issue or a Inkscape issue, but
383 // Inkscape has problems with negative or null values for width and/or height, so avoid them
384 BOX2D rect_dev( org_dev, size_dev );
385 rect_dev.Normalize();
386
387 setFillMode( fill );
388 SetCurrentLineWidth( width );
389
392
393 // Rectangles having a 0 size value for height or width are just not drawn on Inkscape,
394 // so use a line when happens.
395 if( rect_dev.GetSize().x == 0.0 || rect_dev.GetSize().y == 0.0 ) // Draw a line
396 {
397 fprintf( m_outputFile,
398 "<line x1=\"%.*f\" y1=\"%.*f\" x2=\"%.*f\" y2=\"%.*f\" />\n",
399 m_precision, rect_dev.GetPosition().x,
400 m_precision, rect_dev.GetPosition().y,
401 m_precision, rect_dev.GetEnd().x,
402 m_precision, rect_dev.GetEnd().y );
403 }
404 else
405 {
406 fprintf( m_outputFile,
407 "<rect x=\"%f\" y=\"%f\" width=\"%f\" height=\"%f\" rx=\"%f\" />\n",
408 rect_dev.GetPosition().x,
409 rect_dev.GetPosition().y,
410 rect_dev.GetSize().x,
411 rect_dev.GetSize().y,
412 0.0 /* radius of rounded corners */ );
413 }
414}
415
416
417void SVG_PLOTTER::Circle( const VECTOR2I& pos, int diametre, FILL_T fill, int width )
418{
419 VECTOR2D pos_dev = userToDeviceCoordinates( pos );
420 double radius = userToDeviceSize( diametre / 2.0 );
421
422 setFillMode( fill );
423 SetCurrentLineWidth( width );
424
427
428 // If diameter is less than width, switch to filled mode
429 if( fill == FILL_T::NO_FILL && diametre < width )
430 {
431 setFillMode( FILL_T::FILLED_SHAPE );
433
434 radius = userToDeviceSize( ( diametre / 2.0 ) + ( width / 2.0 ) );
435 }
436
437 fprintf( m_outputFile,
438 "<circle cx=\"%.*f\" cy=\"%.*f\" r=\"%.*f\" /> \n",
439 m_precision, pos_dev.x,
440 m_precision, pos_dev.y,
441 m_precision, radius );
442}
443
444
445void SVG_PLOTTER::Arc( const VECTOR2D& aCenter, const EDA_ANGLE& aStartAngle,
446 const EDA_ANGLE& aAngle, double aRadius, FILL_T aFill, int aWidth )
447{
448 /* Draws an arc of a circle, centered on (xc,yc), with starting point (x1, y1) and ending
449 * at (x2, y2). The current pen is used for the outline and the current brush for filling
450 * the shape.
451 *
452 * The arc is drawn in an anticlockwise direction from the start point to the end point.
453 */
454
455 if( aRadius <= 0 )
456 {
457 Circle( aCenter, aWidth, FILL_T::FILLED_SHAPE, 0 );
458 return;
459 }
460
461 EDA_ANGLE startAngle = -aStartAngle;
462 EDA_ANGLE endAngle = startAngle - aAngle;
463
464 if( endAngle < startAngle )
465 std::swap( startAngle, endAngle );
466
467 // Calculate start point.
468 VECTOR2D centre_device = userToDeviceCoordinates( aCenter );
469 double radius_device = userToDeviceSize( aRadius );
470
471 if( m_plotMirror )
472 {
474 {
475 std::swap( startAngle, endAngle );
476 startAngle = ANGLE_180 - startAngle;
477 endAngle = ANGLE_180 - endAngle;
478 }
479 else
480 {
481 startAngle = -startAngle;
482 endAngle = -endAngle;
483 }
484 }
485
486 VECTOR2D start;
487 start.x = radius_device;
488 RotatePoint( start, startAngle );
489 VECTOR2D end;
490 end.x = radius_device;
491 RotatePoint( end, endAngle );
492 start += centre_device;
493 end += centre_device;
494
495 double theta1 = startAngle.AsRadians();
496
497 if( theta1 < 0 )
498 theta1 = theta1 + M_PI * 2;
499
500 double theta2 = endAngle.AsRadians();
501
502 if( theta2 < 0 )
503 theta2 = theta2 + M_PI * 2;
504
505 if( theta2 < theta1 )
506 theta2 = theta2 + M_PI * 2;
507
508 int flg_arc = 0; // flag for large or small arc. 0 means less than 180 degrees
509
510 if( fabs( theta2 - theta1 ) > M_PI )
511 flg_arc = 1;
512
513 int flg_sweep = 0; // flag for sweep always 0
514
515 // Draw a single arc: an arc is one of 3 curve commands (2 other are 2 bezier curves)
516 // params are start point, radius1, radius2, X axe rotation,
517 // flag arc size (0 = small arc > 180 deg, 1 = large arc > 180 deg),
518 // sweep arc ( 0 = CCW, 1 = CW),
519 // end point
520 if( aFill != FILL_T::NO_FILL )
521 {
522 // Filled arcs (in Eeschema) consist of the pie wedge and a stroke only on the arc
523 // This needs to be drawn in two steps.
524 setFillMode( aFill );
526
529
530 fprintf( m_outputFile, "<path d=\"M%.*f %.*f A%.*f %.*f 0.0 %d %d %.*f %.*f L %.*f %.*f Z\" />\n",
531 m_precision, start.x,
532 m_precision, start.y,
533 m_precision, radius_device,
534 m_precision, radius_device,
535 flg_arc,
536 flg_sweep,
537 m_precision, end.x,
538 m_precision, end.y,
539 m_precision, centre_device.x,
540 m_precision, centre_device.y );
541 }
542
543 setFillMode( FILL_T::NO_FILL );
544 SetCurrentLineWidth( aWidth );
545
548
549 fprintf( m_outputFile,
550 "<path d=\"M%.*f %.*f A%.*f %.*f 0.0 %d %d %.*f %.*f\" />\n",
551 m_precision, start.x,
552 m_precision, start.y,
553 m_precision, radius_device,
554 m_precision, radius_device,
555 flg_arc,
556 flg_sweep,
557 m_precision, end.x,
558 m_precision, end.y );
559}
560
561
562void SVG_PLOTTER::BezierCurve( const VECTOR2I& aStart, const VECTOR2I& aControl1,
563 const VECTOR2I& aControl2, const VECTOR2I& aEnd,
564 int aTolerance, int aLineThickness )
565{
566#if 1
567 setFillMode( FILL_T::NO_FILL );
568 SetCurrentLineWidth( aLineThickness );
569
572
573 VECTOR2D start = userToDeviceCoordinates( aStart );
574 VECTOR2D ctrl1 = userToDeviceCoordinates( aControl1 );
575 VECTOR2D ctrl2 = userToDeviceCoordinates( aControl2 );
576 VECTOR2D end = userToDeviceCoordinates( aEnd );
577
578 // Generate a cubic curve: start point and 3 other control points.
579 fprintf( m_outputFile,
580 "<path d=\"M%.*f,%.*f C%.*f,%.*f %.*f,%.*f %.*f,%.*f\" />\n",
581 m_precision, start.x,
582 m_precision, start.y,
583 m_precision, ctrl1.x,
584 m_precision, ctrl1.y,
585 m_precision, ctrl2.x,
586 m_precision, ctrl2.y,
587 m_precision, end.x,
588 m_precision, end.y );
589#else
590 PLOTTER::BezierCurve( aStart, aControl1, aControl2, aEnd, aTolerance, aLineThickness );
591#endif
592}
593
594
595void SVG_PLOTTER::PlotPoly( const std::vector<VECTOR2I>& aCornerList, FILL_T aFill,
596 int aWidth, void* aData )
597{
598 if( aCornerList.size() <= 1 )
599 return;
600
601 setFillMode( aFill );
602 SetCurrentLineWidth( aWidth );
603 fprintf( m_outputFile, "<path ");
604
605 switch( aFill )
606 {
607 case FILL_T::NO_FILL:
608 setSVGPlotStyle( aWidth, false, "fill:none" );
609 break;
610
611 case FILL_T::FILLED_WITH_BG_BODYCOLOR:
612 case FILL_T::FILLED_SHAPE:
613 case FILL_T::FILLED_WITH_COLOR:
614 setSVGPlotStyle( aWidth, false, "fill-rule:evenodd;" );
615 break;
616 }
617
618 VECTOR2D pos = userToDeviceCoordinates( aCornerList[0] );
619 fprintf( m_outputFile,
620 "d=\"M %.*f,%.*f\n",
621 m_precision, pos.x,
622 m_precision, pos.y );
623
624 for( unsigned ii = 1; ii < aCornerList.size() - 1; ii++ )
625 {
626 pos = userToDeviceCoordinates( aCornerList[ii] );
627 fprintf( m_outputFile,
628 "%.*f,%.*f\n",
629 m_precision, pos.x,
630 m_precision, pos.y );
631 }
632
633 // If the corner list ends where it begins, then close the poly
634 if( aCornerList.front() == aCornerList.back() )
635 {
636 fprintf( m_outputFile, "Z\" /> \n" );
637 }
638 else
639 {
640 pos = userToDeviceCoordinates( aCornerList.back() );
641 fprintf( m_outputFile,
642 "%.*f,%.*f\n\" /> \n",
643 m_precision, pos.x,
644 m_precision, pos.y );
645 }
646}
647
648
649void SVG_PLOTTER::PlotImage( const wxImage& aImage, const VECTOR2I& aPos, double aScaleFactor )
650{
651 VECTOR2I pix_size( aImage.GetWidth(), aImage.GetHeight() );
652
653 // Requested size (in IUs)
654 VECTOR2D drawsize( aScaleFactor * pix_size.x, aScaleFactor * pix_size.y );
655
656 // calculate the bitmap start position
657 VECTOR2I start( aPos.x - drawsize.x / 2, aPos.y - drawsize.y / 2 );
658
659 // Rectangles having a 0 size value for height or width are just not drawn on Inkscape,
660 // so use a line when happens.
661 if( drawsize.x == 0.0 || drawsize.y == 0.0 ) // Draw a line
662 {
663 PLOTTER::PlotImage( aImage, aPos, aScaleFactor );
664 }
665 else
666 {
667 wxMemoryOutputStream img_stream;
668
669 if( m_colorMode )
670 {
671 aImage.SaveFile( img_stream, wxBITMAP_TYPE_PNG );
672 }
673 else // Plot in B&W
674 {
675 wxImage image = aImage.ConvertToGreyscale();
676 image.SaveFile( img_stream, wxBITMAP_TYPE_PNG );
677 }
678
679 size_t input_len = img_stream.GetOutputStreamBuffer()->GetBufferSize();
680 std::vector<uint8_t> buffer( input_len );
681 std::vector<uint8_t> encoded;
682
683 img_stream.CopyTo( buffer.data(), buffer.size() );
684 base64::encode( buffer, encoded );
685
686 fprintf( m_outputFile,
687 "<image x=\"%f\" y=\"%f\" xlink:href=\"data:image/png;base64,",
688 userToDeviceSize( start.x ),
689 userToDeviceSize( start.y ) );
690
691 for( size_t i = 0; i < encoded.size(); i++ )
692 {
693 fprintf( m_outputFile, "%c", static_cast<char>( encoded[i] ) );
694
695 if( ( i % 64 ) == 63 )
696 fprintf( m_outputFile, "\n" );
697 }
698
699 fprintf( m_outputFile,
700 "\"\npreserveAspectRatio=\"none\" width=\"%.*f\" height=\"%.*f\" />",
702 userToDeviceSize( drawsize.x ),
704 userToDeviceSize( drawsize.y ) );
705 }
706}
707
708
709void SVG_PLOTTER::PenTo( const VECTOR2I& pos, char plume )
710{
711 if( plume == 'Z' )
712 {
713 if( m_penState != 'Z' )
714 {
715 fputs( "\" />\n", m_outputFile );
716 m_penState = 'Z';
717 m_penLastpos.x = -1;
718 m_penLastpos.y = -1;
719 }
720
721 return;
722 }
723
724 if( m_penState == 'Z' ) // here plume = 'D' or 'U'
725 {
726 VECTOR2D pos_dev = userToDeviceCoordinates( pos );
727
728 // Ensure we do not use a fill mode when moving the pen,
729 // in SVG mode (i;e. we are plotting only basic lines, not a filled area
730 if( m_fillMode != FILL_T::NO_FILL )
731 setFillMode( FILL_T::NO_FILL );
732
735
736 fprintf( m_outputFile, "<path d=\"M%.*f %.*f\n",
737 m_precision, pos_dev.x,
738 m_precision, pos_dev.y );
739 }
740 else if( m_penState != plume || pos != m_penLastpos )
741 {
744
745 VECTOR2D pos_dev = userToDeviceCoordinates( pos );
746
747 fprintf( m_outputFile, "L%.*f %.*f\n",
748 m_precision, pos_dev.x,
749 m_precision, pos_dev.y );
750 }
751
752 m_penState = plume;
753 m_penLastpos = pos;
754}
755
756
757bool SVG_PLOTTER::StartPlot( const wxString& aPageNumber )
758{
759 wxASSERT( m_outputFile );
760
761 static const char* header[] =
762 {
763 "<?xml version=\"1.0\" standalone=\"no\"?>\n",
764 " <!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \n",
765 " \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"> \n",
766 "<svg\n"
767 " xmlns:svg=\"http://www.w3.org/2000/svg\"\n"
768 " xmlns=\"http://www.w3.org/2000/svg\"\n",
769 " xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n",
770 " version=\"1.1\"\n",
771 nullptr
772 };
773
774 // Write header.
775 for( int ii = 0; header[ii] != nullptr; ii++ )
776 {
777 fputs( header[ii], m_outputFile );
778 }
779
780 // Write viewport pos and size
781 VECTOR2D origin; // TODO set to actual value
782 fprintf( m_outputFile, " width=\"%.*fmm\" height=\"%.*fmm\" viewBox=\"%.*f %.*f %.*f %.*f\">\n",
783 m_precision, (double) m_paperSize.x / m_IUsPerDecimil * 2.54 / 1000,
784 m_precision, (double) m_paperSize.y / m_IUsPerDecimil * 2.54 / 1000,
785 m_precision, origin.x, m_precision, origin.y,
788
789 // Write title
790 char date_buf[250];
791 time_t ltime = time( nullptr );
792 strftime( date_buf, 250, "%Y/%m/%d %H:%M:%S", localtime( &ltime ) );
793
794 fprintf( m_outputFile,
795 "<title>SVG Image created as %s date %s </title>\n",
796 TO_UTF8( XmlEsc( wxFileName( m_filename ).GetFullName() ) ),
797 date_buf );
798
799 // End of header
800 fprintf( m_outputFile,
801 " <desc>Image generated by %s </desc>\n",
802 TO_UTF8( XmlEsc( m_creator ) ) );
803
804 // output the pen and brush color (RVB values in hex) and opacity
805 double opacity = 1.0; // 0.0 (transparent to 1.0 (solid)
806 fprintf( m_outputFile,
807 "<g style=\"fill:#%6.6lX; fill-opacity:%.*f;stroke:#%6.6lX; stroke-opacity:%.*f;\n",
813 opacity );
814
815 // output the pen cap and line joint
816 fputs( "stroke-linecap:round; stroke-linejoin:round;\"\n", m_outputFile );
817 fputs( " transform=\"translate(0 0) scale(1 1)\">\n", m_outputFile );
818 return true;
819}
820
821
823{
824 fputs( "</g> \n</svg>\n", m_outputFile );
825 fclose( m_outputFile );
826 m_outputFile = nullptr;
827
828 return true;
829}
830
831
832void SVG_PLOTTER::Text( const VECTOR2I& aPos,
833 const COLOR4D& aColor,
834 const wxString& aText,
835 const EDA_ANGLE& aOrient,
836 const VECTOR2I& aSize,
837 enum GR_TEXT_H_ALIGN_T aH_justify,
838 enum GR_TEXT_V_ALIGN_T aV_justify,
839 int aWidth,
840 bool aItalic,
841 bool aBold,
842 bool aMultilineAllowed,
843 KIFONT::FONT* aFont,
844 const KIFONT::METRICS& aFontMetrics,
845 void* aData )
846{
847 setFillMode( FILL_T::NO_FILL );
848 SetColor( aColor );
849 SetCurrentLineWidth( aWidth );
850
853
854 VECTOR2I text_pos = aPos;
855 const char* hjust = "start";
856
857 switch( aH_justify )
858 {
859 case GR_TEXT_H_ALIGN_CENTER: hjust = "middle"; break;
860 case GR_TEXT_H_ALIGN_RIGHT: hjust = "end"; break;
861 case GR_TEXT_H_ALIGN_LEFT: hjust = "start"; break;
863 wxFAIL_MSG( wxT( "Indeterminate state legal only in dialogs." ) );
864 break;
865 }
866
867 switch( aV_justify )
868 {
869 case GR_TEXT_V_ALIGN_CENTER: text_pos.y += aSize.y / 2; break;
870 case GR_TEXT_V_ALIGN_TOP: text_pos.y += aSize.y; break;
871 case GR_TEXT_V_ALIGN_BOTTOM: break;
873 wxFAIL_MSG( wxT( "Indeterminate state legal only in dialogs." ) );
874 break;
875 }
876
877 VECTOR2I text_size;
878
879 // aSize.x or aSize.y is < 0 for mirrored texts.
880 // The actual text size value is the absolute value
881 text_size.x = std::abs( GRTextWidth( aText, aFont, aSize, aWidth, aBold, aItalic, aFontMetrics ) );
882 text_size.y = std::abs( aSize.x * 4/3 ); // Hershey font height to em size conversion
883 VECTOR2D anchor_pos_dev = userToDeviceCoordinates( aPos );
884 VECTOR2D text_pos_dev = userToDeviceCoordinates( text_pos );
885 VECTOR2D sz_dev = userToDeviceSize( text_size );
886
887 // Output the text as a hidden string (opacity = 0). This allows WYSIWYG search to highlight
888 // a selection in approximately the right area. It also makes it easier for those that need
889 // to edit the text (as text) in subsequent processes.
890 {
891 if( !aOrient.IsZero() )
892 {
893 fprintf( m_outputFile,
894 "<g transform=\"rotate(%f %.*f %.*f)\">\n",
895 m_plotMirror ? aOrient.AsDegrees() : -aOrient.AsDegrees(),
897 anchor_pos_dev.x,
899 anchor_pos_dev.y );
900 }
901
902 fprintf( m_outputFile,
903 "<text x=\"%.*f\" y=\"%.*f\"\n",
905 text_pos_dev.x, m_precision,
906 text_pos_dev.y );
907
909 if( m_plotMirror != ( aSize.x < 0 ) )
910 {
911 fprintf( m_outputFile, "transform=\"scale(-1 1) translate(%f 0)\"\n",
912 -2 * text_pos_dev.x );
913 }
914
915 fprintf( m_outputFile,
916 "textLength=\"%.*f\" font-size=\"%.*f\" lengthAdjust=\"spacingAndGlyphs\"\n"
917 "text-anchor=\"%s\" opacity=\"0\">%s</text>\n",
919 sz_dev.x,
921 sz_dev.y,
922 hjust,
923 TO_UTF8( XmlEsc( aText ) ) );
924
925 if( !aOrient.IsZero() )
926 fputs( "</g>\n", m_outputFile );
927 }
928
929 // Output the text again as graphics with a <desc> tag (for non-WYSIWYG search and for
930 // screen readers)
931 {
932 fprintf( m_outputFile,
933 "<g class=\"stroked-text\"><desc>%s</desc>\n",
934 TO_UTF8( XmlEsc( aText ) ) );
935
936 PLOTTER::Text( aPos, aColor, aText, aOrient, aSize, aH_justify, aV_justify, aWidth,
937 aItalic, aBold, aMultilineAllowed, aFont, aFontMetrics );
938
939 fputs( "</g>", m_outputFile );
940 }
941}
942
943
945 const COLOR4D& aColor,
946 const wxString& aText,
947 const TEXT_ATTRIBUTES& aAttributes,
948 KIFONT::FONT* aFont,
949 const KIFONT::METRICS& aFontMetrics,
950 void* aData )
951{
952 VECTOR2I size = aAttributes.m_Size;
953
954 if( aAttributes.m_Mirrored )
955 size.x = -size.x;
956
957 SVG_PLOTTER::Text( aPos, aColor, aText, aAttributes.m_Angle, size, aAttributes.m_Halign,
958 aAttributes.m_Valign, aAttributes.m_StrokeWidth, aAttributes.m_Italic,
959 aAttributes.m_Bold, aAttributes.m_Multiline, aFont, aFontMetrics, aData );
960}
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:136
const Vec & GetPosition() const
Definition: box2.h:201
const Vec & GetOrigin() const
Definition: box2.h:200
const SizeVec & GetSize() const
Definition: box2.h:196
const Vec GetEnd() const
Definition: box2.h:202
double AsDegrees() const
Definition: eda_angle.h:113
bool IsZero() const
Definition: eda_angle.h:133
double AsRadians() const
Definition: eda_angle.h:117
FONT is an abstract base class for both outline and stroke fonts.
Definition: font.h:131
A color representation with 4 components: red, green, blue, alpha.
Definition: color4d.h:104
int GetDefaultPenWidth() const
const VECTOR2D & GetSizeMils() const
Definition: page_info.h:144
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:658
PAGE_INFO m_pageInfo
Definition: plotter.h:676
bool m_plotMirror
Definition: plotter.h:656
static const int USE_DEFAULT_LINE_WIDTH
Definition: plotter.h:109
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:659
double m_iuPerDeviceUnit
Definition: plotter.h:653
VECTOR2I m_plotOffset
Definition: plotter.h:655
VECTOR2I m_penLastpos
Definition: plotter.h:669
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:677
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:668
wxString m_creator
Definition: plotter.h:671
int m_currentPenWidth
Definition: plotter.h:667
double m_plotScale
Plot scale - chosen by the user (even implicitly with 'fit in a4')
Definition: plotter.h:645
FILE * m_outputFile
Output file.
Definition: plotter.h:662
static const int DO_NOT_SET_LINE_WIDTH
Definition: plotter.h:108
RENDER_SETTINGS * m_renderSettings
Definition: plotter.h:681
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:651
virtual int GetCurrentLineWidth() const
Definition: plotter.h:148
bool m_colorMode
Definition: plotter.h:665
double GetDashMarkLenIU(int aLineWidth) const
Definition: plotter.cpp:137
wxString m_filename
Definition: plotter.h:672
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.
LINE_STYLE m_dashed
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 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
virtual void SetDash(int aLineWidth, LINE_STYLE aLineStyle) override
SVG supports dashed lines.
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:405
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:390
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:391
LINE_STYLE
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_H_ALIGN_INDETERMINATE
GR_TEXT_V_ALIGN_T
@ GR_TEXT_V_ALIGN_BOTTOM
@ GR_TEXT_V_ALIGN_INDETERMINATE
@ GR_TEXT_V_ALIGN_CENTER
@ GR_TEXT_V_ALIGN_TOP
void RotatePoint(int *pX, int *pY, const EDA_ANGLE &aAngle)
Calculate the new point of coord coord pX, pY, for a rotation center 0, 0.
Definition: trigo.cpp:228
VECTOR2< int32_t > VECTOR2I
Definition: vector2d.h:638