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 The 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, see <https://www.gnu.org/licenses/>.
19 */
20
21/* Some info on basic items SVG format, used here:
22 * The root element of all SVG files is the <svg> element.
23 *
24 * The <g> element is used to group SVG shapes together.
25 * Once grouped you can transform the whole group of shapes as if it was a single shape.
26 * This is an advantage compared to a nested <svg> element
27 * which cannot be the target of transformation by itself.
28 *
29 * The <rect> element represents a rectangle.
30 * Using this element you can draw rectangles of various width, height,
31 * with different stroke (outline) and fill colors, with sharp or rounded corners etc.
32 *
33 * <svg xmlns="http://www.w3.org/2000/svg"
34 * xmlns:xlink="http://www.w3.org/1999/xlink">
35 *
36 * <rect x="10" y="10" height="100" width="100"
37 * style="stroke:#006600; fill: #00cc00"/>
38 *
39 * </svg>
40 *
41 * The <circle> element is used to draw circles.
42 * <circle cx="40" cy="40" r="24" style="stroke:#006600; fill:#00cc00"/>
43 *
44 * The <ellipse> element is used to draw ellipses.
45 * An ellipse is a circle that does not have equal height and width.
46 * Its radius in the x and y directions are different, in other words.
47 * <ellipse cx="40" cy="40" rx="30" ry="15"
48 * style="stroke:#006600; fill:#00cc00"/>
49 *
50 * The <line> element is used to draw lines.
51 *
52 * <line x1="0" y1="10" x2="0" y2="100" style="stroke:#006600;"/>
53 * <line x1="10" y1="10" x2="100" y2="100" style="stroke:#006600;"/>
54 *
55 * The <polyline> element is used to draw multiple connected lines
56 * Here is a simple example:
57 *
58 * <polyline points="0,0 30,0 15,30" style="stroke:#006600;"/>
59 *
60 * The <polygon> element is used to draw with multiple (3 or more) sides / edges.
61 * Here is a simple example:
62 *
63 * <polygon points="0,0 50,0 25,50" style="stroke:#660000; fill:#cc3333;"/>
64 *
65 * The <path> element is used to draw advanced shapes combined from lines and arcs,
66 * with or without fill.
67 * It is probably the most advanced and versatile SVG shape of them all.
68 * It is probably also the hardest element to master.
69 * <path d="M50,50
70 * A30,30 0 0,1 35,20
71 * L100,100
72 * M110,110
73 * L100,0"
74 * style="stroke:#660000; fill:none;"/>
75 *
76 * Draw an elliptic arc: it is one of basic path command:
77 * <path d="M(startx,starty) A(radiusx,radiusy)
78 * rotation-axe-x
79 * flag_arc_large,flag_sweep endx,endy">
80 * flag_arc_large: 0 = small arc > 180 deg, 1 = large arc > 180 deg
81 * flag_sweep : 0 = CCW, 1 = CW
82 * The center of ellipse is automatically calculated.
83 */
84
85#include <core/base64.h>
86#include <eda_shape.h>
87#include <string_utils.h>
89#include <font/font.h>
90#include <macros.h>
91#include <trigo.h>
92#include <geometry/shape_rect.h>
93#include <fmt/format.h>
94
95#include <cstdint>
96#include <wx/mstream.h>
97
99
100// Note:
101// During tests, we (JPC) found issues when the coordinates used 6 digits in mantissa
102// especially for stroke-width using very small (but not null) values < 0.00001 mm
103// So to avoid this king of issue, we are using 4 digits in mantissa
104// The resolution (m_precision ) is 0.1 micron, that looks enough for a SVG file
105
111static wxString XmlEsc( const wxString& aStr, bool isAttribute = false )
112{
113 wxString escaped;
114
115 escaped.reserve( aStr.length() );
116
117 for( wxString::const_iterator it = aStr.begin(); it != aStr.end(); ++it )
118 {
119 const wxChar c = *it;
120
121 switch( c )
122 {
123 case wxS( '<' ):
124 escaped.append( wxS( "&lt;" ) );
125 break;
126 case wxS( '>' ):
127 escaped.append( wxS( "&gt;" ) );
128 break;
129 case wxS( '&' ):
130 escaped.append( wxS( "&amp;" ) );
131 break;
132 case wxS( '\r' ):
133 escaped.append( wxS( "&#xD;" ) );
134 break;
135 default:
136 if( isAttribute )
137 {
138 switch( c )
139 {
140 case wxS( '"' ):
141 escaped.append( wxS( "&quot;" ) );
142 break;
143 case wxS( '\t' ):
144 escaped.append( wxS( "&#x9;" ) );
145 break;
146 case wxS( '\n' ):
147 escaped.append( wxS( "&#xA;" ));
148 break;
149 default:
150 escaped.append(c);
151 }
152 }
153 else
154 {
155 escaped.append(c);
156 }
157 }
158 }
159
160 return escaped;
161}
162
163
165 PSLIKE_PLOTTER( aProject )
166{
167 m_graphics_changed = true;
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;
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
188 m_paperSize = m_pageInfo.GetSizeMils();
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
208void SVG_PLOTTER::SetPlotBBox( const BOX2I& aBBoxIU )
209{
210 m_plotBBoxIU = aBBoxIU;
211}
212
213
215{
216 VECTOR2D pos = PLOTTER::userToDeviceCoordinates( aCoordinate );
217
218 if( m_plotMirror )
219 {
222 else
224 }
225
226 return pos;
227}
228
229
231{
232 if( m_fillMode != fill )
233 {
234 m_graphics_changed = true;
235 m_fillMode = fill;
236 }
237}
238
239
240void SVG_PLOTTER::setSVGPlotStyle( int aLineWidth, bool aIsGroup, const std::string& aExtraStyle )
241{
242 if( aIsGroup )
243 fmt::print( m_outputFile, "</g>\n<g " );
244
245 fmt::print( m_outputFile, "style=\"" );
246
248 {
249 fmt::print( m_outputFile, "fill:none; " );
250 }
251 else
252 {
253 // output the background fill color
254 fmt::print( m_outputFile, "fill:#{:06X}; ", m_brush_rgb_color );
255
256 switch( m_fillMode )
257 {
261 fmt::print( m_outputFile, "fill-opacity:{:.{}f}; ", m_brush_alpha, m_precision );
262 break;
263 default: break;
264 }
265 }
266
267 double pen_w = userToDeviceSize( aLineWidth );
268
269 if( pen_w <= 0 )
270 {
271 fmt::print( m_outputFile, "stroke:none;" );
272 }
273 else
274 {
275 // Fix a strange issue found in Inkscape: aWidth < 100 nm create issues on degrouping
276 // objects.
277 // So we use only 4 digits in mantissa for stroke-width.
278 // TODO: perhaps used only 3 or 4 digits in mantissa for all values in mm, because some
279 // issues were previously reported reported when using nm as integer units
280 fmt::print( m_outputFile,
281 "\nstroke:#{:06X}; stroke-width:{:.{}f}; stroke-opacity:{:.{}f}; \n",
283 fmt::print( m_outputFile, "stroke-linecap:round; stroke-linejoin:round;" );
284
285 //set any extra attributes for non-solid lines
286 switch( m_dashed )
287 {
288 case LINE_STYLE::DASH:
289 fmt::print( m_outputFile, "stroke-dasharray:{:.{}f},{:.{}f};",
290 GetDashMarkLenIU( aLineWidth ), m_precision,
291 GetDashGapLenIU( aLineWidth ), m_precision );
292 break;
293
294 case LINE_STYLE::DOT:
295 fmt::print( m_outputFile, "stroke-dasharray:{:f},{:f};", GetDotMarkLenIU( aLineWidth ),
296 GetDashGapLenIU( aLineWidth ) );
297 break;
298
300 fmt::print( m_outputFile, "stroke-dasharray:{:f},{:f},{:f},{:f};",
301 GetDashMarkLenIU( aLineWidth ),
302 GetDashGapLenIU( aLineWidth ), GetDotMarkLenIU( aLineWidth ),
303 GetDashGapLenIU( aLineWidth ) );
304 break;
305
307 fmt::print( m_outputFile, "stroke-dasharray:{:f},{:f},{:f},{:f},{:f},{:f};",
308 GetDashMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ),
309 GetDotMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ),
310 GetDotMarkLenIU( aLineWidth ), GetDashGapLenIU( aLineWidth ) );
311 break;
312
315 default:
316 // Explicitly reset the dash pattern: stroke-dasharray is inherited in SVG, so
317 // inline path styles inside a dashed group would otherwise pick it up.
318 fmt::print( m_outputFile, "stroke-dasharray:none;" );
319 break;
320 }
321 }
322
323 if( aExtraStyle.length() )
324 fmt::print( m_outputFile, "{}", aExtraStyle );
325
326 fmt::print( m_outputFile, "\"" );
327
328 if( aIsGroup )
329 {
330 fmt::print( m_outputFile, ">" );
331 m_graphics_changed = false;
332 }
333
334 fmt::print( m_outputFile, "\n" );
335}
336
337
338void SVG_PLOTTER::SetCurrentLineWidth( int aWidth, void* aData )
339{
340 if( aWidth == DO_NOT_SET_LINE_WIDTH )
341 return;
342 else if( aWidth == USE_DEFAULT_LINE_WIDTH )
343 aWidth = m_renderSettings->GetDefaultPenWidth();
344
345 // Note: aWidth == 0 is fine: used for filled shapes with no outline thickness
346 wxASSERT_MSG( aWidth >= 0, "Plotter called to set negative pen width" );
347
348 if( aWidth != m_currentPenWidth )
349 {
350 m_graphics_changed = true;
351 m_currentPenWidth = aWidth;
352 }
353}
354
355
356void SVG_PLOTTER::StartBlock( void* aData )
357{
358 // We can't use <g></g> for blocks because we're already using it for graphics context, and
359 // our graphics context handling is lazy (ie: it leaves the last group open until the context
360 // changes).
361}
362
363
364void SVG_PLOTTER::EndBlock( void* aData )
365{
366}
367
368
369void SVG_PLOTTER::emitSetRGBColor( double r, double g, double b, double a )
370{
371 uint32_t red = (uint32_t) ( 255.0 * r );
372 uint32_t green = (uint32_t) ( 255.0 * g );
373 uint32_t blue = (uint32_t) ( 255.0 * b );
374 uint32_t rgb_color = ( red << 16 ) | ( green << 8 ) | blue;
375
376 if( m_pen_rgb_color != rgb_color || m_brush_alpha != a )
377 {
378 m_graphics_changed = true;
379 m_pen_rgb_color = rgb_color;
380
381 // Currently, use the same color for brush and pen (i.e. to draw and fill a contour).
382 m_brush_rgb_color = rgb_color;
383 m_brush_alpha = a;
384 }
385}
386
387
388void SVG_PLOTTER::SetDash( int aLineWidth, LINE_STYLE aLineStyle )
389{
390 if( m_dashed != aLineStyle )
391 {
392 m_graphics_changed = true;
393 m_dashed = aLineStyle;
394 }
395}
396
397
398void SVG_PLOTTER::Rect( const VECTOR2I& p1, const VECTOR2I& p2, FILL_T fill, int width,
399 int aCornerRadius )
400{
401 if( aCornerRadius > 0 )
402 {
403 BOX2I box( p1, VECTOR2I( p2.x - p1.x, p2.y - p1.y ) );
404 box.Normalize();
405 SHAPE_RECT rect( box );
406 rect.SetRadius( aCornerRadius );
407 PLOTTER::PlotPoly( rect.Outline(), fill, width, nullptr );
408 return;
409 }
410
411 BOX2I rect( p1, VECTOR2I( p2.x - p1.x, p2.y - p1.y ) );
412 rect.Normalize();
413
414 VECTOR2D org_dev = userToDeviceCoordinates( rect.GetOrigin() );
415 VECTOR2D end_dev = userToDeviceCoordinates( rect.GetEnd() );
416 VECTOR2D size_dev = end_dev - org_dev;
417
418 // Ensure size of rect in device coordinates is > 0
419 // I don't know if this is a SVG issue or a Inkscape issue, but
420 // Inkscape has problems with negative or null values for width and/or height, so avoid them
421 BOX2D rect_dev( org_dev, size_dev );
422 rect_dev.Normalize();
423
424 setFillMode( fill );
425 SetCurrentLineWidth( width );
426
429
430 // Rectangles having a 0 size value for height or width are just not drawn on Inkscape,
431 // so use a line when happens.
432 if( rect_dev.GetSize().x == 0.0 || rect_dev.GetSize().y == 0.0 ) // Draw a line
433 {
434 fmt::print( m_outputFile,
435 "<line x1=\"{:.{}f}\" y1=\"{:.{}f}\" x2=\"{:.{}f}\" y2=\"{:.{}f}\" />\n",
436 rect_dev.GetPosition().x, m_precision,
437 rect_dev.GetPosition().y, m_precision,
438 rect_dev.GetEnd().x, m_precision,
439 rect_dev.GetEnd().y, m_precision );
440 }
441 else
442 {
443 fmt::print( m_outputFile,
444 "<rect x=\"{:f}\" y=\"{:f}\" width=\"{:f}\" height=\"{:f}\" rx=\"{:f}\" />\n",
445 rect_dev.GetPosition().x,
446 rect_dev.GetPosition().y,
447 rect_dev.GetSize().x,
448 rect_dev.GetSize().y,
449 userToDeviceSize( aCornerRadius ) );
450 }
451}
452
453
454void SVG_PLOTTER::Circle( const VECTOR2I& pos, int diametre, FILL_T fill, int width )
455{
456 VECTOR2D pos_dev = userToDeviceCoordinates( pos );
457 double radius = userToDeviceSize( diametre / 2.0 );
458
459 setFillMode( fill );
460 SetCurrentLineWidth( width );
461
464
465 // If diameter is less than width, switch to filled mode
466 if( fill == FILL_T::NO_FILL && diametre < GetCurrentLineWidth() )
467 {
469 width = GetCurrentLineWidth();
471
472 radius = userToDeviceSize( ( diametre / 2.0 ) + ( width / 2.0 ) );
473 }
474
475 fmt::print( m_outputFile,
476 "<circle cx=\"{:.{}f}\" cy=\"{:.{}f}\" r=\"{:.{}f}\" /> \n",
477 pos_dev.x, m_precision,
478 pos_dev.y, m_precision,
480}
481
482
483void SVG_PLOTTER::Arc( const VECTOR2D& aCenter, const EDA_ANGLE& aStartAngle,
484 const EDA_ANGLE& aAngle, double aRadius, FILL_T aFill, int aWidth )
485{
486 /* Draws an arc of a circle, centered on (xc,yc), with starting point (x1, y1) and ending
487 * at (x2, y2). The current pen is used for the outline and the current brush for filling
488 * the shape.
489 *
490 * The arc is drawn in an anticlockwise direction from the start point to the end point.
491 */
492 if( aRadius <= 0 )
493 {
494 Circle( aCenter, aWidth, FILL_T::FILLED_SHAPE, 0 );
495 return;
496 }
497
498 EDA_ANGLE startAngle = -aStartAngle;
499 EDA_ANGLE endAngle = startAngle - aAngle;
500
501 if( endAngle < startAngle )
502 std::swap( startAngle, endAngle );
503
504 // Calculate start point.
505 VECTOR2D centre_device = userToDeviceCoordinates( aCenter );
506 double radius_device = userToDeviceSize( aRadius );
507
508 if( m_plotMirror )
509 {
511 {
512 std::swap( startAngle, endAngle );
513 startAngle = ANGLE_180 - startAngle;
514 endAngle = ANGLE_180 - endAngle;
515 }
516 else
517 {
518 startAngle = -startAngle;
519 endAngle = -endAngle;
520 }
521 }
522
523 VECTOR2D start;
524 start.x = radius_device;
525 RotatePoint( start, startAngle );
527 end.x = radius_device;
528 RotatePoint( end, endAngle );
529 start += centre_device;
530 end += centre_device;
531
532 double theta1 = startAngle.AsRadians();
533
534 if( theta1 < 0 )
535 theta1 = theta1 + M_PI * 2;
536
537 double theta2 = endAngle.AsRadians();
538
539 if( theta2 < 0 )
540 theta2 = theta2 + M_PI * 2;
541
542 if( theta2 < theta1 )
543 theta2 = theta2 + M_PI * 2;
544
545 int flg_arc = 0; // flag for large or small arc. 0 means less than 180 degrees
546
547 if( fabs( theta2 - theta1 ) > M_PI )
548 flg_arc = 1;
549
550 int flg_sweep = 0; // flag for sweep always 0
551
552 // Draw a single arc: an arc is one of 3 curve commands (2 other are 2 bezier curves)
553 // params are start point, radius1, radius2, X axe rotation,
554 // flag arc size (0 = small arc > 180 deg, 1 = large arc > 180 deg),
555 // sweep arc ( 0 = CCW, 1 = CW),
556 // end point
557 if( aFill != FILL_T::NO_FILL )
558 {
559 // Filled arcs (in Eeschema) consist of the pie wedge and a stroke only on the arc
560 // This needs to be drawn in two steps.
561 setFillMode( aFill );
563
566
567 fmt::print( m_outputFile,
568 "<path d=\"M{:.{}f} {:.{}f} A{:.{}f} {:.{}f} 0.0 {:d} {:d} {:.{}f} {:.{}f} L {:.{}f} {:.{}f} Z\" />\n",
569 start.x, m_precision,
570 start.y, m_precision,
571 radius_device, m_precision,
572 radius_device, m_precision,
573 flg_arc,
574 flg_sweep,
575 end.x, m_precision,
576 end.y, m_precision,
577 centre_device.x, m_precision,
578 centre_device.y, m_precision );
579 }
580
582 SetCurrentLineWidth( aWidth );
583
586
587 fmt::print( m_outputFile,
588 "<path d=\"M{:.{}f} {:.{}f} A{:.{}f} {:.{}f} 0.0 {:d} {:d} {:.{}f} {:.{}f}\" />\n",
589 start.x, m_precision,
590 start.y, m_precision,
591 radius_device, m_precision,
592 radius_device, m_precision,
593 flg_arc,
594 flg_sweep,
595 end.x, m_precision,
596 end.y, m_precision );
597}
598
599
600void SVG_PLOTTER::BezierCurve( const VECTOR2I& aStart, const VECTOR2I& aControl1,
601 const VECTOR2I& aControl2, const VECTOR2I& aEnd,
602 int aTolerance, int aLineThickness )
603{
604#if 1
606 SetCurrentLineWidth( aLineThickness );
607
610
611 VECTOR2D start = userToDeviceCoordinates( aStart );
612 VECTOR2D ctrl1 = userToDeviceCoordinates( aControl1 );
613 VECTOR2D ctrl2 = userToDeviceCoordinates( aControl2 );
615
616 // Generate a cubic curve: start point and 3 other control points.
617 fmt::print( m_outputFile,
618 "<path d=\"M{:.{}f},{:.{}f} C{:.{}f},{:.{}f} {:.{}f},{:.{}f} {:.{}f},{:.{}f}\" />\n",
619 start.x, m_precision,
620 start.y, m_precision,
621 ctrl1.x,m_precision,
622 ctrl1.y, m_precision,
623 ctrl2.x, m_precision,
624 ctrl2.y, m_precision,
625 end.x, m_precision,
626 end.y, m_precision );
627#else
628 PLOTTER::BezierCurve( aStart, aControl1, aControl2, aEnd, aTolerance, aLineThickness );
629#endif
630}
631
632
633void SVG_PLOTTER::PlotPoly( const std::vector<VECTOR2I>& aCornerList, FILL_T aFill,
634 int aWidth, void* aData )
635{
636 if( aCornerList.size() <= 1 )
637 return;
638
639 setFillMode( aFill );
640 SetCurrentLineWidth( aWidth );
641 fmt::print( m_outputFile, "<path " );
642
643 switch( aFill )
644 {
645 case FILL_T::NO_FILL:
646 case FILL_T::HATCH:
649 setSVGPlotStyle( aWidth, false, "fill:none" );
650 break;
651
655 setSVGPlotStyle( aWidth, false, "fill-rule:evenodd;" );
656 break;
657 }
658
659 VECTOR2D pos = userToDeviceCoordinates( aCornerList[0] );
660 fmt::print( m_outputFile, "d=\"M {:.{}f},{:.{}f}\n", pos.x, m_precision, pos.y, m_precision );
661
662 for( unsigned ii = 1; ii < aCornerList.size() - 1; ii++ )
663 {
664 pos = userToDeviceCoordinates( aCornerList[ii] );
665 fmt::print( m_outputFile, "{:.{}f},{:.{}f}\n", pos.x, m_precision, pos.y, m_precision );
666 }
667
668 // If the corner list ends where it begins, then close the poly
669 if( aCornerList.front() == aCornerList.back() )
670 {
671 fmt::print( m_outputFile, "Z\" /> \n" );
672 }
673 else
674 {
675 pos = userToDeviceCoordinates( aCornerList.back() );
676 fmt::print( m_outputFile,
677 "{:.{}f},{:.{}f}\n\" /> \n",
678 pos.x, m_precision,
679 pos.y, m_precision );
680 }
681}
682
683
684void SVG_PLOTTER::PlotImage( const wxImage& aImage, const VECTOR2I& aPos, double aScaleFactor )
685{
686 VECTOR2I pix_size( aImage.GetWidth(), aImage.GetHeight() );
687
688 // Requested size (in IUs)
689 VECTOR2D drawsize( aScaleFactor * pix_size.x, aScaleFactor * pix_size.y );
690
691 // calculate the bitmap start position
692 VECTOR2I start( aPos.x - drawsize.x / 2, aPos.y - drawsize.y / 2 );
693
694 // Rectangles having a 0 size value for height or width are just not drawn on Inkscape,
695 // so use a line when happens.
696 if( drawsize.x == 0.0 || drawsize.y == 0.0 ) // Draw a line
697 {
698 PLOTTER::PlotImage( aImage, aPos, aScaleFactor );
699 }
700 else
701 {
702 wxMemoryOutputStream img_stream;
703
704 if( m_colorMode )
705 {
706 aImage.SaveFile( img_stream, wxBITMAP_TYPE_PNG );
707 }
708 else // Plot in B&W
709 {
710 wxImage image = aImage.ConvertToGreyscale();
711 image.SaveFile( img_stream, wxBITMAP_TYPE_PNG );
712 }
713
714 size_t input_len = img_stream.GetOutputStreamBuffer()->GetBufferSize();
715 std::vector<uint8_t> buffer( input_len );
716 std::vector<uint8_t> encoded;
717
718 img_stream.CopyTo( buffer.data(), buffer.size() );
719 base64::encode( buffer, encoded );
720
721 VECTOR2D pos = userToDeviceCoordinates( start );
722 fmt::print( m_outputFile,
723 "<image x=\"{:f}\" y=\"{:f}\" xlink:href=\"data:image/png;base64,", pos.x, pos.y );
724
725 for( size_t i = 0; i < encoded.size(); i++ )
726 {
727 fmt::print( m_outputFile, "{}", static_cast<char>( encoded[i] ) );
728
729 if( ( i % 64 ) == 63 )
730 fmt::print( m_outputFile, "\n" );
731 }
732
733 fmt::print( m_outputFile,
734 "\"\npreserveAspectRatio=\"none\" width=\"{:.{}f}\" height=\"{:.{}f}\" />",
735 userToDeviceSize( drawsize.x ), m_precision,
736 userToDeviceSize( drawsize.y ), m_precision );
737 }
738}
739
740
741void SVG_PLOTTER::PenTo( const VECTOR2I& pos, char plume )
742{
743 if( plume == 'Z' )
744 {
745 if( m_penState != 'Z' )
746 {
747 fmt::print( m_outputFile, "\" />\n" );
748 m_penState = 'Z';
749 m_penLastpos.x = -1;
750 m_penLastpos.y = -1;
751 }
752
753 return;
754 }
755
756 if( m_penState == 'Z' ) // here plume = 'D' or 'U'
757 {
758 VECTOR2D pos_dev = userToDeviceCoordinates( pos );
759
760 // Ensure we do not use a fill mode when moving the pen,
761 // in SVG mode (i;e. we are plotting only basic lines, not a filled area
764
767
768 fmt::print( m_outputFile, "<path d=\"M{:.{}f} {:.{}f}\n",
769 pos_dev.x, m_precision,
770 pos_dev.y, m_precision );
771 }
772 else if( m_penState != plume || pos != m_penLastpos )
773 {
776
777 VECTOR2D pos_dev = userToDeviceCoordinates( pos );
778
779 fmt::print( m_outputFile, "L{:.{}f} {:.{}f}\n",
780 pos_dev.x, m_precision,
781 pos_dev.y, m_precision );
782 }
783
784 m_penState = plume;
785 m_penLastpos = pos;
786}
787
788
789bool SVG_PLOTTER::StartPlot( const wxString& aPageNumber )
790{
791 wxASSERT( m_outputFile );
792
793 std::string header = "<?xml version=\"1.0\" standalone=\"no\"?>\n"
794 " <!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \n"
795 " \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"> \n"
796 "<svg\n"
797 " xmlns:svg=\"http://www.w3.org/2000/svg\"\n"
798 " xmlns=\"http://www.w3.org/2000/svg\"\n"
799 " xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
800 " xmlns:inkscape=\"http://www.inkscape.org/namespaces/inkscape\"\n"
801 " version=\"1.1\"\n";
802
803 // Write header.
804 fmt::print( m_outputFile, "{}", header );
805
806 // Write viewport pos and size. The SVG width/height and viewBox are in mm (device
807 // units). When a plot bounding box was supplied, the viewBox is that box
808 // transformed by the viewport, so the content keeps its origin at the SVG
809 // origin even when it extends to negative coordinates. Otherwise the page
810 // size is used and the origin is the viewbox (which is also the page) corner.
811 VECTOR2D viewBoxOrigin( 0, 0 );
813
814 if( m_plotBBoxIU )
815 {
816 double deviceScale = m_plotScale * m_iuPerDeviceUnit;
817
818 viewBoxOrigin.x = ( m_plotBBoxIU->GetLeft() - m_plotOffset.x ) * deviceScale;
819 viewBoxOrigin.y = ( m_plotBBoxIU->GetTop() - m_plotOffset.y ) * deviceScale;
820 viewboxSize.x = static_cast<double>( m_plotBBoxIU->GetWidth() ) * deviceScale;
821 viewboxSize.y = static_cast<double>( m_plotBBoxIU->GetHeight() ) * deviceScale;
822 }
823
824 // When mirroring, the viewbox also needs to be mirrored, so that the same content is
825 // still visible in it.
826 if( m_plotMirror )
827 {
829 viewBoxOrigin.x = -viewBoxOrigin.x - viewboxSize.x;
830 else
831 viewBoxOrigin.y = -viewBoxOrigin.y - viewboxSize.y;
832 }
833
834 fmt::print( m_outputFile,
835 " width=\"{:.{}f}mm\" height=\"{:.{}f}mm\" viewBox=\"{:.{}f} {:.{}f} {:.{}f} {:.{}f}\">\n",
836 viewboxSize.x, m_precision, viewboxSize.y, m_precision,
837 viewBoxOrigin.x, m_precision, viewBoxOrigin.y, m_precision,
838 viewboxSize.x, m_precision, viewboxSize.y, m_precision );
839
840 // Write title
841 wxString date = GetISO8601CurrentDateTime();
842
843 fmt::print( m_outputFile,
844 "<title>SVG Image created as {} date {} </title>\n",
845 TO_UTF8( XmlEsc( wxFileName( m_filename ).GetFullName() ) ),
846 TO_UTF8( date ) );
847
848 // End of header
849 fmt::print( m_outputFile, " <desc>Image generated by {} </desc>\n",
850 TO_UTF8( XmlEsc( m_creator ) ) );
851
852 // output the pen and brush color (RVB values in hex) and opacity
853 double opacity = 1.0; // 0.0 (transparent to 1.0 (solid)
854 fmt::print( m_outputFile,
855 "<g style=\"fill:#{:06X}; fill-opacity:{:.{}f};stroke:#{:06X}; stroke-opacity:{:.{}f};\n",
860 opacity,
861 m_precision );
862
863 // output the pen cap and line joint
864 fmt::print( m_outputFile, "stroke-linecap:round; stroke-linejoin:round;\"\n" );
865 fmt::print( m_outputFile, " transform=\"translate(0 0) scale(1 1)\">\n" );
866 return true;
867}
868
869
871{
872 fmt::print( m_outputFile, "</g> \n</svg>\n" );
873 fclose( m_outputFile );
874 m_outputFile = nullptr;
875
876 return true;
877}
878
879
880void SVG_PLOTTER::Text( const VECTOR2I& aPos,
881 const COLOR4D& aColor,
882 const wxString& aText,
883 const EDA_ANGLE& aOrient,
884 const VECTOR2I& aSize,
885 enum GR_TEXT_H_ALIGN_T aH_justify,
886 enum GR_TEXT_V_ALIGN_T aV_justify,
887 int aWidth,
888 bool aItalic,
889 bool aBold,
890 bool aMultilineAllowed,
891 KIFONT::FONT* aFont,
892 const KIFONT::METRICS& aFontMetrics,
893 void* aData )
894{
896 SetColor( aColor );
897 SetCurrentLineWidth( aWidth );
898
899 wxString text( aText );
900
901 if( text.Contains( wxS( "@{" ) ) )
902 {
903 EXPRESSION_EVALUATOR evaluator;
904 text = evaluator.Evaluate( text );
905 }
906
909
910 VECTOR2I text_pos = aPos;
911 const char* hjust = "start";
912
913 switch( aH_justify )
914 {
915 case GR_TEXT_H_ALIGN_CENTER: hjust = "middle"; break;
916 case GR_TEXT_H_ALIGN_RIGHT: hjust = "end"; break;
917 case GR_TEXT_H_ALIGN_LEFT: hjust = "start"; break;
919 wxFAIL_MSG( wxT( "Indeterminate state legal only in dialogs." ) );
920 break;
921 }
922
923 switch( aV_justify )
924 {
925 case GR_TEXT_V_ALIGN_CENTER: text_pos.y += aSize.y / 2; break;
926 case GR_TEXT_V_ALIGN_TOP: text_pos.y += aSize.y; break;
927 case GR_TEXT_V_ALIGN_BOTTOM: break;
929 wxFAIL_MSG( wxT( "Indeterminate state legal only in dialogs." ) );
930 break;
931 }
932
933 VECTOR2I text_size;
934
935 // aSize.x or aSize.y is < 0 for mirrored texts.
936 // The actual text size value is the absolute value
937 text_size.x = std::abs( GRTextWidth( text, aFont, aSize, GetCurrentLineWidth(), aBold, aItalic,
938 aFontMetrics ) );
939 text_size.y = std::abs( aSize.x * 4/3 ); // Hershey font height to em size conversion
940 VECTOR2D anchor_pos_dev = userToDeviceCoordinates( aPos );
941 VECTOR2D text_pos_dev = userToDeviceCoordinates( text_pos );
942 VECTOR2D sz_dev = userToDeviceSize( text_size );
943
944 // Output the text as a hidden string (opacity = 0). This allows WYSIWYG search to highlight
945 // a selection in approximately the right area. It also makes it easier for those that need
946 // to edit the text (as text) in subsequent processes.
947 {
948 if( !aOrient.IsZero() )
949 {
950 fmt::print( m_outputFile,
951 "<g transform=\"rotate({:f} {:.{}f} {:.{}f})\">\n",
952 m_plotMirror ? aOrient.AsDegrees() : -aOrient.AsDegrees(),
953 anchor_pos_dev.x,
955 anchor_pos_dev.y,
956 m_precision );
957 }
958
959 fmt::print( m_outputFile,
960 "<text x=\"{:.{}f}\" y=\"{:.{}f}\"\n",
961 text_pos_dev.x, m_precision,
962 text_pos_dev.y, m_precision );
963
965 if( m_plotMirror != ( aSize.x < 0 ) )
966 {
967 fmt::print( m_outputFile, "transform=\"scale(-1 1) translate({:f} 0)\"\n",
968 -2 * text_pos_dev.x );
969 }
970
971 fmt::print( m_outputFile,
972 "textLength=\"{:.{}f}\" font-size=\"{:.{}f}\" lengthAdjust=\"spacingAndGlyphs\"\n"
973 "text-anchor=\"{}\" opacity=\"0\" stroke-opacity=\"0\">{}</text>\n",
974 sz_dev.x,
976 sz_dev.y,
978 hjust,
979 TO_UTF8( XmlEsc( text ) ) );
980
981 if( !aOrient.IsZero() )
982 fmt::print( m_outputFile, "</g>\n" );
983 }
984
985 // Output the text again as graphics with a <desc> tag (for non-WYSIWYG search and for
986 // screen readers)
987 {
988 fmt::print( m_outputFile,
989 "<g class=\"stroked-text\"><desc>{}</desc>\n",
990 TO_UTF8( XmlEsc( text ) ) );
991
992 PLOTTER::Text( aPos, aColor, text, aOrient, aSize, aH_justify, aV_justify, GetCurrentLineWidth(),
993 aItalic, aBold, aMultilineAllowed, aFont, aFontMetrics );
994
995 fmt::print( m_outputFile, "</g>" );
996 }
997}
998
999
1001 const COLOR4D& aColor,
1002 const wxString& aText,
1003 const TEXT_ATTRIBUTES& aAttributes,
1004 KIFONT::FONT* aFont,
1005 const KIFONT::METRICS& aFontMetrics,
1006 void* aData )
1007{
1008 VECTOR2I size = aAttributes.m_Size;
1009
1010 if( aAttributes.m_Mirrored )
1011 size.x = -size.x;
1012
1013 SVG_PLOTTER::Text( aPos, aColor, aText, aAttributes.m_Angle.GetAngle(), size, aAttributes.m_Halign,
1014 aAttributes.m_Valign, aAttributes.m_StrokeWidth, aAttributes.m_Italic,
1015 aAttributes.m_Bold, aAttributes.m_Multiline, aFont, aFontMetrics, aData );
1016}
int blue
int red
int green
static wxString XmlEsc(const wxString &aStr, bool isAttribute=false)
Translates '<' to "<", '>' to ">" and so on, according to the spec: http://www.w3....
BOX2< VECTOR2I > BOX2I
Definition box2.h:914
BOX2< VECTOR2D > BOX2D
Definition box2.h:915
constexpr const Vec & GetPosition() const
Definition box2.h:208
constexpr const Vec GetEnd() const
Definition box2.h:209
constexpr BOX2< Vec > & Normalize()
Ensure that the height and width are positive.
Definition box2.h:143
constexpr const Vec & GetOrigin() const
Definition box2.h:207
constexpr const SizeVec & GetSize() const
Definition box2.h:203
double AsDegrees() const
Definition eda_angle.h:115
bool IsZero() const
Definition eda_angle.h:135
double AsRadians() const
Definition eda_angle.h:119
EDA_ANGLE GetAngle() const
Definition eda_angle.h:533
High-level wrapper for evaluating mathematical and string expressions in wxString format.
wxString Evaluate(const wxString &aInput)
Main evaluation function - processes input string and evaluates all '@{}' expressions.
FONT is an abstract base class for both outline and stroke fonts.
Definition font.h:94
A color representation with 4 components: red, green, blue, alpha.
Definition color4d.h:101
double GetDotMarkLenIU(int aLineWidth) const
Definition plotter.cpp:132
virtual void PlotImage(const wxImage &aImage, const VECTOR2I &aPos, double aScaleFactor)
Only PostScript plotters can plot bitmaps.
Definition plotter.cpp:258
double GetDashGapLenIU(int aLineWidth) const
Definition plotter.cpp:144
bool m_mirrorIsHorizontal
Definition plotter.h:723
PAGE_INFO m_pageInfo
Definition plotter.h:741
bool m_plotMirror
Definition plotter.h:721
static const int USE_DEFAULT_LINE_WIDTH
Definition plotter.h:140
bool m_yaxisReversed
Definition plotter.h:724
double m_iuPerDeviceUnit
Definition plotter.h:718
VECTOR2I m_plotOffset
Definition plotter.h:720
VECTOR2I m_penLastpos
Definition plotter.h:734
virtual VECTOR2D userToDeviceCoordinates(const VECTOR2I &aCoordinate)
Modify coordinates according to the orientation, scale factor, and offsets trace.
Definition plotter.cpp:91
VECTOR2I m_paperSize
Definition plotter.h:742
virtual VECTOR2D userToDeviceSize(const VECTOR2I &size)
Modify size according to the plotter scale factors (VECTOR2I version, returns a VECTOR2D).
Definition plotter.cpp:116
char m_penState
Definition plotter.h:733
virtual void BezierCurve(const VECTOR2I &aStart, const VECTOR2I &aControl1, const VECTOR2I &aControl2, const VECTOR2I &aEnd, int aTolerance, int aLineThickness)
Generic fallback: Cubic Bezier curve rendered as a polyline.
Definition plotter.cpp:230
wxString m_creator
Definition plotter.h:736
int m_currentPenWidth
Definition plotter.h:732
double m_plotScale
Plot scale - chosen by the user (even implicitly with 'fit in a4')
Definition plotter.h:710
FILE * m_outputFile
Output file.
Definition plotter.h:727
static const int DO_NOT_SET_LINE_WIDTH
Definition plotter.h:139
virtual void PlotPoly(const std::vector< VECTOR2I > &aCornerList, FILL_T aFill, int aWidth, void *aData)=0
Draw a polygon ( filled or not ).
RENDER_SETTINGS * m_renderSettings
Definition plotter.h:746
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:547
double m_IUsPerDecimil
Definition plotter.h:716
virtual int GetCurrentLineWidth() const
Definition plotter.h:182
bool m_colorMode
Definition plotter.h:730
double GetDashMarkLenIU(int aLineWidth) const
Definition plotter.cpp:138
wxString m_filename
Definition plotter.h:737
Container for project specific data.
Definition project.h:63
virtual void SetColor(const COLOR4D &color) override
The SetColor implementation is split with the subclasses: the PSLIKE computes the rgb values,...
PSLIKE_PLOTTER(const PROJECT *aProject=nullptr)
virtual void SetTextMode(PLOT_TEXT_MODE mode) override
PS and PDF fully implement native text (for the Latin-1 subset)
const SHAPE_LINE_CHAIN Outline() const
void SetRadius(int aRadius)
Definition shape_rect.h:201
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 SetPlotBBox(const BOX2I &aBBoxIU) override
Set an explicit bounding box for the plotted content (in IUs).
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 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
SVG_PLOTTER(const PROJECT *aProject=nullptr)
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.
uint32_t m_brush_rgb_color
virtual void Rect(const VECTOR2I &p1, const VECTOR2I &p2, FILL_T fill, int width, int aCornerRadius=0) 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.
std::optional< BOX2I > m_plotBBoxIU
virtual void Circle(const VECTOR2I &pos, int diametre, FILL_T fill, int width) override
virtual void PlotPoly(const std::vector< VECTOR2I > &aCornerList, FILL_T aFill, int aWidth, void *aData) override
Draw a polygon ( filled or not ).
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 VECTOR2D userToDeviceCoordinates(const VECTOR2I &aCoordinate) override
Modify coordinates according to the orientation, scale factor, and offsets trace.
virtual void BezierCurve(const VECTOR2I &aStart, const VECTOR2I &aControl1, const VECTOR2I &aControl2, const VECTOR2I &aEnd, int aTolerance, int aLineThickness) override
Generic fallback: Cubic Bezier curve rendered as a polyline.
virtual void Arc(const VECTOR2D &aCenter, const EDA_ANGLE &aStartAngle, const EDA_ANGLE &aAngle, double aRadius, FILL_T aFill, int aWidth) override
virtual void PenTo(const VECTOR2I &pos, char plume) override
Moveto/lineto primitive, moves the 'pen' to the specified direction.
uint32_t m_pen_rgb_color
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 SetCurrentLineWidth(int width, void *aData=nullptr) override
Set the current line width (in IUs) for the next plot.
EDA_ORIENTATION m_Angle
GR_TEXT_H_ALIGN_T m_Halign
GR_TEXT_V_ALIGN_T m_Valign
static constexpr EDA_ANGLE ANGLE_180
Definition eda_angle.h:452
FILL_T
Definition eda_fill.h:29
@ FILLED_WITH_COLOR
Definition eda_fill.h:33
@ NO_FILL
Definition eda_fill.h:30
@ REVERSE_HATCH
Definition eda_fill.h:35
@ HATCH
Definition eda_fill.h:34
@ FILLED_WITH_BG_BODYCOLOR
Definition eda_fill.h:32
@ FILLED_SHAPE
Fill with object color.
Definition eda_fill.h:31
@ CROSS_HATCH
Definition eda_fill.h:36
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:95
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
Definition idf_helpers.h:37
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:437
Plotting engines similar to ps (PostScript, Gerber, svg)
wxString GetISO8601CurrentDateTime()
LINE_STYLE
Dashed line types.
int radius
VECTOR2I end
GR_TEXT_H_ALIGN_T
This is API surface mapped to common.types.HorizontalAlignment.
@ 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
This is API surface mapped to common.types.VertialAlignment.
@ GR_TEXT_V_ALIGN_BOTTOM
@ GR_TEXT_V_ALIGN_INDETERMINATE
@ GR_TEXT_V_ALIGN_CENTER
@ GR_TEXT_V_ALIGN_TOP
#define M_PI
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:227
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708
VECTOR2< double > VECTOR2D
Definition vector2d.h:707