KiCad PCB EDA Suite
Loading...
Searching...
No Matches
grid_helper.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 The KiCad Developers, see AUTHORS.txt for contributors.
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, you may find one here:
18 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
19 * or you may search the http://www.gnu.org website for the version 2 license,
20 * or you may write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22 */
23
24#include "tool/grid_helper.h"
25
26#include <functional>
27#include <cmath>
28#include <limits>
29
30#include <advanced_config.h>
31#include <trace_helpers.h>
32#include <wx/log.h>
34#include <math/util.h> // for KiROUND
35#include <math/vector2d.h>
36#include <tool/tool_manager.h>
37#include <tool/tools_holder.h>
38#include <view/view.h>
40
41
44{
46 m_enableSnap = true;
47 m_enableSnapLine = true;
48 m_enableGrid = true;
49 m_snapItem = std::nullopt;
50
51 m_manualGrid = VECTOR2D( 1, 1 );
53 m_manualOrigin = VECTOR2I( 0, 0 );
55}
56
57
58GRID_HELPER::GRID_HELPER( TOOL_MANAGER* aToolMgr, int aConstructionLayer ) :
60{
61 m_toolMgr = aToolMgr;
62
63 if( !m_toolMgr )
64 return;
65
66 KIGFX::VIEW* view = m_toolMgr->GetView();
67 wxUnusedVar( aConstructionLayer );
68
71
72 m_snapManager.SetUpdateCallback(
73 [view, this]( bool aAnythingShown )
74 {
75 const bool currentlyVisible = view->IsVisible( &m_constructionGeomPreview );
76
77 if( currentlyVisible && aAnythingShown )
78 {
80 }
81 else
82 {
83 view->SetVisible( &m_constructionGeomPreview, aAnythingShown );
84 }
86 m_toolMgr->GetToolHolder()->RefreshCanvas();
87 } );
88
89 // Initialise manual values from view for compatibility
94}
95
96
98{
99 if( !m_toolMgr )
100 return;
101
102 KIGFX::VIEW& view = *m_toolMgr->GetView();
104
105 if( m_anchorDebug )
106 view.Remove( m_anchorDebug.get() );
107}
108
109
111{
112 static bool permitted = ADVANCED_CFG::GetCfg().m_EnableSnapAnchorsDebug;
113
114 if( !m_toolMgr )
115 return nullptr;
116
117 if( permitted && !m_anchorDebug )
118 {
119 KIGFX::VIEW& view = *m_toolMgr->GetView();
120 m_anchorDebug = std::make_unique<KIGFX::ANCHOR_DEBUG>();
121 view.Add( m_anchorDebug.get() );
122 view.SetVisible( m_anchorDebug.get(), true );
123 }
124
125 return m_anchorDebug.get();
126}
127
128
130{
131 if( m_toolMgr )
132 m_toolMgr->GetView()->SetVisible( &m_constructionGeomPreview, aShow );
133}
134
135
136void GRID_HELPER::SetSnapLineDirections( const std::vector<VECTOR2I>& aDirections )
137{
138 m_snapManager.GetSnapLineManager().SetDirections( aDirections );
139}
140
141
143{
144 m_snapManager.GetSnapLineManager().SetSnapLineOrigin( aOrigin );
145}
146
147void GRID_HELPER::SetSnapLineEnd( const std::optional<VECTOR2I>& aEnd )
148{
149 m_snapManager.GetSnapLineManager().SetSnapLineEnd( aEnd );
150}
151
153{
154 m_snapManager.GetSnapLineManager().ClearSnapLine();
155}
156
157
158std::optional<VECTOR2I> GRID_HELPER::SnapToConstructionLines( const VECTOR2I& aPoint,
159 const VECTOR2I& aNearestGrid,
160 const VECTOR2D& aGrid,
161 double aSnapRange ) const
162{
163 const SNAP_LINE_MANAGER& snapLineManager = m_snapManager.GetSnapLineManager();
164 const OPT_VECTOR2I& snapOrigin = snapLineManager.GetSnapLineOrigin();
165
166 wxLogTrace( traceSnap, "SnapToConstructionLines: aPoint=(%d, %d), nearestGrid=(%d, %d), snapRange=%.1f",
167 aPoint.x, aPoint.y, aNearestGrid.x, aNearestGrid.y, aSnapRange );
168
169 if( !snapOrigin || snapLineManager.GetDirections().empty() )
170 {
171 wxLogTrace( traceSnap, " No snap origin or no directions, returning nullopt" );
172 return std::nullopt;
173 }
174
175 const VECTOR2I& origin = *snapOrigin;
176
177 wxLogTrace( traceSnap, " snapOrigin=(%d, %d), directions count=%zu",
178 origin.x, origin.y, snapLineManager.GetDirections().size() );
179
180 const std::vector<VECTOR2I>& directions = snapLineManager.GetDirections();
181 const std::optional<int> activeDirection = snapLineManager.GetActiveDirection();
182
183 if( activeDirection )
184 wxLogTrace( traceSnap, " activeDirection=%d", *activeDirection );
185
186 const VECTOR2D originVec( origin );
187 const VECTOR2D cursorVec( aPoint );
188 const VECTOR2D delta = cursorVec - originVec;
189
190 std::optional<VECTOR2I> bestPoint;
191 double bestPerp = std::numeric_limits<double>::max();
192 double bestDistance = std::numeric_limits<double>::max();
193
194 for( size_t ii = 0; ii < directions.size(); ++ii )
195 {
196 const VECTOR2I& dir = directions[ii];
197 VECTOR2D dirVector( dir );
198 double dirLength = dirVector.EuclideanNorm();
199
200 if( dirLength == 0.0 )
201 {
202 wxLogTrace( traceSnap, " Direction %zu: zero length, skipping", ii );
203 continue;
204 }
205
206 VECTOR2D dirUnit = dirVector / dirLength;
207
208 double distanceAlong = delta.Dot( dirUnit );
209 VECTOR2D projection = originVec + dirUnit * distanceAlong;
210 VECTOR2D offset = delta - dirUnit * distanceAlong;
211 double perpDistance = offset.EuclideanNorm();
212
213 double snapThreshold = aSnapRange;
214
215 if( activeDirection && *activeDirection == static_cast<int>( ii ) )
216 {
217 snapThreshold *= 1.5;
218 wxLogTrace( traceSnap, " Direction %zu: ACTIVE, increased snapThreshold=%.1f", ii, snapThreshold );
219 }
220
221 wxLogTrace( traceSnap, " Direction %zu: dir=(%d, %d), perpDist=%.1f, threshold=%.1f",
222 ii, dir.x, dir.y, perpDistance, snapThreshold );
223
224 if( perpDistance > snapThreshold )
225 {
226 wxLogTrace( traceSnap, " perpDistance > threshold, skipping" );
227 continue;
228 }
229
230 VECTOR2D candidate = projection;
231
232 if( canUseGrid() )
233 {
234 if( dir.x == 0 && dir.y != 0 )
235 {
236 // Vertical construction line: snap to grid intersection
237 candidate.x = origin.x;
238 candidate.y = aNearestGrid.y;
239 wxLogTrace( traceSnap, " Vertical snap: candidate=(%d, %d)",
240 (int)candidate.x, (int)candidate.y );
241 }
242 else if( dir.y == 0 && dir.x != 0 )
243 {
244 // Horizontal construction line: snap to grid intersection
245 candidate.x = aNearestGrid.x;
246 candidate.y = origin.y;
247 wxLogTrace( traceSnap, " Horizontal snap: candidate=(%d, %d)",
248 (int)candidate.x, (int)candidate.y );
249 }
250 else
251 {
252 // Diagonal construction line: find nearest grid intersection along the line
253 // We need to find grid points near the projection point and pick the closest
254 // one that lies on the construction line
255
256 // Get the grid origin for proper alignment
257 VECTOR2D gridOrigin( GetOrigin() );
258
259 // Calculate the projection point relative to grid
260 VECTOR2D relProjection = projection - gridOrigin;
261
262 // Find nearby grid points (check 9 points in a 3x3 grid around the projection)
263 std::vector<VECTOR2D> gridPoints;
264 for( int dx = -1; dx <= 1; ++dx )
265 {
266 for( int dy = -1; dy <= 1; ++dy )
267 {
268 double gridX = std::round( relProjection.x / aGrid.x ) * aGrid.x + dx * aGrid.x;
269 double gridY = std::round( relProjection.y / aGrid.y ) * aGrid.y + dy * aGrid.y;
270 gridPoints.push_back( VECTOR2D( gridX + gridOrigin.x, gridY + gridOrigin.y ) );
271 }
272 }
273
274 // Find the grid point closest to the construction line
275 double bestGridDist = std::numeric_limits<double>::max();
276 VECTOR2D bestGridPt = projection;
277
278 for( const VECTOR2D& gridPt : gridPoints )
279 {
280 // Calculate perpendicular distance from grid point to construction line
281 VECTOR2D gridDelta = gridPt - originVec;
282 double gridDistAlong = gridDelta.Dot( dirUnit );
283 VECTOR2D gridProjection = originVec + dirUnit * gridDistAlong;
284 double gridPerpDist = ( gridPt - gridProjection ).EuclideanNorm();
285
286 // Also consider distance from cursor
287 double distFromCursor = ( gridPt - cursorVec ).EuclideanNorm();
288
289 // Prefer grid points that are close to the line and close to cursor
290 double score = gridPerpDist + distFromCursor * 0.1;
291
292 if( score < bestGridDist )
293 {
294 bestGridDist = score;
295 bestGridPt = gridPt;
296 }
297 }
298
299 candidate = bestGridPt;
300 wxLogTrace( traceSnap, " Diagonal snap: candidate=(%.1f, %.1f), perpDist=%.1f",
301 candidate.x, candidate.y, bestGridDist );
302 }
303 }
304 else
305 {
306 wxLogTrace( traceSnap, " Grid disabled, using projection candidate=(%.1f, %.1f)",
307 candidate.x, candidate.y );
308 }
309
310 VECTOR2I candidateInt( KiROUND( candidate.x ), KiROUND( candidate.y ) );
311
312 if( candidateInt == m_skipPoint )
313 {
314 wxLogTrace( traceSnap, " candidateInt matches m_skipPoint, skipping" );
315 continue;
316 }
317
318 VECTOR2D candidateDelta( candidateInt.x - aPoint.x, candidateInt.y - aPoint.y );
319 double candidateDistance = candidateDelta.EuclideanNorm();
320
321 wxLogTrace( traceSnap, " candidateInt=(%d, %d), candidateDist=%.1f",
322 candidateInt.x, candidateInt.y, candidateDistance );
323
324 if( perpDistance < bestPerp
325 || ( std::abs( perpDistance - bestPerp ) < 1e-9 && candidateDistance < bestDistance ) )
326 {
327 wxLogTrace( traceSnap, " NEW BEST: perpDist=%.1f, candDist=%.1f", perpDistance, candidateDistance );
328 bestPerp = perpDistance;
329 bestDistance = candidateDistance;
330 bestPoint = candidateInt;
331 }
332 }
333
334 if( bestPoint )
335 {
336 wxLogTrace( traceSnap, " RETURNING bestPoint=(%d, %d)", bestPoint->x, bestPoint->y );
337 }
338 else
339 {
340 wxLogTrace( traceSnap, " RETURNING nullopt (no valid snap found)" );
341 }
342
343 return bestPoint;
344}
345
346
348{
349 if( !m_toolMgr )
350 return;
351
352 m_viewSnapPoint.SetPosition( aPoint.m_point );
353 m_viewSnapPoint.SetSnapTypes( aPoint.m_types );
354
355 if( m_toolMgr->GetView()->IsVisible( &m_viewSnapPoint ) )
356 m_toolMgr->GetView()->Update( &m_viewSnapPoint, KIGFX::GEOMETRY );
357 else
358 m_toolMgr->GetView()->SetVisible( &m_viewSnapPoint, true );
359}
360
361
363{
364 VECTOR2D size = m_toolMgr ? m_toolMgr->GetView()->GetGAL()->GetGridSize() : m_manualGrid;
365 return VECTOR2I( KiROUND( size.x ), KiROUND( size.y ) );
366}
367
368
370{
371 return m_toolMgr ? m_toolMgr->GetView()->GetGAL()->GetVisibleGridSize() : m_manualVisibleGrid;
372}
373
374
376{
377 if( m_toolMgr )
378 {
379 VECTOR2D origin = m_toolMgr->GetView()->GetGAL()->GetGridOrigin();
380 return VECTOR2I( origin );
381 }
382
383 return m_manualOrigin;
384}
385
386
388{
389 GRID_HELPER_GRIDS grid = GetItemGrid( aSelection.Front() );
390
391 // Find the largest grid of all the items and use that
392 for( EDA_ITEM* item : aSelection )
393 {
394 GRID_HELPER_GRIDS itemGrid = GetItemGrid( item );
395
396 if( GetGridSize( itemGrid ) > GetGridSize( grid ) )
397 grid = itemGrid;
398 }
399
400 return grid;
401}
402
403
405{
406 return m_toolMgr ? m_toolMgr->GetView()->GetGAL()->GetGridSize() : m_manualGrid;
407}
408
409
410void GRID_HELPER::SetAuxAxes( bool aEnable, const VECTOR2I& aOrigin )
411{
412 if( aEnable )
413 {
414 m_auxAxis = aOrigin;
415 m_viewAxis.SetPosition( aOrigin );
416 if( m_toolMgr )
417 m_toolMgr->GetView()->SetVisible( &m_viewAxis, true );
418 }
419 else
420 {
421 m_auxAxis = std::optional<VECTOR2I>();
422 if( m_toolMgr )
423 m_toolMgr->GetView()->SetVisible( &m_viewAxis, false );
424 }
425}
426
427
429{
430 return computeNearest( aPoint, GetGrid(), GetOrigin() );
431}
432
433
435 const VECTOR2D& aOffset ) const
436{
437 return computeNearest( aPoint, aGrid, aOffset );
438}
439
440
442 const VECTOR2I& aOffset ) const
443{
444 return VECTOR2I( KiROUND( (double) ( aPoint.x - aOffset.x ) / aGrid.x ) * aGrid.x + aOffset.x,
445 KiROUND( (double) ( aPoint.y - aOffset.y ) / aGrid.y ) * aGrid.y + aOffset.y );
446}
447
448
450{
451 return Align( aPoint, GetGrid(), GetOrigin() );
452}
453
454
455VECTOR2I GRID_HELPER::Align( const VECTOR2I& aPoint, const VECTOR2D& aGrid,
456 const VECTOR2D& aOffset ) const
457{
458 if( !canUseGrid() )
459 return aPoint;
460
461 VECTOR2I nearest = AlignGrid( aPoint, aGrid, aOffset );
462
463 if( !m_auxAxis )
464 return nearest;
465
466 if( std::abs( m_auxAxis->x - aPoint.x ) < std::abs( nearest.x - aPoint.x ) )
467 nearest.x = m_auxAxis->x;
468
469 if( std::abs( m_auxAxis->y - aPoint.y ) < std::abs( nearest.y - aPoint.y ) )
470 nearest.y = m_auxAxis->y;
471
472 return nearest;
473}
474
475
477{
478 return m_enableGrid && ( m_toolMgr ? m_toolMgr->GetView()->GetGAL()->GetGridSnapping()
480}
481
482
483std::optional<VECTOR2I> GRID_HELPER::GetSnappedPoint() const
484{
485 if( m_snapItem )
486 return m_snapItem->pos;
487
488 return std::nullopt;
489}
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:990
static const ADVANCED_CFG & GetCfg()
Get the singleton instance's config, which is shared by all consumers.
A base class for most all the KiCad significant classes used in schematics and boards.
Definition eda_item.h:98
KIGFX::CONSTRUCTION_GEOM m_constructionGeomPreview
Show construction geometry (if any) on the canvas.
std::optional< VECTOR2I > m_auxAxis
VECTOR2I computeNearest(const VECTOR2I &aPoint, const VECTOR2I &aGrid, const VECTOR2I &aOffset) const
std::optional< VECTOR2I > SnapToConstructionLines(const VECTOR2I &aPoint, const VECTOR2I &aNearestGrid, const VECTOR2D &aGrid, double aSnapRange) const
void SetSnapLineDirections(const std::vector< VECTOR2I > &aDirections)
VECTOR2I m_skipPoint
bool m_enableGrid
virtual GRID_HELPER_GRIDS GetItemGrid(const EDA_ITEM *aItem) const
Get the coarsest grid that applies to an item.
void showConstructionGeometry(bool aShow)
SNAP_MANAGER m_snapManager
Manage the construction geometry, snap lines, reference points, etc.
virtual ~GRID_HELPER()
VECTOR2D m_manualVisibleGrid
void SetSnapLineOrigin(const VECTOR2I &aOrigin)
bool m_manualGridSnapping
VECTOR2I m_manualOrigin
virtual GRID_HELPER_GRIDS GetSelectionGrid(const SELECTION &aSelection) const
Gets the coarsest grid that applies to a selecion of items.
TOOL_MANAGER * m_toolMgr
std::optional< VECTOR2I > GetSnappedPoint() const
void SetAuxAxes(bool aEnable, const VECTOR2I &aOrigin=VECTOR2I(0, 0))
VECTOR2D GetVisibleGrid() const
std::unique_ptr< KIGFX::ANCHOR_DEBUG > m_anchorDebug
#VIEW_ITEM for visualising anchor points, if enabled.
virtual VECTOR2D GetGridSize(GRID_HELPER_GRIDS aGrid) const
Return the size of the specified grid.
VECTOR2I GetGrid() const
bool m_enableSnapLine
bool m_enableSnap
VECTOR2I GetOrigin() const
bool canUseGrid() const
Check whether it is possible to use the grid – this depends both on local grid helper settings and gl...
void ClearSnapLine()
std::optional< ANCHOR > m_snapItem
KIGFX::ANCHOR_DEBUG * enableAndGetAnchorDebug()
Enable the anchor debug if permitted and return it.
void SetSnapLineEnd(const std::optional< VECTOR2I > &aEnd)
KIGFX::SNAP_INDICATOR m_viewSnapPoint
virtual VECTOR2I Align(const VECTOR2I &aPoint, GRID_HELPER_GRIDS aGrid) const
Definition grid_helper.h:75
void updateSnapPoint(const TYPED_POINT2I &aPoint)
KIGFX::ORIGIN_VIEWITEM m_viewAxis
VECTOR2D m_manualGrid
virtual VECTOR2I AlignGrid(const VECTOR2I &aPoint, GRID_HELPER_GRIDS aGrid) const
Definition grid_helper.h:80
View item to draw debug items for anchors.
const VECTOR2D & GetGridOrigin() const
VECTOR2D GetVisibleGridSize() const
Return the visible grid size in x and y directions.
const VECTOR2D & GetGridSize() const
Return the grid size.
Hold a (potentially large) number of VIEW_ITEMs and renders them on a graphics device provided by the...
Definition view.h:66
virtual void Add(VIEW_ITEM *aItem, int aDrawPriority=-1)
Add a VIEW_ITEM to the view.
Definition view.cpp:298
virtual void Remove(VIEW_ITEM *aItem)
Remove a VIEW_ITEM from the view.
Definition view.cpp:341
virtual void Update(const VIEW_ITEM *aItem, int aUpdateFlags) const
For dynamic VIEWs, inform the associated VIEW that the graphical representation of this item has chan...
Definition view.cpp:1685
GAL * GetGAL() const
Return the GAL this view is using to draw graphical primitives.
Definition view.h:202
bool IsVisible(const VIEW_ITEM *aItem) const
Return information if the item is visible (or not).
Definition view.cpp:1655
void SetVisible(VIEW_ITEM *aItem, bool aIsVisible=true)
Set the item visibility.
Definition view.cpp:1612
EDA_ITEM * Front() const
Definition selection.h:177
const std::vector< VECTOR2I > & GetDirections() const
std::optional< int > GetActiveDirection() const
const OPT_VECTOR2I & GetSnapLineOrigin() const
Master controller class:
T EuclideanNorm() const
Compute the Euclidean norm of the vector, which is defined as sqrt(x ** 2 + y ** 2).
Definition vector2d.h:283
constexpr extended_type Dot(const VECTOR2< T > &aVector) const
Compute dot product of self with aVector.
Definition vector2d.h:554
GRID_HELPER_GRIDS
Definition grid_helper.h:44
bool m_EnableSnapAnchorsDebug
Enable snap anchors debug visualization.
const wxChar *const traceSnap
Flag to enable snap/grid helper debug tracing.
@ GEOMETRY
Position or shape has changed.
Definition view_item.h:55
EDA_ANGLE abs(const EDA_ANGLE &aAngle)
Definition eda_angle.h:400
std::optional< VECTOR2I > OPT_VECTOR2I
Definition seg.h:39
VECTOR2I m_point
Definition point_types.h:77
int delta
wxLogTrace helper definitions.
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:695
VECTOR2< double > VECTOR2D
Definition vector2d.h:694