def test_list(self):
     '''
     Test python lists features
     '''
     P1 = gp_Pnt(1, 2, 3)
     P2 = gp_Pnt(2, 3, 4)
     P3 = gp_Pnt(5, 7, 8)
     l = [P1, P2]
     self.assertEqual(P1 in l, True)
     self.assertNotEqual(P3 in l, True)
     self.assertEqual(l.index(P1), 0)
     self.assertEqual(l.index(P2), 1)
     # Do the same for Vertices (TopoDS_Shape has
     # a HashCode() method overloaded
     V1 = BRepBuilderAPI_MakeVertex(P1).Vertex()
     V2 = BRepBuilderAPI_MakeVertex(P2).Vertex()
     V3 = BRepBuilderAPI_MakeVertex(P3).Vertex()
     vl = [V1, V2]
     self.assertEqual(V1 in vl, True)
     self.assertNotEqual(V3 in vl, True)
     # index test()
     self.assertEqual(vl.index(V1), 0)
     self.assertEqual(vl.index(V2), 1)
     # reverse() test
     vl.reverse()
     self.assertEqual(vl.index(V1), 1)
     self.assertEqual(vl.index(V2), 0)
Exemplo n.º 2
0
def dist_point_to_edge(pnt, edge):    
    assert pnt is not None
    
    vert_maker = BRepBuilderAPI_MakeVertex(gp_Pnt(pnt[0], pnt[1], pnt[2]))
    dss = BRepExtrema_DistShapeShape(vert_maker.Vertex(), edge)
    if not dss.IsDone():
        print('BRepExtrema_ExtPC not done')
        return None, None

    if dss.NbSolution() < 1:
        print('no nearest points found')
        return None, None
    return dss.Value(), as_list(dss.PointOnShape2(1))
Exemplo n.º 3
0
    def AddVerticesToScene(self, pnt_list, vertex_color, vertex_width=5):
        """ shp is a list of gp_Pnt
        """
        vertices_list = []  # will be passed to pythreejs
        BB = BRep_Builder()
        compound = TopoDS_Compound()
        BB.MakeCompound(compound)

        for vertex in pnt_list:
            vertex_to_add = BRepBuilderAPI_MakeVertex(vertex).Shape()
            BB.Add(compound, vertex_to_add)
            vertices_list.append([vertex.X(), vertex.Y(), vertex.Z()])

        # map the Points and the AIS_PointCloud
        # and to the dict of shapes, to have a mapping between meshes and shapes
        point_cloud_id = "%s" % uuid.uuid4().hex
        self._shapes[point_cloud_id] = compound

        vertices_list = np.array(vertices_list, dtype=np.float32)
        attributes = {
            "position": BufferAttribute(vertices_list, normalized=False)
        }
        mat = PointsMaterial(color=vertex_color,
                             sizeAttenuation=True,
                             size=vertex_width)
        geom = BufferGeometry(attributes=attributes)
        points = Points(geometry=geom, material=mat, name=point_cloud_id)
        return points
Exemplo n.º 4
0
def make_vertex(pt):
    """
    """
    gpPnt = gp_Pnt(pt[0], pt[1], pt[2])
    vertex = BRepBuilderAPI_MakeVertex(gpPnt).Vertex()

    return vertex
Exemplo n.º 5
0
def as_occ(pnt, occ_type):
    if occ_type not in [TopoDS_Vertex, gp_Pnt, gp_Dir, gp_Vec]:
        return None
     
    if occ_type is TopoDS_Vertex:
        return BRepBuilderAPI_MakeVertex(gp_Pnt(pnt[0], pnt[1], pnt[2])).Vertex()
    else:
        return occ_type(pnt[0], pnt[1], pnt[2])
Exemplo n.º 6
0
def face_polygon(pnts):
    wire_maker = BRepBuilderAPI_MakeWire()
    verts = [BRepBuilderAPI_MakeVertex(as_occ(pnt, gp_Pnt)).Vertex() for pnt in pnts]
    for i in range(len(verts)):
        j = (i + 1) % len(verts)
        wire_maker.Add(BRepBuilderAPI_MakeEdge(verts[i], verts[j]).Edge())
        
    return BRepBuilderAPI_MakeFace(wire_maker.Wire()).Face() 
Exemplo n.º 7
0
def getShapeSkin(pntStart, wires, pntEnd):

    # Initialize and build
    skiner = BRepOffsetAPI_ThruSections()
    skiner.SetSmoothing(True)
    #skiner.SetMaxDegree(5)

    vstart = BRepBuilderAPI_MakeVertex(pntStart).Vertex()
    skiner.AddVertex(vstart)

    for wire in wires:
        skiner.AddWire(wire)

    vend = BRepBuilderAPI_MakeVertex(pntEnd).Vertex()
    skiner.AddVertex(vend)

    skiner.Build()

    return skiner.Shape()
