Ë
    Jÿi°5  ã                   óÔ  — d Z ddlmZ ddlZddlmZmZmZ ddlm	Z	 ddl
mZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZmZmZ ddlm Z  ddl!m"Z"m#Z# ddl$m%Z%m&Z& ddl'm(Z( ddl)m*Z*m+Z+m,Z, ddl-m.Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:Z:m;Z; ddl<m=Z= ddl>m?Z? ddl@mAZAmBZB ddlCmDZD ddlEmFZFmGZGmHZHmIZImJZJ eBj–                  fdeId eBd!e4fd"„ZLdeId#eeMz  eNz  ez  d!eOfd$„ZPeBj–                  d%d&d'fdeId#eeMz  eNz  d eBd(eOd)eQd*eQd!eOfd+„ZReBj–                  d,eAj¦                  fdeId#eeMz  eNz  d eBd-eOd.eAd!eOfd/„ZT	 	 	 d4deId#eeMz  eNz  d0eQd1eQd2eOd!eOfd3„ZUy)5a×  
build123d 3D Exporters

name: exporters3d.py
by:   Gumyr
date: March 6th, 2024

desc:
    Exporters for 3D models such as STEP.

license:

    Copyright 2024 Gumyr

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

é    )ÚBytesION)ÚPathLikeÚfsdecodeÚfspath)ÚUnion)ÚPreOrderIter)ÚAPIHeaderSection_MakeHeader)ÚBRepMesh_IncrementalMesh)Ú	BRepTools)ÚIFSelect_ReturnStatus)ÚIGESControl_Controller)ÚInterface_Static)ÚMessageÚMessage_GravityÚMessage_ProgressRange)ÚRWGltf_CafWriter)ÚSTEPCAFControl_ControllerÚSTEPCAFControl_Writer)ÚSTEPControl_ControllerÚSTEPControl_StepModelType)ÚStlAPI_Writer)ÚTCollection_AsciiStringÚTCollection_ExtendedStringÚTCollection_HAsciiString)Ú$TColStd_IndexedDataMapOfStringString)ÚTDataStd_Name)Ú	TDF_Label)ÚTDocStd_Document)ÚTopExp_Explorer)ÚXCAFApp_Application)ÚXCAFDoc_ColorTypeÚXCAFDoc_DocumentTool)ÚXSControl_WorkSession)ÚUNITS_PER_METER)ÚPrecisionModeÚUnit)ÚLocation)ÚCompoundÚCurveÚPartÚShapeÚSketchÚ	to_exportÚunitÚreturnc                 ó¬  — t        t        d«      «      }t        j                  «       }|j	                  t        d«      |«       |j                  |«       t        j                  |dt        |   z  «       t        j                  |j                  «       «      }t        j                  |j                  «       «      }t        | t        «      xr t        | j                  «      dkD  }|j!                  | j"                  |«      }t%        | «      D �]/  }|j&                  s|j(                  €Œ|j+                  |j"                  d¬«      }	g }
t        |t        «      �r?|j                  �s2g }t        |t,        «      r%t/        |j"                  t0        j2                  «      }n‹t        |t4        «      r%t/        |j"                  t0        j6                  «      }nVt        |t8        «      r%t/        |j"                  t0        j:                  «      }n!t=        j>                  dd¬	«       t/        «       }|jA                  «       r@|jC                  |jE                  «       «       |jG                  «        |jA                  «       rŒ@|D �cg c]  }|j+                  |d¬«      ‘Œ }
}|j&                  r9|	jI                  «       s)tK        jL                  |	t        |j&                  «      «       |j(                  €�Œß|	g|
z   D ]H  }|jI                  «       rŒ|jO                  ||j(                  j"                  tP        jR                  «       ŒJ �Œ2 |jU                  «        |S c c}w )
a  create_xde

    An OpenCASCADE Technology (OCCT) XDE (eXtended Data Exchange) document is a
    sophisticated framework designed for comprehensive CAD data management,
    facilitating not just the geometric modeling of shapes but also the handling
    of associated metadata, such as material properties, color, layering, and
    annotations. This integrated environment supports the organization and
    manipulation of complex assemblies and parts, enabling users to navigate,
    edit, and query both the structure and attributes of CAD models. XDE's
    architecture is particularly beneficial for applications requiring detailed
    interoperability between different CAD systems, offering robust tools for
    data exchange, visualization, and modification while preserving the integrity
    and attributes of the CAD data across various stages of product development.

    Args:
        to_export (Shape): object or assembly
        unit (Unit, optional): shape units. Defaults to Unit.MM.

    Returns:
        TDocStd_Document: XDE document
    ÚXmlOcafz	MDTV-XCAFé   r   F)ÚfindInstancez$Unknown Compound type, color not seté   )Ú
