KiCad PCB EDA Suite
Loading...
Searching...
No Matches
drc_test_provider_disallow.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.
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 <atomic>
21#include <common.h>
23#include <drc/drc_rtree.h>
24#include <drc/drc_engine.h>
25#include <drc/drc_item.h>
26#include <drc/drc_rule.h>
28#include <pad.h>
29#include <progress_reporter.h>
30#include <thread_pool.h>
31#include <zone.h>
32#include <pcb_track.h>
33#include <mutex>
34
35
36/*
37 "Disallow" test. Goes through all items, matching types/conditions drop errors.
38 Errors generated:
39 - DRCE_ALLOWED_ITEMS
40 - DRCE_TEXT_ON_EDGECUTS
41*/
42
44{
45public:
48
49 virtual ~DRC_TEST_PROVIDER_DISALLOW() = default;
50
51 virtual bool Run() override;
52
53 virtual const wxString GetName() const override { return wxT( "disallow" ); };
54};
55
56
58{
59 if( !reportPhase( _( "Checking keepouts & disallow constraints..." ) ) )
60 return false; // DRC cancelled
61
62 BOARD* board = m_drcEngine->GetBoard();
64
65 // First build out the board's cache of copper-keepout to copper-zone caches. This is where
66 // the bulk of the time is spent, and we can do this in parallel.
67 //
68 std::vector<ZONE*> antiCopperKeepouts;
69 std::vector<ZONE*> copperZones;
70 std::vector<std::pair<ZONE*, ZONE*>> toCache;
71 std::atomic<size_t> done( 1 );
72 int totalCount = 0;
73 std::unique_ptr<DRC_RTREE> antiTrackKeepouts = std::make_unique<DRC_RTREE>();
74
76 [&]( BOARD_ITEM* item ) -> bool
77 {
78 ZONE* zone = static_cast<ZONE*>( item );
79
80 if( zone->GetIsRuleArea() )
81 {
82 if( zone->GetDoNotAllowZoneFills() )
83 antiCopperKeepouts.push_back( zone );
84
85 if( zone->GetDoNotAllowTracks() )
86 {
87 for( PCB_LAYER_ID layer : zone->GetLayerSet() )
88 antiTrackKeepouts->Insert( zone, layer, CLEARANCE_CONSTRAINT );
89 }
90 }
91 else if( zone->IsOnCopperLayer() )
92 {
93 copperZones.push_back( zone );
94 }
95
96 totalCount++;
97
98 return true;
99 } );
100
101 antiTrackKeepouts->Build();
102
103 for( ZONE* keepoutRuleArea : antiCopperKeepouts )
104 {
105 for( ZONE* copperZone : copperZones )
106 {
107 toCache.push_back( { keepoutRuleArea, copperZone } );
108 totalCount++;
109 }
110 }
111
112 auto query_keepouts =
113 [&]( const int idx ) -> size_t
114 {
115 if( m_drcEngine->IsCancelled() )
116 return 0;
117
118 auto [keepoutRuleArea, copperZone] = toCache[idx];
119 BOX2I areaBBox = keepoutRuleArea->GetBoundingBox();
120 BOX2I copperBBox = copperZone->GetBoundingBox();
121 bool isInside = false;
122
123 if( copperZone->IsFilled() && areaBBox.Intersects( copperBBox ) )
124 {
125 // Collisions include touching, so we need to deflate outline by enough to
126 // exclude it. This is particularly important for detecting copper fills as
127 // they will be exactly touching along the entire exclusion border.
128 SHAPE_POLY_SET areaPoly = keepoutRuleArea->GetBoardOutline();
129 areaPoly.Fracture();
131
132 DRC_RTREE* zoneRTree = board->m_CopperZoneRTreeCache[ copperZone ].get();
133
134 if( zoneRTree )
135 {
136 for( size_t ii = 0; ii < keepoutRuleArea->GetLayerSet().size(); ++ii )
137 {
138 if( keepoutRuleArea->GetLayerSet().test( ii ) )
139 {
140 PCB_LAYER_ID layer = PCB_LAYER_ID( ii );
141
142 if( zoneRTree->QueryColliding( areaBBox, &areaPoly, layer ) )
143 {
144 isInside = true;
145 break;
146 }
147
148 if( m_drcEngine->IsCancelled() )
149 return 0;
150 }
151 }
152 }
153 }
154
155 if( m_drcEngine->IsCancelled() )
156 return 0;
157
158 PTR_PTR_LAYER_CACHE_KEY key = { keepoutRuleArea, copperZone, UNDEFINED_LAYER };
159 board->m_IntersectsKeepoutCache.Set( key, isInside );
160
161 done.fetch_add( 1 );
162
163 return 1;
164 };
165
167 auto futures = tp.submit_loop( 0, toCache.size(), query_keepouts, toCache.size() );
168
169 for( auto& ret : futures )
170 {
171 std::future_status status = ret.wait_for( std::chrono::milliseconds( 250 ) );
172
173 while( status != std::future_status::ready )
174 {
175 reportProgress( done, toCache.size() );
176 status = ret.wait_for( std::chrono::milliseconds( 250 ) );
177 }
178 }
179
180 if( m_drcEngine->IsCancelled() )
181 return false;
182
183 // Now go through all the board objects calling the DRC_ENGINE to run the actual disallow
184 // tests. These should be reasonably quick using the caches generated above.
185 //
186 // Collect items first, then process in parallel.
187 std::vector<BOARD_ITEM*> allItems;
188
190 [&]( BOARD_ITEM* item ) -> bool
191 {
192 allItems.push_back( item );
193 return true;
194 } );
195
196 std::atomic<size_t> itemsDone( 0 );
197 size_t itemCount = allItems.size();
198
199 auto checkTextOnEdgeCuts = []( BOARD_ITEM* item ) -> bool
200 {
201 // Items that plot geometry onto Edge.Cuts corrupt the board outline.
202 // Reference images are excluded on purpose because they are never plotted.
203 if( item->Type() == PCB_FIELD_T
204 || item->Type() == PCB_TEXT_T
205 || item->Type() == PCB_TEXTBOX_T
206 || BaseType( item->Type() ) == PCB_TABLE_T
207 || item->Type() == PCB_BARCODE_T
208 || BaseType( item->Type() ) == PCB_DIMENSION_T )
209 {
210 return item->GetLayer() == Edge_Cuts;
211 }
212
213 return false;
214 };
215
216 auto processItem =
217 [&]( const int idx ) -> size_t
218 {
219 if( m_drcEngine->IsCancelled() )
220 {
221 itemsDone.fetch_add( 1 );
222 return 0;
223 }
224
225 bool testTextOnEdge = !m_drcEngine->IsErrorLimitExceeded( DRCE_TEXT_ON_EDGECUTS );
226 bool testDisallow = !m_drcEngine->IsErrorLimitExceeded( DRCE_ALLOWED_ITEMS );
227
228 if( !testTextOnEdge && !testDisallow )
229 {
230 itemsDone.fetch_add( 1 );
231 return 0;
232 }
233
234 BOARD_ITEM* item = allItems[idx];
235
236 if( testTextOnEdge && checkTextOnEdgeCuts( item ) )
237 {
238 std::shared_ptr<DRC_ITEM> drc = DRC_ITEM::Create( DRCE_TEXT_ON_EDGECUTS );
239 drc->SetItems( item );
241 }
242
243 if( testDisallow )
244 {
245 if( item->Type() == PCB_ZONE_T )
246 {
247 ZONE* zone = static_cast<ZONE*>( item );
248
249 if( zone->GetIsRuleArea() && zone->HasKeepoutParametersSet() )
250 {
251 itemsDone.fetch_add( 1 );
252 return 1;
253 }
254 }
255
256 item->ClearFlags( HOLE_PROXY );
257
258 if( item->Type() == PCB_TRACE_T || item->Type() == PCB_ARC_T )
259 {
260 PCB_TRACK* track = static_cast<PCB_TRACK*>( item );
261 PCB_LAYER_ID layer = track->GetLayer();
262
263 antiTrackKeepouts->QueryColliding( track, layer, layer,
264 [&]( BOARD_ITEM* other ) -> bool
265 {
266 return true;
267 },
268 [&]( BOARD_ITEM* other ) -> bool
269 {
270 std::shared_ptr<SHAPE> shape = track->GetEffectiveShape();
271 int dummyActual;
272 VECTOR2I pos;
273 SHAPE_POLY_SET zoneOutlineStorage;
274 SHAPE_POLY_SET* zoneOutline = &zoneOutlineStorage;
275
276 // GetBoardOutline() is expensive. Only use it in DRC where we have to.
277 if( other->GetParentFootprint() )
278 zoneOutlineStorage = static_cast<ZONE*>( other )->GetBoardOutline();
279 else
280 zoneOutline = static_cast<ZONE*>( other )->Outline();
281
282 if( zoneOutline->Collide( shape.get(), 0, &dummyActual, &pos ) )
283 {
284 std::shared_ptr<DRC_ITEM> drcItem = DRC_ITEM::Create( DRCE_ALLOWED_ITEMS );
285 drcItem->SetItems( track );
286 reportViolation( drcItem, pos, track->GetLayerSet().ExtractLayer() );
287 }
288
289 return !m_drcEngine->IsCancelled();
290 },
292 }
293
294 // Tracks and arcs against keepout areas that disallow tracks are already
295 // reported above via antiTrackKeepouts (which collides every crossing, not
296 // just one per rule match). Skip the track/arc case for implicit keepout
297 // rules here to avoid duplicate markers, but still let EvalRules produce
298 // markers for all other item types against implicit keepout rules.
299 bool isTrackOrArc = ( item->Type() == PCB_TRACE_T || item->Type() == PCB_ARC_T );
300
301 auto reportDisallow =
302 [&]( const DRC_CONSTRAINT& aConstraint )
303 {
304 DRC_RULE* rule = aConstraint.GetParentRule();
305
306 if( !rule )
307 return;
308
309 if( isTrackOrArc && rule->IsImplicit() )
310 return;
311
312 std::shared_ptr<DRC_ITEM> drcItem = DRC_ITEM::Create( DRCE_ALLOWED_ITEMS );
313 PCB_LAYER_ID layer = item->GetLayerSet().ExtractLayer();
314 VECTOR2I pos = item->GetPosition();
315
316 // Provide a better location for keepout area collisions by snapping to where
317 // the item actually crosses the keepout outline. Use the cached BOARD_ITEM*
318 // rather than a UUID lookup, since ResolveItem mutates an unsynchronized cache
319 // and this lambda runs inside the parallel DRC worker pool.
320 if( rule->IsImplicit() )
321 {
322 if( ZONE* keepout = dynamic_cast<ZONE*>( rule->m_ImplicitItem ) )
323 {
324 std::shared_ptr<SHAPE> shape = item->GetEffectiveShape( layer );
325 int dummyActual;
326
327 // This is only done when reporting collisions, so we can afford the
328 // more expensive GetBoardOutline().
329 SHAPE_POLY_SET keepoutOutline = keepout->GetBoardOutline();
330 keepoutOutline.Collide( shape.get(), 0, &dummyActual, &pos );
331 }
332 }
333
334 drcItem->SetErrorDetail( wxString::Format( wxS( "(%s)" ), aConstraint.GetName() ) );
335 drcItem->SetItems( item );
336 drcItem->SetViolatingRule( rule );
337 reportViolation( drcItem, pos, layer );
338 };
339
340 DRC_CONSTRAINT constraint = m_drcEngine->EvalRules( DISALLOW_CONSTRAINT, item, nullptr,
342
343 if( constraint.m_DisallowFlags
344 && constraint.GetSeverity() != RPT_SEVERITY_IGNORE )
345 {
346 reportDisallow( constraint );
347 }
348
349 // N.B. HOLE_PROXY is set/cleared on the item's flags for
350 // EvalRules to distinguish hole-specific disallow constraints.
351 // This is a non-atomic read-modify-write on m_flags, so this
352 // provider must run with each item processed by only one thread
353 // at a time (guaranteed by submit_loop's work partitioning).
354 if( item->HasHole() )
355 {
356 item->SetFlags( HOLE_PROXY );
357
358 constraint = m_drcEngine->EvalRules( DISALLOW_CONSTRAINT, item, nullptr, UNDEFINED_LAYER );
359
360 if( constraint.m_DisallowFlags
361 && constraint.GetSeverity() != RPT_SEVERITY_IGNORE )
362 {
363 reportDisallow( constraint );
364 }
365
366 item->ClearFlags( HOLE_PROXY );
367 }
368 }
369
370 itemsDone.fetch_add( 1 );
371 return 1;
372 };
373
374 auto itemFutures = tp.submit_loop( 0, itemCount, processItem, itemCount );
375
376 while( itemsDone < itemCount )
377 {
378 reportProgress( itemsDone, itemCount );
379
380 if( m_drcEngine->IsCancelled() )
381 {
382 for( auto& f : itemFutures )
383 f.wait();
384
385 break;
386 }
387
388 itemFutures.wait_for( std::chrono::milliseconds( 250 ) );
389 }
390
391 return !m_drcEngine->IsCancelled();
392}
393
394
395namespace detail
396{
398}
constexpr int ARC_LOW_DEF
Definition base_units.h:136
BOX2< VECTOR2I > BOX2I
Definition box2.h:927
PCB_LAYER_ID GetLayer() const override
Return the primary layer this item is on.
int GetDRCEpsilon() const
Return an epsilon which accounts for rounding errors, etc.
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
Definition board_item.h:84
FOOTPRINT * GetParentFootprint() const
virtual LSET GetLayerSet() const
Return a std::bitset of all layers on which the item physically resides.
Definition board_item.h:346
virtual std::shared_ptr< SHAPE > GetEffectiveShape(PCB_LAYER_ID aLayer=UNDEFINED_LAYER, FLASHING aFlash=FLASHING::DEFAULT, DRC_CONSTRAINT_T aUsage=NULL_CONSTRAINT) const
Some pad shapes can be complex (rounded/chamfered rectangle), even without considering custom shapes.
virtual bool HasHole() const
Definition board_item.h:207
Information pertinent to a Pcbnew printed circuit board.
Definition board.h:409
SHARDED_CACHE< PTR_PTR_LAYER_CACHE_KEY, bool > m_IntersectsKeepoutCache
Definition board.h:1822
int m_DRCMaxPhysicalClearance
Definition board.h:1859
std::unordered_map< ZONE *, std::unique_ptr< DRC_RTREE > > m_CopperZoneRTreeCache
Definition board.h:1832
BOARD_DESIGN_SETTINGS & GetDesignSettings() const
Definition board.cpp:1299
constexpr bool Intersects(const BOX2< Vec > &aRect) const
Definition box2.h:308
int m_DisallowFlags
Definition drc_rule.h:245
SEVERITY GetSeverity() const
Definition drc_rule.h:221
static std::shared_ptr< DRC_ITEM > Create(int aErrorCode)
Constructs a DRC_ITEM for the given error code.
Definition drc_item.cpp:444
Implement an R-tree for fast spatial and layer indexing of connectable items.
Definition drc_rtree.h:45
int QueryColliding(BOARD_ITEM *aRefItem, PCB_LAYER_ID aRefLayer, PCB_LAYER_ID aTargetLayer, std::function< bool(BOARD_ITEM *)> aFilter=nullptr, std::function< bool(BOARD_ITEM *)> aVisitor=nullptr, int aClearance=0) const
This is a fast test which essentially does bounding-box overlap given a worst-case clearance.
Definition drc_rtree.h:277
bool IsImplicit() const
Definition drc_rule.h:145
BOARD_ITEM * m_ImplicitItem
Definition drc_rule.h:154
virtual ~DRC_TEST_PROVIDER_DISALLOW()=default
virtual const wxString GetName() const override
virtual bool Run() override
Run this provider against the given PCB with configured options (if any).
virtual bool reportPhase(const wxString &aStageName)
int forEachGeometryItem(const std::vector< KICAD_T > &aTypes, const LSET &aLayers, const std::function< bool(BOARD_ITEM *)> &aFunc)
void reportViolation(std::shared_ptr< DRC_ITEM > &item, const VECTOR2I &aMarkerPos, int aMarkerLayer, const std::function< void(PCB_MARKER *)> &aPathGenerator=[](PCB_MARKER *){})
virtual bool reportProgress(size_t aCount, size_t aSize, size_t aDelta=1)
virtual VECTOR2I GetPosition() const
Definition eda_item.h:348
void SetFlags(EDA_ITEM_FLAGS aMask)
Definition eda_item.h:158
KICAD_T Type() const
Returns the type of object.
Definition eda_item.h:110
void ClearFlags(EDA_ITEM_FLAGS aMask=EDA_ITEM_ALL_FLAGS)
Definition eda_item.h:160
PCB_LAYER_ID ExtractLayer() const
Find the first set PCB_LAYER_ID.
Definition lset.cpp:538
static const LSET & AllLayersMask()
Definition lset.cpp:637
virtual LSET GetLayerSet() const override
Return a std::bitset of all layers on which the item physically resides.
std::shared_ptr< SHAPE > GetEffectiveShape(PCB_LAYER_ID aLayer=UNDEFINED_LAYER, FLASHING aFlash=FLASHING::DEFAULT, DRC_CONSTRAINT_T aUsage=NULL_CONSTRAINT) const override
Some pad shapes can be complex (rounded/chamfered rectangle), even without considering custom shapes.
Represent a set of closed polygons.
bool Collide(const SHAPE *aShape, int aClearance=0, int *aActual=nullptr, VECTOR2I *aLocation=nullptr) const override
Check if the boundary of shape (this) lies closer to the shape aShape than aClearance,...
void Deflate(int aAmount, CORNER_STRATEGY aCornerStrategy, int aMaxError)
void Fracture(bool aSimplify=true)
Convert a set of polygons with holes to a single outline with "slits"/"fractures" connecting the oute...
void Set(const KEY &aKey, const VALUE &aValue)
Handle a list of polygons defining a copper zone.
Definition zone.h:70
bool GetIsRuleArea() const
Accessors to parameters used in Rule Area zones:
Definition zone.h:807
bool GetDoNotAllowTracks() const
Definition zone.h:819
virtual LSET GetLayerSet() const override
Return a std::bitset of all layers on which the item physically resides.
Definition zone.h:133
bool HasKeepoutParametersSet() const
Accessor to determine if any keepout parameters are set.
Definition zone.h:798
bool GetDoNotAllowZoneFills() const
Definition zone.h:817
bool IsOnCopperLayer() const override
Definition zone.cpp:616
@ ALLOW_ACUTE_CORNERS
just inflate the polygon. Acute angles create spikes
@ DRCE_TEXT_ON_EDGECUTS
Definition drc_item.h:40
@ DRCE_ALLOWED_ITEMS
Definition drc_item.h:39
@ DISALLOW_CONSTRAINT
Definition drc_rule.h:71
@ CLEARANCE_CONSTRAINT
Definition drc_rule.h:51
#define _(s)
#define HOLE_PROXY
Indicates the BOARD_ITEM is a proxy for its hole.
PCB_LAYER_ID
A quick note on layer IDs:
Definition layer_ids.h:56
@ Edge_Cuts
Definition layer_ids.h:108
@ UNDEFINED_LAYER
Definition layer_ids.h:57
static DRC_REGISTER_TEST_PROVIDER< DRC_TEST_PROVIDER_ANNULAR_WIDTH > dummy
@ RPT_SEVERITY_IGNORE
const double epsilon
thread_pool & GetKiCadThreadPool()
Get a reference to the current thread pool.
static thread_pool * tp
BS::priority_thread_pool thread_pool
Definition thread_pool.h:27
constexpr KICAD_T BaseType(const KICAD_T aType)
Return the underlying type of the given type.
Definition typeinfo.h:259
@ PCB_TEXTBOX_T
class PCB_TEXTBOX, wrapped text on a layer
Definition typeinfo.h:85
@ PCB_ZONE_T
class ZONE, a copper pour area
Definition typeinfo.h:100
@ PCB_TEXT_T
class PCB_TEXT, text on a layer
Definition typeinfo.h:84
@ PCB_FIELD_T
class PCB_FIELD, text associated with a footprint property
Definition typeinfo.h:82
@ PCB_BARCODE_T
class PCB_BARCODE, a barcode (graphic item)
Definition typeinfo.h:93
@ PCB_ARC_T
class PCB_ARC, an arc track segment on a copper layer
Definition typeinfo.h:90
@ PCB_DIMENSION_T
class PCB_DIMENSION_BASE: abstract dimension meta-type
Definition typeinfo.h:92
@ PCB_TABLE_T
class PCB_TABLE, table of PCB_TABLECELLs
Definition typeinfo.h:86
@ PCB_TRACE_T
class PCB_TRACK, a track segment (segment on a copper layer)
Definition typeinfo.h:88
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:683