def occ_triangle_mesh(event=None):
    #
    # Mesh the shape
    #
    BRepMesh_IncrementalMesh(aShape, 0.1)
    builder = BRep_Builder()
    Comp = TopoDS_Compound()
    builder.MakeCompound(Comp)

    ex = TopExp_Explorer(aShape, TopAbs_FACE)
    while ex.More():
        F = topods_Face(ex.Current())
        L = TopLoc_Location()
        facing = (BRep_Tool().Triangulation(F, L)).GetObject()
        tab = facing.Nodes()
        tri = facing.Triangles()
        for i in range(1, facing.NbTriangles() + 1):
            trian = tri.Value(i)
            #print trian
            index1, index2, index3 = trian.Get()
            for j in range(1, 4):
                if j == 1:
                    M = index1
                    N = index2
                elif j == 2:
                    N = index3
                elif j == 3:
                    M = index2
                ME = BRepBuilderAPI_MakeEdge(tab.Value(M), tab.Value(N))
                if ME.IsDone():
                    builder.Add(Comp, ME.Edge())
        ex.Next()
    display.DisplayShape(Comp, update=True)
Exemple #2
0
def writeBRep(filename, shapeList):
    aRes = TopoDS_Compound()
    aBuilder = BRep_Builder()
    aBuilder.MakeCompound(aRes)
    for shape in shapeList:
        aBuilder.Add(aRes, shape)
    breptools_Write(aRes, filename)
Exemple #3
0
def regions2step(splinegons, filename, application_protocol='AP203'):
    """Writes splinegon regions to a STEP file.

    Parameters
    ----------
    splinegons : list
        Each member of the list is a `TopoDS_Face` object, the surface of a region.
    filename : str
        Name of the file the regions are saved into.
    application_protocol : {'AP203', 'AP214IS', 'AP242DIS'}, optional
        Version of schema used for the output STEP file. The default is 'AP203'.

    Returns
    -------
    None

    See Also
    --------
    splinegonize
    write_step_file

    """
    # Initialize a container that we will populate with the splinegons
    builder = BRep_Builder()
    compound = TopoDS_Compound()
    builder.MakeCompound(compound)
    # Combine multiple faces
    for splinegon in splinegons:
        builder.Add(compound, splinegon)
    # Write to STEP file
    write_step_file(compound, filename, application_protocol)
Exemple #4
0
    def export(self, event):
        """ Export the current model to stl """
        from OCC.StlAPI import StlAPI_Writer
        from OCC.BRepMesh import BRepMesh_IncrementalMesh
        #: TODO: All parts
        options = event.parameters.get('options')
        if not isinstance(options, ExportOptions):
            return False

        exporter = StlAPI_Writer()
        exporter.SetASCIIMode(not options.binary)

        #: Make a compound of compounds (if needed)
        compound = TopoDS_Compound()
        builder = BRep_Builder()
        builder.MakeCompound(compound)
        for part in self.parts:
            #: Must mesh the shape first
            if isinstance(part, Part):
                builder.Add(compound, part.proxy.shape)
            else:
                builder.Add(compound, part.proxy.shape.Shape())

        #: Build the mesh
        mesh = BRepMesh_IncrementalMesh(compound, options.linear_deflection,
                                        options.relative,
                                        options.angular_deflection)
        mesh.Perform()
        if not mesh.IsDone():
            raise ExportError("Failed to create the mesh")

        exporter.Write(compound, options.path)
Exemple #5
0
def make_shell(occfacelist):
    builder = BRep_Builder()
    shell = TopoDS_Shell()
    builder.MakeShell(shell)
    for occface in occfacelist:
        builder.Add(shell, occface)

    return shell
Exemple #6
0
def mkCompaund(f1,f2):
    u"""Об'єднує форми для експорту в формат BRep"""
    from OCC.BRep import BRep_Builder
    f=TopoDS_Compound()
    bb=BRep_Builder()
    bb.MakeCompound(f)
    bb.Add(f,f1)
    bb.Add(f,f2)
    return f
 def get_compound(self):
     """ Create and returns a compound from the _shapes list
     """
     # Create a compound
     compound = TopoDS_Compound()
     B = BRep_Builder()
     B.MakeCompound(compound)
     # Populate the compound
     for shape in self._shapes:
         B.Add(compound, shape)
     return compound
