def process_nonchanging_domains(nonchanging_file_name, output_file_name):
	if len(nonchanging_file_name) != 0:

		__objs_original__ = FreeCAD.getDocument("tmp").findObjects()
		len_original =len(__objs_original__)
		print "Loading non-changing component..."
		Import.insert(nonchanging_file_name, "tmp")

		# get objects
		__objs__ = FreeCAD.getDocument("tmp").findObjects()

		# create fusion object
		FreeCAD.getDocument("tmp").addObject("Part::MultiFuse", "FusionTool")

		# add objs to FusionTool
		FreeCAD.getDocument("tmp").FusionTool.Shapes = __objs__[0: len(__objs__)]

		# compute
		FreeCAD.getDocument("tmp").recompute()

		# make one solid
		Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

		# remove all except the last
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
		for i in range(0, len(__objs__) - 1):
			FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

		print "Exporting BOOLEANED file..."
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
		Part.export(__objs__, output_file_name+"_BOOLEANED.step")
		print "Output file " + output_file_name+"_BOOLEANED.step" + " exported."
Example #2
0
def exportCAD(obj_list: Sequence, file_name: str):
    """Export a STEP (Standard for the Exchange of Product Data) 3D CAD file.

    Parameters
    ----------
    obj_list : list
        List of objects to export.
    file_name : str
        Name of file to create and export into.

    Returns
    -------


    """
    if not isinstance(obj_list, list):
        raise TypeError("obj_list must be a list of objects.")
    # The export format is determined by the extension, so we should check it:
    supported_ext = (".step", ".stp")
    if file_name.endswith(supported_ext):
        with silent_stdout():
            Part.export(obj_list, file_name)
    else:
        raise ValueError(file_name + " is not a supported extension (" +
                         ", ".join(supported_ext) + ")")
Example #3
0
def reorient_object(input_file_name, output_file_name, refinement_level):
	__objToExport__ = FreeCAD.getDocument("tmp").findObjects()

	# get the original file
	Import.insert(input_file_name, "tmp")

	# get bounding box
	bB = FreeCAD.getDocument("tmp").Objects[-1].Shape.BoundBox

	# create rotation parameters
	displacement = FreeCAD.Vector(2.0, 0.0, 0.0)
	centerRot = FreeCAD.Vector(bB.XMin, 0.5*(bB.YMin+bB.YMax), bB.ZMin)
	axisRot1 = FreeCAD.Vector(0.0, 0.0, 1.0)
	axisRot2 = FreeCAD.Vector(0.0, 1.0, 0.0)
	angleRot1 = 180.0
	angleRot2 = 90.0

	# import the draft module
	import Draft
	Draft.move(FreeCAD.getDocument("tmp").Objects[0], displacement, copy=False) # perform move
	Draft.rotate(FreeCAD.getDocument("tmp").Objects[0], angleRot1, centerRot,axis=axisRot1,copy=False) # perform first rotation
	Draft.rotate(FreeCAD.getDocument("tmp").Objects[0], angleRot2, centerRot,axis=axisRot2,copy=False) # perform second rotation

	# remove originalGeom
	originalGeom = FreeCAD.getDocument("tmp").Objects[-1].Name
	FreeCAD.getDocument("tmp").removeObject(originalGeom)

	print "Exporting RAW file..."
	Part.export(__objToExport__, output_file_name+".step")
	print "Output file " + output_file_name+".step" + " exported."
def process_nonchanging_domains(nonchanging_file_name, output_file_name, refinement_level):
	if len(nonchanging_file_name) != 0:
		print "Loading non-changing component..."
		Import.insert(nonchanging_file_name, "tmp")
		
		#import Draft
		#scaleFactor = 2**refinement_level
		#scaleVector = FreeCAD.Vector(scaleFactor, scaleFactor, scaleFactor)
		#Draft.scale(FreeCAD.getDocument("tmp").Objects[0], scaleVector)#, center=FreeCAD.Vector(1,1,1),copy=False) # perfom scaling

		# get objects
		__objs__ = FreeCAD.getDocument("tmp").findObjects()

		# create fusion object
		FreeCAD.getDocument("tmp").addObject("Part::MultiFuse", "FusionTool")

		# add objs to FusionTool
		FreeCAD.getDocument("tmp").FusionTool.Shapes = __objs__[0: len(__objs__)]

		# compute
		FreeCAD.getDocument("tmp").recompute()

		# make one solid
		Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

		# remove all except the last
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
		for i in range(0, len(__objs__) - 1):
			FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

		print "Exporting BOOLEANED file..."
		__objs__ = FreeCAD.getDocument("tmp").findObjects()
		Part.export(__objs__, output_file_name+"_BOOLEANED.step")
		print "Output file " + output_file_name+"_BOOLEANED.step" + " exported."
def process_nonchanging_domains(nonchanging_file_name, output_file_name):
    if len(nonchanging_file_name) != 0:

        __objs_original__ = FreeCAD.getDocument("tmp").findObjects()
        len_original = len(__objs_original__)
        print "Loading non-changing component..."
        Import.insert(nonchanging_file_name, "tmp")

        # get objects
        __objs__ = FreeCAD.getDocument("tmp").findObjects()

        # create fusion object
        FreeCAD.getDocument("tmp").addObject("Part::MultiFuse", "FusionTool")

        # add objs to FusionTool
        FreeCAD.getDocument(
            "tmp").FusionTool.Shapes = __objs__[0:len(__objs__)]

        # compute
        FreeCAD.getDocument("tmp").recompute()

        # make one solid
        Part.show(Part.makeSolid(FreeCAD.getDocument("tmp").Objects[-1].Shape))

        # remove all except the last
        __objs__ = FreeCAD.getDocument("tmp").findObjects()
        for i in range(0, len(__objs__) - 1):
            FreeCAD.getDocument("tmp").removeObject(__objs__[i].Name)

        print "Exporting BOOLEANED file..."
        __objs__ = FreeCAD.getDocument("tmp").findObjects()
        Part.export(__objs__, output_file_name + "_BOOLEANED.step")
        print "Output file " + output_file_name + "_BOOLEANED.step" + " exported."