Exemplo n.º 8
0
    def by_point(pnt):
        """
        Create a vertex by a point.

        :param point_like pnt: The point.

        :return: The vertex.
        :rtype: afem.topology.entities.Vertex
        """
        pnt = CheckGeom.to_point(pnt)
        return Vertex(BRepBuilderAPI_MakeVertex(pnt).Vertex())
Exemplo n.º 9
0
def min_distance(pt, face):
    """
    Minimum distance between point and face
    """

    gpPnt = gp_Pnt(pt[0], pt[1], pt[2])
    vertex = BRepBuilderAPI_MakeVertex(gpPnt).Vertex()
    dis = BRepExtrema_DistShapeShape(vertex, face)

    p = dis.PointOnShape2(1)
    d = dis.Value()
    return [d, p]
Exemplo n.º 10
0
def make_vertex(pnt):
    if isinstance(pnt, gp_Pnt2d):
        vertex = BRepBuilderAPI_MakeVertex(gp_Pnt(pnt.X(), pnt.Y(), 0))
    else:
        vertex = BRepBuilderAPI_MakeVertex(pnt)
    vertex.Build()
    return vertex.Shape()
Exemplo n.º 11
0
def edge(event=None):
    # The blud edge
    BlueEdge = BRepBuilderAPI_MakeEdge(gp_Pnt(-80, -50, -20),
                                       gp_Pnt(-30, -60, -60))
    V1 = BRepBuilderAPI_MakeVertex(gp_Pnt(-20, 10, -30))
    V2 = BRepBuilderAPI_MakeVertex(gp_Pnt(10, 7, -25))
    YellowEdge = BRepBuilderAPI_MakeEdge(V1.Vertex(), V2.Vertex())

    #The white edge
    line = gp_Lin(gp_Ax1(gp_Pnt(10, 10, 10), gp_Dir(1, 0, 0)))
    WhiteEdge = BRepBuilderAPI_MakeEdge(line, -20, 10)

    #The red edge
    Elips = gp_Elips(gp_Ax2(gp_Pnt(10, 0, 0), gp_Dir(1, 1, 1)), 60, 30)
    RedEdge = BRepBuilderAPI_MakeEdge(Elips, 0, math.pi/2)

    # The green edge and the both extreme vertex
    P1 = gp_Pnt(-15, 200, 10)
    P2 = gp_Pnt(5, 204, 0)
    P3 = gp_Pnt(15, 200, 0)
    P4 = gp_Pnt(-15, 20, 15)
    P5 = gp_Pnt(-5, 20, 0)
    P6 = gp_Pnt(15, 20, 0)
    P7 = gp_Pnt(24, 120, 0)
    P8 = gp_Pnt(-24, 120, 12.5)
    array = TColgp_Array1OfPnt(1, 8)
    array.SetValue(1, P1)
    array.SetValue(2, P2)
    array.SetValue(3, P3)
    array.SetValue(4, P4)
    array.SetValue(5, P5)
    array.SetValue(6, P6)
    array.SetValue(7, P7)
    array.SetValue(8, P8)
    curve = Geom_BezierCurve(array)
    ME = BRepBuilderAPI_MakeEdge(curve)
    GreenEdge = ME
    V3 = ME.Vertex1()
    V4 = ME.Vertex2()

    display.DisplayColoredShape(BlueEdge.Edge(), 'BLUE')
    display.DisplayShape(V1.Vertex())
    display.DisplayShape(V2.Vertex())
    display.DisplayColoredShape(WhiteEdge.Edge(), 'WHITE')
    display.DisplayColoredShape(YellowEdge.Edge(), 'YELLOW')
    display.DisplayColoredShape(RedEdge.Edge(), 'RED')
    display.DisplayColoredShape(GreenEdge.Edge(), 'GREEN')
    display.DisplayShape(V3)
    display.DisplayShape(V4, update=True)
Exemplo n.º 12
0
    def getDaoSkinningSurface(self, offset):

        limitPoints = self.getCached('getDaoOffsetPoints', offset)
        beginPoint = limitPoints['Begin']
        endPoint = limitPoints['End']

        skinner = BRepOffsetAPI_ThruSections(True)
        skinner.SetSmoothing(True)

        beginVertex = BRepBuilderAPI_MakeVertex(beginPoint).Vertex()
        skinner.AddVertex(beginVertex)

        ks = self.aSkinningSlicesKs
        for i in range(len(ks)):
            sliceWire = self.getCached('getDaoSliceWire', offset, ks[i])
            skinner.AddWire(sliceWire)

        endVertex = BRepBuilderAPI_MakeVertex(endPoint).Vertex()
        skinner.AddVertex(endVertex)

        skinner.Build()
        surface = skinner.Shape()

        return surface