stacklevel)+r   r   r    ÚGetApplication_sÚNewDocumentÚInitDocumentr"   ÚSetLengthUnit_sr$   ÚShapeTool_sÚMainÚColorTool_sÚ
isinstancer(   ÚlenÚchildrenÚAddShapeÚwrappedr   ÚlabelÚcolorÚ	FindShaper*   r   ÚtaÚTopAbs_SOLIDr,   ÚTopAbs_FACEr)   ÚTopAbs_EDGEÚwarningsÚwarnÚMoreÚappendÚCurrentÚNextÚIsNullr   ÚSet_sÚSetColorr!   ÚXCAFDoc_ColorSurfÚUpdateAssemblies)r-   r.   ÚdocÚapplicationÚ
shape_toolÚ
color_toolÚis_assemblyÚ_root_labelÚnodeÚ
node_labelÚsub_node_labelsÚ	sub_nodesÚexplorerÚsub_noderB   s                  úf/workspace/moltex-experiments/.pixi/envs/default/lib/python3.12/site-packages/build123d/exporters3d.pyÚ_create_xdera   B   s—  € ô. Ô5°iÓ@Ó
A€Cô &×6Ñ6Ó8€Kð ×ÑÔ6°{ÓCÀSÔIØ×Ñ˜SÔ!ä×(Ñ(¨¨a´/À$Ñ2GÑ.GÔHô &×1Ñ1°#·(±(³*Ó=€JÜ%×1Ñ1°#·(±(³*Ó=€Jô ˜Y¬Ó1ÒQ´c¸)×:LÑ:LÓ6MÐPQÑ6Q€KØ×%Ñ% i×&7Ñ&7¸ÓE€Kô ˜Y×'ˆØ�zŠz˜dŸj™jÐ0Øà *× 4Ñ 4°T·\±\ÐPUÐ 4Ó Vˆ
ð ˆÜ�dœHÕ%¨d¯m«mØˆIÜ˜$¤Ô%Ü*¨4¯<©<¼¿¹ÓI‘Ü˜D¤&Ô)Ü*¨4¯<©<¼¿¹ÓH‘Ü˜D¤%Ô(Ü*¨4¯<©<¼¿¹ÓH‘ä—‘ÐDÐQRÕSÜ*Ó,�à—-‘-”/Ø× Ñ  ×!1Ñ!1Ó!3Ô4Ø—‘”ð —-‘-•/ñ !*óá )�Hð ×$Ñ$ X¸EÐ$ÕBØ )ð ð ð �:Š:˜j×/Ñ/Ô1Ü×Ñ 
Ô,FÀtÇzÁzÓ,RÔSà�:‰:Ò!Ø$˜¨Ô7�Ø—<‘<”>ØØ×#Ñ#Ø˜4Ÿ:™:×-Ñ-Ô/@×/RÑ/Rõò 8ðC (ðP ×ÑÔ!ð €Jùò's   É<MÚ	file_pathc                 ó„   — t        |t        «      st        |«      }t        j                  | j
                  |«      }|€dS |S )zàExport this shape to a BREP file

    Args:
        to_export (Shape): object or assembly
        file_path: Union[PathLike, str, bytes, BytesIO]: brep file path or memory buffer

    Returns:
        bool: write status
    T)r=   r   r   r   ÚWrite_srA   )r-   rb   Úreturn_values      r`   Úexport_breprf   ž   s@   € ô �i¤Ô)Ü˜YÓ'ˆ	ä×$Ñ$ Y×%6Ñ%6¸	ÓB€LàÐ'ˆ4Ð9¨\Ð9ó    Fçü©ñÒMbP?çš™™™™™¹?ÚbinaryÚlinear_deflectionÚangular_deflectionc                 óž  — | j                   €t        d«      ‚| j                   }| xj                   t        ddd«      z  c_         t        | «      D ]!  }|j                  €Œ|j                  ||«       Œ# t        | |«      }t        t        t        |«      «      |¬«      }	|	j                  d«       t        «       }
t        «       }t        j                  «       }|j                  «       D ]*  }|j!                  t#        t"        j$                  «      «       Œ, |	j'                  ||
|«      }t)        j*                  | j                  «       || _         |S )a  export_gltf

    The glTF (GL Transmission Format) specification primarily focuses on the efficient
    transmission and loading of 3D models as a compact, binary format that is directly
    renderable by graphics APIs like WebGL, OpenGL, and Vulkan. It's designed to store
    detailed 3D model data, including meshes (vertices, normals, textures, etc.),
    animations, materials, and scene hierarchy, among other aspects.

    Args:
        to_export (Shape): object or assembly
        file_path (Union[PathLike, str, bytes]): glTF file path
        unit (Unit, optional): shape units. Defaults to Unit.MM.
        binary (bool, optional): output format. Defaults to False.
        linear_deflection (float, optional): A linear deflection setting which limits
            the distance between a curve and its tessellation. Setting this value too
            low will result in large meshes that can consume computing resources. Setting
            the value too high can result in meshes with a level of detail that is too
            low. The default is a good starting point for a range of cases.
            Defaults to 1e-3.
        angular_deflection (float, optional): Angular deflection setting which limits
            the angle between subsequent segments in a polyline. Defaults to 0.1.

    Raises:
        RuntimeError: Failed to write glTF file

    Returns:
        bool: write status
    z,Shape must have a location to export to glTF)r   r   r   )r2   r   r   i¦ÿÿÿ)ÚtheFileÚtheIsBinaryT)ÚlocationÚ
ValueErrorr'   r   rA   Úmeshra   r   r   r   ÚSetParallelr   r   r   ÚDefaultMessenger_sÚPrintersÚSetTraceLevelr   ÚMessage_FailÚPerformr   ÚClean_s)r-   rb   r.   rj   rk   rl   Úoriginal_locationrZ   rT   ÚwriterÚ	index_mapÚprogressÚ	messengerÚprinterÚstatuss                  r`   Úexport_gltfr�   ³   s,  € ðP ×ÑÐ!ÜÐGÓHÐHØ!×*Ñ*ÐØ×Òœ( 9¨i¸Ó=Ñ=Õô ˜YÖ'ˆØ�<‰<Ñ#Ø�I‰IÐ'Ð);Õ<ð (ô
 (¨	°4Ó8€Cô Ü'¬°Ó(;Ó<È&ô€Fð ×Ñ�tÔÜ4Ó6€IÜ$Ó&€Hä×*Ñ*Ó,€IØ×%Ñ%Ö'ˆØ×Ñœo¬o×.JÑ.JÓKÕLð (ð �^‰^˜C ¨HÓ5€Fô ×Ñ�i×'Ñ'Ô(ð +€IÔð
 €Mrg   TÚwrite_pcurvesÚprecision_modec                 óÚ  — t        | |«      }t        j                  «       }|j                  «       D ]*  }|j	                  t        t
        j                  «      «       Œ, t        «       }t        |d«      }	|	j                  d«       |	j                  d«       |	j                  d«       t        |	j                  «       j                  «       «      }
