Exemplo n.º 1
0
def export_shape_to_svg_by_viewpoints(fname, viewpoints, args):
    converter = Model2SVG(width=args.width,
                          height=args.height,
                          tol=args.tol,
                          margin_left=args.margin_left,
                          margin_top=args.margin_top,
                          line_width=args.line_width,
                          line_width_hidden=args.line_width_hidden)
    try:
        shp = read_step_file(fname)
        boundbox = get_boundingbox(shp)
        max_3d_eadge = max(boundbox[6], boundbox[7], boundbox[8])
        sc = min(args.width, args.height) / max_3d_eadge
        fname_out = os.path.splitext(fname)[0] + '_{}.svg'

        for vp in viewpoints:
            converter.export_shape_to_svg(shape=shp,
                                          filename=fname_out.format(vp),
                                          proj_ax=converter.DIRS[vp],
                                          max_eadge=max_3d_eadge)
        return 1

    except Exception as re:
        print(fname + ' failed, due to: {}'.format(re))
        return 0
Exemplo n.º 2
0
    def __init__(self):
        plotocc.__init__(self)
        self.shell = read_step_file(self.tmpdir + "SurfUV.stp")
        print(self.shell)
        top = TopExp_Explorer(self.shell, TopAbs_FACE)
        self.face = top.Current()
        print(top.Depth())
        print(self.face)
        self.surf = BRep_Tool.Surface(self.face)

        u0, u1, v0, v1 = shapeanalysis_GetFaceUVBounds(self.face)
        print(u0, u1, v0, v1)
        sas = ShapeAnalysis_Surface(self.surf)
        print(sas.Value(u0, v0))
        print(sas.Value(u0, v1))
        print(sas.Value(u1, v0))
        print(sas.Value(u1, v1))

        u = u0
        while u <= u1:
            v = v0
            while v <= v1:
                p = sas.Value(u, v)
                self.display.DisplayShape(p, update=False)
                v += 1 / 3
            u += 1 / 4
Exemplo n.º 3
0
def walk_shapes(dir_path):
    from ..core.file_system import get_list_of_files

    shps = []
    for stp_file in get_list_of_files(dir_path, ".stp"):
        shps += extract_subshapes(read_step_file(stp_file))
    return shps
Exemplo n.º 4
0
    def read_cadfile(self, fileName, disp=True):
        print(fileName)
        base_dir = os.path.dirname(fileName)
        basename = os.path.basename(fileName)
        rootname, extname = os.path.splitext(fileName)
        if extname in [".stp", ".step"]:
            shpe = read_step_file(fileName)
        elif extname in [".igs", ".iges"]:
            shpe = read_iges_file(fileName)
        elif extname in [".stl"]:
            shpe = read_stl_file(fileName)
        elif extname in [".brep"]:
            shpe = TopoDS_Shape()
            builder = BRep_Builder()
            breptools_Read(shpe, fileName, builder)
        elif extname in [".geo"]:
            stlfile = self.import_geofile(fileName, 0.1)
            shpe = read_stl_file(stlfile)
        else:
            print("Incorrect file index")
            # sys.exit(0)

        if disp == True:
            self.display.DisplayShape(shpe, update=True)
        return shpe
Exemplo n.º 5
0
    def Bulk_stptoimag(self):
        pass
        self.file_list = os.listdir(self.chose_document)
        print(self.file_list)
        for file in self.file_list:
            self.canva._display.EraseAll()
            self.canva._display.hide_triedron()
            self.canva._display.display_triedron()
            if "stp" in file or "step" in file or "iges" in file:
                try:
                    if file == "iseg":
                        continue
                    else:
                        read_path = os.path.join(self.chose_document, file)
                        the_shape = read_step_file(read_path)
                        name = file.split(".")
                        ais_shape = AIS_ColoredShape(the_shape)
                        for e in TopologyExplorer(the_shape).solids():
                            rnd_color = (random(), random(), random())
                            ais_shape.SetCustomColor(e,
                                                     rgb_color(0.5, 0.5, 0.5))

                        self.canva._display.Context.Display(ais_shape, True)
                        self.canva._display.FitAll()
                        path = self.chose_document + "\\" + name[0] + ".bmp"
                        self.canva._display.ExportToImage(path)

                except:
                    pass

            self.statusbar.showMessage("状态:表格生成成功")