Exemplo n.º 13
0
def makePoints():
    global aPnt1, aPnt2, aPnt3, aPnt4, aPnt5
    aPnt1 = gp_Pnt(-width / 2., 0, 0)
    aPnt2 = gp_Pnt(-width / 2., -thickness / 4., 0)
    aPnt3 = gp_Pnt(0, -thickness / 2., 0)
    aPnt4 = gp_Pnt(width / 2., -thickness / 4., 0)
    aPnt5 = gp_Pnt(width / 2., 0, 0)
    # points aren't visible on screen
    # make vertices in order to see them
    V1 = BRepBuilderAPI_MakeVertex(aPnt1)
    V2 = BRepBuilderAPI_MakeVertex(aPnt2)
    V3 = BRepBuilderAPI_MakeVertex(aPnt3)
    V4 = BRepBuilderAPI_MakeVertex(aPnt4)
    V5 = BRepBuilderAPI_MakeVertex(aPnt5)
    # add dummy vertex above bottle just to set view size
    V6 = BRepBuilderAPI_MakeVertex(gp_Pnt(0, 0, height * 1.1))
    return (V1, V2, V3, V4, V5, V6)
Exemplo n.º 14
0
    def display_geom(self, geom, rgb=None, transparency=None, material=None):
        """
        Display a geometric entity.
        :param geom: The geometry.
        :type geom: OCC.Core.gp.gp_Pnt or OCC.Core.Geom.Geom_Curve or
            OCC.Core.Geom.Geom_Surface
        :param rgb: The RGB color (r, g, b).
        :type rgb: collections.Sequence(float) or OCC.Core.Quantity.Quantity_Color
        :param float transparency: The transparency (0 to 1).
        :param OCC.Core.Graphic3d.Graphic3d_NameOfMaterial material: The material.
        :return: The AIS_Shape created for the geometry. Returns *None* if the
            entity cannot be converted to a shape.
        :rtype: OCC.Core.AIS.AIS_Shape or None
        """
        if isinstance(geom, gp_Pnt):
            shape = BRepBuilderAPI_MakeVertex(geom).Vertex()
        elif isinstance(geom, Geom_Curve):
            shape = BRepBuilderAPI_MakeEdge(geom).Edge()
        elif isinstance(geom, Geom_Surface):
            shape = BRepBuilderAPI_MakeFace(geom, 1.0e-7).Face()
        else:
            return None

        return self.display_shape(shape, rgb, transparency, material)
Exemplo n.º 15
0
def makePoints(event=None):
    global aPnt1, aPnt2, aPnt3, aPnt4, aPnt5
    aPnt1 = gp_Pnt(-width / 2., 0, 0)
    aPnt2 = gp_Pnt(-width / 2., -thickness / 4., 0)
    aPnt3 = gp_Pnt(0, -thickness / 2., 0)
    aPnt4 = gp_Pnt(width / 2., -thickness / 4., 0)
    aPnt5 = gp_Pnt(width / 2., 0, 0)
    V1 = BRepBuilderAPI_MakeVertex(aPnt1)
    V2 = BRepBuilderAPI_MakeVertex(aPnt2)
    V3 = BRepBuilderAPI_MakeVertex(aPnt3)
    V4 = BRepBuilderAPI_MakeVertex(aPnt4)
    V5 = BRepBuilderAPI_MakeVertex(aPnt5)
    # add dummy point above bottle just to set view size
    V6 = BRepBuilderAPI_MakeVertex(gp_Pnt(0, 0, height * 1.1))
    display.DisplayShape(V1.Vertex())
    display.DisplayShape(V2.Vertex())
    display.DisplayShape(V3.Vertex())
    display.DisplayShape(V4.Vertex())
    display.DisplayShape(V5.Vertex())
    display.DisplayShape(V6.Vertex())
    display.FitAll()
    display.EraseAll()
    display.DisplayShape(V1.Vertex())
    display.DisplayShape(V2.Vertex())
    display.DisplayShape(V3.Vertex())
    display.DisplayShape(V4.Vertex())
    display.DisplayShape(V5.Vertex())
    display.Repaint()
    win.statusBar().showMessage('Make Points complete')
