KiCad PCB EDA Suite
bitmap2component.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) 1992-2019 jean-pierre.charras
5 * Copyright (C) 1992-2021 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#include <algorithm> // std::max
26#include <cerrno>
27#include <cmath>
28#include <cstdio>
29#include <cstdlib>
30#include <cstring>
31#include <string>
32#include <vector>
33#include <kiid.h>
34
35#include <layer_ids.h>
36
37#include <locale_io.h>
38#include <potracelib.h>
39
40#include "bitmap2component.h"
41
42
43/* free a potrace bitmap */
44static void bm_free( potrace_bitmap_t* bm )
45{
46 if( bm != nullptr )
47 {
48 free( bm->map );
49 }
50
51 free( bm );
52}
53
54
55static void BezierToPolyline( std::vector <potrace_dpoint_t>& aCornersBuffer,
56 potrace_dpoint_t p1,
57 potrace_dpoint_t p2,
58 potrace_dpoint_t p3,
59 potrace_dpoint_t p4 );
60
62 m_Data( aData )
63{
65 m_PixmapWidth = 0;
67 m_ScaleX = 1.0;
68 m_ScaleY = 1.0;
69 m_Paths = nullptr;
70 m_CmpName = "LOGO";
71}
72
73
74int BITMAPCONV_INFO::ConvertBitmap( potrace_bitmap_t* aPotrace_bitmap, OUTPUT_FMT_ID aFormat,
75 int aDpi_X, int aDpi_Y, BMP2CMP_MOD_LAYER aModLayer )
76{
77 potrace_param_t* param;
78 potrace_state_t* st;
79
80 // set tracing parameters, starting from defaults
81 param = potrace_param_default();
82
83 if( !param )
84 {
85 char msg[256];
86 sprintf( msg, "Error allocating parameters: %s\n", strerror( errno ) );
87 m_errors += msg;
88 return 1;
89 }
90
91 // For parameters: see http://potrace.sourceforge.net/potracelib.pdf
92 param->turdsize = 0; // area (in pixels) of largest path to be ignored.
93 // Potrace default is 2
94 param->opttolerance = 0.2; // curve optimization tolerance. Potrace default is 0.2
95
96 /* convert the bitmap to curves */
97 st = potrace_trace( param, aPotrace_bitmap );
98
99 if( !st || st->status != POTRACE_STATUS_OK )
100 {
101 if( st )
102 {
103 potrace_state_free( st );
104 }
105
106 potrace_param_free( param );
107
108 char msg[256];
109 sprintf( msg, "Error tracing bitmap: %s\n", strerror( errno ) );
110 m_errors += msg;
111 return 1;
112 }
113
114 m_PixmapWidth = aPotrace_bitmap->w;
115 m_PixmapHeight = aPotrace_bitmap->h; // the bitmap size in pixels
116 m_Paths = st->plist;
117
118 switch( aFormat )
119 {
120 case KICAD_WKS_LOGO:
122 m_ScaleX = PL_IU_PER_MM * 25.4 / aDpi_X; // the conversion scale from PPI to micron
123 m_ScaleY = PL_IU_PER_MM * 25.4 / aDpi_Y; // Y axis is top to bottom
125 break;
126
127 case POSTSCRIPT_FMT:
129 m_ScaleX = 1.0; // the conversion scale
131
132 // output vector data, e.g. as a rudimentary EPS file (mainly for tests)
134 break;
135
136 case EESCHEMA_FMT:
138 m_ScaleX = SCH_IU_PER_MM * 25.4 / aDpi_X; // the conversion scale from PPI to eeschema iu
139 m_ScaleY = -SCH_IU_PER_MM * 25.4 / aDpi_Y; // Y axis is bottom to Top for components in libs
141 break;
142
143 case PCBNEW_KICAD_MOD:
145 m_ScaleX = PCB_IU_PER_MM * 25.4 / aDpi_X; // the conversion scale from PPI to IU
146 m_ScaleY = PCB_IU_PER_MM * 25.4 / aDpi_Y; // Y axis is top to bottom in Footprint Editor
147 createOutputData( aModLayer );
148 break;
149
150 default:
151 break;
152 }
153
154
155 bm_free( aPotrace_bitmap );
156 potrace_state_free( st );
157 potrace_param_free( param );
158
159 return 0;
160}
161
162
164{
165 const char* layerName = "F.SilkS";
166
167 switch( aChoice )
168 {
170 layerName = "F.Mask";
171 break;
172
173 case MOD_LYR_ECO1:
174 layerName = "Eco1.User";
175 break;
176
177 case MOD_LYR_ECO2:
178 layerName = "Eco2.User";
179 break;
180
181 case MOD_LYR_FSILKS:
182 default: // case MOD_LYR_FSILKS only unless there is a bug
183 break;
184 }
185
186 return layerName;
187}
188
189
190void BITMAPCONV_INFO::outputDataHeader( const char * aBrdLayerName )
191{
192 double Ypos = ( m_PixmapHeight / 2 * m_ScaleY ); // fields Y position in mm
193 double fieldSize; // fields text size in mm
194 char strbuf[1024];
195
196 switch( m_Format )
197 {
198 case POSTSCRIPT_FMT:
199 /* output vector data, e.g. as a rudimentary EPS file */
200 m_Data += "%%!PS-Adobe-3.0 EPSF-3.0\n";
201 sprintf( strbuf, "%%%%BoundingBox: 0 0 %d %d\n", m_PixmapWidth, m_PixmapHeight );
202 m_Data += strbuf;
203 m_Data += "gsave\n";
204 break;
205
206 case PCBNEW_KICAD_MOD:
207 // fields text size = 1.5 mm
208 // fields text thickness = 1.5 / 5 = 0.3mm
209 sprintf( strbuf,
210 "(footprint \"%s\" (version 20221018) (generator bitmap2component)\n"
211 " (layer \"F.Cu\")\n",
212 m_CmpName.c_str() );
213
214 m_Data += strbuf;
215 sprintf( strbuf, " (attr board_only exclude_from_pos_files exclude_from_bom)\n" );
216 m_Data += strbuf;
217 sprintf( strbuf,
218 " (fp_text reference \"G***\" (at 0 0) (layer \"%s\")\n"
219 " (effects (font (size 1.5 1.5) (thickness 0.3)))\n"
220 " (tstamp %s)\n )\n",
221 aBrdLayerName, KIID().AsString().ToStdString().c_str() );
222
223 m_Data += strbuf;
224 sprintf( strbuf,
225 " (fp_text value \"%s\" (at 0.75 0) (layer \"%s\") hide\n"
226 " (effects (font (size 1.5 1.5) (thickness 0.3)))\n"
227 " (tstamp %s)\n )\n",
228 m_CmpName.c_str(), aBrdLayerName, KIID().AsString().ToStdString().c_str() );
229
230 m_Data += strbuf;
231 break;
232
233 case KICAD_WKS_LOGO:
234 m_Data += "(kicad_wks (version 20220228) (generator bitmap2component)\n";
235 m_Data += " (setup (textsize 1.5 1.5)(linewidth 0.15)(textlinewidth 0.15)\n";
236 m_Data += " (left_margin 10)(right_margin 10)(top_margin 10)(bottom_margin 10))\n";
237 m_Data += " (polygon (name \"\") (pos 0 0) (linewidth 0.01)\n";
238 break;
239
240 case EESCHEMA_FMT:
241 fieldSize = 1.27; // fields text size in mm (= 50 mils)
242 Ypos /= SCH_IU_PER_MM;
243 Ypos += fieldSize / 2;
244 // sprintf( strbuf, "# pixmap size w = %d, h = %d\n#\n", m_PixmapWidth, m_PixmapHeight );
245 sprintf( strbuf,
246 "(kicad_symbol_lib (version 20220914) (generator bitmap2component)\n"
247 " (symbol \"%s\" (pin_names (offset 1.016)) (in_bom yes) (on_board yes)\n",
248 m_CmpName.c_str() );
249 m_Data += strbuf;
250
251 sprintf( strbuf,
252 " (property \"Reference\" \"#G\" (at 0 %g 0)\n"
253 " (effects (font (size %g %g)) hide)\n )\n",
254 -Ypos, fieldSize, fieldSize );
255 m_Data += strbuf;
256
257 sprintf( strbuf,
258 " (property \"Value\" \"%s\" (at 0 %g 0)\n"
259 " (effects (font (size %g %g)) hide)\n )\n",
260 m_CmpName.c_str(), Ypos, fieldSize, fieldSize );
261 m_Data += strbuf;
262
263 sprintf( strbuf,
264 " (property \"Footprint\" \"\" (at 0 0 0)\n"
265 " (effects (font (size %g %g)) hide)\n )\n",
266 fieldSize, fieldSize );
267 m_Data += strbuf;
268
269 sprintf( strbuf,
270 " (property \"Datasheet\" \"\" (at 0 0 0)\n"
271 " (effects (font (size %g %g)) hide)\n )\n",
272 fieldSize, fieldSize );
273 m_Data += strbuf;
274
275 sprintf( strbuf, " (symbol \"%s_0_0\"\n", m_CmpName.c_str() );
276 m_Data += strbuf;
277 break;
278 }
279}
280
281
283{
284 switch( m_Format )
285 {
286 case POSTSCRIPT_FMT:
287 m_Data += "grestore\n";
288 m_Data += "%%EOF\n";
289 break;
290
291 case PCBNEW_KICAD_MOD:
292 m_Data += ")\n";
293 break;
294
295 case KICAD_WKS_LOGO:
296 m_Data += " )\n)\n";
297 break;
298
299 case EESCHEMA_FMT:
300 m_Data += " )\n"; // end symbol_0_0
301 m_Data += " )\n"; // end symbol
302 m_Data += ")\n"; // end lib
303 break;
304 }
305}
306
307
308void BITMAPCONV_INFO::outputOnePolygon( SHAPE_LINE_CHAIN& aPolygon, const char* aBrdLayerName )
309{
310 // write one polygon to output file.
311 // coordinates are expected in target unit.
312 int ii, jj;
313 VECTOR2I currpoint;
314 char strbuf[1024];
315
316 int offsetX = (int)( m_PixmapWidth / 2 * m_ScaleX );
317 int offsetY = (int)( m_PixmapHeight / 2 * m_ScaleY );
318
319 const VECTOR2I startpoint = aPolygon.CPoint( 0 );
320
321 switch( m_Format )
322 {
323 case POSTSCRIPT_FMT:
324 offsetY = (int)( m_PixmapHeight * m_ScaleY );
325 sprintf( strbuf, "newpath\n%d %d moveto\n", startpoint.x, offsetY - startpoint.y );
326 m_Data += strbuf;
327 jj = 0;
328
329 for( ii = 1; ii < aPolygon.PointCount(); ii++ )
330 {
331 currpoint = aPolygon.CPoint( ii );
332 sprintf( strbuf, " %d %d lineto", currpoint.x, offsetY - currpoint.y );
333 m_Data += strbuf;
334
335 if( jj++ > 6 )
336 {
337 jj = 0;
338 m_Data += "\n";
339 }
340 }
341
342 m_Data += "\nclosepath fill\n";
343 break;
344
345 case PCBNEW_KICAD_MOD:
346 {
347 double width = 0.0; // outline thickness in mm: no thickness
348 m_Data += " (fp_poly\n (pts\n";
349
350 jj = 0;
351
352 for( ii = 0; ii < aPolygon.PointCount(); ii++ )
353 {
354 currpoint = aPolygon.CPoint( ii );
355 sprintf( strbuf, " (xy %f %f)\n",
356 ( currpoint.x - offsetX ) / PCB_IU_PER_MM,
357 ( currpoint.y - offsetY ) / PCB_IU_PER_MM );
358 m_Data += strbuf;
359 }
360 // No need to close polygon
361
362 m_Data += " )\n\n";
363 sprintf( strbuf,
364 " (stroke (width %f) (type solid)) (fill solid) (layer \"%s\") (tstamp %s))\n",
365 width, aBrdLayerName, KIID().AsString().ToStdString().c_str() );
366
367 m_Data += strbuf;
368 }
369 break;
370
371 case KICAD_WKS_LOGO:
372 m_Data += " (pts";
373
374 // Internal units = micron, file unit = mm
375 jj = 1;
376
377 for( ii = 0; ii < aPolygon.PointCount(); ii++ )
378 {
379 currpoint = aPolygon.CPoint( ii );
380 sprintf( strbuf, " (xy %.3f %.3f)",
381 ( currpoint.x - offsetX ) / PL_IU_PER_MM,
382 ( currpoint.y - offsetY ) / PL_IU_PER_MM );
383 m_Data += strbuf;
384
385 if( jj++ > 4 )
386 {
387 jj = 0;
388 m_Data += "\n ";
389 }
390 }
391
392 // Close polygon
393 sprintf( strbuf, " (xy %.3f %.3f) )\n",
394 ( startpoint.x - offsetX ) / PL_IU_PER_MM,
395 ( startpoint.y - offsetY ) / PL_IU_PER_MM );
396 m_Data += strbuf;
397 break;
398
399 case EESCHEMA_FMT:
400 // The polygon outline thickness is fixed here to 0.01 ( 0.0 is the default thickness)
401 #define SCH_LINE_THICKNESS_MM 0.01
402 //sprintf( strbuf, "P %d 0 0 %d", (int) aPolygon.PointCount() + 1, EE_LINE_THICKNESS );
403 m_Data += " (polyline\n (pts\n";
404
405 for( ii = 0; ii < aPolygon.PointCount(); ii++ )
406 {
407 currpoint = aPolygon.CPoint( ii );
408 sprintf( strbuf, " (xy %f %f)\n",
409 ( currpoint.x - offsetX ) / SCH_IU_PER_MM,
410 ( currpoint.y - offsetY ) / SCH_IU_PER_MM );
411 m_Data += strbuf;
412 }
413
414 // Close polygon
415 sprintf( strbuf, " (xy %f %f)\n",
416 ( startpoint.x - offsetX ) / SCH_IU_PER_MM,
417 ( startpoint.y - offsetY ) / SCH_IU_PER_MM );
418 m_Data += strbuf;
419 m_Data += " )\n"; // end pts
420
421 sprintf( strbuf,
422 " (stroke (width %g) (type default))\n (fill (type outline))\n",
424
425 m_Data += strbuf;
426 m_Data += " )\n"; // end polyline
427 break;
428 }
429}
430
431
433{
434 std::vector <potrace_dpoint_t> cornersBuffer;
435
436 // polyset_areas is a set of polygon to draw
437 SHAPE_POLY_SET polyset_areas;
438
439 // polyset_holes is the set of holes inside polyset_areas outlines
440 SHAPE_POLY_SET polyset_holes;
441
442 potrace_dpoint_t( *c )[3];
443
444 LOCALE_IO toggle; // Temporary switch the locale to standard C to r/w floats
445
446 // The layer name has meaning only for .kicad_mod files.
447 // For these files the header creates 2 invisible texts: value and ref
448 // (needed but not useful) on silk screen layer
450
451 bool main_outline = true;
452
453 /* draw each as a polygon with no hole.
454 * Bezier curves are approximated by a polyline
455 */
456 potrace_path_t* paths = m_Paths; // the list of paths
457
458 if(!m_Paths)
459 {
460 m_errors += "No shape in black and white image to convert: no outline created\n";
461 }
462
463 while( paths != nullptr )
464 {
465 int cnt = paths->curve.n;
466 int* tag = paths->curve.tag;
467 c = paths->curve.c;
468 potrace_dpoint_t startpoint = c[cnt - 1][2];
469
470 for( int i = 0; i < cnt; i++ )
471 {
472 switch( tag[i] )
473 {
474 case POTRACE_CORNER:
475 cornersBuffer.push_back( c[i][1] );
476 cornersBuffer.push_back( c[i][2] );
477 startpoint = c[i][2];
478 break;
479
480 case POTRACE_CURVETO:
481 BezierToPolyline( cornersBuffer, startpoint, c[i][0], c[i][1], c[i][2] );
482 startpoint = c[i][2];
483 break;
484 }
485 }
486
487 // Store current path
488 if( main_outline )
489 {
490 main_outline = false;
491
492 // build the current main polygon
493 polyset_areas.NewOutline();
494 for( unsigned int i = 0; i < cornersBuffer.size(); i++ )
495 {
496 polyset_areas.Append( int( cornersBuffer[i].x * m_ScaleX ),
497 int( cornersBuffer[i].y * m_ScaleY ) );
498 }
499 }
500 else
501 {
502 // Add current hole in polyset_holes
503 polyset_holes.NewOutline();
504
505 for( unsigned int i = 0; i < cornersBuffer.size(); i++ )
506 {
507 polyset_holes.Append( int( cornersBuffer[i].x * m_ScaleX ),
508 int( cornersBuffer[i].y * m_ScaleY ) );
509 }
510 }
511
512 cornersBuffer.clear();
513
514 // at the end of a group of a positive path and its negative children, fill.
515 if( paths->next == nullptr || paths->next->sign == '+' )
516 {
519 polyset_areas.BooleanSubtract( polyset_holes, SHAPE_POLY_SET::PM_STRICTLY_SIMPLE );
520
521 // Ensure there are no self intersecting polygons
522 if( polyset_areas.NormalizeAreaOutlines() )
523 {
524 // Convert polygon with holes to a unique polygon
526
527 // Output current resulting polygon(s)
528 for( int ii = 0; ii < polyset_areas.OutlineCount(); ii++ )
529 {
530 SHAPE_LINE_CHAIN& poly = polyset_areas.Outline( ii );
531 outputOnePolygon( poly, getBoardLayerName( aModLayer ));
532 }
533
534 polyset_areas.RemoveAllContours();
535 polyset_holes.RemoveAllContours();
536 main_outline = true;
537 }
538 }
539
540 paths = paths->next;
541 }
542
544}
545
546// a helper function to calculate a square value
547inline double square( double x )
548{
549 return x * x;
550}
551
552
553// a helper function to calculate a cube value
554inline double cube( double x )
555{
556 return x * x * x;
557}
558
559
560/* render a Bezier curve. */
561void BezierToPolyline( std::vector <potrace_dpoint_t>& aCornersBuffer,
562 potrace_dpoint_t p1,
563 potrace_dpoint_t p2,
564 potrace_dpoint_t p3,
565 potrace_dpoint_t p4 )
566{
567 double dd0, dd1, dd, delta, e2, epsilon, t;
568
569 // p1 = starting point
570
571 /* we approximate the curve by small line segments. The interval
572 * size, epsilon, is determined on the fly so that the distance
573 * between the true curve and its approximation does not exceed the
574 * desired accuracy delta. */
575
576 delta = 0.25; /* desired accuracy, in pixels */
577
578 /* let dd = maximal value of 2nd derivative over curve - this must
579 * occur at an endpoint. */
580 dd0 = square( p1.x - 2 * p2.x + p3.x ) + square( p1.y - 2 * p2.y + p3.y );
581 dd1 = square( p2.x - 2 * p3.x + p4.x ) + square( p2.y - 2 * p3.y + p4.y );
582 dd = 6 * sqrt( std::max( dd0, dd1 ) );
583 e2 = 8 * delta <= dd ? 8 * delta / dd : 1;
584 epsilon = sqrt( e2 ); /* necessary interval size */
585
586 for( t = epsilon; t<1; t += epsilon )
587 {
588 potrace_dpoint_t intermediate_point;
589 intermediate_point.x = p1.x * cube( 1 - t ) +
590 3* p2.x* square( 1 - t ) * t +
591 3 * p3.x * (1 - t) * square( t ) +
592 p4.x* cube( t );
593
594 intermediate_point.y = p1.y * cube( 1 - t ) +
595 3* p2.y* square( 1 - t ) * t +
596 3 * p3.y * (1 - t) * square( t ) + p4.y* cube( t );
597
598 aCornersBuffer.push_back( intermediate_point );
599 }
600
601 aCornersBuffer.push_back( p4 );
602}
constexpr double SCH_IU_PER_MM
Definition: base_units.h:73
constexpr double PCB_IU_PER_MM
Definition: base_units.h:71
constexpr double PL_IU_PER_MM
Definition: base_units.h:72
double square(double x)
static void BezierToPolyline(std::vector< potrace_dpoint_t > &aCornersBuffer, potrace_dpoint_t p1, potrace_dpoint_t p2, potrace_dpoint_t p3, potrace_dpoint_t p4)
double cube(double x)
static void bm_free(potrace_bitmap_t *bm)
#define SCH_LINE_THICKNESS_MM
BMP2CMP_MOD_LAYER
@ MOD_LYR_ECO1
@ MOD_LYR_FSILKS
@ MOD_LYR_ECO2
@ MOD_LYR_FSOLDERMASK
OUTPUT_FMT_ID
@ KICAD_WKS_LOGO
@ PCBNEW_KICAD_MOD
@ POSTSCRIPT_FMT
@ EESCHEMA_FMT
void outputDataEnd()
Function outputDataEnd write to file the last strings depending on file format.
std::string & m_Data
BITMAPCONV_INFO(std::string &aData)
potrace_path_t * m_Paths
std::string m_CmpName
void outputDataHeader(const char *aBrdLayerName)
Function outputDataHeader write to file the header depending on file format.
void outputOnePolygon(SHAPE_LINE_CHAIN &aPolygon, const char *aBrdLayerName)
Function outputOnePolygon write one polygon to output file.
enum OUTPUT_FMT_ID m_Format
void createOutputData(BMP2CMP_MOD_LAYER aModLayer=(BMP2CMP_MOD_LAYER) 0)
Creates the data specified by m_Format.
int ConvertBitmap(potrace_bitmap_t *aPotrace_bitmap, OUTPUT_FMT_ID aFormat, int aDpi_X, int aDpi_Y, BMP2CMP_MOD_LAYER aModLayer)
Run the conversion of the bitmap.
std::string m_errors
const char * getBoardLayerName(BMP2CMP_MOD_LAYER aChoice)
Definition: kiid.h:48
Instantiate the current locale within a scope in which you are expecting exceptions to be thrown.
Definition: locale_io.h:41
Represent a polyline containing arcs as well as line segments: A chain of connected line and/or arc s...
int PointCount() const
Return the number of points (vertices) in this line chain.
const VECTOR2I & CPoint(int aIndex) const
Return a reference to a given point in the line chain.
Represent a set of closed polygons.
void BooleanSubtract(const SHAPE_POLY_SET &b, POLYGON_MODE aFastMode)
Perform boolean polyset intersection For aFastMode meaning, see function booleanOp.
void Fracture(POLYGON_MODE aFastMode)
Convert a single outline slitted ("fractured") polygon into a set ouf outlines with holes.
int NormalizeAreaOutlines()
Convert a self-intersecting polygon to one (or more) non self-intersecting polygon(s).
int Append(int x, int y, int aOutline=-1, int aHole=-1, bool aAllowDuplication=false)
Add a new vertex to the contour indexed by aOutline and aHole (defaults to the outline of the last po...
void Simplify(POLYGON_MODE aFastMode)
SHAPE_LINE_CHAIN & Outline(int aIndex)
int NewOutline()
Creates a new hole in a given outline.
int OutlineCount() const
Return the number of vertices in a given outline/hole.
_OUT_STRING AsString(const std::string &aString)
Definition: sexpr.h:131
constexpr int delta