Example #1
1
def ImportElement():
  doc=FreeCAD.ActiveDocument;
  FreeCAD.Console.PrintMessage("Try to import...\n");
  (fname1,fdir1) = QtGui.QFileDialog.getOpenFileName(None,'Open file','');
  ImportGui.insert(fname1,doc.Name);
  doc.recompute();
  ob1=doc.Objects[-1];
    # create groupe and add element to it
  if (hasattr(doc,'OpticalSystem')==False):
    gr1=doc.addObject("App::DocumentObjectGroup","OpticalSystem");
    gr1.newObject("App::DocumentObjectGroup","Rays");
    gr1_e=gr1.newObject("App::DocumentObjectGroup","Elements");
    gr1_e.addObject(ob1);
  else:
    gr1_e=getattr(doc,'Elements');
    gr1_e.addObject(ob1);
  # end if
  ob1.Label="IMPR";
  ob1.ViewObject.ShapeColor=(0.5,0.5,0.5);
  ob1.ViewObject.Transparency=80;
  An=ob1.Placement.Rotation.toEuler();
  P1=ob1.Placement.Base;
  l1=["","Imported",ob1.Name,ob1.Label, \
      P1.x,P1.y,P1.z, \
      An[2],An[1],An[0],None,None,None,1.,1.52,None,None];
  # add lens to list of optical system elements
  OptElementsGui.AddToOSData(l1,"Element");
  doc.recompute();
  if (str(FreeCADGui.ActiveDocument.activeView())=='View3DInventor'):
    FreeCADGui.activeDocument().activeView().viewRear();
    FreeCADGui.activeDocument().activeView().viewRotateRight();
    FreeCADGui.activeDocument().activeView().fitAll();
  # end if
  FreeCAD.Console.PrintMessage("Element is imported\n");
Example #2
0
def import_cad(path, doc):
    """ Imports cad file at path into document doc. May produce more than one FreeCAD object! """
    cadpath = os.path.join('..', '..', path)  # For test bench runs (..\..\ takes you to project root)
    if not os.path.exists(cadpath):
        cadpath = path
        if not os.path.exists(cadpath):
            exitwitherror('Can\'t find cad file!')
    fileformat = cadpath.rsplit('.')[-1].lower()

    newdoc = None
    try:
        if fileformat in ["step", "stp"]:
            ImportGui.insert(cadpath, doc)
        elif fileformat == 'stl':
            Mesh.insert(cadpath, doc)
        elif fileformat == "fcstd":
            # This will create a new doc and ignore doc operator
            newdoc = open_document(cadpath)
        else:
            exitwitherror('Unsupported file format {0} for file to import {1}.'.format(str(fileformat), str(path)))

    except (Exception, IOError) as err:
        logger.error(err)
        exitwitherror('Error attempting to import {0}'.format(cadpath))

    logger.info('Imported CAD file {0}'.format(cadpath))
    return cadpath, fileformat, newdoc
Example #3
0
    def load(self, path):
        """ Loads FC, STEP, or STL file into document object. Will return cadpath and format
            properties to store into Part/Assembly class if desired. """
        cadpath = os.path.join('..', '..', path)  # For test bench runs (..\..\ takes you to project root)
        if not os.path.exists(cadpath):
            cadpath = path
            if not os.path.exists(cadpath):
                exitwitherror('Can\'t find cad file!')
        fileformat = cadpath.rsplit('.')[-1].lower()

        try:
            if fileformat in ["step", "stp"]:
                ImportGui.insert(cadpath, self.Name)
            elif fileformat == 'stl':
                Mesh.insert(cadpath, self.Name)
            elif fileformat == "fcstd":
                # Loading a FC file will always open a new doc, so close the current one and set to the new one.
                self.close()
                self.document = FreeCAD.openDocument(cadpath)
                self.Name = self.document.Name
            else:
                exitwitherror('Unsupported file format {0} for file {1}.'.format(str(fileformat), str(path)))

        except (Exception, IOError) as err:
            logger.error(err)
            exitwitherror('Error attempting to import {0}'.format(cadpath))

        logger.info('Imported CAD file {0}'.format(cadpath))

        return cadpath, fileformat
Example #4
0
def GetSTEPAssembly():
    deviceProperties = clsConnectToEB.ConnectToEB().GetShapeProperties()
    file_path = deviceProperties[2]
    exists = os.path.isfile(file_path)
    if exists:
        ImportGui.insert(file_path, FreeCAD.ActiveDocument.Name)
    else:
        EB_Auxiliaries.MsgDialog("STEP file doesn't exist!")
Example #5
0
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
Example #6
0
def place_steps(doc,placement,board_thickness):
    """ place_steps(doc,placement,board_thickness)->place step models on board 

        list of models and path to step files is set at start of this script
                 model_tab_filename= "" &   step_path="" """
    model_file=pythonopen(model_tab_filename, "r")
    model_lines=model_file.readlines()
    model_file.close()   
    model_dict=[]
    if IDF_diag==1:
        model_file=pythonopen(IDF_diag_path+"/missing_models.lst", "w")
    keys=[]
    #prev_step="*?.*?" #hope nobody will insert this step filename
    step_dict=[]
    for model_line in model_lines:
        model_records=split_records(model_line)  
        if len(model_records)>1 and model_records[0] and not model_records[0] in keys:
           keys.append(model_records[0])  
           model_dict.append((str(model_records[0]).replace('"',''),str(model_records[1]).replace('"','')))
    model_dict=dict(model_dict)
    validkeys=filter(lambda x:x in  [place_item[2] for place_item in placement], model_dict.keys())
    FreeCAD.Console.PrintMessage("Step models to be loaded for footprints: "+str(validkeys)+"\n")
    grp=doc.addObject("App::DocumentObjectGroup", "Step Lib")
    for validkey in validkeys:
         ImportGui.insert(step_path+model_dict[validkey],FreeCAD.ActiveDocument.Name)
         #partName=FreeCAD.ActiveDocument.ActiveObject.Name
         impPart=FreeCAD.ActiveDocument.ActiveObject
         #impPart.Shape=FreeCAD.ActiveDocument.ActiveObject.Shape
         #impPart.ViewObject.DiffuseColor=FreeCAD.ActiveDocument.ActiveObject.ViewObject.DiffuseColor
         impPart.ViewObject.Visibility=0
         impPart.Label=validkey
         grp.addObject(impPart)
         step_dict.append((validkey,impPart))
         FreeCAD.Console.PrintMessage("Reading step file "+str(model_dict[validkey])+" for footprint "+str(validkey)+"\n")
    step_dict=dict(step_dict)
    grp=doc.addObject("App::DocumentObjectGroup", "Step Models")
    for place_item in placement:
      if place_item[2] in step_dict:
        step_model=doc.addObject("Part::Feature",place_item[0]+"_s")
        FreeCAD.Console.PrintMessage("Adding STEP model "+str(place_item[0])+"\n")
        #if prev_step!=place_item[2]:
        #   model0=Part.read(step_path+"/"+model_dict[place_item[2]])
        #   prev_step=place_item[2]
        step_model.Shape=step_dict[place_item[2]].Shape
        step_model.ViewObject.DiffuseColor=step_dict[place_item[2]].ViewObject.DiffuseColor
        z_pos=0
        rotateY=0
        if place_item[6]=='BOTTOM':
           rotateY=pi
           z_pos=-board_thickness
        placmnt=Base.Placement(Base.Vector(place_item[3],place_item[4],z_pos),toQuaternion(rotateY,place_item[5]*pi/180,0))
        step_model.Placement=placmnt
        grp.addObject(step_model)
      else: 
        if IDF_diag==1:
            model_file.writelines(str(place_item[0])+" "+str(place_item[2])+"\n")
            model_file.close() 