Exemplo n.º 16
0
    def DisplayShape(self,
                     shapes,
                     material=None,
                     texture=None,
                     color=None,
                     transparency=None,
                     update=False):
        """ display one or a set of displayable objects
        """
        ais_shapes = []  # the list of all displayed shapes

        if issubclass(shapes.__class__, gp_Pnt):
            # if a gp_Pnt is passed, first convert to vertex
            vertex = BRepBuilderAPI_MakeVertex(shapes)
            shapes = [vertex.Shape()]
        elif isinstance(shapes, gp_Pnt2d):
            vertex = BRepBuilderAPI_MakeVertex(
                gp_Pnt(shapes.X(), shapes.Y(), 0))
            shapes = [vertex.Shape()]
        elif isinstance(shapes, Geom_Surface):
            bounds = True
            toldegen = 1e-6
            face = BRepBuilderAPI_MakeFace()
            face.Init(shapes, bounds, toldegen)
            face.Build()
            shapes = [face.Shape()]
        elif isinstance(shapes, Geom_Curve):
            edge = BRepBuilderAPI_MakeEdge(shapes)
            shapes = [edge.Shape()]
        elif isinstance(shapes, Geom2d_Curve):
            edge2d = BRepBuilderAPI_MakeEdge2d(shapes)
            shapes = [edge2d.Shape()]
        # if only one shapes, create a list with a single shape
        if not isinstance(shapes, list):
            shapes = [shapes]
        # build AIS_Shapes list
        for shape in shapes:
            if material or texture:
                if texture:
                    shape_to_display = AIS_TexturedShape(shape)
                    filename, toScaleU, toScaleV, toRepeatU, toRepeatV, originU, originV = texture.GetProperties(
                    )
                    shape_to_display.SetTextureFileName(
                        TCollection_AsciiString(filename))
                    shape_to_display.SetTextureMapOn()
                    shape_to_display.SetTextureScale(True, toScaleU, toScaleV)
                    shape_to_display.SetTextureRepeat(True, toRepeatU,
                                                      toRepeatV)
                    shape_to_display.SetTextureOrigin(True, originU, originV)
                    shape_to_display.SetDisplayMode(3)
                elif material:
                    shape_to_display = AIS_Shape(shape)
                    shape_to_display.SetMaterial(
                        Graphic3d_MaterialAspect(material))
            else:
                # TODO: can we use .Set to attach all TopoDS_Shapes
                # to this AIS_Shape instance?
                shape_to_display = AIS_Shape(shape)

            ais_shapes.append(shape_to_display)

        # if not SOLO:
        #     # computing graphic properties is expensive
        #     # if an iterable is found, so cluster all TopoDS_Shape under
        #     # an AIS_MultipleConnectedInteractive
        #     #shape_to_display = AIS_MultipleConnectedInteractive()
        #     for ais_shp in ais_shapes:
        #         # TODO : following line crashes with oce-0.18
        #         # why ? fix ?
        #         #shape_to_display.Connect(i)
        #         self.Context.Display(ais_shp, False)
        # set the graphic properties
        if material is None:
            #The default material is too shiny to show the object
            #color well, so I set it to something less reflective
            for shape_to_display in ais_shapes:
                shape_to_display.SetMaterial(
                    Graphic3d_MaterialAspect(Graphic3d_NOM_NEON_GNC))
        if color:
            if isinstance(color, str):
                color = get_color_from_name(color)
            elif isinstance(color, int):
                color = Quantity_Color(color)
            for shp in ais_shapes:
                self.Context.SetColor(shp, color, False)
        if transparency:
            for shape_to_display in ais_shapes:
                shape_to_display.SetTransparency(transparency)
        # display the shapes
        for shape_to_display in ais_shapes:
            self.Context.Display(shape_to_display, False)
        if update:
            # especially this call takes up a lot of time...
            self.FitAll()
            self.Repaint()

        return ais_shapes
Exemplo n.º 17
0
Arquivo: blade.py Projeto: o4fr/BladeX
    def _write_blade_errors(self, upper_face, lower_face, errors):
        """
        Private method to write the errors between the generated foil points in
        3D space from the parametric transformations, and their projections on
        the generated blade faces from the OCC algorithm.

        :param string upper_face: if string is passed then the method generates
            the blade upper surface using the BRepOffsetAPI_ThruSections
            algorithm, then exports the generated CAD into .iges file holding
            the name <upper_face_string>.iges
        :param string lower_face: if string is passed then the method generates
            the blade lower surface using the BRepOffsetAPI_ThruSections
            algorithm, then exports the generated CAD into .iges file holding
            the name <lower_face_string>.iges
        :param string errors: if string is passed then the method writes out
            the distances between each discrete point used to construct the
            blade and the nearest point on the CAD that is perpendicular to
            that point
        """
        from OCC.Core.gp import gp_Pnt
        from OCC.Core.BRepBuilderAPI import BRepBuilderAPI_MakeVertex
        from OCC.Core.BRepExtrema import BRepExtrema_DistShapeShape

        output_string = '\n'
        with open(errors + '.txt', 'w') as f:
            if upper_face:
                output_string += '########## UPPER FACE ##########\n\n'
                output_string += 'N_section\t\tN_point\t\t\tX_crds\t\t\t\t'
                output_string += 'Y_crds\t\t\t\t\tZ_crds\t\t\t\t\tDISTANCE'
                output_string += '\n\n'
                for i in range(self.n_sections):
                    alength = len(self.blade_coordinates_up[i][0])
                    for j in range(alength):
                        vertex = BRepBuilderAPI_MakeVertex(
                            gp_Pnt(
                                1000 * self.blade_coordinates_up[i][0][j],
                                1000 * self.blade_coordinates_up[i][1][j],
                                1000 *
                                self.blade_coordinates_up[i][2][j])).Vertex()
                        projection = BRepExtrema_DistShapeShape(
                            self.generated_upper_face, vertex)
                        projection.Perform()
                        output_string += str(i) + '\t\t\t' + str(
                            j) + '\t\t\t' + str(
                                1000 *
                                self.blade_coordinates_up[i][0][j]) + '\t\t\t'
                        output_string += str(
                            1000 * self.blade_coordinates_up[i][1][j]
                        ) + '\t\t\t' + str(
                            1000 * self.blade_coordinates_up[i][2][j]
                        ) + '\t\t\t' + str(projection.Value())
                        output_string += '\n'

            if lower_face:
                output_string += '########## LOWER FACE ##########\n\n'
                output_string += 'N_section\t\tN_point\t\t\tX_crds\t\t\t\t'
                output_string += 'Y_crds\t\t\t\t\tZ_crds\t\t\t\t\tDISTANCE'
                output_string += '\n\n'
                for i in range(self.n_sections):
                    alength = len(self.blade_coordinates_down[i][0])
                    for j in range(alength):
                        vertex = BRepBuilderAPI_MakeVertex(
                            gp_Pnt(1000 * self.blade_coordinates_down[i][0][j],
                                   1000 * self.blade_coordinates_down[i][1][j],
                                   1000 * self.blade_coordinates_down[i][2][j])
                        ).Vertex()
                        projection = BRepExtrema_DistShapeShape(
                            self.generated_lower_face, vertex)
                        projection.Perform()
                        output_string += str(i) + '\t\t\t' + str(
                            j) + '\t\t\t' + str(
                                1000 * self.blade_coordinates_down[i][0][j]
                            ) + '\t\t\t'
                        output_string += str(
                            1000 * self.blade_coordinates_down[i][1][j]
                        ) + '\t\t\t' + str(
                            1000 * self.blade_coordinates_down[i][2][j]
                        ) + '\t\t\t' + str(projection.Value())
                        output_string += '\n'
            f.write(output_string)
