30#include <wx/filename.h>
32#include <wx/sstream.h>
33#include <wx/stdpaths.h>
36#include <wx/zstream.h>
37#include <wx/wfstream.h>
38#include <wx/zipstrm.h>
39#include <wx/stdstream.h>
42#include <decompress.hpp>
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>
96#include <XCAFApp_Application.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>
109#include "KI_XCAFDoc_AssemblyGraph.hxx"
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>
129#include <BRepBndLib.hxx>
130#include <Bnd_BoundSortBox.hxx>
132#if OCC_VERSION_HEX >= 0x080000
133#include <NCollection_HArray1.hxx>
135#include <Bnd_HArray1OfBox.hxx>
138#include <GProp_GProps.hxx>
139#include <BRepGProp.hxx>
141#include <Geom_Curve.hxx>
142#include <Geom_TrimmedCurve.hxx>
147#include <GC_MakeArcOfCircle.hxx>
148#include <GC_MakeCircle.hxx>
150#include <RWGltf_CafWriter.hxx>
151#include <StlAPI_Writer.hxx>
153#if OCC_VERSION_HEX < 0x080000
154#include <TColStd_IndexedDataMapOfStringString.hxx>
159#if OCC_VERSION_HEX >= 0x070700
160#include <VrmlAPI_CafReader.hxx>
161#include <RWPly_CafWriter.hxx>
173#if OCC_VERSION_HEX >= 0x080000
174 return aFailure.what();
176 return aFailure.GetMessageString();
199 wxFileName lfile( wxString::FromUTF8Unchecked( aFileName ) );
201 if( !lfile.FileExists() )
204 wxString ext = lfile.GetExt().Lower();
206 if( ext == wxT(
"wrl" ) )
209 if( ext == wxT(
"wrz" ) )
212 if( ext == wxT(
"idf" ) )
215 if( ext == wxT(
"emn" ) )
218 if( ext == wxT(
"stpz" ) || ext == wxT(
"gz" ) )
232 const int max_line_count = 3;
234 for(
int ii = 0; ii < max_line_count; ii++ )
236 memset( iline, 0, 82 );
237 ifile.getline( iline, 82 );
243 if( !strncmp( iline,
"ISO-10303-21;", 13 ) )
249 std::string fstr = iline;
253 if( fstr.find(
"urn:oid:1.0.10303." ) != std::string::npos )
262 if( iline[72] ==
'S' && ( iline[80] == 0 || iline[80] == 13 || iline[80] == 10 ) )
269 if( strncmp( iline,
"/*", 2 ) != 0 )
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;
293 center.x = ( -bc * d.
y - cd * b.
y ) * det;
294 center.y = ( b.
x * cd + d.
x * bc ) * det;
301#define APPROX_DBG( stmt )
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;
314 static const double c_smallSize =
pcbIUScale.mmToIU( 0.1 );
315 static const double c_circleCloseGap =
pcbIUScale.mmToIU( 1.0 );
334 int last = c_last_none;
340 APPROX_DBG( std::cout << i <<
" " << aSrc.
CPoint( i ) <<
" " << ( i - 3 ) <<
" "
342 << ( i - 1 ) <<
" " <<
VECTOR2I( p2 ) << std::endl );
347 bool defective =
false;
353 defective |=
std::abs( d01 - d12 ) > ( std::max( d01, d12 ) * c_relLengthDeviation );
361 double a_diff = ( a01 - a12 ).Normalize180().AsDegrees();
362 defective |=
std::abs( a_diff ) < 0.1;
365 double maxAngleDiff = std::max( d01, d12 ) < c_smallSize ? 46.0 : 30.0;
366 defective |=
std::abs( a_diff ) >= maxAngleDiff;
377 for(
int j = i; j <= jEndIdx; j++ )
382 double rad_test = ( p_test -
center ).EuclideanNorm();
383 double d_tl = ( p_test - p_prev ).EuclideanNorm();
387 << int64_t( rad_test ) <<
" ref " << int64_t(
radius )
390 if( rad_dev > c_radiusDeviation )
393 <<
" Radius deviation too large: " << int64_t( rad_dev )
394 <<
" > " << c_radiusDeviation << std::endl );
399 double maxAngleDiff =
400 std::max( std::max( d01, d12 ), d_tl ) < c_smallSize ? 46.0 : 30.0;
402 double a_diff_test = ( a_prev - a_test ).Normalize180().AsDegrees();
403 if(
std::abs( a_diff_test ) >= maxAngleDiff )
405 APPROX_DBG( std::cout <<
" " << j <<
" Angles differ too much " << a_diff_test
410 if(
std::abs( d_tl - d01 ) > ( std::max( d_tl, d01 ) * c_relLengthDeviation ) )
412 APPROX_DBG( std::cout <<
" " << j <<
" Lengths differ too much " << d_tl
413 <<
"; " << d01 << std::endl );
423 if( last != c_last_none )
435 APPROX_DBG( std::cout <<
" Arc central angle too small: "
437 << c_minArcCentralAngle.
AsDegrees() << std::endl );
443 for(
int k = first + 1; last != c_last_none && k < last; k++ )
449 if( dist > c_radiusDeviation )
451 APPROX_DBG( std::cout <<
" Point " << k <<
" too far from arc: " << dist
452 <<
" > " << c_radiusDeviation << std::endl );
457 if( last != c_last_none )
462 int toRemove = last - ( aSrc.
PointCount() - 3 );
492 APPROX_DBG( std::cout <<
" Self-intersection check failed" << std::endl );
497 if( last == c_last_none )
514 if( iarc0 != -1 && iarc1 != -1 )
516 APPROX_DBG( std::cout <<
"Final arcs " << iarc0 <<
" " << iarc1 << std::endl );
526 if( ( p1 - p0 ).EuclideanNorm() < c_circleCloseGap )
544 if(
std::abs( ar0 - ar1 ) <= c_radiusDeviation
545 && ( ac0 - ac1 ).EuclideanNorm() <= c_arcCenterDeviation )
563 NCollection_Sequence<TDF_Label> theLabels;
564 aShapeTool->GetFreeShapes( theLabels );
568 if( theLabels.Length() == 1 )
569 return aShapeTool->GetShape( theLabels.Value( 1 ) );
571 TopoDS_Compound aCompound;
572 BRep_Builder aBuilder;
573 aBuilder.MakeCompound( aCompound );
575 for( NCollection_Sequence<TDF_Label>::Iterator anIt( theLabels ); anIt.More(); anIt.Next() )
577 TopoDS_Shape aFreeShape;
579 if( !aShapeTool->GetShape( anIt.Value(), aFreeShape ) )
582 aBuilder.Add( aCompound, aFreeShape );
585 if( aCompound.NbChildren() > 0 )
596 if( theLabel.IsNull() )
598 Message::SendFail(
"Null label." );
602 if(
std::abs( aScale.X() ) <= gp::Resolution() ||
std::abs( aScale.Y() ) <= gp::Resolution()
603 ||
std::abs( aScale.Z() ) <= gp::Resolution() )
605 Message::SendFail(
"Scale factor is too small." );
609 Handle( XCAFDoc_ShapeTool ) aShapeTool = XCAFDoc_DocumentTool::ShapeTool( theLabel );
611 if( aShapeTool.IsNull() )
613 Message::SendFail(
"Couldn't find XCAFDoc_ShapeTool attribute." );
617 Handle( KI_XCAFDoc_AssemblyGraph ) aG =
new KI_XCAFDoc_AssemblyGraph( theLabel );
621 Message::SendFail(
"Couldn't create assembly graph." );
625 bool anIsDone =
true;
629 aGTrsf.SetVectorialPart( gp_Mat( aScale.X(), 0, 0,
631 0, 0, aScale.Z() ) );
634 BRepBuilderAPI_GTransform aBRepTrsf( aGTrsf );
636 for(
int idx = 1; idx <= aG->NbNodes(); idx++ )
638 const KI_XCAFDoc_AssemblyGraph::NodeType aNodeType = aG->GetNodeType( idx );
640 if( ( aNodeType != KI_XCAFDoc_AssemblyGraph::NodeType_Part )
641 && ( aNodeType != KI_XCAFDoc_AssemblyGraph::NodeType_Occurrence ) )
646 const TDF_Label& aLabel = aG->GetNode( idx );
648 if( aNodeType == KI_XCAFDoc_AssemblyGraph::NodeType_Part )
650 const TopoDS_Shape aShape = aShapeTool->GetShape( aLabel );
651 aBRepTrsf.Perform( aShape,
true );
652 if( !aBRepTrsf.IsDone() )
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() );
662 TopoDS_Shape aScaledShape = aBRepTrsf.Shape();
663 aShapeTool->SetShape( aLabel, aScaledShape );
666 NCollection_Sequence<TDF_Label> aSubshapes;
667 aShapeTool->GetSubShapes( aLabel, aSubshapes );
668 for( NCollection_Sequence<TDF_Label>::Iterator anItSs( aSubshapes ); anItSs.More(); anItSs.Next() )
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 );
677 aLabel.ForgetAttribute( XCAFDoc_Area::GetID() );
678 aLabel.ForgetAttribute( XCAFDoc_Centroid::GetID() );
679 aLabel.ForgetAttribute( XCAFDoc_Volume::GetID() );
681 else if( aNodeType == KI_XCAFDoc_AssemblyGraph::NodeType_Occurrence )
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 );
695 aShapeTool->UpdateAssemblies();
703 BRepAlgoAPI_Fuse mkFuse;
704 NCollection_List<TopoDS_Shape> shapeArguments, shapeTools;
706 for(
const TopoDS_Shape& sh : aInputShapes )
711 if( shapeArguments.IsEmpty() )
712 shapeArguments.Append( sh );
714 shapeTools.Append( sh );
721 mkFuse.SetNonDestructive(
true );
722 mkFuse.SetRunParallel(
true );
723 mkFuse.SetToFillHistory(
false );
724 mkFuse.SetArguments( shapeArguments );
725 mkFuse.SetTools( shapeTools );
728 catch(
const std::bad_alloc& )
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." ),
735 catch(
const Standard_Failure& e )
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." ),
745 if( mkFuse.HasErrors() || mkFuse.HasWarnings() )
747 aReporter->
Report(
_(
"Problems encountered while fusing shapes. This operation is "
748 "memory-intensive; insufficient memory may cause failures." ),
751 if( mkFuse.HasErrors() )
753 wxString msg =
_(
"Errors:\n" );
754 wxStringOutputStream os_stream( &msg );
755 wxStdOutputStream out( os_stream );
757 mkFuse.DumpErrors( out );
761 if( mkFuse.HasWarnings() )
763 wxString msg =
_(
"Warnings:\n" );
764 wxStringOutputStream os_stream( &msg );
765 wxStdOutputStream out( os_stream );
767 mkFuse.DumpWarnings( out );
772 if( mkFuse.IsDone() )
774 TopoDS_Shape fusedShape = mkFuse.Shape();
778 ShapeUpgrade_UnifySameDomain unify( fusedShape,
true,
true,
false );
779 unify.SetSafeInputMode(
true );
780 unify.History() =
nullptr;
783 TopoDS_Shape unifiedShapes = unify.Shape();
785 if( unifiedShapes.IsNull() )
787 aReporter->
Report(
_(
"ShapeUpgrade_UnifySameDomain produced a null shape." ),
792 aOutShape = unifiedShapes;
796 catch(
const std::bad_alloc& )
798 aReporter->
Report(
_(
"Out of memory while unifying shape domains. Consider disabling "
799 "shape fusing or reducing the number of objects." ),
803 catch(
const Standard_Failure& e )
805 aReporter->
Report( wxString::Format(
_(
"OpenCASCADE error while unifying shapes: %s" ),
818 TopoDS_Compound compound;
819 BRep_Builder builder;
820 builder.MakeCompound( compound );
822 for(
const TopoDS_Shape& shape : aInputShapes )
823 builder.Add( compound, shape );
832 TopoDS_Shape outShape;
834 if( aInputShapes.Size() == 1 )
835 return aInputShapes.First();
837 if(
fuseShapes( aInputShapes, outShape, aReporter ) )
846 const TCollection_ExtendedString& aPrefix )
848 Handle( KI_XCAFDoc_AssemblyGraph ) aG =
new KI_XCAFDoc_AssemblyGraph( aLabel );
852 Message::SendFail(
"Couldn't create assembly graph." );
856 bool anIsDone =
true;
858 for(
int idx = 1; idx <= aG->NbNodes(); idx++ )
860 const TDF_Label& lbl = aG->GetNode( idx );
861 Handle( TDataStd_Name ) nameHandle;
863 if( lbl.FindAttribute( TDataStd_Name::GetID(), nameHandle ) )
865 TCollection_ExtendedString
name;
869 name += nameHandle->Get();
872 TDataStd_Name::Set( lbl,
name );
876 TDataStd_Name::Set( lbl, aPrefix );
888 m_app = XCAFApp_Application::GetApplication();
889 m_app->NewDocument(
"MDTV-XCAF", m_doc );
890 m_assy = XCAFDoc_DocumentTool::ShapeTool( m_doc->Main() );
908 if( m_doc->CanClose() == CDM_CCS_OK )
916 const double c_padExtraThickness = 0.005;
918 std::vector<TopoDS_Shape> padShapes;
932 double Zpos, thickness;
938 if( pcb_layer ==
F_Cu )
939 thickness += c_padExtraThickness;
940 else if( pcb_layer ==
B_Cu )
941 thickness -= c_padExtraThickness;
944 TopoDS_Shape testShape;
958 if( testShape.IsNull() )
960 std::vector<TopoDS_Shape> testShapes;
964 if( testShapes.size() > 0 )
965 testShape = testShapes.front();
970 if( pcb_layer ==
F_Cu || pcb_layer ==
B_Cu )
976 if( pcb_layer ==
F_Cu )
978 else if( pcb_layer ==
B_Cu )
994 double f_pos, f_thickness;
995 double b_pos, b_thickness;
1002 f_thickness += c_padExtraThickness;
1003 b_thickness -= c_padExtraThickness;
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;
1010 TopoDS_Shape plating;
1018 hole_height, bottom, aOrigin ) )
1020 padShapes.push_back( plating );
1034 if( seg_hole->GetSeg().A == seg_hole->GetSeg().B )
1051 padShapes.push_back( plating );
1063 if( !padShapes.empty() )
1068 NCollection_List<TopoDS_Shape> padShapesList;
1070 for(
const TopoDS_Shape& shape : padShapes )
1071 padShapesList.Append( shape );
1077 for(
const TopoDS_Shape& shape : padShapes )
1088 const VECTOR2D& aOrigin,
bool aCutCopper,
bool aCutBody )
1090 double margin = 0.001;
1098 double f_pos, f_thickness;
1099 double 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 );
1105 double holeZsize = (
top - bottom ) + ( margin * 2 );
1107 double boardDrill = aShape.
GetWidth();
1108 double copperDrill = boardDrill - aPlatingThickness * 2;
1110 TopoDS_Shape copperHole, boardHole;
1115 holeZsize, bottom - margin, aOrigin ) )
1128 holeZsize, bottom - margin, aOrigin ) )
1144 const wxString& aNetname )
1146 double f_pos, f_thickness;
1147 double 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 );
1153 TopoDS_Shape plating;
1156 (
top - bottom ), bottom, aOrigin ) )
1178 double margin = 0.001;
1182 double copperMargin = 0.5;
1184 double start_pos, start_thickness;
1185 double end_pos, end_thickness;
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 } );
1196 if( aLayerStart ==
F_Cu || aLayerEnd ==
F_Cu )
1197 top += copperMargin;
1198 if( aLayerStart ==
B_Cu || aLayerEnd ==
B_Cu )
1199 bottom -= copperMargin;
1201 double holeZsize = (
top - bottom ) + ( margin * 2 );
1202 double holeZpos = bottom - margin;
1204 double backdrillDiameter = aShape.
GetWidth();
1206 TopoDS_Shape backdrillHole;
1210 backdrillDiameter, holeZsize, holeZpos, aOrigin ) )
1227 bool aFrontSide,
const VECTOR2D& aOrigin )
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 );
1233 if( aDiameter <= 0 || aDepth <= 0 )
1235 wxLogTrace(
traceKiCad2Step, wxT(
"AddCounterbore: REJECTED - invalid diameter=%d or depth=%d" ),
1236 aDiameter, aDepth );
1240 double margin = 0.001;
1243 double copperMargin = 0.5;
1246 double boardZpos, boardThickness;
1250 double f_pos, f_thickness, b_pos, b_thickness;
1257 double topOuterSurface = std::max( f_pos, f_pos + f_thickness );
1258 double bottomOuterSurface = std::min( b_pos, b_pos + b_thickness );
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 );
1264 double diameter_mm =
pcbIUScale.IUTomm( aDiameter );
1265 double depth_mm =
pcbIUScale.IUTomm( aDepth );
1266 double radius_mm = diameter_mm / 2.0;
1268 wxLogTrace(
traceKiCad2Step, wxT(
"AddCounterbore: diameter_mm=%f depth_mm=%f radius_mm=%f" ),
1269 diameter_mm, depth_mm, radius_mm );
1273 double cylinderZpos;
1274 double cylinderHeight;
1280 cylinderZpos = topOuterSurface - depth_mm - margin;
1281 cylinderHeight = depth_mm + copperMargin + 2 * margin;
1287 cylinderZpos = bottomOuterSurface - copperMargin - margin;
1288 cylinderHeight = depth_mm + copperMargin + 2 * margin;
1292 double posX_mm =
pcbIUScale.IUTomm( aPosition.
x - aOrigin.
x );
1293 double posY_mm = -
pcbIUScale.IUTomm( aPosition.
y - aOrigin.
y );
1295 wxLogTrace(
traceKiCad2Step, wxT(
"AddCounterbore: posX_mm=%f posY_mm=%f cylinderZpos=%f cylinderHeight=%f" ),
1296 posX_mm, posY_mm, cylinderZpos, cylinderHeight );
1302 gp_Ax2 axis( gp_Pnt( posX_mm, posY_mm, cylinderZpos ), gp::DZ() );
1304 TopoDS_Shape cylinder = BRepPrimAPI_MakeCylinder( axis, radius_mm, cylinderHeight );
1306 if( cylinder.IsNull() )
1308 wxLogTrace(
traceKiCad2Step, wxT(
"AddCounterbore: FAILED - cylinder shape is null" ) );
1309 m_reporter->Report(
_(
"Failed to create counterbore cylinder shape" ),
1318 wxLogTrace(
traceKiCad2Step, wxT(
"AddCounterbore: SUCCESS - added cylinder. boardCutouts=%zu copperCutouts=%zu" ),
1321 catch(
const Standard_Failure& e )
1324 m_reporter->Report( wxString::Format(
_(
"OCC exception creating counterbore: %s" ),
1335 int aAngle,
bool aFrontSide,
const VECTOR2D& aOrigin )
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 );
1343 if( aDiameter <= 0 || aAngle <= 0 )
1345 wxLogTrace(
traceKiCad2Step, wxT(
"AddCountersink: REJECTED - invalid diameter=%d or angle=%d" ),
1346 aDiameter, aAngle );
1350 double margin = 0.001;
1353 double copperMargin = 0.5;
1356 double boardZpos, boardThickness;
1360 double f_pos, f_thickness, b_pos, b_thickness;
1365 double topOuterSurface = std::max( f_pos, f_pos + f_thickness );
1366 double bottomOuterSurface = std::min( b_pos, b_pos + b_thickness );
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 );
1372 double diameter_mm =
pcbIUScale.IUTomm( aDiameter );
1373 double radius_mm = diameter_mm / 2.0;
1377 double halfAngleRad = ( aAngle / 10.0 ) *
M_PI / 180.0 / 2.0;
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 );
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 );
1406 double bottomRadius_mm = radius_mm - depth_mm * tan( halfAngleRad );
1408 wxLogTrace(
traceKiCad2Step, wxT(
"AddCountersink: bottomRadius_mm=%f (before clamp), tan(halfAngle)=%f" ),
1409 bottomRadius_mm, tan( halfAngleRad ) );
1411 if( bottomRadius_mm < 0 )
1412 bottomRadius_mm = 0;
1417 double coneHeight = depth_mm + copperMargin + margin;
1421 double posX_mm =
pcbIUScale.IUTomm( aPosition.
x - aOrigin.
x );
1422 double posY_mm = -
pcbIUScale.IUTomm( aPosition.
y - aOrigin.
y );
1433 coneZpos = topOuterSurface - depth_mm - margin;
1434 r1 = bottomRadius_mm;
1436 r2 = radius_mm + ( copperMargin + margin ) * tan( halfAngleRad );
1438 wxLogTrace(
traceKiCad2Step, wxT(
"AddCountersink: FRONT - coneZpos=%f r1=%f r2=%f coneHeight=%f" ),
1439 coneZpos, r1, r2, coneHeight );
1441 gp_Ax2 axis( gp_Pnt( posX_mm, posY_mm, coneZpos ), gp::DZ() );
1442 cone = BRepPrimAPI_MakeCone( axis, r1, r2, coneHeight );
1449 coneZpos = bottomOuterSurface - copperMargin - margin;
1451 r1 = radius_mm + ( copperMargin + margin ) * tan( halfAngleRad );
1452 r2 = bottomRadius_mm;
1454 wxLogTrace(
traceKiCad2Step, wxT(
"AddCountersink: BACK - coneZpos=%f r1=%f r2=%f coneHeight=%f" ),
1455 coneZpos, r1, r2, coneHeight );
1457 gp_Ax2 axis( gp_Pnt( posX_mm, posY_mm, coneZpos ), gp::DZ() );
1458 cone = BRepPrimAPI_MakeCone( axis, r1, r2, coneHeight );
1463 wxLogTrace(
traceKiCad2Step, wxT(
"AddCountersink: FAILED - cone shape is null" ) );
1464 m_reporter->Report(
_(
"Failed to create countersink cone shape" ),
1473 wxLogTrace(
traceKiCad2Step, wxT(
"AddCountersink: SUCCESS - added cone. boardCutouts=%zu copperCutouts=%zu" ),
1476 catch(
const Standard_Failure& e )
1479 m_reporter->Report( wxString::Format(
_(
"OCC exception creating countersink: %s" ),
1490 int aAngle,
bool aFrontSide )
1492 std::map<PCB_LAYER_ID, int> knockouts;
1495 double f_pos, f_thickness, b_pos, b_thickness;
1499 double topOuterSurface = std::max( f_pos, f_pos + f_thickness );
1500 double bottomOuterSurface = std::min( b_pos, b_pos + b_thickness );
1503 double diameter_mm =
pcbIUScale.IUTomm( aDiameter );
1504 double radius_mm = diameter_mm / 2.0;
1508 double halfAngleRad = 0.0;
1513 halfAngleRad = ( aAngle / 10.0 ) *
M_PI / 180.0 / 2.0;
1517 depth_mm = radius_mm / tan( halfAngleRad );
1528 double featureTop, featureBottom;
1532 featureTop = topOuterSurface;
1533 featureBottom = topOuterSurface - depth_mm;
1537 featureBottom = bottomOuterSurface;
1538 featureTop = bottomOuterSurface + depth_mm;
1541 wxLogTrace(
traceKiCad2Step, wxT(
"GetCopperLayerKnockouts: featureTop=%f featureBottom=%f depth_mm=%f frontSide=%d" ),
1542 featureTop, featureBottom, depth_mm, aFrontSide ? 1 : 0 );
1551 double layerZ, layerThickness;
1555 double layerTop = std::max( layerZ, layerZ + layerThickness );
1556 double layerBottom = std::min( layerZ, layerZ + layerThickness );
1560 bool layerInRange = ( layerTop >= featureBottom && layerBottom <= featureTop );
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 );
1568 int knockoutDiameter;
1574 double layerSurfaceZ;
1578 layerSurfaceZ = layerTop;
1583 layerSurfaceZ = layerBottom;
1587 double distanceFromSurface;
1589 distanceFromSurface = topOuterSurface - layerSurfaceZ;
1591 distanceFromSurface = layerSurfaceZ - bottomOuterSurface;
1594 double radiusAtLayer_mm = radius_mm - distanceFromSurface * tan( halfAngleRad );
1596 if( radiusAtLayer_mm <= 0 )
1598 wxLogTrace(
traceKiCad2Step, wxT(
"GetCopperLayerKnockouts: layer %d - countersink tapers to point before this layer" ),
1599 static_cast<int>( layer ) );
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 );
1610 knockoutDiameter = aDiameter;
1611 wxLogTrace(
traceKiCad2Step, wxT(
"GetCopperLayerKnockouts: layer %d (counterbore) - diameter=%d" ),
1612 static_cast<int>( layer ), knockoutDiameter );
1615 knockouts[layer] = knockoutDiameter;
1623 double& aThickness )
1626 static const double c_silkscreenAboveCopper = 0.04;
1627 static const double c_soldermaskAboveCopper = 0.015;
1635 double f_pos, f_thickness;
1637 double top = std::max( f_pos, f_pos + f_thickness );
1640 aZPos =
top + c_silkscreenAboveCopper;
1642 aZPos =
top + c_soldermaskAboveCopper;
1648 double b_pos, b_thickness;
1650 double bottom = std::min( b_pos, b_pos + b_thickness );
1653 aZPos = bottom - c_silkscreenAboveCopper;
1655 aZPos = bottom - c_soldermaskAboveCopper;
1663 double& aThickness )
1667 bool wasPrepreg =
false;
1669 const std::vector<BOARD_STACKUP_ITEM*>& materials =
m_stackup.GetList();
1672 for(
auto it = materials.rbegin(); it != materials.rend(); ++it )
1678 if( aLayer ==
B_Cu )
1727 if( !item->IsEnabled() )
1732 for(
int sublayer = 0; sublayer < item->GetSublayersCount(); sublayer++ )
1733 thickness += item->GetThickness( sublayer );
1738 thickness += item->GetThickness();
1748 double f_pos, f_thickness;
1749 double 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 );
1755 aThickness = (
top - bottom );
1769 m_reporter->Report( wxString::Format(
_(
"Board stackup does not define a board thickness; "
1770 "exporting a %.3f mm board body." ),
1775 wxASSERT( aZPos == 0.0 );
1781 const wxString& aRefDes )
1783 double f_pos, f_thickness;
1784 double b_pos, b_thickness;
1788 double boardSurfaceZ;
1791 boardSurfaceZ = std::max( f_pos, f_pos + f_thickness );
1793 boardSurfaceZ = std::min( b_pos, b_pos + b_thickness );
1795 double bodyThickness = aHeight - aStandoff;
1799 zBot = boardSurfaceZ + aStandoff;
1801 zBot = boardSurfaceZ - aHeight;
1809 double aStandoff,
const VECTOR2D& aOrigin )
1811 if( aStandoff <= 0.0 )
1827 double f_pos, f_thickness;
1828 double b_pos, b_thickness;
1832 double boardTopZ = std::max( f_pos, f_pos + f_thickness );
1833 double boardBotZ = std::min( b_pos, b_pos + b_thickness );
1835 static const double c_protrusion = 1.0;
1837 double zOffset = aBody ? aBody->
m_offset.
z : 0.0;
1839 double pinZBot, pinHeight;
1843 pinZBot = boardBotZ - c_protrusion + zOffset;
1844 pinHeight = ( boardTopZ + aStandoff ) - pinZBot;
1848 double pinZTop = boardTopZ + c_protrusion - zOffset;
1849 pinZBot = boardBotZ - aStandoff;
1850 pinHeight = pinZTop - pinZBot;
1856 bool success =
true;
1871 const VECTOR2D& aOrigin,
const wxString& aNetname )
1873 bool success =
true;
1881 double z_pos, thickness;
1884 std::vector<TopoDS_Shape>* targetVec =
nullptr;
1892 else if( aLayer ==
F_Mask )
1899 m_reporter->Report( wxString::Format(
_(
"Could not add shape (%d points) to copper layer %s." ),
1912 const std::vector<wxString>& aAltFilenames,
1913 const wxString& aRefDes,
bool aBottom,
VECTOR2D aPosition,
1915 VECTOR3D aScale,
bool aSubstituteModels )
1917 if( aFileName.empty() )
1919 m_reporter->Report( wxString::Format(
_(
"No model defined for %s." ), aRefDes ),
1928 wxString errorMessage;
1930 if( !
getModelLabel( aBaseName, aFileName, aAltFilenames, aScale, lmodel, aSubstituteModels,
1933 if( errorMessage.IsEmpty() )
1934 errorMessage.Printf(
_(
"No model for filename '%s'." ), aFileName );
1941 TopLoc_Location toploc;
1943 if( !
getModelLocation( aBottom, aPosition, aRotation, aOffset, aOrientation, toploc ) )
1946 wxString::Format(
_(
"No location data for filename '%s'." ), aFileName ),
1952 TDF_Label llabel = m_assy->AddComponent(
m_assy_label, lmodel, toploc );
1954 if( llabel.IsNull() )
1957 wxString::Format(
_(
"Could not add component with filename '%s'." ), aFileName ),
1965 TCollection_ExtendedString refdes( aRefDes.utf8_str() );
1966 TDataStd_Name::Set( llabel, refdes );
1977 m_assy->UpdateAssemblies();
2049 const VECTOR2D& aEndPoint,
double aWidth,
double aThickness,
2050 double aZposition,
const VECTOR2D& aOrigin )
2057 double len = ( aEndPoint - aStartPoint ).EuclideanNorm();
2058 double h_width = aWidth/2.0;
2060 coords[0] =
VECTOR2D{ 0.0, h_width };
2063 coords[1] =
VECTOR2D{ len, h_width };
2066 coords[2] =
VECTOR2D{ len + h_width, 0.0 };
2069 coords[3] =
VECTOR2D{ len, -h_width };
2072 coords[4] =
VECTOR2D{ 0, -h_width };
2075 coords[5] =
VECTOR2D{ -h_width, 0.0 };
2078 EDA_ANGLE seg_angle( aEndPoint - aStartPoint );
2080 for(
int ii = 0; ii < 6; ii++ )
2083 coords[ii] += aStartPoint;
2088 gp_Pnt coords3D[ 6 ];
2090 for(
int ii = 0; ii < 6; ii++ )
2092 coords3D[ii] = gp_Pnt(
pcbIUScale.IUTomm( coords[ii].
x - aOrigin.
x ),
2093 -
pcbIUScale.IUTomm( coords[ii].
y - aOrigin.
y ), aZposition );
2097 BRepBuilderAPI_MakeWire wire;
2098 bool success =
true;
2110 Handle( Geom_Circle )
circle = GC_MakeCircle( coords3D[1],
2115 edge = BRepBuilderAPI_MakeEdge(
circle );
2120 edge = BRepBuilderAPI_MakeEdge( coords3D[0], coords3D[1] );
2123 Handle( Geom_TrimmedCurve ) arcOfCircle =
2124 GC_MakeArcOfCircle( coords3D[1],
2128 edge = BRepBuilderAPI_MakeEdge( arcOfCircle );
2131 edge = BRepBuilderAPI_MakeEdge( coords3D[3], coords3D[4] );
2134 Handle( Geom_TrimmedCurve ) arcOfCircle2 =
2135 GC_MakeArcOfCircle( coords3D[4],
2139 edge = BRepBuilderAPI_MakeEdge( arcOfCircle2 );
2143 catch(
const Standard_Failure& e )
2145 m_reporter->Report( wxString::Format(
_(
"OCC exception building shape segment: %s" ),
2151 BRepBuilderAPI_MakeFace face;
2155 gp_Pln plane( coords3D[0], gp::DZ() );
2156 face = BRepBuilderAPI_MakeFace( plane, wire );
2158 catch(
const Standard_Failure& e )
2160 m_reporter->Report( wxString::Format(
_(
"OCC exception building face: %s" ),
2166 if( aThickness != 0.0 )
2168 aShape = BRepPrimAPI_MakePrism( face, gp_Vec( 0, 0, aThickness ) );
2170 if( aShape.IsNull() )
2172 m_reporter->Report(
_(
"Failed to create a prismatic shape" ),
2189 double aZposition,
const VECTOR2D& aOrigin )
2191 std::vector<TopoDS_Shape> testShapes;
2194 aHeight, aZposition, aOrigin );
2196 if( testShapes.size() > 0 )
2197 aShape = testShapes.front();
2220 double aMergeOCCMaxDist,
double aZposition,
const VECTOR2D& aOrigin,
2224 [&](
const VECTOR2D& aKiCoords ) -> gp_Pnt
2226 return gp_Pnt(
pcbIUScale.IUTomm( aKiCoords.x - aOrigin.
x ),
2227 -
pcbIUScale.IUTomm( aKiCoords.y - aOrigin.
y ), aZposition );
2237 gp_Pnt start = toPoint( aPt0 );
2238 gp_Pnt
end = toPoint( aPt1 );
2240 BRepBuilderAPI_MakeEdge mkEdge( start,
end );
2242 if( !mkEdge.IsDone() || mkEdge.Edge().IsNull() )
2244 aReporter->
Report( wxString::Format(
_(
"Failed to make segment edge (%d %d) -> (%d %d), "
2252 aMkWire.Add( mkEdge.Edge() );
2254 if( aMkWire.Error() != BRepLib_WireDone )
2256 aReporter->
Report( wxString::Format(
_(
"Failed to add segment edge (%d %d) -> (%d %d)" ),
2270 Handle( Geom_Curve ) curve;
2272 if( aArc.GetCentralAngle() ==
ANGLE_360 )
2274 gp_Ax2 axis = gp::XOY();
2275 axis.SetLocation( toPoint( aArc.GetCenter() ) );
2277 curve = GC_MakeCircle( axis,
pcbIUScale.IUTomm( aArc.GetRadius() ) ).Value();
2281 curve = GC_MakeArcOfCircle( toPoint( aPt0 ), toPoint( aArc.GetArcMid() ),
2282 toPoint( aArc.GetP1() ) ).Value();
2285 if( curve.IsNull() )
2288 aMkWire.Add( BRepBuilderAPI_MakeEdge( curve ) );
2290 if( !aMkWire.IsDone() )
2292 aReporter->
Report( wxString::Format(
_(
"Failed to add arc curve from (%d %d), arc p0 "
2293 "(%d %d), mid (%d %d), p1 (%d %d)" ),
2295 aArc.GetP0().x, aArc.GetP0().y,
2296 aArc.GetArcMid().x, aArc.GetArcMid().y,
2297 aArc.GetP1().x, aArc.GetP1().y ),
2307 bool isFirstShape =
true;
2320 if( nextShape != -1 )
2326 lastPt = aChain.
CPoint( i );
2336 firstPt = currentArc.
GetP0();
2341 lastPt = currentArc.
GetP0();
2343 if( addArc( lastPt, currentArc ) )
2344 lastPt = currentArc.
GetP1();
2363 isFirstShape =
false;
2366 if( lastPt != firstPt && !
addSegment( lastPt, firstPt ) )
2368 aReporter->
Report( wxString::Format(
_(
"Failed to close wire at %d, %d -> %d, %d **" ),
2370 firstPt.
x, firstPt.
y ),
2376 catch(
const Standard_Failure& e )
2378 aReporter->
Report( wxString::Format(
_(
"OCC exception creating wire: %s" ),
2389 bool aConvertToArcs,
double aThickness,
double aZposition,
2397 if( aConvertToArcs )
2401 for(
size_t polyId = 0; polyId < approximated.
CPolygons().size(); polyId++ )
2405 for(
size_t contId = 0; contId <
polygon.size(); contId++ )
2409 fallbackPoly = workingPoly;
2410 workingPoly = approximated;
2429 auto toPoint = [&](
const VECTOR2D& aKiCoords ) -> gp_Pnt
2431 return gp_Pnt(
pcbIUScale.IUTomm( aKiCoords.x - aOrigin.
x ),
2432 -
pcbIUScale.IUTomm( aKiCoords.y - aOrigin.
y ), aZposition );
2436 gp_Pln basePlane( gp_Pnt( 0.0, 0.0, aZposition ),
2437 std::signbit( aThickness ) ? -gp::DZ() : gp::DZ() );
2439 for(
size_t polyId = 0; polyId < workingPoly.
CPolygons().size(); polyId++ )
2443 auto tryMakeWire = [
this, &aZposition,
2444 &aOrigin](
const SHAPE_LINE_CHAIN& aContour,
bool aAllowRetry ) -> TopoDS_Wire
2447 BRepLib_MakeWire mkWire;
2451 if( mkWire.IsDone() )
2453 wire = mkWire.Wire();
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() ),
2467 if( !wire.IsNull() )
2469 BRepAlgoAPI_Check check( wire,
false,
true );
2471 if( !check.IsValid() )
2473 m_reporter->Report( wxString::Format(
_(
"Wire self-interference check failed\n"
2474 "z: %g; bounding box: %s" ),
2486 BRepBuilderAPI_MakeFace mkFace;
2488 for(
size_t contId = 0; contId <
polygon.size(); contId++ )
2494 bool allow_retry = aConvertToArcs ? true :
false;
2496 TopoDS_Wire wire = tryMakeWire(
polygon[contId], allow_retry );
2498 if( aConvertToArcs && wire.IsNull() )
2500 m_reporter->Report( wxString::Format(
_(
"Using non-simplified polygon." ) ),
2504 allow_retry =
false;
2505 wire = tryMakeWire( fallbackPoly.
CPolygon( polyId )[contId], allow_retry );
2510 if( !wire.IsNull() )
2512 if( basePlane.Axis().Direction().Z() < 0 )
2515 mkFace = BRepBuilderAPI_MakeFace( basePlane, wire );
2519 m_reporter->Report( wxString::Format( wxT(
"** Outline skipped **\n"
2520 "z: %g; bounding box: %s" ),
2529 if( !wire.IsNull() )
2531 if( basePlane.Axis().Direction().Z() > 0 )
2538 m_reporter->Report( wxString::Format( wxT(
"** Hole skipped **\n"
2539 "z: %g; bounding box: %s" ),
2546 catch(
const Standard_Failure& e )
2548 m_reporter->Report( wxString::Format(
_(
"OCC exception creating contour %d: %s" ),
2549 static_cast<int>( contId ),
2556 if( mkFace.IsDone() )
2558 TopoDS_Shape faceShape = mkFace.Shape();
2560 if( aThickness != 0.0 )
2562 TopoDS_Shape prism = BRepPrimAPI_MakePrism( faceShape, gp_Vec( 0, 0, aThickness ) );
2563 aShapes.push_back( prism );
2565 if( prism.IsNull() )
2573 aShapes.push_back( faceShape );
2589 {
_HKI(
"Green" ), wxColor( 20, 51, 36 ) },
2590 {
_HKI(
"Red" ), wxColor( 181, 19, 21 ) },
2591 {
_HKI(
"Blue" ), wxColor( 2, 59, 162 ) },
2592 {
_HKI(
"Purple" ), wxColor( 32, 2, 53 ) },
2593 {
_HKI(
"Black" ), wxColor( 11, 11, 11 ) },
2594 {
_HKI(
"White" ), wxColor( 245, 245, 245 ) },
2595 {
_HKI(
"Yellow" ), wxColor( 194, 195, 0 ) },
2596 {
_HKI(
"User defined" ), wxColor( 128, 128, 128 ) }
2606 if( aColorStr.StartsWith( wxT(
"#" ) ) )
2608 aColorOut =
COLOR4D( aColorStr );
2613 const std::vector<FAB_LAYER_COLOR>& colors =
2620 if( fabColor.GetName() == aColorStr )
2622 aColorOut = fabColor.GetColor( aType );
2644 Handle( XCAFDoc_VisMaterialTool ) visMatTool = XCAFDoc_DocumentTool::VisMaterialTool( m_doc->Main() );
2649 m_reporter->Report( wxString::Format( wxT(
"Build board outlines (%d outlines) with %d points." ),
2654 double boardThickness;
2674 for(
size_t contId = 0; contId <
polygon.size(); contId++ )
2678 polyset.
Append( contour );
2685 m_reporter->Report(
_(
"OCC error creating main outline." ),
2694 m_reporter->Report(
_(
"OCC error creating hole in main outline." ),
2706 BRepBndLib::Add( brdShape, brdBndBox );
2709 m_reporter->Report( wxString::Format( wxT(
"Build board cutouts and holes (%d hole(s))." ),
2714 [&brdBndBox]( std::vector<TopoDS_Shape>& input, Bnd_BoundSortBox& bsbHoles,
2715 std::vector<Bnd_Box>& holeBoxes )
2719 Bnd_Box brdWithHolesBndBox = brdBndBox;
2721#if OCC_VERSION_HEX >= 0x080000
2722 Handle( NCollection_HArray1<Bnd_Box> ) holeBoxSet =
2723 new NCollection_HArray1<Bnd_Box>( 0, input.size() - 1 );
2725 Handle( Bnd_HArray1OfBox ) holeBoxSet =
new Bnd_HArray1OfBox( 0, input.size() - 1 );
2727 holeBoxes.resize( input.size() );
2729 for(
size_t i = 0; i < input.size(); i++ )
2732 BRepBndLib::Add( input[i], bbox );
2733 brdWithHolesBndBox.Add( bbox );
2734 ( *holeBoxSet )[i] = bbox;
2735 holeBoxes[i] = bbox;
2738 bsbHoles.Initialize( brdWithHolesBndBox, holeBoxSet );
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 )
2746 m_reporter->Report( wxString::Format(
_(
"Subtracting holes for %s" ), aWhat ),
2749 for(
auto& [netname, vec] : aShapesMap )
2757 auto subtractLoopFn = [&](
const int shapeId )
2759 TopoDS_Shape& shape = vec[shapeId];
2762 BRepBndLib::Add( shape, shapeBbox );
2764 NCollection_List<TopoDS_Shape> holelist;
2767 std::unique_lock lock( mutex );
2769 const NCollection_List<int>& indices = aBSBHoles.Compare( shapeBbox );
2771 for(
const int&
index : indices )
2772 holelist.Append( aHolesList[
index] );
2778 if( holelist.IsEmpty() )
2780 for(
size_t i = 0; i < aHoleBoxes.size(); i++ )
2782 if( !shapeBbox.IsOut( aHoleBoxes[i] ) )
2783 holelist.Append( aHolesList[i] );
2788 if( holelist.IsEmpty() )
2791 NCollection_List<TopoDS_Shape> cutArgs;
2792 cutArgs.Append( shape );
2794 BRepAlgoAPI_Cut
cut;
2798 cut.SetNonDestructive(
true );
2799 cut.SetRunParallel(
false );
2800 cut.SetToFillHistory(
false );
2802 cut.SetArguments( cutArgs );
2803 cut.SetTools( holelist );
2806 if(
cut.HasErrors() ||
cut.HasWarnings() )
2808 m_reporter->Report( wxString::Format(
_(
"** Got problems while cutting "
2817 std::unique_lock lock( mutex );
2821 if(
cut.HasErrors() )
2823 wxString msg =
_(
"Errors:\n" );
2824 wxStringOutputStream os_stream( &msg );
2825 wxStdOutputStream out( os_stream );
2827 cut.DumpErrors( out );
2831 if(
cut.HasWarnings() )
2833 wxString msg =
_(
"Warnings:\n" );
2834 wxStringOutputStream os_stream( &msg );
2835 wxStdOutputStream out( os_stream );
2837 cut.DumpWarnings( out );
2842 shape =
cut.Shape();
2848 BS::multi_future<void> cutFutures;
2852 cutFutures =
tp.submit_loop( 0, vec.size(), subtractLoopFn );
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 )
2870 std::map<wxString, std::vector<TopoDS_Shape>> aShapesMap{ { wxEmptyString, aShapesList } };
2872 subtractShapesMap( aWhat, aShapesMap, aHolesList, aBSBHoles, aHoleBoxes );
2873 aShapesList = aShapesMap[wxEmptyString];
2879 Bnd_BoundSortBox bsbHoles;
2880 std::vector<Bnd_Box> holeBoxes;
2888 Bnd_BoundSortBox bsbHoles;
2889 std::vector<Bnd_Box> holeBoxes;
2898 std::map<wxString, NCollection_List<TopoDS_Shape>> shapesToFuseMap;
2900 auto addShapes = [&shapesToFuseMap](
const wxString& aNetname,
2901 const std::vector<TopoDS_Shape>& aShapes )
2903 for(
const TopoDS_Shape& shape : aShapes )
2904 shapesToFuseMap[aNetname].Append( shape );
2908 addShapes( netname, shapes );
2911 addShapes( netname, shapes );
2914 addShapes( netname, shapes );
2922 std::vector<std::pair<wxString, const NCollection_List<TopoDS_Shape>*>> fuseWork;
2923 fuseWork.reserve( shapesToFuseMap.size() );
2925 for(
const auto& [netname, toFuse] : shapesToFuseMap )
2926 fuseWork.emplace_back( netname, &toFuse );
2929 BS::multi_future<void> mf;
2930 mf.reserve( fuseWork.size() );
2936 for(
const auto& work : fuseWork )
2938 const wxString netname = work.first;
2939 const NCollection_List<TopoDS_Shape>* toFuse = work.second;
2941 mf.push_back(
tp.submit_task(
2942 [
this, &mutex, netname, toFuse]()
2944 TopoDS_Shape fusedShape = fuseShapesOrCompound( *toFuse, m_reporter );
2946 if( !fusedShape.IsNull() )
2948 std::unique_lock lock( mutex );
2950 m_board_copper_fused[netname].emplace_back( fusedShape );
2952 m_board_copper[netname].clear();
2953 m_board_copper_pads[netname].clear();
2954 m_board_copper_vias[netname].clear();
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 )
2986 std::map<wxString, std::vector<TopoDS_Shape>> shapesMap;
2990 std::vector<TopoDS_Shape> allShapes;
2992 for(
const auto& [netname, shapesList] : aShapesMap )
2993 allShapes.insert( allShapes.end(), shapesList.begin(), shapesList.end() );
2995 if( !allShapes.empty() )
2996 shapesMap[wxEmptyString].emplace_back(
makeCompound( allShapes ) );
3000 shapesMap = aShapesMap;
3003 for(
const auto& [netname, shapesList] : shapesMap )
3005 std::vector<TopoDS_Shape> newList;
3010 newList = shapesList;
3014 for( TopoDS_Shape& shape : newList )
3016 Handle( TDataStd_TreeNode ) node;
3019 TDF_Label lbl = m_assy->AddComponent( m_assy_label, shape,
false );
3021 m_pcb_labels.push_back( lbl );
3023 if( m_pcb_labels.back().IsNull() )
3026 lbl.FindAttribute( XCAFDoc::ShapeRefGUID(), node );
3027 TDF_Label shpLbl = node->Father()->Label();
3029 if( !shpLbl.IsNull() )
3031 if( visMatTool && !aVisMatLabel.IsNull() )
3032 visMatTool->SetShapeMaterial( shpLbl, aVisMatLabel );
3036 shapeName << m_pcbName;
3038 shapeName << aShapeName;
3040 if( !netname.empty() )
3043 shapeName << netname;
3046 if( newList.size() > 1 )
3052 TCollection_ExtendedString partname( shapeName.ToUTF8().data() );
3053 TDataStd_Name::Set( shpLbl, partname );
3061 auto pushToAssembly =
3062 [&](
const std::vector<TopoDS_Shape>& aShapesList,
const TDF_Label& aVisMatLabel,
3063 const wxString& aShapeName,
bool aCompound,
const wxString& aNiceName )
3065 const std::map<wxString, std::vector<TopoDS_Shape>> shapesMap{ { wxEmptyString, aShapesList } };
3067 pushToAssemblyMap( shapesMap, aVisMatLabel, aShapeName, aCompound, aCompound, aNiceName );
3071 [&](
const TCollection_AsciiString& aName,
const Quantity_ColorRGBA& aBaseColor,
3072 double aMetallic,
double aRoughness ) -> TDF_Label
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 );
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 );
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;
3102 if( item->GetBrdLayerId() ==
F_Mask || item->GetBrdLayerId() ==
B_Mask )
3106 if( item->GetBrdLayerId() ==
F_Mask )
3107 front_mask_color.SetValues( col.
r, col.
g, col.
b, col.
a );
3109 back_mask_color.SetValues( col.
r, col.
g, col.
b, col.
a );
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 );
3118 board_color.SetValues( col.
r, col.
g, col.
b, col.
a );
3122 if( !m_enabledLayers.Contains(
F_Mask ) && !m_enabledLayers.Contains(
B_Mask ) )
3124 board_color = front_mask_color;
3125 board_color.SetAlpha( 1.0 );
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 );
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" );
3145 if( aPushBoardBody )
3146 pushToAssembly( m_board_outlines, board_mat,
"PCB",
false,
"Body" );
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 );
3151 for(
auto& entry : m_extruded_bodies )
3153 if( entry.bodyShapes.empty() && entry.pinShapes.empty() )
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() ) );
3162 if( !entry.bodyShapes.empty() )
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;
3169 double metallic, roughness;
3171 switch( entry.material )
3192 Quantity_ColorRGBA bodyClr( Quantity_Color( r, g, b, Quantity_TOC_RGB ), a );
3193 TDF_Label body_mat = makeMaterial(
"extruded_body", bodyClr, metallic, roughness );
3195 TopoDS_Shape bodyCompound =
makeCompound( entry.bodyShapes );
3196 TDF_Label bodyLbl = m_assy->AddComponent( fpLabel, bodyCompound,
false );
3198 Handle( TDataStd_TreeNode ) bodyNode;
3199 bodyLbl.FindAttribute( XCAFDoc::ShapeRefGUID(), bodyNode );
3200 TDF_Label bodyShpLbl = bodyNode->Father()->Label();
3202 if( !bodyShpLbl.IsNull() )
3204 visMatTool->SetShapeMaterial( bodyShpLbl, body_mat );
3205 TDataStd_Name::Set( bodyShpLbl,
3206 TCollection_ExtendedString( ( entry.refDes +
"_body" ).ToUTF8().data() ) );
3212 for( TopoDS_Shape& pinShape : entry.pinShapes )
3214 TDF_Label pinLbl = m_assy->AddComponent( fpLabel, pinShape,
false );
3216 Handle( TDataStd_TreeNode ) pinNode;
3217 pinLbl.FindAttribute( XCAFDoc::ShapeRefGUID(), pinNode );
3218 TDF_Label pinShpLbl = pinNode->Father()->Label();
3220 if( !pinShpLbl.IsNull() )
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() ) );
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() ) );
3232 m_pcb_labels.push_back( fpCompLbl );
3235#if( defined OCC_VERSION_HEX ) && ( OCC_VERSION_HEX > 0x070101 )
3236 m_assy->UpdateAssemblies();
3245bool STEP_PCB_MODEL::WriteIGES(
const wxString& aFileName )
3249 m_reporter->Report( wxString::Format(
_(
"No valid PCB assembly; cannot create output file '%s'." ),
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 );
3269 if(
false == writer.Perform( m_doc, aFileName.c_str() ) )
3278 wxFileInputStream input( inputFile );
3279 wxFileOutputStream output( outputFile );
3283 m_reporter->Report( wxString::Format(
_(
"Cannot create input stream '%s'.\n" ), inputFile ) );
3287 if( !output.IsOk() )
3289 m_reporter->Report( wxString::Format(
_(
"Cannot create output stream '%s'.\n" ), outputFile ) );
3293 wxZlibOutputStream zlibStream( output, -1, wxZLIB_GZIP );
3295 if( !zlibStream.IsOk() )
3297 m_reporter->Report(
_(
"Impossible create compress stream" ) );
3301 input.Read( zlibStream );
3303 if( input.LastRead() == 0 || zlibStream.LastWrite() == 0 )
3305 m_reporter->Report(
_(
"Compress read or write error" ) );
3319 m_reporter->Report( wxString::Format(
_(
"No valid PCB assembly; cannot create output file '%s'." ),
3327 wxFileName fn( aFileName );
3329 STEPCAFControl_Writer writer;
3330 writer.SetColorMode(
true );
3331 writer.SetNameMode(
true );
3338 if( !Interface_Static::SetCVal(
"write.step.product.name", fn.GetName().ToAscii() ) )
3340 m_reporter->Report(
_(
"Failed to set STEP product name, but will attempt to continue." ),
3346 if( !Interface_Static::SetIVal(
"write.surfacecurve.mode", aOptimize ? 0 : 1 ) )
3348 m_reporter->Report(
_(
"Failed to set surface curve mode, but will attempt to continue." ),
3352 if(
false == writer.Transfer( m_doc, STEPControl_AsIs ) )
3355 APIHeaderSection_MakeHeader hdr( writer.ChangeWriter().Model() );
3359 hdr.SetName(
new TCollection_HAsciiString( fn.GetFullName().ToAscii() ) );
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" ) );
3367 bool success =
true;
3370 wxString currCWD = wxGetCwd();
3371 wxString workCWD = fn.GetPath();
3373 if( !workCWD.IsEmpty() )
3374 wxSetWorkingDirectory( workCWD );
3376 wxString tmpfname(
"$tempfile$.step" );
3378 if(
false == writer.Write( tmpfname.c_str() ) )
3381 if( compress && success )
3383 wxString srcTmp( tmpfname );
3384 wxString dstTmp(
"$tempfile$.stpz" );
3387 wxRemoveFile( srcTmp );
3398 if( !wxRenameFile( tmpfname, fn.GetFullName(),
true ) )
3400 m_reporter->Report( wxString::Format(
_(
"Cannot rename temporary file '%s' to '%s'." ),
3408 wxSetWorkingDirectory( currCWD );
3418 m_reporter->Report( wxString::Format(
_(
"No valid PCB assembly; cannot create output file '%s'." ),
3427 Handle( XCAFDoc_ShapeTool ) s_assy = XCAFDoc_DocumentTool::ShapeTool( m_doc->Main() );
3432 wxFileName fn( aFileName );
3434 wxFFileOutputStream ffStream( fn.GetFullPath() );
3435 wxStdOutputStream stdStream( ffStream );
3437#if OCC_VERSION_HEX >= 0x070600
3438 BRepTools::Write( shape, stdStream,
false,
false, TopTools_FormatVersion_VERSION_1 );
3440 BRepTools::Write( shape, stdStream );
3449 wxFileName fn( aFileName );
3451 wxFFileOutputStream ffStream( fn.GetFullPath() );
3452 wxStdOutputStream file( ffStream );
3454 if( !ffStream.IsOk() )
3456 m_reporter->Report( wxString::Format(
"Could not open file '%s'", fn.GetFullPath() ),
3464 Handle( XCAFDoc_ShapeTool ) s_assy = XCAFDoc_DocumentTool::ShapeTool( m_doc->Main() );
3469 std::map<wxString, std::vector<int>> groups[4];
3470 std::map<wxString, double> groupAreas;
3471 TopExp_Explorer exp;
3474 for( exp.Init( shape, TopAbs_FACE ); exp.More(); exp.Next() )
3476 TopoDS_Shape subShape = exp.Current();
3479 BRepBndLib::Add( subShape, bbox );
3483 for(
const auto& pair : pairs )
3485 const auto& [point, padTestShape] = pair;
3487 if( bbox.IsOut( point ) )
3490 BRepAdaptor_Surface surface( TopoDS::Face( subShape ) );
3492 if( surface.GetType() != GeomAbs_Plane )
3495 BRepExtrema_DistShapeShape dist( padTestShape, subShape );
3498 if( !dist.IsDone() )
3501 if( dist.Value() < Precision::Approximation() )
3504 groups[2][padKey].push_back( faceIndex );
3506 GProp_GProps system;
3507 BRepGProp::SurfaceProperties( subShape, system );
3509 double surfaceArea = system.Mass() / 1e6;
3510 groupAreas[padKey] += surfaceArea;
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 );
3526 BRepTools::Write( shape, file,
true,
true, TopTools_FormatVersion_VERSION_1 );
3528 file <<
"]]></shape>" << std::endl;
3529 file <<
" <topology>" << std::endl;
3531 NCollection_IndexedMap<TopoDS_Shape, TopTools_ShapeMapHasher> mainMap;
3532 TopExp::MapShapes( shape, mainMap );
3533 std::set<int> topo[4];
3535 static const TopAbs_ShapeEnum c_dimShapeTypes[] = { TopAbs_VERTEX, TopAbs_EDGE, TopAbs_FACE,
3538 static const std::string c_dimLabel[] = {
"vertex",
"edge",
"face",
"solid" };
3539 static const std::string c_dimLabels[] = {
"vertices",
"edges",
"faces",
"solids" };
3541 for(
int dim = 0; dim < 4; dim++ )
3543 for( exp.Init( shape, c_dimShapeTypes[dim] ); exp.More(); exp.Next() )
3545 TopoDS_Shape subShape = exp.Current();
3546 int idx = mainMap.FindIndex( subShape );
3548 if( idx && !topo[dim].count( idx ) )
3549 topo[dim].insert( idx );
3553 for(
int dim = 0; dim <= 3; dim++ )
3555 std::string labels = c_dimLabels[dim];
3556 std::string label = c_dimLabel[dim];
3558 file <<
" <" << labels <<
" count=\"" << topo[dim].size() <<
"\">" << std::endl;
3561 for(
auto p : topo[dim] )
3563 std::string
name(
"" );
3564 file <<
" <" << label <<
" index=\"" <<
index <<
"\" "
3565 <<
"name=\"" <<
name <<
"\" "
3566 <<
"reference=\"" << p <<
"\"/>" << std::endl;
3570 file <<
" </" << labels <<
">" << std::endl;
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() <<
"\">"
3579 int groupNumber = 1;
3584 for(
int dim = 0; dim <= 3; dim++ )
3586 std::string label = c_dimLabel[dim];
3588 for(
auto g : groups[dim] )
3591 wxString
name = g.first;
3595 std::ostringstream gs;
3596 gs <<
"G_" << dim <<
"D_" << g.first;
3599 file <<
" <group name=\"" <<
name <<
"\" dimension=\"" << label;
3605 file <<
"\" count=\"" << g.second.size() <<
"\">" << std::endl;
3607 for(
auto index : g.second )
3608 file <<
" <element index=\"" <<
index <<
"\"/>" << std::endl;
3610 file <<
" </group>" << std::endl;
3612 m_reporter->Report( wxString::Format(
"%d\t%s\t%g",
3624 file <<
" </groups>" << std::endl;
3625 file <<
" <fields count=\"0\"/>" << std::endl;
3626 file <<
"</XAO>" << std::endl;
3633 const std::vector<wxString>& aAltFilenames,
VECTOR3D aScale,
3634 TDF_Label& aLabel,
bool aSubstituteModels,
3635 wxString* aErrorMessage )
3637 std::string fileNameUTF8 = aFileName.utf8_string();
3639 std::string model_key = fileNameUTF8 +
"_" + std::to_string( aScale.
x ) +
"_"
3640 + std::to_string( aScale.
y ) +
"_" + std::to_string( aScale.
z );
3642 MODEL_MAP::const_iterator mm =
m_models.find( model_key );
3646 aLabel = mm->second;
3652 Handle( TDocStd_Document ) doc;
3653 m_app->NewDocument(
"MDTV-XCAF", doc );
3656 TCollection_ExtendedString partname( aBaseName.utf8_str() );
3661 if( !
readIGES( doc, fileNameUTF8.c_str() ) )
3663 m_reporter->Report( wxString::Format( wxT(
"readIGES() failed on filename '%s'." ), aFileName ),
3671 if( !
readSTEP( doc, fileNameUTF8.c_str() ) )
3673 m_reporter->Report( wxString::Format( wxT(
"readSTEP() failed on filename '%s'." ), aFileName ),
3684 wxFFileInputStream ifile( aFileName );
3685 wxFileName outFile( aFileName );
3687 outFile.SetPath( wxStandardPaths::Get().GetTempDir() );
3688 outFile.SetExt( wxT(
"step" ) );
3689 wxFileOffset size = ifile.GetLength();
3691 if( size == wxInvalidOffset )
3693 m_reporter->Report( wxString::Format( wxT(
"getModelLabel() failed on filename '%s'." ),
3700 bool success =
false;
3703 wxFFileOutputStream ofile( outFile.GetFullPath() );
3708 char* buffer =
new char[size];
3710 ifile.Read( buffer, size );
3711 std::string expanded;
3715 expanded = gzip::decompress( buffer, size );
3723 if( expanded.empty() )
3727 wxZipInputStream izipfile( ifile );
3728 std::unique_ptr<wxZipEntry> zip_file( izipfile.GetNextEntry() );
3730 if( zip_file && !zip_file->IsDir() && izipfile.CanRead() )
3732 izipfile.Read( ofile );
3737 m_reporter->Report( wxString::Format( wxT(
"failed to decompress '%s'." ), aFileName ),
3743 ofile.Write( expanded.data(), expanded.size() );
3751 success =
getModelLabel( aBaseName, outFile.GetFullPath(), aAltFilenames,
3752 VECTOR3D( 1.0, 1.0, 1.0 ), aLabel,
false );
3771 if( aSubstituteModels )
3773 wxFileName wrlName( aFileName );
3775 wxString basePath = wrlName.GetPath();
3776 wxString baseName = wrlName.GetName();
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" ) );
3797 alts.Add( wxT(
"iges" ) );
3798 alts.Add( wxT(
"IGES" ) );
3799 alts.Add( wxT(
"igs" ) );
3800 alts.Add( wxT(
"IGS" ) );
3804 for(
const auto& altExt : alts )
3808 if( !aAltFilenames.empty() )
3810 for(
const wxString& altPath : aAltFilenames )
3812 wxFileName iterFn( altPath );
3814 if( iterFn.GetExt() == altExt )
3823 altFile = wxFileName( basePath, baseName + wxT(
"." ) + altExt );
3826 if( altFile.IsOk() && altFile.FileExists() )
3836 VECTOR3D( 1.0, 1.0, 1.0 ), aLabel,
false ) )
3850 if(
readVRML( doc, fileNameUTF8.c_str() ) )
3852 Handle( XCAFDoc_ShapeTool ) shapeTool =
3853 XCAFDoc_DocumentTool::ShapeTool( doc->Main() );
3860 wxString::Format( wxT(
"readVRML() failed on filename '%s'." ),
3870 aErrorMessage->Printf(
_(
"Cannot use VRML models when exporting to non-mesh formats." ) );
3880 m_reporter->Report( wxString::Format(
_(
"Cannot identify actual file type for '%s'." ), aFileName ),
3887 if( aLabel.IsNull() )
3889 m_reporter->Report( wxString::Format(
_(
"Could not transfer model data from file '%s'." ), aFileName ),
3896 TDataStd_Name::Set( aLabel, partname );
3906 TopLoc_Location& aLocation )
3920 lPos.SetTranslation( gp_Vec( aPosition.
x, -aPosition.
y, 0.0 ) );
3926 double boardThickness;
3929 double top = std::max( boardZPos, boardZPos + boardThickness );
3930 double bottom = std::min( boardZPos, boardZPos + boardThickness );
3935 double f_pos, f_thickness;
3939 bottom += f_thickness;
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 );
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 );
3959 lOff.SetTranslation( gp_Vec( offset.
x, offset.
y, offset.
z ) );
3960 lPos.Multiply( lOff );
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 );
3970 aLocation = TopLoc_Location( lPos );
3977 IGESControl_Controller::Init();
3978 IGESCAFControl_Reader reader;
3979 IFSelect_ReturnStatus stat = reader.ReadFile( fname );
3981 if( stat != IFSelect_RetDone )
3985 if( !Interface_Static::SetIVal(
"read.precision.mode", 1 ) )
3989 if( !Interface_Static::SetRVal(
"read.precision.val",
USER_PREC ) )
3993 reader.SetColorMode(
true );
3994 reader.SetNameMode(
false );
3995 reader.SetLayerMode(
false );
3997 if( !reader.Transfer( doc ) )
3999 if( doc->CanClose() == CDM_CCS_OK )
4006 if( reader.NbShapes() < 1 )
4008 if( doc->CanClose() == CDM_CCS_OK )
4020 STEPCAFControl_Reader reader;
4021 IFSelect_ReturnStatus stat = reader.ReadFile( fname );
4023 if( stat != IFSelect_RetDone )
4027 if( !Interface_Static::SetIVal(
"read.precision.mode", 1 ) )
4031 if( !Interface_Static::SetRVal(
"read.precision.val",
USER_PREC ) )
4035 reader.SetColorMode(
true );
4036 reader.SetNameMode(
true );
4037 reader.SetLayerMode(
false );
4039 if( !reader.Transfer( doc ) )
4041 if( doc->CanClose() == CDM_CCS_OK )
4048 if( reader.NbRootsForTransfer() < 1 )
4050 if( doc->CanClose() == CDM_CCS_OK )
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 );
4069 if( !reader.Perform( TCollection_AsciiString( fname ), Message_ProgressRange() ) )
4082 Handle( XCAFDoc_ShapeTool ) s_assy = XCAFDoc_DocumentTool::ShapeTool(
source->Main() );
4084 NCollection_Sequence<TDF_Label> frshapes;
4085 s_assy->GetFreeShapes( frshapes );
4087 Handle( XCAFDoc_ShapeTool ) d_assy = XCAFDoc_DocumentTool::ShapeTool( dest->Main() );
4096 TDF_Label d_targetLabel = d_assy->NewShape();
4098 if( !XCAFDoc_Editor::Extract( frshapes, d_targetLabel,
false ) )
4104 if( aScale.
x != 1.0 || aScale.
y != 1.0 || aScale.
z != 1.0 )
4107 return d_targetLabel;
4113 NCollection_Sequence<TDF_Label> freeShapes;
4114 aShapeTool->GetFreeShapes( freeShapes );
4120 for(
int i = 1; i <= freeShapes.Length(); ++i )
4122 TDF_Label label = freeShapes.Value( i );
4124 aShapeTool->GetShape( label, shape );
4129 const double linearDeflection = 0.14;
4130 const double angularDeflection =
DEG2RAD( 30.0 );
4131 BRepMesh_IncrementalMesh mesh( shape, linearDeflection,
false, angularDeflection,
4153 wxFileName fn( aFileName );
4155 const char* tmpGltfname =
"$tempfile$.glb";
4156 RWGltf_CafWriter cafWriter( tmpGltfname,
true );
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 );
4166#if OCC_VERSION_HEX >= 0x080000
4167 NCollection_IndexedDataMap<TCollection_AsciiString, TCollection_AsciiString> metadata;
4169 TColStd_IndexedDataMapOfStringString metadata;
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" ),
4181 bool success =
true;
4184 wxString currCWD = wxGetCwd();
4185 wxString workCWD = fn.GetPath();
4187 if( !workCWD.IsEmpty() )
4188 wxSetWorkingDirectory( workCWD );
4190 success = cafWriter.Perform( m_doc, metadata, Message_ProgressRange() );
4199 m_reporter->Report(
_(
"Could not post-process GLB line primitives; the exported "
4200 "model may not import in strict glTF viewers." ),
4207 if( !wxRenameFile( tmpGltfname, fn.GetFullName(),
true ) )
4209 m_reporter->Report( wxString::Format(
_(
"Cannot rename temporary file '%s' to '%s'." ),
4217 wxSetWorkingDirectory( currCWD );
4225#if OCC_VERSION_HEX < 0x070700
4232 m_reporter->Report( wxString::Format(
_(
"No valid PCB assembly; cannot create output file '%s'." ),
4242 wxFileName fn( aFileName );
4244 const char* tmpFname =
"$tempfile$.ply";
4245 RWPly_CafWriter cafWriter( tmpFname );
4247 cafWriter.SetFaceId(
true );
4248 cafWriter.ChangeCoordinateSystemConverter().SetInputLengthUnit( 0.001 );
4249 cafWriter.ChangeCoordinateSystemConverter().SetInputCoordinateSystem( RWMesh_CoordinateSystem_Zup );
4251#if OCC_VERSION_HEX >= 0x080000
4252 NCollection_IndexedDataMap<TCollection_AsciiString, TCollection_AsciiString> metadata;
4254 TColStd_IndexedDataMapOfStringString metadata;
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" ),
4264 metadata.Add( TCollection_AsciiString(
"generated_at" ),
4267 bool success =
true;
4270 wxString currCWD = wxGetCwd();
4271 wxString workCWD = fn.GetPath();
4273 if( !workCWD.IsEmpty() )
4274 wxSetWorkingDirectory( workCWD );
4276 success = cafWriter.Perform( m_doc, metadata, Message_ProgressRange() );
4283 if( !wxRenameFile( tmpFname, fn.GetFullName(),
true ) )
4285 m_reporter->Report( wxString::Format(
_(
"Cannot rename temporary file '%s' to '%s'." ),
4293 wxSetWorkingDirectory( currCWD );
4304 m_reporter->Report( wxString::Format(
_(
"No valid PCB assembly; cannot create output file '%s'." ),
4314 wxFileName fn( aFileName );
4316 const char* tmpFname =
"$tempfile$.stl";
4319 wxString currCWD = wxGetCwd();
4320 wxString workCWD = fn.GetPath();
4322 if( !workCWD.IsEmpty() )
4323 wxSetWorkingDirectory( workCWD );
4325 bool success = StlAPI_Writer().Write(
getOneShape( m_assy ), tmpFname );
4332 if( !wxRenameFile( tmpFname, fn.GetFullName(),
true ) )
4334 m_reporter->Report( wxString::Format(
_(
"Cannot rename temporary file '%s' to '%s'." ),
4342 wxSetWorkingDirectory( currCWD );
4354 wxString::Format(
_(
"No valid PCB assembly; cannot create output file '%s'.\n" ), aFileName ),
4363 wxFileName fn( aFileName );
4365 const char* tmpFname =
"$tempfile$.u3d";
4368 wxString currCWD = wxGetCwd();
4369 wxString workCWD = fn.GetPath();
4371 if( !workCWD.IsEmpty() )
4372 wxSetWorkingDirectory( workCWD );
4375 bool success = writer.
Perform( m_doc );
4381 if( !wxRenameFile( tmpFname, fn.GetFullName(),
true ) )
4383 m_reporter->Report( wxString::Format( wxT(
"Cannot rename temporary file '%s' to '%s'.\n" ), tmpFname,
4390 wxSetWorkingDirectory( currCWD );
4401 wxString::Format(
_(
"No valid PCB assembly; cannot create output file '%s'.\n" ), aFileName ),
4410 wxFileName fn( aFileName );
4412 wxFileName u3dTmpfn = wxFileName::CreateTempFileName(
"" );
4413 wxFileName pdfTmpfn = wxFileName::CreateTempFileName(
"" );
4415 U3D::WRITER writer( u3dTmpfn.GetFullPath().ToStdString() );
4416 bool success = writer.
Perform( m_doc );
4419 std::unique_ptr<PDF_PLOTTER> plotter = std::make_unique<PDF_PLOTTER>();
4421 plotter->SetColorMode(
true );
4422 plotter->Set3DExport(
true );
4425 plotter->SetRenderSettings( &renderSettings );
4427 if( !plotter->OpenFile( pdfTmpfn.GetFullPath() ) )
4429 m_reporter->Report( wxString::Format( wxT(
"Cannot open temporary file '%s'.\n" ), pdfTmpfn.GetFullPath() ),
4435 plotter->StartPlot(
"1",
"3D Model" );
4436 double fov_degrees = 16.5f;
4441 std::vector<PDF_3D_VIEW> views;
4446 std::vector<float> c2wMatrix =
4450 .m_name =
"Default",
4451 .m_cameraMatrix = c2wMatrix,
4452 .m_cameraCenter = (float)
distance,
4453 .m_fov = (
float) fov_degrees,
4462 .m_cameraMatrix = c2wMatrix,
4463 .m_cameraCenter = (float)
distance,
4464 .m_fov = (
float) fov_degrees,
4473 .m_cameraMatrix = c2wMatrix,
4474 .m_cameraCenter = (float)
distance,
4475 .m_fov = (
float) fov_degrees,
4484 .m_cameraMatrix = c2wMatrix,
4485 .m_cameraCenter = (float)
distance,
4486 .m_fov = (
float) fov_degrees,
4489 plotter->Plot3DModel( u3dTmpfn.GetFullPath(), views );
4498 if( !wxRenameFile( pdfTmpfn.GetFullPath(), fn.GetFullPath(),
true ) )
4500 m_reporter->Report( wxString::Format( wxT(
"Cannot rename temporary file '%s' to '%s'.\n" ),
4501 pdfTmpfn.GetFullPath(), fn.GetFullPath() ),
4507 wxRemoveFile( u3dTmpfn.GetFullPath() );
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.
constexpr EDA_IU_SCALE pcbIUScale
bool IsPrmSpecified(const wxString &aPrmValue)
@ BS_ITEM_TYPE_SILKSCREEN
@ BS_ITEM_TYPE_DIELECTRIC
@ BS_ITEM_TYPE_SOLDERMASK
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 ...
wxString GetNetname() const
const wxString & GetShortNetname() const
FOOTPRINT * GetParentFootprint() 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
constexpr coord_type GetRight() const
constexpr coord_type GetTop() const
constexpr coord_type GetBottom() const
A color representation with 4 components: red, green, blue, alpha.
COLOR4D & Darken(double aFactor)
Makes the color darker by a given factor.
PCB specific render settings.
LSET is a set of PCB_LAYER_IDs.
LSEQ Seq(const LSEQ &aSequence) const
Return an LSEQ from the union of this LSET and a desired sequence.
PAD_PROP GetProperty() const
LSET GetLayerSet() const override
Return a std::bitset of all layers on which the item physically resides.
bool FlashLayer(int aLayer, bool aOnlyCheckIfPermitted=false) const
Check to see whether the pad should be flashed on the specific layer.
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.
bool IsOnLayer(PCB_LAYER_ID aLayer) const override
Test to see if this object is on the given layer.
PAD_ATTRIB GetAttribute() const
const wxString & GetNumber() const
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.
VECTOR2I GetDrillSize() const
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.
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED)
Report a string with a given severity.
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
VECTOR2I NearestPoint(const VECTOR2I &aP) const
const VECTOR2I & GetP1() const
const VECTOR2I & GetP0() const
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 isBoardOutlineValid()
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)
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.
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
bool WriteSTL(const wxString &aFileName)
void SetStackup(const BOARD_STACKUP &aStackup)
void SetNetFilter(const wxString &aFilter)
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)
bool WriteBREP(const wxString &aFileName)
bool Perform(const Handle(TDocStd_Document) &aDocument)
const VECTOR3D & GetCenter() const
const Bnd_Box & GetMeshBoundingBox() const
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).
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.
static constexpr EDA_ANGLE ANGLE_360
bool FixGlbLinesPrimitives(const wxString &aFilePath)
Fix LINES primitives in a GLB file that have odd index counts.
const wxChar *const traceKiCad2Step
Flag to enable KiCad2Step debug tracing.
Handle(KICAD3D_INFO) KICAD3D_INFO
wxString LayerName(int aLayer)
Returns the default display name for a given layer.
bool IsFrontLayer(PCB_LAYER_ID aLayerId)
Layer classification: check if it's a front layer.
bool IsBackLayer(PCB_LAYER_ID aLayerId)
Layer classification: check if it's a back layer.
bool IsCopperLayer(int aLayerId)
Test whether a layer is a copper layer.
bool IsInnerCopperLayer(int aLayerId)
Test whether a layer is an inner (In1_Cu to In30_Cu) copper layer.
PCB_LAYER_ID
A quick note on layer IDs:
This file contains miscellaneous commonly used macros and functions.
EDA_ANGLE abs(const EDA_ANGLE &aAngle)
@ PTH
Plated through hole pad.
@ CASTELLATED
a pad with a castellated through hole
Plotting engines similar to ps (PostScript, Gerber, svg)
static float distance(const SFVEC2UI &a, const SFVEC2UI &b)
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()
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)
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)
SHAPE_CIRCLE circle(c.m_circle_center, c.m_circle_radius)
thread_pool & GetKiCadThreadPool()
Get a reference to the current thread pool.
BS::priority_thread_pool thread_pool
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.
double DEG2RAD(double deg)
VECTOR2< int32_t > VECTOR2I
VECTOR2< double > VECTOR2D
VECTOR3< double > VECTOR3D
static PIECE polygon(std::vector< VIA_CROSS_SECTION_GEOMETRY::POINT > aPoints, bool aMixed=false)