Example #7
0
def place_steps(doc,placement,board_thickness):
    """ place_steps(doc,placement,board_thickness)->place step models on board 

        list of models and path to step files is set at start of this script
                 model_tab_filename= "" &   step_path="" """
    model_file=pythonopen(model_tab_filename, "r")
    model_lines=model_file.readlines()
    model_file.close()   
    model_dict=[]
    if IDF_diag==1:
        model_file=pythonopen(IDF_diag_path+"/missing_models.lst", "w")
    keys=[]
    #prev_step="*?.*?" #hope nobody will insert this step filename
    step_dict=[]
    for model_line in model_lines:
        model_records=split_records(model_line)  
        if len(model_records)>1 and model_records[0] and not model_records[0] in keys:
           keys.append(model_records[0])  
           model_dict.append((str(model_records[0]).replace('"',''),str(model_records[1]).replace('"','')))
    model_dict=dict(model_dict)
    validkeys=filter(lambda x:x in  [place_item[2] for place_item in placement], model_dict.keys())
    FreeCAD.Console.PrintMessage("Step models to be loaded for footprints: "+str(validkeys)+"\n")
    grp=doc.addObject("App::DocumentObjectGroup", "Step Lib")
    for validkey in validkeys:
         ImportGui.insert(step_path+model_dict[validkey],FreeCAD.ActiveDocument.Name)
         #partName=FreeCAD.ActiveDocument.ActiveObject.Name
         impPart=FreeCAD.ActiveDocument.ActiveObject
         #impPart.Shape=FreeCAD.ActiveDocument.ActiveObject.Shape
         #impPart.ViewObject.DiffuseColor=FreeCAD.ActiveDocument.ActiveObject.ViewObject.DiffuseColor
         impPart.ViewObject.Visibility=0
         impPart.Label=validkey
         grp.addObject(impPart)
         step_dict.append((validkey,impPart))
         FreeCAD.Console.PrintMessage("Reading step file "+str(model_dict[validkey])+" for footprint "+str(validkey)+"\n")
    step_dict=dict(step_dict)
    grp=doc.addObject("App::DocumentObjectGroup", "Step Models")
    for place_item in placement:
      if place_item[2] in step_dict:
        step_model=doc.addObject("Part::Feature",place_item[0]+"_s")
        FreeCAD.Console.PrintMessage("Adding STEP model "+str(place_item[0])+"\n")
        #if prev_step!=place_item[2]:
        #   model0=Part.read(step_path+"/"+model_dict[place_item[2]])
        #   prev_step=place_item[2]
        step_model.Shape=step_dict[place_item[2]].Shape
        step_model.ViewObject.DiffuseColor=step_dict[place_item[2]].ViewObject.DiffuseColor
        z_pos=0
        rotateY=0
        if place_item[6]=='BOTTOM':
           rotateY=pi
           z_pos=-board_thickness
        placmnt=Base.Placement(Base.Vector(place_item[3],place_item[4],z_pos),toQuaternion(rotateY,place_item[5]*pi/180,0))
        step_model.Placement=placmnt
        grp.addObject(step_model)
      else: 
        if IDF_diag==1:
            model_file.writelines(str(place_item[0])+" "+str(place_item[2])+"\n")
            model_file.close() 
    def importNumberRing10(self, modelName):
        """ imports a step file of the ring with numbers (0..9) for the rotary coded switch
        :rtype: ``solid``
        """
        cwd = os.path.dirname(os.path.realpath(__file__)) + "/NumberRing10.step"

        ImportGui.insert(cwd, modelName)

        tmp = FreeCAD.ActiveDocument.Objects[-1]
        tmp.Placement=\
                    FreeCAD.Placement(FreeCAD.Vector(0, 0, self.body_height + self.cover_thickness + self.body_board_distance), FreeCAD.Rotation(FreeCAD.Vector(0,0,0), FreeCAD.Vector(0,0,0)))
        #App.Placement(App.Vector(0,0,5), App.Rotation(App.Vector(0,0,1),0), App.Vector(0,0,0))
        d = os.path.dirname(os.path.realpath(__file__)) + "/NumberRing10.step"
    def Activated(self):
        a2plib.setAutoSolve(True)  # makes no sense without autosolve = ON
        doc = FreeCAD.activeDocument()
        fileName = doc.FileName
        workingDir, basicFileName = os.path.split(fileName)

        filesToUpdate = []
        subAsmNeedsUpdate, filesToUpdate = createUpdateFileList(
            fileName, workingDir, filesToUpdate, True)

        for f in filesToUpdate:
            #-------------------------------------------
            # update necessary documents
            #-------------------------------------------

            # look only for filenames, not paths, as there are problems on WIN10 (Address-translation??)
            importDoc = None
            importDocIsOpen = False
            requestedFile = os.path.split(f)[1]
            for d in FreeCAD.listDocuments().values():
                recentFile = os.path.split(d.FileName)[1]
                if requestedFile == recentFile:
                    importDoc = d  # file is already open...
                    importDocIsOpen = True
                    break

            if not importDocIsOpen:
                if f.lower().endswith('.fcstd'):
                    importDoc = FreeCAD.openDocument(f)
                elif f.lower().endswith('.stp') or f.lower().endswith('.step'):
                    import ImportGui
                    fname = os.path.splitext(os.path.basename(f))[0]
                    FreeCAD.newDocument(fname)
                    newname = FreeCAD.ActiveDocument.Name
                    FreeCAD.setActiveDocument(newname)
                    ImportGui.insert(filename, newname)
                    importDoc = FreeCAD.ActiveDocument
                else:
                    msg = "A part can only be imported from a FreeCAD '*.fcstd' file"
                    QtGui.QMessageBox.information(
                        QtGui.QApplication.activeWindow(), "Value Error", msg)
                    return

            updateImportedParts(importDoc)
            FreeCADGui.updateGui()
            importDoc.save()
            print(u"==== Assembly '{}' has been updated! =====".format(
                importDoc.FileName))
            if importDoc != doc:
                FreeCAD.closeDocument(importDoc.Name)
Example #10
0
def GetSingleShapeFromSTEP(file_path):
    doc = FreeCAD.ActiveDocument
    current_instances = set(doc.findObjects())
    ImportGui.insert(file_path, doc.Name)
    new_instances = list(set(doc.findObjects()) - current_instances)
    if not len(new_instances) == 1:
        DeleteObjects(doc, new_instances)
        return
    obj = new_instances[0]
    shape = Part.makeCompound(obj.Shape)
    newObj = doc.addObject("Part::Feature", "Test")
    newObj.Shape = obj.Shape.copy()
    newObj.ViewObject.ShapeColor = obj.ViewObject.ShapeColor
    newObj.ViewObject.DiffuseColor = obj.ViewObject.DiffuseColor
    doc.removeObject(obj.Name)
Example #11
0
def exportVRML(doc, modelName, scale, dir):

    ## Export to VRML scaled 1/2.54
    #VrmlFileName='.//'+doc.Label+'.wrl'
    ## outdir=os.path.dirname(os.path.realpath(__file__))+dir
    outdir = dir
    #FreeCAD.Console.PrintMessage('\r\n'+outdir)
    VrmlFileName = outdir + '/' + modelName + '.wrl'
    StepFileName = outdir + '/' + modelName + '.step'
    objs = []
    objs = GetListOfObjects(FreeCAD, doc)
    #objs.append(FreeCAD.getDocument(doc.Name).getObject("Fusion001"))
    FreeCAD.ActiveDocument.addObject('Part::Feature',
                                     'Vrml_model').Shape = objs[0].Shape
    FreeCAD.ActiveDocument.ActiveObject.Label = 'Vrml_model'
    FreeCADGui.ActiveDocument.ActiveObject.ShapeColor = FreeCADGui.getDocument(
        doc.Name).getObject(objs[0].Name).ShapeColor
    FreeCADGui.ActiveDocument.ActiveObject.LineColor = FreeCADGui.getDocument(
        doc.Name).getObject(objs[0].Name).LineColor
    FreeCADGui.ActiveDocument.ActiveObject.PointColor = FreeCADGui.getDocument(
        doc.Name).getObject(objs[0].Name).PointColor
    FreeCADGui.ActiveDocument.ActiveObject.DiffuseColor = FreeCADGui.getDocument(
        doc.Name).getObject(objs[0].Name).DiffuseColor
    FreeCAD.ActiveDocument.recompute()
    newObj = FreeCAD.getDocument(doc.Name).getObject('Vrml_model')
    #scale to export vrml  start
    Draft.scale(newObj,
                delta=FreeCAD.Vector(scale, scale, scale),
                center=FreeCAD.Vector(0, 0, 0),
                legacy=True)

    FreeCAD.activeDocument().recompute()
    #we need to remove object to export only scaled model
    FreeCAD.getDocument(doc.Name).removeObject(objs[0].Name)
    __objs__ = []
    __objs__.append(FreeCAD.getDocument(doc.Name).getObject("Vrml_model"))
    FreeCADGui.export(__objs__, VrmlFileName)
    FreeCAD.activeDocument().recompute()

    #restoring step module
    import ImportGui
    ImportGui.insert(StepFileName, doc.Name)

    FreeCAD.Console.PrintMessage(FreeCAD.ActiveDocument.ActiveObject.Label +
                                 " exported and scaled to Vrml\r\n")
    del __objs__

    return 0
 def GetShapeWithColor(self, fp, stepFilePath):
     doc = FreeCAD.ActiveDocument
     current_instances = set(doc.findObjects())
     ImportGui.insert(stepFilePath, doc.Name)
     new_instances = list(set(doc.findObjects()) - current_instances)
     if not len(new_instances) == 1:
         self.DeleteObjects(doc, new_instances)
         print("In step file are more as one shapes!")
         self.GetShapeWithoutColor(fp, stepFilePath)
     else:
         print("In step file is one shape!")
         newObj = new_instances[0]
         fp.Shape = newObj.Shape
         fp.ViewObject.ShapeColor = newObj.ViewObject.ShapeColor
         fp.ViewObject.DiffuseColor = newObj.ViewObject.DiffuseColor
         self.DeleteObjects(doc, new_instances)
Example #13
0
    def convert(self, alpha=None):
        doc = FreeCAD.newDocument("Unnamed")
        FreeCAD.setActiveDocument("Unnamed")
        ImportGui.insert(self._step_file, "Unnamed")
        for rootobj in doc.RootObjects:
            self._handle_object(rootobj)

        scadfile = os.path.join(
            self._out_dir, os.path.basename(self._step_file) + '.scad'
        )
        print(f'Writing SCAD file with import statements to: {scadfile}')
        with open(scadfile, 'w') as fh:
            fh.write(f'imported_alpha = {alpha};\n')
            for f in self._objects:
                fh.write(f.scad(alpha=alpha) + '\n')
        print('\tfile written')
        FreeCAD.closeDocument("Unnamed")