Exemplo n.º 18
0
tubemesh = Mesh.from_obj(compas.get('tubemesh.obj'))
tubemesh.quads_to_triangles()

print(tubemesh.number_of_vertices())
print(tubemesh.number_of_faces())

# ==============================================================================
# To OCC
# ==============================================================================

shell = TopoDS_Shell()
builder = BRep_Builder()
builder.MakeShell(shell)

vertexdict = {vertex: BRepBuilderAPI_MakeVertex(gp_Pnt(* tubemesh.vertex_attributes(vertex, 'xyz'))) for vertex in tubemesh.vertices()}

for face in tubemesh.faces():
    wire = BRepBuilderAPI_MakeWire()
    for u, v in tubemesh.face_halfedges(face):
        edge = BRepBuilderAPI_MakeEdge(vertexdict[u].Vertex(), vertexdict[v].Vertex())
        wire.Add(edge.Edge())
    face = BRepBuilderAPI_MakeFace(wire.Wire()).Face()
    builder.Add(shell, face)

# ==============================================================================
# Explore
# ==============================================================================

polygons = []
Exemplo n.º 19
0
    def DisplayMesh(self,
                    part,
                    edge_color=None,
                    vertex_color=None,
                    vertex_width=2):
        """

        :param part:
        :param edge_color:
        :param vertex_color:
        :param vertex_width:
        :type part: ada.Part
        """
        from itertools import chain
        from random import randint

        from OCC.Core.BRep import BRep_Builder
        from OCC.Core.BRepBuilderAPI import BRepBuilderAPI_MakeVertex
        from OCC.Core.gp import gp_Pnt
        from OCC.Core.TopoDS import TopoDS_Compound

        # edge_color = format_color(*part.colour) if edge_color is None else edge_color

        edge_color = (format_color(randint(0, 255), randint(
            0, 255), randint(0, 255)) if edge_color is None else edge_color)
        vertex_color = self._default_vertex_color if vertex_color is None else vertex_color

        pmesh_id = "%s" % uuid.uuid4().hex

        BB = BRep_Builder()
        compound = TopoDS_Compound()
        BB.MakeCompound(compound)
        vertices_list = []

        def togp(n_):
            return gp_Pnt(float(n_[0]), float(n_[1]), float(n_[2]))

        for vertex in map(togp, part.fem.nodes):
            vertex_to_add = BRepBuilderAPI_MakeVertex(vertex).Shape()
            BB.Add(compound, vertex_to_add)
            vertices_list.append([vertex.X(), vertex.Y(), vertex.Z()])

        attributes = {
            "position": BufferAttribute(vertices_list, normalized=False)
        }
        mat = PointsMaterial(color=vertex_color,
                             sizeAttenuation=False,
                             size=vertex_width)
        geom = BufferGeometry(attributes=attributes)
        points_geom = Points(geometry=geom, material=mat, name=pmesh_id)

        def grab_nodes(el):
            """

            :param el:
            :type el: ada.fem.Elem
            :return:
            """
            if el.edges_seq is None:
                return None
            return [
                part.fem.nodes.from_id(i).p for i in
                [el.nodes[e].id for ed_seq in el.edges_seq for e in ed_seq]
            ]

        lmesh_id = "%s" % uuid.uuid4().hex

        edges_nodes = list(
            chain.from_iterable(
                filter(None, map(grab_nodes, part.fem.elements))))
        np_edge_vertices = np.array(edges_nodes, dtype=np.float32)
        np_edge_indices = np.arange(np_edge_vertices.shape[0], dtype=np.uint32)
        edge_geometry = BufferGeometry(
            attributes={
                "position": BufferAttribute(np_edge_vertices),
                "index": BufferAttribute(np_edge_indices),
            })
        edge_material = LineBasicMaterial(color=edge_color, linewidth=1)

        edge_geom = LineSegments(
            geometry=edge_geometry,
            material=edge_material,
            type="LinePieces",
            name=lmesh_id,
        )
        output = [points_geom, edge_geom]

        for elem in output:
            self._shapes[elem.name] = compound
            self._refs[elem.name] = part
            self._displayed_pickable_objects.add(elem)

        self._fem_sets_opts.options = ["None"] + [
            s.name for s in filter(
                lambda x: "internal" not in x.metadata.keys(), part.fem.sets)
        ]
