pns_optimizer.cpp 20.5 KB
Newer Older
1 2 3
/*
 * KiRouter - a push-and-(sometimes-)shove PCB router
 *
4
 * Copyright (C) 2013-2014 CERN
5
 * Author: Tomasz Wlostowski <tomasz.wlostowski@cern.ch>
6
 *
7 8 9 10
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or (at your
 * option) any later version.
11
 *
12 13 14 15
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License along
18
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
19
 */
20

21 22 23 24 25 26 27 28 29
#include <boost/foreach.hpp>

#include <geometry/shape_line_chain.h>
#include <geometry/shape_rect.h>

#include "pns_line.h"
#include "pns_node.h"
#include "pns_optimizer.h"
#include "pns_utils.h"
30
#include "pns_router.h"
31 32

/**
33
 *  Cost Estimator Methods
34
 */
35
int PNS_COST_ESTIMATOR::CornerCost( const SEG& aA, const SEG& aB )
36
{
37
    DIRECTION_45 dir_a( aA ), dir_b( aB );
38

39 40 41 42
    switch( dir_a.Angle( dir_b ) )
    {
    case DIRECTION_45::ANG_OBTUSE:
        return 1;
43

44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
    case DIRECTION_45::ANG_STRAIGHT:
        return 0;

    case DIRECTION_45::ANG_ACUTE:
        return 50;

    case DIRECTION_45::ANG_RIGHT:
        return 30;

    case DIRECTION_45::ANG_HALF_FULL:
        return 60;

    default:
        return 100;
    }
59 60
}

61 62

int PNS_COST_ESTIMATOR::CornerCost( const SHAPE_LINE_CHAIN& aLine )
63
{
64 65 66 67 68 69
    int total = 0;

    for( int i = 0; i < aLine.SegmentCount() - 1; ++i )
        total += CornerCost( aLine.CSegment( i ), aLine.CSegment( i + 1 ) );

    return total;
70 71 72
}


73
int PNS_COST_ESTIMATOR::CornerCost( const PNS_LINE& aLine )
74
{
75
    return CornerCost( aLine.CLine() );
76 77
}

78 79

void PNS_COST_ESTIMATOR::Add( PNS_LINE& aLine )
80
{
81
    m_lengthCost += aLine.CLine().Length();
82
    m_cornerCost += CornerCost( aLine );
83 84
}

85 86

void PNS_COST_ESTIMATOR::Remove( PNS_LINE& aLine )
87
{
88
    m_lengthCost -= aLine.CLine().Length();
89
    m_cornerCost -= CornerCost( aLine );
90 91
}

92 93

void PNS_COST_ESTIMATOR::Replace( PNS_LINE& aOldLine, PNS_LINE& aNewLine )
94
{
95
    m_lengthCost -= aOldLine.CLine().Length();
96
    m_cornerCost -= CornerCost( aOldLine );
97
    m_lengthCost += aNewLine.CLine().Length();
98
    m_cornerCost += CornerCost( aNewLine );
99 100 101
}


102 103 104
bool PNS_COST_ESTIMATOR::IsBetter( PNS_COST_ESTIMATOR& aOther,
        double aLengthTollerance,
        double aCornerTollerance ) const
105
{
106 107
    if( aOther.m_cornerCost < m_cornerCost && aOther.m_lengthCost < m_lengthCost )
        return true;
108

109 110
    else if( aOther.m_cornerCost < m_cornerCost * aCornerTollerance &&
             aOther.m_lengthCost < m_lengthCost * aLengthTollerance )
111 112 113
        return true;

    return false;
114 115 116 117
}


/**
118 119 120 121
 *  Optimizer
 **/
PNS_OPTIMIZER::PNS_OPTIMIZER( PNS_NODE* aWorld ) :
    m_world( aWorld ), m_collisionKindMask( PNS_ITEM::ANY ), m_effortLevel( MERGE_SEGMENTS )
122
{
123
    // m_cache = new SHAPE_INDEX_LIST<PNS_ITEM*>();
124 125 126
}