Example #6
0
def export(exportList, filename):

    "called on exporting a file"

    if not converter:
        FreeCAD.Console.PrintError(
            translate(
                "CADExchanger",
                "CAD Exchanger converter path is not set. Please check Preferences -> Import/Export/CAD Exchanger\n"
            ))
        return
    if subprocess.call(converter) != 1:
        FreeCAD.Console.PrintError(
            translate("CADExchanger", "Error while running CAD Exchanger\n"))
        return
    import Part
    tempname = tempfile.mkstemp(suffix=".brep")[1]
    Part.export(exportList, tempname)
    exstr = [converter, " -i ", tempname, " -e ", filename]
    print "executing " + "".join(exstr)
    result = subprocess.call(exstr)
    if result != 0:
        FreeCAD.Console.PrintError(
            translate("CADExchanger",
                      "Error during CAD Exchanger conversion\n"))
    return
Example #7
0
            def func():

                #check-in fichier step asscocies if exists
                #api/doc_id/files/[all/]
                url= "api/object/%s/files/all/" % doc["id"]
                res = PLUGIN.get_data(url)
                root, f_name = os.path.split(path)
                fileName, fileExtension = os.path.splitext(f_name)
                doc_step = [obj for obj in res["files"] if obj["filename"] == fileName+".stp"]

                fileName, fileExtension = os.path.splitext(path)
                path_stp= (fileName + ".stp").encode("utf-8")
                Part.export(gdoc.Objects, path_stp)

                if not doc_step:    #il faut generer un nouvelle fichier step
                    doc_step_file=self.upload_file(doc,path_stp) # XXX
                    doc_step.append(doc_step_file)
                else:                   #il faut un check-in
                    url = self.SERVER + "api/object/%s/checkin/%s/" % (doc["id"], doc_step[0]["id"]) # XXX
                    self.upload(url, path_stp)
                    os.remove(path_stp)

                url = self.SERVER + "api/object/%s/checkin/%s/" % (doc["id"], doc_file_id) # XXX
                self.upload(url, path)

                if not unlock:
                    self.get_data("api/object/%s/lock/%s/" % (doc["id"], doc_file_id)) # XXX
                    if doc_step:
                        self.get_data("api/object/%s/lock/%s/" % (doc["id"], doc_step[0]["id"])) # XXX
                else:
                    self.send_thumbnail(gdoc)
                    self.forget(gdoc)
Example #8
0
def convert_stl_to_step(in_pair):
    [in_stl, out_step] = in_pair
    print('converting stl to step: {} -> {}'.format(in_stl, out_step))
    in_stl = copy_stl_to_tmp_stl(in_stl)

    Mesh.insert(in_stl)
    App.ActiveDocument.recompute()
    FreeCAD.getDocument("Unnamed").addObject("Part::Feature", "test001")
    __shape__ = Part.Shape()
    __shape__.makeShapeFromMesh(
        FreeCAD.getDocument("Unnamed").getObject("test").Mesh.Topology,
        0.100000)
    FreeCAD.getDocument("Unnamed").getObject("test001").Shape = __shape__
    FreeCAD.getDocument("Unnamed").getObject("test001").purgeTouched()
    del __shape__
    App.ActiveDocument.addObject(
        'Part::Feature',
        'test001').Shape = App.ActiveDocument.test001.Shape.removeSplitter()
    App.ActiveDocument.ActiveObject.Label = App.ActiveDocument.test001.Label
    App.ActiveDocument.recompute()

    __objs__ = []
    __objs__.append(FreeCAD.getDocument("Unnamed").getObject("test001001"))
    Part.export(__objs__, out_step)
    del __objs__
Example #9
0
    def create(self, data, filename, unlock):
        res = self.get_data("api/create/", data)
        if not filename:
            return False, "Bad file name"
        if res["result"] != "ok":
            return False, res["error"]
        else:
            doc = res["object"]
            # create a new doc
            rep = os.path.join(self.PLUGIN_DIR, doc["type"], doc["reference"],
                               doc["revision"])
            try:
                os.makedirs(rep, 0700)
            except os.error:
                # directory already exists, just ignores the exception
                pass
            gdoc = FreeCAD.ActiveDocument
            ggui = FreeCAD.Gui.ActiveDocument # for Visibility Checking
            filename = filename.decode("utf8")
            path = os.path.join(rep, filename)
            fileName, fileExtension = os.path.splitext(filename)
            path_stp=os.path.join(rep, (fileName+".stp")).encode("utf-8")
            #create temporal file stp
            lines=re.split('\n',gdoc.DependencyGraph)
            edges={}
            for line in lines:
                if truth(re.match("\A\d+\[label",line) ):
                    labeln=re.sub('];','',re.split('=',line)[-1])
                    labeln=re.sub('"','',labeln) # UTF-8 national labels
                    current_object=gdoc.getObjectsByLabel(labeln)[0]
                    if "Group" in current_object.PropertiesList:
                        pass
                    else:
                        if ggui.getObject(current_object.Name).Visibility:
                            edges[re.findall("\A\d+",line)[0]]= labeln # Append graph nodes
            ImportObj=[]
            for ind in edges.keys():
                ImportObj.append(gdoc.getObjectsByLabel(edges[ind])[0])
            Part.export(ImportObj, path_stp)
            
            gdoc.saveAs(path)
            save(gdoc)

            #upload stp and freecad object
            doc_step_file=self.upload_file(doc, path_stp)
            doc_file = self.upload_file(doc, path.encode("utf-8"))

            #remove temporal file stp
            os.remove(path_stp)

            self.add_managed_file(doc, doc_file, path)
            self.load_file(doc, doc_file["id"], path, gdoc)
            if not unlock:
                self.get_data("api/object/%s/lock/%s/" % (doc["id"], doc_file["id"]))
                self.get_data("api/object/%s/lock/%s/" % (doc["id"], doc_step_file["id"]))
            else:
                self.send_thumbnail(gdoc)
                self.forget(gdoc)
            return True, ""