Exemplo n.º 20
0
def to_Vertex(arg):
    return BRepBuilderAPI_MakeVertex(to_Pnt(arg)).Vertex()
Exemplo n.º 21
0
def make_vertex(*args):
    vert = BRepBuilderAPI_MakeVertex(*args)
    result = vert.Vertex()
    return result
Exemplo n.º 22
0
    def DisplayMesh(self,
                    part: "Part",
                    edge_color=None,
                    vertex_color=None,
                    vertex_width=2):
        from OCC.Core.BRep import BRep_Builder
        from OCC.Core.BRepBuilderAPI import BRepBuilderAPI_MakeVertex
        from OCC.Core.gp import gp_Pnt
        from OCC.Core.TopoDS import TopoDS_Compound

        # edge_color = format_color(*part.colour) if edge_color is None else edge_color
        rgb = randint(0, 255), randint(0, 255), randint(0, 255)
        edge_color = format_color(*rgb) if edge_color is None else edge_color
        vertex_color = self._default_vertex_color if vertex_color is None else vertex_color

        pmesh_id = "%s" % uuid.uuid4().hex

        BB = BRep_Builder()
        compound = TopoDS_Compound()
        BB.MakeCompound(compound)
        vertices_list = []

        def togp(n_):
            return gp_Pnt(float(n_[0]), float(n_[1]), float(n_[2]))

        for vertex in map(togp, part.fem.nodes):
            vertex_to_add = BRepBuilderAPI_MakeVertex(vertex).Shape()
            BB.Add(compound, vertex_to_add)
            vertices_list.append([vertex.X(), vertex.Y(), vertex.Z()])

        attributes = {
            "position": BufferAttribute(vertices_list, normalized=False)
        }
        mat = PointsMaterial(color=vertex_color,
                             sizeAttenuation=False,
                             size=vertex_width)
        geom = BufferGeometry(attributes=attributes)
        points_geom = Points(geometry=geom, material=mat, name=pmesh_id)
        lmesh_id = "%s" % uuid.uuid4().hex
        edges_nodes = list(
            chain.from_iterable(
                filter(
                    None,
                    [get_vertices_from_elem(el) for el in part.fem.elements])))
        np_edge_vertices = np.array(edges_nodes, dtype=np.float32)
        np_edge_indices = np.arange(np_edge_vertices.shape[0], dtype=np.uint32)
        vertex_col = tuple([x / 255 for x in rgb])
        edge_geometry = BufferGeometry(
            attributes={
                "position": BufferAttribute(np_edge_vertices),
                "index": BufferAttribute(np_edge_indices),
                "color": BufferAttribute(
                    [vertex_col for n in np_edge_vertices]),
            })
        edge_material = LineBasicMaterial(vertexColors="VertexColors",
                                          linewidth=5)

        edge_geom = LineSegments(
            geometry=edge_geometry,
            material=edge_material,
            type="LinePieces",
            name=lmesh_id,
        )
        output = [points_geom, edge_geom]

        for elem in output:
            self._shapes[elem.name] = compound
            self._refs[elem.name] = part
            self._displayed_pickable_objects.add(elem)

        self._fem_sets_opts.options = ["None"] + [
            f"{part.fem.name}.{s.name}" for s in filter(
                lambda x: "internal" not in x.metadata.keys(), part.fem.sets)
        ]
        self._fem_refs[part.fem.name] = (part.fem, edge_geometry)
    ay = gp_XYZ(aYDir.X(), aYDir.Y(), aYDir.Z())
    az = gp_XYZ(aZDir.X(), aZDir.Y(), aZDir.Z())
    p = gp_Pnt(aBaryCenter.X(), aBaryCenter.Y(), aBaryCenter.Z())
    anAxes = gp_Ax2(p, gp_Dir(aZDir), gp_Dir(aXDir))
    anAxes.SetLocation(
        gp_Pnt(p.XYZ() - ax * aHalfX - ay * aHalfY - az * aHalfZ))
    aBox = BRepPrimAPI_MakeBox(anAxes, 2.0 * aHalfX, 2.0 * aHalfY,
                               2.0 * aHalfZ).Shape()
    return aBox