Exemplo n.º 6
0
 def readExtGeometry(self):
     self.shape = TopoDS_Shape
     extg = self.object.find(self.dict['externalgeometryref'])
     if extg == None:
         if self.logging == True:
             OCXCommon.Message(self.object, 'has no external geometry')
     else:
         extfile = str(extg.get(self.dict['externalref'])
                       )  # Relative path to the input ocxfile
         extfile = extfile.replace('\\', '/')  #Fix for UNIX systems
         gfile = Path(extfile)
         # Build the full file path
         file = self.ocxfile.parent
         for part in gfile.parts:
             file = file / part
         filename = file.resolve()
         format = extg.get('geometryFormat')
         if filename.is_file():
             if format == 'STEP':
                 self.shape = read_step_file(str(filename))
                 self.done = True
             elif format == '.igs':  # TODO: S3D export must change to 'IGES'
                 self.shape = read_iges_file(str(filename))
                 self.done = True
             else:
                 print('Unknown geometry format')
         else:
             print(file + ' not exist')
     return
Exemplo n.º 7
0
 def Exchange_stp_3xd(self):
     try:
         for file in self.file_list:
             if "stp" in file or "step" in file or "iges" in file :
                 try:
                     the_shape = read_step_file(file)
                     my_renderer = x3dom_renderer.X3DomRenderer("./")
                     name=file.split(".")
                     my_renderer.DisplayShape(the_shape,export_edges=True,color=(random(), random(), random()),file_name=name[0])
                     
                     #if file=="iseg":
                         #pass
                     #else:
                         #the_shape = read_step_file(file)
                         #ais_shape=AIS_ColoredShape(the_shape)
                         #for e in TopologyExplorer(the_shape).shells():
                             #rnd_color = (random(), random(), random())
                             #ais_shape.SetCustomColor(e, rgb_color(random(), random(), random()))
                             #display.EraseAll()
                             #context.Display(ais_shape,True)
                             #display.FitAll()
                             #path='./'+name[0]+".bmp"
                             #display.View.Dump(path)
                         
                 except:
                     pass             
     except:
         pass
Exemplo n.º 8
0
def main():
    shp = read_step_file(
        'Models/00000000_290a9120f9f249a7a05cfe9c_step_000.step')
    shape_type = get_type_as_string(shp)
    t = TopologyFactory(shape_type)
    shape = t.create_shape_object(shp)
    shape.parse_shape()
    with open("model2.json", "w") as f:
        json.dump(shape.config, f, indent=4)
Exemplo n.º 9
0
    def test_tesselate_STEP_file(self):
        """loads a step file, tesselate. The as1_pe_203 contains
        free edges"""
        stp_file = os.path.join(os.path.join("test_io", "as1_pe_203.stp"))
        stp_file_shape = read_step_file(stp_file)
        stp_file_tesselator = ShapeTesselator(stp_file_shape)

        # free edges have been excluded, then should work as expected
        stp_file_tesselator.Compute(compute_edges=True)
Exemplo n.º 10
0
def import_as_multiple_shapes(event=None):
    compound = read_step_file(
        os.path.join('..', 'assets', 'models', 'as1_pe_203.stp'))
    t = TopologyExplorer(compound)
    display.EraseAll()
    for solid in t.solids():
        color = Quantity_Color(random.random(), random.random(),
                               random.random(), Quantity_TOC_RGB)
        display.DisplayColoredShape(solid, color)
    display.FitAll()
Exemplo n.º 11
0
def convert_stp_handler(file_path, is_bin=False):
    # 1. read stp file and convert to stl
    convert_stl_path = file_path + '.stl'
    shapes = read_step_file(file_path)
    write_stl_by_shapes(shapes, convert_stl_path)
    result = convert_stl_to_draco_gltf(file_path, convert_stl_path, is_bin)

    if not config['app']['save_convert_temp_file']:
        clear_file(convert_stl_path)
    return result
