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->GetCopperZoneRTree( copperZone );
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 =
200 []( BOARD_ITEM* item ) -> bool
201 {
202 // Items that plot geometry onto Edge.Cuts corrupt the board outline.
203 // Reference images are excluded on purpose because they are never plotted.
204 if( item->Type() == PCB_FIELD_T
205 || item->Type() == PCB_TEXT_T
206 || item->Type() == PCB_TEXTBOX_T
207 || BaseType( item->Type() ) == PCB_TABLE_T
208 || item->Type() == PCB_BARCODE_T
209 || BaseType( item->Type() ) == PCB_DIMENSION_T )
210 {
211 return item->GetLayer() == Edge_Cuts;
212 }
213
214 return false;
215 };
216
217 auto processItem =
218 [&]( const int idx ) -> size_t
219 {
220 if( m_drcEngine->IsCancelled() )
221 {
222 itemsDone.fetch_add( 1 );
223 return 0;
224 }
225
226 bool testTextOnEdge = !m_drcEngine->IsErrorLimitExceeded( DRCE_TEXT_ON_EDGECUTS );
227 bool testDisallow = !m_drcEngine->IsErrorLimitExceeded( DRCE_ALLOWED_ITEMS );
228
229 if( !testTextOnEdge && !testDisallow )
230 {
231 itemsDone.fetch_add( 1 );
232 return 0;
233 }
234
235 BOARD_ITEM* item = allItems[idx];
236
237 if( testTextOnEdge && checkTextOnEdgeCuts( item ) )
238 {
239 std::shared_ptr<DRC_ITEM> drc = DRC_ITEM::Create( DRCE_TEXT_ON_EDGECUTS );
240 drc->SetItems( item );
242 }
243
244 if( testDisallow )
245 {
246 if( item->Type() == PCB_ZONE_T )
247 {
248 ZONE* zone = static_cast<ZONE*>( item );
249
250 if( zone->GetIsRuleArea() && zone->HasKeepoutParametersSet() )
251 {
252 itemsDone.fetch_add( 1 );
253 return 1;
254 }
255 }
256
257 item->ClearFlags( HOLE_PROXY );
258
259 if( item->Type() == PCB_TRACE_T || item->Type() == PCB_ARC_T )
260 {
261 PCB_TRACK* track = static_cast<PCB_TRACK*>( item );
262 PCB_LAYER_ID layer = track->GetLayer();
263
264 antiTrackKeepouts->QueryColliding( track, layer, layer,
265 [&]( BOARD_ITEM* other ) -> bool
266 {
267 return true;
268 },
269 [&]( BOARD_ITEM* other ) -> bool
270 {
271 std::shared_ptr<SHAPE> shape = track->GetEffectiveShape();
272 int dummyActual;
273 VECTOR2I pos;
274 SHAPE_POLY_SET zoneOutlineStorage;
275 SHAPE_POLY_SET* zoneOutline = &zoneOutlineStorage;
276
277 // GetBoardOutline() is expensive. Only use it in DRC where we have to.
278 if( other->GetParentFootprint() )
279 zoneOutlineStorage = static_cast<ZONE*>( other )->GetBoardOutline();
280 else
281 zoneOutline = static_cast<ZONE*>( other )->Outline();
282
283 if( zoneOutline->Collide( shape.get(), 0, &dummyActual, &pos ) )
284 {
285 std::shared_ptr<DRC_ITEM> drcItem = DRC_ITEM::Create( DRCE_ALLOWED_ITEMS );
286 drcItem->SetItems( track );
287 reportViolation( drcItem, pos, track->GetLayerSet().ExtractLayer() );
288 }
289
290 return !m_drcEngine->IsCancelled();
291 },
293 }
294
295 // Tracks and arcs against keepout areas that disallow tracks are already
296 // reported above via antiTrackKeepouts (which collides every crossing, not
297 // just one per rule match). Skip the track/arc case for implicit keepout
298 // rules here to avoid duplicate markers, but still let EvalRules produce
299 // markers for all other item types against implicit keepout rules.
300 bool isTrackOrArc = ( item->Type() == PCB_TRACE_T || item->Type() == PCB_ARC_T );
301
302 auto reportDisallow =
303 [&]( const DRC_CONSTRAINT& aConstraint )
304 {
305 DRC_RULE* rule = aConstraint.GetParentRule();
306
307 if( !rule )
308 return;
309
310 if( isTrackOrArc && rule->IsImplicit() )
311 return;
312
313 std::shared_ptr<DRC_ITEM> drcItem = DRC_ITEM::Create( DRCE_ALLOWED_ITEMS );
314 PCB_LAYER_ID layer = item->GetLayerSet().ExtractLayer();
315 VECTOR2I pos = item->GetPosition();
316
317 // Provide a better location for keepout area collisions by snapping to where
318 // the item actually crosses the keepout outline. Use the cached BOARD_ITEM*
319 // rather than a UUID lookup, since ResolveItem mutates an unsynchronized cache
320 // and this lambda runs inside the parallel DRC worker pool.
321 if( rule->IsImplicit() )
322 {
323 if( ZONE* keepout = dynamic_cast<ZONE*>( rule->m_ImplicitItem ) )
324 {
325 std::shared_ptr<SHAPE> shape = item->GetEffectiveShape( layer );
326 int dummyActual;
327
328 // This is only done when reporting collisions, so we can afford the
329 // more expensive GetBoardOutline().
330 SHAPE_POLY_SET keepoutOutline = keepout->GetBoardOutline();
331 keepoutOutline.Collide( shape.get(), 0, &dummyActual, &pos );
332 }
333 }
334
335 drcItem->SetErrorDetail( wxString::Format( wxS( "(%s)" ), aConstraint.GetName() ) );
336 drcItem->SetItems( item );
337 drcItem->SetViolatingRule( rule );
338 reportViolation( drcItem, pos, layer );
339 };
340
341 DRC_CONSTRAINT constraint = m_drcEngine->EvalRules( DISALLOW_CONSTRAINT, item, nullptr,
343
344 if( constraint.m_DisallowFlags
345 && constraint.GetSeverity() != RPT_SEVERITY_IGNORE )
346 {
347 reportDisallow( constraint );
348 }
349
350 // N.B. HOLE_PROXY is set/cleared on the item's flags for
351 // EvalRules to distinguish hole-specific disallow constraints.
352 // This is a non-atomic read-modify-write on m_flags, so this
353 // provider must run with each item processed by only one thread
354 // at a time (guaranteed by submit_loop's work partitioning).
355 if( item->HasHole() )
356 {
357 item->SetFlags( HOLE_PROXY );
358
359 constraint = m_drcEngine->EvalRules( DISALLOW_CONSTRAINT, item, nullptr, UNDEFINED_LAYER );
360
361 if( constraint.m_DisallowFlags
362 && constraint.GetSeverity() != RPT_SEVERITY_IGNORE )
363 {
364 reportDisallow( constraint );
365 }
366
367 item->ClearFlags( HOLE_PROXY );
368 }
369 }
370
371 itemsDone.fetch_add( 1 );
372 return 1;
373 };
374
375 auto itemFutures = tp.submit_loop( 0, itemCount, processItem, itemCount );
376
377 while( itemsDone < itemCount )
378 {
379 reportProgress( itemsDone, itemCount );
380
381 if( m_drcEngine->IsCancelled() )
382 {
383 for( auto& f : itemFutures )
384 f.wait();
385
386 break;
387 }
388
389 itemFutures.wait_for( std::chrono::milliseconds( 250 ) );
390 }
391
392 return !m_drcEngine->IsCancelled();
393}
394
395
396namespace detail
397{
399}
constexpr int ARC_LOW_DEF
Definition base_units.h:143
BOX2< VECTOR2I > BOX2I
Definition box2.h:914
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:85
FOOTPRINT * GetParentFootprint() const
virtual LSET GetLayerSet() const
Return a std::bitset of all layers on which the item physically resides.
Definition board_item.h:355
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:208
Information pertinent to a Pcbnew printed circuit board.
Definition board.h:411
SHARDED_CACHE< PTR_PTR_LAYER_CACHE_KEY, bool > m_IntersectsKeepoutCache
Definition board.h:1775
int m_DRCMaxPhysicalClearance
Definition board.h:1810
BOARD_DESIGN_SETTINGS & GetDesignSettings()
Definition board.cpp:1290
DRC_RTREE * GetCopperZoneRTree(ZONE *aZone) const
Look up a zone's filled-copper R-tree.
Definition board.h:1818
constexpr bool Intersects(const BOX2< Vec > &aRect) const
Definition box2.h:308
int m_DisallowFlags
Definition drc_rule.h:205
SEVERITY GetSeverity() const
Definition drc_rule.h:181
static std::shared_ptr< DRC_ITEM > Create(int aErrorCode)
Constructs a DRC_ITEM for the given error code.
Definition drc_item.cpp:492
Implement an R-tree for fast spatial and layer indexing of connectable items.
Definition drc_rtree.h:46
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:231
bool IsImplicit() const
Definition drc_rule.h:70
BOARD_ITEM * m_ImplicitItem
Definition drc_rule.h:79
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:832
bool GetDoNotAllowTracks() const
Definition zone.h:851
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:823
bool GetDoNotAllowZoneFills() const
Definition zone.h:849
bool IsOnCopperLayer() const override
Definition zone.cpp:650
@ ALLOW_ACUTE_CORNERS
just inflate the polygon. Acute angles create spikes
@ DISALLOW_CONSTRAINT
@ CLEARANCE_CONSTRAINT
@ DRCE_TEXT_ON_EDGECUTS
Definition drc_item.h:51
@ DRCE_ALLOWED_ITEMS
Definition drc_item.h:50
#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:260
@ 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:708