Example #10
0
    def saveFile(self):

        import FreeCADGui
        if self.form.Radio_Selection.isChecked():
            objects = FreeCADGui.Selection.getSelection()
        else:
            objects = [
                obj for obj in FreeCAD.ActiveDocument.Objects
                if obj.ViewObject.isVisible()
            ]
        if not objects:
            QtGui.QMessageBox.critical(
                None, translate("Web", "Nothing to upload"),
                translate(
                    "The selection of the document contains no object to upload"
                ))
            return None
        filename = os.path.join(tempfile._get_default_tempdir(),
                                next(tempfile._get_candidate_names()))
        filetype = self.form.Combo_Filetype.currentIndex()
        # 0 = obj + mtl, 1 = obj, 2 = dae, 3 = stl, 4 = IGES, 5 = iv (currently not working)
        if filetype == 0:  # OBJ + MTL
            import importOBJ
            importOBJ.export(objects, filename + ".obj")
            return self.packFiles(filename,
                                  [filename + ".obj", filename + ".mtl"])
        elif filetype == 1:  # OBJ (mesh exporter)
            import Mesh
            Mesh.export(objects, filename + ".obj")
            return self.packFiles(filename, [filename + ".obj"])
        elif filetype == 2:  # DAE
            import importDAE
            importDAE.export(objects, filename + ".dae")
            return self.packFiles(filename, [filename + ".dae"])
        elif filetype == 3:  # STL
            import Mesh
            Mesh.export(objects, filename + ".stl")
            return self.packFiles(filename, [filename + ".stl"])
        elif filetype == 4:  # IGES
            import Part
            Part.export(objects, filename + ".iges")
            return self.packFiles(filename, [filename + ".iges"])
        elif filetype == 5:  # IV
            import FreeCADGui
            FreeCADGui.export(objects, filename + ".iv")
            # removing FreeCAD-specific nodes
            f = open(filename + ".iv", "rb")
            s = f.read()
            f.close()
            s = s.replace("SoBrepEdgeSet", "SoIndexedLineSet")
            s = s.replace("SoBrepFaceSet", "SoIndexedFaceSet")
            s = s.replace("\n", "--endl--")
            s = re.sub("highlightIndex .*?\]", " ", s)
            s = re.sub("partIndex .*?\]", " ", s)
            s = s.replace("--endl--", "\n")
            f = open(filename + ".iv", "wb")
            f.write(s)
            f.close()
            return self.packFiles(filename, [filename + ".iv"])
Example #11
0
def exportCAD(obj, fileName):
    ''' Export a STEP (Standard for the Exchange of Product Data) 3D CAD file
    for the object.
    '''
    # The export format is determined by the extension, so we should check it:
    if (fileName[-5:] == '.step') or (fileName[-4:] == '.stp'):
        Part.export([obj], fileName)
    else:
        raise ValueError('The file path' + fileName + ' does not end in .step or .stp. \
                          Please fix this and try your export again.')
def save_and_export(folder_name, final_object_name, final_file_name):

    export_string = u"%s/%s.step" % (folder_name, final_file_name)

    __objs__ = []
    __objs__.append(
        FreeCAD.getDocument("Unnamed").getObject(
            final_object_name))  # use this to save and export each file
    Part.export(__objs__, export_string)  # exports solid part
    del __objs__
    def inner(*P):
        objs = []
        for obj in P:
            objs.append(FreeCAD.getDocument("test").getObject(obj.identifier))

        if frmt == "stl":
            Mesh.export(objs, dir + name + ".stl")
        elif frmt == "obj":
            pass
        elif frmt == "iges":
            Part.export(objs, dir + name + ".igs")
        elif frmt == "step":
            Part.export(objs, dir + name + ".step")
Example #14
0
    def create(self, data, filename, unlock):
        res = self.get_data("api/create/", data)
        if not filename:
            return False, "Bad file name"
        if res["result"] != "ok":
            return False, res["error"]
        else:
            doc = res["object"]
            # create a new doc
            rep = os.path.join(self.PLUGIN_DIR, doc["type"], doc["reference"],
                               doc["revision"])
            try:
                os.makedirs(rep, 0700)
            except os.error:
                # directory already exists, just ignores the exception
                pass
            gdoc = App.ActiveDocument
            filename = filename.decode("utf8")
            path = os.path.join(rep, filename)
            fileName, fileExtension = os.path.splitext(filename)
            path_stp = os.path.join(rep, (fileName + ".stp")).encode("utf-8")
            # create temporal file stp
            Part.export(gdoc.Objects, path_stp)

            # -- gf : tried commenting these lines but openPLM needs a file
            #         for transfer
            # gdoc.FileName = path  # ActiveDocument file name is read-only !
            App.ActiveDocument.saveAs(path)
            # save(gdoc)
            # --

            # upload stp and freecad object
            doc_step_file = self.upload_file(doc, path_stp)
            doc_file = self.upload_file(doc, path.encode("utf-8"))

            # remove temporal file stp
            os.remove(path_stp)

            self.add_managed_file(doc, doc_file, path)
            self.load_file(doc, doc_file["id"], path, gdoc)
            if not unlock:
                self.get_data("api/object/%s/lock/%s/" %
                              (doc["id"], doc_file["id"]))
                self.get_data("api/object/%s/lock/%s/" %
                              (doc["id"], doc_step_file["id"]))
            else:
                self.send_thumbnail(gdoc)
                self.forget(gdoc)
            return True, ""
Example #15
0
def solid2STEP (solids,outputFilenames):
    if type(solids) is not list:
        solids=[solids]
    if type(outputFilenames) is not list: # all the solids go into one file
        tmpParts = []
        for i in range(len(solids)):
            tmpParts.append(mydoc.addObject("Part::Feature"))
            tmpParts[i].Shape = solids[i]
        Part.export(tmpParts,outputFilenames)
        for i in range(len(tmpParts)): # remove all objects from the document
            mydoc.removeObject(tmpParts[i].Name)
    else: # list of filenames
        for i in range(len(solids)):
            solids[i].exportStep(outputFilenames[i])        
    return