def exportVRML(doc,modelName,scale,dir):

	## Export to VRML scaled 1/2.54
	#VrmlFileName='.//'+doc.Label+'.wrl'
	## outdir=os.path.dirname(os.path.realpath(__file__))+dir
	outdir=dir
	FreeCAD.Console.PrintMessage('\r\n'+outdir)
	VrmlFileName=outdir+'/'+modelName+'.wrl'
	StepFileName=outdir+'/'+modelName+'.step'
	objs=[]
	objs=GetListOfObjects(FreeCAD, doc)
	#objs.append(FreeCAD.getDocument(doc.Name).getObject("Fusion001"))
	FreeCAD.ActiveDocument.addObject('Part::Feature','Vrml_model').Shape=objs[0].Shape
	FreeCAD.ActiveDocument.ActiveObject.Label='Vrml_model'
	FreeCADGui.ActiveDocument.ActiveObject.ShapeColor=FreeCADGui.getDocument(doc.Name).getObject(objs[0].Name).ShapeColor
	FreeCADGui.ActiveDocument.ActiveObject.LineColor=FreeCADGui.getDocument(doc.Name).getObject(objs[0].Name).LineColor
	FreeCADGui.ActiveDocument.ActiveObject.PointColor=FreeCADGui.getDocument(doc.Name).getObject(objs[0].Name).PointColor
	FreeCADGui.ActiveDocument.ActiveObject.DiffuseColor=FreeCADGui.getDocument(doc.Name).getObject(objs[0].Name).DiffuseColor
	FreeCAD.ActiveDocument.recompute()
	newObj=FreeCAD.getDocument(doc.Name).getObject('Vrml_model')
	#scale to export vrml  start
	Draft.scale(newObj,delta=FreeCAD.Vector(scale,scale,scale),center=FreeCAD.Vector(0,0,0),legacy=True)

	FreeCAD.activeDocument().recompute()
	#we need to remove object to export only scaled model
	FreeCAD.getDocument(doc.Name).removeObject(objs[0].Name)
	__objs__=[]
	__objs__.append(FreeCAD.getDocument(doc.Name).getObject("Vrml_model"))
	FreeCADGui.export(__objs__,VrmlFileName)
	FreeCAD.activeDocument().recompute()

	#restoring step module
	import ImportGui
	ImportGui.insert(StepFileName,doc.Name)

	FreeCAD.Console.PrintMessage(FreeCAD.ActiveDocument.ActiveObject.Label+" exported and scaled to Vrml\r\n")
	del __objs__

	return 0
Example #15
0
def GetShapeFromSTEP(file_path):

    doc = FreeCAD.ActiveDocument
    current_instances = set(doc.findObjects())
    ImportGui.insert(file_path, doc.Name)
    new_instances = set(doc.findObjects()) - current_instances
    shapes = list(new_instances)
    sh = []
    cols = []
    areas = []

    for s in shapes:
        # print(s.TypeId)

        if hasattr(s, "Shape"):
            if hasattr(s.ViewObject, "DiffuseColor"):
                col = list(zip(s.Shape.Faces, s.ViewObject.DiffuseColor))
                print(len(s.Shape.Faces))
                print(len(s.ViewObject.DiffuseColor))
                print(s.ViewObject.DiffuseColor)
                print(len(col))
                cols.append(col)
                # print(s.ViewObject.DiffuseColor)
                sh.append(s.Shape)

    for c in cols:
        for faceshape, colortuple in c:
            areas.append((faceshape.Area, colortuple))

    # for s in shapes:
    #     try:
    #         doc.removeObject(s.Name)
    #     except:
    #         pass
    shape = Part.makeCompound(sh)
    # print(len(shape.Faces))
    # print(len(areas))
    Part.show(shape)
Example #16
0
def insert(filename, doc):

    sayz("stpZ version " + ___stpZversion___)
    with gz.open(filename, 'rb') as f:
        file_content = f.read()

    ext = os.path.splitext(os.path.basename(filename))[1]
    fname = os.path.splitext(os.path.basename(filename))[0]
    basepath = os.path.split(filename)[0]
    filepath = os.path.join(basepath, fname + u'.stp')

    tempdir = tempfile.gettempdir()  # get the current temporary directory
    tempfilepath = os.path.join(tempdir, fname + u'.stp')

    with six.builtins.open(tempfilepath, 'wb') as f:  #py3
        f.write(file_content)
    ImportGui.insert(tempfilepath, doc)
    #ImportGui.open(tempfilepath)
    try:
        os.remove(tempfilepath)
    except OSError:
        sayzerr("error on removing " + tempfilepath + " file")
        pass
Example #17
0
def insert(filename,doc):

    sayz("stpZ version "+___stpZversion___)
    with gzip_utf8.open(filename, 'rb') as f:
        file_content = f.read()

    ext = os.path.splitext(os.path.basename(filename))[1]
    fname=os.path.splitext(os.path.basename(filename))[0]
    basepath=os.path.split(filename)[0]
    filepath = os.path.join(basepath,fname + u'.stp')

    tempdir = tempfile.gettempdir() # get the current temporary directory
    tempfilepath = os.path.join(tempdir,fname + u'.stp')
    
    with builtin.open(tempfilepath, 'w') as f: #py3
        f.write(file_content)
    ImportGui.insert(tempfilepath, doc)
    #ImportGui.open(tempfilepath)
    try:
        os.remove(tempfilepath)
    except OSError:
        sayzerr("error on removing "+tempfilepath+" file")
        pass
def importPart(filename):
    doc_assembly = App.ActiveDocument
    App.Console.PrintMessage("importing part from %s\n" % filename)
    
    doc_already_open = filename in [ d.FileName for d in App.listDocuments().values() ]
    App.Console.PrintMessage("%s open already %s" % (filename, doc_already_open))
    
    if doc_already_open:
        doc = [ d for d in App.listDocuments().values() if d.FileName == filename][0]
    else:
        if filename.lower().endswith('.fcstd'):
            App.Console.PrintMessage('opening %s' % filename)
            doc = App.openDocument(filename)
            App.Console.PrintMessage('succesfully opened %s' % filename)
        else: #trying shaping import http://forum.freecadweb.org/viewtopic.php?f=22&t=12434&p=99772#p99772x
            import ImportGui
            doc = App.newDocument( os.path.basename(filename) )
            shapeobj=ImportGui.insert(filename,doc.Name)
    
    visibleObjects = [ obj for obj in doc.Objects
                       if hasattr(obj,'ViewObject') and obj.ViewObject.isVisible()
                       and hasattr(obj,'Shape') and len(obj.Shape.Faces) > 0 and 'Body' not in obj.Name] # len(obj.Shape.Faces) > 0 to avoid sketches, skip Body
    App.Console.PrintMessage('Visible objects %s' % visibleObjects)
    
    obj = doc_assembly.addObject("Part::FeaturePython", 'part123456')
    obj.addProperty("App::PropertyFile", "sourceFile", "D3D_ImportPart").sourceFile = filename
    obj.addProperty("App::PropertyFloat", "timeLastImport", "D3D_ImportPart")
    obj.setEditorMode("timeLastImport", 1)
    obj.addProperty("App::PropertyBool", "fixedPosition", "D3D_ImportPart")
    obj.fixedPosition = not any([i.fixedPosition for i in doc_assembly.Objects if hasattr(i, 'fixedPosition') ])
    #obj.addProperty("App::PropertyBool", "updateColors", "importPart").updateColors = True
    obj_to_copy  = visibleObjects[0]
    obj.Shape = obj_to_copy.Shape.copy()
    
    obj.Proxy = Proxy_importPart()
    obj.timeLastImport = os.path.getmtime( filename )
    #clean up
    #if subAssemblyImport:
    #    doc_assembly.removeObject(tempPartName)
    if not doc_already_open: #then close again
        App.closeDocument(doc.Name)
        App.setActiveDocument(doc_assembly.Name)
        App.ActiveDocument = doc_assembly
    return obj
Example #19
0
    def Activated(cls, idx=0):
        _ = idx
        from .assembly import Assembly

        objs = []
        for obj in FreeCADGui.Selection.getSelection():
            if obj.isDerivedFrom('App::LinkGroup'):
                objs.append(obj)
            else:
                objs = None
                break

        filenames = None
        if not objs:
            filenames = QtGui.QFileDialog.getOpenFileNames(
                QtGui.QApplication.activeWindow(), 'Please select file', None,
                'STEP (*.stp *.step);;All (*.*)')[0]
            if not filenames:
                return

        FreeCAD.setActiveTransaction('Assembly import')

        doc = FreeCAD.ActiveDocument
        if not doc:
            doc = FreeCAD.newDocument()

        if filenames:
            import ImportGui
            for name in filenames:
                obj = ImportGui.insert(name,
                                       doc.Name,
                                       merge=False,
                                       useLinkGroup=True,
                                       mode=cls.importMode())
                if obj:
                    objs.append(obj)

        for obj in objs:
            Assembly.fromLinkGroup(obj)
        FreeCAD.closeActiveTransaction()
        return