obb = Bnd_OBB()

# choose n random vertices
n = 10
for _ in range(n):
    x = random.uniform(100, 1000)
    y = random.uniform(100, 1000)
    z = random.uniform(100, 1000)
    p = BRepBuilderAPI_MakeVertex(gp_Pnt(x, y, z)).Shape()
    display.DisplayShape(p)
    brepbndlib_AddOBB(p, obb)
obb_shape = ConvertBndToShape(obb)
display.DisplayShape(obb_shape)

# a ref box
b = BRepPrimAPI_MakeBox(10, 10, 10).Shape()
display.DisplayShape(b, update=True)

start_display()
Exemplo n.º 24
0
def make_vertex(*args):
    vert = BRepBuilderAPI_MakeVertex(*args)
    assert_isdone(vert, "failed to produce edge")
    result = vert.Vertex()
    return result
Exemplo n.º 25
0
    def DisplayShape(self,
                     shapes,
                     material=None,
                     texture=None,
                     color=None,
                     transparency=None,
                     update=False):
        """ display one or a set of displayable objects
        """
        SOLO = False  # assume multiple instances by default
        # if a gp_Pnt is passed, first convert to vertex
        if issubclass(shapes.__class__, gp_Pnt):
            vertex = BRepBuilderAPI_MakeVertex(shapes)
            shapes = [vertex.Shape()]
            SOLO = True
        elif isinstance(shapes, gp_Pnt2d):
            vertex = BRepBuilderAPI_MakeVertex(
                gp_Pnt(shapes.X(), shapes.Y(), 0))
            shapes = [vertex.Shape()]
            SOLO = True
        # if a Geom_Curve is passed
        elif callable(getattr(shapes, "GetHandle", None)):
            handle = shapes.GetHandle()
            if issubclass(handle.__class__, Handle_Geom_Curve):
                edge = BRepBuilderAPI_MakeEdge(handle)
                shapes = [edge.Shape()]
                SOLO = True
            elif issubclass(handle.__class__, Handle_Geom2d_Curve):
                edge2d = BRepBuilderAPI_MakeEdge2d(handle)
                shapes = [edge2d.Shape()]
                SOLO = True
            elif issubclass(handle.__class__, Handle_Geom_Surface):
                bounds = True
                toldegen = 1e-6
                face = BRepBuilderAPI_MakeFace()
                face.Init(handle, bounds, toldegen)
                face.Build()
                shapes = [face.Shape()]
                SOLO = True
        elif isinstance(shapes, Handle_Geom_Surface):
            bounds = True
            toldegen = 1e-6
            face = BRepBuilderAPI_MakeFace()
            face.Init(shapes, bounds, toldegen)
            face.Build()
            shapes = [face.Shape()]
            SOLO = True
        elif isinstance(shapes, Handle_Geom_Curve):
            edge = BRepBuilderAPI_MakeEdge(shapes)
            shapes = [edge.Shape()]
            SOLO = True
        elif isinstance(shapes, Handle_Geom2d_Curve):
            edge2d = BRepBuilderAPI_MakeEdge2d(shapes)
            shapes = [edge2d.Shape()]
            SOLO = True
        elif issubclass(shapes.__class__, TopoDS_Shape):
            shapes = [shapes]
            SOLO = True

        ais_shapes = []

        for shape in shapes:
            if material or texture:
                if texture:
                    self.View.SetSurfaceDetail(V3d_TEX_ALL)
                    shape_to_display = AIS_TexturedShape(shape)
                    filename, toScaleU, toScaleV, toRepeatU, toRepeatV, originU, originV = texture.GetProperties(
                    )
                    shape_to_display.SetTextureFileName(
                        TCollection_AsciiString(filename))
                    shape_to_display.SetTextureMapOn()
                    shape_to_display.SetTextureScale(True, toScaleU, toScaleV)
                    shape_to_display.SetTextureRepeat(True, toRepeatU,
                                                      toRepeatV)
                    shape_to_display.SetTextureOrigin(True, originU, originV)
                    shape_to_display.SetDisplayMode(3)
                elif material:
                    shape_to_display = AIS_Shape(shape)
                    shape_to_display.SetMaterial(material)
            else:
                # TODO: can we use .Set to attach all TopoDS_Shapes
                # to this AIS_Shape instance?
                shape_to_display = AIS_Shape(shape)

            ais_shapes.append(shape_to_display.GetHandle())

        if not SOLO:
            # computing graphic properties is expensive
            # if an iterable is found, so cluster all TopoDS_Shape under
            # an AIS_MultipleConnectedInteractive
            #shape_to_display = AIS_MultipleConnectedInteractive()
            for ais_shp in ais_shapes:
                # TODO : following line crashes with oce-0.18
                # why ? fix ?
                #shape_to_display.Connect(i)
                self.Context.Display(ais_shp, False)
            shape_to_display = ais_shapes
            return shape_to_display
        # set the graphic properties
        if material is None:
            #The default material is too shiny to show the object
            #color well, so I set it to something less reflective
            shape_to_display.SetMaterial(Graphic3d_NOM_NEON_GNC)
        if color:
            if isinstance(color, str):
                color = get_color_from_name(color)
            for shp in ais_shapes:
                self.Context.SetColor(shp, color, False)
        if transparency:
            shape_to_display.SetTransparency(transparency)
        if update:
            # only update when explicitely told to do so
            self.Context.Display(shape_to_display.GetHandle(), False)
            # especially this call takes up a lot of time...
            self.FitAll()
            self.Repaint()
        else:
            self.Context.Display(shape_to_display.GetHandle(), False)

        if SOLO:
            return ais_shapes[0]
        else:
            return shape_to_display