| j                  r$|
j!                  t#        | j                  «      «       |
j%                  t#        d«      «       t'        j(                  «        t+        j(                  «        t-        j(                  «        t/        j0                  dt3        |«      «       t/        j0                  d|j4                  «       |	j7                  |t8        j:                  «       |	j=                  t?        |«      «      t@        jB                  k(  }|stE        d«      ‚|S )a×  export_step

    Export a build123d Shape or assembly with color and label attributes.
    Note that if the color of a node in an assembly isn't set, it will be
    assigned the color of its nearest ancestor.

    Args:
        to_export (Shape): object or assembly
        file_path (Union[PathLike, str, bytes]): step file path
        unit (Unit, optional): shape units. Defaults to Unit.MM.
        write_pcurves (bool, optional): write parametric curves to the STEP file.
            Defaults to True.
        precision_mode (PrecisionMode, optional): geometric data precision.
            Defaults to PrecisionMode.AVERAGE.

    Raises:
        RuntimeError: Unknown Compound type

    Returns:
        bool: success
    FTÚ	build123dzwrite.surfacecurve.modezwrite.precision.modezFailed to write STEP file)#ra   r   rt   ru   rv   r   rw   r#   r   ÚSetColorModeÚSetLayerModeÚSetNameModer	   ÚWriterÚModelrB   ÚSetNamer   ÚSetOriginatingSystemr   ÚInit_sr   r   r   Ú	SetIVal_sÚintÚvalueÚTransferr   ÚSTEPControl_AsIsÚWriter   r   ÚIFSelect_RetDoneÚRuntimeError)r-   rb   r.   r‚   rƒ   rT   r~   r   Úsessionr{   Úheaderr€   s               r`   Úexport_stepr˜     ss  € ô< �i Ó