Exemple #8
0
    def update_shape(self, change):
        """ Create the toolkit shape for the proxy object.

        """
        builder = BRep_Builder()
        shape = self.shape
        builder.MakeCompound(shape)
        for s in self.shapes:
            if hasattr(s.shape, 'Shape'):
                builder.Add(shape, s.shape.Shape())
            elif s.shape is not None:
                builder.Add(shape, s.shape)
        self.builder = builder
Exemple #9
0
def read_step_file(filename, as_compound=True, verbosity=True):
    """ read the STEP file and returns a compound
    filename: the file path
    verbosity: optional, False by default.
    as_compound: True by default. If there are more than one shape at root,
    gather all shapes into one compound. Otherwise returns a list of shapes.
    """
    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
        if verbosity:
            failsonly = False
            step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity)
            step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity)
        transfer_result = step_reader.TransferRoots()
        if not transfer_result:
            raise AssertionError("Transfer failed.")
        _nbs = step_reader.NbShapes()
        if _nbs == 0:
            raise AssertionError("No shape to transfer.")
        elif _nbs == 1:  # most cases
            return step_reader.Shape(1)
        elif _nbs > 1:
            print("Number of shapes:", _nbs)
            shps = []
            # loop over root shapes
            for k in range(1, _nbs + 1):
                new_shp = step_reader.Shape(k)
                if not new_shp.IsNull():
                    shps.append(new_shp)
            if as_compound:
                builder = BRep_Builder()
                compound = TopoDS_Compound()
                builder.MakeCompound(compound)
                for s in shps:
                    builder.Add(compound, s)
                # shps = compound
                # compound, result = list_of_shapes_to_compound(shps)
                # if not result:
                #    print("Warning: all shapes were not added to the compound")
                return compound
            else:
                print("Warning, returns a list of shapes.")
                return shps
    else:
        raise AssertionError("Error: can't read file.")
    return None
Exemple #10
0
def make_compound(shape_array):
    """
    Creates a TopoDS_Compund from a list of TopoDS_Shapes

    :param shape_array: list of shapes
    :return: TopoDS_Compound
    """

    b = BRep_Builder()
    c = TopoDS_Compound()
    b.MakeCompound(c)
    for shape in shape_array:
        b.Add(c, shape)
    return c
def read_iges_file(filename, return_as_shapes=False, verbosity=False):
    """ read the IGES file and returns a compound
    filename: the file path
    return_as_shapes: optional, False by default. If True returns a list of shapes,
                      else returns a single compound
    verbosity: optionl, False by default.
    """
    assert os.path.isfile(filename)

    iges_reader = IGESControl_Reader()
    status = iges_reader.ReadFile(filename)

    _shapes = []

    if status == IFSelect_RetDone:  # check status
        if verbosity:
            failsonly = False
            iges_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity)
            iges_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity)
        iges_reader.TransferRoots()
        nbr = iges_reader.NbRootsForTransfer()
        for n in range(1, nbr + 1):
            nbs = iges_reader.NbShapes()
            if nbs == 0:
                print("At least one shape in IGES cannot be transfered")
            elif nbr == 1 and nbs == 1:
                aResShape = iges_reader.Shape(1)
                if aResShape.IsNull():
                    print("At least one shape in IGES cannot be transferred")
                else:
                    _shapes.append(aResShape)
            else:
                for i in range(1, nbs + 1):
                    aShape = iges_reader.Shape(i)
                    if aShape.IsNull():
                        print(
                            "At least one shape in STEP cannot be transferred")
                    else:
                        _shapes.append(aShape)
    # if not return as shapes
    # create a compound and store all shapes
    # TODO
    if not return_as_shapes:
        builder = BRep_Builder()
        Comp = TopoDS_Compound()
        builder.MakeCompound(Comp)
        for s in _shapes:
            builder.Add(Comp, s)
        _shapes = Comp
    return _shapes
