def shape_from_stl(filename): if not os.path.isfile(filename): raise FileNotFoundError("%s not found." % filename) stl_reader = StlAPI_Reader() the_shape = TopoDS_Shape() stl_reader.Read(the_shape, filename) if the_shape.IsNull(): raise AssertionError("Shape is null.") return the_shape
def read_stl_file(filename): """ opens a stl file, reads the content, and returns a BRep topods_shape object """ assert os.path.isfile(filename) stl_reader = StlAPI_Reader() the_shape = TopoDS_Shape() stl_reader.Read(the_shape, filename) assert not the_shape.IsNull() return the_shape
def read_stl_file(filename): """opens a stl file, reads the content, and returns a BRep topods_shape object""" if not os.path.isfile(filename): raise FileNotFoundError(f"{filename} not found.") the_shape = TopoDS_Shape() stlapi_Read(the_shape, filename) if the_shape.IsNull(): raise AssertionError("Shape is null.") return the_shape
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 read_cadfile(self, fileName, disp=True): print(fileName) base_dir = os.path.dirname(fileName) basename = os.path.basename(fileName) rootname, extname = os.path.splitext(fileName) if extname in [".stp", ".step"]: shpe = read_step_file(fileName) elif extname in [".igs", ".iges"]: shpe = read_iges_file(fileName) elif extname in [".stl"]: shpe = read_stl_file(fileName) elif extname in [".brep"]: shpe = TopoDS_Shape() builder = BRep_Builder() breptools_Read(shpe, fileName, builder) elif extname in [".geo"]: stlfile = self.import_geofile(fileName, 0.1) shpe = read_stl_file(stlfile) else: print("Incorrect file index") # sys.exit(0) if disp == True: self.display.DisplayShape(shpe, update=True) return shpe
def from_line_linear(cls, linear_mass_kg_per_m: float, linear_entity: TopoDS_Shape, cad_unit: str, name: str = ""): r"""Construct a Weight from linear mass [kg / m] and length. Parameters ---------- linear_mass_kg_per_m : Linear mass [kg/m] linear_entity : An OCC linear shape cad_unit : the 1D unit in which the linear_entity Shape is defined. name : name given to the mass """ linear_types = GlobalProperties.linear_types if topo_lut[linear_entity.ShapeType()] not in linear_types: msg = "topo_lut[linear_entity.ShapeType()] should be a linear type" logger.error(msg) raise AssertionError(msg) mass_kg = linear_mass_kg_per_m * convert( GlobalProperties(linear_entity).length, from_unit=cad_unit, to_unit="m") return Mass.from_line_fixed(mass_kg, linear_entity, cad_unit, name)
def from_volume_fixed(cls, mass_kg: float, volume: TopoDS_Shape, cad_unit: str, name: str = ""): r""" Construct a Mass with its CG at the CG of the volume. Parameters ---------- mass_kg : Total mass [kg] volume : An OCC volumic shape cad_unit : the 1D unit in which the volume Shape is defined. name : name given to the mass """ assert isinstance(mass_kg, (float, int)) assert (mass_kg >= 0.) assert topo_lut[volume.ShapeType()] in GlobalProperties.volumic_types obj = cls() obj._mass_kg = mass_kg position_gp_pnt = GlobalProperties(volume).centre position_m = position2positionm( Position(position_gp_pnt.X(), position_gp_pnt.Y(), position_gp_pnt.Z(), unit=cad_unit)) obj._cg_m = position_m obj._name = name return obj
def _union(lst): if len(lst) == 1: return lst[0] nrsize = 0 rsize = len(lst) // 2 + len(lst) % 2 narr = [TopoDS_Shape() for i in range(rsize)] for i in range(len(lst) // 2): narr[i] = occ_pair_union(lst[i].Shape(), lst[len(lst) - i - 1].Shape()) if len(lst) % 2: narr[rsize - 1] = lst[len(lst) // 2].Shape() while rsize != 1: nrsize = rsize // 2 + rsize % 2 for i in range(rsize // 2): narr[i] = occ_pair_union(narr[i], narr[rsize - i - 1]) if rsize % 2: narr[nrsize - 1] = narr[rsize // 2] rsize = nrsize return Shape(narr[0])
def read_stl(filepath): assert isinstance(filepath, Path) assert filepath.is_file() stl = TopoDS_Shape() reader = StlAPI_Reader() success = reader.Read(stl, str(filepath)) assert success return stl
def test_repr_overload(self) -> None: """Test if repr string is properly returned""" p = gp_Pnt(1, 2, 3) self.assertEqual(repr(p), "<class 'gp_Pnt'>") empty_shape = TopoDS_Shape() self.assertEqual(repr(empty_shape), "<class 'TopoDS_Shape': Null>") shp = BRepPrimAPI_MakeBox(10, 20, 30).Shape() self.assertEqual(repr(shp), "<class 'TopoDS_Solid'>")
def _from_brep(path): from zencad.geom.shape import Shape path = os.path.expanduser(path) shp = TopoDS_Shape() builder = BRep_Builder() breptools.Read(shp, path, builder) return Shape(shp)
def voxel_to_TopoDS(model, voxel_length, voxel_width, voxel_height): (position_x, position_y, position_z) = np.where(model.data) voxel = TopoDS_Compound() counter = TopoDS_Builder() counter.MakeCompound(voxel) for i in range(position_x.size): voxel1 = TopoDS_Shape( BRepPrimAPI_MakeBox(voxel_length, voxel_width, voxel_height).Shape()) transmat = gp_Trsf() x, y, z = position_x[i] * voxel_length, position_y[ i] * voxel_width, position_z[i] * voxel_height transmat.SetTranslation(gp_Vec(float(x), float(y), float(z))) location = TopLoc_Location(transmat) voxel1.Location(location) counter.Add(voxel, voxel1) return voxel
def get_type_as_string(topods_shape: TopoDS_Shape) -> str: """just get the type string, remove TopAbs_ and lowercas all ending letters""" types = { TopAbs_VERTEX: "Vertex", TopAbs_COMPSOLID: "CompSolid", TopAbs_FACE: "Face", TopAbs_WIRE: "Wire", TopAbs_EDGE: "Edge", TopAbs_COMPOUND: "Compound", TopAbs_COMPSOLID: "CompSolid", TopAbs_SOLID: "Solid", } return types[topods_shape.ShapeType()]
def load_shape(self, filename): self.shape_name = filename.split('/')[-1].split('.')[0] print(self.shape_name) self.shape = TopoDS_Shape() builder = BRep_Builder() breptools_Read(self.shape, filename, builder) cnt = 0 for face in TopologyExplorer(self.shape).faces(): self.face_ais[face] = display.DisplayShape(face) self.face_id[face] = cnt cnt += 1 self.face_label = [-1] * cnt
def move_to_box(iname, cname, wname, visualize=False): """Move foam to periodic box. Works on BREP files. Information about physical volumes is lost. Args: iname (str): input filename cname (str): output filename with cells wname (str): output filename with walls visualize (bool): show picture of foam morphology in box if True """ cells = TopoDS_Shape() builder = BRep_Builder() breptools_Read(cells, iname, builder) texp = TopologyExplorer(cells) solids = list(texp.solids()) cells = TopoDS_Compound() builder.MakeCompound(cells) box = BRepPrimAPI_MakeBox(gp_Pnt(1, -1, -1), 3, 3, 3).Shape() vec = gp_Vec(-1, 0, 0) solids = slice_and_move(solids, box, vec) box = BRepPrimAPI_MakeBox(gp_Pnt(-3, -1, -1), 3, 3, 3).Shape() vec = gp_Vec(1, 0, 0) solids = slice_and_move(solids, box, vec) box = BRepPrimAPI_MakeBox(gp_Pnt(-1, 1, -1), 3, 3, 3).Shape() vec = gp_Vec(0, -1, 0) solids = slice_and_move(solids, box, vec) box = BRepPrimAPI_MakeBox(gp_Pnt(-1, -3, -1), 3, 3, 3).Shape() vec = gp_Vec(0, 1, 0) solids = slice_and_move(solids, box, vec) box = BRepPrimAPI_MakeBox(gp_Pnt(-1, -1, 1), 3, 3, 3).Shape() vec = gp_Vec(0, 0, -1) solids = slice_and_move(solids, box, vec) box = BRepPrimAPI_MakeBox(gp_Pnt(-1, -1, -3), 3, 3, 3).Shape() vec = gp_Vec(0, 0, 1) solids = slice_and_move(solids, box, vec) create_compound(solids, cells, builder) breptools_Write(cells, cname) if visualize: display, start_display, _, _ = init_display() display.DisplayShape(cells, update=True) start_display() box = BRepPrimAPI_MakeBox(gp_Pnt(0, 0, 0), 1, 1, 1).Shape() walls = BRepAlgoAPI_Cut(box, cells).Shape() breptools_Write(walls, wname) if visualize: display, start_display, _, _ = init_display() display.DisplayShape(walls, update=True) start_display()
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)
def run_beam_face(self, beam0=gp_Ax3(), shpe=TopoDS_Shape(), tr=0): v0 = dir_to_vec(beam0.Direction()) v1 = dir_to_vec(beam0.XDirection()) p0 = beam0.Location() lin = gp_Lin(beam0.Axis()) api = BRepIntCurveSurface_Inter() api.Init(shpe, lin, 1.0E-9) dst = np.inf num = 0 sxy = p0 uvw = [0, 0, 0] fce = None while api.More(): p1 = api.Pnt() dst1 = p0.Distance(p1) if dst1 < dst and api.W() > 1.0E-6: dst = dst1 uvw = [api.U(), api.V(), api.W()] sxy = api.Pnt() fce = api.Face() api.Next() else: api.Next() print(*uvw) u, v, w = uvw surf = BRepAdaptor_Surface(fce) prop = BRepLProp_SLProps(surf, u, v, 2, 1.0E-9) p1, vx, vy = prop.Value(), prop.D1U(), prop.D1V() vz = vx.Crossed(vy) if vz.Dot(v0) > 0: vz.Reverse() vx.Normalize() vy.Normalize() vz.Normalize() beam1 = gp_Ax3(p1, vec_to_dir(v0.Reversed()), vec_to_dir(v1.Reversed())) norm1 = gp_Ax3(p1, vec_to_dir(vz), vec_to_dir(vx)) if tr == 0: beam1.Mirror(norm1.Ax2()) if beam1.Direction().Dot(norm1.Direction()) < 0: beam1.ZReverse() elif tr == 1: beam1.ZReverse() return beam1
def compute_cylinder(i): shape = TopoDS_Shape() builder = BRep_Builder() breptools_Read(shape, './face_pass_{}.brep'.format(i), builder) face = OCCUtils.Topo(shape).faces().__next__() iksolver = IKClient("127.0.0.1",8826) ttg = TurningToolpathGenerator(face,iksolver) #ttg.pitch = 1.0 ttg.v_initial_extension = 0 ttg.cutting_angle = 5 ttg.create_target_vis_edges = True ttg.makeHelixOnCyl() ttg.generate_tool_targets() ttg.write_target_edges("./pass_{}_targets.brep".format(i)) ttg.write_gcode("./pass_{}.ngc".format(i))
def from_line_fixed(cls, mass_kg: float, linear_entity: TopoDS_Shape, cad_unit: str, name: str = ""): r"""Construct a Mass with its CG at the CG of the linear entity. Parameters ---------- mass_kg : Total mass [kg] linear_entity : An OCC linear shape cad_unit : the 1D unit in which the linear_entity Shape is defined. name : name given to the mass """ if not isinstance(mass_kg, (float, int)): msg = "mass_kg should be a float or an int" logger.error(msg) raise ValueError(msg) if mass_kg < 0.: msg = "mass_kg should be positive or zero" logger.error(msg) raise ValueError(msg) if topo_lut[linear_entity.ShapeType( )] not in GlobalProperties.linear_types: msg = "linear_entity.ShapeType() should be a linear type" logger.error(msg) raise ValueError(msg) obj = cls() obj._mass_kg = mass_kg position_gp_pnt = GlobalProperties(linear_entity).centre position_m = position2positionm( Position(position_gp_pnt.X(), position_gp_pnt.Y(), position_gp_pnt.Z(), unit=cad_unit)) obj._cg_m = position_m obj._name = name return obj
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 test_check_shape(): r"""check_shape() tests""" # Null shapes should raise a ValueError with pytest.raises(ValueError): check_shape(TopoDS_Shape()) with pytest.raises(ValueError): check_shape(TopoDS_Shell()) builderapi_makeedge = BRepBuilderAPI_MakeEdge(gp_Pnt(), gp_Pnt(10, 10, 10)) shape = builderapi_makeedge.Shape() # a ValueError should be raised is check_shape() is not give # a TopoDS_Shape or subclass with pytest.raises(ValueError): check_shape(gp_Pnt()) with pytest.raises(ValueError): check_shape(builderapi_makeedge) # a TopoDS_Shape should pass the check without raising any exception check_shape(shape) # a subclass of shape should not raise any exception check_shape(Topo(shape, return_iter=False).edges[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.Core.BRepTools import breptools_Read from OCC.Core.TopoDS import TopoDS_Shape from OCC.Core.BRep import BRep_Builder shape = TopoDS_Shape() builder = BRep_Builder() breptools_Read(shape, brep_filepath, builder) return shape
def from_volume_volumic(cls, volumic_mass_kg_per_m3: float, volume: TopoDS_Shape, cad_unit: str, name: str): r"""Construct a Mass from volumic mass [kg/m3] and volume. The CG is at the CG of the volume. Parameters ---------- volumic_mass_kg_per_m3 : Volumic mass [kg/m3] volume : An OCC volumic shape cad_unit : the 1D unit in which the volume Shape is defined. name : name given to the mass """ if topo_lut[volume.ShapeType()] not in GlobalProperties.volumic_types: msg = "volume.ShapeType() should be of volumic type" logger.error(msg) raise ValueError(msg) mass_kg = volumic_mass_kg_per_m3 * convert( GlobalProperties(volume).volume, from_unit=f"{cad_unit}3", to_unit="m3") return Mass.from_volume_fixed(mass_kg, volume, cad_unit, name)
def from_surface_surfacic(cls, surfacic_mass_kg_per_m2: float, surface: TopoDS_Shape, cad_unit: str, name: str = ""): r"""Construct a Mass from surfacic mass [kg / m2] and surface. The CG is at the CG of the surface. Parameters ---------- surfacic_mass_kg_per_m2 : Surfacic mass [kg/m2] surface : An OCC surfacic shape cad_unit : the 1D unit in which the surface Shape is defined. name : name given to the mass """ assert topo_lut[surface.ShapeType()] in GlobalProperties.surfacic_types mass_kg = surfacic_mass_kg_per_m2 * convert( GlobalProperties(surface).area, from_unit=f"{cad_unit}2", to_unit="m2") return Mass.from_surface_fixed(mass_kg, surface, cad_unit, name)
def is_wire(topods_shape: TopoDS_Shape) -> bool: if not hasattr(topods_shape, "ShapeType"): return False return topods_shape.ShapeType() == TopAbs_WIRE
def test_repr_for_null_TopoDS_Shape(self): # create null vertex and shape v = TopoDS_Vertex() self.assertTrue('Null' in v.__repr__()) s = TopoDS_Shape() self.assertTrue('Null' in s.__repr__())
# tool tip target I = 0.001 J = 0.001 K = 0.001 # tool target direction U = 0.00 V = 0.00 W = 1.00 x,y,z,a,b = ik_client.solve((I,J,K,U,V,W),1e-6,False) """ ## Load the face for the first pass that was created earlier in FreeCAD shape = TopoDS_Shape() builder = BRep_Builder() breptools_Read(shape, './pass_2_surface.brep', builder) face = OCCUtils.Topo(shape).faces().__next__() ## Higher level use of the ik_client # The inverse kinematics solver gets invoked may times by TurningToolpathGenerator. ttg = TurningToolpathGenerator(face, ik_client) ttg.ball_radius = 25.4 / 16 ttg.cutting_angle = 5 ttg.inside = False # False -> cut outside ttg.reverse_helix = True ttg.initial_extension = 1 ttg.output_offset = [0, 0, 0, 90, 0] ttg.create_target_vis_edges = True
def get_brep(): cylinder_head = TopoDS_Shape() builder = BRep_Builder() breptools_Read(cylinder_head, '../assets/models/cylinder_head.brep', builder) return cylinder_head
def test_repr_for_null_topods_shapes(self): # create null vertex and shape v = TopoDS_Vertex() s = TopoDS_Shape() self.assertTrue('Null' in v.__repr__()) self.assertTrue('Null' in s.__repr__())
##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 threejs_renderer from OCC.Core.BRep import BRep_Builder from OCC.Core.TopoDS import TopoDS_Shape from OCC.Core.BRepTools import breptools_Read from OCC.Extend.TopologyUtils import TopologyExplorer # loads brep shape cylinder_head = TopoDS_Shape() builder = BRep_Builder() breptools_Read(cylinder_head, 'models/cylinder_head.brep', builder) # render cylinder head in x3dom my_renderer = threejs_renderer.ThreejsRenderer() all_faces = TopologyExplorer(cylinder_head).faces() # display each face for face in all_faces: my_renderer.DisplayShape(face) my_renderer.render()
def is_compsolid(topods_shape: TopoDS_Shape) -> bool: if not hasattr(topods_shape, "ShapeType"): return False return topods_shape.ShapeType() == TopAbs_COMPSOLID