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 
26 #include <fctsys.h>
28 
29 #include <vector>
30 
31 #include <plotter.h>
32 #include <kicad_string.h>
33 #include <pcb_edit_frame.h>
34 #include <pgm_base.h>
35 
36 #include <class_board.h>
37 
38 #include <pcbplot.h>
39 #include <pcbnew.h>
41 #include <reporter.h>
42 #include <gbr_metadata.h>
43 #include <class_module.h>
44 
45 
47 {
48  m_pcb = aPcb;
49  /* Set conversion scale depending on drill file units */
50  m_conversionUnits = 1.0 / IU_PER_MM; // Gerber units = mm
51  m_forceSmdItems = false;
52  m_plotPad1Marker = true; // Place a marker to pin 1 (or A1) position
53  m_plotOtherPadsMarker = true; // Place a marker to other pins position
54  m_layer = PCB_LAYER_ID::UNDEFINED_LAYER; // No layer set
55 }
56 
57 
58 int PLACEFILE_GERBER_WRITER::CreatePlaceFile( wxString& aFullFilename, PCB_LAYER_ID aLayer,
59  bool aIncludeBrdEdges )
60 {
61  m_layer = aLayer;
62 
63  PCB_PLOT_PARAMS plotOpts = m_pcb->GetPlotOptions();
64 
65  if( plotOpts.GetUseAuxOrigin() )
67 
68  // Collect footprints on the right layer
69  std::vector<MODULE*> fp_list;
70 
71  for( MODULE* footprint : m_pcb->Modules() )
72  {
73  if( footprint->GetAttributes() & MOD_VIRTUAL )
74  continue;
75 
76  if( footprint->GetLayer() == aLayer )
77  fp_list.push_back( footprint );
78  }
79 
80  LOCALE_IO dummy_io; // Use the standard notation for float numbers
81 
82  GERBER_PLOTTER plotter;
83 
84  // Gerber drill file imply X2 format:
85  plotter.UseX2format( true );
86  plotter.UseX2NetAttributes( true );
87 
88  // Add the standard X2 header, without FileFunction
89  AddGerberX2Header( &plotter, m_pcb );
90  plotter.SetViewport( m_offset, IU_PER_MILS/10, /* scale */ 1.0, /* mirror */false );
91  // has meaning only for gerber plotter. Must be called only after SetViewport
92  plotter.SetGerberCoordinatesFormat( 6 );
93  plotter.SetCreator( wxT( "PCBNEW" ) );
94 
95  // Add the standard X2 FileFunction for P&P files
96  // %TF.FileFunction,Component,Ln,[top][bottom]*%
97  wxString text;
98  text.Printf( "%%TF.FileFunction,Component,L%d,%s*%%",
99  aLayer == B_Cu ? m_pcb->GetCopperLayerCount() : 1,
100  aLayer == B_Cu ? "Bot" : "Top" );
101  plotter.AddLineToHeader( text );
102 
103  // Add file polarity (positive)
104  text = "%TF.FilePolarity,Positive*%";
105  plotter.AddLineToHeader( text );
106 
107  if( !plotter.OpenFile( aFullFilename ) )
108  return -1;
109 
110  // We need a BRDITEMS_PLOTTER to plot pads
111  BRDITEMS_PLOTTER brd_plotter( &plotter, m_pcb, plotOpts );
112 
113  plotter.StartPlot();
114 
115  // Some tools in P&P files have the type and size defined.
116  // they are position flash (round), pad1 flash (diamond), other pads flash (round)
117  // and component outline thickness (polyline)
118  int flash_position_shape_diam = Millimeter2iu( 0.3 ); // defined size for position shape (circle)
119  int pad1_mark_size = Millimeter2iu( 0.36 ); // defined size for pad 1 position (diamond)
120  int other_pads_mark_size = 0; // defined size for position shape (circle)
121  int line_thickness = Millimeter2iu( 0.1 ); // defined size for component outlines
122 
123  brd_plotter.SetLayerSet( LSET( aLayer ) );
124  int cmp_count = 0;
125  bool allowUtf8 = true;
126 
127  // Plot components data: position, outlines, pad1 and other pads.
128  for( MODULE* footprint : fp_list )
129  {
130  // Manage the aperture attribute component position:
131  GBR_METADATA gbr_metadata;
133 
134  // Add object attribute: component reference to flash (mainly usefull for users)
135  // using quoted UTF8 string
136  wxString ref = ConvertNotAllowedCharsInGerber( footprint->GetReference(),
137  allowUtf8, true );
138 
139  gbr_metadata.SetCmpReference( ref );
141 
142  // Add P&P specific attributes
143  GBR_CMP_PNP_METADATA pnpAttrib;
144 
145  // Add rotation info (rotation is CCW, in degrees):
146  pnpAttrib.m_Orientation = mapRotationAngle( footprint->GetOrientationDegrees() );
147 
148  // Add component type info (SMD or Through Hole):
149  bool is_smd_mount = footprint->GetAttributes() & MOD_CMS;
150 
151  // Smd footprints can have through holes (thermal vias).
152  // but if a footprint is not set as SMD, it will be set as SMD
153  // if it does not have through hole pads
154  if( !is_smd_mount && !footprint->HasNonSMDPins() )
155  is_smd_mount = true;
156 
157  pnpAttrib.m_MountType = is_smd_mount ? GBR_CMP_PNP_METADATA::MOUNT_TYPE_SMD
159 
160  // Add component value info:
161  pnpAttrib.m_Value = ConvertNotAllowedCharsInGerber( footprint->GetValue(), allowUtf8, true );
162 
163  // Add component footprint info:
164  wxString fp_info = FROM_UTF8( footprint->GetFPID().GetLibItemName().c_str() );
165  pnpAttrib.m_Footprint = ConvertNotAllowedCharsInGerber( fp_info, allowUtf8, true );
166 
167  // Add footprint lib name:
168  fp_info = FROM_UTF8( footprint->GetFPID().GetLibNickname().c_str() );
169  pnpAttrib.m_LibraryName = ConvertNotAllowedCharsInGerber( fp_info, allowUtf8, true );
170 
171  gbr_metadata.m_NetlistMetadata.SetExtraData( pnpAttrib.FormatCmpPnPMetadata() );
172 
173  wxPoint flash_pos = footprint->GetPosition();
174 
175  plotter.FlashPadCircle( flash_pos, flash_position_shape_diam, FILLED, &gbr_metadata );
176  gbr_metadata.m_NetlistMetadata.ClearExtraData();
177 
178  // Now some extra metadata is output, avoid blindly clearing the full metadata list
180 
181  // We plot the footprint courtyard when possible.
182  // If not, the pads bounding box will be used.
183  bool useFpPadsBbox = true;
184 
185  if( footprint->BuildPolyCourtyard() )
186  {
188 
189  SHAPE_POLY_SET& courtyard = aLayer == B_Cu ?
190  footprint->GetPolyCourtyardBack():
191  footprint->GetPolyCourtyardFront();
192 
193  for( int ii = 0; ii < courtyard.OutlineCount(); ii++ )
194  {
195  SHAPE_LINE_CHAIN poly = courtyard.Outline( ii );
196 
197  if( !poly.PointCount() )
198  continue;
199 
200  useFpPadsBbox = false;
201  plotter.PLOTTER::PlotPoly( poly, NO_FILL, line_thickness, &gbr_metadata );
202  }
203  }
204 
205  if( useFpPadsBbox )
206  {
208 
209  // bbox of fp pads, pos 0, rot 0, non flipped
210  EDA_RECT bbox = footprint->GetFpPadsLocalBbox();
211 
212  // negate bbox Y values if the fp is flipped (always flipped around X axis
213  // in Gerber P&P files).
214  int y_sign = aLayer == B_Cu ? -1 : 1;
215 
216  SHAPE_LINE_CHAIN poly;
217  poly.Append( bbox.GetLeft(), y_sign*bbox.GetTop() );
218  poly.Append( bbox.GetLeft(), y_sign*bbox.GetBottom() );
219  poly.Append( bbox.GetRight(), y_sign*bbox.GetBottom() );
220  poly.Append( bbox.GetRight(), y_sign*bbox.GetTop() );
221  poly.SetClosed( true );
222 
223  poly.Rotate( -footprint->GetOrientationRadians(), VECTOR2I( 0, 0 ) );
224  poly.Move( footprint->GetPosition() );
225  plotter.PLOTTER::PlotPoly( poly, NO_FILL, line_thickness, &gbr_metadata );
226  }
227 
228  std::vector<D_PAD*>pad_key_list;
229 
230  if( m_plotPad1Marker )
231  {
232  findPads1( pad_key_list, footprint );
233 
234  for( D_PAD* pad1 : pad_key_list )
235  {
236  gbr_metadata.SetApertureAttrib(
238 
239  gbr_metadata.SetPadName( pad1->GetName(), allowUtf8, true );
240 
241  gbr_metadata.SetPadPinFunction( pad1->GetPinFunction(), allowUtf8, true );
242 
244 
245  // Flashes a diamond at pad position:
246  plotter.FlashRegularPolygon( pad1->GetPosition(),
247  pad1_mark_size,
248  4, 0.0, FILLED, &gbr_metadata );
249  }
250  }
251 
253  {
254 
255  gbr_metadata.SetApertureAttrib(
258 
259  for( D_PAD* pad: footprint->Pads() )
260  {
261  bool skip_pad = false;
262 
263  for( D_PAD* pad1 : pad_key_list )
264  {
265  if( pad == pad1 ) // Already plotted
266  {
267  skip_pad = true;
268  break;
269  }
270  }
271 
272  if( skip_pad )
273  continue;
274 
275  // Skip also pads not on the current layer, like pads only
276  // on a tech layer
277  if( !pad->IsOnLayer( aLayer ) )
278  continue;
279 
280  gbr_metadata.SetPadName( pad->GetName(), allowUtf8, true );
281 
282  gbr_metadata.SetPadPinFunction( pad->GetPinFunction(), allowUtf8, true );
283 
284  // Flashes a round, 0 sized round shape at pad position
285  plotter.FlashPadCircle( pad->GetPosition(),
286  other_pads_mark_size,
287  FILLED, &gbr_metadata );
288  }
289  }
290 
291  plotter.ClearAllAttributes(); // Unconditionally close all .TO attributes
292 
293  cmp_count++;
294  }
295 
296  // Plot board outlines, if requested
297  if( aIncludeBrdEdges )
298  {
299  brd_plotter.SetLayerSet( LSET( Edge_Cuts ) );
300 
301  // Plot edge layer and graphic items
302  brd_plotter.PlotBoardGraphicItems();
303 
304  // Draw footprint other graphic items:
305  for( MODULE* footprint : fp_list )
306  {
307  for( auto item : footprint->GraphicalItems() )
308  {
309  if( item->Type() == PCB_MODULE_EDGE_T && item->GetLayer() == Edge_Cuts )
310  brd_plotter.PlotFootprintGraphicItem((EDGE_MODULE*) item );
311  }
312  }
313  }
314 
315 
316  plotter.EndPlot();
317 
318  return cmp_count;
319 }
320 
321 
323 {
324  // convert a kicad footprint orientation to gerber rotation, depending on the layer
325  // Currently, same notation as kicad
326  return aAngle;
327 }
328 
329 
330 void PLACEFILE_GERBER_WRITER::findPads1( std::vector<D_PAD*>& aPadList, MODULE* aFootprint ) const
331 {
332  // Fint the pad "1" or pad "A1"
333  // this is possible only if only one pad is found
334  // Usefull to place a marker in this position
335 
336  for( D_PAD* pad : aFootprint->Pads() )
337  {
338  if( !pad->IsOnLayer( m_layer ) )
339  continue;
340 
341  if( pad->GetName() == "1" || pad->GetName() == "A1")
342  aPadList.push_back( pad );
343  }
344 }
345 
346 
347 const wxString PLACEFILE_GERBER_WRITER::GetPlaceFileName( const wxString& aFullBaseFilename,
348  PCB_LAYER_ID aLayer ) const
349 {
350  // Gerber files extension is always .gbr.
351  // Therefore, to mark pnp files, add "-pnp" to the filename, and a layer id.
352  wxFileName fn = aFullBaseFilename;
353 
354  wxString post_id = "-pnp_";
355  post_id += aLayer == B_Cu ? "bottom" : "top";
356  fn.SetName( fn.GetName() + post_id );
357  fn.SetExt( GerberFileExtension );
358 
359  return fn.GetFullPath();
360 }
a class to 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.
void findPads1(std::vector< D_PAD * > &aPadList, MODULE *aFootprint) const
Find the pad(s) 1 (or pad "A1") of a footprint Usefull to plot a marker at this (these) position(s)
aperture used to draw component footprint bounding box in placement files
Definition: gbr_metadata.h:113
virtual void SetCreator(const wxString &aCreator)
Definition: plotter.h:164
const PCB_PLOT_PARAMS & GetPlotOptions() const
Definition: class_board.h:575
int OutlineCount() const
Returns the number of outlines in the set
void UseX2NetAttributes(bool aEnable)
Definition: plotter.h:1302
static wxString FROM_UTF8(const char *cstring)
function FROM_UTF8 converts a UTF8 encoded C string to a wxString for all wxWidgets build modes.
Definition: macros.h:114
aperture used for flashed pin 1 (or A1 or AA1) position in placement files
Definition: gbr_metadata.h:107
Instantiate the current locale within a scope in which you are expecting exceptions to be thrown.
Definition: common.h:216
aperture used for flashed pads position in placement files
Definition: gbr_metadata.h:108
print info associated to a component (TO.C attribute)
int GetTop() const
Definition: eda_rect.h:123
virtual bool OpenFile(const wxString &aFullFilename)
Open or create the plot file aFullFilename.
Definition: plotter.cpp:77
void SetNetAttribType(int aNetAttribType)
Definition: gbr_metadata.h:170
int GetLeft() const
Definition: eda_rect.h:122
void Move(const VECTOR2I &aVector) override
virtual void FlashRegularPolygon(const wxPoint &aShapePos, int aDiameter, int aCornerCount, double aOrient, EDA_DRAW_MODE_T aTraceMode, void *aData) override
Flash a regular polygon.
PADS & Pads()
Definition: class_module.h:169
Set for modules listed in the automatic insertion list (usually SMD footprints)
Definition: class_module.h:68
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:282
void UseX2format(bool aEnable)
Definition: plotter.h:1301
BOARD_DESIGN_SETTINGS & GetDesignSettings() const
Function GetDesignSettings.
Definition: class_board.h:551
const std::string GerberFileExtension
void AddLineToHeader(const wxString &aExtraString)
Function AddLineToHeader Add a line to the list of free lines to print at the beginning of the file.
Definition: plotter.h:179
VECTOR2< int > VECTOR2I
Definition: vector2d.h:594
int PointCount() const
Function PointCount()
class EDGE_MODULE, a footprint edge
Definition: typeinfo.h:94
virtual bool StartPlot() override
Function StartPlot Write GERBER header to file initialize global variable g_Plot_PlotOutputFile.
this class handle info which can be added in a gerber P&P file as attribute of a component Only appli...
void Append(int aX, int aY, bool aAllowDuplication=false)
Function Append()
int GetBottom() const
Definition: eda_rect.h:124
void SetPadPinFunction(const wxString &aPadPinFunction, bool aUseUTF8, bool aEscapeString)
Definition: gbr_metadata.h:187
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.
void SetLayerSet(LSET aLayerMask)
Definition: pcbplot.h:92
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.
MODULES & Modules()
Definition: class_board.h:266
SHAPE_POLY_SET.
void SetPadName(const wxString &aPadname, bool aUseUTF8=false, bool aEscapeString=false)
Definition: gbr_metadata.h:182
SHAPE_LINE_CHAIN & Outline(int aIndex)
Returns the reference to aIndex-th outline in the set
void PlotBoardGraphicItems()
plot items like text and graphics, but not tracks and modules
void PlotFootprintGraphicItem(EDGE_MODULE *aEdge)
int GetRight() const
Definition: eda_rect.h:121
PCB_LAYER_ID m_layer
The board layer currently used (typically F_Cu or B_Cu)
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.
aperture used to draw component outline courtyard in placement files
Definition: gbr_metadata.h:115
PCB_PLOT_PARAMS handles plot parameters and options when plotting/printing a board.
virtual void FlashPadCircle(const wxPoint &pos, int diametre, EDA_DRAW_MODE_T trace_mode, void *aData) override
Filled circular flashes are stored as apertures.
void Rotate(double aAngle, const VECTOR2I &aCenter=VECTOR2I(0, 0)) override
Function Rotate rotates all vertices by a given angle.
aperture used for flashed cmp position in placement files
Definition: gbr_metadata.h:106
const wxString GetPlaceFileName(const wxString &aFullBaseFilename, PCB_LAYER_ID aLayer) const
see class PGM_BASE
wxString FormatCmpPnPMetadata()
BOARD holds information pertinent to a Pcbnew printed circuit board.
Definition: class_board.h:180
virtual bool EndPlot() override
SHAPE_LINE_CHAIN.
Virtual component: when created by copper shapes on board (Like edge card connectors,...
Definition: class_module.h:70
int GetCopperLayerCount() const
Function GetCopperLayerCount.
EDA_RECT handles the component boundary box.
Definition: eda_rect.h:44
#define IU_PER_MILS
Definition: plotter.cpp:138
bool m_TryKeepPreviousAttributes
If true, do not clear all attributes when a atribute has changed Usefull when some attributes need to...
wxString ConvertNotAllowedCharsInGerber(const wxString &aString, bool aAllowUtf8Chars, bool aQuoteString)
Similar to FormatStringToGerber.
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:160
GBR_NETLIST_METADATA m_NetlistMetadata
a item to handle object attribute:
Definition: gbr_metadata.h:212
bool GetUseAuxOrigin() const
void SetCmpReference(const wxString &aComponentRef)
Definition: gbr_metadata.h:192
wxPoint m_AuxOrigin
origin for plot exports
void ClearExtraData()
Clear the extra data string printed at end of net attributes.