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, see <https://www.gnu.org/licenses/>.
18 */
19
20#include "tool/grid_helper.h"
21
22#include <functional>
23#include <cmath>
24#include <limits>
25
26#include <advanced_config.h>
27#include <trace_helpers.h>
28#include <wx/log.h>
30#include <math/util.h> // for KiROUND
31#include <math/vector2d.h>
32#include <tool/tool_manager.h>
33#include <tool/tools_holder.h>
34#include <view/view.h>
36#include <gal/painter.h>
37
38
41{
43 m_enableSnap = true;
44 m_enableSnapLine = true;
45 m_enableGrid = true;
46 m_snapItem = std::nullopt;
47
48 m_manualGrid = VECTOR2D( 1, 1 );
50 m_manualOrigin = VECTOR2I( 0, 0 );
52}
53
54
55GRID_HELPER::GRID_HELPER( TOOL_MANAGER* aToolMgr, int aConstructionLayer ) :
57{
58 m_toolMgr = aToolMgr;
60 if( !m_toolMgr )
61 return;
62
63 KIGFX::VIEW* view = m_toolMgr->GetView();
64 KIGFX::RENDER_SETTINGS* settings = view->GetPainter()->GetSettings();
65 KIGFX::COLOR4D constructionColor = settings->GetLayerColor( aConstructionLayer );
66
67 m_constructionGeomPreview.SetColor( constructionColor );
68 m_constructionGeomPreview.SetPersistentColor( constructionColor );
69
72
73 m_snapManager.SetUpdateCallback(
74 [view, this]( bool aAnythingShown )
75 {
76 const bool currentlyVisible = view->IsVisible( &m_constructionGeomPreview );
77
78 if( currentlyVisible && aAnythingShown )
79 {
81 }
82 else
83 {
84 view->SetVisible( &m_constructionGeomPreview, aAnythingShown );
85 }
86
87 m_toolMgr->GetToolHolder()->RefreshCanvas();
88 } );
89
90 // Initialise manual values from view for compatibility
91 m_manualGrid = view->GetGAL()->GetGridSize();
92 m_manualVisibleGrid = view->GetGAL()->GetVisibleGridSize();
95}
99{
100 if( !m_toolMgr )
101 return;
102
103 KIGFX::VIEW& view = *m_toolMgr->GetView();
105
106 if( m_anchorDebug )
107 view.Remove( m_anchorDebug.get() );
108}
109
110
112{
113 static bool permitted = ADVANCED_CFG::GetCfg().m_EnableSnapAnchorsDebug;
114
115 if( !m_toolMgr )
116 return nullptr;
117
118 if( permitted && !m_anchorDebug )
119 {
120 KIGFX::VIEW& view = *m_toolMgr->GetView();
121 m_anchorDebug = std::make_unique<KIGFX::ANCHOR_DEBUG>();
122 view.Add( m_anchorDebug.get() );
123 view.SetVisible( m_anchorDebug.get(), true );
124 }
125
126 return m_anchorDebug.get();
127}
128
129
131{
132 if( m_toolMgr )
133 m_toolMgr->GetView()->SetVisible( &m_constructionGeomPreview, aShow );
134}
135
136
137void GRID_HELPER::SetSnapLineDirections( const std::vector<VECTOR2I>& aDirections )
138{
139 m_snapManager.GetSnapLineManager().SetDirections( aDirections );
140}
141
142
144{
145 m_snapManager.GetSnapLineManager().SetSnapLineOrigin( aOrigin );
146}
147
148void GRID_HELPER::SetSnapLineEnd( const std::optional<VECTOR2I>& aEnd )
149{
150 m_snapManager.GetSnapLineManager().SetSnapLineEnd( aEnd );
151}
152
154{
155 m_snapManager.GetSnapLineManager().ClearSnapLine();
156}
157
158
159std::optional<VECTOR2I> GRID_HELPER::SnapToConstructionLines( const VECTOR2I& aPoint,
160 const VECTOR2I& aNearestGrid,
161 const VECTOR2D& aGrid,
162 double aSnapRange ) const
163{
164 const SNAP_LINE_MANAGER& snapLineManager = m_snapManager.GetSnapLineManager();
165 const OPT_VECTOR2I& snapOrigin = snapLineManager.GetSnapLineOrigin();
166
167 wxLogTrace( traceSnap, "SnapToConstructionLines: aPoint=(%d, %d), nearestGrid=(%d, %d), snapRange=%.1f",
168 aPoint.x, aPoint.y, aNearestGrid.x, aNearestGrid.y, aSnapRange );
169
170 if( !snapOrigin || snapLineManager.GetDirections().empty() )
171 {
172 wxLogTrace( traceSnap, " No snap origin or no directions, returning nullopt" );
173 return std::nullopt;
174 }
175
176 const VECTOR2I& origin = *snapOrigin;
177
178 wxLogTrace( traceSnap, " snapOrigin=(%d, %d), directions count=%zu",
179 origin.x, origin.y, snapLineManager.GetDirections().size() );
180
181 const std::vector<VECTOR2I>& directions = snapLineManager.GetDirections();
182 const std::optional<int> activeDirection = snapLineManager.GetActiveDirection();
183
184 if( activeDirection )
185 wxLogTrace( traceSnap, " activeDirection=%d", *activeDirection );
186
187 const VECTOR2D originVec( origin );
188 const VECTOR2D cursorVec( aPoint );
189 const VECTOR2D delta = cursorVec - originVec;
190
191 std::optional<VECTOR2I> bestPoint;
192 double bestPerp = std::numeric_limits<double>::max();
193 double bestDistance = std::numeric_limits<double>::max();
194
195 for( size_t ii = 0; ii < directions.size(); ++ii )
196 {
197 const VECTOR2I& dir = directions[ii];
198 VECTOR2D dirVector( dir );
199 double dirLength = dirVector.EuclideanNorm();
200
201 if( dirLength == 0.0 )
202 {
203 wxLogTrace( traceSnap, " Direction %zu: zero length, skipping", ii );
204 continue;
205 }
206
207 VECTOR2D dirUnit = dirVector / dirLength;
208
209 double distanceAlong = delta.Dot( dirUnit );
210 VECTOR2D projection = originVec + dirUnit * distanceAlong;
211 VECTOR2D offset = delta - dirUnit * distanceAlong;
212 double perpDistance = offset.EuclideanNorm();
213
214 double snapThreshold = aSnapRange;
215
216 if( activeDirection && *activeDirection == static_cast<int>( ii ) )
217 {
218 snapThreshold *= 1.5;
219 wxLogTrace( traceSnap, " Direction %zu: ACTIVE, increased snapThreshold=%.1f", ii, snapThreshold );
220 }
221
222 wxLogTrace( traceSnap, " Direction %zu: dir=(%d, %d), perpDist=%.1f, threshold=%.1f",
223 ii, dir.x, dir.y, perpDistance, snapThreshold );
224
225 if( perpDistance > snapThreshold )
226 {
227 wxLogTrace( traceSnap, " perpDistance > threshold, skipping" );
228 continue;
229 }
230
231 VECTOR2D candidate = projection;
232
233 if( canUseGrid() )
234 {
235 if( dir.x == 0 && dir.y != 0 )
236 {
237 // Vertical construction line: snap to grid intersection
238 candidate.x = origin.x;
239 candidate.y = aNearestGrid.y;
240 wxLogTrace( traceSnap, " Vertical snap: candidate=(%d, %d)",
241 (int)candidate.x, (int)candidate.y );
242 }
243 else if( dir.y == 0 && dir.x != 0 )
244 {
245 // Horizontal construction line: snap to grid intersection
246 candidate.x = aNearestGrid.x;
247 candidate.y = origin.y;
248 wxLogTrace( traceSnap, " Horizontal snap: candidate=(%d, %d)",
249 (int)candidate.x, (int)candidate.y );
250 }
251 else
252 {
253 // Diagonal construction line: find nearest grid intersection along the line
254 // We need to find grid points near the projection point and pick the closest
255 // one that lies on the construction line
256
257 // Get the grid origin for proper alignment
258 VECTOR2D gridOrigin( GetOrigin() );
259
260 // Calculate the projection point relative to grid
261 VECTOR2D relProjection = projection - gridOrigin;
262
263 // Find nearby grid points (check 9 points in a 3x3 grid around the projection)
264 std::vector<VECTOR2D> gridPoints;
265 for( int dx = -1; dx <= 1; ++dx )
266 {
267 for( int dy = -1; dy <= 1; ++dy )
268 {
269 double gridX = std::round( relProjection.x / aGrid.x ) * aGrid.x + dx * aGrid.x;
270 double gridY = std::round( relProjection.y / aGrid.y ) * aGrid.y + dy * aGrid.y;
271 gridPoints.push_back( VECTOR2D( gridX + gridOrigin.x, gridY + gridOrigin.y ) );
272 }
273 }
274
275 // Find the grid point closest to the construction line
276 double bestGridDist = std::numeric_limits<double>::max();
277 VECTOR2D bestGridPt = projection;
278
279 for( const VECTOR2D& gridPt : gridPoints )
280 {
281 // Calculate perpendicular distance from grid point to construction line
282 VECTOR2D gridDelta = gridPt - originVec;
283 double gridDistAlong = gridDelta.Dot( dirUnit );
284 VECTOR2D gridProjection = originVec + dirUnit * gridDistAlong;
285 double gridPerpDist = ( gridPt - gridProjection ).EuclideanNorm();
286
287 // Also consider distance from cursor
288 double distFromCursor = ( gridPt - cursorVec ).EuclideanNorm();
289
290 // Prefer grid points that are close to the line and close to cursor
291 double score = gridPerpDist + distFromCursor * 0.1;
292
293 if( score < bestGridDist )
294 {
295 bestGridDist = score;
296 bestGridPt = gridPt;
297 }
298 }
299
300 candidate = bestGridPt;
301 wxLogTrace( traceSnap, " Diagonal snap: candidate=(%.1f, %.1f), perpDist=%.1f",
302 candidate.x, candidate.y, bestGridDist );
303 }
304 }
305 else
306 {
307 wxLogTrace( traceSnap, " Grid disabled, using projection candidate=(%.1f, %.1f)",
308 candidate.x, candidate.y );
309 }
310
311 VECTOR2I candidateInt = KiROUND( candidate );
312
313 if( candidateInt == m_skipPoint )
314 {
315 wxLogTrace( traceSnap, " candidateInt matches m_skipPoint, skipping" );
316 continue;
317 }
318
319 VECTOR2D candidateDelta( candidateInt.x - aPoint.x, candidateInt.y - aPoint.y );
320 double candidateDistance = candidateDelta.EuclideanNorm();
321
322 wxLogTrace( traceSnap, " candidateInt=(%d, %d), candidateDist=%.1f",
323 candidateInt.x, candidateInt.y, candidateDistance );
324
325 if( perpDistance < bestPerp
326 || ( std::abs( perpDistance - bestPerp ) < 1e-9 && candidateDistance < bestDistance ) )
327 {
328 wxLogTrace( traceSnap, " NEW BEST: perpDist=%.1f, candDist=%.1f", perpDistance, candidateDistance );
329 bestPerp = perpDistance;
330 bestDistance = candidateDistance;
331 bestPoint = candidateInt;
332 }
333 }
334
335 if( bestPoint )
336 {
337 wxLogTrace( traceSnap, " RETURNING bestPoint=(%d, %d)", bestPoint->x, bestPoint->y );
338 }
339 else
340 {
341 wxLogTrace( traceSnap, " RETURNING nullopt (no valid snap found)" );
342 }
343
344 return bestPoint;
345}
346
347
349{
350 if( !m_toolMgr )
351 return;
352
353 m_viewSnapPoint.SetPosition( aPoint.m_point );
354 m_viewSnapPoint.SetSnapTypes( aPoint.m_types );
355
356 if( m_toolMgr->GetView()->IsVisible( &m_viewSnapPoint ) )
357 m_toolMgr->GetView()->Update( &m_viewSnapPoint, KIGFX::GEOMETRY );
358 else
359 m_toolMgr->GetView()->SetVisible( &m_viewSnapPoint, true );
360}
361
362
364{
365 VECTOR2D size = m_toolMgr ? m_toolMgr->GetView()->GetGAL()->GetGridSize() : m_manualGrid;
366 return VECTOR2I( KiROUND( size.x ), KiROUND( size.y ) );
367}
368
369
371{
372 return m_toolMgr ? m_toolMgr->GetView()->GetGAL()->GetVisibleGridSize() : m_manualVisibleGrid;
373}
374
375
377{
378 if( m_toolMgr )
379 {
380 VECTOR2D origin = m_toolMgr->GetView()->GetGAL()->GetGridOrigin();
381 return VECTOR2I( origin );
382 }
383
384 return m_manualOrigin;
385}
386
387
389{
390 GRID_HELPER_GRIDS grid = GetItemGrid( aSelection.Front() );
391
392 // Find the largest grid of all the items and use that
393 for( EDA_ITEM* item : aSelection )
394 {
395 GRID_HELPER_GRIDS itemGrid = GetItemGrid( item );
396
397 if( GetGridSize( itemGrid ) > GetGridSize( grid ) )
398 grid = itemGrid;
399 }
400
401 return grid;
402}
403
404
406{
407 return m_toolMgr ? m_toolMgr->GetView()->GetGAL()->GetGridSize() : m_manualGrid;
408}
409
410
411void GRID_HELPER::SetAuxAxes( bool aEnable, const VECTOR2I& aOrigin )
412{
413 if( aEnable )
414 {
415 m_auxAxis = aOrigin;
416 m_viewAxis.SetPosition( aOrigin );
417 if( m_toolMgr )
418 m_toolMgr->GetView()->SetVisible( &m_viewAxis, true );
419 }
420 else
421 {
422 m_auxAxis = std::optional<VECTOR2I>();
423 if( m_toolMgr )
424 m_toolMgr->GetView()->SetVisible( &m_viewAxis, false );
425 }
426}
427
428
430{
431 return computeNearest( aPoint, GetGrid(), GetOrigin() );
432}
433
434
436 const VECTOR2D& aOffset ) const
437{
438 // Round the grid size and offset rather than relying on the implicit VECTOR2D->VECTOR2I
439 // truncation in computeNearest. Grid sizes that aren't exact in IEEE 754 (e.g., 0.254mm =
440 // 10 mil) would otherwise truncate to the wrong integer (253999 instead of 254000),
441 // producing positions that aren't true grid multiples.
442 return computeNearest( aPoint, KiROUND( aGrid ), KiROUND( aOffset ) );
443}
444
445
447 const VECTOR2I& aOffset ) const
448{
449 return VECTOR2I( KiROUND( (double) ( aPoint.x - aOffset.x ) / aGrid.x ) * aGrid.x + aOffset.x,
450 KiROUND( (double) ( aPoint.y - aOffset.y ) / aGrid.y ) * aGrid.y + aOffset.y );
451}
452
453
455{
456 return Align( aPoint, GetGrid(), GetOrigin() );
457}
458
459
460VECTOR2I GRID_HELPER::Align( const VECTOR2I& aPoint, const VECTOR2D& aGrid,
461 const VECTOR2D& aOffset ) const
462{
463 if( !canUseGrid() )
464 return aPoint;
465
466 VECTOR2I nearest = AlignGrid( aPoint, aGrid, aOffset );
467
468 if( !m_auxAxis )
469 return nearest;
470
471 if( std::abs( m_auxAxis->x - aPoint.x ) < std::abs( nearest.x - aPoint.x ) )
472 nearest.x = m_auxAxis->x;
473
474 if( std::abs( m_auxAxis->y - aPoint.y ) < std::abs( nearest.y - aPoint.y ) )
475 nearest.y = m_auxAxis->y;
476
477 return nearest;
478}
479
480
482{
483 return m_enableGrid && ( m_toolMgr ? m_toolMgr->GetView()->GetGAL()->GetGridSnapping()
485}
486
487
488std::optional<VECTOR2I> GRID_HELPER::GetSnappedPoint() const
489{
490 if( m_snapItem )
491 return m_snapItem->pos;
492
493 return std::nullopt;
494}
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:986
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:96
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:82
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:87
View item to draw debug items for anchors.
A color representation with 4 components: red, green, blue, alpha.
Definition color4d.h:101
const VECTOR2D & GetGridOrigin() const
Container for all the knowledge about how graphical objects are drawn on any output surface/device.
const COLOR4D & GetLayerColor(int aLayer) const
Return the color used to draw a layer.
Hold a (potentially large) number of VIEW_ITEMs and renders them on a graphics device provided by the...
Definition view.h:63
virtual void Add(VIEW_ITEM *aItem, int aDrawPriority=-1)
Add a VIEW_ITEM to the view.
Definition view.cpp:300
virtual void Remove(VIEW_ITEM *aItem)
Remove a VIEW_ITEM from the view.
Definition view.cpp:404
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:1835
GAL * GetGAL() const
Return the GAL this view is using to draw graphical primitives.
Definition view.h:207
PAINTER * GetPainter() const
Return the painter object used by the view for drawing #VIEW_ITEMS.
Definition view.h:225
bool IsVisible(const VIEW_ITEM *aItem) const
Return information if the item is visible (or not).
Definition view.cpp:1805
void SetVisible(VIEW_ITEM *aItem, bool aIsVisible=true)
Set the item visibility.
Definition view.cpp:1756
EDA_ITEM * Front() const
Definition selection.h:173
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:279
constexpr extended_type Dot(const VECTOR2< T > &aVector) const
Compute dot product of self with aVector.
Definition vector2d.h:542
GRID_HELPER_GRIDS
Definition grid_helper.h:40
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:51
EDA_ANGLE abs(const EDA_ANGLE &aAngle)
Definition eda_angle.h:400
std::optional< VECTOR2I > OPT_VECTOR2I
Definition seg.h:35
VECTOR2I m_point
Definition point_types.h:73
int delta
wxLogTrace helper definitions.
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:683
VECTOR2< double > VECTOR2D
Definition vector2d.h:682