Exemplo n.º 12
0
 def executeOnFile(file):
     global files_processed
     print('\n>> file', file_counter)
     compound = read_step_file(file, verbosity=False) # always 3 unknown entities
     ex = TopologyExplorer(compound)
     for face in ex.faces():
         type_counter[BRepAdaptor_Surface(face).GetType()] += 1
         if BRepAdaptor_Surface(face).GetType() == FILTER_TYPE:
             os.makedirs(OUTPUT_DIR, exist_ok=True)
             #TODO write model face to new file
             files_processed += 1
Exemplo n.º 13
0
    def add_file(self):
        # app = QApplication(sys.argv)
        ex = App()
        filename = ex.openFileNameDialog()
        # sys.exit(app.exec_())
        name = os.path.split(filename)[-1]
        # print(name)
        self.path_modules[name] = filename
        self.modules[name] = read_step_file(filename)

        self.reload_modules()
Exemplo n.º 14
0
def filter_all_step_files(event=None):
    inputFiles = glob.glob(os.path.join('../resources/step', '*.step'))
    for inputFile in inputFiles:
        compound = read_step_file(inputFile)
        index = 0
        for face in TopologyExplorer(compound).faces():
            if BRepAdaptor_Surface(face).GetType() == FILTER_TYPE:
                fileName = os.path.join(OUTPUT_DIR,
                                        str(index) + OUTPUT_EXTENSION)
                os.makedirs(OUTPUT_DIR, exist_ok=True)
                write_step_file(face, fileName)
                index += 1
Exemplo n.º 15
0
    def vizualization_all(self):
        self.display, self.start_display, self.add_menu, self.add_function_to_menu = init_display(
        )
        frame1 = read_step_file(
            os.path.join('part_of_sattelate', 'karkase', self.name_frame))
        self.display.DisplayShape(frame1, color='GREEN', transparency=0.9)
        for model in self.modules:
            self.display.DisplayShape(self.modules[model],
                                      color='RED',
                                      transparency=0.9)

        self.start_display()
Exemplo n.º 16
0
def glue_solids(event=None):
    display.EraseAll()
    display.Context.RemoveAll(True)
    # Without common edges
    S1 = read_step_file(os.path.join('part_of_sattelate', 'pribore', 'DAV_WS16.STEP'))
    display.DisplayShape(S1, color='BLUE', transparency=0.9)
    measure(S1)

    # the face to glue
    S2 = read_step_file(os.path.join('part_of_sattelate', 'pribore', 'Camara_WS16.STEP'))

    trsf = gp_Trsf()

    trsf.SetTranslation(gp_Vec(750, 0, 0))
    S2.Move(TopLoc_Location(trsf))

    fuse_shp = BRepAlgoAPI_Fuse(S1, S2).Shape()

    props = GProp_GProps()
    brepgprop_VolumeProperties(fuse_shp, props)
    # Get inertia properties
    mass = props.Mass()
    cog = props.CentreOfMass()
    matrix_of_inertia = props.MatrixOfInertia()
    # Display inertia properties
    print("Cube mass = %s" % mass)
    cog_x, cog_y, cog_z = cog.Coord()
    print("Center of mass: x = %f;y = %f;z = %f;" % (cog_x, cog_y, cog_z))


    display.DisplayShape(fuse_shp)
    #pstring = 'x: % \n y: % \n z: %' % (cog_x, cog_y, cog_z)
    pnt = gp_Pnt(cog_x, cog_y, cog_z)
    # display points
    display.DisplayShape(pnt, update=True)
    pnt = gp_Pnt(0, 0, 0)
    # display points
    display.DisplayShape(pnt, update=True)
    #display.DisplayMessage(pnt, pstring)
    display.FitAll()
