Beispiel #1
0
 def __init__(self, faces):
     topods_shell = TopoDS_Shell()
     builder = BRep_Builder()
     builder.MakeShell(topods_shell)
     for face in faces:
         builder.Add(topods_shell, face.object)
     self._shell = Shell(topods_shell)
Beispiel #2
0
def load_dxf(filename):
    doc = ezdxf.readfile(filename)
    edges = TopTools_HSequenceOfShape()

    for element in doc.modelspace():
        dxf_type = element.dxftype()
        d = element.dxf
        if dxf_type == 'LINE':
            node = Segment(points=[d.start, d.end]).render()
        elif dxf_type == 'ARC':
            node = Arc(position=d.center,
                       radius=d.radius,
                       alpha1=radians(d.start_angle),
                       alpha2=radians(d.end_angle)).render()
        elif dxf_type == 'CIRCLE':
            node = Circle(radius=d.radius, position=d.center).render()
        else:
            log.warning(f"Unhandled element: {element}")
            continue
        edges.Append(node)

    wires = ShapeAnalysis_FreeBounds.ConnectEdgesToWires_(edges, 1e-6, False)

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

    for i in range(1, wires.Size() + 1):
        builder.Add(shape, wires.Value(i))

    return [TopoShape(shape=shape)]
Beispiel #3
0
    def create_shape(self):
        d = self.declaration
        if not d.source:
            return
        if os.path.exists(os.path.expanduser(d.source)):
            svg = etree.parse(os.path.expanduser(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)

        bbox = self.get_bounding_box(shape)
        cx, cy = bbox.dx / 2, bbox.dy / 2

        # Move to position and align along direction axis
        t = gp_Trsf()
        axis = gp_Ax3()
        axis.SetDirection(d.direction.proxy)
        t.SetTransformation(axis)
        pos = d.position-(cx, cy, 0)
        t.SetTranslationPart(gp_Vec(*pos))

        self.shape = BRepBuilderAPI_Transform(shape, t, False).Shape()
Beispiel #4
0
    def to_shell(cls, entity):
        """
        Convert an entity to a shell.

        :param entity: The entity.

        :return: A shell.
        :rtype: OCCT.TopoDS.TopoDS_Shell

        :raise TypeError: If entity cannot be converted to a shell.
        """
        if isinstance(entity, TopoDS_Shell):
            return entity

        if cls.is_shape(entity) and entity.ShapeType() == TopAbs_SHELL:
            return TopoDS.Shell_(entity)

        if cls.is_shape(entity) and entity.ShapeType() == TopAbs_FACE:
            shell = TopoDS_Shell()
            builder = BRep_Builder()
            builder.MakeShell(shell)
            builder.Add(shell, entity)
            return shell

        raise TypeError('Failed to convert entity to a shell.')
Beispiel #5
0
    def to_compound(cls, entity):
        """
        Convert an entity to a compound.

        :param entity: The entity.

        :return: A compound
        :rtype: OCCT.TopoDS.TopoDS_Compound

        :raise TypeError: If entity cannot be converted to a compound.
        """
        if isinstance(entity, TopoDS_Compound):
            return entity

        if cls.is_shape(entity) and entity.ShapeType() == TopAbs_COMPOUND:
            return TopoDS.Compound_(entity)

        if cls.is_shape(entity):
            cp = TopoDS_Compound
            builder = BRep_Builder()
            builder.MakeCompound(cp)
            builder.Add(cp, entity)
            return cp

        raise TypeError('Failed to convert entity to a compound.')
Beispiel #6
0
 def load_stl(self, path):
     """ Load a stl model """
     builder = BRep_Builder()
     shape = TopoDS_Face()
     builder.MakeFace(shape)
     poly = RWStl.ReadFile_(path, None)
     builder.UpdateFace(shape, poly)
     return [TopoShape(shape=shape)]
Beispiel #7
0
 def __init__(self, shapes):
     topods_compound = TopoDS_Compound()
     builder = BRep_Builder()
     builder.MakeCompound(topods_compound)
     for shape in shapes:
         shape = Shape.to_shape(shape)
         if isinstance(shape, Shape):
             builder.Add(topods_compound, shape.object)
     self._cp = Compound(topods_compound)
 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
Beispiel #9
0
    def to_shell(self):
        """
        Create a shell from the face.

        :return: The shell.
        :rtype: afem.topology.entities.Shell
        """
        topods_shell = TopoDS_Shell()
        builder = BRep_Builder()
        builder.MakeShell(topods_shell)
        builder.Add(topods_shell, self.object)
        return Shell(topods_shell)
Beispiel #10
0
    def compound(shapes):
        """
        Create a compound from a list of shapes.

        :param shapes: List of shapes.
        :type: collections.Sequence(OCCT.TopoDS.TopoDS_Shape)
        """

        cp = TopoDS_Compound()
        builder = BRep_Builder()
        builder.MakeCompound(cp)
        for shape in shapes:
            builder.Add(cp, shape)
        return cp
Beispiel #11
0
    def by_face(face):
        """
        Create a shell from a face.

        :param afem.topology.entities.Face face: The face.

        :return: The shell.
        :rtype: afem.topology.entities.Shell
        """
        topods_shell = TopoDS_Shell()
        builder = BRep_Builder()
        builder.MakeShell(topods_shell)
        builder.Add(topods_shell, face.object)
        return Shell(topods_shell)
Beispiel #12
0
def load_brep(filename):
    """ Load a brep model """
    shape = TopoDS_Shape()
    builder = BRep_Builder()
    BRepTools.Read_(shape, filename, builder, None)
    # TODO: Load colors
    return [TopoShape(shape=shape)]
Beispiel #13
0
    def by_shapes(shapes):
        """
        Create a new compound from a collection of shapes.

        :param collections.Sequence(afem.topology.entities.Shape) shapes: The
            shapes.

        :return: The new compound.
        :rtype: afem.topology.entities.Compound
        """
        topods_compound = TopoDS_Compound()
        builder = BRep_Builder()
        builder.MakeCompound(topods_compound)
        for shape in shapes:
            if isinstance(shape, Shape):
                builder.Add(topods_compound, shape.object)
        return Compound(topods_compound)
Beispiel #14
0
    def import_step(self, fn):
        """
        Import a STEP file generated by the OpenVSP.

        :param str fn: The full path to the file.

        :return: None.

        :raise RuntimeError: If the file cannot be read.
        """
        print('Importing OpenVSP STEP file...')

        # Build a compound for geometric sets
        compound = TopoDS_Compound()
        BRep_Builder().MakeCompound(compound)

        # Read file
        step_reader = STEPControl_Reader()
        status = step_reader.ReadFile(fn)
        if status not in [IFSelect_RetVoid, IFSelect_RetDone]:
            raise RuntimeError("Unable to read OpenVSP STEP file.")

        # TODO Convert to desired units
        # Interface_Static.SetCVal_("xstep.cascade.unit", "SOME UNIT HERE")

        # Transfer
        # OpenVSP STEP files result in one root and one shape (a compound)
        step_reader.TransferRoot(1)
        master_shape = step_reader.Shape(1)

        # Iterate over master shape to find compounds for geometric sets. These
        # sets contain the surfaces that make up the component.
        iterator = TopoDS_Iterator(master_shape, True, True)
        more = True
        while iterator.More() and more:
            print('--Processing a component...')
            # The compound
            compound = iterator.Value()
            # Hack to handle single component for now...
            if compound.ShapeType() != TopAbs_COMPOUND:
                compound = master_shape
                more = False

            solid, is_valid, invalid_shapes = _build_solid(
                compound, self._divide)
            if is_valid:
                print('  Successfully built a solid.')
                self._solids.append(solid)
            else:
                print('  Failed to build a valid solid.')
                self._invalid.append(solid)
                self._invalid_shapes += invalid_shapes

            # Next shape
            iterator.Next()

        print('Finished.\n')
Beispiel #15
0
    def create_shape(self):
        d = self.declaration
        if not d.source:
            return
        if os.path.exists(os.path.expanduser(d.source)):
            svg = etree.parse(os.path.expanduser(d.source)).getroot()
        else:
            svg = etree.fromstring(d.source)
        node = self.doc = OccSvgDoc(element=svg)
        viewbox = svg.attrib.get('viewBox')
        x, y = (0, 0)
        sx, sy = (1, 1)
        if viewbox:
            ow = parse_unit(svg.attrib.get('width'))
            oh = parse_unit(svg.attrib.get('height'))
            x, y, iw, ih = map(parse_unit, viewbox.split())
            sx = ow / iw
            sy = oh / ih

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

        shapes = node.create_shape()
        for s in shapes:
            builder.Add(shape, s)

        bbox = self.get_bounding_box(shape)

        # Move to position and align along direction axis
        t = self.get_transform()
        if d.mirror:
            m = gp_Trsf()
            m.SetMirror(gp_Ax2(gp_Pnt(*bbox.center), gp_Dir(0, 1, 0)))
            t.Multiply(m)

        # Apply viewport scale
        s = gp_Trsf()
        s.SetValues(sx, 0, 0, x, 0, sy, 0, y, 0, 0, 1, 0)
        t.Multiply(s)

        self.shape = BRepBuilderAPI_Transform(shape, t, False).Shape()
Beispiel #16
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

        """

        # 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()
        # TODO: pyOCCT needs to support updating the reference
        # 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")
def simple_mesh():
    #
    # Create the 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))
        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)
Beispiel #18
0
    def read_brep(fn):
        """
        Read a BREP file and return as a single shape.

        :param str fn: Filename.

        :return: The shape.
        :rtype: OCCT.TopoDS.TopoDS_Shape
        """
        shape = TopoDS_Shape()
        builder = BRep_Builder()
        BRepTools.Read_(shape, fn, builder)
        return shape
Beispiel #19
0
def read_brep(fn):
    """
    Read a BREP file and return the shape.

    :param str fn: The filename.

    :return: The shape.
    :rtype: afem.topology.entities.Shape
    """
    shape = TopoDS_Shape()
    builder = BRep_Builder()
    BRepTools.Read_(shape, fn, builder)

    return Shape.wrap(shape)
Beispiel #20
0
    def update_shape(self, change=None):
        """ Create the toolkit shape for the proxy object.

        """
        d = self.declaration
        builder = self.builder = BRep_Builder()
        shape = TopoDS_Compound()
        builder.MakeCompound(shape)
        for c in self.children():
            if not isinstance(c, OccShape):
                continue
            if c.shape is None or not c.declaration.display:
                continue
            # Note infinite planes cannot be added to a compound!
            builder.Add(shape, c.shape)
        location = self.location = self._default_location()
        shape.Location(location)
        self.shape = shape
##
##This file is part of pythonOCC.
##
##pythonOCC is free software: you can redistribute it and/or modify
##it under the terms of the GNU Lesser General Public License as published by
##the Free Software Foundation, either version 3 of the License, or
##(at your option) any later version.
##
##pythonOCC is distributed in the hope that it will be useful,
##but WITHOUT ANY WARRANTY; without even the implied warranty of
##MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##GNU Lesser General Public License for more details.
##
##You should have received a copy of the GNU Lesser General Public License
##along with pythonOCC.  If not, see <http://www.gnu.org/licenses/>.

from OCC.Display.WebGl import x3dom_renderer
from OCCT.BRep import BRep_Builder
from OCCT.TopoDS import TopoDS_Shape
from OCCT.BRepTools import breptools_Read

# loads brep shape
cylinder_head = TopoDS_Shape()
builder = BRep_Builder()
breptools_Read(cylinder_head, '../assets/models/cylinder_head.brep', builder)

# render cylinder head in x3dom
my_renderer = x3dom_renderer.X3DomRenderer()
my_renderer.DisplayShape(cylinder_head)
my_renderer.render()
Beispiel #22
0
def _build_solid(compound, divide_closed):
    """
    Method to try and build a valid solid from an OpenVSP component.
    """
    # Get all the faces in the compound. The surfaces must be split. Discard
    # any with zero area.
    top_exp = TopExp_Explorer(compound, TopAbs_FACE)
    faces = []
    while top_exp.More():
        shape = top_exp.Current()
        face = CheckShape.to_face(shape)
        fprop = GProp_GProps()
        BRepGProp.SurfaceProperties_(face, fprop, 1.0e-7)
        a = fprop.Mass()
        if a <= 1.0e-7:
            top_exp.Next()
            continue
        faces.append(face)
        top_exp.Next()

    # Replace any planar B-Spline surfaces with planes
    non_planar_faces = []
    planar_faces = []
    for f in faces:
        hsrf = BRep_Tool.Surface_(f)
        try:
            is_pln = GeomLib_IsPlanarSurface(hsrf, 1.0e-7)
            if is_pln.IsPlanar():
                w = ShapeAnalysis.OuterWire_(f)
                # Fix the wire because they are usually degenerate edges in
                # the planar end caps.
                builder = BRepBuilderAPI_MakeWire()
                for e in ExploreShape.get_edges(w):
                    if LinearProps(e).length > 1.0e-7:
                        builder.Add(e)
                w = builder.Wire()
                fix = ShapeFix_Wire()
                fix.Load(w)
                geom_pln = Geom_Plane(is_pln.Plan())
                fix.SetSurface(geom_pln)
                fix.FixReorder()
                fix.FixConnected()
                fix.FixEdgeCurves()
                fix.FixDegenerated()
                w = fix.WireAPIMake()
                # Build the planar face
                fnew = BRepBuilderAPI_MakeFace(w, True).Face()
                planar_faces.append(fnew)
            else:
                non_planar_faces.append(f)
        except RuntimeError:
            non_planar_faces.append(f)

    # Make a compound of the faces
    shape = CreateShape.compound(non_planar_faces + planar_faces)

    # Split closed faces
    if divide_closed:
        divide = ShapeUpgrade_ShapeDivideClosed(shape)
        divide.Perform()
        shape = divide.Result()

    # Sew shape
    sew = BRepBuilderAPI_Sewing(1.0e-7)
    sew.Load(shape)
    sew.Perform()
    sewn_shape = sew.SewedShape()

    if sewn_shape.ShapeType() == TopAbs_FACE:
        face = sewn_shape
        sewn_shape = TopoDS_Shell()
        builder = BRep_Builder()
        builder.MakeShell(sewn_shape)
        builder.Add(sewn_shape, face)

    # Attempt to unify planar domains
    unify_shp = ShapeUpgrade_UnifySameDomain(sewn_shape, False, True, False)
    unify_shp.Build()
    shape = unify_shp.Shape()

    # Make solid
    shell = ExploreShape.get_shells(shape)[0]
    solid = ShapeFix_Solid().SolidFromShell(shell)

    # Limit tolerance
    FixShape.limit_tolerance(solid)

    # Check shape validity
    check_shp = BRepCheck_Analyzer(solid, True)
    if check_shp.IsValid():
        return solid, True, []
    else:
        invalid_shapes = _topods_iterator_check(solid, check_shp)
        return solid, False, invalid_shapes
def get_brep():
    cylinder_head = TopoDS_Shape()
    builder = BRep_Builder()
    breptools_Read(cylinder_head, '../assets/models/cylinder_head.brep',
                   builder)
    return cylinder_head
Beispiel #24
0
 def load_brep(self, path):
     """ Load a brep model """
     shape = TopoDS_Shape()
     builder = BRep_Builder()
     BRepTools.Read_(shape, path, builder, None)
     return [TopoShape(shape=shape)]
Beispiel #25
0
anEdge1OnSurf2 = BRepBuilderAPI_MakeEdge(anArc2, aCyl2)
anEdge2OnSurf2 = BRepBuilderAPI_MakeEdge(aSegment.Value(), 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
bottle = TopoDS_Compound()
aBuilder = BRep_Builder()
aBuilder.MakeCompound(bottle)
aBuilder.Add(bottle, myBody.Shape())
aBuilder.Add(bottle, myThreading)
print("bottle finished")

if __name__ == "__main__":
    from OCC.Display.SimpleGui import init_display
    display, start_display, add_menu, add_function_to_menu = init_display()
    display.DisplayColoredShape(bottle, update=True)
    start_display()