KiCad PCB EDA Suite
Loading...
Searching...
No Matches
ar_autoplacer.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) 2012 Jean-Pierre Charras, [email protected]
5 * Copyright (C) 2012 SoftPLC Corporation, Dick Hollenbeck <[email protected]>
6 * Copyright (C) 2011 Wayne Stambaugh <[email protected]>
7 *
8 * Copyright The 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
28#include <confirm.h>
29#include <pcb_edit_frame.h>
30#include <widgets/msgpanel.h>
31#include <board.h>
32#include <footprint.h>
33#include <lset.h>
34#include <pcb_shape.h>
35#include <pad.h>
36#include <board_commit.h>
38#include <progress_reporter.h>
39
40#include "ar_autoplacer.h"
41#include "ar_matrix.h"
42#include <memory>
44
45#define AR_GAIN 16
46#define AR_KEEPOUT_MARGIN 500
47#define AR_ABORT_PLACEMENT -1
48
49#define STEP_AR_MM 1.0
50
51/* Bits characterizing cell */
52#define CELL_IS_EMPTY 0x00
53#define CELL_IS_HOLE 0x01 /* a conducting hole or obstacle */
54#define CELL_IS_MODULE 0x02 /* auto placement occupied by a footprint */
55#define CELL_IS_EDGE 0x20 /* Area and auto-placement: limiting cell contour (Board, Zone) */
56#define CELL_IS_FRIEND 0x40 /* Area and auto-placement: cell part of the net */
57#define CELL_IS_ZONE 0x80 /* Area and auto-placement: cell available */
58
59
61{
62 m_board = aBoard;
63 m_connectivity = std::make_unique<CONNECTIVITY_DATA>( );
64
65 for( FOOTPRINT* footprint : m_board->Footprints() )
66 m_connectivity->Add( footprint );
67
69 m_progressReporter = nullptr;
70 m_refreshCallback = nullptr;
71 m_minCost = 0.0;
72}
73
74
75void AR_AUTOPLACER::placeFootprint( FOOTPRINT* aFootprint, bool aDoNotRecreateRatsnest,
76 const VECTOR2I& aPos )
77{
78 if( !aFootprint )
79 return;
80
81 aFootprint->SetPosition( aPos );
82 m_connectivity->Update( aFootprint );
83}
84
85
87{
88 m_matrix.UnInitRoutingMatrix();
89
90 BOX2I bbox = m_board->GetBoardEdgesBoundingBox();
91
92 if( bbox.GetWidth() == 0 || bbox.GetHeight() == 0 )
93 return 0;
94
95 // Build the board shape
96 m_board->GetBoardPolygonOutlines( m_boardShape );
99
100 m_matrix.ComputeMatrixSize( bbox );
101 int nbCells = m_matrix.m_Ncols * m_matrix.m_Nrows;
102
103 // Choose the number of board sides.
104 m_matrix.m_RoutingLayersCount = 2;
105 m_matrix.InitRoutingMatrix();
106 m_matrix.m_routeLayerBottom = B_Cu;
107 m_matrix.m_routeLayerTop = F_Cu;
108
109 // Fill (mark) the cells inside the board:
110 fillMatrix();
111
112 // Other obstacles can be added here:
113 for( auto drawing : m_board->Drawings() )
114 {
115 switch( drawing->Type() )
116 {
117 case PCB_SHAPE_T:
118 if( drawing->GetLayer() != Edge_Cuts )
119 {
120 m_matrix.TracePcbShape( (PCB_SHAPE*) drawing, CELL_IS_HOLE | CELL_IS_EDGE,
121 m_matrix.m_GridRouting, AR_MATRIX::WRITE_CELL );
122 }
123
124 break;
125
126 default:
127 break;
128 }
129 }
130
131 // Initialize top layer. to the same value as the bottom layer
132 if( m_matrix.m_BoardSide[AR_SIDE_TOP] )
133 {
134 memcpy( m_matrix.m_BoardSide[AR_SIDE_TOP], m_matrix.m_BoardSide[AR_SIDE_BOTTOM],
135 nbCells * sizeof(AR_MATRIX::MATRIX_CELL) );
136 }
137
138 return 1;
139}
140
141
143{
144 std::vector <int> x_coordinates;
145 bool success = true;
146 int step = m_matrix.m_GridRouting;
147 VECTOR2I coord_orgin = m_matrix.GetBrdCoordOrigin(); // Board coordinate of matruix cell (0,0)
148
149 // Create a single board outline:
150 SHAPE_POLY_SET brd_shape = m_boardShape.CloneDropTriangulation();
151 brd_shape.Fracture();
152 const SHAPE_LINE_CHAIN& outline = brd_shape.Outline(0);
153 const BOX2I& rect = outline.BBox();
154
155 // Creates the horizontal segments
156 // Calculate the y limits of the area
157 for( int refy = rect.GetY(), endy = rect.GetBottom(); refy < endy; refy += step )
158 {
159 // The row index (vertical position) of current line scan inside the placement matrix
160 int idy = (refy - coord_orgin.y) / step;
161
162 // Ensure we are still inside the placement matrix
163 if( idy >= m_matrix.m_Nrows )
164 break;
165
166 // Ensure we are inside the placement matrix
167 if( idy <= 0 )
168 continue;
169
170 // find all intersection points of an infinite line with polyline sides
171 x_coordinates.clear();
172
173 for( int v = 0; v < outline.PointCount(); v++ )
174 {
175 int seg_startX = outline.CPoint( v ).x;
176 int seg_startY = outline.CPoint( v ).y;
177 int seg_endX = outline.CPoint( v + 1 ).x;
178 int seg_endY = outline.CPoint( v + 1 ).y;
179
180 /* Trivial cases: skip if ref above or below the segment to test */
181 if( ( seg_startY > refy ) && ( seg_endY > refy ) )
182 continue;
183
184 // segment below ref point, or its Y end pos on Y coordinate ref point: skip
185 if( ( seg_startY <= refy ) && (seg_endY <= refy ) )
186 continue;
187
188 /* at this point refy is between seg_startY and seg_endY
189 * see if an horizontal line at Y = refy is intersecting this segment
190 */
191 // calculate the x position of the intersection of this segment and the
192 // infinite line this is more easier if we move the X,Y axis origin to
193 // the segment start point:
194
195 seg_endX -= seg_startX;
196 seg_endY -= seg_startY;
197 double newrefy = (double) ( refy - seg_startY );
198 double intersec_x;
199
200 if ( seg_endY == 0 ) // horizontal segment on the same line: skip
201 continue;
202
203 // Now calculate the x intersection coordinate of the horizontal line at
204 // y = newrefy and the segment from (0,0) to (seg_endX,seg_endY) with the
205 // horizontal line at the new refy position the line slope is:
206 // slope = seg_endY/seg_endX; and inv_slope = seg_endX/seg_endY
207 // and the x pos relative to the new origin is:
208 // intersec_x = refy/slope = refy * inv_slope
209 // Note: because horizontal segments are already tested and skipped, slope
210 // exists (seg_end_y not O)
211 double inv_slope = (double) seg_endX / seg_endY;
212 intersec_x = newrefy * inv_slope;
213 x_coordinates.push_back( (int) intersec_x + seg_startX );
214 }
215
216 // A line scan is finished: build list of segments
217
218 // Sort intersection points by increasing x value:
219 // So 2 consecutive points are the ends of a segment
220 std::sort( x_coordinates.begin(), x_coordinates.end() );
221
222 // An even number of coordinates is expected, because a segment has 2 ends.
223 // An if this algorithm always works, it must always find an even count.
224 if( ( x_coordinates.size() & 1 ) != 0 )
225 {
226 success = false;
227 break;
228 }
229
230 // Fill cells having the same Y coordinate
231 int iimax = x_coordinates.size() - 1;
232
233 for( int ii = 0; ii < iimax; ii += 2 )
234 {
235 int seg_start_x = x_coordinates[ii] - coord_orgin.x;
236 int seg_end_x = x_coordinates[ii + 1] - coord_orgin.x;
237
238 // Fill cells at y coord = idy,
239 // and at x cood >= seg_start_x and <= seg_end_x
240
241 for( int idx = seg_start_x / step; idx < m_matrix.m_Ncols; idx++ )
242 {
243 if( idx * step > seg_end_x )
244 break;
245
246 if( idx * step >= seg_start_x )
247 m_matrix.SetCell( idy, idx, AR_SIDE_BOTTOM, CELL_IS_ZONE );
248 }
249 }
250 } // End examine segments in one area
251
252 return success;
253}
254
255
256void AR_AUTOPLACER::addFpBody( const VECTOR2I& aStart, const VECTOR2I& aEnd, const LSET& aLayerMask )
257{
258 // Add a polygonal shape (rectangle) to m_fpAreaFront and/or m_fpAreaBack
259 if( aLayerMask[ F_Cu ] )
260 {
261 m_fpAreaTop.NewOutline();
262 m_fpAreaTop.Append( aStart.x, aStart.y );
263 m_fpAreaTop.Append( aEnd.x, aStart.y );
264 m_fpAreaTop.Append( aEnd.x, aEnd.y );
265 m_fpAreaTop.Append( aStart.x, aEnd.y );
266 }
267
268 if( aLayerMask[ B_Cu ] )
269 {
270 m_fpAreaBottom.NewOutline();
271 m_fpAreaBottom.Append( aStart.x, aStart.y );
272 m_fpAreaBottom.Append( aEnd.x, aStart.y );
273 m_fpAreaBottom.Append( aEnd.x, aEnd.y );
274 m_fpAreaBottom.Append( aStart.x, aEnd.y );
275 }
276}
277
278
279void AR_AUTOPLACER::addPad( PAD* aPad, int aClearance )
280{
281 // Add a polygonal shape (rectangle) to m_fpAreaFront and/or m_fpAreaBack
282 BOX2I bbox = aPad->GetBoundingBox();
283 bbox.Inflate( aClearance );
284
285 if( aPad->IsOnLayer( F_Cu ) )
286 {
287 m_fpAreaTop.NewOutline();
288 m_fpAreaTop.Append( bbox.GetLeft(), bbox.GetTop() );
289 m_fpAreaTop.Append( bbox.GetRight(), bbox.GetTop() );
290 m_fpAreaTop.Append( bbox.GetRight(), bbox.GetBottom() );
291 m_fpAreaTop.Append( bbox.GetLeft(), bbox.GetBottom() );
292 }
293
294 if( aPad->IsOnLayer( B_Cu ) )
295 {
296 m_fpAreaBottom.NewOutline();
297 m_fpAreaBottom.Append( bbox.GetLeft(), bbox.GetTop() );
298 m_fpAreaBottom.Append( bbox.GetRight(), bbox.GetTop() );
299 m_fpAreaBottom.Append( bbox.GetRight(), bbox.GetBottom() );
300 m_fpAreaBottom.Append( bbox.GetLeft(), bbox.GetBottom() );
301 }
302}
303
304
305void AR_AUTOPLACER::buildFpAreas( FOOTPRINT* aFootprint, int aFpClearance )
306{
307 m_fpAreaTop.RemoveAllContours();
308 m_fpAreaBottom.RemoveAllContours();
309
310 aFootprint->BuildCourtyardCaches();
311 m_fpAreaTop = aFootprint->GetCourtyard( F_CrtYd );
312 m_fpAreaBottom = aFootprint->GetCourtyard( B_CrtYd );
313
314 LSET layerMask;
315
316 if( aFootprint->GetLayer() == F_Cu )
317 layerMask.set( F_Cu );
318
319 if( aFootprint->GetLayer() == B_Cu )
320 layerMask.set( B_Cu );
321
322 BOX2I fpBBox = aFootprint->GetBoundingBox( false );
323
324 fpBBox.Inflate( ( m_matrix.m_GridRouting / 2 ) + aFpClearance );
325
326 // Add a minimal area to the fp area:
327 addFpBody( fpBBox.GetOrigin(), fpBBox.GetEnd(), layerMask );
328
329 // Trace pads + clearance areas.
330 for( PAD* pad : aFootprint->Pads() )
331 {
332 int margin = (m_matrix.m_GridRouting / 2) + pad->GetOwnClearance( pad->GetLayer() );
333 addPad( pad, margin );
334 }
335}
336
337
339{
340 int ox, oy, fx, fy;
341 LSET layerMask;
342 BOX2I fpBBox = aFootprint->GetBoundingBox( false );
343
344 fpBBox.Inflate( m_matrix.m_GridRouting / 2 );
345 ox = fpBBox.GetX();
346 fx = fpBBox.GetRight();
347 oy = fpBBox.GetY();
348 fy = fpBBox.GetBottom();
349
350 if( ox < m_matrix.m_BrdBox.GetX() )
351 ox = m_matrix.m_BrdBox.GetX();
352
353 if( ox > m_matrix.m_BrdBox.GetRight() )
354 ox = m_matrix.m_BrdBox.GetRight();
355
356 if( fx < m_matrix.m_BrdBox.GetX() )
357 fx = m_matrix.m_BrdBox.GetX();
358
359 if( fx > m_matrix.m_BrdBox.GetRight() )
360 fx = m_matrix.m_BrdBox.GetRight();
361
362 if( oy < m_matrix.m_BrdBox.GetY() )
363 oy = m_matrix.m_BrdBox.GetY();
364
365 if( oy > m_matrix.m_BrdBox.GetBottom() )
366 oy = m_matrix.m_BrdBox.GetBottom();
367
368 if( fy < m_matrix.m_BrdBox.GetY() )
369 fy = m_matrix.m_BrdBox.GetY();
370
371 if( fy > m_matrix.m_BrdBox.GetBottom() )
372 fy = m_matrix.m_BrdBox.GetBottom();
373
374 if( aFootprint->GetLayer() == F_Cu )
375 layerMask.set( F_Cu );
376
377 if( aFootprint->GetLayer() == B_Cu )
378 layerMask.set( B_Cu );
379
380 m_matrix.TraceFilledRectangle( ox, oy, fx, fy, layerMask,
382
383 // Trace pads + clearance areas.
384 for( PAD* pad : aFootprint->Pads() )
385 {
386 int margin = (m_matrix.m_GridRouting / 2) + pad->GetOwnClearance( pad->GetLayer() );
388 }
389
390 // Trace clearance.
391 int margin = ( m_matrix.m_GridRouting * aFootprint->GetPadCount() ) / AR_GAIN;
392 m_matrix.CreateKeepOutRectangle( ox, oy, fx, fy, margin, AR_KEEPOUT_MARGIN , layerMask );
393
394 // Build the footprint courtyard
395 buildFpAreas( aFootprint, margin );
396
397 // Substract the shape to free areas
398 m_topFreeArea.BooleanSubtract( m_fpAreaTop );
399 m_bottomFreeArea.BooleanSubtract( m_fpAreaBottom );
400}
401
402
403int AR_AUTOPLACER::testRectangle( const BOX2I& aRect, int side )
404{
405 BOX2I rect = aRect;
406
407 rect.Inflate( m_matrix.m_GridRouting / 2 );
408
409 VECTOR2I start = rect.GetOrigin();
410 VECTOR2I end = rect.GetEnd();
411
412 start -= m_matrix.m_BrdBox.GetOrigin();
413 end -= m_matrix.m_BrdBox.GetOrigin();
414
415 int row_min = start.y / m_matrix.m_GridRouting;
416 int row_max = end.y / m_matrix.m_GridRouting;
417 int col_min = start.x / m_matrix.m_GridRouting;
418 int col_max = end.x / m_matrix.m_GridRouting;
419
420 if( start.y > row_min * m_matrix.m_GridRouting )
421 row_min++;
422
423 if( start.x > col_min * m_matrix.m_GridRouting )
424 col_min++;
425
426 if( row_min < 0 )
427 row_min = 0;
428
429 if( row_max >= ( m_matrix.m_Nrows - 1 ) )
430 row_max = m_matrix.m_Nrows - 1;
431
432 if( col_min < 0 )
433 col_min = 0;
434
435 if( col_max >= ( m_matrix.m_Ncols - 1 ) )
436 col_max = m_matrix.m_Ncols - 1;
437
438 for( int row = row_min; row <= row_max; row++ )
439 {
440 for( int col = col_min; col <= col_max; col++ )
441 {
442 unsigned int data = m_matrix.GetCell( row, col, side );
443
444 if( ( data & CELL_IS_ZONE ) == 0 )
445 return AR_OUT_OF_BOARD;
446
447 if( (data & CELL_IS_MODULE) )
449 }
450 }
451
452 return AR_FREE_CELL;
453}
454
455
456unsigned int AR_AUTOPLACER::calculateKeepOutArea( const BOX2I& aRect, int side )
457{
458 VECTOR2I start = aRect.GetOrigin();
459 VECTOR2I end = aRect.GetEnd();
460
461 start -= m_matrix.m_BrdBox.GetOrigin();
462 end -= m_matrix.m_BrdBox.GetOrigin();
463
464 int row_min = start.y / m_matrix.m_GridRouting;
465 int row_max = end.y / m_matrix.m_GridRouting;
466 int col_min = start.x / m_matrix.m_GridRouting;
467 int col_max = end.x / m_matrix.m_GridRouting;
468
469 if( start.y > row_min * m_matrix.m_GridRouting )
470 row_min++;
471
472 if( start.x > col_min * m_matrix.m_GridRouting )
473 col_min++;
474
475 if( row_min < 0 )
476 row_min = 0;
477
478 if( row_max >= ( m_matrix.m_Nrows - 1 ) )
479 row_max = m_matrix.m_Nrows - 1;
480
481 if( col_min < 0 )
482 col_min = 0;
483
484 if( col_max >= ( m_matrix.m_Ncols - 1 ) )
485 col_max = m_matrix.m_Ncols - 1;
486
487 unsigned int keepOutCost = 0;
488
489 for( int row = row_min; row <= row_max; row++ )
490 {
491 for( int col = col_min; col <= col_max; col++ )
492 {
493 // m_matrix.GetDist returns the "cost" of the cell
494 // at position (row, col)
495 // in autoplace this is the cost of the cell, if it is
496 // inside aRect
497 keepOutCost += m_matrix.GetDist( row, col, side );
498 }
499 }
500
501 return keepOutCost;
502}
503
504
505int AR_AUTOPLACER::testFootprintOnBoard( FOOTPRINT* aFootprint, bool TstOtherSide,
506 const VECTOR2I& aOffset )
507{
508 int side = AR_SIDE_TOP;
509 int otherside = AR_SIDE_BOTTOM;
510
511 if( aFootprint->GetLayer() == B_Cu )
512 {
513 side = AR_SIDE_BOTTOM; otherside = AR_SIDE_TOP;
514 }
515
516 BOX2I fpBBox = aFootprint->GetBoundingBox( false );
517 fpBBox.Move( -1*aOffset );
518
519 int diag = testRectangle( fpBBox, side );
520
521 if( diag != AR_FREE_CELL )
522 return diag;
523
524 if( TstOtherSide )
525 {
526 diag = testRectangle( fpBBox, otherside );
527
528 if( diag != AR_FREE_CELL )
529 return diag;
530 }
531
532 int marge = ( m_matrix.m_GridRouting * aFootprint->GetPadCount() ) / AR_GAIN;
533
534 fpBBox.Inflate( marge );
535 return calculateKeepOutArea( fpBBox, side );
536}
537
538
540{
541 int error = 1;
542 VECTOR2I lastPosOK;
543 double min_cost, curr_cost, Score;
544 bool testOtherSide;
545
546 lastPosOK = m_matrix.m_BrdBox.GetOrigin();
547
548 VECTOR2I fpPos = aFootprint->GetPosition();
549 BOX2I fpBBox = aFootprint->GetBoundingBox( false );
550
551 // Move fpBBox to have the footprint position at (0,0)
552 fpBBox.Move( -fpPos );
553 VECTOR2I fpBBoxOrg = fpBBox.GetOrigin();
554
555 // Calculate the limit of the footprint position, relative to the routing matrix area
556 VECTOR2I xylimit = m_matrix.m_BrdBox.GetEnd() - fpBBox.GetEnd();
557
558 VECTOR2I initialPos = m_matrix.m_BrdBox.GetOrigin() - fpBBoxOrg;
559
560 // Stay on grid.
561 initialPos.x -= initialPos.x % m_matrix.m_GridRouting;
562 initialPos.y -= initialPos.y % m_matrix.m_GridRouting;
563
564 m_curPosition = initialPos;
565 VECTOR2I fpOffset = fpPos - m_curPosition;
566
567 // Examine pads, and set testOtherSide to true if a footprint has at least 1 pad through.
568 testOtherSide = false;
569
570 if( m_matrix.m_RoutingLayersCount > 1 )
571 {
572 LSET other( { aFootprint->GetLayer() == B_Cu ? F_Cu : B_Cu } );
573
574 for( PAD* pad : aFootprint->Pads() )
575 {
576 if( !( pad->GetLayerSet() & other ).any() )
577 continue;
578
579 testOtherSide = true;
580 break;
581 }
582 }
583
584 fpBBox.SetOrigin( fpBBoxOrg + m_curPosition );
585
586 min_cost = -1.0;
587// m_frame->SetStatusText( wxT( "Score ??, pos ??" ) );
588
589
590 for( ; m_curPosition.x < xylimit.x; m_curPosition.x += m_matrix.m_GridRouting )
591 {
592 m_curPosition.y = initialPos.y;
593
594 for( ; m_curPosition.y < xylimit.y; m_curPosition.y += m_matrix.m_GridRouting )
595 {
596
597 fpBBox.SetOrigin( fpBBoxOrg + m_curPosition );
598 fpOffset = fpPos - m_curPosition;
599 int keepOutCost = testFootprintOnBoard( aFootprint, testOtherSide, fpOffset );
600
601 if( keepOutCost >= 0 ) // i.e. if the footprint can be put here
602 {
603 error = 0;
604 // m_frame->build_ratsnest_footprint( aFootprint ); // fixme
605 curr_cost = computePlacementRatsnestCost( aFootprint, fpOffset );
606 Score = curr_cost + keepOutCost;
607
608 if( (min_cost >= Score ) || (min_cost < 0 ) )
609 {
610 lastPosOK = m_curPosition;
611 min_cost = Score;
612/*
613 wxString msg;
614 msg.Printf( wxT( "Score %g, pos %s, %s" ),
615 min_cost,
616 ::CoordinateToString( LastPosOK.x ),
617 ::CoordinateToString( LastPosOK.y ) );
618 m_frame->SetStatusText( msg );*/
619 }
620 }
621 }
622 }
623
624 // Regeneration of the modified variable.
625 m_curPosition = lastPosOK;
626
627 m_minCost = min_cost;
628 return error;
629}
630
631
632const PAD* AR_AUTOPLACER::nearestPad( FOOTPRINT* aRefFP, PAD* aRefPad, const VECTOR2I& aOffset )
633{
634 const PAD* nearest = nullptr;
635 int64_t nearestDist = INT64_MAX;
636
637 for( FOOTPRINT* footprint : m_board->Footprints() )
638 {
639 if ( footprint == aRefFP )
640 continue;
641
642 if( !m_matrix.m_BrdBox.Contains( footprint->GetPosition() ) )
643 continue;
644
645 for( PAD* pad: footprint->Pads() )
646 {
647 if( pad->GetNetCode() != aRefPad->GetNetCode() || pad->GetNetCode() <= 0 )
648 continue;
649
650 auto dist = ( VECTOR2I( aRefPad->GetPosition() - aOffset ) -
651 VECTOR2I( pad->GetPosition() ) ).EuclideanNorm();
652
653 if ( dist < nearestDist )
654 {
655 nearestDist = dist;
656 nearest = pad;
657 }
658 }
659 }
660
661 return nearest;
662}
663
664
666{
667 double curr_cost;
668 VECTOR2I start; // start point of a ratsnest
669 VECTOR2I end; // end point of a ratsnest
670 int dx, dy;
671
672 curr_cost = 0;
673
674 for( PAD* pad : aFootprint->Pads() )
675 {
676 const PAD* nearest = nearestPad( aFootprint, pad, aOffset );
677
678 if( !nearest )
679 continue;
680
681 start = VECTOR2I( pad->GetPosition() ) - VECTOR2I(aOffset);
682 end = VECTOR2I( nearest->GetPosition() );
683
684 //m_overlay->SetIsStroke( true );
685 //m_overlay->SetStrokeColor( COLOR4D(0.0, 1.0, 0.0, 1.0) );
686 //m_overlay->Line( start, end );
687
688 // Cost of the ratsnest.
689 dx = end.x - start.x;
690 dy = end.y - start.y;
691
692 dx = abs( dx );
693 dy = abs( dy );
694
695 // ttry to have always dx >= dy to calculate the cost of the ratsnest
696 if( dx < dy )
697 std::swap( dx, dy );
698
699 // Cost of the connection = length + penalty due to the slope
700 // dx is the biggest length relative to the X or Y axis
701 // the penalty is max for 45 degrees ratsnests,
702 // and 0 for horizontal or vertical ratsnests.
703 // For Horizontal and Vertical ratsnests, dy = 0;
704 double conn_cost = hypot( dx, dy * 2.0 );
705 curr_cost += conn_cost; // Total cost = sum of costs of each connection
706 }
707
708 return curr_cost;
709}
710
711
712// Sort routines
713static bool sortFootprintsByComplexity( FOOTPRINT* ref, FOOTPRINT* compare )
714{
715 double ff1, ff2;
716
717 ff1 = ref->GetArea() * ref->GetPadCount();
718 ff2 = compare->GetArea() * compare->GetPadCount();
719
720 return ff2 < ff1;
721}
722
723
725{
726 double ff1, ff2;
727
728 ff1 = ref->GetArea() * ref->GetFlag();
729 ff2 = compare->GetArea() * compare->GetFlag();
730 return ff2 < ff1;
731}
732
733
735{
736 std::vector<FOOTPRINT*> fpList;
737
738
739 for( FOOTPRINT* footprint : m_board->Footprints() )
740 fpList.push_back( footprint );
741
742 sort( fpList.begin(), fpList.end(), sortFootprintsByComplexity );
743
744 for( unsigned kk = 0; kk < fpList.size(); kk++ )
745 {
746 FOOTPRINT* footprint = fpList[kk];
747 footprint->SetFlag( 0 );
748
749 if( !footprint->NeedsPlaced() )
750 continue;
751
752 m_connectivity->Update( footprint );
753 }
754
755 m_connectivity->RecalculateRatsnest();
756
757 for( unsigned kk = 0; kk < fpList.size(); kk++ )
758 {
759 FOOTPRINT* footprint = fpList[kk];
760
761 auto edges = m_connectivity->GetRatsnestForComponent( footprint, true );
762
763 footprint->SetFlag( edges.size() ) ;
764 }
765
766 sort( fpList.begin(), fpList.end(), sortFootprintsByRatsnestSize );
767
768 // Search for "best" footprint.
769 FOOTPRINT* bestFootprint = nullptr;
770 FOOTPRINT* altFootprint = nullptr;
771
772 for( unsigned ii = 0; ii < fpList.size(); ii++ )
773 {
774 FOOTPRINT* footprint = fpList[ii];
775
776 if( !footprint->NeedsPlaced() )
777 continue;
778
779 altFootprint = footprint;
780
781 if( footprint->GetFlag() == 0 )
782 continue;
783
784 bestFootprint = footprint;
785 break;
786 }
787
788 if( bestFootprint )
789 return bestFootprint;
790 else
791 return altFootprint;
792}
793
794
796{
797 // Draw the board free area
798 m_overlay->Clear();
799 m_overlay->SetIsFill( true );
800 m_overlay->SetIsStroke( false );
801
802 SHAPE_POLY_SET freeArea = m_topFreeArea.CloneDropTriangulation();
803 freeArea.Fracture();
804
805 // Draw the free polygon areas, top side:
806 if( freeArea.OutlineCount() > 0 )
807 {
808 m_overlay->SetIsFill( true );
809 m_overlay->SetIsStroke( false );
810 m_overlay->SetFillColor( COLOR4D(0.7, 0.0, 0.1, 0.2) );
811 m_overlay->Polygon( freeArea );
812 }
813
814 freeArea = m_bottomFreeArea;
815 freeArea.Fracture();
816
817 // Draw the free polygon areas, bottom side:
818 if( freeArea.OutlineCount() > 0 )
819 {
820 m_overlay->SetFillColor( COLOR4D(0.0, 0.7, 0.0, 0.2) );
821 m_overlay->Polygon( freeArea );
822 }
823}
824
825
826AR_RESULT AR_AUTOPLACER::AutoplaceFootprints( std::vector<FOOTPRINT*>& aFootprints,
827 BOARD_COMMIT* aCommit,
828 bool aPlaceOffboardModules )
829{
830 VECTOR2I memopos;
831 int error;
832 bool cancelled = false;
833
834 memopos = m_curPosition;
835
836 m_matrix.m_GridRouting = m_gridSize; //(int) m_frame->GetScreen()->GetGridSize().x;
837
838 // Ensure Board.m_GridRouting has a reasonable value:
839 if( m_matrix.m_GridRouting < pcbIUScale.mmToIU( 0.25 ) )
840 m_matrix.m_GridRouting = pcbIUScale.mmToIU( 0.25 );
841
842 // Compute footprint parameters used in autoplace
843 if( genPlacementRoutingMatrix( ) == 0 )
844 return AR_FAILURE;
845
846 int placedCount = 0;
847
848 for( FOOTPRINT* footprint : m_board->Footprints() )
849 footprint->SetNeedsPlaced( false );
850
851 std::vector<FOOTPRINT*> offboardMods;
852
853 if( aPlaceOffboardModules )
854 {
855 for( FOOTPRINT* footprint : m_board->Footprints() )
856 {
857 if( !m_matrix.m_BrdBox.Contains( footprint->GetPosition() ) )
858 offboardMods.push_back( footprint );
859 }
860 }
861
862 for( FOOTPRINT* footprint : aFootprints )
863 {
864 footprint->SetNeedsPlaced( true );
865 aCommit->Modify( footprint );
866 }
867
868 for( FOOTPRINT* footprint : offboardMods )
869 {
870 footprint->SetNeedsPlaced( true );
871 aCommit->Modify( footprint );
872 }
873
874 for( FOOTPRINT* footprint : m_board->Footprints() )
875 {
876 if( footprint->NeedsPlaced() ) // Erase from screen
877 placedCount++;
878 else
879 genModuleOnRoutingMatrix( footprint );
880 }
881
883 {
884 m_progressReporter->Report( _( "Autoplacing components..." ) );
885 m_progressReporter->SetMaxProgress( placedCount );
886 }
887
889
891 m_refreshCallback( nullptr );
892
893 FOOTPRINT* footprint;
894
895 while( ( footprint = pickFootprint() ) != nullptr )
896 {
897 // Display some info about activity, footprint placement can take a while:
898
900 m_progressReporter->SetTitle( wxString::Format( _( "Autoplacing %s" ),
901 footprint->GetReference() ) );
902
903 error = getOptimalFPPlacement( footprint );
904
905 if( error == AR_ABORT_PLACEMENT )
906 break;
907
908 // Place footprint.
909 placeFootprint( footprint, true, m_curPosition );
910
911 genModuleOnRoutingMatrix( footprint );
912 footprint->SetIsPlaced( true );
913 footprint->SetNeedsPlaced( false );
915
917 m_refreshCallback( footprint );
918
920 {
921 m_progressReporter->AdvanceProgress();
922
923 if ( !m_progressReporter->KeepRefreshing( false ) )
924 {
925 cancelled = true;
926 break;
927 }
928 }
929 }
930
931 m_curPosition = memopos;
932
933 m_matrix.UnInitRoutingMatrix();
934
935 return cancelled ? AR_CANCELLED : AR_COMPLETED;
936}
#define CELL_IS_MODULE
#define STEP_AR_MM
#define AR_KEEPOUT_MARGIN
#define AR_GAIN
#define CELL_IS_ZONE
#define CELL_IS_EDGE
static bool sortFootprintsByRatsnestSize(FOOTPRINT *ref, FOOTPRINT *compare)
#define AR_ABORT_PLACEMENT
#define CELL_IS_HOLE
static bool sortFootprintsByComplexity(FOOTPRINT *ref, FOOTPRINT *compare)
AR_RESULT
@ AR_COMPLETED
@ AR_FAILURE
@ AR_CANCELLED
@ AR_FREE_CELL
@ AR_OCCUIPED_BY_MODULE
@ AR_OUT_OF_BOARD
#define AR_SIDE_BOTTOM
Definition ar_matrix.h:43
#define AR_SIDE_TOP
Definition ar_matrix.h:42
constexpr EDA_IU_SCALE pcbIUScale
Definition base_units.h:112
BOX2< VECTOR2I > BOX2I
Definition box2.h:922
std::function< int(FOOTPRINT *aFootprint)> m_refreshCallback
std::unique_ptr< CONNECTIVITY_DATA > m_connectivity
void drawPlacementRoutingMatrix()
int getOptimalFPPlacement(FOOTPRINT *aFootprint)
AR_RESULT AutoplaceFootprints(std::vector< FOOTPRINT * > &aFootprints, BOARD_COMMIT *aCommit, bool aPlaceOffboardModules=false)
int testRectangle(const BOX2I &aRect, int side)
SHAPE_POLY_SET m_fpAreaTop
bool fillMatrix()
Fill m_matrix cells from m_boardShape.
AR_AUTOPLACER(BOARD *aBoard)
PROGRESS_REPORTER * m_progressReporter
const PAD * nearestPad(FOOTPRINT *aRefFP, PAD *aRefPad, const VECTOR2I &aOffset)
void buildFpAreas(FOOTPRINT *aFootprint, int aFpClearance)
unsigned int calculateKeepOutArea(const BOX2I &aRect, int side)
void placeFootprint(FOOTPRINT *aFootprint, bool aDoNotRecreateRatsnest, const VECTOR2I &aPos)
FOOTPRINT * pickFootprint()
Find the "best" footprint place.
void genModuleOnRoutingMatrix(FOOTPRINT *aFootprint)
SHAPE_POLY_SET m_topFreeArea
void addPad(PAD *aPad, int aClearance)
void addFpBody(const VECTOR2I &aStart, const VECTOR2I &aEnd, const LSET &aLayerMask)
int testFootprintOnBoard(FOOTPRINT *aFootprint, bool TstOtherSide, const VECTOR2I &aOffset)
AR_MATRIX m_matrix
SHAPE_POLY_SET m_fpAreaBottom
double computePlacementRatsnestCost(FOOTPRINT *aFootprint, const VECTOR2I &aOffset)
std::shared_ptr< KIGFX::VIEW_OVERLAY > m_overlay
SHAPE_POLY_SET m_boardShape
VECTOR2I m_curPosition
int genPlacementRoutingMatrix()
SHAPE_POLY_SET m_bottomFreeArea
unsigned char MATRIX_CELL
Definition ar_matrix.h:51
@ WRITE_OR_CELL
Definition ar_matrix.h:57
BASE_SET & set(size_t pos)
Definition base_set.h:116
Information pertinent to a Pcbnew printed circuit board.
Definition board.h:322
constexpr BOX2< Vec > & Inflate(coord_type dx, coord_type dy)
Inflates the rectangle horizontally by dx and vertically by dy.
Definition box2.h:558
constexpr const Vec GetEnd() const
Definition box2.h:212
constexpr void SetOrigin(const Vec &pos)
Definition box2.h:237
constexpr coord_type GetY() const
Definition box2.h:208
constexpr size_type GetWidth() const
Definition box2.h:214
constexpr coord_type GetX() const
Definition box2.h:207
constexpr size_type GetHeight() const
Definition box2.h:215
constexpr coord_type GetLeft() const
Definition box2.h:228
constexpr void Move(const Vec &aMoveVector)
Move the rectangle by the aMoveVector.
Definition box2.h:138
constexpr const Vec & GetOrigin() const
Definition box2.h:210
constexpr coord_type GetRight() const
Definition box2.h:217
constexpr coord_type GetTop() const
Definition box2.h:229
constexpr coord_type GetBottom() const
Definition box2.h:222
COMMIT & Modify(EDA_ITEM *aItem, BASE_SCREEN *aScreen=nullptr, RECURSE_MODE aRecurse=RECURSE_MODE::NO_RECURSE)
Modify a given item in the model.
Definition commit.h:106
void SetPosition(const VECTOR2I &aPos) override
void SetIsPlaced(bool isPlaced)
Definition footprint.h:478
void SetFlag(int aFlag)
Definition footprint.h:336
unsigned GetPadCount(INCLUDE_NPTH_T aIncludeNPTH=INCLUDE_NPTH_T(INCLUDE_NPTH)) const
Return the number of pads.
std::deque< PAD * > & Pads()
Definition footprint.h:224
PCB_LAYER_ID GetLayer() const override
Return the primary layer this item is on.
Definition footprint.h:257
bool NeedsPlaced() const
Definition footprint.h:486
void BuildCourtyardCaches(OUTLINE_ERROR_HANDLER *aErrorHandler=nullptr)
Build complex polygons of the courtyard areas from graphic items on the courtyard layers.
double GetArea(int aPadding=0) const
void SetNeedsPlaced(bool needsPlaced)
Definition footprint.h:487
const wxString & GetReference() const
Definition footprint.h:661
const SHAPE_POLY_SET & GetCourtyard(PCB_LAYER_ID aLayer) const
Used in DRC to test the courtyard area (a complex polygon).
int GetFlag() const
Definition footprint.h:338
VECTOR2I GetPosition() const override
Definition footprint.h:245
const BOX2I GetBoundingBox() const override
Return the orthogonal bounding box of this object for display purposes.
A color representation with 4 components: red, green, blue, alpha.
Definition color4d.h:104
LSET is a set of PCB_LAYER_IDs.
Definition lset.h:37
Definition pad.h:54
const BOX2I GetBoundingBox() const override
The bounding box is cached, so this will be efficient most of the time.
Definition pad.cpp:867
bool IsOnLayer(PCB_LAYER_ID aLayer) const override
Test to see if this object is on the given layer.
Definition pad.h:783
VECTOR2I GetPosition() const override
Definition pad.h:208
Represent a polyline containing arcs as well as line segments: A chain of connected line and/or arc s...
int PointCount() const
Return the number of points (vertices) in this line chain.
const VECTOR2I & CPoint(int aIndex) const
Return a reference to a given point in the line chain.
const BOX2I BBox(int aClearance=0) const override
Compute a bounding box of the shape, with a margin of aClearance a collision.
Represent a set of closed polygons.
void Fracture()
Convert a set of polygons with holes to a single outline with "slits"/"fractures" connecting the oute...
SHAPE_LINE_CHAIN & Outline(int aIndex)
Return the reference to aIndex-th outline in the set.
int OutlineCount() const
Return the number of outlines in the set.
This file is part of the common library.
#define _(s)
@ F_CrtYd
Definition layer_ids.h:116
@ Edge_Cuts
Definition layer_ids.h:112
@ B_Cu
Definition layer_ids.h:65
@ B_CrtYd
Definition layer_ids.h:115
@ F_Cu
Definition layer_ids.h:64
Message panel definition file.
Class that computes missing connections on a PCB.
VECTOR2I end
@ PCB_SHAPE_T
class PCB_SHAPE, a segment not on copper layers
Definition typeinfo.h:88
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:695