Exemplo n.º 17
0
def sample(path):
    def read_step_file(filename, verbosity=True):
        """ read the STEP file and returns a compound (based on OCC.Extend.DataExchange)
        filename: the file path
        return_as_shapes: optional, False by default. If True returns a list of shapes,
                          else returns a single compound
        verbosity: optional, False by default.
        """
        if not os.path.isfile(filename):
            raise FileNotFoundError("%s not found." % filename)

        step_reader = STEPControl_Reader()
        status = step_reader.ReadFile(filename)

        if status != IFSelect_RetDone:  # check status
            raise AssertionError("Error: can't read file.")

        if verbosity:
            failsonly = False
            step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity)
            step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity)

        _nbr = step_reader.TransferRoots()
        _nbs = step_reader.NbShapes()

        shape_to_return = step_reader.OneShape()  # a compound
        if shape_to_return is None:
            raise AssertionError("Shape is None.")
        elif shape_to_return.IsNull():
            raise AssertionError("Shape is Null.")

        return shape_to_return
    print('>> start sampler of type', SAMPLER_TYPES.string_dict[SAMPLER_TYPE])
    print('>> loading step file \'', path, '\'', sep='')
    compound = read_step_file(path, verbosity=False)
    shape_maps = generate_shape_maps(compound)

    print('>> generating framework and sampling...')
    framework = generate_mesh_framework(compound, shape_maps)
    face_meshes = sample_edges_in_framework(framework, shape_maps)

    mesh = MeshkD(path, face_meshes)
    for meta_block in mesh.meta_blocks:
        meta_block[MeshkD.SM_PARC] = PARAMETERIZE_FOR_ARC_LENGTH
        meta_block[MeshkD.SM_TYPE] = SAMPLER_TYPE
        meta_block[MeshkD.SM_SMFY] = SIMPLIFY_LINEAR_EDGES
        meta_block[MeshkD.SV_NOSM] = NUMBER_OF_SAMPLES
        meta_block[MeshkD.SV_MNOS] = MIN_NUMBER_OF_SAMPLES
        meta_block[MeshkD.SV_AFAK] = ADAPTIVE_REFINEMENT_FACTOR
        meta_block[MeshkD.SV_ARES] = ADAPTIVE_SCAN_RESOLUTION

    return mesh
Exemplo n.º 18
0
    def vizualization_all(self):
        # print(self.modules)
        self.display, self.start_display, self.add_menu, self.add_function_to_menu = init_display(
        )
        frame1 = read_step_file(self.name_frame)
        self.display.DisplayShape(frame1, color='GREEN', transparency=0.9)
        print(len(self.modules))
        for model in self.modules:
            self.display.DisplayShape(self.modules[model],
                                      color='RED',
                                      transparency=0.9)

        self.start_display()
Exemplo n.º 19
0
 def handler(self, file_path, is_bin):
     super(StpModel, self).handler(file_path, is_bin)
     # read stp file and convert to stl
     convert_stl_path = file_path + '.stl'
     try:
         shapes = read_step_file(file_path)
         StlModel.write_by_shapes(shapes, convert_stl_path)
         result = StlModel.convert_to_draco_gltf(file_path,
                                                 convert_stl_path, is_bin,
                                                 True)
     finally:
         self.clear_file(convert_stl_path)
     return result
Exemplo n.º 20
0
def import_filtered_output(event=None):
    outputFiles = glob.glob(os.path.join(OUTPUT_DIR, '*' + OUTPUT_EXTENSION))
    if len(outputFiles) > 0:
        display.EraseAll()
        for outputFile in outputFiles:
            compound = read_step_file(outputFile)
            color = Quantity_Color(random.random(), random.random(),
                                   random.random(), Quantity_TOC_RGB)
            display.DisplayColoredShape(compound, color)
        display.FitAll()
    else:
        display.EraseAll()
        print("import_output_file() error - No output file(s) found")
Exemplo n.º 21
0
    def add_folder(self):
        ex = App_folder()
        filename = ex.openFileNameDialog()
        # sys.exit(app.exec_())
        print(filename)
        from os import listdir
        from os.path import isfile, join
        onlyfiles = [f for f in listdir(filename) if isfile(join(filename, f))]
        print(onlyfiles)
        for name in onlyfiles:
            #self.path_modules[name] = filename
            self.modules[name] = read_step_file(filename+'/'+name)

        self.reload_modules()