Example #16
0
    def Activated(self):
        import Part
        shapes = []

        sel = FreeCADGui.Selection.getSelection()
        objs = FreeCAD.ActiveDocument.Objects
        if len(sel) == 0:
            for obj in objs:
                if (obj.ViewObject.Visibility == True):
                    shapes.append(obj)
        else:
            for obj in sel:
                shapes.append(obj)

        Part.export(shapes, "2610172.stp")
    def build(self):
        outfile = self.generate_test_filename()
        document_name = self.__class__.__name__
        if os.path.exists(outfile):
            os.remove(outfile)
        App.newDocument(document_name)
        doc = App.getDocument(document_name)

        __objs__ = self.build_geometry(doc)
        if __objs__:
            Part.export(__objs__, outfile)  # it build a compound shape
            del __objs__

        App.closeDocument(document_name)
        return outfile
Example #18
0
def exportCAD(obj_list, file_name):
    ''' Export a STEP (Standard for the Exchange of Product Data) 3D CAD file.

    :param list obj_list:       List of objects to export.
    :param string file_name:    Name of file to create and export into.
    '''
    if not isinstance(obj_list, list):
        raise TypeError("obj_list must be a list of objects.")
    # The export format is determined by the extension, so we should check it:
    supported_ext = ('.step', '.stp')
    if file_name.endswith(supported_ext):
        with silent_stdout():
            Part.export(obj_list, file_name)
    else:
        raise ValueError(file_name + ' is not a supported extension (' +
                         ', '.join(supported_ext) + ')')
Example #19
0
def convert_openscad_to_step(scad_filename,
                             step_filename,
                             objname='difference'):

    # NOTES:
    # * Works with ubuntu 18.04 (python 2.7.17 and freecad 0.16)
    # * Needs rework for ubuntu 20.04 (python 3.8.2 and freecad 0.18.4)

    # TODO: automatically determine the top level object (objname)

    part_name = os.path.basename(scad_filename)
    part_name = part_name.replace(".scad", "")

    importCSG.open(scad_filename)
    FreeCAD.setActiveDocument(part_name)
    part = FreeCAD.getDocument(part_name).getObject(objname)
    Part.export([part], step_filename)
Example #20
0
def reorient_object(input_file_name, output_file_name):
    __objToExport__ = FreeCAD.getDocument("tmp").findObjects()

    # get the original file
    Import.insert(input_file_name, "tmp")

    # get bounding box
    bB = FreeCAD.getDocument("tmp").Objects[-1].Shape.BoundBox

    # create rotation parameters
    #print "XMin:", bB.XMin, "XMax:", bB.XMax, "YMin:", bB.YMin, "YMax:", bB.YMax, "ZMin:", bB.ZMin, "ZMax:", bB.ZMax
    displacement = FreeCAD.Vector(-bB.ZMin, bB.YMin, -bB.XMin)
    centerRot = FreeCAD.Vector(bB.XMin, 0.5 * (bB.YMin + bB.YMax), bB.ZMin)
    axisRot1 = FreeCAD.Vector(0.0, 0.0, 1.0)
    axisRot2 = FreeCAD.Vector(0.0, 1.0, 0.0)
    angleRot1 = 180.0
    angleRot2 = 90.0

    # import the draft module
    import Draft
    Draft.move(FreeCAD.getDocument("tmp").Objects[0], displacement,
               copy=False)  # perform move
    Draft.rotate(FreeCAD.getDocument("tmp").Objects[0],
                 angleRot1,
                 centerRot,
                 axis=axisRot1,
                 copy=False)  # perform first rotation
    Draft.rotate(FreeCAD.getDocument("tmp").Objects[0],
                 angleRot2,
                 centerRot,
                 axis=axisRot2,
                 copy=False)  # perform second rotation

    # remove originalGeom
    originalGeom = FreeCAD.getDocument("tmp").Objects[-1].Name
    FreeCAD.getDocument("tmp").removeObject(originalGeom)

    print "Exporting RAW file..."
    Part.export(__objToExport__, output_file_name + ".step")
    print "Output file " + output_file_name + ".step" + " exported."

    return bB.YMax
Example #21
0
    def create(self, data, filename, unlock):
        res = self.get_data("api/create/", data)
        if not filename:
            return False, "Bad file name"
        if res["result"] != "ok":
            return False, res["error"]
        else:
            doc = res["object"]
            # create a new doc
            rep = os.path.join(self.PLUGIN_DIR, doc["type"], doc["reference"],
                               doc["revision"])
            try:
                os.makedirs(rep, 0700)
            except os.error:
                # directory already exists, just ignores the exception
                pass
            gdoc = FreeCAD.ActiveDocument
            filename = filename.decode("utf8")
            path = os.path.join(rep, filename)
            fileName, fileExtension = os.path.splitext(filename)
            path_stp=os.path.join(rep, (fileName+".stp")).encode("utf-8")
            #create temporal file stp
            Part.export(gdoc.Objects, path_stp)
            gdoc.FileName = path
            save(gdoc)

            #upload stp and freecad object
            doc_step_file=self.upload_file(doc, path_stp)
            doc_file = self.upload_file(doc, path.encode("utf-8"))

            #remove temporal file stp
            os.remove(path_stp)

            self.add_managed_file(doc, doc_file, path)
            self.load_file(doc, doc_file["id"], path, gdoc)
            if not unlock:
                self.get_data("api/object/%s/lock/%s/" % (doc["id"], doc_file["id"]))
                self.get_data("api/object/%s/lock/%s/" % (doc["id"], doc_step_file["id"]))
            else:
                self.send_thumbnail(gdoc)
                self.forget(gdoc)
            return True, ""
