def Activated(self): FreeCAD.ActiveDocument.openTransaction(translate("Path_CompoundExtended","Create Compound")) FreeCADGui.addModule("PathScripts.PathCompoundExtended") snippet = ''' import Path import PathScripts from PathScripts import PathUtils incl = [] prjexists = False sel = FreeCADGui.Selection.getSelection() for s in sel: if s.isDerivedFrom("Path::Feature"): incl.append(s) obj = FreeCAD.ActiveDocument.addObject("Path::FeatureCompoundPython","Compound") PathScripts.PathCompoundExtended.ObjectCompoundExtended(obj) PathScripts.PathCompoundExtended.ViewProviderCompoundExtended(obj.ViewObject) project = PathUtils.addToProject(obj) if incl: children = [] p = project.Group g = obj.Group for child in incl: p.remove(child) children.append(FreeCAD.ActiveDocument.getObject(child.Name)) project.Group = p g.append(children) obj.Group = children ''' FreeCADGui.doCommand(snippet) FreeCAD.ActiveDocument.commitTransaction() FreeCAD.ActiveDocument.recompute()
def Activated(self): from DraftTools import translate FreeCAD.ActiveDocument.openTransaction(str(translate("Spreadsheet","Create Spreadsheet"))) FreeCADGui.doCommand("import Spreadsheet") FreeCADGui.doCommand("Spreadsheet.makeSpreadsheet()") FreeCAD.ActiveDocument.commitTransaction() FreeCAD.ActiveDocument.recompute()
def c1a(menu,isactive,name,*info): global _Command name1="Animation_"+name t=_Command(name,*info) t.IsActive=isactive FreeCADGui.addCommand(name1,t) FreeCAD.tcmds6.append([menu,name1,name,isactive,info])
def Activated(self): super(ShapeModifierTrigger , self).Activated() import Base if Base.__currentStage__ != 'DL' : # not 'DL' stage print Base.__currentStage__ self.finish() return sels=FreeCADGui.Selection.getSelectionEx() if len(sels)!=1 : # select more than 2 objects return s = sels[0] count = 0 for subName in sels[0].SubElementNames: if 'Edge' in subName : # FreeCAD may get error object selected, this code confirm the object is valid count+=1 if count>1 : return if s.ObjectName=='ShapeMover' or s.ObjectName=='ShapeModifier': return import Base obj = sels[0].Object name , idx = Base.getRealTypeAndIndex(obj.Label) print 'trigger modifier for %s --> %d'%(name , idx) self.docName = s.DocumentName self.objName = s.ObjectName self.subElement = s.SubElementNames[0] Base.__shapeBeModifying__ = [self.docName , self.objName , self.subElement] print 'prepare done in ShapeModifierTrigger' if name=='JointLine': FreeCADGui.runCommand('DDA_JointLineModifier')
def c2a(menu,isactive,title,name,*info): global _Command t=_Command(name,*info) title1="Animation_"+title t.IsActive=isactive FreeCADGui.addCommand(title1,t) FreeCAD.tcmds6.append([menu,title1,name,isactive,info])
def Activated(self): p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch") self.Length = p.GetFloat("PanelLength",1000) self.Width = p.GetFloat("PanelWidth",1000) self.Thickness = p.GetFloat("PanelThickness",10) self.Profile = None self.continueCmd = False self.rotated = False self.DECIMALS = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Units").GetInt("Decimals",2) self.FORMAT = "%." + str(self.DECIMALS) + "f mm" sel = FreeCADGui.Selection.getSelection() if sel: if len(sel) == 1: if Draft.getType(sel[0]) == "Panel": return FreeCAD.ActiveDocument.openTransaction(str(translate("Arch","Create Panel"))) FreeCADGui.addModule("Arch") for obj in sel: FreeCADGui.doCommand("Arch.makePanel(FreeCAD.ActiveDocument." + obj.Name + ",thickness=" + str(self.Thickness) + ")") FreeCAD.ActiveDocument.commitTransaction() FreeCAD.ActiveDocument.recompute() return # interactive mode if hasattr(FreeCAD,"DraftWorkingPlane"): FreeCAD.DraftWorkingPlane.setup() import DraftTrackers self.points = [] self.tracker = DraftTrackers.boxTracker() self.tracker.width(self.Width) self.tracker.height(self.Thickness) self.tracker.length(self.Length) self.tracker.on() FreeCADGui.Snapper.getPoint(callback=self.getPoint,movecallback=self.update,extradlg=self.taskbox())
def itemActivated(self): FreeCADGui.Selection.clearSelection() slist = self.form.baseList.selectedItems() for i in slist: o = FreeCAD.ActiveDocument.getObject(i.text()) FreeCADGui.Selection.addSelection(o) FreeCADGui.updateGui()
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 Activated(self): string_lin_mat_obj = "FreeCAD.ActiveDocument.getObject('" + self.selobj.Name + "')" command_to_run = "FemGui.getActiveAnalysis().addObject(ObjectsFem.makeMaterialMechanicalNonlinear(FreeCAD.ActiveDocument, " + string_lin_mat_obj + "))" FreeCAD.ActiveDocument.openTransaction("Create FemMaterialMechanicalNonlinear") FreeCADGui.addModule("ObjectsFem") FreeCADGui.doCommand(command_to_run) # set some property of the solver to nonlinear (only if one solver is available and if this solver is a CalculiX solver): # nonlinear material # nonlinear geometry --> it is triggered anyway https://forum.freecadweb.org/viewtopic.php?f=18&t=23101&p=180489#p180489 solver_object = None for m in self.active_analysis.Group: if m.isDerivedFrom('Fem::FemSolverObjectPython'): if not solver_object: solver_object = m else: # we do not change attributes if we have more than one solver, since we do not know which one to take solver_object = None break # set solver attribute for nonlinearity for ccxtools CalculiX solver or new frame work CalculiX solver if hasattr(solver_object, "Proxy") and (solver_object.Proxy.Type == 'Fem::FemSolverCalculixCcxTools' or solver_object.Proxy.Type == 'Fem::FemSolverObjectCalculix'): print('Set MaterialNonlinearity and GeometricalNonlinearity to nonlinear for ' + solver_object.Label) solver_object.MaterialNonlinearity = "nonlinear" solver_object.GeometricalNonlinearity = "nonlinear" FreeCADGui.Selection.clearSelection() FreeCAD.ActiveDocument.recompute()
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 Activated(self): sel = FreeCADGui.Selection.getSelection() if len(sel) == 1 and sel[0].isDerivedFrom("App::MaterialObjectPython"): lin_mat_obj = sel[0] # check if an nonlinear material exists which is based on the selected material already allow_nonlinear_material = True for o in FreeCAD.ActiveDocument.Objects: if hasattr(o, "Proxy") and o.Proxy is not None and o.Proxy.Type == "FemMaterialMechanicalNonlinear" and o.LinearBaseMaterial == lin_mat_obj: FreeCAD.Console.PrintError(o.Name + ' is based on the selected material: ' + lin_mat_obj.Name + '. Only one nonlinear object for each material allowed.\n') allow_nonlinear_material = False break if allow_nonlinear_material: string_lin_mat_obj = "App.ActiveDocument.getObject('" + lin_mat_obj.Name + "')" command_to_run = "FemGui.getActiveAnalysis().Member = FemGui.getActiveAnalysis().Member + [FemMaterialMechanicalNonlinear.makeFemMaterialMechanicalNonlinear(" + string_lin_mat_obj + ")]" FreeCAD.ActiveDocument.openTransaction("Create FemMaterialMechanicalNonlinear") FreeCADGui.addModule("FemMaterialMechanicalNonlinear") FreeCADGui.doCommand(command_to_run) # set the material nonlinear property of the solver to nonlinear if only one solver is available and if this solver is a CalculiX solver solver_object = None for m in FemGui.getActiveAnalysis().Member: if m.isDerivedFrom('Fem::FemSolverObjectPython'): if not solver_object: solver_object = m else: # we do not change the material nonlinear attribut if we have more than one solver solver_object = None break if solver_object and solver_object.SolverType == 'FemSolverCalculix': solver_object.MaterialNonlinearity = "nonlinear"
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 Activated(self): FreeCAD.ActiveDocument.openTransaction("Create FemMeshGroup") FreeCADGui.addModule("ObjectsFem") self.mesh = FreeCADGui.Selection.getSelection()[0] # see 'with_gmsh_femmesh' in FemCommands for selection check FreeCADGui.doCommand("ObjectsFem.makeMeshGroup(FreeCAD.ActiveDocument, FreeCAD.ActiveDocument." + self.mesh.Name + ")") FreeCADGui.Selection.clearSelection()
def Activated(self): sel = FreeCADGui.Selection.getSelection() p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch") link = p.GetBool("FreeLinking",False) floorobj = [] warning = False for obj in sel : if not Draft.getType(obj) in ["Site", "Building"] : floorobj.append(obj) else : if link == True : floorobj.append(obj) else: warning = True if warning : message = translate( "Arch" , "You can put anything but Site, Building, Floor object in a Floor object.\n\ Floor object are not allowed to accept Site or Building object.\n\ Site, Building and Floor objects will be removed from the selection.\n\ You can change that in the preferences.\n" ) ArchCommands.printMessage( message ) if sel and len(floorobj) == 0: message = translate( "Arch" , "There is no valid object in the selection.\n\ Floor creation aborted.\n" ) ArchCommands.printMessage( message ) else : ss = "[ " for o in floorobj: ss += "FreeCAD.ActiveDocument." + o.Name + ", " ss += "]" FreeCAD.ActiveDocument.openTransaction(translate("Arch","Create Floor")) FreeCADGui.addModule("Arch") FreeCADGui.doCommand("Arch.makeFloor("+ss+")") FreeCAD.ActiveDocument.commitTransaction() FreeCAD.ActiveDocument.recompute()
def setEdit(self, vobj, mode=0): try: machine = run.getMachine(vobj.Object) except run.MustSaveError: error_message = ( "Please save the file before opening the task panel. " "This must be done because the location of the working " "directory is set to \"Beside *.FCStd File\"." ) App.Console.PrintError(error_message + "\n") QtGui.QMessageBox.critical( Gui.getMainWindow(), "Can't open Task Panel", error_message ) return False except run.DirectoryDoesNotExistError: error_message = "Selected working directory doesn't exist." App.Console.PrintError(error_message + "\n") QtGui.QMessageBox.critical( Gui.getMainWindow(), "Can't open Task Panel", error_message ) return False task = _TaskPanelFemSolverControl.ControlTaskPanel(machine) Gui.Control.showDialog(task) return True
def has_no_material_assigned(self): if ' *ERROR in calinput: no material was assigned' in self.ccx_stdout: without_material_elements = [] without_material_elemnodes = [] for line in self.ccx_stdout.splitlines(): if 'to element' in line: # print(line) # print(line.split()) non_mat_ele = int(line.split()[2]) # print(non_mat_ele) if non_mat_ele not in without_material_elements: without_material_elements.append(non_mat_ele) for e in without_material_elements: for n in self.mesh.FemMesh.getElementNodes(e): without_material_elemnodes.append(n) without_material_elements = sorted(without_material_elements) without_material_elemnodes = sorted(without_material_elemnodes) command_for_withoutmatnodes = 'without_material_elemnodes = ' + str(without_material_elemnodes) command_to_highlight = "Gui.ActiveDocument." + self.mesh.Name + ".HighlightedNodes = without_material_elemnodes" # some output for the user FreeCAD.Console.PrintError('\n\nCalculiX returned an error due to elements without materials.\n') FreeCAD.Console.PrintMessage('without_material_elements = {}\n'.format(without_material_elements)) FreeCAD.Console.PrintMessage(command_for_withoutmatnodes + '\n') if FreeCAD.GuiUp: import FreeCADGui FreeCADGui.doCommand(command_for_withoutmatnodes) # with this the list without_material_elemnodes will be available for further user interaction FreeCAD.Console.PrintMessage('\n') FreeCADGui.doCommand(command_to_highlight) FreeCAD.Console.PrintMessage('\nFollowing some commands to copy which highlight the elements without materials or to reset the highlighted nodes:\n') FreeCAD.Console.PrintMessage(command_to_highlight + '\n') FreeCAD.Console.PrintMessage('Gui.ActiveDocument.' + self.mesh.Name + '.HighlightedNodes = []\n\n') # command to reset the Highlighted Nodes return True else: return False
def has_nonpositive_jacobians(self): if '*ERROR in e_c3d: nonpositive jacobian' in self.ccx_stdout: nonpositive_jacobian_elements = [] nonpositive_jacobian_elenodes = [] for line in self.ccx_stdout.splitlines(): if 'determinant in element' in line: # print(line) # print(line.split()) non_posjac_ele = int(line.split()[3]) # print(non_posjac_ele) if non_posjac_ele not in nonpositive_jacobian_elements: nonpositive_jacobian_elements.append(non_posjac_ele) for e in nonpositive_jacobian_elements: for n in self.mesh.FemMesh.getElementNodes(e): nonpositive_jacobian_elenodes.append(n) nonpositive_jacobian_elements = sorted(nonpositive_jacobian_elements) nonpositive_jacobian_elenodes = sorted(nonpositive_jacobian_elenodes) command_for_nonposjacnodes = 'nonpositive_jacobian_elenodes = ' + str(nonpositive_jacobian_elenodes) command_to_highlight = "Gui.ActiveDocument." + self.mesh.Name + ".HighlightedNodes = nonpositive_jacobian_elenodes" # some output for the user FreeCAD.Console.PrintError('\n\nCalculiX returned an error due to nonpositive jacobian elements.\n') FreeCAD.Console.PrintMessage('nonpositive_jacobian_elements = {}\n'.format(nonpositive_jacobian_elements)) FreeCAD.Console.PrintMessage(command_for_nonposjacnodes + '\n') if FreeCAD.GuiUp: import FreeCADGui FreeCADGui.doCommand(command_for_nonposjacnodes) # with this the list nonpositive_jacobian_elenodes will be available for further user interaction FreeCAD.Console.PrintMessage('\n') FreeCADGui.doCommand(command_to_highlight) FreeCAD.Console.PrintMessage('\nFollowing some commands to copy which highlight the nonpositive jacobians or to reset the highlighted nodes:\n') FreeCAD.Console.PrintMessage(command_to_highlight + '\n') FreeCAD.Console.PrintMessage('Gui.ActiveDocument.' + self.mesh.Name + '.HighlightedNodes = []\n\n') # command to reset the Highlighted Nodes return True else: return False
def curve_to_script(i,c): com = ["import FreeCAD", "from FreeCAD import Vector", "import Part",""] if isinstance(c,Part.BSplineCurve): com.append("poles%d = %r"%(i,c.getPoles())) com.append("weights%d = %r"%(i,c.getWeights())) com.append("knots%d = %r"%(i,c.getKnots())) com.append("mults%d = %r"%(i,c.getMultiplicities())) com.append("periodic%d = %r"%(i,c.isPeriodic())) com.append("degree%d = %s"%(i,c.Degree)) com.append("rational%d = %r"%(i,c.isRational())) com.append("bs%d = Part.BSplineCurve()"%i) #com.append("bs%d.buildFromPolesMultsKnots(poles%d, mults%d, knots%d, periodic%d, degree%d, )"%(i,i,i,i,i,i)) com.append("bs%d.buildFromPolesMultsKnots(poles%d, mults%d, knots%d, periodic%d, degree%d, weights%d, rational%d)"%(i,i,i,i,i,i,i,i)) com.append('obj%d = FreeCAD.ActiveDocument.addObject("Part::Spline","BSplineCurve%d")'%(i,i)) com.append('obj%d.Shape = bs%d.toShape()'%(i,i)) elif isinstance(c,Part.BezierCurve): com.append("poles%d = %r"%(i,c.getPoles())) #com.append("degree%d = %s"%(i,c.Degree)) com.append("be%d = Part.BezierCurve()"%i) com.append("be%d.increase(%s)"%(i,c.Degree)) com.append("be%d.setPoles(poles%d)"%(i,i)) if c.isRational(): w = c.getWeights() for j in range(len(w)): com.append("be%d.setWeight(%i,%f)"%(i,j+1,w[j])) com.append('obj%d = FreeCAD.ActiveDocument.addObject("Part::Spline","BezierCurve%d")'%(i,i)) com.append('obj%d.Shape = be%d.toShape()'%(i,i)) com.append("") for s in com: FreeCADGui.doCommand(s)
def Activated(self): global QtGui, QtCore from PyQt4 import QtGui, QtCore self.Width = 0.1 self.Height = 1 self.Align = "Center" self.continueCmd = False p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch") self.JOIN_WALLS = p.GetBool("joinWallSketches") sel = FreeCADGui.Selection.getSelection() done = False self.existing = [] if sel: import Draft if Draft.getType(sel[0]) != "Wall": FreeCAD.ActiveDocument.openTransaction(str(translate("Arch","Create Wall"))) FreeCADGui.doCommand('import Arch') for obj in sel: FreeCADGui.doCommand('Arch.makeWall(FreeCAD.ActiveDocument.'+obj.Name+')') FreeCAD.ActiveDocument.commitTransaction() FreeCAD.ActiveDocument.recompute() done = True if not done: import DraftTrackers self.points = [] self.tracker = DraftTrackers.boxTracker() FreeCADGui.Snapper.getPoint(callback=self.getPoint,extradlg=self.taskbox())
def Execute(cls, base, template): FreeCADGui.addModule('PathScripts.PathJobGui') if template: template = "'%s'" % template else: template = 'None' FreeCADGui.doCommand('PathScripts.PathJobGui.Create(%s, %s)' % ([o.Name for o in base], template))
def browse(self): url = self.prefs.GetString("BimServerUrl","http://localhost:8082")+"/apps/bimviews" if self.prefs.GetBool("BimServerBrowser",False): FreeCADGui.addModule("WebGui") FreeCADGui.doCommand("WebGui.openBrowser(\""+url+"\")") else: QtGui.QDesktopServices.openUrl(QtCore.QUrl(url, QtCore.QUrl.TolerantMode))
def Activated(self): import PythonQt from PyQt4 import QtGui mw=QtGui.qApp.activeWindow() QtGui.QMessageBox.information(mw,"PyQt","""PyQt was loaded successfully.\n Load the PyQt sandbox now...""") FreeCADGui.activateWorkbench("PythonQtWorkbench")
def comboBox(): """Workbench selector combo box.""" cBox = QtGui.QComboBox() cBox.setMinimumWidth(220) listWB = Gui.listWorkbenches() listWBSorted = sorted(listWB) listWBSorted.reverse() for i in listWBSorted: try: icon = wbIcon(Gui.listWorkbenches()[i].Icon) except AttributeError: icon = QtGui.QIcon(":/icons/freecad") cBox.insertItem(0, icon, listWB[i].MenuText, listWB[i].__class__.__name__) cBox.insertSeparator(0) icon = QtGui.QIcon(":/icons/freecad") cBox.insertItem(0, icon, "Global shortcuts", "GlobalShortcuts") cBox.setCurrentIndex(0) activeWB = Gui.activeWorkbench().__class__.__name__ for count in range(cBox.count()): if cBox.itemData(count) == activeWB: cBox.setCurrentIndex(count) return cBox
def Activated(self): import PythonQt from PySide import QtGui mw = FreeCADGui.getMainWindow() QtGui.QMessageBox.information(mw, "PySide", """PySide was loaded successfully.""") FreeCADGui.activateWorkbench("PythonQtWorkbench")
def Activated(self): FreeCAD.ActiveDocument.openTransaction(translate("PathPost","Post Process the Selected path(s)")) FreeCADGui.addModule("PathScripts.PathPost") #select the PathProject that you want to post output from obj = FreeCADGui.Selection.getSelection() #default to the dumper post and default .tap file postname = "dumper_post" filename = "tmp.tap" #check if the user has a project and has set the default post and output filename if hasattr(obj[0],"Group") and hasattr(obj[0],"Path"): #Check for a machine and use the post processor if it's set proj = obj[0] postobj = None for p in obj[0].Group: if p.Name == "Machine": postobj = p #need to check for existance of these: obj.PostProcessor, obj.OutputFile if postobj and postobj.PostProcessor: sys.path.append(os.path.split(postobj.PostProcessor)[0]) lessextn = os.path.splitext(postobj.PostProcessor)[0] postname = os.path.split(lessextn)[1] if proj.OutputFile: filename = proj.OutputFile exec "import %s as current_post" % postname current_post.export(obj,filename) FreeCAD.ActiveDocument.commitTransaction() FreeCAD.ActiveDocument.recompute()
def render(self, output_filename=None, quick=False, nox=False): self._quick = quick self._nox = nox if self.dialect: self.layers = self.dialect(self.filenames) if self.verbose: print("Using Layers : ") self.layers.print_layermap() else: raise AttributeError('FreeCAD backend needs a valid layer map to do ' 'anything. Specify an implemented layer name ' 'dialect and try again. ') if not self._nox: FreeCADGui.showMainWindow() if not output_filename: output_filename = self.layers.pcbname if os.path.splitext(output_filename)[1].upper() == 'FCSTD': output_filename = output_filename[:-len('.fcstd')] self._output_name = output_filename self._create_output_file() self._create_body() self._create_top_surface() self._create_bottom_surface() self._create_drills() self._write_output_file() if not self._nox: FreeCADGui.getMainWindow().close()
def postStart(): "executes needed operations after loading a file" param = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Start") # switch workbench wb = param.GetString("AutoloadModule","") if wb: # don't switch workbenches if we are not in Start anymore if FreeCADGui.activeWorkbench() and (FreeCADGui.activeWorkbench().name() == "StartWorkbench"): FreeCADGui.activateWorkbench(wb) # close start tab cl = param.GetBool("closeStart",False) if cl: title = QtGui.QApplication.translate("Workbench","Start page") mw = FreeCADGui.getMainWindow() if mw: mdi = mw.findChild(QtGui.QMdiArea) if mdi: for mdichild in mdi.children(): for subw in mdichild.findChildren(QtGui.QMdiSubWindow): if subw.windowTitle() == title: subw.close()
def has_for_nonpositive_jacobians(self): if '*ERROR in e_c3d: nonpositive jacobian' in self.ccx_stdout: print('CalculiX returned an error due to nonpositive jacobian elements.') nonpositive_jacobian_elements = [] nonpositive_jacobian_elenodes = [] for line in self.ccx_stdout.splitlines(): if 'determinant in element' in line: # print line # print line.split() non_posjac_ele = int(line.split()[3]) # print(non_posjac_ele) if non_posjac_ele not in nonpositive_jacobian_elements: nonpositive_jacobian_elements.append(non_posjac_ele) for e in nonpositive_jacobian_elements: for n in self.mesh.FemMesh.getElementNodes(e): nonpositive_jacobian_elenodes.append(n) nonpositive_jacobian_elements = sorted(nonpositive_jacobian_elements) nonpositive_jacobian_elenodes = sorted(nonpositive_jacobian_elenodes) command_for_nonposjacnodes = 'nonpositive_jacobian_elenodes = ' + str(nonpositive_jacobian_elenodes) command_to_highlight = "Gui.ActiveDocument." + self.mesh.Name + ".HighlightedNodes = nonpositive_jacobian_elenodes" print('nonpositive_jacobian_elements = ' + str(nonpositive_jacobian_elements)) print(command_for_nonposjacnodes) print(command_to_highlight) print('Gui.ActiveDocument.Extrude_Mesh.HighlightedNodes = []\n') # command to reset the Highlighted Nodes if FreeCAD.GuiUp: import FreeCADGui FreeCADGui.doCommand(command_for_nonposjacnodes) FreeCADGui.doCommand(command_to_highlight) return True else: return False
def runme(): if PluginManager.toolbar >= 0: try: t=FreeCADGui.getMainWindow() wb=FreeCADGui.activeWorkbench() name="TEST" try: name=wb.name() except: wbs='a'+ str(wb) pat=r".*\.(.+) inst.*" import re m = re.match(pat, wbs) if m: name=m.group(1) import Part #FreeCAD.Console.PrintMessage("\n " +name) #FreeCAD.Console.PrintMessage(" gen ..") if name <>"NoneWorkbench": PluginManager.gentoolbars(name) #FreeCAD.Console.PrintMessage(" .. gened" ) except: sayexc("except 2") # PluginManager.gentoolbars("Robot") PluginManager.toolbar +=1 self=FreeCAD.Gui.getMainWindow() self.show()
def Activated(self): sel = FreeCADGui.Selection.getSelection() p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch") link = p.GetBool("FreeLinking",False) siteobj = [] warning = False for obj in sel : if Draft.getType(obj) == "Building": siteobj.append(obj) else : if link == True : siteobj.append(obj) else: warning = True if warning : message = translate( "Arch" , "Please select only Building objects or nothing!\n\ Site are not allowed to accept other object than Building.\n\ Other objects will be removed from the selection.\n\ You can change that in the preferences." ) ArchCommands.printMessage( message ) if sel and len(siteobj) == 0: message = translate( "Arch" , "There is no valid object in the selection.\n\ Site creation aborted." ) ArchCommands.printMessage( message ) else : ss = "[ " for o in siteobj: ss += "FreeCAD.ActiveDocument." + o.Name + ", " ss += "]" FreeCAD.ActiveDocument.openTransaction(translate("Arch","Create Site")) FreeCADGui.addModule("Arch") FreeCADGui.doCommand("Arch.makeSite("+ss+")") FreeCAD.ActiveDocument.commitTransaction() FreeCAD.ActiveDocument.recompute()
self.update() def removeElement(self): if self.obj: it = self.tree.currentItem() if it: comp = FreeCAD.ActiveDocument.getObject(str(it.toolTip(0))) ArchComponent.removeFromComponent(self.obj, comp) self.update() def accept(self): FreeCAD.ActiveDocument.recompute() FreeCADGui.ActiveDocument.resetEdit() return True def retranslateUi(self, TaskPanel): TaskPanel.setWindowTitle( QtGui.QApplication.translate("Arch", "Objects", None)) self.delButton.setText( QtGui.QApplication.translate("Arch", "Remove", None)) self.addButton.setText( QtGui.QApplication.translate("Arch", "Add", None)) self.title.setText( QtGui.QApplication.translate("Arch", "Objects seen by this section plane", None)) if FreeCAD.GuiUp: FreeCADGui.addCommand('Arch_SectionPlane', _CommandSectionPlane())
def createMesh(sel): FreeCAD.ActiveDocument.openTransaction("Create CFD mesh by GMSH") mesh_obj_name = sel[0].Name + "_Mesh" FreeCADGui.addModule("CfdMeshGmsh") # FemGmsh has been adjusted for CFD like only first order element FreeCADGui.doCommand("CfdMeshGmsh.makeCfdMeshGmsh('" + mesh_obj_name + "')") FreeCADGui.doCommand("App.ActiveDocument.ActiveObject.Part = App.ActiveDocument." + sel[0].Name) FreeCADGui.addModule("FemGui") if FemGui.getActiveAnalysis(): FreeCADGui.doCommand("FemGui.getActiveAnalysis().Member = FemGui.getActiveAnalysis().Member + [App.ActiveDocument.ActiveObject]") FreeCADGui.doCommand("Gui.ActiveDocument.setEdit(App.ActiveDocument.ActiveObject.Name)")
def launch(self): import FreeCADGui from PySide import QtGui # create the dialog self.dialog = FreeCADGui.PySideUic.loadUi( os.path.join(os.path.dirname(__file__), "AddonManager.ui")) # cleanup the leftovers from previous runs self.repos = [] self.macros = [] self.macro_repo_dir = tempfile.mkdtemp() self.doUpdate = [] self.addon_removed = False for worker in [ "update_worker", "check_worker", "show_worker", "showmacro_worker", "macro_worker", "install_worker" ]: if hasattr(self, worker): thread = getattr(self, worker) if thread: if thread.isFinished(): setattr(self, worker, None) self.dialog.tabWidget.setCurrentIndex(0) # these 2 settings to prevent loading an addon description on start (let the user click something first) self.firsttime = True self.firstmacro = True # restore window geometry and splitter state from stored state pref = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons") w = pref.GetInt("WindowWidth", 600) h = pref.GetInt("WindowHeight", 480) self.dialog.resize(w, h) sl = pref.GetInt("SplitterLeft", 298) sr = pref.GetInt("SplitterRight", 274) self.dialog.splitter.setSizes([sl, sr]) # set nice icons to everything, by theme with fallback to FreeCAD icons self.dialog.setWindowIcon(QtGui.QIcon(":/icons/AddonManager.svg")) self.dialog.buttonExecute.setIcon( QtGui.QIcon.fromTheme("execute", QtGui.QIcon(":/icons/button_valid.svg"))) self.dialog.buttonUninstall.setIcon( QtGui.QIcon.fromTheme("cancel", QtGui.QIcon(":/icons/edit_Cancel.svg"))) self.dialog.buttonInstall.setIcon( QtGui.QIcon.fromTheme("download", QtGui.QIcon(":/icons/edit_OK.svg"))) self.dialog.buttonUpdateAll.setIcon( QtGui.QIcon(":/icons/button_valid.svg")) self.dialog.buttonConfigure.setIcon( QtGui.QIcon(":/icons/preferences-system.svg")) self.dialog.tabWidget.setTabIcon(0, QtGui.QIcon(":/icons/Group.svg")) self.dialog.tabWidget.setTabIcon( 1, QtGui.QIcon(":/icons/applications-python.svg")) # enable/disable stuff self.dialog.buttonExecute.setEnabled(False) self.dialog.buttonUninstall.setEnabled(False) self.dialog.buttonInstall.setEnabled(False) self.dialog.buttonUpdateAll.setEnabled(False) # connect slots self.dialog.buttonExecute.clicked.connect(self.executemacro) self.dialog.rejected.connect(self.reject) self.dialog.buttonInstall.clicked.connect(self.install) self.dialog.buttonUninstall.clicked.connect(self.remove) self.dialog.buttonUpdateAll.clicked.connect(self.apply_updates) self.dialog.listWorkbenches.currentRowChanged.connect(self.show) self.dialog.tabWidget.currentChanged.connect(self.switchtab) self.dialog.listMacros.currentRowChanged.connect(self.show_macro) self.dialog.buttonConfigure.clicked.connect(self.show_config) # allow to open links in browser self.dialog.description.setOpenLinks(True) self.dialog.description.setOpenExternalLinks(True) # center the dialog over the FreeCAD window mw = FreeCADGui.getMainWindow() self.dialog.move(mw.frameGeometry().topLeft() + mw.rect().center() - self.dialog.rect().center()) # populate the list self.update() # rock 'n roll!!! self.dialog.exec_()
def Activated(self): from FreeCAD import Base import Draft #import re #import math #import sys NodeList = {} MemberList = {} ProjectDescription = '' numNode = 0 #factor = 25.42 factor = 1 path = 'c:\\Frame3DD-master\\examples\\' try: fName = QFileDialog.getOpenFileName( None, QString.fromLocal8Bit("Read a Frame3DD's 3DD file"), path, "*.3DD") # PyQt4 # "here the text displayed on windows" "here the filter (extension)" except Exception: fName, Filter = PySide.QtGui.QFileDialog.getOpenFileName( None, "Read a Frame3DD's 3DD file", path, "*.3DD") #PySide print("src: " + fName) DesName = FreeCAD.getHomePath() + "bin/hFrame3DDfc.3DD" print("Des: " + DesName) shutil.copyfile(fName, DesName) #000000000000000000000000000000000000000000000000000000000000000000 fp = open(fName) line = fp.readline().strip() print(line) #node 11111111111111111111111111111111111111111111111111 line = moveon(fp) print(line) data = line.split() numNode = int(data[0]) print("numNode: " + str(numNode)) line = moveon(fp) nodeCount = 1 dataNode = line.split() NodeList[dataNode[0]] = Node(dataNode[0], float(dataNode[1]), float(dataNode[2]), float(dataNode[3])) nodeCount += 1 while 1: line = moveon(fp) dataNode = line.split() #print (dataNode[0]) NodeList[dataNode[0]] = Node(dataNode[0], float(dataNode[1]), float(dataNode[2]), float(dataNode[3])) nodeCount += 1 if nodeCount > numNode: break #node 11111111111111111111111111111111111111111111111111111111111 GrpNode = FreeCAD.ActiveDocument.getObject('Nodes') if GrpNode != None: GrpNode.removeObjectsFromDocument() else: FreeCAD.ActiveDocument.addObject("App::DocumentObjectGroup", "Nodes") GrpNode = FreeCAD.ActiveDocument.getObject('Nodes') for id in NodeList: #Msg(id ); Msg( iNode) ; Msg('\n') iPoint = Draft.makePoint(NodeList[id].x * factor, NodeList[id].y * factor, NodeList[id].z * factor) iPoint.Label = "N" + id iPoint.ViewObject.PointColor = (0.667, 0.000, 0.000) GrpNode.addObject(iPoint) #GrpNode.append(iPoint) #reaction 222222222222222222222222222222222222222222222222222222 line = moveon(fp) data = line.split() numReaction = int(data[0]) print("numReaction: " + str(numReaction)) if numReaction > 0: for j in range(numReaction): line = moveon(fp) #data = line.split() # Member 333333333333333333333333333333333333333 line = moveon(fp) data = line.split() numMember = int(data[0]) print("numMember: " + str(numMember)) line = moveon(fp) memberCount = 1 dataMember = line.split() MemberList[dataMember[0]] = Member(dataMember[0], dataMember[1], dataMember[2]) memberCount += 1 while 1: line = moveon(fp) dataMember = line.split() MemberList[dataMember[0]] = Member(dataMember[0], dataMember[1], dataMember[2]) memberCount += 1 if memberCount > numMember: break #member 3333333333333333333333333333333333333333333333333333333 GrpMember = FreeCAD.ActiveDocument.getObject('Members') if GrpMember != None: GrpMember.removeObjectsFromDocument() else: FreeCAD.ActiveDocument.addObject("App::DocumentObjectGroup", "Members") GrpMember = FreeCAD.ActiveDocument.getObject('Members') for id in MemberList: n1 = MemberList[id].n1 n2 = MemberList[id].n2 points = [ Base.Vector(NodeList[n1].x * factor, NodeList[n1].y * factor, NodeList[n1].z * factor), Base.Vector(NodeList[n2].x * factor, NodeList[n2].y * factor, NodeList[n2].z * factor) ] iMember = Draft.makeWire(points, closed=False, face=True, support=None) iMember.Label = "M" + id GrpMember.addObject(iMember) #GrpMember.append(iMember) # 444444444444444444444 line = moveon(fp) line = moveon(fp) line = moveon(fp) line = moveon(fp) line = moveon(fp) # AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA #Static line = moveon(fp) data = line.split() print(line) numSLC = int(data[0]) print("numSLC: " + str(numSLC)) GLC = [] Larrow = 100.0 ULarrow = 20.0 GrpSLoadCase = FreeCAD.ActiveDocument.getObject('StaticLoadCases') if GrpSLoadCase != None: GrpSLoadCase.removeObjectsFromDocument() else: FreeCAD.ActiveDocument.addObject("App::DocumentObjectGroup", "StaticLoadCases") GrpSLoadCase = FreeCAD.ActiveDocument.getObject('StaticLoadCases') for i in range(numSLC): # Begin Static Load Case 1 of 2 # gravitational acceleration for self-weight loading (global) #.gX gY gZ #.in./s^2 in./s^2 in./s^2 print(" ") print("LC = " + str(i)) print(" ") line = moveon(fp) #0 0 0 iLoadCase = FreeCAD.ActiveDocument.addObject( "App::DocumentObjectGroup", "SLC" + str(i)) GLC.append(iLoadCase) GrpSLoadCase.addObject(GLC[i]) # number of loaded nodes (Point Load) aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa line = moveon(fp) print(line) data = line.split() numLN = int(data[0]) print("numLN: " + str(numLN)) if numLN > 0: #.n Fx Fy Fz Mxx Myy Mzz #. kip kip kip in.k in.k in.k GPLarrow = [] for j in range(numLN): #2 0 -10.0 0 0 0 0 #3 0 -20.0 0 0 0 0 print("PL = " + str(j)) tStr = "" tStr = "LC" + str(i) + "PL" + str(j) iPointLoad = FreeCAD.ActiveDocument.addObject( "App::DocumentObjectGroup", tStr) GPLarrow.append(iPointLoad) GLC[i].addObject(GPLarrow[j]) line = moveon(fp) data = line.split() n1 = str(data[0]) Fx = data[1] Fy = data[2] Fz = data[3] Mx = data[4] My = data[5] Mz = data[6] if Fx != "0": #Vertical pointsLN = [ Base.Vector(NodeList[n1].x * factor, NodeList[n1].y * factor, NodeList[n1].z * factor), Base.Vector((NodeList[n1].x - Larrow) * factor, (NodeList[n1].y) * factor, (NodeList[n1].z) * factor) ] iPointLoadV = Draft.makeWire(pointsLN, closed=False, face=True, support=None) iPointLoadV.Label = "LC" + str(i) + "PL" + str( j) + "FxV" iPointLoadV.ViewObject.LineColor = (0.667, 0., 0.000) GPLarrow[j].addObject(iPointLoadV) #Arrow Left pointsLNL = [ Base.Vector((NodeList[n1].x - Larrow) * factor, (NodeList[n1].y) * factor, NodeList[n1].z * factor), Base.Vector( (NodeList[n1].x - Larrow + Larrow / 10.0) * factor, (NodeList[n1].y + Larrow / 10.0) * factor, NodeList[n1].z * factor) ] iPointLoadL = Draft.makeWire(pointsLNL, closed=False, face=True, support=None) iPointLoadL.Label = "LC" + str(i) + "PL" + str( j) + "FxL" iPointLoadL.ViewObject.LineColor = (0.667, 0., 0.000) GPLarrow[j].addObject(iPointLoadL) #Arrow Right pointsLNR = [ Base.Vector((NodeList[n1].x - Larrow) * factor, (NodeList[n1].y) * factor, NodeList[n1].z * factor), Base.Vector( (NodeList[n1].x - Larrow + Larrow / 10.0) * factor, (NodeList[n1].y - Larrow / 10.0) * factor, NodeList[n1].z * factor) ] iPointLoadR = Draft.makeWire(pointsLNR, closed=False, face=True, support=None) iPointLoadR.Label = "LC" + str(i) + "PL" + str( j) + "FxR" iPointLoadR.ViewObject.LineColor = (0.667, 0., 0.000) GPLarrow[j].addObject(iPointLoadR) if Fy != "0": #Vertical pointsLN = [ Base.Vector(NodeList[n1].x * factor, NodeList[n1].y * factor, NodeList[n1].z * factor), Base.Vector((NodeList[n1].x) * factor, (NodeList[n1].y - Larrow) * factor, (NodeList[n1].z) * factor) ] iPointLoadV = Draft.makeWire(pointsLN, closed=False, face=True, support=None) iPointLoadV.Label = "LC" + str(i) + "PL" + str( j) + "FyV" iPointLoadV.ViewObject.LineColor = (0., 0.667, 0.000) GPLarrow[j].addObject(iPointLoadV) #Arrow Left pointsLNL = [ Base.Vector(NodeList[n1].x * factor, (NodeList[n1].y - Larrow) * factor, NodeList[n1].z * factor), Base.Vector( (NodeList[n1].x - Larrow / 10.0) * factor, (NodeList[n1].y - Larrow + Larrow / 10.0) * factor, NodeList[n1].z * factor) ] iPointLoadL = Draft.makeWire(pointsLNL, closed=False, face=True, support=None) iPointLoadL.Label = "LC" + str(i) + "PL" + str( j) + "FyL" iPointLoadL.ViewObject.LineColor = (0., 0.667, 0.000) GPLarrow[j].addObject(iPointLoadL) #Arrow Right pointsLNR = [ Base.Vector(NodeList[n1].x * factor, (NodeList[n1].y - Larrow) * factor, NodeList[n1].z * factor), Base.Vector( (NodeList[n1].x + Larrow / 10.0) * factor, (NodeList[n1].y - Larrow + Larrow / 10.0) * factor, NodeList[n1].z * factor) ] iPointLoadR = Draft.makeWire(pointsLNR, closed=False, face=True, support=None) iPointLoadR.Label = "LC" + str(i) + "PL" + str( j) + "FyR" iPointLoadR.ViewObject.LineColor = (0., 0.667, 0.000) GPLarrow[j].addObject(iPointLoadR) if Fz != "0": #Vertical pointsLN = [ Base.Vector(NodeList[n1].x * factor, NodeList[n1].y * factor, NodeList[n1].z * factor), Base.Vector((NodeList[n1].x) * factor, (NodeList[n1].y) * factor, (NodeList[n1].z - Larrow) * factor) ] iPointLoadV = Draft.makeWire(pointsLN, closed=False, face=True, support=None) iPointLoadV.Label = "LC" + str(i) + "PL" + str( j) + "FzV" iPointLoadV.ViewObject.LineColor = (0., 0., 0.667) GPLarrow[j].addObject(iPointLoadV) #Arrow Left pointsLNL = [ Base.Vector(NodeList[n1].x * factor, (NodeList[n1].y) * factor, (NodeList[n1].z - Larrow) * factor), Base.Vector( (NodeList[n1].x - Larrow / 10.0) * factor, (NodeList[n1].y) * factor, (NodeList[n1].z - Larrow + Larrow / 10.0) * factor) ] iPointLoadL = Draft.makeWire(pointsLNL, closed=False, face=True, support=None) iPointLoadL.Label = "LC" + str(i) + "PL" + str( j) + "FzL" iPointLoadL.ViewObject.LineColor = (0., 0., 0.667) GPLarrow[j].addObject(iPointLoadL) #Arrow Right pointsLNR = [ Base.Vector(NodeList[n1].x * factor, (NodeList[n1].y) * factor, (NodeList[n1].z - Larrow) * factor), Base.Vector( (NodeList[n1].x + Larrow / 10.0) * factor, (NodeList[n1].y) * factor, (NodeList[n1].z - Larrow + Larrow / 10.0) * factor) ] iPointLoadR = Draft.makeWire(pointsLNR, closed=False, face=True, support=None) iPointLoadR.Label = "LC" + str(i) + "PL" + str( j) + "FzR" iPointLoadR.ViewObject.LineColor = (0., 0., 0.667) GPLarrow[j].addObject(iPointLoadR) if Mx != 0: iMx = 1 if My != 0: iMy = 1 if My != 0: iMy = 1 # number of uniform loads bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb #line = fp.readline().strip() line = moveon(fp) print(line) data = line.split() numUL = int(data[0]) print("numUL: " + str(numUL)) if numUL > 0: #.e Ux Uy Uz # N/mm N/mm N/mm GULarrow = [] for j in range(numUL): #2 0 0.1 0 #1 0 0 0.1 iuniformLoad = FreeCAD.ActiveDocument.addObject( "App::DocumentObjectGroup", "UL" + str(j)) GULarrow.append(iuniformLoad) GLC[i].addObject(GULarrow[j]) line = moveon(fp) data = line.split() n0 = str(data[0]) n1 = MemberList[n0].n1 n2 = MemberList[n0].n2 Ux = data[1] Uy = data[2] Uz = data[3] iUx = 0 iUy = 0 iUz = 0 if Ux != "0": #n1 #Vertical pointsUL = [ Base.Vector(NodeList[n1].x * factor, NodeList[n1].y * factor, NodeList[n1].z * factor), Base.Vector((NodeList[n1].x - ULarrow) * factor, (NodeList[n1].y) * factor, (NodeList[n1].z) * factor) ] iuniformLoadV = Draft.makeWire(pointsUL, closed=False, face=True, support=None) iuniformLoadV.Label = "ULa" + str(j) + "V" iuniformLoadV.ViewObject.LineColor = (0.667, 0., 0.) GULarrow[j].addObject(iuniformLoadV) #Arrow Left pointsULL = [ Base.Vector((NodeList[n1].x - ULarrow) * factor, (NodeList[n1].y) * factor, NodeList[n1].z * factor), Base.Vector( (NodeList[n1].x - ULarrow + Larrow / 10.0) * factor, (NodeList[n1].y + Larrow / 10.0) * factor, NodeList[n1].z * factor) ] iuniformLoadL = Draft.makeWire(pointsULL, closed=False, face=True, support=None) iuniformLoadL.Label = "ULa" + str(j) + "L" iuniformLoadL.ViewObject.LineColor = (0.667, 0., 0.) GULarrow[j].addObject(iuniformLoadL) #Arrow Right pointsULR = [ Base.Vector((NodeList[n1].x - ULarrow) * factor, (NodeList[n1].y) * factor, NodeList[n1].z * factor), Base.Vector( (NodeList[n1].x - ULarrow + Larrow / 10.0) * factor, (NodeList[n1].y - Larrow / 10.0) * factor, NodeList[n1].z * factor) ] iuniformLoadR = Draft.makeWire(pointsULR, closed=False, face=True, support=None) iuniformLoadR.Label = "ULa" + str(j) + "R" iuniformLoadR.ViewObject.LineColor = (0.667, 0., 0.) GULarrow[j].addObject(iuniformLoadR) #n2 #Vertical pointsULn2 = [ Base.Vector(NodeList[n2].x * factor, NodeList[n2].y * factor, NodeList[n2].z * factor), Base.Vector((NodeList[n2].x - ULarrow) * factor, (NodeList[n2].y) * factor, (NodeList[n2].z) * factor) ] iuniformLoadV = Draft.makeWire(pointsULn2, closed=False, face=True, support=None) iuniformLoadV.Label = "ULb" + str(j) + "V" iuniformLoadV.ViewObject.LineColor = (0.667, 0., 0.) GULarrow[j].addObject(iuniformLoadV) #Arrow Left pointsULLn2 = [ Base.Vector((NodeList[n2].x - ULarrow) * factor, (NodeList[n2].y) * factor, NodeList[n2].z * factor), Base.Vector( (NodeList[n2].x - ULarrow + Larrow / 10.0) * factor, (NodeList[n2].y - Larrow / 10.0) * factor, NodeList[n2].z * factor) ] iuniformLoadL = Draft.makeWire(pointsULLn2, closed=False, face=True, support=None) iuniformLoadL.Label = "ULb" + str(j) + "L" iuniformLoadL.ViewObject.LineColor = (0.667, 0., 0.) GULarrow[j].addObject(iuniformLoadL) #Arrow Right pointsULRn2 = [ Base.Vector((NodeList[n2].x - ULarrow) * factor, (NodeList[n2].y) * factor, NodeList[n2].z * factor), Base.Vector( (NodeList[n2].x - ULarrow + Larrow / 10.0) * factor, (NodeList[n2].y + Larrow / 10.0) * factor, NodeList[n2].z * factor) ] iuniformLoadR = Draft.makeWire(pointsULRn2, closed=False, face=True, support=None) iuniformLoadR.Label = "ULb" + str(j) + "R" iuniformLoadR.ViewObject.LineColor = (0.667, 0., 0.) GULarrow[j].addObject(iuniformLoadR) #line linking n1 & n2 pointsULn1n2 = [ Base.Vector((NodeList[n1].x - ULarrow) * factor, (NodeList[n1].y) * factor, NodeList[n1].z * factor), Base.Vector((NodeList[n2].x - ULarrow) * factor, (NodeList[n2].y) * factor, NodeList[n2].z * factor) ] iuniformLoadLab = Draft.makeWire(pointsULn1n2, closed=False, face=True, support=None) iuniformLoadLab.Label = "ULab" + str(j) + "Link" iuniformLoadLab.ViewObject.LineColor = (0.667, 0., 0.) GULarrow[j].addObject(iuniformLoadLab) if Uy != "0": #n1 #Vertical pointsUL = [ Base.Vector(NodeList[n1].x * factor, NodeList[n1].y * factor, NodeList[n1].z * factor), Base.Vector((NodeList[n1].x) * factor, (NodeList[n1].y - ULarrow) * factor, (NodeList[n1].z) * factor) ] iuniformLoadV = Draft.makeWire(pointsUL, closed=False, face=True, support=None) iuniformLoadV.Label = "ULa" + str(j) + "V" iuniformLoadV.ViewObject.LineColor = (0., 0.667, 0.) GULarrow[j].addObject(iuniformLoadV) #Arrow Left pointsULL = [ Base.Vector(NodeList[n1].x * factor, (NodeList[n1].y - ULarrow) * factor, NodeList[n1].z * factor), Base.Vector( (NodeList[n1].x - Larrow / 10.0) * factor, (NodeList[n1].y - ULarrow + Larrow / 10.0) * factor, NodeList[n1].z * factor) ] iuniformLoadL = Draft.makeWire(pointsULL, closed=False, face=True, support=None) iuniformLoadL.Label = "ULa" + str(j) + "L" iuniformLoadL.ViewObject.LineColor = (0., 0.667, 0.) GULarrow[j].addObject(iuniformLoadL) #Arrow Right pointsULR = [ Base.Vector(NodeList[n1].x * factor, (NodeList[n1].y - ULarrow) * factor, NodeList[n1].z * factor), Base.Vector( (NodeList[n1].x + Larrow / 10.0) * factor, (NodeList[n1].y - ULarrow + Larrow / 10.0) * factor, NodeList[n1].z * factor) ] iuniformLoadR = Draft.makeWire(pointsULR, closed=False, face=True, support=None) iuniformLoadR.Label = "ULa" + str(j) + "R" iuniformLoadR.ViewObject.LineColor = (0., 0.667, 0.) GULarrow[j].addObject(iuniformLoadR) #n2 #Vertical pointsULn2 = [ Base.Vector(NodeList[n2].x * factor, NodeList[n2].y * factor, NodeList[n2].z * factor), Base.Vector((NodeList[n2].x) * factor, (NodeList[n2].y - ULarrow) * factor, (NodeList[n2].z) * factor) ] iuniformLoadV = Draft.makeWire(pointsULn2, closed=False, face=True, support=None) iuniformLoadV.Label = "ULb" + str(j) + "V" iuniformLoadV.ViewObject.LineColor = (0., 0.667, 0.) GULarrow[j].addObject(iuniformLoadV) #Arrow Left pointsULLn2 = [ Base.Vector(NodeList[n2].x * factor, (NodeList[n2].y - ULarrow) * factor, NodeList[n2].z * factor), Base.Vector( (NodeList[n2].x - Larrow / 10.0) * factor, (NodeList[n2].y - ULarrow + Larrow / 10.0) * factor, NodeList[n2].z * factor) ] iuniformLoadL = Draft.makeWire(pointsULLn2, closed=False, face=True, support=None) iuniformLoadL.Label = "ULb" + str(j) + "L" iuniformLoadL.ViewObject.LineColor = (0., 0.667, 0.) GULarrow[j].addObject(iuniformLoadL) #Arrow Right pointsULRn2 = [ Base.Vector(NodeList[n2].x * factor, (NodeList[n2].y - ULarrow) * factor, NodeList[n2].z * factor), Base.Vector( (NodeList[n2].x + Larrow / 10.0) * factor, (NodeList[n2].y - ULarrow + Larrow / 10.0) * factor, NodeList[n2].z * factor) ] iuniformLoadR = Draft.makeWire(pointsULRn2, closed=False, face=True, support=None) iuniformLoadR.Label = "ULb" + str(j) + "R" iuniformLoadR.ViewObject.LineColor = (0., 0.667, 0.) GULarrow[j].addObject(iuniformLoadR) #line linking n1 & n2 pointsULn1n2 = [ Base.Vector(NodeList[n1].x * factor, (NodeList[n1].y - ULarrow) * factor, NodeList[n1].z * factor), Base.Vector(NodeList[n2].x * factor, (NodeList[n2].y - ULarrow) * factor, NodeList[n2].z * factor) ] iuniformLoadLab = Draft.makeWire(pointsULn1n2, closed=False, face=True, support=None) iuniformLoadLab.Label = "ULab" + str(j) + "Link" iuniformLoadLab.ViewObject.LineColor = (0., 0.667, 0.) GULarrow[j].addObject(iuniformLoadLab) if Uz != "0": #n1 #Vertical pointsUL = [ Base.Vector(NodeList[n1].x * factor, NodeList[n1].y * factor, NodeList[n1].z * factor), Base.Vector((NodeList[n1].x) * factor, (NodeList[n1].y) * factor, (NodeList[n1].z - ULarrow) * factor) ] iuniformLoadV = Draft.makeWire(pointsUL, closed=False, face=True, support=None) iuniformLoadV.Label = "ULa" + str(j) + "V" iuniformLoadV.ViewObject.LineColor = (0., 0., 0.667) GULarrow[j].addObject(iuniformLoadV) #Arrow Left pointsULL = [ Base.Vector(NodeList[n1].x * factor, (NodeList[n1].y) * factor, (NodeList[n1].z - ULarrow) * factor), Base.Vector( (NodeList[n1].x - Larrow / 10.0) * factor, (NodeList[n1].y - ULarrow + Larrow / 10.0) * factor, NodeList[n1].z * factor) ] iuniformLoadL = Draft.makeWire(pointsULL, closed=False, face=True, support=None) iuniformLoadL.Label = "ULa" + str(j) + "L" iuniformLoadL.ViewObject.LineColor = (0., 0., 0.667) GULarrow[j].addObject(iuniformLoadL) #Arrow Right pointsULR = [ Base.Vector(NodeList[n1].x * factor, (NodeList[n1].y) * factor, (NodeList[n1].z - ULarrow) * factor), Base.Vector( (NodeList[n1].x + Larrow / 10.0) * factor, (NodeList[n1].y - ULarrow + Larrow / 10.0) * factor, NodeList[n1].z * factor) ] iuniformLoadR = Draft.makeWire(pointsULR, closed=False, face=True, support=None) iuniformLoadR.Label = "ULa" + str(j) + "R" iuniformLoadR.ViewObject.LineColor = (0., 0., 0.667) GULarrow[j].addObject(iuniformLoadR) #n2 #Vertical pointsULn2 = [ Base.Vector(NodeList[n2].x * factor, NodeList[n2].y * factor, NodeList[n2].z * factor), Base.Vector((NodeList[n2].x) * factor, (NodeList[n2].y) * factor, (NodeList[n2].z - ULarrow) * factor) ] iuniformLoadV = Draft.makeWire(pointsULn2, closed=False, face=True, support=None) iuniformLoadV.Label = "ULb" + str(j) + "V" iuniformLoadV.ViewObject.LineColor = (0., 0., 0.667) GULarrow[j].addObject(iuniformLoadV) #Arrow Left pointsULLn2 = [ Base.Vector(NodeList[n2].x * factor, (NodeList[n2].y) * factor, (NodeList[n2].z - ULarrow) * factor), Base.Vector( (NodeList[n2].x - Larrow / 10.0) * factor, (NodeList[n2].y) * factor, (NodeList[n2].z - ULarrow + Larrow / 10.0) * factor) ] iuniformLoadL = Draft.makeWire(pointsULLn2, closed=False, face=True, support=None) iuniformLoadL.Label = "ULb" + str(j) + "L" iuniformLoadL.ViewObject.LineColor = (0., 0., 0.667) GULarrow[j].addObject(iuniformLoadL) #Arrow Right pointsULRn2 = [ Base.Vector(NodeList[n2].x * factor, (NodeList[n2].y) * factor, (NodeList[n2].z - ULarrow) * factor), Base.Vector( (NodeList[n2].x + Larrow / 10.0) * factor, (NodeList[n2].y) * factor, (NodeList[n2].z - ULarrow + Larrow / 10.0) * factor) ] iuniformLoadR = Draft.makeWire(pointsULRn2, closed=False, face=True, support=None) iuniformLoadR.Label = "ULb" + str(j) + "R" iuniformLoadR.ViewObject.LineColor = (0., 0., 0.667) GULarrow[j].addObject(iuniformLoadR) #line linking n1 & n2 pointsULn1n2 = [ Base.Vector(NodeList[n1].x * factor, (NodeList[n1].y) * factor, (NodeList[n1].z - ULarrow) * factor), Base.Vector(NodeList[n2].x * factor, (NodeList[n2].y) * factor, (NodeList[n2].z - ULarrow) * factor) ] iuniformLoadLab = Draft.makeWire(pointsULn1n2, closed=False, face=True, support=None) iuniformLoadLab.Label = "ULab" + str(j) + "Link" iuniformLoadLab.ViewObject.LineColor = (0., 0., 0.667) GULarrow[j].addObject(iuniformLoadLab) # number of trapezoidal loads ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc #line = fp.readline().strip() line = moveon(fp) print(line) data = line.split() numTL = int(data[0]) print("numTL: " + str(numTL)) if numTL > 0: #.e x1 x2 w1 w2 # mm mm N/mm N/mm GTLarrow = [] for j in range(numTL): # 3 20 80 0.01 0.05 # location and loading - local x-axis # 0 0 0 0 # location and loading - local y-axis # 80 830 -0.05 0.07 # location and loading - local z-axis itrapezoidalLoad = FreeCAD.ActiveDocument.addObject( "App::DocumentObjectGroup", "trapezoidalL" + str(j)) GTLarrow.append(itrapezoidalLoad) GLC[i].addObject(GTLarrow[j]) line = moveon(fp) line = moveon(fp) line = moveon(fp) # number of internal concentrated loads ddddddddddddddddddddddddddddddddddddddddddddd line = moveon(fp) print(line) data = line.split() numICL = int(data[0]) print("numICL: " + str(numICL)) if numICL > 0: #.e Px Py Pz x # N N N mm GICLarrow = [] for j in range(numICL): # 1 0 100 -900 600 # 2 0 -200 200 800 iICLoad = FreeCAD.ActiveDocument.addObject( "App::DocumentObjectGroup", "ICL" + str(j)) GICLarrow.append(iICLoad) GLC[i].addObject(GICLarrow[j]) line = moveon(fp) # number of temperature loads eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee #line = fp.readline().strip() line = moveon(fp) print(line) data = line.split() numTempL = int(data[0]) print("numTempL: " + str(numTempL)) if numTempL > 0: #.e alpha hy hz Ty+ Ty- Tz+ Tz- # /degC mm mm degC degC degC degC GTempLarrow = [] for j in range(numTempL): #1 12e-6 10 10 20 10 10 -10 iTempLoad = FreeCAD.ActiveDocument.addObject( "App::DocumentObjectGroup", "TempL" + str(j)) GTempLarrow.append(iTempLoad) GLC[i].addObject(GTempLarrow[j]) line = moveon(fp) #print (line) data = line.split() n0 = str(data[0]) n1 = MemberList[n0].n1 n2 = MemberList[n0].n2 #n1,n2 #points=[ Base.Vector(NodeList[n1].x*factor,NodeList[n1].y*factor,NodeList[n1].z*factor ), Base.Vector(NodeList[n2].x*factor,NodeList[n2].y*factor,NodeList[n2].z*factor) ] #iTempLoadV = Draft.makeWire(points,closed=False,face=True,support=None) #iTempLoadV.Label = "TempLa"+str(j)+"V" #iTempLoadV.ViewObject.LineColor = (1.,0.,0.) #GTempLarrow[j].addObject(iTempLoadV) #MemberList[n0].ViewObject.LineColor = (1.,0.,0.) #print ('M'+n0) #tMember =FreeCAD.ActiveDocument.getObject('M1') #print (tMember) #tMember.ViewObject.LineColor = (1.,0.,0.) # number of nodes with prescribed displacements ffffffffffffffffffffffffffffffffffffffffffffffffffffff #line = fp.readline().strip() line = moveon(fp) print(line) data = line.split() numPD = int(data[0]) print("numPD: " + str(numPD)) if numPD > 0: #.n Dx Dy Dz Dxx Dyy Dzz #. in in in rad. rad. rad. GPDarrow = [] for j in range(numPD): # 8 0.1 0.0 0.0 0.0 0.0 0.0 print("PD = " + str(j)) tStr = "" tStr = "PD" + str(j) print(tStr) iPD = FreeCAD.ActiveDocument.addObject( "App::DocumentObjectGroup", tStr) GPDarrow.append(iPD) GLC[i].addObject(GPDarrow[j]) line = moveon(fp) #data = line.split() # BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB # dynamic #6 # number of desired dynamic modes of vibration print(" ") line = moveon(fp) data = line.split() print(line) numDLC = int(data[0]) print("numDLC: " + str(numDLC)) GDLC = [] if numDLC > 0: #1 # 1: subspace Jacobi 2: Stodola #0 # 0: consistent mass ... 1: lumped mass matrix #1e-9 # mode shape tolerance #0.0 # shift value ... for unrestrained structures #10.0 # exaggerate modal mesh deformations line = moveon(fp) line = moveon(fp) line = moveon(fp) line = moveon(fp) line = moveon(fp) #11111111111111111111111111111111111111111111111111111111111111111111111 # number of nodes with extra inertia line = moveon(fp) data = line.split() print(line) numExtInertia = int(data[0]) print("numExtInertia: " + str(numExtInertia)) if numExtInertia > 0: #.n Mass Ixx Iyy Izz # ton ton.mm^2 ton.mm^2 ton.mm^2 for j in range(numExtInertia): #1 0.1 0 0 0 line = moveon(fp) #data = line.split() #22222222222222222222222222222222222222222222222222222222222222222222 # frame elements with extra mass line = moveon(fp) data = line.split() print(line) numExtMass = int(data[0]) print("numExtMass: " + str(numExtMass)) if numExtMass > 0: #.n Mass Ixx Iyy Izz # ton ton.mm^2 ton.mm^2 ton.mm^2 for j in range(numExtMass): #1 0.1 0 0 0 line = moveon(fp) #data = line.split() #33333333333333333333333333333333333333333333333333333333333333333333333333333 # number of modes to animate, nA line = moveon(fp) data = line.split() print(line) numModesAni = int(data[0]) print("numModesAni: " + str(numModesAni)) if numModesAni > 0: # 1 2 3 4 5 6 # list of modes to animate - omit if nA == 0 line = moveon(fp) #2 # pan rate during animation line = moveon(fp) #Msg('Done!!\n\n') FreeCAD.ActiveDocument.recompute() FreeCADGui.activeDocument().activeView().viewAxonometric() FreeCADGui.SendMsgToActiveView("ViewFit")
for j in range(numExtMass): #1 0.1 0 0 0 line = moveon(fp) #data = line.split() #33333333333333333333333333333333333333333333333333333333333333333333333333333 # number of modes to animate, nA line = moveon(fp) data = line.split() print(line) numModesAni = int(data[0]) print("numModesAni: " + str(numModesAni)) if numModesAni > 0: # 1 2 3 4 5 6 # list of modes to animate - omit if nA == 0 line = moveon(fp) #2 # pan rate during animation line = moveon(fp) #Msg('Done!!\n\n') FreeCAD.ActiveDocument.recompute() FreeCADGui.activeDocument().activeView().viewAxonometric() FreeCADGui.SendMsgToActiveView("ViewFit") #Msg ("Well done.") FreeCADGui.addCommand('hFrame3DDfc3DDin', hFrame3DDfc3DDin())
def Activated(self): doc = '' obj = '' sublinks = '(' doc_num = 0 obj_num = 0 face_num = 0 edge_num = 0 vert_num = 0 selection = FreeCADGui.Selection.getSelectionEx() if selection == []: FreeCAD.Console.PrintError('Selection is empty.\n') for selobj in selection: if not selobj.DocumentName == doc: doc = selobj.DocumentName doc_num += 1 FreeCADGui.doCommand( "doc{} = FreeCAD.getDocument('{}')".format(doc_num, doc)) if not selobj.ObjectName == obj: obj = selobj.ObjectName obj_num += 1 FreeCADGui.doCommand("o{} = doc{}.getObject('{}')".format( obj_num, doc_num, obj)) if selobj.HasSubObjects: for sub in selobj.SubElementNames: sublinks += "(o{},('{}')),".format(obj_num, sub) if 'Vertex' in sub: vert_num += 1 FreeCADGui.doCommand("v{} = o{}.Shape.{}".format( vert_num, obj_num, sub)) if 'Edge' in sub: edge_num += 1 FreeCADGui.doCommand("e{} = o{}.Shape.{}".format( edge_num, obj_num, sub)) if 'Face' in sub: face_num += 1 FreeCADGui.doCommand("f{} = o{}.Shape.{}".format( face_num, obj_num, sub)) sublinks += ")" if len(sublinks) > 1: FreeCADGui.doCommand("_sub_link_buffer = {}".format(sublinks)) if obj_num > 1: ol = '' for oi in range(obj_num): ol += "o{},".format(oi + 1) FreeCADGui.doCommand("ol = ({})".format(ol)) if vert_num > 1: vl = '' for vi in range(vert_num): vl += "v{},".format(vi + 1) FreeCADGui.doCommand("vl = ({})".format(vl)) if edge_num > 1: el = '' for ei in range(edge_num): el += "e{},".format(ei + 1) FreeCADGui.doCommand("el = ({})".format(el)) if face_num > 1: fl = '' for fi in range(face_num): fl += "f{},".format(fi + 1) FreeCADGui.doCommand("fl = ({})".format(fl))
ol = '' for oi in range(obj_num): ol += "o{},".format(oi + 1) FreeCADGui.doCommand("ol = ({})".format(ol)) if vert_num > 1: vl = '' for vi in range(vert_num): vl += "v{},".format(vi + 1) FreeCADGui.doCommand("vl = ({})".format(vl)) if edge_num > 1: el = '' for ei in range(edge_num): el += "e{},".format(ei + 1) FreeCADGui.doCommand("el = ({})".format(el)) if face_num > 1: fl = '' for fi in range(face_num): fl += "f{},".format(fi + 1) FreeCADGui.doCommand("fl = ({})".format(fl)) def IsActive(self): if FreeCAD.ActiveDocument: selection = FreeCADGui.Selection.getSelectionEx() if selection: return True else: return False FreeCADGui.addCommand('to_console', ToConsole())
Another possibility is to rename the `'Circle'` object to `'Arc'`. Then both a circle and an arc would internally be `'Arc'` objects, and in the Gui Commands they both would use the `Arc` command. """ def __init__(self): self.closedCircle = True self.featureName = "Circle" def GetResources(self): """Set icon, menu and tooltip.""" return { 'Pixmap': 'Draft_Circle', 'Accel': "C, I", 'MenuText': QT_TRANSLATE_NOOP("Draft_Circle", "Circle"), 'ToolTip': QT_TRANSLATE_NOOP( "Draft_Circle", "Creates a circle (full circular arc).\nCTRL to snap, ALT to select tangent objects." ) } Gui.addCommand('Draft_Circle', Circle()) ## @}
if _v['gui'] & self.menu: self.appendMenu(_k, _v['cmd']) #self.init_dev_commands() def Activated(self): """ Called when switching to this workbench """ pass def Deactivated(self): """ Called when switiching away from this workbench """ pass def ContextMenu(self, recipient): """ Right-click menu options """ # "recipient" will be either "view" or "tree" for _k, _v in self.fn.items(): if _v['gui'] & self.context: self.appendContextMenu(_k, _v['cmds']) Gui.addWorkbench(TrailsWorkbench())
#* USA * #* * #*************************************************************************** # This is the start page template import os, FreeCAD, FreeCADGui, tempfile, time, zipfile, urllib, re, sys from PySide import QtGui from xml.etree.ElementTree import parse try: import io as cStringIO except: import cStringIO FreeCADGui.addLanguagePath(":/translations") FreeCADGui.updateLocale() def translate(context, text): "convenience function for the Qt translator" # return str(QtGui.QApplication.translate(context, text, None, QtGui.QApplication.UnicodeUTF8).toUtf8()) try: _encoding = QtGui.QApplication.UnicodeUTF8 u = QtGui.QApplication.translate(context, text, None, _encoding) except AttributeError: u = QtGui.QApplication.translate(context, text, None) if sys.version_info.major < 3: u = u.encode("utf8")
def MakePart(params, name, n=1): global formerDOC global LIST_license #name = PartName(params, 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__)) expVRML.say(models_dir) out_dir=models_dir+destination_dir if not os.path.exists(out_dir): os.makedirs(out_dir) #having a period '.' character in the model name REALLY messes with things. also '-' docname = name.replace(".","").replace("-","_") newdoc = App.newDocument(docname) App.setActiveDocument(docname) App.ActiveDocument=App.getDocument(docname) Gui.ActiveDocument=Gui.getDocument(docname) FreeCAD.Console.PrintMessage(params) pins_output = MakeResistorPin(params, n) base_output = MakeResistor(params, n) marking_output = MakeMarking(params, n) show(base_output) show(pins_output) if not (marking_output == 0): show(marking_output) doc = FreeCAD.ActiveDocument objs=GetListOfObjects(FreeCAD, doc) # select the color based on shape if (params.shape == "power") or (params.shape == "radial") or (params.shape == "shunt"): # white colour for power resistors chosen_body_color = ceramic_color chosen_body_color_key = ceramic_color_key elif (params.shape == "bare"): # metal/pin colour for bare resistors chosen_body_color = pins_color chosen_body_color_key = pins_color_key else: # light brown colour for din/axial/arrays/etc. chosen_body_color = body_color chosen_body_color_key = body_color_key # body and pin colours Color_Objects(Gui,objs[0],chosen_body_color) Color_Objects(Gui,objs[1],pins_color) col_body=Gui.ActiveDocument.getObject(objs[0].Name).DiffuseColor[0] col_pin=Gui.ActiveDocument.getObject(objs[1].Name).DiffuseColor[0] material_substitutions={ col_body[:-1]:chosen_body_color_key, col_pin[:-1]:pins_color_key } # optional marking bodies if (len(objs) >= 3): Color_Objects(Gui,objs[2],marking_color) col_marking=Gui.ActiveDocument.getObject(objs[2].Name).DiffuseColor[0] material_substitutions[col_marking[:-1]] = marking_color_key expVRML.say(material_substitutions) # fuse everything while len(objs) > 1: FreeCAD.Console.PrintMessage(len(objs)) FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name, objs[1].Name) objs = GetListOfObjects(FreeCAD, doc) doc.Label=docname #objs=GetListOfObjects(FreeCAD, doc) objs[0].Label=docname restore_Main_Tools() doc.Label = docname #save the STEP file exportSTEP(doc, name, out_dir) if LIST_license[0]=="": LIST_license=Lic.LIST_int_license LIST_license.append("") Lic.addLicenseToStep(out_dir+'/', name+".step", LIST_license,\ STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licOrg, STR_licPreProc) # scale and export Vrml model scale=1/2.54 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+name+'.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, name,out_dir) if save_memory == True: doc=FreeCAD.ActiveDocument FreeCAD.closeDocument(doc.Name) return 0
import FreeCADGui class Curve2(): """Curve2""" def GetResources(self): return { 'Pixmap': 'My_Command_Icon', # the name of a svg file available in the resources 'Accel': "Shift+2", # a default shortcut (optional) 'MenuText': "Two-Center Curve", 'ToolTip': "Add a two-center curve" } def Activated(self): "Do something here" return def IsActive(self): return FreeCADGui.ActiveDocument != None FreeCADGui.addCommand('Curve2', Curve2())
"""Validate the entry radius in the user interface. This function is called by the toolbar or taskpanel interface when a valid radius has been entered in the input field. """ import DraftGeomUtils self.rad = rad if len(self.tangents) == 2: cir = DraftGeomUtils.circleFrom2tan1rad(self.tangents[0], self.tangents[1], rad) if self.center: _c = DraftGeomUtils.findClosestCircle(self.center, cir) self.center = _c.Center else: self.center = cir[-1].Center elif self.tangents and self.tanpoints: cir = DraftGeomUtils.circleFrom1tan1pt1rad(self.tangents[0], self.tanpoints[0], rad) if self.center: _c = DraftGeomUtils.findClosestCircle(self.center, cir) self.center = _c.Center else: self.center = cir[-1].Center self.drawPolygon() Gui.addCommand('Draft_Polygon', Polygon()) ## @}
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA """Glass module for FreeCAD - Gui.""" import FreeCADGui as Gui import FreeCAD from PySide import QtGui from PySide import QtCore mode = 0 wid = QtGui.QWidget() mw = Gui.getMainWindow() p = FreeCAD.ParamGet("User parameter:BaseApp/Glass") try: mw.setDockOptions(mw.dockOptions() | mw.GroupedDragging) except AttributeError: pass def firstRun(): """Setup defaults on the first run.""" pTree = FreeCAD.ParamGet( "User parameter:BaseApp/Preferences/DockWindows/TreeView") pTree.SetBool("Enabled", True) pStyle = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/MainWindow")
'fem-material-fluid', 'MenuText': QtCore.QT_TRANSLATE_NOOP("FEM_MaterialFluid", "FEM material for Fluid"), 'Accel': "M, M", 'ToolTip': QtCore.QT_TRANSLATE_NOOP("FEM_MaterialFluid", "Creates a FEM material for Fluid") } self.is_active = 'with_analysis' def Activated(self): femDoc = FemGui.getActiveAnalysis().Document if FreeCAD.ActiveDocument is not femDoc: FreeCADGui.setActiveDocument(femDoc) FreeCAD.ActiveDocument.openTransaction("Create Fluid Material") FreeCADGui.addModule("ObjectsFem") FreeCADGui.doCommand( "ObjectsFem.makeMaterialFluid(FreeCAD.ActiveDocument, 'FluidMaterial')" ) FreeCADGui.doCommand("FreeCAD.ActiveDocument." + FemGui.getActiveAnalysis().Name + ".addObject(App.ActiveDocument.ActiveObject)") FreeCADGui.doCommand( "FreeCADGui.ActiveDocument.setEdit(FreeCAD.ActiveDocument.ActiveObject.Name)" ) FreeCADGui.addCommand('FEM_MaterialFluid', _CommandFemMaterialFluid())
# Reload tools reload(cq_cad_tools) # Explicitly load all needed functions from cq_cad_tools import FuseObjs_wColors, GetListOfObjects, restore_Main_Tools, \ exportSTEP, close_CQ_Example, exportVRML, saveFCdoc, z_RotateObject, Color_Objects, \ CutObjs_wColors, checkRequirements # from export_x3d import exportX3D, Mesh try: # Gui.SendMsgToActiveView("Run") # cq Gui from Gui.Command import * Gui.activateWorkbench("CadQueryWorkbench") import cadquery as cq from Helpers import show # CadQuery Gui except: try: from CadQuery.Gui.Command import * Gui.activateWorkbench("CadQueryWorkbench") import cadquery as cq from Helpers import show except: # catch *all* exceptions msg="missing CadQuery 0.3.0 or later Module!\r\n\r\n" msg+="https://github.com/jmwright/cadquery-freecad-module/wiki\n" reply = QtGui.QMessageBox.information(None,"Info ...",msg) # maui end
"PathToolBit", "Load an existing ToolBit object from a file") } def selectedTool(self): sel = FreeCADGui.Selection.getSelectionEx() if 1 == len(sel) and isinstance(sel[0].Object.Proxy, PathScripts.PathToolBit.ToolBit): return sel[0].Object return None def IsActive(self): return FreeCAD.ActiveDocument is not None def Activated(self): if PathScripts.PathToolBitGui.LoadTools(): FreeCAD.ActiveDocument.recompute() if FreeCAD.GuiUp: FreeCADGui.addCommand('Path_ToolBitCreate', CommandToolBitCreate()) FreeCADGui.addCommand('Path_ToolBitLoad', CommandToolBitLoad()) FreeCADGui.addCommand('Path_ToolBitSave', CommandToolBitSave(False)) FreeCADGui.addCommand('Path_ToolBitSaveAs', CommandToolBitSave(True)) CommandList = [ 'Path_ToolBitCreate', 'Path_ToolBitLoad', 'Path_ToolBitSave', 'Path_ToolBitSaveAs' ] FreeCAD.Console.PrintLog("Loading PathToolBitCmd... done\n")
FCC.PrintError("CommandFillet: two elements needed" + "\n") return if len(wires) != 2: FCC.PrintError("CommandFillet: two elements needed" + "\n") return for o in wires: FCC.PrintMessage("CommandFillet: " + Draft.getType(o) + "\n") # Choose only wires. # A test could be used to chose edges in general. if Draft.getType(o) not in "Wire": FCC.PrintError("CommandFillet: wires needed" + "\n") return doc = 'FreeCAD.ActiveDocument.' _wires = '[' + doc + wires[0].Name + ', ' + doc + wires[1].Name + ']' rems = [doc + 'removeObject("' + o.Name + '")' for o in wires] FreeCADGui.addModule("Draft") func = DraftTools.translate("draft", "Create fillet") arg = ['arc = DraftFillet.makeFillet(' + _wires + ')'] + rems +\ ['Draft.autogroup(arc)', 'FreeCAD.ActiveDocument.recompute()'] DraftGui.todo.delayCommit([(func, arg)]) if FreeCAD.GuiUp: FreeCADGui.addCommand('Draft_Fillet', CommandFillet())
if len(selection) == 2: FreeCADGui.doCommand( "CurvedShapes.makeNotchConnector(tools[0], [base], CutDepth=-50.0)" ) FreeCAD.ActiveDocument.recompute() def IsActive(self): """Here you can define if the command must be active or not (greyed) if certain conditions are met or not. This function is optional.""" if FreeCAD.ActiveDocument: return (True) else: return (False) def GetResources(self): return { 'Pixmap': os.path.join(CurvedShapes.get_module_path(), "Resources", "icons", "NotchConnector.svg"), 'Accel': "", # a default shortcut (optional) 'MenuText': "Notch Connector", 'ToolTip': __doc__ } FreeCADGui.addCommand('NotchConnector', NotchConnector())
return True return False def Activated(self): FreeCAD.ActiveDocument.openTransaction( translate("Path_Fixture", "Create a Fixture Offset")) FreeCADGui.addModule("PathScripts.PathFixture") snippet = ''' import Path import PathScripts from PathScripts import PathUtils prjexists = False obj = FreeCAD.ActiveDocument.addObject("Path::FeaturePython","Fixture") PathScripts.PathFixture.Fixture(obj) obj.Active = True PathScripts.PathFixture._ViewProviderFixture(obj.ViewObject) PathUtils.addToJob(obj) ''' FreeCADGui.doCommand(snippet) FreeCAD.ActiveDocument.commitTransaction() FreeCAD.ActiveDocument.recompute() if FreeCAD.GuiUp: # register the FreeCAD command FreeCADGui.addCommand('Path_Fixture', CommandPathFixture()) FreeCAD.Console.PrintLog("Loading PathFixture... done\n")
ImportGui.insert(filename, newname) importDoc = FreeCAD.ActiveDocument else: msg = "A part can only be imported from a FreeCAD '*.fcstd' file" QtGui.QMessageBox.information( QtGui.QApplication.activeWindow(), "Value Error", msg) return if importDoc == doc and partial == True: updateImportedParts(importDoc, True) else: updateImportedParts(importDoc) FreeCADGui.updateGui() importDoc.save() print(u"==== Assembly '{}' has been updated! =====".format( importDoc.FileName)) if importDoc != doc: FreeCAD.closeDocument(importDoc.Name) def GetResources(self): return { 'Pixmap': ':/icons/a2p_RecursiveUpdate.svg', 'MenuText': 'Update imports recursively', 'ToolTip': toolTip } FreeCADGui.addCommand('a2p_recursiveUpdateImportedPartsCommand', a2p_recursiveUpdateImportedPartsCommand())
def Activated(self): FreeCADGui.doCommand("import CurvedShapes") FreeCADGui.doCommand("import NotchConnector") selection = FreeCADGui.Selection.getSelection() if len(selection) < 2: return for sel in selection: if sel == selection[0]: FreeCADGui.doCommand( "base = FreeCAD.ActiveDocument.getObject('%s')" % (sel.Name)) elif sel == selection[1]: FreeCADGui.doCommand( "tools = [FreeCAD.ActiveDocument.getObject('%s')]" % (sel.Name)) else: FreeCADGui.doCommand( "tools.append(FreeCAD.ActiveDocument.getObject('%s'))" % (sel.Name)) FreeCADGui.doCommand( "CurvedShapes.makeNotchConnector(base, tools, CutDepth=50.0)") if len(selection) == 2: FreeCADGui.doCommand( "CurvedShapes.makeNotchConnector(tools[0], [base], CutDepth=-50.0)" ) FreeCAD.ActiveDocument.recompute()
def set_mesh_params(self): FreeCADGui.doCommand( "\nFreeCAD.ActiveDocument.{}.CharacteristicLengthMax " "= '{}'".format(self.mesh_obj.Name, self.clmax)) FreeCADGui.doCommand("FreeCAD.ActiveDocument.{}.MeshUtility " "= '{}'".format(self.mesh_obj.Name, self.utility)) FreeCADGui.doCommand("FreeCAD.ActiveDocument.{}.ElementDimension " "= '{}'".format(self.mesh_obj.Name, self.dimension)) FreeCADGui.doCommand("FreeCAD.ActiveDocument.{}.CellsBetweenLevels " "= {}".format(self.mesh_obj.Name, self.cellsbetweenlevels)) FreeCADGui.doCommand("FreeCAD.ActiveDocument.{}.EdgeRefinement " "= {}".format(self.mesh_obj.Name, self.edgerefine)) FreeCADGui.doCommand("FreeCAD.ActiveDocument.{}.PointInMesh " "= {}".format(self.mesh_obj.Name, self.PointInMesh))
def Activated(self): a2plib.setAutoSolve(True) # makes no sense without autosolve = ON doc = FreeCAD.activeDocument() fileName = doc.FileName workingDir, basicFileName = os.path.split(fileName) selectedFiles = [] partial = False selection = [ s for s in FreeCADGui.Selection.getSelection() if s.Document == FreeCAD.ActiveDocument and ( a2plib.isA2pPart(s) or a2plib.isA2pSketch()) ] if selection and len(selection) > 0: flags = QtGui.QMessageBox.StandardButton.Yes | QtGui.QMessageBox.StandardButton.No msg = u"Do you want to update only the selected parts?" response = QtGui.QMessageBox.information( QtGui.QApplication.activeWindow(), u"RECURSIVE UPDATE", msg, flags) if response == QtGui.QMessageBox.Yes: for s in selection: fDir, fName = os.path.split(s.sourceFile) selectedFiles.append(fName) partial = True filesToUpdate = [] subAsmNeedsUpdate, filesToUpdate = createUpdateFileList( fileName, workingDir, filesToUpdate, True, selectedFiles) for f in filesToUpdate: #------------------------------------------- # update necessary documents #------------------------------------------- # look only for filenames, not paths, as there are problems on WIN10 (Address-translation??) importDoc = None importDocIsOpen = False requestedFile = os.path.split(f)[1] for d in FreeCAD.listDocuments().values(): recentFile = os.path.split(d.FileName)[1] if requestedFile == recentFile: importDoc = d # file is already open... importDocIsOpen = True break if not importDocIsOpen: if f.lower().endswith('.fcstd'): importDoc = FreeCAD.openDocument(f) elif f.lower().endswith('.stp') or f.lower().endswith('.step'): import ImportGui fname = os.path.splitext(os.path.basename(f))[0] FreeCAD.newDocument(fname) newname = FreeCAD.ActiveDocument.Name FreeCAD.setActiveDocument(newname) ImportGui.insert(filename, newname) importDoc = FreeCAD.ActiveDocument else: msg = "A part can only be imported from a FreeCAD '*.fcstd' file" QtGui.QMessageBox.information( QtGui.QApplication.activeWindow(), "Value Error", msg) return if importDoc == doc and partial == True: updateImportedParts(importDoc, True) else: updateImportedParts(importDoc) FreeCADGui.updateGui() importDoc.save() print(u"==== Assembly '{}' has been updated! =====".format( importDoc.FileName)) if importDoc != doc: FreeCAD.closeDocument(importDoc.Name)
def Activated(self): try: selection = Gui.Selection.getSelectionEx() if (len(selection) < 1): # An object must be selected errMessage = "Select a face to use Extrude" faced.getInfo(selection).errorDialog(errMessage) return m = selection[0].Object f = App.activeDocument().addObject('Part::Extrusion', 'ExtrudeOriginal') faceSelected = faced.getInfo(selection[0]).getFaceName() f.Base = m #f.Base = App.activeDocument().getObject(m.Name) f.DirMode = "Normal" #Dont use Custom as it leads to PROBLEM! f.DirLink = None degreeAngle = m.Placement.Rotation.Angle * 180 * 22 / 7 # Convert to Radians print(degreeAngle) """ YOU SHOULD NOT SPECIFY THIS .. OTHERWISE WOULD BE WRONG!! if degreeAngle == 0: f.Dir = m.Placement.Rotation.Axis elif ((degreeAngle== 90) or (degreeAngle== -90)): f.Dir = (0, 1, 0) elif ((degreeAngle == 120) or (degreeAngle== -120)): f.Dir = (1, 0, 0) """ f.LengthFwd = QtGui.QInputDialog.getDouble(None, "Get length", "Length:", 0, -10000.0, 10000.0, 2)[0] while (f.LengthFwd == 0): _sleep(.1) Gui.updateGui() f.LengthRev = 0.0 f.Solid = True f.Reversed = False f.Symmetric = False f.TaperAngle = 0.0 f.TaperAngleRev = 0.0 # Make a simple copy of the object App.ActiveDocument.recompute() newShape = Part.getShape(f, '', needSubElement=False, refine=False) newObj = App.ActiveDocument.addObject('Part::Feature', 'Extrude').Shape = newShape App.ActiveDocument.ActiveObject.Label = f.Label App.ActiveDocument.recompute() # if something went wrong .. delete all new objecst. if newObj.isValid() == False: App.ActiveDocument.removeObject(newObj.Name) App.ActiveDocument.removeObject(f.Name) # Shape is not OK errMessage = "Failed to extrude the shape" faced.getInfo(m).errorDialog(errMessage) else: # Remove old objects App.ActiveDocument.clearUndos() App.ActiveDocument.recompute() App.ActiveDocument.removeObject(f.Name) App.ActiveDocument.removeObject(m.Name) return App.ActiveDocument.recompute() except Exception as err: App.Console.PrintError("'Design456_Extrude' Failed. " "{err}\n".format(err=str(err))) exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print(exc_type, fname, exc_tb.tb_lineno)
# check that the selection contains exactly what we want selection = FreeCADGui.Selection.getSelection() if len(selection) != 1: FreeCAD.Console.PrintError( translate("Path_FromShape", "Please select exactly one Part-based object\n")) return if not (selection[0].isDerivedFrom("Part::Feature")): FreeCAD.Console.PrintError( translate("Path_FromShape", "Please select exactly one Part-based object\n")) return FreeCAD.ActiveDocument.openTransaction( translate("Path_FromShape", "Create path from shape")) FreeCADGui.addModule("PathScripts.PathUtils") FreeCADGui.doCommand( "obj = FreeCAD.activeDocument().addObject('Path::FeatureShape','PathShape')" ) FreeCADGui.doCommand("obj.Shape = FreeCAD.activeDocument()." + selection[0].Name + ".Shape") FreeCADGui.doCommand('PathScripts.PathUtils.addToJob(obj)') FreeCAD.ActiveDocument.commitTransaction() FreeCAD.ActiveDocument.recompute() if FreeCAD.GuiUp: # register the FreeCAD command FreeCADGui.addCommand('Path_FromShape', CommandFromShape())
'ToolTip': "Disable/enable Part-o-magic. (disables the workbench)"} def Activated(self): if Params.EnablePartOMagic.get(): Params.EnablePartOMagic.set(False) msgbox("Part-o-Magic", "You've just DISABLED part-o-magic workbench. The workbench will disappear after you restart FreeCAD. \n\n" "If you disabled it by accident, click this button again to re-enable part-o-magic now. You can re-enable it by deleting configuration file.") else: Params.EnablePartOMagic.set(True) msgbox("Part-o-Magic", "You've just ENABLED part-o-magic workbench.") def IsActive(self): return True if App.GuiUp: Gui.addCommand('PartOMagic_Power', CommandTogglePartOMagic()) class CommandEnableObserver: "Switches Part-O-magic observer on" def GetResources(self): from PartOMagic.Gui.Utils import getIconPath return {'Pixmap' : getIconPath("PartOMagic_EnableObserver.svg"), 'MenuText': "Enable Observer", 'Accel': "", 'ToolTip': "Enable Observer. (enable adding new objects to active containers, and enable visibility automation)"} def Activated(self): import PartOMagic.Gui.Observer as Observer
importCSG.process_ObjectsViaOpenSCAD(FreeCAD.activeDocument(), objList, "minkowski") FreeCAD.ActiveDocument.recompute() def GetResources(self): return { 'Pixmap': 'OpenSCAD_Minkowski', 'MenuText': QtCore.QT_TRANSLATE_NOOP('OpenSCAD_Minkowski', 'Minkowski'), 'ToolTip': QtCore.QT_TRANSLATE_NOOP('OpenSCAD_Minkowski', 'Perform Minkowski') } FreeCADGui.addCommand('OpenSCAD_ColorCodeShape', ColorCodeShape()) FreeCADGui.addCommand('OpenSCAD_ExplodeGroup', ExplodeGroup()) FreeCADGui.addCommand('OpenSCAD_Edgestofaces', Edgestofaces()) FreeCADGui.addCommand('OpenSCAD_RefineShapeFeature', RefineShapeFeature()) FreeCADGui.addCommand('OpenSCAD_MirrorMeshFeature', MirrorMeshFeature()) FreeCADGui.addCommand('OpenSCAD_ScaleMeshFeature', ScaleMeshFeature()) FreeCADGui.addCommand('OpenSCAD_ResizeMeshFeature', ResizeMeshFeature()) FreeCADGui.addCommand('OpenSCAD_IncreaseToleranceFeature', IncreaseToleranceFeature()) FreeCADGui.addCommand('OpenSCAD_ExpandPlacements', ExpandPlacements()) FreeCADGui.addCommand('OpenSCAD_ReplaceObject', ReplaceObject()) FreeCADGui.addCommand('OpenSCAD_RemoveSubtree', RemoveSubtree()) FreeCADGui.addCommand('OpenSCAD_AddOpenSCADElement', AddOpenSCADElement()) FreeCADGui.addCommand('OpenSCAD_MeshBoolean', OpenSCADMeshBoolean()) FreeCADGui.addCommand('OpenSCAD_Hull', Hull()) FreeCADGui.addCommand('OpenSCAD_Minkowski', Minkowski())
def activate(self): if hasattr(self, "Object"): FreeCADGui.Selection.clearSelection() FreeCADGui.Selection.addSelection(self.Object) FreeCADGui.runCommand("Draft_AutoGroup")
App.ActiveDocument.clearUndos() App.ActiveDocument.recompute() App.ActiveDocument.removeObject(f.Name) App.ActiveDocument.removeObject(m.Name) return App.ActiveDocument.recompute() except Exception as err: App.Console.PrintError("'Design456_Extrude' Failed. " "{err}\n".format(err=str(err))) exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print(exc_type, fname, exc_tb.tb_lineno) def GuiViewFit(self): try: Gui.SendMsgToActiveView("ViewFit") self.timer.stop() except Exception as err: App.Console.PrintError("'Design456_Extrude_ViewFit' Failed. " "{err}\n".format(err=str(err))) def GetResources(self): return { 'Pixmap': Design456Init.ICON_PATH + '/Extrude.svg', 'MenuText': 'Extrude', 'ToolTip': 'Extrude' } Gui.addCommand('Design456_Extrude', Design456_Extrude())