Exemple #12
0
    def export(self):
        """ Export a DeclaraCAD model from an enaml file to an STL based on the
        given options.
        
        Parameters
        ----------
        options: declaracad.occ.plugin.ExportOptions
        
        """
        from OCC.BRep import BRep_Builder
        from OCC.BRepMesh import BRepMesh_IncrementalMesh
        from OCC.StlAPI import StlAPI_Writer
        from OCC.TopoDS import TopoDS_Compound
        
        # Make a compound of compounds (if needed)
        compound = TopoDS_Compound()
        builder = BRep_Builder()
        builder.MakeCompound(compound)
        
        # Load the enaml model file
        parts = load_model(self.filename)
        
        for part in parts:
            # Render the part from the declaration
            shape = part.render()
            
            # Must mesh the shape firsts
            if hasattr(shape, 'Shape'):
                builder.Add(compound, shape.Shape())
            else:
                builder.Add(compound, shape)

        #: Build the mesh
        exporter = StlAPI_Writer()
        exporter.SetASCIIMode(not self.binary)
        mesh = BRepMesh_IncrementalMesh(
            compound,
            self.linear_deflection,
            self.relative,
            self.angular_deflection
        )
        mesh.Perform()
        if not mesh.IsDone():
            raise RuntimeError("Failed to create the mesh")
        
        exporter.Write(compound, self.path)
            
        if not os.path.exists(self.path):
            raise RuntimeError("Failed to write shape")
Exemple #13
0
 def test_default_constructor_DEFINE_STANDARD_ALLOC(self):
     ''' OCE classes the defines standard alllocator can be instanciated
     if they're not abstract nor define any protected or private
     constructor '''
     BRep_Builder()
     TopoDS_Builder()
     ShapeAnalysis_Curve()
def get_brep():
    from OCC.BRep import BRep_Builder
    from OCC.BRepTools import breptools_Read
    from OCC.TopoDS import TopoDS_Shape

    cylinder_head = TopoDS_Shape()
    builder = BRep_Builder()
    breptools_Read(cylinder_head, './models/cylinder_head.brep', builder)
    return cylinder_head
Exemple #15
0
def step_reader(step_string):

    from OCC.StlAPI import StlAPI_Writer
    from OCC.STEPControl import STEPControl_Reader
    from OCC.BRep import BRep_Builder
    from OCC.TopoDS import TopoDS_Compound
    from OCC.IFSelect import IFSelect_RetDone, IFSelect_ItemsByEntity

    builder = BRep_Builder()
    comp = TopoDS_Compound()
    builder.MakeCompound(comp)

    stl_writer = StlAPI_Writer()
    stl_writer.SetASCIIMode(True)

    with io.tmpfile(contents=io.shapes()[shape_name][:][0]) as tmpfile:
        step_reader = STEPControl_Reader()

        status = step_reader.ReadFile(tmpfile[1])

        if status == IFSelect_RetDone:  # check status
            failsonly = False
            step_reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity)
            step_reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity)

            ok = step_reader.TransferRoot(1)
            nbs = step_reader.NbShapes()

            l = []
            for i in range(1, nbs + 1):
                shape = step_reader.Shape(i)

                builder.Add(comp, shape)

            with io.tmpfile(suffix='.stl') as tmpf:
                    stl_writer.Write(comp, tmpf[1])
                    tmpf[0].flush()

                    reader = vtk.vtkSTLReader()
                    reader.SetFileName(tmpf[1])
                    reader.Update()

                    return reader
Exemple #16
0
def occ_load_file(filename):
    """
    load in pythonocc a igs or step file

    :param filename: a filename with extension
    :return: a topods_shape
    """

    from OCC.STEPControl import STEPControl_Reader
    from OCC.IGESControl import IGESControl_Reader
    from OCC.BRep import BRep_Builder
    from OCC.TopoDS import TopoDS_Compound
    from OCC.IFSelect import IFSelect_RetDone,\
    IFSelect_ItemsByEntity

    reader_switch = {
        'stp': STEPControl_Reader,
        'step': STEPControl_Reader,
        'igs': IGESControl_Reader,
        'iges': IGESControl_Reader
    }

    builder = BRep_Builder()
    comp = TopoDS_Compound()
    builder.MakeCompound(comp)

    reader = reader_switch[os.path.splitext(filename)[1][1:].lower()]()

    status = reader.ReadFile(filename)

    if status == IFSelect_RetDone:  # check status
        failsonly = False
        reader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity)
        reader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity)

        ok = reader.TransferRoots()
        nbs = reader.NbShapes()

        for i in range(1, nbs + 1):
            shape = reader.Shape(i)
            builder.Add(comp, shape)

    return comp