127
PNS_OPTIMIZER::~PNS_OPTIMIZER()
128
{
129 130
    // delete m_cache;
}
131 132


133
struct PNS_OPTIMIZER::CACHE_VISITOR
134
{
135
    CACHE_VISITOR( const PNS_ITEM* aOurItem, PNS_NODE* aNode, int aMask ) :
136 137 138 139
        m_ourItem( aOurItem ),
        m_collidingItem( NULL ),
        m_node( aNode ),
        m_mask( aMask )
140
    {}
141 142 143

    bool operator()( PNS_ITEM* aOtherItem )
    {
144
        if( !m_mask & aOtherItem->Kind() )
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
            return true;

        int clearance = m_node->GetClearance( aOtherItem, m_ourItem );

        if( !aOtherItem->Collide( m_ourItem, clearance ) )
            return true;

        m_collidingItem = aOtherItem;
        return false;
    }

    const PNS_ITEM* m_ourItem;
    PNS_ITEM* m_collidingItem;
    PNS_NODE* m_node;
    int m_mask;
160 161
};

162 163

void PNS_OPTIMIZER::cacheAdd( PNS_ITEM* aItem, bool aIsStatic = false )
164
{
165 166
    if( m_cacheTags.find( aItem ) != m_cacheTags.end() )
        return;
167

168
    m_cache.Add( aItem );
169 170
    m_cacheTags[aItem].m_hits = 1;
    m_cacheTags[aItem].m_isStatic = aIsStatic;
171 172
}

173 174

void PNS_OPTIMIZER::removeCachedSegments( PNS_LINE* aLine, int aStartVertex, int aEndVertex )
175
{
176
    PNS_LINE::SEGMENT_REFS* segs = aLine->LinkedSegments();
177

178 179
    if( !segs )
        return;
180

181
    if( aEndVertex < 0 )
182
        aEndVertex += aLine->PointCount();
183

184 185 186 187 188 189
    for( int i = aStartVertex; i < aEndVertex - 1; i++ )
    {
        PNS_SEGMENT* s = (*segs)[i];
        m_cacheTags.erase( s );
        m_cache.Remove( s );
    }    // *cacheRemove( (*segs)[i] );
190 191
}

192 193

void PNS_OPTIMIZER::CacheRemove( PNS_ITEM* aItem )
194
{
195
    if( aItem->Kind() == PNS_ITEM::LINE )
196
        removeCachedSegments( static_cast<PNS_LINE*>( aItem ) );
197 198
}

199 200

void PNS_OPTIMIZER::CacheStaticItem( PNS_ITEM* aItem )
201
{
202
    cacheAdd( aItem, true );
203 204
}

205

206 207
void PNS_OPTIMIZER::ClearCache( bool aStaticOnly  )
{
208 209 210 211 212 213 214 215 216
    if( !aStaticOnly )
    {
        m_cacheTags.clear();
        m_cache.Clear();
        return;
    }

    for( CachedItemTags::iterator i = m_cacheTags.begin(); i!= m_cacheTags.end(); ++i )
    {
217
        if( i->second.m_isStatic )
218 219 220 221 222
        {
            m_cache.Remove( i->first );
            m_cacheTags.erase( i->first );
        }
    }
223 224
}

225 226

bool PNS_OPTIMIZER::checkColliding( PNS_ITEM* aItem, bool aUpdateCache )
227
{
228
    CACHE_VISITOR v( aItem, m_world, m_collisionKindMask );
229 230 231 232

    return m_world->CheckColliding( aItem );

    // something is wrong with the cache, need to investigate.
233
    m_cache.Query( aItem->Shape(), m_world->GetMaxClearance(), v, false );
234 235 236

    if( !v.m_collidingItem )
    {
237
        PNS_NODE::OPT_OBSTACLE obs = m_world->CheckColliding( aItem );
238 239 240 241

        if( obs )
        {
            if( aUpdateCache )
242
                cacheAdd( obs->m_item );
243 244 245 246 247 248

            return true;
        }
    }
    else
    {
249
        m_cacheTags[v.m_collidingItem].m_hits++;
250 251 252 253
        return true;
    }

    return false;
254 255
}

