def extrusion_to_solid(extrusion, name): from OCC.Core.BRepBuilderAPI import BRepBuilderAPI_Sewing, BRepBuilderAPI_MakeSolid from OCC.Core.TopoDS import topods from OCC.Core.BRepGProp import brepgprop_VolumeProperties from OCC.Core.GProp import GProp_GProps from OCCUtils.Topology import Topo d = extrusion_to_ruled_surfaces(extrusion, cap=True) sew = BRepBuilderAPI_Sewing() make_solid = BRepBuilderAPI_MakeSolid() faces = {} for k in d.keys(): faces[name + '_' + k] = d[k] sew.Add(d[k].Shape()) sew.Perform() shell = sew.SewedShape() make_solid.Add(topods.Shell(shell)) gp = GProp_GProps() #make_solid.Add(shell) solid = make_solid.Solid() brepgprop_VolumeProperties(shell, gp) print gp.Mass() return Part(name, faces, solid)
def centre_mass2(self): from OCC.Core.GProp import GProp_GProps from OCC.Core.BRepGProp import brepgprop_VolumeProperties, brepgprop_SurfaceProperties, \ brepgprop_LinearProperties props = GProp_GProps() brepgprop_VolumeProperties(self.m_w_frame, props) # Get inertia properties mass = props.Mass() cog = props.CentreOfMass() matrix_of_inertia = props.MatrixOfInertia() # Display inertia properties # print("Cube mass = %s" % mass) cog_x, cog_y, cog_z = cog.Coord() # print("Center of mass: x = %f;y = %f;z = %f;" % (cog_x, cog_y, cog_z)) mat = props.MatrixOfInertia() ####################################################################################### variation_inertial = abs(mat.Value(2, 3)) + abs(mat.Value(1, 2)) + abs( mat.Value(1, 3)) + abs(mat.Value(2, 1)) + abs(mat.Value( 3, 1)) + abs(mat.Value(3, 2)) var1, var2 = (cog_x**2 + cog_y**2 + cog_z**2)**0.5, variation_inertial if var1 < 0.0001 or var2 < 0.0001: var1, var2 = 10**10, 10**10 return var1, var2
def centre_mass_vizuall(self): flag = 0 shape = 0 for name in self.modules: if flag == 0: cp = BRepBuilderAPI_Copy(self.modules[name]) cp.Perform(self.modules[name]) shape = cp.Shape() flag = 1 shape = BRepAlgoAPI_Fuse(shape, self.modules[name]).Shape() props = GProp_GProps() brepgprop_VolumeProperties(shape, props) # Get inertia properties mass = props.Mass() cog = props.CentreOfMass() matrix_of_inertia = props.MatrixOfInertia() # Display inertia properties # print("Cube mass = %s" % mass) cog_x, cog_y, cog_z = cog.Coord() # print("Center of mass: x = %f;y = %f;z = %f;" % (cog_x, cog_y, cog_z)) mat = props.MatrixOfInertia() ####################################################################################### list_1 = [mat.Value(1, 1), mat.Value(1, 2), mat.Value(1, 3)] list_2 = [mat.Value(2, 1), mat.Value(2, 2), mat.Value(2, 3)] list_3 = [mat.Value(3, 1), mat.Value(3, 2), mat.Value(3, 3)] print('\t'.join(str(i) for i in list_1)) print('\t'.join(str(i) for i in list_2)) print('\t'.join(str(i) for i in list_3)) var1 = (cog_x**2 + cog_y**2 + cog_z**2)**0.5 print(var1)
def __init__(self, shape, tol=1.0e-7, only_closed=False, skip_shared=False): super(VolumeProps, self).__init__() brepgprop_VolumeProperties(shape.object, self._props, tol, only_closed, skip_shared)
def volume(self): """ :return: The voume of all solids of the shape. :rtype: float """ props = GProp_GProps() brepgprop_VolumeProperties(self.object, props, True) return props.Mass()
def one_obj_with_all(self, name): mass = 0 props = GProp_GProps() for body2 in self.modules: if name == body2: continue body_inter = BRepAlgoAPI_Common(self.modules[body2], self.modules[name]).Shape() # self.display.DisplayShape(body_inter, color='WHITE') brepgprop_VolumeProperties(body_inter, props) mass += props.Mass() return mass
def system(self): self._system = GProp_GProps() # todo, type should be abstracted with TopoDS... _topo_type = self.instance.topo_type if _topo_type == 'face' or _topo_type == 'shell': brepgprop_SurfaceProperties(self.instance, self._system) elif _topo_type == 'edge': brepgprop_LinearProperties(self.instance, self._system) elif _topo_type == 'solid': brepgprop_VolumeProperties(self.instance, self._system) return self._system
def get_volume(stepfile): from OCC.Core.GProp import GProp_GProps from OCC.Core.STEPControl import STEPControl_Reader from OCC.Core.BRepGProp import brepgprop_VolumeProperties step_reader = STEPControl_Reader() step_reader.ReadFile(stepfile) step_reader.TransferRoot() shape = step_reader.Shape() prop = GProp_GProps() brepgprop_VolumeProperties(shape, prop, 1e-5) return prop.Mass()
def inter_with_frame(self): # print('Start_inter_analyse') all_result = 0 props = GProp_GProps() # print(self.modules) for model in self.modules: # print('#') body_inter = BRepAlgoAPI_Common(self.frame, self.modules[model]).Shape() # self.display.DisplayShape(body_inter, color='YELLOW') brepgprop_VolumeProperties(body_inter, props) mass = props.Mass() if mass > 0: self.valume_inter[model] = props.Mass() all_result += mass return all_result
def cube_inertia_properties(): """ Compute the inertia properties of a shape """ # Create and display cube print("Creating a cubic box shape (50*50*50)") cube_shape = BRepPrimAPI_MakeBox(50., 50., 50.).Shape() # Compute inertia properties props = GProp_GProps() brepgprop_VolumeProperties(cube_shape, props) # Get inertia properties mass = props.Mass() cog = props.CentreOfMass() matrix_of_inertia = props.MatrixOfInertia() # Display inertia properties print("Cube mass = %s" % mass) cog_x, cog_y, cog_z = cog.Coord() print("Center of mass: x = %f;y = %f;z = %f;" % (cog_x, cog_y, cog_z))
def measure_shape_mass_center_of_gravity(shape): """Returns the shape center of gravity Returns a gp_Pnt if requested (set as_Pnt to True) or a list of 3 coordinates, by default.""" inertia_props = GProp_GProps() if is_edge(shape): brepgprop_LinearProperties(shape, inertia_props) mass_property = "Length" elif is_face(shape): brepgprop_SurfaceProperties(shape, inertia_props) mass_property = "Area" else: brepgprop_VolumeProperties(shape, inertia_props) mass_property = "Volume" cog = inertia_props.CentreOfMass() mass = inertia_props.Mass() return cog, mass, mass_property
def _centre_of_mass(shape): r""" Parameters ---------- shape : OCC Shape Returns ------- gp_Pnt """ from OCC.Core.BRepGProp import brepgprop_VolumeProperties from OCC.Core.GProp import GProp_GProps g = GProp_GProps() brepgprop_VolumeProperties(shape, g) return g.CentreOfMass()
def solid_volume(occsolid): """ This function calculates the volume of the OCCsolid. Parameters ---------- occsolid : OCCsolid The OCCsolid to be analysed. Returns ------- volume : float The volume of the solid. """ props = GProp_GProps() brepgprop_VolumeProperties(occsolid, props) volume = props.Mass() return volume
def reconstruct_object(array): from OCC.Core.BRepBuilderAPI import BRepBuilderAPI_Sewing, BRepBuilderAPI_MakeSolid from OCC.Core.BRepGProp import brepgprop_VolumeProperties from OCC.Core.GProp import GProp_GProps from OCC.Core.TopoDS import topods obj = BRepBuilderAPI_Sewing() for i, si in enumerate(array): obj.Add(si) obj.Perform() shell = obj.SewedShape() make_solid = BRepBuilderAPI_MakeSolid() make_solid.Add(topods.Shell(shell)) gp = GProp_GProps() #make_solid.Add(shell) solid = make_solid.Solid() brepgprop_VolumeProperties(shell, gp) print 'RECONSTRUCTED SOLID VOLUME :' print gp.Mass() return solid
def glue_solids(event=None): display.EraseAll() display.Context.RemoveAll(True) # Without common edges S1 = read_step_file(os.path.join('part_of_sattelate', 'pribore', 'DAV_WS16.STEP')) display.DisplayShape(S1, color='BLUE', transparency=0.9) measure(S1) # the face to glue S2 = read_step_file(os.path.join('part_of_sattelate', 'pribore', 'Camara_WS16.STEP')) trsf = gp_Trsf() trsf.SetTranslation(gp_Vec(750, 0, 0)) S2.Move(TopLoc_Location(trsf)) fuse_shp = BRepAlgoAPI_Fuse(S1, S2).Shape() props = GProp_GProps() brepgprop_VolumeProperties(fuse_shp, props) # Get inertia properties mass = props.Mass() cog = props.CentreOfMass() matrix_of_inertia = props.MatrixOfInertia() # Display inertia properties print("Cube mass = %s" % mass) cog_x, cog_y, cog_z = cog.Coord() print("Center of mass: x = %f;y = %f;z = %f;" % (cog_x, cog_y, cog_z)) display.DisplayShape(fuse_shp) #pstring = 'x: % \n y: % \n z: %' % (cog_x, cog_y, cog_z) pnt = gp_Pnt(cog_x, cog_y, cog_z) # display points display.DisplayShape(pnt, update=True) pnt = gp_Pnt(0, 0, 0) # display points display.DisplayShape(pnt, update=True) #display.DisplayMessage(pnt, pstring) display.FitAll()
def inter_with_frame2(self): from OCC.Core.GProp import GProp_GProps from OCC.Core.BRepAlgoAPI import BRepAlgoAPI_Fuse, BRepAlgoAPI_Common, BRepAlgoAPI_Section, BRepAlgoAPI_Cut from OCC.Core.BRepGProp import brepgprop_VolumeProperties, brepgprop_SurfaceProperties, \ brepgprop_LinearProperties # print('Start_inter_analyse') all_result = 0 props = GProp_GProps() # print(self.modules) for model in self.modules: # print('#') body_inter = BRepAlgoAPI_Common(self.frame, self.modules[model]).Shape() # self.display.DisplayShape(body_inter, color='YELLOW') brepgprop_VolumeProperties(body_inter, props) mass = props.Mass() # print(mass) if mass > 1e-6: # print(mass) all_result += 1 return all_result
def inter_objects2(self): # print('Start_inter_analyse') self.inter_mass = 0 props = GProp_GProps() for i in range(len(self.names_models) - 2): for j in range(i + 1, len(self.names_models) - 1): if self.names_models[i] == self.names_models[j]: continue body_inter = BRepAlgoAPI_Common( self.modules[self.names_models[i]], self.modules[self.names_models[j]]).Shape() # self.display.DisplayShape(body_inter, color='WHITE') brepgprop_VolumeProperties(body_inter, props) mass = props.Mass() # print(mass) if mass > 0: self.inter_mass += mass self.valume_inter_obj[self.names_models[i]][ self.names_models[j]] = mass return self.inter_mass
def centre_mass(self, shape): props = GProp_GProps() brepgprop_VolumeProperties(shape, props) # Get inertia properties mass = props.Mass() cog = props.CentreOfMass() matrix_of_inertia = props.MatrixOfInertia() # Display inertia properties # print("Cube mass = %s" % mass) cog_x, cog_y, cog_z = cog.Coord() # print("Center of mass: x = %f;y = %f;z = %f;" % (cog_x, cog_y, cog_z)) mat = props.MatrixOfInertia() ####################################################################################### variation_inertial = abs(mat.Value(2, 3)) + abs(mat.Value(1, 2)) + abs( mat.Value(1, 3)) + abs(mat.Value(2, 1)) + abs(mat.Value( 3, 1)) + abs(mat.Value(3, 2)) var1, var2 = (cog_x**2 + cog_y**2 + cog_z**2)**0.5, variation_inertial if var1 < 0.0001 or var2 < 0.0001: var1, var2 = 10**10, 10**10 return var1, var2
def calc_volume(s): props = GProp_GProps() brepgprop_VolumeProperties(s.geometry, props) return props.Mass()
def volume(self): '''returns the volume of a solid ''' prop = GProp_GProps() brepgprop_VolumeProperties(self.shape, prop, self.tolerance) return prop
def mesh_model(model, max_size=1e-5, tolerance=1e-7, repair=False, terminal=1): # In/Output definitions fil = model.split("/")[-1][:-5] folder = "/".join(model.split("/")[:-1]) scale_factor = 1000.0 verts = [] norms = [] faces = [] curvs = [] vert_map = {} d1_feats = [] d2_feats = [] t_curves = [] #norm_map = {} with fileinput.FileInput(model, inplace=True) as fi: for line in fi: print(line.replace( "UNCERTAINTY_MEASURE_WITH_UNIT( LENGTH_MEASURE( 1.00000000000000E-06 )", "UNCERTAINTY_MEASURE_WITH_UNIT( LENGTH_MEASURE( 1.00000000000000E-17 )" ), end='') stats = {} # OCC definitions occ_steps = read_step_file(model) stats["#parts"] = len(occ_steps) stats["model"] = model print("Reading step %s with %i parts." % (model, len(occ_steps))) #tot = 0 #for s in occ_steps: # occ_topo = TopologyExplorer(s) # print(s) # print(len(list(occ_topo.edges()))) # tot += len(list(occ_topo.edges())) occ_cnt = 0 bbox = get_boundingbox(occ_steps[occ_cnt], use_mesh=True) diag = np.sqrt(bbox[6]**2 + bbox[7]**2 + bbox[8]**2) max_length = diag * max_size #, 9e-06 tolerance = diag * tolerance #print(fil, diag, max_length, tolerance) stats["bbox"] = bbox stats["max_length"] = float(max_length) stats["tolerance"] = float(tolerance) stats["diag"] = float(diag) occ_topo = TopologyExplorer(occ_steps[occ_cnt]) occ_top = Topo(occ_steps[occ_cnt]) occ_props = GProp_GProps() occ_brt = BRep_Tool() # Gmsh definitions gmsh.initialize() gmsh.clear() gmsh.option.setNumber("General.Terminal", terminal) gmsh.option.setNumber("Geometry.Tolerance", tolerance) gmsh.option.setNumber("Geometry.OCCFixDegenerated", 0) gmsh.option.setNumber("Geometry.OCCFixSmallEdges", 0) gmsh.option.setNumber("Geometry.OCCFixSmallFaces", 0) gmsh.option.setNumber("Geometry.OCCSewFaces", 0) gmsh.option.setNumber("Mesh.CharacteristicLengthMax", max_length) gmsh.open(model) # Gmsh meshing #gmsh.model.mesh.generate(1) #gmsh.model.mesh.refine() #gmsh.model.mesh.refine() gmsh.model.mesh.generate(2) #gmsh.write("results/" + file + ".stl") gmsh_edges = gmsh.model.getEntities(1) gmsh_surfs = gmsh.model.getEntities(2) #print("O", tot, "G", len(gmsh_edges)) #continue gmsh_entities = gmsh.model.getEntities() #gmsh.model.occ.synchronize() #print(dir(gmsh.model.occ)) total_edges = 0 total_surfs = 0 for l in range(len(occ_steps)): topo = TopologyExplorer(occ_steps[l]) total_edges += len(list(topo.edges())) total_surfs += len(list(topo.faces())) vol = brepgprop_VolumeProperties(occ_steps[l], occ_props, tolerance) #print(dir(occ_props), dir(occ_props.PrincipalProperties()), dir(occ_props.volume()), occ_props.Mass()) sur = brepgprop_SurfaceProperties(occ_steps[l], occ_props, tolerance) #print(vol, "Test", sur) stats["#edges"] = total_edges stats["#surfs"] = total_surfs stats["volume"] = vol stats["surface"] = sur stats["curves"] = [] stats["surfs"] = [] stats["#points"] = 0 print("Number of surfaces: %i, Number of curves: %i" % (total_surfs, total_edges)) #print(total_edges, total_surfs, len(gmsh_edges), len(gmsh_surfs)) if not total_edges == len(gmsh_edges): print("Skipping due to wrong EDGES", model) return if not total_surfs == len(gmsh_surfs): print("Skipping due to wrong SURFS", model) return #print("Reading curvature") v_cnt = 1 v_nodes = [] occ_offset = 0 invalid_model = False c_cnt = 0 #v_cont_cnt = 0 #print(len(list(occ_topo.edges())), len(list(occ_topo.solids())), len(list(occ_topo.faces())), len(list(occ_topo.vertices()))) for e in gmsh_entities[:]: #print(e) nodeTags, nodeCoords, nodeParams = gmsh.model.mesh.getNodes( e[0], e[1], True) elemTypes, elemTags, elemNodeTags = gmsh.model.mesh.getElements( e[0], e[1]) n_id = e[1] - occ_offset #print(e, occ_offset, n_id) #print(e, nodeTags, nodeCoords, nodeParams, gmsh.model.getType(e[0], e[1]), elemTypes, elemTags, elemNodeTags) if e[0] == 0: # Process points #print(e[1], nodeCoords) vert_map[e[1]] = v_cnt verts.append([ nodeCoords[0] * 1000.0, nodeCoords[1] * 1000.0, nodeCoords[2] * 1000.0 ]) v_cnt += 1 stats["#points"] += 1 #pass if e[0] == 1: # Process contours if n_id - 1 == len(list(occ_topo.edges())): #print("CNT", occ_cnt) occ_cnt += 1 occ_offset = e[1] - 1 n_id = 1 occ_topo = TopologyExplorer(occ_steps[occ_cnt]) occ_top = Topo(occ_steps[occ_cnt]) #print("Defunct curve", n_id, len(list(occ_topo.edges()))) #continue #print(n_id) curve = BRepAdaptor_Curve(list(occ_topo.edges())[n_id - 1]) # Add type and parametric nodes/indices #print("type", edge_map[curve.GetType()]) if gmsh.model.getType(e[0], e[1]) == "Unknown": #print("Skipping OtherCurve", nodeTags) continue for i, n in enumerate(nodeTags): if n >= v_cnt: vert_map[n] = v_cnt verts.append([ nodeCoords[i * 3] * 1000.0, nodeCoords[i * 3 + 1] * 1000.0, nodeCoords[i * 3 + 2] * 1000.0 ]) v_cnt += 1 else: print(n, v_cnt) #print(v_ind, type(v_ind), v_par, type(v_par)) stats["curves"].append(edge_map[curve.GetType()]) #print(n_id, edge_map[curve.GetType()], gmsh.model.getType(e[0], e[1])) #print(list(occ_topo.edges()), n_id-1) c_type = edge_map[curve.GetType()] #gmsh.model.getType(e[0], e[1]) if not gmsh.model.getType(e[0], e[1]) == edge_map[curve.GetType()]: print("Skipped due to non matching edges ", model, gmsh.model.getType(e[0], e[1]), edge_map[curve.GetType()]) #invalid_model = True #break d1_feat = convert_curve(curve) edg = list(occ_topo.edges())[n_id - 1] for f in occ_top.faces_from_edge(edg): #ee = (e) #print(dir(ee)) #d1_feat = {} su = BRepAdaptor_Surface(f) c = BRepAdaptor_Curve2d(edg, f) t_curve = { "surface": f, "3dcurve": c_cnt, "2dcurve": convert_2dcurve(c) } #print(edge_map[c.GetType()], surf_map[su.GetType()], edge_map[curve.GetType()]) #d1f = convert_2dcurve(c) #print(d1f) #ccnt += 1 #print(d1_feat) t_curves.append(t_curve) if len(elemNodeTags) > 0: #v_ind = [int(elemNodeTags[0][0]) - 1] # first vertex v_ind = [int(nodeTags[-2]) - 1] for no in nodeTags[:-2]: v_ind.append(int(no) - 1) # interior vertices v_ind.append(int(nodeTags[-1]) - 1) #v_ind.append(int(elemNodeTags[0][-1]) - 1) # last vertex d1_feat["vert_indices"] = v_ind #v_par = [float(curve.FirstParameter())] # first param v_par = [float(nodeParams[-2] * scale_factor)] for no in nodeParams[:-2]: v_par.append(float(no * scale_factor)) # interior params v_par.append(float(nodeParams[-1] * scale_factor)) #v_par.append(float(curve.LastParameter())) # last param d1_feat["vert_parameters"] = v_par else: print("No nodetags", edge_map[curve.GetType()], elemNodeTags) #print("VERTS", len(d1_feat["vert_indices"]), len(d1_feat["vert_parameters"])) d1_feats.append(d1_feat) c_cnt += 1 #t_curve = curve.Trim(curve.FirstParameter(), curve.LastParameter(), 0.0001).GetObject() #print(curve.FirstParameter(), curve.LastParameter()) #print("Processing surfaces") gmsh_entities = gmsh.model.getEntities(2) n_cnt = 1 occ_offset = 0 occ_cnt = 0 occ_topo = TopologyExplorer(occ_steps[occ_cnt]) occ_top = Topo(occ_steps[occ_cnt]) f_cnt = 0 f_sum = 0 first_face = True mean_curv = 0.0 curv_cnt = 0 gaus_curv = 0.0 s_cnt = 0 for e in gmsh_entities[:]: #print(e) nodeTags, nodeCoords, nodeParams = gmsh.model.mesh.getNodes( e[0], e[1], True) elemTypes, elemTags, elemNodeTags = gmsh.model.mesh.getElements( e[0], e[1]) n_id = e[1] - occ_offset #print(e, occ_offset, n_id) #print(e, nodeTags, nodeCoords, nodeParams, gmsh.model.getType(e[0], e[1]), elemTypes, elemTags, elemNodeTags) if e[0] == 2: #print(e, gmsh.model.getType(e[0], e[1]), elemTypes) if n_id - 1 == len(list(occ_topo.faces())): #print("CNT", occ_cnt) occ_cnt += 1 occ_offset = e[1] - 1 n_id = 1 occ_topo = TopologyExplorer(occ_steps[occ_cnt]) occ_top = Topo(occ_steps[occ_cnt]) if "getNormals" in dir(gmsh.model): nls = gmsh.model.getNormals(e[1], nodeParams) else: nls = gmsh.model.getNormal(e[1], nodeParams) curvMax, curvMin, dirMax, dirMin = gmsh.model.getPrincipalCurvatures( e[1], nodeParams) #surf = BRepAdaptor_Surface(list(occ_topo.faces())[n_id-1]) norm_map = {} for i, n in enumerate(nodeTags): norms.append([nls[i * 3], nls[i * 3 + 1], nls[i * 3 + 2]]) curvs.append([ curvMin[i], curvMax[i], dirMin[i * 3], dirMin[i * 3 + 1], dirMin[i * 3 + 2], dirMax[i * 3], dirMax[i * 3 + 1], dirMax[i * 3 + 2] ]) curv_cnt += 1 mean_curv += (curvMin[i] + curvMax[i]) / 2.0 gaus_curv += (curvMin[i] * curvMax[i]) norm_map[n] = n_cnt n_cnt += 1 if n in vert_map.keys(): v = verts[vert_map[n] - 1] #print("Vert contained", n) #v_cont_cnt += 1 # assert(v[0] == nodeCoords[i*3] * 1000.0 and v[1] == nodeCoords[i*3+1] * 1000.0 and v[2] == nodeCoords[i*3+2] * 1000.0) continue else: vert_map[n] = v_cnt #occ_node = surf.Value(nodeParams[i], nodeParams[i+1]) #vertices.append([occ_node.X(), occ_node.Y(), occ_node.Z()]) verts.append([ nodeCoords[i * 3] * 1000.0, nodeCoords[i * 3 + 1] * 1000.0, nodeCoords[i * 3 + 2] * 1000.0 ]) #print("S", occ_node.Coord(), [nodeCoords[i*3]*1000, nodeCoords[i*3+1]*1000, nodeCoords[i*3+2]*1000]) #print(occ_node.Coord(), nodeCoords[i*3:(i+1)*3]) v_cnt += 1 d2_faces = [] for i, t in enumerate(elemTypes): for j in range(len(elemTags[i])): faces.append([ vert_map[elemNodeTags[i][j * 3]], vert_map[elemNodeTags[i][j * 3 + 1]], vert_map[elemNodeTags[i][j * 3 + 2]], norm_map[elemNodeTags[i][j * 3]], norm_map[elemNodeTags[i][j * 3 + 1]], norm_map[elemNodeTags[i][j * 3 + 2]] ]) d2_faces.append(f_cnt) f_cnt += 1 #print(len(list(occ_topo.faces())), n_id-1) surf = BRepAdaptor_Surface(list(occ_topo.faces())[n_id - 1]) #print("type", edge_map[curve.GetType()]) #if gmsh.model.getType(e[0], e[1]) == "Unknown": # print("Skipping OtherCurve", nodeTags) # continue #print(surf) g_type = gmsh_map[gmsh.model.getType(e[0], e[1])] if g_type != "Other" and not g_type == surf_map[surf.GetType()]: print("Skipped due to non matching surfaces ", model, g_type, surf_map[surf.GetType()]) #invalid_model = True #break stats["surfs"].append(surf_map[surf.GetType()]) d2_feat = convert_surface(surf) d2_feat["face_indices"] = d2_faces for tc in t_curves: if tc["surface"] == list(occ_topo.faces())[n_id - 1]: tc["surface"] = s_cnt if len(elemNodeTags) > 0: #print(len(elemNodeTags[0]), len(nodeTags), len(nodeParams)) v_ind = [] #int(elemNodeTags[0][0])] # first vertex for no in nodeTags: v_ind.append(int(no) - 1) # interior vertices #v_ind.append(int(elemNodeTags[0][-1])) # last vertex d2_feat["vert_indices"] = v_ind v_par = [] #float(surf.FirstParameter())] # first param for io in range(int(len(nodeParams) / 2)): v_par.append([ float(nodeParams[io * 2] * scale_factor), float(nodeParams[io * 2 + 1] * scale_factor) ]) # interior params #v_par.append(float(surf.LastParameter())) # last param d2_feat["vert_parameters"] = v_par else: print("No nodetags", edge_map[curve.GetType()], elemNodeTags) f_sum += len(d2_feat["face_indices"]) d2_feats.append(d2_feat) s_cnt += 1 if invalid_model: return stats["#sharp"] = 0 stats["gaus_curv"] = float(gaus_curv / curv_cnt) stats["mean_curv"] = float(mean_curv / curv_cnt) if not f_sum == len(faces): print("Skipping due to wrong FACES", model) return if True: vert2norm = {} for f in faces: #print(f) for fii in range(3): if f[fii] in vert2norm: vert2norm[f[fii]].append(f[fii + 3]) else: vert2norm[f[fii]] = [f[fii + 3]] for d1f in d1_feats: sharp = True for vi in d1f["vert_indices"][1:-1]: #print(vi, vert2norm.keys()) nos = list(set(vert2norm[vi + 1])) if len(nos) == 2: n0 = np.array(norms[nos[0]]) n1 = np.array(norms[nos[1]]) #print(np.linalg.norm(n0), np.linalg.norm(n1)) if np.abs(n0.dot(n1)) > 0.95: sharp = False #break else: sharp = False if sharp: stats["#sharp"] += 1 d1f["sharp"] = sharp stats["#verts"] = len(verts) stats["#faces"] = len(faces) stats["#norms"] = len(norms) #with open("results/" + file + ".json", "w") as fil: # json.dump(d1_feats, fil, sort_keys=True, indent=2) #with open("results/" + file + "_faces.json", "w") as fil: # json.dump(d2_feats, fil, sort_keys=True, indent=2) features = {"curves": d1_feats, "surfaces": d2_feats, "trim": t_curves} if True: res_path = folder.replace("/step/", "/feat/") fip = fil.replace("_step_", "_features_") print("%s/%s.yml" % (res_path, fip)) with open("%s/%s.yml" % (res_path, fip), "w") as fili: yaml.dump(features, fili, indent=2) res_path = folder.replace("/step/", "/stat/") fip = fil.replace("_step_", "_stats_") with open("%s/%s.yml" % (res_path, fip), "w") as fili: yaml.dump(stats, fili, indent=2) print("Generated model with %i vertices and %i faces." % (len(verts), len(faces))) res_path = folder.replace("/step/", "/obj/") fip = fil.replace("_step_", "_trimesh_") with open("%s/%s.obj" % (res_path, fip), "w") as fili: for v in verts: fili.write("v %f %f %f\n" % (v[0], v[1], v[2])) for vn in norms: #print(np.linalg.norm(vn)) fili.write("vn %f %f %f\n" % (vn[0], vn[1], vn[2])) for vn in curvs: fili.write( "vc %f %f %f %f %f %f %f %f\n" % (vn[0], vn[1], vn[2], vn[3], vn[4], vn[5], vn[6], vn[7])) for f in faces: fili.write("f %i//%i %i//%i %i//%i\n" % (f[0], f[3], f[1], f[4], f[2], f[5])) faces = np.array(faces) face_indices = faces[:, :3] - 1 norm_indices = faces[:, 3:] - 1 gmsh.clear() gmsh.finalize() #print(curvs) return { "statistics": stats, "features": features, "vertices": np.array(verts), "normals": np.array(norms), "curvatures": np.array(curvs), "face_indices": face_indices, "normal_indices": norm_indices, "trim": t_curves }
def inter_one_object_frame(self, name): props = GProp_GProps() body_inter = BRepAlgoAPI_Common(self.frame, self.modules[name]).Shape() brepgprop_VolumeProperties(body_inter, props) # print(props.Mass()) return props.Mass()
def measure_shape_volume(shape): """Returns shape volume""" inertia_props = GProp_GProps() brepgprop_VolumeProperties(shape, inertia_props) mass = inertia_props.Mass() return mass
def cal_vol(self, shp=TopoDS_Shape()): brepgprop_VolumeProperties(shp, self.prop) return self.prop.Mass()
def calc_volume(s): props = OCC.Core.GProp.GProp_GProps() brepgprop_VolumeProperties(s, props) return props.Mass()
def inter_with_frame(self): # print('Start_inter_analyse') #print(self.names_models) all_result = 0 props = GProp_GProps() # self.display.DisplayShape(body_inter, color='YELLOW') brepgprop_VolumeProperties(self.frame, props) mass_frame = props.Mass() cp = BRepBuilderAPI_Copy(self.frame) cp.Perform(self.frame) shape = cp.Shape() builder = BOPAlgo_Builder() for name in self.modules: builder.AddArgument(self.modules[name]) builder.SetRunParallel(True) builder.Perform() models = builder.Shape() props = GProp_GProps() # self.display.DisplayShape(body_inter, color='YELLOW') brepgprop_VolumeProperties(models, props) mass_models = props.Mass() mass_1 = mass_frame + mass_models '''builder = BOPAlgo_Builder() builder.AddArgument(shape) builder.AddArgument(models) builder.SetRunParallel(True) builder.Perform() m_w_frame = builder.Shape()''' self.m_w_frame = BRepAlgoAPI_Fuse(shape, models).Shape() # self.display.DisplayShape(m_w_frame, color='YELLOW', transparency=0.9) props = GProp_GProps() brepgprop_VolumeProperties(self.m_w_frame, props) mass_2 = props.Mass() mass = mass_1 - mass_2 # print(self.modules) '''for model in self.modules: # print('#') props = GProp_GProps() new_shape = BRepAlgoAPI_Cut(shape, self.modules[model]).Shape() # self.display.DisplayShape(body_inter, color='YELLOW') brepgprop_VolumeProperties(new_shape, props) mass_frame_2 = props.Mass() self.display.DisplayShape(new_shape, color='YELLOW', transparency=0.9) mass = mass_frame - mass_frame_2 props = GProp_GProps() inter = TopOpeBRep_ShapeIntersector() inter.InitIntersection(self.modules[model], self.frame) flag = inter.MoreIntersection() body_inter = inter.CurrentGeomShape(1) brepgprop_VolumeProperties(body_inter, props) mass = props.Mass() props = GProp_GProps() body_inter = inter.CurrentGeomShape(2) brepgprop_VolumeProperties(body_inter, props) mass = abs(mass) + abs(props.Mass()) dss = BRepExtrema_DistShapeShape() dss.LoadS1(self.modules[model]) dss.LoadS2(self.frame) dss.Perform() flag = dss.IsDone() mass = dss.Value() print(mass) print(flag)''' print(mass) if mass > 1e-6: # print(mass) all_result += 1 return all_result
#display.DisplayMessage(pnt, pstring) display.FitAll() #S2 += S1 #display.DisplayShape(S2, color='RED', transparency=0.9) #kode to move #trsf = gp_Trsf() ''' trsf.SetTranslation(gp_Vec(750, 0, 0)) shp.Move(TopLoc_Location(trsf)) display.EraseAll() display.DisplayShape(shp, update=True) ''' ''' props = GProp_GProps() brepgprop_VolumeProperties(shp, props) # Get inertia properties mass = props.Mass() cog = props.CentreOfMass() matrix_of_inertia = props.MatrixOfInertia() # Display inertia properties print("Cube mass = %s" % mass) cog_x, cog_y, cog_z = cog.Coord() print("Center of mass: x = %f;y = %f;z = %f;" % (cog_x, cog_y, cog_z)) ''' glue_solids() start_display()
def count_volume_from_shape(shape: TopoDS_Shape): props = GProp_GProps() brepgprop_VolumeProperties(shape, props) return props.Mass()