|
| 1 | +import os |
| 2 | +import tempfile |
| 3 | + |
| 4 | +from ..typed import BinaryIO, Dict, Optional |
| 5 | + |
| 6 | +# used as an intermediate format |
| 7 | +from .gltf import load_glb |
| 8 | + |
| 9 | + |
| 10 | +def load_step( |
| 11 | + file_obj: BinaryIO, |
| 12 | + file_type, |
| 13 | + tol_linear: Optional[float] = None, |
| 14 | + tol_angular: Optional[float] = None, |
| 15 | + tol_relative: Optional[bool] = False, |
| 16 | + merge_primitives: bool = True, |
| 17 | + **kwargs, |
| 18 | +) -> Dict: |
| 19 | + """ |
| 20 | + Use `cascadio` a packaged version of OpenCASCADE |
| 21 | + to load a STEP file using GLB as an intermediate. |
| 22 | +
|
| 23 | + Parameters |
| 24 | + ----------- |
| 25 | + file_obj |
| 26 | + STEP file to load. |
| 27 | + **kwargs |
| 28 | + Passed to `cascadio.step_to_glb` |
| 29 | +
|
| 30 | + Returns |
| 31 | + ---------- |
| 32 | + kwargs |
| 33 | + Keyword arguments for a Scene. |
| 34 | + """ |
| 35 | + # TODO : update upstream `cascadio` to accept bytes objects |
| 36 | + # so that we don't need to write a temporary file to disc! |
| 37 | + with tempfile.TemporaryDirectory() as F: |
| 38 | + # temporarily copy the STEP |
| 39 | + stepfile = os.path.join(F, "data.step") |
| 40 | + with open(stepfile, "wb") as f: |
| 41 | + f.write(file_obj.read()) |
| 42 | + |
| 43 | + # where to save the converted GLB |
| 44 | + glbfile = os.path.join(F, "converted.glb") |
| 45 | + |
| 46 | + # the arguments for cascadio are not optional so |
| 47 | + # filter out any `None` value arguments here |
| 48 | + cascadio_kwargs = { |
| 49 | + "merge_primitives": bool(merge_primitives), |
| 50 | + "tol_linear": tol_linear, |
| 51 | + "tol_angular": tol_angular, |
| 52 | + "tol_relative": tol_relative, |
| 53 | + } |
| 54 | + # run the conversion |
| 55 | + cascadio.step_to_glb( |
| 56 | + stepfile, |
| 57 | + glbfile, |
| 58 | + **{k: v for k, v in cascadio_kwargs.items() if v is not None}, |
| 59 | + ) |
| 60 | + |
| 61 | + with open(glbfile, "rb") as f: |
| 62 | + # return the parsed intermediate file |
| 63 | + return load_glb(file_obj=f, merge_primitives=merge_primitives, **kwargs) |
| 64 | + |
| 65 | + |
| 66 | +try: |
| 67 | + # wheels for most platforms: `pip install cascadio` |
| 68 | + import cascadio |
| 69 | + |
| 70 | + _cascade_loaders = {"stp": load_step, "step": load_step} |
| 71 | +except BaseException: |
| 72 | + _cascade_loaders = {} |
0 commit comments