Exemple #17
0
 def create_shape(self):
     d = self.declaration
     if not d.source:
         return
     if os.path.exists(d.source):
         svg = etree.parse(d.source).getroot()
     else:
         svg = etree.fromstring(d.source)
     node = OccSvgDoc(element=svg)
     
     builder = BRep_Builder()
     shape = TopoDS_Compound()
     builder.MakeCompound(shape)
     
     shapes = node.create_shape()
     for s in shapes:
         builder.Add(shape, s)
     self.wires = shapes
     self.shape = shape
Exemple #18
0
def simple_mesh():
    #
    # Create the shape
    #
    shape = BRepPrimAPI_MakeBox(200, 200, 200).Shape()
    theBox = BRepPrimAPI_MakeBox(200, 60, 60).Shape()
    theSphere = BRepPrimAPI_MakeSphere(gp_Pnt(100, 20, 20), 80).Shape()
    shape = BRepAlgoAPI_Fuse(theSphere, theBox).Shape()
    #
    # Mesh the shape
    #
    BRepMesh_IncrementalMesh(shape, 0.8)
    builder = BRep_Builder()
    comp = TopoDS_Compound()
    builder.MakeCompound(comp)

    bt = BRep_Tool()
    ex = TopExp_Explorer(shape, TopAbs_FACE)
    while ex.More():
        face = topods_Face(ex.Current())
        location = TopLoc_Location()
        facing = (bt.Triangulation(face, location)).GetObject()
        tab = facing.Nodes()
        tri = facing.Triangles()
        for i in range(1, facing.NbTriangles()+1):
            trian = tri.Value(i)
            index1, index2, index3 = trian.Get()
            for j in range(1, 4):
                if j == 1:
                    m = index1
                    n = index2
                elif j == 2:
                    n = index3
                elif j == 3:
                    m = index2
                me = BRepBuilderAPI_MakeEdge(tab.Value(m), tab.Value(n))
                if me.IsDone():
                    builder.Add(comp, me.Edge())
        ex.Next()
    display.EraseAll()
    display.DisplayShape(shape)
    display.DisplayShape(comp, update=True)
Exemple #19
0
    def vstep(step_str):

        step = int(step_str)

        positions = dpos_data[nbobjs * step:nbobjs * step + nbobjs, 2:]

        builder = BRep_Builder()
        comp = TopoDS_Compound()
        builder.MakeCompound(comp)

        for _id in range(positions.shape[0]):

            q0, q1, q2, q3, q4, q5, q6 = [float(x) for x in positions[_id, :]]

            obj = obj_by_id[_id + 1]

            q = Quaternion((q3, q4, q5, q6))

            for shape_name, avatar in zip(io.instances()[obj], avatars(obj)):
                offset = get_offset(obj, shape_name)
                p = q.rotate(offset[0])
                r = q * Quaternion(offset[1])

                tr = gp_Trsf()
                qocc = gp_Quaternion(r[1], r[2], r[3], r[0])
                tr.SetRotation(qocc)
                xyz = gp_XYZ(q0 + p[0], q1 + p[1], q2 + p[2])
                vec = gp_Vec(xyz)
                tr.SetTranslationPart(vec)
                loc = TopLoc_Location(tr)

                display.Context.SetLocation(avatar, loc)

                moved_shape = BRepBuilderAPI_Transform(
                    avatar.GetObject().Shape(), tr, True).Shape()

                builder.Add(comp, moved_shape)

            display.Context.UpdateCurrentViewer()

        write_step((step_str, comp))
