def ask_point_uv(xyz, face, uvrange): """ This is a general function which gives the uv coordiates from the xyz coordinates. The uv value is not normlized. """ gpPnt = gp_Pnt(float(xyz[0]), float(xyz[1]), float(xyz[2])) surface = BRep_Tool().Surface(face) ### Handle_Geom_Surface sas = ShapeAnalysis_Surface(surface) gpPnt2D = sas.ValueOfUV(gpPnt, 0.01) uv = list(gpPnt2D.Coord()) # print(uvrange) # print(uv) geom_surface = surface.GetObject() tol = 0.001 if geom_surface.IsUPeriodic() == True: # print (geom_surface.UPeriod()) if uv[0] < uvrange[0] and uvrange[0] - uv[0] > tol: uv[0] = uv[0] + geom_surface.UPeriod() if uv[0] > uvrange[1] and uv[0] - uvrange[1] > tol: uv[0] = uv[0] - geom_surface.UPeriod() if geom_surface.IsVPeriodic() == True: if uv[1] < uvrange[2] and uvrange[2] - uv[1] > tol: uv[1] = uv[1] + geom_surface.VPeriod() if uv[1] > uvrange[3] and uv[1] - uvrange[3] > tol: uv[1] = uv[1] - geom_surface.VPeriod() # print(uv) return uv
def collect_dumpable_shapes(self, shape): if shape.ShapeType() == TopAbs_EDGE: points = [] try: points = discretize_edge(shape, 0.25) except: points = [] else: debug("Discretize done !") return points debug("edge: %s/%s"%(str(shape), self.describe_edge(shape))) it = TopoDS_Iterator(shape) points = [] while it.More(): shp = it.Value() brt = BRep_Tool() debug("vertex: %s"%(str(shp),)) pnt = brt.Pnt(topods_Vertex(shp)) points.append((pnt.X(), pnt.Y(), pnt.Z())) it.Next() return points else: lines = [] it = TopoDS_Iterator(shape) while it.More(): shp = it.Value() lines.append(self.collect_dumpable_shapes(shp)) it.Next() return lines
def vertex_fillet(cube_shp, vert): # apply a fillet on incident edges on a vertex afillet = BRepFilletAPI_MakeFillet(cube_shp) cnt = 0 # find edges from vertex _map = TopTools_IndexedDataMapOfShapeListOfShape() topexp_MapShapesAndAncestors(cube_shp, TopAbs_VERTEX, TopAbs_EDGE, _map) results = _map.FindFromKey(vert) topology_iterator = TopTools_ListIteratorOfListOfShape(results) while topology_iterator.More(): edge = topods_Edge(topology_iterator.Value()) topology_iterator.Next() first, last = topexp_FirstVertex(edge), topexp_LastVertex(edge) vertex, first_vert, last_vert = BRep_Tool().Pnt(vert), BRep_Tool().Pnt(first), BRep_Tool().Pnt(last) if edge.Orientation(): if not vertex.IsEqual(first_vert, 0.001): afillet.Add(0, 20., edge) else: afillet.Add(20, 0, edge) cnt += 1 afillet.Build() if afillet.IsDone(): return afillet.Shape() else: raise AssertionError('you failed on me you fool!')
def face_mesh_triangle(comp=TopoDS_Shape(), isR=0.1, thA=0.1): # Mesh the shape BRepMesh_IncrementalMesh(comp, isR, True, thA, True) bild1 = BRep_Builder() comp1 = TopoDS_Compound() bild1.MakeCompound(comp1) bt = BRep_Tool() ex = TopExp_Explorer(comp, TopAbs_FACE) while ex.More(): face = topods_Face(ex.Current()) location = TopLoc_Location() facing = bt.Triangulation(face, location) tab = facing.Nodes() tri = facing.Triangles() print(facing.NbTriangles(), facing.NbNodes()) 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(): bild1.Add(comp1, me.Edge()) ex.Next() return comp1
def pcurve(self, face): """ computes the 2d parametric spline that lies on the surface of the face :return: Geom2d_Curve, u, v """ crv, u, v = BRep_Tool().CurveOnSurface(self, face) return crv.GetObject(), u, v
def curve(self): if self._curve is not None and not self.is_dirty: pass else: self._curve_handle = BRep_Tool().Curve(self)[0] self._curve = self._curve_handle.GetObject() return self._curve
def project_curve(self, other): # this way Geom_Circle and alike are valid too if (isinstance(other, TopoDS_Edge) or isinstance(other, Geom_Curve) or issubclass(other, Geom_Curve)): # convert edge to curve first, last = topexp.FirstVertex(other), topexp.LastVertex(other) lbound, ubound = BRep_Tool().Parameter(first, other), BRep_Tool().Parameter(last, other) other = BRep_Tool.Curve(other, lbound, ubound).GetObject() return geomprojlib.Project(other, self.surface_handle)
def GetEdgeXY(edge): x = [] y = [] t= Topo(edge) for vertex in t.vertices(): # print("vertices type",type(t.vertices())) class 'list_iterator' pnt = BRep_Tool().Pnt(vertex) # print('X', pnt.X(), 'Y', pnt.Y(), 'Z', pnt.Z()) x.append(pnt.X()) y.append(pnt.Y()) return x[0],y[0],x[1],y[1]
def getPntsEdgesFacesIntersect(edgesShape, facesShape): pnts = [] faces = getShapeItems(facesShape, TopAbs_FACE) edges = getShapeItems(edgesShape, TopAbs_EDGE) for edge in edges: for face in faces: curve3 = BRep_Tool.Curve(edge) curve = Geom_TrimmedCurve(curve3[0],curve3[1],curve3[2]) surface = BRep_Tool.Surface(face) pntsToAdd = getPntsCurveSurfaceIntersect(curve, surface) pnts += pntsToAdd return pnts
def continuity_edge_face(self, edge, face): """ compute the continuity between two faces at :edge: :param edge: an Edge or TopoDS_Edge from :face: :param face: a Face or TopoDS_Face :return: bool, GeomAbs_Shape if it has continuity, otherwise False, None """ bt = BRep_Tool() if bt.HasContinuity(edge, self, face): continuity = bt.Continuity(edge, self, face) return True, continuity else: return False, None
def __new__(cls, *args, info=None): args = [evalcache.unlazy_if_need(a) for a in args] if len(args) == 0: input_array = (0, 0, 0) elif isinstance(args[0], TopoDS_Vertex): pnt = BRep_Tool.Pnt(args[0]) input_array = (pnt.X(), pnt.Y(), pnt.Z()) elif isinstance(args[0], (gp_Pnt, gp_Dir, gp_Vec, gp_XYZ)): input_array = (args[0].X(), args[0].Y(), args[0].Z()) else: try: _ = args[0][0] input_array = args[0] except: input_array = args if len(input_array) == 1: input_array = ((input_array[0], 0, 0)) elif len(input_array) == 2: input_array = ((input_array[0], input_array[1], 0)) elif len(input_array) == 3: input_array = ((input_array[0], input_array[1], input_array[2])) obj = numpy.asarray(input_array).view(cls) obj.info = info return obj
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)) 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)
def point(self): """ :return: A point at vertex location. :rtype: afem.geometry.entities.Point """ gp_pnt = BRep_Tool.Pnt_(self.object) return Point(gp_pnt.X(), gp_pnt.Y(), gp_pnt.Z())
def wire_gcode(wire): print(f'Wire Orientation: {o(wire)}') if wire.Orientation() == TopAbs_REVERSED: wire.Reverse() for edge in WireExplorer(wire).ordered_edges(): print(f'Edge Orientation: {o(edge)}') tmp = BRepAdaptor_Curve(edge) # get underlying curve c, start, end = BRep_Tool.Curve(edge) # display start and endpoints of curve start_point = tmp.Value(tmp.FirstParameter()) end_point = tmp.Value(tmp.LastParameter()) if edge.Orientation() == TopAbs_FORWARD: display.DisplayColoredShape( BRepBuilderAPI_MakeVertex(start_point).Vertex(), "BLUE") display.DisplayColoredShape( BRepBuilderAPI_MakeVertex(end_point).Vertex(), "RED") else: display.DisplayColoredShape( BRepBuilderAPI_MakeVertex(start_point).Vertex(), "RED") display.DisplayColoredShape( BRepBuilderAPI_MakeVertex(end_point).Vertex(), "BLUE") # display individual curve display.DisplayShape(edge, update=True) time.sleep(1)
def project_face_on_faceplane(occface2projon, occface2proj): """ This function projects the OCCface onto another OCCface plane. The plane stretches through infinity. Parameters ---------- occface2projon : OCCface The OCCface to be projected on. occface2proj : OCCface The OCCface to be projected. Returns ------- list of points : pyptlist The list of projected points. """ wire_list = list(Topology.Topo(occface2proj).wires()) occpt_list = [] for wire in wire_list: occpts = Topology.WireExplorer(wire).ordered_vertices() occpt_list.extend(occpts) proj_ptlist = [] for occpt in occpt_list: occ_pnt = BRep_Tool.Pnt(occpt) pypt = (occ_pnt.X(), occ_pnt.Y(), occ_pnt.Z()) projected_pt = project_point_on_faceplane(pypt, occface2projon) proj_ptlist.append(projected_pt) return proj_ptlist
def __init__(self, shape1, shape2, pnt=None, tol=-1.): shape = IntersectShapes(shape1, shape2).shape pnt = CheckGeom.to_point(pnt) self._found = False self._pln = None if pnt is None: tool = PlaneByEdges(shape, tol) self._found = tool.found self._pln = tool.plane elif CheckGeom.is_point(pnt): edges = shape.edges pnts = [pnt] for edge in edges: BRepMesh_IncrementalMesh(edge.object, 0.001) loc = TopLoc_Location() poly3d = BRep_Tool.Polygon3D_(edge.object, loc) if poly3d.NbNodes == 0: continue tcol_pnts = poly3d.Nodes() for i in range(1, tcol_pnts.Length() + 1): gp_pnt = tcol_pnts.Value(i) pnt = CheckGeom.to_point(gp_pnt) pnts.append(pnt) if len(pnts) < 3: raise ValueError('Less than three points to fit a plane.') if tol < 0.: tol = 1.0e-7 tool = PlaneByApprox(pnts, tol) self._found = True self._pln = tool.plane else: raise TypeError('Invalid input.')
def write_edge(points_edge, topo_edge): """ Method to recreate an Edge associated to a geometric curve after the modification of its points. :param points_edge: the deformed points array. :param topo_edge: the Edge to be modified :return: Edge (Shape) :rtype: TopoDS_Edge """ # convert Edge to Geom B-spline Curve nurbs_converter = BRepBuilderAPI_NurbsConvert(topo_edge) nurbs_converter.Perform(topo_edge) nurbs_curve = nurbs_converter.Shape() topo_curve = topods_Edge(nurbs_curve) h_geomcurve = BRep_Tool.Curve(topo_curve)[0] h_bcurve = geomconvert_CurveToBSplineCurve(h_geomcurve) bspline_edge_curve = h_bcurve # Edge geometric properties nb_cpt = bspline_edge_curve.NbPoles() # check consistency if points_edge.shape[0] != nb_cpt: raise ValueError("Input control points do not have not have the " "same number as the geometric edge!") else: for i in range(1, nb_cpt + 1): cpt = points_edge[i - 1] bspline_edge_curve.SetPole(i, gp_Pnt(cpt[0], cpt[1], cpt[2])) new_edge = BRepBuilderAPI_MakeEdge(bspline_edge_curve) return new_edge.Edge()
def surface(self): """ :return: The underlying surface of the face. :rtype: afem.geometry.entities.Surface """ geom_surface = BRep_Tool.Surface_(self.object) return Surface.wrap(geom_surface)
def curve(self): """ :return: The underlying curve of the edge. :rtype: afem.geometry.entities.Curve """ geom_curve, _, _ = BRep_Tool.Curve_(self.object, 0., 0.) return Curve.wrap(geom_curve)
def face_expand(self, face=TopoDS_Face()): plan = self.pln_on_face(face) find_edge = LocOpe_FindEdges(self.tmp_face, face) find_edge.InitIterator() edge_n = 0 while find_edge.More(): edge = find_edge.EdgeTo() line = self.prop_edge(edge) e_curve, u0, u1 = BRep_Tool.Curve(edge) p = e_curve.Value((u0 + u1) / 2) i = (edge_n + self.tmp_face_n) % len(self.colors) self.display.DisplayShape(edge, color=self.colors[i]) self.display.DisplayMessage( p, "Face{:d}-Edge{:d}".format(self.tmp_face_n, edge_n)) plan_axs = plan.Position() line_axs = line.Position() line_axs.SetLocation(p) print() print("Face: {:d}, Edge: {:d}".format(self.tmp_face_n, edge_n)) print(self.tmp_axis.Axis()) print(plan.Position().Axis()) #print(self.cal_len(edge), self.cal_are(face)) self.face_rotate(face, line_axs) #self.face_tranfer(face, plan.Axis()) plan = self.pln_on_face(face) print(face, self.cal_are(face), plan) print(plan, plan.Axis()) find_edge.Next() edge_n += 1
def __init__(self): plotocc.__init__(self) self.shell = read_step_file(self.tmpdir + "SurfUV.stp") print(self.shell) top = TopExp_Explorer(self.shell, TopAbs_FACE) self.face = top.Current() print(top.Depth()) print(self.face) self.surf = BRep_Tool.Surface(self.face) u0, u1, v0, v1 = shapeanalysis_GetFaceUVBounds(self.face) print(u0, u1, v0, v1) sas = ShapeAnalysis_Surface(self.surf) print(sas.Value(u0, v0)) print(sas.Value(u0, v1)) print(sas.Value(u1, v0)) print(sas.Value(u1, v1)) u = u0 while u <= u1: v = v0 while v <= v1: p = sas.Value(u, v) self.display.DisplayShape(p, update=False) v += 1 / 3 u += 1 / 4
def sxy_tar(self): prf = self.dir + self.tar.name + "_" + "sz" + "_profile.txt" sx = float(getline(prf, 7).split()[1]) sy = float(getline(prf, 8).split()[1]) sxy = gp_Pnt(sx, sy, 0).Transformed(self.tar.trf) h_srf = BRep_Tool.Surface(self.tar.srf) self.tar.sxy = GeomAPI_ProjectPointOnSurf(sxy, h_srf).Point(1)
def getVectorTangentToCurveAtPoint(aEdge, uRatio): aCurve, aFP, aLP = BRep_Tool.Curve(aEdge) aP = aFP + (aLP - aFP) * uRatio v1 = gp_Vec() p1 = gp_Pnt() aCurve.D1(aP, p1, v1) return v1
def triangle_mesh_solid(solid, lin_tol=1e-2, ang_tol=0.5): """Computes a triangular mesh for a solid using BRepMesh. The resolution or quality of the mesh approximation can be adjusted with lin_tol and ang_tol (linear and angular tolerances). The computed mesh is returned as a tuple of lists: triangles - a list of each triangles' 3x vertices represented as indexes into the vertices list vertices - a list of the mesh's 3D vertices """ if isinstance(solid, Solid): obj = [solid.wrapped] elif isinstance(solid, list): obj = [x.wrapped for x in solid] else: obj = [solid] vertices = [] triangles = [] for o in obj: mesh = BRepMesh_IncrementalMesh(o, lin_tol, False, ang_tol) mesh.Perform() ms = Shape.cast(mesh.Shape()) bt = BRep_Tool() mesh_faces = ms.Faces() for mesh_face in mesh_faces: face = mesh_face.wrapped location = TopLoc_Location() facing = bt.Triangulation(face, location) tri = facing.Triangles() num_tri = facing.NbTriangles() vtx = facing.Nodes() txf = face.Location().Transformation() rev = (True if face.Orientation() == TopAbs_Orientation.TopAbs_REVERSED else False) for i in range(1, num_tri + 1): idx = list(tri.Value(i).Get()) ci = [0, 2, 1] if rev else [0, 1, 2] for j in ci: pt = [ vtx.Value(idx[j]).Transformed(txf).X(), vtx.Value(idx[j]).Transformed(txf).Y(), vtx.Value(idx[j]).Transformed(txf).Z(), ] if pt not in vertices: vertices.append(pt) idx[j] = vertices.index(pt) triangles.append(idx) return triangles, vertices
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() dump_topology_to_string(shp, level + 1, buffer)
def to_numpy(arg): if isinstance(arg, (gp_Vec, gp_Pnt, gp_Dir)): return numpy.array([arg.X(), arg.Y(), arg.Z()]) elif isinstance(arg, (TopoDS_Vertex)): arg = BRep_Tool.Pnt(arg) return numpy.array([arg.X(), arg.Y(), arg.Z()]) else: raise Exception("unresolved type", arg.__class__)
def EdgeSplitShapely(lst_edges): lines = [] for edge in lst_edges: t = Topo(edge) x_lst = [] y_lst = [] for vertex in t.vertices(): pnt = BRep_Tool().Pnt(vertex) x_lst.append(pnt.X()) y_lst.append(pnt.Y()) line = geometry.LineString([[x_lst[0],y_lst[0]],[x_lst[1],y_lst[1]]]) lines.append(line) multi_line = geometry.MultiLineString(lines) merge_line = ops.linemerge(multi_line) print(merge_line)
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 as_list(occ_obj): if type(occ_obj) not in [TopoDS_Vertex, gp_Pnt, gp_Dir, gp_Vec]: return None if type(occ_obj) is TopoDS_Vertex: occ_obj = BRep_Tool.Pnt(occ_obj) return list(occ_obj.Coord())
def uv_from_projected_point_on_face(face, pt): ''' returns the uv coordinate from a projected point on a face ''' srf = BRep_Tool().Surface(face) sas = ShapeAnalysis_Surface(srf) uv = sas.ValueOfUV(pt, 1e-2) print('distance', sas.Value(uv).Distance(pt)) return uv.Coord()