def convertModel(group, docName):
    global _fileName
    acis = getReader()
    bodies = _resolveNodes(acis)
    stepfile = export(acis.name, acis.header, bodies)
    ImportGui.insert(stepfile, docName)
    def createPack(self):
        s = self.qSpinBox_n_cells_in_series.value()
        p = self.qSpinBox_n_cells_in_parallel.value()

        self.cell = Cell(self.model.text(), self.freecad_dir)
        # For now, n cells in series = width, n cells in para = length
        n_cells_in_height = p

        self.space_between_cells = float(self.qSpinBox_space_cells.value())

        # Shorthands
        
        prop = 'App::Property'
        
        fl = prop+'Float'
        pi = prop+'Integer'
        pl = prop+'Length'

        self.part = App.activeDocument().addObject('App::Part',generate_freecad_name())
        self.part.Label = BATTERY_PACK_DEFAULT_PART_LABEL
        self.part.addProperty(pl, 'Width', 'Dimensions', 'Battery pack width').Width = '10 mm'
        self.part.addProperty(pi, 'serie', 'Cells arrangement', 'Cells in series').serie = s
        self.part.addProperty(pi, 'para', 'Cells arrangement', 'Cells in parallel').para = p
        self.part.addProperty(
            fl,
            'space_between_cells',
            'Cells arrangement',
            'Space between cells'
        ).space_between_cells = self.space_between_cells

        # Default value, will change when we set the number of cells, the space between the cells, etc...
        self.part.addProperty(fl,
                            'total_nickel_strip_length',
                            "Connections",
                            "Total nickel strip length").total_nickel_strip_length = 0.0
        
        self.part.addProperty(pi, 'nc', 'Cell', 'Number of cells in the pack').nc = 0
        self.part.setExpression("nc", "serie*para")

        ### Cell ###
        self.part.addProperty(prop+'String', 'cell', 'Cell', 'Model of Cell used').cell = self.model.text()
        self.part.addProperty(fl, 'cell_price', 'Cell', 'Individual cell price').cell_price = self.cell.price
        self.part.addProperty(fl, 'cell_weight', 'Cell', 'Individual cell weight').cell_weight = self.cell.weight
        self.part.addProperty(fl, 'cell_radius', 'Cell', 'Individual cell radius').cell_radius = self.cell.radius
        self.part.addProperty(fl, 'cell_height', 'Cell', 'Individual cell height').cell_height = self.cell.height

        ### Nickel Strip ###
        self.part.addProperty(fl,
                            'nickel_strip_width',
                            'Nickel strip',
                            'Nickel strip width').nickel_strip_width = NICKEL_STRIP_WIDTH

        self.part.addProperty(fl,
                            'nickel_strip_height',
                            'Nickel strip',
                            'Nickel strip height'
                            ).nickel_strip_height = NICKEL_STRIP_HEIGHT

        self.part.addProperty(fl,
                            'nickel_strip_weight_per_mm3',
                            'Nickel strip',
                            'Nickel strip weight per mm3'
                            ).nickel_strip_weight_per_mm3 = NICKEL_STRIP_WEIGHT_PER_MM3

        ### Weight ###

        self.part.addProperty(fl,
                            'battery_holder_weight',
                            'Weight',
                            'Individual battery holder weight').battery_holder_weight = BATTERY_HOLDER_WEIGHT

        self.part.addProperty(fl, 'total_cells_weight', 'Weight', 'Total cells weight').total_cells_weight = 0.0
        self.part.setExpression("total_cells_weight", "cell_weight*nc")

        self.part.addProperty(fl,
                            'total_nickel_strip_weight',
                            'Weight',
                            'Total weight of nickel strip').total_nickel_strip_weight = 0.0

        self.part.addProperty(fl,
                            'total_battery_holders_weight',
                            'Weight',
                            'Total battery holders weight').total_battery_holders_weight = 0.0

        self.part.addProperty(fl,
                            'total_weight',
                            'Weight',
                            'Total weight of the battery pack').total_weight = 0.0
        
        ### Price ###

        self.part.addProperty(fl, 'total_cells_price', 'Price', 'Total cells price').total_cells_price = 0.0
        
        self.part.addProperty(fl,
                            'nickel_strip_price_per_mm',
                            'Price', 'Nickel strip price per mm'
                            ).nickel_strip_price_per_mm = NICKEL_STRIP_PRICE_PER_MM
        
        self.part.addProperty(fl,
                            'total_nickel_strip_price',
                            'Price',
                            'Total nickel strip price'
                            ).total_nickel_strip_price = 0.0

        Gui.activateView('Gui::View3DInventor', True)
        Gui.activeView().setActiveObject('part', self.part)
        App.ActiveDocument.recompute()

        for w in range(self.part.serie):
            placement_of_last_cell = self.create3dCell(w, self.part.space_between_cells)
            App.ActiveDocument.recompute()
        
        # Hacky way to import a .step model
        # Source : <https://forum.freecadweb.org/viewtopic.php?f=3&t=3951>

        current_instances = set(App.ActiveDocument.findObjects())
        ImportGui.insert(get_mod_path(self.freecad_dir)+HOLDER_PATH, App.ActiveDocument.Name)
        new_instances = set(App.ActiveDocument.findObjects()) - current_instances
        
        # Rotates the part 180 so the bottom of the holder is correctly placed
        new_instances.pop().Placement = App.Placement(App.Vector(0,0,0), App.Rotation(0,180,0), App.Vector(0,0,0))
        
        # Creates the nickel strips connecting all the cells in series
        
        # we multiply by 2 for the top and bottom strips
        self.part.setExpression(
            "total_nickel_strip_length",
            "2*(  ( (serie*((cell_radius*2)) ) + serie*(space_between_cells) ) - space_between_cells )"
        )

        # TEMPORARY
        #self.create_nickel_strips(placement_of_last_cell)
       
        # Volume * weight per mm³
        self.part.setExpression(
            "total_nickel_strip_weight",
            "total_nickel_strip_length*nickel_strip_width*nickel_strip_height*nickel_strip_weight_per_mm3"
        )
        
        self.part.setExpression(
            "total_battery_holders_weight",
            "battery_holder_weight*nc*2"
        )
        
        # One holder on top, one on the bottom
        self.part.setExpression(
            "total_weight",
            "total_nickel_strip_weight+total_battery_holders_weight+total_cells_weight"
        )
        
        ### Price ###
        self.part.setExpression("total_cells_price", "cell_price*nc")
        
        self.part.setExpression(
            "total_nickel_strip_price",
            "nickel_strip_price_per_mm*total_nickel_strip_length"
        )

        Gui.SendMsgToActiveView("ViewFit")
        App.ActiveDocument.recompute()

        self.close()
                        HDLR_stepfile_w = open(FLDR_toStepFiles + FNME_stepfile, 'w') # open
                    except:
                        print "broken_3"
                    else:
                        # overwrite with new preamble
                        for line in LIST_PMBL:
                            HDLR_stepfile_w.write(line + "\n")
                        # add old data section
                        for line in PMBL_stepfile[(DICT_positions["A"]-1):]:
                            HDLR_stepfile_w.write(line.strip() + "\n")
                        HDLR_stepfile_w.close()

                    # load STEP model, manipulate and save as VRML
                    FreeCAD.newDocument("Unnamed")
                    FreeCAD.setActiveDocument("Unnamed")
                    ImportGui.insert(FLDR_toStepFiles + FNME_stepfile,"Unnamed")
                    FNME_vrmlfile = FNME_stepfile[:-4] + ".wrl"
                    FNME_povfile = FNME_stepfile[:-4] + ".pov"
                    # change display mode
                    for part in FreeCAD.ActiveDocument.Objects:
                        part.ViewObject.DisplayMode = 1 #Shaded
                    if FLAG_makeTransparent: # if transparency is needed
#                        from PySide import QtGui
#                        QtGui.QInputDialog.getText(None, "Get text", "Input:")[0]
                        pass
                    objs=[] # select all parts
                    for part in FreeCAD.ActiveDocument.Objects:                    
                        objs.append(part)

                    exportToVRML(objs,(FLDR_toVrmlFiles + FNME_vrmlfile), 0.3937)                    
Example #23
0
for subsystem, v in structure.items():
    subsystem_grp = doc.addObject("App::DocumentObjectGroup", subsystem)
    subsystem_grp.Label = subsystem
    for step, vv in v.items():
        step_name = get_layer_tail(step)
        step_grp = doc.addObject("App::DocumentObjectGroup", step_name)
        step_grp.Label = step_name
        subsystem_grp.addObject(step_grp)
        for partkind, vvv in vv.items():
            partkind_name = "%s::%s" % (step_name, partkind)
            partkind_grp = doc.addObject("App::DocumentObjectGroup",
                                         partkind_name)
            partkind_grp.Label = partkind_name
            step_grp.addObject(partkind_grp)

            filename = get_part_filename(subsystem, step_name, partkind)
            FreeCAD.Console.PrintMessage(filename + "\n")
            preimport_obj_count = len(doc.Objects)
            ImportGui.insert(os.path.join(step_dir, filename), doc.Name)
            # group new objects
            for i in range(preimport_obj_count, len(doc.Objects)):
                obj = doc.Objects[i]
                if obj.TypeId == 'Part::Feature':
                    partkind_grp.addObject(obj)

    FreeCAD.Gui.SendMsgToActiveView("ViewFit")
    if not subsystem == "1.frame-bottom":
        subsystem_grp.ViewObject.Visibility = False

    doc.recompute()
