You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2216 lines
82 KiB

Clean up arc/circle polygonization. 1) For a while now we've been using a calculated seg count from a given maxError, and a correction factor to push the radius out so that all the error is outside the arc/circle. However, the second calculation (which pre-dates the first) is pretty much just the inverse of the first (and yields nothing more than maxError back). This is particularly sub-optimal given the cost of trig functions. 2) There are a lot of old optimizations to reduce segcounts in certain situations, someting that our error-based calculation compensates for anyway. (Smaller radii need fewer segments to meet the maxError condition.) But perhaps more importantly we now surface maxError in the UI and we don't really want to call it "Max deviation except when it's not". 3) We were also clamping the segCount twice: once in the calculation routine and once in most of it's callers. Furthermore, the caller clamping was inconsistent (both in being done and in the clamping value). We now clamp only in the calculation routine. 4) There's no reason to use the correction factors in the 3Dviewer; it's just a visualization and whether the polygonization error is inside or outside the shape isn't really material. 5) The arc-correction-disabling stuff (used for solder mask layer) was somewhat fragile in that it depended on the caller to turn it back on afterwards. It's now only exposed as a RAII object which automatically cleans up when it goes out of scope. 6) There were also bugs in a couple of the polygonization routines where we'd accumulate round-off error in adding up the segments and end up with an overly long last segment (which of course would voilate the error max). This was the cause of the linked bug and also some issues with vias that we had fudged in the past with extra clearance. Fixes https://gitlab.com/kicad/code/kicad/issues/5567
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
Clean up arc/circle polygonization. 1) For a while now we've been using a calculated seg count from a given maxError, and a correction factor to push the radius out so that all the error is outside the arc/circle. However, the second calculation (which pre-dates the first) is pretty much just the inverse of the first (and yields nothing more than maxError back). This is particularly sub-optimal given the cost of trig functions. 2) There are a lot of old optimizations to reduce segcounts in certain situations, someting that our error-based calculation compensates for anyway. (Smaller radii need fewer segments to meet the maxError condition.) But perhaps more importantly we now surface maxError in the UI and we don't really want to call it "Max deviation except when it's not". 3) We were also clamping the segCount twice: once in the calculation routine and once in most of it's callers. Furthermore, the caller clamping was inconsistent (both in being done and in the clamping value). We now clamp only in the calculation routine. 4) There's no reason to use the correction factors in the 3Dviewer; it's just a visualization and whether the polygonization error is inside or outside the shape isn't really material. 5) The arc-correction-disabling stuff (used for solder mask layer) was somewhat fragile in that it depended on the caller to turn it back on afterwards. It's now only exposed as a RAII object which automatically cleans up when it goes out of scope. 6) There were also bugs in a couple of the polygonization routines where we'd accumulate round-off error in adding up the segments and end up with an overly long last segment (which of course would voilate the error max). This was the cause of the linked bug and also some issues with vias that we had fudged in the past with extra clearance. Fixes https://gitlab.com/kicad/code/kicad/issues/5567
5 years ago
  1. /*
  2. * This program source code file is part of KiCad, a free EDA CAD application.
  3. *
  4. * Copyright (C) 2014-2017 CERN
  5. * Copyright (C) 2014-2023 KiCad Developers, see AUTHORS.txt for contributors.
  6. * @author Tomasz Włostowski <tomasz.wlostowski@cern.ch>
  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,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU 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, you may find one here:
  20. * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  21. * or you may search the http://www.gnu.org website for the version 2 license,
  22. * or you may write to the Free Software Foundation, Inc.,
  23. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
  24. */
  25. #include <future>
  26. #include <core/kicad_algo.h>
  27. #include <advanced_config.h>
  28. #include <board.h>
  29. #include <board_design_settings.h>
  30. #include <zone.h>
  31. #include <footprint.h>
  32. #include <pad.h>
  33. #include <pcb_target.h>
  34. #include <pcb_track.h>
  35. #include <pcb_text.h>
  36. #include <pcb_textbox.h>
  37. #include <connectivity/connectivity_data.h>
  38. #include <convert_basic_shapes_to_polygon.h>
  39. #include <board_commit.h>
  40. #include <progress_reporter.h>
  41. #include <geometry/shape_poly_set.h>
  42. #include <geometry/convex_hull.h>
  43. #include <geometry/geometry_utils.h>
  44. #include <confirm.h>
  45. #include <core/thread_pool.h>
  46. #include <math/util.h> // for KiROUND
  47. #include "zone_filler.h"
  48. ZONE_FILLER::ZONE_FILLER( BOARD* aBoard, COMMIT* aCommit ) :
  49. m_board( aBoard ),
  50. m_brdOutlinesValid( false ),
  51. m_commit( aCommit ),
  52. m_progressReporter( nullptr ),
  53. m_maxError( ARC_HIGH_DEF ),
  54. m_worstClearance( 0 )
  55. {
  56. // To enable add "DebugZoneFiller=1" to kicad_advanced settings file.
  57. m_debugZoneFiller = ADVANCED_CFG::GetCfg().m_DebugZoneFiller;
  58. }
  59. ZONE_FILLER::~ZONE_FILLER()
  60. {
  61. }
  62. void ZONE_FILLER::SetProgressReporter( PROGRESS_REPORTER* aReporter )
  63. {
  64. m_progressReporter = aReporter;
  65. wxASSERT_MSG( m_commit, wxT( "ZONE_FILLER must have a valid commit to call "
  66. "SetProgressReporter" ) );
  67. }
  68. /**
  69. * Fills the given list of zones.
  70. *
  71. * NB: Invalidates connectivity - it is up to the caller to obtain a lock on the connectivity
  72. * data before calling Fill to prevent access to stale data by other coroutines (for example,
  73. * ratsnest redraw). This will generally be required if a UI-based progress reporter has been
  74. * installed.
  75. *
  76. * Caller is also responsible for re-building connectivity afterwards.
  77. */
  78. bool ZONE_FILLER::Fill( std::vector<ZONE*>& aZones, bool aCheck, wxWindow* aParent )
  79. {
  80. std::lock_guard<KISPINLOCK> lock( m_board->GetConnectivity()->GetLock() );
  81. std::vector<std::pair<ZONE*, PCB_LAYER_ID>> toFill;
  82. std::map<std::pair<ZONE*, PCB_LAYER_ID>, MD5_HASH> oldFillHashes;
  83. std::map<ZONE*, std::map<PCB_LAYER_ID, ISOLATED_ISLANDS>> isolatedIslandsMap;
  84. std::shared_ptr<CONNECTIVITY_DATA> connectivity = m_board->GetConnectivity();
  85. // Rebuild (from scratch, ignoring dirty flags) just in case. This really needs to be reliable.
  86. connectivity->ClearRatsnest();
  87. connectivity->Build( m_board, m_progressReporter );
  88. m_worstClearance = m_board->GetMaxClearanceValue();
  89. if( m_progressReporter )
  90. {
  91. m_progressReporter->Report( aCheck ? _( "Checking zone fills..." )
  92. : _( "Building zone fills..." ) );
  93. m_progressReporter->SetMaxProgress( aZones.size() );
  94. m_progressReporter->KeepRefreshing();
  95. }
  96. // The board outlines is used to clip solid areas inside the board (when outlines are valid)
  97. m_boardOutline.RemoveAllContours();
  98. m_brdOutlinesValid = m_board->GetBoardPolygonOutlines( m_boardOutline );
  99. // Update and cache zone bounding boxes and pad effective shapes so that we don't have to
  100. // make them thread-safe.
  101. //
  102. for( ZONE* zone : m_board->Zones() )
  103. zone->CacheBoundingBox();
  104. for( FOOTPRINT* footprint : m_board->Footprints() )
  105. {
  106. for( PAD* pad : footprint->Pads() )
  107. {
  108. if( pad->IsDirty() )
  109. {
  110. pad->BuildEffectiveShapes( UNDEFINED_LAYER );
  111. pad->BuildEffectivePolygon();
  112. }
  113. }
  114. for( ZONE* zone : footprint->Zones() )
  115. zone->CacheBoundingBox();
  116. // Rules may depend on insideCourtyard() or other expressions
  117. footprint->BuildCourtyardCaches();
  118. }
  119. LSET boardCuMask = m_board->GetEnabledLayers() & LSET::AllCuMask();
  120. auto findHighestPriorityZone = [&]( const BOX2I& aBBox, const PCB_LAYER_ID aItemLayer,
  121. const int aNetcode,
  122. const std::function<bool( const ZONE* )> aTestFn ) -> ZONE*
  123. {
  124. unsigned highestPriority = 0;
  125. ZONE* highestPriorityZone = nullptr;
  126. for( ZONE* zone : m_board->Zones() )
  127. {
  128. // Rule areas are not filled
  129. if( zone->GetIsRuleArea() )
  130. continue;
  131. if( zone->GetAssignedPriority() < highestPriority )
  132. continue;
  133. if( !zone->IsOnLayer( aItemLayer ) )
  134. continue;
  135. // Degenerate zones will cause trouble; skip them
  136. if( zone->GetNumCorners() <= 2 )
  137. continue;
  138. if( !zone->GetBoundingBox().Intersects( aBBox ) )
  139. continue;
  140. if( !aTestFn( zone ) )
  141. continue;
  142. // Prefer highest priority and matching netcode
  143. if( zone->GetAssignedPriority() > highestPriority || zone->GetNetCode() == aNetcode )
  144. {
  145. highestPriority = zone->GetAssignedPriority();
  146. highestPriorityZone = zone;
  147. }
  148. }
  149. return highestPriorityZone;
  150. };
  151. auto isInPourKeepoutArea = [&]( const BOX2I& aBBox, const PCB_LAYER_ID aItemLayer,
  152. const VECTOR2I aTestPoint ) -> bool
  153. {
  154. for( ZONE* zone : m_board->Zones() )
  155. {
  156. if( !zone->GetIsRuleArea() )
  157. continue;
  158. if( !zone->GetDoNotAllowCopperPour() )
  159. continue;
  160. if( !zone->IsOnLayer( aItemLayer ) )
  161. continue;
  162. // Degenerate zones will cause trouble; skip them
  163. if( zone->GetNumCorners() <= 2 )
  164. continue;
  165. if( !zone->GetBoundingBox().Intersects( aBBox ) )
  166. continue;
  167. if( zone->Outline()->Contains( aTestPoint ) )
  168. return true;
  169. }
  170. return false;
  171. };
  172. // Determine state of conditional via flashing
  173. for( PCB_TRACK* track : m_board->Tracks() )
  174. {
  175. if( track->Type() == PCB_VIA_T )
  176. {
  177. PCB_VIA* via = static_cast<PCB_VIA*>( track );
  178. via->ClearZoneLayerOverrides();
  179. if( !via->GetRemoveUnconnected() )
  180. continue;
  181. BOX2I bbox = via->GetBoundingBox();
  182. VECTOR2I center = via->GetPosition();
  183. int testRadius = via->GetDrillValue() / 2 + 1;
  184. unsigned netcode = via->GetNetCode();
  185. LSET layers = via->GetLayerSet() & boardCuMask;
  186. // Checking if the via hole touches the zone outline
  187. auto viaTestFn = [&]( const ZONE* aZone ) -> bool
  188. {
  189. return aZone->Outline()->Contains( center, -1, testRadius );
  190. };
  191. for( PCB_LAYER_ID layer : layers.Seq() )
  192. {
  193. if( !via->ConditionallyFlashed( layer ) )
  194. continue;
  195. if( isInPourKeepoutArea( bbox, layer, center ) )
  196. {
  197. via->SetZoneLayerOverride( layer, ZLO_FORCE_NO_ZONE_CONNECTION );
  198. }
  199. else
  200. {
  201. ZONE* zone = findHighestPriorityZone( bbox, layer, netcode, viaTestFn );
  202. if( zone && zone->GetNetCode() == via->GetNetCode() )
  203. via->SetZoneLayerOverride( layer, ZLO_FORCE_FLASHED );
  204. else
  205. via->SetZoneLayerOverride( layer, ZLO_FORCE_NO_ZONE_CONNECTION );
  206. }
  207. }
  208. }
  209. }
  210. // Determine state of conditional pad flashing
  211. for( FOOTPRINT* footprint : m_board->Footprints() )
  212. {
  213. for( PAD* pad : footprint->Pads() )
  214. {
  215. pad->ClearZoneLayerOverrides();
  216. if( !pad->GetRemoveUnconnected() )
  217. continue;
  218. BOX2I bbox = pad->GetBoundingBox();
  219. VECTOR2I center = pad->GetPosition();
  220. unsigned netcode = pad->GetNetCode();
  221. LSET layers = pad->GetLayerSet() & boardCuMask;
  222. auto padTestFn = [&]( const ZONE* aZone ) -> bool
  223. {
  224. return aZone->Outline()->Contains( center );
  225. };
  226. for( PCB_LAYER_ID layer : layers.Seq() )
  227. {
  228. if( !pad->ConditionallyFlashed( layer ) )
  229. continue;
  230. if( isInPourKeepoutArea( bbox, layer, center ) )
  231. {
  232. pad->SetZoneLayerOverride( layer, ZLO_FORCE_NO_ZONE_CONNECTION );
  233. }
  234. else
  235. {
  236. ZONE* zone = findHighestPriorityZone( bbox, layer, netcode, padTestFn );
  237. if( zone && zone->GetNetCode() == pad->GetNetCode() )
  238. pad->SetZoneLayerOverride( layer, ZLO_FORCE_FLASHED );
  239. else
  240. pad->SetZoneLayerOverride( layer, ZLO_FORCE_NO_ZONE_CONNECTION );
  241. }
  242. }
  243. }
  244. }
  245. for( ZONE* zone : aZones )
  246. {
  247. // Rule areas are not filled
  248. if( zone->GetIsRuleArea() )
  249. continue;
  250. // Degenerate zones will cause trouble; skip them
  251. if( zone->GetNumCorners() <= 2 )
  252. continue;
  253. if( m_commit )
  254. m_commit->Modify( zone );
  255. // calculate the hash value for filled areas. it will be used later to know if the
  256. // current filled areas are up to date
  257. for( PCB_LAYER_ID layer : zone->GetLayerSet().Seq() )
  258. {
  259. zone->BuildHashValue( layer );
  260. oldFillHashes[ { zone, layer } ] = zone->GetHashValue( layer );
  261. // Add the zone to the list of zones to test or refill
  262. toFill.emplace_back( std::make_pair( zone, layer ) );
  263. isolatedIslandsMap[ zone ][ layer ] = ISOLATED_ISLANDS();
  264. }
  265. // Remove existing fill first to prevent drawing invalid polygons on some platforms
  266. zone->UnFill();
  267. }
  268. auto check_fill_dependency =
  269. [&]( ZONE* aZone, PCB_LAYER_ID aLayer, ZONE* aOtherZone ) -> bool
  270. {
  271. // Check to see if we have to knock-out the filled areas of a higher-priority
  272. // zone. If so we have to wait until said zone is filled before we can fill.
  273. // If the other zone is already filled on the requested layer then we're
  274. // good-to-go
  275. if( aOtherZone->GetFillFlag( aLayer ) )
  276. return false;
  277. // Even if keepouts exclude copper pours, the exclusion is by outline rather than
  278. // filled area, so we're good-to-go here too
  279. if( aOtherZone->GetIsRuleArea() )
  280. return false;
  281. // If the other zone is never going to be filled then don't wait for it
  282. if( aOtherZone->GetNumCorners() <= 2 )
  283. return false;
  284. // If the zones share no common layers
  285. if( !aOtherZone->GetLayerSet().test( aLayer ) )
  286. return false;
  287. if( aZone->HigherPriority( aOtherZone ) )
  288. return false;
  289. // Same-net zones always use outlines to produce determinate results
  290. if( aOtherZone->SameNet( aZone ) )
  291. return false;
  292. // A higher priority zone is found: if we intersect and it's not filled yet
  293. // then we have to wait.
  294. BOX2I inflatedBBox = aZone->GetBoundingBox();
  295. inflatedBBox.Inflate( m_worstClearance );
  296. if( !inflatedBBox.Intersects( aOtherZone->GetBoundingBox() ) )
  297. return false;
  298. return aZone->Outline()->Collide( aOtherZone->Outline(), m_worstClearance );
  299. };
  300. auto fill_lambda =
  301. [&]( std::pair<ZONE*, PCB_LAYER_ID> aFillItem ) -> int
  302. {
  303. PCB_LAYER_ID layer = aFillItem.second;
  304. ZONE* zone = aFillItem.first;
  305. bool canFill = true;
  306. // Check for any fill dependencies. If our zone needs to be clipped by
  307. // another zone then we can't fill until that zone is filled.
  308. for( ZONE* otherZone : aZones )
  309. {
  310. if( otherZone == zone )
  311. continue;
  312. if( check_fill_dependency( zone, layer, otherZone ) )
  313. {
  314. canFill = false;
  315. break;
  316. }
  317. }
  318. if( m_progressReporter && m_progressReporter->IsCancelled() )
  319. return 0;
  320. if( !canFill )
  321. return 0;
  322. // Now we're ready to fill.
  323. {
  324. std::unique_lock<std::mutex> zoneLock( zone->GetLock(), std::try_to_lock );
  325. if( !zoneLock.owns_lock() )
  326. return 0;
  327. SHAPE_POLY_SET fillPolys;
  328. if( !fillSingleZone( zone, layer, fillPolys ) )
  329. return 0;
  330. zone->SetFilledPolysList( layer, fillPolys );
  331. }
  332. if( m_progressReporter )
  333. m_progressReporter->AdvanceProgress();
  334. return 1;
  335. };
  336. auto tesselate_lambda =
  337. [&]( std::pair<ZONE*, PCB_LAYER_ID> aFillItem ) -> int
  338. {
  339. if( m_progressReporter && m_progressReporter->IsCancelled() )
  340. return 0;
  341. PCB_LAYER_ID layer = aFillItem.second;
  342. ZONE* zone = aFillItem.first;
  343. {
  344. std::unique_lock<std::mutex> zoneLock( zone->GetLock(), std::try_to_lock );
  345. if( !zoneLock.owns_lock() )
  346. return 0;
  347. zone->CacheTriangulation( layer );
  348. zone->SetFillFlag( layer, true );
  349. }
  350. return 1;
  351. };
  352. // Calculate the copper fills (NB: this is multi-threaded)
  353. //
  354. std::vector<std::pair<std::future<int>, int>> returns;
  355. returns.reserve( toFill.size() );
  356. size_t finished = 0;
  357. bool cancelled = false;
  358. thread_pool& tp = GetKiCadThreadPool();
  359. for( const std::pair<ZONE*, PCB_LAYER_ID>& fillItem : toFill )
  360. returns.emplace_back( std::make_pair( tp.submit( fill_lambda, fillItem ), 0 ) );
  361. while( !cancelled && finished != 2 * toFill.size() )
  362. {
  363. for( size_t ii = 0; ii < returns.size(); ++ii )
  364. {
  365. auto& ret = returns[ii];
  366. if( ret.second > 1 )
  367. continue;
  368. std::future_status status = ret.first.wait_for( std::chrono::seconds( 0 ) );
  369. if( status == std::future_status::ready )
  370. {
  371. if( ret.first.get() ) // lambda completed
  372. {
  373. ++finished;
  374. ret.second++; // go to next step
  375. }
  376. if( !cancelled )
  377. {
  378. // Queue the next step (will re-queue the existing step if it didn't complete)
  379. if( ret.second == 0 )
  380. returns[ii].first = tp.submit( fill_lambda, toFill[ii] );
  381. else if( ret.second == 1 )
  382. returns[ii].first = tp.submit( tesselate_lambda, toFill[ii] );
  383. }
  384. }
  385. }
  386. std::this_thread::sleep_for( std::chrono::milliseconds( 100 ) );
  387. if( m_progressReporter )
  388. {
  389. m_progressReporter->KeepRefreshing();
  390. if( m_progressReporter->IsCancelled() )
  391. cancelled = true;
  392. }
  393. }
  394. // Make sure that all futures have finished.
  395. // This can happen when the user cancels the above operation
  396. for( auto& ret : returns )
  397. {
  398. if( ret.first.valid() )
  399. {
  400. std::future_status status = ret.first.wait_for( std::chrono::seconds( 0 ) );
  401. while( status != std::future_status::ready )
  402. {
  403. if( m_progressReporter )
  404. m_progressReporter->KeepRefreshing();
  405. status = ret.first.wait_for( std::chrono::milliseconds( 100 ) );
  406. }
  407. }
  408. }
  409. // Now update the connectivity to check for isolated copper islands
  410. // (NB: FindIsolatedCopperIslands() is multi-threaded)
  411. //
  412. if( m_progressReporter )
  413. {
  414. if( m_progressReporter->IsCancelled() )
  415. return false;
  416. m_progressReporter->AdvancePhase();
  417. m_progressReporter->Report( _( "Removing isolated copper islands..." ) );
  418. m_progressReporter->KeepRefreshing();
  419. }
  420. connectivity->SetProgressReporter( m_progressReporter );
  421. connectivity->FillIsolatedIslandsMap( isolatedIslandsMap );
  422. connectivity->SetProgressReporter( nullptr );
  423. if( m_progressReporter && m_progressReporter->IsCancelled() )
  424. return false;
  425. for( ZONE* zone : aZones )
  426. {
  427. // Keepout zones are not filled
  428. if( zone->GetIsRuleArea() )
  429. continue;
  430. zone->SetIsFilled( true );
  431. }
  432. // Now remove isolated copper islands according to the isolated islands strategy assigned
  433. // by the user (always, never, below-certain-size).
  434. //
  435. for( const auto& [ zone, zoneIslands ] : isolatedIslandsMap )
  436. {
  437. // If *all* the polygons are islands, do not remove any of them
  438. bool allIslands = true;
  439. for( const auto& [ layer, layerIslands ] : zoneIslands )
  440. {
  441. if( layerIslands.m_IsolatedOutlines.size()
  442. != static_cast<size_t>( zone->GetFilledPolysList( layer )->OutlineCount() ) )
  443. {
  444. allIslands = false;
  445. break;
  446. }
  447. }
  448. if( allIslands )
  449. continue;
  450. for( const auto& [ layer, layerIslands ] : zoneIslands )
  451. {
  452. if( m_debugZoneFiller && LSET::InternalCuMask().Contains( layer ) )
  453. continue;
  454. if( layerIslands.m_IsolatedOutlines.empty() )
  455. continue;
  456. std::vector<int> islands = layerIslands.m_IsolatedOutlines;
  457. // The list of polygons to delete must be explored from last to first in list,
  458. // to allow deleting a polygon from list without breaking the remaining of the list
  459. std::sort( islands.begin(), islands.end(), std::greater<int>() );
  460. std::shared_ptr<SHAPE_POLY_SET> poly = zone->GetFilledPolysList( layer );
  461. long long int minArea = zone->GetMinIslandArea();
  462. ISLAND_REMOVAL_MODE mode = zone->GetIslandRemovalMode();
  463. for( int idx : islands )
  464. {
  465. SHAPE_LINE_CHAIN& outline = poly->Outline( idx );
  466. if( mode == ISLAND_REMOVAL_MODE::ALWAYS )
  467. poly->DeletePolygonAndTriangulationData( idx, false );
  468. else if ( mode == ISLAND_REMOVAL_MODE::AREA && outline.Area( true ) < minArea )
  469. poly->DeletePolygonAndTriangulationData( idx, false );
  470. else
  471. zone->SetIsIsland( layer, idx );
  472. }
  473. poly->UpdateTriangulationDataHash();
  474. zone->CalculateFilledArea();
  475. if( m_progressReporter && m_progressReporter->IsCancelled() )
  476. return false;
  477. }
  478. }
  479. // Now remove islands which are either outside the board edge or fail to meet the minimum
  480. // area requirements
  481. using island_check_return = std::vector<std::pair<std::shared_ptr<SHAPE_POLY_SET>, int>>;
  482. std::vector<std::pair<std::shared_ptr<SHAPE_POLY_SET>, double>> polys_to_check;
  483. // rough estimate to save re-allocation time
  484. polys_to_check.reserve( m_board->GetCopperLayerCount() * aZones.size() );
  485. for( ZONE* zone : aZones )
  486. {
  487. LSET zoneCopperLayers = zone->GetLayerSet() & LSET::AllCuMask( MAX_CU_LAYERS );
  488. // Min-thickness is the web thickness. On the other hand, a blob min-thickness by
  489. // min-thickness is not useful. Since there's no obvious definition of web vs. blob, we
  490. // arbitrarily choose "at least 3X the area".
  491. double minArea = (double) zone->GetMinThickness() * zone->GetMinThickness() * 3;
  492. for( PCB_LAYER_ID layer : zoneCopperLayers.Seq() )
  493. {
  494. if( m_debugZoneFiller && LSET::InternalCuMask().Contains( layer ) )
  495. continue;
  496. polys_to_check.emplace_back( zone->GetFilledPolysList( layer ), minArea );
  497. }
  498. }
  499. auto island_lambda =
  500. [&]( int aStart, int aEnd ) -> island_check_return
  501. {
  502. island_check_return retval;
  503. for( int ii = aStart; ii < aEnd && !cancelled; ++ii )
  504. {
  505. auto [poly, minArea] = polys_to_check[ii];
  506. for( int jj = poly->OutlineCount() - 1; jj >= 0; jj-- )
  507. {
  508. SHAPE_POLY_SET island;
  509. SHAPE_POLY_SET intersection;
  510. const SHAPE_LINE_CHAIN& test_poly = poly->Polygon( jj ).front();
  511. double island_area = test_poly.Area();
  512. if( island_area < minArea )
  513. continue;
  514. island.AddOutline( test_poly );
  515. intersection.BooleanIntersection( m_boardOutline, island,
  516. SHAPE_POLY_SET::POLYGON_MODE::PM_FAST );
  517. // Nominally, all of these areas should be either inside or outside the
  518. // board outline. So this test should be able to just compare areas (if
  519. // they are equal, you are inside). But in practice, we sometimes have
  520. // slight overlap at the edges, so testing against half-size area acts as
  521. // a fail-safe.
  522. if( intersection.Area() < island_area / 2.0 )
  523. retval.emplace_back( poly, jj );
  524. }
  525. }
  526. return retval;
  527. };
  528. auto island_returns = tp.parallelize_loop( 0, polys_to_check.size(), island_lambda );
  529. cancelled = false;
  530. // Allow island removal threads to finish
  531. for( size_t ii = 0; ii < island_returns.size(); ++ii )
  532. {
  533. std::future<island_check_return>& ret = island_returns[ii];
  534. if( ret.valid() )
  535. {
  536. std::future_status status = ret.wait_for( std::chrono::seconds( 0 ) );
  537. while( status != std::future_status::ready )
  538. {
  539. if( m_progressReporter )
  540. {
  541. m_progressReporter->KeepRefreshing();
  542. if( m_progressReporter->IsCancelled() )
  543. cancelled = true;
  544. }
  545. status = ret.wait_for( std::chrono::milliseconds( 100 ) );
  546. }
  547. }
  548. }
  549. if( cancelled )
  550. return false;
  551. for( size_t ii = 0; ii < island_returns.size(); ++ii )
  552. {
  553. std::future<island_check_return>& ret = island_returns[ii];
  554. if( ret.valid() )
  555. {
  556. for( auto& action_item : ret.get() )
  557. action_item.first->DeletePolygonAndTriangulationData( action_item.second, true );
  558. }
  559. }
  560. for( ZONE* zone : aZones )
  561. zone->CalculateFilledArea();
  562. if( aCheck )
  563. {
  564. bool outOfDate = false;
  565. for( ZONE* zone : aZones )
  566. {
  567. // Keepout zones are not filled
  568. if( zone->GetIsRuleArea() )
  569. continue;
  570. for( PCB_LAYER_ID layer : zone->GetLayerSet().Seq() )
  571. {
  572. zone->BuildHashValue( layer );
  573. if( oldFillHashes[ { zone, layer } ] != zone->GetHashValue( layer ) )
  574. outOfDate = true;
  575. }
  576. }
  577. if( outOfDate )
  578. {
  579. KIDIALOG dlg( aParent, _( "Zone fills are out-of-date. Refill?" ),
  580. _( "Confirmation" ), wxOK | wxCANCEL | wxICON_WARNING );
  581. dlg.SetOKCancelLabels( _( "Refill" ), _( "Continue without Refill" ) );
  582. dlg.DoNotShowCheckbox( __FILE__, __LINE__ );
  583. if( dlg.ShowModal() == wxID_CANCEL )
  584. return false;
  585. }
  586. else
  587. {
  588. // No need to commit something that hasn't changed (and committing will set
  589. // the modified flag).
  590. return false;
  591. }
  592. }
  593. if( m_progressReporter )
  594. {
  595. if( m_progressReporter->IsCancelled() )
  596. return false;
  597. m_progressReporter->AdvancePhase();
  598. m_progressReporter->KeepRefreshing();
  599. }
  600. return true;
  601. }
  602. /**
  603. * Add a knockout for a pad. The knockout is 'aGap' larger than the pad (which might be
  604. * either the thermal clearance or the electrical clearance).
  605. */
  606. void ZONE_FILLER::addKnockout( PAD* aPad, PCB_LAYER_ID aLayer, int aGap, SHAPE_POLY_SET& aHoles )
  607. {
  608. if( aPad->GetShape() == PAD_SHAPE::CUSTOM )
  609. {
  610. SHAPE_POLY_SET poly;
  611. aPad->TransformShapeToPolygon( poly, aLayer, aGap, m_maxError, ERROR_OUTSIDE );
  612. // the pad shape in zone can be its convex hull or the shape itself
  613. if( aPad->GetCustomShapeInZoneOpt() == CUST_PAD_SHAPE_IN_ZONE_CONVEXHULL )
  614. {
  615. std::vector<VECTOR2I> convex_hull;
  616. BuildConvexHull( convex_hull, poly );
  617. aHoles.NewOutline();
  618. for( const VECTOR2I& pt : convex_hull )
  619. aHoles.Append( pt );
  620. }
  621. else
  622. aHoles.Append( poly );
  623. }
  624. else
  625. {
  626. aPad->TransformShapeToPolygon( aHoles, aLayer, aGap, m_maxError, ERROR_OUTSIDE );
  627. }
  628. }
  629. /**
  630. * Add a knockout for a pad's hole.
  631. */
  632. void ZONE_FILLER::addHoleKnockout( PAD* aPad, int aGap, SHAPE_POLY_SET& aHoles )
  633. {
  634. aPad->TransformHoleToPolygon( aHoles, aGap, m_maxError, ERROR_OUTSIDE );
  635. }
  636. /**
  637. * Add a knockout for a graphic item. The knockout is 'aGap' larger than the item (which
  638. * might be either the electrical clearance or the board edge clearance).
  639. */
  640. void ZONE_FILLER::addKnockout( BOARD_ITEM* aItem, PCB_LAYER_ID aLayer, int aGap,
  641. bool aIgnoreLineWidth, SHAPE_POLY_SET& aHoles )
  642. {
  643. switch( aItem->Type() )
  644. {
  645. case PCB_FIELD_T:
  646. case PCB_TEXT_T:
  647. {
  648. PCB_TEXT* text = static_cast<PCB_TEXT*>( aItem );
  649. if( text->IsVisible() )
  650. {
  651. if( text->IsKnockout() )
  652. {
  653. int antiGap = -m_maxError * 2; // Don't leave gaps around knockout text
  654. text->TransformShapeToPolygon( aHoles, aLayer, antiGap, m_maxError, ERROR_OUTSIDE );
  655. }
  656. else
  657. {
  658. text->TransformShapeToPolygon( aHoles, aLayer, aGap, m_maxError, ERROR_OUTSIDE );
  659. }
  660. }
  661. break;
  662. }
  663. case PCB_TEXTBOX_T:
  664. {
  665. PCB_TEXTBOX* textbox = static_cast<PCB_TEXTBOX*>( aItem );
  666. if( textbox->IsVisible() )
  667. textbox->TransformShapeToPolygon( aHoles, aLayer, aGap, m_maxError, ERROR_OUTSIDE );
  668. break;
  669. }
  670. case PCB_SHAPE_T:
  671. case PCB_TARGET_T:
  672. aItem->TransformShapeToPolygon( aHoles, aLayer, aGap, m_maxError, ERROR_OUTSIDE,
  673. aIgnoreLineWidth );
  674. break;
  675. default:
  676. break;
  677. }
  678. }
  679. /**
  680. * Removes thermal reliefs from the shape for any pads connected to the zone. Does NOT add
  681. * in spokes, which must be done later.
  682. */
  683. void ZONE_FILLER::knockoutThermalReliefs( const ZONE* aZone, PCB_LAYER_ID aLayer,
  684. SHAPE_POLY_SET& aFill,
  685. std::vector<PAD*>& aThermalConnectionPads,
  686. std::vector<PAD*>& aNoConnectionPads )
  687. {
  688. BOARD_DESIGN_SETTINGS& bds = m_board->GetDesignSettings();
  689. ZONE_CONNECTION connection;
  690. DRC_CONSTRAINT constraint;
  691. int padClearance;
  692. int holeClearance;
  693. SHAPE_POLY_SET holes;
  694. for( FOOTPRINT* footprint : m_board->Footprints() )
  695. {
  696. for( PAD* pad : footprint->Pads() )
  697. {
  698. BOX2I padBBox = pad->GetBoundingBox();
  699. padBBox.Inflate( m_worstClearance );
  700. if( !padBBox.Intersects( aZone->GetBoundingBox() ) )
  701. continue;
  702. if( pad->GetNetCode() != aZone->GetNetCode()
  703. || pad->GetNetCode() <= 0
  704. || pad->GetZoneLayerOverride( aLayer ) == ZLO_FORCE_NO_ZONE_CONNECTION )
  705. {
  706. // collect these for knockout in buildCopperItemClearances()
  707. aNoConnectionPads.push_back( pad );
  708. continue;
  709. }
  710. if( aZone->IsTeardropArea() )
  711. {
  712. connection = ZONE_CONNECTION::FULL;
  713. }
  714. else
  715. {
  716. constraint = bds.m_DRCEngine->EvalZoneConnection( pad, aZone, aLayer );
  717. connection = constraint.m_ZoneConnection;
  718. }
  719. switch( connection )
  720. {
  721. case ZONE_CONNECTION::THERMAL:
  722. constraint = bds.m_DRCEngine->EvalRules( THERMAL_RELIEF_GAP_CONSTRAINT, pad, aZone,
  723. aLayer );
  724. padClearance = constraint.GetValue().Min();
  725. if( pad->CanFlashLayer( aLayer ) )
  726. {
  727. aThermalConnectionPads.push_back( pad );
  728. addKnockout( pad, aLayer, padClearance, holes );
  729. }
  730. else if( pad->GetDrillSize().x > 0 )
  731. {
  732. pad->TransformHoleToPolygon( holes, padClearance, m_maxError, ERROR_OUTSIDE );
  733. }
  734. break;
  735. case ZONE_CONNECTION::NONE:
  736. constraint = bds.m_DRCEngine->EvalRules( PHYSICAL_CLEARANCE_CONSTRAINT, pad,
  737. aZone, aLayer );
  738. if( constraint.GetValue().Min() > aZone->GetLocalClearance() )
  739. padClearance = constraint.GetValue().Min();
  740. else
  741. padClearance = aZone->GetLocalClearance();
  742. if( pad->FlashLayer( aLayer ) )
  743. {
  744. addKnockout( pad, aLayer, padClearance, holes );
  745. }
  746. else if( pad->GetDrillSize().x > 0 )
  747. {
  748. constraint = bds.m_DRCEngine->EvalRules( PHYSICAL_HOLE_CLEARANCE_CONSTRAINT,
  749. pad, aZone, aLayer );
  750. if( constraint.GetValue().Min() > padClearance )
  751. holeClearance = constraint.GetValue().Min();
  752. else
  753. holeClearance = padClearance;
  754. pad->TransformHoleToPolygon( holes, holeClearance, m_maxError, ERROR_OUTSIDE );
  755. }
  756. break;
  757. default:
  758. // No knockout
  759. continue;
  760. }
  761. }
  762. }
  763. aFill.BooleanSubtract( holes, SHAPE_POLY_SET::PM_FAST );
  764. }
  765. /**
  766. * Removes clearance from the shape for copper items which share the zone's layer but are
  767. * not connected to it.
  768. */
  769. void ZONE_FILLER::buildCopperItemClearances( const ZONE* aZone, PCB_LAYER_ID aLayer,
  770. const std::vector<PAD*> aNoConnectionPads,
  771. SHAPE_POLY_SET& aHoles )
  772. {
  773. BOARD_DESIGN_SETTINGS& bds = m_board->GetDesignSettings();
  774. long ticker = 0;
  775. auto checkForCancel =
  776. [&ticker]( PROGRESS_REPORTER* aReporter ) -> bool
  777. {
  778. return aReporter && ( ticker++ % 50 ) == 0 && aReporter->IsCancelled();
  779. };
  780. // A small extra clearance to be sure actual track clearances are not smaller than
  781. // requested clearance due to many approximations in calculations, like arc to segment
  782. // approx, rounding issues, etc.
  783. BOX2I zone_boundingbox = aZone->GetBoundingBox();
  784. int extra_margin = pcbIUScale.mmToIU( ADVANCED_CFG::GetCfg().m_ExtraClearance );
  785. // Items outside the zone bounding box are skipped, so it needs to be inflated by the
  786. // largest clearance value found in the netclasses and rules
  787. zone_boundingbox.Inflate( m_worstClearance + extra_margin );
  788. auto evalRulesForItems =
  789. [&bds]( DRC_CONSTRAINT_T aConstraint, const BOARD_ITEM* a, const BOARD_ITEM* b,
  790. PCB_LAYER_ID aEvalLayer ) -> int
  791. {
  792. DRC_CONSTRAINT c = bds.m_DRCEngine->EvalRules( aConstraint, a, b, aEvalLayer );
  793. return c.GetValue().Min();
  794. };
  795. // Add non-connected pad clearances
  796. //
  797. auto knockoutPadClearance =
  798. [&]( PAD* aPad )
  799. {
  800. int init_gap = evalRulesForItems( PHYSICAL_CLEARANCE_CONSTRAINT, aZone, aPad, aLayer );
  801. int gap = init_gap;
  802. bool hasHole = aPad->GetDrillSize().x > 0;
  803. bool flashLayer = aPad->FlashLayer( aLayer );
  804. bool platedHole = hasHole && aPad->GetAttribute() == PAD_ATTRIB::PTH;
  805. if( flashLayer || platedHole )
  806. {
  807. gap = std::max( gap, evalRulesForItems( CLEARANCE_CONSTRAINT,
  808. aZone, aPad, aLayer ) );
  809. }
  810. if( flashLayer && gap > 0 )
  811. addKnockout( aPad, aLayer, gap + extra_margin, aHoles );
  812. if( hasHole )
  813. {
  814. // NPTH do not need copper clearance gaps to their holes
  815. if( aPad->GetAttribute() == PAD_ATTRIB::NPTH )
  816. gap = init_gap;
  817. gap = std::max( gap, evalRulesForItems( PHYSICAL_HOLE_CLEARANCE_CONSTRAINT,
  818. aZone, aPad, aLayer ) );
  819. gap = std::max( gap, evalRulesForItems( HOLE_CLEARANCE_CONSTRAINT,
  820. aZone, aPad, aLayer ) );
  821. if( gap > 0 )
  822. addHoleKnockout( aPad, gap + extra_margin, aHoles );
  823. }
  824. };
  825. for( PAD* pad : aNoConnectionPads )
  826. {
  827. if( checkForCancel( m_progressReporter ) )
  828. return;
  829. knockoutPadClearance( pad );
  830. }
  831. // Add non-connected track clearances
  832. //
  833. auto knockoutTrackClearance =
  834. [&]( PCB_TRACK* aTrack )
  835. {
  836. if( aTrack->GetBoundingBox().Intersects( zone_boundingbox ) )
  837. {
  838. bool sameNet = aTrack->GetNetCode() == aZone->GetNetCode()
  839. && aZone->GetNetCode() != 0;
  840. int gap = evalRulesForItems( PHYSICAL_CLEARANCE_CONSTRAINT,
  841. aZone, aTrack, aLayer );
  842. if( aTrack->Type() == PCB_VIA_T )
  843. {
  844. PCB_VIA* via = static_cast<PCB_VIA*>( aTrack );
  845. if( via->GetZoneLayerOverride( aLayer ) == ZLO_FORCE_NO_ZONE_CONNECTION )
  846. sameNet = false;
  847. }
  848. if( !sameNet )
  849. {
  850. gap = std::max( gap, evalRulesForItems( CLEARANCE_CONSTRAINT,
  851. aZone, aTrack, aLayer ) );
  852. }
  853. if( aTrack->Type() == PCB_VIA_T )
  854. {
  855. PCB_VIA* via = static_cast<PCB_VIA*>( aTrack );
  856. if( via->FlashLayer( aLayer ) && gap > 0 )
  857. {
  858. via->TransformShapeToPolygon( aHoles, aLayer, gap + extra_margin,
  859. m_maxError, ERROR_OUTSIDE );
  860. }
  861. gap = std::max( gap, evalRulesForItems( PHYSICAL_HOLE_CLEARANCE_CONSTRAINT,
  862. aZone, via, aLayer ) );
  863. if( !sameNet )
  864. {
  865. gap = std::max( gap, evalRulesForItems( HOLE_CLEARANCE_CONSTRAINT,
  866. aZone, via, aLayer ) );
  867. }
  868. if( gap > 0 )
  869. {
  870. int radius = via->GetDrillValue() / 2;
  871. TransformCircleToPolygon( aHoles, via->GetPosition(),
  872. radius + gap + extra_margin,
  873. m_maxError, ERROR_OUTSIDE );
  874. }
  875. }
  876. else
  877. {
  878. if( gap > 0 )
  879. {
  880. aTrack->TransformShapeToPolygon( aHoles, aLayer, gap + extra_margin,
  881. m_maxError, ERROR_OUTSIDE );
  882. }
  883. }
  884. }
  885. };
  886. for( PCB_TRACK* track : m_board->Tracks() )
  887. {
  888. if( !track->IsOnLayer( aLayer ) )
  889. continue;
  890. if( checkForCancel( m_progressReporter ) )
  891. return;
  892. knockoutTrackClearance( track );
  893. }
  894. // Add graphic item clearances.
  895. //
  896. auto knockoutGraphicClearance =
  897. [&]( BOARD_ITEM* aItem )
  898. {
  899. int shapeNet = ( aItem->Type() == PCB_SHAPE_T ) ? static_cast<PCB_SHAPE*>( aItem )->GetNetCode() : -1;
  900. bool sameNet = shapeNet == aZone->GetNetCode() && aZone->GetNetCode() != 0;
  901. // A item on the Edge_Cuts or Margin is always seen as on any layer:
  902. if( aItem->IsOnLayer( aLayer )
  903. || aItem->IsOnLayer( Edge_Cuts )
  904. || aItem->IsOnLayer( Margin ) )
  905. {
  906. if( aItem->GetBoundingBox().Intersects( zone_boundingbox ) )
  907. {
  908. bool ignoreLineWidths = false;
  909. int gap = evalRulesForItems( PHYSICAL_CLEARANCE_CONSTRAINT,
  910. aZone, aItem, aLayer );
  911. if( aItem->IsOnLayer( aLayer ) && !sameNet )
  912. {
  913. gap = std::max( gap, evalRulesForItems( CLEARANCE_CONSTRAINT,
  914. aZone, aItem, aLayer ) );
  915. }
  916. else if( aItem->IsOnLayer( Edge_Cuts ) )
  917. {
  918. gap = std::max( gap, evalRulesForItems( EDGE_CLEARANCE_CONSTRAINT,
  919. aZone, aItem, Edge_Cuts ) );
  920. ignoreLineWidths = true;
  921. }
  922. else if( aItem->IsOnLayer( Margin ) )
  923. {
  924. gap = std::max( gap, evalRulesForItems( EDGE_CLEARANCE_CONSTRAINT,
  925. aZone, aItem, Margin ) );
  926. }
  927. if( gap > 0 )
  928. addKnockout( aItem, aLayer, gap + extra_margin, ignoreLineWidths, aHoles );
  929. }
  930. }
  931. };
  932. for( FOOTPRINT* footprint : m_board->Footprints() )
  933. {
  934. knockoutGraphicClearance( &footprint->Reference() );
  935. knockoutGraphicClearance( &footprint->Value() );
  936. std::set<PAD*> allowedNetTiePads;
  937. // Don't knock out holes for graphic items which implement a net-tie to the zone's net
  938. // on the layer being filled.
  939. if( footprint->IsNetTie() )
  940. {
  941. for( PAD* pad : footprint->Pads() )
  942. {
  943. if( pad->GetNetCode() == aZone->GetNetCode() )
  944. {
  945. if( pad->IsOnLayer( aLayer ) )
  946. allowedNetTiePads.insert( pad );
  947. for( PAD* other : footprint->GetNetTiePads( pad ) )
  948. {
  949. if( other->IsOnLayer( aLayer ) )
  950. allowedNetTiePads.insert( other );
  951. }
  952. }
  953. }
  954. }
  955. for( BOARD_ITEM* item : footprint->GraphicalItems() )
  956. {
  957. if( checkForCancel( m_progressReporter ) )
  958. return;
  959. BOX2I itemBBox = item->GetBoundingBox();
  960. if( !zone_boundingbox.Intersects( itemBBox ) )
  961. continue;
  962. bool skipItem = false;
  963. if( item->IsOnLayer( aLayer ) )
  964. {
  965. std::shared_ptr<SHAPE> itemShape = item->GetEffectiveShape();
  966. for( PAD* pad : allowedNetTiePads )
  967. {
  968. if( pad->GetBoundingBox().Intersects( itemBBox )
  969. && pad->GetEffectiveShape()->Collide( itemShape.get() ) )
  970. {
  971. skipItem = true;
  972. break;
  973. }
  974. }
  975. }
  976. if( !skipItem )
  977. knockoutGraphicClearance( item );
  978. }
  979. }
  980. for( BOARD_ITEM* item : m_board->Drawings() )
  981. {
  982. if( checkForCancel( m_progressReporter ) )
  983. return;
  984. knockoutGraphicClearance( item );
  985. }
  986. // Add non-connected zone clearances
  987. //
  988. auto knockoutZoneClearance =
  989. [&]( ZONE* aKnockout )
  990. {
  991. // If the zones share no common layers
  992. if( !aKnockout->GetLayerSet().test( aLayer ) )
  993. return;
  994. if( aKnockout->GetBoundingBox().Intersects( zone_boundingbox ) )
  995. {
  996. if( aKnockout->GetIsRuleArea() )
  997. {
  998. // Keepouts use outline with no clearance
  999. aKnockout->TransformSmoothedOutlineToPolygon( aHoles, 0, m_maxError,
  1000. ERROR_OUTSIDE, nullptr );
  1001. }
  1002. else
  1003. {
  1004. int gap = evalRulesForItems( PHYSICAL_CLEARANCE_CONSTRAINT, aZone,
  1005. aKnockout, aLayer );
  1006. gap = std::max( gap, evalRulesForItems( CLEARANCE_CONSTRAINT, aZone,
  1007. aKnockout, aLayer ) );
  1008. SHAPE_POLY_SET poly;
  1009. aKnockout->TransformShapeToPolygon( poly, aLayer, gap + extra_margin,
  1010. m_maxError, ERROR_OUTSIDE );
  1011. aHoles.Append( poly );
  1012. }
  1013. }
  1014. };
  1015. for( ZONE* otherZone : m_board->Zones() )
  1016. {
  1017. if( checkForCancel( m_progressReporter ) )
  1018. return;
  1019. // Negative clearance permits zones to short
  1020. if( evalRulesForItems( CLEARANCE_CONSTRAINT, aZone, otherZone, aLayer ) < 0 )
  1021. continue;
  1022. if( otherZone->GetIsRuleArea() )
  1023. {
  1024. if( otherZone->GetDoNotAllowCopperPour() && !aZone->IsTeardropArea() )
  1025. knockoutZoneClearance( otherZone );
  1026. }
  1027. else if( otherZone->HigherPriority( aZone ) )
  1028. {
  1029. if( !otherZone->SameNet( aZone ) )
  1030. knockoutZoneClearance( otherZone );
  1031. }
  1032. }
  1033. for( FOOTPRINT* footprint : m_board->Footprints() )
  1034. {
  1035. for( ZONE* otherZone : footprint->Zones() )
  1036. {
  1037. if( checkForCancel( m_progressReporter ) )
  1038. return;
  1039. if( otherZone->GetIsRuleArea() )
  1040. {
  1041. if( otherZone->GetDoNotAllowCopperPour() && !aZone->IsTeardropArea() )
  1042. knockoutZoneClearance( otherZone );
  1043. }
  1044. else if( otherZone->HigherPriority( aZone ) )
  1045. {
  1046. if( !otherZone->SameNet( aZone ) )
  1047. knockoutZoneClearance( otherZone );
  1048. }
  1049. }
  1050. }
  1051. aHoles.Simplify( SHAPE_POLY_SET::PM_FAST );
  1052. }
  1053. /**
  1054. * Removes the outlines of higher-proirity zones with the same net. These zones should be
  1055. * in charge of the fill parameters within their own outlines.
  1056. */
  1057. void ZONE_FILLER::subtractHigherPriorityZones( const ZONE* aZone, PCB_LAYER_ID aLayer,
  1058. SHAPE_POLY_SET& aRawFill )
  1059. {
  1060. BOX2I zoneBBox = aZone->GetBoundingBox();
  1061. auto knockoutZoneOutline =
  1062. [&]( ZONE* aKnockout )
  1063. {
  1064. // If the zones share no common layers
  1065. if( !aKnockout->GetLayerSet().test( aLayer ) )
  1066. return;
  1067. if( aKnockout->GetBoundingBox().Intersects( zoneBBox ) )
  1068. {
  1069. // Processing of arc shapes in zones is not yet supported because Clipper
  1070. // can't do boolean operations on them. The poly outline must be converted to
  1071. // segments first.
  1072. SHAPE_POLY_SET outline = aKnockout->Outline()->CloneDropTriangulation();
  1073. outline.ClearArcs();
  1074. aRawFill.BooleanSubtract( outline, SHAPE_POLY_SET::PM_FAST );
  1075. }
  1076. };
  1077. for( ZONE* otherZone : m_board->Zones() )
  1078. {
  1079. // Don't use the `HigherPriority()` check here because we _only_ want to knock out zones
  1080. // with explicitly higher priorities, not those with equal priorities
  1081. if( otherZone->SameNet( aZone )
  1082. && otherZone->GetAssignedPriority() > aZone->GetAssignedPriority() )
  1083. {
  1084. // Do not remove teardrop area: it is not useful and not good
  1085. if( !otherZone->IsTeardropArea() )
  1086. knockoutZoneOutline( otherZone );
  1087. }
  1088. }
  1089. for( FOOTPRINT* footprint : m_board->Footprints() )
  1090. {
  1091. for( ZONE* otherZone : footprint->Zones() )
  1092. {
  1093. if( otherZone->SameNet( aZone ) && otherZone->HigherPriority( aZone ) )
  1094. {
  1095. // Do not remove teardrop area: it is not useful and not good
  1096. if( !otherZone->IsTeardropArea() )
  1097. knockoutZoneOutline( otherZone );
  1098. }
  1099. }
  1100. }
  1101. }
  1102. #define DUMP_POLYS_TO_COPPER_LAYER( a, b, c ) \
  1103. { if( m_debugZoneFiller && aDebugLayer == b ) \
  1104. { \
  1105. m_board->SetLayerName( b, c ); \
  1106. SHAPE_POLY_SET d = a; \
  1107. d.Fracture( SHAPE_POLY_SET::PM_STRICTLY_SIMPLE ); \
  1108. aFillPolys = d; \
  1109. return false; \
  1110. } \
  1111. }
  1112. /**
  1113. * 1 - Creates the main zone outline using a correction to shrink the resulting area by
  1114. * m_ZoneMinThickness / 2. The result is areas with a margin of m_ZoneMinThickness / 2
  1115. * so that when drawing outline with segments having a thickness of m_ZoneMinThickness the
  1116. * outlines will match exactly the initial outlines
  1117. * 2 - Knocks out thermal reliefs around thermally-connected pads
  1118. * 3 - Builds a set of thermal spoke for the whole zone
  1119. * 4 - Knocks out unconnected copper items, deleting any affected spokes
  1120. * 5 - Removes unconnected copper islands, deleting any affected spokes
  1121. * 6 - Adds in the remaining spokes
  1122. */
  1123. bool ZONE_FILLER::fillCopperZone( const ZONE* aZone, PCB_LAYER_ID aLayer, PCB_LAYER_ID aDebugLayer,
  1124. const SHAPE_POLY_SET& aSmoothedOutline,
  1125. const SHAPE_POLY_SET& aMaxExtents, SHAPE_POLY_SET& aFillPolys )
  1126. {
  1127. m_maxError = m_board->GetDesignSettings().m_MaxError;
  1128. // Features which are min_width should survive pruning; features that are *less* than
  1129. // min_width should not. Therefore we subtract epsilon from the min_width when
  1130. // deflating/inflating.
  1131. int half_min_width = aZone->GetMinThickness() / 2;
  1132. int epsilon = pcbIUScale.mmToIU( 0.001 );
  1133. // Solid polygons are deflated and inflated during calculations. Deflating doesn't cause
  1134. // issues, but inflate is tricky as it can create excessively long and narrow spikes for
  1135. // acute angles.
  1136. // ALLOW_ACUTE_CORNERS cannot be used due to the spike problem.
  1137. // CHAMFER_ACUTE_CORNERS is tempting, but can still produce spikes in some unusual
  1138. // circumstances (https://gitlab.com/kicad/code/kicad/-/issues/5581).
  1139. // It's unclear if ROUND_ACUTE_CORNERS would have the same issues, but is currently avoided
  1140. // as a "less-safe" option.
  1141. // ROUND_ALL_CORNERS produces the uniformly nicest shapes, but also a lot of segments.
  1142. // CHAMFER_ALL_CORNERS improves the segment count.
  1143. CORNER_STRATEGY fastCornerStrategy = CORNER_STRATEGY::CHAMFER_ALL_CORNERS;
  1144. CORNER_STRATEGY cornerStrategy = CORNER_STRATEGY::ROUND_ALL_CORNERS;
  1145. std::vector<PAD*> thermalConnectionPads;
  1146. std::vector<PAD*> noConnectionPads;
  1147. std::deque<SHAPE_LINE_CHAIN> thermalSpokes;
  1148. SHAPE_POLY_SET clearanceHoles;
  1149. aFillPolys = aSmoothedOutline;
  1150. DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In1_Cu, wxT( "smoothed-outline" ) );
  1151. if( m_progressReporter && m_progressReporter->IsCancelled() )
  1152. return false;
  1153. /* -------------------------------------------------------------------------------------
  1154. * Knockout thermal reliefs.
  1155. */
  1156. knockoutThermalReliefs( aZone, aLayer, aFillPolys, thermalConnectionPads, noConnectionPads );
  1157. DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In2_Cu, wxT( "minus-thermal-reliefs" ) );
  1158. if( m_progressReporter && m_progressReporter->IsCancelled() )
  1159. return false;
  1160. /* -------------------------------------------------------------------------------------
  1161. * Knockout electrical clearances.
  1162. */
  1163. buildCopperItemClearances( aZone, aLayer, noConnectionPads, clearanceHoles );
  1164. DUMP_POLYS_TO_COPPER_LAYER( clearanceHoles, In3_Cu, wxT( "clearance-holes" ) );
  1165. if( m_progressReporter && m_progressReporter->IsCancelled() )
  1166. return false;
  1167. /* -------------------------------------------------------------------------------------
  1168. * Add thermal relief spokes.
  1169. */
  1170. buildThermalSpokes( aZone, aLayer, thermalConnectionPads, thermalSpokes );
  1171. if( m_progressReporter && m_progressReporter->IsCancelled() )
  1172. return false;
  1173. // Create a temporary zone that we can hit-test spoke-ends against. It's only temporary
  1174. // because the "real" subtract-clearance-holes has to be done after the spokes are added.
  1175. static const bool USE_BBOX_CACHES = true;
  1176. SHAPE_POLY_SET testAreas = aFillPolys.CloneDropTriangulation();
  1177. testAreas.BooleanSubtract( clearanceHoles, SHAPE_POLY_SET::PM_FAST );
  1178. DUMP_POLYS_TO_COPPER_LAYER( testAreas, In4_Cu, wxT( "minus-clearance-holes" ) );
  1179. // Prune features that don't meet minimum-width criteria
  1180. if( half_min_width - epsilon > epsilon )
  1181. {
  1182. testAreas.Deflate( half_min_width - epsilon, fastCornerStrategy, m_maxError );
  1183. DUMP_POLYS_TO_COPPER_LAYER( testAreas, In5_Cu, wxT( "spoke-test-deflated" ) );
  1184. testAreas.Inflate( half_min_width - epsilon, fastCornerStrategy, m_maxError );
  1185. DUMP_POLYS_TO_COPPER_LAYER( testAreas, In6_Cu, wxT( "spoke-test-reinflated" ) );
  1186. }
  1187. if( m_progressReporter && m_progressReporter->IsCancelled() )
  1188. return false;
  1189. // Spoke-end-testing is hugely expensive so we generate cached bounding-boxes to speed
  1190. // things up a bit.
  1191. testAreas.BuildBBoxCaches();
  1192. int interval = 0;
  1193. SHAPE_POLY_SET debugSpokes;
  1194. for( const SHAPE_LINE_CHAIN& spoke : thermalSpokes )
  1195. {
  1196. const VECTOR2I& testPt = spoke.CPoint( 3 );
  1197. // Hit-test against zone body
  1198. if( testAreas.Contains( testPt, -1, 1, USE_BBOX_CACHES ) )
  1199. {
  1200. if( m_debugZoneFiller )
  1201. debugSpokes.AddOutline( spoke );
  1202. aFillPolys.AddOutline( spoke );
  1203. continue;
  1204. }
  1205. if( interval++ > 400 )
  1206. {
  1207. if( m_progressReporter && m_progressReporter->IsCancelled() )
  1208. return false;
  1209. interval = 0;
  1210. }
  1211. // Hit-test against other spokes
  1212. for( const SHAPE_LINE_CHAIN& other : thermalSpokes )
  1213. {
  1214. // Hit test in both directions to avoid interactions with round-off errors.
  1215. // (See https://gitlab.com/kicad/code/kicad/-/issues/13316.)
  1216. if( &other != &spoke
  1217. && other.PointInside( testPt, 1, USE_BBOX_CACHES )
  1218. && spoke.PointInside( other.CPoint( 3 ), 1, USE_BBOX_CACHES ) )
  1219. {
  1220. if( m_debugZoneFiller )
  1221. debugSpokes.AddOutline( spoke );
  1222. aFillPolys.AddOutline( spoke );
  1223. break;
  1224. }
  1225. }
  1226. }
  1227. DUMP_POLYS_TO_COPPER_LAYER( debugSpokes, In7_Cu, wxT( "spokes" ) );
  1228. if( m_progressReporter && m_progressReporter->IsCancelled() )
  1229. return false;
  1230. aFillPolys.BooleanSubtract( clearanceHoles, SHAPE_POLY_SET::PM_FAST );
  1231. DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In8_Cu, wxT( "after-spoke-trimming" ) );
  1232. /* -------------------------------------------------------------------------------------
  1233. * Prune features that don't meet minimum-width criteria
  1234. */
  1235. if( half_min_width - epsilon > epsilon )
  1236. aFillPolys.Deflate( half_min_width - epsilon, fastCornerStrategy, m_maxError );
  1237. // Min-thickness is the web thickness. On the other hand, a blob min-thickness by
  1238. // min-thickness is not useful. Since there's no obvious definition of web vs. blob, we
  1239. // arbitrarily choose "at least 2X min-thickness on one axis". (Since we're doing this
  1240. // during the deflated state, that means we test for "at least min-thickness".)
  1241. for( int ii = aFillPolys.OutlineCount() - 1; ii >= 0; ii-- )
  1242. {
  1243. std::vector<SHAPE_LINE_CHAIN>& island = aFillPolys.Polygon( ii );
  1244. BOX2I islandExtents;
  1245. for( const VECTOR2I& pt : island.front().CPoints() )
  1246. {
  1247. islandExtents.Merge( pt );
  1248. if( islandExtents.GetSizeMax() > aZone->GetMinThickness() )
  1249. break;
  1250. }
  1251. if( islandExtents.GetSizeMax() < aZone->GetMinThickness() )
  1252. aFillPolys.DeletePolygon( ii );
  1253. }
  1254. DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In9_Cu, wxT( "deflated" ) );
  1255. if( m_progressReporter && m_progressReporter->IsCancelled() )
  1256. return false;
  1257. /* -------------------------------------------------------------------------------------
  1258. * Process the hatch pattern (note that we do this while deflated)
  1259. */
  1260. if( aZone->GetFillMode() == ZONE_FILL_MODE::HATCH_PATTERN )
  1261. {
  1262. if( !addHatchFillTypeOnZone( aZone, aLayer, aDebugLayer, aFillPolys ) )
  1263. return false;
  1264. }
  1265. if( m_progressReporter && m_progressReporter->IsCancelled() )
  1266. return false;
  1267. /* -------------------------------------------------------------------------------------
  1268. * Finish minimum-width pruning by re-inflating
  1269. */
  1270. if( half_min_width - epsilon > epsilon )
  1271. aFillPolys.Inflate( half_min_width - epsilon, cornerStrategy, m_maxError, true );
  1272. DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In15_Cu, wxT( "after-reinflating" ) );
  1273. /* -------------------------------------------------------------------------------------
  1274. * Ensure additive changes (thermal stubs and inflating acute corners) do not add copper
  1275. * outside the zone boundary, inside the clearance holes, or between otherwise isolated
  1276. * islands
  1277. */
  1278. for( PAD* pad : thermalConnectionPads )
  1279. addHoleKnockout( pad, 0, clearanceHoles );
  1280. aFillPolys.BooleanIntersection( aMaxExtents, SHAPE_POLY_SET::PM_FAST );
  1281. DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In16_Cu, wxT( "after-trim-to-outline" ) );
  1282. aFillPolys.BooleanSubtract( clearanceHoles, SHAPE_POLY_SET::PM_FAST );
  1283. DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In17_Cu, wxT( "after-trim-to-clearance-holes" ) );
  1284. /* -------------------------------------------------------------------------------------
  1285. * Lastly give any same-net but higher-priority zones control over their own area.
  1286. */
  1287. subtractHigherPriorityZones( aZone, aLayer, aFillPolys );
  1288. DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In18_Cu, wxT( "minus-higher-priority-zones" ) );
  1289. aFillPolys.Fracture( SHAPE_POLY_SET::PM_FAST );
  1290. return true;
  1291. }
  1292. bool ZONE_FILLER::fillNonCopperZone( const ZONE* aZone, PCB_LAYER_ID aLayer,
  1293. const SHAPE_POLY_SET& aSmoothedOutline,
  1294. SHAPE_POLY_SET& aFillPolys )
  1295. {
  1296. BOARD_DESIGN_SETTINGS& bds = m_board->GetDesignSettings();
  1297. BOX2I zone_boundingbox = aZone->GetBoundingBox();
  1298. SHAPE_POLY_SET clearanceHoles;
  1299. long ticker = 0;
  1300. auto checkForCancel =
  1301. [&ticker]( PROGRESS_REPORTER* aReporter ) -> bool
  1302. {
  1303. return aReporter && ( ticker++ % 50 ) == 0 && aReporter->IsCancelled();
  1304. };
  1305. auto knockoutGraphicClearance =
  1306. [&]( BOARD_ITEM* aItem )
  1307. {
  1308. if( aItem->IsKnockout() && aItem->IsOnLayer( aLayer )
  1309. && aItem->GetBoundingBox().Intersects( zone_boundingbox ) )
  1310. {
  1311. DRC_CONSTRAINT cc = bds.m_DRCEngine->EvalRules( PHYSICAL_CLEARANCE_CONSTRAINT,
  1312. aZone, aItem, aLayer );
  1313. addKnockout( aItem, aLayer, cc.GetValue().Min(), false, clearanceHoles );
  1314. }
  1315. };
  1316. for( FOOTPRINT* footprint : m_board->Footprints() )
  1317. {
  1318. if( checkForCancel( m_progressReporter ) )
  1319. return false;
  1320. knockoutGraphicClearance( &footprint->Reference() );
  1321. knockoutGraphicClearance( &footprint->Value() );
  1322. for( BOARD_ITEM* item : footprint->GraphicalItems() )
  1323. knockoutGraphicClearance( item );
  1324. }
  1325. for( BOARD_ITEM* item : m_board->Drawings() )
  1326. {
  1327. if( checkForCancel( m_progressReporter ) )
  1328. return false;
  1329. knockoutGraphicClearance( item );
  1330. }
  1331. aFillPolys = aSmoothedOutline;
  1332. aFillPolys.BooleanSubtract( clearanceHoles, SHAPE_POLY_SET::PM_FAST );
  1333. for( ZONE* keepout : m_board->Zones() )
  1334. {
  1335. if( !keepout->GetIsRuleArea() )
  1336. continue;
  1337. if( keepout->GetDoNotAllowCopperPour() && keepout->IsOnLayer( aLayer ) )
  1338. {
  1339. if( keepout->GetBoundingBox().Intersects( zone_boundingbox ) )
  1340. aFillPolys.BooleanSubtract( *keepout->Outline(), SHAPE_POLY_SET::PM_FAST );
  1341. }
  1342. }
  1343. // Features which are min_width should survive pruning; features that are *less* than
  1344. // min_width should not. Therefore we subtract epsilon from the min_width when
  1345. // deflating/inflating.
  1346. int half_min_width = aZone->GetMinThickness() / 2;
  1347. int epsilon = pcbIUScale.mmToIU( 0.001 );
  1348. aFillPolys.Deflate( half_min_width - epsilon, CORNER_STRATEGY::CHAMFER_ALL_CORNERS, m_maxError );
  1349. // Remove the non filled areas due to the hatch pattern
  1350. if( aZone->GetFillMode() == ZONE_FILL_MODE::HATCH_PATTERN )
  1351. {
  1352. if( !addHatchFillTypeOnZone( aZone, aLayer, aLayer, aFillPolys ) )
  1353. return false;
  1354. }
  1355. // Re-inflate after pruning of areas that don't meet minimum-width criteria
  1356. if( half_min_width - epsilon > epsilon )
  1357. aFillPolys.Inflate( half_min_width - epsilon, CORNER_STRATEGY::ROUND_ALL_CORNERS, m_maxError );
  1358. aFillPolys.Fracture( SHAPE_POLY_SET::PM_STRICTLY_SIMPLE );
  1359. return true;
  1360. }
  1361. /*
  1362. * Build the filled solid areas data from real outlines (stored in m_Poly)
  1363. * The solid areas can be more than one on copper layers, and do not have holes
  1364. * ( holes are linked by overlapping segments to the main outline)
  1365. */
  1366. bool ZONE_FILLER::fillSingleZone( ZONE* aZone, PCB_LAYER_ID aLayer, SHAPE_POLY_SET& aFillPolys )
  1367. {
  1368. SHAPE_POLY_SET* boardOutline = m_brdOutlinesValid ? &m_boardOutline : nullptr;
  1369. SHAPE_POLY_SET maxExtents;
  1370. SHAPE_POLY_SET smoothedPoly;
  1371. PCB_LAYER_ID debugLayer = UNDEFINED_LAYER;
  1372. if( m_debugZoneFiller && LSET::InternalCuMask().Contains( aLayer ) )
  1373. {
  1374. debugLayer = aLayer;
  1375. aLayer = F_Cu;
  1376. }
  1377. if( !aZone->BuildSmoothedPoly( maxExtents, aLayer, boardOutline, &smoothedPoly ) )
  1378. return false;
  1379. if( m_progressReporter && m_progressReporter->IsCancelled() )
  1380. return false;
  1381. if( aZone->IsOnCopperLayer() )
  1382. {
  1383. if( fillCopperZone( aZone, aLayer, debugLayer, smoothedPoly, maxExtents, aFillPolys ) )
  1384. aZone->SetNeedRefill( false );
  1385. }
  1386. else
  1387. {
  1388. if( fillNonCopperZone( aZone, aLayer, smoothedPoly, aFillPolys ) )
  1389. aZone->SetNeedRefill( false );
  1390. }
  1391. return true;
  1392. }
  1393. /**
  1394. * Function buildThermalSpokes
  1395. */
  1396. void ZONE_FILLER::buildThermalSpokes( const ZONE* aZone, PCB_LAYER_ID aLayer,
  1397. const std::vector<PAD*>& aSpokedPadsList,
  1398. std::deque<SHAPE_LINE_CHAIN>& aSpokesList )
  1399. {
  1400. BOARD_DESIGN_SETTINGS& bds = m_board->GetDesignSettings();
  1401. BOX2I zoneBB = aZone->GetBoundingBox();
  1402. DRC_CONSTRAINT constraint;
  1403. zoneBB.Inflate( std::max( bds.GetBiggestClearanceValue(), aZone->GetLocalClearance() ) );
  1404. // Is a point on the boundary of the polygon inside or outside? This small epsilon lets
  1405. // us avoid the question.
  1406. int epsilon = KiROUND( pcbIUScale.IU_PER_MM * 0.04 ); // about 1.5 mil
  1407. for( PAD* pad : aSpokedPadsList )
  1408. {
  1409. // We currently only connect to pads, not pad holes
  1410. if( !pad->IsOnLayer( aLayer ) )
  1411. continue;
  1412. constraint = bds.m_DRCEngine->EvalRules( THERMAL_RELIEF_GAP_CONSTRAINT, pad, aZone, aLayer );
  1413. int thermalReliefGap = constraint.GetValue().Min();
  1414. constraint = bds.m_DRCEngine->EvalRules( THERMAL_SPOKE_WIDTH_CONSTRAINT, pad, aZone, aLayer );
  1415. int spoke_w = constraint.GetValue().Opt();
  1416. // Spoke width should ideally be smaller than the pad minor axis.
  1417. // Otherwise the thermal shape is not really a thermal relief,
  1418. // and the algo to count the actual number of spokes can fail
  1419. int spoke_max_allowed_w = std::min( pad->GetSize().x, pad->GetSize().y );
  1420. spoke_w = std::max( spoke_w, constraint.Value().Min() );
  1421. spoke_w = std::min( spoke_w, constraint.Value().Max() );
  1422. // ensure the spoke width is smaller than the pad minor size
  1423. spoke_w = std::min( spoke_w, spoke_max_allowed_w );
  1424. // Cannot create stubs having a width < zone min thickness
  1425. if( spoke_w < aZone->GetMinThickness() )
  1426. continue;
  1427. int spoke_half_w = spoke_w / 2;
  1428. // Quick test here to possibly save us some work
  1429. BOX2I itemBB = pad->GetBoundingBox();
  1430. itemBB.Inflate( thermalReliefGap + epsilon );
  1431. if( !( itemBB.Intersects( zoneBB ) ) )
  1432. continue;
  1433. bool customSpokes = false;
  1434. if( pad->GetShape() == PAD_SHAPE::CUSTOM )
  1435. {
  1436. for( const std::shared_ptr<PCB_SHAPE>& primitive : pad->GetPrimitives() )
  1437. {
  1438. if( primitive->IsProxyItem() && primitive->GetShape() == SHAPE_T::SEGMENT )
  1439. {
  1440. customSpokes = true;
  1441. break;
  1442. }
  1443. }
  1444. }
  1445. // Thermal spokes consist of square-ended segments from the pad center to points just
  1446. // outside the thermal relief. The outside end has an extra center point (which must be
  1447. // at idx 3) which is used for testing whether or not the spoke connects to copper in the
  1448. // parent zone.
  1449. auto buildSpokesFromOrigin =
  1450. [&]( const BOX2I& box )
  1451. {
  1452. for( int i = 0; i < 4; i++ )
  1453. {
  1454. SHAPE_LINE_CHAIN spoke;
  1455. switch( i )
  1456. {
  1457. case 0: // lower stub
  1458. spoke.Append( +spoke_half_w, -spoke_half_w );
  1459. spoke.Append( -spoke_half_w, -spoke_half_w );
  1460. spoke.Append( -spoke_half_w, box.GetBottom() );
  1461. spoke.Append( 0, box.GetBottom() ); // test pt
  1462. spoke.Append( +spoke_half_w, box.GetBottom() );
  1463. break;
  1464. case 1: // upper stub
  1465. spoke.Append( +spoke_half_w, +spoke_half_w );
  1466. spoke.Append( -spoke_half_w, +spoke_half_w );
  1467. spoke.Append( -spoke_half_w, box.GetTop() );
  1468. spoke.Append( 0, box.GetTop() ); // test pt
  1469. spoke.Append( +spoke_half_w, box.GetTop() );
  1470. break;
  1471. case 2: // right stub
  1472. spoke.Append( -spoke_half_w, +spoke_half_w );
  1473. spoke.Append( -spoke_half_w, -spoke_half_w );
  1474. spoke.Append( box.GetRight(), -spoke_half_w );
  1475. spoke.Append( box.GetRight(), 0 ); // test pt
  1476. spoke.Append( box.GetRight(), +spoke_half_w );
  1477. break;
  1478. case 3: // left stub
  1479. spoke.Append( +spoke_half_w, +spoke_half_w );
  1480. spoke.Append( +spoke_half_w, -spoke_half_w );
  1481. spoke.Append( box.GetLeft(), -spoke_half_w );
  1482. spoke.Append( box.GetLeft(), 0 ); // test pt
  1483. spoke.Append( box.GetLeft(), +spoke_half_w );
  1484. break;
  1485. }
  1486. spoke.SetClosed( true );
  1487. aSpokesList.push_back( std::move( spoke ) );
  1488. }
  1489. };
  1490. if( customSpokes )
  1491. {
  1492. SHAPE_POLY_SET thermalPoly;
  1493. SHAPE_LINE_CHAIN thermalOutline;
  1494. pad->TransformShapeToPolygon( thermalPoly, aLayer, thermalReliefGap + epsilon,
  1495. m_maxError, ERROR_OUTSIDE );
  1496. if( thermalPoly.OutlineCount() )
  1497. thermalOutline = thermalPoly.Outline( 0 );
  1498. for( const std::shared_ptr<PCB_SHAPE>& primitive : pad->GetPrimitives() )
  1499. {
  1500. if( primitive->IsProxyItem() && primitive->GetShape() == SHAPE_T::SEGMENT )
  1501. {
  1502. SEG seg( primitive->GetStart(), primitive->GetEnd() );
  1503. SHAPE_LINE_CHAIN::INTERSECTIONS intersections;
  1504. RotatePoint( seg.A, pad->GetOrientation() );
  1505. RotatePoint( seg.B, pad->GetOrientation() );
  1506. seg.A += pad->ShapePos();
  1507. seg.B += pad->ShapePos();
  1508. // Make sure seg.A is the origin
  1509. if( !pad->GetEffectivePolygon()->Contains( seg.A ) )
  1510. seg.Reverse();
  1511. // Trim seg.B to the thermal outline
  1512. if( thermalOutline.Intersect( seg, intersections ) )
  1513. {
  1514. seg.B = intersections.front().p;
  1515. VECTOR2I offset = ( seg.B - seg.A ).Perpendicular().Resize( spoke_half_w );
  1516. SHAPE_LINE_CHAIN spoke;
  1517. spoke.Append( seg.A + offset );
  1518. spoke.Append( seg.A - offset );
  1519. spoke.Append( seg.B - offset );
  1520. spoke.Append( seg.B ); // test pt
  1521. spoke.Append( seg.B + offset );
  1522. spoke.SetClosed( true );
  1523. aSpokesList.push_back( std::move( spoke ) );
  1524. }
  1525. }
  1526. }
  1527. }
  1528. // If the spokes are at a cardinal angle then we can generate them from a bounding box
  1529. // without trig.
  1530. else if( ( pad->GetOrientation() + pad->GetThermalSpokeAngle() ).IsCardinal() )
  1531. {
  1532. BOX2I spokesBox = pad->GetBoundingBox();
  1533. spokesBox.Inflate( thermalReliefGap + epsilon );
  1534. // Spokes are from center of pad shape, not from hole.
  1535. spokesBox.Offset( - pad->ShapePos() );
  1536. buildSpokesFromOrigin( spokesBox );
  1537. auto spokeIter = aSpokesList.rbegin();
  1538. for( int ii = 0; ii < 4; ++ii, ++spokeIter )
  1539. spokeIter->Move( pad->ShapePos() );
  1540. }
  1541. // Even if the spokes are rotated, we can fudge it for round and square pads by rotating
  1542. // the bounding box to match the spokes.
  1543. else if( pad->GetSizeX() == pad->GetSizeY() && pad->GetShape() != PAD_SHAPE::CUSTOM )
  1544. {
  1545. // Since the bounding-box needs to be correclty rotated we use a dummy pad to keep
  1546. // from dirtying the real pad's cached shapes.
  1547. PAD dummy_pad( *pad );
  1548. dummy_pad.SetOrientation( pad->GetThermalSpokeAngle() );
  1549. // Spokes are from center of pad shape, not from hole. So the dummy pad has no shape
  1550. // offset and is at position 0,0
  1551. dummy_pad.SetPosition( VECTOR2I( 0, 0 ) );
  1552. dummy_pad.SetOffset( VECTOR2I( 0, 0 ) );
  1553. BOX2I spokesBox = dummy_pad.GetBoundingBox();
  1554. spokesBox.Inflate( thermalReliefGap + epsilon );
  1555. buildSpokesFromOrigin( spokesBox );
  1556. auto spokeIter = aSpokesList.rbegin();
  1557. for( int ii = 0; ii < 4; ++ii, ++spokeIter )
  1558. {
  1559. spokeIter->Rotate( pad->GetOrientation() + pad->GetThermalSpokeAngle() );
  1560. spokeIter->Move( pad->ShapePos() );
  1561. }
  1562. }
  1563. // And lastly, even when we have to resort to trig, we can use it only in a post-process
  1564. // after the rotated-bounding-box trick from above.
  1565. else
  1566. {
  1567. // Since the bounding-box needs to be correclty rotated we use a dummy pad to keep
  1568. // from dirtying the real pad's cached shapes.
  1569. PAD dummy_pad( *pad );
  1570. dummy_pad.SetOrientation( pad->GetThermalSpokeAngle() );
  1571. // Spokes are from center of pad shape, not from hole. So the dummy pad has no shape
  1572. // offset and is at position 0,0
  1573. dummy_pad.SetPosition( VECTOR2I( 0, 0 ) );
  1574. dummy_pad.SetOffset( VECTOR2I( 0, 0 ) );
  1575. BOX2I spokesBox = dummy_pad.GetBoundingBox();
  1576. // In this case make the box -big-; we're going to clip to the "real" bbox later.
  1577. spokesBox.Inflate( thermalReliefGap + spokesBox.GetWidth() + spokesBox.GetHeight() );
  1578. buildSpokesFromOrigin( spokesBox );
  1579. BOX2I realBBox = pad->GetBoundingBox();
  1580. realBBox.Inflate( thermalReliefGap + epsilon );
  1581. auto spokeIter = aSpokesList.rbegin();
  1582. for( int ii = 0; ii < 4; ++ii, ++spokeIter )
  1583. {
  1584. spokeIter->Rotate( pad->GetOrientation() + pad->GetThermalSpokeAngle() );
  1585. spokeIter->Move( pad->ShapePos() );
  1586. VECTOR2I origin_p = spokeIter->GetPoint( 0 );
  1587. VECTOR2I origin_m = spokeIter->GetPoint( 1 );
  1588. VECTOR2I origin = ( origin_p + origin_m ) / 2;
  1589. VECTOR2I end_m = spokeIter->GetPoint( 2 );
  1590. VECTOR2I end = spokeIter->GetPoint( 3 );
  1591. VECTOR2I end_p = spokeIter->GetPoint( 4 );
  1592. ClipLine( &realBBox, origin_p.x, origin_p.y, end_p.x, end_p.y );
  1593. ClipLine( &realBBox, origin_m.x, origin_m.y, end_m.x, end_m.y );
  1594. ClipLine( &realBBox, origin.x, origin.y, end.x, end.y );
  1595. spokeIter->SetPoint( 2, end_m );
  1596. spokeIter->SetPoint( 3, end );
  1597. spokeIter->SetPoint( 4, end_p );
  1598. }
  1599. }
  1600. }
  1601. for( size_t ii = 0; ii < aSpokesList.size(); ++ii )
  1602. aSpokesList[ii].GenerateBBoxCache();
  1603. }
  1604. bool ZONE_FILLER::addHatchFillTypeOnZone( const ZONE* aZone, PCB_LAYER_ID aLayer,
  1605. PCB_LAYER_ID aDebugLayer, SHAPE_POLY_SET& aFillPolys )
  1606. {
  1607. // Build grid:
  1608. // obviously line thickness must be > zone min thickness.
  1609. // It can happens if a board file was edited by hand by a python script
  1610. // Use 1 micron margin to be *sure* there is no issue in Gerber files
  1611. // (Gbr file unit = 1 or 10 nm) due to some truncation in coordinates or calculations
  1612. // This margin also avoid problems due to rounding coordinates in next calculations
  1613. // that can create incorrect polygons
  1614. int thickness = std::max( aZone->GetHatchThickness(),
  1615. aZone->GetMinThickness() + pcbIUScale.mmToIU( 0.001 ) );
  1616. int linethickness = thickness - aZone->GetMinThickness();
  1617. int gridsize = thickness + aZone->GetHatchGap();
  1618. int maxError = m_board->GetDesignSettings().m_MaxError;
  1619. SHAPE_POLY_SET filledPolys = aFillPolys.CloneDropTriangulation();
  1620. // Use a area that contains the rotated bbox by orientation, and after rotate the result
  1621. // by -orientation.
  1622. if( !aZone->GetHatchOrientation().IsZero() )
  1623. filledPolys.Rotate( - aZone->GetHatchOrientation() );
  1624. BOX2I bbox = filledPolys.BBox( 0 );
  1625. // Build hole shape
  1626. // the hole size is aZone->GetHatchGap(), but because the outline thickness
  1627. // is aZone->GetMinThickness(), the hole shape size must be larger
  1628. SHAPE_LINE_CHAIN hole_base;
  1629. int hole_size = aZone->GetHatchGap() + aZone->GetMinThickness();
  1630. VECTOR2I corner( 0, 0 );;
  1631. hole_base.Append( corner );
  1632. corner.x += hole_size;
  1633. hole_base.Append( corner );
  1634. corner.y += hole_size;
  1635. hole_base.Append( corner );
  1636. corner.x = 0;
  1637. hole_base.Append( corner );
  1638. hole_base.SetClosed( true );
  1639. // Calculate minimal area of a grid hole.
  1640. // All holes smaller than a threshold will be removed
  1641. double minimal_hole_area = hole_base.Area() * aZone->GetHatchHoleMinArea();
  1642. // Now convert this hole to a smoothed shape:
  1643. if( aZone->GetHatchSmoothingLevel() > 0 )
  1644. {
  1645. // the actual size of chamfer, or rounded corner radius is the half size
  1646. // of the HatchFillTypeGap scaled by aZone->GetHatchSmoothingValue()
  1647. // aZone->GetHatchSmoothingValue() = 1.0 is the max value for the chamfer or the
  1648. // radius of corner (radius = half size of the hole)
  1649. int smooth_value = KiROUND( aZone->GetHatchGap()
  1650. * aZone->GetHatchSmoothingValue() / 2 );
  1651. // Minimal optimization:
  1652. // make smoothing only for reasonable smooth values, to avoid a lot of useless segments
  1653. // and if the smooth value is small, use chamfer even if fillet is requested
  1654. #define SMOOTH_MIN_VAL_MM 0.02
  1655. #define SMOOTH_SMALL_VAL_MM 0.04
  1656. if( smooth_value > pcbIUScale.mmToIU( SMOOTH_MIN_VAL_MM ) )
  1657. {
  1658. SHAPE_POLY_SET smooth_hole;
  1659. smooth_hole.AddOutline( hole_base );
  1660. int smooth_level = aZone->GetHatchSmoothingLevel();
  1661. if( smooth_value < pcbIUScale.mmToIU( SMOOTH_SMALL_VAL_MM ) && smooth_level > 1 )
  1662. smooth_level = 1;
  1663. // Use a larger smooth_value to compensate the outline tickness
  1664. // (chamfer is not visible is smooth value < outline thickess)
  1665. smooth_value += aZone->GetMinThickness() / 2;
  1666. // smooth_value cannot be bigger than the half size oh the hole:
  1667. smooth_value = std::min( smooth_value, aZone->GetHatchGap() / 2 );
  1668. // the error to approximate a circle by segments when smoothing corners by a arc
  1669. maxError = std::max( maxError * 2, smooth_value / 20 );
  1670. switch( smooth_level )
  1671. {
  1672. case 1:
  1673. // Chamfer() uses the distance from a corner to create a end point
  1674. // for the chamfer.
  1675. hole_base = smooth_hole.Chamfer( smooth_value ).Outline( 0 );
  1676. break;
  1677. default:
  1678. if( aZone->GetHatchSmoothingLevel() > 2 )
  1679. maxError /= 2; // Force better smoothing
  1680. hole_base = smooth_hole.Fillet( smooth_value, maxError ).Outline( 0 );
  1681. break;
  1682. case 0:
  1683. break;
  1684. };
  1685. }
  1686. }
  1687. // Build holes
  1688. SHAPE_POLY_SET holes;
  1689. for( int xx = 0; ; xx++ )
  1690. {
  1691. int xpos = xx * gridsize;
  1692. if( xpos > bbox.GetWidth() )
  1693. break;
  1694. for( int yy = 0; ; yy++ )
  1695. {
  1696. int ypos = yy * gridsize;
  1697. if( ypos > bbox.GetHeight() )
  1698. break;
  1699. // Generate hole
  1700. SHAPE_LINE_CHAIN hole( hole_base );
  1701. hole.Move( VECTOR2I( xpos, ypos ) );
  1702. holes.AddOutline( hole );
  1703. }
  1704. }
  1705. holes.Move( bbox.GetPosition() );
  1706. if( !aZone->GetHatchOrientation().IsZero() )
  1707. holes.Rotate( aZone->GetHatchOrientation() );
  1708. DUMP_POLYS_TO_COPPER_LAYER( holes, In10_Cu, wxT( "hatch-holes" ) );
  1709. int outline_margin = aZone->GetMinThickness() * 1.1;
  1710. // Using GetHatchThickness() can look more consistent than GetMinThickness().
  1711. if( aZone->GetHatchBorderAlgorithm() && aZone->GetHatchThickness() > outline_margin )
  1712. outline_margin = aZone->GetHatchThickness();
  1713. // The fill has already been deflated to ensure GetMinThickness() so we just have to
  1714. // account for anything beyond that.
  1715. SHAPE_POLY_SET deflatedFilledPolys = aFillPolys.CloneDropTriangulation();
  1716. deflatedFilledPolys.Deflate( outline_margin - aZone->GetMinThickness(),
  1717. CORNER_STRATEGY::CHAMFER_ALL_CORNERS, maxError );
  1718. holes.BooleanIntersection( deflatedFilledPolys, SHAPE_POLY_SET::PM_FAST );
  1719. DUMP_POLYS_TO_COPPER_LAYER( holes, In11_Cu, wxT( "fill-clipped-hatch-holes" ) );
  1720. SHAPE_POLY_SET deflatedOutline = aZone->Outline()->CloneDropTriangulation();
  1721. deflatedOutline.Deflate( outline_margin, CORNER_STRATEGY::CHAMFER_ALL_CORNERS, maxError );
  1722. holes.BooleanIntersection( deflatedOutline, SHAPE_POLY_SET::PM_FAST );
  1723. DUMP_POLYS_TO_COPPER_LAYER( holes, In12_Cu, wxT( "outline-clipped-hatch-holes" ) );
  1724. if( aZone->GetNetCode() != 0 )
  1725. {
  1726. // Vias and pads connected to the zone must not be allowed to become isolated inside
  1727. // one of the holes. Effectively this means their copper outline needs to be expanded
  1728. // to be at least as wide as the gap so that it is guaranteed to touch at least one
  1729. // edge.
  1730. BOX2I zone_boundingbox = aZone->GetBoundingBox();
  1731. SHAPE_POLY_SET aprons;
  1732. int min_apron_radius = ( aZone->GetHatchGap() * 10 ) / 19;
  1733. for( PCB_TRACK* track : m_board->Tracks() )
  1734. {
  1735. if( track->Type() == PCB_VIA_T )
  1736. {
  1737. PCB_VIA* via = static_cast<PCB_VIA*>( track );
  1738. if( via->GetNetCode() == aZone->GetNetCode()
  1739. && via->IsOnLayer( aLayer )
  1740. && via->GetBoundingBox().Intersects( zone_boundingbox ) )
  1741. {
  1742. int r = std::max( min_apron_radius,
  1743. via->GetDrillValue() / 2 + outline_margin );
  1744. TransformCircleToPolygon( aprons, via->GetPosition(), r, maxError,
  1745. ERROR_OUTSIDE );
  1746. }
  1747. }
  1748. }
  1749. for( FOOTPRINT* footprint : m_board->Footprints() )
  1750. {
  1751. for( PAD* pad : footprint->Pads() )
  1752. {
  1753. if( pad->GetNetCode() == aZone->GetNetCode()
  1754. && pad->IsOnLayer( aLayer )
  1755. && pad->GetBoundingBox().Intersects( zone_boundingbox ) )
  1756. {
  1757. // What we want is to bulk up the pad shape so that the narrowest bit of
  1758. // copper between the hole and the apron edge is at least outline_margin
  1759. // wide (and that the apron itself meets min_apron_radius. But that would
  1760. // take a lot of code and math, and the following approximation is close
  1761. // enough.
  1762. int pad_width = std::min( pad->GetSize().x, pad->GetSize().y );
  1763. int slot_width = std::min( pad->GetDrillSize().x, pad->GetDrillSize().y );
  1764. int min_annular_ring_width = ( pad_width - slot_width ) / 2;
  1765. int clearance = std::max( min_apron_radius - pad_width / 2,
  1766. outline_margin - min_annular_ring_width );
  1767. clearance = std::max( 0, clearance - linethickness / 2 );
  1768. pad->TransformShapeToPolygon( aprons, aLayer, clearance, maxError,
  1769. ERROR_OUTSIDE );
  1770. }
  1771. }
  1772. }
  1773. holes.BooleanSubtract( aprons, SHAPE_POLY_SET::PM_FAST );
  1774. }
  1775. DUMP_POLYS_TO_COPPER_LAYER( holes, In13_Cu, wxT( "pad-via-clipped-hatch-holes" ) );
  1776. // Now filter truncated holes to avoid small holes in pattern
  1777. // It happens for holes near the zone outline
  1778. for( int ii = 0; ii < holes.OutlineCount(); )
  1779. {
  1780. double area = holes.Outline( ii ).Area();
  1781. if( area < minimal_hole_area ) // The current hole is too small: remove it
  1782. holes.DeletePolygon( ii );
  1783. else
  1784. ++ii;
  1785. }
  1786. // create grid. Use SHAPE_POLY_SET::PM_STRICTLY_SIMPLE to
  1787. // generate strictly simple polygons needed by Gerber files and Fracture()
  1788. aFillPolys.BooleanSubtract( aFillPolys, holes, SHAPE_POLY_SET::PM_STRICTLY_SIMPLE );
  1789. DUMP_POLYS_TO_COPPER_LAYER( aFillPolys, In14_Cu, wxT( "after-hatching" ) );
  1790. return true;
  1791. }