256 257

bool PNS_OPTIMIZER::checkColliding( PNS_LINE* aLine, const SHAPE_LINE_CHAIN& aOptPath )
258
{
259 260 261
    PNS_LINE tmp( *aLine, aOptPath );

    return checkColliding( &tmp );
262 263
}

264 265

bool PNS_OPTIMIZER::mergeObtuse( PNS_LINE* aLine )
266
{
267
    SHAPE_LINE_CHAIN& line = aLine->Line();
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297

    int step = line.PointCount() - 3;
    int iter = 0;
    int segs_pre = line.SegmentCount();

    if( step < 0 )
        return false;

    SHAPE_LINE_CHAIN current_path( line );

    while( 1 )
    {
        iter++;
        int n_segs = current_path.SegmentCount();
        int max_step = n_segs - 2;

        if( step > max_step )
            step = max_step;

        if( step < 2 )
        {
            line = current_path;
            return current_path.SegmentCount() < segs_pre;
        }

        bool found_anything = false;
        int n = 0;

        while( n < n_segs - step )
        {
298 299
            const SEG s1 = current_path.CSegment( n );
            const SEG s2 = current_path.CSegment( n + step );
300 301 302 303 304 305 306 307
            SEG s1opt, s2opt;

            if( DIRECTION_45( s1 ).IsObtuse( DIRECTION_45( s2 ) ) )
            {
                VECTOR2I ip = *s1.IntersectLines( s2 );

                if( s1.Distance( ip ) <= 1 || s2.Distance( ip ) <= 1 )
                {
Maciej Suminski's avatar
Maciej Suminski committed
308 309
                    s1opt = SEG( s1.A, ip );
                    s2opt = SEG( ip, s2.B );
310 311 312
                }
                else
                {
Maciej Suminski's avatar
Maciej Suminski committed
313 314
                    s1opt = SEG( s1.A, ip );
                    s2opt = SEG( ip, s2.B );
315 316 317 318 319 320
                }


                if( DIRECTION_45( s1opt ).IsObtuse( DIRECTION_45( s2opt ) ) )
                {
                    SHAPE_LINE_CHAIN opt_path;
Maciej Suminski's avatar
Maciej Suminski committed
321 322 323
                    opt_path.Append( s1opt.A );
                    opt_path.Append( s1opt.B );
                    opt_path.Append( s2opt.B );
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353

                    PNS_LINE opt_track( *aLine, opt_path );

                    if( !checkColliding( &opt_track ) )
                    {
                        current_path.Replace( s1.Index() + 1, s2.Index(), ip );
                        // removeCachedSegments(aLine, s1.Index(), s2.Index());
                        n_segs = current_path.SegmentCount();
                        found_anything = true;
                        break;
                    }
                }
            }

            n++;
        }

        if( !found_anything )
        {
            if( step <= 2 )
            {
                line = current_path;
                return line.SegmentCount() < segs_pre;
            }

            step--;
        }
    }

    return line.SegmentCount() < segs_pre;
354 355 356
}


357
bool PNS_OPTIMIZER::mergeFull( PNS_LINE* aLine )
358
{
359
    SHAPE_LINE_CHAIN& line = aLine->Line();
360
    int step = line.SegmentCount() - 1;
361

362
    int segs_pre = line.SegmentCount();
363

364
    line.Simplify();
365

366 367
    if( step < 0 )
        return false;
368

369
    SHAPE_LINE_CHAIN current_path( line );
370

371 372 373 374
    while( 1 )
    {
        int n_segs = current_path.SegmentCount();
        int max_step = n_segs - 2;
375

376 377
        if( step > max_step )
            step = max_step;
378

379 380
        if( step < 1 )
            break;
381

382
        bool found_anything = mergeStep( aLine, current_path, step );
383

384 385 386 387 388 389 390
        if( !found_anything )
            step--;
    }

    aLine->SetShape( current_path );

    return current_path.SegmentCount() < segs_pre;
391 392
}

