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