def vertices(self): verts = self.native_vertices() pnts = [] pnts_filtered = [] for vertex in verts: pnt = BRep_Tool.Pnt(vertex.Vertex()) pnts.append(point3(pnt)) # Фильтруем вершины, исключая близколежащие. for p in pnts: for f in pnts_filtered: if numpy.linalg.norm(p-f) < 1e-5: break else: pnts_filtered.append(p) return pnts_filtered
def dump_topology_to_string(shape, level=0, buffer=""): """ Reutnrs the details of an object from the top down """ brt = BRep_Tool() s = shape.ShapeType() if s == TopAbs_VERTEX: pnt = brt.Pnt(topods_Vertex(shape)) print(".." * level + "<Vertex %i: %s %s %s>\n" % ( hash(shape), pnt.X(), pnt.Y(), pnt.Z())) else: print(".." * level, end="") print(shape_type_string(shape)) it = TopoDS_Iterator(shape) while it.More() and level < 5: # LEVEL MAX shp = it.Value() it.Next() print(dump_topology_to_string(shp, level + 1, buffer))
def dumpTopology(shape, level=0): """ Print the details of an object from the top down """ brt = BRep_Tool() s = shape.ShapeType() if s == TopAbs_VERTEX: pnt = brt.Pnt(topods_Vertex(shape)) print(".." * level + "<Vertex %i: %s %s %s>" % (hash(shape), pnt.X(), pnt.Y(), pnt.Z())) else: print(".." * level, end="") print(shapeTypeString(shape)) it = TopoDS_Iterator(shape) while it.More(): shp = it.Value() it.Next() dumpTopology(shp, level + 1)
def occvertex_list_2_occpt_list(occvertex_list): """ This function constructs a list of OCC points (gp_pnt) from a list of OCCvertices. Parameters ---------- occvertex_list : list of OCCvertices List of OCCvertices to be converted to a list of OCC points (gp_pnt). Returns ------- list of points : list of OCC points (gp_pnt) A list of OCC points (gp_pnt) constructed from the list of OCCvertices. """ point_list = [] for vert in occvertex_list: point_list.append(BRep_Tool.Pnt(vert)) return point_list
def check_remaining(array): from OCC.Extend.TopologyUtils import TopologyExplorer from OCC.Core.BRepClass3d import BRepClass3d_SolidClassifier from OCC.Core.TopoDS import topods_Vertex from OCC.Core.BRep import BRep_Tool for i, si in enumerate(array): while si.to_check: face, isol = si.to_check.pop(0) brt = BRep_Tool() states = [] for v in TopologyExplorer(face).vertices(): pnt = brt.Pnt(topods_Vertex(v)) classifier = BRepClass3d_SolidClassifier( array[isol].solid, gp_Pnt(pnt.X(), pnt.Y(), pnt.Z()), 1.e-10) states.append(classifier.State()) if (0 not in states): #if 'fore' in array[isol].name: print states si.kept.append(face)
def dump_topology_to_string(shape: TopoDS_Shape, level: Optional[int] = 0, buffer: Optional[str] = "") -> None: """ Return the details of an object from the top down """ brt = BRep_Tool() s = shape.ShapeType() if s == TopAbs_VERTEX: pnt = brt.Pnt(topods_Vertex(shape)) print(".." * level + f"<Vertex {hash(shape)}: {pnt.X()} {pnt.Y()} {pnt.Z()}>\n") else: print(".." * level, end="") print(shape) it = TopoDS_Iterator(shape) while it.More() and level < 5: # LEVEL MAX shp = it.Value() it.Next() dump_topology_to_string(shp, level + 1, buffer)
def srf_nrml_facing_solid_inward(occface, occsolid): """ This function checks if the OCCface is facing the inside of the OCCsolid. Parameters ---------- occface : OCCface The OCCface to be checked. occsolid : OCCsolid The OCCsolid. Returns ------- True or False : bool If True the face is facing the inside of the solid, if False the face is not facing inwards. """ #move the face in the direction of the normal #first offset the face so that vert will be within the solid o_wire = Construct.make_offset(occface, 0.0001) o_face = BRepBuilderAPI_MakeFace(o_wire).Face() wire_list = list(Topology.Topo(o_face).wires()) occpt_list = [] for wire in wire_list: occpts = Topology.WireExplorer(wire).ordered_vertices() occpt_list.extend(occpts) pt = BRep_Tool.Pnt(occpt_list[0]) #a point that is on the edge of the face normal = face_normal(occface) gp_direction2move = gp_Vec(normal[0], normal[1], normal[2]) gp_moved_pt = pt.Translated(gp_direction2move.Multiplied(0.001)) mv_pt = (gp_moved_pt.X(), gp_moved_pt.Y(), gp_moved_pt.Z()) in_solid = point_in_solid(occsolid, mv_pt) if in_solid: return True else: return False
def DumpTop(self, shape, level=0): """ Print the details of an object from the top down """ brt = BRep_Tool() s = shape.ShapeType() if s == TopAbs_VERTEX: pnt = brt.Pnt(topods_Vertex(shape)) dmp = " " * level dmp += "%s - " % shapeTypeString(shape) dmp += "%.5e %.5e %.5e" % (pnt.X(), pnt.Y(), pnt.Z()) print(dmp) else: dmp = " " * level dmp += shapeTypeString(shape) print(dmp) it = TopoDS_Iterator(shape) while it.More(): shp = it.Value() it.Next() self.DumpTop(shp, level + 1)
def parts_in_others_boxes(array): from OCC.Extend.TopologyUtils import TopologyExplorer from OCC.Core.BRepClass3d import BRepClass3d_SolidClassifier from OCC.Core.TopoDS import topods_Vertex from OCC.Core.BRep import BRep_Tool for i, si in enumerate(array): for faci in si.splitsolid: for j, sj in enumerate(array): if i != j: boxj = sj.box.Shape() states = [] for v in TopologyExplorer(faci).vertices(): brt = BRep_Tool() pnt = brt.Pnt(topods_Vertex(v)) classifier = BRepClass3d_SolidClassifier( boxj, gp_Pnt(pnt.X(), pnt.Y(), pnt.Z()), 1.e-12) states.append(classifier.State()) if 0 in states: si.to_check.append([faci, j]) if faci not in [ftc[0] for ftc in si.to_check]: si.kept.append(faci)
def corners(house): d = {} iface = -1 topo = Topo(house['volume']) house['boundaries'] = {'walls': [], 'windows': [], 'heats': []} house['faces'] = [] for f in topo.wires(): iface += 1 key = 'face' + str(iface) print 'new_face' edges = [] d[key] = [] topof = Topo(f) for e in topof.edges(): vts = Topo(e) print 'edge' edge = [] for i, v in enumerate(vts.vertices()): brt = BRep_Tool() pnt = brt.Pnt(topods_Vertex(v)) edge.append([pnt.X(), pnt.Y(), pnt.Z()]) edges.append(edge) print len(edges) first_edge = edges.pop(0) point_array = [first_edge[0], first_edge[1]] print 'edges :' for e in edges: print e print '-------' while len(edges) > 0: for i, e in enumerate(edges): if point_array[-1] in e: ed = edges.pop(i) print point_array[-1] if ed[0] == point_array[-1]: point_array.append(ed[1]) elif ed[1] == point_array[-1]: point_array.append(ed[0]) break d[key] = point_array house['faces'].append(point_array) return d
def recognize_clicked(self, shp, *kwargs): """ This is the function called every time a face is clicked in the 3d view """ x, y, z = self.convertScreenPos(kwargs[0], kwargs[1]) point = gp_Pnt(x, y, z) for shape in shp: if shape.ShapeType() == TopAbs_SOLID: pass if shape.ShapeType() == TopAbs_EDGE: self.recognize_edge(topods_Edge(shape)) if shape.ShapeType() == TopAbs_FACE: pass if shape.ShapeType()==TopAbs_VERTEX: point = BRep_Tool.Pnt(shape) print(shape.ShapeType(), point.X(), point.Y(), point.Z()) if self._state == self.DRAW_START: self._currentPos = point self._clicked.append(point) if self._shape_type == self.SURFACE_REVOLUTION: self.interactive.interaction_revolvedSurface(kwargs[0], kwargs[1]) elif self._shape_type == self.SURFACE_BEZIER: self.interactive.interaction_bezierSurface(kwargs[0], kwargs[1])
def getWireStartPointAndTangentDir(aWire): ex = BRepTools_WireExplorer(aWire) edge = ex.Current() vertex = ex.CurrentVertex() v = getVectorTangentToCurveAtPoint(edge, 0) return BRep_Tool.Pnt(vertex), gp_Dir(v)
#section.SetFuzzyValue(1.e-18) section.ComputePCurveOn1(True) section.ComputePCurveOn2(True) section.Approximation(True) section.Build() #dumpTopology(section.Shape()) display.DisplayColoredShape(section.Shape(), 'GREEN') all_points = [] all_edges = [] for edg in Topo(section.Shape()).edges(): brt = BRep_Tool() print '--- edge -----' edge_points = [] tpedg = Topo(edg) for v in tpedg.vertices(): pnt = brt.Pnt(topods_Vertex(v)) edge_points.append(Point([pnt.X(), pnt.Y(), pnt.Z()])) display.DisplayColoredShape(pnt, 'GREEN') all_points.append(edge_points) if len(all_points) != 0: pol = segments_to_polyline(all_points) all_edges = polyline3d_to_edges(pol) for edg in all_edges: face_explorer = TopExp_Explorer(faces1[f].Shape(), TopAbs_FACE) while False: #face_explorer.More(): try: TopOpeBRepTool_CurveTool_MakePCurveOnFace( edg, topods_Face(face_explorer.Current())) print 'done' except:
def _render_shape(self, shape_index, shape=None, edges=None, vertices=None, mesh_color=None, edge_color=None, vertex_color=None, render_edges=False, edge_width=1, vertex_width=5, deflection=0.05, transparent=False, opacity=1.0): edge_list = None edge_lines = None points = None shape_mesh = None if shape is not None: if mesh_color is None: mesh_color = self.default_mesh_color if edge_color is None: edge_color = self.default_edge_color if vertex_color is None: vertex_color = self.default_edge_color # same as edge_color # BEGIN copy # The next lines are copied with light modifications from # https://github.com/tpaviot/pythonocc-core/blob/master/src/Display/WebGl/jupyter_renderer.py # first, compute the tesselation tess = Tesselator(shape) tess.Compute(uv_coords=False, compute_edges=render_edges, mesh_quality=self.quality, parallel=True) # get vertices and normals vertices_position = tess.GetVerticesPositionAsTuple() number_of_triangles = tess.ObjGetTriangleCount() number_of_vertices = len(vertices_position) # number of vertices should be a multiple of 3 if number_of_vertices % 3 != 0: raise AssertionError("Wrong number of vertices") if number_of_triangles * 9 != number_of_vertices: raise AssertionError("Wrong number of triangles") # then we build the vertex and faces collections as numpy ndarrays np_vertices = np.array(vertices_position, dtype='float32')\ .reshape(int(number_of_vertices / 3), 3) # Note: np_faces is just [0, 1, 2, 3, 4, 5, ...], thus arange is used np_faces = np.arange(np_vertices.shape[0], dtype='uint32') # compute normals np_normals = np.array(tess.GetNormalsAsTuple(), dtype='float32').reshape(-1, 3) if np_normals.shape != np_vertices.shape: raise AssertionError("Wrong number of normals/shapes") # build a BufferGeometry instance shape_geometry = BufferGeometry( attributes={ 'position': BufferAttribute(np_vertices), 'index': BufferAttribute(np_faces), 'normal': BufferAttribute(np_normals) }) shp_material = self._material(mesh_color, transparent=True, opacity=opacity) shape_mesh = Mesh(geometry=shape_geometry, material=shp_material, name="mesh_%d" % shape_index) if render_edges: edge_list = list( map( lambda i_edge: [ tess.GetEdgeVertex(i_edge, i_vert) for i_vert in range( tess.ObjEdgeGetVertexCount(i_edge)) ], range(tess.ObjGetEdgeCount()))) # END copy if vertices is not None: vertices_list = [] for vertex in vertices: p = BRep_Tool.Pnt(vertex) vertices_list.append((p.X(), p.Y(), p.Z())) vertices_list = np.array(vertices_list, dtype=np.float32) attributes = { "position": BufferAttribute(vertices_list, normalized=False) } mat = PointsMaterial(color=vertex_color, sizeAttenuation=False, size=vertex_width) geom = BufferGeometry(attributes=attributes) points = Points(geometry=geom, material=mat) if edges is not None: edge_list = [discretize_edge(edge, deflection) for edge in edges] if edge_list is not None: edge_list = _flatten(list(map(_explode, edge_list))) lines = LineSegmentsGeometry(positions=edge_list) mat = LineMaterial(linewidth=edge_width, color=edge_color) edge_lines = LineSegments2(lines, mat, name="edges_%d" % shape_index) if shape_mesh is not None or edge_lines is not None or points is not None: index_mapping = {"mesh": None, "edges": None, "shape": shape_index} if shape_mesh is not None: ind = len(self.pickable_objects.children) self.pickable_objects.add(shape_mesh) index_mapping["mesh"] = ind if edge_lines is not None: ind = len(self.pickable_objects.children) self.pickable_objects.add(edge_lines) index_mapping["edges"] = ind if points is not None: ind = len(self.pickable_objects.children) self.pickable_objects.add(points) index_mapping["mesh"] = ind self.pick_mapping.append(index_mapping)
# Explore # ============================================================================== polygons = [] tool = BRep_Tool() wires = TopExp_Explorer(shell, TopAbs_WIRE) while wires.More(): wire = topods_Wire(wires.Current()) vertices = TopExp_Explorer(wire, TopAbs_VERTEX) points = [] while vertices.More(): vertex = topods_Vertex(vertices.Current()) point = tool.Pnt(vertex) x = point.X() y = point.Y() z = point.Z() points.append([x, y, z]) vertices.Next() polygons.append(points) wires.Next() # ============================================================================== # Viz # ============================================================================== mesh = Mesh.from_polygons(polygons)
def write_face(self, points_face, list_points_edge, topo_face, toledge): """ Method to recreate a Face associated to a geometric surface after the modification of Face points. It returns a TopoDS_Face. :param points_face: the new face points array. :param list_points_edge: new edge points :param topo_face: the face to be modified :param toledge: tolerance on the surface creation after modification :return: TopoDS_Face (Shape) :rtype: TopoDS_Shape """ # convert Face to Geom B-spline Surface nurbs_converter = BRepBuilderAPI_NurbsConvert(topo_face) nurbs_converter.Perform(topo_face) nurbs_face = nurbs_converter.Shape() topo_nurbsface = topods.Face(nurbs_face) h_geomsurface = BRep_Tool.Surface(topo_nurbsface) h_bsurface = geomconvert_SurfaceToBSplineSurface(h_geomsurface) bsurface = h_bsurface nb_u = bsurface.NbUPoles() nb_v = bsurface.NbVPoles() # check consistency if points_face.shape[0] != nb_u * nb_v: raise ValueError("Input control points do not have not have the " "same number as the geometric face!") # cycle on the face points indice_cpt = 0 for iu in range(1, nb_u + 1): for iv in range(1, nb_v + 1): cpt = points_face[indice_cpt] bsurface.SetPole(iu, iv, gp_Pnt(cpt[0], cpt[1], cpt[2])) indice_cpt += 1 # create modified new face new_bspline_tface = BRepBuilderAPI_MakeFace() toler = precision_Confusion() new_bspline_tface.Init(bsurface, False, toler) # cycle on the wires face_wires_explorer = TopExp_Explorer( topo_nurbsface.Oriented(TopAbs_FORWARD), TopAbs_WIRE) ind_edge_total = 0 while face_wires_explorer.More(): # get old wire twire = topods_Wire(face_wires_explorer.Current()) # cycle on the edges ind_edge = 0 wire_explorer_edge = TopExp_Explorer( twire.Oriented(TopAbs_FORWARD), TopAbs_EDGE) # check edges order on the wire mode3d = True tolerance_edges = toledge wire_order = ShapeAnalysis_WireOrder(mode3d, tolerance_edges) # an edge list deformed_edges = [] # cycle on the edges while wire_explorer_edge.More(): tedge = topods_Edge(wire_explorer_edge.Current()) new_bspline_tedge = self.write_edge( list_points_edge[ind_edge_total], tedge) deformed_edges.append(new_bspline_tedge) analyzer = topexp() vfirst = analyzer.FirstVertex(new_bspline_tedge) vlast = analyzer.LastVertex(new_bspline_tedge) pt1 = BRep_Tool.Pnt(vfirst) pt2 = BRep_Tool.Pnt(vlast) wire_order.Add(pt1.XYZ(), pt2.XYZ()) ind_edge += 1 ind_edge_total += 1 wire_explorer_edge.Next() # grouping the edges in a wire, then in the face # check edges order and connectivity within the wire wire_order.Perform() # new wire to be created stol = ShapeFix_ShapeTolerance() new_bspline_twire = BRepBuilderAPI_MakeWire() for order_i in range(1, wire_order.NbEdges() + 1): deformed_edge_i = wire_order.Ordered(order_i) if deformed_edge_i > 0: # insert the deformed edge to the new wire new_edge_toadd = deformed_edges[deformed_edge_i - 1] stol.SetTolerance(new_edge_toadd, toledge) new_bspline_twire.Add(new_edge_toadd) if new_bspline_twire.Error() != 0: stol.SetTolerance(new_edge_toadd, toledge * 10.0) new_bspline_twire.Add(new_edge_toadd) else: deformed_edge_revers = deformed_edges[ np.abs(deformed_edge_i) - 1] stol.SetTolerance(deformed_edge_revers, toledge) new_bspline_twire.Add(deformed_edge_revers) if new_bspline_twire.Error() != 0: stol.SetTolerance(deformed_edge_revers, toledge * 10.0) new_bspline_twire.Add(deformed_edge_revers) # add new wire to the Face new_bspline_tface.Add(new_bspline_twire.Wire()) face_wires_explorer.Next() return topods.Face(new_bspline_tface.Face())
def vertex2pnt(vertex): '''returns a gp_Pnt from a TopoDS_Vertex ''' from OCC.Core.BRep import BRep_Tool return BRep_Tool.Pnt(vertex)
def getPointsFromVertexes(vertexes): ps = [] for v in vertexes: ps += [BRep_Tool.Pnt(v)] return ps