393

394
bool PNS_OPTIMIZER::Optimize( PNS_LINE* aLine, PNS_LINE* aResult )//, int aStartVertex, int aEndVertex )
395
{
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
    if( !aResult )
        aResult = aLine;
    else
        *aResult = *aLine;

    m_keepPostures = false;

    bool rv = false;

    if( m_effortLevel & MERGE_SEGMENTS )
        rv |= mergeFull( aResult );

    if( m_effortLevel & MERGE_OBTUSE )
        rv |= mergeObtuse( aResult );

    if( m_effortLevel & SMART_PADS )
        rv |= runSmartPads( aResult );

414 415 416
    if( m_effortLevel & FANOUT_CLEANUP )
        rv |= fanoutCleanup( aResult );

417
    return rv;
418 419 420
}


421
bool PNS_OPTIMIZER::mergeStep( PNS_LINE* aLine, SHAPE_LINE_CHAIN& aCurrentPath, int step )
422
{
423 424 425 426 427
    int n = 0;
    int n_segs = aCurrentPath.SegmentCount();

    int cost_orig = PNS_COST_ESTIMATOR::CornerCost( aCurrentPath );

428
    if( aLine->SegmentCount() < 4 )
429 430
        return false;

431 432
    DIRECTION_45 orig_start( aLine->CSegment( 0 ) );
    DIRECTION_45 orig_end( aLine->CSegment( -1 ) );
433 434 435 436 437 438

    while( n < n_segs - step )
    {
        const SEG s1    = aCurrentPath.CSegment( n );
        const SEG s2    = aCurrentPath.CSegment( n + step );

439 440
        SHAPE_LINE_CHAIN path[2];
        SHAPE_LINE_CHAIN* picked = NULL;
441 442 443 444 445
        int cost[2];

        for( int i = 0; i < 2; i++ )
        {
            bool postureMatch = true;
Maciej Suminski's avatar
Maciej Suminski committed
446
            SHAPE_LINE_CHAIN bypass = DIRECTION_45().BuildInitialTrace( s1.A, s2.B, i );
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
            cost[i] = INT_MAX;


            if( n == 0 && orig_start != DIRECTION_45( bypass.CSegment( 0 ) ) )
                postureMatch = false;
            else if( n == n_segs - step && orig_end != DIRECTION_45( bypass.CSegment( -1 ) ) )
                postureMatch = false;

            if( (postureMatch || !m_keepPostures) && !checkColliding( aLine, bypass ) )
            {
                path[i] = aCurrentPath;
                path[i].Replace( s1.Index(), s2.Index(), bypass );
                path[i].Simplify();
                cost[i] = PNS_COST_ESTIMATOR::CornerCost( path[i] );
            }
        }

        if( cost[0] < cost_orig && cost[0] < cost[1] )
            picked = &path[0];
        else if( cost[1] < cost_orig )
            picked = &path[1];

        if( picked )
        {
            n_segs = aCurrentPath.SegmentCount();
            aCurrentPath = *picked;
            return true;
        }

        n++;
    }

    return false;
480 481
}

482

483
PNS_OPTIMIZER::BREAKOUT_LIST PNS_OPTIMIZER::circleBreakouts( int aWidth,
484
        const SHAPE* aShape, bool aPermitDiagonal ) const
485
{
486
    BREAKOUT_LIST breakouts;
487 488 489 490 491 492 493 494 495 496 497 498 499

    for( int angle = 0; angle < 360; angle += 45 )
    {
        const SHAPE_CIRCLE* cir = static_cast<const SHAPE_CIRCLE*>( aShape );
        SHAPE_LINE_CHAIN l;
        VECTOR2I p0 = cir->GetCenter();
        VECTOR2I v0( cir->GetRadius() * M_SQRT2, 0 );
        l.Append( p0 );
        l.Append( p0 + v0.Rotate( angle * M_PI / 180.0 ) );
        breakouts.push_back( l );
    }

    return breakouts;
500 501 502
}