Example #22
0
 def export(self, p, result, label, data_hash, config):
     # export the plate to different file formats
     log.info("Exporting %s layer for %s" % (label, data_hash))
     # draw the part so we can export it
     Part.show(p.val().wrapped)
     doc = FreeCAD.ActiveDocument
     # export the drawing into different formats
     pwd_len = len(config['app']['pwd']) # the absolute part of the working directory (aka - outside the web space)
     result['exports'][label] = []
     if 'js' in result['formats']:
         with open("%s/%s_%s.js" % (config['app']['export'], label, data_hash), "w") as f:
             cadquery.exporters.exportShape(p, 'TJS', f)
             result['exports'][label].append({'name':'js', 'url':'%s/%s_%s.js' % (config['app']['export'][pwd_len:], label, data_hash)})
             log.info("Exported 'JS'")
     if 'brp' in result['formats']:
         Part.export(doc.Objects, "%s/%s_%s.brp" % (config['app']['export'], label, data_hash))
         result['exports'][label].append({'name':'brp', 'url':'%s/%s_%s.brp' % (config['app']['export'][pwd_len:], label, data_hash)})
         log.info("Exported 'BRP'")
     if 'stp' in result['formats']:
         Part.export(doc.Objects, "%s/%s_%s.stp" % (config['app']['export'], label, data_hash))
         result['exports'][label].append({'name':'stp', 'url':'%s/%s_%s.stp' % (config['app']['export'][pwd_len:], label, data_hash)})
         log.info("Exported 'STP'")
     if 'stl' in result['formats']:
         Mesh.export(doc.Objects, "%s/%s_%s.stl" % (config['app']['export'], label, data_hash))
         result['exports'][label].append({'name':'stl', 'url':'%s/%s_%s.stl' % (config['app']['export'][pwd_len:], label, data_hash)})
         log.info("Exported 'STL'")
     if 'dxf' in result['formats']:
         importDXF.export(doc.Objects, "%s/%s_%s.dxf" % (config['app']['export'], label, data_hash))
         result['exports'][label].append({'name':'dxf', 'url':'%s/%s_%s.dxf' % (config['app']['export'][pwd_len:], label, data_hash)})
         log.info("Exported 'DXF'")
     if 'svg' in result['formats']:
         importSVG.export(doc.Objects, "%s/%s_%s.svg" % (config['app']['export'], label, data_hash))
         result['exports'][label].append({'name':'svg', 'url':'%s/%s_%s.svg' % (config['app']['export'][pwd_len:], label, data_hash)})
         log.info("Exported 'SVG'")
     if 'json' in result['formats'] and label == SWITCH_LAYER:
         with open("%s/%s_%s.json" % (config['app']['export'], label, data_hash), 'w') as json_file:
             json_file.write(repr(self))
         result['exports'][label].append({'name':'json', 'url':'%s/%s_%s.json' % (config['app']['export'][pwd_len:], label, data_hash)})
         log.info("Exported 'JSON'")
     # remove all the documents from the view before we move on
     for o in doc.Objects:
         doc.removeObject(o.Label)
Example #23
0
            def func():

                #check-in fichier step asscocies if exists
                #api/doc_id/files/[all/]
                url = "api/object/%s/files/all/" % doc["id"]
                res = PLUGIN.get_data(url)
                root, f_name = os.path.split(path)
                fileName, fileExtension = os.path.splitext(f_name)
                doc_step = [
                    obj for obj in res["files"]
                    if obj["filename"] == fileName + ".stp"
                ]

                fileName, fileExtension = os.path.splitext(path)
                path_stp = (fileName + ".stp").encode("utf-8")
                Part.export(gdoc.Objects, path_stp)

                if not doc_step:  #il faut generer un nouvelle fichier step
                    doc_step_file = self.upload_file(doc, path_stp)  # XXX
                    doc_step.append(doc_step_file)
                else:  #il faut un check-in
                    url = self.SERVER + "api/object/%s/checkin/%s/" % (
                        doc["id"], doc_step[0]["id"])  # XXX
                    self.upload(url, path_stp)
                    os.remove(path_stp)

                url = self.SERVER + "api/object/%s/checkin/%s/" % (
                    doc["id"], doc_file_id)  # XXX
                self.upload(url, path)

                if not unlock:
                    self.get_data("api/object/%s/lock/%s/" %
                                  (doc["id"], doc_file_id))  # XXX
                    if doc_step:
                        self.get_data("api/object/%s/lock/%s/" %
                                      (doc["id"], doc_step[0]["id"]))  # XXX
                else:
                    self.send_thumbnail(gdoc)
                    self.forget(gdoc)
Example #24
0
 def addtolibrary(self):
     import Part, Mesh, os
     self.fileDialog = QtGui.QFileDialog.getSaveFileName(None,u"Save As", self.librarypath)
     print(self.fileDialog[0])
     # check if file saving has been canceled and save .fcstd, .step and .stl copies
     if self.fileDialog[0] != "":
         # remove the file extension from the file path
         fileName = os.path.splitext(self.fileDialog[0])[0]
         FCfilename = fileName + ".fcstd"
         FreeCAD.ActiveDocument.saveAs(FCfilename)
         if self.stepCB.isChecked() or self.stlCB.isChecked():
             toexport = []
             objs = FreeCAD.ActiveDocument.Objects
             for obj in objs :
                 if obj.ViewObject.Visibility == True :
                     toexport.append(obj)
             if self.stepCB.isChecked() and self.linked == False:
                 STEPfilename = fileName + ".step"
                 Part.export(toexport,STEPfilename)
             if self.stlCB.isChecked() and self.linked == False:
                 STLfilename = fileName + ".stl"
                 Mesh.export(toexport,STLfilename)
     return self.fileDialog[0]
def export(exportList,filename):

    """Called by FreeCAD on exporting a file"""

    import Part

    converter = getConverter()
    if not converter:
        FreeCAD.Console.PrintError(translate("CADExchanger","CAD Exchanger converter path is not set. Please check Preferences -> Import/Export/CAD Exchanger\n"))
        return
    tempname = tempfile.mkstemp(suffix=".brep")[1]
    Part.export(exportList,tempname)
    exstr = [converter, " -i \"", tempname, "\" -e \"", filename, "\""]
    print ("executing "+"".join(exstr))
    #result = subprocess.call(exstr)
    result = subprocess.Popen("".join(exstr), shell=True, stdout=subprocess.PIPE)
    stdout = result.communicate()[0]
    if result.returncode != 0:
        FreeCAD.Console.PrintError(translate("CADExchanger","Error during CADExchanger conversion\n"))
        if not isinstance(stdout,str):
            stdout = stdout.decode("utf8")
        print('CADExchanger output:\n' + stdout)
    return
Example #26
0
import Part

doc = FreeCAD.newDocument("Box_5")