Exemplo n.º 22
0
 def Exchange_stp_3xd(self):
     try:
         for file in self.file_list:
             if "stp" in file or "step" in file or "iges" in file :
                 try:
                     the_shape = read_step_file(file)
                     my_renderer = x3dom_renderer.X3DomRenderer("./")
                     name=file.split(".")
                     my_renderer.DisplayShape(the_shape,export_edges=True,color=(random(), random(), random()),file_name=name[0])
                 except:
                     pass
               
     except:
         pass
Exemplo n.º 23
0
def extract_shapes(step_path, scale, transform, rotate):
    shapes = []

    cad_file_path = pathlib.Path(step_path)
    if cad_file_path.is_file():
        shapes += extract_subshapes(
            read_step_file(str(cad_file_path), as_compound=False))
    elif cad_file_path.is_dir():
        shapes += walk_shapes(cad_file_path)
    else:
        raise Exception(
            f'step_ref "{step_path}" does not represent neither file or folder found on system'
        )

    shapes = [transform_shape(s, scale, transform, rotate) for s in shapes]
    return shapes
Exemplo n.º 24
0
    def __init__(self, frame, modules):

        self.name_frame = frame
        self.modules = {}
        self.names_models = []
        self.history_args = {}
        self.valume_inter_obj = defaultdict(dict)

        # for testing, remove later
        self.progress = []

        self.test_var = 40
        self.test_2_var = 0.0000
        self.current_body = ''
        self.iteration = 1

        self.d = 3.1
        self.px = 220 - self.d
        self.py = 220 - self.d
        self.pz = 246

        self.peep_factor = 0
        self.peep_list = {}

        self.dimensoins = {}
        self.profiles = {}
        self.valume_inter = {}
        self.inter_mass = 0
        # self.display, self.start_display, self.add_menu, self.add_function_to_menu = init_display()
        for model in modules:
            self.modules[model[2]] = read_step_file(
                os.path.join(model[0], model[1], model[2]))
            self.names_models.append(model[2])

        self.reserv_models = self.modules.copy()

        for model in self.modules:
            bbox = Bnd_Box()
            brepbndlib_Add(self.modules[model], bbox)
            xmin, ymin, zmin, xmax, ymax, zmax = bbox.Get()
            self.dimensoins[model] = [xmin, xmax, ymin, ymax, zmin, zmax]
            # print(model)
            self.profiles[model] = [self.glue_solids(self.modules[model])]
Exemplo n.º 25
0
    def __init__(
        self,
        name,
        geom,
        colour=None,
        opacity=1.0,
        mass: float = None,
        cog: Tuple[float, float, float] = None,
        metadata=None,
        units="m",
        ifc_elem=None,
        guid=None,
        material: Union[Material, str] = None,
        placement=Placement(),
        ifc_ref: IfcRef = None,
    ):

        super().__init__(
            name,
            guid=guid,
            metadata=metadata,
            units=units,
            ifc_elem=ifc_elem,
            placement=placement,
            ifc_ref=ifc_ref,
            colour=colour,
            opacity=opacity,
        )
        if type(geom) in (str, pathlib.WindowsPath, pathlib.PurePath, pathlib.Path):
            from OCC.Extend.DataExchange import read_step_file

            geom = read_step_file(str(geom))

        self._geom = geom
        self._mass = mass
        self._cog = cog
        if isinstance(material, Material):
            self._material = material
        else:
            self._material = get_material(material)

        self._bbox = None