Example #24
0
def export(variant, fuse=False, overwrite=False, saveFCStd=False, exportDXF=False):
    partPrefix = variant[:-4]
    partPostfix = variant[5:]
    pinCount = int(variant[5:7])

    srcName = srcDir+variant+'.stp'
    if not os.path.isfile(srcName):
        FreeCAD.Console.PrintMessage('missing ' + variant + '.stp\n')
        return

    if not os.path.exists(dstDir):
        os.makedirs(dstDir)

    bodyCutName = 'body-' + partPrefix + '#'

    bodyCut = None
    try:
        tmpl = App.getDocument(libName)
    except:
        tmpl = App.openDocument(tmplDir+libName+'.FCStd')
    for obj in tmpl.Objects:
        if obj.Label.startswith(bodyCutName):
            bodyCut = obj
            break

    if bodyCut == None:
        FreeCAD.Console.PrintMessage('missing template for ' + partPrefix + '\n')
        return

    FreeCAD.Console.PrintMessage('cehcking  ' + variant + '\n')

    names = [x for x in obj.Label.split('#')]
    pitch = float(names[2])
    dstName = dstDir+names[3]\
            .replace('%e',partPrefix)\
            .replace('%o',partPostfix)\
            .replace('%c','%02d'%pinCount)\
            .replace('%p','%.2f'%pitch)

    settings = { 'align':'' }

    if len(names) > 4:
        for i in range(4,len(names)):
            if names[i] == '': continue
            option = [x for x in names[i].split(':')]
            if not option[0] in settings:
                FreeCAD.Console.PrintWarning('unknown setting : ' + option[0] + '\n')
            else:
                settings[option[0]] = option[1]

    if os.path.isfile(dstName+'.stp'):
        if not overwrite:
            FreeCAD.Console.PrintMessage(dstName + ' already exists, skip!\n')
            return

    FreeCAD.Console.PrintMessage('exporting ' + dstName + '\n')

    newDoc = App.newDocument(variant+'_'+str(random.randrange(10000,99999)))
    guiDoc = Gui.getDocument(newDoc.Name)

    bodyCut = newDoc.copyObject(bodyCut,True)
    FreeCAD.Console.PrintMessage(bodyCut.Name +  '\n')
    guiDoc.getObject(bodyCut.Name).Visibility = False;

    ImportGui.insert(srcName,newDoc.Name)

    objs = newDoc.getObjectsByLabel(bodyName)
    if not objs:
        FreeCAD.Console.PrintMessage('missing body for ' + partPrefix + '\n')
        return
    part = objs[0]
    guiDoc.getObject(part.Name).Visibility = False;

    objs = newDoc.getObjectsByLabel(fpName)
    if not objs:
        FreeCAD.Console.PrintMessage('missing footprint for ' + partPrefix + '\n')
        return
    footprint = objs[0]

    # NOTE!!! If we don't use Placement.copy here, we will be getting a surprise
    # from FreeCAD. Even if we reset the bodyCut.Placement below, whenever we change
    # the non-copied placement, bodyCut.Placement will get an update, too! Spooky!!
    # There seems to be some dangling internal reference bug here.
    placement = bodyCut.Placement.copy()
    bodyCut.Placement = App.Placement()

    offset = (pinCount-2)*pitch/2

    if settings['align'] == 'pin':
        placement.Base.x += offset

    footprint.Placement = placement.copy()

    for obj in bodyCut.Shapes:
        # any better way to id array object?
        if 'ArrayType' in obj.PropertiesList:
            # TODO, we assum interval x sets the pitch, add more check later
            obj.IntervalX.x = pitch
            obj.NumberX = pinCount
            obj.Placement.Base.x -= offset
        else:
            for sobj in obj.Shapes:
                if sobj.TypeId == 'Part::Mirroring':
                    sobj.Source.Placement.Base.x -= offset

    newDoc.recompute()

    colors = []
    objs = []
    shapes = []

    def make_part(obj,isCut):
        names = [x for x in obj.Label.split('#')]
        newObj = newDoc.addObject("Part::Feature", names[0])
        if isCut:
            newObj.Shape = part.Shape.cut(obj.Shape).removeSplitter()
        else:
            newObj.Shape = part.Shape.common(obj.Shape).removeSplitter()
        color = names[1]
        if not color in shaderColors.named_colors:
            FreeCAD.Console.PrintWarning('unknown color : ' + color + '\n')
            color = None
        else:
            newObj.ViewObject.ShapeColor = shaderColors.named_colors[color].getDiffuseFloat()
            if not color in colors:
                colors.append(color)
        newObj.Placement = placement.copy()
        shapes.append(newObj)
        objs.append(expVRML.exportObject(freecad_object = newObj, shape_color=color, face_colors=None))

    make_part(bodyCut,True)

    for obj in bodyCut.Shapes:
        make_part(obj,False)

    if fuse:
        newObj = newDoc.addObject("Part::MultiFuse", 'part')
        newObj.Shapes = shapes
        shapes = [newObj]

    newDoc.recompute()

    ImportGui.export(shapes,dstName+'.stp')

    if exportDXF:
        shapes = []
        shapes.append(footprint)
        importDXF.export(shapes,dstName+'.dxf')

    scale=1/2.54
    colored_meshes = expVRML.getColoredMesh(Gui, objs , scale)
    expVRML.writeVRMLFile(colored_meshes, dstName+'.wrl', colors)

    if saveFCStd:
        newDoc.saveAs(dstName+'.FCStd')
    App.closeDocument(newDoc.Name)
Example #25
0
def importPart( filename, partName=None, doc_assembly=None ):
    if doc_assembly == None:
        doc_assembly = FreeCAD.ActiveDocument
    updateExistingPart = partName <> None
    if updateExistingPart:
        FreeCAD.Console.PrintMessage("updating part %s from %s\n" % (partName,filename))
    else:
        FreeCAD.Console.PrintMessage("importing part from %s\n" % filename)
    doc_already_open = filename in [ d.FileName for d in FreeCAD.listDocuments().values() ]
    debugPrint(4, "%s open already %s" % (filename, doc_already_open))
    if doc_already_open:
        doc = [ d for d in FreeCAD.listDocuments().values() if d.FileName == filename][0]
    else:
        if filename.lower().endswith('.fcstd'):
            debugPrint(4, '  opening %s' % filename)
            doc = FreeCAD.openDocument(filename)
            debugPrint(4, '  succesfully opened %s' % filename)
        else: #trying shaping import http://forum.freecadweb.org/viewtopic.php?f=22&t=12434&p=99772#p99772x
            import ImportGui
            doc = FreeCAD.newDocument( os.path.basename(filename) )
            shapeobj=ImportGui.insert(filename,doc.Name)

    visibleObjects = [ obj for obj in doc.Objects
                       if hasattr(obj,'ViewObject') and obj.ViewObject.isVisible()
                       and hasattr(obj,'Shape') and len(obj.Shape.Faces) > 0] # len(obj.Shape.Faces) > 0 to avoid sketches

    debugPrint(3, '%s objects %s' % (doc.Name, doc.Objects))
    if any([ 'importPart' in obj.Content for obj in doc.Objects]) and not len(visibleObjects) == 1:
        subAssemblyImport = True
        debugPrint(2, 'Importing subassembly from %s' % filename)
        tempPartName = 'import_temporary_part'
        obj_to_copy = doc_assembly.addObject("Part::FeaturePython",tempPartName)
        obj_to_copy.Proxy = Proxy_muxAssemblyObj()
        obj_to_copy.ViewObject.Proxy = ImportedPartViewProviderProxy()
        obj_to_copy.Shape =  muxObjects(doc)
        if (not updateExistingPart) or \
                (updateExistingPart and getattr( doc_assembly.getObject(partName),'updateColors',True)):
            muxMapColors(doc, obj_to_copy)
    else:
        subAssemblyImport = False
        if len(visibleObjects) <> 1:
            if not updateExistingPart:
                msg = "A part can only be imported from a FreeCAD document with exactly one visible part. Aborting operation"
                QtGui.QMessageBox.information(  QtGui.qApp.activeWindow(), "Value Error", msg )
            else:
                msg = "Error updating part from %s: A part can only be imported from a FreeCAD document with exactly one visible part. Aborting update of %s" % (partName, filename)
            QtGui.QMessageBox.information(  QtGui.qApp.activeWindow(), "Value Error", msg )
        #QtGui.QMessageBox.warning( QtGui.qApp.activeWindow(), "Value Error!", msg, QtGui.QMessageBox.StandardButton.Ok )
            return
        obj_to_copy  = visibleObjects[0]

    if updateExistingPart:
        obj = doc_assembly.getObject(partName)
        prevPlacement = obj.Placement
        if not hasattr(obj, 'updateColors'):
            obj.addProperty("App::PropertyBool","updateColors","importPart").updateColors = True
        importUpdateConstraintSubobjects( doc_assembly, obj, obj_to_copy )
    else:
        partName = findUnusedObjectName( doc.Label + '_', document=doc_assembly )
        try:
            obj = doc_assembly.addObject("Part::FeaturePython",partName)
        except UnicodeEncodeError:
            safeName = findUnusedObjectName('import_', document=doc_assembly)
            obj = doc_assembly.addObject("Part::FeaturePython", safeName)
            obj.Label = findUnusedLabel( doc.Label + '_', document=doc_assembly )
        obj.addProperty("App::PropertyFile",    "sourceFile",    "importPart").sourceFile = filename
        obj.addProperty("App::PropertyFloat", "timeLastImport","importPart")
        obj.setEditorMode("timeLastImport",1)
        obj.addProperty("App::PropertyBool","fixedPosition","importPart")
        obj.fixedPosition = not any([i.fixedPosition for i in doc_assembly.Objects if hasattr(i, 'fixedPosition') ])
        obj.addProperty("App::PropertyBool","updateColors","importPart").updateColors = True
    obj.Shape = obj_to_copy.Shape.copy()
    if updateExistingPart:
        obj.Placement = prevPlacement
    else:
        for p in obj_to_copy.ViewObject.PropertiesList: #assuming that the user may change the appearance of parts differently depending on the assembly.
            if hasattr(obj.ViewObject, p) and p not in ['DiffuseColor']:
                setattr(obj.ViewObject, p, getattr(obj_to_copy.ViewObject, p))
        obj.ViewObject.Proxy = ImportedPartViewProviderProxy()
    if getattr(obj,'updateColors',True):
        obj.ViewObject.DiffuseColor = copy.copy( obj_to_copy.ViewObject.DiffuseColor )
    obj.Proxy = Proxy_importPart()
    obj.timeLastImport = os.path.getmtime( filename )
    #clean up
    if subAssemblyImport:
        doc_assembly.removeObject(tempPartName)
    if not doc_already_open: #then close again
        FreeCAD.closeDocument(doc.Name)
        FreeCAD.setActiveDocument(doc_assembly.Name)
        FreeCAD.ActiveDocument = doc_assembly
    return obj