503
PNS_OPTIMIZER::BREAKOUT_LIST PNS_OPTIMIZER::rectBreakouts( int aWidth,
504
        const SHAPE* aShape, bool aPermitDiagonal ) const
505
{
506 507
    const SHAPE_RECT* rect = static_cast<const SHAPE_RECT*>(aShape);
    VECTOR2I s = rect->GetSize(), c = rect->GetPosition() + VECTOR2I( s.x / 2, s.y / 2 );
508
    BREAKOUT_LIST breakouts;
509 510 511

    VECTOR2I d_offset;

512 513
    d_offset.x = ( s.x > s.y ) ? ( s.x - s.y ) / 2 : 0;
    d_offset.y = ( s.x < s.y ) ? ( s.y - s.x ) / 2 : 0;
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529

    VECTOR2I d_vert  = VECTOR2I( 0, s.y / 2 + aWidth );
    VECTOR2I d_horiz = VECTOR2I( s.x / 2 + aWidth, 0 );

    breakouts.push_back( SHAPE_LINE_CHAIN( c, c + d_horiz ) );
    breakouts.push_back( SHAPE_LINE_CHAIN( c, c - d_horiz ) );
    breakouts.push_back( SHAPE_LINE_CHAIN( c, c + d_vert ) );
    breakouts.push_back( SHAPE_LINE_CHAIN( c, c - d_vert ) );

    if( aPermitDiagonal )
    {
        int l = aWidth + std::min( s.x, s.y ) / 2;
        VECTOR2I d_diag;

        if( s.x >= s.y )
        {
530
            breakouts.push_back( SHAPE_LINE_CHAIN( c, c + d_offset,
531
                                                   c + d_offset + VECTOR2I( l, l ) ) );
532
            breakouts.push_back( SHAPE_LINE_CHAIN( c, c + d_offset,
533
                                                   c + d_offset - VECTOR2I( -l, l ) ) );
534
            breakouts.push_back( SHAPE_LINE_CHAIN( c, c - d_offset,
535
                                                   c - d_offset + VECTOR2I( -l, l ) ) );
536
            breakouts.push_back( SHAPE_LINE_CHAIN( c, c - d_offset,
537 538 539 540 541
                                                   c - d_offset - VECTOR2I( l, l ) ) );
        }
        else
        {
            // fixme: this could be done more efficiently
542
            breakouts.push_back( SHAPE_LINE_CHAIN( c, c + d_offset,
543 544 545 546 547 548 549 550 551 552 553
                                                   c + d_offset + VECTOR2I( l, l ) ) );
            breakouts.push_back( SHAPE_LINE_CHAIN( c, c - d_offset,
                                                   c - d_offset - VECTOR2I( -l, l ) ) );
            breakouts.push_back( SHAPE_LINE_CHAIN( c, c + d_offset,
                                                   c + d_offset + VECTOR2I( -l, l ) ) );
            breakouts.push_back( SHAPE_LINE_CHAIN( c, c - d_offset,
                                                   c - d_offset - VECTOR2I( l, l ) ) );
        }
    }

    return breakouts;
554 555
}

556

557
PNS_OPTIMIZER::BREAKOUT_LIST PNS_OPTIMIZER::computeBreakouts( int aWidth,
558
        const PNS_ITEM* aItem, bool aPermitDiagonal ) const
