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");
def createConstraintArea(obj, typeCA): try: if not FreeCAD.activeDocument() or getPCBheight()[0]: return # grp = createGroup_Areas() if obj.isDerivedFrom("Sketcher::SketchObject"): if not obj.Shape.isClosed(): FreeCAD.Console.PrintWarning("Sketcher is not closed!\n") return # obj.ViewObject.Visibility = False #layerName = PCBconstraintAreas[typeCA][0] layerColor = (PCBconstraintAreas[typeCA][3][0] / 255., PCBconstraintAreas[typeCA][3][1] / 255., PCBconstraintAreas[typeCA][3][2] / 255.) layerTransparent = PCBconstraintAreas[typeCA][2] typeL = PCBconstraintAreas[typeCA][1] #numLayer = 0 # a = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", typeCA + "_{0}".format(0)) constraintAreaObject(a, typeL) a.Base = obj viewProviderConstraintAreaObject(a.ViewObject) grp.addObject(a) FreeCADGui.activeDocument().getObject(a.Name).ShapeColor = layerColor FreeCADGui.activeDocument().getObject(a.Name).Transparency = layerTransparent FreeCADGui.activeDocument().getObject(a.Name).DisplayMode = 1 #grp.Proxy.Object.Group.append(a) #grp.Object.Group.append(a) return a except Exception ,e: FreeCAD.Console.PrintWarning("{0} \n".format(e))
def Activated(self): FreeCAD.Console.PrintMessage(self.exFile + "\r\n") #So we can open the "Open File" dialog mw = FreeCADGui.getMainWindow() #Start off defaulting to the Examples directory module_base_path = module_locator.module_path() exs_dir_path = os.path.join(module_base_path, 'Examples') #We need to close any file that's already open in the editor window CadQueryCloseScript().Activated() #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 ImportCQ.open(os.path.join(exs_dir_path, self.exFile)) docname = os.path.splitext(os.path.basename(self.exFile))[0] FreeCAD.newDocument(docname) #Execute the script CadQueryExecuteScript().Activated() #Get a nice view of our model FreeCADGui.activeDocument().activeView().viewAxometric() FreeCADGui.SendMsgToActiveView("ViewFit")
def generate(self): if self.base == None: FreeCAD.Console.PrintWarning("Mandatory field is empty!\n") elif not self.base.isDerivedFrom("Sketcher::SketchObject"): FreeCAD.Console.PrintWarning("Wrong object!\n") # grp = createGroup_Glue() if self.side == 'TOP': typeL = PCBlayers["tGlue"][3] else: typeL = PCBlayers["bGlue"][3] # a = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "Glue_{0}".format(0)) PCBgluePath(a, typeL) a.Base = self.base if self.width == 0: a.Width = 1 else: a.Width = self.width a.Height = self.height a.Flat = self.flat viewProviderPCBgluePath(a.ViewObject) grp.addObject(a) FreeCADGui.activeDocument().getObject(a.Name).ShapeColor = self.color FreeCADGui.activeDocument().getObject(a.Name).Transparency = self.transparent # self.base.ViewObject.Visibility = False
def generatePCB(self, PCB, doc, groupBRD, gruboscPlytki): doc.addObject('Sketcher::SketchObject', 'PCB_Border') doc.PCB_Border.Placement = FreeCAD.Placement(FreeCAD.Vector(0.0, 0.0, 0.0), FreeCAD.Rotation(0.0, 0.0, 0.0, 1.0)) # for i in PCB[0]: if i[0] == 'Arc': # arc by 3 points x1 = i[1] y1 = i[2] x2 = i[3] y2 = i[4] [x3, y3] = self.arcMidPoint([x2, y2], [x1, y1], i[5]) arc = Part.Arc(FreeCAD.Vector(x1, y1, 0.0), FreeCAD.Vector(x3, y3, 0.0), FreeCAD.Vector(x2, y2, 0.0)) doc.PCB_Border.addGeometry(self.Draft2Sketch(arc, doc.PCB_Border)) elif i[0] == 'Arc_2': # arc by center / start angle / stop angle / radius doc.PCB_Border.addGeometry(Part.ArcOfCircle(Part.Circle(FreeCAD.Vector(i[1], i[2], 0), FreeCAD.Vector(0, 0, 1), i[3]), i[4], i[5])) elif i[0] == 'Circle': doc.PCB_Border.addGeometry(Part.Circle(FreeCAD.Vector(i[1], i[2]), FreeCAD.Vector(0, 0, 1), i[3])) elif i[0] == 'Line': doc.PCB_Border.addGeometry(Part.Line(FreeCAD.Vector(i[1], i[2], 0), FreeCAD.Vector(i[3], i[4], 0))) # #if PCB[1]: PCBboard = doc.addObject("Part::FeaturePython", "Board") PCBboardObject(PCBboard) PCBboard.Thickness = gruboscPlytki PCBboard.Border = doc.PCB_Border viewProviderPCBboardObject(PCBboard.ViewObject) groupBRD.addObject(doc.Board) FreeCADGui.activeDocument().getObject(PCBboard.Name).ShapeColor = PCBconf.PCB_COLOR FreeCADGui.activeDocument().PCB_Border.Visibility = False self.updateView()
def constraintAreaF(self, typeCA): ''' create constraint area ''' zaznaczoneObiekty = FreeCADGui.Selection.getSelection() if len(zaznaczoneObiekty) and getPCBheight()[0]: grp = createGroup_Areas() for i in zaznaczoneObiekty: if i.isDerivedFrom("Sketcher::SketchObject") and i.Shape.isClosed(): i.ViewObject.Visibility = False #layerName = PCBconstraintAreas[typeCA][0] layerColor = (PCBconstraintAreas[typeCA][3][0] / 255., PCBconstraintAreas[typeCA][3][1] / 255., PCBconstraintAreas[typeCA][3][2] / 255.) layerTransparent = PCBconstraintAreas[typeCA][2] typeL = PCBconstraintAreas[typeCA][1] #numLayer = 0 # a = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", typeCA + "_{0}".format(0)) constraintAreaObject(a, typeL) a.Base = i viewProviderConstraintAreaObject(a.ViewObject) grp.addObject(a) FreeCADGui.activeDocument().getObject(a.Name).ShapeColor = layerColor FreeCADGui.activeDocument().getObject(a.Name).Transparency = layerTransparent FreeCADGui.activeDocument().getObject(a.Name).DisplayMode = 1 #grp.Proxy.Object.Group.append(a) #grp.Object.Group.append(a) elif not pcb[0]: FreeCAD.Console.PrintWarning("No PCB found\n")
def MakeHeader(n, params): name = HeaderName(n,params) #having a period '.' character in the model name REALLY messes with things. docname = name.replace(".","") newdoc = FreeCAD.newDocument(docname) App.setActiveDocument(docname) Gui.ActiveDocument=Gui.getDocument(docname) pins = MakePinRow(n,params) #duplicate pin rows if params.rows > 1: for i in range(1,params.rows): pins = pins.union(MakePinRow(n,params).translate((0,i*params.p,0))) base = MakeBase(n,params) #assign some colors base_color = (50,50,50) pins_color = (225,175,0) show(base,base_color+(0,)) show(pins,pins_color+(0,)) doc = FreeCAD.ActiveDocument objs=GetListOfObjects(FreeCAD, doc) FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name, objs[1].Name) doc.Label=docname objs=GetListOfObjects(FreeCAD, doc) objs[0].Label=docname restore_Main_Tools() if (params.rot !=0): z_RotateObject(doc, params.rot) out_dir = "./generated_pinheaders/" doc.Label = docname #save the STEP file exportSTEP(doc, name, out_dir) #save the VRML file scale=0.3937001 exportVRML(doc,name,scale,out_dir) # Save the doc in Native FC format saveFCdoc(App, Gui, doc, name,out_dir) Gui.SendMsgToActiveView("ViewFit") Gui.activeDocument().activeView().viewAxometric() return 0
def make_3D_model(models_dir, model_class, modelID): LIST_license = ["",] CheckedmodelName = modelID.replace('.', '').replace('-', '_').replace('(', '').replace(')', '') Newdoc = App.newDocument(CheckedmodelName) App.setActiveDocument(CheckedmodelName) Gui.ActiveDocument=Gui.getDocument(CheckedmodelName) destination_dir = model_class.get_dest_3D_dir(modelID) material_substitutions = model_class.make_3D_model(modelID) modelName = model_class.get_model_name(modelID) doc = FreeCAD.ActiveDocument doc.Label = CheckedmodelName objs=GetListOfObjects(FreeCAD, doc) objs[0].Label = CheckedmodelName restore_Main_Tools() script_dir=os.path.dirname(os.path.realpath(__file__)) expVRML.say(models_dir) out_dir=models_dir+os.sep+destination_dir if not os.path.exists(out_dir): os.makedirs(out_dir) exportSTEP(doc, modelName, out_dir) if LIST_license[0]=="": LIST_license=Lic.LIST_int_license LIST_license.append("") Lic.addLicenseToStep(out_dir + os.sep, modelName+".step", LIST_license,\ STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licOrg, STR_licPreProc) # scale and export Vrml model scale=1/2.54 #exportVRML(doc,modelName,scale,out_dir) del objs objs=GetListOfObjects(FreeCAD, doc) expVRML.say("######################################################################") expVRML.say(objs) expVRML.say("######################################################################") export_objects, used_color_keys = expVRML.determineColors(Gui, objs, material_substitutions) export_file_name=out_dir+os.sep+modelName+'.wrl' colored_meshes = expVRML.getColoredMesh(Gui, export_objects , scale) #expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys)# , LIST_license expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys, LIST_license) #scale=0.3937001 #exportVRML(doc,modelName,scale,out_dir) # Save the doc in Native FC format saveFCdoc(App, Gui, doc, modelName,out_dir) #display BBox Gui.activateWorkbench("PartWorkbench") Gui.SendMsgToActiveView("ViewFit") Gui.activeDocument().activeView().viewAxometric()
def gen_house(self): le=float(self.root.ids['le'].text()) wi=float(self.root.ids['wi'].text()) hiall=float(self.root.ids['hiall'].text()) hi=float(self.root.ids['hi'].text()) midy=1-float(self.root.ids['midx'].value())/100 midx=float(self.root.ids['midy'].value())/100 wy=float(self.root.ids['wx'].value())/100 wx=float(self.root.ids['wy'].value())/100 s= gen_haus(le,wi,hiall,hi,90,midx,wx,midy,wy) s.ViewObject.ShapeColor=(1.0,0.0,0.0) FreeCADGui.activeDocument().activeView().viewAxonometric()
def process_emp_model(doc,filename): """process_emp(document, filename)-> adds idf/emp geometry from emp file""" global emn_version emn_version=3.0 placement=[] placement=[['Ref', '"Geometry"', '"PartNbr_Library_emp"', 0.0, 0.0, 0.0, 0.0, 'TOP', 'ECAD']] board_thickness=1.6 process_emp(doc,filename,placement,board_thickness) FreeCAD.ActiveDocument.getObject("EMP_Models").removeObjectsFromDocument() FreeCAD.ActiveDocument.removeObject("EMP_Models") FreeCADGui.ActiveDocument.ActiveObject.BoundingBox = True FreeCADGui.ActiveDocument.ActiveObject.Visibility=True FreeCADGui.SendMsgToActiveView("ViewFit") FreeCADGui.activeDocument().activeView().viewAxometric()
def CopyObj(obj, NMsuff = ""): name = obj.Name shape = obj.Shape newshape = shape.copy() t = obj.Type newobject = FreeCAD.ActiveDocument.addObject(t,name) for p in s.PropertiesList: newobject.getPropertyByName(p) = obj.getPropertyByName(p) newobject.Shape = newshape colr = FreeCADGui.activeDocument().getObject(obj.Name).ShapeColor FreeCADGui.activeDocument().getObject(newobject.Name).ShapeColor = colr #newobject.ShapeColor = sel.ShapeColor newobject.Label = obj.Label + NMsuff return newobject
def draw(self): try: Gui.getDocument('yRodR') Gui.getDocument('yRodR').resetEdit() App.getDocument('yRodR').recompute() App.closeDocument("yRodR") App.setActiveDocument("") App.ActiveDocument=None Gui.ActiveDocument=None except: pass #make document App.newDocument("yRodR") App.setActiveDocument("yRodR") App.ActiveDocument=App.getDocument("yRodR") Gui.ActiveDocument=Gui.getDocument("yRodR") #make sketch App.activeDocument().addObject('Sketcher::SketchObject','Sketch') App.activeDocument().Sketch.Placement = App.Placement(App.Vector(0.000000,0.000000,0.000000),App.Rotation(-0.707107,0.000000,0.000000,-0.707107)) Gui.activeDocument().activeView().setCamera('#Inventor V2.1 ascii \n OrthographicCamera {\n viewportMapping ADJUST_CAMERA\n position 87 0 0 \n orientation 0.57735026 0.57735026 0.57735026 2.0943952 \n nearDistance -112.887\n farDistance 287.28699\n aspectRatio 1\n focalDistance 87\n height 143.52005\n\n}') # Gui.activeDocument().setEdit('Sketch') App.ActiveDocument.Sketch.addGeometry(Part.Circle(App.Vector(0,0,0),App.Vector(0,0,1),gv.yRodDiaR/2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('Coincident',0,3,-1,1)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('Radius',0,gv.yRodDiaR/2)) App.ActiveDocument.recompute() # Gui.getDocument('yRodR').resetEdit() App.getDocument('yRodR').recompute() #Pad sketch App.activeDocument().addObject("PartDesign::Pad","Pad") App.activeDocument().Pad.Sketch = App.activeDocument().Sketch App.activeDocument().Pad.Length = 10.0 App.ActiveDocument.recompute() Gui.activeDocument().hide("Sketch") App.ActiveDocument.Pad.Length = gv.yRodLength App.ActiveDocument.Pad.Reversed = 0 App.ActiveDocument.Pad.Midplane = 0 App.ActiveDocument.Pad.Length2 = 100.000000 App.ActiveDocument.Pad.Type = 0 App.ActiveDocument.Pad.UpToFace = None App.ActiveDocument.recompute() # Gui.activeDocument().resetEdit() #set view as axiometric # Gui.activeDocument().activeView().viewAxometric()
def build_and_save(i): ModelName='pinstrip_p254_'+str(i)+'x1' Newdoc = FreeCAD.newDocument(ModelName) App.setActiveDocument(ModelName) Gui.ActiveDocument=Gui.getDocument(ModelName) FreeCAD.Console.PrintMessage('making all pin headers\r\n') case, pins = make_pinheader(i) color_attr=case_color+(0,) show(case, color_attr) #FreeCAD.Console.PrintMessage(pins_color) color_attr=pins_color+(0,) #FreeCAD.Console.PrintMessage(color_attr) show(pins, color_attr) doc = FreeCAD.ActiveDocument objs=GetListOfObjects(FreeCAD, doc) FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name, objs[1].Name) doc.Label=ModelName objs=GetListOfObjects(FreeCAD, doc) objs[0].Label=ModelName restore_Main_Tools() #rotate if required if (rotation!=0): z_RotateObject(doc, rotation) out_dir=destination_dir if not os.path.exists(out_dir): os.makedirs(out_dir) #out_dir="./generated_qfp/" # export STEP model exportSTEP(doc,ModelName,out_dir) # scale and export Vrml model scale=0.3937001 exportVRML(doc,ModelName,scale,out_dir) # Save the doc in Native FC format saveFCdoc(App, Gui, doc, ModelName,out_dir) #display BBox FreeCADGui.ActiveDocument.getObject("Part__Feature").BoundingBox = True #import ImportGui #ImportGui.insert(u"C:/Cad/Progetti_K/FreeCAD-models/scripts/3D-models/CadQuery/reference-block.step","mypin") Gui.SendMsgToActiveView("ViewFit") Gui.activeDocument().activeView().viewAxometric() return 0
def generateHoles(self, dane, doc, Hmin, Hmax): doc.addObject('Sketcher::SketchObject', 'PCB_Holes') doc.PCB_Holes.Placement = FreeCAD.Placement(FreeCAD.Vector(0.0, 0.0, 0.0), FreeCAD.Rotation(0.0, 0.0, 0.0, 1.0)) FreeCADGui.activeDocument().PCB_Holes.Visibility = False # for i in dane: x = float("%4.3f" % i[0]) y = float("%4.3f" % i[1]) r = float("%4.3f" % i[2]) if r == 0: continue if Hmin == 0 and Hmax == 0: doc.PCB_Holes.addGeometry(Part.Circle(FreeCAD.Vector(x, y, 0.), FreeCAD.Vector(0, 0, 1), r)) elif Hmin != 0 and Hmax == 0 and Hmin <= r * 2: doc.PCB_Holes.addGeometry(Part.Circle(FreeCAD.Vector(x, y, 0.), FreeCAD.Vector(0, 0, 1), r)) elif Hmax != 0 and Hmin == 0 and r * 2 <= Hmax: doc.PCB_Holes.addGeometry(Part.Circle(FreeCAD.Vector(x, y, 0.), FreeCAD.Vector(0, 0, 1), r)) elif Hmin <= r * 2 <= Hmax: doc.PCB_Holes.addGeometry(Part.Circle(FreeCAD.Vector(x, y, 0.), FreeCAD.Vector(0, 0, 1), r)) #### ##hole = [Part.Circle(FreeCAD.Vector(x, y), FreeCAD.Vector(0, 0, 1), r).toShape()] ##hole = Part.Wire(hole) ##hole = Part.Face(hole) #hole = [Part.Circle(FreeCAD.Vector(x, y, -1), FreeCAD.Vector(0, 0, 1), r).toShape()] #hole = Part.Wire(hole) #hole = Part.Face(hole).extrude(FreeCAD.Base.Vector(0, 0, 2)) #holeModel.append(hole) #holeModel = Part.makeCompound(holeModel) doc.Board.Holes = doc.PCB_Holes doc.recompute()
def Activated(self): view = FreeCADGui.activeDocument().activeView() #filename, filetype = QtGui.QFileDialog.getOpenFileName( # QtGui.qApp.activeWindow(), # "Select FreeCAD document to import part from", # "",# "" is the default, os.path.dirname(FreeCAD.ActiveDocument.FileName), # "FreeCAD Document (*.fcstd)" # ) dialog = QtGui.QFileDialog( QtGui.qApp.activeWindow(), "Select FreeCAD document to import part from" ) dialog.setNameFilter("Supported Formats (*.FCStd *.brep *.brp *.imp *.iges *.igs *.obj *.step *.stp);;All files (*.*)") if dialog.exec_(): filename = dialog.selectedFiles()[0] else: return importedObject = importPart( filename ) FreeCAD.ActiveDocument.recompute() if not importedObject.fixedPosition: #will be true for the first imported part PartMover( view, importedObject ) else: from PySide import QtCore self.timer = QtCore.QTimer() QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"), self.GuiViewFit) self.timer.start( 200 ) #0.2 seconds
def Activated(self): # Mouse events try: m_ev; except NameError: m_ev=FreeCADGui.activeDocument().activeView(); o1 = ViewObserver(m_ev); m_ev.addEventCallback("SoMouseButtonEvent",o1.logPosition);
def Activated(self): import FreeCADGui centerX = 20 centerY = 5 height = 15 import Base windowInfo = Base.__windowInfo__ if windowInfo!=None and len(windowInfo)==4: centerX = (windowInfo[0]+windowInfo[1])/2 centerY = (windowInfo[2]+windowInfo[3])/2 height = (windowInfo[1]-windowInfo[0])*0.75 print windowInfo print 'camera center : ( %f , %f )'% (centerX,centerY) camera = '#Inventor V2.1 ascii\n\n\nOrthographicCamera {\n viewportMapping ADJUST_CAMERA\n position %f %f 3\n orientation 0 0 1 0\n aspectRatio 1\n focalDistance 5\n height %f\n\n}\n'%(centerX,centerY,height) FreeCADGui.activeDocument().activeView().setCamera(camera)
def createBox(parts): if len(parts): elem = Part.makeCompound(parts) BoundBox = FreeCAD.ActiveDocument.addObject("Part::Box", "PCB_Bounding_Box_1") BoundBox.Label = "PCB Bounding Box 1" BoundBox.Length = elem.BoundBox.XLength BoundBox.Width = elem.BoundBox.YLength BoundBox.Height = elem.BoundBox.ZLength BoundBox.Placement.Base.x = elem.BoundBox.XMin BoundBox.Placement.Base.y = elem.BoundBox.YMin BoundBox.Placement.Base.z = elem.BoundBox.ZMin FreeCADGui.activeDocument().getObject(BoundBox.Name).ShapeColor = (1.0, 0.0, 0.0, 0.0) FreeCADGui.activeDocument().getObject(BoundBox.Name).Transparency = 80 FreeCADGui.activeDocument().getObject(BoundBox.Name).BoundingBox = True FreeCADGui.activeDocument().getObject(BoundBox.Name).LineWidth = 10.00 FreeCADGui.activeDocument().getObject(BoundBox.Name).DisplayMode = "Shaded" FreeCAD.ActiveDocument.recompute() return BoundBox
def makeAssemblyFile(): try: Gui.getDocument('PrinterAssembly') Gui.getDocument('PrinterAssembly').resetEdit() App.getDocument('PrinterAssembly').recompute() App.closeDocument("PrinterAssembly") App.setActiveDocument("") App.ActiveDocument=None Gui.ActiveDocument=None except: pass #make document #Make Assembly file App.newDocument("PrinterAssembly") App.setActiveDocument("PrinterAssembly") App.ActiveDocument=App.getDocument("PrinterAssembly") Gui.ActiveDocument=Gui.getDocument("PrinterAssembly") Gui.activeDocument().activeView().setCamera('#Inventor V2.1 ascii \n OrthographicCamera {\n viewportMapping ADJUST_CAMERA \n position 0 0 87 \n orientation 0 0 1 0 \n nearDistance -112.88701 \n farDistance 287.28702 \n aspectRatio 1 \n focalDistance 87 \n height 143.52005 }') Gui.activeDocument().activeView().viewAxometric()
def __init__(self,msg): self.beam=self.edge=None FreeCADGui.Selection.clearSelection() try: self.av=FreeCADGui.activeDocument().activeView() self.stop=self.av.addEventCallback("SoKeyboardEvent",self.goOut) FreeCAD.Console.PrintMessage('\n'+msg+'\n') FreeCAD.Console.PrintWarning('*** [ESC] to exit. ***\n') except: FreeCAD.Console.PrintError('No view available\n') FreeCADGui.Selection.removeObserver(self)
def CreateScreen(): doc=FreeCAD.ActiveDocument; l=25.5; h=25.5; pl = FreeCAD.Placement(); pl.Rotation = FreeCAD.Rotation(0.,0.,0.); pl.Base = FreeCAD.Vector(-l/2.,-h/2.,0.); scr_ob=Draft.makeRectangle(length=l,height=h,placement=pl,face=False, \ support=None); # 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(scr_ob); else: gr1_e=getattr(doc,'Elements'); gr1_e.addObject(scr_ob); # end if scr_ob.MakeFace = True; scr_ob.Label="SCR"; scr_ob.ViewObject.ShapeColor=(0.5,0.5,0.5); An=pl.Rotation.toEuler(); l1=["","Screen",scr_ob.Name,scr_ob.Label, \ pl.Base.x+l/2.,pl.Base.y+h/2.,pl.Base.z, \ An[2],An[1],An[0],None,l,h,1.,1.,None,None]; OptElementsGui.AddToOSData(l1,"Element"); # add lens to list of optical system elements 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("Screen was created\n");
def CreateInitialRay(): doc=FreeCAD.ActiveDocument; ray_ob=doc.addObject("Part::Line","IR"); # create groupe and add element to it if (hasattr(doc,'OpticalSystem')==False): gr1=doc.addObject("App::DocumentObjectGroup","OpticalSystem"); gr1_r=gr1.newObject("App::DocumentObjectGroup","Rays"); gr1.newObject("App::DocumentObjectGroup","Elements"); gr1_r.addObject(ray_ob); else: gr1_r=getattr(doc,'Rays'); gr1_r.addObject(ray_ob); # end if ray_ob.X1=0.; ray_ob.Y1=0.; ray_ob.Z1=0.; ray_ob.X2=0.; ray_ob.Y2=0.; ray_ob.Z2=1.; ray_ob.ViewObject.LineWidth=1.; Pr=FreeCAD.Vector(0.,0.,0.); ray_ob.Placement.Base=Pr; An=ray_ob.Placement.Rotation.toEuler(); wl1=555.; col1=ray_ob.ViewObject.LineColor; length1=ray_ob.Shape.Length; l1=["","Ray",ray_ob.Name,ray_ob.Label, Pr[0], Pr[1], Pr[2], \ An[2], An[1], An[0], wl1, str(col1), length1]; OptElementsGui.AddToOSData(l1,"Ray"); 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("Initial Ray was created\n");
def CreateLens(): doc=FreeCAD.ActiveDocument; lens_ob=Draft.makeCircle(10); # 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(lens_ob); else: gr1_e=getattr(doc,'Elements'); gr1_e.addObject(lens_ob); # end if lens_ob.MakeFace=True; lens_ob.Label="PLEN"; lens_ob.Radius.Value=25.5/2.; lens_ob.ViewObject.ShapeColor=(0.5,0.5,0.5); lens_ob.ViewObject.Transparency=60; R=lens_ob.Placement.Base; An=lens_ob.Placement.Rotation.toEuler(); Ap=2.*lens_ob.Radius.Value; f=0.1*1000.; l1=["","ThinLens",lens_ob.Name,lens_ob.Label,R.x,R.y,R.z, \ An[2],An[1],An[0],Ap,None,None,None,None,f,None]; OptElementsGui.AddToOSData(l1,"Element"); # add lens to list of optical system elements doc.recompute(); if (str(FreeCADGui.ActiveDocument.activeView())=='View3DInventor'): FreeCADGui.activeDocument().activeView().viewRear(); FreeCADGui.activeDocument().activeView().viewRotateRight(); FreeCADGui.activeDocument().activeView().fitAll(); # end if doc.recompute(); FreeCAD.Console.PrintMessage("Lens was created\n");
def Activated(self): # So we can open the "Open File" dialog mw = FreeCADGui.getMainWindow() # Try to keep track of the previous path used to open as a convenience to the user if self.previousPath is None: # Start off defaulting to the Examples directory module_base_path = module_locator.module_path() exs_dir_path = os.path.join(module_base_path, "Examples") self.previousPath = exs_dir_path filename = QtGui.QFileDialog.getOpenFileName( mw, mw.tr("Open CadQuery Script"), self.previousPath, mw.tr("CadQuery Files (*.py)") ) # Make sure the user didn't click cancel if filename[0]: # We need to close any file that's already open in the editor window CadQueryCloseScript().Activated() self.previousPath = filename[0] # Append this script's directory to sys.path sys.path.append(os.path.dirname(filename[0])) # We've created a library that FreeCAD can use as well to open CQ files ImportCQ.open(filename[0]) docname = os.path.splitext(os.path.basename(filename[0]))[0] FreeCAD.newDocument(docname) # Execute the script CadQueryExecuteScript().Activated() # Get a nice view of our model FreeCADGui.activeDocument().activeView().viewAxometric() FreeCADGui.SendMsgToActiveView("ViewFit")
def __init__(self,dialog='anyFile.ui'): dialogPath=join(dirname(abspath(__file__)),"dialogs",dialog) FreeCAD.Console.PrintMessage(dialogPath+"\n") self.form=FreeCADGui.PySideUic.loadUi(dialogPath) FreeCAD.Console.PrintMessage(dialogPath+" loaded\n") if platform.startswith('win'):# or vQt>=5: FreeCAD.Console.PrintWarning("No keyboard shortcuts.\n No callback on SoEvent") else: FreeCAD.Console.PrintMessage('Keyboard shortcuts available.\n"S" to select\n"RETURN" to perform action\n') try: self.view=FreeCADGui.activeDocument().activeView() # get3DView() self.call=self.view.addEventCallback("SoEvent", self.action) except: FreeCAD.Console.PrintError('No view available.\n')
def __init__(self, show_main_window=True, name='SimpleSolidPython'): self.main_window = None if show_main_window: self.app = QtGui.QApplication(['SimpleSolidPython']) FreeCADGui.showMainWindow() self.main_window = self.getMainWindow() else: FreeCADGui.setupWithoutGUI() #self.main_window.showMinimized() self.doc=FreeCAD.newDocument(name) try: self.view = FreeCADGui.activeDocument().activeView() #self.view = self.doc.activeView() print('Unable to get the active view') except AttributeError: pass
def CreateBulkPrism(): OptElementsGui.CreateData(""); OptElementsGui.UpdateFunction(); doc=FreeCAD.ActiveDocument; LS1=float(tw.item(0,1).text()); # Length of side 1, mm LS2=float(tw.item(0,2).text()); # Length of side 2, mm AP1=float(tw.item(0,3).text()); # Angle, degrees T1=float(tw.item(0,4).text()); # Thickness n1=1.; n2=float(tw.item(0,5).text()); # refractive index ob1=doc.addObject("Part::Wedge","Wedge"); LS3=(LS1**2.+LS2**2.-2.*LS1*LS2*math.cos(math.pi*AP1/180.))**0.5; X1=(LS3**2.+LS1**2.-LS2**2.)/(2.*LS3); H1=(LS1**2.-X1**2.)**0.5; # Width ob1.Xmin.Value=-T1/2.; ob1.Xmax.Value=T1/2.; ob1.X2min.Value=-T1/2.; ob1.X2max.Value=T1/2.; # Height ob1.Zmin.Value=-LS3/2.; ob1.Zmax.Value=LS3/2.; ob1.Z2min.Value=0.; ob1.Z2max.Value=0.; # Thickness ob1.Ymin.Value=0.; ob1.Ymax.Value=H1; ob1.Placement=FreeCAD.Placement(FreeCAD.Vector(0,0,0), \ FreeCAD.Rotation(FreeCAD.Vector(1,0,0),-90)); ob1.Label="BPRISM"; doc.recompute(); ob1.ViewObject.ShapeColor=(0.5,0.5,0.5); ob1.ViewObject.DisplayMode='Flat Lines'; ob1.ViewObject.Transparency=60; doc.recompute(); # 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 P1=ob1.Placement.Base; An=ob1.Placement.Rotation.toEuler(); l1=["","BulkPrism",ob1.Name,ob1.Label,P1.x,P1.y,P1.z, \ An[2],An[1],An[0],None,LS3,H1,n1,n2,None,T1]; # Add plate to list of optical system elements OptElementsGui.AddToOSData(l1,"Element"); if (str(FreeCADGui.ActiveDocument.activeView())=='View3DInventor'): FreeCADGui.activeDocument().activeView().viewRear(); FreeCADGui.activeDocument().activeView().viewRotateRight(); FreeCADGui.activeDocument().activeView().fitAll(); # end if doc.recompute(); FreeCAD.Console.PrintMessage("Bulk prism is created\n");
def CreatePlate(): doc=FreeCAD.ActiveDocument; l=25.5; h=25.5; pl = FreeCAD.Placement(); pl.Rotation = FreeCAD.Rotation(0.,0.,0.); pl.Base = FreeCAD.Vector(-l/2.,-h/2.,0.); # First interface int_ob1=Draft.makeRectangle(length=l,height=h,placement=pl,face=False, \ support=None); int_ob1.MakeFace = True; int_ob1.Label="PLT1"; int_ob1.ViewObject.ShapeColor=(0.5,0.5,0.5); # Second interface 1 mm thickness pl.Base = FreeCAD.Vector(-l/2.,-h/2.,1.); int_ob2=Draft.makeRectangle(length=l,height=h,placement=pl,face=False, \ support=None); int_ob2.MakeFace = True; int_ob2.Label="PLT2"; int_ob2.ViewObject.ShapeColor=(0.5,0.5,0.5); # Add to Fusion Plate # Create Fusion plt_ob=doc.addObject("Part::MultiFuse","IPLT"); # 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(plt_ob); else: gr1_e=getattr(doc,'Elements'); gr1_e.addObject(plt_ob); # end if plt_ob.Shapes = [int_ob1,int_ob2]; int_ob1.ViewObject.Visibility=False; int_ob2.ViewObject.Visibility=False; plt_ob.ViewObject.ShapeColor=int_ob1.ViewObject.ShapeColor; plt_ob.ViewObject.Transparency=80; doc.recompute(); t1=(plt_ob.Shape.Faces[0].Placement.Base- \ plt_ob.Shape.Faces[1].Placement.Base).Length; An=pl.Rotation.toEuler(); l1=["","IPlate",plt_ob.Name,plt_ob.Label, \ pl.Base.x+l/2.,pl.Base.y+h/2.,pl.Base.z, \ An[2],An[1],An[0],None,l,h,1.,1.,None,t1]; # add plate to list of optical system elements OptElementsGui.AddToOSData(l1,"Element"); if (str(FreeCADGui.ActiveDocument.activeView())=='View3DInventor'): FreeCADGui.activeDocument().activeView().viewRear(); FreeCADGui.activeDocument().activeView().viewRotateRight(); FreeCADGui.activeDocument().activeView().fitAll(); # end if FreeCAD.Console.PrintMessage("Plate was created\n");
def accept(self): if self.pcbBorder.text() == '' or self.pcbHoles.text() == '': FreeCAD.Console.PrintWarning("Mandatory field is empty!\n") elif self.pcbBorder.text() == self.pcbHoles.text(): FreeCAD.Console.PrintWarning("One sketch used two times!\n") else: groupBRD = createGroup_PCB() PCBboard = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "Board") PCBboardObject(PCBboard) PCBboard.Thickness = self.gruboscPlytki.value() PCBboard.Border = FreeCAD.ActiveDocument.getObject(self.pcbBorder.text()) PCBboard.Holes = FreeCAD.ActiveDocument.getObject(self.pcbHoles.text()) viewProviderPCBboardObject(PCBboard.ViewObject) groupBRD.addObject(FreeCAD.ActiveDocument.Board) FreeCADGui.activeDocument().getObject(PCBboard.Name).ShapeColor = self.pcbColor.getColor() FreeCAD.ActiveDocument.getObject(self.pcbBorder.text()).ViewObject.Visibility = False FreeCAD.ActiveDocument.getObject(self.pcbHoles.text()).ViewObject.Visibility = False return True
def CreateBulkPlate(): OptElementsGui.CreateData(""); OptElementsGui.UpdateFunction(); doc=FreeCAD.ActiveDocument; W1=float(tw.item(0,1).text()); # width H1=float(tw.item(0,2).text()); # height T1=float(tw.item(0,3).text()); # thickness n1=1.; n2=float(tw.item(0,4).text()); # refractive index #ob1=doc.addObject("Part::Box","Box"); ob1=doc.addObject("Part::Wedge","Wedge"); ob1.Xmin=-W1/2.; ob1.Xmax=W1/2.; ob1.X2min=-W1/2.; ob1.X2max=W1/2.; ob1.Ymin=-H1/2.; ob1.Ymax=H1/2.; ob1.Zmin=-T1/2.; ob1.Zmax=T1/2.; ob1.Z2min=-T1/2.; ob1.Z2max=T1/2.; ob1.Label="BPLT"; doc.recompute(); #ob1.Length.Value=W1; #ob1.Width.Value=H1; #ob1.Height.Value=T1; #ob1.Placement.Base=FreeCAD.Vector(-W1/2.,-H1/2.,0.); ob1.ViewObject.ShapeColor=(0.5,0.5,0.5); ob1.ViewObject.DisplayMode='Flat Lines'; ob1.ViewObject.Transparency=60; doc.recompute(); # 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 P1=ob1.Placement.Base; An=ob1.Placement.Rotation.toEuler(); l1=["","BulkPlate",ob1.Name,ob1.Label,P1.x,P1.y,P1.z, \ An[2],An[1],An[0],None,W1,H1,n1,n2,None,T1]; # Add plate to list of optical system elements OptElementsGui.AddToOSData(l1,"Element"); if (str(FreeCADGui.ActiveDocument.activeView())=='View3DInventor'): FreeCADGui.activeDocument().activeView().viewRear(); FreeCADGui.activeDocument().activeView().viewRotateRight(); FreeCADGui.activeDocument().activeView().fitAll(); # end if doc.recompute(); FreeCAD.Console.PrintMessage("Bulk plate was created\n");
def generateOneModel(params, log): ModelName = params.modelName FreeCAD.Console.PrintMessage('\n\n############## ' + part_params['code_metric'] + ' ###############\n') CheckedModelName = ModelName.replace('.', '').replace('-', '_').replace( '(', '').replace(')', '') Newdoc = App.newDocument(CheckedModelName) App.setActiveDocument(CheckedModelName) Gui.ActiveDocument = Gui.getDocument(CheckedModelName) #body, base, mark, pins = make_tantalum_th(params) body, pins, pinmark = make_tantalum_th( params) #body, base, mark, pins, top show(body) show(pins) show(pinmark) doc = FreeCAD.ActiveDocument print(GetListOfObjects(FreeCAD, doc)) objs = GetListOfObjects(FreeCAD, doc) Color_Objects(Gui, objs[0], body_color) Color_Objects(Gui, objs[1], pins_color) Color_Objects(Gui, objs[2], marking_color) col_body = Gui.ActiveDocument.getObject(objs[0].Name).DiffuseColor[0] col_pin = Gui.ActiveDocument.getObject(objs[1].Name).DiffuseColor[0] col_mark = Gui.ActiveDocument.getObject(objs[2].Name).DiffuseColor[0] material_substitutions = { col_body[:-1]: body_color_key, col_pin[:-1]: pins_color_key, col_mark[:-1]: marking_color_key } expVRML.say(material_substitutions) del objs objs = GetListOfObjects(FreeCAD, doc) FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name, objs[1].Name) objs = GetListOfObjects(FreeCAD, doc) FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name, objs[1].Name) #stop doc.Label = CheckedModelName objs = GetListOfObjects(FreeCAD, doc) objs[0].Label = CheckedModelName restore_Main_Tools() #rotate if required objs = GetListOfObjects(FreeCAD, doc) FreeCAD.getDocument(doc.Name).getObject( objs[0].Name).Placement = FreeCAD.Placement( FreeCAD.Vector(params.F / 2, 0, 0), FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), params.rotation)) #out_dir=destination_dir+params.dest_dir_prefix+'/' script_dir = os.path.dirname(os.path.realpath(__file__)) expVRML.say(script_dir) #out_dir=script_dir+os.sep+destination_dir+os.sep+params.dest_dir_prefix out_dir = models_dir + destination_dir if not os.path.exists(out_dir): os.makedirs(out_dir) #out_dir="./generated_qfp/" # export STEP model exportSTEP(doc, ModelName, out_dir) if LIST_license[0] == "": LIST_license = Lic.LIST_int_license LIST_license.append("") Lic.addLicenseToStep(out_dir+'/', ModelName+".step", LIST_license,\ STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licOrg, STR_licPreProc) # scale and export Vrml model scale = 1 / 2.54 #exportVRML(doc,ModelName,scale,out_dir) objs = GetListOfObjects(FreeCAD, doc) expVRML.say( "######################################################################" ) expVRML.say(objs) expVRML.say( "######################################################################" ) export_objects, used_color_keys = expVRML.determineColors( Gui, objs, material_substitutions) export_file_name = out_dir + os.sep + ModelName + '.wrl' colored_meshes = expVRML.getColoredMesh(Gui, export_objects, scale) expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys, LIST_license) if save_memory == False: Gui.SendMsgToActiveView("ViewFit") Gui.activeDocument().activeView().viewAxometric() # Save the doc in Native FC format saveFCdoc(App, Gui, doc, ModelName, out_dir) if save_memory == True: doc = FreeCAD.ActiveDocument FreeCAD.closeDocument(doc.Name)
def on_keypress2(ef, keystring): print print print print "on_key_press:", keystring try: camera = FreeCADGui.activeDocument().activeView().getCameraNode() # # Hilfspunkt kameraposition # c=App.ActiveDocument.Vertex # # # Hud # panel=App.ActiveDocument.Compound # # Kugel im HUD # s=App.ActiveDocument.Sphere001 if ef.firstCall: FreeCADGui.activeDocument().activeView().setCameraType( "Perspective") ef.firstCall = False campos = FreeCAD.Vector(0, 0, 0) camera.position.setValue(campos) nD = 100 fD = 12000000 camera.nearDistance.setValue(nD) camera.farDistance.setValue(fD) if keystring == 'X' or keystring == 'Insert': ef.campos.x += 10 if keystring == 'Y' or keystring == 'Home': ef.campos.y += 10 if keystring == 'Z' or keystring == 'PageUp': ef.campos.z += 10 if keystring == 'Shift-X' or keystring == 'Delete': ef.campos.x -= 10 if keystring == 'Shift-Y' or keystring == 'End': ef.campos.y -= 10 if keystring == 'Shift-Z' or keystring == 'PageDown': ef.campos.z -= 10 if keystring == 'F12': ef.campos = FreeCAD.Vector(0, 0, 0) ef.laenge = 0 ef.breite = 0 ef.roll = 0 if keystring == 'Control-Left': ef.roll += 10 if keystring == 'Control-Right': ef.roll -= 10 if keystring == 'Control-Down': ef.roll = 0 if ef.mode == 'turn': if keystring == 'Up': ef.breite += 1.0 if keystring == 'Down': ef.breite -= 1.0 if keystring == 'Shift-Up' or keystring == 'Shift-Down': ef.breite = -ef.breite if ef.laenge <= 0: ef.laenge += 180 else: ef.laenge -= 180 if keystring == 'Left': ef.laenge -= 1.1 if keystring == 'Right': ef.laenge += 1.2 if keystring == 'Shift-Left' or keystring == 'Shift-Right': if ef.laenge <= 0: ef.laenge += 180 else: ef.laenge -= 180 elif ef.mode == 'walk': Msg('walk mode') if keystring == 'Left': ef.direction -= 0.1 ef.laenge = -90 + ef.direction * 180 / math.pi if keystring == 'Right': ef.direction += 0.1 ef.laenge = -90 + ef.direction * 180 / math.pi if keystring == 'Up': ef.campos.x -= ef.speed * math.cos(ef.direction) ef.campos.y += ef.speed * math.sin(ef.direction) ef.campos.z += ef.speed * math.sin(ef.breite / 180 * math.pi) if keystring == 'Down': ef.campos.x += ef.speed * math.cos(ef.direction) ef.campos.y -= ef.speed * math.sin(ef.direction) ef.campos.z -= ef.speed * math.sin(ef.breite / 180 * math.pi) if keystring == 'Return': pass elif ef.mode == 'xyz': Err('xyz mode') if keystring == 'Up': ef.campos.z += ef.speed * math.cos(math.pi * ef.roll / 180) if keystring == 'Down': ef.campos.z -= ef.speed * math.cos(math.pi * ef.roll / 180) # if keystring=='Up': # ef.campos.x += ef.speed*math.cos(ef.direction) # ef.campos.y += ef.speed*math.sin(ef.direction) # if keystring=='Down': # ef.campos.x -= ef.speed*math.cos(ef.direction) # ef.campos.y -= ef.speed*math.sin(ef.direction) if keystring == 'Left': ef.campos.y += ef.speed * math.sin(0.0 + ef.laenge / 180 * math.pi) ef.campos.x -= ef.speed * math.cos(0.0 + ef.laenge / 180 * math.pi) if keystring == 'Right': ef.campos.y -= ef.speed * math.sin(0.0 + ef.laenge / 180 * math.pi) ef.campos.x += ef.speed * math.cos(0.0 + ef.laenge / 180 * math.pi) else: Err("no known mode -- no action") ef.compass.direction(ef.laenge) ef.horizon.direction(ef.roll) ef.horizon.setnick(ef.breite) r = 1000 pos3 = FreeCAD.Vector( r * math.sin(ef.laenge / 180 * math.pi) * math.cos(ef.breite / 180 * math.pi), r * math.cos(ef.laenge / 180 * math.pi) * math.cos(ef.breite / 180 * math.pi), r * math.sin(ef.breite / 180 * math.pi)) dir = FreeCAD.Vector(pos3) # .sub(ef.campos) dir.normalize() print print ef.direction print "ef.campos", ef.campos ef.map.setPos(ef.campos.x, ef.campos.y, ef.campos.z) spos = FreeCAD.Vector(ef.campos) d = 200 prpos = FreeCAD.Vector(d * dir.x, d * dir.y, d * dir.z) ppos = spos.add(prpos) # kamera position # c.Placement.Base=ef.campos camera.position.setValue(ef.campos) camera.pointAt( coin.SbVec3f(ppos), coin.SbVec3f(0, 0.0 + math.sin(math.pi * ef.roll / 180), 0.0 + math.cos(math.pi * ef.roll / 180))) print "Roll ", ef.roll # #hud # panel.Placement.Base=ppos # panel.Placement.Rotation=FreeCAD.Rotation(ef.laenge,-ef.breite,0) # #drehung des kompass/horizonts # s.Placement.Rotation=FreeCAD.Rotation(-ef.laenge-90,0,ef.breite) # # kamera einstellungen # if keystring == 'F9': a = camera.heightAngle.getValue() print a a += 0.01 camera.heightAngle.setValue(a) if keystring == 'F10': a = camera.heightAngle.getValue() a -= 0.01 camera.heightAngle.setValue(a) if keystring == 'F11': camera.heightAngle.setValue(0.785398185253) if keystring == 'F5': nD = camera.nearDistance.getValue() nD *= 1.03 print "near Distance", nD camera.nearDistance.setValue(nD) if keystring == 'F6': nD = camera.nearDistance.getValue() nD /= 1.03 if nD > 0: print "near Distance", nD camera.nearDistance.setValue(nD) if keystring == 'F2': fn = '/home/microelly2/FCB/b175_camera_controller/P1170438.JPG' ef.tex.filename = fn if keystring == 'F3': fn = '/home/microelly2/FCB/b175_camera_controller/P1170039.JPG' ef.tex.filename = fn if keystring == 'F4': fn = '/home/microelly2/FCB/b175_camera_controller/winter.jpg' ef.tex.filename = fn # # ausgabe daten # if 1 or keystring == 'F2': t = FreeCAD.Vector(prpos) try: t.normalize() except: pass campos2 = (round(ef.campos[0]), round(ef.campos[1]), round(ef.campos[2])) print print "Camera position ", campos2 print "Camera direction ", (round(t.x, 2), round(t.y, 2), round(t.z, 2)) nD = camera.nearDistance.getValue() print "near Distance ", round(nD) a = camera.heightAngle.getValue() print "height Angle ", round(a / math.pi * 180) print "focal length ", round(10 / math.tan(a / 2)) print out = '' out += "camera position " + str(campos2) + "\n" out += "camera direction " + str( [round(t.x, 2), round(t.y, 2), round(t.z, 2)]) + "\n" out += "speed " + str(ef.speed) + "\n" out += "dir " + str(round(ef.direction * 180 / math.pi)) + "\n" out += '\n' out += "height Angle " + str(round(a / math.pi * 180)) + '\n' out += "focal length " + str(round(10 / math.tan(a / 2))) + "\n" out += "near Distance " + str(round(nD)) + '\n' ef.navi.output.setText(out) FreeCAD.ActiveDocument.recompute() FreeCADGui.updateGui() if keystring == 'Escape': print "stoppe eventserver ..." stop() sg = FreeCADGui.ActiveDocument.ActiveView.getSceneGraph() ef.output.deleteLater() ef.navi.deleteLater() sg.removeChild(ef.background) except: sayexc() stop() return True
def Activated(self): FreeCADGui.activeDocument().activeView().setCameraType("Perspective") cam = FreeCADGui.ActiveDocument.ActiveView.getCameraNode() cam.heightAngle = 0.4
def Activated(self): import ObjectsFem isMystran = 1 ininame = "Mod/hfcMystran/hfcMystran.ini" inifile = FreeCAD.getHomePath() + ininame if os.path.exists(inifile): iniF = open(inifile, "r") path = iniF.readline() iniF.close() else: path = FreeCAD.getHomePath() try: fName = QFileDialog.getOpenFileName( None, QString.fromLocal8Bit("Read a Mystarn's Dat/bdf file"), path, "*.Dat *.bdf") # PyQt4 except Exception: fName, Filter = PySide.QtGui.QFileDialog.getOpenFileName( None, "Read a Mystran's Dat/bdf file", path, "*.Dat *.bdf") #PySide print("src: " + fName) DesName = FreeCAD.getHomePath() + "bin/hfcMystran.Dat" print("Des: " + DesName) shutil.copyfile(fName, DesName) data = fName.split("/") n = len(data) path = "" for i in range(n - 1): path = path + data[i] + "/" inifileOut = FreeCAD.getHomePath() + ininame iniFout = open(inifileOut, "w") iniFout.writelines(path) iniFout.close() #print (path) iHfc = FreeCAD.ActiveDocument.getObject('hfc') if iHfc == None: iHfc = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", 'hfc') hfc(iHfc) #iHfc.ViewObject.Proxy=0 #ViewProviderCFG(iHfc.ViewObject) iHfc.DatPath = path iHfc.DatFile = fName numNode = 0 numMember = 0 nodes_x = [] nodes_y = [] nodes_z = [] NodeList = {} MemberList = {} DisplacementList = {} NodeEndList = {} MemberEndList = {} ProjectDescription = '' nodes = {} results = [] mode_results = {} mode_disp = {} iFilled = [] mode_disp_x = [] mode_disp_y = [] mode_disp_z = [] nDisp = 0 mDisp = 0 isDebug = 1 #factor = 25.42 factor = 1 factorZoom = 100 #000000000000000000000000000000000000000000000000000000000000000000 fpDat = open(fName) tline = [] for line in fpDat: aline = line.strip() if len(aline) == 0 or aline[0] == '$': continue else: tline.append(line.strip()) fpDat.close() for id in range(len(tline)): aline = tline[id].strip() data = aline.split() data1 = aline.split(",") #print (data) # Node 22222222222222222222222222222222222222222222222222222222222222222222 if data[0] == 'GRID': # gid cp x1 #GRID 10101 0 0.000 0.000 0.000 0 gid = aline[8:16].strip() #cid1=aline[16:24].strip() x = aline[24:32].strip() y = aline[32:40].strip() z = aline[40:48].strip() NodeList[gid] = Node(gid, float(x), float(y), float(z)) numNode = numNode + 1 if data[0] == 'GRID*': #GRID* 1 0.00000E+00 0.00000E+00 gid = aline[8:24].strip() #cid1=aline[24:40].strip() x = aline[40:56].strip() y = aline[56:72].strip() bline = tline[id + 1].strip() z = bline[8:24].strip() NodeList[gid] = Node(gid, float(x), float(y), float(z)) numNode = numNode + 1 # Member 33333333333333333333333333333333333333333333333333333333333333333333333333333333333333 #CBAR 201 2 11 21 0.0 0.0 1.0 if data[0] == 'CBAR': MemberList[data[1].strip()] = MemberCBAR( data[1].strip(), data[3], data[4], data[0].strip()) numMember += 1 #CBEAM 9400 9401 9401 9402 0. 0. 1. if data[0] == 'CBEAM': MemberList[data[1].strip()] = MemberCBEAM( data[1].strip(), data[3], data[4], data[0].strip()) numMember += 1 #CROD, 418,418,8,3 if data[0] == 'CROD': MemberList[data[1].strip()] = MemberCROD( data[1].strip(), data[3], data[4], data[0].strip()) numMember += 1 #CROD, 418,418,8,3 if data1[0] == 'CROD': MemberList[data1[1].strip()] = MemberCROD( data1[1].strip(), data1[3], data1[4], data1[0].strip()) numMember += 1 #CTRIA3 24 91 1033 1032 1023 if data[0] == 'CTRIA3': MemberList[data[1].strip()] = MemberCTRIA3( data[1].strip(), data[3], data[4], data[5], data[0].strip()) numMember += 1 #CQUAD4 1001 1 1001 1002 2002 2001 if data[0] == 'CQUAD4': MemberList[data[1].strip()] = MemberCQUAD4( data[1].strip(), data[3], data[4], data[5], data[6], data[0].strip()) numMember += 1 #CQUAD8 16004 1 16007 16009 18009 18007 16008 17009 #18008 17007 if data[0] == 'CQUAD8': MemberList[data[1].strip()] = MemberCQUAD8( data[1].strip(), data[3], data[4], data[5], data[6], data[0].strip()) numMember += 1 #CTETRA 1 1 8 13 67 33 if data[0] == 'CTETRA': MemberList[data[1].strip()] = MemberCQUAD4( data[1].strip(), data[3], data[4], data[5], data[6], data[0].strip()) numMember += 1 # #CHEXA 10101 100 10101 10103 10303 10301 30101 30103+E 1 #+E 1 30303 30301 if data[0] == 'CHEXA': bline = tline[id + 1].strip() if len(aline) == 80: eid = aline[9:16].strip() pid = aline[17:24].strip() g1 = aline[25:32].strip() g2 = aline[33:40].strip() g3 = aline[41:48].strip() g4 = aline[49:56].strip() g5 = aline[57:64].strip() g6 = aline[65:72].strip() if aline[73:80] == bline[1:8]: g7 = bline[9:16].strip() g8 = bline[17:24].strip() #print (eid+" "+g1+" "+g2+" "+g3+" "+g4+" "+g5+" "+g6+" "+g7+" "+g8) MemberList[eid] = MemberCHEXA(eid, g1, g2, g3, g4, g5, g6, g7, g8, data[0].strip()) numMember += 1 #print (NodeList) #print (MemberList) print('numNode = ' + str(numNode)) print('numMember = ' + str(numMember)) #for id in NodeList: # print (NodeList[id].id+" "+str(NodeList[id].x)+" "+str(NodeList[id].y)+" "+str(NodeList[id].z)) femmesh = Fem.FemMesh() # nodes #print ("Add nodes") for id in NodeList: # node #femmesh.addNode(NodeList[id].x,NodeList[id].y,NodeList[id].z, int(id)+1 ) femmesh.addNode(NodeList[id].x, NodeList[id].y, NodeList[id].z, int(id)) for id in MemberList: mtype = MemberList[id].mtype if mtype == 'CROD': n1 = int(MemberList[id].n1) n2 = int(MemberList[id].n2) femmesh.addEdge([n1, n2]) elif mtype == 'CBAR': n1 = int(MemberList[id].n1) n2 = int(MemberList[id].n2) femmesh.addEdge([n1, n2]) elif mtype == 'CBEAM': n1 = int(MemberList[id].n1) n2 = int(MemberList[id].n2) femmesh.addEdge([n1, n2]) elif mtype == 'CTRIA3': n1 = int(MemberList[id].n1) n2 = int(MemberList[id].n2) n3 = int(MemberList[id].n3) femmesh.addEdge([n1, n2]) femmesh.addEdge([n2, n3]) femmesh.addEdge([n3, n1]) #femmesh.addFace([n1,n2,n3]) elif mtype == 'CQUAD4': n1 = int(MemberList[id].n1) n2 = int(MemberList[id].n2) n3 = int(MemberList[id].n3) n4 = int(MemberList[id].n4) #print (str(n1)+" "+str(n2)+" "+str(n3)+" "+str(n4)) femmesh.addEdge([n1, n2]) femmesh.addEdge([n2, n3]) femmesh.addEdge([n3, n4]) femmesh.addEdge([n4, n1]) #femmesh.addFace([n1,n2,n3,n4]) elif mtype == 'CQUAD8': n1 = int(MemberList[id].n1) n2 = int(MemberList[id].n2) n3 = int(MemberList[id].n3) n4 = int(MemberList[id].n4) femmesh.addEdge([n1, n2]) femmesh.addEdge([n2, n3]) femmesh.addEdge([n3, n4]) femmesh.addEdge([n4, n1]) #femmesh.addFace([n1,n2,n3,n4]) elif mtype == 'CTETRA': n1 = int(MemberList[id].n1) n2 = int(MemberList[id].n2) n3 = int(MemberList[id].n3) n4 = int(MemberList[id].n4) femmesh.addEdge([n1, n2]) femmesh.addEdge([n2, n3]) femmesh.addEdge([n3, n4]) femmesh.addEdge([n4, n1]) #femmesh.addVolume([n1,n2,n3,n4]) elif mtype == 'CHEXA': n1 = int(MemberList[id].n1) n2 = int(MemberList[id].n2) n3 = int(MemberList[id].n3) n4 = int(MemberList[id].n4) n5 = int(MemberList[id].n5) n6 = int(MemberList[id].n6) n7 = int(MemberList[id].n7) n8 = int(MemberList[id].n8) femmesh.addEdge([n1, n2]) femmesh.addEdge([n2, n3]) femmesh.addEdge([n3, n4]) femmesh.addEdge([n4, n1]) femmesh.addEdge([n5, n6]) femmesh.addEdge([n6, n7]) femmesh.addEdge([n7, n8]) femmesh.addEdge([n8, n5]) femmesh.addEdge([n1, n5]) femmesh.addEdge([n2, n6]) femmesh.addEdge([n3, n7]) femmesh.addEdge([n4, n8]) #femmesh.addVolume([n1,n2,n3,n4,n5,n6,n7,n8]) else: print(mtype + ' Not supported yet') result_mesh_object = None result_mesh_object = ObjectsFem.makeMeshResult(FreeCAD.ActiveDocument, "hfcMesh") result_mesh_object.FemMesh = femmesh FreeCAD.ActiveDocument.recompute() FreeCADGui.activeDocument().activeView().viewAxonometric() FreeCADGui.SendMsgToActiveView("ViewFit") print('Input done.') print('')
def generateHoles(self, dane, doc, Hmin, Hmax): doc.addObject('Sketcher::SketchObject', 'PCB_Holes') doc.PCB_Holes.Placement = FreeCAD.Placement( FreeCAD.Vector(0.0, 0.0, 0.0), FreeCAD.Rotation(0.0, 0.0, 0.0, 1.0)) FreeCADGui.activeDocument().PCB_Holes.Visibility = False # for i in dane: x = float("%4.3f" % i[0]) y = float("%4.3f" % i[1]) r = float("%4.3f" % i[2]) if r == 0: continue if len(i) > 3: # oval r2 = float("%4.3f" % i[3]) p1 = i[4] p2 = i[5] p3 = i[6] p4 = i[7] if r > r2: doc.PCB_Holes.addGeometry( Part.Line(FreeCAD.Vector(p1[0], p1[1], 0), FreeCAD.Vector(p2[0], p2[1], 0))) doc.PCB_Holes.addGeometry( Part.Line(FreeCAD.Vector(p3[0], p3[1], 0), FreeCAD.Vector(p4[0], p4[1], 0))) p5 = self.arcMidPoint(p1, p3, 180) doc.PCB_Holes.addGeometry( Part.Arc(FreeCAD.Vector(p1[0], p1[1], 0.0), FreeCAD.Vector(p5[0], p5[1], 0.0), FreeCAD.Vector(p3[0], p3[1], 0.0))) p5 = self.arcMidPoint(p2, p4, -180) doc.PCB_Holes.addGeometry( Part.Arc(FreeCAD.Vector(p2[0], p2[1], 0.0), FreeCAD.Vector(p5[0], p5[1], 0.0), FreeCAD.Vector(p4[0], p4[1], 0.0))) else: doc.PCB_Holes.addGeometry( Part.Line(FreeCAD.Vector(p1[0], p1[1], 0), FreeCAD.Vector(p3[0], p3[1], 0))) doc.PCB_Holes.addGeometry( Part.Line(FreeCAD.Vector(p2[0], p2[1], 0), FreeCAD.Vector(p4[0], p4[1], 0))) p5 = self.arcMidPoint(p1, p2, -180) doc.PCB_Holes.addGeometry( Part.Arc(FreeCAD.Vector(p1[0], p1[1], 0.0), FreeCAD.Vector(p5[0], p5[1], 0.0), FreeCAD.Vector(p2[0], p2[1], 0.0))) p5 = self.arcMidPoint(p3, p4, 180) doc.PCB_Holes.addGeometry( Part.Arc(FreeCAD.Vector(p3[0], p3[1], 0.0), FreeCAD.Vector(p5[0], p5[1], 0.0), FreeCAD.Vector(p4[0], p4[1], 0.0))) else: # circle if Hmin == 0 and Hmax == 0: doc.PCB_Holes.addGeometry( Part.Circle(FreeCAD.Vector(x, y, 0.), FreeCAD.Vector(0, 0, 1), r)) elif Hmin != 0 and Hmax == 0 and Hmin <= r * 2: doc.PCB_Holes.addGeometry( Part.Circle(FreeCAD.Vector(x, y, 0.), FreeCAD.Vector(0, 0, 1), r)) elif Hmax != 0 and Hmin == 0 and r * 2 <= Hmax: doc.PCB_Holes.addGeometry( Part.Circle(FreeCAD.Vector(x, y, 0.), FreeCAD.Vector(0, 0, 1), r)) elif Hmin <= r * 2 <= Hmax: doc.PCB_Holes.addGeometry( Part.Circle(FreeCAD.Vector(x, y, 0.), FreeCAD.Vector(0, 0, 1), r)) #### ##hole = [Part.Circle(FreeCAD.Vector(x, y), FreeCAD.Vector(0, 0, 1), r).toShape()] ##hole = Part.Wire(hole) ##hole = Part.Face(hole) #hole = [Part.Circle(FreeCAD.Vector(x, y, -1), FreeCAD.Vector(0, 0, 1), r).toShape()] #hole = Part.Wire(hole) #hole = Part.Face(hole).extrude(FreeCAD.Base.Vector(0, 0, 2)) #holeModel.append(hole) #holeModel = Part.makeCompound(holeModel) doc.Board.Holes = doc.PCB_Holes doc.recompute()
def draw_S800(): sweep_offset = 210 wing_span = 820 midWidth = 150 midLength = 200 WingInside_height_top = 25 WingInside_height_bot = 5 WingInside_length = 260 WingOutside_height_top = 20 WingOutside_height_bot = 3 WingOutside_length = 165 Middle_height_top = 40 Middle_height_bot = 20 Middle_length = WingInside_length WingletTop_height_top = 3 WingletTop_height_bot = 3 Winglet_angle_y = 10 WingletBottom_height_top = WingletTop_height_top WingletBottom_height_bot = WingletTop_height_bot WingletBottom_length = WingOutside_length ElevonThickness = 1 ElevonLeftAngle = 20 ElevonRightAngle = -20 if FreeCAD.ActiveDocument is not None and FreeCAD.ActiveDocument.Name == "S800": FreeCAD.closeDocument(FreeCAD.ActiveDocument.Name) FreeCAD.setActiveDocument("") FreeCAD.ActiveDocument = None doc = FreeCAD.newDocument('S800') SplineFoilWingInside = doc.addObject('Sketcher::SketchObject', 'SplineFoilWingInside') makeSplineFoilSketch(SplineFoilWingInside, WingInside_length, WingInside_height_top, WingInside_height_bot, ElevonThickness) SplineFoilWingInside.ViewObject.Visibility = False SplineFoilWingInside.Placement = Placement(Vector(midWidth / 2, 0.0, 1.0), Rotation(0.5, 0.5, 0.5, 0.5)) SplineFoilWingInside.ViewObject.Visibility = False SplineFoilWingOutside = doc.addObject('Sketcher::SketchObject', 'SplineFoilWingOutside') makeSplineFoilSketch(SplineFoilWingOutside, WingOutside_length, WingOutside_height_top, WingOutside_height_bot, ElevonThickness) SplineFoilWingOutside.ViewObject.Visibility = False SplineFoilWingOutside.Placement = Placement( Vector(wing_span / 2, sweep_offset, 1.0), Rotation(0.5, 0.5, 0.5, 0.5)) SplineFoilWingOutside.ViewObject.Visibility = False SplineFoilWingletBottom = doc.addObject('Sketcher::SketchObject', 'SplineFoilWingletBottom') makeSplineFoilSketch(SplineFoilWingletBottom, WingletBottom_length, WingletBottom_height_top, WingletBottom_height_bot, 0.5) SplineFoilWingletBottom.ViewObject.Visibility = False SplineFoilWingletBottom.Placement.Rotation.Axis = Vector(0.0, 0.0, 0.1) SplineFoilWingletBottom.Placement.Rotation.Angle = math.radians(90) SplineFoilWingletBottom.Placement.Base.y = sweep_offset SplineFoilWingletBottom.Placement.Base.x = wing_span / 2 + WingletTop_height_bot * 1.5 SplineFoilWingletBottom.Placement.Base.z = WingOutside_height_top SplineFoilWingletBottom.ViewObject.Visibility = False doc.recompute() Draft.rotate([SplineFoilWingletBottom], Winglet_angle_y, SplineFoilWingletBottom.Placement.Base, Vector(0, 1, 0), copy=False) doc.recompute() SplineFoilMiddle = doc.addObject('Sketcher::SketchObject', 'SplineFoilMiddle') makeSplineFoilSketch(SplineFoilMiddle, Middle_length, Middle_height_top, Middle_height_bot, ElevonThickness) SplineFoilMiddle.Placement = Placement(Vector(0.0, 0.0, 0.0), Rotation(0.5, 0.5, 0.5, 0.5)) SplineFoilMiddle.ViewObject.Visibility = False MiddleProfile = createSketch_MiddleProfile(doc) MiddleProfile.ViewObject.Visibility = False MiddlePart1 = CurvedShapes.makeCurvedSegment(SplineFoilMiddle, SplineFoilWingInside, [MiddleProfile], Items=4, Surface=True, Solid=True, Distribution='elliptic', DistributionReverse=True) MiddlePart1.Label = "MiddlePart1" MiddlePart1.ViewObject.Visibility = False MainWing = doc.addObject('Part::Loft', 'MainWing') MainWing.Sections = [SplineFoilWingInside, SplineFoilWingOutside] MainWing.Solid = True WingToWinglet = CurvedShapes.makeInterpolatedMiddle( SplineFoilWingOutside, SplineFoilWingletBottom, Surface=True, Solid=True) WingToWinglet.Label = "WingToWinglet" WingletProfile = makeWingletProfile(doc) WingletProfile.ViewObject.Visibility = False doc.recompute() Winglet = CurvedShapes.makeCurvedArray(SplineFoilWingletBottom, [WingletProfile], Items=8, OffsetStart=0.01, OffsetEnd=0.01, Surface=True, Solid=True) Winglet.Label = "Winget" doc.recompute() Draft.rotate([Winglet], Winglet_angle_y, SplineFoilWingletBottom.Placement.Base, Vector(0, 1, 0), copy=False) doc.recompute() sketchCutout = doc.addObject('Sketcher::SketchObject', 'sketchCutout') sketchCutout.addGeometry( Part.LineSegment(Vector(0.0, 400.0, 0.0), Vector(274.99999999950205, 400.0, 0.0)), False) sketchCutout.addGeometry( Part.LineSegment(Vector(274.99999999950205, 400.0, 0.0), Vector(75.0, 200.0, 0.0)), False) sketchCutout.addGeometry( Part.LineSegment(Vector(75.0, 200.0, 0.0), Vector(0.0, 200.0, 0.0)), False) sketchCutout.addGeometry( Part.LineSegment(Vector(0.0, 200.0, 0.0), Vector(0.0, 400.0, 0.0)), False) sketchCutout.addConstraint(Sketcher.Constraint('PointOnObject', 0, 1, -2)) sketchCutout.addConstraint(Sketcher.Constraint('Horizontal', 0)) sketchCutout.addConstraint(Sketcher.Constraint('Coincident', 0, 2, 1, 1)) sketchCutout.addConstraint(Sketcher.Constraint('Coincident', 1, 2, 2, 1)) sketchCutout.addConstraint(Sketcher.Constraint('PointOnObject', 2, 2, -2)) sketchCutout.addConstraint(Sketcher.Constraint('Horizontal', 2)) sketchCutout.addConstraint(Sketcher.Constraint('Coincident', 2, 2, 3, 1)) sketchCutout.addConstraint(Sketcher.Constraint('Coincident', 3, 2, 0, 1)) sketchCutout.addConstraint( Sketcher.Constraint('Angle', 1, 2, 2, 1, 2.356194)) sketchCutout.addConstraint( Sketcher.Constraint('DistanceX', 2, 2, 2, 1, midWidth / 2)) sketchCutout.addConstraint( Sketcher.Constraint('DistanceY', 2, 2, midLength)) sketchCutout.addConstraint( Sketcher.Constraint('DistanceY', 3, 1, 3, 2, midLength)) sketchCutout.ViewObject.Visibility = False cutout = doc.addObject('Part::Extrusion', 'cutout') cutout.Base = sketchCutout cutout.DirMode = "Normal" cutout.LengthFwd = 100.0 cutout.LengthRev = 100.0 cutout.Solid = True cutout.Symmetric = True cutout.ViewObject.Visibility = False MiddlePart = doc.addObject('Part::Cut', 'MiddlePart') MiddlePart.Base = MiddlePart1 MiddlePart.Tool = cutout cutpathPoints = [Vector(midWidth / 2, midLength, -WingInside_height_bot)] cutpathPoints.append( Vector( wing_span / 2, midLength + sweep_offset - WingInside_length + WingOutside_length, -WingOutside_height_bot)) cutpath = Draft.makeWire(cutpathPoints) cutpath.ViewObject.Visibility = False cutExtrude = doc.addObject('Part::Extrusion', 'cutExtrude') cutExtrude.Base = cutpath cutExtrude.DirMode = "Normal" cutExtrude.LengthFwd = WingInside_height_bot + WingInside_height_top doc.recompute() Wing = doc.addObject('Part::Cut', 'Wing') Wing.Base = MainWing Wing.Tool = cutout doc.recompute() WingSlice = BOPTools.SplitFeatures.makeSlice(name='WingSlice') WingSlice.Base = [Wing, cutExtrude][0] WingSlice.Tools = [Wing, cutExtrude][1:] WingSlice.Mode = 'Split' WingSlice.Proxy.execute(WingSlice) WingSlice.purgeTouched() WingSlice.ViewObject.Visibility = False for obj in WingSlice.ViewObject.Proxy.claimChildren(): obj.ViewObject.hide() WingAndElevon = CompoundTools.Explode.explodeCompound(WingSlice) Wing1 = WingAndElevon[0].Group[0] Wing1.Label = "Wing1" ElevonLeft = WingAndElevon[0].Group[1] ElevonLeft.Label = "ElevonLeft" HalfWing = doc.addObject('Part::Compound', 'HalfWing') HalfWing.Links = [MiddlePart, Wing1, WingToWinglet, Winglet] FullWing = doc.addObject('Part::Mirroring', 'FullWing') FullWing.Normal = Vector(1.0, 0.0, 0.0) FullWing.Source = HalfWing ElevonRight1 = Draft.clone(ElevonLeft) ElevonRight1.ViewObject.Visibility = False ElevonRight = doc.addObject('Part::Mirroring', 'ElevonRight') ElevonRight.Normal = Vector(1.0, 0.0, 0.0) ElevonRight.Source = ElevonRight1 doc.recompute() axis = cutpathPoints[1].sub(cutpathPoints[0]) center = ElevonLeft.Placement.Base.add( Vector(midWidth / 2, midLength, ElevonLeft.Shape.BoundBox.ZMax)) Draft.rotate([ElevonLeft], ElevonLeftAngle, center, axis=axis, copy=False) Draft.rotate([ElevonRight1], ElevonRightAngle, center, axis=axis, copy=False) FreeCADGui.activeDocument().activeView().viewIsometric() FreeCADGui.SendMsgToActiveView("ViewFit") return
def IsActive(self): """Return True when this command should be available.""" if Gui.activeDocument(): return True else: return False
def Activated(self): obj = makePythonObject() FreeCADGui.activeDocument().setEdit(obj.Name, 0)
def generateOneModel(params, log): excluded_pins_x = () ##no pin excluded excluded_pins_xmirror = () ##no pin excluded place_pinMark = True ##default =True used to exclude pin mark to build sot23-3; sot23-5; sc70 (asimmetrical pins, no pinmark) ModelName = params.modelName FreeCAD.Console.PrintMessage('\n\n############## ' + ModelName + ' ###############\n') CheckedModelName = ModelName.replace('.', '').replace('-', '_').replace( '(', '').replace(')', '') Newdoc = App.newDocument(CheckedModelName) App.setActiveDocument(CheckedModelName) Gui.ActiveDocument = Gui.getDocument(CheckedModelName) #case, pins, pinmark = make_case(params) case_bot, case, pins, pinmark = make_case(params) if case_bot is not None: show(case_bot) show(case) show(pins) show(pinmark) #stop doc = FreeCAD.ActiveDocument objs = GetListOfObjects(FreeCAD, doc) if case_bot is not None: Color_Objects(Gui, objs[0], body_bot_color) Color_Objects(Gui, objs[1], body_color) Color_Objects(Gui, objs[2], pins_color) Color_Objects(Gui, objs[3], marking_color) col_body_bot = Gui.ActiveDocument.getObject( objs[0].Name).DiffuseColor[0] col_body = Gui.ActiveDocument.getObject(objs[1].Name).DiffuseColor[0] col_pin = Gui.ActiveDocument.getObject(objs[2].Name).DiffuseColor[0] col_mark = Gui.ActiveDocument.getObject(objs[3].Name).DiffuseColor[0] material_substitutions = { col_body_bot[:-1]: body_bot_color_key, col_body[:-1]: body_color_key, col_pin[:-1]: pins_color_key, col_mark[:-1]: marking_color_key } expVRML.say(material_substitutions) if (color_pin_mark == True) and (place_pinMark == True): CutObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[1].Name, objs[3].Name) else: #removing pinMark App.getDocument(doc.Name).removeObject(objs[3].Name) ### #sleep del objs objs = GetListOfObjects(FreeCAD, doc) FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name, objs[1].Name) objs = GetListOfObjects(FreeCAD, doc) FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name, objs[1].Name) else: Color_Objects(Gui, objs[0], body_color) Color_Objects(Gui, objs[1], pins_color) Color_Objects(Gui, objs[2], marking_color) col_body = Gui.ActiveDocument.getObject(objs[0].Name).DiffuseColor[0] col_pin = Gui.ActiveDocument.getObject(objs[1].Name).DiffuseColor[0] col_mark = Gui.ActiveDocument.getObject(objs[2].Name).DiffuseColor[0] material_substitutions = { col_body[:-1]: body_color_key, col_pin[:-1]: pins_color_key, col_mark[:-1]: marking_color_key } #expVRML.say(material_substitutions) if (color_pin_mark == True) and (place_pinMark == True): CutObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name, objs[2].Name) else: #removing pinMark App.getDocument(doc.Name).removeObject(objs[2].Name) ### #sleep del objs objs = GetListOfObjects(FreeCAD, doc) FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name, objs[1].Name) ## objs[0].Label='body' ## objs[1].Label='pins' ## objs[2].Label='mark' ### ## print objs[0].Name, objs[1].Name, objs[2].Name ## sleep doc.Label = CheckedModelName objs = GetListOfObjects(FreeCAD, doc) objs[0].Label = CheckedModelName restore_Main_Tools() #rotate if required if (params.rotation != 0): rot = params.rotation z_RotateObject(doc, rot) #out_dir=destination_dir+params.dest_dir_prefix+'/' script_dir = os.path.dirname(os.path.realpath(__file__)) #models_dir=script_dir+"/../_3Dmodels" #expVRML.say(models_dir) if len(params.dest_dir_prefix) >= 1: out_dir = models_dir + destination_dir + os.sep + params.dest_dir_prefix else: out_dir = models_dir + destination_dir if not os.path.exists(out_dir): os.makedirs(out_dir) #out_dir="./generated_qfp/" # export STEP model exportSTEP(doc, ModelName, out_dir) global LIST_license if LIST_license[0] == "": LIST_license = Lic.LIST_int_license LIST_license.append("") Lic.addLicenseToStep(out_dir+'/', ModelName+".step", LIST_license,\ STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licOrg, STR_licPreProc) # scale and export Vrml model scale = 1 / 2.54 #exportVRML(doc,ModelName,scale,out_dir) objs = GetListOfObjects(FreeCAD, doc) export_objects, used_color_keys = expVRML.determineColors( Gui, objs, material_substitutions) export_file_name = out_dir + os.sep + ModelName + '.wrl' colored_meshes = expVRML.getColoredMesh(Gui, export_objects, scale) #expVRML.writeVRMLFile added creaeAngle expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys, LIST_license, 0.9) # Save the doc in Native FC format #saveFCdoc(App, Gui, doc, ModelName,out_dir) #display BBox #FreeCADGui.ActiveDocument.getObject("Part__Feature").BoundingBox = True if footprints_dir is not None and os.path.isdir( footprints_dir ) and not save_memory and not check_Model: #it doesn't make sense to import the footprint right before we close the file. #expVRML.say (ModelName) #stop sys.argv = [ "fc", "dummy", footprints_dir + os.sep + ModelName, "savememory" ] #setup = get_setup_file() # << You need the parentheses expVRML.say(sys.argv[2]) if not ksu_present: try: import kicadStepUptools ksu_present = True expVRML.say("ksu present!") kicadStepUptools.KSUWidget.close() #kicadStepUptools.KSUWidget.setWindowState(QtCore.Qt.WindowMinimized) #kicadStepUptools.KSUWidget.destroy() #for i in QtGui.qApp.topLevelWidgets(): # if i.objectName() == "kicadStepUp": # i.deleteLater() kicadStepUptools.KSUWidget.close() except: ksu_present = False expVRML.say("ksu not present") else: kicadStepUptools.KSUWidget.close() reload(kicadStepUptools) kicadStepUptools.KSUWidget.close() #kicadStepUptools.KSUWidget.setWindowState(QtCore.Qt.WindowMinimized) #kicadStepUptools.KSUWidget.destroy() #FreeCADGui.insert(u"C:\Temp\FCAD_sg\QFN_packages\QFN-12-1EP_3x3mm_Pitch0_5mm.kicad_mod") #FreeCADGui.insert(script_dir+os.sep+"ModelName.kicad_mod") if save_memory == False: Gui.activateWorkbench("PartWorkbench") Gui.SendMsgToActiveView("ViewFit") Gui.activeDocument().activeView().viewBottom() #Gui.activeDocument().activeView().viewAxometric() saveFCdoc(App, Gui, doc, ModelName, out_dir) if save_memory == True or check_Model == True: doc = FreeCAD.ActiveDocument print("closing: {}".format(doc.Name)) FreeCAD.closeDocument(doc.Name) if check_Model == True: step_path = out_dir + '/' + ModelName + ".step" runGeometryCheck(App, Gui, step_path, log, ModelName, save_memory=save_memory)
def make_3D_model(models_dir, model_class, modelName): LIST_license = [ "", ] CheckedmodelName = modelName.replace('.', '').replace('-', '_').replace( '(', '').replace(')', '') Newdoc = App.newDocument(CheckedmodelName) App.setActiveDocument(CheckedmodelName) Gui.ActiveDocument = Gui.getDocument(CheckedmodelName) destination_dir = model_class.get_dest_3D_dir() material_substitutions = model_class.make_3D_model(modelName) doc = FreeCAD.ActiveDocument doc.Label = CheckedmodelName objs = GetListOfObjects(FreeCAD, doc) objs[0].Label = CheckedmodelName restore_Main_Tools() script_dir = os.path.dirname(os.path.realpath(__file__)) expVRML.say(models_dir) out_dir = models_dir + os.sep + destination_dir if not os.path.exists(out_dir): os.makedirs(out_dir) exportSTEP(doc, modelName, out_dir) if LIST_license[0] == "": LIST_license = Lic.LIST_int_license LIST_license.append("") Lic.addLicenseToStep(out_dir+'/', modelName+".step", LIST_license,\ STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licOrg, STR_licPreProc) # scale and export Vrml model scale = 1 / 2.54 #exportVRML(doc,modelName,scale,out_dir) del objs objs = GetListOfObjects(FreeCAD, doc) expVRML.say( "######################################################################" ) expVRML.say(objs) expVRML.say( "######################################################################" ) export_objects, used_color_keys = expVRML.determineColors( Gui, objs, material_substitutions) export_file_name = out_dir + os.sep + modelName + '.wrl' colored_meshes = expVRML.getColoredMesh(Gui, export_objects, scale) #expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys)# , LIST_license expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys, LIST_license) #scale=0.3937001 #exportVRML(doc,modelName,scale,out_dir) # Save the doc in Native FC format saveFCdoc(App, Gui, doc, modelName, out_dir) #display BBox Gui.activateWorkbench("PartWorkbench") Gui.SendMsgToActiveView("ViewFit") Gui.activeDocument().activeView().viewAxometric()
import Part import Drawing import sys #from termcolor import colored, cprint from PySide import QtGui, QtCore import cPickle import SearchAgent import begin import myWedget_Ui import time os.chdir("/usr/lib/freecad") App = FreeCAD App.newDocument() v = FreeCADGui.activeDocument().activeView() useditems = [] existitem = [] restartcontrol = [] gobackcontrol = [] correctnum = [] completetrain = 0 log = [] Board = [] uniontime=2 commontime=1 cuttime=1 uniontime_2=1 commontime_2=2
def make_3D_model(models_dir, model_class, modelName): r"""Creates a 3D model and exports it to STEO and VRML. :param models_dir: directory name for STEP and VRML 3D model file export :type models_dir: ``string`` :param model_class: Class containing functions and parameter to generate the 3D model :type model_class: ``class`` :param modelName: The KiCad file name of the 3D model. :type modelName: ``string`` """ if not model_class.isValidModel (): FreeCAD.Console.PrintMessage("Model: " + modelName + ' has invalid parameter and was skipped.\r\n') return LIST_license = ["",] CheckedmodelName = modelName.replace('.', '').replace('-', '_').replace('(', '').replace(')', '') Newdoc = App.newDocument(CheckedmodelName) App.setActiveDocument(CheckedmodelName) Gui.ActiveDocument=Gui.getDocument(CheckedmodelName) destination_dir = model_class.get_dest_3D_dir() material_substitutions = model_class.make_3D_model() doc = FreeCAD.ActiveDocument doc.Label = CheckedmodelName objs=GetListOfObjects(FreeCAD, doc) objs[0].Label = CheckedmodelName restore_Main_Tools() script_dir=os.path.dirname(os.path.realpath(__file__)) expVRML.say(models_dir) out_dir=models_dir+os.sep+destination_dir if not os.path.exists(out_dir): os.makedirs(out_dir) exportSTEP(doc, modelName, out_dir) if LIST_license[0]=="": LIST_license=Lic.LIST_int_license LIST_license.append("") Lic.addLicenseToStep(out_dir+'/', modelName+".step", LIST_license,\ STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licOrg, STR_licPreProc) # scale and export Vrml model scale=1/2.54 #exportVRML(doc,modelName,scale,out_dir) del objs objs=GetListOfObjects(FreeCAD, doc) expVRML.say("######################################################################") expVRML.say(objs) expVRML.say("######################################################################") export_objects, used_color_keys = expVRML.determineColors(Gui, objs, material_substitutions) export_file_name=out_dir + os.sep + modelName + '.wrl' colored_meshes = expVRML.getColoredMesh(Gui, export_objects , scale) #expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys)# , LIST_license expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys, LIST_license) #scale=0.3937001 #exportVRML(doc,modelName,scale,out_dir) # Save the doc in Native FC format saveFCdoc(App, Gui, doc, modelName,out_dir) #display BBox Gui.activateWorkbench("PartWorkbench") Gui.SendMsgToActiveView("ViewFit") Gui.activeDocument().activeView().viewAxometric()
def MakeHeader(n, model, all_params): global formerDOC global LIST_license ModelName = model.replace('yy', "{n:02}".format(n=n)) full_path = os.path.realpath(__file__) expVRML.say(full_path) scriptdir = os.path.dirname(os.path.realpath(__file__)) expVRML.say(scriptdir) sub_path = full_path.split(scriptdir) expVRML.say(sub_path) sub_dir_name = full_path.split(os.sep)[-2] expVRML.say(sub_dir_name) sub_path = full_path.split(sub_dir_name)[0] expVRML.say(sub_path) models_dir = sub_path + "_3Dmodels" script_dir = os.path.dirname(os.path.realpath(__file__)) #models_dir=script_dir+"/../_3Dmodels" expVRML.say(models_dir) out_dir = models_dir + all_params[model]['output_directory'] if not os.path.exists(out_dir): os.makedirs(out_dir) CheckedModelName = ModelName.replace('.', '').replace('-', '_').replace( '(', '').replace(')', '') newdoc = App.newDocument(CheckedModelName) App.setActiveDocument(CheckedModelName) App.ActiveDocument = App.getDocument(CheckedModelName) Gui.ActiveDocument = Gui.getDocument(CheckedModelName) header_type = all_params[model]['type'] pitch = all_params[model]['pitch'] rows = all_params[model]['rows'] base_width = all_params[model]['base_width'] base_height = all_params[model]['base_height'] base_chamfer = all_params[model]['base_chamfer'] pin_width = all_params[model]['pin_width'] pin_length_above_base = all_params[model]['pin_length_above_base'] pin_end_chamfer = all_params[model]['pin_end_chamfer'] rotation = all_params[model]['rotation'] if base_chamfer == 'auto': base_chamfer = pitch / 10. if pin_end_chamfer == 'auto': pin_end_chamfer = pin_width / 4. if header_type == 'Vertical_THT': pin_length_below_board = all_params[model]['pin_length_below_board'] base = make_Vertical_THT_base(n, pitch, rows, base_width, base_height, base_chamfer) pins = make_Vertical_THT_pins(n, pitch, rows, pin_length_above_base, pin_length_below_board, base_height, pin_width, pin_end_chamfer) elif header_type == 'Horizontal_THT': pin_length_below_board = all_params[model]['pin_length_below_board'] base_x_offset = all_params[model]['base_x_offset'] base = make_Horizontal_THT_base(n, pitch, rows, base_width, base_height, base_x_offset, base_chamfer) pins = make_Horizontal_THT_pins(n, pitch, rows, pin_length_above_base, pin_length_below_board, base_height, base_width, pin_width, pin_end_chamfer, base_x_offset) elif header_type == 'Vertical_SMD': pin_length_horizontal = all_params[model]['pin_length_horizontal'] base_z_offset = all_params[model]['base_z_offset'] if rows == 1: pin_1_start = all_params[model]['pin_1_start'] else: pin_1_start = None pins = make_Vertical_SMD_pins(n, pitch, rows, pin_length_above_base, pin_length_horizontal, base_height, base_width, pin_width, pin_end_chamfer, base_z_offset, pin_1_start) base = make_Vertical_SMD_base(n, pitch, base_width, base_height, base_chamfer, base_z_offset) else: print 'Header type: ' print header_type print ' is not recognized, please check parameters' stop show(base) show(pins) doc = FreeCAD.ActiveDocument objs = GetListOfObjects(FreeCAD, doc) Color_Objects(Gui, objs[0], body_color) Color_Objects(Gui, objs[1], pins_color) #Color_Objects(Gui,objs[2],marking_color) col_body = Gui.ActiveDocument.getObject(objs[0].Name).DiffuseColor[0] col_pin = Gui.ActiveDocument.getObject(objs[1].Name).DiffuseColor[0] #col_mark=Gui.ActiveDocument.getObject(objs[2].Name).DiffuseColor[0] material_substitutions = { col_body[:-1]: body_color_key, col_pin[:-1]: pins_color_key, #col_mark[:-1]:marking_color_key } expVRML.say(material_substitutions) #objs=GetListOfObjects(FreeCAD, doc) FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name, objs[1].Name) doc.Label = CheckedModelName objs = GetListOfObjects(FreeCAD, doc) objs[0].Label = CheckedModelName restore_Main_Tools() if (rotation != 0): z_RotateObject(doc, rotation) #out_dir = models_dir+"/generated_pinheaders" doc.Label = CheckedModelName #save the STEP file exportSTEP(doc, ModelName, out_dir) if LIST_license[0] == "": LIST_license = Lic.LIST_int_license LIST_license.append("") Lic.addLicenseToStep(out_dir+'/', ModelName+".step", LIST_license,\ STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licOrg, STR_licPreProc) # scale and export Vrml model scale = 1 / 2.54 #exportVRML(doc,ModelName,scale,out_dir) objs = GetListOfObjects(FreeCAD, doc) expVRML.say( "######################################################################" ) expVRML.say(objs) expVRML.say( "######################################################################" ) export_objects, used_color_keys = expVRML.determineColors( Gui, objs, material_substitutions) export_file_name = out_dir + os.sep + ModelName + '.wrl' colored_meshes = expVRML.getColoredMesh(Gui, export_objects, scale) expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys, LIST_license) #save the VRML file #scale=0.3937001 #exportVRML(doc,name,scale,out_dir) if save_memory == False: Gui.SendMsgToActiveView("ViewFit") Gui.activeDocument().activeView().viewAxometric() # Save the doc in Native FC format saveFCdoc(App, Gui, doc, ModelName, out_dir, False) check_Model = True if save_memory == True or check_Model == True: doc = FreeCAD.ActiveDocument FreeCAD.closeDocument(doc.Name) step_path = os.path.join(out_dir, ModelName + u'.step') if check_Model == True: #ImportGui.insert(step_path,ModelName) ImportGui.open(step_path) docu = FreeCAD.ActiveDocument if cq_cad_tools.checkUnion(docu) == True: FreeCAD.Console.PrintMessage('step file is correctly Unioned\n') else: FreeCAD.Console.PrintError('step file is NOT Unioned\n') stop FC_majorV = int(FreeCAD.Version()[0]) FC_minorV = int(FreeCAD.Version()[1]) if FC_majorV == 0 and FC_minorV >= 17: for o in docu.Objects: if hasattr(o, 'Shape'): chks = cq_cad_tools.checkBOP(o.Shape) print 'chks ', chks print cq_cad_tools.mk_string(o.Label) if chks != True: msg = 'shape \'' + o.Name + '\' \'' + cq_cad_tools.mk_string( o.Label) + '\' is INVALID!\n' FreeCAD.Console.PrintError(msg) FreeCAD.Console.PrintWarning(chks[0]) stop else: msg = 'shape \'' + o.Name + '\' \'' + cq_cad_tools.mk_string( o.Label) + '\' is valid\n' FreeCAD.Console.PrintMessage(msg) else: FreeCAD.Console.PrintError('BOP check requires FC 0.17+\n') # Save the doc in Native FC format saveFCdoc(App, Gui, docu, ModelName, out_dir, False) doc = FreeCAD.ActiveDocument FreeCAD.closeDocument(doc.Name) return 0
def make_3D_model(models_dir, variant): LIST_license = [ "", ] modelName = all_params[variant].modelName CheckedmodelName = modelName.replace('.', '').replace('-', '_').replace( '(', '').replace(')', '') Newdoc = App.newDocument(CheckedmodelName) App.setActiveDocument(CheckedmodelName) Gui.ActiveDocument = Gui.getDocument(CheckedmodelName) case = make_case(all_params[variant]) casetop = make_case_top(all_params[variant]) if (all_params[variant].pintype == CASE_THT_TYPE): pins = make_pins_tht(all_params[variant]) if (all_params[variant].pintype == CASE_THT_N_TYPE): pins = make_pins_tht_n(all_params[variant]) if (all_params[variant].pintype == CASE_SMD_TYPE): pins = make_pins_smd(all_params[variant]) show(case) show(casetop) show(pins) #show(pinmark) #stop doc = FreeCAD.ActiveDocument objs = GetListOfObjects(FreeCAD, doc) body_color_key = all_params[variant].body_color_key body_top_color_key = all_params[variant].body_top_color_key pin_color_key = all_params[variant].pin_color_key body_color = shaderColors.named_colors[body_color_key].getDiffuseFloat() body_top_color = shaderColors.named_colors[ body_top_color_key].getDiffuseFloat() pin_color = shaderColors.named_colors[pin_color_key].getDiffuseFloat() Color_Objects(Gui, objs[0], body_color) Color_Objects(Gui, objs[1], body_top_color) Color_Objects(Gui, objs[2], pin_color) col_body = Gui.ActiveDocument.getObject(objs[0].Name).DiffuseColor[0] col_body_top = Gui.ActiveDocument.getObject(objs[1].Name).DiffuseColor[0] col_pin = Gui.ActiveDocument.getObject(objs[2].Name).DiffuseColor[0] material_substitutions = { col_body[:-1]: body_color_key, col_body_top[:-1]: body_top_color_key, col_pin[:-1]: pin_color_key } expVRML.say(material_substitutions) while len(objs) > 1: FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name, objs[1].Name) del objs objs = GetListOfObjects(FreeCAD, doc) doc.Label = CheckedmodelName del objs objs = GetListOfObjects(FreeCAD, doc) objs[0].Label = CheckedmodelName restore_Main_Tools() script_dir = os.path.dirname(os.path.realpath(__file__)) expVRML.say(models_dir) out_dir = models_dir + destination_dir if not os.path.exists(out_dir): os.makedirs(out_dir) exportSTEP(doc, modelName, out_dir) if LIST_license[0] == "": LIST_license = Lic.LIST_int_license LIST_license.append("") Lic.addLicenseToStep(out_dir+'/', modelName+".step", LIST_license,\ STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licOrg, STR_licPreProc) # scale and export Vrml model scale = 1 / 2.54 #exportVRML(doc,modelName,scale,out_dir) del objs objs = GetListOfObjects(FreeCAD, doc) expVRML.say( "######################################################################" ) expVRML.say(objs) expVRML.say( "######################################################################" ) export_objects, used_color_keys = expVRML.determineColors( Gui, objs, material_substitutions) export_file_name = out_dir + os.sep + modelName + '.wrl' colored_meshes = expVRML.getColoredMesh(Gui, export_objects, scale) #expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys)# , LIST_license expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys, LIST_license) #scale=0.3937001 #exportVRML(doc,modelName,scale,out_dir) # Save the doc in Native FC format saveFCdoc(App, Gui, doc, modelName, out_dir) #display BBox Gui.activateWorkbench("PartWorkbench") Gui.SendMsgToActiveView("ViewFit") Gui.activeDocument().activeView().viewAxometric()
import FreeCAD as App import FreeCADGui as Gui import Part, PartGui import Cloud import time print "doc\n" doc = FreeCAD.newDocument("titi") #console.log(doc) print "doc" Gui.SendMsgToActiveView("ViewFit") myView = Gui.activeDocument().activeView() Gui.runCommand('Std_PerspectiveCamera', 1) Gui.activeDocument().activeView().setCameraType("Perspective") box = doc.addObject("Part::Box", "myBox") box.Height = 4 box.Width = 2 doc.recompute() #Cloud.cloudurl(u"https://justyour.parts") #Cloud.cloudtcpport(u"443") #Cloud.cloudaccesskey(u"") #Cloud.cloudsecretkey(u"") #Cloud.cloudrestore(u"test") #box = doc.addObject("Part::Box","myBox") #box.Height=4 #box.Width=2 #doc.recompute() from pivy import coin pos3 = FreeCAD.Vector(0, 0, 0) camera = FreeCADGui.ActiveDocument.ActiveView.getCameraNode()
def print_export(objSelect): show_message = True PlaceOld = objSelect.Placement #_________Motor_Holder_________ if 'motorholder' in objSelect.Name or 'nema_holder' in objSelect.Name: pos = objSelect.Placement.Base rot = FreeCAD.Rotation(FreeCAD.Vector(0, 1, 0), 180) centre = FreeCAD.Vector(0, 0, 0) #_________Idler_Tensioner_________ elif 'idler_tensioner' in objSelect.Name: pos = objSelect.Placement.Base rot = FreeCAD.Rotation(FreeCAD.Vector(0, 1, 0), 90) centre = FreeCAD.Vector(0, 0, 0) #_________Tensioner_Holder_________ elif 'tensioner_holder' in objSelect.Name: pos = objSelect.Placement.Base rot = FreeCAD.Rotation(FreeCAD.Vector(1, 0, 0), -90) centre = FreeCAD.Vector(0, 0, 0) #_________Filter_Holder_________ elif 'filter_holder' in objSelect.Name: pos = objSelect.Placement.Base rot = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 0), 0) centre = FreeCAD.Vector(0, 0, 0) #_________Nema_Holder_________ #elif 'nema_holder' in objSelect.Name: # pos = objSelect.Placement.Base # rot = FreeCAD.Rotation(FreeCAD.Vector(0,1,0),180) # centre = FreeCAD.Vector(0,0,0) #_________Linbearhouse_________ elif 'linbear' in objSelect.Name: if 'top' in objSelect.Name: pos = objSelect.Placement.Base rot = FreeCAD.Rotation(FreeCAD.Vector(0, 1, 0), 180) centre = FreeCAD.Vector(0, 0, 0) elif 'bot' in objSelect.Name: pos = objSelect.Placement.Base rot = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 0), 0) centre = FreeCAD.Vector(0, 0, 0) else: message = QtGui.QMessageBox() message.setText('Error') message.setStandardButtons(QtGui.QMessageBox.Ok) message.setDefaultButton(QtGui.QMessageBox.Ok) message.exec_() #_________Bracket_________ elif 'bracket' in objSelect.Name: pos = objSelect.Placement.Base rot = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 0), 0) centre = FreeCAD.Vector(0, 0, 0) #_________Bracket_3_________ #elif bracket3 in objSelect.Name: # pos = objSelect.Placement.Base # rot = FreeCAD.Rotation(FreeCAD.Vector(0,0,0),0) # centre = FreeCAD.Vector(0,0,0) #_________Bracket_Twin_________ #elif bracket_twin in objSelect.Name: # pos = objSelect.Placement.Base # rot = FreeCAD.Rotation(FreeCAD.Vector(0,0,0),0) # centre = FreeCAD.Vector(0,0,0) #_________Shaft_________ elif 'shaft' in objSelect.Name: pos = objSelect.Placement.Base rot = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 0), 0) centre = FreeCAD.Vector(0, 0, 0) #_________IdlepulleyHold_________ elif 'idlepulleyhold' in objSelect.Name: pos = objSelect.Placement.Base rot = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 0), 0) centre = FreeCAD.Vector(0, 0, 0) #_________Simple_End_Stop_Holder_________ elif 'simple_endstop_holder' in objSelect.Name: pos = objSelect.Placement.Base rot = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 0), 0) centre = FreeCAD.Vector(0, 0, 0) #_________Stop_Holder_________ elif 'stop_holder' in objSelect.Name: pos = objSelect.Placement.Base rot = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 0), 0) centre = FreeCAD.Vector(0, 0, 0) #_________Belt_Clamp_________ elif 'belt_clamp' in objSelect.Name: pos = objSelect.Placement.Base rot = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 0), 0) centre = FreeCAD.Vector(0, 0, 0) #_________Sensor_Holder_________ elif 'sensorholder' in objSelect.Name: pos = objSelect.Placement.Base rot = FreeCAD.Rotation(FreeCAD.Vector(0, 1, 0), 90) centre = FreeCAD.Vector(0, 0, 0) #_________Not_Name_________ else: message = QtGui.QMessageBox() message.setText('This object is not a workbench object.\n') message.setStandardButtons(QtGui.QMessageBox.Ok) message.setDefaultButton(QtGui.QMessageBox.Ok) message.exec_() show_message = False ####################################################### #_________Message_And_Change_________ if show_message == True: """message = QtGui.QMessageBox() message.setText("You select " + objSelect.Name + " to change to print position and export.\n") message.setStandardButtons(QtGui.QMessageBox.Ok) message.setDefaultButton(QtGui.QMessageBox.Ok) message.exec_()""" objSelect.Placement = FreeCAD.Placement(pos, rot, centre) FreeCADGui.activeDocument().activeView().viewAxonometric() FreeCADGui.SendMsgToActiveView("ViewFit") #_________EXPORT_________ #Open the file explorer to set the folder gui = QtGui.QWidget() folderName = QtGui.QFileDialog.getExistingDirectory( gui, "Select directory", "c:/", QtGui.QFileDialog.ShowDirsOnly) # take the path and export the object stlFileName = str(folderName) + "/" + objSelect.Name + ".stl" mesh_shp = MeshPart.meshFromShape(objSelect.Shape, LinearDeflection=kparts.LIN_DEFL, AngularDeflection=kparts.ANG_DEFL) mesh_shp.write(stlFileName) del mesh_shp objSelect.Placement = PlaceOld message = QtGui.QMessageBox() message.setText("You export " + objSelect.Name + " in " + folderName) message.setStandardButtons(QtGui.QMessageBox.Ok) message.setDefaultButton(QtGui.QMessageBox.Ok) message.exec_()
def generateConstraintAreas(self, areas, doc, layerNumber, grp, layerName, layerColor, layerTransparent): typeL = PCBconf.PCBconstraintAreas[PCBconf.softLayers[ self.databaseType][layerNumber][1]][1] mainGroup = doc.addObject("App::DocumentObjectGroup", layerName) grp.addObject(mainGroup) for i in areas: ser = doc.addObject('Sketcher::SketchObject', "Sketch_{0}".format(layerName)) ser.ViewObject.Visibility = False # if i[0] == 'rect': try: height = i[5] except: height = 0 x1 = i[1] y1 = i[2] x2 = i[3] y2 = i[2] x3 = i[3] y3 = i[4] x4 = i[1] y4 = i[4] try: if i[6] != 0: xs = (i[1] + i[3]) / 2. ys = (i[2] + i[4]) / 2. mat = mathFunctions() (x1, y1) = mat.obrocPunkt2([x1, y1], [xs, ys], i[6]) (x2, y2) = mat.obrocPunkt2([x2, y2], [xs, ys], i[6]) (x3, y3) = mat.obrocPunkt2([x3, y3], [xs, ys], i[6]) (x4, y4) = mat.obrocPunkt2([x4, y4], [xs, ys], i[6]) except: pass ser.addGeometry( Part.Line(FreeCAD.Vector(x1, y1, 0), FreeCAD.Vector(x2, y2, 0))) ser.addGeometry( Part.Line(FreeCAD.Vector(x2, y2, 0), FreeCAD.Vector(x3, y3, 0))) ser.addGeometry( Part.Line(FreeCAD.Vector(x3, y3, 0), FreeCAD.Vector(x4, y4, 0))) ser.addGeometry( Part.Line(FreeCAD.Vector(x4, y4, 0), FreeCAD.Vector(x1, y1, 0))) elif i[0] == 'circle': try: height = i[5] except: height = 0 if i[4] == 0: ser.addGeometry( Part.Circle(FreeCAD.Vector(i[1], i[2]), FreeCAD.Vector(0, 0, 1), i[3])) else: ser.addGeometry( Part.Circle(FreeCAD.Vector(i[1], i[2]), FreeCAD.Vector(0, 0, 1), i[3] + i[4] / 2)) ser.addGeometry( Part.Circle(FreeCAD.Vector(i[1], i[2]), FreeCAD.Vector(0, 0, 1), i[3] - i[4] / 2)) elif i[0] == 'polygon': try: height = i[2] except: height = 0 for j in i[1]: if j[0] == 'Line': ser.addGeometry( Part.Line(FreeCAD.Vector(j[1], j[2], 0), FreeCAD.Vector(j[3], j[4], 0))) elif j[0] == 'Arc': x1 = j[1] y1 = j[2] x2 = j[3] y2 = j[4] [x3, y3] = self.arcMidPoint([x2, y2], [x1, y1], j[5]) arc = Part.Arc(FreeCAD.Vector(x1, y1, 0.0), FreeCAD.Vector(x3, y3, 0.0), FreeCAD.Vector(x2, y2, 0.0)) ser.addGeometry(self.Draft2Sketch(arc, ser)) # a = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", layerName + "_{0}".format(0)) layerObj = constraintAreaObject(a, typeL) a.Base = ser if height != 0: a.Height = height viewProviderConstraintAreaObject(a.ViewObject) mainGroup.addObject(a) FreeCADGui.activeDocument().getObject( a.Name).ShapeColor = layerColor FreeCADGui.activeDocument().getObject( a.Name).Transparency = layerTransparent FreeCADGui.activeDocument().getObject(a.Name).DisplayMode = 1 self.updateView()
#*************************************************************************** #* * #* Copyright (c) 2012 * #* Yorik van Havre <*****@*****.**> * #* * #* This program is free software; you can redistribute it and/or modify * #* it under the terms of the GNU Lesser General Public License (LGPL) * #* as published by the Free Software Foundation; either version 2 of * #* the License, or (at your option) any later version. * #* for detail see the LICENCE text file. * #* * #* This program is distributed in the hope that it will be useful, * #* but WITHOUT ANY WARRANTY; without even the implied warranty of * #* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * #* GNU Library General Public License for more details. * #* * #* You should have received a copy of the GNU Library General Public * #* License along with this program; if not, write to the Free Software * #* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * #* USA * #* * #*************************************************************************** import FreeCAD, FreeCADGui FreeCAD.open(FreeCAD.getResourceDir() + "examples/ArchDetail.FCStd") FreeCADGui.activeDocument().sendMsgToViews("ViewFit")
def export_one_part(modul, variant, with_plug=False): if not variant in modul.all_params: FreeCAD.Console.PrintMessage("Parameters for %s doesn't exist in 'M.all_params', skipping." % variant) return destination_dir="Connectors_Phoenix.3dshapes" if with_plug: destination_dir="Connectors_Phoenix__with_plug.3dshapes" ModelName = variant ModelName = ModelName.replace(".","_") FileName = modul.all_params[variant].file_name Newdoc = FreeCAD.newDocument(ModelName) App.setActiveDocument(ModelName) App.ActiveDocument=App.getDocument(ModelName) Gui.ActiveDocument=Gui.getDocument(ModelName) #App.setActiveDocument(ModelName) #Gui.ActiveDocument=Gui.getDocument(ModelName) (pins, body, insert, mount_screw, plug, plug_screws) = modul.generate_part(variant, with_plug) color_attr = body_color + (0,) show(body, color_attr) color_attr = pins_color + (0,) show(pins, color_attr) if insert is not None: color_attr = insert_color + (0,) show(insert, color_attr) if mount_screw is not None: color_attr = screw_color + (0,) show(mount_screw, color_attr) if plug is not None: color_attr = body_color + (0,) show(plug, color_attr) color_attr = screw_color + (0,) show(plug_screws, color_attr) doc = FreeCAD.ActiveDocument doc.Label=ModelName objs=FreeCAD.ActiveDocument.Objects FreeCAD.Console.PrintMessage(objs) i=0 objs[i].Label = ModelName + "__body" i+=1 objs[i].Label = ModelName + "__pins" i+=1 if insert is not None: objs[i].Label = ModelName + "__thread_insert" i+=1 if mount_screw is not None: objs[i].Label = ModelName + "__mount_screw" i+=1 if plug is not None: objs[i].Label = ModelName + "__plug" i+=1 objs[i].Label = ModelName + "__plug_screws" restore_Main_Tools() out_dir=destination_dir if not os.path.exists(out_dir): os.makedirs(out_dir) used_color_keys = [body_color_key, pins_color_key] export_file_name=destination_dir+os.sep+FileName+'.wrl' export_objects = [] i=0 export_objects.append(expVRML.exportObject(freecad_object = objs[i], shape_color=body_color_key, face_colors=None)) i+=1 export_objects.append(expVRML.exportObject(freecad_object = objs[i], shape_color=pins_color_key, face_colors=None)) i+=1 if insert is not None: export_objects.append(expVRML.exportObject(freecad_object = objs[i], shape_color=insert_color_key, face_colors=None)) used_color_keys.append(insert_color_key) i+=1 if mount_screw is not None: export_objects.append(expVRML.exportObject(freecad_object = objs[i], shape_color=screw_color_key, face_colors=None)) used_color_keys.append(screw_color_key) i+=1 if plug is not None: export_objects.append(expVRML.exportObject(freecad_object = objs[i], shape_color=body_color_key, face_colors=None)) i+=1 export_objects.append(expVRML.exportObject(freecad_object = objs[i], shape_color=screw_color_key, face_colors=None)) scale=1/2.54 colored_meshes = expVRML.getColoredMesh(Gui, export_objects , scale) expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys, LIST_license) fusion = multiFuseObjs_wColors(FreeCAD, FreeCADGui, ModelName, objs, keepOriginals=True) exportSTEP(doc,FileName,out_dir,fusion) L.addLicenseToStep(out_dir+'/', FileName+".step", LIST_license,\ STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licPreProc) saveFCdoc(App, Gui, doc, FileName,out_dir) FreeCAD.activeDocument().recompute() # FreeCADGui.activateWorkbench("PartWorkbench") FreeCADGui.SendMsgToActiveView("ViewFit") FreeCADGui.activeDocument().activeView().viewAxometric()
def addSelection( self, docName, objName, sub, pnt ): debugPrint(4,'addSelection: docName,objName,sub = %s,%s,%s' % (docName, objName, sub)) FreeCADGui.Selection.removeObserver(self) obj = FreeCAD.ActiveDocument.getObject(objName) view = FreeCADGui.activeDocument().activeView() PartMover( view, obj )
def draw(self): try: Gui.getDocument(self.name) Gui.getDocument(self.name).resetEdit() App.getDocument(self.name).recompute() App.closeDocument(self.name) App.setActiveDocument("") App.ActiveDocument=None Gui.ActiveDocument=None except: pass #make document App.newDocument(self.name) App.setActiveDocument(self.name) App.ActiveDocument=App.getDocument(self.name) Gui.ActiveDocument=Gui.getDocument(self.name) #extrude crossBarTop uf.extrudeFrameMember(self.name, gv.crossBarLength) if gv.zMotorMountLocation == "Bottom": return #Make Holes for zMotorMount plates #Sketch points p1x = 0 p1y = 0 p2x = p1x p2y = gv.frameWidth/2+gv.zRodZScrewDist-gv.zMotorMountPlateWidth/4 p3x = p1x p3y = gv.frameWidth/2+gv.zRodZScrewDist+gv.zMotorMountPlateWidth/4 p4x = p1x p4y = gv.crossBarLength - (gv.frameWidth/2+gv.zRodZScrewDist+gv.zMotorMountPlateWidth/4) p5x = p1x p5y = gv.crossBarLength - (gv.frameWidth/2+gv.zRodZScrewDist-gv.zMotorMountPlateWidth/4) p6x = p1x p6y = gv.crossBarLength #Make Sketch App.activeDocument().addObject('Sketcher::SketchObject','Sketch001') App.activeDocument().Sketch001.Support = (App.ActiveDocument.Pad,["Face2"]) App.activeDocument().recompute() # Gui.activeDocument().setEdit('Sketch001') App.ActiveDocument.Sketch001.addExternal("Pad","Edge7") App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addGeometry(Part.Line(App.Vector(p1x,p1y,0),App.Vector(p2x,p2y,0))) App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Coincident',-1,1,0,1)) App.ActiveDocument.recompute() App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Vertical',0)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addGeometry(Part.Line(App.Vector(p2x,p2y,0),App.Vector(p3x,p3y,0))) App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Coincident',0,2,1,1)) App.ActiveDocument.recompute() App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Vertical',1)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addGeometry(Part.Line(App.Vector(p3x,p3y,0),App.Vector(p4x,p4y,0))) App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Coincident',1,2,2,1)) App.ActiveDocument.recompute() App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Vertical',2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addGeometry(Part.Line(App.Vector(p4x,p4y,0),App.Vector(p5x,p5y,0))) App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Coincident',2,2,3,1)) App.ActiveDocument.recompute() App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Vertical',3)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addGeometry(Part.Line(App.Vector(p5x,p5y,0),App.Vector(p6x,p6y,0))) App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Coincident',3,2,4,1)) App.ActiveDocument.recompute() App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('PointOnObject',4,2,-3)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Vertical',4)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Equal',1,3)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Equal',4,0)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.toggleConstruction(0) App.ActiveDocument.Sketch001.toggleConstruction(1) App.ActiveDocument.Sketch001.toggleConstruction(2) App.ActiveDocument.Sketch001.toggleConstruction(3) App.ActiveDocument.Sketch001.toggleConstruction(4) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addGeometry(Part.Circle(App.Vector(p2x,p2y,0),App.Vector(0,0,1),gv.mountToFrameDia/2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Coincident',5,3,0,2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addGeometry(Part.Circle(App.Vector(p3x,p3y,0),App.Vector(0,0,1),gv.mountToFrameDia/2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Coincident',6,3,1,2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addGeometry(Part.Circle(App.Vector(p4x,p4y,0),App.Vector(0,0,1),gv.mountToFrameDia/2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Coincident',7,3,2,2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addGeometry(Part.Circle(App.Vector(p5x,p5y,0),App.Vector(0,0,1),gv.mountToFrameDia/2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Coincident',8,3,3,2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Equal',8,7)) App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Equal',7,6)) App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Equal',6,5)) App.ActiveDocument.recompute() #Add Dimensions App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('Radius',8,gv.mountToFrameDia/2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('DistanceY',3,gv.zMotorMountPlateWidth/2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint(Sketcher.Constraint('DistanceY',4,p2y)) App.ActiveDocument.recompute() # Gui.getDocument(self.name).resetEdit() App.getDocument(self.name).recompute() #Cut holes through All App.activeDocument().addObject("PartDesign::Pocket","Pocket") App.activeDocument().Pocket.Sketch = App.activeDocument().Sketch001 App.activeDocument().Pocket.Length = 5.0 App.ActiveDocument.recompute() Gui.activeDocument().hide("Sketch001") Gui.activeDocument().hide("Pad") # Gui.ActiveDocument.Pocket.ShapeColor=Gui.ActiveDocument.Pad.ShapeColor # Gui.ActiveDocument.Pocket.LineColor=Gui.ActiveDocument.Pad.LineColor # Gui.ActiveDocument.Pocket.PointColor=Gui.ActiveDocument.Pad.PointColor App.ActiveDocument.Pocket.Length = 5.000000 App.ActiveDocument.Pocket.Type = 1 App.ActiveDocument.Pocket.UpToFace = None App.ActiveDocument.recompute()
def Activated(self): selection = [s for s in FreeCADGui.Selection.getSelectionEx() if s.Document == FreeCAD.ActiveDocument ] if len(selection) == 1: PartMover( FreeCADGui.activeDocument().activeView(), selection[0].Object ) else: PartMoverSelectionObserver()
def draw(self): #helper Variables width = gv.printableWidth + gv.printBedPadding length = gv.printableLength + gv.printBedPadding #Make file and build part try: Gui.getDocument("printBedSupport") Gui.getDocument("printBedSupport").resetEdit() App.getDocument("printBedSupport").recompute() App.closeDocument("printBedSupport") App.setActiveDocument("") App.ActiveDocument = None Gui.ActiveDocument = None except: pass #Create Document App.newDocument("printBedSupport") App.setActiveDocument("printBedSupport") App.ActiveDocument = App.getDocument("printBedSupport") Gui.ActiveDocument = Gui.getDocument("printBedSupport") #make plate #Sketch points p1x = -width / 2 p1y = -length / 2 p2x = -width / 2 p2y = length / 2 p3x = width / 2 p3y = length / 2 p4x = width / 2 p4y = -length / 2 p5x = -(width / 2 - gv.printBedMountHolePadding) p5y = -(length / 2 - gv.printBedMountHolePadding) p6x = -(width / 2 - gv.printBedMountHolePadding) p6y = (length / 2 - gv.printBedMountHolePadding) p7x = (width / 2 - gv.printBedMountHolePadding) p7y = (length / 2 - gv.printBedMountHolePadding) p8x = (width / 2 - gv.printBedMountHolePadding) p8y = -(length / 2 - gv.printBedMountHolePadding) p9x = (width / 2 - gv.printBedMountHolePadding) p9y = length / 2 p10x = width / 2 p10y = (length / 2 - gv.printBedMountHolePadding) App.activeDocument().addObject('Sketcher::SketchObject', 'Sketch') App.activeDocument().Sketch.Placement = App.Placement( App.Vector(0.000000, 0.000000, 0.000000), App.Rotation(0.000000, 0.000000, 0.000000, 1.000000)) Gui.activeDocument().activeView().setCamera( '#Inventor V2.1 ascii \n OrthographicCamera {\n viewportMapping ADJUST_CAMERA \n position 0 0 87 \n orientation 0 0 1 0 \n nearDistance -112.88701 \n farDistance 287.28702 \n aspectRatio 1 \n focalDistance 87 \n height 143.52005 }' ) # Gui.activeDocument().setEdit('Sketch') App.ActiveDocument.Sketch.addGeometry( Part.Line(App.Vector(p1x, p1y, 0), App.Vector(p4x, p4y, 0))) App.ActiveDocument.Sketch.addGeometry( Part.Line(App.Vector(p4x, p4y, 0), App.Vector(p3x, p3y, 0))) App.ActiveDocument.Sketch.addGeometry( Part.Line(App.Vector(p3x, p3y, 0), App.Vector(p2x, p2y, 0))) App.ActiveDocument.Sketch.addGeometry( Part.Line(App.Vector(p2x, p2y, 0), App.Vector(p1x, p1y, 0))) App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Coincident', 0, 2, 1, 1)) App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Coincident', 1, 2, 2, 1)) App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Coincident', 2, 2, 3, 1)) App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Coincident', 3, 2, 0, 1)) App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Horizontal', 0)) App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Horizontal', 2)) App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Vertical', 1)) App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Vertical', 3)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Symmetric', 1, 2, 0, 1, -1, 1)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addGeometry( Part.Line(App.Vector(p5x, p5y, 0), App.Vector(p8x, p8y, 0))) App.ActiveDocument.Sketch.addGeometry( Part.Line(App.Vector(p8x, p8y, 0), App.Vector(p7x, p7y, 0))) App.ActiveDocument.Sketch.addGeometry( Part.Line(App.Vector(p7x, p7y, 0), App.Vector(p6x, p6y, 0))) App.ActiveDocument.Sketch.addGeometry( Part.Line(App.Vector(p6x, p6y, 0), App.Vector(p5x, p5y, 0))) App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Coincident', 4, 2, 5, 1)) App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Coincident', 5, 2, 6, 1)) App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Coincident', 6, 2, 7, 1)) App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Coincident', 7, 2, 4, 1)) App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Horizontal', 4)) App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Horizontal', 6)) App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Vertical', 5)) App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Vertical', 7)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addGeometry( Part.Line(App.Vector(p9x, p9y, 0), App.Vector(p7x, p7y, 0))) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('PointOnObject', 8, 1, 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Coincident', 8, 2, 5, 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addGeometry( Part.Line(App.Vector(p7x, p7y, 0), App.Vector(p10x, p10y, 0))) App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Coincident', 8, 2, 9, 1)) App.ActiveDocument.recompute() App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('PointOnObject', 9, 2, 1)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Horizontal', 9)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Vertical', 8)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Equal', 8, 9)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.movePoint(4, 0, App.Vector(0.000000, 0.000000, 0), 1) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.toggleConstruction(6) App.ActiveDocument.Sketch.toggleConstruction(5) App.ActiveDocument.Sketch.toggleConstruction(7) App.ActiveDocument.Sketch.toggleConstruction(4) App.ActiveDocument.Sketch.toggleConstruction(8) App.ActiveDocument.Sketch.toggleConstruction(9) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addGeometry( Part.Circle(App.Vector(p6x, p6y, 0), App.Vector(0, 0, 1), gv.mountToPrintedDia / 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Coincident', 10, 3, 6, 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addGeometry( Part.Circle(App.Vector(p7x, p7y, 0), App.Vector(0, 0, 1), gv.mountToPrintedDia / 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Coincident', 11, 3, 5, 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addGeometry( Part.Circle(App.Vector(p5x, p5y, 0), App.Vector(0, 0, 1), gv.mountToPrintedDia / 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Coincident', 12, 3, 4, 1)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addGeometry( Part.Circle(App.Vector(p8x, p8y, 0), App.Vector(0, 0, 1), gv.mountToPrintedDia / 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Coincident', 13, 3, 4, 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Equal', 13, 12)) App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Equal', 12, 10)) App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Equal', 10, 11)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Symmetric', 5, 2, 4, 1, -1, 1)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('DistanceY', 1, length)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('DistanceX', 0, width)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint( 'DistanceX', 9, gv.printBedMountHolePadding + gv.mountToPrintedDia / 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.addConstraint( Sketcher.Constraint('Radius', 10, gv.mountToPrintedDia / 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch.movePoint( 4, 1, App.Vector(-37.291931, -32.210766, 0), 0) App.ActiveDocument.recompute() # Gui.getDocument('printBedSupport').resetEdit() App.getDocument('printBedSupport').recompute() App.activeDocument().addObject("PartDesign::Pad", "Pad") App.activeDocument().Pad.Sketch = App.activeDocument().Sketch App.activeDocument().Pad.Length = 10.0 App.ActiveDocument.recompute() Gui.activeDocument().hide("Sketch") App.ActiveDocument.Pad.Length = gv.printBedSupportThickness App.ActiveDocument.Pad.Reversed = 0 App.ActiveDocument.Pad.Midplane = 0 App.ActiveDocument.Pad.Length2 = 100.000000 App.ActiveDocument.Pad.Type = 0 App.ActiveDocument.Pad.UpToFace = None App.ActiveDocument.recompute() # Gui.activeDocument().resetEdit() #Make holes for y bushing mounts #Sketch Points p1x = -gv.yRodSpacing / 2 p1y = -length / 2 p2x = -gv.yRodSpacing / 2 p2y = length / 2 p3x = gv.yRodSpacing / 2 p3y = -length / 2 p4x = gv.yRodSpacing / 2 p4y = length / 2 p5x = -gv.yRodSpacing / 2 - gv.yBushingMountSlotSpacing / 2 p5y = -gv.yBushingNutSeparation / 2 p6x = -gv.yRodSpacing / 2 + gv.yBushingMountSlotSpacing / 2 p6y = -gv.yBushingNutSeparation / 2 p7x = -gv.yRodSpacing / 2 - gv.yBushingMountSlotSpacing / 2 p7y = gv.yBushingNutSeparation / 2 p8x = -gv.yRodSpacing / 2 + gv.yBushingMountSlotSpacing / 2 p8y = gv.yBushingNutSeparation / 2 p9x = gv.yRodSpacing / 2 - gv.yBushingMountSlotSpacing / 2 p9y = -gv.yBushingNutSeparation / 2 p10x = gv.yRodSpacing / 2 + gv.yBushingMountSlotSpacing / 2 p10y = -gv.yBushingNutSeparation / 2 p11x = gv.yRodSpacing / 2 - gv.yBushingMountSlotSpacing / 2 p11y = gv.yBushingNutSeparation / 2 p12x = gv.yRodSpacing / 2 + gv.yBushingMountSlotSpacing / 2 p12y = gv.yBushingNutSeparation / 2 p13x = p1x p13y = p5y p14x = p1x p14y = p7y p15x = p3x p15y = p5y p16x = p3x p16y = p7y #Make Sketch App.activeDocument().addObject('Sketcher::SketchObject', 'Sketch001') App.activeDocument().Sketch001.Support = uf.getFace( App.ActiveDocument.Pad, None, None, None, None, gv.printBedSupportThickness, 0) App.activeDocument().recompute() # Gui.activeDocument().setEdit('Sketch001') App.ActiveDocument.Sketch001.addExternal( "Pad", uf.getEdge(App.ActiveDocument.Pad, 0, 0, length / 2, 0, gv.printBedSupportThickness, 0)) App.ActiveDocument.Sketch001.addExternal( "Pad", uf.getEdge(App.ActiveDocument.Pad, 0, 0, -length / 2, 0, gv.printBedSupportThickness, 0)) App.ActiveDocument.Sketch001.addGeometry( Part.Line(App.Vector(p1x, p1y, 0), App.Vector(p2x, p2y, 0))) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('PointOnObject', 0, 1, -4)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addGeometry( Part.Line(App.Vector(p3x, p3y, 0), App.Vector(p4x, p4y, 0))) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('PointOnObject', 1, 1, -4)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Symmetric', 1, 2, 0, 2, -2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addGeometry( Part.Line(App.Vector(p5x, p5y, 0), App.Vector(p6x, p6y, 0))) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Horizontal', 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addGeometry( Part.Line(App.Vector(p7x, p7y, 0), App.Vector(p8x, p8y, 0))) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Horizontal', 3)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addGeometry( Part.Line(App.Vector(p9x, p9y, 0), App.Vector(p10x, p10y, 0))) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addGeometry( Part.Line(App.Vector(p11x, p11y, 0), App.Vector(p12x, p12y, 0))) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Horizontal', 5)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Horizontal', 4)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Equal', 3, 5)) App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Equal', 5, 4)) App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Equal', 4, 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Symmetric', 3, 2, 3, 1, 0)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Symmetric', 2, 2, 2, 1, 0)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Symmetric', 5, 2, 5, 1, 1)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Symmetric', 4, 2, 4, 1, 1)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('PointOnObject', 3, 2, 5)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('PointOnObject', 0, 2, -3)) App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('PointOnObject', 2, 2, 4)) App.ActiveDocument.recompute() #Add Dimmensions early to avoid squishing sketch App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Distance', 5, 2, 4, gv.yBushingNutSeparation)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Distance', 1, 1, 0, 1, gv.yRodSpacing)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('DistanceX', 4, gv.yBushingMountSlotSpacing)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Symmetric', 3, 1, 2, 1, -1)) App.ActiveDocument.recompute() #continue adding other constraints App.ActiveDocument.Sketch001.toggleConstruction(0) App.ActiveDocument.Sketch001.toggleConstruction(1) App.ActiveDocument.Sketch001.toggleConstruction(5) App.ActiveDocument.Sketch001.toggleConstruction(4) App.ActiveDocument.Sketch001.toggleConstruction(2) App.ActiveDocument.Sketch001.toggleConstruction(3) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addGeometry( Part.Circle(App.Vector(p5x, p5y, 0), App.Vector(0, 0, 1), gv.mountToPrintedDia / 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Coincident', 6, 3, 2, 1)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addGeometry( Part.Circle(App.Vector(p6x, p6y, 0), App.Vector(0, 0, 1), gv.mountToPrintedDia / 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Coincident', 7, 3, 2, 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addGeometry( Part.Circle(App.Vector(p7x, p7y, 0), App.Vector(0, 0, 1), gv.mountToPrintedDia / 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Coincident', 8, 3, 3, 1)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addGeometry( Part.Circle(App.Vector(p8x, p8y, 0), App.Vector(0, 0, 1), gv.mountToPrintedDia / 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Coincident', 9, 3, 3, 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addGeometry( Part.Circle(App.Vector(p9x, p9y, 0), App.Vector(0, 0, 1), gv.mountToPrintedDia / 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Coincident', 10, 3, 5, 1)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addGeometry( Part.Circle(App.Vector(p10x, p10y, 0), App.Vector(0, 0, 1), gv.mountToPrintedDia / 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Coincident', 11, 3, 5, 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addGeometry( Part.Circle(App.Vector(p11x, p11y, 0), App.Vector(0, 0, 1), gv.mountToPrintedDia / 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Coincident', 12, 3, 4, 1)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addGeometry( Part.Circle(App.Vector(p12x, p12y, 0), App.Vector(0, 0, 1), gv.mountToPrintedDia / 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Coincident', 13, 3, 4, 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Equal', 6, 7)) App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Equal', 7, 8)) App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Equal', 8, 9)) App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Equal', 9, 10)) App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Equal', 10, 11)) App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Equal', 11, 12)) App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Equal', 12, 13)) App.ActiveDocument.recompute() #Add hole Dimensions App.ActiveDocument.Sketch001.addConstraint( Sketcher.Constraint('Radius', 11, gv.mountToPrintedDia / 2)) App.ActiveDocument.recompute() #Cut bushing mount holes through all App.activeDocument().addObject("PartDesign::Pocket", "Pocket") App.activeDocument().Pocket.Sketch = App.activeDocument().Sketch001 App.activeDocument().Pocket.Length = 5.0 App.ActiveDocument.recompute() Gui.activeDocument().hide("Sketch001") Gui.activeDocument().hide("Pad") # Gui.activeDocument().setEdit('Pocket') # Gui.ActiveDocument.Pocket.ShapeColor=Gui.ActiveDocument.Pad.ShapeColor # Gui.ActiveDocument.Pocket.LineColor=Gui.ActiveDocument.Pad.LineColor # Gui.ActiveDocument.Pocket.PointColor=Gui.ActiveDocument.Pad.PointColor App.ActiveDocument.Pocket.Length = 5.000000 App.ActiveDocument.Pocket.Type = 1 App.ActiveDocument.Pocket.UpToFace = None App.ActiveDocument.recompute() # Gui.activeDocument().resetEdit() #Make holes for y belt anchor #Sketch points p1x = gv.yMotorPulleyDia / 2 p1y = gv.yBeltAnchorHoleSpacing / 2 p2x = p1x p2y = -p1y #Make Sketch App.activeDocument().addObject('Sketcher::SketchObject', 'Sketch002') App.activeDocument().Sketch002.Support = uf.getFace( App.ActiveDocument.Pocket, None, None, None, None, gv.printBedSupportThickness, 0) App.activeDocument().recompute() # Gui.activeDocument().setEdit('Sketch002') App.ActiveDocument.Sketch002.addGeometry( Part.Circle(App.Vector(p1x, p1y, 0), App.Vector(0, 0, 1), gv.mountToPrintedDia / 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch002.addGeometry( Part.Circle(App.Vector(p2x, p2y, 0), App.Vector(0, 0, 1), gv.mountToPrintedDia / 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch002.addConstraint( Sketcher.Constraint('Symmetric', 0, 3, 1, 3, -1)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch002.addConstraint( Sketcher.Constraint('Equal', 0, 1)) App.ActiveDocument.recompute() #Add dimensions App.ActiveDocument.Sketch002.addConstraint( Sketcher.Constraint('Radius', 0, gv.mountToPrintedDia / 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch002.addConstraint( Sketcher.Constraint('DistanceX', -2, 1, 1, 3, gv.yMotorPulleyDia / 2)) App.ActiveDocument.recompute() App.ActiveDocument.Sketch002.addConstraint( Sketcher.Constraint('Distance', 0, 3, 1, 3, gv.yBeltAnchorHoleSpacing)) App.ActiveDocument.recompute() # Gui.getDocument('printBedSupport').resetEdit() App.getDocument('printBedSupport').recompute() #Cut holes App.activeDocument().addObject("PartDesign::Pocket", "Pocket001") App.activeDocument().Pocket001.Sketch = App.activeDocument().Sketch002 App.activeDocument().Pocket001.Length = 5.0 App.ActiveDocument.recompute() Gui.activeDocument().hide("Sketch002") Gui.activeDocument().hide("Pocket") # Gui.ActiveDocument.Pocket001.ShapeColor=Gui.ActiveDocument.Pocket.ShapeColor # Gui.ActiveDocument.Pocket001.LineColor=Gui.ActiveDocument.Pocket.LineColor # Gui.ActiveDocument.Pocket001.PointColor=Gui.ActiveDocument.Pocket.PointColor App.ActiveDocument.Pocket001.Length = 5.000000 App.ActiveDocument.Pocket001.Type = 1 App.ActiveDocument.Pocket001.UpToFace = None App.ActiveDocument.recompute()
def Activated(self): selection = [s for s in FreeCADGui.Selection.getSelectionEx() if s.Document == FreeCAD.ActiveDocument ] if len(selection) == 1: PartMover( FreeCADGui.activeDocument().activeView(), duplicateImportedPart( selection[0].Object ) )
def navi(): '''navigator startup''' mw = QtGui.qApp #widget.setCursor(QtCore.Qt.SizeAllCursor) #cursor ausblenden #mw.setOverrideCursor(QtCore.Qt.BlankCursor) # FreeCADGui.activateWorkbench("NoneWorkbench") mw.setOverrideCursor(QtCore.Qt.PointingHandCursor) ef = EventFilter() ef.laenge = 0.0 ef.breite = 0.0 ef.campos = FreeCAD.Vector(0, 0, 20000) # ef.output.hide() ef.mouseMode = False ef.firstCall = True ef.mode = "turn" ef.navi = myNavigatorWidget(ef) ef.speed = 100 ef.direction = 0.5 * math.pi ef.roll = 0 #-------------- # get a jpg filename # jpgfilename = QtGui.QFileDialog.getOpenFileName(QtGui.qApp.activeWindow(),'Open image file','*.jpg') fn = '/home/microelly2/FCB/b175_camera_controller/winter.jpg' fn = os.path.dirname(__file__) + "/../pics/winter.jpg" sg = FreeCADGui.ActiveDocument.ActiveView.getSceneGraph() print sg col = coin.SoBaseColor() #col.rgb=(1,0,0) trans = coin.SoTranslation() trans.translation.setValue([0, 0, 0]) myCustomNode = coin.SoSeparator() #myCustomNode.addChild(col) if 0 or False: cub = coin.SoCylinder() cub.radius.setValue(3000) cub.height.setValue(4000) cub.parts.set("SIDES") s = coin.SoRotationXYZ() s.angle.setValue(1.5708) s.axis.setValue(0) myCustomNode.addChild(s) s = coin.SoRotationXYZ() s.angle.setValue(math.pi) s.axis.setValue(1) myCustomNode.addChild(s) else: cub = coin.SoSphere() cub.radius.setValue(10000000) s = coin.SoRotationXYZ() s.angle.setValue(1.5708) s.axis.setValue(0) myCustomNode.addChild(s) s = coin.SoRotationXYZ() s.angle.setValue(math.pi) s.axis.setValue(1) myCustomNode.addChild(s) if False: l = coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(0, 1, 0)) l.color.setValue(coin.SbColor(0, 0, 1)) myCustomNode.addChild(l) l = coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(0, -1, 0)) l.color.setValue(coin.SbColor(0, 1, 1)) myCustomNode.addChild(l) l = coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(0, 0, 1)) l.color.setValue(coin.SbColor(1, 0, 0)) myCustomNode.addChild(l) l = coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(0, 0, -1)) l.color.setValue(coin.SbColor(0.6, 0.6, 1)) myCustomNode.addChild(l) l = coin.SoSpotLight() l.direction.setValue(coin.SbVec3f(1, 0, 1)) l.color.setValue(coin.SbColor(0, 1, 0)) l.location.setValue(coin.SbVec3f(0, 0, 0)) # l.cutOffAngle.setValue(0.01) # l.dropOffRate.setValue(1) myCustomNode.addChild(l) #myCustomNode.addChild(trans) myCustomNode.addChild(cub) sg.addChild(myCustomNode) tex = coin.SoTexture2() tex.filename = fn myCustomNode.insertChild(tex, 0) #--------------- ef.background = myCustomNode ef.tex = tex FreeCAD.eventfilter = ef mw.installEventFilter(ef) FreeCAD.eventfilter.on_key_press = on_keypress2 FreeCAD.eventfilter.on_move = on_move3 FreeCAD.eventfilter.on_clicks = on_clicks3 FreeCAD.eventfilter.on_windowslist = on_windowslist2 on_keypress2(FreeCAD.eventfilter, 'O') view = FreeCADGui.activeDocument().activeView() FreeCADGui.ActiveDocument.ActiveView.setAnimationEnabled(False) mgr = view.getViewer().getSoRenderManager() mgr.setAutoClipping(0) FreeCAD.ActiveDocument.recompute() FreeCADGui.updateGui() print "File ", __file__ print "1!!" return ef
) expVRML.say(objs) expVRML.say( "######################################################################" ) export_objects, used_color_keys = expVRML.determineColors( Gui, objs, material_substitutions) export_file_name = out_dir + os.sep + ModelName + '.wrl' colored_meshes = expVRML.getColoredMesh(Gui, export_objects, scale) expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys, LIST_license) # Save the doc in Native FC format if save_memory == False: Gui.SendMsgToActiveView("ViewFit") Gui.activeDocument().activeView().viewAxometric() # Save the doc in Native FC format saveFCdoc(App, Gui, doc, ModelName, out_dir, False) check_Model = True if save_memory == True or check_Model == True: doc = FreeCAD.ActiveDocument FreeCAD.closeDocument(doc.Name) step_path = os.path.join(out_dir, ModelName + u'.step') if check_Model == True: #ImportGui.insert(step_path,ModelName) ImportGui.open(step_path) docu = FreeCAD.ActiveDocument if cq_cad_tools.checkUnion(docu) == True:
def make_3D_model(models_dir, variant): LIST_license = [ "", ] modelName = all_params[variant].modelName CheckedmodelName = modelName.replace('.', '').replace('-', '_').replace( '(', '').replace(')', '') Newdoc = App.newDocument(CheckedmodelName) App.setActiveDocument(CheckedmodelName) Gui.ActiveDocument = Gui.getDocument(CheckedmodelName) case = make_case(all_params[variant]) casetop = make_case_top(all_params[variant]) pins = make_pins(all_params[variant]) show(case) show(casetop) show(pins) #show(pinmark) #stop doc = FreeCAD.ActiveDocument objs = GetListOfObjects(FreeCAD, doc) body_color_key = all_params[variant].body_color_key body_top_color_key = all_params[variant].body_top_color_key pin_color_key = all_params[variant].pin_color_key body_color = shaderColors.named_colors[body_color_key].getDiffuseFloat() body_top_color = shaderColors.named_colors[ body_top_color_key].getDiffuseFloat() pin_color = shaderColors.named_colors[pin_color_key].getDiffuseFloat() Color_Objects(Gui, objs[0], body_color) Color_Objects(Gui, objs[1], body_top_color) Color_Objects(Gui, objs[2], pin_color) col_body = Gui.ActiveDocument.getObject(objs[0].Name).DiffuseColor[0] col_body_top = Gui.ActiveDocument.getObject(objs[1].Name).DiffuseColor[0] col_pin = Gui.ActiveDocument.getObject(objs[2].Name).DiffuseColor[0] material_substitutions = { col_body[:-1]: body_color_key, col_body_top[:-1]: body_top_color_key, col_pin[:-1]: pin_color_key } expVRML.say(material_substitutions) while len(objs) > 1: FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name, objs[1].Name) del objs objs = GetListOfObjects(FreeCAD, doc) doc.Label = CheckedmodelName del objs objs = GetListOfObjects(FreeCAD, doc) objs[0].Label = CheckedmodelName restore_Main_Tools() script_dir = os.path.dirname(os.path.realpath(__file__)) expVRML.say(models_dir) out_dir = models_dir + os.sep + all_params[variant].dest_dir_prefix if not os.path.exists(out_dir): os.makedirs(out_dir) step_path = '{dir:s}/{name:s}.step'.format(dir=out_dir, name=modelName) exportSTEP(doc, modelName, out_dir) if LIST_license[0] == "": LIST_license = Lic.LIST_int_license LIST_license.append("") Lic.addLicenseToStep(out_dir, '{:s}.step'.format(modelName), LIST_license, cq_parameters.LICENCE_Info.STR_licAuthor, cq_parameters.LICENCE_Info.STR_licEmail, cq_parameters.LICENCE_Info.STR_licOrgSys, cq_parameters.LICENCE_Info.STR_licPreProc) # scale and export Vrml model scale = 1 / 2.54 #exportVRML(doc,modelName,scale,out_dir) del objs objs = GetListOfObjects(FreeCAD, doc) expVRML.say( "######################################################################" ) expVRML.say(objs) expVRML.say( "######################################################################" ) export_objects, used_color_keys = expVRML.determineColors( Gui, objs, material_substitutions) export_file_name = out_dir + os.sep + modelName + '.wrl' colored_meshes = expVRML.getColoredMesh(Gui, export_objects, scale) # expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys)# , LIST_license expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys, LIST_license) # Save the doc in Native FC format doc.recompute() saveFCdoc(App, Gui, doc, modelName, out_dir) #FreeCADGui.activateWorkbench("PartWorkbench") if save_memory == False and check_Model == False: FreeCADGui.SendMsgToActiveView("ViewFit") FreeCADGui.activeDocument().activeView().viewAxometric() if save_memory == True or check_Model == True: FreeCAD.closeDocument(doc.Name) os.remove(out_dir + os.sep + modelName + '.FCStd') if check_Model == True: with open(out_dir + os.sep + check_log_file, 'a+') as log: log.write('# Check report for Molex 3d model genration\n') runGeometryCheck(App, Gui, step_path, log, modelName, save_memory=save_memory) log.close()
def resetCamera(self): import FreeCADGui camera = '#Inventor V2.1 ascii\n\n\nOrthographicCamera {\n viewportMapping ADJUST_CAMERA\n position 0 0 1\n orientation 0 0 1 0\n aspectRatio 1\n focalDistance 5\n height 40\n\n}\n' FreeCADGui.activeDocument().activeView().setCamera(camera)
def accept(self): self.v.removeEventCallback("SoEvent", self.track) for obj in FreeCAD.ActiveDocument.Objects: if 'Point_d_w_h' == obj.Name: FreeCAD.ActiveDocument.removeObject('Point_d_w_h') Size_Value = {0: 6, 1: 8, 2: 10, 3: 12} Values_Pillow = {0: 0, 1: 1} TOL_Value = {0: 0.4, 1: 0.7} Size = Size_Value[self.Sk.Size_ComboBox.currentIndex()] Pillow = Values_Pillow[self.Sk.Pillow_ComboBox.currentIndex()] Tol = TOL_Value[self.Sk.Pillow_ComboBox.currentIndex()] pos = FreeCAD.Vector(self.Sk.pos_x.value(), self.Sk.pos_y.value(), self.Sk.pos_z.value()) positions_d = [0, 1] positions_w = [-1, 0, 1] positions_h = [0, 1] pos_d = positions_d[self.Sk.pos_d.currentIndex()] pos_w = positions_w[self.Sk.pos_w.currentIndex()] pos_h = positions_h[self.Sk.pos_h.currentIndex()] axis_d = FreeCAD.Vector(self.Sk.axis_d_x.value(), self.Sk.axis_d_y.value(), self.Sk.axis_d_z.value()) axis_w = FreeCAD.Vector(self.Sk.axis_w_x.value(), self.Sk.axis_w_y.value(), self.Sk.axis_w_z.value()) axis_h = FreeCAD.Vector(self.Sk.axis_h_x.value(), self.Sk.axis_h_y.value(), self.Sk.axis_h_z.value()) if ortonormal_axis(axis_d, axis_w, axis_h) == True: if Pillow == 0 or (Pillow == 1 and Size == 8): # Pillow only exist for size 8. comps_new.Sk_dir( size=Size, fc_axis_h=axis_h, fc_axis_d=axis_d, fc_axis_w=axis_w, pos_h=pos_h, pos_w=pos_w, pos_d=pos_d, pillow=Pillow, pos=pos, tol=Tol, #0.7, # for the pillow block wfco=1, name="shaft" + str(Size) + "_holder") FreeCADGui.activeDocument().activeView().viewAxonometric( ) #Axonometric view FreeCADGui.SendMsgToActiveView( "ViewFit") #Fit the view to the object FreeCADGui.Control.closeDialog() #close the dialog elif Pillow == 1 and Size != 8: message = QtWidgets.QMessageBox() message.setText("This Size don't have Pillow option") message.setStandardButtons(QtWidgets.QMessageBox.Ok) message.setDefaultButton(QtWidgets.QMessageBox.Ok) message.exec_()
def draw_HortenHIX(): rib_material_height = 33.0 length = 500 scaleFactor = 1 #length / 85 if FreeCAD.ActiveDocument is not None and FreeCAD.ActiveDocument.Name == "Horten_HIX": FreeCAD.closeDocument(FreeCAD.ActiveDocument.Name) FreeCAD.setActiveDocument("") ActiveDocument = None FreeCAD.ActiveDocument = None doc = FreeCAD.newDocument('Horten_HIX') wing_sweep = 32.2 twist = 3 wing_ribs = 10 front_part_fraction = 0.97 WingTop_parts = [] line = Draft.makeWire([ Vector(0.0, 73.39, 0.0) * scaleFactor, Vector(72.64, 27.65, 0.0) * scaleFactor ]) WingTop_parts.append(line) line = Draft.makeWire([ Vector(75.22, 11.01, 0.0) * scaleFactor, Vector(35.0, 22.43, 0.0) * scaleFactor ]) WingTop_parts.append(line) poles = [] poles.append(Vector(72.64, 27.65, 0.0) * scaleFactor) poles.append(Vector(86.21, 19.11, 0.0) * scaleFactor) poles.append(Vector(86.21, 7.88, 0.0) * scaleFactor) poles.append(Vector(75.22, 11.01, 0.0) * scaleFactor) weights = [1.0, 1.0, 1.0, 1.0] knots = [0.0, 1.0] mults = [4, 4] bspline = Part.BSplineCurve() bspline.buildFromPolesMultsKnots(poles, mults, knots, False, 3, weights, False) bezier = doc.addObject('Part::Spline', 'BSplineCurve') bezier.Shape = bspline.toShape() WingTop_parts.append(bezier) poles = [] poles.append(Vector(0.0, 0.0, 0.0) * scaleFactor) poles.append(Vector(15.13, 28.07, 0.0) * scaleFactor) poles.append(Vector(35.0, 22.43, 0.0) * scaleFactor) weights = [1.0, 1.0, 1.0] knots = [0.0, 1.0] mults = [3, 3] bspline = Part.BSplineCurve() bspline.buildFromPolesMultsKnots(poles, mults, knots, False, 2, weights, False) bezier = doc.addObject('Part::Spline', 'BSplineCurve') bezier.Shape = bspline.toShape() WingTop_parts.append(bezier) WingTop = doc.addObject('Part::Compound', 'WingTop') WingTop.Links = WingTop_parts WingTop.Placement.Base = Vector(0.0, 0.0, 0.0) * scaleFactor WingTop.Placement.Rotation = Rotation(0.0, 0.0, 0.0, 1.0) WingTop.ViewObject.LineColor = (1.0, 0.0, 0.0, 0.0) WingTop.ViewObject.LineColorArray = [(1.0, 0.0, 0.0, 0.0)] WingFront_parts = [] line = Draft.makeWire([ Vector(0.0, -4.31, 0.0) * scaleFactor, Vector(77.02, 2.59, 0.0) * scaleFactor ]) WingFront_parts.append(line) poles = [] poles.append(Vector(0.0, 7.35, 0.0) * scaleFactor) poles.append(Vector(5.43, 4.71, 0.0) * scaleFactor) poles.append(Vector(16.41, 2.6, 0.0) * scaleFactor) poles.append(Vector(41.55, 2.77, 0.0) * scaleFactor) poles.append(Vector(76.91, 3.93, 0.0) * scaleFactor) poles.append(Vector(83.72, 4.28, 0.0) * scaleFactor) poles.append(Vector(83.72, 3.38, 0.0) * scaleFactor) poles.append(Vector(77.02, 2.59, 0.0) * scaleFactor) weights = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0] knots = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0] mults = [4, 1, 1, 1, 1, 4] bspline = Part.BSplineCurve() bspline.buildFromPolesMultsKnots(poles, mults, knots, False, 3, weights, False) bezier = doc.addObject('Part::Spline', 'BSplineCurve') bezier.Shape = bspline.toShape() WingFront_parts.append(bezier) WingFront = doc.addObject('Part::Compound', 'WingFront') WingFront.Links = WingFront_parts WingFront.Placement.Base = Vector(0.0, 0.0, 0.0) * scaleFactor WingFront.Placement.Rotation = Rotation(0.7071067811865475, -0.0, -0.0, 0.7071067811865476) WingFront.ViewObject.LineColor = (1.0, 0.0, 0.5, 0.0) WingFront.ViewObject.LineColorArray = [(1.0, 0.0, 0.5, 0.0)] WingProfile_parts = [] poles = [] poles.append(Vector(65.04, 0.0, 0.0) * scaleFactor) poles.append(Vector(24.39, -4.45, 0.0) * scaleFactor) poles.append(Vector(10.95, -2.98, 0.0) * scaleFactor) poles.append(Vector(2.58, -2.28, 0.0) * scaleFactor) poles.append(Vector(3.23, 0.0, 0.0) * scaleFactor) poles.append(Vector(3.89, 2.3, 0.0) * scaleFactor) poles.append(Vector(13.51, 5.94, 0.0) * scaleFactor) poles.append(Vector(27.26, 5.54, 0.0) * scaleFactor) poles.append(Vector(65.04, 0.0, 0.0) * scaleFactor) weights = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0] knots = [ 0.0, 0.1666666666666667, 0.3333333333333333, 0.5, 0.6666666666666666, 0.8333333333333334, 1.0 ] mults = [4, 1, 1, 1, 1, 1, 4] bspline = Part.BSplineCurve() bspline.buildFromPolesMultsKnots(poles, mults, knots, False, 3, weights, False) bezier = doc.addObject('Part::Spline', 'BSplineCurve') bezier.Shape = bspline.toShape() WingProfile_parts.append(bezier) WingProfile = doc.addObject('Part::Compound', 'WingProfile') WingProfile.Links = WingProfile_parts WingProfile.Placement.Base = Vector(5.0, 73.0, 0.0) * scaleFactor WingProfile.Placement.Rotation = Rotation(0.5, -0.5, -0.5, 0.5) WingProfile.ViewObject.LineColor = (1.0, 0.33, 0.0, 0.0) WingProfile.ViewObject.LineColorArray = [(1.0, 0.33, 0.0, 0.0)] # Profiles ^^^ doc.recompute() WingArray = CurvedShapes.makeCurvedArray(Base=WingProfile, Hullcurves=[WingTop, WingFront], Axis=Vector(1, 0, 0), Items=16, OffsetStart=0, OffsetEnd=0, Twist=twist, Surface=False, Solid=False, Distribution='parabolic', DistributionReverse=True, extract=False) WingTopLeft = doc.addObject('Part::Mirroring', 'WingTopLeft') WingTopLeft.Normal = Vector(1.0, 0.0, 0.0) WingTopLeft.Source = WingTop WingTopLeft.ViewObject.hide() WingFrontLeft = doc.addObject('Part::Mirroring', 'WingFrontLeft') WingFrontLeft.Normal = Vector(1.0, 0.0, 0.0) WingFrontLeft.Source = WingFront WingFrontLeft.ViewObject.hide() doc.recompute() winglength = WingFrontLeft.Shape.BoundBox.XLength WingSurface = CurvedShapes.makeCurvedArray( Base=WingProfile, Hullcurves=[WingTopLeft, WingFrontLeft], Axis=Vector(-1, 0, 0), Items=32, OffsetStart=0, OffsetEnd=0, Twist=-twist, Surface=True, Solid=True, Distribution='sinusoidal') WingSurface.Label = "WingSurface" Cockpit = drawCockpit(doc, scaleFactor, WingSurface) Turbine = makeTurbine(doc, scaleFactor) TurbineCut = makeTurbineCut(doc, scaleFactor) doc.recompute() Draft.rotate([Turbine, TurbineCut], -6, Vector(0.0, length, 0.0), axis=Vector(1.0, 0.0, 0.0), copy=False) Turbine.Placement.Base = Vector(0.0, 0.0, 6.5) * scaleFactor TurbineCut.Placement.Base = Vector(0.0, 0.0, 6.5) * scaleFactor Wing = doc.addObject('Part::Cut', 'Wing') Wing.Base = WingSurface Wing.Tool = TurbineCut doc.recompute() ymax = WingSurface.Shape.BoundBox.YMin + WingSurface.Shape.BoundBox.YLength rota = FreeCAD.Rotation(Vector(0, 0, 1), 28) vecToWingEnd28 = rota.multVec(Vector(0, 1, 0)) WingCutFront = CurvedShapes.cutSurfaces([Wing], Normal=vecToWingEnd28, Position=Vector(0, ymax * 0.85, 0), Face=False, Simplify=0) WingCutFront.Label = "WingCutFront" rota = FreeCAD.Rotation(Vector(0, 0, 1), 18) vecToWingEnd18 = rota.multVec(Vector(0, 1, 0)) WingCutBack = CurvedShapes.cutSurfaces([Wing], Normal=vecToWingEnd18, Position=Vector(0, ymax * 0.55, 0), Face=False, Simplify=0) WingCutBack.Label = "WingCutBack" doc.recompute() FreeCADGui.activeDocument().activeView().viewIsometric() FreeCADGui.SendMsgToActiveView("ViewFit")