Example #26
0
    subsystem_grp = doc.addObject("App::DocumentObjectGroup", subsystem)
    subsystem_grp.Label = subsystem
    for step,vv in v.items():
        step_name = get_layer_tail(step)
        step_grp = doc.addObject("App::DocumentObjectGroup", step_name)
        step_grp.Label = step_name
        subsystem_grp.addObject(step_grp)
        for partkind,vvv in vv.items():
            partkind_name = "%s::%s" % (step_name,partkind)
            partkind_grp = doc.addObject("App::DocumentObjectGroup", partkind_name)
            partkind_grp.Label = partkind_name
            step_grp.addObject(partkind_grp)

            filename = get_part_filename(subsystem, step_name, partkind)
            FreeCAD.Console.PrintMessage(filename + "\n")
            preimport_obj_count = len(doc.Objects)
            ImportGui.insert(os.path.join(step_dir, filename), doc.Name)
            # group new objects
            for i in range(preimport_obj_count, len(doc.Objects)):
                obj = doc.Objects[i]
                if obj.TypeId == 'Part::Feature':
                    partkind_grp.addObject(obj)


    FreeCAD.Gui.SendMsgToActiveView("ViewFit")
    if not subsystem == "1.frame-bottom":
        subsystem_grp.ViewObject.Visibility=False

    doc.recompute()

Example #27
0
    def Activated(self):
        FreeCAD.Console.PrintWarning('opening ' + self.exFile + "\r\n")
        import os, sys
        # So we can open the "Open File" dialog
        mw = FreeCADGui.getMainWindow()

        # Start off defaulting to the Examples directory
        ksu_base_path = ksu_locator.module_path()
        exs_dir_path = os.path.join(ksu_base_path, 'demo')
        abs_ksu_path = ksu_locator.abs_module_path()
        # Append this script's directory to sys.path
        sys.path.append(os.path.dirname(exs_dir_path))

        # We've created a library that FreeCAD can use as well to open CQ files
        fnameDemo = (os.path.join(exs_dir_path, self.exFile))
        demo_model = 'dpak-to252.step'
        stepfname = (os.path.join(exs_dir_path, 'shapes', demo_model))
        ext = os.path.splitext(os.path.basename(fnameDemo))[1]
        nme = os.path.splitext(os.path.basename(fnameDemo))[0]
        FC_majorV = int(FreeCAD.Version()[0])
        FC_minorV = int(FreeCAD.Version()[1])

        if ext.lower() == ".pdf":
            import subprocess, sys
            if sys.platform == "linux" or sys.platform == "linux2":
                # linux
                subprocess.call(["xdg-open", fnameDemo])
            if sys.platform == "darwin":
                # osx
                cmd_open = 'open ' + fnameDemo
                os.system(cmd_open)  #win, osx
            else:
                # win
                subprocess.Popen([fnameDemo], shell=True)
        elif ext.lower() == ".kicad_pcb" or ext.lower() == ".kicad_mod":
            #FreeCAD.Console.PrintMessage(abs_ksu_path + "\r\n")
            #FreeCAD.Console.PrintMessage(stepfname + "\r\n")
            #FreeCAD.Console.PrintMessage(exs_dir_path + "\r\n")
            import kicadStepUptools
            #    reload( kicadStepUptools )
            if reload_Gui:
                reload_lib(kicadStepUptools)
            from kicadStepUptools import open, create_axis  #onLoadBoard, onLoadFootprint
            if ext.lower() == ".kicad_mod":
                dname = (demo_model).split('.')[0].replace('-', '_')
                doc = FreeCAD.newDocument(dname)
                dname = doc.Name
                #print dname
                FreeCAD.setActiveDocument(dname)
                FreeCAD.ActiveDocument = FreeCAD.getDocument(dname)
                FreeCADGui.ActiveDocument = FreeCADGui.getDocument(dname)
                #doc=FreeCAD.newDocument((demo_model).split('.')[0].replace('-','_'))
                #FreeCAD.setActiveDocument(doc)
                import ImportGui
                ImportGui.insert(stepfname, doc.Name)
                FreeCADGui.activeDocument().activeView().viewAxonometric()
                open(fnameDemo)
                if FreeCAD.ActiveDocument.getObject("axis") is None:
                    create_axis()
            else:
                open(fnameDemo)
            #docL=FreeCAD.ActiveDocument.Label
        elif ext.lower() == ".fcstd":
            if FC_majorV == 0 and FC_minorV < 17:
                fnameDemo = fnameDemo.rstrip(ext) + '-fc16' + ext
                FreeCAD.Console.PrintWarning('opening ' + fnameDemo + "\r\n")
            FreeCAD.open(fnameDemo)
            FreeCADGui.activeDocument().activeView().viewAxonometric()
        elif ext.lower() == ".step":
            if FC_majorV == 0 and FC_minorV < 17:
                fnameDemo = fnameDemo.rstrip(ext) + '-fc16' + ext
                FreeCAD.Console.PrintWarning('opening ' + fnameDemo + "\r\n")
            import ImportGui
            ImportGui.open(fnameDemo)
            FreeCADGui.activeDocument().activeView().viewAxonometric()
            FreeCADGui.SendMsgToActiveView("ViewFit")