559
{
560
    switch( aItem->Kind() )
561 562
    {
    case PNS_ITEM::VIA:
563 564 565 566
    {
        const PNS_VIA* via = static_cast<const PNS_VIA*>( aItem );
        return circleBreakouts( aWidth, via->Shape(), aPermitDiagonal );
    }
567 568

    case PNS_ITEM::SOLID:
569 570
    {
        const SHAPE* shape = aItem->Shape();
571

572 573 574 575
        switch( shape->Type() )
        {
        case SH_RECT:
            return rectBreakouts( aWidth, shape, aPermitDiagonal );
576

577 578 579 580 581 582
        case SH_SEGMENT:
        {
            const SHAPE_SEGMENT* seg = static_cast<const SHAPE_SEGMENT*> (shape);
            const SHAPE_RECT rect = ApproximateSegmentAsRect ( *seg );
            return rectBreakouts( aWidth, &rect, aPermitDiagonal );
        }
583

584 585
        case SH_CIRCLE:
            return circleBreakouts( aWidth, shape, aPermitDiagonal );
586

587 588
        default:
            break;
589
        }
590
    }
591 592 593 594 595

    default:
        break;
    }

596
    return BREAKOUT_LIST();
597 598
}

599 600

PNS_ITEM* PNS_OPTIMIZER::findPadOrVia( int aLayer, int aNet, const VECTOR2I& aP ) const
601
{
602
    PNS_JOINT* jt = m_world->FindJoint( aP, aLayer, aNet );
603 604 605 606

    if( !jt )
        return NULL;

607
    BOOST_FOREACH( PNS_ITEM* item, jt->LinkList() )
608
    {
609
        if( item->OfKind( PNS_ITEM::VIA | PNS_ITEM::SOLID ) )
610 611 612 613
            return item;
    }

    return NULL;
614 615
}

616 617

int PNS_OPTIMIZER::smartPadsSingle( PNS_LINE* aLine, PNS_ITEM* aPad, bool aEnd, int aEndVertex )
618
{
619 620 621 622 623 624 625
    int min_cost = INT_MAX; // PNS_COST_ESTIMATOR::CornerCost( line );
    int min_len = INT_MAX;
    DIRECTION_45 dir;

    const int ForbiddenAngles = DIRECTION_45::ANG_ACUTE | DIRECTION_45::ANG_RIGHT |
                                DIRECTION_45::ANG_HALF_FULL | DIRECTION_45::ANG_UNDEFINED;

626 627
    typedef std::pair<int, SHAPE_LINE_CHAIN> RtVariant;
    std::vector<RtVariant> variants;
628

629
    BREAKOUT_LIST breakouts = computeBreakouts( aLine->Width(), aPad, true );
630

631
    SHAPE_LINE_CHAIN line = ( aEnd ? aLine->CLine().Reverse() : aLine->CLine() );
632 633


634
    int p_end = std::min( aEndVertex, std::min( 3, line.PointCount() - 1 ) );
635 636 637 638 639 640 641 642

    for( int p = 1; p <= p_end; p++ )
    {
        BOOST_FOREACH( SHAPE_LINE_CHAIN & l, breakouts ) {

            for( int diag = 0; diag < 2; diag++ )
            {
                SHAPE_LINE_CHAIN v;
643
                SHAPE_LINE_CHAIN connect = dir.BuildInitialTrace( l.CPoint( -1 ),
644
                                                                  line.CPoint( p ), diag == 0 );
645 646 647

                DIRECTION_45 dir_bkout( l.CSegment( -1 ) );

648 649 650
                if(!connect.SegmentCount())
                    continue;
                
651 652 653 654 655
                int ang1 = dir_bkout.Angle( DIRECTION_45( connect.CSegment( 0 ) ) );
                int ang2 = 0;

                if( (ang1 | ang2) & ForbiddenAngles )
                    continue;
656

657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
                if( l.Length() > line.Length() )
                    continue;

                v = l;

                v.Append( connect );

                for( int i = p + 1; i < line.PointCount(); i++ )
                    v.Append( line.CPoint( i ) );

                PNS_LINE tmp( *aLine, v );
                int cc = tmp.CountCorners( ForbiddenAngles );

                if( cc == 0 )
                {
                    RtVariant vp;
                    vp.first = p;
                    vp.second = aEnd ? v.Reverse() : v;
                    vp.second.Simplify();
                    variants.push_back( vp );
                }
            }
        }
    }

    SHAPE_LINE_CHAIN l_best;
683 684
    bool found = false;
    int p_best = -1;
685

686
    BOOST_FOREACH( RtVariant& vp, variants )
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
    {
        PNS_LINE tmp( *aLine, vp.second );
        int cost = PNS_COST_ESTIMATOR::CornerCost( vp.second );
        int len = vp.second.Length();

        if( !checkColliding( &tmp ) )
        {
            if( cost < min_cost || ( cost == min_cost && len < min_len ) )
            {
                l_best = vp.second;
                p_best = vp.first;
                found  = true;

                if( cost == min_cost )
                    min_len = std::min( len, min_len );

                min_cost = std::min( cost, min_cost );
            }
        }
    }

    if( found )
    {
        aLine->SetShape( l_best );
        return p_best;
    }

    return -1;
715 716
}

