KiCad PCB EDA Suite
gendrill_gerber_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) 2017 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
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 
31 #include <string_utils.h>
32 #include <locale_io.h>
33 #include <board.h>
34 #include <footprint.h>
35 #include <pcb_track.h>
36 #include <pad.h>
37 #include <pcbplot.h>
38 #include <gendrill_gerber_writer.h>
39 #include <reporter.h>
40 #include <gbr_metadata.h>
41 
42 // set to 1 to use flashed oblong holes, 0 to draw them by a line.
43 #define FLASH_OVAL_HOLE 1
44 
45 
47  : GENDRILL_WRITER_BASE( aPcb )
48 {
50  m_conversionUnits = 1.0;
51  m_unitsMetric = true;
52  m_drillFileExtension = "gbr";
53  m_merge_PTH_NPTH = false;
54 }
55 
56 
57 void GERBER_WRITER::CreateDrillandMapFilesSet( const wxString& aPlotDirectory, bool aGenDrill,
58  bool aGenMap, REPORTER* aReporter )
59 {
60  // Note: In Gerber drill files, NPTH and PTH are always separate files
61  m_merge_PTH_NPTH = false;
62 
63  wxFileName fn;
64  wxString msg;
65 
66  std::vector<DRILL_LAYER_PAIR> hole_sets = getUniqueLayerPairs();
67 
68  // append a pair representing the NPTH set of holes, for separate drill files.
69  // (Gerber drill files are separate files for PTH and NPTH)
70  hole_sets.emplace_back( F_Cu, B_Cu );
71 
72  for( std::vector<DRILL_LAYER_PAIR>::const_iterator it = hole_sets.begin();
73  it != hole_sets.end(); ++it )
74  {
75  DRILL_LAYER_PAIR pair = *it;
76  // For separate drill files, the last layer pair is the NPTH drill file.
77  bool doing_npth = ( it == hole_sets.end() - 1 );
78 
79  buildHolesList( pair, doing_npth );
80 
81  // The file is created if it has holes, or if it is the non plated drill file
82  // to be sure the NPTH file is up to date in separate files mode.
83  // Also a PTH drill/map file is always created, to be sure at least one plated hole drill
84  // file is created (do not create any PTH drill file can be seen as not working drill
85  // generator).
86  if( getHolesCount() > 0 || doing_npth || pair == DRILL_LAYER_PAIR( F_Cu, B_Cu ) )
87  {
88  fn = getDrillFileName( pair, doing_npth, false );
89  fn.SetPath( aPlotDirectory );
90 
91  if( aGenDrill )
92  {
93  wxString fullFilename = fn.GetFullPath();
94 
95  int result = createDrillFile( fullFilename, doing_npth, pair );
96 
97  if( result < 0 )
98  {
99  if( aReporter )
100  {
101  msg.Printf( _( "Failed to create file '%s'." ), fullFilename );
102  aReporter->Report( msg, RPT_SEVERITY_ERROR );
103  }
104 
105  break;
106  }
107  else
108  {
109  if( aReporter )
110  {
111  msg.Printf( _( "Created file '%s'." ), fullFilename );
112  aReporter->Report( msg, RPT_SEVERITY_ACTION );
113  }
114  }
115 
116  }
117  }
118  }
119 
120  if( aGenMap )
121  CreateMapFilesSet( aPlotDirectory, aReporter );
122 
123  if( aReporter )
124  aReporter->ReportTail( _( "Done." ), RPT_SEVERITY_INFO );
125 }
126 
127 
128 #if !FLASH_OVAL_HOLE
129 // A helper class to transform an oblong hole to a segment
130 static void convertOblong2Segment( wxSize aSize, double aOrient, wxPoint& aStart, wxPoint& aEnd );
131 #endif
132 
133 
134 int GERBER_WRITER::createDrillFile( wxString& aFullFilename, bool aIsNpth,
135  DRILL_LAYER_PAIR aLayerPair )
136 {
137  int holes_count;
138 
139  LOCALE_IO dummy; // Use the standard notation for double numbers
140 
141  GERBER_PLOTTER plotter;
142 
143  // Gerber drill file imply X2 format:
144  plotter.UseX2format( true );
145  plotter.UseX2NetAttributes( true );
146  plotter.DisableApertMacros( false );
147 
148  // Add the standard X2 header, without FileFunction
149  AddGerberX2Header( &plotter, m_pcb );
150  plotter.SetViewport( m_offset, IU_PER_MILS/10, /* scale */ 1.0, /* mirror */false );
151 
152  // has meaning only for gerber plotter. Must be called only after SetViewport
153  plotter.SetGerberCoordinatesFormat( 6 );
154  plotter.SetCreator( wxT( "PCBNEW" ) );
155 
156  // Add the standard X2 FileFunction for drill files
157  // %TF.FileFunction,Plated[NonPlated],layer1num,layer2num,PTH[NPTH][Blind][Buried],Drill[Route][Mixed]*%
158  wxString text = BuildFileFunctionAttributeString( aLayerPair,
159  aIsNpth
160  ? TYPE_FILE::NPTH_FILE
161  : TYPE_FILE::PTH_FILE );
162  plotter.AddLineToHeader( text );
163 
164  // Add file polarity (positive)
165  text = "%TF.FilePolarity,Positive*%";
166  plotter.AddLineToHeader( text );
167 
168  if( !plotter.OpenFile( aFullFilename ) )
169  return -1;
170 
171  plotter.StartPlot();
172 
173  holes_count = 0;
174 
175  wxPoint hole_pos;
176  bool last_item_is_via = true; // a flag to clear object attributes when a via hole is created.
177 
178  for( unsigned ii = 0; ii < m_holeListBuffer.size(); ii++ )
179  {
180  HOLE_INFO& hole_descr = m_holeListBuffer[ii];
181  hole_pos = hole_descr.m_Hole_Pos;
182 
183  // Manage the aperture attributes: in drill files 3 attributes can be used:
184  // "ViaDrill", only for vias, not pads
185  // "ComponentDrill", only for Through Holes pads
186  // "Slot" for oblong holes;
187  GBR_METADATA gbr_metadata;
188 
189  if( dyn_cast<const PCB_VIA*>( hole_descr.m_ItemParent ) )
190  {
192 
193  if( !last_item_is_via )
194  {
195  // be sure the current object attribute is cleared for vias
196  plotter.EndBlock( nullptr );
197  }
198 
199  last_item_is_via = true;
200  }
201  else if( dyn_cast<const PAD*>( hole_descr.m_ItemParent ) )
202  {
203  last_item_is_via = false;
204  const PAD* pad = dyn_cast<const PAD*>( hole_descr.m_ItemParent );
205 
206  if( pad->GetProperty() == PAD_PROP::CASTELLATED )
207  {
208  gbr_metadata.SetApertureAttrib(
210  }
211  else
212  {
213  // Good practice of oblong pad holes (slots) is to use a specific aperture for
214  // routing, not used in drill commands.
215  if( hole_descr.m_Hole_Shape )
216  gbr_metadata.SetApertureAttrib(
218  else
219  gbr_metadata.SetApertureAttrib(
221  }
222 
223  // Add object attribute: component reference to pads (mainly useful for users)
224  wxString ref = pad->GetParent()->GetReference();
225 
226  gbr_metadata.SetCmpReference( ref );
228  }
229 
230  if( hole_descr.m_Hole_Shape )
231  {
232 #if FLASH_OVAL_HOLE // set to 1 to use flashed oblong holes,
233  // 0 to draw them as a line.
234  plotter.FlashPadOval( hole_pos, hole_descr.m_Hole_Size,
235  hole_descr.m_Hole_Orient, FILLED, &gbr_metadata );
236 #else
237  // Use routing for oblong hole (Slots)
238  wxPoint start, end;
239  convertOblong2Segment( hole_descr.m_Hole_Size, hole_descr.m_Hole_Orient, start, end );
240  int width = std::min( hole_descr.m_Hole_Size.x, hole_descr.m_Hole_Size.y );
241 
242  if ( width == 0 )
243  continue;
244 
245  plotter.ThickSegment( start+hole_pos, end+hole_pos, width, FILLED, &gbr_metadata );
246 #endif
247  }
248  else
249  {
250  int diam = std::min( hole_descr.m_Hole_Size.x, hole_descr.m_Hole_Size.y );
251  plotter.FlashPadCircle( hole_pos, diam, FILLED, &gbr_metadata );
252  }
253 
254  holes_count++;
255  }
256 
257  plotter.EndPlot();
258 
259  return holes_count;
260 }
261 
262 
263 #if !FLASH_OVAL_HOLE
264 void convertOblong2Segment( wxSize aSize, double aOrient, wxPoint& aStart, wxPoint& aEnd )
265 {
266  wxSize size( aSize );
267  double orient = aOrient;
268 
269  /* The pad will be drawn as an oblong shape with size.y > size.x
270  * (Oval vertical orientation 0)
271  */
272  if( size.x > size.y )
273  {
274  std::swap( size.x, size.y );
275  orient = AddAngles( orient, 900 );
276  }
277 
278  int deltaxy = size.y - size.x; // distance between centers of the oval
279 
280  int cx = 0;
281  int cy = deltaxy / 2;
282  RotatePoint( &cx, &cy, orient );
283  aStart = wxPoint( cx, cy );
284  cx = 0; cy = -deltaxy / 2;
285  RotatePoint( &cx, &cy, orient );
286  aEnd = wxPoint( cx, cy );
287 }
288 #endif
289 
290 
291 void GERBER_WRITER::SetFormat( int aRightDigits )
292 {
293  /* Set conversion scale depending on drill file units */
294  m_conversionUnits = 1.0 / IU_PER_MM; // Gerber units = mm
295 
296  // Set precision (unit is mm).
297  m_precision.m_Lhs = 4;
298  m_precision.m_Rhs = aRightDigits == 6 ? 6 : 5;
299 }
300 
301 
302 const wxString GERBER_WRITER::getDrillFileName( DRILL_LAYER_PAIR aPair, bool aNPTH,
303  bool aMerge_PTH_NPTH ) const
304 {
305  // Gerber files extension is always .gbr.
306  // Therefore, to mark drill files, add "-drl" to the filename.
307  wxFileName fname( GENDRILL_WRITER_BASE::getDrillFileName( aPair, aNPTH, aMerge_PTH_NPTH ) );
308  fname.SetName( fname.GetName() + "-drl" );
309 
310  return fname.GetFullPath();
311 }
Handle special data (items attributes) during plot.
BOARD_ITEM * m_ItemParent
virtual const wxString getDrillFileName(DRILL_LAYER_PAIR aPair, bool aNPTH, bool aMerge_PTH_NPTH) const
virtual void SetCreator(const wxString &aCreator)
Definition: plotter.h:174
void UseX2NetAttributes(bool aEnable)
aperture used for flashed cmp position in placement files.
Definition: gbr_metadata.h:143
Instantiate the current locale within a scope in which you are expecting exceptions to be thrown.
Definition: locale_io.h:40
virtual void EndBlock(void *aData) override
Define the end of a group of drawing items the group is started by StartBlock().
print info associated to a component (TO.C attribute)
static constexpr double IU_PER_MM
Mock up a conversion function.
virtual void ThickSegment(const wxPoint &start, const wxPoint &end, int width, OUTLINE_MODE tracemode, void *aData) override
virtual bool OpenFile(const wxString &aFullFilename)
Open or create the plot file aFullFilename.
Definition: plotter.cpp:76
void CreateMapFilesSet(const wxString &aPlotDirectory, REPORTER *aReporter=nullptr)
Create the full set of map files for the board, in PS, PDF ...
void SetNetAttribType(int aNetAttribType)
Definition: gbr_metadata.h:219
virtual REPORTER & ReportTail(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED)
Places the report at the end of the list, for objects that support report ordering.
Definition: reporter.h:99
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)
aperture used for via holes in drill files.
Definition: gbr_metadata.h:139
void SetFormat(int aRightDigits=6)
Initialize internal parameters to match the given format.
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
std::vector< DRILL_LAYER_PAIR > getUniqueLayerPairs() const
Get unique layer pairs by examining the micro and blind_buried vias.
void RotatePoint(int *pX, int *pY, double angle)
Definition: trigo.cpp:229
A pure virtual class used to derive REPORTER objects from.
Definition: reporter.h:70
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED)=0
Report a string with a given severity.
virtual bool StartPlot() override
Write GERBER header to file initialize global variable g_Plot_PlotOutputFile.
Board plot function definition file.
static LIB_SYMBOL * dummy()
Used to draw a dummy shape when a LIB_SYMBOL is not found in library.
Definition: sch_symbol.cpp:72
T AddAngles(T a1, T2 a2)
Add two angles (keeping the result normalized). T2 is here.
Definition: trigo.h:341
aperture used for pad holes in drill files.
Definition: gbr_metadata.h:140
void CreateDrillandMapFilesSet(const wxString &aPlotDirectory, bool aGenDrill, bool aGenMap, REPORTER *aReporter=nullptr)
Create the full set of Excellon drill file for the board filenames are computed from the board name,...
const wxString BuildFileFunctionAttributeString(DRILL_LAYER_PAIR aLayerPair, TYPE_FILE aHoleType, bool aCompatNCdrill=false) const
virtual void SetViewport(const wxPoint &aOffset, double aIusPerDecimil, double aScale, bool aMirror) override
Set the plot offset and scaling for the current plot.
#define _(s)
Handle hole which must be drilled (diameter, position and layers).
std::pair< PCB_LAYER_ID, PCB_LAYER_ID > DRILL_LAYER_PAIR
Metadata which can be added in a gerber file as attribute in X2 format.
Definition: gbr_metadata.h:204
virtual void FlashPadOval(const wxPoint &aPadPos, const wxSize &size, double orient, OUTLINE_MODE trace_mode, void *aData) override
void buildHolesList(DRILL_LAYER_PAIR aLayerPair, bool aGenerateNPTH_list)
Create the list of holes and tools for a given board.
Plotting engine (Gerber)
void DisableApertMacros(bool aDisable)
Disable Aperture Macro (AM) command, only for broken Gerber Readers.
Information pertinent to a Pcbnew printed circuit board.
Definition: board.h:190
virtual const wxString getDrillFileName(DRILL_LAYER_PAIR aPair, bool aNPTH, bool aMerge_PTH_NPTH) const override
virtual bool EndPlot() override
Definition: layer_ids.h:71
#define IU_PER_MILS
Definition: plotter.cpp:136
virtual void SetGerberCoordinatesFormat(int aResolution, bool aUseInches=false) override
Selection of Gerber units and resolution (number of digits in mantissa).
void SetApertureAttrib(GBR_APERTURE_METADATA::GBR_APERTURE_ATTRIB aApertAttribute)
Definition: gbr_metadata.h:209
a pad with a castellated through hole
virtual void FlashPadCircle(const wxPoint &pos, int diametre, OUTLINE_MODE trace_mode, void *aData) override
Filled circular flashes are stored as apertures.
Classes used in drill files, map files and report files generation.
GERBER_WRITER(BOARD *aPcb)
Definition: pad.h:57
std::vector< HOLE_INFO > m_holeListBuffer
void SetCmpReference(const wxString &aComponentRef)
Definition: gbr_metadata.h:241
int createDrillFile(wxString &aFullFilename, bool aIsNpth, DRILL_LAYER_PAIR aLayerPair)
Create an Excellon drill file.
Create drill maps and drill reports and drill files.