box = doc.addObject("Part::Box", "myBox")
box.Height = 5
box.Length = 5
box.Width = 5

doc.recompute()

Part.export([box], "box.stp")

Gui.activeDocument().activeView().viewIsometric()
Gui.SendMsgToActiveView("ViewFit")

Example #27
0
 def writeIGS(self,filePath):
     import Part
     Part.export(self.objs,filePath)
Example #28
0
        sphere_name).Placement = App.Placement(
            App.Vector(x, y, z), App.Rotation(App.Vector(0, 0, 1), 0))

    #FreeCAD.getDocument("Unnamed").getObject(sphere_name).Radius = '1 mm'
    FreeCAD.getDocument("Unnamed").getObject(sphere_name).Radius = radius

    App.ActiveDocument.recompute()

    exec_string_volume = "new_vol = App.ActiveDocument." + sphere_name + ".Shape.Volume"
    exec(exec_string_volume)
    print new_vol
    if new_vol < 0:
        exec_string_copy = "sphere_copy=App.ActiveDocument." + sphere_name + ".Shape.copy()"
        exec(exec_string_copy)
        sphere_copy.reverse()

        sphere_name = sphere_name + "_rev"
        __o__ = App.ActiveDocument.addObject("Part::Feature", sphere_name)
        __o__.Label = sphere_name
        __o__.Shape = sphere_copy
        del sphere_copy, __o__
        exec_string_volume_rev = "new_vol = App.ActiveDocument()." + sphere_name + ".Shape.Volume"
        exec(exec_string_volume_rev)
        App.ActiveDocument.recompute()

    print radius
    __objs__ = []
    __objs__.append(FreeCAD.getDocument("Unnamed").getObject(sphere_name))
    Part.export(__objs__, export_string)  # exports solid part
    del __objs__
f.Symmetric = True
f.TaperAngle = 0.000000000000000
f.TaperAngleRev = 0.000000000000000
FreeCAD.getDocument("Unnamed").getObject("Extrude_conical").LengthFwd = '2 mm'
# App.getDocument('Unnamed').Extrude_conical.setExpression('LengthFwd', u'Spreadsheet.beadDomainZ')
App.ActiveDocument.recompute()

#Exporting the `Extrude_conical`
__objs__ = []
__objs__.append(FreeCAD.getDocument("Unnamed").getObject("Extrude_conical"))
# import ImportGui
# ImportGui.export(__objs__,u"/Users/sourav/ownCloud/FreeCAD/FAB_FreeCADCmd.step")
# del __objs__
#
# __objs__=[]
# __objs__.append(FreeCAD.getDocument("Unnamed").getObject("BooleanFragments"))
import Part
Part.export(__objs__, u"Extrude_conical.stl")
Part.export(__objs__, u"Extrude_conical.brep")
del __objs__

print('this script complete sucessfully')

######################### end of paste ##############################
# '''
# exit FreeCAD, only after you have done the debugging
FreeCAD.closeDocument('Unnamed')
if FreeCAD.GuiUp:
    Gui.doCommand('exit(0)')  # another way to exit
# '''
Example #30
0
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 28 15:38:31 2012