Exemple #20
0
def discretize(shape, tol):
    """This method discretizes the OpenCascade shape.

    :param shape: Shape to discretize
    :type shape:
    :return: discretized face; profile coordinates; id of the surface the\
    coordinates belong to
    :rtype: OCC.TopoDS.TopoDS_Compound; numpy.ndarray; numpy.ndarray
    """
    BRepMesh_IncrementalMesh(shape, tol, False, 5)
    builder = BRep_Builder()
    comp = TopoDS_Compound()
    builder.MakeCompound(comp)

    bt = BRep_Tool()
    ex = TopExp_Explorer(shape, TopAbs_EDGE)
    edge_coords = np.zeros([0, 3])
    edge_ids = np.zeros([0], dtype=int)
    edge_id = 0
    while ex.More():
        edge = topods_Edge(ex.Current())
        location = TopLoc_Location()
        edging = (bt.Polygon3D(edge, location)).GetObject()
        tab = edging.Nodes()
        for i in range(1, edging.NbNodes() + 1):
            p = tab.Value(i)
            edge_coords = np.append(edge_coords,
                                    [[p.X(), p.Y(), p.Z()]],
                                    axis=0)
            edge_ids = np.append(edge_ids, edge_id)
            mv = BRepBuilderAPI_MakeVertex(p)
            if mv.IsDone():
                builder.Add(comp, mv.Vertex())
        edge_id += 1
        ex.Next()

    edge_coords = np.round(edge_coords, 8)
    return edge_coords, edge_ids
Exemple #21
0
def read_brep(filename):
    """
    Reads in a brep file

    :return: The shape
    """
    if not Path(filename).is_file():
        print("File not found: " + filename)
        raise FileNotFoundError(filename)

    b = BRep_Builder()
    shape = TopoDS_Shape()
    if not breptools_Read(shape, filename, b):
        raise RuntimeError("Cannot read brep file: " + filename)
    return shape
Exemple #22
0
def read_brep(brep_filepath):
    """
    This function writes a 3D model into brep format.
 
    Parameters
    ----------
    brep_filepath : str
        The file path of the brep file. 
        
    Returns
    -------
    occtopology : OCCtopology
        Geometries read from the brep.
        OCCtopology includes: OCCshape, OCCcompound, OCCcompsolid, OCCsolid, OCCshell, OCCface, OCCwire, OCCedge, OCCvertex 
    """
    from OCC.BRepTools import breptools_Read
    from OCC.TopoDS import TopoDS_Shape
    from OCC.BRep import BRep_Builder

    shape = TopoDS_Shape()
    builder = BRep_Builder()
    breptools_Read(shape, brep_filepath, builder)
    return shape
def draw_lineandvertices(event=None):
    Line_1 = TopoDS_Shape()
    Vertex_1 = TopoDS_Shape()
    Vertex_2 = TopoDS_Shape()
    builder = BRep_Builder()
    builder1 = BRep_Builder()
    compound = TopoDS_Compound()
    builder1.MakeCompound(compound)
    breptools_Read(Line_1, 'Line_1.brep', builder)
    breptools_Read(Vertex_1, 'Vertex_1.brep', builder)
    breptools_Read(Vertex_2, 'Vertex_2.brep', builder)
    builder1.Add(compound,Line_1)
    builder1.Add(compound,Vertex_1)
    builder1.Add(compound,Vertex_2)

    #display.DisplayShape({Line_1, Vertex_1, Vertex_2}, update=True)
    #display.DisplayShape(Group_1, update=True)
    display.DisplayShape(compound, update=True)
    breptools_Write(compound, 'compound.brep')

    display.FitAll()
Exemple #24
0
point = gp_Pnt(X1, Y1, Z1)
sphere_r1 = BRepPrimAPI_MakeSphere(point, radius)
sphere_r1_shape = sphere_r1.Shape()

radius = 0.01
sphere_r01 = BRepPrimAPI_MakeSphere(point, radius)
sphere_r01_shape = sphere_r01.Shape()

radius = 0.001
sphere_r001 = BRepPrimAPI_MakeSphere(point, radius)
sphere_r001_shape = sphere_r001.Shape()

from OCC.BRep import BRep_Builder
from OCC.TopoDS import TopoDS_Compound

builder = BRep_Builder()
comp = TopoDS_Compound()
builder.MakeCompound(comp)

from OCC.BRep import BRep_Builder
from OCC.TopoDS import TopoDS_Compound

