KiCad PCB EDA Suite
spread_footprints.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) 2013 Jean-Pierre Charras, jean-pierre.charras@ujf-grenoble.fr
5  * Copyright (C) 2013 SoftPLC Corporation, Dick Hollenbeck <dick@softplc.com>
6  * Copyright (C) 2013 Wayne Stambaugh <stambaughw@verizon.net>
7  *
8  * Copyright (C) 1992-2016 KiCad Developers, see AUTHORS.txt for contributors.
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, you may find one here:
22  * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
23  * or you may search the http://www.gnu.org website for the version 2 license,
24  * or you may write to the Free Software Foundation, Inc.,
25  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
26  */
27 
37 #include <algorithm>
38 
39 #include <fctsys.h>
40 #include <convert_to_biu.h>
41 #include <class_drawpanel.h>
42 #include <confirm.h>
43 #include <pcbnew.h>
44 #include <wxPcbStruct.h>
45 #include <class_board.h>
46 #include <class_module.h>
47 
49 
51 {
52  int n; // Original index of this subrect, before sorting
53 
54  TSubRect() : TRect(),
55  n( 0 )
56  {
57  }
58 
59  TSubRect( int _w, int _h, int _n ) :
60  TRect( 0, 0, _w, _h ), n( _n ) { }
61 };
62 
63 typedef std::vector<TSubRect> CSubRectArray;
64 
65 // Use 0.01 mm units to calculate placement, to avoid long calculation time
66 const int scale = (int)(0.01 * IU_PER_MM);
67 
68 // Populates a list of rectangles, from a list of modules
69 void fillRectList( CSubRectArray& vecSubRects, std::vector <MODULE*>& aModuleList )
70 {
71  vecSubRects.clear();
72 
73  for( unsigned ii = 0; ii < aModuleList.size(); ii++ )
74  {
75  EDA_RECT fpBox = aModuleList[ii]->GetBoundingBox();
76  TSubRect fpRect( fpBox.GetWidth()/scale, fpBox.GetHeight()/scale, ii );
77  vecSubRects.push_back( fpRect );
78  }
79 }
80 
81 // Populates a list of rectangles, from a list of EDA_RECT
82 void fillRectList( CSubRectArray& vecSubRects, std::vector <EDA_RECT>& aRectList )
83 {
84  vecSubRects.clear();
85 
86  for( unsigned ii = 0; ii < aRectList.size(); ii++ )
87  {
88  EDA_RECT& rect = aRectList[ii];
89  TSubRect fpRect( rect.GetWidth()/scale, rect.GetHeight()/scale, ii );
90  vecSubRects.push_back( fpRect );
91  }
92 }
93 
94 
95 
96 // Spread a list of rectangles inside a placement area
97 void spreadRectangles( CRectPlacement& aPlacementArea,
98  CSubRectArray& vecSubRects,
99  int areaSizeX, int areaSizeY )
100 {
101  areaSizeX/= scale;
102  areaSizeY/= scale;
103 
104  // Sort the subRects based on dimensions, larger dimension goes first.
105  std::sort( vecSubRects.begin(), vecSubRects.end(), CRectPlacement::TRect::Greater );
106 
107  // gives the initial size to the area
108  aPlacementArea.Init( areaSizeX, areaSizeY );
109 
110  // Add all subrects
111  CSubRectArray::iterator it;
112  for( it = vecSubRects.begin(); it != vecSubRects.end(); )
113  {
114  CRectPlacement::TRect r( 0, 0, it->w, it->h );
115 
116  bool bPlaced = aPlacementArea.AddAtEmptySpotAutoGrow( &r, areaSizeX, areaSizeY );
117 
118  if( !bPlaced ) // No room to place the rectangle: enlarge area and retry
119  {
120  areaSizeX = ceil(areaSizeX * 1.1);
121  areaSizeY = ceil(areaSizeY * 1.1);
122  aPlacementArea.Init( areaSizeX, areaSizeY );
123  it = vecSubRects.begin();
124  continue;
125  }
126 
127  // When correctly placed in a placement area, the coords are returned in r.x and r.y
128  // Store them.
129  it->x = r.x;
130  it->y = r.y;
131 
132  it++;
133  }
134 }
135 
136 
137 void moveFootprintsInArea( CRectPlacement& aPlacementArea,
138  std::vector <MODULE*>& aModuleList,
139  EDA_RECT& aFreeArea,
140  bool aFindAreaOnly )
141 {
142  CSubRectArray vecSubRects;
143 
144  fillRectList( vecSubRects, aModuleList );
145  spreadRectangles( aPlacementArea, vecSubRects,
146  aFreeArea.GetWidth(), aFreeArea.GetHeight() );
147 
148  if( aFindAreaOnly )
149  return;
150 
151  for( unsigned it = 0; it < vecSubRects.size(); ++it )
152  {
153  wxPoint pos( vecSubRects[it].x, vecSubRects[it].y );
154  pos.x *= scale;
155  pos.y *= scale;
156 
157  MODULE * module = aModuleList[vecSubRects[it].n];
158 
159  EDA_RECT fpBBox = module->GetBoundingBox();
160  wxPoint mod_pos = pos + ( module->GetPosition() - fpBBox.GetOrigin() )
161  + aFreeArea.GetOrigin();
162 
163  module->Move( mod_pos - module->GetPosition() );
164  }
165 }
166 
167 static bool sortFootprintsbySheetPath( MODULE* ref, MODULE* compare );
168 
169 /* Function to move components in a rectangular area format 4 / 3,
170  * starting from the mouse cursor.
171  * Footprints are grouped by sheet.
172  * Components with the LOCKED status set are not moved
173  */
174 void PCB_EDIT_FRAME::SpreadFootprints( std::vector<MODULE*>* aFootprints,
175  bool aMoveFootprintsOutsideBoardOnly,
176  bool aCheckForBoardEdges,
177  wxPoint aSpreadAreaPosition,
178  bool aPrepareUndoCommand )
179 {
181  bool edgesExist = bbox.GetWidth() || bbox.GetHeight();
182  // if aFootprintsOutsideBoardOnly is true, and if board outline exists,
183  // we have to filter footprints to move:
184  bool outsideBrdFilter = aMoveFootprintsOutsideBoardOnly && edgesExist;
185 
186  // no edges exist
187  if( aMoveFootprintsOutsideBoardOnly && !edgesExist )
188  {
189  DisplayError( this,
190  _( "Could not automatically place footprints. No board outlines detected." ) );
191  return;
192  }
193 
194 
195  // Build candidate list
196  // calculate also the area needed by these footprints
197  std::vector <MODULE*> footprintList;
198 
199  for( MODULE* footprint : *aFootprints )
200  {
201  footprint->CalculateBoundingBox();
202 
203  if( outsideBrdFilter )
204  {
205  if( bbox.Contains( footprint->GetPosition() ) )
206  continue;
207  }
208 
209  if( footprint->IsLocked() )
210  continue;
211 
212  footprintList.push_back( footprint );
213  }
214 
215  if( footprintList.empty() )
216  return;
217 
218  // sort footprints by sheet path. we group them later by sheet
219  sort( footprintList.begin(), footprintList.end(), sortFootprintsbySheetPath );
220 
221  // Undo command: init undo list. If aPrepareUndoCommand == false
222  // no undo command will be initialized.
223  // Useful when a undo command is already initialized by the caller
224  PICKED_ITEMS_LIST undoList;
225 
226  if( aPrepareUndoCommand )
227  {
228  undoList.m_Status = UR_CHANGED;
229  ITEM_PICKER picker( NULL, UR_CHANGED );
230 
231  for( MODULE* footprint : footprintList )
232  {
233  // Undo: add copy of the footprint to undo list
234  picker.SetItem( footprint );
235  picker.SetLink( footprint->Clone() );
236  undoList.PushItem( picker );
237  }
238  }
239 
240  // Extract and place footprints by sheet
241  std::vector <MODULE*> footprintListBySheet;
242  std::vector <EDA_RECT> placementSheetAreas;
243  double subsurface;
244  double placementsurface = 0.0;
245 
246  // put the placement area position on mouse cursor.
247  // this position will be adjusted later
248  wxPoint placementAreaPosition = aSpreadAreaPosition;
249 
250  // We sometimes do not want to move footprints inside an existing board.
251  // Therefore, move the placement area position outside the board bounding box
252  // to the left of the board
253  if( aCheckForBoardEdges && edgesExist )
254  {
255  if( placementAreaPosition.x < bbox.GetEnd().x &&
256  placementAreaPosition.y < bbox.GetEnd().y )
257  {
258  // the placement area could overlap the board
259  // move its position to a safe location
260  placementAreaPosition.x = bbox.GetEnd().x;
261  placementAreaPosition.y = bbox.GetOrigin().y;
262  }
263  }
264 
265  // The placement uses 2 passes:
266  // the first pass creates the rectangular areas to place footprints
267  // each sheet in schematic creates one rectangular area.
268  // the second pass moves footprints inside these areas
269  MODULE* footprint;
270  for( int pass = 0; pass < 2; pass++ )
271  {
272  int subareaIdx = 0;
273  footprintListBySheet.clear();
274  subsurface = 0.0;
275 
276  for( unsigned ii = 0; ii < footprintList.size(); ii++ )
277  {
278  footprint = footprintList[ii];
279  bool islastItem = false;
280 
281  if( ii == footprintList.size() - 1 ||
282  ( footprintList[ii]->GetPath().BeforeLast( '/' ) !=
283  footprintList[ii+1]->GetPath().BeforeLast( '/' ) ) )
284  islastItem = true;
285 
286  footprintListBySheet.push_back( footprint );
287  subsurface += footprint->GetArea();
288 
289  if( islastItem )
290  {
291  // end of the footprint sublist relative to the same sheet path
292  // calculate placement of the current sublist
293  EDA_RECT freeArea;
294  int Xsize_allowed = (int) ( sqrt( subsurface ) * 4.0 / 3.0 );
295  int Ysize_allowed = (int) ( subsurface / Xsize_allowed );
296 
297  freeArea.SetWidth( Xsize_allowed );
298  freeArea.SetHeight( Ysize_allowed );
299  CRectPlacement placementArea;
300 
301  if( pass == 1 )
302  {
303  wxPoint areapos = placementSheetAreas[subareaIdx].GetOrigin()
304  + placementAreaPosition;
305  freeArea.SetOrigin( areapos );
306  }
307 
308  bool findAreaOnly = pass == 0;
309  moveFootprintsInArea( placementArea, footprintListBySheet,
310  freeArea, findAreaOnly );
311 
312  if( pass == 0 )
313  {
314  // Populate sheet placement areas list
315  EDA_RECT sub_area;
316  sub_area.SetWidth( placementArea.GetW()*scale );
317  sub_area.SetHeight( placementArea.GetH()*scale );
318  // Add a margin around the sheet placement area:
319  sub_area.Inflate( Millimeter2iu( 1.5 ) );
320 
321  placementSheetAreas.push_back( sub_area );
322 
323  placementsurface += (double) sub_area.GetWidth()*
324  sub_area.GetHeight();
325  }
326 
327  // Prepare buffers for next sheet
328  subsurface = 0.0;
329  footprintListBySheet.clear();
330  subareaIdx++;
331  }
332  }
333 
334  // End of pass:
335  // At the end of the first pass, we have to find position of each sheet
336  // placement area
337  if( pass == 0 )
338  {
339  int Xsize_allowed = (int) ( sqrt( placementsurface ) * 4.0 / 3.0 );
340  int Ysize_allowed = (int) ( placementsurface / Xsize_allowed );
341  CRectPlacement placementArea;
342  CSubRectArray vecSubRects;
343 
344  fillRectList( vecSubRects, placementSheetAreas );
345  spreadRectangles( placementArea, vecSubRects, Xsize_allowed, Ysize_allowed );
346 
347  for( unsigned it = 0; it < vecSubRects.size(); ++it )
348  {
349  TSubRect& srect = vecSubRects[it];
350  wxPoint pos( srect.x*scale, srect.y*scale );
351  wxSize size( srect.w*scale, srect.h*scale );
352  placementSheetAreas[srect.n].SetOrigin( pos );
353  placementSheetAreas[srect.n].SetSize( size );
354  }
355  }
356  } // End pass
357 
358  // Undo: commit list
359  if( aPrepareUndoCommand )
360  SaveCopyInUndoList( undoList, UR_CHANGED );
361 
362  OnModify();
363 
364  m_canvas->Refresh();
365 }
366 
367 
368 // Sort function, used to group footprints by sheet.
369 // Footprints are sorted by their sheet path.
370 // (the full sheet path restricted to the time stamp of the sheet itself,
371 // without the time stamp of the footprint ).
372 static bool sortFootprintsbySheetPath( MODULE* ref, MODULE* compare )
373 {
374  if( ref->GetPath().Length() == compare->GetPath().Length() )
375  return ref->GetPath().BeforeLast( '/' ).Cmp( compare->GetPath().BeforeLast( '/' ) ) < 0;
376 
377  return ref->GetPath().Length() < compare->GetPath().Length();
378 }
virtual void OnModify() override
Function OnModify must be called after a board change to set the modified flag.
Definition: pcbframe.cpp:1001
int GetH() const
void SpreadFootprints(std::vector< MODULE * > *aFootprints, bool aMoveFootprintsOutsideBoardOnly, bool aCheckForBoardEdges, wxPoint aSpreadAreaPosition, bool aPrepareUndoCommand=true)
Function SpreadFootprints Footprints (after loaded by reading a netlist for instance) are moved to be...
virtual void Refresh(bool eraseBackground=true, const wxRect *rect=NULL) override
Update the board display after modifying it bu a python script (note: it is automatically called by a...
Definition: draw_panel.cpp:325
void Init(int w=1, int h=1)
This file is part of the common library.
bool Contains(const wxPoint &aPoint) const
Function Contains.
Class BOARD to handle a board.
const wxPoint & GetPosition() const override
Definition: class_module.h:175
int GetHeight() const
void SetOrigin(const wxPoint &pos)
BOARD * GetBoard() const
void fillRectList(CSubRectArray &vecSubRects, std::vector< MODULE * > &aModuleList)
static bool Greater(const TRect &a, const TRect &b)
void SetLink(EDA_ITEM *aItem)
const EDA_RECT GetBoardEdgesBoundingBox() const
Function GetBoardEdgesBoundingBox Returns the board bounding box calculated using exclusively the boa...
Definition: class_board.h:797
const wxPoint & GetOrigin() const
const EDA_RECT GetBoundingBox() const override
Function GetBoundingBox returns the orthogonal, bounding box of this object for display purposes...
void SetHeight(int val)
int GetW() const
static bool sortFootprintsbySheetPath(MODULE *ref, MODULE *compare)
std::vector< TSubRect > CSubRectArray
Class PICKED_ITEMS_LIST is a holder to handle information on schematic or board items.
void SaveCopyInUndoList(BOARD_ITEM *aItemToCopy, UNDO_REDO_T aTypeCommand, const wxPoint &aTransformPoint=wxPoint(0, 0)) override
Function SaveCopyInUndoList Creates a new entry in undo list of commands.
Definition: undo_redo.cpp:199
void SetItem(EDA_ITEM *aItem)
void SetWidth(int val)
const wxPoint GetEnd() const
TSubRect(int _w, int _h, int _n)
EDA_DRAW_PANEL * m_canvas
The area to draw on.
Definition: draw_frame.h:93
const int scale
double GetArea() const
Definition: class_module.h:545
void Move(const wxPoint &aMoveVector) override
Function Move move this object.
Class EDA_RECT handles the component boundary box.
int GetWidth() const
bool AddAtEmptySpotAutoGrow(TRect *pRect, int maxW, int maxH)
Module description (excepted pads)
const wxString & GetPath() const
Definition: class_module.h:193
void moveFootprintsInArea(CRectPlacement &aPlacementArea, std::vector< MODULE * > &aModuleList, EDA_RECT &aFreeArea, bool aFindAreaOnly)
void DisplayError(wxWindow *parent, const wxString &text, int displaytime)
Function DisplayError displays an error or warning message box with aMessage.
Definition: confirm.cpp:73
void spreadRectangles(CRectPlacement &aPlacementArea, CSubRectArray &vecSubRects, int areaSizeX, int areaSizeY)
EDA_RECT & Inflate(wxCoord dx, wxCoord dy)
Function Inflate inflates the rectangle horizontally by dx and vertically by dy.