Example #28
0
def importPart( filename, partName=None, doc_assembly=None ):
    if doc_assembly == None:
        doc_assembly = FreeCAD.ActiveDocument
    updateExistingPart = partName != None
    if updateExistingPart:
        FreeCAD.Console.PrintMessage("updating part %s from %s\n" % (partName,filename))
    else:
        FreeCAD.Console.PrintMessage("importing part from %s\n" % filename)
    doc_already_open = filename in [ d.FileName for d in FreeCAD.listDocuments().values() ]
    debugPrint(4, "%s open already %s" % (filename, doc_already_open))
    if doc_already_open:
        doc = [ d for d in FreeCAD.listDocuments().values() if d.FileName == filename][0]
        close_doc = False
    else:
        if filename.lower().endswith('.fcstd'):
            doc = Fcstd_File_Parser( filename )
            close_doc = False
        else: #trying shaping import http://forum.freecadweb.org/viewtopic.php?f=22&t=12434&p=99772#p99772x
            import ImportGui
            doc = FreeCAD.newDocument( os.path.basename(filename) )
            shapeobj = ImportGui.insert(filename,doc.Name)
            close_doc = True

    visibleObjects = [ obj for obj in doc.Objects
                       if hasattr(obj,'ViewObject') and obj.ViewObject.isVisible()
                       and hasattr(obj,'Shape') and len(obj.Shape.Faces) > 0 and 'Body' not in obj.Name] # len(obj.Shape.Faces) > 0 to avoid sketches, skip Body

    debugPrint(3, '%s objects %s' % (doc.Name, doc.Objects))
    if any([ 'importPart' in obj.Content for obj in doc.Objects]) and not len(visibleObjects) == 1:
        subAssemblyImport = True
        debugPrint(2, 'Importing subassembly from %s' % filename)
        tempPartName = 'import_temporary_part'
        obj_to_copy = doc_assembly.addObject("Part::FeaturePython",tempPartName)
        obj_to_copy.Proxy = Proxy_muxAssemblyObj()
        obj_to_copy.ViewObject.Proxy = ImportedPartViewProviderProxy()
        obj_to_copy.Shape =  muxObjects(doc)
        if (not updateExistingPart) or \
                (updateExistingPart and getattr( doc_assembly.getObject(partName),'updateColors',True)):
            muxMapColors(doc, obj_to_copy)
    else:
        subAssemblyImport = False
        if len(visibleObjects) != 1:
            if not updateExistingPart:
                msg = "A part can only be imported from a FreeCAD document with exactly one visible part. Aborting operation"
                QtGui.QMessageBox.information(  QtGui.QApplication.activeWindow(), "Value Error", msg )
            else:
                msg = "Error updating part from %s: A part can only be imported from a FreeCAD document with exactly one visible part. Aborting update of %s" % (partName, filename)
            QtGui.QMessageBox.information(  QtGui.QApplication.activeWindow(), "Value Error", msg )
        #QtGui.QMessageBox.warning( QtGui.QApplication.activeWindow(), "Value Error!", msg, QtGui.QMessageBox.StandardButton.Ok )
            return
        obj_to_copy  = visibleObjects[0]

    if updateExistingPart:
        obj = doc_assembly.getObject(partName)
        prevPlacement = obj.Placement
        if not hasattr(obj, 'updateColors'):
            obj.addProperty("App::PropertyBool","updateColors","importPart").updateColors = True
        importUpdateConstraintSubobjects( doc_assembly, obj, obj_to_copy )
    else:
        partName = findUnusedObjectName( doc.Label + '_', document=doc_assembly )
        try:
            obj = doc_assembly.addObject("Part::FeaturePython",partName)
        except UnicodeEncodeError:
            safeName = findUnusedObjectName('import_', document=doc_assembly)
            obj = doc_assembly.addObject("Part::FeaturePython", safeName)
            obj.Label = findUnusedLabel( doc.Label + '_', document=doc_assembly )
        obj.addProperty("App::PropertyFile",    "sourceFile",    "importPart").sourceFile = filename
        obj.addProperty("App::PropertyFloat", "timeLastImport","importPart")
        obj.setEditorMode("timeLastImport",1)
        obj.addProperty("App::PropertyBool","fixedPosition","importPart")
        obj.fixedPosition = not any([i.fixedPosition for i in doc_assembly.Objects if hasattr(i, 'fixedPosition') ])
        obj.addProperty("App::PropertyBool","updateColors","importPart").updateColors = True
    obj.Shape = obj_to_copy.Shape.copy()
    if updateExistingPart:
        obj.Placement = prevPlacement
    else:
        # for Fcstd_File_Parser not all properties are implemented...
        for p in obj_to_copy.ViewObject.PropertiesList: #assuming that the user may change the appearance of parts differently depending on the assembly.
            if hasattr(obj.ViewObject, p) and p not in ['DiffuseColor']:
                try:
                    setattr(obj.ViewObject, p, getattr(obj_to_copy.ViewObject, p))
                except Exception as msg:
                    FreeCAD.Console.PrintWarning('Unable to setattr(obj.ViewObject, %s, %s)\n' % (p, getattr(obj_to_copy.ViewObject, p) ))
        obj.ViewObject.Proxy = ImportedPartViewProviderProxy()
    if getattr(obj,'updateColors',True) and hasattr( obj_to_copy.ViewObject, 'DiffuseColor'):
        obj.ViewObject.DiffuseColor = copy.copy( obj_to_copy.ViewObject.DiffuseColor )
        #obj.ViewObject.Transparency = copy.copy( obj_to_copy.ViewObject.Transparency )   # .Transparency property
        tsp = copy.copy( obj_to_copy.ViewObject.Transparency )   #  .Transparency workaround for FC 0.17 @ Nov 2016
        if tsp < 100 and tsp!=0:
            obj.ViewObject.Transparency = tsp+1
        if tsp == 100:
            obj.ViewObject.Transparency = tsp-1
        obj.ViewObject.Transparency = tsp   # .Transparency workaround end
    obj.Proxy = Proxy_importPart()
    obj.timeLastImport = os.path.getmtime( filename )
    #clean up
    if subAssemblyImport:
        doc_assembly.removeObject(tempPartName)
    if close_doc: 
        FreeCAD.closeDocument( doc.Name )
        FreeCAD.setActiveDocument( doc_assembly.Name )
        FreeCAD.ActiveDocument = doc_assembly
    return obj
Example #29
0
def export(variant, overwrite=False, saveFCStd=False, exportDXF=False):
    partPrefix = variant[:-4]
    partPostfix = variant[5:]
    pinCount = int(variant[5:7])

    srcName = srcDir+variant+'.stp'
    if not os.path.isfile(srcName):
        FreeCAD.Console.PrintMessage('missing ' + variant + '.stp\n')
        return

    if not os.path.exists(dstDir):
        os.makedirs(dstDir)

    bodyCutName = 'body-' + partPrefix + '#'

    bodyCut = None
    try:
        tmpl = App.getDocument(tmplName)
    except:
        tmpl = App.openDocument(tmplName+'.FCStd')
    for obj in tmpl.Objects:
        if obj.Label.startswith(bodyCutName):
            bodyCut = obj
            break

    if bodyCut == None:
        FreeCAD.Console.PrintMessage('missing template for ' + partPrefix + '\n')
        return

    FreeCAD.Console.PrintMessage('cehcking  ' + variant + '\n')

    names = [x for x in obj.Label.split('#')]
    pitch = float(names[2])
    dstName = dstDir+names[3]\
            .replace('%e',partPrefix)\
            .replace('%o',partPostfix)\
            .replace('%c','%02d'%pinCount)\
            .replace('%p','%.2f'%pitch)


    if os.path.isfile(dstName+'.stp'):
        if not overwrite:
            FreeCAD.Console.PrintMessage(dstName + ' already exists, skip!\n')
            return

    FreeCAD.Console.PrintMessage('exporting ' + dstName + '\n')

    newDoc = App.newDocument(variant+'_'+str(random.randrange(10000,99999)))
    guiDoc = Gui.getDocument(newDoc.Name)

    bodyCut = newDoc.copyObject(bodyCut,True)
    guiDoc.getObject(bodyCut.Name).Visibility = False;

    ImportGui.insert(srcName,newDoc.Name)

    objs = newDoc.getObjectsByLabel(bodyName)
    if not objs:
        FreeCAD.Console.PrintMessage('missing body for ' + partPrefix + '\n')
        return
    part = objs[0]
    guiDoc.getObject(part.Name).Visibility = False;

    objs = newDoc.getObjectsByLabel(fpName)
    if not objs:
        FreeCAD.Console.PrintMessage('missing footprint for ' + partPrefix + '\n')
        return
    footprint = objs[0]

    placement = bodyCut.Placement
    bodyCut.Placement = App.Placement()

    for obj in bodyCut.Shapes:
        # any better way to id array object?
        if 'ArrayType' in obj.PropertiesList:
            # TODO, we assum interval x sets the pitch, add more check later
            obj.IntervalX.x = pitch
            obj.NumberX = pinCount
            obj.Placement.Base.x -= (pinCount-2)*pitch/2
        else:
            for sobj in obj.Shapes:
                if sobj.TypeId == 'Part::Mirroring':
                    sobj.Source.Placement.Base.x -= (pinCount-2)*pitch/2

    newDoc.recompute()

    colors = []
    objs = []
    shapes = []

    def make_part(obj,isCut):
        names = [x for x in obj.Label.split('#')]
        newObj = newDoc.addObject("Part::Feature", names[0])
        if isCut:
            newObj.Shape = part.Shape.cut(obj.Shape).removeSplitter()
        else:
            newObj.Shape = part.Shape.common(obj.Shape).removeSplitter()
        color = names[1]
        if not color in shaderColors.named_colors:
            FreeCAD.Console.PrintWarning('unknown color : ' + color + '\n')
            color = None
        else:
            newObj.ViewObject.ShapeColor = shaderColors.named_colors[color].getDiffuseFloat()
            if not color in colors:
                colors.append(color)
        newObj.Placement = placement
        shapes.append(newObj)
        objs.append(expVRML.exportObject(freecad_object = newObj, shape_color=color, face_colors=None))

    make_part(bodyCut,True)

    for obj in bodyCut.Shapes:
        make_part(obj,False)

    newDoc.recompute()

    ImportGui.export(shapes,dstName+'.stp')

    if exportDXF:
        shapes = []
        shapes.append(footprint)
        importDXF.export(shapes,dstName+'.dxf')

    scale=1/2.54
    colored_meshes = expVRML.getColoredMesh(Gui, objs , scale)
    expVRML.writeVRMLFile(colored_meshes, dstName+'.wrl', colors)

    if saveFCStd:
        newDoc.saveAs(dstName+'.FCStd')
    App.closeDocument(newDoc.Name)
                        HDLR_stepfile_w = open(PATH_toStepFiles + FNME_stepfile, 'w') # open
                    except:
                        print "broken_3"
                    else:
                        # overwrite with new preamble
                        for line in LIST_PMBL:
                            HDLR_stepfile_w.write(line + "\n")
                        # add old data section
                        for line in PMBL_stepfile[(DICT_positions["A"]-1):]:
                            HDLR_stepfile_w.write(line.strip() + "\n")
                        HDLR_stepfile_w.close()

                    # load STEP model, manipulate and save as VRML
                    FreeCAD.newDocument("Unnamed")
                    FreeCAD.setActiveDocument("Unnamed")
                    ImportGui.insert(PATH_toStepFiles + FNME_stepfile,"Unnamed")
                    FNME_vrmlfile = FNME_stepfile[:-4] + ".wrl"
                    # change display mode and scale down
                    for part in FreeCAD.ActiveDocument.Objects:
                        part.ViewObject.DisplayMode = 1 #Shaded
                        Draft.scale(part,delta=App.Vector(0.3937,0.3937,0.3937),center=App.Vector(0,0,0),legacy=True)
                    if FLAG_makeTransparent: # if transparency is needed
                        