builder.Add(comp, sphere_r1_shape)

radius = 1.0
point = gp_Pnt(4., 0., 0.)
sphere_r1_t = BRepPrimAPI_MakeSphere(point, radius)
sphere_r1_t_shape = sphere_r1_t.Shape()

builder.Add(comp, sphere_r1_t_shape)
anEdge2OnSurf2 = BRepBuilderAPI_MakeEdge(aSegment.Value(),
                                         Handle_Geom_Surface(aCyl2))

threadingWire1 = BRepBuilderAPI_MakeWire(anEdge1OnSurf1.Edge(),
                                         anEdge2OnSurf1.Edge())
threadingWire2 = BRepBuilderAPI_MakeWire(anEdge1OnSurf2.Edge(),
                                         anEdge2OnSurf2.Edge())

# Compute the 3D representations of the edges/wires
breplib.BuildCurves3d(threadingWire1.Shape())
breplib.BuildCurves3d(threadingWire2.Shape())

# Create the surfaces of the threading
aTool = BRepOffsetAPI_ThruSections(True)
aTool.AddWire(threadingWire1.Wire())
aTool.AddWire(threadingWire2.Wire())
aTool.CheckCompatibility(False)
myThreading = aTool.Shape()

# Build the resulting compound
aRes = TopoDS_Compound()
aBuilder = BRep_Builder()
aBuilder.MakeCompound(aRes)
aBuilder.Add(aRes, myBody.Shape())
aBuilder.Add(aRes, myThreading)

display, start_display, add_menu, add_function_to_menu = init_display('wx')
display.DisplayColoredShape(aRes)

start_display()
Exemple #26
0
import ifcopenshell.geom


# Specify to return pythonOCC shapes from ifcopenshell.geom.create_shape()
settings = ifcopenshell.geom.settings()
settings.set(settings.USE_PYTHON_OPENCASCADE, True)

# Initialize a graphical display window
occ_display = ifcopenshell.geom.utils.initialize_display()

# Open the IFC file using IfcOpenShell
ifc_file = ifcopenshell.open("castest_01.ifc")

# Making compound
compound = TopoDS_Compound()
builder = BRep_Builder()
builder.MakeCompound(compound)

# Display the geometrical contents of the file using Python OpenCascade
products = ifc_file.by_type("IfcProduct")
for product in products:
    # Adding a element to compund maked
    if product.is_a("IfcOpeningElement"): continue
    if product.Representation:
        shape = ifcopenshell.geom.create_shape(settings, product).geometry
        display_shape = ifcopenshell.geom.utils.display_shape(shape)
        builder.Add(compound,shape)
        if product.is_a("IfcPlate"):
            # Plates are the transparent parts of the window assembly
            # in the IfcOpenHouse model
            ifcopenshell.geom.utils.set_shape_transparency(display_shape, 0.8)