&€Cô ×*Ñ*Ó,€IØ×%Ñ%Ö'ˆØ×Ñœo¬o×.JÑ.JÓKÕLð (ô $Ó%€GÜ" 7¨EÓ2€FØ
×Ñ˜ÔØ
×Ñ˜ÔØ
×Ñ�tÔä(¨¯©«×)>Ñ)>Ó)@ÓA€FØ‡‚Ø�‰Ô/°	·±Ó@ÔAð ×ÑÔ 8¸Ó EÔFô ×$Ñ$Ô&Ü×!Ñ!Ô#Ü×!Ñ!Ô#Ü×ÑÐ8¼#¸mÓ:LÔMÜ×ÑÐ5°~×7KÑ7KÔLØ
‡O�O�CÔ2×CÑCÔDà�\‰\œ& Ó+Ó,Ô0E×0VÑ0VÑV€FÙÜÐ6Ó7Ð7à€Mrg   Ú	toleranceÚangular_toleranceÚascii_formatc                 óÄ   — t        | j                  |d|d«      }|j                  «        t        «       }||_        t        |«      }|j                  | j                  |«      S )aÍ  Export STL

    Exports a shape to a specified STL file.

    Args:
        to_export (Shape): object or assembly
        file_path (str): The path and file name to write the STL output to.
        tolerance (float, optional): A linear deflection setting which limits the distance
            between a curve and its tessellation. Setting this value too low will result in
            large meshes that can consume computing resources. Setting the value too high can
            result in meshes with a level of detail that is too low. The default is a good
            starting point for a range of cases. Defaults to 1e-3.
        angular_tolerance (float, optional): Angular deflection setting which limits the angle
            between subsequent segments in a polyline. Defaults to 0.1.
        ascii_format (bool, optional): Export the file as ASCII (True) or binary (False)
            STL format. Defaults to False (binary).

    Returns:
        bool: Success
    T)r
   rA   rx   r   Ú	ASCIIModeÚstrr“   )r-   rb   r™   rš   r›   rr   r{   s          r`   Ú
export_stlrŸ   E  sZ   € ô6 $Ø×Ñ˜9 dÐ,=¸tó€Dð 	‡L�L„Nä‹_€Fà#€FÔä�I“€Ià�<‰<˜	×)Ñ)¨9Ó5Ð5rg   )rh   ri   F)VÚ__doc__Úior   rI   Úosr   r   r   Útypingr   Ú
OCP.TopAbsÚTopAbsrE   Úanytreer   ÚOCP.APIHeaderSectionr	   ÚOCP.BRepMeshr
   ÚOCP.BRepToolsr   ÚOCP.IFSelectr   ÚOCP.IGESControlr   ÚOCP.Interfacer   ÚOCP.Messager   r   r   Ú
OCP.RWGltfr   ÚOCP.STEPCAFControlr   r   ÚOCP.STEPControlr   r   Ú
OCP.StlAPIr   ÚOCP.TCollectionr   r   r   ÚOCP.TColStdr   ÚOCP.TDataStdr   ÚOCP.TDFr   ÚOCP.TDocStdr   Ú
OCP.TopExpr   ÚOCP.XCAFAppr    ÚOCP.XCAFDocr!   r"   ÚOCP.XSControlr#   Úbuild123d.build_commonr$   Úbuild123d.build_enumsr%   r&   Úbuild123d.geometryr'   Úbuild123d.topologyr(   r)   r*   r+   r,   ÚMMra   rž   ÚbytesÚboolrf   Úfloatr�   ÚAVERAGEr˜   rŸ   © rg   r`   Ú<module>rÅ      sà  ðñõ> Û ß )Ñ )Ý å Ý  Ý <Ý 1Ý #Ý .Ý 2Ý *ß GÑ GÝ 'ß Oß MÝ $ß iÑ iÝ <Ý &Ý Ý (Ý &Ý +ß ?Ý /å 2ß 5Ý 'ß CÕ Cð 04¯w©wñ Y˜5ð Y¨ð YÐ;Kó Yðx:Øð:à˜#‰~ Ñ%¨Ñ/ð:ð 
ó:ð0 —‘ØØ$Ø #ñMØðMà˜#‰~ Ñ%ðMð ðMð ð	Mð
 ðMð ðMð 
óMðf —‘ØØ$1×$9Ñ$9ñ?Øð?à˜#‰~ Ñ%ð?ð ð?ð ð	?ð
 "ð?ð 
ó?ðJ Ø"Øñ&6Øð&6à˜#‰~ Ñ%ð&6ð ð&6ð ð	&6ð
 ð&6ð 
ô&6rg   