KiCad PCB EDA Suite
Loading...
Searching...
No Matches
pns_tool_base.cpp
Go to the documentation of this file.
1/*
2 * KiRouter - a push-and-(sometimes-)shove PCB router
3 *
4 * Copyright (C) 2013 CERN
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 * Author: Tomasz Wlostowski <[email protected]>
7 *
8 * This program is free software: you can redistribute it and/or modify it
9 * under the terms of the GNU General Public License as published by the
10 * Free Software Foundation, either version 3 of the License, or (at your
11 * option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful, but
14 * WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22
23#include <functional>
24using namespace std::placeholders;
25
28#include <pcb_painter.h>
29#include <pcbnew_settings.h>
30#include <view/view_controls.h>
31
32#include <tool/tool_manager.h>
34#include <wx/log.h>
35
36#include "pns_kicad_iface.h"
37#include "pns_tool_base.h"
38#include "pns_arc.h"
39#include "pns_solid.h"
40#include "pns_dragger.h"
41
42const unsigned int PNS::TOOL_BASE::COORDS_PADDING = pcbIUScale.mmToIU( 20 );
43
44using namespace KIGFX;
45
46namespace PNS {
47
48
49TOOL_BASE::TOOL_BASE( const std::string& aToolName ) :
50 PCB_TOOL_BASE( aToolName )
51{
52 m_gridHelper = nullptr;
53 m_iface = nullptr;
54 m_router = nullptr;
55 m_cancelled = false;
56
57 m_startItem = nullptr;
58
59 m_endItem = nullptr;
60 m_gridHelper = nullptr;
61
62 m_cancelled = false;
64}
65
66
68{
69 delete m_gridHelper;
70 delete m_router;
71 delete m_iface; // Delete after m_router because PNS::NODE dtor needs m_ruleResolver
72}
73
74
76{
77 delete m_gridHelper;
78 delete m_router;
79 delete m_iface; // Delete after m_router because PNS::NODE dtor needs m_ruleResolver
80
81 if( aReason == RESET_REASON::SHUTDOWN )
82 {
83 m_gridHelper = nullptr;
84 m_router = nullptr;
85 m_iface = nullptr;
86 return;
87 }
88
90 m_iface->SetBoard( board() );
91 m_iface->SetView( getView() );
92 m_iface->SetHostTool( this );
93
94 m_router = new ROUTER;
95 m_router->SetInterface( m_iface );
96 m_router->ClearWorld();
97 m_router->SyncWorld();
98
99 m_router->UpdateSizes( m_savedSizes );
100
101 PCBNEW_SETTINGS* settings = frame()->GetPcbNewSettings();
102
103 if( !settings->m_PnsSettings )
104 settings->m_PnsSettings = std::make_unique<ROUTING_SETTINGS>( settings, "tools.pns" );
105
106 m_router->LoadSettings( settings->m_PnsSettings.get() );
107
108 m_gridHelper = new PCB_GRID_HELPER( m_toolMgr, frame()->GetMagneticItemsSettings() );
109}
110
111
113{
114 m_selectableItemMask = aMask;
115}
116
117
118ITEM* TOOL_BASE::pickSingleItem( const VECTOR2I& aWhere, NET_HANDLE aNet, int aLayer,
119 bool aIgnorePads, const std::vector<ITEM*> aAvoidItems, int aPermittedItemMask )
120{
121 int tl = aLayer > 0 ? aLayer
122 : m_router->GetInterface()->GetPNSLayerFromBoardLayer(
123 static_cast<PCB_LAYER_ID>( getView()->GetTopLayer() ) );
124 int maxSlopRadius = std::max( m_gridHelper->GetGrid().x, m_gridHelper->GetGrid().y );
125
126 static const int candidateCount = 5;
127 ITEM* prioritized[candidateCount];
128 SEG::ecoord dist[candidateCount];
129
130 for( int i = 0; i < candidateCount; i++ )
131 {
132 prioritized[i] = nullptr;
133 dist[i] = VECTOR2I::ECOORD_MAX;
134 }
135
136 auto haveCandidates =
137 [&]()
138 {
139 for( ITEM* item : prioritized )
140 {
141 if( item )
142 return true;
143 }
144
145 return false;
146 };
147
148 for( int slopRadius : { 0, maxSlopRadius } )
149 {
150 ITEM_SET candidates = m_router->QueryHoverItems( aWhere, slopRadius );
151
152 for( ITEM* item : candidates.Items() )
153 {
154 if( (item->Kind() & aPermittedItemMask ) == 0 )
155 continue;
156
157 if( !item->IsRoutable() )
158 continue;
159
160 if( !m_iface->IsPNSCopperLayer( item->Layers().Start() ) )
161 continue;
162
163 if( !m_iface->IsAnyLayerVisible( item->Layers() ) )
164 continue;
165
166 if( alg::contains( aAvoidItems, item ) )
167 continue;
168
169 // fixme: this causes flicker with live loop removal...
170 //if( item->Parent() && !item->Parent()->ViewIsVisible() )
171 // continue;
172
173 if( item->OfKind( ITEM::SOLID_T ) && aIgnorePads )
174 {
175 continue;
176 }
177 else if( m_router->Mode() == PNS::PNS_MODE_ROUTE_DIFF_PAIR || m_router->GetInterface()->GetNetCode( aNet) <= 0 || item->Net() == aNet )
178 {
179 if( item->OfKind( ITEM::VIA_T | ITEM::SOLID_T ) )
180 {
181 SEG::ecoord d = ( item->Shape( aLayer )->Centre() - aWhere ).SquaredEuclideanNorm();
182
183 if( d < dist[2] )
184 {
185 prioritized[2] = item;
186 dist[2] = d;
187 }
188
189 if( item->Layers().Overlaps( tl ) && d < dist[0] )
190 {
191 prioritized[0] = item;
192 dist[0] = d;
193 }
194 }
195 else // ITEM::SEGMENT_T | ITEM::ARC_T
196 {
197 LINKED_ITEM* li = static_cast<LINKED_ITEM*>( item );
198 SEG::ecoord d = std::min( ( li->Anchor( 0 ) - aWhere ).SquaredEuclideanNorm(),
199 ( li->Anchor( 1 ) - aWhere ).SquaredEuclideanNorm() );
200
201 if( d < dist[3] )
202 {
203 prioritized[3] = item;
204 dist[3] = d;
205 }
206
207 if( item->Layers().Overlaps( tl ) && d < dist[1] )
208 {
209 prioritized[1] = item;
210 dist[1] = d;
211 }
212 }
213 }
214 else if( item->OfKind( ITEM::SOLID_T ) && item->IsFreePad() )
215 {
216 // Allow free pads only when already inside pad
217 if( item->Shape( -1 )->Collide( aWhere ) )
218 {
219 prioritized[0] = item;
220 dist[0] = 0;
221 }
222 }
223 else if ( item->Net() == 0 && m_router->Settings().Mode() == RM_MarkObstacles )
224 {
225 // Allow unconnected items as last resort in RM_MarkObstacles mode
226 if( item->Layers().Overlaps( tl ) )
227 prioritized[4] = item;
228 }
229 }
230
231 if( haveCandidates() )
232 break;
233 }
234
235 ITEM* rv = nullptr;
236
237 bool highContrast = ( frame()->GetDisplayOptions().m_ContrastModeDisplay != HIGH_CONTRAST_MODE::NORMAL );
238
239 for( ITEM* item : prioritized )
240 {
241 if( highContrast && item && !item->Layers().Overlaps( tl ) )
242 item = nullptr;
243
244 if( item && ( aLayer < 0 || item->Layers().Overlaps( aLayer ) ) )
245 {
246 rv = item;
247 break;
248 }
249 }
250
251 if( rv )
252 {
253 wxLogTrace( wxT( "PNS" ), wxT( "%s, layer : %d, tl: %d" ),
254 rv->KindStr().c_str(),
255 rv->Layers().Start(),
256 tl );
257 }
258
259 return rv;
260}
261
262
263void TOOL_BASE::highlightNets( bool aEnabled, std::set<NET_HANDLE> aNets )
264{
266 std::set<int> netcodes;
267
268 for( const NET_HANDLE& net : aNets )
269 netcodes.insert( m_router->GetInterface()->GetNetCode( net ) );
270
271 if( netcodes.size() > 0 && aEnabled )
272 {
273 // If the user has previously set some of the routed nets to be highlighted,
274 // we assume they want to keep them highlighted after routing
275
276 const std::set<int>& currentNetCodes = rs->GetHighlightNetCodes();
277 bool keep = false;
278
279 for( const int& netcode : netcodes )
280 {
281 if( currentNetCodes.find( netcode ) != currentNetCodes.end() )
282 {
283 keep = true;
284 break;
285 }
286 }
287
288 if( rs->IsHighlightEnabled() && keep )
289 m_startHighlightNetcodes = currentNetCodes;
290 else
292
293 rs->SetHighlight( netcodes, true );
294 }
295 else
296 {
298 }
299
300 // Do not remove this call. This is required to update the layers when we highlight a net.
301 // In this case, highlighting a net dims all other elements, so the colors need to update
303}
304
305
307{
308 // Sync PNS engine settings with the general PCB editor options.
309 ROUTING_SETTINGS& pnss = m_router->Settings();
310
311 // Don't snap to items that move with the drag, or the cursor sticks to their old position
312 if( m_startItem && aItem && m_router->GetState() == ROUTER::DRAG_SEGMENT
313 && m_router->GetDragger() )
314 {
315 DRAGGER* dragger = dynamic_cast<DRAGGER*>( m_router->GetDragger() );
316
317 if( dragger && dragger->IsDragOrigin( aItem ) )
318 return false;
319 }
320
321 MAGNETIC_SETTINGS* magSettings = frame()->GetMagneticItemsSettings();
322
324 || magSettings->pads == MAGNETIC_OPTIONS::CAPTURE_ALWAYS );
325
327 || magSettings->tracks == MAGNETIC_OPTIONS::CAPTURE_ALWAYS );
328
329 if( aItem )
330 {
332 return pnss.GetSnapToTracks();
333 else if( aItem->OfKind( ITEM::SOLID_T ) )
334 return pnss.GetSnapToPads();
335 }
336
337 return false;
338}
339
340
341void TOOL_BASE::updateStartItem( const TOOL_EVENT& aEvent, bool aIgnorePads )
342{
343 int tl = m_router->GetInterface()->GetPNSLayerFromBoardLayer( ToLAYER_ID( getView()->GetTopLayer() ) );
344 GAL* gal = m_toolMgr->GetView()->GetGAL();
345 VECTOR2I pos = aEvent.HasPosition() ? (VECTOR2I) aEvent.Position() : m_startSnapPoint;
346
347 pos = GetClampedCoords( pos, COORDS_PADDING );
348
349 if( aEvent.Modifier( MD_CTRL ) && aEvent.Modifier( MD_SHIFT ) )
350 {
351 m_startItem = nullptr;
354 return;
355 }
356
357 // Snapping uses ViewGetLOD(), which use the layerVisibilityCache. Make sure the cache is up-to-date.
358 m_toolMgr->GetView()->SyncLayerVisibilityCache();
359
360 controls()->ForceCursorPosition( false );
361 m_gridHelper->SetUseGrid( gal->GetGridSnapping() && !aEvent.DisableGridSnapping() );
362 m_gridHelper->SetSnap( !aEvent.Modifier( MD_SHIFT ) );
363
364 m_startItem = pickSingleItem( pos, nullptr, -1, aIgnorePads, {}, m_selectableItemMask );
365
366 if( !m_gridHelper->GetUseGrid() && m_startItem && !m_startItem->Layers().Overlaps( tl ) )
367 m_startItem = nullptr;
368
371}
372
373
375{
376 int layer;
377 GAL* gal = m_toolMgr->GetView()->GetGAL();
378
379 // Snapping uses ViewGetLOD(), which use the layerVisibilityCache. Make sure the cache is up-to-date.
380 m_toolMgr->GetView()->SyncLayerVisibilityCache();
381
382 m_gridHelper->SetUseGrid( gal->GetGridSnapping() && !aEvent.DisableGridSnapping() );
383 m_gridHelper->SetSnap( !aEvent.Modifier( MD_SHIFT ) );
384
385 controls()->ForceCursorPosition( false );
386
387 VECTOR2I mousePos = GetClampedCoords( controls()->GetMousePosition(), COORDS_PADDING );
388
389 if( m_router->GetState() == ROUTER::ROUTE_TRACK && aEvent.IsDrag() )
390 {
391 // If the user is moving the mouse quickly while routing then clicks will come in as
392 // short drags. In this case we want to use the drag origin rather than the current
393 // mouse position.
394 mousePos = aEvent.DragOrigin();
395 }
396
397 if( m_router->Settings().Mode() != RM_MarkObstacles &&
398 ( m_router->GetCurrentNets().empty() || m_router->GetCurrentNets().front() == nullptr ) )
399 {
400 m_endSnapPoint = snapToItem( nullptr, mousePos );
402 m_endItem = nullptr;
403
404 return;
405 }
406
407 if( m_router->IsPlacingVia() )
408 layer = -1;
409 else
410 layer = m_router->GetCurrentLayer();
411
412 ITEM* endItem = nullptr;
413
414 std::vector<NET_HANDLE> nets = m_router->GetCurrentNets();
415
416 for( NET_HANDLE net : nets )
417 {
418
419 endItem = pickSingleItem( mousePos, net, layer, false, {}, m_selectableItemMask ); //{ m_startItem } );
420
421 if( endItem )
422 break;
423 }
424
425 if( m_gridHelper->GetSnap() && checkSnap( endItem ) )
426 {
427 m_endItem = endItem;
428 m_endSnapPoint = snapToItem( endItem, mousePos );
429 }
430 else
431 {
432 m_endItem = nullptr;
433 m_endSnapPoint = m_gridHelper->Align( mousePos, m_router->IsPlacingVia() ? GRID_VIAS
434 : GRID_WIRES );
435 }
436
438
439 if( m_endItem )
440 {
441 wxLogTrace( wxT( "PNS" ), wxT( "%s, layer : %d" ),
442 m_endItem->KindStr().c_str(),
443 m_endItem->Layers().Start() );
444 }
445}
446
447
449{
450 return m_router;
451}
452
453
455{
456 return m_iface;
457}
458
459
460const VECTOR2I TOOL_BASE::snapToItem( ITEM* aItem, const VECTOR2I& aP )
461{
462 if( !aItem || !m_iface->IsItemVisible( aItem ) )
463 {
464 return m_gridHelper->Align( aP, m_router->IsPlacingVia() ? GRID_VIAS : GRID_WIRES );
465 }
466
467 switch( aItem->Kind() )
468 {
469 case ITEM::SOLID_T:
470 {
471 SOLID* solid = static_cast<SOLID*>( aItem );
472
473 if( solid->AnchorPoints().empty() )
474 return solid->Anchor( 0 );
475
477 SEG::ecoord minDist = std::numeric_limits<SEG::ecoord>::max();
478
479 for( VECTOR2I anchorCandidate : solid->AnchorPoints() )
480 {
481 SEG::ecoord distSq = ( aP - anchorCandidate ).SquaredEuclideanNorm();
482
483 if( distSq < minDist )
484 {
485 minDist = distSq;
486 anchor = anchorCandidate;
487 }
488 }
489
490 return anchor;
491 }
492
493 case ITEM::VIA_T:
494 return static_cast<VIA*>( aItem )->Pos();
495
496 case ITEM::SEGMENT_T:
497 case ITEM::ARC_T:
498 {
499 LINKED_ITEM* li = static_cast<LINKED_ITEM*>( aItem );
500 VECTOR2I A = li->Anchor( 0 );
501 VECTOR2I B = li->Anchor( 1 );
502 SEG::ecoord w_sq = SEG::Square( li->Width() / 2 );
503 SEG::ecoord distA_sq = ( aP - A ).SquaredEuclideanNorm();
504 SEG::ecoord distB_sq = ( aP - B ).SquaredEuclideanNorm();
505
506 if( distA_sq < w_sq || distB_sq < w_sq )
507 {
508 return ( distA_sq < distB_sq ) ? A : B;
509 }
510 else if( aItem->Kind() == ITEM::SEGMENT_T )
511 {
512 // TODO(snh): Clean this up
513 SEGMENT* seg = static_cast<SEGMENT*>( li );
514 return m_gridHelper->AlignToSegment( aP, seg->Seg() );
515 }
516 else if( aItem->Kind() == ITEM::ARC_T )
517 {
518 ARC* arc = static_cast<ARC*>( li );
519 return m_gridHelper->AlignToArc( aP, *static_cast<const SHAPE_ARC*>( arc->Shape( -1 ) ) );
520 }
521
522 break;
523 }
524
525 default:
526 break;
527 }
528
529 return m_gridHelper->Align( aP, m_router->IsPlacingVia() ? GRID_VIAS : GRID_WIRES );
530}
531
532}
constexpr EDA_IU_SCALE pcbIUScale
Definition base_units.h:128
@ NORMAL
Inactive layers are shown normally (no high-contrast mode)
Abstract interface for drawing on a 2D-surface.
virtual RENDER_SETTINGS * GetSettings()=0
Return a pointer to current settings that are going to be used when drawing items.
Container for all the knowledge about how graphical objects are drawn on any output surface/device.
const std::set< int > & GetHighlightNetCodes() const
Return the netcode of currently highlighted net.
bool IsHighlightEnabled() const
Return current highlight setting.
void SetHighlight(bool aEnabled, int aNetcode=-1, bool aMulti=false)
Turns on/off highlighting.
virtual void ForceCursorPosition(bool aEnabled, const VECTOR2D &aPosition=VECTOR2D(0, 0))
Place the cursor immediately at a given point.
virtual VECTOR2D GetMousePosition(bool aWorldCoordinates=true) const =0
Return the current mouse pointer position.
void UpdateAllLayersColor()
Apply the new coloring scheme to all layers.
Definition view.cpp:1171
PAINTER * GetPainter() const
Return the painter object used by the view for drawing VIEW_ITEM objects.
Definition view.h:242
std::unique_ptr< PNS::ROUTING_SETTINGS > m_PnsSettings
T * frame() const
KIGFX::VIEW_CONTROLS * controls() const
PCB_TOOL_BASE(TOOL_ID aId, const std::string &aName)
Constructor.
BOARD * board() const
const SHAPE * Shape(int aLayer) const override
Return the geometrical shape of the item.
Definition pns_arc.h:80
DRAGGER.
Definition pns_dragger.h:48
bool IsDragOrigin(const ITEM *aItem) const
Return true if aItem is a world item that moves with the drag: a link of the original line,...
Base class for PNS router board items.
Definition pns_item.h:98
const PNS_LAYER_RANGE & Layers() const
Definition pns_item.h:212
PnsKind Kind() const
Return the type (kind) of the item.
Definition pns_item.h:173
bool OfKind(int aKindMask) const
Definition pns_item.h:181
virtual VECTOR2I Anchor(int n) const
Definition pns_item.h:272
std::string KindStr() const
Definition pns_item.cpp:318
virtual int Width() const
Contain all persistent settings of the router, such as the mode, optimization effort,...
void SetSnapToTracks(bool aSnap)
const SEG & Seg() const
const std::vector< VECTOR2I > & AnchorPoints() const
Definition pns_solid.h:132
virtual VECTOR2I Anchor(int aN) const override
Definition pns_solid.cpp:95
bool checkSnap(ITEM *aItem)
virtual void updateStartItem(const TOOL_EVENT &aEvent, bool aIgnorePads=false)
ROUTER * Router() const
virtual void setSelectableItemMask(int aMask)
PNS_KICAD_IFACE * GetInterface() const
std::set< int > m_startHighlightNetcodes
const VECTOR2I snapToItem(ITEM *aSnapToItem, const VECTOR2I &aP)
virtual void Reset(RESET_REASON aReason) override
Bring the tool to a known, initial state.
virtual void highlightNets(bool aEnabled, std::set< NET_HANDLE > aNetcodes={})
virtual ~TOOL_BASE()
SIZES_SETTINGS m_savedSizes
PNS_KICAD_IFACE * m_iface
virtual ITEM * pickSingleItem(const VECTOR2I &aWhere, NET_HANDLE aNet=nullptr, int aLayer=-1, bool aIgnorePads=false, const std::vector< ITEM * > aAvoidItems={}, int aPermittedItemMask=ITEM::ANY_T)
virtual void updateEndItem(const TOOL_EVENT &aEvent)
TOOL_BASE(const std::string &aToolName)
static const unsigned int COORDS_PADDING
ROUTER * m_router
VECTOR2I m_endSnapPoint
PCB_GRID_HELPER * m_gridHelper
VECTOR2I m_startSnapPoint
int Start() const
VECTOR2I::extended_type ecoord
Definition seg.h:40
static SEG::ecoord Square(int a)
Definition seg.h:119
TOOL_MANAGER * m_toolMgr
Definition tool_base.h:220
KIGFX::VIEW * getView() const
Return the instance of KIGFX::VIEW object used in the application.
Definition tool_base.cpp:34
RESET_REASON
Determine the reason of reset for a tool.
Definition tool_base.h:74
@ SHUTDOWN
Tool is being shut down.
Definition tool_base.h:80
Generic, UI-independent tool event.
Definition tool_event.h:167
bool HasPosition() const
Returns if it this event has a valid position (true for mouse events and context-menu or hotkey-based...
Definition tool_event.h:256
bool DisableGridSnapping() const
Definition tool_event.h:367
const VECTOR2D Position() const
Return mouse cursor position in world coordinates.
Definition tool_event.h:289
bool IsDrag(int aButtonMask=BUT_ANY) const
Definition tool_event.h:311
int Modifier(int aMask=MD_MODIFIER_MASK) const
Return information about key modifiers state (Ctrl, Alt, etc.).
Definition tool_event.h:362
const VECTOR2D DragOrigin() const
Return the point where dragging has started.
Definition tool_event.h:295
static constexpr extended_type ECOORD_MAX
Definition vector2d.h:72
a few functions useful in geometry calculations.
VECTOR2< ret_type > GetClampedCoords(const VECTOR2< in_type > &aCoords, pad_type aPadding=1u)
Clamp a vector to values that can be negated, respecting numeric limits of coordinates data type with...
@ GRID_VIAS
Definition grid_helper.h:61
@ GRID_WIRES
Definition grid_helper.h:60
PCB_LAYER_ID
A quick note on layer IDs:
Definition layer_ids.h:56
PCB_LAYER_ID ToLAYER_ID(int aLayer)
Definition lset.cpp:750
The Cairo implementation of the graphics abstraction layer.
Definition eda_group.h:30
Push and Shove diff pair dimensions (gap) settings dialog.
@ RM_MarkObstacles
Ignore collisions, mark obstacles.
void * NET_HANDLE
Definition pns_item.h:55
@ PNS_MODE_ROUTE_DIFF_PAIR
Definition pns_router.h:70
bool contains(const _Container &__container, _Value __value)
Returns true if the container contains the given value.
Definition kicad_algo.h:96
MAGNETIC_OPTIONS tracks
MAGNETIC_OPTIONS pads
static std::vector< int > candidates(const SEGMENT_INDEX &aIndex, const SEG &aQuery, int aPadding)
@ MD_CTRL
Definition tool_event.h:140
@ MD_SHIFT
Definition tool_event.h:139
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708