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-2021 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 
31 #include <string_utils.h>
32 #include <locale_io.h>
33 #include <macros.h>
34 
35 #include <board.h>
36 #include <board_design_settings.h>
37 
38 #include <pcbplot.h>
40 #include <gbr_metadata.h>
41 #include <footprint.h>
42 #include <pad.h>
43 
44 
46 {
47  m_pcb = aPcb;
48  m_plotPad1Marker = true; // Place a marker to pin 1 (or A1) position
49  m_plotOtherPadsMarker = true; // Place a marker to other pins position
50  m_layer = PCB_LAYER_ID::UNDEFINED_LAYER; // No layer set
51 }
52 
53 
54 int PLACEFILE_GERBER_WRITER::CreatePlaceFile( wxString& aFullFilename, PCB_LAYER_ID aLayer,
55  bool aIncludeBrdEdges )
56 {
57  m_layer = aLayer;
58 
59  PCB_PLOT_PARAMS plotOpts = m_pcb->GetPlotOptions();
60 
61  if( plotOpts.GetUseAuxOrigin() )
63 
64  // Collect footprints on the right layer
65  std::vector<FOOTPRINT*> fp_list;
66 
67  for( FOOTPRINT* footprint : m_pcb->Footprints() )
68  {
69  if( footprint->GetAttributes() & FP_EXCLUDE_FROM_POS_FILES )
70  continue;
71 
72  if( footprint->GetLayer() == aLayer )
73  fp_list.push_back( footprint );
74  }
75 
76  LOCALE_IO dummy_io; // Use the standard notation for float numbers
77 
78  GERBER_PLOTTER plotter;
79 
80  // Gerber drill file imply X2 format:
81  plotter.UseX2format( true );
82  plotter.UseX2NetAttributes( true );
83 
84  // Add the standard X2 header, without FileFunction
85  AddGerberX2Header( &plotter, m_pcb );
86  plotter.SetViewport( m_offset, IU_PER_MILS/10, /* scale */ 1.0, /* mirror */false );
87 
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 useful 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  {
185  gbr_metadata.SetApertureAttrib(
187 
188  const SHAPE_POLY_SET& courtyard = footprint->GetPolyCourtyard( aLayer );
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_T::NO_FILL, line_thickness, &gbr_metadata );
199  }
200  }
201 
202  if( useFpPadsBbox )
203  {
204  gbr_metadata.SetApertureAttrib(
206 
207  // bbox of fp pads, pos 0, rot 0, non flipped
208  EDA_RECT bbox = footprint->GetFpPadsLocalBbox();
209 
210  // negate bbox Y values if the fp is flipped (always flipped around X axis
211  // in Gerber P&P files).
212  int y_sign = aLayer == B_Cu ? -1 : 1;
213 
214  SHAPE_LINE_CHAIN poly;
215  poly.Append( bbox.GetLeft(), y_sign*bbox.GetTop() );
216  poly.Append( bbox.GetLeft(), y_sign*bbox.GetBottom() );
217  poly.Append( bbox.GetRight(), y_sign*bbox.GetBottom() );
218  poly.Append( bbox.GetRight(), y_sign*bbox.GetTop() );
219  poly.SetClosed( true );
220 
221  poly.Rotate( -footprint->GetOrientationRadians(), VECTOR2I( 0, 0 ) );
222  poly.Move( footprint->GetPosition() );
223  plotter.PLOTTER::PlotPoly( poly, FILL_T::NO_FILL, line_thickness, &gbr_metadata );
224  }
225 
226  std::vector<PAD*>pad_key_list;
227 
228  if( m_plotPad1Marker )
229  {
230  findPads1( pad_key_list, footprint );
231 
232  for( PAD* pad1 : pad_key_list )
233  {
234  gbr_metadata.SetApertureAttrib(
236 
237  gbr_metadata.SetPadName( pad1->GetNumber(), allowUtf8, true );
238 
239  gbr_metadata.SetPadPinFunction( pad1->GetPinFunction(), allowUtf8, true );
240 
242 
243  // Flashes a diamond at pad position:
244  plotter.FlashRegularPolygon( pad1->GetPosition(), pad1_mark_size, 4, 0.0, FILLED,
245  &gbr_metadata );
246  }
247  }
248 
250  {
251  gbr_metadata.SetApertureAttrib(
254 
255  for( PAD* pad: footprint->Pads() )
256  {
257  bool skip_pad = false;
258 
259  for( PAD* pad1 : pad_key_list )
260  {
261  if( pad == pad1 ) // Already plotted
262  {
263  skip_pad = true;
264  break;
265  }
266  }
267 
268  if( skip_pad )
269  continue;
270 
271  // Skip also pads not on the current layer, like pads only
272  // on a tech layer
273  if( !pad->IsOnLayer( aLayer ) )
274  continue;
275 
276  gbr_metadata.SetPadName( pad->GetNumber(), allowUtf8, true );
277 
278  gbr_metadata.SetPadPinFunction( pad->GetPinFunction(), allowUtf8, true );
279 
280  // Flashes a round, 0 sized round shape at pad position
281  plotter.FlashPadCircle( pad->GetPosition(), other_pads_mark_size, FILLED,
282  &gbr_metadata );
283  }
284  }
285 
286  plotter.ClearAllAttributes(); // Unconditionally close all .TO attributes
287 
288  cmp_count++;
289  }
290 
291  // Plot board outlines, if requested
292  if( aIncludeBrdEdges )
293  {
294  brd_plotter.SetLayerSet( LSET( Edge_Cuts ) );
295 
296  // Plot edge layer and graphic items
297  brd_plotter.PlotBoardGraphicItems();
298 
299  // Draw footprint other graphic items:
300  for( FOOTPRINT* footprint : fp_list )
301  {
302  for( BOARD_ITEM* item : footprint->GraphicalItems() )
303  {
304  if( item->Type() == PCB_FP_SHAPE_T && item->GetLayer() == Edge_Cuts )
305  brd_plotter.PlotFootprintGraphicItem( (FP_SHAPE*) item );
306  }
307  }
308  }
309 
310  plotter.EndPlot();
311 
312  return cmp_count;
313 }
314 
315 
317 {
318  // Convert a KiCad footprint orientation to gerber rotation, depending on the layer
319  // Currently, same notation as KiCad.
320  return aAngle;
321 }
322 
323 
324 void PLACEFILE_GERBER_WRITER::findPads1( std::vector<PAD*>& aPadList, FOOTPRINT* aFootprint ) const
325 {
326  // Fint the pad "1" or pad "A1"
327  // this is possible only if only one pad is found
328  // useful to place a marker in this position
329 
330  for( PAD* pad : aFootprint->Pads() )
331  {
332  if( !pad->IsOnLayer( m_layer ) )
333  continue;
334 
335  if( pad->GetNumber() == "1" || pad->GetNumber() == "A1")
336  aPadList.push_back( pad );
337  }
338 }
339 
340 
341 const wxString PLACEFILE_GERBER_WRITER::GetPlaceFileName( const wxString& aFullBaseFilename,
342  PCB_LAYER_ID aLayer ) const
343 {
344  // Gerber files extension is always .gbr.
345  // Therefore, to mark pnp files, add "-pnp" to the filename, and a layer id.
346  wxFileName fn = aFullBaseFilename;
347 
348  wxString post_id = "-pnp_";
349  post_id += aLayer == B_Cu ? "bottom" : "top";
350  fn.SetName( fn.GetName() + post_id );
351  fn.SetExt( GerberFileExtension );
352 
353  return fn.GetFullPath();
354 }
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)
Create an pnp gerber file.
aperture used to draw component outline courtyard in placement files.
Definition: gbr_metadata.h:161
virtual void SetCreator(const wxString &aCreator)
Definition: plotter.h:174
const PCB_PLOT_PARAMS & GetPlotOptions() const
Definition: board.h:538
int OutlineCount() const
Return the number of vertices in a given outline/hole.
void UseX2NetAttributes(bool aEnable)
#define MALFORMED_B_COURTYARD
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:49
int GetTop() const
Definition: eda_rect.h:113
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
#define MALFORMED_F_COURTYARD
int GetLeft() const
Definition: eda_rect.h:112
void Move(const VECTOR2I &aVector) override
void AddGerberX2Header(PLOTTER *aPlotter, const BOARD *aBoard, bool aUseX1CompatibilityMode)
Calculate some X2 attributes as defined in the Gerber file format specification J4 (chapter 5) and ad...
Definition: pcbplot.cpp:282
void UseX2format(bool aEnable)
class FP_SHAPE, a footprint edge
Definition: typeinfo.h:93
const std::string GerberFileExtension
void PlotFootprintGraphicItem(const FP_SHAPE *aShape)
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:183
VECTOR2< int > VECTOR2I
Definition: vector2d.h:623
int PointCount() const
Return the number of points (vertices) in this line chain.
BOARD_DESIGN_SETTINGS & GetDesignSettings() const
Definition: board.cpp:590
virtual bool StartPlot() override
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)
Append a new point at the end of the line chain.
PADS & Pads()
Definition: footprint.h:168
This file contains miscellaneous commonly used macros and functions.
int GetBottom() const
Definition: eda_rect.h:114
void SetPadPinFunction(const wxString &aPadPinFunction, bool aUseUTF8, bool aEscapeString)
Definition: gbr_metadata.h:236
Board plot function definition file.
void SetClosed(bool aClosed)
Mark the line chain as closed (i.e.
LSET is a set of PCB_LAYER_IDs.
Definition: layer_ids.h:504
void SetLayerSet(LSET aLayerMask)
Definition: pcbplot.h:84
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:233
int GetRight() const
Definition: eda_rect.h:111
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
Parameters and options when plotting/printing a board.
Plotting engine (Gerber)
void Rotate(double aAngle, const VECTOR2I &aCenter=VECTOR2I(0, 0)) override
Rotate all vertices by a given angle.
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
wxString FormatCmpPnPMetadata()
Information pertinent to a Pcbnew printed circuit board.
Definition: board.h:190
void findPads1(std::vector< PAD * > &aPadList, FOOTPRINT *aFootprint) const
Find the pad(s) 1 (or pad "A1") of a footprint.
virtual bool EndPlot() override
Represent a polyline (an zero-thickness chain of connected line segments).
PCB_LAYER_ID
A quick note on layer IDs:
Definition: layer_ids.h:65
int GetCopperLayerCount() const
Definition: board.cpp:455
Handle the component boundary box.
Definition: eda_rect.h:42
#define IU_PER_MILS
Definition: plotter.cpp:136
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
Selection of Gerber units and resolution (number of digits in mantissa).
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:57
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.