Exemplo n.º 26
0
def main():
    input_folder = "{:08d}".format(int(sys.argv[1]))
    print(int(sys.argv[1]))
    filename = [file for file in os.listdir(os.path.join('/adarsh-lab/Aditya/ABCDataset',input_folder)) if os.path.splitext(file)[1] in ['.step', '.stp']][0]
    filename = os.path.join('/adarsh-lab/Aditya/ABCDataset',input_folder,filename)
    try:
        shp = read_step_file(filename)
        shape_type = get_type_as_string(shp)
        t =  TopologyFactory(shape_type) 
        shape = t.create_shape_object(shp)  
        shape.parse_shape()
        # seq=(os.path.splitext(filename)[0],"primitive",".json")

        out_filename = input_folder+'.json'
        out_filename = os.path.join('/adarsh-lab/Anjana/Points',out_filename)
        with open(out_filename, "w") as f:
            json.dump(shape.config, f, indent=4)

    except KeyError:
        print("Some Invalid Shape")
Exemplo n.º 27
0
    def open_frame(self, event=None):
        '''
        open step model of the frame
        :return: None
        '''

        app = QApplication(sys.argv)
        ex = App()
        filename = ex.openFileNameDialog()
        #sys.exit(app.exec_())
        print(os.path.split(filename)[-1])
        self.name_frame = filename

        self.frame = read_step_file(filename)

        #self.frame = read_step_file(filename)
        self.display.EraseAll()
        self.display.Context.RemoveAll(True)
        self.display.DisplayShape(self.frame, color='GREEN', transparency=0.9)
        self.display.FitAll()
Exemplo n.º 28
0
def Exchange_stp_3xd(file="aaa.stp",path="."):
    pass
    file=file
    global num_click
    num_click+=1
    try:
        os.mkdir(str(num_click))
    except:
        pass
    the_shape = read_step_file(file)
    path=str(num_click)
    my_renderer = x3dom_renderer.X3DomRenderer(path=path)
    my_renderer.DisplayShape(the_shape,export_edges=True,color=(random(), random(), random()))
    my_renderer.run()
    os.path.join(path, "index.html")
    path="."+"\\"+ path +"\\"+"index.html"
    print(path)

    with open(path,"r") as f:
          html=f.read()
          f.close()
    return html
Exemplo n.º 29
0
    def __init__(self, frame, modules, walls):

        #self.display, self.start_display, self.add_menu, self.add_function_to_menu = init_display()
        self.name_frame = frame
        self.modules = {}
        self.names_models = []
        self.history_args = {}
        self.progress = []
        self.valume_inter_obj = defaultdict(dict)

        # for testing, remove later

        self.inter_mass = 0
        self.reserv_models = {}
        # self.display, self.start_display, self.add_menu, self.add_function_to_menu = init_display()
        for model in modules:
            #self.reserv_models[model[2]] = read_step_file(os.path.join(model[0], model[1], model[2]))
            self.reserv_models[model] = read_step_file(modules[model])
            self.names_models.append(model)

        self.walls = walls
        '''for number, wall in enumerate(walls):
Exemplo n.º 30
0
def convert_stp_handler(file_path):
    # 1. read stp file and convert to stl
    convert_stl_path = file_path + '.stl'
    shapes = read_step_file(file_path)
    write_stl_by_shapes(shapes, convert_stl_path)
    return convert_stl_to_draco_gltf(file_path, convert_stl_path)
import os
import os.path
import time

from OCC.Core.Visualization import Tesselator

from OCC.Extend.TopologyUtils import TopologyExplorer
from OCC.Extend.DataExchange import read_step_file

# TEST 1 : one big STEP file into one single compound
# loads the step file
# load twice, not a copy/paste typo. It's because meshes are stored
# the second time, meshing time is much faster
print("TEST 1 ===")
step_file = os.path.join('..', 'demos', 'assets', 'models', 'RC_Buggy_2_front_suspension.stp')
shp = read_step_file(step_file)
shp2 = read_step_file(step_file)

# tesselate in single thread mode
print("Tesselate in single thread mode")
t_single = Tesselator(shp)
t0 = time.monotonic()
t_single.Compute(parallel=False, mesh_quality=0.5)
t1 = time.monotonic()
delta_single = t1-t0

# tesselate in parallel thread mode
print("Tesselate in parallelized mode")
t_multi = Tesselator(shp2)
t2 = time.monotonic()
t_multi.Compute(parallel=True, mesh_quality=0.5)