#                        from PySide import QtGui
#                        QtGui.QInputDialog.getText(None, "Get text", "Input:")[0]
                        pass
                    __objs__=[] # select all parts (again)
                    for part in FreeCAD.ActiveDocument.Objects:                    
                        __objs__.append(part)
                    FreeCADGui.export(__objs__,(PATH_toVrmlFiles + FNME_vrmlfile))
                    del __objs__
Example #31
0
import sys
sys.path.append("C:\\Program Files\\FreeCAD 0.19\\bin")

import FreeCAD
import FreeCADGui
FreeCADGui.setupWithoutGUI()
import Part
import ImportGui

print (FreeCAD.listDocuments())

test = FreeCAD.newDocument("testDoc")

ImportGui.insert("C:\\temp\\JMA(KAE-10D).STEP",test.Name)
ImportGui.insert("C:\\temp\\stift.STEP",test.Name)

doc = FreeCAD.ActiveDocument
objs = FreeCAD.ActiveDocument.Objects

print("objects before cutting")
print("----------------------")
for obj in objs:
    a = obj.Name
    b = obj.Label
    try:
        c = obj.LabelText
        print(a +" "+ (b) +" "+ (c) + "\n")
    except:
        print((a) +" "+ (b) + "\n")
print("----------------------")
Example #32
0
    def Activated(self):
        a2plib.setAutoSolve(True)  # makes no sense without autosolve = ON
        doc = FreeCAD.activeDocument()
        fileName = doc.FileName
        workingDir, basicFileName = os.path.split(fileName)

        selectedFiles = []
        partial = False
        selection = [
            s for s in FreeCADGui.Selection.getSelection()
            if s.Document == FreeCAD.ActiveDocument and (
                a2plib.isA2pPart(s) or a2plib.isA2pSketch(s))
        ]
        if selection and len(selection) > 0:
            flags = QtGui.QMessageBox.StandardButton.Yes | QtGui.QMessageBox.StandardButton.No
            msg = u"Do you want to update only the selected parts?"
            response = QtGui.QMessageBox.information(
                QtGui.QApplication.activeWindow(), u"RECURSIVE UPDATE", msg,
                flags)
            if response == QtGui.QMessageBox.Yes:
                for s in selection:
                    fDir, fName = os.path.split(s.sourceFile)
                    selectedFiles.append(fName)
                    partial = True

        filesToUpdate = []
        subAsmNeedsUpdate, filesToUpdate = createUpdateFileList(
            fileName, workingDir, filesToUpdate, True, selectedFiles)

        for f in filesToUpdate:
            #-------------------------------------------
            # update necessary documents
            #-------------------------------------------

            # look only for filenames, not paths, as there are problems on WIN10 (Address-translation??)
            importDoc = None
            importDocIsOpen = False
            requestedFile = os.path.split(f)[1]
            for d in FreeCAD.listDocuments().values():
                recentFile = os.path.split(d.FileName)[1]
                if requestedFile == recentFile:
                    importDoc = d  # file is already open...
                    importDocIsOpen = True
                    break

            if not importDocIsOpen:
                if f.lower().endswith('.fcstd'):
                    importDoc = FreeCAD.openDocument(f)
                elif f.lower().endswith('.stp') or f.lower().endswith('.step'):
                    import ImportGui
                    fname = os.path.splitext(os.path.basename(f))[0]
                    FreeCAD.newDocument(fname)
                    newname = FreeCAD.ActiveDocument.Name
                    FreeCAD.setActiveDocument(newname)
                    ImportGui.insert(filename, newname)
                    importDoc = FreeCAD.ActiveDocument
                else:
                    msg = "A part can only be imported from a FreeCAD '*.fcstd' file"
                    QtGui.QMessageBox.information(
                        QtGui.QApplication.activeWindow(), "Value Error", msg)
                    return

            if importDoc == doc and partial == True:
                updateImportedParts(importDoc, True)
            else:
                updateImportedParts(importDoc)

            FreeCADGui.updateGui()
            importDoc.save()
            print(u"==== Assembly '{}' has been updated! =====".format(
                importDoc.FileName))
            if importDoc != doc:
                FreeCAD.closeDocument(importDoc.Name)
Example #33
0
class partsManaging(mathFunctions):
    
    def __init__(self):
        self.objColors = {}
        
        # allSocked - definicja zachowania przy dodawaniu podstawki dla wszystkich obeiktow
        #   -1 - brak podstawek
        #    0 - zapytaj o dodanie podstawki (def)
        #    1 - dodaj podstawki dla wszystkich obiektow
        self.allSocked = 0
    
    def adjustRotation(self, angle):
        if angle > 360 or angle < 360:  # max = 360deg; min= -360deg
            angle = angle % 360
        
        return angle
        
    def updateView(self):
        FreeCADGui.ActiveDocument.ActiveView.viewAxometric()
        FreeCADGui.ActiveDocument.ActiveView.fitAll()
        
    def getPartShape(self, filePath, step_model, koloroweElemnty):
        #if not partExistPath(filePath)[0]:
            #return step_model
        
        if filePath in self.objColors:
            step_model.Shape = self.objColors[filePath]['shape']
            if koloroweElemnty:
                step_model.ViewObject.DiffuseColor = self.objColors[filePath]['col']
            return step_model
        else:
            self.objColors[filePath] = {}
        
        #active = FreeCAD.ActiveDocument.Label
        
        # colFile
        colFile = os.path.join(os.path.dirname(filePath), os.path.splitext(os.path.basename(filePath))[0] + '.col')
        try:
            if os.path.exists(colFile):
                colFileData = __builtin__.open(colFile, "r").readlines()
                header = colFileData[0].strip().split("|")
                
                if len(header) >= 2 and header[0] == "2" and str(os.path.getmtime(filePath)) == header[1]:  # col file version
                    shape = Part.Shape()
                    shape.importBrepFromString("".join(colFileData[2:]))
                    
                    step_model.Shape = shape
                    if koloroweElemnty:
                        step_model.ViewObject.DiffuseColor = eval(colFileData[1].strip())
                    
                    self.objColors[filePath]['shape'] = shape
                    self.objColors[filePath]['col'] = eval(colFileData[1].strip())
                    
                    if len(colFileData[2:]) > 20:
                        return step_model
        except Exception, e:
            FreeCAD.Console.PrintWarning("{0} \n".format(e))
        ##
        colFileData = __builtin__.open(colFile, "w")
        colFileData.write("2|{0}\n".format(os.path.getmtime(filePath)))  # wersja|data
        
        FreeCAD.newDocument('importingPartsPCB')
        #FreeCAD.setActiveDocument('importingPartsPCB')
        FreeCAD.ActiveDocument = FreeCAD.getDocument('importingPartsPCB')
        FreeCADGui.ActiveDocument = FreeCADGui.getDocument('importingPartsPCB')
        ImportGui.insert(u"{0}".format(filePath), "importingPartsPCB")
        
        fuse = []
        for i in FreeCAD.ActiveDocument.Objects:
            if i.isDerivedFrom("Part::Feature") and i.ViewObject.Visibility and len(i.Shape.Solids):
                fuse.append(i)
        try:
            if len(fuse) == 1:
                shape = fuse[0].Shape
                col = fuse[0].ViewObject.DiffuseColor
            else:
                newPart = FreeCAD.ActiveDocument.addObject("Part::MultiFuse","Union").Shapes=fuse
                FreeCAD.ActiveDocument.recompute()
            
                shape = FreeCAD.ActiveDocument.getObject("Union").Shape
                col = FreeCAD.ActiveDocument.getObject("Union").ViewObject.DiffuseColor
        except Exception,e:
            FreeCAD.Console.PrintWarning("{0} \n".format(e))
Example #34
0
import FreeCAD
from xml.dom import minidom
import inspect
import ImportGui
import Mesh

App.newDocument("Unnamed1")
App.setActiveDocument("Unnamed1")
App.ActiveDocument = App.getDocument("Unnamed1")
Gui.ActiveDocument = Gui.getDocument("Unnamed1")

ImportGui.insert(u"C:/Users/isekaitenseiproject/Downloads/happymini_body.stp",
                 "Unnamed")
inspect.getmembers(FreeCAD.getDocument("Unnamed1"))
members = inspect.getmembers(FreeCAD.getDocument("Unnamed1"))

doc = minidom.parseString(members[3][1])
parts = doc.getElementsByTagName("Object")
__objs__ = []

for p in parts:
    __objs__.append(
        FreeCAD.getDocument("Unnamed1").getObject(p.attributes['name'].value))

Mesh.export(__obj__,
            u"C:/Users/isekaitenseiproject/Downloads/happymini-cad.obj")
del __obj__