717
bool PNS_OPTIMIZER::runSmartPads( PNS_LINE* aLine )
718
{
719 720
    SHAPE_LINE_CHAIN& line = aLine->Line();
    
721 722
    if( line.PointCount() < 3 )
        return false;
723

724
    VECTOR2I p_start = line.CPoint( 0 ), p_end = line.CPoint( -1 );
725

726 727
    PNS_ITEM* startPad = findPadOrVia( aLine->Layer(), aLine->Net(), p_start );
    PNS_ITEM* endPad = findPadOrVia( aLine->Layer(), aLine->Net(), p_end );
728

729
    int vtx = -1;
730

731 732
    if( startPad )
        vtx = smartPadsSingle( aLine, startPad, false, 3 );
733

734 735
    if( endPad )
        smartPadsSingle( aLine, endPad, true,
736
                         vtx < 0 ? line.PointCount() - 1 : line.PointCount() - 1 - vtx );
737

738
    aLine->Line().Simplify();
739

740
    return true;
741 742
}

743 744

bool PNS_OPTIMIZER::Optimize( PNS_LINE* aLine, int aEffortLevel, PNS_NODE* aWorld )
745
{
746
    PNS_OPTIMIZER opt( aWorld );
747 748 749 750

    opt.SetEffortLevel( aEffortLevel );
    opt.SetCollisionMask( -1 );
    return opt.Optimize( aLine );
751
}
752 753


754
bool PNS_OPTIMIZER::fanoutCleanup( PNS_LINE* aLine )
755 756 757 758 759 760 761 762 763 764 765 766
{
    if( aLine->PointCount() < 3 )
        return false;

    VECTOR2I p_start = aLine->CPoint( 0 ), p_end = aLine->CPoint( -1 );

    PNS_ITEM* startPad = findPadOrVia( aLine->Layer(), aLine->Net(), p_start );
    PNS_ITEM* endPad = findPadOrVia( aLine->Layer(), aLine->Net(), p_end );

    int thr = aLine->Width() * 10; 
    int len = aLine->CLine().Length();

767
    if( !startPad )
768 769
        return false;

770
    bool startMatch = startPad->OfKind( PNS_ITEM::VIA | PNS_ITEM::SOLID );
771 772 773 774
    bool endMatch = false;   

    if(endPad)
    {
775
        endMatch = endPad->OfKind( PNS_ITEM::VIA | PNS_ITEM::SOLID );
776 777 778 779
    } else {
        endMatch = aLine->EndsWithVia();
    }
    
780
    if( startMatch && endMatch && len < thr )
781 782 783
    {
        for(int i = 0; i < 2; i++ )
        {
784 785
            SHAPE_LINE_CHAIN l2 = DIRECTION_45().BuildInitialTrace( p_start, p_end, i );
            PNS_ROUTER::GetInstance()->DisplayDebugLine( l2, 4, 10000 );
786
            PNS_LINE repl;
787
            repl = PNS_LINE( *aLine, l2 );
788

789
            if( !m_world->CheckColliding( &repl ) )
790
            {
791
                aLine->SetShape( repl.CLine() );
792 793 794 795
                return true;
            }
        }
    }
796

797 798
    return false;
}