def check_all_shapes(flist): document_name = "all_shapes" App.newDocument(document_name) for f in flist: Part.insert(f, document_name) # doc = App.getDocument(document_name) objs = App.ActiveDocument.Objects solids = [] origVols = [] origBboxes = [] for obj in objs: bb = obj.Shape.BoundBox v = obj.Shape.Volume if verbosity: print(bb) print(v) origVols.append(v) origBboxes.append(bb) solids.append(obj.Shape) tol = 0.0 pieces, map = solids[0].generalFuse(solids[1:], tol) result_fragments = pieces.Solids for i, solid in enumerate(result_fragments): if not float_equal(origVols[i], solid.Volume): print("volume_change as", origVols[i], solid.Volume) check_similarity(origBboxes[i], solid.BoundBox) App.ActiveDocument.closeDocument()
def test_exportCAD(): myDoc = FreeCAD.newDocument('testDoc') testDir = os.path.join(repo_path(), 'tests') filePath = os.path.join(testDir, 'testExport.step') from qmt.freecad.geomUtils import makeBB testBB = (-1., 1., -2., 2., -3., 3.) testShape = makeBB(testBB) exportCAD(testShape, filePath) import Part Part.insert(filePath, 'testDoc') CADImport = myDoc.getObject("testExport") xMin = CADImport.Shape.BoundBox.XMin xMax = CADImport.Shape.BoundBox.XMax yMin = CADImport.Shape.BoundBox.YMin yMax = CADImport.Shape.BoundBox.YMax zMin = CADImport.Shape.BoundBox.ZMin zMax = CADImport.Shape.BoundBox.ZMax assert testBB == (xMin, xMax, yMin, yMax, zMin, zMax) os.remove(filePath) with pytest.raises(ValueError) as err: exportCAD(testShape, 'not_a_step_file') assert 'does not end' in str(err.value) FreeCAD.closeDocument('testDoc')
def get_boundbox(filename): _, fname = os.path.split(filename) document_name = fname.split(".")[0] App.newDocument(document_name) Part.insert(filename, document_name) # doc = App.getDocument(document_name) obj = App.ActiveDocument.Objects[0] # get the first and only obj for brep # print(obj.Label) if hasattr(obj, "Shape"): bbox = obj.Shape.BoundBox App.closeDocument(App.ActiveDocument.Name) return bbox
def load_shape(filename): # this function does not work properly on multiple files _, fname = os.path.split(filename) document_name = fname.split(".")[0] App.newDocument(document_name) Part.insert(filename, document_name) # doc = App.getDocument(document_name) obj = App.ActiveDocument.Objects[0] # get the first and only obj for brep print(obj.Label) s = None if hasattr(obj, "Shape"): s = obj.Shape App.closeDocument(App.ActiveDocument.Name) return s # it is possible to return shape after document close
def validate(self): self._setUp() # this method should be override if result is not single DocumentObject assert os.path.exists(self.geometry_file) default_document_name = self.__class__.__name__ + "_processed" App.newDocument(default_document_name) Part.insert(self.output_geometry_file, default_document_name) doc = App.getDocument(default_document_name) obj = doc.Objects[0] # get the first and only obj for brep if hasattr(obj, "Shape"): shape = obj.Shape self.validate_geometry(shape) # tear down App.closeDocument( default_document_name) # will this be done if failed?
def importGeometryAndMesh(geo_file, mesh_file): # caller guarant input parameter is valid path and type, each is a tuple of (filename, suffix) docname = FreeCAD.ActiveDocument.Name if geo_file: if isinstance(geo_file, (str, unicode)) and os.path.exists(geo_file): geo_suffix = geo_file.split(u'.')[-1] #if geo_suffix not in [u'iges', u'igs', u'step', u'stp', u'brep', u'fcstd']: # should be done in caller # FreeCAD.Console.PrintError(u"only step, brep, fcstd and iges geometry files are supported, while input file suffix is: {}".format(geo_suffix)) # return False # there must be a document to import objects #FreeCADGui.addModule("Part") #FreeCADGui.doCommand("Part.insert(u'" + geo_file + "','" + docname + "')") import Part Part.insert(geo_file, docname) part_obj = FreeCAD.ActiveDocument.ActiveObject elif geo_file.isDerivedFrom("Part::Feature"): part_obj = geo_file else: FreeCAD.Console.PrintError( "part should be provided as a valid file path or Part::Feature dervied Object" ) mesh_suffix = mesh_file.split(u'.')[-1] #if mesh_suffix not in [u'unv', u'inp', u'vtk', u'vtu', u'med']: # any type supported by FemMesh import # FreeCAD.Console.PrintError(u"input file suffix: {}, is NOT supported for mesh importing".format(geo_suffix)) # return False import Fem fem_mesh = Fem.read(mesh_file) # Fem.insert() gives <Fem::FemMeshObject object> can not add dynamic property # mesh must NOT been scaled to metre, or using LengthUnit property! if fem_mesh: #mesh_obj.isDerivedFrom("Part::FeaturePython"): import CfdObjects mesh_obj = CfdObjects.makeCfdMeshImported() mesh_obj.FemMesh = fem_mesh mesh_obj.Part = part_obj mesh_obj.Imported = True mesh_obj.ImportedMeshPath = mesh_file FreeCAD.Console.PrintMessage( 'The Part should have an FEM mesh imported') return mesh_obj else: FreeCAD.Console.PrintError( 'Mesh importing failed for {}'.format(mesh_file)) return False
def importGeometryAndMesh(geo_file, mesh_file): # caller guarant input parameter is valid path and type, each is a tuple of (filename, suffix) docname = FreeCAD.ActiveDocument.Name if geo_file: if os.path.exists(geo_file): geo_suffix = geo_file.split(u'.')[-1] if geo_suffix not in [u'iges', u'igs', u'step', u'stp', u'brep']: FreeCAD.Console.PrintError(u"only step, brep and iges geometry files are supported, while input file suffix is: {}".format(geo_suffix)) return False # there must be a document to import objects #FreeCADGui.addModule("Part") #FreeCADGui.doCommand("Part.insert(u'" + geo_file + "','" + docname + "')") import Part Part.insert(geo_file , docname) part_obj = FreeCAD.ActiveDocument.ActiveObject elif geo_file.isDerivedFrom("Part::Feature"): part_obj = geo_file else: part_obj = None mesh_suffix = mesh_file.split(u'.')[-1] if mesh_suffix not in [u'unv', u'inp', u'vtk', u'vtu', u'med']: FreeCAD.Console.PrintError(u"input file suffix: {}, is NOT supported for mesh importing".format(geo_suffix)) return False import Fem fem_mesh = Fem.read(mesh_file) #FreeCADGui.addModule("Fem") #FreeCADGui.doCommand("Fem.read(u'" + mesh_file + "')") # Fem.insert() gives <Fem::FemMeshObject object> can not add dynamic property # mesh must NOT been scaled to metre, or using LengthUnit property if fem_mesh: #mesh_obj.isDerivedFrom("Part::FeaturePython"): #FreeCADGui.addModule("CfdObjects") # FemGmsh has been adjusted for CFD like only first order element #FreeCADGui.doCommand("CfdObjects.makeCfdMeshImported('" + mesh_obj_name + "')") import CfdObjects mesh_obj = CfdObjects.makeCfdMeshImported() mesh_obj.FemMesh = fem_mesh mesh_obj.Part = part_obj FreeCAD.Console.PrintMessage('The Part should have an FEM mesh imported') return mesh_obj else: FreeCAD.Console.PrintError('Mesh importing failed for {}'.format(mesh_file))
def extract_assembly_points(step_path, step_name, doc_path, obj_path, part_type): global unique_radius """extract assembly_points from step file Arguments: step_path {string} -- [step file path] Returns: assembly_points {list} -- [list of assembly_point] assembly_point {dict} -- { "id": int "pose": { "xyz": [float list] "quaternion": [float list] } "is_used": False } """ # create document doc_name = step_name doc = FreeCAD.newDocument(doc_name) # load step to document FreeCAD.setActiveDocument(doc.Name) Part.insert(step_path, doc.Name) obj = doc.ActiveObject obj.Label = part_type.value Mesh.export([obj], obj_path) #region extract circles reverse_condition = hole_condition[step_name] circles = get_circles(obj, reverse_condition) if "pin" in step_name: mid_circle1 = copy.deepcopy(circles[0]) mid_circle2 = copy.deepcopy(circles[1]) position = [val1/2 + val2/2 for val1, val2 in zip(mid_circle1.position, mid_circle2.position)] mid_circle1.position = position mid_circle2.position = position circles += [mid_circle1, mid_circle2] #endregion # extract circle holes circle_holes = get_circle_holes(circles) # if "bolt_side" in step_name: # mid_circle = copy.deepcopy(circles[-1]) # position = [val1/2 + val2/2 for val1, val2 in zip(circles[0].position, circles[-1].position)] # mid_circle.position = position # added_circles = [mid_circle, circles[-1]] # circle_holes += get_circle_holes(added_circles) for hole in circle_holes: hole.create_hole() hole.visualize_hole(doc) hole.set_hole_type(doc, obj) hole.remove_hole(doc) # TODO: if not to do this error occur when assembly for cir in hole.circle_group: cir.visualize_circle(doc) # hole.visualize_frame(doc) if hole.radius in unique_radius: pass else: unique_radius.append(hole.radius) unique_radius.sort() point_2_position = {} if step_name in bolt_condition.keys(): point_list = bolt_condition[step_name] for point_idx in point_list: target_hole = circle_holes[point_idx] mean_pos = np.zeros(3) for cir in target_hole.circle_group: mean_pos+= np.array(cir.get_position_m()) mean_pos /= len(target_hole.circle_group) point_2_position[point_idx] = list(mean_pos) # if "bolt_side" in step_name: # circle_holes[1].radius = 7.9 if "bracket" in step_name: circle_holes[1].radius = 8.0 # extract assembly point from circle holes assembly_points = [] for hole in circle_holes: assembly_point = { "type": hole.type, "radius": hole.radius, "edge_index": hole.start_circle.edge_index, "depth": hole.depth * 0.001, "direction": hole.direction, "pose": { "position": npfloat_to_float(hole.start_circle.get_position_m()), "quaternion": npfloat_to_float(hole.start_circle.quaternion) }, } assembly_points.append(assembly_point) if "bracket" in step_name: assembly_points[1]["type"] = "penet" new_point = copy.deepcopy(assembly_points[1]) new_point["radius"] = 6.2 assembly_points.append(new_point) if step_name in bolt_condition.keys(): point_list = bolt_condition[step_name] for point_idx in point_list: assembly_points[point_idx]["type"] = "penet" new_point = copy.deepcopy(assembly_points[point_idx]) new_point["radius"] = 7.9 new_point["pose"]["position"] = npfloat_to_float(point_2_position[point_idx]) assembly_points.append(new_point) temp = {} for idx, val in enumerate(assembly_points): temp[idx] = val assembly_points = temp doc.saveAs(doc_path) FreeCAD.closeDocument(doc.Name) return assembly_points
from FreeCAD import Base import Draft import os # set STEP subdirectory for importing parts from path=os.path.realpath(__file__) path=os.path.dirname(path) path=os.path.join(path,"STEP") # create new document App.newDocument("TK0_Assembly") ##### CREATE MAIN Z_FRAME ##### # add bottom front extrusion Part.insert(os.path.join(path,"HFS5-2020x500mm.stp"),"TK0_Assembly") hf1 = App.getDocument("TK0_Assembly").HFS5_2020x500mm hf1.Placement.move(App.Vector(-250,-75.1,10)) # add upper front extrusion Draft.move([FreeCAD.getDocument("TK0_Assembly").HFS5_2020x500mm],FreeCAD.Vector(0,0,480),copy=True) # add front left upright extrusion Draft.move([FreeCAD.getDocument("TK0_Assembly").HFS5_2020x500mm],FreeCAD.Vector(-260,0,0),copy=True) hf2 = App.getDocument("TK0_Assembly").HFS5_2020x500mm002 hf2.Placement=App.Placement(App.Vector(-260,-75.1,0),App.Rotation(0,0.707107,0,-0.707107)) # add front right upright extrusion Draft.move([FreeCAD.getDocument("TK0_Assembly").HFS5_2020x500mm002],FreeCAD.Vector(520,0,0),copy=True) # add frame connectors
extension = ".step" list_of_files = [filei for filei in os.listdir(cwd) if file.lower().endswith(extension)] else: sys.argv.pop(0) list_of_files = sys.argv for i in range(len(list_of_files)): # opening of file file = cwd + list_of_files[i] FreeCAD.newDocument() FreeCAD.setActiveDocument("Unnamed") doc = FreeCAD.getDocument("Unnamed") FreeCAD.ActiveDocument = doc Part.insert(file,"Unnamed") # before converting to mesh we need to merge all shapes in the document if len(doc.Objects) > 1: FreeCAD.activeDocument().addObject("Part::MultiFuse","Fusion") FreeCAD.activeDocument().Fusion.Shapes = [doc.Objects[k] for k in range(len(doc.Objects) - 1)] FreeCAD.ActiveDocument.recompute() mesh = doc.addObject("Mesh::Feature","Mesh") mesh.Mesh = MeshPart.meshFromShape(doc.getObject("Fusion").Shape,5,0,0,0.5) else: mesh = doc.addObject("Mesh::Feature","Mesh") mesh.Mesh = MeshPart.meshFromShape(doc.getObject(doc.Objects[0].Name).Shape,5,0,0,0.5) del doc, mesh # saving the stl file
printed_parts = {} workdir = os.path.dirname(__file__) for part, make_mirror in [ ('left_y_idler_plate', True), ('left_y_motor_plate', True), ('left_y_carriage_plate', False), ('left_z_rod_support', True), ('left_z_rod_plate', True), ('x_carriage_plate', False), ('titan_mount_plate', False), ]: remove(part) if os.path.exists(f'{workdir}/printed/{part}.brep'): print("file found") Part.insert(f'{workdir}/printed/{part}.brep', App.ActiveDocument.Name) p = App.ActiveDocument.getObject(part) if p.ViewObject: p.ViewObject.Visibility = False printed_parts[part] = p if make_mirror and part.startswith('left'): right_part = 'right' + part[4:] remove(right_part) rp = App.ActiveDocument.addObject("Part::Mirroring", right_part) rp.Source = p rp.Label = right_part rp.Normal = (1, 0, 0) rp.Base = (frame_front_vslot_length / 2, 0, 0) if rp.ViewObject:
folder_str = '/home/joshua/Downloads/particle_FULLset_' + str(time) + '_newbed' fusion_string = 'App.activeDocument().Fusion.Shapes = [' fusion_name = "Fusion" App.newDocument("Unnamed") for num in range(part_number): sphere_name = "Sphere_" + str(num + 1) export_string = u"%s/%s.stp" % (folder_str, fusion_name) dist_arr = [] insert_string = "/home/joshua/Downloads/particle_FULLset_" + str( time) + "_newbed/" + sphere_name + ".stp" Part.insert(insert_string, "Unnamed") #__objs__=[] #__objs__.append(FreeCAD.getDocument("Unnamed").getObject(sphere_name)) fusion_string = fusion_string + 'App.activeDocument().' + sphere_name + ',' App.activeDocument().addObject("Part::MultiFuse", fusion_name) #App.activeDocument().Fusion.Shapes = [App.activeDocument().Sphere,App.activeDocument().Sphere002,App.activeDocument().Sphere001,App.activeDocument().Sphere003,] fusion_string = fusion_string + ']' exec(fusion_string) solid_name = fusion_name + "_solid" App.ActiveDocument.recompute() #__s__=App.ActiveDocument.Fusion.Shape.Faces
time = int(sys.argv[2]) #part_number = 18 #time = 4 # eventually import this folder_str = '/home/joshua/Downloads/particle_FULLset_' + str(time) + '_newbed' fusion_name = "Fusion" insert_string_fusion = "/home/joshua/Downloads/particle_FULLset_" + str( time) + "_newbed/Fusion.stp" cut_string_old = fusion_name count = 0 App.newDocument("Unnamed") Part.insert(insert_string_fusion, "Unnamed") for num in range(part_number): sphere_name = "Sphere_small_" + str(num + 1) insert_string = "/home/joshua/Downloads/particle_FULLset_" + str( time) + "_newbed/" + sphere_name + ".stp" Part.insert(insert_string, "Unnamed") tool_name = sphere_name base_name = cut_string_old cut_string = fusion_name + str(num + 1) base_string = "App.activeDocument()." + cut_string + ".Base = App.activeDocument()." + base_name
def checkChangeVolumeError(): # sys.path.append("/usr/share/freecad-daily/Mod/Part/") import BOPTools.SplitFeatures import CompoundTools.Explode pattern = "ctypeErrorOriginal" pattern = "relatedShape" flist = glob.glob(case_folder + "dump_" + pattern + dump_file_format) for f in flist: print(f) document_name = "Unnamed" App.newDocument(document_name) Part.insert(f, document_name) # doc = App.getDocument(document_name) obj = App.ActiveDocument.Objects[0] s = obj.Shape solids = [] origVols = [] origBboxes = [] if verbosity: print("before fragments") for solid in s.Solids: if verbosity: print(solid.BoundBox) print(solid.Volume) origVols.append(solid.Volume) origBboxes.append(solid.BoundBox) solids.append(solid) # bool fragments and print the result if App.GuiUp: g = CompoundTools.Explode.explodeCompound( obj) # return a group obj j = BOPTools.SplitFeatures.makeBooleanFragments( name="BooleanFragments") j.Objects = g j.Mode = "Standard" # CompSolid Split # j.Tolerance = 0.0; j.Proxy.execute(j) j.purgeTouched() input_obj = (App.ActiveDocument.BooleanFragments ) # compound type by standard Mode result_fragments = input_obj.Shape.Solids else: tol = 0.0 pieces, map = solids[0].generalFuse(solids[1:], tol) result_fragments = pieces.Solids # CompoundTools.Explode.explodeCompound(input_obj) assert (len(solids) == len(result_fragments)) if verbosity: print("after fragments") for i, solid in enumerate(result_fragments): vol = solid.Volume if verbosity: print(solid.BoundBox) print(vol) if not float_equal(origVols[i], vol): print("volume_change", origVols[i], vol) check_similarity(origBboxes[i], solid.BoundBox) App.closeDocument(document_name)
import os import FreeCAD import Part FreeCAD.newDocument("vitamins") FreeCAD.setActiveDocument("vitamins") for fn in os.listdir('vitamins/breps'): print("----------- {} ------------".format(fn)) if fn.endswith('.brep'): fn = fn[:] name = fn[:-5] print(fn, name) p = Part.insert('vitamins/breps/' + fn, "vitamins") x = 0 y = 0 for o in FreeCAD.ActiveDocument.Objects: print(o.Name) o.Placement = FreeCAD.Placement( FreeCAD.Vector(x, y, 0), FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), 0)) x += 100 if x > 500: x = 0 y += 100 FreeCAD.ActiveDocument.recompute() FreeCAD.ActiveDocument.saveAs("vitamins/vitamins.FCStd")
# pf.Shape = shape # #print(file_path.split('.step')[0] + '.stl') # Mesh.export([pf], dir_path + '/model.stl') for i in range(len(dirs)): dir_path = path + dirs[i] for f in [dir_path + '/' + j for j in os.listdir(dir_path)]: if '.step' in f: file_path = f file = file_path FreeCAD.newDocument() FreeCAD.setActiveDocument("Unnamed") doc = FreeCAD.getDocument("Unnamed") FreeCAD.ActiveDocument = doc Part.insert(file, "Unnamed") # before converting to mesh we need to merge all shapes in the document if len(doc.Objects) > 1: FreeCAD.activeDocument().addObject("Part::MultiFuse", "Fusion") FreeCAD.activeDocument().Fusion.Shapes = [ doc.Objects[k] for k in range(len(doc.Objects) - 1) ] FreeCAD.ActiveDocument.recompute() mesh = doc.addObject("Mesh::Feature", "Mesh") mesh.Mesh = MeshPart.meshFromShape( doc.getObject("Fusion").Shape, 5, 0, 0, 0.5) else: mesh = doc.addObject("Mesh::Feature", "Mesh") mesh.Mesh = MeshPart.meshFromShape( doc.getObject(doc.Objects[0].Name).Shape, 5, 0, 0, 0.5)
from FreeCAD import Base import Draft import os # set STEP subdirectory for importing parts from path = os.path.realpath(__file__) path = os.path.dirname(path) path = os.path.join(path, "STEP") # create new document App.newDocument("TK0_Assembly") ##### CREATE MAIN Z_FRAME ##### # add bottom front extrusion Part.insert(os.path.join(path, "HFS5-2020x500mm.stp"), "TK0_Assembly") hf1 = App.getDocument("TK0_Assembly").HFS5_2020x500mm hf1.Placement.move(App.Vector(-250, -75.1, 10)) # add upper front extrusion Draft.move([FreeCAD.getDocument("TK0_Assembly").HFS5_2020x500mm], FreeCAD.Vector(0, 0, 480), copy=True) # add front left upright extrusion Draft.move([FreeCAD.getDocument("TK0_Assembly").HFS5_2020x500mm], FreeCAD.Vector(-260, 0, 0), copy=True) hf2 = App.getDocument("TK0_Assembly").HFS5_2020x500mm002 hf2.Placement = App.Placement(App.Vector(-260, -75.1, 0), App.Rotation(0, 0.707107, 0, -0.707107))
def read(filename): "reads the file and creates objects in the active document" #import importZip; reload(importZip) print("open Zip STEP version " + ___ZipVersion___) z = zipfile.ZipFile(filename) l = z.printdir() #il = z.infolist() nl = z.namelist() print("file list: ", nl) import ImportGui, FreeCADGui for f in nl: if '.stp' in f.lower() or '.step' in f.lower(): #\ #or '.igs' in f.lower() or '.iges' in f.lower(): file_content = z.read(f) #sfe = z.extract(f) #print ('extracted ',sfe) print('extracted ', f) # fname=os.path.splitext(os.path.basename(filename))[0] # ext = os.path.splitext(os.path.basename(filename))[1] fname = f print('fname ', f) tempdir = tempfile.gettempdir( ) # get the current temporary directory tempfilepath = os.path.join(tempdir, fname) # + ext) z.extract(fname, tempdir) doc = FreeCAD.ActiveDocument ImportGui.insert(tempfilepath, doc.Name) FreeCADGui.SendMsgToActiveView("ViewFit") try: os.remove(tempfilepath) except OSError: FreeCAD.Console.PrintError("error on removing " + tempfilepath + " file") pass elif '.fcstd' in f.lower(): #\ fname = f tempdir = tempfile.gettempdir( ) # get the current temporary directory tempfilepath = os.path.join(tempdir, fname) # + ext) z.extract(fname, tempdir) doc = FreeCAD.ActiveDocument i = 0 for obj in FreeCAD.ActiveDocument.Objects: i += 1 if i == 0: FreeCAD.closeDocument(doc.Name) FreeCAD.open(tempfilepath) #ImportGui.insert(tempfilepath,doc.Name) FreeCADGui.SendMsgToActiveView("ViewFit") try: os.remove(tempfilepath) except OSError: FreeCAD.Console.PrintError("error on removing " + tempfilepath + " file") pass elif '.brep' in f.lower(): #\ fname = f tempdir = tempfile.gettempdir( ) # get the current temporary directory tempfilepath = os.path.join(tempdir, fname) # + ext) z.extract(fname, tempdir) doc = FreeCAD.ActiveDocument import Part #Part.open(tempfilepath,doc.Name) Part.insert(tempfilepath, doc.Name) #FreeCAD.open(tempfilepath) #ImportGui.insert(tempfilepath,doc.Name) FreeCADGui.SendMsgToActiveView("ViewFit") try: os.remove(tempfilepath) except OSError: FreeCAD.Console.PrintError("error on removing " + tempfilepath + " file") pass