Exemple #27
0
    def write(self, mesh_points, filename, tolerance=None):
        """
		Writes a output file, called filename, copying all the structures from self.filename but
		the coordinates. mesh_points is a matrix that contains the new coordinates to
		write in the output file.

		:param numpy.ndarray mesh_points: it is a `n_points`-by-3 matrix containing
			the coordinates of the points of the mesh
		:param string filename: name of the output file.
		:param float tolerance: tolerance for the construction of the faces and wires
			in the write function. If not given it uses `self.tolerance`.
		"""
        self._check_filename_type(filename)
        self._check_extension(filename)
        self._check_infile_instantiation()

        self.outfile = filename

        if tolerance is not None:
            self.tolerance = tolerance

        # cycle on the faces to update the control points position
        # init some quantities
        faces_explorer = TopExp_Explorer(self.shape, TopAbs_FACE)
        n_faces = 0
        control_point_position = self._control_point_position

        compound_builder = BRep_Builder()
        compound = OCC.TopoDS.TopoDS_Compound()
        compound_builder.MakeCompound(compound)

        while faces_explorer.More():
            # similar to the parser method
            face = OCC.TopoDS.topods_Face(faces_explorer.Current())
            nurbs_converter = BRepBuilderAPI_NurbsConvert(face)
            nurbs_converter.Perform(face)
            nurbs_face = nurbs_converter.Shape()
            face_aux = OCC.TopoDS.topods_Face(nurbs_face)
            brep_face = BRep_Tool.Surface(OCC.TopoDS.topods_Face(nurbs_face))
            bspline_face = geomconvert_SurfaceToBSplineSurface(brep_face)
            occ_face = bspline_face.GetObject()

            n_poles_u = occ_face.NbUPoles()
            n_poles_v = occ_face.NbVPoles()

            i = 0
            for pole_u_direction in range(n_poles_u):
                for pole_v_direction in range(n_poles_v):
                    control_point_coordinates = mesh_points[
                        i + control_point_position[n_faces], :]
                    point_xyz = gp_XYZ(*control_point_coordinates)

                    gp_point = gp_Pnt(point_xyz)
                    occ_face.SetPole(pole_u_direction + 1,
                                     pole_v_direction + 1, gp_point)
                    i += 1

            # construct the deformed wire for the trimmed surfaces
            wire_maker = BRepBuilderAPI_MakeWire()
            tol = ShapeFix_ShapeTolerance()
            brep = BRepBuilderAPI_MakeFace(occ_face.GetHandle(),
                                           self.tolerance).Face()
            brep_face = BRep_Tool.Surface(brep)

            # cycle on the edges
            edge_explorer = TopExp_Explorer(nurbs_face, TopAbs_EDGE)
            while edge_explorer.More():
                edge = OCC.TopoDS.topods_Edge(edge_explorer.Current())
                # edge in the (u,v) coordinates
                edge_uv_coordinates = BRep_Tool.CurveOnSurface(edge, face_aux)
                # evaluating the new edge: same (u,v) coordinates, but different (x,y,x) ones
                edge_phis_coordinates_aux = BRepBuilderAPI_MakeEdge(\
                 edge_uv_coordinates[0], brep_face)
                edge_phis_coordinates = edge_phis_coordinates_aux.Edge()
                tol.SetTolerance(edge_phis_coordinates, self.tolerance)
                wire_maker.Add(edge_phis_coordinates)
                edge_explorer.Next()

            # grouping the edges in a wire
            wire = wire_maker.Wire()

            # trimming the surfaces
            brep_surf = BRepBuilderAPI_MakeFace(occ_face.GetHandle(),
                                                wire).Shape()
            compound_builder.Add(compound, brep_surf)
            n_faces += 1
            faces_explorer.Next()
        self.write_shape_to_file(compound, self.outfile)
Exemple #28
0
def load_brep(BRepFile):
    BRepShape = TopoDS_Shape()
    builder = BRep_Builder()
    breptools_Read(BRepShape, BRepFile, builder)

    return BRepShape
Exemple #29
0
    # Number of points
    n = 100000

    # List for storing TopoDS_Shape instances of vertices if required.
    vertexList = []

    # Set the side length
    side_length = 10.0
    # The side length of the box that contains the shapes that will be tested
    xSideLength = ySideLength = zSideLength = 0.0
    xMin = xMax = yMin = yMax = zMin = zMax = 0.0

    # Read the file to get the shape to be sampled.
    shape = TopoDS_Shape()
    builder = BRep_Builder()
    breptools_Read(shape, "cubeWithHole.brep", builder)

    # Loop over the shape pulled from the input and look for solids.
    solids = []  # A list for storing solids from the file
    i = 0  # A counter for writing vertices/points
    allPointsDataFrame = pd.DataFrame([])  # A dataframe for ALL points
    # OpenCASCADE can only successfully execute point inclusion queries if the
    # shape in question is a full solid, which is defined in their topology as
    # TopAbs_SOLID. Each solid in the file can sampled individually by pulling
    # it from the compound.
    if shape.ShapeType() != TopAbs_SOLID:
        # Create a topology explorer and pull all the solids from the shape
        explorer = TopExp_Explorer(shape, TopAbs_SOLID)
        # Loop over all the solids
        while explorer.More():
Exemple #30
0
 def load_brep(self, path):
     """ Load a brep model """
     shape = TopoDS_Shape()
     builder = BRep_Builder()
     breptools_Read(shape, path, builder)
     return shape