KiCad PCB EDA Suite
Loading...
Searching...
No Matches
step_pcb_model.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 (C) 2022 Mark Roszko <[email protected]>
5 * Copyright (C) 2016 Cirilo Bernardo <[email protected]>
6 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 2
11 * of the License, or (at your 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, see <https://www.gnu.org/licenses/>.
20 */
21
22#include <algorithm>
23#include <cmath>
24#include <functional>
25#include <new>
26#include <sstream>
27#include <string>
28#include <utility>
29#include <wx/file.h>
30#include <wx/filename.h>
31#include <wx/filefn.h>
32#include <wx/sstream.h>
33#include <wx/stdpaths.h>
34#include <wx/stream.h>
35#include <wx/string.h>
36#include <wx/zstream.h>
37#include <wx/wfstream.h>
38#include <wx/zipstrm.h>
39#include <wx/stdstream.h>
40#include <wx/crt.h>
41
42#include <decompress.hpp>
43
44#include <thread_pool.h>
45#include <trace_helpers.h>
46#include <board.h>
48#include <footprint.h>
50#include <pcb_3d_body.h>
51#include <pad.h>
52#include <pcb_track.h>
53#include <kiplatform/io.h>
54#include <string_utils.h>
55#include <build_version.h>
60#include <reporter.h>
61
63
65#include <pcb_painter.h>
66
67#include "step_pcb_model.h"
68#include "streamwrapper.h"
69
70#include <IGESCAFControl_Reader.hxx>
71#include <IGESCAFControl_Writer.hxx>
72#include <IGESControl_Controller.hxx>
73#include <IGESData_GlobalSection.hxx>
74#include <IGESData_IGESModel.hxx>
75#include <Interface_Static.hxx>
76#include <Quantity_Color.hxx>
77#include <STEPCAFControl_Reader.hxx>
78#include <STEPCAFControl_Writer.hxx>
79#include <APIHeaderSection_MakeHeader.hxx>
80#include <Standard_Failure.hxx>
81#include <Standard_Handle.hxx>
82#include <Standard_Version.hxx>
83#include <TCollection_AsciiString.hxx>
84#include <TCollection_ExtendedString.hxx>
85#include <TDocStd_Document.hxx>
86#include <TDataStd_Name.hxx>
87#include <TDataStd_TreeNode.hxx>
88#include <TDF_ChildIterator.hxx>
89#include <NCollection_IndexedDataMap.hxx>
90#include <NCollection_IndexedMap.hxx>
91#include <NCollection_Sequence.hxx>
92#include <TDF_Tool.hxx>
93#include <TopTools_ShapeMapHasher.hxx>
94#include <TopExp_Explorer.hxx>
95#include <TopoDS.hxx>
96#include <XCAFApp_Application.hxx>
97#include <XCAFDoc.hxx>
98#include <XCAFDoc_DocumentTool.hxx>
99#include <XCAFDoc_ColorTool.hxx>
100#include <XCAFDoc_ShapeTool.hxx>
101#include <XCAFDoc_VisMaterialTool.hxx>
102#include <XCAFDoc_Area.hxx>
103#include <XCAFDoc_Centroid.hxx>
104#include <XCAFDoc_Editor.hxx>
105#include <XCAFDoc_Location.hxx>
106#include <XCAFDoc_Volume.hxx>
107#include "kicad3d_info.h"
108
109#include "KI_XCAFDoc_AssemblyGraph.hxx"
110
111#include <BRep_Tool.hxx>
112#include <BRepMesh_IncrementalMesh.hxx>
113#include <BRepBuilderAPI_GTransform.hxx>
114#include <BRepBuilderAPI_MakeEdge.hxx>
115#include <BRepBuilderAPI_MakeWire.hxx>
116#include <BRepBuilderAPI_MakeFace.hxx>
117#include <BRepExtrema_DistShapeShape.hxx>
118#include <BRepPrimAPI_MakeCone.hxx>
119#include <BRepPrimAPI_MakeCylinder.hxx>
120#include <BRepPrimAPI_MakePrism.hxx>
121#include <BRepTools.hxx>
122#include <BRepLib_MakeWire.hxx>
123#include <BRepAdaptor_Surface.hxx>
124#include <BRepAlgoAPI_Check.hxx>
125#include <BRepAlgoAPI_Cut.hxx>
126#include <BRepAlgoAPI_Fuse.hxx>
127#include <ShapeUpgrade_UnifySameDomain.hxx>
128
129#include <BRepBndLib.hxx>
130#include <Bnd_BoundSortBox.hxx>
131
132#if OCC_VERSION_HEX >= 0x080000
133#include <NCollection_HArray1.hxx>
134#else
135#include <Bnd_HArray1OfBox.hxx>
136#endif
137
138#include <GProp_GProps.hxx>
139#include <BRepGProp.hxx>
140
141#include <Geom_Curve.hxx>
142#include <Geom_TrimmedCurve.hxx>
143
144#include <gp_Ax2.hxx>
145#include <gp_Dir.hxx>
146#include <gp_Pnt.hxx>
147#include <GC_MakeArcOfCircle.hxx>
148#include <GC_MakeCircle.hxx>
149
150#include <RWGltf_CafWriter.hxx>
151#include <StlAPI_Writer.hxx>
152
153#if OCC_VERSION_HEX < 0x080000
154#include <TColStd_IndexedDataMapOfStringString.hxx>
155#endif
156
157#include "glb_utils.h"
158
159#if OCC_VERSION_HEX >= 0x070700
160#include <VrmlAPI_CafReader.hxx>
161#include <RWPly_CafWriter.hxx>
162#endif
163
164#include <macros.h>
166
167static constexpr double USER_PREC = 1e-4;
168static constexpr double USER_ANGLE_PREC = 1e-6;
169
170
171static const char* occFailureMessage( const Standard_Failure& aFailure )
172{
173#if OCC_VERSION_HEX >= 0x080000
174 return aFailure.what();
175#else
176 return aFailure.GetMessageString();
177#endif
178}
179
180// nominal offset from the board
181static constexpr double BOARD_OFFSET = 0.05;
182
183// supported file types for 3D models
195
196
197MODEL3D_FORMAT_TYPE fileType( const char* aFileName )
198{
199 wxFileName lfile( wxString::FromUTF8Unchecked( aFileName ) );
200
201 if( !lfile.FileExists() )
202 return FMT_NONE;
203
204 wxString ext = lfile.GetExt().Lower();
205
206 if( ext == wxT( "wrl" ) )
207 return FMT_WRL;
208
209 if( ext == wxT( "wrz" ) )
210 return FMT_WRZ;
211
212 if( ext == wxT( "idf" ) )
213 return FMT_IDF; // component outline
214
215 if( ext == wxT( "emn" ) )
216 return FMT_EMN; // PCB assembly
217
218 if( ext == wxT( "stpz" ) || ext == wxT( "gz" ) )
219 return FMT_STEPZ;
220
221 OPEN_ISTREAM( ifile, aFileName );
222
223 if( ifile.fail() )
224 return FMT_NONE;
225
226 char iline[82];
227 MODEL3D_FORMAT_TYPE format_type = FMT_NONE;
228
229 // The expected header should be the first line.
230 // However some files can have a comment at the beginning of the file
231 // So read up to max_line_count lines to try to find the actual header
232 const int max_line_count = 3;
233
234 for( int ii = 0; ii < max_line_count; ii++ )
235 {
236 memset( iline, 0, 82 );
237 ifile.getline( iline, 82 );
238
239 iline[81] = 0; // ensure NULL termination when string is too long
240
241 // check for STEP in Part 21 format
242 // (this can give false positives since Part 21 is not exclusively STEP)
243 if( !strncmp( iline, "ISO-10303-21;", 13 ) )
244 {
245 format_type = FMT_STEP;
246 break;
247 }
248
249 std::string fstr = iline;
250
251 // check for STEP in XML format
252 // (this can give both false positive and false negatives)
253 if( fstr.find( "urn:oid:1.0.10303." ) != std::string::npos )
254 {
255 format_type = FMT_STEP;
256 break;
257 }
258
259 // Note: this is a very simple test which can yield false positives; the only
260 // sure method for determining if a file *not* an IGES model is to attempt
261 // to load it.
262 if( iline[72] == 'S' && ( iline[80] == 0 || iline[80] == 13 || iline[80] == 10 ) )
263 {
264 format_type = FMT_IGES;
265 break;
266 }
267
268 // Only a comment (starting by "/*") is allowed as header
269 if( strncmp( iline, "/*", 2 ) != 0 ) // not a comment
270 break;
271 }
272
273 CLOSE_STREAM( ifile );
274
275 return format_type;
276}
277
278
280 const VECTOR2D& p3 )
281{
283
284 // Move coordinate origin to p2, to simplify calculations
285 VECTOR2D b = p1 - p2;
286 VECTOR2D d = p3 - p2;
287 double bc = ( b.x * b.x + b.y * b.y ) / 2.0;
288 double cd = ( -d.x * d.x - d.y * d.y ) / 2.0;
289 double det = -b.x * d.y + d.x * b.y;
290
291 // We're fine with divisions by 0
292 det = 1.0 / det;
293 center.x = ( -bc * d.y - cd * b.y ) * det;
294 center.y = ( b.x * cd + d.x * bc ) * det;
295 center += p2;
296
297 return center;
298}
299
300
301#define APPROX_DBG( stmt )
302//#define APPROX_DBG( stmt ) stmt
303
305{
306 // An algo that takes 3 points, calculates a circle center,
307 // then tries to find as many points fitting the circle.
308
309 static const double c_radiusDeviation = 1000.0;
310 static const double c_arcCenterDeviation = 1000.0;
311 static const double c_relLengthDeviation = 0.8;
312 static const int c_last_none = -1000; // Meaning the arc cannot be constructed
313 // Allow larger angles for segments below this size
314 static const double c_smallSize = pcbIUScale.mmToIU( 0.1 );
315 static const double c_circleCloseGap = pcbIUScale.mmToIU( 1.0 );
316 // Minimum arc central angle to avoid converting nearly-straight segments to arcs
317 static const EDA_ANGLE c_minArcCentralAngle( 10.0, DEGREES_T );
318
319 APPROX_DBG( std::cout << std::endl );
320
321 if( aSrc.PointCount() < 4 )
322 return aSrc;
323
324 if( !aSrc.IsClosed() )
325 return aSrc; // non-closed polygons are not supported
326
328
329 int jEndIdx = aSrc.PointCount() - 3;
330
331 for( int i = 0; i < aSrc.PointCount(); i++ )
332 {
333 int first = i - 3;
334 int last = c_last_none;
335
336 VECTOR2D p0 = aSrc.CPoint( i - 3 );
337 VECTOR2D p1 = aSrc.CPoint( i - 2 );
338 VECTOR2D p2 = aSrc.CPoint( i - 1 );
339
340 APPROX_DBG( std::cout << i << " " << aSrc.CPoint( i ) << " " << ( i - 3 ) << " "
341 << VECTOR2I( p0 ) << " " << ( i - 2 ) << " " << VECTOR2I( p1 ) << " "
342 << ( i - 1 ) << " " << VECTOR2I( p2 ) << std::endl );
343
344 VECTOR2D v01 = p1 - p0;
345 VECTOR2D v12 = p2 - p1;
346
347 bool defective = false;
348
349 double d01 = v01.EuclideanNorm();
350 double d12 = v12.EuclideanNorm();
351
352 // Check distance differences between 3 first points
353 defective |= std::abs( d01 - d12 ) > ( std::max( d01, d12 ) * c_relLengthDeviation );
354
355 if( !defective )
356 {
357 // Check angles between 3 first points
358 EDA_ANGLE a01( v01 );
359 EDA_ANGLE a12( v12 );
360
361 double a_diff = ( a01 - a12 ).Normalize180().AsDegrees();
362 defective |= std::abs( a_diff ) < 0.1;
363
364 // Larger angles are allowed for smaller geometry
365 double maxAngleDiff = std::max( d01, d12 ) < c_smallSize ? 46.0 : 30.0;
366 defective |= std::abs( a_diff ) >= maxAngleDiff;
367 }
368
369 if( !defective )
370 {
371 // Find last point lying on the circle created from 3 first points
373 double radius = ( p0 - center ).EuclideanNorm();
374 VECTOR2D p_prev = p2;
375 EDA_ANGLE a_prev( v12 );
376
377 for( int j = i; j <= jEndIdx; j++ )
378 {
379 VECTOR2D p_test = aSrc.CPoint( j );
380
381 EDA_ANGLE a_test( p_test - p_prev );
382 double rad_test = ( p_test - center ).EuclideanNorm();
383 double d_tl = ( p_test - p_prev ).EuclideanNorm();
384 double rad_dev = std::abs( radius - rad_test );
385
386 APPROX_DBG( std::cout << " " << j << " " << aSrc.CPoint( j ) << " rad "
387 << int64_t( rad_test ) << " ref " << int64_t( radius )
388 << std::endl );
389
390 if( rad_dev > c_radiusDeviation )
391 {
392 APPROX_DBG( std::cout << " " << j
393 << " Radius deviation too large: " << int64_t( rad_dev )
394 << " > " << c_radiusDeviation << std::endl );
395 break;
396 }
397
398 // Larger angles are allowed for smaller geometry
399 double maxAngleDiff =
400 std::max( std::max( d01, d12 ), d_tl ) < c_smallSize ? 46.0 : 30.0;
401
402 double a_diff_test = ( a_prev - a_test ).Normalize180().AsDegrees();
403 if( std::abs( a_diff_test ) >= maxAngleDiff )
404 {
405 APPROX_DBG( std::cout << " " << j << " Angles differ too much " << a_diff_test
406 << std::endl );
407 break;
408 }
409
410 if( std::abs( d_tl - d01 ) > ( std::max( d_tl, d01 ) * c_relLengthDeviation ) )
411 {
412 APPROX_DBG( std::cout << " " << j << " Lengths differ too much " << d_tl
413 << "; " << d01 << std::endl );
414 break;
415 }
416
417 last = j;
418 p_prev = p_test;
419 a_prev = a_test;
420 }
421 }
422
423 if( last != c_last_none )
424 {
425 // Try to add an arc, testing for self-interference
426 SHAPE_ARC arc( aSrc.CPoint( first ), aSrc.CPoint( ( first + last ) / 2 ),
427 aSrc.CPoint( last ), 0 );
428
429 // Reject arcs with small central angles as they represent nearly-straight segments.
430 // A large-radius arc through nearly-collinear points should remain as line segments.
431 EDA_ANGLE centralAngle = arc.GetCentralAngle();
432
433 if( std::abs( centralAngle.AsDegrees() ) < c_minArcCentralAngle.AsDegrees() )
434 {
435 APPROX_DBG( std::cout << " Arc central angle too small: "
436 << centralAngle.AsDegrees() << " < "
437 << c_minArcCentralAngle.AsDegrees() << std::endl );
438 last = c_last_none;
439 }
440
441 // Verify that all intermediate points are close to the arc curve. This prevents
442 // falsely identifying corners as arcs.
443 for( int k = first + 1; last != c_last_none && k < last; k++ )
444 {
445 VECTOR2I pt = aSrc.CPoint( k );
446 VECTOR2I nearest = arc.NearestPoint( pt );
447 double dist = ( VECTOR2D( pt ) - VECTOR2D( nearest ) ).EuclideanNorm();
448
449 if( dist > c_radiusDeviation )
450 {
451 APPROX_DBG( std::cout << " Point " << k << " too far from arc: " << dist
452 << " > " << c_radiusDeviation << std::endl );
453 last = c_last_none;
454 }
455 }
456
457 if( last != c_last_none )
458 {
459 if( last > aSrc.PointCount() - 3 && !dst.IsArcSegment( 0 ) )
460 {
461 // If we've found an arc at the end, but already added segments at the start, remove them.
462 int toRemove = last - ( aSrc.PointCount() - 3 );
463
464 while( toRemove )
465 {
466 dst.RemoveShape( 0 );
467 toRemove--;
468 }
469 }
470
471 SHAPE_LINE_CHAIN testChain = dst;
472
473 testChain.Append( arc );
474 testChain.Append( aSrc.Slice( last, std::max( last, aSrc.PointCount() - 3 ) ) );
475 testChain.SetClosed( aSrc.IsClosed() );
476
477 if( !testChain.SelfIntersectingWithArcs() )
478 {
479 // Add arc
480 dst.Append( arc );
481
482 APPROX_DBG( std::cout << " Add arc start " << arc.GetP0() << " mid "
483 << arc.GetArcMid() << " end " << arc.GetP1() << std::endl );
484
485 i = last + 3;
486 }
487 else
488 {
489 // Self-interference
490 last = c_last_none;
491
492 APPROX_DBG( std::cout << " Self-intersection check failed" << std::endl );
493 }
494 }
495 }
496
497 if( last == c_last_none )
498 {
499 if( first < 0 )
500 jEndIdx = first + aSrc.PointCount();
501
502 // Add point
503 dst.Append( p0 );
504 APPROX_DBG( std::cout << " Add pt " << VECTOR2I( p0 ) << std::endl );
505 }
506 }
507
508 dst.SetClosed( true );
509
510 // Try to merge arcs
511 int iarc0 = dst.ArcIndex( 0 );
512 int iarc1 = dst.ArcIndex( dst.GetSegmentCount() - 1 );
513
514 if( iarc0 != -1 && iarc1 != -1 )
515 {
516 APPROX_DBG( std::cout << "Final arcs " << iarc0 << " " << iarc1 << std::endl );
517
518 if( iarc0 == iarc1 )
519 {
520 SHAPE_ARC arc = dst.Arc( iarc0 );
521
522 VECTOR2D p0 = arc.GetP0();
523 VECTOR2D p1 = arc.GetP1();
524
525 // If we have only one arc and the gap is small, make it a circle
526 if( ( p1 - p0 ).EuclideanNorm() < c_circleCloseGap )
527 {
528 dst.Clear();
529 dst.Append( SHAPE_ARC( arc.GetCenter(), arc.GetP0(), ANGLE_360 ) );
530 }
531 }
532 else
533 {
534 // Merge first and last arcs if they are similar
535 SHAPE_ARC arc0 = dst.Arc( iarc0 );
536 SHAPE_ARC arc1 = dst.Arc( iarc1 );
537
538 VECTOR2D ac0 = arc0.GetCenter();
539 VECTOR2D ac1 = arc1.GetCenter();
540
541 double ar0 = arc0.GetRadius();
542 double ar1 = arc1.GetRadius();
543
544 if( std::abs( ar0 - ar1 ) <= c_radiusDeviation
545 && ( ac0 - ac1 ).EuclideanNorm() <= c_arcCenterDeviation )
546 {
547 dst.RemoveShape( 0 );
548 dst.RemoveShape( -1 );
549
550 SHAPE_ARC merged( arc1.GetP0(), arc1.GetArcMid(), arc0.GetP1(), 0 );
551
552 dst.Append( merged );
553 }
554 }
555 }
556
557 return dst;
558}
559
560
561static TopoDS_Shape getOneShape( Handle( XCAFDoc_ShapeTool ) aShapeTool )
562{
563 NCollection_Sequence<TDF_Label> theLabels;
564 aShapeTool->GetFreeShapes( theLabels );
565
566 TopoDS_Shape aShape;
567
568 if( theLabels.Length() == 1 )
569 return aShapeTool->GetShape( theLabels.Value( 1 ) );
570
571 TopoDS_Compound aCompound;
572 BRep_Builder aBuilder;
573 aBuilder.MakeCompound( aCompound );
574
575 for( NCollection_Sequence<TDF_Label>::Iterator anIt( theLabels ); anIt.More(); anIt.Next() )
576 {
577 TopoDS_Shape aFreeShape;
578
579 if( !aShapeTool->GetShape( anIt.Value(), aFreeShape ) )
580 continue;
581
582 aBuilder.Add( aCompound, aFreeShape );
583 }
584
585 if( aCompound.NbChildren() > 0 )
586 aShape = aCompound;
587
588 return aShape;
589}
590
591
592// Apply scaling to shapes within theLabel.
593// Based on XCAFDoc_Editor::RescaleGeometry
594static bool rescaleShapes( const TDF_Label& theLabel, const gp_XYZ& aScale )
595{
596 if( theLabel.IsNull() )
597 {
598 Message::SendFail( "Null label." );
599 return false;
600 }
601
602 if( std::abs( aScale.X() ) <= gp::Resolution() || std::abs( aScale.Y() ) <= gp::Resolution()
603 || std::abs( aScale.Z() ) <= gp::Resolution() )
604 {
605 Message::SendFail( "Scale factor is too small." );
606 return false;
607 }
608
609 Handle( XCAFDoc_ShapeTool ) aShapeTool = XCAFDoc_DocumentTool::ShapeTool( theLabel );
610
611 if( aShapeTool.IsNull() )
612 {
613 Message::SendFail( "Couldn't find XCAFDoc_ShapeTool attribute." );
614 return false;
615 }
616
617 Handle( KI_XCAFDoc_AssemblyGraph ) aG = new KI_XCAFDoc_AssemblyGraph( theLabel );
618
619 if( aG.IsNull() )
620 {
621 Message::SendFail( "Couldn't create assembly graph." );
622 return false;
623 }
624
625 bool anIsDone = true;
626
627 // clang-format off
628 gp_GTrsf aGTrsf;
629 aGTrsf.SetVectorialPart( gp_Mat( aScale.X(), 0, 0,
630 0, aScale.Y(), 0,
631 0, 0, aScale.Z() ) );
632 // clang-format on
633
634 BRepBuilderAPI_GTransform aBRepTrsf( aGTrsf );
635
636 for( int idx = 1; idx <= aG->NbNodes(); idx++ )
637 {
638 const KI_XCAFDoc_AssemblyGraph::NodeType aNodeType = aG->GetNodeType( idx );
639
640 if( ( aNodeType != KI_XCAFDoc_AssemblyGraph::NodeType_Part )
641 && ( aNodeType != KI_XCAFDoc_AssemblyGraph::NodeType_Occurrence ) )
642 {
643 continue;
644 }
645
646 const TDF_Label& aLabel = aG->GetNode( idx );
647
648 if( aNodeType == KI_XCAFDoc_AssemblyGraph::NodeType_Part )
649 {
650 const TopoDS_Shape aShape = aShapeTool->GetShape( aLabel );
651 aBRepTrsf.Perform( aShape, true );
652 if( !aBRepTrsf.IsDone() )
653 {
654 Standard_SStream aSS;
655 TCollection_AsciiString anEntry;
656 TDF_Tool::Entry( aLabel, anEntry );
657 aSS << "Shape " << anEntry << " is not scaled!";
658 Message::SendFail( aSS.str().c_str() );
659 anIsDone = false;
660 return false;
661 }
662 TopoDS_Shape aScaledShape = aBRepTrsf.Shape();
663 aShapeTool->SetShape( aLabel, aScaledShape );
664
665 // Update sub-shapes
666 NCollection_Sequence<TDF_Label> aSubshapes;
667 aShapeTool->GetSubShapes( aLabel, aSubshapes );
668 for( NCollection_Sequence<TDF_Label>::Iterator anItSs( aSubshapes ); anItSs.More(); anItSs.Next() )
669 {
670 const TDF_Label& aLSs = anItSs.Value();
671 const TopoDS_Shape aSs = aShapeTool->GetShape( aLSs );
672 const TopoDS_Shape aSs1 = aBRepTrsf.ModifiedShape( aSs );
673 aShapeTool->SetShape( aLSs, aSs1 );
674 }
675
676 // These attributes will be recomputed eventually, but clear them just in case
677 aLabel.ForgetAttribute( XCAFDoc_Area::GetID() );
678 aLabel.ForgetAttribute( XCAFDoc_Centroid::GetID() );
679 aLabel.ForgetAttribute( XCAFDoc_Volume::GetID() );
680 }
681 else if( aNodeType == KI_XCAFDoc_AssemblyGraph::NodeType_Occurrence )
682 {
683 TopLoc_Location aLoc = aShapeTool->GetLocation( aLabel );
684 gp_Trsf aTrsf = aLoc.Transformation();
685 aTrsf.SetTranslationPart( aTrsf.TranslationPart().Multiplied( aScale ) );
686 XCAFDoc_Location::Set( aLabel, aTrsf );
687 }
688 }
689
690 if( !anIsDone )
691 {
692 return false;
693 }
694
695 aShapeTool->UpdateAssemblies();
696
697 return anIsDone;
698}
699
700
701static bool fuseShapes( auto& aInputShapes, TopoDS_Shape& aOutShape, REPORTER* aReporter )
702{
703 BRepAlgoAPI_Fuse mkFuse;
704 NCollection_List<TopoDS_Shape> shapeArguments, shapeTools;
705
706 for( const TopoDS_Shape& sh : aInputShapes )
707 {
708 if( sh.IsNull() )
709 continue;
710
711 if( shapeArguments.IsEmpty() )
712 shapeArguments.Append( sh );
713 else
714 shapeTools.Append( sh );
715 }
716
717 try
718 {
719 // Non-destructive mode keeps OCC from mutating the shared input TShapes (pcurve and
720 // tolerance writes), which is what lets these ops run on parallel worker threads.
721 mkFuse.SetNonDestructive( true );
722 mkFuse.SetRunParallel( true );
723 mkFuse.SetToFillHistory( false );
724 mkFuse.SetArguments( shapeArguments );
725 mkFuse.SetTools( shapeTools );
726 mkFuse.Build();
727 }
728 catch( const std::bad_alloc& )
729 {
730 aReporter->Report( _( "Out of memory while fusing shapes. Consider disabling shape fusing, "
731 "reducing the number of objects (e.g., vias), or freeing system memory." ),
733 return false;
734 }
735 catch( const Standard_Failure& e )
736 {
737 aReporter->Report( wxString::Format( _( "OpenCASCADE error while fusing shapes: %s\n"
738 "This may indicate insufficient memory. Consider "
739 "disabling shape fusing or reducing board complexity." ),
740 occFailureMessage( e ) ),
742 return false;
743 }
744
745 if( mkFuse.HasErrors() || mkFuse.HasWarnings() )
746 {
747 aReporter->Report( _( "Problems encountered while fusing shapes. This operation is "
748 "memory-intensive; insufficient memory may cause failures." ),
750
751 if( mkFuse.HasErrors() )
752 {
753 wxString msg = _( "Errors:\n" );
754 wxStringOutputStream os_stream( &msg );
755 wxStdOutputStream out( os_stream );
756
757 mkFuse.DumpErrors( out );
758 aReporter->Report( msg, RPT_SEVERITY_ERROR );
759 }
760
761 if( mkFuse.HasWarnings() )
762 {
763 wxString msg = _( "Warnings:\n" );
764 wxStringOutputStream os_stream( &msg );
765 wxStdOutputStream out( os_stream );
766
767 mkFuse.DumpWarnings( out );
768 aReporter->Report( msg, RPT_SEVERITY_WARNING );
769 }
770 }
771
772 if( mkFuse.IsDone() )
773 {
774 TopoDS_Shape fusedShape = mkFuse.Shape();
775
776 try
777 {
778 ShapeUpgrade_UnifySameDomain unify( fusedShape, true, true, false );
779 unify.SetSafeInputMode( true );
780 unify.History() = nullptr;
781 unify.Build();
782
783 TopoDS_Shape unifiedShapes = unify.Shape();
784
785 if( unifiedShapes.IsNull() )
786 {
787 aReporter->Report( _( "ShapeUpgrade_UnifySameDomain produced a null shape." ),
789 }
790 else
791 {
792 aOutShape = unifiedShapes;
793 return true;
794 }
795 }
796 catch( const std::bad_alloc& )
797 {
798 aReporter->Report( _( "Out of memory while unifying shape domains. Consider disabling "
799 "shape fusing or reducing the number of objects." ),
801 return false;
802 }
803 catch( const Standard_Failure& e )
804 {
805 aReporter->Report( wxString::Format( _( "OpenCASCADE error while unifying shapes: %s" ),
806 occFailureMessage( e ) ),
808 return false;
809 }
810 }
811
812 return false;
813}
814
815
816static TopoDS_Compound makeCompound( const auto& aInputShapes )
817{
818 TopoDS_Compound compound;
819 BRep_Builder builder;
820 builder.MakeCompound( compound );
821
822 for( const TopoDS_Shape& shape : aInputShapes )
823 builder.Add( compound, shape );
824
825 return compound;
826}
827
828
829// Try to fuse shapes. If that fails, just add them to a compound
830static TopoDS_Shape fuseShapesOrCompound( const NCollection_List<TopoDS_Shape>& aInputShapes, REPORTER* aReporter )
831{
832 TopoDS_Shape outShape;
833
834 if( aInputShapes.Size() == 1 )
835 return aInputShapes.First();
836
837 if( fuseShapes( aInputShapes, outShape, aReporter ) )
838 return outShape;
839
840 return makeCompound( aInputShapes );
841}
842
843
844// Sets names in assembly to <aPrefix> (<old name>), or to <aPrefix>
845static bool prefixNames( const TDF_Label& aLabel,
846 const TCollection_ExtendedString& aPrefix )
847{
848 Handle( KI_XCAFDoc_AssemblyGraph ) aG = new KI_XCAFDoc_AssemblyGraph( aLabel );
849
850 if( aG.IsNull() )
851 {
852 Message::SendFail( "Couldn't create assembly graph." );
853 return false;
854 }
855
856 bool anIsDone = true;
857
858 for( int idx = 1; idx <= aG->NbNodes(); idx++ )
859 {
860 const TDF_Label& lbl = aG->GetNode( idx );
861 Handle( TDataStd_Name ) nameHandle;
862
863 if( lbl.FindAttribute( TDataStd_Name::GetID(), nameHandle ) )
864 {
865 TCollection_ExtendedString name;
866
867 name += aPrefix;
868 name += " (";
869 name += nameHandle->Get();
870 name += ")";
871
872 TDataStd_Name::Set( lbl, name );
873 }
874 else
875 {
876 TDataStd_Name::Set( lbl, aPrefix );
877 }
878 }
879
880 return anIsDone;
881}
882
883
884STEP_PCB_MODEL::STEP_PCB_MODEL( const wxString& aPcbName, REPORTER* aReporter ) :
885 m_syncReporter( *aReporter ),
887{
888 m_app = XCAFApp_Application::GetApplication();
889 m_app->NewDocument( "MDTV-XCAF", m_doc );
890 m_assy = XCAFDoc_DocumentTool::ShapeTool( m_doc->Main() );
891 m_assy_label = m_assy->NewShape();
892 m_hasPCB = false;
893 m_simplifyShapes = true;
894 m_components = 0;
898 m_minx = 1.0e10; // absurdly large number; any valid PCB X value will be smaller
899 m_pcbName = aPcbName;
900 m_fuseShapes = false;
901 m_extraPadThickness = true;
903}
904
905
907{
908 if( m_doc->CanClose() == CDM_CCS_OK )
909 m_doc->Close();
910}
911
912
913bool STEP_PCB_MODEL::AddPadShape( const PAD* aPad, const VECTOR2D& aOrigin, bool aVia,
914 SHAPE_POLY_SET* aClipPolygon )
915{
916 const double c_padExtraThickness = 0.005;
917 bool success = true;
918 std::vector<TopoDS_Shape> padShapes;
919 bool castellated = aClipPolygon && aPad->GetProperty() == PAD_PROP::CASTELLATED;
920
921 for( PCB_LAYER_ID pcb_layer : aPad->GetLayerSet().Seq() )
922 {
923 if( !m_enabledLayers.Contains( pcb_layer ) )
924 continue;
925
926 if( pcb_layer == F_Mask || pcb_layer == B_Mask )
927 continue;
928
929 if( !aPad->FlashLayer( pcb_layer ) )
930 continue;
931
932 double Zpos, thickness;
933 getLayerZPlacement( pcb_layer, Zpos, thickness );
934
935 if( !aVia && m_extraPadThickness )
936 {
937 // Pad surface as a separate face for FEM simulations.
938 if( pcb_layer == F_Cu )
939 thickness += c_padExtraThickness;
940 else if( pcb_layer == B_Cu )
941 thickness -= c_padExtraThickness;
942 }
943
944 TopoDS_Shape testShape;
945
946 // Make a shape on copper layers
947 SHAPE_POLY_SET polySet;
948 aPad->TransformShapeToPolygon( polySet, pcb_layer, 0, aPad->GetMaxError(), ERROR_INSIDE );
949
950 if( castellated )
951 {
952 polySet.ClearArcs();
953 polySet.BooleanIntersection( *aClipPolygon );
954 }
955
956 success &= MakeShapes( padShapes, polySet, m_simplifyShapes, thickness, Zpos, aOrigin );
957
958 if( testShape.IsNull() )
959 {
960 std::vector<TopoDS_Shape> testShapes;
961
962 MakeShapes( testShapes, polySet, m_simplifyShapes, 0.0, Zpos + thickness, aOrigin );
963
964 if( testShapes.size() > 0 )
965 testShape = testShapes.front();
966 }
967
968 if( !aVia && m_extraPadThickness && !testShape.IsNull() )
969 {
970 if( pcb_layer == F_Cu || pcb_layer == B_Cu )
971 {
972 wxString name;
973
974 name << "Pad_";
975
976 if( pcb_layer == F_Cu )
977 name << 'F' << '_';
978 else if( pcb_layer == B_Cu )
979 name << 'B' << '_';
980
981 name << aPad->GetParentFootprint()->GetReferenceAsString() << '_'
982 << aPad->GetNumber() << '_' << aPad->GetShortNetname();
983
984 gp_Pnt point( pcbIUScale.IUTomm( aPad->GetX() - aOrigin.x ),
985 -pcbIUScale.IUTomm( aPad->GetY() - aOrigin.y ), Zpos + thickness );
986
987 m_pad_points[name].emplace_back( point, testShape );
988 }
989 }
990 }
991
992 if( aPad->GetAttribute() == PAD_ATTRIB::PTH && aPad->IsOnLayer( F_Cu ) && aPad->IsOnLayer( B_Cu ) )
993 {
994 double f_pos, f_thickness;
995 double b_pos, b_thickness;
996 getLayerZPlacement( F_Cu, f_pos, f_thickness );
997 getLayerZPlacement( B_Cu, b_pos, b_thickness );
998
999 if( !aVia && m_extraPadThickness )
1000 {
1001 // Pad surface is slightly thicker
1002 f_thickness += c_padExtraThickness;
1003 b_thickness -= c_padExtraThickness;
1004 }
1005
1006 double top = std::max( f_pos, f_pos + f_thickness );
1007 double bottom = std::min( b_pos, b_pos + b_thickness );
1008 double hole_height = top - bottom;
1009
1010 TopoDS_Shape plating;
1011
1012 std::shared_ptr<SHAPE_SEGMENT> seg_hole = aPad->GetEffectiveHoleShape();
1013 double width = std::min( aPad->GetDrillSize().x, aPad->GetDrillSize().y );
1014
1015 if( !castellated )
1016 {
1017 if( MakeShapeAsThickSegment( plating, seg_hole->GetSeg().A, seg_hole->GetSeg().B, width,
1018 hole_height, bottom, aOrigin ) )
1019 {
1020 padShapes.push_back( plating );
1021 }
1022 else
1023 {
1024 success = false;
1025 }
1026 }
1027 else
1028 {
1029 // Note:
1030 // the truncated hole shape is exported as a vertical filled shape. The hole itself
1031 // will be removed later, when all holes are removed from the board
1032 SHAPE_POLY_SET polyHole;
1033
1034 if( seg_hole->GetSeg().A == seg_hole->GetSeg().B ) // Hole is a circle
1035 {
1036 TransformCircleToPolygon( polyHole, seg_hole->GetSeg().A, width/2,
1037 aPad->GetMaxError(), ERROR_OUTSIDE );
1038
1039 }
1040 else
1041 {
1042 TransformOvalToPolygon( polyHole, seg_hole->GetSeg().A, seg_hole->GetSeg().B, width,
1043 aPad->GetMaxError(), ERROR_OUTSIDE );
1044 }
1045
1046 polyHole.ClearArcs();
1047 polyHole.BooleanIntersection( *aClipPolygon );
1048
1049 if( MakePolygonAsWall( plating, polyHole, hole_height, bottom, aOrigin ) )
1050 {
1051 padShapes.push_back( plating );
1052 }
1053 else
1054 {
1055 success = false;
1056 }
1057 }
1058 }
1059
1060 if( !success ) // Error
1061 m_reporter->Report( _( "OCC error adding pad/via polygon." ), RPT_SEVERITY_ERROR );
1062
1063 if( !padShapes.empty() )
1064 {
1065 // Fuse pad shapes here before fusing them with tracks because OCCT sometimes has trouble
1066 if( m_fuseShapes )
1067 {
1068 NCollection_List<TopoDS_Shape> padShapesList;
1069
1070 for( const TopoDS_Shape& shape : padShapes )
1071 padShapesList.Append( shape );
1072
1073 m_board_copper_pads[aPad->GetNetname()].push_back( fuseShapesOrCompound( padShapesList, m_reporter ) );
1074 }
1075 else
1076 {
1077 for( const TopoDS_Shape& shape : padShapes )
1078 m_board_copper_pads[aPad->GetNetname()].push_back( shape );
1079 }
1080 }
1081
1082 return success;
1083}
1084
1085
1086bool STEP_PCB_MODEL::AddHole( const SHAPE_SEGMENT& aShape, int aPlatingThickness,
1087 PCB_LAYER_ID aLayerTop, PCB_LAYER_ID aLayerBot, bool aVia,
1088 const VECTOR2D& aOrigin, bool aCutCopper, bool aCutBody )
1089{
1090 double margin = 0.001; // a small margin on the Z axix to be sure the hole
1091 // is bigger than the board with copper
1092 // must be > OCC_MAX_DISTANCE_TO_MERGE_POINTS
1093
1094 // Pads are taller by 0.01 mm
1095 if( !aVia && m_extraPadThickness)
1096 margin += 0.01;
1097
1098 double f_pos, f_thickness;
1099 double b_pos, b_thickness;
1100 getLayerZPlacement( aLayerTop, f_pos, f_thickness );
1101 getLayerZPlacement( aLayerBot, b_pos, b_thickness );
1102 double top = std::max( f_pos, f_pos + f_thickness );
1103 double bottom = std::min( b_pos, b_pos + b_thickness );
1104
1105 double holeZsize = ( top - bottom ) + ( margin * 2 );
1106
1107 double boardDrill = aShape.GetWidth();
1108 double copperDrill = boardDrill - aPlatingThickness * 2;
1109
1110 TopoDS_Shape copperHole, boardHole;
1111
1112 if( aCutCopper )
1113 {
1114 if( MakeShapeAsThickSegment( copperHole, aShape.GetSeg().A, aShape.GetSeg().B, copperDrill,
1115 holeZsize, bottom - margin, aOrigin ) )
1116 {
1117 m_copperCutouts.push_back( copperHole );
1118 }
1119 else
1120 {
1121 return false;
1122 }
1123 }
1124
1125 if( aCutBody )
1126 {
1127 if( MakeShapeAsThickSegment( boardHole, aShape.GetSeg().A, aShape.GetSeg().B, boardDrill,
1128 holeZsize, bottom - margin, aOrigin ) )
1129 {
1130 m_boardCutouts.push_back( boardHole );
1131 }
1132 else
1133 {
1134 return false;
1135 }
1136 }
1137
1138 return true;
1139}
1140
1141
1143 PCB_LAYER_ID aLayerBot, bool aVia, const VECTOR2D& aOrigin,
1144 const wxString& aNetname )
1145{
1146 double f_pos, f_thickness;
1147 double b_pos, b_thickness;
1148 getLayerZPlacement( aLayerTop, f_pos, f_thickness );
1149 getLayerZPlacement( aLayerBot, b_pos, b_thickness );
1150 double top = std::max( f_pos, f_pos + f_thickness );
1151 double bottom = std::min( b_pos, b_pos + b_thickness );
1152
1153 TopoDS_Shape plating;
1154
1155 if( !MakeShapeAsThickSegment( plating, aShape.GetSeg().A, aShape.GetSeg().B, aShape.GetWidth(),
1156 ( top - bottom ), bottom, aOrigin ) )
1157 {
1158 return false;
1159 }
1160
1161 if( aVia )
1162 m_board_copper_vias[aNetname].push_back( plating );
1163 else
1164 m_board_copper_pads[aNetname].push_back( plating );
1165
1166 return true;
1167}
1168
1169
1171 PCB_LAYER_ID aLayerEnd, const VECTOR2D& aOrigin )
1172{
1173 // A backdrill removes board material and copper plating between two layers.
1174 // The backdrill typically starts from an outer layer and drills into an inner layer.
1175 // For example, a top backdrill starts at F_Cu and ends at an inner layer.
1176 // A bottom backdrill starts at B_Cu and ends at an inner layer.
1177
1178 double margin = 0.001; // a small margin on the Z axis to ensure the hole
1179 // is bigger than the board section being removed
1180
1181 // Extra margin to extend past outer copper layers to ensure complete annular ring removal
1182 double copperMargin = 0.5; // 0.5mm extra to cut through any copper/pad thickness
1183
1184 double start_pos, start_thickness;
1185 double end_pos, end_thickness;
1186 getLayerZPlacement( aLayerStart, start_pos, start_thickness );
1187 getLayerZPlacement( aLayerEnd, end_pos, end_thickness );
1188
1189 // Calculate the Z extent of the backdrill
1190 double top = std::max( { start_pos, start_pos + start_thickness,
1191 end_pos, end_pos + end_thickness } );
1192 double bottom = std::min( { start_pos, start_pos + start_thickness,
1193 end_pos, end_pos + end_thickness } );
1194
1195 // Extend past outer copper layers if the backdrill reaches them
1196 if( aLayerStart == F_Cu || aLayerEnd == F_Cu )
1197 top += copperMargin;
1198 if( aLayerStart == B_Cu || aLayerEnd == B_Cu )
1199 bottom -= copperMargin;
1200
1201 double holeZsize = ( top - bottom ) + ( margin * 2 );
1202 double holeZpos = bottom - margin;
1203
1204 double backdrillDiameter = aShape.GetWidth();
1205
1206 TopoDS_Shape backdrillHole;
1207
1208 // Create the backdrill hole shape - this cuts the board body
1209 if( MakeShapeAsThickSegment( backdrillHole, aShape.GetSeg().A, aShape.GetSeg().B,
1210 backdrillDiameter, holeZsize, holeZpos, aOrigin ) )
1211 {
1212 m_boardCutouts.push_back( backdrillHole );
1213
1214 // This removes annular rings and barrel copper between the backdrill layers.
1215 m_copperCutouts.push_back( backdrillHole );
1216 }
1217 else
1218 {
1219 return false;
1220 }
1221
1222 return true;
1223}
1224
1225
1226bool STEP_PCB_MODEL::AddCounterbore( const VECTOR2I& aPosition, int aDiameter, int aDepth,
1227 bool aFrontSide, const VECTOR2D& aOrigin )
1228{
1229 wxLogTrace( traceKiCad2Step, wxT( "AddCounterbore: pos=(%d,%d) diameter=%d depth=%d frontSide=%d origin=(%f,%f)" ),
1230 aPosition.x, aPosition.y, aDiameter, aDepth, aFrontSide ? 1 : 0, aOrigin.x, aOrigin.y );
1231
1232 // A counterbore is a cylindrical recess from the top or bottom of the board
1233 if( aDiameter <= 0 || aDepth <= 0 )
1234 {
1235 wxLogTrace( traceKiCad2Step, wxT( "AddCounterbore: REJECTED - invalid diameter=%d or depth=%d" ),
1236 aDiameter, aDepth );
1237 return false;
1238 }
1239
1240 double margin = 0.001; // small margin to ensure clean cuts
1241
1242 // Extra margin to extend past outer copper layers to ensure complete annular ring removal
1243 double copperMargin = 0.5; // 0.5mm extra to cut through any copper/pad thickness
1244
1245 // Get board body position (between copper layers)
1246 double boardZpos, boardThickness;
1247 getBoardBodyZPlacement( boardZpos, boardThickness );
1248
1249 // Get copper layer positions - these extend beyond the board body
1250 double f_pos, f_thickness, b_pos, b_thickness;
1251 getLayerZPlacement( F_Cu, f_pos, f_thickness );
1252 getLayerZPlacement( B_Cu, b_pos, b_thickness );
1253
1254 // Calculate actual outer surfaces including copper
1255 // F_Cu: f_pos is inner surface, f_pos + f_thickness is outer surface (copper extends upward)
1256 // B_Cu: b_pos is inner surface, b_pos + b_thickness is outer surface (thickness is negative, copper extends downward)
1257 double topOuterSurface = std::max( f_pos, f_pos + f_thickness );
1258 double bottomOuterSurface = std::min( b_pos, b_pos + b_thickness );
1259
1260 wxLogTrace( traceKiCad2Step, wxT( "AddCounterbore: boardZpos=%f boardThickness=%f f_pos=%f f_thickness=%f topOuter=%f bottomOuter=%f" ),
1261 boardZpos, boardThickness, f_pos, f_thickness, topOuterSurface, bottomOuterSurface );
1262
1263 // Convert dimensions to mm
1264 double diameter_mm = pcbIUScale.IUTomm( aDiameter );
1265 double depth_mm = pcbIUScale.IUTomm( aDepth );
1266 double radius_mm = diameter_mm / 2.0;
1267
1268 wxLogTrace( traceKiCad2Step, wxT( "AddCounterbore: diameter_mm=%f depth_mm=%f radius_mm=%f" ),
1269 diameter_mm, depth_mm, radius_mm );
1270
1271 // Calculate cylinder position based on which side
1272 // The cylinder must extend past the outer surface to ensure complete copper removal
1273 double cylinderZpos;
1274 double cylinderHeight;
1275
1276 if( aFrontSide )
1277 {
1278 // Counterbore from top - cylinder extends from above outer copper surface down to depth
1279 // Add copperMargin above the surface to ensure complete annular ring removal
1280 cylinderZpos = topOuterSurface - depth_mm - margin;
1281 cylinderHeight = depth_mm + copperMargin + 2 * margin;
1282 }
1283 else
1284 {
1285 // Counterbore from bottom - cylinder extends from below outer copper surface up to depth
1286 // Add copperMargin below the surface to ensure complete annular ring removal
1287 cylinderZpos = bottomOuterSurface - copperMargin - margin;
1288 cylinderHeight = depth_mm + copperMargin + 2 * margin;
1289 }
1290
1291 // Convert position to mm
1292 double posX_mm = pcbIUScale.IUTomm( aPosition.x - aOrigin.x );
1293 double posY_mm = -pcbIUScale.IUTomm( aPosition.y - aOrigin.y );
1294
1295 wxLogTrace( traceKiCad2Step, wxT( "AddCounterbore: posX_mm=%f posY_mm=%f cylinderZpos=%f cylinderHeight=%f" ),
1296 posX_mm, posY_mm, cylinderZpos, cylinderHeight );
1297
1298 try
1299 {
1300 // Create coordinate system for the cylinder
1301 // The cylinder axis is along Z, positioned at the counterbore center
1302 gp_Ax2 axis( gp_Pnt( posX_mm, posY_mm, cylinderZpos ), gp::DZ() );
1303
1304 TopoDS_Shape cylinder = BRepPrimAPI_MakeCylinder( axis, radius_mm, cylinderHeight );
1305
1306 if( cylinder.IsNull() )
1307 {
1308 wxLogTrace( traceKiCad2Step, wxT( "AddCounterbore: FAILED - cylinder shape is null" ) );
1309 m_reporter->Report( _( "Failed to create counterbore cylinder shape" ),
1311 return false;
1312 }
1313
1314 // Add to both board and copper cutouts
1315 m_boardCutouts.push_back( cylinder );
1316 m_copperCutouts.push_back( cylinder );
1317
1318 wxLogTrace( traceKiCad2Step, wxT( "AddCounterbore: SUCCESS - added cylinder. boardCutouts=%zu copperCutouts=%zu" ),
1319 m_boardCutouts.size(), m_copperCutouts.size() );
1320 }
1321 catch( const Standard_Failure& e )
1322 {
1323 wxLogTrace( traceKiCad2Step, wxT( "AddCounterbore: EXCEPTION - %s" ), occFailureMessage( e ) );
1324 m_reporter->Report( wxString::Format( _( "OCC exception creating counterbore: %s" ),
1325 occFailureMessage( e ) ),
1327 return false;
1328 }
1329
1330 return true;
1331}
1332
1333
1334bool STEP_PCB_MODEL::AddCountersink( const VECTOR2I& aPosition, int aDiameter, int aDepth,
1335 int aAngle, bool aFrontSide, const VECTOR2D& aOrigin )
1336{
1337 wxLogTrace( traceKiCad2Step, wxT( "AddCountersink: pos=(%d,%d) diameter=%d depth=%d angle=%d frontSide=%d origin=(%f,%f)" ),
1338 aPosition.x, aPosition.y, aDiameter, aDepth, aAngle, aFrontSide ? 1 : 0, aOrigin.x, aOrigin.y );
1339
1340 // A countersink is a conical recess from the top or bottom of the board
1341 // The angle parameter is the total cone angle in decidegrees
1342 // (angle between opposite sides of the cone)
1343 if( aDiameter <= 0 || aAngle <= 0 )
1344 {
1345 wxLogTrace( traceKiCad2Step, wxT( "AddCountersink: REJECTED - invalid diameter=%d or angle=%d" ),
1346 aDiameter, aAngle );
1347 return false;
1348 }
1349
1350 double margin = 0.001; // small margin to ensure clean cuts
1351
1352 // Extra margin to extend past outer copper layers to ensure complete annular ring removal
1353 double copperMargin = 0.5; // 0.5mm extra to cut through any copper/pad thickness
1354
1355 // Get board body position (between copper layers)
1356 double boardZpos, boardThickness;
1357 getBoardBodyZPlacement( boardZpos, boardThickness );
1358
1359 // Get copper layer positions - these extend beyond the board body
1360 double f_pos, f_thickness, b_pos, b_thickness;
1361 getLayerZPlacement( F_Cu, f_pos, f_thickness );
1362 getLayerZPlacement( B_Cu, b_pos, b_thickness );
1363
1364 // Calculate actual outer surfaces including copper
1365 double topOuterSurface = std::max( f_pos, f_pos + f_thickness );
1366 double bottomOuterSurface = std::min( b_pos, b_pos + b_thickness );
1367
1368 wxLogTrace( traceKiCad2Step, wxT( "AddCountersink: boardZpos=%f boardThickness=%f f_pos=%f f_thickness=%f topOuter=%f bottomOuter=%f" ),
1369 boardZpos, boardThickness, f_pos, f_thickness, topOuterSurface, bottomOuterSurface );
1370
1371 // Convert dimensions to mm
1372 double diameter_mm = pcbIUScale.IUTomm( aDiameter );
1373 double radius_mm = diameter_mm / 2.0;
1374
1375 // Convert angle from decidegrees to radians
1376 // aAngle is the total cone angle, so half-angle is used for geometry
1377 double halfAngleRad = ( aAngle / 10.0 ) * M_PI / 180.0 / 2.0;
1378
1379 // If depth is not specified, calculate it from the diameter and angle
1380 // The countersink depth is the full cone height: depth = radius / tan(halfAngle)
1381 double depth_mm;
1382 if( aDepth <= 0 )
1383 {
1384 // Calculate depth from diameter and angle
1385 depth_mm = radius_mm / tan( halfAngleRad );
1386 wxLogTrace( traceKiCad2Step, wxT( "AddCountersink: depth not specified, calculated depth_mm=%f from radius=%f and angle" ),
1387 depth_mm, radius_mm );
1388 }
1389 else
1390 {
1391 depth_mm = pcbIUScale.IUTomm( aDepth );
1392 }
1393
1394 wxLogTrace( traceKiCad2Step, wxT( "AddCountersink: diameter_mm=%f depth_mm=%f radius_mm=%f halfAngleRad=%f (deg=%f)" ),
1395 diameter_mm, depth_mm, radius_mm, halfAngleRad, halfAngleRad * 180.0 / M_PI );
1396
1397 // Calculate the cone geometry
1398 // For a countersink, R1 (bottom radius) may be 0 (sharp point) or non-zero
1399 // R2 (top radius) is at the surface
1400 // The cone depth determines how deep it goes
1401
1402 // Calculate bottom radius based on depth and angle
1403 // tan(halfAngle) = (R2 - R1) / depth
1404 // If we want the surface radius to be radius_mm and depth to be depth_mm:
1405 // R1 = R2 - depth * tan(halfAngle)
1406 double bottomRadius_mm = radius_mm - depth_mm * tan( halfAngleRad );
1407
1408 wxLogTrace( traceKiCad2Step, wxT( "AddCountersink: bottomRadius_mm=%f (before clamp), tan(halfAngle)=%f" ),
1409 bottomRadius_mm, tan( halfAngleRad ) );
1410
1411 if( bottomRadius_mm < 0 )
1412 bottomRadius_mm = 0; // Cone comes to a point before reaching full depth
1413
1414 // Calculate position based on which side
1415 // Extend the cone past the outer surface by copperMargin to ensure complete copper removal
1416 double coneZpos;
1417 double coneHeight = depth_mm + copperMargin + margin;
1418 double r1, r2; // bottom and top radii for BRepPrimAPI_MakeCone
1419
1420 // Convert position to mm
1421 double posX_mm = pcbIUScale.IUTomm( aPosition.x - aOrigin.x );
1422 double posY_mm = -pcbIUScale.IUTomm( aPosition.y - aOrigin.y );
1423
1424 try
1425 {
1426 TopoDS_Shape cone;
1427
1428 if( aFrontSide )
1429 {
1430 // Countersink from top - cone apex points down
1431 // In OCC, cone is built from z=0 to z=H with R1 at z=0 and R2 at z=H
1432 // For a top countersink, we want large radius at top, small at bottom
1433 coneZpos = topOuterSurface - depth_mm - margin;
1434 r1 = bottomRadius_mm; // smaller radius at bottom (deeper into board)
1435 // Extend the top radius to account for the copperMargin extension above the surface
1436 r2 = radius_mm + ( copperMargin + margin ) * tan( halfAngleRad );
1437
1438 wxLogTrace( traceKiCad2Step, wxT( "AddCountersink: FRONT - coneZpos=%f r1=%f r2=%f coneHeight=%f" ),
1439 coneZpos, r1, r2, coneHeight );
1440
1441 gp_Ax2 axis( gp_Pnt( posX_mm, posY_mm, coneZpos ), gp::DZ() );
1442 cone = BRepPrimAPI_MakeCone( axis, r1, r2, coneHeight );
1443 }
1444 else
1445 {
1446 // Countersink from bottom - cone apex points up
1447 // For bottom countersink, large radius at bottom, small at top
1448 // Extend below the surface by copperMargin
1449 coneZpos = bottomOuterSurface - copperMargin - margin;
1450 // Extend the bottom radius to account for the copperMargin extension below the surface
1451 r1 = radius_mm + ( copperMargin + margin ) * tan( halfAngleRad );
1452 r2 = bottomRadius_mm; // smaller radius at top (deeper into board)
1453
1454 wxLogTrace( traceKiCad2Step, wxT( "AddCountersink: BACK - coneZpos=%f r1=%f r2=%f coneHeight=%f" ),
1455 coneZpos, r1, r2, coneHeight );
1456
1457 gp_Ax2 axis( gp_Pnt( posX_mm, posY_mm, coneZpos ), gp::DZ() );
1458 cone = BRepPrimAPI_MakeCone( axis, r1, r2, coneHeight );
1459 }
1460
1461 if( cone.IsNull() )
1462 {
1463 wxLogTrace( traceKiCad2Step, wxT( "AddCountersink: FAILED - cone shape is null" ) );
1464 m_reporter->Report( _( "Failed to create countersink cone shape" ),
1466 return false;
1467 }
1468
1469 // Add to both board and copper cutouts
1470 m_boardCutouts.push_back( cone );
1471 m_copperCutouts.push_back( cone );
1472
1473 wxLogTrace( traceKiCad2Step, wxT( "AddCountersink: SUCCESS - added cone. boardCutouts=%zu copperCutouts=%zu" ),
1474 m_boardCutouts.size(), m_copperCutouts.size() );
1475 }
1476 catch( const Standard_Failure& e )
1477 {
1478 wxLogTrace( traceKiCad2Step, wxT( "AddCountersink: EXCEPTION - %s" ), occFailureMessage( e ) );
1479 m_reporter->Report( wxString::Format( _( "OCC exception creating countersink: %s" ),
1480 occFailureMessage( e ) ),
1482 return false;
1483 }
1484
1485 return true;
1486}
1487
1488
1489std::map<PCB_LAYER_ID, int> STEP_PCB_MODEL::GetCopperLayerKnockouts( int aDiameter, int aDepth,
1490 int aAngle, bool aFrontSide )
1491{
1492 std::map<PCB_LAYER_ID, int> knockouts;
1493
1494 // Get the outer surface positions (including copper)
1495 double f_pos, f_thickness, b_pos, b_thickness;
1496 getLayerZPlacement( F_Cu, f_pos, f_thickness );
1497 getLayerZPlacement( B_Cu, b_pos, b_thickness );
1498
1499 double topOuterSurface = std::max( f_pos, f_pos + f_thickness );
1500 double bottomOuterSurface = std::min( b_pos, b_pos + b_thickness );
1501
1502 // Convert dimensions to mm
1503 double diameter_mm = pcbIUScale.IUTomm( aDiameter );
1504 double radius_mm = diameter_mm / 2.0;
1505
1506 // Calculate depth in mm
1507 double depth_mm;
1508 double halfAngleRad = 0.0;
1509
1510 if( aAngle > 0 )
1511 {
1512 // Countersink - calculate half angle
1513 halfAngleRad = ( aAngle / 10.0 ) * M_PI / 180.0 / 2.0;
1514
1515 // If depth is not specified for countersink, calculate from diameter and angle
1516 if( aDepth <= 0 )
1517 depth_mm = radius_mm / tan( halfAngleRad );
1518 else
1519 depth_mm = pcbIUScale.IUTomm( aDepth );
1520 }
1521 else
1522 {
1523 // Counterbore - use specified depth
1524 depth_mm = pcbIUScale.IUTomm( aDepth );
1525 }
1526
1527 // Determine the Z range of the feature
1528 double featureTop, featureBottom;
1529
1530 if( aFrontSide )
1531 {
1532 featureTop = topOuterSurface;
1533 featureBottom = topOuterSurface - depth_mm;
1534 }
1535 else
1536 {
1537 featureBottom = bottomOuterSurface;
1538 featureTop = bottomOuterSurface + depth_mm;
1539 }
1540
1541 wxLogTrace( traceKiCad2Step, wxT( "GetCopperLayerKnockouts: featureTop=%f featureBottom=%f depth_mm=%f frontSide=%d" ),
1542 featureTop, featureBottom, depth_mm, aFrontSide ? 1 : 0 );
1543
1544 // Iterate through all copper layers and check if they fall within the feature range
1545 for( const BOARD_STACKUP_ITEM* item : m_stackup.GetList() )
1546 {
1547 if( item->GetType() != BS_ITEM_TYPE_COPPER )
1548 continue;
1549
1550 PCB_LAYER_ID layer = item->GetBrdLayerId();
1551 double layerZ, layerThickness;
1552 getLayerZPlacement( layer, layerZ, layerThickness );
1553
1554 // Get the Z range of this copper layer (both inner and outer surfaces)
1555 double layerTop = std::max( layerZ, layerZ + layerThickness );
1556 double layerBottom = std::min( layerZ, layerZ + layerThickness );
1557
1558 // Check if this layer overlaps with the feature Z range
1559 // A layer is affected if any part of it is within the feature range
1560 bool layerInRange = ( layerTop >= featureBottom && layerBottom <= featureTop );
1561
1562 wxLogTrace( traceKiCad2Step, wxT( "GetCopperLayerKnockouts: layer %d Z=[%f, %f] feature=[%f, %f] inRange=%d" ),
1563 static_cast<int>( layer ), layerBottom, layerTop, featureBottom, featureTop, layerInRange ? 1 : 0 );
1564
1565 if( !layerInRange )
1566 continue;
1567
1568 int knockoutDiameter;
1569
1570 if( aAngle > 0 )
1571 {
1572 // Countersink - calculate diameter at this layer's Z level
1573 // Use the layer surface that's closest to the feature origin surface
1574 double layerSurfaceZ;
1575 if( aFrontSide )
1576 {
1577 // For front-side countersink, use the top surface of the layer
1578 layerSurfaceZ = layerTop;
1579 }
1580 else
1581 {
1582 // For back-side countersink, use the bottom surface of the layer
1583 layerSurfaceZ = layerBottom;
1584 }
1585
1586 // Distance from the surface determines the radius at this Z
1587 double distanceFromSurface;
1588 if( aFrontSide )
1589 distanceFromSurface = topOuterSurface - layerSurfaceZ;
1590 else
1591 distanceFromSurface = layerSurfaceZ - bottomOuterSurface;
1592
1593 // Radius at this depth: r = R - d * tan(halfAngle)
1594 double radiusAtLayer_mm = radius_mm - distanceFromSurface * tan( halfAngleRad );
1595
1596 if( radiusAtLayer_mm <= 0 )
1597 {
1598 wxLogTrace( traceKiCad2Step, wxT( "GetCopperLayerKnockouts: layer %d - countersink tapers to point before this layer" ),
1599 static_cast<int>( layer ) );
1600 continue; // Cone tapers to a point before reaching this layer
1601 }
1602
1603 knockoutDiameter = pcbIUScale.mmToIU( radiusAtLayer_mm * 2.0 );
1604 wxLogTrace( traceKiCad2Step, wxT( "GetCopperLayerKnockouts: layer %d (countersink) - distFromSurface=%f radiusAtLayer=%f diameter=%d" ),
1605 static_cast<int>( layer ), distanceFromSurface, radiusAtLayer_mm, knockoutDiameter );
1606 }
1607 else
1608 {
1609 // Counterbore - constant diameter
1610 knockoutDiameter = aDiameter;
1611 wxLogTrace( traceKiCad2Step, wxT( "GetCopperLayerKnockouts: layer %d (counterbore) - diameter=%d" ),
1612 static_cast<int>( layer ), knockoutDiameter );
1613 }
1614
1615 knockouts[layer] = knockoutDiameter;
1616 }
1617
1618 return knockouts;
1619}
1620
1621
1622void STEP_PCB_MODEL::getLayerZPlacement( const PCB_LAYER_ID aLayer, double& aZPos,
1623 double& aThickness )
1624{
1625 // Offsets above copper in mm
1626 static const double c_silkscreenAboveCopper = 0.04;
1627 static const double c_soldermaskAboveCopper = 0.015;
1628
1629 if( IsCopperLayer( aLayer ) )
1630 {
1631 getCopperLayerZPlacement( aLayer, aZPos, aThickness );
1632 }
1633 else if( IsFrontLayer( aLayer ) )
1634 {
1635 double f_pos, f_thickness;
1636 getCopperLayerZPlacement( F_Cu, f_pos, f_thickness );
1637 double top = std::max( f_pos, f_pos + f_thickness );
1638
1639 if( aLayer == F_SilkS )
1640 aZPos = top + c_silkscreenAboveCopper;
1641 else
1642 aZPos = top + c_soldermaskAboveCopper;
1643
1644 aThickness = 0.0; // Normal points up
1645 }
1646 else if( IsBackLayer( aLayer ) )
1647 {
1648 double b_pos, b_thickness;
1649 getCopperLayerZPlacement( B_Cu, b_pos, b_thickness );
1650 double bottom = std::min( b_pos, b_pos + b_thickness );
1651
1652 if( aLayer == B_SilkS )
1653 aZPos = bottom - c_silkscreenAboveCopper;
1654 else
1655 aZPos = bottom - c_soldermaskAboveCopper;
1656
1657 aThickness = -0.0; // Normal points down
1658 }
1659}
1660
1661
1663 double& aThickness )
1664{
1665 int z = 0;
1666 int thickness = 0;
1667 bool wasPrepreg = false;
1668
1669 const std::vector<BOARD_STACKUP_ITEM*>& materials = m_stackup.GetList();
1670
1671 // Iterate from bottom to top
1672 for( auto it = materials.rbegin(); it != materials.rend(); ++it )
1673 {
1674 const BOARD_STACKUP_ITEM* item = *it;
1675
1676 if( item->GetType() == BS_ITEM_TYPE_COPPER )
1677 {
1678 if( aLayer == B_Cu )
1679 {
1680 // This is the first encountered layer
1681 thickness = -item->GetThickness();
1682 break;
1683 }
1684
1685 // Inner copper position is usually inside prepreg
1686 if( wasPrepreg && item->GetBrdLayerId() != F_Cu )
1687 {
1688 z += item->GetThickness();
1689 thickness = -item->GetThickness();
1690 }
1691 else
1692 {
1693 thickness = item->GetThickness();
1694 }
1695
1696 if( item->GetBrdLayerId() == aLayer )
1697 break;
1698
1699 if( !wasPrepreg && item->GetBrdLayerId() != B_Cu )
1700 z += item->GetThickness();
1701 }
1702 else if( item->GetType() == BS_ITEM_TYPE_DIELECTRIC )
1703 {
1704 wasPrepreg = ( item->GetTypeName() == KEY_PREPREG );
1705
1706 // Dielectric can have sub-layers. Layer 0 is the main layer
1707 // Not frequent, but possible
1708 thickness = 0;
1709 for( int idx = 0; idx < item->GetSublayersCount(); idx++ )
1710 thickness += item->GetThickness( idx );
1711
1712 z += thickness;
1713 }
1714 }
1715
1716 aZPos = pcbIUScale.IUTomm( z );
1717 aThickness = pcbIUScale.IUTomm( thickness );
1718}
1719
1720
1722{
1723 int thickness = 0;
1724
1725 for( const BOARD_STACKUP_ITEM* item : m_stackup.GetList() )
1726 {
1727 if( !item->IsEnabled() )
1728 continue;
1729
1730 if( item->GetType() == BS_ITEM_TYPE_DIELECTRIC )
1731 {
1732 for( int sublayer = 0; sublayer < item->GetSublayersCount(); sublayer++ )
1733 thickness += item->GetThickness( sublayer );
1734 }
1735 else if( item->GetType() == BS_ITEM_TYPE_COPPER
1736 && IsInnerCopperLayer( item->GetBrdLayerId() ) )
1737 {
1738 thickness += item->GetThickness();
1739 }
1740 }
1741
1742 return pcbIUScale.IUTomm( thickness );
1743}
1744
1745
1746void STEP_PCB_MODEL::getBoardBodyZPlacement( double& aZPos, double& aThickness )
1747{
1748 double f_pos, f_thickness;
1749 double b_pos, b_thickness;
1750 getLayerZPlacement( F_Cu, f_pos, f_thickness );
1751 getLayerZPlacement( B_Cu, b_pos, b_thickness );
1752 double top = std::min( f_pos, f_pos + f_thickness );
1753 double bottom = std::max( b_pos, b_pos + b_thickness );
1754
1755 aThickness = ( top - bottom );
1756 aZPos = bottom;
1757
1758 if( aThickness < BOARD_THICKNESS_MIN_MM )
1759 {
1760 // The copper walk keys off list position, so a truncated or reordered stackup collapses
1761 // the body and MakeShapes() emits a flat face; summing the layers ignores the order
1762 aThickness = getStackupBodyThickness();
1763
1764 if( aThickness < BOARD_THICKNESS_MIN_MM )
1765 aThickness = BOARD_THICKNESS_DEFAULT_MM;
1766
1767 aZPos = 0.0;
1768
1769 m_reporter->Report( wxString::Format( _( "Board stackup does not define a board thickness; "
1770 "exporting a %.3f mm board body." ),
1771 aThickness ),
1773 }
1774
1775 wxASSERT( aZPos == 0.0 );
1776}
1777
1778
1779bool STEP_PCB_MODEL::AddExtrudedBody( const SHAPE_POLY_SET& aOutline, bool aBottom, double aStandoff, double aHeight,
1780 const VECTOR2D& aOrigin, uint32_t aColor, EXTRUSION_MATERIAL aMaterial,
1781 const wxString& aRefDes )
1782{
1783 double f_pos, f_thickness;
1784 double b_pos, b_thickness;
1785 getLayerZPlacement( F_Cu, f_pos, f_thickness );
1786 getLayerZPlacement( B_Cu, b_pos, b_thickness );
1787
1788 double boardSurfaceZ;
1789
1790 if( !aBottom )
1791 boardSurfaceZ = std::max( f_pos, f_pos + f_thickness );
1792 else
1793 boardSurfaceZ = std::min( b_pos, b_pos + b_thickness );
1794
1795 double bodyThickness = aHeight - aStandoff;
1796 double zBot;
1797
1798 if( !aBottom )
1799 zBot = boardSurfaceZ + aStandoff;
1800 else
1801 zBot = boardSurfaceZ - aHeight;
1802
1803 m_extruded_bodies.push_back( { {}, {}, aRefDes, aColor, aMaterial } );
1804 return MakeShapes( m_extruded_bodies.back().bodyShapes, aOutline, m_simplifyShapes, bodyThickness, zBot, aOrigin );
1805}
1806
1807
1808bool STEP_PCB_MODEL::AddExtrudedPins( const FOOTPRINT* aFootprint, const EXTRUDED_3D_BODY* aBody, bool aBottom,
1809 double aStandoff, const VECTOR2D& aOrigin )
1810{
1811 if( aStandoff <= 0.0 )
1812 return false;
1813
1814 SHAPE_POLY_SET pinPoly;
1815 SHAPE_POLY_SET pegPoly;
1816
1817 if( !GetExtrusionPinOutlines( aFootprint, pinPoly, pegPoly ) )
1818 return false;
1819
1820 if( aBody )
1821 {
1822 VECTOR2I fpPos = aFootprint->GetPosition();
1823 ApplyExtrusionTransform( pinPoly, aBody, fpPos );
1824 ApplyExtrusionTransform( pegPoly, aBody, fpPos );
1825 }
1826
1827 double f_pos, f_thickness;
1828 double b_pos, b_thickness;
1829 getLayerZPlacement( F_Cu, f_pos, f_thickness );
1830 getLayerZPlacement( B_Cu, b_pos, b_thickness );
1831
1832 double boardTopZ = std::max( f_pos, f_pos + f_thickness );
1833 double boardBotZ = std::min( b_pos, b_pos + b_thickness );
1834
1835 static const double c_protrusion = 1.0; // 1mm below opposite side
1836
1837 double zOffset = aBody ? aBody->m_offset.z : 0.0;
1838
1839 double pinZBot, pinHeight;
1840
1841 if( !aBottom )
1842 {
1843 pinZBot = boardBotZ - c_protrusion + zOffset;
1844 pinHeight = ( boardTopZ + aStandoff ) - pinZBot;
1845 }
1846 else
1847 {
1848 double pinZTop = boardTopZ + c_protrusion - zOffset;
1849 pinZBot = boardBotZ - aStandoff;
1850 pinHeight = pinZTop - pinZBot;
1851 }
1852
1853 if( m_extruded_bodies.empty() )
1854 return false;
1855
1856 bool success = true;
1857
1858 if( pinPoly.OutlineCount() > 0 )
1859 success &= MakeShapes( m_extruded_bodies.back().pinShapes, pinPoly, m_simplifyShapes, pinHeight, pinZBot,
1860 aOrigin );
1861
1862 if( pegPoly.OutlineCount() > 0 )
1863 success &= MakeShapes( m_extruded_bodies.back().bodyShapes, pegPoly, m_simplifyShapes, pinHeight, pinZBot,
1864 aOrigin );
1865
1866 return success;
1867}
1868
1869
1871 const VECTOR2D& aOrigin, const wxString& aNetname )
1872{
1873 bool success = true;
1874
1875 if( aPolyShapes->IsEmpty() )
1876 return true;
1877
1878 if( !m_enabledLayers.Contains( aLayer ) )
1879 return true;
1880
1881 double z_pos, thickness;
1882 getLayerZPlacement( aLayer, z_pos, thickness );
1883
1884 std::vector<TopoDS_Shape>* targetVec = nullptr;
1885
1886 if( IsCopperLayer( aLayer ) )
1887 targetVec = &m_board_copper[aNetname];
1888 else if( aLayer == F_SilkS )
1889 targetVec = &m_board_front_silk;
1890 else if( aLayer == B_SilkS )
1891 targetVec = &m_board_back_silk;
1892 else if( aLayer == F_Mask )
1893 targetVec = &m_board_front_mask;
1894 else
1895 targetVec = &m_board_back_mask;
1896
1897 if( !MakeShapes( *targetVec, *aPolyShapes, m_simplifyShapes, thickness, z_pos, aOrigin ) )
1898 {
1899 m_reporter->Report( wxString::Format( _( "Could not add shape (%d points) to copper layer %s." ),
1900 aPolyShapes->FullPointCount(),
1901 LayerName( aLayer ) ),
1903
1904 success = false;
1905 }
1906
1907 return success;
1908}
1909
1910
1911bool STEP_PCB_MODEL::AddComponent( const wxString& aBaseName, const wxString& aFileName,
1912 const std::vector<wxString>& aAltFilenames,
1913 const wxString& aRefDes, bool aBottom, VECTOR2D aPosition,
1914 double aRotation, VECTOR3D aOffset, VECTOR3D aOrientation,
1915 VECTOR3D aScale, bool aSubstituteModels )
1916{
1917 if( aFileName.empty() )
1918 {
1919 m_reporter->Report( wxString::Format( _( "No model defined for %s." ), aRefDes ),
1921 return false;
1922 }
1923
1924 m_reporter->Report( wxString::Format( wxT( "Adding component %s." ), aRefDes ), RPT_SEVERITY_DEBUG );
1925
1926 // first retrieve a label
1927 TDF_Label lmodel;
1928 wxString errorMessage;
1929
1930 if( !getModelLabel( aBaseName, aFileName, aAltFilenames, aScale, lmodel, aSubstituteModels,
1931 &errorMessage ) )
1932 {
1933 if( errorMessage.IsEmpty() )
1934 errorMessage.Printf( _( "No model for filename '%s'." ), aFileName );
1935
1936 m_reporter->Report( errorMessage, RPT_SEVERITY_ERROR );
1937 return false;
1938 }
1939
1940 // calculate the Location transform
1941 TopLoc_Location toploc;
1942
1943 if( !getModelLocation( aBottom, aPosition, aRotation, aOffset, aOrientation, toploc ) )
1944 {
1945 m_reporter->Report(
1946 wxString::Format( _( "No location data for filename '%s'." ), aFileName ),
1948 return false;
1949 }
1950
1951 // add the located sub-assembly
1952 TDF_Label llabel = m_assy->AddComponent( m_assy_label, lmodel, toploc );
1953
1954 if( llabel.IsNull() )
1955 {
1956 m_reporter->Report(
1957 wxString::Format( _( "Could not add component with filename '%s'." ), aFileName ),
1959 return false;
1960 }
1961
1962 m_pcb_labels.push_back( llabel );
1963
1964 // attach the RefDes name
1965 TCollection_ExtendedString refdes( aRefDes.utf8_str() );
1966 TDataStd_Name::Set( llabel, refdes );
1967
1968 KICAD3D_INFO::Set( llabel, KICAD3D_MODEL_TYPE::COMPONENT, aRefDes.utf8_string() );
1969
1970 // Rebuild compound shapes for all assemblies so that the newly added component
1971 // contributes to its parent's aggregate TopoDS_Shape. This is required when the
1972 // transferred sub-model was synthesized from a source label tree (via
1973 // XCAFDoc_Editor::Extract), because Extract leaves the assembly shape as an empty
1974 // compound until UpdateAssemblies is invoked. Without this the downstream writers
1975 // (STEPCAFControl_Writer, RWGltf_CafWriter, RWObj_CafWriter) see no geometry for
1976 // the added component.
1977 m_assy->UpdateAssemblies();
1978
1979 return true;
1980}
1981
1982
1984{
1985 m_enabledLayers = aLayers;
1986}
1987
1988
1990{
1991 m_fuseShapes = aValue;
1992}
1993
1994
1996{
1997 m_simplifyShapes = aValue;
1998}
1999
2000
2002{
2003 m_stackup = aStackup;
2004}
2005
2006
2007void STEP_PCB_MODEL::SetNetFilter( const wxString& aFilter )
2008{
2009 m_netFilter = aFilter;
2010}
2011
2012
2014{
2015 m_extraPadThickness = aValue;
2016}
2017
2018
2019void STEP_PCB_MODEL::SetCopperColor( double r, double g, double b )
2020{
2021 m_copperColor[0] = r;
2022 m_copperColor[1] = g;
2023 m_copperColor[2] = b;
2024}
2025
2026
2027void STEP_PCB_MODEL::SetPadColor( double r, double g, double b )
2028{
2029 m_padColor[0] = r;
2030 m_padColor[1] = g;
2031 m_padColor[2] = b;
2032}
2033
2034
2036{
2037 // Ensure a minimal value (in mm)
2038 m_mergeOCCMaxDist = aDistance;
2039}
2040
2041
2043{
2044 return m_pcb_labels.size() > 0;
2045}
2046
2047
2048bool STEP_PCB_MODEL::MakeShapeAsThickSegment( TopoDS_Shape& aShape, const VECTOR2D& aStartPoint,
2049 const VECTOR2D& aEndPoint, double aWidth, double aThickness,
2050 double aZposition, const VECTOR2D& aOrigin )
2051{
2052 // make a wide segment from 2 lines and 2 180 deg arcs
2053 // We need 6 points (3 per arcs)
2054 VECTOR2D coords[6];
2055
2056 // We build a horizontal segment, and after rotate it
2057 double len = ( aEndPoint - aStartPoint ).EuclideanNorm();
2058 double h_width = aWidth/2.0;
2059 // First is end point of first arc, and also start point of first line
2060 coords[0] = VECTOR2D{ 0.0, h_width };
2061
2062 // end point of first line and start point of second arc
2063 coords[1] = VECTOR2D{ len, h_width };
2064
2065 // middle point of second arc
2066 coords[2] = VECTOR2D{ len + h_width, 0.0 };
2067
2068 // start point of second line and end point of second arc
2069 coords[3] = VECTOR2D{ len, -h_width };
2070
2071 // end point of second line and start point of first arc
2072 coords[4] = VECTOR2D{ 0, -h_width };
2073
2074 // middle point of first arc
2075 coords[5] = VECTOR2D{ -h_width, 0.0 };
2076
2077 // Rotate and move to segment position
2078 EDA_ANGLE seg_angle( aEndPoint - aStartPoint );
2079
2080 for( int ii = 0; ii < 6; ii++ )
2081 {
2082 RotatePoint( coords[ii], VECTOR2D{ 0, 0 }, -seg_angle ),
2083 coords[ii] += aStartPoint;
2084 }
2085
2086
2087 // Convert to 3D points
2088 gp_Pnt coords3D[ 6 ];
2089
2090 for( int ii = 0; ii < 6; ii++ )
2091 {
2092 coords3D[ii] = gp_Pnt( pcbIUScale.IUTomm( coords[ii].x - aOrigin.x ),
2093 -pcbIUScale.IUTomm( coords[ii].y - aOrigin.y ), aZposition );
2094 }
2095
2096 // Build OpenCascade shape outlines
2097 BRepBuilderAPI_MakeWire wire;
2098 bool success = true;
2099
2100 // Short segments (distance between end points < m_mergeOCCMaxDist(in mm)) must be
2101 // skipped because OCC merge end points, and a null shape is created
2102 bool short_seg = pcbIUScale.IUTomm( len ) <= m_mergeOCCMaxDist;
2103
2104 try
2105 {
2106 TopoDS_Edge edge;
2107
2108 if( short_seg )
2109 {
2110 Handle( Geom_Circle ) circle = GC_MakeCircle( coords3D[1], // arc1 start point
2111 coords3D[2], // arc1 mid point
2112 coords3D[5] // arc2 mid point
2113 );
2114
2115 edge = BRepBuilderAPI_MakeEdge( circle );
2116 wire.Add( edge );
2117 }
2118 else
2119 {
2120 edge = BRepBuilderAPI_MakeEdge( coords3D[0], coords3D[1] );
2121 wire.Add( edge );
2122
2123 Handle( Geom_TrimmedCurve ) arcOfCircle =
2124 GC_MakeArcOfCircle( coords3D[1], // start point
2125 coords3D[2], // mid point
2126 coords3D[3] // end point
2127 );
2128 edge = BRepBuilderAPI_MakeEdge( arcOfCircle );
2129 wire.Add( edge );
2130
2131 edge = BRepBuilderAPI_MakeEdge( coords3D[3], coords3D[4] );
2132 wire.Add( edge );
2133
2134 Handle( Geom_TrimmedCurve ) arcOfCircle2 =
2135 GC_MakeArcOfCircle( coords3D[4], // start point
2136 coords3D[5], // mid point
2137 coords3D[0] // end point
2138 );
2139 edge = BRepBuilderAPI_MakeEdge( arcOfCircle2 );
2140 wire.Add( edge );
2141 }
2142 }
2143 catch( const Standard_Failure& e )
2144 {
2145 m_reporter->Report( wxString::Format( _( "OCC exception building shape segment: %s" ),
2146 occFailureMessage( e ) ),
2148 return false;
2149 }
2150
2151 BRepBuilderAPI_MakeFace face;
2152
2153 try
2154 {
2155 gp_Pln plane( coords3D[0], gp::DZ() );
2156 face = BRepBuilderAPI_MakeFace( plane, wire );
2157 }
2158 catch( const Standard_Failure& e )
2159 {
2160 m_reporter->Report( wxString::Format( _( "OCC exception building face: %s" ),
2161 occFailureMessage( e ) ),
2163 return false;
2164 }
2165
2166 if( aThickness != 0.0 )
2167 {
2168 aShape = BRepPrimAPI_MakePrism( face, gp_Vec( 0, 0, aThickness ) );
2169
2170 if( aShape.IsNull() )
2171 {
2172 m_reporter->Report( _( "Failed to create a prismatic shape" ),
2174 return false;
2175 }
2176 }
2177 else
2178 {
2179 aShape = face;
2180 }
2181
2182 return success;
2183}
2184
2185
2186bool STEP_PCB_MODEL::MakePolygonAsWall( TopoDS_Shape& aShape,
2187 SHAPE_POLY_SET& aPolySet,
2188 double aHeight,
2189 double aZposition, const VECTOR2D& aOrigin )
2190{
2191 std::vector<TopoDS_Shape> testShapes;
2192
2193 bool success = MakeShapes( testShapes, aPolySet, m_simplifyShapes,
2194 aHeight, aZposition, aOrigin );
2195
2196 if( testShapes.size() > 0 )
2197 aShape = testShapes.front();
2198 else
2199 success = false;
2200
2201 return success;
2202}
2203
2204
2205static wxString formatBBox( const BOX2I& aBBox )
2206{
2207 wxString str;
2208 UNITS_PROVIDER unitsProvider( pcbIUScale, EDA_UNITS::MM );
2209
2210 str << "x0: " << unitsProvider.StringFromValue( aBBox.GetLeft(), false ) << "; ";
2211 str << "y0: " << unitsProvider.StringFromValue( aBBox.GetTop(), false ) << "; ";
2212 str << "x1: " << unitsProvider.StringFromValue( aBBox.GetRight(), false ) << "; ";
2213 str << "y1: " << unitsProvider.StringFromValue( aBBox.GetBottom(), false );
2214
2215 return str;
2216}
2217
2218
2219static bool makeWireFromChain( BRepLib_MakeWire& aMkWire, const SHAPE_LINE_CHAIN& aChain,
2220 double aMergeOCCMaxDist, double aZposition, const VECTOR2D& aOrigin,
2221 REPORTER* aReporter )
2222{
2223 auto toPoint =
2224 [&]( const VECTOR2D& aKiCoords ) -> gp_Pnt
2225 {
2226 return gp_Pnt( pcbIUScale.IUTomm( aKiCoords.x - aOrigin.x ),
2227 -pcbIUScale.IUTomm( aKiCoords.y - aOrigin.y ), aZposition );
2228 };
2229
2230 try
2231 {
2232 auto addSegment = [&]( const VECTOR2I& aPt0, const VECTOR2I& aPt1 ) -> bool
2233 {
2234 if( aPt0 == aPt1 )
2235 return false;
2236
2237 gp_Pnt start = toPoint( aPt0 );
2238 gp_Pnt end = toPoint( aPt1 );
2239
2240 BRepBuilderAPI_MakeEdge mkEdge( start, end );
2241
2242 if( !mkEdge.IsDone() || mkEdge.Edge().IsNull() )
2243 {
2244 aReporter->Report( wxString::Format( _( "Failed to make segment edge (%d %d) -> (%d %d), "
2245 "skipping" ),
2246 aPt0.x, aPt0.y,
2247 aPt1.x, aPt1.y ),
2249 }
2250 else
2251 {
2252 aMkWire.Add( mkEdge.Edge() );
2253
2254 if( aMkWire.Error() != BRepLib_WireDone )
2255 {
2256 aReporter->Report( wxString::Format( _( "Failed to add segment edge (%d %d) -> (%d %d)" ),
2257 aPt0.x, aPt0.y,
2258 aPt1.x, aPt1.y ),
2260 return false;
2261 }
2262 }
2263
2264 return true;
2265 };
2266
2267 auto addArc = [&]( const VECTOR2I& aPt0, const SHAPE_ARC& aArc ) -> bool
2268 {
2269 // Do not export too short segments: they create broken shape because OCC thinks
2270 Handle( Geom_Curve ) curve;
2271
2272 if( aArc.GetCentralAngle() == ANGLE_360 )
2273 {
2274 gp_Ax2 axis = gp::XOY();
2275 axis.SetLocation( toPoint( aArc.GetCenter() ) );
2276
2277 curve = GC_MakeCircle( axis, pcbIUScale.IUTomm( aArc.GetRadius() ) ).Value();
2278 }
2279 else
2280 {
2281 curve = GC_MakeArcOfCircle( toPoint( aPt0 ), toPoint( aArc.GetArcMid() ),
2282 toPoint( aArc.GetP1() ) ).Value();
2283 }
2284
2285 if( curve.IsNull() )
2286 return false;
2287
2288 aMkWire.Add( BRepBuilderAPI_MakeEdge( curve ) );
2289
2290 if( !aMkWire.IsDone() )
2291 {
2292 aReporter->Report( wxString::Format( _( "Failed to add arc curve from (%d %d), arc p0 "
2293 "(%d %d), mid (%d %d), p1 (%d %d)" ),
2294 aPt0.x, aPt0.y,
2295 aArc.GetP0().x, aArc.GetP0().y,
2296 aArc.GetArcMid().x, aArc.GetArcMid().y,
2297 aArc.GetP1().x, aArc.GetP1().y ),
2299 return false;
2300 }
2301
2302 return true;
2303 };
2304
2305 VECTOR2I firstPt;
2306 VECTOR2I lastPt;
2307 bool isFirstShape = true;
2308
2309 for( int i = 0; i <= aChain.PointCount() && i != -1; i = aChain.NextShape( i ) )
2310 {
2311 if( i == 0 )
2312 {
2313 if( aChain.IsArcSegment( 0 ) && aChain.IsArcSegment( aChain.PointCount() - 1 )
2314 && aChain.ArcIndex( 0 ) == aChain.ArcIndex( aChain.PointCount() - 1 ) )
2315 {
2316 // Skip first arc (we should encounter it later)
2317 int nextShape = aChain.NextShape( i );
2318
2319 // If nextShape points to the end, then we have a circle.
2320 if( nextShape != -1 )
2321 i = nextShape;
2322 }
2323 }
2324
2325 if( isFirstShape )
2326 lastPt = aChain.CPoint( i );
2327
2328 bool isArc = aChain.IsArcSegment( i );
2329
2330 if( aChain.IsArcStart( i ) )
2331 {
2332 const SHAPE_ARC& currentArc = aChain.Arc( aChain.ArcIndex( i ) );
2333
2334 if( isFirstShape )
2335 {
2336 firstPt = currentArc.GetP0();
2337 lastPt = firstPt;
2338 }
2339
2340 if( addSegment( lastPt, currentArc.GetP0() ) )
2341 lastPt = currentArc.GetP0();
2342
2343 if( addArc( lastPt, currentArc ) )
2344 lastPt = currentArc.GetP1();
2345 }
2346 else if( !isArc )
2347 {
2348 const SEG& seg = aChain.CSegment( i );
2349
2350 if( isFirstShape )
2351 {
2352 firstPt = seg.A;
2353 lastPt = firstPt;
2354 }
2355
2356 if( addSegment( lastPt, seg.A ) )
2357 lastPt = seg.A;
2358
2359 if( addSegment( lastPt, seg.B ) )
2360 lastPt = seg.B;
2361 }
2362
2363 isFirstShape = false;
2364 }
2365
2366 if( lastPt != firstPt && !addSegment( lastPt, firstPt ) )
2367 {
2368 aReporter->Report( wxString::Format( _( "Failed to close wire at %d, %d -> %d, %d **" ),
2369 lastPt.x, lastPt.y,
2370 firstPt.x, firstPt.y ),
2372
2373 return false;
2374 }
2375 }
2376 catch( const Standard_Failure& e )
2377 {
2378 aReporter->Report( wxString::Format( _( "OCC exception creating wire: %s" ),
2379 occFailureMessage( e ) ),
2381 return false;
2382 }
2383
2384 return true;
2385}
2386
2387
2388bool STEP_PCB_MODEL::MakeShapes( std::vector<TopoDS_Shape>& aShapes, const SHAPE_POLY_SET& aPolySet,
2389 bool aConvertToArcs, double aThickness, double aZposition,
2390 const VECTOR2D& aOrigin )
2391{
2392 SHAPE_POLY_SET workingPoly = aPolySet;
2393 workingPoly.Simplify();
2394
2395 SHAPE_POLY_SET fallbackPoly = workingPoly;
2396
2397 if( aConvertToArcs )
2398 {
2399 SHAPE_POLY_SET approximated = workingPoly;
2400
2401 for( size_t polyId = 0; polyId < approximated.CPolygons().size(); polyId++ )
2402 {
2403 SHAPE_POLY_SET::POLYGON& polygon = approximated.Polygon( polyId );
2404
2405 for( size_t contId = 0; contId < polygon.size(); contId++ )
2406 polygon[contId] = approximateLineChainWithArcs( polygon[contId] );
2407 }
2408
2409 fallbackPoly = workingPoly;
2410 workingPoly = approximated;
2411
2412 // TODO: this is not accurate because it doesn't check arcs.
2413 /*if( approximated.IsSelfIntersecting() )
2414 {
2415 m_reporter->Report( wxString::Format( _( "Approximated polygon self-intersection check failed\n"
2416 "z: %g; bounding box: %s" ) ),
2417 aZposition,
2418 formatBBox( workingPoly.BBox() ) ),
2419 RPT_SEVERITY_ERROR );
2420 }
2421 else
2422 {
2423 fallbackPoly = workingPoly;
2424 workingPoly = approximated;
2425 }*/
2426 }
2427
2428#if 0 // No longer in use
2429 auto toPoint = [&]( const VECTOR2D& aKiCoords ) -> gp_Pnt
2430 {
2431 return gp_Pnt( pcbIUScale.IUTomm( aKiCoords.x - aOrigin.x ),
2432 -pcbIUScale.IUTomm( aKiCoords.y - aOrigin.y ), aZposition );
2433 };
2434#endif
2435
2436 gp_Pln basePlane( gp_Pnt( 0.0, 0.0, aZposition ),
2437 std::signbit( aThickness ) ? -gp::DZ() : gp::DZ() );
2438
2439 for( size_t polyId = 0; polyId < workingPoly.CPolygons().size(); polyId++ )
2440 {
2441 SHAPE_POLY_SET::POLYGON& polygon = workingPoly.Polygon( polyId );
2442
2443 auto tryMakeWire = [this, &aZposition,
2444 &aOrigin]( const SHAPE_LINE_CHAIN& aContour, bool aAllowRetry ) -> TopoDS_Wire
2445 {
2446 TopoDS_Wire wire;
2447 BRepLib_MakeWire mkWire;
2448
2449 makeWireFromChain( mkWire, aContour, m_mergeOCCMaxDist, aZposition, aOrigin, m_reporter );
2450
2451 if( mkWire.IsDone() )
2452 {
2453 wire = mkWire.Wire();
2454 }
2455 else
2456 {
2457 m_reporter->Report(
2458 wxString::Format( _( "Wire not done (contour points %d): OCC error %d\n"
2459 "z: %g; bounding box: %s" ),
2460 static_cast<int>( aContour.PointCount() ),
2461 static_cast<int>( mkWire.Error() ),
2462 aZposition,
2463 formatBBox( aContour.BBox() ) ),
2465 }
2466
2467 if( !wire.IsNull() )
2468 {
2469 BRepAlgoAPI_Check check( wire, false, true );
2470
2471 if( !check.IsValid() )
2472 {
2473 m_reporter->Report( wxString::Format( _( "Wire self-interference check failed\n"
2474 "z: %g; bounding box: %s" ),
2475 aZposition,
2476 formatBBox( aContour.BBox() ) ),
2478
2479 wire.Nullify();
2480 }
2481 }
2482
2483 return wire;
2484 };
2485
2486 BRepBuilderAPI_MakeFace mkFace;
2487
2488 for( size_t contId = 0; contId < polygon.size(); contId++ )
2489 {
2490 try
2491 {
2492 // We allow retry when trying to convert polygon[contId] when a convert error
2493 // happens, using an equivalent polygon shape.
2494 bool allow_retry = aConvertToArcs ? true : false;
2495
2496 TopoDS_Wire wire = tryMakeWire( polygon[contId], allow_retry );
2497
2498 if( aConvertToArcs && wire.IsNull() )
2499 {
2500 m_reporter->Report( wxString::Format( _( "Using non-simplified polygon." ) ),
2502
2503 // Fall back to original shape. Do not allow retry
2504 allow_retry = false;
2505 wire = tryMakeWire( fallbackPoly.CPolygon( polyId )[contId], allow_retry );
2506 }
2507
2508 if( contId == 0 ) // Outline
2509 {
2510 if( !wire.IsNull() )
2511 {
2512 if( basePlane.Axis().Direction().Z() < 0 )
2513 wire.Reverse();
2514
2515 mkFace = BRepBuilderAPI_MakeFace( basePlane, wire );
2516 }
2517 else
2518 {
2519 m_reporter->Report( wxString::Format( wxT( "** Outline skipped **\n"
2520 "z: %g; bounding box: %s" ),
2521 aZposition,
2522 formatBBox( polygon[contId].BBox() ) ),
2524 break;
2525 }
2526 }
2527 else // Hole
2528 {
2529 if( !wire.IsNull() )
2530 {
2531 if( basePlane.Axis().Direction().Z() > 0 )
2532 wire.Reverse();
2533
2534 mkFace.Add( wire );
2535 }
2536 else
2537 {
2538 m_reporter->Report( wxString::Format( wxT( "** Hole skipped **\n"
2539 "z: %g; bounding box: %s" ),
2540 aZposition,
2541 formatBBox( polygon[contId].BBox() ) ),
2543 }
2544 }
2545 }
2546 catch( const Standard_Failure& e )
2547 {
2548 m_reporter->Report( wxString::Format( _( "OCC exception creating contour %d: %s" ),
2549 static_cast<int>( contId ),
2550 occFailureMessage( e ) ),
2552 return false;
2553 }
2554 }
2555
2556 if( mkFace.IsDone() )
2557 {
2558 TopoDS_Shape faceShape = mkFace.Shape();
2559
2560 if( aThickness != 0.0 )
2561 {
2562 TopoDS_Shape prism = BRepPrimAPI_MakePrism( faceShape, gp_Vec( 0, 0, aThickness ) );
2563 aShapes.push_back( prism );
2564
2565 if( prism.IsNull() )
2566 {
2567 m_reporter->Report( _( "Failed to create a prismatic shape" ), RPT_SEVERITY_ERROR );
2568 return false;
2569 }
2570 }
2571 else
2572 {
2573 aShapes.push_back( faceShape );
2574 }
2575 }
2576 else
2577 {
2578 m_reporter->Report( _( "** Face skipped **" ), RPT_SEVERITY_DEBUG );
2579 }
2580 }
2581
2582 return true;
2583}
2584
2585
2586// These colors are based on 3D viewer's colors and are different to "gbrjobColors"
2587static std::vector<FAB_LAYER_COLOR> s_soldermaskColors = {
2588 { NotSpecifiedPrm(), wxColor( 20, 51, 36 ) }, // Not specified, not in .gbrjob file
2589 { _HKI( "Green" ), wxColor( 20, 51, 36 ) }, // used in .gbrjob file
2590 { _HKI( "Red" ), wxColor( 181, 19, 21 ) }, // used in .gbrjob file
2591 { _HKI( "Blue" ), wxColor( 2, 59, 162 ) }, // used in .gbrjob file
2592 { _HKI( "Purple" ), wxColor( 32, 2, 53 ) }, // used in .gbrjob file
2593 { _HKI( "Black" ), wxColor( 11, 11, 11 ) }, // used in .gbrjob file
2594 { _HKI( "White" ), wxColor( 245, 245, 245 ) }, // used in .gbrjob file
2595 { _HKI( "Yellow" ), wxColor( 194, 195, 0 ) }, // used in .gbrjob file
2596 { _HKI( "User defined" ), wxColor( 128, 128, 128 ) } // Free; the name is a dummy name here
2597};
2598
2599
2600static bool colorFromStackup( BOARD_STACKUP_ITEM_TYPE aType, const wxString& aColorStr,
2601 COLOR4D& aColorOut )
2602{
2603 if( !IsPrmSpecified( aColorStr ) )
2604 return false;
2605
2606 if( aColorStr.StartsWith( wxT( "#" ) ) ) // User defined color
2607 {
2608 aColorOut = COLOR4D( aColorStr );
2609 return true;
2610 }
2611 else
2612 {
2613 const std::vector<FAB_LAYER_COLOR>& colors =
2614 ( aType == BS_ITEM_TYPE_SOLDERMASK || aType == BS_ITEM_TYPE_SILKSCREEN )
2616 : GetStandardColors( aType );
2617
2618 for( const FAB_LAYER_COLOR& fabColor : colors )
2619 {
2620 if( fabColor.GetName() == aColorStr )
2621 {
2622 aColorOut = fabColor.GetColor( aType );
2623 return true;
2624 }
2625 }
2626 }
2627
2628 return false;
2629}
2630
2631
2632bool STEP_PCB_MODEL::CreatePCB( SHAPE_POLY_SET& aOutline, const VECTOR2D& aOrigin, bool aPushBoardBody )
2633{
2634 if( m_hasPCB )
2635 {
2636 if( !isBoardOutlineValid() )
2637 return false;
2638
2639 return true;
2640 }
2641
2643
2644 Handle( XCAFDoc_VisMaterialTool ) visMatTool = XCAFDoc_DocumentTool::VisMaterialTool( m_doc->Main() );
2645
2646 m_hasPCB = true; // whether or not operations fail we note that CreatePCB has been invoked
2647
2648 // Support for more than one main outline (more than one board)
2649 m_reporter->Report( wxString::Format( wxT( "Build board outlines (%d outlines) with %d points." ),
2650 aOutline.OutlineCount(),
2651 aOutline.FullPointCount() ),
2653
2654 double boardThickness;
2655 double boardZPos;
2656 getBoardBodyZPlacement( boardZPos, boardThickness );
2657
2658#if 1
2659 // This code should work, and it is working most of time
2660 // However there are issues if the main outline is a circle with holes:
2661 // holes from vias and pads are not working
2662 // see bug https://gitlab.com/kicad/code/kicad/-/issues/17446
2663 // (Holes are missing from STEP export with circular PCB outline)
2664 // Hard to say if the bug is in our code or in OCC 7.7
2665 if( !MakeShapes( m_board_outlines, aOutline, false, boardThickness, boardZPos, aOrigin ) )
2666 {
2667 // Error
2668 m_reporter->Report( _( "OCC error creating main outline." ), RPT_SEVERITY_ERROR );
2669 }
2670#else
2671 // Workaround for bug #17446 Holes are missing from STEP export with circular PCB outline
2672 for( const SHAPE_POLY_SET::POLYGON& polygon : aOutline.CPolygons() )
2673 {
2674 for( size_t contId = 0; contId < polygon.size(); contId++ )
2675 {
2676 const SHAPE_LINE_CHAIN& contour = polygon[contId];
2677 SHAPE_POLY_SET polyset;
2678 polyset.Append( contour );
2679
2680 if( contId == 0 ) // main Outline
2681 {
2682 if( !MakeShapes( m_board_outlines, polyset, false, boardThickness, boardZPos,
2683 aOrigin ) )
2684 {
2685 m_reporter->Report( _( "OCC error creating main outline." ),
2687 }
2688 }
2689 else // Hole inside the main outline
2690 {
2691 if( !MakeShapes( m_boardCutouts, polyset, false, boardThickness, boardZPos,
2692 aOrigin ) )
2693 {
2694 m_reporter->Report( _( "OCC error creating hole in main outline." ),
2696 }
2697 }
2698 }
2699 }
2700#endif
2701
2702 // Even if we've disabled board body export, we still need the shapes for bounding box calculations.
2703 Bnd_Box brdBndBox;
2704
2705 for( const TopoDS_Shape& brdShape : m_board_outlines )
2706 BRepBndLib::Add( brdShape, brdBndBox );
2707
2708 // subtract cutouts (if any)
2709 m_reporter->Report( wxString::Format( wxT( "Build board cutouts and holes (%d hole(s))." ),
2710 (int) ( m_boardCutouts.size() + m_copperCutouts.size() ) ),
2712
2713 auto buildBSB =
2714 [&brdBndBox]( std::vector<TopoDS_Shape>& input, Bnd_BoundSortBox& bsbHoles,
2715 std::vector<Bnd_Box>& holeBoxes )
2716 {
2717 // We need to encompass every location we'll need to test in the global bbox,
2718 // otherwise Bnd_BoundSortBox doesn't work near the boundaries.
2719 Bnd_Box brdWithHolesBndBox = brdBndBox;
2720
2721#if OCC_VERSION_HEX >= 0x080000
2722 Handle( NCollection_HArray1<Bnd_Box> ) holeBoxSet =
2723 new NCollection_HArray1<Bnd_Box>( 0, input.size() - 1 );
2724#else
2725 Handle( Bnd_HArray1OfBox ) holeBoxSet = new Bnd_HArray1OfBox( 0, input.size() - 1 );
2726#endif
2727 holeBoxes.resize( input.size() );
2728
2729 for( size_t i = 0; i < input.size(); i++ )
2730 {
2731 Bnd_Box bbox;
2732 BRepBndLib::Add( input[i], bbox );
2733 brdWithHolesBndBox.Add( bbox );
2734 ( *holeBoxSet )[i] = bbox;
2735 holeBoxes[i] = bbox;
2736 }
2737
2738 bsbHoles.Initialize( brdWithHolesBndBox, holeBoxSet );
2739 };
2740
2741 auto subtractShapesMap =
2742 [this, &tp]( const wxString& aWhat, std::map<wxString, std::vector<TopoDS_Shape>>& aShapesMap,
2743 std::vector<TopoDS_Shape>& aHolesList, Bnd_BoundSortBox& aBSBHoles,
2744 const std::vector<Bnd_Box>& aHoleBoxes )
2745 {
2746 m_reporter->Report( wxString::Format( _( "Subtracting holes for %s" ), aWhat ),
2748
2749 for( auto& [netname, vec] : aShapesMap )
2750 {
2751 // Cuts share the hole TShapes as tools across threads. SetNonDestructive keeps
2752 // OCC from mutating those shared inputs, so the cuts are safe to run in parallel.
2753 // Bnd_BoundSortBox::Compare is not reentrant (it overwrites internal scratch and
2754 // returns a reference to it), so the hole lookup is serialized with a mutex.
2755 std::mutex mutex;
2756
2757 auto subtractLoopFn = [&]( const int shapeId )
2758 {
2759 TopoDS_Shape& shape = vec[shapeId];
2760
2761 Bnd_Box shapeBbox;
2762 BRepBndLib::Add( shape, shapeBbox );
2763
2764 NCollection_List<TopoDS_Shape> holelist;
2765
2766 {
2767 std::unique_lock lock( mutex );
2768
2769 const NCollection_List<int>& indices = aBSBHoles.Compare( shapeBbox );
2770
2771 for( const int& index : indices )
2772 holelist.Append( aHolesList[index] );
2773
2774 // Workaround for OCCT bug (https://github.com/Open-Cascade-SAS/OCCT/issues/506)
2775 // Bnd_BoundSortBox::Compare can fail to detect intersections in certain edge
2776 // cases (e.g., single item). Fall back to direct bounding box intersection
2777 // checks when Compare returns empty but intersections may exist.
2778 if( holelist.IsEmpty() )
2779 {
2780 for( size_t i = 0; i < aHoleBoxes.size(); i++ )
2781 {
2782 if( !shapeBbox.IsOut( aHoleBoxes[i] ) )
2783 holelist.Append( aHolesList[i] );
2784 }
2785 }
2786 }
2787
2788 if( holelist.IsEmpty() )
2789 return; // nothing to cut for this shape
2790
2791 NCollection_List<TopoDS_Shape> cutArgs;
2792 cutArgs.Append( shape );
2793
2794 BRepAlgoAPI_Cut cut;
2795
2796 // Non-destructive protects the shared hole tools. Parallelism comes from the
2797 // outer thread pool, so this op runs single-threaded to avoid oversubscribing.
2798 cut.SetNonDestructive( true );
2799 cut.SetRunParallel( false );
2800 cut.SetToFillHistory( false );
2801
2802 cut.SetArguments( cutArgs );
2803 cut.SetTools( holelist );
2804 cut.Build();
2805
2806 if( cut.HasErrors() || cut.HasWarnings() )
2807 {
2808 m_reporter->Report( wxString::Format( _( "** Got problems while cutting "
2809 "%s net '%s' **" ),
2810 aWhat,
2811 UnescapeString( netname ) ),
2813
2814 {
2815 // Dump writes to std::cout; serialize it so parallel cuts do not
2816 // interleave their output.
2817 std::unique_lock lock( mutex );
2818 shapeBbox.Dump();
2819 }
2820
2821 if( cut.HasErrors() )
2822 {
2823 wxString msg = _( "Errors:\n" );
2824 wxStringOutputStream os_stream( &msg );
2825 wxStdOutputStream out( os_stream );
2826
2827 cut.DumpErrors( out );
2828 m_reporter->Report( msg, RPT_SEVERITY_WARNING);
2829 }
2830
2831 if( cut.HasWarnings() )
2832 {
2833 wxString msg = _( "Warnings:\n" );
2834 wxStringOutputStream os_stream( &msg );
2835 wxStdOutputStream out( os_stream );
2836
2837 cut.DumpWarnings( out );
2838 m_reporter->Report( msg, RPT_SEVERITY_WARNING );
2839 }
2840 }
2841
2842 shape = cut.Shape();
2843 };
2844
2845 // submit_loop can throw mid-submission after queueing some blocks. Drain the
2846 // pool before unwinding so no queued block outlives the captured mutex and
2847 // vector. get() then re-raises any worker exception.
2848 BS::multi_future<void> cutFutures;
2849
2850 try
2851 {
2852 cutFutures = tp.submit_loop( 0, vec.size(), subtractLoopFn );
2853 }
2854 catch( ... )
2855 {
2856 tp.wait();
2857 throw;
2858 }
2859
2860 cutFutures.wait();
2861 cutFutures.get();
2862 }
2863 };
2864
2865 auto subtractShapes =
2866 [subtractShapesMap]( const wxString& aWhat, std::vector<TopoDS_Shape>& aShapesList,
2867 std::vector<TopoDS_Shape>& aHolesList, Bnd_BoundSortBox& aBSBHoles,
2868 const std::vector<Bnd_Box>& aHoleBoxes )
2869 {
2870 std::map<wxString, std::vector<TopoDS_Shape>> aShapesMap{ { wxEmptyString, aShapesList } };
2871
2872 subtractShapesMap( aWhat, aShapesMap, aHolesList, aBSBHoles, aHoleBoxes );
2873 aShapesList = aShapesMap[wxEmptyString];
2874 };
2875
2876
2877 if( m_boardCutouts.size() )
2878 {
2879 Bnd_BoundSortBox bsbHoles;
2880 std::vector<Bnd_Box> holeBoxes;
2881 buildBSB( m_boardCutouts, bsbHoles, holeBoxes );
2882
2883 subtractShapes( _( "shapes" ), m_board_outlines, m_boardCutouts, bsbHoles, holeBoxes );
2884 }
2885
2886 if( m_copperCutouts.size() )
2887 {
2888 Bnd_BoundSortBox bsbHoles;
2889 std::vector<Bnd_Box> holeBoxes;
2890 buildBSB( m_copperCutouts, bsbHoles, holeBoxes );
2891
2892 subtractShapesMap( _( "pads" ), m_board_copper_pads, m_copperCutouts, bsbHoles, holeBoxes );
2893 subtractShapesMap( _( "vias" ), m_board_copper_vias, m_copperCutouts, bsbHoles, holeBoxes );
2894 }
2895
2896 if( m_fuseShapes )
2897 {
2898 std::map<wxString, NCollection_List<TopoDS_Shape>> shapesToFuseMap;
2899
2900 auto addShapes = [&shapesToFuseMap]( const wxString& aNetname,
2901 const std::vector<TopoDS_Shape>& aShapes )
2902 {
2903 for( const TopoDS_Shape& shape : aShapes )
2904 shapesToFuseMap[aNetname].Append( shape );
2905 };
2906
2907 for( const auto& [netname, shapes] : m_board_copper )
2908 addShapes( netname, shapes );
2909
2910 for( const auto& [netname, shapes] : m_board_copper_pads )
2911 addShapes( netname, shapes );
2912
2913 for( const auto& [netname, shapes] : m_board_copper_vias )
2914 addShapes( netname, shapes );
2915
2916 m_reporter->Report( wxT( "Fusing shapes" ), RPT_SEVERITY_DEBUG );
2917
2918 // Fuse each net on the thread pool. SetNonDestructive keeps the shared input TShapes
2919 // immutable, so the parallel BRepAlgoAPI ops are heap-safe. The member-map writes are the
2920 // only shared mutable state and are guarded by the mutex. Work items hold stable pointers
2921 // into shapesToFuseMap so the workers never touch the map's non-const operator[].
2922 std::vector<std::pair<wxString, const NCollection_List<TopoDS_Shape>*>> fuseWork;
2923 fuseWork.reserve( shapesToFuseMap.size() );
2924
2925 for( const auto& [netname, toFuse] : shapesToFuseMap )
2926 fuseWork.emplace_back( netname, &toFuse );
2927
2928 std::mutex mutex;
2929 BS::multi_future<void> mf;
2930 mf.reserve( fuseWork.size() );
2931
2932 // A submission can throw after queueing tasks (allocation failure). Drain the pool before
2933 // unwinding so no task outlives the captured mutex.
2934 try
2935 {
2936 for( const auto& work : fuseWork )
2937 {
2938 const wxString netname = work.first;
2939 const NCollection_List<TopoDS_Shape>* toFuse = work.second;
2940
2941 mf.push_back( tp.submit_task(
2942 [this, &mutex, netname, toFuse]()
2943 {
2944 TopoDS_Shape fusedShape = fuseShapesOrCompound( *toFuse, m_reporter );
2945
2946 if( !fusedShape.IsNull() )
2947 {
2948 std::unique_lock lock( mutex );
2949
2950 m_board_copper_fused[netname].emplace_back( fusedShape );
2951
2952 m_board_copper[netname].clear();
2953 m_board_copper_pads[netname].clear();
2954 m_board_copper_vias[netname].clear();
2955 }
2956 } ) );
2957 }
2958 }
2959 catch( ... )
2960 {
2961 tp.wait();
2962 throw;
2963 }
2964
2965 mf.wait();
2966 mf.get();
2967 }
2968
2969 // push the board to the data structure
2970 m_reporter->Report( wxT( "Generate board full shape." ), RPT_SEVERITY_DEBUG );
2971
2972 // AddComponent adds a label that has a reference (not a parent/child relation) to the real
2973 // label. We need to extract that real label to name it for the STEP output cleanly
2974 // Why are we trying to name the bare board? Because CAD tools like SolidWorks do fun things
2975 // like "deduplicate" imported STEPs by swapping STEP assembly components with already
2976 // identically named assemblies. So we want to avoid having the PCB be generally defaulted
2977 // to "Component" or "Assembly".
2978
2979 // aCompoundNets will place all geometry within a net into one compound.
2980 // aCompoundAll will place all geometry into one compound.
2981 auto pushToAssemblyMap =
2982 [&]( const std::map<wxString, std::vector<TopoDS_Shape>>& aShapesMap,
2983 const TDF_Label& aVisMatLabel, const wxString& aShapeName, bool aCompoundNets,
2984 bool aCompoundAll, const wxString& aNiceName )
2985 {
2986 std::map<wxString, std::vector<TopoDS_Shape>> shapesMap;
2987
2988 if( aCompoundAll )
2989 {
2990 std::vector<TopoDS_Shape> allShapes;
2991
2992 for( const auto& [netname, shapesList] : aShapesMap )
2993 allShapes.insert( allShapes.end(), shapesList.begin(), shapesList.end() );
2994
2995 if( !allShapes.empty() )
2996 shapesMap[wxEmptyString].emplace_back( makeCompound( allShapes ) );
2997 }
2998 else
2999 {
3000 shapesMap = aShapesMap;
3001 }
3002
3003 for( const auto& [netname, shapesList] : shapesMap )
3004 {
3005 std::vector<TopoDS_Shape> newList;
3006
3007 if( aCompoundNets )
3008 newList.emplace_back( makeCompound( shapesList ) );
3009 else
3010 newList = shapesList;
3011
3012 int i = 1;
3013
3014 for( TopoDS_Shape& shape : newList )
3015 {
3016 Handle( TDataStd_TreeNode ) node;
3017
3018 // Dont expand the component or else coloring it gets hard
3019 TDF_Label lbl = m_assy->AddComponent( m_assy_label, shape, false );
3020 KICAD3D_INFO::Set( lbl, KICAD3D_MODEL_TYPE::BOARD, aNiceName.ToStdString() );
3021 m_pcb_labels.push_back( lbl );
3022
3023 if( m_pcb_labels.back().IsNull() )
3024 return;
3025
3026 lbl.FindAttribute( XCAFDoc::ShapeRefGUID(), node );
3027 TDF_Label shpLbl = node->Father()->Label();
3028
3029 if( !shpLbl.IsNull() )
3030 {
3031 if( visMatTool && !aVisMatLabel.IsNull() )
3032 visMatTool->SetShapeMaterial( shpLbl, aVisMatLabel );
3033
3034 wxString shapeName;
3035
3036 shapeName << m_pcbName;
3037 shapeName << '_';
3038 shapeName << aShapeName;
3039
3040 if( !netname.empty() )
3041 {
3042 shapeName << '_';
3043 shapeName << netname;
3044 }
3045
3046 if( newList.size() > 1 )
3047 {
3048 shapeName << '_';
3049 shapeName << i;
3050 }
3051
3052 TCollection_ExtendedString partname( shapeName.ToUTF8().data() );
3053 TDataStd_Name::Set( shpLbl, partname );
3054 }
3055
3056 i++;
3057 }
3058 }
3059 };
3060
3061 auto pushToAssembly =
3062 [&]( const std::vector<TopoDS_Shape>& aShapesList, const TDF_Label& aVisMatLabel,
3063 const wxString& aShapeName, bool aCompound, const wxString& aNiceName )
3064 {
3065 const std::map<wxString, std::vector<TopoDS_Shape>> shapesMap{ { wxEmptyString, aShapesList } };
3066
3067 pushToAssemblyMap( shapesMap, aVisMatLabel, aShapeName, aCompound, aCompound, aNiceName );
3068 };
3069
3070 auto makeMaterial =
3071 [&]( const TCollection_AsciiString& aName, const Quantity_ColorRGBA& aBaseColor,
3072 double aMetallic, double aRoughness ) -> TDF_Label
3073 {
3074 Handle( XCAFDoc_VisMaterial ) vismat = new XCAFDoc_VisMaterial;
3075 XCAFDoc_VisMaterialPBR pbr;
3076 pbr.BaseColor = aBaseColor;
3077 pbr.Metallic = aMetallic;
3078 pbr.Roughness = aRoughness;
3079 vismat->SetPbrMaterial( pbr );
3080 return visMatTool->AddMaterial( vismat, aName );
3081 };
3082
3083 // Init colors for the board items
3084 Quantity_ColorRGBA copper_color( m_copperColor[0], m_copperColor[1], m_copperColor[2], 1.0 );
3085 Quantity_ColorRGBA pad_color( m_padColor[0], m_padColor[1], m_padColor[2], 1.0 );
3086
3087 // Viewers show the back faces of a translucent solid, which reads as inverted normals
3088 Quantity_ColorRGBA board_color( 0.42f, 0.45f, 0.29f, 1.0f );
3089 Quantity_ColorRGBA front_silk_color( 1.0f, 1.0f, 1.0f, 0.9f );
3090 Quantity_ColorRGBA back_silk_color = front_silk_color;
3091 Quantity_ColorRGBA front_mask_color( 0.08f, 0.2f, 0.14f, 0.83f );
3092 Quantity_ColorRGBA back_mask_color = front_mask_color;
3093
3094 // Get colors from stackup
3095 for( const BOARD_STACKUP_ITEM* item : m_stackup.GetList() )
3096 {
3097 COLOR4D col;
3098
3099 if( !colorFromStackup( item->GetType(), item->GetColor(), col ) )
3100 continue;
3101
3102 if( item->GetBrdLayerId() == F_Mask || item->GetBrdLayerId() == B_Mask )
3103 {
3104 col.Darken( 0.2 );
3105
3106 if( item->GetBrdLayerId() == F_Mask )
3107 front_mask_color.SetValues( col.r, col.g, col.b, col.a );
3108 else
3109 back_mask_color.SetValues( col.r, col.g, col.b, col.a );
3110 }
3111
3112 if( item->GetBrdLayerId() == F_SilkS )
3113 front_silk_color.SetValues( col.r, col.g, col.b, col.a );
3114 else if( item->GetBrdLayerId() == B_SilkS )
3115 back_silk_color.SetValues( col.r, col.g, col.b, col.a );
3116
3117 if( item->GetType() == BS_ITEM_TYPE_DIELECTRIC && item->GetTypeName() == KEY_CORE )
3118 board_color.SetValues( col.r, col.g, col.b, col.a );
3119 }
3120
3121 // Paint board body in soldermask colors if soldermask is not exported as a layer
3122 if( !m_enabledLayers.Contains( F_Mask ) && !m_enabledLayers.Contains( B_Mask ) )
3123 {
3124 board_color = front_mask_color;
3125 board_color.SetAlpha( 1.0 );
3126 }
3127
3128 TDF_Label front_mask_mat = makeMaterial( "soldermask", front_mask_color, 0.0, 0.6 );
3129 TDF_Label back_mask_mat = makeMaterial( "soldermask", back_mask_color, 0.0, 0.6 );
3130 TDF_Label front_silk_mat = makeMaterial( "silkscreen", front_silk_color, 0.0, 0.9 );
3131 TDF_Label back_silk_mat = makeMaterial( "silkscreen", back_silk_color, 0.0, 0.9 );
3132 TDF_Label copper_mat = makeMaterial( "copper", copper_color, 1.0, 0.4 );
3133 TDF_Label pad_mat = makeMaterial( "pad", pad_color, 1.0, 0.4 );
3134 TDF_Label board_mat = makeMaterial( "board", board_color, 0.0, 0.8 );
3135
3136 pushToAssemblyMap( m_board_copper, copper_mat, "copper", true, true, "Copper" );
3137 pushToAssemblyMap( m_board_copper_pads, pad_mat, "pad", true, true, "Pads" );
3138 pushToAssemblyMap( m_board_copper_vias, copper_mat, "via", true, true, "Via" );
3139 pushToAssemblyMap( m_board_copper_fused, copper_mat, "copper", true, true, "Copper" );
3140 pushToAssembly( m_board_front_silk, front_silk_mat, "silkscreen", true, "Top Silkscreen" );
3141 pushToAssembly( m_board_back_silk, back_silk_mat, "silkscreen", true, "Bottom Silkscreen" );
3142 pushToAssembly( m_board_front_mask, front_mask_mat, "soldermask", true, "Top Soldermask" );
3143 pushToAssembly( m_board_back_mask, back_mask_mat, "soldermask", true, "Bottom Soldermask" );
3144
3145 if( aPushBoardBody )
3146 pushToAssembly( m_board_outlines, board_mat, "PCB", false, "Body" );
3147
3148 Quantity_ColorRGBA pinClr( Quantity_Color( 0.75, 0.75, 0.75, Quantity_TOC_RGB ), 1.0 );
3149 TDF_Label pin_mat = makeMaterial( "extruded_pin", pinClr, 0.6, 0.3 );
3150
3151 for( auto& entry : m_extruded_bodies )
3152 {
3153 if( entry.bodyShapes.empty() && entry.pinShapes.empty() )
3154 continue;
3155
3156 TopoDS_Compound asmCompound;
3157 BRep_Builder asmBuilder;
3158 asmBuilder.MakeCompound( asmCompound );
3159 TDF_Label fpLabel = m_assy->AddShape( asmCompound, true );
3160 TDataStd_Name::Set( fpLabel, TCollection_ExtendedString( ( entry.refDes + " (extruded)" ).ToUTF8().data() ) );
3161
3162 if( !entry.bodyShapes.empty() )
3163 {
3164 double r = ( ( entry.colorKey >> 24 ) & 0xFF ) / 255.0;
3165 double g = ( ( entry.colorKey >> 16 ) & 0xFF ) / 255.0;
3166 double b = ( ( entry.colorKey >> 8 ) & 0xFF ) / 255.0;
3167 double a = ( entry.colorKey & 0xFF ) / 255.0;
3168
3169 double metallic, roughness;
3170
3171 switch( entry.material )
3172 {
3173 default:
3175 metallic = 0.0;
3176 roughness = 0.6;
3177 break;
3179 metallic = 0.0;
3180 roughness = 0.9;
3181 break;
3183 metallic = 0.8;
3184 roughness = 0.3;
3185 break;
3187 metallic = 1.0;
3188 roughness = 0.4;
3189 break;
3190 }
3191
3192 Quantity_ColorRGBA bodyClr( Quantity_Color( r, g, b, Quantity_TOC_RGB ), a );
3193 TDF_Label body_mat = makeMaterial( "extruded_body", bodyClr, metallic, roughness );
3194
3195 TopoDS_Shape bodyCompound = makeCompound( entry.bodyShapes );
3196 TDF_Label bodyLbl = m_assy->AddComponent( fpLabel, bodyCompound, false );
3197
3198 Handle( TDataStd_TreeNode ) bodyNode;
3199 bodyLbl.FindAttribute( XCAFDoc::ShapeRefGUID(), bodyNode );
3200 TDF_Label bodyShpLbl = bodyNode->Father()->Label();
3201
3202 if( !bodyShpLbl.IsNull() )
3203 {
3204 visMatTool->SetShapeMaterial( bodyShpLbl, body_mat );
3205 TDataStd_Name::Set( bodyShpLbl,
3206 TCollection_ExtendedString( ( entry.refDes + "_body" ).ToUTF8().data() ) );
3207 }
3208 }
3209
3210 int pinIdx = 1;
3211
3212 for( TopoDS_Shape& pinShape : entry.pinShapes )
3213 {
3214 TDF_Label pinLbl = m_assy->AddComponent( fpLabel, pinShape, false );
3215
3216 Handle( TDataStd_TreeNode ) pinNode;
3217 pinLbl.FindAttribute( XCAFDoc::ShapeRefGUID(), pinNode );
3218 TDF_Label pinShpLbl = pinNode->Father()->Label();
3219
3220 if( !pinShpLbl.IsNull() )
3221 {
3222 visMatTool->SetShapeMaterial( pinShpLbl, pin_mat );
3223 wxString pinName = wxString::Format( "%s_pin_%d", entry.refDes, pinIdx++ );
3224 TDataStd_Name::Set( pinShpLbl, TCollection_ExtendedString( pinName.ToUTF8().data() ) );
3225 }
3226 }
3227
3228 TopLoc_Location loc;
3229 TDF_Label fpCompLbl = m_assy->AddComponent( m_assy_label, fpLabel, loc );
3230 TDataStd_Name::Set( fpCompLbl, TCollection_ExtendedString( entry.refDes.ToUTF8().data() ) );
3231 KICAD3D_INFO::Set( fpCompLbl, KICAD3D_MODEL_TYPE::BOARD, entry.refDes.ToStdString() );
3232 m_pcb_labels.push_back( fpCompLbl );
3233 }
3234
3235#if( defined OCC_VERSION_HEX ) && ( OCC_VERSION_HEX > 0x070101 )
3236 m_assy->UpdateAssemblies();
3237#endif
3238
3239 return true;
3240}
3241
3242
3243#ifdef SUPPORTS_IGES
3244// write the assembly model in IGES format
3245bool STEP_PCB_MODEL::WriteIGES( const wxString& aFileName )
3246{
3247 if( !isBoardOutlineValid() )
3248 {
3249 m_reporter->Report( wxString::Format( _( "No valid PCB assembly; cannot create output file '%s'." ),
3250 aFileName ),
3252 return false;
3253 }
3254
3256
3257 wxFileName fn( aFileName );
3258 IGESControl_Controller::Init();
3259 IGESCAFControl_Writer writer;
3260 writer.SetColorMode( true );
3261 writer.SetNameMode( true );
3262 IGESData_GlobalSection header = writer.Model()->GlobalSection();
3263 header.SetFileName( new TCollection_HAsciiString( fn.GetFullName().ToAscii() ) );
3264 header.SetSendName( new TCollection_HAsciiString( "KiCad electronic assembly" ) );
3265 header.SetAuthorName( new TCollection_HAsciiString( Interface_Static::CVal( "write.iges.header.author" ) ) );
3266 header.SetCompanyName( new TCollection_HAsciiString( Interface_Static::CVal( "write.iges.header.company" ) ) );
3267 writer.Model()->SetGlobalSection( header );
3268
3269 if( false == writer.Perform( m_doc, aFileName.c_str() ) )
3270 return false;
3271
3272 return true;
3273}
3274#endif
3275
3276bool STEP_PCB_MODEL::CompressSTEP( wxString& inputFile, wxString& outputFile )
3277{
3278 wxFileInputStream input( inputFile );
3279 wxFileOutputStream output( outputFile );
3280
3281 if( !input.IsOk() )
3282 {
3283 m_reporter->Report( wxString::Format( _( "Cannot create input stream '%s'.\n" ), inputFile ) );
3284 return false;
3285 }
3286
3287 if( !output.IsOk() )
3288 {
3289 m_reporter->Report( wxString::Format( _( "Cannot create output stream '%s'.\n" ), outputFile ) );
3290 return false;
3291 }
3292
3293 wxZlibOutputStream zlibStream( output, -1, wxZLIB_GZIP );
3294
3295 if( !zlibStream.IsOk() )
3296 {
3297 m_reporter->Report( _( "Impossible create compress stream" ) );
3298 return false;
3299 }
3300
3301 input.Read( zlibStream );
3302
3303 if( input.LastRead() == 0 || zlibStream.LastWrite() == 0 )
3304 {
3305 m_reporter->Report( _( "Compress read or write error" ) );
3306 return false;
3307 }
3308
3309 zlibStream.Close();
3310 output.Close();
3311
3312 return true;
3313}
3314
3315bool STEP_PCB_MODEL::WriteSTEP( const wxString& aFileName, bool aOptimize, bool compress )
3316{
3317 if( !isBoardOutlineValid() )
3318 {
3319 m_reporter->Report( wxString::Format( _( "No valid PCB assembly; cannot create output file '%s'." ),
3320 aFileName ),
3322 return false;
3323 }
3324
3326
3327 wxFileName fn( aFileName );
3328
3329 STEPCAFControl_Writer writer;
3330 writer.SetColorMode( true );
3331 writer.SetNameMode( true );
3332
3333 // This must be set before we "transfer" the document.
3334 // Should default to kicad_pcb.general.title_block.title,
3335 // but in the meantime, defaulting to the basename of the output
3336 // target is still better than "open cascade step translter v..."
3337 // UTF8 should be ok from ISO 10303-21:2016, but... older stuff? use boring ascii
3338 if( !Interface_Static::SetCVal( "write.step.product.name", fn.GetName().ToAscii() ) )
3339 {
3340 m_reporter->Report( _( "Failed to set STEP product name, but will attempt to continue." ),
3342 }
3343
3344 // Setting write.surfacecurve.mode to 0 reduces file size and write/read times.
3345 // But there are reports that this mode might be less compatible in some cases.
3346 if( !Interface_Static::SetIVal( "write.surfacecurve.mode", aOptimize ? 0 : 1 ) )
3347 {
3348 m_reporter->Report( _( "Failed to set surface curve mode, but will attempt to continue." ),
3350 }
3351
3352 if( false == writer.Transfer( m_doc, STEPControl_AsIs ) )
3353 return false;
3354
3355 APIHeaderSection_MakeHeader hdr( writer.ChangeWriter().Model() );
3356
3357 // Note: use only Ascii7 chars, non Ascii7 chars (therefore UFT8 chars)
3358 // are creating issues in the step file
3359 hdr.SetName( new TCollection_HAsciiString( fn.GetFullName().ToAscii() ) );
3360
3361 // TODO: how to control and ensure consistency with IGES?
3362 hdr.SetAuthorValue( 1, new TCollection_HAsciiString( "Pcbnew" ) );
3363 hdr.SetOrganizationValue( 1, new TCollection_HAsciiString( "Kicad" ) );
3364 hdr.SetOriginatingSystem( new TCollection_HAsciiString( "KiCad to STEP converter" ) );
3365 hdr.SetDescriptionValue( 1, new TCollection_HAsciiString( "KiCad electronic assembly" ) );
3366
3367 bool success = true;
3368
3369 // Creates a temporary file with a ascii7 name, because writer does not know unicode filenames.
3370 wxString currCWD = wxGetCwd();
3371 wxString workCWD = fn.GetPath();
3372
3373 if( !workCWD.IsEmpty() )
3374 wxSetWorkingDirectory( workCWD );
3375
3376 wxString tmpfname( "$tempfile$.step" );
3377
3378 if( false == writer.Write( tmpfname.c_str() ) )
3379 success = false;
3380
3381 if( compress && success )
3382 {
3383 wxString srcTmp( tmpfname );
3384 wxString dstTmp( "$tempfile$.stpz" );
3385
3386 success = STEP_PCB_MODEL::CompressSTEP( srcTmp, dstTmp );
3387 wxRemoveFile( srcTmp );
3388
3389 tmpfname = dstTmp;
3390 }
3391
3392 if( success )
3393 {
3394
3395 // Preserve the permissions of the current file
3396 KIPLATFORM::IO::DuplicatePermissions( fn.GetFullPath(), tmpfname.c_str() );
3397
3398 if( !wxRenameFile( tmpfname, fn.GetFullName(), true ) )
3399 {
3400 m_reporter->Report( wxString::Format( _( "Cannot rename temporary file '%s' to '%s'." ),
3401 tmpfname,
3402 fn.GetFullName() ),
3404 success = false;
3405 }
3406 }
3407
3408 wxSetWorkingDirectory( currCWD );
3409
3410 return success;
3411}
3412
3413
3414bool STEP_PCB_MODEL::WriteBREP( const wxString& aFileName )
3415{
3416 if( !isBoardOutlineValid() )
3417 {
3418 m_reporter->Report( wxString::Format( _( "No valid PCB assembly; cannot create output file '%s'." ),
3419 aFileName ),
3421 return false;
3422 }
3423
3425
3426 // s_assy = shape tool for the source
3427 Handle( XCAFDoc_ShapeTool ) s_assy = XCAFDoc_DocumentTool::ShapeTool( m_doc->Main() );
3428
3429 // retrieve assembly as a single shape
3430 TopoDS_Shape shape = getOneShape( s_assy );
3431
3432 wxFileName fn( aFileName );
3433
3434 wxFFileOutputStream ffStream( fn.GetFullPath() );
3435 wxStdOutputStream stdStream( ffStream );
3436
3437#if OCC_VERSION_HEX >= 0x070600
3438 BRepTools::Write( shape, stdStream, false, false, TopTools_FormatVersion_VERSION_1 );
3439#else
3440 BRepTools::Write( shape, stdStream );
3441#endif
3442
3443 return true;
3444}
3445
3446
3447bool STEP_PCB_MODEL::WriteXAO( const wxString& aFileName )
3448{
3449 wxFileName fn( aFileName );
3450
3451 wxFFileOutputStream ffStream( fn.GetFullPath() );
3452 wxStdOutputStream file( ffStream );
3453
3454 if( !ffStream.IsOk() )
3455 {
3456 m_reporter->Report( wxString::Format( "Could not open file '%s'", fn.GetFullPath() ),
3458 return false;
3459 }
3460
3462
3463 // s_assy = shape tool for the source
3464 Handle( XCAFDoc_ShapeTool ) s_assy = XCAFDoc_DocumentTool::ShapeTool( m_doc->Main() );
3465
3466 // retrieve assembly as a single shape
3467 const TopoDS_Shape shape = getOneShape( s_assy );
3468
3469 std::map<wxString, std::vector<int>> groups[4];
3470 std::map<wxString, double> groupAreas;
3471 TopExp_Explorer exp;
3472 int faceIndex = 0;
3473
3474 for( exp.Init( shape, TopAbs_FACE ); exp.More(); exp.Next() )
3475 {
3476 TopoDS_Shape subShape = exp.Current();
3477
3478 Bnd_Box bbox;
3479 BRepBndLib::Add( subShape, bbox );
3480
3481 for( const auto& [padKey, pairs] : m_pad_points )
3482 {
3483 for( const auto& pair : pairs )
3484 {
3485 const auto& [point, padTestShape] = pair;
3486
3487 if( bbox.IsOut( point ) )
3488 continue;
3489
3490 BRepAdaptor_Surface surface( TopoDS::Face( subShape ) );
3491
3492 if( surface.GetType() != GeomAbs_Plane )
3493 continue;
3494
3495 BRepExtrema_DistShapeShape dist( padTestShape, subShape );
3496 dist.Perform();
3497
3498 if( !dist.IsDone() )
3499 continue;
3500
3501 if( dist.Value() < Precision::Approximation() )
3502 {
3503 // Push as a face group
3504 groups[2][padKey].push_back( faceIndex );
3505
3506 GProp_GProps system;
3507 BRepGProp::SurfaceProperties( subShape, system );
3508
3509 double surfaceArea = system.Mass() / 1e6; // Convert to meters^2
3510 groupAreas[padKey] += surfaceArea;
3511 }
3512 }
3513 }
3514
3515 faceIndex++;
3516 }
3517
3518 // Based on Gmsh code
3519 file << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl;
3520 file << "<XAO version=\"1.0\" author=\"KiCad\">" << std::endl;
3521 file << " <geometry name=\"" << fn.GetName() << "\">" << std::endl;
3522 file << " <shape format=\"BREP\"><![CDATA[";
3523#if OCC_VERSION_HEX < 0x070600
3524 BRepTools::Write( shape, file );
3525#else
3526 BRepTools::Write( shape, file, true, true, TopTools_FormatVersion_VERSION_1 );
3527#endif
3528 file << "]]></shape>" << std::endl;
3529 file << " <topology>" << std::endl;
3530
3531 NCollection_IndexedMap<TopoDS_Shape, TopTools_ShapeMapHasher> mainMap;
3532 TopExp::MapShapes( shape, mainMap );
3533 std::set<int> topo[4];
3534
3535 static const TopAbs_ShapeEnum c_dimShapeTypes[] = { TopAbs_VERTEX, TopAbs_EDGE, TopAbs_FACE,
3536 TopAbs_SOLID };
3537
3538 static const std::string c_dimLabel[] = { "vertex", "edge", "face", "solid" };
3539 static const std::string c_dimLabels[] = { "vertices", "edges", "faces", "solids" };
3540
3541 for( int dim = 0; dim < 4; dim++ )
3542 {
3543 for( exp.Init( shape, c_dimShapeTypes[dim] ); exp.More(); exp.Next() )
3544 {
3545 TopoDS_Shape subShape = exp.Current();
3546 int idx = mainMap.FindIndex( subShape );
3547
3548 if( idx && !topo[dim].count( idx ) )
3549 topo[dim].insert( idx );
3550 }
3551 }
3552
3553 for( int dim = 0; dim <= 3; dim++ )
3554 {
3555 std::string labels = c_dimLabels[dim];
3556 std::string label = c_dimLabel[dim];
3557
3558 file << " <" << labels << " count=\"" << topo[dim].size() << "\">" << std::endl;
3559 int index = 0;
3560
3561 for( auto p : topo[dim] )
3562 {
3563 std::string name( "" );
3564 file << " <" << label << " index=\"" << index << "\" "
3565 << "name=\"" << name << "\" "
3566 << "reference=\"" << p << "\"/>" << std::endl;
3567
3568 index++;
3569 }
3570 file << " </" << labels << ">" << std::endl;
3571 }
3572
3573 file << " </topology>" << std::endl;
3574 file << " </geometry>" << std::endl;
3575 file << " <groups count=\""
3576 << groups[0].size() + groups[1].size() + groups[2].size() + groups[3].size() << "\">"
3577 << std::endl;
3578
3579 int groupNumber = 1;
3580
3581 m_reporter->Report( wxT( "Pad definitions:" ), RPT_SEVERITY_DEBUG );
3582 m_reporter->Report( wxT( "Number\tName\tArea (m^2)" ), RPT_SEVERITY_DEBUG );
3583
3584 for( int dim = 0; dim <= 3; dim++ )
3585 {
3586 std::string label = c_dimLabel[dim];
3587
3588 for( auto g : groups[dim] )
3589 {
3590 //std::string name = model->getPhysicalName( dim, g.first );
3591 wxString name = g.first;
3592
3593 if( name.empty() )
3594 { // create same unique name as for MED export
3595 std::ostringstream gs;
3596 gs << "G_" << dim << "D_" << g.first;
3597 name = gs.str();
3598 }
3599 file << " <group name=\"" << name << "\" dimension=\"" << label;
3600//#if 1
3601// // Gmsh XAO extension: also save the physical tag, so that XAO can be used
3602// // to serialize OCC geometries, ready to be used by GetDP, GmshFEM & co
3603// file << "\" tag=\"" << g.first;
3604//#endif
3605 file << "\" count=\"" << g.second.size() << "\">" << std::endl;
3606
3607 for( auto index : g.second )
3608 file << " <element index=\"" << index << "\"/>" << std::endl;
3609
3610 file << " </group>" << std::endl;
3611
3612 m_reporter->Report( wxString::Format( "%d\t%s\t%g",
3613 groupNumber,
3614 name,
3615 groupAreas[name] ),
3617
3618 groupNumber++;
3619 }
3620 }
3621
3622 m_reporter->Report( wxT( "" ), RPT_SEVERITY_DEBUG );
3623
3624 file << " </groups>" << std::endl;
3625 file << " <fields count=\"0\"/>" << std::endl;
3626 file << "</XAO>" << std::endl;
3627
3628 return true;
3629}
3630
3631
3632bool STEP_PCB_MODEL::getModelLabel( const wxString& aBaseName, const wxString& aFileName,
3633 const std::vector<wxString>& aAltFilenames, VECTOR3D aScale,
3634 TDF_Label& aLabel, bool aSubstituteModels,
3635 wxString* aErrorMessage )
3636{
3637 std::string fileNameUTF8 = aFileName.utf8_string();
3638
3639 std::string model_key = fileNameUTF8 + "_" + std::to_string( aScale.x ) + "_"
3640 + std::to_string( aScale.y ) + "_" + std::to_string( aScale.z );
3641
3642 MODEL_MAP::const_iterator mm = m_models.find( model_key );
3643
3644 if( mm != m_models.end() )
3645 {
3646 aLabel = mm->second;
3647 return true;
3648 }
3649
3650 aLabel.Nullify();
3651
3652 Handle( TDocStd_Document ) doc;
3653 m_app->NewDocument( "MDTV-XCAF", doc );
3654
3655 MODEL3D_FORMAT_TYPE modelFmt = fileType( fileNameUTF8.c_str() );
3656 TCollection_ExtendedString partname( aBaseName.utf8_str() );
3657
3658 switch( modelFmt )
3659 {
3660 case FMT_IGES:
3661 if( !readIGES( doc, fileNameUTF8.c_str() ) )
3662 {
3663 m_reporter->Report( wxString::Format( wxT( "readIGES() failed on filename '%s'." ), aFileName ),
3665 return false;
3666 }
3667
3668 break;
3669
3670 case FMT_STEP:
3671 if( !readSTEP( doc, fileNameUTF8.c_str() ) )
3672 {
3673 m_reporter->Report( wxString::Format( wxT( "readSTEP() failed on filename '%s'." ), aFileName ),
3675 return false;
3676 }
3677
3678 break;
3679
3680 case FMT_STEPZ:
3681 {
3682 // To export a compressed step file (.stpz or .stp.gz file), the best way is to
3683 // decaompress it in a temporaty file and load this temporary file
3684 wxFFileInputStream ifile( aFileName );
3685 wxFileName outFile( aFileName );
3686
3687 outFile.SetPath( wxStandardPaths::Get().GetTempDir() );
3688 outFile.SetExt( wxT( "step" ) );
3689 wxFileOffset size = ifile.GetLength();
3690
3691 if( size == wxInvalidOffset )
3692 {
3693 m_reporter->Report( wxString::Format( wxT( "getModelLabel() failed on filename '%s'." ),
3694 aFileName ),
3696 return false;
3697 }
3698
3699 {
3700 bool success = false;
3701
3702 {
3703 wxFFileOutputStream ofile( outFile.GetFullPath() );
3704
3705 if( !ofile.IsOk() )
3706 return false;
3707
3708 char* buffer = new char[size];
3709
3710 ifile.Read( buffer, size );
3711 std::string expanded;
3712
3713 try
3714 {
3715 expanded = gzip::decompress( buffer, size );
3716 success = true;
3717 }
3718 catch( ... )
3719 {
3720 // ignore - we try unzipping it below
3721 }
3722
3723 if( expanded.empty() )
3724 {
3725 ifile.Reset();
3726 ifile.SeekI( 0 );
3727 wxZipInputStream izipfile( ifile );
3728 std::unique_ptr<wxZipEntry> zip_file( izipfile.GetNextEntry() );
3729
3730 if( zip_file && !zip_file->IsDir() && izipfile.CanRead() )
3731 {
3732 izipfile.Read( ofile );
3733 success = true;
3734 }
3735 else
3736 {
3737 m_reporter->Report( wxString::Format( wxT( "failed to decompress '%s'." ), aFileName ),
3739 }
3740 }
3741 else
3742 {
3743 ofile.Write( expanded.data(), expanded.size() );
3744 }
3745
3746 delete[] buffer;
3747 }
3748
3749 if( success )
3750 {
3751 success = getModelLabel( aBaseName, outFile.GetFullPath(), aAltFilenames,
3752 VECTOR3D( 1.0, 1.0, 1.0 ), aLabel, false );
3753 }
3754
3755 return success;
3756 }
3757
3758 break;
3759 }
3760
3761 case FMT_WRL:
3762 case FMT_WRZ:
3763 /* WRL files are preferred for internal rendering, due to superior material properties, etc.
3764 * However they are not suitable for MCAD export.
3765 *
3766 * If a .wrl file is specified, attempt to locate a replacement file for it.
3767 *
3768 * If a valid replacement file is found, the label for THAT file will be associated with
3769 * the .wrl file
3770 */
3771 if( aSubstituteModels )
3772 {
3773 wxFileName wrlName( aFileName );
3774
3775 wxString basePath = wrlName.GetPath();
3776 wxString baseName = wrlName.GetName();
3777
3778 // List of alternate files to look for
3779 // Given in order of preference
3780 // (Break if match is found)
3781 wxArrayString alts;
3782
3783 // Step files
3784 alts.Add( wxT( "stp" ) );
3785 alts.Add( wxT( "step" ) );
3786 alts.Add( wxT( "STP" ) );
3787 alts.Add( wxT( "STEP" ) );
3788 alts.Add( wxT( "Stp" ) );
3789 alts.Add( wxT( "Step" ) );
3790 alts.Add( wxT( "stpz" ) );
3791 alts.Add( wxT( "stpZ" ) );
3792 alts.Add( wxT( "STPZ" ) );
3793 alts.Add( wxT( "step.gz" ) );
3794 alts.Add( wxT( "stp.gz" ) );
3795
3796 // IGES files
3797 alts.Add( wxT( "iges" ) );
3798 alts.Add( wxT( "IGES" ) );
3799 alts.Add( wxT( "igs" ) );
3800 alts.Add( wxT( "IGS" ) );
3801
3802 //TODO - Other alternative formats?
3803
3804 for( const auto& altExt : alts )
3805 {
3806 wxFileName altFile;
3807
3808 if( !aAltFilenames.empty() )
3809 {
3810 for( const wxString& altPath : aAltFilenames )
3811 {
3812 wxFileName iterFn( altPath );
3813
3814 if( iterFn.GetExt() == altExt )
3815 {
3816 altFile = iterFn;
3817 break;
3818 }
3819 }
3820 }
3821 else
3822 {
3823 altFile = wxFileName( basePath, baseName + wxT( "." ) + altExt );
3824 }
3825
3826 if( altFile.IsOk() && altFile.FileExists() )
3827 {
3828 // When substituting a STEP/IGS file for VRML, do not apply the VRML scaling
3829 // to the new STEP model. This process of auto-substitution is janky as all
3830 // heck so let's not mix up un-displayed scale factors with potentially
3831 // mis-matched files. And hope that the user doesn't have multiples files
3832 // named "model.wrl" and "model.stp" referring to different parts.
3833 // TODO: Fix model handling in v7. Default models should only be STP.
3834 // Have option to override this in DISPLAY.
3835 if( getModelLabel( aBaseName, altFile.GetFullPath(), {},
3836 VECTOR3D( 1.0, 1.0, 1.0 ), aLabel, false ) )
3837 {
3838 return true;
3839 }
3840 }
3841 }
3842 }
3843
3844 // VRML models only work when exporting to mesh formats
3845 // Also OCCT < 7.9.0 fails to load most VRML 2.0 models because of Switch nodes
3849 {
3850 if( readVRML( doc, fileNameUTF8.c_str() ) )
3851 {
3852 Handle( XCAFDoc_ShapeTool ) shapeTool =
3853 XCAFDoc_DocumentTool::ShapeTool( doc->Main() );
3854
3855 prefixNames( shapeTool->Label(), partname );
3856 }
3857 else
3858 {
3859 m_reporter->Report(
3860 wxString::Format( wxT( "readVRML() failed on filename '%s'." ),
3861 aFileName ),
3863
3864 return false;
3865 }
3866 }
3867 else // Substitution is not allowed
3868 {
3869 if( aErrorMessage )
3870 aErrorMessage->Printf( _( "Cannot use VRML models when exporting to non-mesh formats." ) );
3871
3872 return false;
3873 }
3874
3875 break;
3876
3877 // TODO: implement IDF and EMN converters
3878
3879 default:
3880 m_reporter->Report( wxString::Format( _( "Cannot identify actual file type for '%s'." ), aFileName ),
3882 return false;
3883 }
3884
3885 aLabel = transferModel( doc, m_doc, aScale );
3886
3887 if( aLabel.IsNull() )
3888 {
3889 m_reporter->Report( wxString::Format( _( "Could not transfer model data from file '%s'." ), aFileName ),
3891 return false;
3892 }
3893
3894 // attach the PART NAME ( base filename: note that in principle
3895 // different models may have the same base filename )
3896 TDataStd_Name::Set( aLabel, partname );
3897
3898 m_models.insert( MODEL_DATUM( model_key, aLabel ) );
3899 ++m_components;
3900 return true;
3901}
3902
3903
3904bool STEP_PCB_MODEL::getModelLocation( bool aBottom, const VECTOR2D& aPosition, double aRotation,
3905 const VECTOR3D& aOffset, const VECTOR3D& aOrientation,
3906 TopLoc_Location& aLocation )
3907{
3908 // Order of operations:
3909 // a. aOrientation is applied -Z*-Y*-X
3910 // b. aOffset is applied
3911 // Top ? add thickness to the Z offset
3912 // c. Bottom ? Rotate on X axis (in contrast to most ECAD which mirror on Y),
3913 // then rotate on +Z
3914 // Top ? rotate on -Z
3915 // d. aPosition is applied
3916 //
3917 // Note: Y axis is inverted in KiCad
3918
3919 gp_Trsf lPos;
3920 lPos.SetTranslation( gp_Vec( aPosition.x, -aPosition.y, 0.0 ) );
3921
3922 // Offset board thickness
3923 VECTOR3D offset( aOffset );
3924 offset.z += BOARD_OFFSET;
3925
3926 double boardThickness;
3927 double boardZPos;
3928 getBoardBodyZPlacement( boardZPos, boardThickness );
3929 double top = std::max( boardZPos, boardZPos + boardThickness );
3930 double bottom = std::min( boardZPos, boardZPos + boardThickness );
3931
3932 // 3D step models are placed on the top of copper layers.
3933 // This is true for SMD shapes, and perhaps not always true for TH shapes,
3934 // but we use this Z position for any 3D shape.
3935 double f_pos, f_thickness;
3936 getLayerZPlacement( F_Cu, f_pos, f_thickness );
3937 top += f_thickness;
3938 getLayerZPlacement( B_Cu, f_pos, f_thickness );
3939 bottom += f_thickness; // f_thickness is < 0 for B_Cu layer
3940
3941 gp_Trsf lRot;
3942
3943 if( aBottom )
3944 {
3945 offset.z -= bottom;
3946 lRot.SetRotation( gp_Ax1( gp_Pnt( 0.0, 0.0, 0.0 ), gp_Dir( 0.0, 0.0, 1.0 ) ), aRotation );
3947 lPos.Multiply( lRot );
3948 lRot.SetRotation( gp_Ax1( gp_Pnt( 0.0, 0.0, 0.0 ), gp_Dir( 1.0, 0.0, 0.0 ) ), M_PI );
3949 lPos.Multiply( lRot );
3950 }
3951 else
3952 {
3953 offset.z += top;
3954 lRot.SetRotation( gp_Ax1( gp_Pnt( 0.0, 0.0, 0.0 ), gp_Dir( 0.0, 0.0, 1.0 ) ), aRotation );
3955 lPos.Multiply( lRot );
3956 }
3957
3958 gp_Trsf lOff;
3959 lOff.SetTranslation( gp_Vec( offset.x, offset.y, offset.z ) );
3960 lPos.Multiply( lOff );
3961
3962 gp_Trsf lOrient;
3963 lOrient.SetRotation( gp_Ax1( gp_Pnt( 0.0, 0.0, 0.0 ), gp_Dir( 0.0, 0.0, 1.0 ) ), -aOrientation.z );
3964 lPos.Multiply( lOrient );
3965 lOrient.SetRotation( gp_Ax1( gp_Pnt( 0.0, 0.0, 0.0 ), gp_Dir( 0.0, 1.0, 0.0 ) ), -aOrientation.y );
3966 lPos.Multiply( lOrient );
3967 lOrient.SetRotation( gp_Ax1( gp_Pnt( 0.0, 0.0, 0.0 ), gp_Dir( 1.0, 0.0, 0.0 ) ), -aOrientation.x );
3968 lPos.Multiply( lOrient );
3969
3970 aLocation = TopLoc_Location( lPos );
3971 return true;
3972}
3973
3974
3975bool STEP_PCB_MODEL::readIGES( Handle( TDocStd_Document )& doc, const char* fname )
3976{
3977 IGESControl_Controller::Init();
3978 IGESCAFControl_Reader reader;
3979 IFSelect_ReturnStatus stat = reader.ReadFile( fname );
3980
3981 if( stat != IFSelect_RetDone )
3982 return false;
3983
3984 // Enable user-defined shape precision
3985 if( !Interface_Static::SetIVal( "read.precision.mode", 1 ) )
3986 return false;
3987
3988 // Set the shape conversion precision to USER_PREC (default 0.0001 has too many triangles)
3989 if( !Interface_Static::SetRVal( "read.precision.val", USER_PREC ) )
3990 return false;
3991
3992 // set other translation options
3993 reader.SetColorMode( true ); // use model colors
3994 reader.SetNameMode( false ); // don't use IGES label names
3995 reader.SetLayerMode( false ); // ignore LAYER data
3996
3997 if( !reader.Transfer( doc ) )
3998 {
3999 if( doc->CanClose() == CDM_CCS_OK )
4000 doc->Close();
4001
4002 return false;
4003 }
4004
4005 // are there any shapes to translate?
4006 if( reader.NbShapes() < 1 )
4007 {
4008 if( doc->CanClose() == CDM_CCS_OK )
4009 doc->Close();
4010
4011 return false;
4012 }
4013
4014 return true;
4015}
4016
4017
4018bool STEP_PCB_MODEL::readSTEP( Handle( TDocStd_Document )& doc, const char* fname )
4019{
4020 STEPCAFControl_Reader reader;
4021 IFSelect_ReturnStatus stat = reader.ReadFile( fname );
4022
4023 if( stat != IFSelect_RetDone )
4024 return false;
4025
4026 // Enable user-defined shape precision
4027 if( !Interface_Static::SetIVal( "read.precision.mode", 1 ) )
4028 return false;
4029
4030 // Set the shape conversion precision to USER_PREC (default 0.0001 has too many triangles)
4031 if( !Interface_Static::SetRVal( "read.precision.val", USER_PREC ) )
4032 return false;
4033
4034 // set other translation options
4035 reader.SetColorMode( true ); // use model colors
4036 reader.SetNameMode( true ); // use label names
4037 reader.SetLayerMode( false ); // ignore LAYER data
4038
4039 if( !reader.Transfer( doc ) )
4040 {
4041 if( doc->CanClose() == CDM_CCS_OK )
4042 doc->Close();
4043
4044 return false;
4045 }
4046
4047 // are there any shapes to translate?
4048 if( reader.NbRootsForTransfer() < 1 )
4049 {
4050 if( doc->CanClose() == CDM_CCS_OK )
4051 doc->Close();
4052
4053 return false;
4054 }
4055
4056 return true;
4057}
4058
4059
4060bool STEP_PCB_MODEL::readVRML( Handle( TDocStd_Document ) & doc, const char* fname )
4061{
4062#if OCC_VERSION_HEX >= 0x070700
4063 VrmlAPI_CafReader reader;
4064 RWMesh_CoordinateSystemConverter conv;
4065 conv.SetInputLengthUnit( 2.54 );
4066 reader.SetCoordinateSystemConverter( conv );
4067 reader.SetDocument( doc );
4068
4069 if( !reader.Perform( TCollection_AsciiString( fname ), Message_ProgressRange() ) )
4070 return false;
4071
4072 return true;
4073#else
4074 return false;
4075#endif
4076}
4077
4078
4079TDF_Label STEP_PCB_MODEL::transferModel( Handle( TDocStd_Document ) & source,
4080 Handle( TDocStd_Document ) & dest, const VECTOR3D& aScale )
4081{
4082 Handle( XCAFDoc_ShapeTool ) s_assy = XCAFDoc_DocumentTool::ShapeTool( source->Main() );
4083
4084 NCollection_Sequence<TDF_Label> frshapes;
4085 s_assy->GetFreeShapes( frshapes );
4086
4087 Handle( XCAFDoc_ShapeTool ) d_assy = XCAFDoc_DocumentTool::ShapeTool( dest->Main() );
4088
4089 // Create a new top-level assembly in the destination and clone the source's free shapes
4090 // into it with XCAFDoc_Editor::Extract. Extract rebuilds the XDE label tree by walking
4091 // the component reference graph, so it preserves colors, names and sub-assembly structure
4092 // even when the source root does not directly own the part labels (as is the case with
4093 // default KiCad 3D models produced by CadQuery). It is also immune to the
4094 // "not self-contained" restriction of TDocStd_XLinkTool::Copy, so Fusion 360 STEP files
4095 // with linked components work as well.
4096 TDF_Label d_targetLabel = d_assy->NewShape();
4097
4098 if( !XCAFDoc_Editor::Extract( frshapes, d_targetLabel, false ) )
4099 {
4100 m_reporter->Report( wxT( "Failed to transfer model." ), RPT_SEVERITY_ERROR );
4101 return TDF_Label();
4102 }
4103
4104 if( aScale.x != 1.0 || aScale.y != 1.0 || aScale.z != 1.0 )
4105 rescaleShapes( d_targetLabel, gp_XYZ( aScale.x, aScale.y, aScale.z ) );
4106
4107 return d_targetLabel;
4108}
4109
4110
4111bool STEP_PCB_MODEL::performMeshing( Handle( XCAFDoc_ShapeTool ) & aShapeTool )
4112{
4113 NCollection_Sequence<TDF_Label> freeShapes;
4114 aShapeTool->GetFreeShapes( freeShapes );
4115
4116 m_reporter->Report( wxT( "Meshing model" ), RPT_SEVERITY_DEBUG );
4117
4118 // GLTF is a mesh format, we have to trigger opencascade to mesh the shapes we composited into the asesmbly
4119 // To mesh models, lets just grab the free shape root and execute on them
4120 for( int i = 1; i <= freeShapes.Length(); ++i )
4121 {
4122 TDF_Label label = freeShapes.Value( i );
4123 TopoDS_Shape shape;
4124 aShapeTool->GetShape( label, shape );
4125
4126 // These deflection values basically affect the accuracy of the mesh generated, a tighter
4127 // deflection will result in larger meshes
4128 // We could make this a tunable parameter, but for now fix it
4129 const double linearDeflection = 0.14;
4130 const double angularDeflection = DEG2RAD( 30.0 );
4131 BRepMesh_IncrementalMesh mesh( shape, linearDeflection, false, angularDeflection,
4132 true );
4133 }
4134
4135 return true;
4136}
4137
4138
4139bool STEP_PCB_MODEL::WriteGLTF( const wxString& aFileName )
4140{
4141 /*if( !isBoardOutlineValid() )
4142 {
4143 m_reporter->Report( wxString::Format( _( "No valid PCB assembly; cannot create output file '%s'." ),
4144 aFileName ),
4145 RPT_SEVERITY_ERROR );
4146 return false;
4147 }*/
4148
4150
4151 performMeshing( m_assy );
4152
4153 wxFileName fn( aFileName );
4154
4155 const char* tmpGltfname = "$tempfile$.glb";
4156 RWGltf_CafWriter cafWriter( tmpGltfname, true );
4157
4158 cafWriter.SetTransformationFormat( RWGltf_WriterTrsfFormat_Compact );
4159 cafWriter.ChangeCoordinateSystemConverter().SetInputLengthUnit( 0.001 );
4160 cafWriter.ChangeCoordinateSystemConverter().SetInputCoordinateSystem(
4161 RWMesh_CoordinateSystem_Zup );
4162#if OCC_VERSION_HEX >= 0x070700
4163 cafWriter.SetParallel( true );
4164#endif
4165
4166#if OCC_VERSION_HEX >= 0x080000
4167 NCollection_IndexedDataMap<TCollection_AsciiString, TCollection_AsciiString> metadata;
4168#else
4169 TColStd_IndexedDataMapOfStringString metadata;
4170#endif
4171
4172 metadata.Add( TCollection_AsciiString( "pcb_name" ),
4173 TCollection_ExtendedString( fn.GetName().wc_str() ) );
4174 metadata.Add( TCollection_AsciiString( "source_pcb_file" ),
4175 TCollection_ExtendedString( fn.GetFullName().wc_str() ) );
4176 metadata.Add( TCollection_AsciiString( "generator" ),
4177 TCollection_AsciiString( wxString::Format( wxS( "KiCad %s" ), GetSemanticVersion() ).ToAscii() ) );
4178 metadata.Add( TCollection_AsciiString( "generated_at" ),
4179 TCollection_AsciiString( GetISO8601CurrentDateTime().ToAscii() ) );
4180
4181 bool success = true;
4182
4183 // Creates a temporary file with a ascii7 name, because writer does not know unicode filenames.
4184 wxString currCWD = wxGetCwd();
4185 wxString workCWD = fn.GetPath();
4186
4187 if( !workCWD.IsEmpty() )
4188 wxSetWorkingDirectory( workCWD );
4189
4190 success = cafWriter.Perform( m_doc, metadata, Message_ProgressRange() );
4191
4192 if( success )
4193 {
4194 // OCCT 7.9+ can produce LINES primitives with odd index counts for degenerate
4195 // BSpline edges, violating the glTF spec and causing Blender import failures. A
4196 // failure here leaves the original writer output intact, so warn and keep going.
4197 if( !FixGlbLinesPrimitives( wxString( tmpGltfname ) ) )
4198 {
4199 m_reporter->Report( _( "Could not post-process GLB line primitives; the exported "
4200 "model may not import in strict glTF viewers." ),
4202 }
4203
4204 // Preserve the permissions of the current file
4205 KIPLATFORM::IO::DuplicatePermissions( fn.GetFullPath(), tmpGltfname );
4206
4207 if( !wxRenameFile( tmpGltfname, fn.GetFullName(), true ) )
4208 {
4209 m_reporter->Report( wxString::Format( _( "Cannot rename temporary file '%s' to '%s'." ),
4210 tmpGltfname,
4211 fn.GetFullName() ),
4213 success = false;
4214 }
4215 }
4216
4217 wxSetWorkingDirectory( currCWD );
4218
4219 return success;
4220}
4221
4222
4223bool STEP_PCB_MODEL::WritePLY( const wxString& aFileName )
4224{
4225#if OCC_VERSION_HEX < 0x070700
4226 m_reporter->Report( wxT( "PLY export is not supported before OCCT 7.7.0" ), RPT_SEVERITY_ERROR );
4227 return false;
4228#else
4229
4230 if( !isBoardOutlineValid() )
4231 {
4232 m_reporter->Report( wxString::Format( _( "No valid PCB assembly; cannot create output file '%s'." ),
4233 aFileName ),
4235 return false;
4236 }
4237
4239
4240 performMeshing( m_assy );
4241
4242 wxFileName fn( aFileName );
4243
4244 const char* tmpFname = "$tempfile$.ply";
4245 RWPly_CafWriter cafWriter( tmpFname );
4246
4247 cafWriter.SetFaceId( true ); // TODO: configurable SetPartId/SetFaceId
4248 cafWriter.ChangeCoordinateSystemConverter().SetInputLengthUnit( 0.001 );
4249 cafWriter.ChangeCoordinateSystemConverter().SetInputCoordinateSystem( RWMesh_CoordinateSystem_Zup );
4250
4251#if OCC_VERSION_HEX >= 0x080000
4252 NCollection_IndexedDataMap<TCollection_AsciiString, TCollection_AsciiString> metadata;
4253#else
4254 TColStd_IndexedDataMapOfStringString metadata;
4255#endif
4256
4257 metadata.Add( TCollection_AsciiString( "pcb_name" ),
4258 TCollection_ExtendedString( fn.GetName().wc_str() ) );
4259 metadata.Add( TCollection_AsciiString( "source_pcb_file" ),
4260 TCollection_ExtendedString( fn.GetFullName().wc_str() ) );
4261 metadata.Add( TCollection_AsciiString( "generator" ),
4262 TCollection_AsciiString( wxString::Format( wxS( "KiCad %s" ),
4263 GetSemanticVersion() ).ToAscii() ) );
4264 metadata.Add( TCollection_AsciiString( "generated_at" ),
4265 TCollection_AsciiString( GetISO8601CurrentDateTime().ToAscii() ) );
4266
4267 bool success = true;
4268
4269 // Creates a temporary file with a ascii7 name, because writer does not know unicode filenames.
4270 wxString currCWD = wxGetCwd();
4271 wxString workCWD = fn.GetPath();
4272
4273 if( !workCWD.IsEmpty() )
4274 wxSetWorkingDirectory( workCWD );
4275
4276 success = cafWriter.Perform( m_doc, metadata, Message_ProgressRange() );
4277
4278 if( success )
4279 {
4280 // Preserve the permissions of the current file
4281 KIPLATFORM::IO::DuplicatePermissions( fn.GetFullPath(), tmpFname );
4282
4283 if( !wxRenameFile( tmpFname, fn.GetFullName(), true ) )
4284 {
4285 m_reporter->Report( wxString::Format( _( "Cannot rename temporary file '%s' to '%s'." ),
4286 tmpFname,
4287 fn.GetFullName() ),
4289 success = false;
4290 }
4291 }
4292
4293 wxSetWorkingDirectory( currCWD );
4294
4295 return success;
4296#endif
4297}
4298
4299
4300bool STEP_PCB_MODEL::WriteSTL( const wxString& aFileName )
4301{
4302 if( !isBoardOutlineValid() )
4303 {
4304 m_reporter->Report( wxString::Format( _( "No valid PCB assembly; cannot create output file '%s'." ),
4305 aFileName ),
4307 return false;
4308 }
4309
4311
4312 performMeshing( m_assy );
4313
4314 wxFileName fn( aFileName );
4315
4316 const char* tmpFname = "$tempfile$.stl";
4317
4318 // Creates a temporary file with a ascii7 name, because writer does not know unicode filenames.
4319 wxString currCWD = wxGetCwd();
4320 wxString workCWD = fn.GetPath();
4321
4322 if( !workCWD.IsEmpty() )
4323 wxSetWorkingDirectory( workCWD );
4324
4325 bool success = StlAPI_Writer().Write( getOneShape( m_assy ), tmpFname );
4326
4327 if( success )
4328 {
4329 // Preserve the permissions of the current file
4330 KIPLATFORM::IO::DuplicatePermissions( fn.GetFullPath(), tmpFname );
4331
4332 if( !wxRenameFile( tmpFname, fn.GetFullName(), true ) )
4333 {
4334 m_reporter->Report( wxString::Format( _( "Cannot rename temporary file '%s' to '%s'." ),
4335 tmpFname,
4336 fn.GetFullName() ),
4338 success = false;
4339 }
4340 }
4341
4342 wxSetWorkingDirectory( currCWD );
4343
4344 return success;
4345}
4346
4347
4348
4349bool STEP_PCB_MODEL::WriteU3D( const wxString& aFileName )
4350{
4351 if( !isBoardOutlineValid() )
4352 {
4353 m_reporter->Report(
4354 wxString::Format( _( "No valid PCB assembly; cannot create output file '%s'.\n" ), aFileName ),
4356 return false;
4357 }
4358
4360
4361 performMeshing( m_assy );
4362
4363 wxFileName fn( aFileName );
4364
4365 const char* tmpFname = "$tempfile$.u3d";
4366
4367 // Creates a temporary file with a ascii7 name, because writer does not know unicode filenames.
4368 wxString currCWD = wxGetCwd();
4369 wxString workCWD = fn.GetPath();
4370
4371 if( !workCWD.IsEmpty() )
4372 wxSetWorkingDirectory( workCWD );
4373
4374 U3D::WRITER writer( tmpFname );
4375 bool success = writer.Perform( m_doc );
4376 if( success )
4377 {
4378 // Preserve the permissions of the current file
4379 KIPLATFORM::IO::DuplicatePermissions( fn.GetFullPath(), tmpFname );
4380
4381 if( !wxRenameFile( tmpFname, fn.GetFullName(), true ) )
4382 {
4383 m_reporter->Report( wxString::Format( wxT( "Cannot rename temporary file '%s' to '%s'.\n" ), tmpFname,
4384 fn.GetFullName() ),
4386 success = false;
4387 }
4388 }
4389
4390 wxSetWorkingDirectory( currCWD );
4391
4392 return success;
4393}
4394
4395
4396bool STEP_PCB_MODEL::WritePDF( const wxString& aFileName )
4397{
4398 if( !isBoardOutlineValid() )
4399 {
4400 m_reporter->Report(
4401 wxString::Format( _( "No valid PCB assembly; cannot create output file '%s'.\n" ), aFileName ),
4403 return false;
4404 }
4405
4407
4408 performMeshing( m_assy );
4409
4410 wxFileName fn( aFileName );
4411
4412 wxFileName u3dTmpfn = wxFileName::CreateTempFileName( "" );
4413 wxFileName pdfTmpfn = wxFileName::CreateTempFileName( "" );
4414
4415 U3D::WRITER writer( u3dTmpfn.GetFullPath().ToStdString() );
4416 bool success = writer.Perform( m_doc );
4417
4418 // PDF test
4419 std::unique_ptr<PDF_PLOTTER> plotter = std::make_unique<PDF_PLOTTER>();
4420
4421 plotter->SetColorMode( true );
4422 plotter->Set3DExport( true );
4423 plotter->SetCreator( wxString::Format( "KiCad %s", GetMajorMinorPatchVersion() ) );
4424 KIGFX::PCB_RENDER_SETTINGS renderSettings;
4425 plotter->SetRenderSettings( &renderSettings );
4426
4427 if( !plotter->OpenFile( pdfTmpfn.GetFullPath() ) )
4428 {
4429 m_reporter->Report( wxString::Format( wxT( "Cannot open temporary file '%s'.\n" ), pdfTmpfn.GetFullPath() ),
4431 success = false;
4432 }
4433 else
4434 {
4435 plotter->StartPlot( "1", "3D Model" );
4436 double fov_degrees = 16.5f;
4437
4438 // kind of an arbitrary distance determination
4439 float distance = sqrt( writer.GetMeshBoundingBox().SquareExtent() ) * 3;
4440
4441 std::vector<PDF_3D_VIEW> views;
4442
4443 VECTOR3D camTarget = writer.GetCenter();
4444
4445
4446 std::vector<float> c2wMatrix =
4447 PDF_PLOTTER::CreateC2WMatrixFromAngles( camTarget, distance, 180.0f, -75.0f, 25.0f );
4448
4449 views.emplace_back( PDF_3D_VIEW{
4450 .m_name = "Default",
4451 .m_cameraMatrix = c2wMatrix,
4452 .m_cameraCenter = (float) distance,
4453 .m_fov = (float) fov_degrees,
4454 } );
4455
4456
4457
4458 c2wMatrix = PDF_PLOTTER::CreateC2WMatrixFromAngles( camTarget, distance, 180.0, 0.0f, 0.0f );
4459
4460 views.emplace_back( PDF_3D_VIEW{
4461 .m_name = "Top",
4462 .m_cameraMatrix = c2wMatrix,
4463 .m_cameraCenter = (float) distance,
4464 .m_fov = (float) fov_degrees,
4465 } );
4466
4467
4468
4469 c2wMatrix = PDF_PLOTTER::CreateC2WMatrixFromAngles( camTarget, distance, 0.0, 0.0f, 0.0f );
4470
4471 views.emplace_back( PDF_3D_VIEW{
4472 .m_name = "Bottom",
4473 .m_cameraMatrix = c2wMatrix,
4474 .m_cameraCenter = (float) distance,
4475 .m_fov = (float) fov_degrees,
4476 } );
4477
4478
4479
4480 c2wMatrix = PDF_PLOTTER::CreateC2WMatrixFromAngles( camTarget, distance, 90.0f, -90.0f, 90.0f );
4481
4482 views.emplace_back( PDF_3D_VIEW{
4483 .m_name = "Front",
4484 .m_cameraMatrix = c2wMatrix,
4485 .m_cameraCenter = (float) distance,
4486 .m_fov = (float) fov_degrees,
4487 } );
4488
4489 plotter->Plot3DModel( u3dTmpfn.GetFullPath(), views );
4490 plotter->EndPlot();
4491 }
4492
4493 if( success )
4494 {
4495 // Preserve the permissions of the current file
4496 KIPLATFORM::IO::DuplicatePermissions( fn.GetFullPath(), pdfTmpfn.GetFullPath() );
4497
4498 if( !wxRenameFile( pdfTmpfn.GetFullPath(), fn.GetFullPath(), true ) )
4499 {
4500 m_reporter->Report( wxString::Format( wxT( "Cannot rename temporary file '%s' to '%s'.\n" ),
4501 pdfTmpfn.GetFullPath(), fn.GetFullPath() ),
4503 success = false;
4504 }
4505 }
4506
4507 wxRemoveFile( u3dTmpfn.GetFullPath() );
4508
4509 return success;
4510}
bool GetExtrusionPinOutlines(const FOOTPRINT *aFootprint, SHAPE_POLY_SET &aPinPoly, SHAPE_POLY_SET &aPegPoly)
Get the hole outline polygons for extruded pin rendering.
void ApplyExtrusionTransform(SHAPE_POLY_SET &aOutline, const EXTRUDED_3D_BODY *aBody, const VECTOR2I &aFpPos)
Apply 2D extrusion transforms (rotation, scale, offset) to an outline.
int index
const char * name
@ ERROR_OUTSIDE
@ ERROR_INSIDE
constexpr EDA_IU_SCALE pcbIUScale
Definition base_units.h:128
bool IsPrmSpecified(const wxString &aPrmValue)
BOARD_STACKUP_ITEM_TYPE
@ BS_ITEM_TYPE_COPPER
@ BS_ITEM_TYPE_SILKSCREEN
@ BS_ITEM_TYPE_DIELECTRIC
@ BS_ITEM_TYPE_SOLDERMASK
BOX2< VECTOR2I > BOX2I
Definition box2.h:917
wxString GetMajorMinorPatchVersion()
Get the major, minor and patch version in a string major.minor.patch This is extracted by CMake from ...
wxString GetSemanticVersion()
Get the semantic version string for KiCad defined inside the KiCadVersion.cmake file in the variable ...
const wxString & GetShortNetname() const
int GetY() const
Definition board_item.h:154
int GetX() const
Definition board_item.h:148
FOOTPRINT * GetParentFootprint() const
int GetMaxError() const
Manage one layer needed to make a physical board.
wxString GetTypeName() const
int GetSublayersCount() const
PCB_LAYER_ID GetBrdLayerId() const
int GetThickness(int aDielectricSubLayer=0) const
BOARD_STACKUP_ITEM_TYPE GetType() const
Manage layers needed to make a physical board.
constexpr coord_type GetLeft() const
Definition box2.h:231
constexpr coord_type GetRight() const
Definition box2.h:220
constexpr coord_type GetTop() const
Definition box2.h:232
constexpr coord_type GetBottom() const
Definition box2.h:225
double AsDegrees() const
Definition eda_angle.h:115
VECTOR3D m_offset
Definition pcb_3d_body.h:52
wxString GetReferenceAsString() const
Definition footprint.h:802
VECTOR2I GetPosition() const override
Definition footprint.h:379
A color representation with 4 components: red, green, blue, alpha.
Definition color4d.h:101
double r
Red component.
Definition color4d.h:391
double g
Green component.
Definition color4d.h:392
COLOR4D & Darken(double aFactor)
Makes the color darker by a given factor.
Definition color4d.h:223
double a
Alpha component.
Definition color4d.h:394
double b
Blue component.
Definition color4d.h:393
PCB specific render settings.
Definition pcb_painter.h:94
LSET is a set of PCB_LAYER_IDs.
Definition lset.h:37
LSEQ Seq(const LSEQ &aSequence) const
Return an LSEQ from the union of this LSET and a desired sequence.
Definition lset.cpp:309
Definition pad.h:61
PAD_PROP GetProperty() const
Definition pad.h:585
LSET GetLayerSet() const override
Return a std::bitset of all layers on which the item physically resides.
Definition pad.h:579
bool FlashLayer(int aLayer, bool aOnlyCheckIfPermitted=false) const
Check to see whether the pad should be flashed on the specific layer.
Definition pad.cpp:697
std::shared_ptr< SHAPE_SEGMENT > GetEffectiveHoleShape(PCB_LAYER_ID aLayer=UNDEFINED_LAYER, DRC_CONSTRAINT_T aUsage=NULL_CONSTRAINT) const override
Return a SHAPE_SEGMENT object representing the pad's hole.
Definition pad.cpp:1233
bool IsOnLayer(PCB_LAYER_ID aLayer) const override
Test to see if this object is on the given layer.
Definition pad.h:950
PAD_ATTRIB GetAttribute() const
Definition pad.h:582
const wxString & GetNumber() const
Definition pad.h:143
void TransformShapeToPolygon(SHAPE_POLY_SET &aBuffer, PCB_LAYER_ID aLayer, int aClearance, int aMaxError, ERROR_LOC aErrorLoc=ERROR_INSIDE, bool aIgnoreLineWidth=false) const override
Convert the pad shape to a closed polygon.
Definition pad.cpp:3036
VECTOR2I GetDrillSize() const
Definition pad.h:320
static std::vector< float > CreateC2WMatrixFromAngles(const VECTOR3D &aTargetPosition, float aCameraDistance, float aYawDegrees, float aPitchDegrees, float aRollDegrees)
Generates the camera to world matrix for use with a 3D View.
A pure virtual class used to derive REPORTER objects from.
Definition reporter.h:73
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED)
Report a string with a given severity.
Definition reporter.h:102
Definition seg.h:38
VECTOR2I A
Definition seg.h:45
VECTOR2I B
Definition seg.h:46
EDA_ANGLE GetCentralAngle() const
Get the "central angle" of the arc - this is the angle at the point of the "pie slice".
const VECTOR2I & GetArcMid() const
Definition shape_arc.h:116
VECTOR2I NearestPoint(const VECTOR2I &aP) const
const VECTOR2I & GetP1() const
Definition shape_arc.h:115
double GetRadius() const
const VECTOR2I & GetP0() const
Definition shape_arc.h:114
const VECTOR2I & GetCenter() const
Represent a polyline containing arcs as well as line segments: A chain of connected line and/or arc s...
const SHAPE_ARC & Arc(size_t aArc) const
bool IsClosed() const override
void SetClosed(bool aClosed)
Mark the line chain as closed (i.e.
int PointCount() const
Return the number of points (vertices) in this line chain.
ssize_t ArcIndex(size_t aSegment) const
Return the arc index for the given segment index.
void Clear()
Remove all points from the line chain.
const std::optional< INTERSECTION > SelfIntersectingWithArcs() const
Check if the line chain is self-intersecting.
int NextShape(int aPointIndex) const
Return the vertex index of the next shape in the chain, or -1 if aPointIndex is the last shape.
void Append(int aX, int aY, bool aAllowDuplication=false)
Append a new point at the end of the line chain.
const VECTOR2I & CPoint(int aIndex) const
Return a reference to a given point in the line chain.
const SHAPE_LINE_CHAIN Slice(int aStartIndex, int aEndIndex) const
Return a subset of this line chain containing the [start_index, end_index] range of points.
virtual size_t GetSegmentCount() const override
const SEG CSegment(int aIndex) const
Return a constant copy of the aIndex segment in the line chain.
bool IsArcSegment(size_t aSegment) const
void RemoveShape(int aPointIndex)
Remove the shape at the given index from the line chain.
bool IsArcStart(size_t aIndex) const
Represent a set of closed polygons.
void ClearArcs()
Removes all arc references from all the outlines and holes in the polyset.
bool IsEmpty() const
Return true if the set is empty (no polygons at all)
POLYGON & Polygon(int aIndex)
Return the aIndex-th subpolygon in the set.
int FullPointCount() const
Return the number of points in the shape poly set.
int Append(int x, int y, int aOutline=-1, int aHole=-1, bool aAllowDuplication=false)
Appends a vertex at the end of the given outline/hole (default: the last outline)
void Simplify()
Simplify the polyset (merges overlapping polys, eliminates degeneracy/self-intersections)
std::vector< SHAPE_LINE_CHAIN > POLYGON
represents a single polygon outline with holes.
void BooleanIntersection(const SHAPE_POLY_SET &b)
Perform boolean polyset intersection.
int OutlineCount() const
Return the number of outlines in the set.
const POLYGON & CPolygon(int aIndex) const
const std::vector< POLYGON > & CPolygons() const
const SEG & GetSeg() const
int GetWidth() const override
bool MakeShapeAsThickSegment(TopoDS_Shape &aShape, const VECTOR2D &aStartPoint, const VECTOR2D &aEndPoint, double aWidth, double aThickness, double aZposition, const VECTOR2D &aOrigin)
Make a segment shape based on start and end point.
OUTPUT_FORMAT m_outFmt
The current output format for created file.
void SetCopperColor(double r, double g, double b)
bool WritePLY(const wxString &aFileName)
bool AddCountersink(const VECTOR2I &aPosition, int aDiameter, int aDepth, int aAngle, bool aFrontSide, const VECTOR2D &aOrigin)
Add a countersink shape to remove board material from the top or bottom of a hole.
std::map< wxString, std::vector< TopoDS_Shape > > m_board_copper_vias
std::map< wxString, std::vector< TopoDS_Shape > > m_board_copper_pads
bool WriteSTEP(const wxString &aFileName, bool aOptimize, bool compress)
std::vector< TopoDS_Shape > m_board_back_mask
bool AddExtrudedPins(const FOOTPRINT *aFootprint, const EXTRUDED_3D_BODY *aBody, bool aBottom, double aStandoff, const VECTOR2D &aOrigin)
Add pin extrusions for pad holes.
wxString m_pcbName
Name of the PCB, which will most likely be the file name of the path.
std::vector< TopoDS_Shape > m_boardCutouts
bool AddPolygonShapes(const SHAPE_POLY_SET *aPolyShapes, PCB_LAYER_ID aLayer, const VECTOR2D &aOrigin, const wxString &aNetname)
bool CreatePCB(SHAPE_POLY_SET &aOutline, const VECTOR2D &aOrigin, bool aPushBoardBody)
void getBoardBodyZPlacement(double &aZPos, double &aThickness)
double getStackupBodyThickness() const
TDF_Label transferModel(Handle(TDocStd_Document)&source, Handle(TDocStd_Document) &dest, const VECTOR3D &aScale)
TDF_Label m_assy_label
bool getModelLocation(bool aBottom, const VECTOR2D &aPosition, double aRotation, const VECTOR3D &aOffset, const VECTOR3D &aOrientation, TopLoc_Location &aLocation)
void SetFuseShapes(bool aValue)
bool WriteXAO(const wxString &aFileName)
bool WriteGLTF(const wxString &aFileName)
Write the assembly in binary GLTF Format.
REPORTER * m_reporter
std::vector< TDF_Label > m_pcb_labels
STEP_PCB_MODEL(const wxString &aPcbName, REPORTER *aReporter)
std::vector< EXTRUDED_BODY_ENTRY > m_extruded_bodies
bool AddBackdrill(const SHAPE_SEGMENT &aShape, PCB_LAYER_ID aLayerStart, PCB_LAYER_ID aLayerEnd, const VECTOR2D &aOrigin)
Add a backdrill hole shape to remove board material and copper plating.
void getLayerZPlacement(PCB_LAYER_ID aLayer, double &aZPos, double &aThickness)
std::vector< TopoDS_Shape > m_board_outlines
void SetSimplifyShapes(bool aValue)
bool WriteU3D(const wxString &aFileName)
SYNC_REPORTER m_syncReporter
Thread-safe wrapper around the caller's reporter.
bool getModelLabel(const wxString &aBaseName, const wxString &aFileName, const std::vector< wxString > &aAltFilenames, VECTOR3D aScale, TDF_Label &aLabel, bool aSubstituteModels, wxString *aErrorMessage=nullptr)
Load a 3D model data.
bool readVRML(Handle(TDocStd_Document) &aDoc, const char *aFname)
void SetPadColor(double r, double g, double b)
bool AddCounterbore(const VECTOR2I &aPosition, int aDiameter, int aDepth, bool aFrontSide, const VECTOR2D &aOrigin)
Add a counterbore shape to remove board material from the top or bottom of a hole.
void SetEnabledLayers(const LSET &aLayers)
void SetExtraPadThickness(bool aValue)
bool performMeshing(Handle(XCAFDoc_ShapeTool) &aShapeTool)
bool MakePolygonAsWall(TopoDS_Shape &aShape, SHAPE_POLY_SET &aPolySet, double aHeight, double aZposition, const VECTOR2D &aOrigin)
Make a polygonal shape to create a vertical wall.
bool readSTEP(Handle(TDocStd_Document) &aDoc, const char *aFname)
std::vector< TopoDS_Shape > m_board_front_silk
Handle(XCAFApp_Application) m_app
bool WritePDF(const wxString &aFileName)
virtual ~STEP_PCB_MODEL()
std::vector< TopoDS_Shape > m_board_front_mask
double m_copperColor[3]
bool WriteSTL(const wxString &aFileName)
void SetStackup(const BOARD_STACKUP &aStackup)
void SetNetFilter(const wxString &aFilter)
double m_padColor[3]
std::map< wxString, std::vector< TopoDS_Shape > > m_board_copper
std::map< PCB_LAYER_ID, int > GetCopperLayerKnockouts(int aDiameter, int aDepth, int aAngle, bool aFrontSide)
Get the knockout diameters for copper layers that a counterbore or countersink crosses.
bool MakeShapes(std::vector< TopoDS_Shape > &aShapes, const SHAPE_POLY_SET &aPolySet, bool aConvertToArcs, double aThickness, double aZposition, const VECTOR2D &aOrigin)
Convert a SHAPE_POLY_SET to TopoDS_Shape's (polygonal vertical prisms, or flat faces)
bool AddBarrel(const SHAPE_SEGMENT &aShape, PCB_LAYER_ID aLayerTop, PCB_LAYER_ID aLayerBot, bool aVia, const VECTOR2D &aOrigin, const wxString &aNetname)
bool readIGES(Handle(TDocStd_Document) &aDoc, const char *aFname)
bool AddHole(const SHAPE_SEGMENT &aShape, int aPlatingThickness, PCB_LAYER_ID aLayerTop, PCB_LAYER_ID aLayerBot, bool aVia, const VECTOR2D &aOrigin, bool aCutCopper, bool aCutBody)
std::vector< TopoDS_Shape > m_copperCutouts
bool CompressSTEP(wxString &inputFile, wxString &outputFile)
std::vector< TopoDS_Shape > m_board_back_silk
void getCopperLayerZPlacement(PCB_LAYER_ID aLayer, double &aZPos, double &aThickness)
bool AddComponent(const wxString &aBaseName, const wxString &aFileName, const std::vector< wxString > &aAltFilenames, const wxString &aRefDes, bool aBottom, VECTOR2D aPosition, double aRotation, VECTOR3D aOffset, VECTOR3D aOrientation, VECTOR3D aScale, bool aSubstituteModels=true)
bool AddExtrudedBody(const SHAPE_POLY_SET &aOutline, bool aBottom, double aStandoff, double aHeight, const VECTOR2D &aOrigin, uint32_t aColor, EXTRUSION_MATERIAL aMaterial, const wxString &aRefDes)
Add an extruded 3D body from a 2D outline polygon.
std::map< wxString, std::vector< std::pair< gp_Pnt, TopoDS_Shape > > > m_pad_points
bool AddPadShape(const PAD *aPad, const VECTOR2D &aOrigin, bool aVia, SHAPE_POLY_SET *aClipPolygon=nullptr)
void OCCSetMergeMaxDistance(double aDistance=OCC_MAX_DISTANCE_TO_MERGE_POINTS)
BOARD_STACKUP m_stackup
bool WriteBREP(const wxString &aFileName)
bool Perform(const Handle(TDocStd_Document) &aDocument)
Definition writer.cpp:963
const VECTOR3D & GetCenter() const
Definition writer.h:205
const Bnd_Box & GetMeshBoundingBox() const
Definition writer.h:206
wxString StringFromValue(double aValue, bool aAddUnitLabel=false, EDA_DATA_TYPE aType=EDA_DATA_TYPE::DISTANCE) const
Converts aValue in internal units into a united string.
T EuclideanNorm() const
Compute the Euclidean norm of the vector, which is defined as sqrt(x ** 2 + y ** 2).
Definition vector2d.h:281
void TransformCircleToPolygon(SHAPE_LINE_CHAIN &aBuffer, const VECTOR2I &aCenter, int aRadius, int aError, ERROR_LOC aErrorLoc, int aMinSegCount=0)
Convert a circle to a polygon, using multiple straight lines.
void TransformOvalToPolygon(SHAPE_POLY_SET &aBuffer, const VECTOR2I &aStart, const VECTOR2I &aEnd, int aWidth, int aError, ERROR_LOC aErrorLoc, int aMinSegCount=0)
Convert a oblong shape to a polygon, using multiple segments.
#define _(s)
@ DEGREES_T
Definition eda_angle.h:30
static constexpr EDA_ANGLE ANGLE_360
Definition eda_angle.h:478
bool FixGlbLinesPrimitives(const wxString &aFilePath)
Fix LINES primitives in a GLB file that have odd index counts.
Definition glb_utils.cpp:42
const wxChar *const traceKiCad2Step
Flag to enable KiCad2Step debug tracing.
std::string source
Handle(KICAD3D_INFO) KICAD3D_INFO
wxString LayerName(int aLayer)
Returns the default display name for a given layer.
Definition layer_id.cpp:31
bool IsFrontLayer(PCB_LAYER_ID aLayerId)
Layer classification: check if it's a front layer.
Definition layer_ids.h:847
bool IsBackLayer(PCB_LAYER_ID aLayerId)
Layer classification: check if it's a back layer.
Definition layer_ids.h:870
bool IsCopperLayer(int aLayerId)
Test whether a layer is a copper layer.
Definition layer_ids.h:744
bool IsInnerCopperLayer(int aLayerId)
Test whether a layer is an inner (In1_Cu to In30_Cu) copper layer.
Definition layer_ids.h:766
PCB_LAYER_ID
A quick note on layer IDs:
Definition layer_ids.h:56
@ B_Mask
Definition layer_ids.h:94
@ B_Cu
Definition layer_ids.h:61
@ F_Mask
Definition layer_ids.h:93
@ F_SilkS
Definition layer_ids.h:96
@ B_SilkS
Definition layer_ids.h:97
@ F_Cu
Definition layer_ids.h:60
This file contains miscellaneous commonly used macros and functions.
bool DuplicatePermissions(const wxString &aSrc, const wxString &aDest)
Duplicates the file security data from one file to another ensuring that they are the same between bo...
Definition unix/io.cpp:55
EDA_ANGLE abs(const EDA_ANGLE &aAngle)
Definition eda_angle.h:461
@ PTH
Plated through hole pad.
Definition padstack.h:99
@ CASTELLATED
a pad with a castellated through hole
Definition padstack.h:125
#define _HKI(x)
Definition page_info.cpp:40
EXTRUSION_MATERIAL
Definition pcb_3d_body.h:31
Plotting engines similar to ps (PostScript, Gerber, svg)
static float distance(const SFVEC2UI &a, const SFVEC2UI &b)
@ RPT_SEVERITY_WARNING
@ RPT_SEVERITY_ERROR
@ RPT_SEVERITY_DEBUG
static bool addSegment(VRML_LAYER &model, IDF_SEGMENT *seg, int icont, int iseg)
const std::vector< FAB_LAYER_COLOR > & GetStandardColors(BOARD_STACKUP_ITEM_TYPE aType)
wxString NotSpecifiedPrm()
#define KEY_PREPREG
#define KEY_CORE
MODEL3D_FORMAT_TYPE
@ FMT_STEP
@ FMT_IGES
@ FMT_IDF
@ FMT_WRZ
@ FMT_STEPZ
@ FMT_NONE
@ FMT_WRL
@ FMT_EMN
static bool rescaleShapes(const TDF_Label &theLabel, const gp_XYZ &aScale)
static bool colorFromStackup(BOARD_STACKUP_ITEM_TYPE aType, const wxString &aColorStr, COLOR4D &aColorOut)
static bool makeWireFromChain(BRepLib_MakeWire &aMkWire, const SHAPE_LINE_CHAIN &aChain, double aMergeOCCMaxDist, double aZposition, const VECTOR2D &aOrigin, REPORTER *aReporter)
#define APPROX_DBG(stmt)
static const char * occFailureMessage(const Standard_Failure &aFailure)
static constexpr double BOARD_OFFSET
static wxString formatBBox(const BOX2I &aBBox)
static bool fuseShapes(auto &aInputShapes, TopoDS_Shape &aOutShape, REPORTER *aReporter)
static TopoDS_Compound makeCompound(const auto &aInputShapes)
static std::vector< FAB_LAYER_COLOR > s_soldermaskColors
static TopoDS_Shape fuseShapesOrCompound(const NCollection_List< TopoDS_Shape > &aInputShapes, REPORTER *aReporter)
MODEL3D_FORMAT_TYPE fileType(const char *aFileName)
static VECTOR2D CircleCenterFrom3Points(const VECTOR2D &p1, const VECTOR2D &p2, const VECTOR2D &p3)
static SHAPE_LINE_CHAIN approximateLineChainWithArcs(const SHAPE_LINE_CHAIN &aSrc)
static bool prefixNames(const TDF_Label &aLabel, const TCollection_ExtendedString &aPrefix)
static constexpr double USER_ANGLE_PREC
static constexpr double USER_PREC
static TopoDS_Shape getOneShape(Handle(XCAFDoc_ShapeTool) aShapeTool)
static constexpr double OCC_MAX_DISTANCE_TO_MERGE_POINTS
Default distance between points to treat them as separate ones (mm) 0.001 mm or less is a reasonable ...
static constexpr double BOARD_THICKNESS_DEFAULT_MM
std::pair< std::string, TDF_Label > MODEL_DATUM
static constexpr double BOARD_THICKNESS_MIN_MM
#define CLOSE_STREAM(var)
#define OPEN_ISTREAM(var, name)
wxString UnescapeString(const wxString &aSource)
wxString GetISO8601CurrentDateTime()
KIBIS top(path, &reporter)
VECTOR2I center
int radius
VECTOR2I end
SHAPE_CIRCLE circle(c.m_circle_center, c.m_circle_radius)
#define M_PI
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
wxLogTrace helper definitions.
void RotatePoint(int *pX, int *pY, const EDA_ANGLE &aAngle)
Calculate the new point of coord coord pX, pY, for a rotation center 0, 0.
Definition trigo.cpp:227
double DEG2RAD(double deg)
Definition trigo.h:178
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708
VECTOR2< double > VECTOR2D
Definition vector2d.h:707
VECTOR3< double > VECTOR3D
Definition vector3.h:230
static PIECE polygon(std::vector< VIA_CROSS_SECTION_GEOMETRY::POINT > aPoints, bool aMixed=false)