@author: daniel
"""
import sys
FREECADPATH = '/usr/lib/freecad/lib' # path to your FreeCAD.so or FreeCAD.dll file
sys.path.append(FREECADPATH)
import FreeCADGui
import FreeCAD
import Draft
import Part
import os
import numpy

FreeCAD.newDocument('test')
points=[FreeCAD.Vector(1.11162757874,0.741084873676,0.0),FreeCAD.Vector(-2.7989192009,1.25719761848,0.0),FreeCAD.Vector(-3.65248990059,-0.059551473707,0.0),FreeCAD.Vector(-0.73446804285,-1.29689872265,0.0),FreeCAD.Vector(0.542580187321,0.337458372116,0.0),FreeCAD.Vector(0.800636351109,0.688150286674,0.0),FreeCAD.Vector(1.40276777744,0.708000779152,0.0)]
spln=Draft.makeBSpline(points,closed=False,face=False,support=None)
objs=[]
#objs.append(FreeCAD.getDocument("test").getObject("BSpline001"))
Part.export([spln],"/home/daniel/Documents/test2.igs")
Example #31
0
cyl1.Radius = 0.2 * radius
cyl1.Height = 1.1 * height
cyl1.Placement = Base.Placement(Base.Vector(-1.1 * radius, 0.0, -0.2 * height),
                                Base.Rotation(0.0, 0.0, 0.0, 1))

arr = Draft.makeArray(cyl1, Base.Vector(1, 0, 0), Base.Vector(0, 1, 0), 2, 2)
arr.ArrayType = "polar"
arr.NumberPolar = 6

dif2 = doc.addObject("Part::Cut", "dif2")
dif2.Base = dif
dif2.Tool = arr

cyl2 = doc.addObject("Part::Cylinder", "cyl2")
cyl2.Radius = 0.3 * radius
cyl2.Height = height

dif3 = doc.addObject("Part::Cut", "dif3")
dif3.Base = dif2
dif3.Tool = cyl2

doc.recompute()

Part.export([dif3], 'screwdriver_handle.step')

doc.saveAs('screwdriver_handle.FCStd')

mesh = doc.addObject("Mesh::Feature", "Mesh")
mesh.Mesh = MeshPart.meshFromShape(Shape=dif3.Shape, MaxLength=0.002)
mesh.Mesh.write("./screwdriver_handle.bdf", "NAS", "mesh")
Example #32
0
cyl3.Height = height
cyl3.Placement = Base.Placement(Base.Vector(0, 0, height),
                                Base.Rotation(0, 0, 0, 1))

tip1 = doc.addObject("Part::Box", "tip1")
tip1.Length = radius
tip1.Width = 2 * radius
tip1.Height = 3 * radius
tip1.Placement = Base.Placement(Base.Vector(0, -radius, 1.71 * height),
                                Base.Rotation(Base.Vector(0, 1, 0), -10),
                                Base.Vector(0, 0, 3 * radius))

tip2 = doc.addObject("Part::Mirroring", "tip2")
tip2.Source = tip1
tip2.Normal = (1, 0, 0)

tip3 = doc.addObject("Part::MultiFuse", "tip3")
tip3.Shapes = [tip1, tip2]

dif4 = doc.addObject("Part::Cut", "dif4")
dif4.Base = cyl3
dif4.Tool = tip3

uni2 = doc.addObject("Part::MultiFuse", "uni2")
uni2.Shapes = [cyl2, dif4]

doc.recompute()

Part.export([dif3, uni2], 'screwdriver_full.step')
doc.saveAs('screwdriver_full.FCStd')
Example #33
0
import os
import FreeCAD
import Part
import PartDesign

App = FreeCAD
print(dir(PartDesign))
for part in [
        'left_y_idler_plate',
        'left_y_motor_plate',
        'left_y_carriage_plate',
        'left_z_rod_support',
        'left_z_rod_plate',
        'x_carriage_plate',
        'titan_mount_plate',
]:
    FreeCAD.open(f"{part}.FCStd")
    App.setActiveDocument(part)
    body = None
    for o in FreeCAD.ActiveDocument.Objects:
        if o.TypeId == "PartDesign::Body":
            body = o
            break

    print(body)
    Part.export([body], f'printed/{part}.brep')
Example #34
0
 def saveFile(self):
     
     import FreeCADGui
     if self.form.Radio_Selection.isChecked():
         objects = FreeCADGui.Selection.getSelection()
     else:
         objects = [obj for obj in FreeCAD.ActiveDocument.Objects if obj.ViewObject.isVisible()]
     if not objects:
         QtGui.QMessageBox.critical(None,translate("WebTools","Nothing to upload"),translate("The selection of the document contains no object to upload"))
         return None
     filename = os.path.join(tempfile._get_default_tempdir(),next(tempfile._get_candidate_names()))
     filetype = self.form.Combo_Filetype.currentIndex()
     # 0 = obj + mtl, 1 = obj, 2 = dae, 3 = stl, 4 = IGES, 5 = iv (currently not working)
     if filetype == 0: # OBJ + MTL
         import importOBJ
         importOBJ.export(objects,filename+".obj")
         return self.packFiles(filename,[filename+".obj",filename+".mtl"])
     elif filetype == 1: # OBJ (mesh exporter)
         import Mesh
         Mesh.export(objects,filename+".obj")
         return self.packFiles(filename,[filename+".obj"])
     elif filetype == 2: # DAE
         import importDAE
         importDAE.export(objects,filename+".dae")
         return self.packFiles(filename,[filename+".dae"])
     elif filetype == 3: # STL
         import Mesh
         Mesh.export(objects,filename+".stl")
         return self.packFiles(filename,[filename+".stl"])
     elif filetype == 4: # IGES
         import Part
         Part.export(objects,filename+".iges")
         return self.packFiles(filename,[filename+".iges"])
     elif filetype == 5: # IV
         import FreeCADGui
         # remove objects with no face (unsupported by this format)
         nobjects = []
         for o in objects:
             if o.isDerivedFrom("Part::Feature"):
                 if o.Shape.Faces:
                     nobjects.append(o)
         FreeCADGui.export(nobjects,filename+".iv")
         # removing FreeCAD-specific nodes
         f = open(filename+".iv","rb")
         s = f.read()
         f.close()
         ver = FreeCAD.Version()
         vinfo = "# Exported by FreeCAD v" + ver[0] + "." + ver[1] + " build" + ver[2] + "\n"
         vinfo += "# http://www.freecadweb.org\n"
         s = s.replace("#Inventor V2.1 ascii","#Inventor V2.1 ascii\n"+vinfo)
         s = s.replace("SoBrepEdgeSet","IndexedLineSet")
         s = s.replace("SoBrepFaceSet","IndexedFaceSet")
         s = s.replace("SoBrepPointSet","IndexedPointSet")
         s = s.replace("\n","--endl--")
         s = re.sub("--endl--[ \t]+highlightIndex.*?--endl--","--endl--",s)
         s = re.sub("--endl--[ \t]+partIndex.*?--endl--","--endl--",s)
         s = re.sub("--endl--[ \t]+selectionIndex.*?--endl--","--endl--",s)
         s = re.sub("SFInt32 highlightIndex, ","",s)
         s = re.sub("MFInt32 partIndex, ","",s)
         s = re.sub("MFInt32 selectionIndex ","",s)
         s = re.sub(", \]"," \]",s)
         s = s.replace("--endl--","\n")
         f = open(filename+".iv","wb")
         f.write(s)
         f.close()
         print("saved "+filename+".iv")
         return self.packFiles(filename,[filename+".iv"])
import FreeCAD
import Mesh
import Part
import importDWG

projects = [
  "open_air_case_frame",
  "foot",
]

objects = []
for project in projects:
  FreeCAD.openDocument("./projects/"+project+".fcstd")
  FreeCAD.setActiveDocument(project)

  objects.append(FreeCAD.getDocument(project).getObject("Group"))

  Mesh.export(objects, u"./exports/"+project+".obj")
  Mesh.export(objects, u"./exports/"+project+".amf")
  Part.export(objects, u"./exports/"+project+".iges")
  importDWG.export(objects, u"./exports/"+project+".dwg")

  del objects
    FreeCAD.Gui.activeDocument().activeView().viewAxometric()


if DOC is None:
    FreeCAD.newDocument(DOC_NAME)
    FreeCAD.setActiveDocument(DOC_NAME)
    DOC = FreeCAD.activeDocument()
else:
    clear_doc()

# EPS= tolerance to use to cut the parts
EPS = 0.10
EPS_C = EPS * -0.5

cylinder_1 = Part.makeCylinder(4, 40)

cylinder_2 = Part.makeCylinder(3.5, 40)

# Cut
cut = cylinder_1.cut(cylinder_2)

Part.show(cut)

DOC.recompute()

step_file = "C:\\part_spacer_bottom_support_ground.stp"

Part.export([cut], step_file)

setview()
    # Gui.ActiveDocument.getObject(baseName).ShapeColor=Gui.ActiveDocument.getObject("Pad").ShapeColor
    # Gui.ActiveDocument.getObject(baseName).DisplayMode=Gui.ActiveDocument.getObject("Pad").DisplayMode
    App.ActiveDocument.recompute()
if (sphereNum > 1):  # 如果存在多于两个球体
    for i in range(sphereNum - 1):
        baseName = ZONENAME + str(i)
        sphereName = "Sphere" + str(
            i + 1)  # 第二个球体的名字,第n个球体的名字为"Sphere"+str(n-1)
        cutName = ZONENAME + str(i + 1)  # “fluid”后面的数字n表示减去了n+1个球之后的结构名

        App.activeDocument().addObject("Part::Cut", cutName)
        App.activeDocument().getObject(
            cutName).Base = App.activeDocument().getObject(baseName)
        App.activeDocument().getObject(
            cutName).Tool = App.activeDocument().getObject(sphereName)
        # Gui.activeDocument().hide(baseName)
        # Gui.activeDocument().hide(sphereName)
        # Gui.ActiveDocument.getObject(cutName).ShapeColor=Gui.ActiveDocument.getObject(baseName).ShapeColor
        # Gui.ActiveDocument.getObject(cutName).DisplayMode=Gui.ActiveDocument.getObject(baseName).DisplayMode
        App.ActiveDocument.recompute()

__objs__ = []
object = ZONENAME + str(sphereNum - 1)
print_to("\nZoneName=" + object)
__objs__.append(FreeCAD.ActiveDocument.getObject(object))
print_to("\nmodelFile=" + os.path.join(modelFolder, modelName))
Part.export(__objs__, (os.path.join(modelFolder, modelName)))

del __objs__
# exit()
    radius_cathode = 150
    alpha = (i*2*math.pi)/12
    cylinder_vector = (radius_anode*math.cos(alpha), radius_anode*math.sin(alpha), 0)
    cylinder_3 = Part.makeCylinder(9.525, 10)
    cylinder_3.translate(cylinder_vector)
    disc = disc.cut(cylinder_3)
    cylinder_4 = Part.makeCylinder(8.525, 15)
    cylinder_4.translate(cylinder_vector)
    disc = disc.cut(cylinder_4)

# Cut the holes for the screws fixing the cathodes on the disc
for i in range(12):
    axe_y = FreeCAD.Vector(0, 1, 0)
    axe_z = FreeCAD.Vector(0, 0, 1)
    radius_screw = 133
    alpha = (i*2*math.pi)/12
    cylinder_vector = FreeCAD.Vector(radius_screw*math.cos(alpha), radius_screw*math.sin(alpha), 4.5)
    cylinder = Part.makeCylinder(2.5, 17, cylinder_vector, axe_y)
    cylinder.rotate(cylinder_vector, axe_z, alpha*(360/(2*math.pi)) - 90)
    disc = disc.cut(cylinder)

Part.show(disc)

DOC.recompute()

step_file = "C:\\part_disc_cathode.stp"

Part.export([disc], step_file) 

setview()
Example #39
0
radiatorSHP = Part.makeBox(RL,RW,RH,Base.Vector(RX,RY,RZ))
doc.addObject("Part::Feature","radiator")
doc.radiator.Shape = radiatorSHP

# FANS on radiator
FR = 3 # radius
FD = 2 # depth
FS = 2 # fan's distance from radiator's bottom
FX = float(RL)/2+RX; FYleft = RY; FYright = RY+RW; FZ = RZ+FS+FR
leftFanSHP = Part.makeCylinder(FR,FD,Base.Vector(FX,FYleft,FZ),Base.Vector(0,-1,0))
doc.addObject("Part::Feature","leftFan")
doc.leftFan.Shape = leftFanSHP
rightFanSHP = Part.makeCylinder(FR,FD,Base.Vector(FX,FYright,FZ),Base.Vector(0,1,0))
doc.addObject("Part::Feature","rightFan")
doc.rightFan.Shape = rightFanSHP



__objs__=[]
__objs__.append(FreeCAD.getDocument("transformer").getObject("tank"))
__objs__.append(FreeCAD.getDocument("transformer").getObject("midBush"))
__objs__.append(FreeCAD.getDocument("transformer").getObject("leftBush"))
__objs__.append(FreeCAD.getDocument("transformer").getObject("rightBush"))
__objs__.append(FreeCAD.getDocument("transformer").getObject("expVessel"))
__objs__.append(FreeCAD.getDocument("transformer").getObject("radiator"))
__objs__.append(FreeCAD.getDocument("transformer").getObject("leftFan"))
__objs__.append(FreeCAD.getDocument("transformer").getObject("rightFan"))


Part.export(__objs__,"C:/Users/XJULLI/Documents/MacroJuju/official.step")

def setview():
    # Rearrange View
    FreeCAD.Gui.SendMsgToActiveView("ViewFit")
    FreeCAD.Gui.activeDocument().activeView().viewAxometric()


if DOC is None:
    FreeCAD.newDocument(DOC_NAME)
    FreeCAD.setActiveDocument(DOC_NAME)
    DOC = FreeCAD.activeDocument()
else:
    clear_doc()

# EPS= tolerance to use to cut the parts
EPS = 0.10
EPS_C = EPS * -0.5

torus = Part.makeTorus(19.05, 3.175)

Part.show(torus)

DOC.recompute()

step_file = "C:\\part_torus.stp"

Part.export([torus], step_file)

setview()
Example #41
0
else:
    clear_doc()

# EPS= tolerance to use to cut the parts
EPS = 0.10
EPS_C = EPS * -0.5

cylinder_1 = Part.makeCylinder(11, 20)

cylinder_2 = Part.makeCylinder(6.35, 20)

cylinder_3 = cylinder_1.cut(cylinder_2)

cylinder_4 = Part.makeCylinder(11, 18)

cylinder_5 = Part.makeCylinder(6.35 + (8.525 - 6.35), 18)

cylinder_6 = cylinder_4.cut(cylinder_5)

spacer = cylinder_3.cut(cylinder_6)

Part.show(spacer)

DOC.recompute()

step_file = "C:\\part_spacer_anode_cathode.stp"

Part.export([spacer], step_file)

setview()