KiCad PCB EDA Suite
gerber_placefile_writer.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) 2019 Jean_Pierre Charras <jp.charras at wanadoo.fr>
5  * Copyright (C) 1992-2019 KiCad Developers, see AUTHORS.txt for contributors.
6  *
7  * This program is free software: you can redistribute it and/or modify it
8  * under the terms of the GNU General Public License as published by the
9  * Free Software Foundation, either version 3 of the License, or (at your
10  * option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along
18  * with this program. If not, see <http://www.gnu.org/licenses/>.
19  */
20 
27 
28 #include <vector>
29 
30 #include <plotter.h>
31 #include <plotters_specific.h>
32 #include <kicad_string.h>
33 #include <locale_io.h>
34 #include <pcb_edit_frame.h>
35 #include <pgm_base.h>
36 
37 #include <board.h>
38 
39 #include <pcbplot.h>
41 #include <reporter.h>
42 #include <gbr_metadata.h>
43 #include <footprint.h>
44 
45 
47 {
48  m_pcb = aPcb;
49  m_plotPad1Marker = true; // Place a marker to pin 1 (or A1) position
50  m_plotOtherPadsMarker = true; // Place a marker to other pins position
51  m_layer = PCB_LAYER_ID::UNDEFINED_LAYER; // No layer set
52 }
53 
54 
55 int PLACEFILE_GERBER_WRITER::CreatePlaceFile( wxString& aFullFilename, PCB_LAYER_ID aLayer,
56  bool aIncludeBrdEdges )
57 {
58  m_layer = aLayer;
59 
60  PCB_PLOT_PARAMS plotOpts = m_pcb->GetPlotOptions();
61 
62  if( plotOpts.GetUseAuxOrigin() )
64 
65  // Collect footprints on the right layer
66  std::vector<FOOTPRINT*> fp_list;
67 
68  for( FOOTPRINT* footprint : m_pcb->Footprints() )
69  {
70  if( footprint->GetAttributes() & FP_EXCLUDE_FROM_POS_FILES )
71  continue;
72 
73  if( footprint->GetLayer() == aLayer )
74  fp_list.push_back( footprint );
75  }
76 
77  LOCALE_IO dummy_io; // Use the standard notation for float numbers
78 
79  GERBER_PLOTTER plotter;
80 
81  // Gerber drill file imply X2 format:
82  plotter.UseX2format( true );
83  plotter.UseX2NetAttributes( true );
84 
85  // Add the standard X2 header, without FileFunction
86  AddGerberX2Header( &plotter, m_pcb );
87  plotter.SetViewport( m_offset, IU_PER_MILS/10, /* scale */ 1.0, /* mirror */false );
88  // has meaning only for gerber plotter. Must be called only after SetViewport
89  plotter.SetGerberCoordinatesFormat( 6 );
90  plotter.SetCreator( wxT( "PCBNEW" ) );
91 
92  // Add the standard X2 FileFunction for P&P files
93  // %TF.FileFunction,Component,Ln,[top][bottom]*%
94  wxString text;
95  text.Printf( "%%TF.FileFunction,Component,L%d,%s*%%",
96  aLayer == B_Cu ? m_pcb->GetCopperLayerCount() : 1,
97  aLayer == B_Cu ? "Bot" : "Top" );
98  plotter.AddLineToHeader( text );
99 
100  // Add file polarity (positive)
101  text = "%TF.FilePolarity,Positive*%";
102  plotter.AddLineToHeader( text );
103 
104  if( !plotter.OpenFile( aFullFilename ) )
105  return -1;
106 
107  // We need a BRDITEMS_PLOTTER to plot pads
108  BRDITEMS_PLOTTER brd_plotter( &plotter, m_pcb, plotOpts );
109 
110  plotter.StartPlot();
111 
112  // Some tools in P&P files have the type and size defined.
113  // they are position flash (round), pad1 flash (diamond), other pads flash (round)
114  // and component outline thickness (polyline)
115  int flash_position_shape_diam = Millimeter2iu( 0.3 ); // defined size for position shape (circle)
116  int pad1_mark_size = Millimeter2iu( 0.36 ); // defined size for pad 1 position (diamond)
117  int other_pads_mark_size = 0; // defined size for position shape (circle)
118  int line_thickness = Millimeter2iu( 0.1 ); // defined size for component outlines
119 
120  brd_plotter.SetLayerSet( LSET( aLayer ) );
121  int cmp_count = 0;
122  bool allowUtf8 = true;
123 
124  // Plot components data: position, outlines, pad1 and other pads.
125  for( FOOTPRINT* footprint : fp_list )
126  {
127  // Manage the aperture attribute component position:
128  GBR_METADATA gbr_metadata;
130 
131  // Add object attribute: component reference to flash (mainly usefull for users)
132  // using quoted UTF8 string
133  wxString ref = ConvertNotAllowedCharsInGerber( footprint->Reference().GetShownText(),
134  allowUtf8, true );
135 
136  gbr_metadata.SetCmpReference( ref );
138 
139  // Add P&P specific attributes
140  GBR_CMP_PNP_METADATA pnpAttrib;
141 
142  // Add rotation info (rotation is CCW, in degrees):
143  pnpAttrib.m_Orientation = mapRotationAngle( footprint->GetOrientationDegrees() );
144 
146 
147  if( footprint->GetAttributes() & FP_THROUGH_HOLE )
149  else if( footprint->GetAttributes() & FP_SMD )
151 
152  // Add component value info:
153  pnpAttrib.m_Value = ConvertNotAllowedCharsInGerber( footprint->Value().GetShownText(),
154  allowUtf8, true );
155 
156  // Add component footprint info:
157  wxString fp_info = FROM_UTF8( footprint->GetFPID().GetLibItemName().c_str() );
158  pnpAttrib.m_Footprint = ConvertNotAllowedCharsInGerber( fp_info, allowUtf8, true );
159 
160  // Add footprint lib name:
161  fp_info = FROM_UTF8( footprint->GetFPID().GetLibNickname().c_str() );
162  pnpAttrib.m_LibraryName = ConvertNotAllowedCharsInGerber( fp_info, allowUtf8, true );
163 
164  gbr_metadata.m_NetlistMetadata.SetExtraData( pnpAttrib.FormatCmpPnPMetadata() );
165 
166  wxPoint flash_pos = footprint->GetPosition();
167 
168  plotter.FlashPadCircle( flash_pos, flash_position_shape_diam, FILLED, &gbr_metadata );
169  gbr_metadata.m_NetlistMetadata.ClearExtraData();
170 
171  // Now some extra metadata is output, avoid blindly clearing the full metadata list
173 
174  // We plot the footprint courtyard when possible.
175  // If not, the pads bounding box will be used.
176  bool useFpPadsBbox = true;
177  bool onBack = aLayer == B_Cu;
178 
179  footprint->BuildPolyCourtyards();
180 
181  int checkFlag = onBack ? MALFORMED_B_COURTYARD : MALFORMED_F_COURTYARD;
182 
183  if( ( footprint->GetFlags() & checkFlag ) == 0 )
184  {
186 
187  const SHAPE_POLY_SET& courtyard = onBack ? footprint->GetPolyCourtyardBack()
188  : footprint->GetPolyCourtyardFront();
189 
190  for( int ii = 0; ii < courtyard.OutlineCount(); ii++ )
191  {
192  SHAPE_LINE_CHAIN poly = courtyard.Outline( ii );
193 
194  if( !poly.PointCount() )
195  continue;
196 
197  useFpPadsBbox = false;
198  plotter.PLOTTER::PlotPoly( poly, FILL_TYPE::NO_FILL, line_thickness, &gbr_metadata );
199  }
200  }
201 
202  if( useFpPadsBbox )
203  {
205 
206  // bbox of fp pads, pos 0, rot 0, non flipped
207  EDA_RECT bbox = footprint->GetFpPadsLocalBbox();
208 
209  // negate bbox Y values if the fp is flipped (always flipped around X axis
210  // in Gerber P&P files).
211  int y_sign = aLayer == B_Cu ? -1 : 1;
212 
213  SHAPE_LINE_CHAIN poly;
214  poly.Append( bbox.GetLeft(), y_sign*bbox.GetTop() );
215  poly.Append( bbox.GetLeft(), y_sign*bbox.GetBottom() );
216  poly.Append( bbox.GetRight(), y_sign*bbox.GetBottom() );
217  poly.Append( bbox.GetRight(), y_sign*bbox.GetTop() );
218  poly.SetClosed( true );
219 
220  poly.Rotate( -footprint->GetOrientationRadians(), VECTOR2I( 0, 0 ) );
221  poly.Move( footprint->GetPosition() );
222  plotter.PLOTTER::PlotPoly( poly, FILL_TYPE::NO_FILL, line_thickness, &gbr_metadata );
223  }
224 
225  std::vector<PAD*>pad_key_list;
226 
227  if( m_plotPad1Marker )
228  {
229  findPads1( pad_key_list, footprint );
230 
231  for( PAD* pad1 : pad_key_list )
232  {
233  gbr_metadata.SetApertureAttrib(
235 
236  gbr_metadata.SetPadName( pad1->GetName(), allowUtf8, true );
237 
238  gbr_metadata.SetPadPinFunction( pad1->GetPinFunction(), allowUtf8, true );
239 
241 
242  // Flashes a diamond at pad position:
243  plotter.FlashRegularPolygon( pad1->GetPosition(),
244  pad1_mark_size,
245  4, 0.0, FILLED, &gbr_metadata );
246  }
247  }
248 
250  {
251 
252  gbr_metadata.SetApertureAttrib(
255 
256  for( PAD* pad: footprint->Pads() )
257  {
258  bool skip_pad = false;
259 
260  for( PAD* pad1 : pad_key_list )
261  {
262  if( pad == pad1 ) // Already plotted
263  {
264  skip_pad = true;
265  break;
266  }
267  }
268 
269  if( skip_pad )
270  continue;
271 
272  // Skip also pads not on the current layer, like pads only
273  // on a tech layer
274  if( !pad->IsOnLayer( aLayer ) )
275  continue;
276 
277  gbr_metadata.SetPadName( pad->GetName(), allowUtf8, true );
278 
279  gbr_metadata.SetPadPinFunction( pad->GetPinFunction(), allowUtf8, true );
280 
281  // Flashes a round, 0 sized round shape at pad position
282  plotter.FlashPadCircle( pad->GetPosition(),
283  other_pads_mark_size,
284  FILLED, &gbr_metadata );
285  }
286  }
287 
288  plotter.ClearAllAttributes(); // Unconditionally close all .TO attributes
289 
290  cmp_count++;
291  }
292 
293  // Plot board outlines, if requested
294  if( aIncludeBrdEdges )
295  {
296  brd_plotter.SetLayerSet( LSET( Edge_Cuts ) );
297 
298  // Plot edge layer and graphic items
299  brd_plotter.PlotBoardGraphicItems();
300 
301  // Draw footprint other graphic items:
302  for( FOOTPRINT* footprint : fp_list )
303  {
304  for( BOARD_ITEM* item : footprint->GraphicalItems() )
305  {
306  if( item->Type() == PCB_FP_SHAPE_T && item->GetLayer() == Edge_Cuts )
307  brd_plotter.PlotFootprintGraphicItem( (FP_SHAPE*) item );
308  }
309  }
310  }
311 
312 
313  plotter.EndPlot();
314 
315  return cmp_count;
316 }
317 
318 
320 {
321  // convert a kicad footprint orientation to gerber rotation, depending on the layer
322  // Currently, same notation as kicad
323  return aAngle;
324 }
325 
326 
327 void PLACEFILE_GERBER_WRITER::findPads1( std::vector<PAD*>& aPadList, FOOTPRINT* aFootprint ) const
328 {
329  // Fint the pad "1" or pad "A1"
330  // this is possible only if only one pad is found
331  // Usefull to place a marker in this position
332 
333  for( PAD* pad : aFootprint->Pads() )
334  {
335  if( !pad->IsOnLayer( m_layer ) )
336  continue;
337 
338  if( pad->GetName() == "1" || pad->GetName() == "A1")
339  aPadList.push_back( pad );
340  }
341 }
342 
343 
344 const wxString PLACEFILE_GERBER_WRITER::GetPlaceFileName( const wxString& aFullBaseFilename,
345  PCB_LAYER_ID aLayer ) const
346 {
347  // Gerber files extension is always .gbr.
348  // Therefore, to mark pnp files, add "-pnp" to the filename, and a layer id.
349  wxFileName fn = aFullBaseFilename;
350 
351  wxString post_id = "-pnp_";
352  post_id += aLayer == B_Cu ? "bottom" : "top";
353  fn.SetName( fn.GetName() + post_id );
354  fn.SetExt( GerberFileExtension );
355 
356  return fn.GetFullPath();
357 }
virtual void FlashRegularPolygon(const wxPoint &aShapePos, int aDiameter, int aCornerCount, double aOrient, OUTLINE_MODE aTraceMode, void *aData) override
Flash a regular polygon.
Handle special data (items attributes) during plot.
Classes used in place file generation.
int CreatePlaceFile(wxString &aFullFilename, PCB_LAYER_ID aLayer, bool aIncludeBrdEdges)
Creates an pnp gerber file.
aperture used to draw component outline courtyard in placement files.
Definition: gbr_metadata.h:161
Plot settings, and plotting engines (PostScript, Gerber, HPGL and DXF)
virtual void SetCreator(const wxString &aCreator)
Definition: plotter.h:172
const PCB_PLOT_PARAMS & GetPlotOptions() const
Definition: board.h:602
int OutlineCount() const
Return the number of vertices in a given outline/hole.
void UseX2NetAttributes(bool aEnable)
static wxString FROM_UTF8(const char *cstring)
Convert a UTF8 encoded C string to a wxString for all wxWidgets build modes.
Definition: macros.h:110
aperture used for flashed pads position in placement files.
Definition: gbr_metadata.h:149
Instantiate the current locale within a scope in which you are expecting exceptions to be thrown.
Definition: locale_io.h:40
aperture used to draw component physical body outline without pins in placement files.
Definition: gbr_metadata.h:152
print info associated to a component (TO.C attribute)
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
Definition: board_item.h:82
Plotting engines (PostScript, Gerber, HPGL and DXF)
int GetTop() const
Definition: eda_rect.h:118
virtual bool OpenFile(const wxString &aFullFilename)
Open or create the plot file aFullFilename.
Definition: plotter.cpp:76
void SetNetAttribType(int aNetAttribType)
Definition: gbr_metadata.h:219
int GetLeft() const
Definition: eda_rect.h:117
void Move(const VECTOR2I &aVector) override
void AddGerberX2Header(PLOTTER *aPlotter, const BOARD *aBoard, bool aUseX1CompatibilityMode)
Calculates some X2 attributes, as defined in the Gerber file format specification J4 (chapter 5) and ...
Definition: pcbplot.cpp:279
void UseX2format(bool aEnable)
BOARD_DESIGN_SETTINGS & GetDesignSettings() const
Definition: board.h:584
class FP_SHAPE, a footprint edge
Definition: typeinfo.h:93
const std::string GerberFileExtension
void AddLineToHeader(const wxString &aExtraString)
Add a line to the list of free lines to print at the beginning of the file.
Definition: plotter.h:180
VECTOR2< int > VECTOR2I
Definition: vector2d.h:623
int PointCount() const
Function PointCount()
virtual bool StartPlot() override
Function StartPlot Write GERBER header to file initialize global variable g_Plot_PlotOutputFile.
Information which can be added in a gerber P&P file as attribute of a component.
void Append(int aX, int aY, bool aAllowDuplication=false)
Function Append()
PADS & Pads()
Definition: footprint.h:164
int GetBottom() const
Definition: eda_rect.h:119
void SetPadPinFunction(const wxString &aPadPinFunction, bool aUseUTF8, bool aEscapeString)
Definition: gbr_metadata.h:236
Board plot function definition file.
void SetClosed(bool aClosed)
Function SetClosed()
PCB_LAYER_ID
A quick note on layer IDs:
LSET is a set of PCB_LAYER_IDs.
#define MALFORMED_B_COURTYARD
Definition: eda_item.h:124
void SetLayerSet(LSET aLayerMask)
Definition: pcbplot.h:90
void ClearAllAttributes()
Remove (clear) all attributes from object attributes dictionary (TO.
void SetExtraData(const wxString &aExtraData)
Set the extra data string printed at end of net attributes.
Represent a set of closed polygons.
void SetPadName(const wxString &aPadname, bool aUseUTF8=false, bool aEscapeString=false)
Definition: gbr_metadata.h:231
SHAPE_LINE_CHAIN & Outline(int aIndex)
void PlotBoardGraphicItems()
plot items like text and graphics, but not tracks and footprints
FOOTPRINTS & Footprints()
Definition: board.h:296
int GetRight() const
Definition: eda_rect.h:116
Definition of file extensions used in Kicad.
virtual void SetViewport(const wxPoint &aOffset, double aIusPerDecimil, double aScale, bool aMirror) override
Set the plot offset and scaling for the current plot.
Metadata which can be added in a gerber file as attribute in X2 format.
Definition: gbr_metadata.h:204
PCB_PLOT_PARAMS handles plot parameters and options when plotting/printing a board.
void Rotate(double aAngle, const VECTOR2I &aCenter=VECTOR2I(0, 0)) override
Function Rotate rotates all vertices by a given angle.
#define MALFORMED_F_COURTYARD
Definition: eda_item.h:123
aperture used for flashed pin 1 (or A1 or AA1) position in placement files.
Definition: gbr_metadata.h:146
const wxString GetPlaceFileName(const wxString &aFullBaseFilename, PCB_LAYER_ID aLayer) const
see class PGM_BASE
wxString FormatCmpPnPMetadata()
Information pertinent to a Pcbnew printed circuit board.
Definition: board.h:189
void findPads1(std::vector< PAD * > &aPadList, FOOTPRINT *aFootprint) const
Find the pad(s) 1 (or pad "A1") of a footprint Usefull to plot a marker at this (these) position(s)
virtual bool EndPlot() override
SHAPE_LINE_CHAIN.
void PlotFootprintGraphicItem(FP_SHAPE *aShape)
int GetCopperLayerCount() const
Definition: board.cpp:435
Handle the component boundary box.
Definition: eda_rect.h:42
#define IU_PER_MILS
Definition: plotter.cpp:137
bool m_TryKeepPreviousAttributes
If true, do not clear all attributes when a attribute has changed.
wxString ConvertNotAllowedCharsInGerber(const wxString &aString, bool aAllowUtf8Chars, bool aQuoteString)
Normalize aString and convert it to a Gerber compatible wxString.
virtual void SetGerberCoordinatesFormat(int aResolution, bool aUseInches=false) override
Function SetGerberCoordinatesFormat selection of Gerber units and resolution (number of digits in man...
print info associated to a flashed pad (TO.P attribute)
double mapRotationAngle(double aAngle)
convert a kicad footprint orientation to gerber rotation both are in degrees
void SetApertureAttrib(GBR_APERTURE_METADATA::GBR_APERTURE_ATTRIB aApertAttribute)
Definition: gbr_metadata.h:209
virtual void FlashPadCircle(const wxPoint &pos, int diametre, OUTLINE_MODE trace_mode, void *aData) override
Filled circular flashes are stored as apertures.
GBR_NETLIST_METADATA m_NetlistMetadata
An item to handle object attribute.
Definition: gbr_metadata.h:262
bool GetUseAuxOrigin() const
Definition: pad.h:60
static constexpr int Millimeter2iu(double mm)
void SetCmpReference(const wxString &aComponentRef)
Definition: gbr_metadata.h:241
wxPoint m_AuxOrigin
origin for plot exports
void ClearExtraData()
Clear the extra data string printed at end of net attributes.