Exemplo n.º 26
0
def make_vertex(*args):
    vert = BRepBuilderAPI_MakeVertex(*args)
    with assert_isdone(vert, 'failed to produce vertex'):
        result = vert.Vertex()
        vert.Delete()
        return result
Exemplo n.º 27
0
    def ConvertShape(
        self,
        shape,
        export_edges=False,
        color=(0.65, 0.65, 0.7),
        specular_color=(0.2, 0.2, 0.2),
        shininess=0.9,
        transparency=0.0,
        line_color=(0, 0.0, 0.0),
        line_width=1.0,
        point_size=1.0,
        mesh_quality=1.0,
    ):
        # if the shape is an edge or a wire, use the related functions
        color = color_to_hex(color)
        specular_color = color_to_hex(specular_color)
        if is_edge(shape):
            print("discretize an edge")
            pnts = discretize_edge(shape)
            edge_hash = "edg%s" % uuid.uuid4().hex
            shape_content = export_edgedata_to_json(edge_hash, pnts)
            # store this edge hash
            self._3js_edges[edge_hash] = [color, line_width, shape_content]
            return self._3js_shapes, self._3js_edges, self._3js_vertex
        elif is_wire(shape):
            print("discretize a wire")
            pnts = discretize_wire(shape)
            wire_hash = "wir%s" % uuid.uuid4().hex
            shape_content = export_edgedata_to_json(wire_hash, pnts)
            # store this edge hash
            self._3js_edges[wire_hash] = [color, line_width, shape_content]
            return self._3js_shapes, self._3js_edges, self._3js_vertex
        # if shape is array of gp_Pnt
        elif isinstance(shape, list) and isinstance(shape[0], gp_Pnt):
            print("storage points")
            vertices_list = []  # will be passed to javascript
            BB = BRep_Builder()
            compound = TopoDS_Compound()
            BB.MakeCompound(compound)

            for vertex in shape:
                vertext_to_add = BRepBuilderAPI_MakeVertex(vertex).Shape()
                BB.Add(compound, vertext_to_add)
                vertices_list.append([vertex.X(), vertex.Y(), vertex.Z()])
            points_hash = "pnt%s" % uuid.uuid4().hex
            # store this vertex hash. Note: TopoDS_Compound did not save now
            self._3js_vertex[points_hash] = [color, point_size, vertices_list]
            return self._3js_shapes, self._3js_edges, self._3js_vertex

        # convert as TopoDS_Shape
        shape_uuid = uuid.uuid4().hex
        shape_hash = "shp%s" % shape_uuid
        # tesselate
        tess = ShapeTesselator(shape)
        tess.Compute(compute_edges=export_edges,
                     mesh_quality=mesh_quality,
                     parallel=True)
        # update spinning cursor
        sys.stdout.write("\r%s mesh shape %s, %i triangles     " % (next(
            self.spinning_cursor), shape_hash, tess.ObjGetTriangleCount()))
        sys.stdout.flush()
        # export to 3JS
        # generate the mesh
        shape_content = tess.ExportShapeToThreejsJSONString(shape_uuid)
        # add this shape to the shape dict, sotres everything related to it
        self._3js_shapes[shape_hash] = [
            export_edges,
            color,
            specular_color,
            shininess,
            transparency,
            line_color,
            line_width,
            shape_content,
        ]
        # draw edges if necessary
        if export_edges:
            # export each edge to a single json
            # get number of edges
            nbr_edges = tess.ObjGetEdgeCount()
            for i_edge in range(nbr_edges):
                # after that, the file can be appended
                edge_content = ""
                edge_point_set = []
                nbr_vertices = tess.ObjEdgeGetVertexCount(i_edge)
                for i_vert in range(nbr_vertices):
                    edge_point_set.append(tess.GetEdgeVertex(i_edge, i_vert))
                # write to file
                edge_hash = "edg%s" % uuid.uuid4().hex
                edge_content += export_edgedata_to_json(
                    edge_hash, edge_point_set)
                # store this edge hash, with black color
                self._3js_edges[edge_hash] = [
                    color_to_hex((0, 0, 0)),
                    line_width,
                    edge_content,
                ]
        return self._3js_shapes, self._3js_edges, self._3js_vertex