def makeBoxEnclosure():
    FreeCAD.newDocument()
    a=FreeCAD.ActiveDocument.addObject("Part::FeaturePython","BoxEnclosure")
    BoxEnclosure(a)
    a.ViewObject.Proxy=0 # just set it to something different from None (this assignment is needed to run an internal notification)
    FreeCAD.ActiveDocument.recompute()
    return a
Example #2
0
    def Activated(self):
        import ExplodedAssembly as ea
        if not(FreeCAD.ActiveDocument):
            FreeCAD.newDocument()

        ea.checkDocumentStructure()
        FreeCAD.Console.PrintMessage('Exploded Assembly workbench loaded\n')
Example #3
0
def DVPartTest():
    path = os.path.dirname(os.path.abspath(__file__))
    print ('TDPart path: ' + path)
    templateFileSpec = path + '/TestTemplate.svg'

    FreeCAD.newDocument("TDPart")
    FreeCAD.setActiveDocument("TDPart")
    FreeCAD.ActiveDocument=FreeCAD.getDocument("TDPart")

    box = FreeCAD.ActiveDocument.addObject("Part::Box","Box")

    page = FreeCAD.ActiveDocument.addObject('TechDraw::DrawPage','Page')
    FreeCAD.ActiveDocument.addObject('TechDraw::DrawSVGTemplate','Template')
    FreeCAD.ActiveDocument.Template.Template = templateFileSpec
    FreeCAD.ActiveDocument.Page.Template = FreeCAD.ActiveDocument.Template
    page.Scale = 5.0
#    page.ViewObject.show()    # unit tests run in console mode
    print("page created")

    view = FreeCAD.ActiveDocument.addObject('TechDraw::DrawViewPart','View')
    rc = page.addView(view)

    FreeCAD.ActiveDocument.View.Source = [FreeCAD.ActiveDocument.Box]

    FreeCAD.ActiveDocument.recompute()

    rc = False
    if ("Up-to-date" in view.State):
        rc = True
    FreeCAD.closeDocument("TDPart")
    return rc
Example #4
0
    def __init__(self,mainSec,flapSec,tol=10.**-5,FREECADPATH='/usr/lib/freecad/lib'):
        import sys
        sys.path.append(FREECADPATH)        
        import FreeCAD
        import Draft
        mainSec=self.unique(mainSec,tol)
        flapSec=self.unique(flapSec,tol)
        Mmin=mainSec[:,0].argmin()
        Fmin=flapSec[:,0].argmin()
        
        mainTop=mainSec[0:Mmin+1,:]
        mainBot=mainSec[Mmin:,:]
        flapTop=flapSec[0:Fmin+1,:]
        flapBot=flapSec[Fmin:,:]

        FreeCAD.newDocument('flap2igs')    
        objs=[]    
#        self.mainObj=self.getSpline(mainSec)
#        self.flapObj=self.getSpline(flapSec)
#        objs.append(self.mainObj)
#        objs.append(self.flapObj)
                
#        self.cutObj=Draft.cut(self.boundaryObj,self.mainObj)
#        self.cutObj=Draft.cut(self.boundaryObj,self.mainObj)
        objs.append(self.getSpline(mainTop))
        objs.append(self.getSpline(mainBot))
        objs.append(self.getSpline(flapTop))
        objs.append(self.getSpline(flapBot))
        objs=self.closeTE(objs,mainSec)
        objs=self.closeTE(objs,flapSec)
        self.objs=objs
    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")
Example #6
0
    def on_addButton_clicked(self, checked):
        if FreeCAD.activeDocument() is None:
            FreeCAD.newDocument()

        items = self.ui.partsTree.selectedItems()

        if len(items) < 1:
            return

        data = items[0].data(0, 32).toPyObject()

        if not isinstance(data, BOLTSClass):
            return

        params = {}
        #read parameters from widgets
        for key in self.param_widgets:
            params[key] = self.param_widgets[key].getValue()
        params = data.parameters.collect(params)
        params['standard'] = data.name

        params['name'] = data.naming.template % \
         tuple(params[k] for k in data.naming.substitute)

        lengths = {"Length (mm)": "mm", "Length (in)": "in"}

        for key, tp in data.parameters.types.iteritems():
            if tp in lengths:
                params[key] = FreeCAD.Units.translateUnit(
                    "%g %s" % (params[key], lengths[tp]))

        #add part
        self.repo.freecad.getbase[data.id].add_part(params,
                                                    FreeCAD.ActiveDocument)
    def Activated(self):
        #Grab our code editor so we can interact with it
        mw = FreeCADGui.getMainWindow()
        cqCodePane = mw.findChild(QtGui.QPlainTextEdit, "cqCodePane")

        #Clear the old render before re-rendering
        clearActiveDocument()

        #Save our code to a tempfile and render it
        tempFile = tempfile.NamedTemporaryFile(delete=False)
        tempFile.write(cqCodePane.toPlainText().encode('utf-8'))
        tempFile.close()

        docname = os.path.splitext(os.path.basename(cqCodePane.file.path))[0]

        #If the matching 3D view has been closed, we need to open a new one
        try:
           FreeCAD.getDocument(docname)
        except:
            FreeCAD.newDocument(docname)

        #We import this way because using execfile() causes non-standard script execution in some situations
        imp.load_source('temp_module', tempFile.name)

        msg = QtGui.QApplication.translate(
            "cqCodeWidget",
            "Executed ",
            None,
            QtGui.QApplication.UnicodeUTF8)
        FreeCAD.Console.PrintMessage(msg + cqCodePane.file.path + "\r\n")
Example #8
0
 def setUp(self):
     try:
         FreeCAD.setActiveDocument("FemTest")
     except:
         FreeCAD.newDocument("FemTest")
     finally:
         FreeCAD.setActiveDocument("FemTest")
     self.active_doc = FreeCAD.ActiveDocument
Example #9
0
 def setUp(self):
     # setting a new document to hold the tests
     if FreeCAD.ActiveDocument:
         if FreeCAD.ActiveDocument.Name != "DraftTest":
             FreeCAD.newDocument("DraftTest")
     else:
         FreeCAD.newDocument("DraftTest")
     FreeCAD.setActiveDocument("DraftTest")
Example #10
0
 def getObjectFromList(self, lst):
     if lst.currentItem():
         item = str(lst.currentItem().text())
         if not App.ActiveDocument:
             App.newDocument()
         return App.ActiveDocument.getObject(item)
     else:
         return None
Example #11
0
def makeMesh():
	FreeCAD.newDocument()
	import Mesh

	a=FreeCAD.ActiveDocument.addObject("Mesh::FeaturePython","Mesh")
	a.Mesh=Mesh.createSphere(5.0)
	MeshFeature(a)
	ViewProviderMesh(a.ViewObject)
Example #12
0
 def setUp(self):
     self.doc_name = "TestObjectCreate"
     try:
         FreeCAD.setActiveDocument(self.doc_name)
     except:
         FreeCAD.newDocument(self.doc_name)
     finally:
         FreeCAD.setActiveDocument(self.doc_name)
     self.active_doc = FreeCAD.ActiveDocument
Example #13
0
def makeTexture():
	FreeCAD.newDocument()
	box = FreeCAD.ActiveDocument.addObject("Part::Box","Box")
	tex=FreeCAD.ActiveDocument.addObject("App::FeaturePython","Texture")
	Texture(tex, box)
	box.ViewObject.Selectable = False
	ViewProviderTexture(tex.ViewObject)
	box.touch()
	FreeCAD.ActiveDocument.recompute()
Example #14
0
 def setUp(self):
     self.doc_name = "TestsFemCommon"
     try:
         FreeCAD.setActiveDocument(self.doc_name)
     except:
         FreeCAD.newDocument(self.doc_name)
     finally:
         FreeCAD.setActiveDocument(self.doc_name)
     self.active_doc = FreeCAD.ActiveDocument
Example #15
0
    def accept(self):
        if FreeCAD.ActiveDocument is None:
            FreeCAD.newDocument("Gear")

        gear = fcgear.makeGear(
            self.gc.m.value(), self.gc.Z.value(), self.gc.angle.value(), not self.gc.split.currentIndex()
        )
        FreeCADGui.SendMsgToActiveView("ViewFit")
        return super(GearDialog, self).accept()
Example #16
0
 def testSaveAndRestore(self):
   # saving and restoring
   SaveName = self.TempPath + os.sep + "UnicodeTest.FCStd"
   self.Doc.saveAs(SaveName)
   FreeCAD.closeDocument("SaveRestoreTests")
   self.Doc = FreeCAD.open(SaveName)
   self.failUnless(self.Doc.Label_1.Label == u"हिन्दी")
   FreeCAD.closeDocument("UnicodeTest")
   FreeCAD.newDocument("SaveRestoreTests")
Example #17
0
 def setUp(self):
     try:
         FreeCAD.setActiveDocument("FemTest")
     except:
         FreeCAD.newDocument("FemTest")
     finally:
         FreeCAD.setActiveDocument("FemTest")
     self.active_doc = FreeCAD.ActiveDocument
     self.box = self.active_doc.addObject("Part::Box", "Box")
     self.active_doc.recompute()
Example #18
0
 def setUp(self):
     # init, is executed before every test
     self.doc_name = "TestResult"
     try:
         FreeCAD.setActiveDocument(self.doc_name)
     except:
         FreeCAD.newDocument(self.doc_name)
     finally:
         FreeCAD.setActiveDocument(self.doc_name)
     self.active_doc = FreeCAD.ActiveDocument
Example #19
0
def makeGear(m, Z, angle, split=True):
    if FreeCAD.ActiveDocument is None:
        FreeCAD.newDocument("Gear")
    doc = FreeCAD.ActiveDocument
    w = FCWireBuilder()
    involute.CreateExternalGear(w, m, Z, angle, split)
    gearw = Part.Wire([o.toShape() for o in w.wire])
    gear = doc.addObject("Part::Feature", "Gear")
    gear.Shape = gearw
    return gear
Example #20
0
	def write_output(self,out_path,version,stable=False):
		self.clear_output_dir(out_path)

		ver_root = join(out_path,version)
		makedirs(ver_root)

		#generate version file
		date = datetime.now()
		version_file = open(join(ver_root,"VERSION"),"w")
		version_file.write("%s\n%d-%d-%d\n" %
			(version, date.year, date.month, date.day))
		version_file.close()

		#Disable writing bytecode to avoid littering the freecad database with pyc files
		write_bytecode = sys.dont_write_bytecode
		sys.dont_write_bytecode = True

		for coll in self.repo.itercollections():
			if not exists(join(ver_root,coll.id)):
				makedirs(join(ver_root,coll.id))

			sys.path.append(join(self.repo.path,"freecad",coll.id))
			for cl,base in self.dbs["freecad"].iterclasses(["class","base"],filter_collection=coll):
				if cl.parameters.common is None:
					continue

				for free in cl.parameters.common:
					try:
						params = cl.parameters.collect(dict(zip(cl.parameters.free,free)))
					except:
						print("A problem occured when parameters for %s where collected for %s" % (free,cl.id))
						raise

					for std, in self.dbs["freecad"].iterstandards(filter_class=cl):
						params['name'] = std.labeling.get_nice(params)
						filename = std.labeling.get_safe(params) + ".igs"
						doc = FreeCAD.newDocument()
						add_part(base,params,doc)
						shape = doc.ActiveObject.Shape
						shape.exportIges(join(ver_root,coll.id,filename))
						FreeCAD.closeDocument(doc.Name)

					for name, in self.dbs["freecad"].iternames(filter_class=cl):
						params['name'] = name.labeling.get_nice(params)
						filename = name.labeling.get_safe(params) + ".igs"
						doc = FreeCAD.newDocument()
						add_part(base,params,doc)
						shape = doc.ActiveObject.Shape
						shape.exportIges(join(ver_root,coll.id,filename))
						FreeCAD.closeDocument(doc.Name)
			sys.path.pop()

		#restore byte code writing
		sys.dont_write_bytecode = write_bytecode
Example #21
0
 def setUp(self):
     try:
         FreeCAD.setActiveDocument("FemTest")
     except:
         FreeCAD.newDocument("FemTest")
     finally:
         FreeCAD.setActiveDocument("FemTest")
     self.active_doc = FreeCAD.ActiveDocument
     self.mesh_name = 'Mesh'
     self.temp_dir = testtools.get_fem_test_tmp_dir()
     self.test_file_dir = testtools.get_fem_test_home_dir() + 'ccx/'
Example #22
0
 def setUp(self):
     self.doc_name = "TestSolverFrameWork"
     try:
         FreeCAD.setActiveDocument(self.doc_name)
     except:
         FreeCAD.newDocument(self.doc_name)
     finally:
         FreeCAD.setActiveDocument(self.doc_name)
     self.active_doc = FreeCAD.ActiveDocument
     self.mesh_name = 'Mesh'
     self.temp_dir = testtools.get_fem_test_tmp_dir()
     self.test_file_dir = testtools.get_fem_test_home_dir() + 'ccx/'
Example #23
0
	def on_addButton_clicked(self,checked):
		if FreeCAD.activeDocument() is None:
			FreeCAD.newDocument()

		items = self.ui.partsTree.selectedItems()

		if len(items) < 1:
			return

		data = unpack(items[0].data(0,32))

		if isinstance(data,ClassName):
			cl = self.repo.class_names.get_src(data)
		elif isinstance(data,ClassStandard):
			cl = self.repo.class_standards.get_src(data)
		else:
			return

		params = {}
		#read parameters from widgets
		for key in self.param_widgets:
			params[key] = self.param_widgets[key].getValue()
		params = cl.parameters.collect(params)

		params['name'] = data.labeling.get_nice(params)

		lengths = {"Length (mm)" : "mm", "Length (in)" : "in"}

		for key,tp in cl.parameters.types.iteritems():
			if tp in lengths:
				if params[key] is None:
					#A undefined value is not necessarily fatal
					continue
				revision = int(FreeCAD.Version()[2].split()[0])
				if revision >= 2836:
					params[key] = FreeCAD.Units.parseQuantity("%g %s" %
						(params[key], lengths[tp])).Value
				else:
					params[key] = FreeCAD.Units.translateUnit("%g %s" %
						(params[key], lengths[tp]))

		#add part
		try:
			base = self.dbs["freecad"].base_classes.get_src(cl)
			coll = self.repo.collection_classes.get_src(cl)
			add_part(coll,base,params,FreeCAD.ActiveDocument)
			FreeCADGui.SendMsgToActiveView("ViewFit")
			FreeCAD.ActiveDocument.recompute()
		except ValueError as e:
			QtGui.QErrorMessage(self).showMessage(str(e))
		except Exception as e:
			FreeCAD.Console.PrintMessage(e)
			QtGui.QErrorMessage(self).showMessage("An error occured when trying to add the part: %s\nParameter Values: %s" % (e,params))
Example #24
0
    def Activated(self, index):
        if FreeCAD.ActiveDocument is None:
            FreeCAD.newDocument()
        FreeCAD.ActiveDocument.openTransaction(b"New Pool")
        code = '''from App import UsbPool
from Gui import UsbPoolGui, PySerialGui
obj = FreeCAD.ActiveDocument.addObject("App::DocumentObjectGroupPython", "Pool")
UsbPool.Pool(obj)
UsbPoolGui._ViewProviderPool(obj.ViewObject)'''
        FreeCADGui.doCommand(code)
        FreeCAD.ActiveDocument.commitTransaction()
        FreeCAD.ActiveDocument.recompute()
Example #25
0
 def setUp(self):
     # init, is executed before every test
     self.doc_name = "TestCcxTools"
     try:
         FreeCAD.setActiveDocument(self.doc_name)
     except:
         FreeCAD.newDocument(self.doc_name)
     finally:
         FreeCAD.setActiveDocument(self.doc_name)
     self.active_doc = FreeCAD.ActiveDocument
     self.mesh_name = 'Mesh'
     self.temp_dir = testtools.get_fem_test_tmp_dir()
     self.test_file_dir = join(testtools.get_fem_test_home_dir(), 'ccx')
Example #26
0
 def setUp(self):
     try:
         FreeCAD.setActiveDocument("TherMechFemTest")
     except:
         FreeCAD.newDocument("TherMechFemTest")
     finally:
         FreeCAD.setActiveDocument("TherMechFemTest")
     self.active_doc = FreeCAD.ActiveDocument
     self.box = self.active_doc.addObject("Part::Box", "Box")
     self.box.Height = 25.4
     self.box.Width = 25.4
     self.box.Length = 203.2
     self.active_doc.recompute()
Example #27
0
 def tryToGetDocument(self, docName , createIfNotExist=False):
     import FreeCAD , FreeCADGui
     doc = None
     try:
         doc = FreeCADGui.getDocument(docName)
     except:
         if createIfNotExist:
             FreeCAD.newDocument(docName)
             doc =  FreeCADGui.getDocument(docName)
             #print 'create doc %s'%docName
         else:
             doc = None
     return doc
Example #28
0
	def draw(self):
		try:
			Gui.getDocument('zRodR')
			Gui.getDocument('zRodR').resetEdit()
			App.getDocument('zRodR').recompute()
			App.closeDocument("zRodR")
			App.setActiveDocument("")
			App.ActiveDocument=None
			Gui.ActiveDocument=None	
		except:
			pass

		#make document
		App.newDocument("zRodR")
		App.setActiveDocument("zRodR")
		App.ActiveDocument=App.getDocument("zRodR")
		Gui.ActiveDocument=Gui.getDocument("zRodR")
		
		#make sketch
	#	sketch = App.activeDocument().addObject('Sketcher::SketchObject','Sketch')
		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 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(50,50,0),App.Vector(0,0,1),gv.zRodDiaR))
		App.ActiveDocument.recompute()
		#sketch.addConstraint(Sketcher.Constraint('Coincident',0,3,-1,1)) 
		App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('Coincident',0,3,-1,1)) 
		App.ActiveDocument.recompute()
		App.ActiveDocument.Sketch.addConstraint(Sketcher.Constraint('Radius',0,gv.zRodDiaR/2)) 
		App.ActiveDocument.recompute()
		Gui.getDocument('zRodR').resetEdit()
		App.getDocument('zRodR').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.zRodLength
		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()
Example #29
0
	def on_addButton_clicked(self,checked):
		if FreeCAD.activeDocument() is None:
			FreeCAD.newDocument()

		items = self.ui.partsTree.selectedItems()

		if len(items) < 1:
			return

		data = unpack(items[0].data(0,32))

		if not isinstance(data,BOLTSClass):
			return

		params = {}
		#read parameters from widgets
		for key in self.param_widgets:
			params[key] = self.param_widgets[key].getValue()
		params = data.parameters.collect(params)
		params['standard'] = data.name

		params['name'] = data.naming.template % \
			tuple(params[k] for k in data.naming.substitute)

		lengths = {"Length (mm)" : "mm", "Length (in)" : "in"}

		for key,tp in data.parameters.types.iteritems():
			if tp in lengths:
				if params[key] is None:
					#A undefined value is not necessarily fatal
					continue
				revision = int(FreeCAD.Version()[2].split()[0])
				if revision >= 2836:
					params[key] = FreeCAD.Units.parseQuantity("%g %s" %
						(params[key], lengths[tp])).Value
				else:
					params[key] = FreeCAD.Units.translateUnit("%g %s" %
						(params[key], lengths[tp]))

		#add part
		try:
			base = self.freecad.getbase[data.id]
			add_part(base,params,FreeCAD.ActiveDocument)
			FreeCADGui.SendMsgToActiveView("ViewFit")
			FreeCAD.ActiveDocument.recompute()
		except ValueError as e:
			QtGui.QErrorMessage(self).showMessage(str(e))
		except Exception as e:
			FreeCAD.Console.PrintMessage(e)
			QtGui.QErrorMessage(self).showMessage("An error occured when trying to add the part: %s\nParameter Values: %s" % (e,params))
def makeAssemblyFile():
    try:
        App.getDocument('PrinterAssembly').recompute()
        App.closeDocument("PrinterAssembly")
        App.setActiveDocument("")
        App.ActiveDocument = None
    except:
        pass

    # make document
    # Make Assembly file
    App.newDocument("PrinterAssembly")
    App.setActiveDocument("PrinterAssembly")
    App.ActiveDocument = App.getDocument("PrinterAssembly")
def export_one_part(modul, variant):
    if not variant in modul.all_params:
        FreeCAD.Console.PrintMessage(
            "Parameters for %s not found - skipping." % variant)
        return
    ModelName = variant
    ModelName = ModelName.replace(".", "_")
    FileName = modul.all_params[variant].file_name

    FreeCAD.Console.PrintMessage(FileName)

    Newdoc = FreeCAD.newDocument(ModelName)
    App.setActiveDocument(ModelName)
    App.ActiveDocument = App.getDocument(ModelName)
    Gui.ActiveDocument = Gui.getDocument(ModelName)

    # Model details
    #################################################################################################

    (body, pins, contacts) = modul.generate_part(variant)

    color_attr = body_color + (0, )
    show(body, color_attr)

    color_attr = pins_color + (0, )
    show(pins, color_attr)

    color_attr = contacts_color + (0, )
    show(contacts, 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
    objs[i].Label = ModelName + "__contacts"
    i += 1

    restore_Main_Tools()

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

    used_color_keys = [body_color_key, contacts_color_key]
    export_file_name = out_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
    export_objects.append(
        expVRML.exportObject(freecad_object=objs[i],
                             shape_color=contacts_color_key,
                             face_colors=None))
    i += 1

    #################################################################################################

    scale = 1 / 2.54
    colored_meshes = expVRML.getColoredMesh(Gui, export_objects, scale)

    expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys,
                          L.LIST_int_license)

    fusion = multiFuseObjs_wColors(FreeCAD,
                                   FreeCADGui,
                                   ModelName,
                                   objs,
                                   keepOriginals=True)

    exportSTEP(doc, FileName, out_dir, fusion)
    L.addLicenseToStep(out_dir+'/', FileName+".step", L.LIST_int_license,\
        L.STR_int_licAuthor, L.STR_int_licEmail, L.STR_int_licOrgSys, L.STR_int_licPreProc)

    saveFCdoc(App, Gui, doc, FileName, out_dir)

    FreeCAD.activeDocument().recompute()
    FreeCADGui.SendMsgToActiveView("ViewFit")
    FreeCADGui.activeDocument().activeView().viewAxometric()
Example #32
0
def newdoc():
    """Create a new Freecad document"""
    return FreeCAD.newDocument("Example")
Example #33
0
def makeLine():
	FreeCAD.newDocument()
	a=FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Line")
	Line(a)
	#ViewProviderLine(a.ViewObject)
	a.ViewObject.Proxy=0 # just set it to something different from None
Example #34
0
def makeMolecule():
	FreeCAD.newDocument()
	a=FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Molecule")
	Molecule(a)
	ViewProviderMolecule(a.ViewObject)
Example #35
0
def makeOctahedron():
	FreeCAD.newDocument()
	a=FreeCAD.ActiveDocument.addObject("App::FeaturePython","Octahedron")
	Octahedron(a)
	ViewProviderOctahedron(a.ViewObject)
Example #36
0
def insert(filename, docname, skip=[], only=[], root=None):
    """insert(filename,docname,skip=[],only=[],root=None):
    imports the contents of an IFC file.
    skip can contain a list of ids of objects to be skipped,
    only can restrict the import to certain object ids
    (will also get their children) and root can be used to
    import only the derivates of a certain element type
    (default = ifcProduct)."""

    getPreferences()

    # *****************************************************************
    # we are going to overwrite skip and only
    # needs to be after getPreferences
    # skip = [1030, 1922, 9813, 13030, 28999, 30631, 34909, 39120]
    #
    # only = [679567]
    # add this modules to the modules to reload on my reload tool

    try:
        import ifcopenshell
    except:
        FreeCAD.Console.PrintError(
            "IfcOpenShell was not found on this system. "
            "IFC support is disabled\n")
        return

    if DEBUG:
        print("Opening ", filename, "...", end="")
    try:
        doc = FreeCAD.getDocument(docname)
    except:
        doc = FreeCAD.newDocument(docname)
    FreeCAD.ActiveDocument = doc

    if DEBUG:
        print("done.")

    global ROOT_ELEMENT
    if root:
        ROOT_ELEMENT = root

    from ifcopenshell import geom
    settings = ifcopenshell.geom.settings()
    settings.set(settings.USE_BREP_DATA, True)
    settings.set(settings.SEW_SHELLS, True)
    settings.set(settings.USE_WORLD_COORDS, True)
    settings.set(settings.DISABLE_OPENING_SUBTRACTIONS, False)
    settings.set(settings.INCLUDE_CURVES, True)
    settings.set(settings.EXCLUDE_SOLIDS_AND_SURFACES, True)

    # global ifcfile # keeping global for debugging purposes
    filename = ifcdecode(filename, utf=True)
    ifcfile = ifcopenshell.open(filename)

    # get the length scale facter from of unit of the ifc file
    length_scale = get_prj_unit_length_scale(ifcfile)
    print("Length scale = {}\n".format(length_scale))

    reinforcements = ifcfile.by_type("IfcReinforcingBar")
    rebar_objs = []
    base_rebars = {}  # {rebar_mark_number : rebar_obj}
    reinforcement_counter = 1

    # reinforcements
    for pno, rebar in enumerate(reinforcements):
        pid = rebar.id()
        ptype = rebar.is_a()
        print("Product {} of {} is Entity #{}: {}, ".format(
            pno + 1,
            len(reinforcements),
            pid,
            ptype,
        ),
              end="",
              flush=True)

        if pid in skip:
            print(" --> is in skip list, thus skipped", end="\n")
            continue
        if only and pid not in only:
            print(
                " --> only list is no empty and pid "
                "not in only list, thus skipped",
                end="\n")
            continue

        # properties, get the mark number
        # print("")
        # build list of related property sets
        psets = getIfcPropertySets(ifcfile, pid)
        # print(psets)
        # build dict of properties
        ifc_properties = {}
        rebar_mark_number = 0
        ifc_properties = getIfcProperties(ifcfile, pid, psets, ifc_properties)
        # print(ifc_properties)
        # get the mark number (Position number)
        for key, value in ifc_properties.items():
            pset, pname, ptype, pvalue = getPropertyData(
                key, value, {"Debug": True})
            if (pset == "Allplan_ReinforcingBar" and
                    pname == "Position number"  # need to be Position not Mark!
                ):
                rebar_mark_number = pvalue
        # print(rebar_mark_number)
        # print("")
        # for debugging, TODO some Parameter to only import certain mark numbers
        # if rebar_mark_number != 3:
        #     continue

        # get the radius and the IfcCurve (Directrix) out of the ifc
        ifc_shape_representation = rebar.Representation.Representations[0]
        item_ifc_shape_representation = ifc_shape_representation.Items[0]
        mapping_source = item_ifc_shape_representation.MappingSource
        ifc_swept_disk_solid = mapping_source.MappedRepresentation.Items[0]
        radius = ifc_swept_disk_solid.Radius * length_scale
        # print(radius)
        entity_polyline = ifc_swept_disk_solid.Directrix

        # sweep path
        # get the geometry out of the IfcCurve (Directrix) and create a Wire
        cr = ifcopenshell.geom.create_shape(settings, entity_polyline)
        brep = cr.brep_data
        sweep_path = Part.Shape()
        sweep_path.importBrepFromString(brep)
        sweep_path.scale(1000.0)  # IfcOpenShell always outputs in meters

        # does it makes sense to check if the sweep_path and Radius
        # really are the same if mark number equals (yes, thus TODO)
        base_placement = FreeCAD.Placement()
        if rebar_mark_number not in base_rebars:
            # create a new rebar shape
            wire = Draft.makeWire(sweep_path.Wires[0])
            rebar_shape = archadd.BaseRebar(wire,
                                            diameter=2 * radius,
                                            mark=rebar_mark_number,
                                            name="BaseRebar_Mark_" +
                                            str(rebar_mark_number))
            rebar_shape.IfcProperties = ifc_properties
            print("based on: {}, ".format(wire.Name), end="")
            rebar_objs.append(rebar_shape)
            base_rebars[rebar_mark_number] = rebar_shape
        else:
            # get the relative placement between
            # the base wire (the one in base_rebars already)
            # the sweep_path
            base_wire_obj = base_rebars[rebar_mark_number].Base
            print("based on: {}, ".format(base_wire_obj.Name), end="")
            base_placement = get_relative_placement(base_wire_obj.Shape,
                                                    sweep_path)
            # print(base_placement)

        # reinforcement made out of the imported rebar
        # coord placements
        vec_base_rebar = []
        for ifc_mapped_item in ifc_shape_representation.Items:
            ifc_cartesian_point = ifc_mapped_item.MappingTarget.LocalOrigin
            coord = ifc_cartesian_point.Coordinates
            co_vec = vec(coord[0] * length_scale, coord[1] * length_scale,
                         coord[2] * length_scale)
            vec_base_rebar.append(co_vec)
        # print("\n{}".format(vec_base_rebar))

        # check if we have a linear reinforcement
        is_linear_reinforcement = False
        space_one = 0
        if len(vec_base_rebar) > 1:
            # edge from first point to last point
            ed = Part.Edge(
                Part.LineSegment(vec_base_rebar[0], vec_base_rebar[-1]))
            # spacing between first and second point
            space_one = vec_base_rebar[1] - vec_base_rebar[0]
            for i, co_vec in enumerate(vec_base_rebar):
                # check distance point to edge
                dist = ed.distToShape(Part.Vertex(co_vec))[0]
                if dist > 2:
                    # 2 mm, much better would be some dimensionless value
                    break
                # check spaceing, if they are constant
                if i > 0:
                    space_i = vec_base_rebar[i] - vec_base_rebar[i - 1]
                    difference_length = (space_one - space_i).Length
                    if difference_length > 2:
                        # 2 mm, much better would be some dimensionless value
                        break
            else:
                is_linear_reinforcement = True

        # get placement for first reinforcement bar
        relplacement_firstbar = rebar.ObjectPlacement.RelativePlacement
        coord_firstbar = relplacement_firstbar.Location.Coordinates
        vec_firstbar = vec(coord_firstbar[0] * length_scale,
                           coord_firstbar[1] * length_scale,
                           coord_firstbar[2] * length_scale)
        firstbar_pl = FreeCAD.Placement(vec_firstbar,
                                        FreeCAD.Rotation(vec(0, 0, 1), 0),
                                        vec(0, 0, 0))

        marker_size = 25
        lattice_placement = None
        if (REINFORCEMENT_LATTICE is True and is_linear_reinforcement is True):
            # linear lattice reinforcement
            print("reinforcement: linear lattice")
            # print(len(vec_base_rebar))
            # print(space_one)
            space_length = space_one.Length
            la = lattice2LinearArray.makeLinearArray(name="LinearArray")
            # SpanN ... put in Count
            # Step will be calculated
            # SpanStep ... put in Step (space between rebars)
            # Count will be calculated
            la.GeneratorMode = "SpanStep"
            # https://forum.freecadweb.org/viewtopic.php?f=22&t=37657#p320586
            la.Alignment = "Justify"
            la.SpanEnd = (len(vec_base_rebar) - 1) * space_length
            la.Step = space_length
            la.MarkerSize = marker_size
            # direction of linear lattice2 placement
            la.Dir = space_one
            # do not change the orientation of the little planes
            # https://forum.freecadweb.org/viewtopic.php?f=22&t=37893&p=322427#p322421
            la.OrientMode = "None"
            lattice2Executer.executeFeature(la)
            la.Placement = firstbar_pl
            if la.Count != len(vec_base_rebar):
                print("Problem: {} != {}".format(la.Count,
                                                 len(vec_base_rebar)))
            lattice_placement = la
        elif (REINFORCEMENT_LATTICE is True
              and is_linear_reinforcement is False):
            # custom lattice placement for every rebar of this reinforcement
            print("reinforcement: custom lattice")
            custom_pls = []
            for co_vec in vec_base_rebar:
                custom_pl = lattice2Placement.makeLatticePlacement(
                    name=str(ifc_cartesian_point.id()))
                custom_pl.PlacementChoice = "Custom"
                custom_pl.MarkerSize = marker_size
                lattice2Executer.executeFeature(custom_pl)
                custom_pl.Placement = FreeCAD.Placement(
                    co_vec, FreeCAD.Rotation(vec(0, 0, 1), 0), vec(0, 0, 0))
                custom_pls.append(custom_pl)

                # lattice array placement from custom lattice placements
                cpa = lattice2JoinArrays.makeJoinArrays(
                    name="CustomPlacementArray")
                cpa.Links = custom_pls
                cpa.MarkerSize = marker_size
                lattice2Executer.executeFeature(cpa)
                cpa.Placement = firstbar_pl
                lattice_placement = cpa
                if FreeCAD.GuiUp:
                    for child in cpa.ViewObject.Proxy.claimChildren():
                        child.ViewObject.hide()

        if lattice_placement is not None:
            # lattice2 reinforcement
            archadd.ReinforcementLattice(
                rebar_shape,
                lattice_placement,
                base_placement,
                # name="Reinforcement_"+str(reinforcement_counter)
                name="ReinforcementLattice_" + str(pid))

        if (REINFORCEMENT_LATTICE is False
                and is_linear_reinforcement is True):
            # linear reinforcement
            print("reinforcement: linear std")
            if space_one == 0:
                # TODO handle a reinforcement with one rebar
                # this should not be a linear reinforcement
                continue
            amount = len(vec_base_rebar)
            spacing = space_one.Length
            # distance = (len(vec_base_rebar) - 1) * spacing

            archadd.ReinforcementLinear(
                rebar_shape,
                amount=amount,
                spacing=spacing,
                direction=space_one,
                base_placement=firstbar_pl.multiply(base_placement),
                # name="Reinforcement_"+str(reinforcement_counter)
                name="ReinforcementLinear_" + str(pid))
        elif (REINFORCEMENT_LATTICE is False
              and is_linear_reinforcement is False):
            # individual reinforcement
            print("reinforcement: individual std")
            individuals = []
            for co in vec_base_rebar:
                v_placement_lok = FreeCAD.Placement(co, FreeCAD.Rotation())
                v_placement_glob = v_placement_lok.multiply(firstbar_pl)
                v = doc.addObject("Part::Vertex", "Vertex1")
                v_vec = v_placement_glob.Base
                v.X, v.Y, v.Z = v_vec.x, v_vec.y, v_vec.z,
                v.ViewObject.PointColor = (1.0, 0.7, 0.0, 0.0)
                v.ViewObject.PointSize = 15
                individuals.append(v)
            archadd.ReinforcementIndividual(rebar_shape,
                                            individuals=individuals,
                                            base_placement=base_placement,
                                            name="ReinforcementIndividual_" +
                                            str(pid))

        reinforcement_counter += 1
        # print("")

    FreeCAD.ActiveDocument.recompute()
    # End reinforcements loop

    if FreeCAD.GuiUp:
        FreeCADGui.activeDocument().activeView().viewAxometric()
        FreeCADGui.SendMsgToActiveView("ViewFit")
    return doc
Example #37
0
def init_doc(doc=None):
    if doc is None:
        doc = FreeCAD.newDocument()
    return doc
Example #38
0
def makeBox():
	FreeCAD.newDocument()
	a=FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Box")
	Box(a)
	ViewProviderBox(a.ViewObject)
Example #39
0
 def __init__(self, outdir='/tmp'):
     self.outdir = outdir
     FreeCADGui.showMainWindow()
     self.doc = FreeCAD.newDocument()
Example #40
0
	def setUp(self):
		# set up a planar face with 2 triangles
		self.planarMesh = []
		FreeCAD.newDocument("MeshTest")

def clear_doc():
    # Clear the active document deleting all the objects
    for obj in DOC.Objects:
        DOC.removeObject(obj.Name)


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


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

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

# part_moyeu_amovible_volant_inertie
De = 85.5
L = 44.45
part_moyeu_amovible_volant_inertie = Part.makeCylinder(De / 2, L)

cylinder_1 = Part.makeCylinder(20 / 2, L)
Example #42
0
def insert(filename,docname):
    try:
        doc=FreeCAD.getDocument(docname)
    except NameError:
        doc=FreeCAD.newDocument(docname)
    readfile(filename).addtofreecad(doc)
Example #43
0
    def addtofreecad(self,doc=None,fcpar=None):
        def center(obj,x,y,z):
             obj.Placement = FreeCAD.Placement(\
                FreeCAD.Vector(-x/2.0,-y/2.0,-z/2.0),\
                FreeCAD.Rotation(0,0,0,1))

        import FreeCAD,Part
        if not doc:
            doc=FreeCAD.newDocument()
        namel=self.name.lower()
        multifeature={'union':"Part::MultiFuse",'imp_union':"Part::MultiFuse",
                      'intersection':"Part::MultiCommon"}
        if namel in multifeature:
            if len(self.children)>1:
                obj=doc.addObject(multifeature[namel],namel)
                subobjs = [child.addtofreecad(doc,obj) for child in self.children]
                obj.Shapes = subobjs
                for subobj in subobjs:
                    subobj.ViewObject.hide()
            elif len(self.children)==1:
                obj = self.children[0].addtofreecad(doc,fcpar or True)
            else:
                obj = fcpar
        elif namel == 'difference':
            if len(self.children)==1:
                obj = self.children[0].addtofreecad(doc,fcpar or True)
            else: 
                obj=doc.addObject("Part::Cut",namel)
                base = self.children[0].addtofreecad(doc,obj)
            
                if len(self.children)==2:
                    tool = self.children[1].addtofreecad(doc,obj)
                else:
                    tool = Node(name='imp_union',\
                        children=self.children[1:]).addtofreecad(doc,obj)
                obj.Base = base
                obj.Tool = tool
                base.ViewObject.hide()
                tool.ViewObject.hide()
        elif namel == 'cube':
            obj=doc.addObject('Part::Box',namel)
            x,y,z=self.arguments['size']
            obj.Length=x
            obj.Width=y
            obj.Height=z
            if self.arguments['center']:
                center(obj,x,y,z)
        elif namel == 'sphere':
            obj=doc.addObject("Part::Sphere",namel)
            obj.Radius = self.arguments['r']
        elif namel == 'cylinder':
            h = self.arguments['h']
            r1 ,r2 = self.arguments['r1'], self.arguments['r2']
            if '$fn' in self.arguments and self.arguments['$fn'] > 2 \
            and self.arguments['$fn']<=Node.fnmin: # polygonal
                if r1 == r2: # prismatic
                    obj = doc.addObject("Part::Prism","prism")
                    obj.Polygon = int(self.arguments['$fn'])
                    obj.Circumradius  = r1
                    obj.Height  = h
                    if self.arguments['center']:
                        center(obj,0,0,h)
                    #base.ViewObject.hide()
                elif False: #use Frustum Feature with makeRuledSurface
                    obj=doc.addObject("Part::FeaturePython",'frustum')
                    Frustum(obj,r1,r2,int(self.arguments['$fn']),h)
                    ViewProviderTree(obj.ViewObject)
                    if self.arguments['center']:
                        center(obj,0,0,h)
                else: #Use Part::Loft and GetWire Feature
                    obj=doc.addObject('Part::Loft','frustum')
                    import Draft
                    p1 = Draft.makePolygon(int(self.arguments['$fn']),r1)
                    p2 = Draft.makePolygon(int(self.arguments['$fn']),r2)
                    if self.arguments['center']:
                        p1.Placement = FreeCAD.Placement(\
                        FreeCAD.Vector(0.0,0.0,-h/2.0),FreeCAD.Rotation())
                        p2.Placement = FreeCAD.Placement(\
                        FreeCAD.Vector(0.0,0.0,h/2.0),FreeCAD.Rotation())
                    else:
                        p2.Placement = FreeCAD.Placement(\
                        FreeCAD.Vector(0.0,0.0,h),FreeCAD.Rotation())
                    w1=doc.addObject("Part::FeaturePython",'polygonwire1')
                    w2=doc.addObject("Part::FeaturePython",'polygonwire2')
                    GetWire(w1,p1)
                    GetWire(w2,p2)
                    ViewProviderTree(w1.ViewObject)
                    ViewProviderTree(w2.ViewObject)
                    obj.Sections=[w1,w2]
                    obj.Solid=True
                    obj.Ruled=True
                    p1.ViewObject.hide()
                    p2.ViewObject.hide()
                    w1.ViewObject.hide()
                    w2.ViewObject.hide()
            else:
                if r1 == r2:
                    obj=doc.addObject("Part::Cylinder",namel)
                    obj.Height = h
                    obj.Radius = r1
                else:
                    obj=doc.addObject("Part::Cone",'cone')
                    obj.Height = h
                    obj.Radius1, obj.Radius2 = r1, r2
                if self.arguments['center']:
                    center(obj,0,0,h)
        elif namel == 'polyhedron':
            obj = doc.addObject("Part::Feature",namel)
            points=self.arguments['points']
            faces=self.arguments['triangles']
            shell=Part.Shell([Part.Face(Part.makePolygon(\
                    [tuple(points[pointindex]) for pointindex in \
                    (face+face[0:1])])) for face in faces])
#            obj.Shape=Part.Solid(shell).removeSplitter()
            solid=Part.Solid(shell).removeSplitter()
            if solid.Volume < 0:
#                solid.complement()
                solid.reverse()
            obj.Shape=solid#.removeSplitter()

        elif namel == 'polygon':
            obj = doc.addObject("Part::Feature",namel)
            points=self.arguments['points']
            paths = self.arguments.get('paths')
            if not paths:
                faces=[Part.Face(Part.makePolygon([(x,y,0) for x,y in points+points[0:1]]))]
            else:
                faces= [Part.Face(Part.makePolygon([(points[pointindex][0],points[pointindex][1],0) for \
                    pointindex in (path+path[0:1])])) for path in paths]
            obj.Shape=subtractfaces(faces)
        elif namel == 'square':
            obj = doc.addObject("Part::Plane",namel)
            x,y = self.arguments['size']
            obj.Length = x
            obj.Width = y
            if self.arguments['center']:
                center(obj,x,y,0)
        elif namel == 'circle':
            r = self.arguments['r']
            import Draft
            if '$fn' in self.arguments and self.arguments['$fn'] != 0 \
            and self.arguments['$fn']<=Node.fnmin:
                obj=Draft.makePolygon(int(self.arguments['$fn']),r)
            else:
                obj=Draft.makeCircle(r) # create a Face
                #obj = doc.addObject("Part::Circle",namel);obj.Radius = r
        elif namel == 'color':
            if len(self.children) == 1:
                obj = self.children[0].addtofreecad(doc,fcpar or True)
            else:
                obj = Node(name='imp_union',\
                        children=self.children).addtofreecad(doc,fcpar or True)
            obj.ViewObject.ShapeColor = tuple([float(p) for p in self.arguments[:3]]) #RGB
            transp = 100 - int(math.floor(100*self.arguments[3])) #Alpha
            obj.ViewObject.Transparency = transp
        elif namel == 'multmatrix':
            assert(len(self.children)>0)
            m1l=[round(f,12) for f in sum(self.arguments,[])] #That's the original matrix
            m1=FreeCAD.Matrix(*tuple(m1l)) #That's the original matrix
            if isspecialorthogonalpython(fcsubmatrix(m1)): #a Placement can represent the transformation
                if len(self.children) == 1:
                    obj = self.children[0].addtofreecad(doc,fcpar or True)
                else:
                    obj = Node(name='imp_union',\
                            children=self.children).addtofreecad(doc,fcpar or True) 
                    #FreeCAD.Console.PrintMessage('obj %s\nmat %s/n' % (obj.Placement,m1))
                obj.Placement=FreeCAD.Placement(m1).multiply(obj.Placement)
            else: #we need to apply the matrix transformation to the Shape using a custom PythonFeature
                obj=doc.addObject("Part::FeaturePython",namel)
                if len(self.children) == 1:
                    child = self.children[0].addtofreecad(doc,obj)
                else:
                    child = Node(name='imp_union',\
                            children=self.children).addtofreecad(doc,obj)
                MatrixTransform(obj,m1,child) #This object is not mutable from the GUI
                ViewProviderTree(obj.ViewObject)
        #elif namel == 'import': pass #Custom Feature
        elif namel == 'linear_extrude':
            height = self.arguments['height']
            twist = self.arguments.get('twist')
            if not twist:
                obj = doc.addObject("Part::Extrusion",namel)
            else: #twist
                obj=doc.addObject("Part::FeaturePython",'twist_extrude')
            if len(self.children)==0:
                base= Node('import',self.arguments).addtofreecad(doc,obj)
            elif len(self.children)==1:
                base = self.children[0].addtofreecad(doc,obj)
            else:
                base = Node(name='imp_union',\
                            children=self.children).addtofreecad(doc,obj)
            if False and base.isDerivedFrom('Part::MultiFuse'):
                #does not solve all the problems
                newobj=doc.addObject("Part::FeaturePython",'refine')
                RefineShape(newobj,base)
                ViewProviderTree(newobj.ViewObject)
                base.ViewObject.hide()
                base=newobj
            if not twist:
                obj.Base= base
                obj.Dir = (0,0,height)
            else: #twist
                Twist(obj,base,height,-twist)
                ViewProviderTree(obj.ViewObject)
            if self.arguments['center']:
                center(obj,0,0,height)
            base.ViewObject.hide()

        elif namel == 'rotate_extrude':
            obj = doc.addObject("Part::Revolution",namel)
            if len(self.children)==0:
                base= Node('import',self.arguments).addtofreecad(doc,obj)
            elif len(self.children)==1:
                base = self.children[0].addtofreecad(doc,obj)
            else:
                base = Node(name='imp_union',\
                            children=self.children).addtofreecad(doc,obj)
            if False and base.isDerivedFrom('Part::MultiFuse'):
                #creates 'Axe and meridian are confused' Errors
                newobj=doc.addObject("Part::FeaturePython",'refine')
                RefineShape(newobj,base)
                ViewProviderTree(newobj.ViewObject)
                base.ViewObject.hide()
                base=newobj
            obj.Source= base
            obj.Axis = (0.00,1.00,0.00)
            obj.Base = (0.00,0.00,0.00)
            obj.Angle = 360.00
            base.ViewObject.hide()
            obj.Placement=FreeCAD.Placement(FreeCAD.Vector(),FreeCAD.Rotation(0,0,90))
        elif namel == 'projection':
            if self.arguments['cut']:
                planename='xy_plane_used_for_project_cut'
                obj=doc.addObject('Part::MultiCommon','projection_cut')
                plane = doc.getObject(planename)
                if not plane:
                    plane=doc.addObject("Part::Plane",planename)
                    plane.Length=Node.planedim*2
                    plane.Width=Node.planedim*2
                    plane.Placement = FreeCAD.Placement(FreeCAD.Vector(\
                    -Node.planedim,-Node.planedim,0),FreeCAD.Rotation(0,0,0,1))
                #plane.ViewObject.hide()
                subobjs = [child.addtofreecad(doc,obj) for child in self.children]
                subobjs.append(plane)
                obj.Shapes = subobjs
                for subobj in subobjs:
                    subobj.ViewObject.hide()
            else:
                #Do a proper projection
                raise(NotImplementedError)
        elif namel == 'import':
            filename = self.arguments.get('file')
            scale = self.arguments.get('scale')
            origin = self.arguments.get('origin')
            if filename:
                import os
                docname=os.path.split(filename)[1]
                objname,extension = docname.split('.',1)
                if not os.path.isabs(filename):
                    try:
                        global lastimportpath
                        filename=os.path.join(lastimportpath,filename)
                    except: raise #no path given
                # Check for a mesh fileformat support by the Mesh mddule
                if extension.lower() in reverseimporttypes()['Mesh']:
                    import Mesh
                    mesh1 = doc.getObject(objname) #reuse imported object
                    if not mesh1:
                        Mesh.insert(filename)
                        mesh1=doc.getObject(objname)
                    mesh1.ViewObject.hide()
                    sh=Part.Shape()
                    sh.makeShapeFromMesh(mesh1.Mesh.Topology,0.1)
                    solid = Part.Solid(sh)
                    obj=doc.addObject("Part::FeaturePython",'import_%s_%s'%(extension,objname))
                    #obj=doc.addObject('Part::Feature',)
                    ImportObject(obj,mesh1) #This object is not mutable from the GUI
                    ViewProviderTree(obj.ViewObject)
                    solid=solid.removeSplitter()
                    if solid.Volume < 0:
                        #sh.reverse()
                        #sh = sh.copy()
                        solid.complement()
                    obj.Shape=solid#.removeSplitter()
                elif extension in ['dxf']:
                    layera = self.arguments.get('layer')
                    featname='import_dxf_%s_%s'%(objname,layera)
                    # reusing an already imported object does not work if the
                    # shape in not yet calculated
                    import importDXF
                    global dxfcache
                    layers=dxfcache.get(id(doc),[])
                    if layers:
                        groupobj=[go for go in layers if (not layera) or go.Label == layera]
                    else:
                        groupobj= None
                    if not groupobj:
                        groupname=objname
                        layers = importDXF.processdxf(doc,filename) or importDXF.layers
                        dxfcache[id(doc)] = layers[:]
                        for l in layers:
                            for o in l.Group:
                                o.ViewObject.hide()
                            l.ViewObject.hide()
                        groupobj=[go for go in layers if (not layera) or go.Label == layera]
                    edges=[]
                    for shapeobj in groupobj[0].Group:
                        edges.extend(shapeobj.Shape.Edges)
                    try:
                        f=edgestofaces(edges)
                    except Part.OCCError:
                        FreeCAD.Console.PrintError(\
 'processing of dxf import failed\nPlease rework \'%s\' manually\n' % layera)
                        f=Part.Shape() #empty Shape
                    obj=doc.addObject("Part::FeaturePython",'import_dxf_%s_%s'%(objname,layera))
                    #obj=doc.addObject('Part::Feature',)
                    ImportObject(obj,groupobj[0]) #This object is not mutable from the GUI
                    ViewProviderTree(obj.ViewObject)
                    obj.Shape=f

                else:
                    FreeCAD.Console.ErrorMessage(\
                            'Filetype of %s not supported\n' % (filename))
                    raise(NotImplementedError)
                if obj: #handle origin and scale
                    if scale is not None and scale !=1:
                        if origin is not None and any([c != 0 for c in origin]):
                            raise(NotImplementedError)# order of transformations unknown
                        child = obj
                        m1=FreeCAD.Matrix()
                        m1.scale(scale,scale,scale)
                        obj=doc.addObject("Part::FeaturePython",'scale_import')
                        MatrixTransform(obj,m1,child) #This object is not mutable from the GUI
                        ViewProviderTree(obj.ViewObject)
                    elif origin is not None and any([c != 0 for c in origin]):
                        placement=FreeCAD.Placement(FreeCAD.Vector(*[-c for c in origin]),FreeCAD.Rotation())
                        obj.Placement=placement.multiply(obj.Placement)
                else:
                    FreeCAD.Console.ErrorMessage('Import of %s failed\n' % (filename))


        elif namel == 'minkowski':
            childrennames=[child.name.lower() for child in self.children]
            if len(self.children) == 2 and \
                childrennames.count('cube')==1 and \
                (childrennames.count('sphere') + \
                childrennames.count('cylinder')) == 1:
                if self.children[0].name.lower() == 'cube':
                    cube = self.children[0]
                    roundobj = self.children[1]
                elif self.children[1].name.lower() == 'cube':
                    cube = self.children[1]
                    roundobj = self.children[0]
                roundobjname=roundobj.name.lower()
                issphere =  roundobjname == 'sphere'
                cubeobj=doc.addObject('Part::Box','roundedcube')
                x,y,z=cube.arguments['size']
                r=roundobj.arguments.get('r') or \
                        roundobj.arguments.get('r1')
                cubeobj.Length=x+2*r
                cubeobj.Width=y+2*r
                cubeobj.Height=z+2*r*issphere
                obj=doc.addObject("Part::Fillet","%s_%s"%(namel,roundobjname))
                obj.Base = cubeobj
                cubeobj.ViewObject.hide()
                if issphere:
                    obj.Edges = [(i,r,r) for i in range(1,13)]
                else:#cylinder
                    obj.Edges = [(i,r,r) for i in [1,3,5,7]]
                if cube.arguments['center']:
                    center(cubeobj,x+2*r,y+2*r,z+2*r*issphere)
                else: #htandle a rotated cylinder
                    #OffsetShape
                    raise(NotImplementedError)
            elif childrennames.count('sphere')==1:
                sphereindex=childrennames.index('sphere')
                sphere=self.children[sphereindex]
                offset=sphere.arguments['r']
                nonsphere=self.children[0:sphereindex]+\
                        self.sphere[sphereindex+1:]
                obj=doc.addObject("Part::FeaturePython",'Offset')
                if len(nonsphere) == 1:
                    child = nonsphere[0].addtofreecad(doc,obj)
                else:
                    child = Node(name='imp_union',\
                        children=nonsphere).addtofreecad(doc,obj)
                OffsetShape(obj,child,offset)
                ViewProviderTree(obj.ViewObject)
            elif False:
                raise(NotImplementedError)
                pass # handle rotated cylinders and select edges that 
                     #radius = radius0 * m1.multiply(FreeCAD.Vector(0,0,1)).dot(edge.Curve.tangent(0)[0])
            else:
                raise(NotImplementedError)
        elif namel == 'surface':
            obj = doc.addObject("Part::Feature",namel) #include filename?
            obj.Shape,xoff,yoff=makeSurfaceVolume(self.arguments['file'])
            if self.arguments['center']:
                center(obj,xoff,yoff,0.0)
            return obj
            #import os
            #scadstr = 'surface(file = "%s", center = %s );' % \
            #    (self.arguments['file'], 'true' if self.arguments['center'] else 'false')
            #docname=os.path.split(self.arguments['file'])[1]
            #objname,extension = docname.split('.',1)
            #obj = openscadmesh(doc,scadstr,objname)

        elif namel in ['glide','hull']:
            raise(NotImplementedError)
        elif namel in ['render','subdiv'] or True:
            lenchld=len(self.children)
            if lenchld == 1:
                FreeCAD.Console.PrintMessage('Not recognized %s\n' % (self))
                obj = self.children[0].addtofreecad(doc,fcpar)
            elif lenchld >1:
                obj = Node(name='imp_union',\
                        children=self.children).addtofreecad(doc,fcpar or True)
            else:
                obj = doc.addObject("Part::Feature",'Not_Impl_%s'%namel)
        if fcpar == True: #We are the last real object, our parent is not rendered.
            return obj

        if fcpar:
            try:
                obj.ViewObject.hide()
            except: raise
            if True: #never refine the Shape, as it itroduces crashes
                return obj
            else: #refine Shape
                import Draft
                if obj.Type =='Part::Extrusion' and obj.Base.Type == 'Part::Part2DObjectPython' and \
                    isinstance(obj.Base.Proxy,Draft._Polygon) or \
                    (not obj.isDerivedFrom('Part::Extrusion') and \
                    not obj.isDerivedFrom('Part::Boolean') and \
                    not obj.isDerivedFrom('Part::Cut') and \
                    not obj.isDerivedFrom('Part::MultiCommon') and \
                    not obj.isDerivedFrom('Part::MultiFuse') and \
                    not obj.isDerivedFrom('Part::Revolution') ) \
                    or (obj.isDerivedFrom('Part::FeaturePython') and isinstance(obj.Proxy,RefineShape)):
                    return obj
                else:
                    newobj=doc.addObject("Part::FeaturePython",'refine')
                    RefineShape(newobj,obj)
                    ViewProviderTree(newobj.ViewObject)
                    obj.ViewObject.hide()
                    return newobj

        else:
            doc.recompute()
Example #44
0
def makeDistanceBolt():
	FreeCAD.newDocument()
	bolt=FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Distance_Bolt")
	bolt.Label = "Distance bolt"
	DistanceBolt(bolt)
	bolt.ViewObject.Proxy=0
Example #45
0
	def draw(self):
		#helper Variables
		width = gv.printableWidth + gv.printBedPadding
		length = gv.printableLength + gv.printBedPadding
		
		#Make file and build part
		try:
			Gui.getDocument("printBed")
			Gui.getDocument("printBed").resetEdit()
			App.getDocument("printBed").recompute()
			App.closeDocument("printBed")
			App.setActiveDocument("")
			App.ActiveDocument=None
			Gui.ActiveDocument=None	
		except:
			pass

		#Create Document
		App.newDocument("printBed")
		App.setActiveDocument("printBed")
		App.ActiveDocument=App.getDocument("printBed")
		Gui.ActiveDocument=Gui.getDocument("printBed")
		
		#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('printBed').resetEdit()
		App.getDocument('printBed').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.printBedThickness
		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 view axiometric
#		Gui.activeDocument().activeView().viewAxometric()
		
Example #46
0
    def draw(self):

        if self.side == "Right":
            self.rodDia = gv.zRodDiaR
        elif self.side == "Left":
            self.rodDia = gv.zRodDiaL

        #set up helper Variables
        supportWidth = (self.rodDia + gv.printedToPrintedDia +
                        gv.clampNutFaceToFace + 2 * gv.clampNutPadding)

        tabWidth = gv.slotDia + gv.slotWidth + 2 * gv.slotPadding
        tabLength = 2 * gv.slotPadding + gv.slotDia
        totalLength = 2 * tabLength + gv.zRodSupportLength

        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)
        App.ActiveDocument = App.getDocument(self.name)

        #Create tabs
        #Sketch points
        p1x = -tabWidth / 2
        p1y = totalLength / 2
        p2x = tabWidth / 2
        p2y = totalLength / 2
        p3x = tabWidth / 2
        p3y = -totalLength / 2
        p4x = -tabWidth / 2
        p4y = -totalLength / 2

        #MakeSketch
        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(p2x, p2y, 0)))
        App.ActiveDocument.Sketch.addGeometry(
            Part.Line(App.Vector(p2x, p2y, 0), App.Vector(p3x, p3y, 0)))
        App.ActiveDocument.Sketch.addGeometry(
            Part.Line(App.Vector(p3x, p3y, 0), App.Vector(p4x, p4y, 0)))
        App.ActiveDocument.Sketch.addGeometry(
            Part.Line(App.Vector(p4x, p4y, 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', 0, 1, 1, 2, -1, 1))
        App.ActiveDocument.recompute()

        #add dimensions
        App.ActiveDocument.Sketch.addConstraint(
            Sketcher.Constraint('DistanceY', 1, -totalLength))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch.addConstraint(
            Sketcher.Constraint('DistanceX', 2, -tabWidth))
        App.ActiveDocument.recompute()
        #		Gui.getDocument(self.name).resetEdit()
        App.getDocument(self.name).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.tabThickness
        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()

        #Cut top slot
        #Sketch Points
        p1x = -gv.slotWidth / 2
        p1y = gv.zRodSupportLength / 2 + gv.slotPadding
        p2x = gv.slotWidth / 2
        p2y = gv.zRodSupportLength / 2 + gv.slotPadding
        p3x = -gv.slotWidth / 2
        p3y = gv.zRodSupportLength / 2 + gv.slotPadding + gv.slotDia / 2
        p4x = gv.slotWidth / 2
        p4y = gv.zRodSupportLength / 2 + gv.slotPadding + gv.slotDia / 2
        p5x = gv.slotWidth / 2
        p5y = gv.zRodSupportLength / 2 + gv.slotPadding - gv.slotDia / 2
        p6x = -gv.slotWidth / 2
        p6y = gv.zRodSupportLength / 2 + gv.slotPadding - gv.slotDia / 2
        p7x = 0
        p7y = gv.zRodSupportLength / 2 + gv.slotPadding - gv.slotDia / 2

        #make Sketch
        App.activeDocument().addObject('Sketcher::SketchObject', 'Sketch001')
        #		Gui.activeDocument().setEdit('Sketch001')
        App.activeDocument().Sketch001.Support = uf.getFace(
            App.ActiveDocument.Pad, None, None, None, None, gv.tabThickness, 0)
        App.activeDocument().recompute()
        App.ActiveDocument.Sketch001.addExternal(
            "Pad",
            uf.getEdge(App.ActiveDocument.Pad, 0, 0, 0, 1, gv.tabThickness, 0))
        App.ActiveDocument.Sketch001.addGeometry(
            Part.ArcOfCircle(
                Part.Circle(App.Vector(p1x, p1y, 0), App.Vector(0, 0, 1),
                            gv.slotDia / 2), math.pi / 2, -math.pi / 2))
        App.ActiveDocument.Sketch001.addGeometry(
            Part.ArcOfCircle(
                Part.Circle(App.Vector(p2x, p2y, 0), App.Vector(0, 0, 1),
                            gv.slotDia / 2), -math.pi / 2, math.pi / 2))
        App.ActiveDocument.Sketch001.addGeometry(
            Part.Line(App.Vector(p6x, p6y, 0), App.Vector(p5x, p5y, 0)))
        App.ActiveDocument.Sketch001.addGeometry(
            Part.Line(App.Vector(p3x, p3y, 0), App.Vector(p4x, p4y, 0)))
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('Tangent', 0, 2))
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('Tangent', 0, 3))
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('Tangent', 1, 2))
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('Tangent', 1, 3))
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('Coincident', 0, 1, 3, 1))
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('Coincident', 0, 2, 2, 1))
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('Coincident', 2, 2, 1, 1))
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('Coincident', 3, 2, 1, 2))
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('Horizontal', 2))
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('Equal', 0, 1))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch001.addGeometry(
            Part.Point(App.Vector(p7x, p7y, 0)))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('PointOnObject', 4, 1, 2))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('PointOnObject', 4, 1, -2))
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('Symmetric', 1, 1, 0, 2, 4, 1))
        App.ActiveDocument.recompute()

        #add dimensions
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('Radius', 1, gv.slotDia / 2))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('Distance', 0, 3, 1, 3, gv.slotWidth))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('Distance', 0, 1, -3, gv.slotPadding))
        App.ActiveDocument.recompute()
        #		Gui.getDocument(self.name).resetEdit()
        App.getDocument(self.name).recompute()

        #Cut slot 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()
        #		Gui.activeDocument().resetEdit()

        #Mirror slot along horizotal axis
        App.activeDocument().addObject("PartDesign::Mirrored", "Mirrored")
        App.ActiveDocument.recompute()
        App.activeDocument().Mirrored.Originals = [
            App.activeDocument().Pocket,
        ]
        App.activeDocument().Mirrored.MirrorPlane = (
            App.activeDocument().Sketch001, ["V_Axis"])
        Gui.activeDocument().Pocket.Visibility = False
        #		Gui.ActiveDocument.Mirrored.ShapeColor=Gui.ActiveDocument.Pocket.ShapeColor
        #		Gui.ActiveDocument.Mirrored.DisplayMode=Gui.ActiveDocument.Pocket.DisplayMode
        App.ActiveDocument.Mirrored.Originals = [
            App.ActiveDocument.Pocket,
        ]
        App.ActiveDocument.Mirrored.MirrorPlane = (
            App.ActiveDocument.Sketch001, ["H_Axis"])
        App.ActiveDocument.recompute()
        #		Gui.activeDocument().resetEdit()

        #Make rod support column
        #Sketch points
        p1x = -supportWidth / 2
        p1y = -gv.zRodSupportLength / 2
        p2x = -supportWidth / 2
        p2y = gv.zRodSupportLength / 2
        p3x = supportWidth / 2
        p3y = gv.zRodSupportLength / 2
        p4x = supportWidth / 2
        p4y = -gv.zRodSupportLength / 2

        #Make sketch
        App.activeDocument().addObject('Sketcher::SketchObject', 'Sketch002')
        App.activeDocument().Sketch002.Support = uf.getFace(
            App.ActiveDocument.Mirrored, None, None, None, None, 0, 0)
        App.activeDocument().recompute()
        #		Gui.activeDocument().setEdit('Sketch002')
        App.ActiveDocument.Sketch002.addGeometry(
            Part.Line(App.Vector(p1x, p1y, 0), App.Vector(p4x, p4y, 0)))
        App.ActiveDocument.Sketch002.addGeometry(
            Part.Line(App.Vector(p4x, p4y, 0), App.Vector(p3x, p3y, 0)))
        App.ActiveDocument.Sketch002.addGeometry(
            Part.Line(App.Vector(p3x, p3y, 0), App.Vector(p2x, p2y, 0)))
        App.ActiveDocument.Sketch002.addGeometry(
            Part.Line(App.Vector(p2x, p2y, 0), App.Vector(p1x, p1y, 0)))
        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('Coincident', 0, 2, 1, 1))
        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('Coincident', 1, 2, 2, 1))
        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('Coincident', 2, 2, 3, 1))
        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('Coincident', 3, 2, 0, 1))
        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('Horizontal', 0))
        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('Horizontal', 2))
        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('Vertical', 1))
        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('Vertical', 3))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('Symmetric', 0, 1, 1, 2, -1, 1))
        App.ActiveDocument.recompute()

        #add dimensions
        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('DistanceY', 1, gv.zRodSupportLength))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('DistanceX', 2, -supportWidth))
        App.ActiveDocument.recompute()
        #		Gui.getDocument(self.name).resetEdit()
        App.getDocument(self.name).recompute()

        #pad rod support
        App.activeDocument().addObject("PartDesign::Pad", "Pad001")
        App.activeDocument().Pad001.Sketch = App.activeDocument().Sketch002
        App.activeDocument().Pad001.Length = 10.0
        App.ActiveDocument.recompute()
        Gui.activeDocument().hide("Sketch002")
        Gui.activeDocument().hide("Mirrored")
        #		Gui.ActiveDocument.Pad001.ShapeColor=Gui.ActiveDocument.Mirrored.ShapeColor
        #		Gui.ActiveDocument.Pad001.LineColor=Gui.ActiveDocument.Mirrored.LineColor
        #		Gui.ActiveDocument.Pad001.PointColor=Gui.ActiveDocument.Mirrored.PointColor
        App.ActiveDocument.Pad001.Length = gv.zRodStandoff - gv.clampGap / 2
        App.ActiveDocument.Pad001.Reversed = 1
        App.ActiveDocument.Pad001.Midplane = 0
        App.ActiveDocument.Pad001.Length2 = 100.000000
        App.ActiveDocument.Pad001.Type = 0
        App.ActiveDocument.Pad001.UpToFace = None
        App.ActiveDocument.recompute()
        #		Gui.activeDocument().resetEdit()

        #Make cut out for z rod
        #Sketch points
        p1x = 0
        p1y = gv.zRodStandoff
        p2x = -self.rodDia / 2
        p2y = gv.zRodStandoff
        p3x = self.rodDia / 2
        p3y = gv.zRodStandoff

        #make sketch
        App.activeDocument().addObject('Sketcher::SketchObject', 'Sketch003')
        #		Gui.activeDocument().setEdit('Sketch003')
        App.activeDocument().Sketch003.Support = uf.getFace(
            App.ActiveDocument.Pad001, 0, 0, -gv.zRodSupportLength / 2, 0,
            None, None)
        App.ActiveDocument.Sketch003.addExternal(
            "Pad001",
            uf.getEdge(App.ActiveDocument.Pad001, 0, 0,
                       -gv.zRodSupportLength / 2, 0,
                       gv.zRodStandoff - gv.clampGap / 2, 0))
        App.activeDocument().recompute()
        App.ActiveDocument.Sketch003.addGeometry(
            Part.ArcOfCircle(
                Part.Circle(App.Vector(p1x, p1y, 0), App.Vector(0, 0, 1),
                            self.rodDia / 2), math.pi, 2 * math.pi))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch003.addConstraint(
            Sketcher.Constraint('PointOnObject', 0, 3, -2))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch003.addGeometry(
            Part.Line(App.Vector(p2x, p2y, 0), App.Vector(p3x, p3y, 0)))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch003.addConstraint(
            Sketcher.Constraint('Coincident', 1, 1, 0, 1))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch003.addConstraint(
            Sketcher.Constraint('Coincident', 1, 2, 0, 2))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch003.addConstraint(
            Sketcher.Constraint('Horizontal', 1))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch003.addConstraint(
            Sketcher.Constraint('PointOnObject', 0, 3, 1))

        #Add dimensions
        App.ActiveDocument.Sketch003.addConstraint(
            Sketcher.Constraint('Distance', 0, 3, -3, gv.clampGap / 2))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch003.addConstraint(
            Sketcher.Constraint('Radius', 0, self.rodDia / 2))
        App.ActiveDocument.recompute()
        #		Gui.getDocument(self.name).resetEdit()
        App.getDocument(self.name).recompute()

        #Cut through all
        App.activeDocument().addObject("PartDesign::Pocket", "Pocket001")
        App.activeDocument().Pocket001.Sketch = App.activeDocument().Sketch003
        App.activeDocument().Pocket001.Length = 5.0
        App.ActiveDocument.recompute()
        Gui.activeDocument().hide("Sketch003")
        Gui.activeDocument().hide("Pad001")
        #		Gui.ActiveDocument.Pocket001.ShapeColor=Gui.ActiveDocument.Pad001.ShapeColor
        #		Gui.ActiveDocument.Pocket001.LineColor=Gui.ActiveDocument.Pad001.LineColor
        #		Gui.ActiveDocument.Pocket001.PointColor=Gui.ActiveDocument.Pad001.PointColor
        App.ActiveDocument.Pocket001.Length = 5.000000
        App.ActiveDocument.Pocket001.Type = 1
        App.ActiveDocument.Pocket001.UpToFace = None
        App.ActiveDocument.recompute()
        #		Gui.activeDocument().resetEdit()

        #cut Right clamp hole
        #Sketch points
        p1x = self.rodDia / 2 + gv.printedToPrintedDia / 2
        p1y = 0

        #Make sketch
        App.activeDocument().addObject('Sketcher::SketchObject', 'Sketch004')
        App.activeDocument().Sketch004.Support = uf.getFace(
            App.ActiveDocument.Pocket001, 0, 1, 0, 0,
            gv.zRodStandoff - gv.clampGap / 2, 0)
        App.activeDocument().recompute()
        #		Gui.activeDocument().setEdit('Sketch004')
        App.ActiveDocument.Sketch004.addGeometry(
            Part.Circle(App.Vector(p1x, p1y, 0), App.Vector(0, 0, 1),
                        gv.printedToPrintedDia / 2))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch004.addConstraint(
            Sketcher.Constraint('PointOnObject', 0, 3, -1))
        App.ActiveDocument.recompute()

        #Add dimensions
        App.ActiveDocument.Sketch004.addConstraint(
            Sketcher.Constraint('Radius', 0, gv.printedToPrintedDia / 2))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch004.addConstraint(
            Sketcher.Constraint('Distance', -1, 1, 0, 3,
                                self.rodDia / 2 + gv.printedToPrintedDia / 2))
        App.ActiveDocument.recompute()
        #		Gui.getDocument(self.name).resetEdit()
        App.getDocument(self.name).recompute()

        #Cut clamp hole through all
        App.activeDocument().addObject("PartDesign::Pocket", "Pocket002")
        App.activeDocument().Pocket002.Sketch = App.activeDocument().Sketch004
        App.activeDocument().Pocket002.Length = 5.0
        App.ActiveDocument.recompute()
        Gui.activeDocument().hide("Sketch004")
        Gui.activeDocument().hide("Pocket001")
        #		Gui.ActiveDocument.Pocket002.ShapeColor=Gui.ActiveDocument.Pocket001.ShapeColor
        #		Gui.ActiveDocument.Pocket002.LineColor=Gui.ActiveDocument.Pocket001.LineColor
        #		Gui.ActiveDocument.Pocket002.PointColor=Gui.ActiveDocument.Pocket001.PointColor
        App.ActiveDocument.Pocket002.Length = 5.000000
        App.ActiveDocument.Pocket002.Type = 1
        App.ActiveDocument.Pocket002.UpToFace = None
        App.ActiveDocument.recompute()
        #		Gui.activeDocument().resetEdit()

        #Reflect clamp hole accross verticle axis
        App.activeDocument().addObject("PartDesign::Mirrored", "Mirrored001")
        App.ActiveDocument.recompute()
        App.activeDocument().Mirrored001.Originals = [
            App.activeDocument().Pocket002,
        ]
        App.activeDocument().Mirrored001.MirrorPlane = (
            App.activeDocument().Sketch004, ["V_Axis"])
        Gui.activeDocument().Pocket002.Visibility = False
        #		Gui.ActiveDocument.Mirrored001.ShapeColor=Gui.ActiveDocument.Pocket002.ShapeColor
        #		Gui.ActiveDocument.Mirrored001.DisplayMode=Gui.ActiveDocument.Pocket002.DisplayMode
        App.ActiveDocument.Mirrored001.Originals = [
            App.ActiveDocument.Pocket002,
        ]
        App.ActiveDocument.Mirrored001.MirrorPlane = (
            App.ActiveDocument.Sketch004, ["V_Axis"])
        App.ActiveDocument.recompute()
        #		Gui.activeDocument().resetEdit()

        #refine shape
        App.activeDocument().addObject(
            "Part::Feature", "Refined"
        ).Shape = App.ActiveDocument.Mirrored001.Shape.removeSplitter()
        Gui.activeDocument().hide("Mirrored001")

        #Add Nut trap to right side
        #Sketch Points
        mat = uf.hexagonPoints(self.rodDia / 2 + gv.printedToPrintedDia / 2, 0,
                               gv.clampNutFaceToFace, 0)

        p1x = mat[0][0]
        p1y = mat[0][1]
        p2x = mat[1][0]
        p2y = mat[1][1]
        p3x = mat[2][0]
        p3y = mat[2][1]
        p4x = mat[3][0]
        p4y = mat[3][1]
        p5x = mat[4][0]
        p5y = mat[4][1]
        p6x = mat[5][0]
        p6y = mat[5][1]
        p7x = mat[6][0]
        p7y = mat[6][1]
        hexRadius = mat[7][0]

        #make sketch
        App.activeDocument().addObject('Sketcher::SketchObject', 'Sketch005')
        #		Gui.activeDocument().setEdit('Sketch005')
        App.activeDocument().Sketch005.Support = uf.getFace(
            App.ActiveDocument.Refined, 0, 0, 0, 0, 0, 0)
        App.ActiveDocument.Sketch005.addExternal(
            "Refined",
            uf.getEdge(App.ActiveDocument.Refined,
                       0,
                       1,
                       None,
                       None,
                       0,
                       0,
                       radius=gv.printedToPrintedDia / 2,
                       makeUnique=True))

        App.ActiveDocument.Sketch005.addGeometry(
            Part.Line(App.Vector(p1x, p1y, 0), App.Vector(p2x, p2y, 0)))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch005.addGeometry(
            Part.Line(App.Vector(p2x, p2y, 0), App.Vector(p3x, p3y, 0)))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch005.addConstraint(
            Sketcher.Constraint('Coincident', 0, 2, 1, 1))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch005.addGeometry(
            Part.Line(App.Vector(p3x, p3y, 0), App.Vector(p4x, p4y, 0)))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch005.addConstraint(
            Sketcher.Constraint('Coincident', 1, 2, 2, 1))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch005.addGeometry(
            Part.Line(App.Vector(p4x, p4y, 0), App.Vector(p5x, p5y, 0)))
        App.ActiveDocument.Sketch005.addConstraint(
            Sketcher.Constraint('Coincident', 2, 2, 3, 1))
        App.ActiveDocument.recompute()
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch005.addGeometry(
            Part.Line(App.Vector(p5x, p5y, 0), App.Vector(p6x, p6y, 0)))
        App.ActiveDocument.Sketch005.addConstraint(
            Sketcher.Constraint('Coincident', 3, 2, 4, 1))
        App.ActiveDocument.recompute()
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch005.addGeometry(
            Part.Line(App.Vector(p6x, p6y, 0), App.Vector(p1x, p1y, 0)))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch005.addConstraint(
            Sketcher.Constraint('Coincident', 4, 2, 5, 1))
        App.ActiveDocument.recompute()
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch005.addConstraint(
            Sketcher.Constraint('Coincident', 5, 2, 0, 1))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch005.addGeometry(
            Part.Circle(App.Vector(p7x, p7y, 0), App.Vector(0, 0, 1),
                        hexRadius))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch005.addConstraint(
            Sketcher.Constraint('PointOnObject', 0, 1, 6))
        App.ActiveDocument.Sketch005.addConstraint(
            Sketcher.Constraint('PointOnObject', 0, 2, 6))
        App.ActiveDocument.Sketch005.addConstraint(
            Sketcher.Constraint('PointOnObject', 1, 2, 6))
        App.ActiveDocument.Sketch005.addConstraint(
            Sketcher.Constraint('PointOnObject', 2, 2, 6))
        App.ActiveDocument.Sketch005.addConstraint(
            Sketcher.Constraint('PointOnObject', 3, 2, 6))
        App.ActiveDocument.Sketch005.addConstraint(
            Sketcher.Constraint('PointOnObject', 4, 2, 6))
        App.ActiveDocument.Sketch005.addConstraint(
            Sketcher.Constraint('Equal', 5, 0))
        App.ActiveDocument.Sketch005.addConstraint(
            Sketcher.Constraint('Equal', 0, 1))
        App.ActiveDocument.Sketch005.addConstraint(
            Sketcher.Constraint('Equal', 1, 2))
        App.ActiveDocument.Sketch005.addConstraint(
            Sketcher.Constraint('Equal', 2, 3))
        App.ActiveDocument.Sketch005.addConstraint(
            Sketcher.Constraint('Equal', 3, 4))
        App.ActiveDocument.Sketch005.toggleConstruction(6)
        App.ActiveDocument.Sketch005.addConstraint(
            Sketcher.Constraint('Coincident', -3, 3, 6, 3))
        App.ActiveDocument.recompute()

        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch005.addConstraint(
            Sketcher.Constraint('Distance', 0, 2, 4, gv.clampNutFaceToFace))
        App.ActiveDocument.recompute()
        #		Gui.getDocument(self.name).resetEdit()
        App.getDocument(self.name).recompute()

        #cut nut trap out
        App.activeDocument().addObject("PartDesign::Pocket", "Pocket003")
        App.activeDocument().Pocket003.Sketch = App.activeDocument().Sketch005
        App.activeDocument().Pocket003.Length = 5.0
        App.ActiveDocument.recompute()
        Gui.activeDocument().hide("Sketch005")
        Gui.activeDocument().hide("Refined")
        #		Gui.ActiveDocument.Pocket003.ShapeColor=Gui.ActiveDocument.Pocket002.ShapeColor
        #		Gui.ActiveDocument.Pocket003.LineColor=Gui.ActiveDocument.Pocket002.LineColor
        #		Gui.ActiveDocument.Pocket003.PointColor=Gui.ActiveDocument.Pocket002.PointColor
        App.ActiveDocument.Pocket003.Length = gv.rodSupportNutTrapDepthMin
        App.ActiveDocument.Pocket003.Type = 0
        App.ActiveDocument.Pocket003.UpToFace = None
        App.ActiveDocument.recompute()
        #		Gui.activeDocument().resetEdit()

        #Mirror nut trap
        App.activeDocument().addObject("PartDesign::Mirrored", "Mirrored002")
        App.ActiveDocument.recompute()
        App.activeDocument().Mirrored002.Originals = [
            App.activeDocument().Pocket003,
        ]
        App.activeDocument().Mirrored002.MirrorPlane = (
            App.activeDocument().Sketch005, ["V_Axis"])
        Gui.activeDocument().Pocket003.Visibility = False
        #		Gui.ActiveDocument.Mirrored002.ShapeColor=Gui.ActiveDocument.Pocket003.ShapeColor
        #		Gui.ActiveDocument.Mirrored002.DisplayMode=Gui.ActiveDocument.Pocket003.DisplayMode
        App.ActiveDocument.Mirrored002.Originals = [
            App.ActiveDocument.Pocket003,
        ]
        App.ActiveDocument.Mirrored002.MirrorPlane = (
            App.ActiveDocument.Sketch005, ["V_Axis"])
        App.ActiveDocument.recompute()
        #		Gui.activeDocument().resetEdit()

        #Set view as axometric
        #		Gui.activeDocument().activeView().viewAxometric()

        #Make the coresponding xRodClamp
        try:
            #		Gui.getDocument(self.name+"Clamp")
            #		Gui.getDocument(self.name+"Clamp").resetEdit()
            App.getDocument(self.name + "Clamp").recompute()
            App.closeDocument(self.name + "Clamp")
            App.setActiveDocument("")
            App.ActiveDocument = None

    #		Gui.ActiveDocument=None
        except:
            pass

        #make document
        App.newDocument(self.name + "Clamp")
        App.setActiveDocument(self.name + "Clamp")
        App.ActiveDocument = App.getDocument(self.name + "Clamp")
        #		Gui.ActiveDocument=Gui.getDocument(self.name+"Clamp")
        App.ActiveDocument = App.getDocument(self.name + "Clamp")

        #Make clamp body
        #Sketch points
        p1x = -supportWidth / 2
        p1y = -gv.zRodSupportLength / 2
        p2x = -supportWidth / 2
        p2y = gv.zRodSupportLength / 2
        p3x = supportWidth / 2
        p3y = gv.zRodSupportLength / 2
        p4x = supportWidth / 2
        p4y = -gv.zRodSupportLength / 2

        #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.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', 0, 1, 1, 2, -1, 1))
        App.ActiveDocument.recompute()

        #add dimensions
        App.ActiveDocument.Sketch.addConstraint(
            Sketcher.Constraint('DistanceY', 1, gv.zRodSupportLength))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch.addConstraint(
            Sketcher.Constraint('DistanceX', 2, -supportWidth))
        App.ActiveDocument.recompute()
        #		Gui.getDocument(self.name+"Clamp").resetEdit()
        App.getDocument(self.name + "Clamp").recompute()

        #pad rod support
        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 = self.rodDia / 2 + gv.clampThickness - gv.clampGap / 2
        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 cut out for rod
        #sketch points
        p1x = 0
        p1y = self.rodDia / 2 + gv.clampThickness
        p2x = -self.rodDia / 2
        p2y = self.rodDia / 2 + gv.clampThickness
        p3x = self.rodDia / 2
        p3y = self.rodDia / 2 + gv.clampThickness

        #Make Sketch
        #make sketch
        App.activeDocument().addObject('Sketcher::SketchObject', 'Sketch001')
        App.activeDocument().Sketch001.Support = uf.getFace(
            App.ActiveDocument.Pad, 0, 0, -gv.zRodSupportLength / 2, 0, None,
            None)
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch001.addExternal(
            "Pad",
            uf.getEdge(App.ActiveDocument.Pad, 0, 0, -gv.zRodSupportLength / 2,
                       0,
                       self.rodDia / 2 + gv.clampThickness - gv.clampGap / 2,
                       0))
        #		Gui.activeDocument().setEdit('Sketch001')
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch001.addGeometry(
            Part.ArcOfCircle(
                Part.Circle(App.Vector(p1x, p1y, 0), App.Vector(0, 0, 1),
                            self.rodDia / 2), math.pi, 2 * math.pi))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('PointOnObject', 0, 3, -2))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch001.addGeometry(
            Part.Line(App.Vector(p2x, p2y, 0), App.Vector(p3x, p3y, 0)))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('Coincident', 1, 1, 0, 1))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('Coincident', 1, 2, 0, 2))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('Horizontal', 1))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('PointOnObject', 0, 3, 1))

        #Add dimensions
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('Distance', 0, 3, -3, gv.clampGap / 2))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('Radius', 0, self.rodDia / 2))
        App.ActiveDocument.recompute()
        #		Gui.getDocument(self.name+"Clamp").resetEdit()
        App.getDocument(self.name + "Clamp").recompute()

        #Cut 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()
        #		Gui.activeDocument().resetEdit()

        #cut Right clamp hole
        #Sketch points
        p1x = self.rodDia / 2 + gv.printedToPrintedDia / 2
        p1y = 0

        #Make sketch
        App.activeDocument().addObject('Sketcher::SketchObject', 'Sketch002')
        App.activeDocument().Sketch002.Support = uf.getFace(
            App.ActiveDocument.Pocket, 0, 1, 0, 0,
            self.rodDia / 2 + gv.clampThickness - gv.clampGap / 2, 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.printedToPrintedDia / 2))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('PointOnObject', 0, 3, -1))
        App.ActiveDocument.recompute()

        #Add dimensions
        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('Radius', 0, gv.printedToPrintedDia / 2))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('Distance', -1, 1, 0, 3,
                                self.rodDia / 2 + gv.printedToPrintedDia / 2))
        App.ActiveDocument.recompute()
        #		Gui.getDocument(self.name+"Clamp").resetEdit()
        App.getDocument(self.name + "Clamp").recompute()

        #Cut clamp hole through all
        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()
        #		Gui.activeDocument().resetEdit()

        #Mirror clamp hole
        App.activeDocument().addObject("PartDesign::Mirrored", "Mirrored")
        App.ActiveDocument.recompute()
        App.activeDocument().Mirrored.Originals = [
            App.activeDocument().Pocket001,
        ]
        App.activeDocument().Mirrored.MirrorPlane = (
            App.activeDocument().Sketch002, ["V_Axis"])
        Gui.activeDocument().Pocket001.Visibility = False
        #		Gui.activeDocument().setEdit('Mirrored')
        #		Gui.ActiveDocument.Mirrored.ShapeColor=Gui.ActiveDocument.Pocket001.ShapeColor
        #		Gui.ActiveDocument.Mirrored.DisplayMode=Gui.ActiveDocument.Pocket001.DisplayMode
        App.ActiveDocument.Mirrored.Originals = [
            App.ActiveDocument.Pocket001,
        ]
        App.ActiveDocument.Mirrored.MirrorPlane = (
            App.ActiveDocument.Sketch002, ["V_Axis"])
        App.ActiveDocument.recompute()
Example #47
0
def run_FreeCAD_View3D(self, *args, **kwargs):

    name=self.getData('name')
    Shape=self.getPinObject('Shape_in')
    workspace=self.getData('Workspace')
    mode='1'
    wireframe=False
    transparency=50
    #+#todo make the parameters to pins
    timeA=time.time()
    shape=self.getPinObject('Shape_in')
    s=shape
    say("--------",s,s.Volume,s.Area)
    l=FreeCAD.listDocuments()
    if workspace=='' or workspace=='None':
        w=FreeCAD.ActiveDocument
        '''
        try:
            w=l['Unnamed']
        except:
            w=FreeCAD.newDocument("Unnamed")
            FreeCADGui.runCommand("Std_TileWindows")
        '''
    else:
        if workspace in l.keys():
            w=l[workspace]
        else:
            w=FreeCAD.newDocument(workspace)

            #Std_CascadeWindows
            FreeCADGui.runCommand("Std_ViewDimetric")
            FreeCADGui.runCommand("Std_ViewFitAll")
            FreeCADGui.runCommand("Std_TileWindows")


    f=w.getObject(name)
    if f == None:
        f = w.addObject('Part::Feature', name)

    say("off-------",self.getData('off'))
    if self.getData('off'):
        f.ViewObject.hide()
        return
    else:
        f.ViewObject.show()

    if s  !=  None:
        if 1 or s.Volume != 0:
            f.Shape=s
        else:  
            t=Part.makeBox(0.001,0.001,0.001)#.toShape()
            f.Shape=t

    f.recompute()
    f.purgeTouched()

    if 1:
        if not wireframe:
            f.ViewObject.DisplayMode = "Flat Lines"
            f.ViewObject.ShapeColor = (random.random(),random.random(),1.)
        else:
            f.ViewObject.DisplayMode = "Wireframe"
            f.ViewObject.LineColor = (random.random(),random.random(),1.)
Example #48
0
    def accept(self):

        if self.form.groupNewDocument.isChecked() or (FreeCAD.ActiveDocument == None):
            doc = FreeCAD.newDocument()
            if self.form.projectName.text():
                doc.Label = self.form.projectName.text()
            FreeCAD.ActiveDocument = doc
        if not FreeCAD.ActiveDocument:
            FreeCAD.Console.PrintError("No active document, aborting.\n")
        import Draft,Arch
        site = None
        outline = None
        if self.form.groupSite.isChecked():
            site = Arch.makeSite()
            site.Label = self.form.siteName.text()
            site.Address = self.form.siteAddress.text()
            site.Longitude = self.form.siteLongitude.value()
            site.Latitude = self.form.siteLatitude.value()
            if hasattr(site,"NorthDeviation"):
                site.NorthDeviation = self.form.siteDeviation.value()
            elif hasattr(site,"Declination"):
                site.Declination = self.form.siteDeviation.value()
            site.Elevation = FreeCAD.Units.Quantity(self.form.siteElevation.text()).Value
        if self.form.groupBuilding.isChecked():
            building = Arch.makeBuilding()
            if site:
                site.Group = [building]
            building.Label = self.form.buildingName.text()
            building.BuildingType = self.form.buildingUse.currentText()
            buildingWidth = FreeCAD.Units.Quantity(self.form.buildingWidth.text()).Value
            buildingLength = FreeCAD.Units.Quantity(self.form.buildingLength.text()).Value
            distVAxes = FreeCAD.Units.Quantity(self.form.distVAxes.text()).Value
            distHAxes = FreeCAD.Units.Quantity(self.form.distHAxes.text()).Value
            levelHeight = FreeCAD.Units.Quantity(self.form.levelHeight.text()).Value
            color = self.form.lineColor.property("color").getRgbF()[:3]
            if buildingWidth and buildingLength:
                outline = Draft.makeRectangle(buildingLength,buildingWidth,face=False)
                outline.Label = "Building Outline"
                outline.ViewObject.DrawStyle = "Dashed"
                outline.ViewObject.LineColor = color
                outline.ViewObject.LineWidth = self.form.lineWidth.value()*2
                grp = FreeCAD.ActiveDocument.addObject("App::DocumentObjectGroup")
                grp.Label = "Layout"
                building.addObject(grp)
                grp.addObject(outline)
                if self.form.buildingName.text():
                    outtext = Draft.makeText([self.form.buildingName.text()],point=FreeCAD.Vector(Draft.getParam("textheight",0.20)*0.3,-Draft.getParam("textheight",0.20)*1.43,0))
                    outtext.Label = "Building Label"
                    outtext.ViewObject.TextColor = color
                    grp.addObject(outtext)
            axisV = None
            if self.form.countVAxes.value() and distVAxes:
                axisV = Arch.makeAxis(num = self.form.countVAxes.value(), size = distVAxes, name="vaxis")
                axisV.Label = "Vertical Axes"
                axisV.ViewObject.BubblePosition = "Both"
                axisV.ViewObject.LineWidth = self.form.lineWidth.value()
                axisV.ViewObject.FontSize = Draft.getParam("textheight",0.20)
                axisV.ViewObject.BubbleSize = Draft.getParam("textheight",0.20)*1.43
                axisV.ViewObject.LineColor = color
                if outline:
                    axisV.setExpression('Length', outline.Name+'.Height * 1.1')
                    axisV.setExpression('Placement.Base.y', outline.Name+'.Placement.Base.y - '+axisV.Name+'.Length * 0.05')
                    axisV.setExpression('Placement.Base.x', outline.Name+'.Placement.Base.x')
            axisH = None
            if self.form.countHAxes.value() and distHAxes:
                axisH = Arch.makeAxis(num = self.form.countHAxes.value(), size = distHAxes, name="haxis")
                axisH.Label = "Horizontal Axes"
                axisH.ViewObject.BubblePosition = "Both"
                axisH.ViewObject.NumberingStyle = "A,B,C"
                axisH.ViewObject.LineWidth = self.form.lineWidth.value()
                axisH.ViewObject.FontSize = Draft.getParam("textheight",0.20)
                axisH.ViewObject.BubbleSize = Draft.getParam("textheight",0.20)*1.43
                axisH.Placement.Rotation = FreeCAD.Rotation(FreeCAD.Vector(0,0,1),90)
                axisH.ViewObject.LineColor = color
                if outline:
                    axisH.setExpression('Length', outline.Name+'.Length * 1.1')
                    axisH.setExpression('Placement.Base.x', outline.Name+'.Placement.Base.x + '+axisH.Name+'.Length * 0.945')
                    axisH.setExpression('Placement.Base.y', outline.Name+'.Placement.Base.y')
            if axisV and axisH:
                axisG = Arch.makeAxisSystem([axisH,axisV])
                axisG.Label = "Axes"
                grp.addObject(axisG)
            else:
                if axisV:
                    grp.addObject(axisV)
                if axisH:
                    grp.addObject(axisH)
            if self.form.countLevels.value() and levelHeight:
                h = 0
                alabels = []
                for i in range(self.form.countLevels.value()):
                    lev = Arch.makeFloor()
                    lev.Label = "Level "+str(i)
                    alabels.append(lev.Label)
                    lev.Height = levelHeight
                    lev.Placement.move(FreeCAD.Vector(0,0,h))
                    h += levelHeight
                    building.addObject(lev)
                    if self.form.levelsWP.isChecked():
                        prx = Draft.makeWorkingPlaneProxy(FreeCAD.Placement())
                        prx.Placement.move(FreeCAD.Vector(0,0,h))
                        lev.addObject(prx)
                if self.form.levelsAxis.isChecked():
                    axisL = Arch.makeAxis(num = self.form.countLevels.value(), size = levelHeight, name="laxis")
                    axisL.Label = "Level Axes"
                    axisL.ViewObject.BubblePosition = "None"
                    axisL.ViewObject.LineWidth = self.form.lineWidth.value()
                    axisL.ViewObject.FontSize = Draft.getParam("textheight",0.20)
                    axisL.Placement.Rotation = FreeCAD.Rotation(FreeCAD.Vector (0.577350269189626, -0.5773502691896257, 0.5773502691896257),120)
                    axisL.ViewObject.LineColor = color
                    axisL.ViewObject.LabelOffset.Rotation = FreeCAD.Rotation(FreeCAD.Vector(1,0,0),90)
                    axisL.Labels = alabels
                    axisL.ViewObject.ShowLabel = True
                    if outline:
                        axisL.setExpression('Length', outline.Name+'.Length * 1.1')
                        axisL.setExpression('Placement.Base.x', outline.Name+'.Placement.Base.x + '+axisL.Name+'.Length * 0.945')
                        axisL.setExpression('Placement.Base.y', outline.Name+'.Placement.Base.y')
                        grp.addObject(axisL)
                        axisL.ViewObject.LabelOffset.Base = FreeCAD.Vector(-axisL.Length.Value + Draft.getParam("textheight",0.20)*0.43,0,Draft.getParam("textheight",0.20)*0.43)
        self.form.hide()
        FreeCAD.ActiveDocument.recompute()
        if outline:
            FreeCADGui.Selection.clearSelection()
            FreeCADGui.Selection.addSelection(outline)
            FreeCADGui.SendMsgToActiveView("ViewSelection")
            FreeCADGui.Selection.clearSelection()
        if hasattr(FreeCADGui,"Snapper"):
            FreeCADGui.Snapper.show()
        return True
Example #49
0
def makeEnumTest():
	FreeCAD.newDocument()
	a=FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Enum")
	EnumTest(a)
	ViewProviderEnumTest(a.ViewObject)
    def testFunctions(self):
        """ Test all built-in simple functions """
        doc = FreeCAD.newDocument()
        sheet = self.doc.addObject('Spreadsheet::Sheet', 'Spreadsheet')
        sheet.set('A1', '=cos(60)')  # Cos
        sheet.set('B1', '=cos(60deg)')
        sheet.set('C1', '=cos(pi / 2 * 1rad)')
        sheet.set('A2', '=sin(30)')  # Sin
        sheet.set('B2', '=sin(30deg)')
        sheet.set('C2', '=sin(pi / 6 * 1rad)')
        sheet.set('A3', '=tan(45)')  # Tan
        sheet.set('B3', '=tan(45deg)')
        sheet.set('C3', '=tan(pi / 4 * 1rad)')
        sheet.set('A4', '=abs(3)')  # Abs
        sheet.set('B4', '=abs(-3)')
        sheet.set('C4', '=abs(-3mm)')
        sheet.set('A5', '=exp(3)')  # Exp
        sheet.set('B5', '=exp(-3)')
        sheet.set('C5', '=exp(-3mm)')
        sheet.set('A6', '=log(3)')  # Log
        sheet.set('B6', '=log(-3)')
        sheet.set('C6', '=log(-3mm)')
        sheet.set('A7', '=log10(10)')  # Log10
        sheet.set('B7', '=log10(-3)')
        sheet.set('C7', '=log10(-3mm)')
        sheet.set('A8', '=round(3.4)')  # Round
        sheet.set('B8', '=round(3.6)')
        sheet.set('C8', '=round(-3.4)')
        sheet.set('D8', '=round(-3.6)')
        sheet.set('E8', '=round(3.4mm)')
        sheet.set('F8', '=round(3.6mm)')
        sheet.set('G8', '=round(-3.4mm)')
        sheet.set('H8', '=round(-3.6mm)')
        sheet.set('A9', '=trunc(3.4)')  # Trunc
        sheet.set('B9', '=trunc(3.6)')
        sheet.set('C9', '=trunc(-3.4)')
        sheet.set('D9', '=trunc(-3.6)')
        sheet.set('E9', '=trunc(3.4mm)')
        sheet.set('F9', '=trunc(3.6mm)')
        sheet.set('G9', '=trunc(-3.4mm)')
        sheet.set('H9', '=trunc(-3.6mm)')
        sheet.set('A10', '=ceil(3.4)')  # Ceil
        sheet.set('B10', '=ceil(3.6)')
        sheet.set('C10', '=ceil(-3.4)')
        sheet.set('D10', '=ceil(-3.6)')
        sheet.set('E10', '=ceil(3.4mm)')
        sheet.set('F10', '=ceil(3.6mm)')
        sheet.set('G10', '=ceil(-3.4mm)')
        sheet.set('H10', '=ceil(-3.6mm)')
        sheet.set('A11', '=floor(3.4)')  # Floor
        sheet.set('B11', '=floor(3.6)')
        sheet.set('C11', '=floor(-3.4)')
        sheet.set('D11', '=floor(-3.6)')
        sheet.set('E11', '=floor(3.4mm)')
        sheet.set('F11', '=floor(3.6mm)')
        sheet.set('G11', '=floor(-3.4mm)')
        sheet.set('H11', '=floor(-3.6mm)')
        sheet.set('A12', '=asin(0.5)')  # Asin
        sheet.set('B12', '=asin(0.5mm)')
        sheet.set('A13', '=acos(0.5)')  # Acos
        sheet.set('B13', '=acos(0.5mm)')
        sheet.set('A14', '=atan(sqrt(3))')  # Atan
        sheet.set('B14', '=atan(0.5mm)')
        sheet.set('A15', '=sinh(0.5)')  # Sinh
        sheet.set('B15', '=sinh(0.5mm)')
        sheet.set('A16', '=cosh(0.5)')  # Cosh
        sheet.set('B16', '=cosh(0.5mm)')
        sheet.set('A17', '=tanh(0.5)')  # Tanh
        sheet.set('B17', '=tanh(0.5mm)')
        sheet.set('A18', '=sqrt(4)')  # Sqrt
        sheet.set('B18', '=sqrt(4mm^2)')
        sheet.set('A19', '=mod(7; 4)')  # Mod
        sheet.set('B19', '=mod(-7; 4)')
        sheet.set('C19', '=mod(7mm; 4)')
        sheet.set('D19', '=mod(7mm; 4mm)')
        sheet.set('A20', '=atan2(3; 3)')  # Atan2
        sheet.set('B20', '=atan2(-3; 3)')
        sheet.set('C20', '=atan2(3mm; 3)')
        sheet.set('D20', '=atan2(3mm; 3mm)')
        sheet.set('A21', '=pow(7; 4)')  # Pow
        sheet.set('B21', '=pow(-7; 4)')
        sheet.set('C21', '=pow(7mm; 4)')
        sheet.set('D21', '=pow(7mm; 4mm)')
        sheet.set('A23', '=hypot(3; 4)')  # Hypot
        sheet.set('B23', '=hypot(-3; 4)')
        sheet.set('C23', '=hypot(3mm; 4)')
        sheet.set('D23', '=hypot(3mm; 4mm)')
        sheet.set('A24', '=hypot(3; 4; 5)')  # Hypot
        sheet.set('B24', '=hypot(-3; 4; 5)')
        sheet.set('C24', '=hypot(3mm; 4; 5)')
        sheet.set('D24', '=hypot(3mm; 4mm; 5mm)')
        sheet.set('A26', '=cath(5; 3)')  # Cath
        sheet.set('B26', '=cath(-5; 3)')
        sheet.set('C26', '=cath(5mm; 3)')
        sheet.set('D26', '=cath(5mm; 3mm)')

        l = math.sqrt(5 * 5 + 4 * 4 + 3 * 3)
        sheet.set('A27', '=cath(%0.15f; 5; 4)' % l)  # Cath
        sheet.set('B27', '=cath(%0.15f; -5; 4)' % l)
        sheet.set('C27', '=cath(%0.15f mm; 5mm; 4)' % l)
        sheet.set('D27', '=cath(%0.15f mm; 5mm; 4mm)' % l)

        self.doc.recompute()
        self.assertMostlyEqual(sheet.A1, 0.5)  # Cos
        self.assertMostlyEqual(sheet.B1, 0.5)
        self.assertMostlyEqual(sheet.C1, 0)
        self.assertMostlyEqual(sheet.A2, 0.5)  # Sin
        self.assertMostlyEqual(sheet.B2, 0.5)
        self.assertMostlyEqual(sheet.C2, 0.5)
        self.assertMostlyEqual(sheet.A3, 1)  # Tan
        self.assertMostlyEqual(sheet.B3, 1)
        self.assertMostlyEqual(sheet.C3, 1)
        self.assertMostlyEqual(sheet.A4, 3)  # Abs
        self.assertMostlyEqual(sheet.B4, 3)
        self.assertMostlyEqual(sheet.C4, Units.Quantity('3 mm'))
        self.assertMostlyEqual(sheet.A5, math.exp(3))  # Exp
        self.assertMostlyEqual(sheet.B5, math.exp(-3))
        self.assertTrue(sheet.C5.startswith(u'ERR: Unit must be empty.'))
        self.assertMostlyEqual(sheet.A6, math.log(3))  # Log
        self.assertTrue(math.isnan(sheet.B6))
        self.assertTrue(sheet.C6.startswith(u'ERR: Unit must be empty.'))
        self.assertMostlyEqual(sheet.A7, math.log10(10))  # Log10
        self.assertTrue(math.isnan(sheet.B7))
        self.assertTrue(sheet.C7.startswith(u'ERR: Unit must be empty.'))
        self.assertMostlyEqual(sheet.A8, 3)  # Round
        self.assertMostlyEqual(sheet.B8, 4)
        self.assertMostlyEqual(sheet.C8, -3)
        self.assertMostlyEqual(sheet.D8, -4)
        self.assertEqual(sheet.E8, Units.Quantity('3 mm'))
        self.assertEqual(sheet.F8, Units.Quantity('4 mm'))
        self.assertEqual(sheet.G8, Units.Quantity('-3 mm'))
        self.assertEqual(sheet.H8, Units.Quantity('-4 mm'))
        self.assertMostlyEqual(sheet.A9, 3)  # Trunc
        self.assertMostlyEqual(sheet.B9, 3)
        self.assertMostlyEqual(sheet.C9, -3)
        self.assertMostlyEqual(sheet.D9, -3)
        self.assertEqual(sheet.E9, Units.Quantity('3 mm'))
        self.assertEqual(sheet.F9, Units.Quantity('3 mm'))
        self.assertEqual(sheet.G9, Units.Quantity('-3 mm'))
        self.assertEqual(sheet.H9, Units.Quantity('-3 mm'))
        self.assertMostlyEqual(sheet.A10, 4)  # Ceil
        self.assertMostlyEqual(sheet.B10, 4)
        self.assertMostlyEqual(sheet.C10, -3)
        self.assertMostlyEqual(sheet.D10, -3)
        self.assertMostlyEqual(sheet.E10, Units.Quantity('4 mm'))
        self.assertMostlyEqual(sheet.F10, Units.Quantity('4 mm'))
        self.assertMostlyEqual(sheet.G10, Units.Quantity('-3 mm'))
        self.assertMostlyEqual(sheet.H10, Units.Quantity('-3 mm'))
        self.assertMostlyEqual(sheet.A11, 3)  # Floor
        self.assertMostlyEqual(sheet.B11, 3)
        self.assertMostlyEqual(sheet.C11, -4)
        self.assertMostlyEqual(sheet.D11, -4)
        self.assertMostlyEqual(sheet.E11, Units.Quantity('3 mm'))
        self.assertMostlyEqual(sheet.F11, Units.Quantity('3 mm'))
        self.assertMostlyEqual(sheet.G11, Units.Quantity('-4 mm'))
        self.assertMostlyEqual(sheet.H11, Units.Quantity('-4 mm'))
        self.assertMostlyEqual(sheet.A12, Units.Quantity('30 deg'))  # Asin
        self.assertTrue(sheet.B12.startswith(u'ERR: Unit must be empty.'))
        self.assertMostlyEqual(sheet.A13, Units.Quantity('60 deg'))  # Acos
        self.assertTrue(sheet.B13.startswith(u'ERR: Unit must be empty.'))
        self.assertMostlyEqual(sheet.A14, Units.Quantity('60 deg'))  # Atan
        self.assertTrue(sheet.B14.startswith(u'ERR: Unit must be empty.'))
        self.assertMostlyEqual(sheet.A15, math.sinh(0.5))  # Sinh
        self.assertTrue(sheet.B15.startswith(u'ERR: Unit must be empty.'))
        self.assertMostlyEqual(sheet.A16, math.cosh(0.5))  # Cosh
        self.assertTrue(sheet.B16.startswith(u'ERR: Unit must be empty.'))
        self.assertMostlyEqual(sheet.A17, math.tanh(0.5))  # Tanh
        self.assertTrue(sheet.B17.startswith(u'ERR: Unit must be empty.'))
        self.assertMostlyEqual(sheet.A18, 2)  # Sqrt
        self.assertMostlyEqual(sheet.B18, Units.Quantity('2 mm'))
        self.assertMostlyEqual(sheet.A19, 3)  # Mod
        self.assertMostlyEqual(sheet.B19, -3)
        self.assertMostlyEqual(sheet.C19, Units.Quantity('3 mm'))
        self.assertEqual(sheet.D19, 3)
        self.assertMostlyEqual(sheet.A20, Units.Quantity('45 deg'))  # Atan2
        self.assertMostlyEqual(sheet.B20, Units.Quantity('-45 deg'))
        self.assertTrue(sheet.C20.startswith(u'ERR: Units must be equal'))
        self.assertMostlyEqual(sheet.D20, Units.Quantity('45 deg'))
        self.assertMostlyEqual(sheet.A21, 2401)  # Pow
        self.assertMostlyEqual(sheet.B21, 2401)
        self.assertMostlyEqual(sheet.C21, Units.Quantity('2401mm^4'))
        self.assertTrue(
            sheet.D21.startswith(
                u'ERR: Exponent is not allowed to have a unit.'))
        self.assertMostlyEqual(sheet.A23, 5)  # Hypot
        self.assertMostlyEqual(sheet.B23, 5)
        self.assertTrue(sheet.C23.startswith(u'ERR: Units must be equal'))
        self.assertMostlyEqual(sheet.D23, Units.Quantity('5mm'))

        l = math.sqrt(3 * 3 + 4 * 4 + 5 * 5)
        self.assertMostlyEqual(sheet.A24, l)  # Hypot
        self.assertMostlyEqual(sheet.B24, l)
        self.assertTrue(sheet.C24.startswith(u'ERR: Units must be equal'))
        self.assertMostlyEqual(sheet.D24,
                               Units.Quantity("7.07106781186548 mm"))
        self.assertMostlyEqual(sheet.A26, 4)  # Cath
        self.assertMostlyEqual(sheet.B26, 4)
        self.assertTrue(sheet.C26.startswith(u'ERR: Units must be equal'))
        self.assertMostlyEqual(sheet.D26, Units.Quantity('4mm'))

        l = math.sqrt(5 * 5 + 4 * 4 + 3 * 3)
        l = math.sqrt(l * l - 5 * 5 - 4 * 4)
        self.assertMostlyEqual(sheet.A27, l)  # Cath
        self.assertMostlyEqual(sheet.B27, l)
        self.assertTrue(sheet.C27.startswith(u'ERR: Units must be equal'))
        self.assertMostlyEqual(sheet.D27, Units.Quantity("3 mm"))
        FreeCAD.closeDocument(doc.Name)
Example #51
0
    s.ViewObject.ShapeColor = f.ViewObject.ShapeColor
    s.ViewObject.LineColor = f.ViewObject.LineColor
    s.ViewObject.PointColor = f.ViewObject.PointColor
    s.ViewObject.DiffuseColor = f.ViewObject.DiffuseColor
    doc.recompute()
    for o in objs:
        doc.removeObject(o.Name)
    doc.removeObject(f.Name)


import libraries

if __name__ == "__main__":
    script_dir = os.path.dirname(os.path.realpath(__file__))
    db_dir = os.path.join("database")
    doc = FreeCAD.newDocument("3DPartGen")

    for library in libraries.__all__:
        FreeCAD.Console.PrintMessage("Processing Library '" + library + "'\n")
        libmod = vars(libraries)[library]
        libmod.read_params(os.path.join(db_dir, library + ".csv"))
        out_dir = os.path.join(script_dir, library + ".3dshapes")
        if not os.path.exists(out_dir):
            os.makedirs(out_dir)
        FreeCAD.Console.PrintMessage(
            str(len(libmod.all_params)) + " parts found!\n")
        for part in libmod.all_params.keys():
            for o in doc.Objects:
                doc.removeObject(o.Name)
            FreeCAD.Console.PrintMessage("Generating part '" + part + "'\n")
            libmod.make(libmod.all_params[part])
Example #52
0
    def draw(self):

        try:
            App.getDocument(self.name).recompute()
            App.closeDocument(self.name)
            App.setActiveDocument("")
            App.ActiveDocument = None
        except:
            pass

        #make document
        App.newDocument(self.name)
        App.setActiveDocument(self.name)
        App.ActiveDocument = App.getDocument(self.name)

        #Make profile of angle and extrude it
        p1x = 0
        p1y = 0
        p2x = 0
        p2y = gv.extruderMountAngleWidth
        p3x = p2y
        p3y = p2y
        p4x = p3x
        p4y = gv.extruderMountAngleWidth - gv.extruderMountAngleThickness
        p5x = gv.extruderMountAngleThickness
        p5y = p4y
        p6x = p5x
        p6y = p1y

        #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.500000, 0.500000, 0.500000, 0.500000))
        App.ActiveDocument.Sketch.addGeometry(
            Part.Line(App.Vector(p1x, p1y, 0), App.Vector(p2x, p2y, 0)))
        App.ActiveDocument.Sketch.addConstraint(
            Sketcher.Constraint('Coincident', -1, 1, 0, 1))
        App.ActiveDocument.recompute()
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch.addConstraint(
            Sketcher.Constraint('PointOnObject', 0, 2, -2))
        App.ActiveDocument.recompute()

        App.ActiveDocument.Sketch.addGeometry(
            Part.Line(App.Vector(p2x, p2y, 0), App.Vector(p3x, p3y, 0)))
        App.ActiveDocument.Sketch.addConstraint(
            Sketcher.Constraint('Coincident', 0, 2, 1, 1))
        App.ActiveDocument.recompute()
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch.addConstraint(
            Sketcher.Constraint('Horizontal', 1))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch.addGeometry(
            Part.Line(App.Vector(p3x, p3y, 0), App.Vector(p4x, p4y, 0)))
        App.ActiveDocument.Sketch.addConstraint(
            Sketcher.Constraint('Coincident', 1, 2, 2, 1))
        App.ActiveDocument.recompute()
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch.addConstraint(
            Sketcher.Constraint('Vertical', 2))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch.addGeometry(
            Part.Line(App.Vector(p4x, p4y, 0), App.Vector(p5x, p5y, 0)))
        App.ActiveDocument.Sketch.addConstraint(
            Sketcher.Constraint('Coincident', 2, 2, 3, 1))
        App.ActiveDocument.recompute()
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch.addConstraint(
            Sketcher.Constraint('Horizontal', 3))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch.addGeometry(
            Part.Line(App.Vector(p5x, p5y, 0), App.Vector(p6x, p6y, 0)))
        App.ActiveDocument.Sketch.addConstraint(
            Sketcher.Constraint('Coincident', 3, 2, 4, 1))
        App.ActiveDocument.recompute()
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch.addConstraint(
            Sketcher.Constraint('Vertical', 4))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch.addGeometry(
            Part.Line(App.Vector(p6x, p6y, 0), App.Vector(p1x, p1y, 0)))
        App.ActiveDocument.Sketch.addConstraint(
            Sketcher.Constraint('Coincident', 4, 2, 5, 1))
        App.ActiveDocument.Sketch.addConstraint(
            Sketcher.Constraint('Coincident', 5, 2, 0, 1))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch.addConstraint(
            Sketcher.Constraint('Horizontal', 5))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch.addConstraint(
            Sketcher.Constraint('Equal', 0, 1))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch.addConstraint(
            Sketcher.Constraint('Equal', 2, 5))
        App.ActiveDocument.recompute()

        #Add dimensions
        App.ActiveDocument.Sketch.addConstraint(
            Sketcher.Constraint('DistanceY', 0, gv.extruderMountAngleWidth))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch.addConstraint(
            Sketcher.Constraint('DistanceY', 2,
                                -gv.extruderMountAngleThickness))
        App.ActiveDocument.recompute()
        App.getDocument('extruderMountAngle').recompute()

        #Extrude the extruder mount angle
        App.activeDocument().addObject("PartDesign::Pad", "Pad")
        App.activeDocument().Pad.Sketch = App.activeDocument().Sketch
        App.activeDocument().Pad.Length = 10.0
        App.ActiveDocument.recompute()
        App.ActiveDocument.Pad.Length = gv.xCarriageWidth
        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()

        #Cut holes for mounting to xCarriage
        #Sketch Points
        p1x = (gv.extruderMountAngleWidth - gv.extruderMountAngleThickness) / 2
        p1y = gv.xCarriageWidth
        p2x = p1x
        p2y = gv.xCarriageWidth - gv.xCarriageMountHoleHorizOffset
        p3x = p1x
        p3y = gv.xCarriageMountHoleHorizOffset
        p4x = p1x
        p4y = 0

        #Make Sketch
        App.activeDocument().addObject('Sketcher::SketchObject', 'Sketch001')
        App.activeDocument().Sketch001.Support = uf.getFace(
            App.ActiveDocument.Pad, None, None, gv.extruderMountAngleThickness,
            0, None, None)  #(App.ActiveDocument.Pad,["Face5"])
        App.activeDocument().recompute()
        #		App.ActiveDocument.Sketch001.addExternal("Pad","Edge16")
        App.ActiveDocument.Sketch001.addExternal(
            "Pad",
            uf.getEdge(
                App.ActiveDocument.Pad, gv.xCarriageWidth, 0,
                gv.extruderMountAngleThickness, 0,
                (gv.extruderMountAngleWidth - gv.extruderMountAngleThickness) /
                2, 0))
        App.ActiveDocument.Sketch001.addExternal(
            "Pad",
            uf.getEdge(
                App.ActiveDocument.Pad, 0, 0, gv.extruderMountAngleThickness,
                0,
                (gv.extruderMountAngleWidth - gv.extruderMountAngleThickness) /
                2, 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, -3))
        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('PointOnObject', 2, 2, -4))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('Vertical', 2))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('Symmetric', -3, 1, -3, 2, 0, 1))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('Equal', 0, 2))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch001.toggleConstruction(0)
        App.ActiveDocument.Sketch001.toggleConstruction(1)
        App.ActiveDocument.Sketch001.toggleConstruction(2)
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch001.addGeometry(
            Part.Circle(App.Vector(p2x, p2y, 0), App.Vector(0, 0, 1),
                        gv.mountToPrintedDia / 2))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('Coincident', 3, 3, 0, 2))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch001.addGeometry(
            Part.Circle(App.Vector(p3x, p3y, 0), App.Vector(0, 0, 1),
                        gv.mountToPrintedDia / 2))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('Coincident', 4, 3, 1, 2))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('Equal', 4, 3))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('Radius', 3, gv.mountToPrintedDia / 2))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch001.addConstraint(
            Sketcher.Constraint('DistanceY', 0,
                                -gv.xCarriageMountHoleHorizOffset))
        App.ActiveDocument.recompute()
        App.getDocument(self.name).recompute()

        #Cut mounting 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()
        App.ActiveDocument.Pocket.Length = 5.000000
        App.ActiveDocument.Pocket.Type = 1
        App.ActiveDocument.Pocket.UpToFace = None
        App.ActiveDocument.recompute()

        #Make mounting holes for extruderMountPlate
        #SketchPoints
        p1x = (gv.extruderMountAngleWidth + gv.extruderMountAngleThickness) / 2
        p1y = gv.xCarriageWidth
        p2x = p1x
        p2y = gv.xCarriageWidth - gv.xCarriageMountHoleHorizOffset
        p3x = p1x
        p3y = gv.xCarriageMountHoleHorizOffset
        p4x = p1x
        p4y = 0

        #Make Sketch
        App.activeDocument().addObject('Sketcher::SketchObject', 'Sketch002')
        App.activeDocument().Sketch002.Support = uf.getFace(
            App.ActiveDocument.Pocket, None, None, None, None,
            gv.extruderMountAngleWidth - gv.extruderMountAngleThickness,
            0)  #(App.ActiveDocument.Pocket,["Face10"])
        App.activeDocument().recompute()
        App.ActiveDocument.Sketch002.addExternal(
            "Pocket",
            uf.getEdge(
                App.ActiveDocument.Pocket, gv.xCarriageWidth, 0,
                (gv.extruderMountAngleWidth + gv.extruderMountAngleThickness) /
                2, 0,
                (gv.extruderMountAngleWidth - gv.extruderMountAngleThickness),
                0))
        App.ActiveDocument.Sketch002.addExternal(
            "Pocket",
            uf.getEdge(
                App.ActiveDocument.Pocket, 0, 0,
                (gv.extruderMountAngleWidth + gv.extruderMountAngleThickness) /
                2, 0,
                (gv.extruderMountAngleWidth - gv.extruderMountAngleThickness),
                0))

        App.ActiveDocument.Sketch002.addGeometry(
            Part.Line(App.Vector(p1x, p1y, 0), App.Vector(p2x, p2y, 0)))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('PointOnObject', 0, 1, -3))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('Vertical', 0))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch002.addGeometry(
            Part.Line(App.Vector(p2x, p2y, 0), App.Vector(p3x, p3y, 0)))
        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('Coincident', 0, 2, 1, 1))
        App.ActiveDocument.recompute()
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('Vertical', 1))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch002.addGeometry(
            Part.Line(App.Vector(p3x, p3y, 0), App.Vector(p4x, p4y, 0)))
        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('Coincident', 1, 2, 2, 1))
        App.ActiveDocument.recompute()
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('PointOnObject', 2, 2, -4))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('Vertical', 2))
        App.ActiveDocument.recompute()

        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('Symmetric', -3, 1, -3, 2, 0, 1))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('Equal', 0, 2))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch002.toggleConstruction(0)
        App.ActiveDocument.Sketch002.toggleConstruction(1)
        App.ActiveDocument.Sketch002.toggleConstruction(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('Coincident', 3, 3, 0, 2))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch002.addGeometry(
            Part.Circle(App.Vector(p3x, p3y, 0), App.Vector(0, 0, 1),
                        gv.mountToPrintedDia / 2))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('Coincident', 4, 3, 1, 2))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('Equal', 4, 3))
        App.ActiveDocument.recompute()

        #Add dimensions
        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('Radius', 3, gv.mountToPrintedDia / 2))
        App.ActiveDocument.recompute()
        App.ActiveDocument.Sketch002.addConstraint(
            Sketcher.Constraint('DistanceY', 0,
                                -gv.xCarriageMountHoleHorizOffset))
        App.ActiveDocument.recompute()
        App.getDocument(self.name).recompute()

        #Cut mounting holes through all
        App.activeDocument().addObject("PartDesign::Pocket", "Pocket001")
        App.activeDocument().Pocket001.Sketch = App.activeDocument().Sketch002
        App.activeDocument().Pocket001.Length = 5.0
        App.ActiveDocument.recompute()
        App.ActiveDocument.Pocket001.Length = 5.000000
        App.ActiveDocument.Pocket001.Type = 1
        App.ActiveDocument.Pocket001.UpToFace = None
        App.ActiveDocument.recompute()
Example #53
0
 def setUp(self):
     self.doc = FreeCAD.newDocument("PathPostTest")
Example #54
0
class OldObject:
    def __init__(self, obj):
        obj.addProperty("App::PropertyLength", "Length")
        obj.addProperty("App::PropertyArea", "Area")
        obj.Length = 15
        obj.Area = 300
        obj.Proxy = self
        self.Type = "Custom"

    def execute(self, obj):
        pass

import FreeCAD as App
import old_module

doc = App.newDocument()
doc.FileName = "my_document.FCStd"

obj = doc.addObject("Part::FeaturePython", "Custom")
old_module.OldObject(obj)

if App.GuiUp:
    obj.ViewObject.Proxy = 1

doc.recompute()
doc.save()

obj = App.ActiveDocument.Custom

print(obj.PropertiesList)
Example #55
0
    def setUp(self):
        # setUp is executed before every test
        doc_name = self.__class__.__name__
        self.document = FreeCAD.newDocument(doc_name)

        self.test_file_dir = join(testtools.get_fem_test_home_dir(), "open")
Example #56
0
 def setUp(self):
     self.doc = FreeCAD.newDocument('test-property-bag')
 def setUp(self):
     self.doc = FreeCAD.newDocument()
     self.TempPath = tempfile.gettempdir()
     FreeCAD.Console.PrintLog('  Using temp path: ' + self.TempPath + '\n')
 def setUp(self):
     self.Doc = FreeCAD.newDocument("SketchGuiTest")
Example #59
0
        6: "3196 Aalseth Lane_R21_bem.ifc",
        7: "3196 Aalseth Lane - AC - IFC4 BIM-BEM - Entier.ifc",
        8: "0014_Vernier112D_ENE_ModèleÉnergétique_R21_1LocalParEtage.ifc",
        9:
        "0014_Vernier112D_ENE_ModèleÉnergétique_R21_1LocalParEtage_space[460].ifc",
        10: "Ersatzneubau Alphütte_1-1210_31_23.ifc",
    }
    IFC_PATH = os.path.join(TEST_FOLDER, TEST_FILES[3])
    DOC = FreeCAD.ActiveDocument
    WITH_GUI = True

    if DOC:  # Remote debugging
        import ptvsd

        # Allow other computers to attach to ptvsd at this IP address and port.
        ptvsd.enable_attach(address=("localhost", 5678), redirect_output=True)
        # Pause the program until a remote debugger is attached
        ptvsd.wait_for_attach()
        # breakpoint()

        boundaries.process_test_file(IFC_PATH, DOC)
    else:
        if WITH_GUI:
            FreeCADGui.showMainWindow()
            DOC = FreeCAD.newDocument()

            boundaries.process_test_file(IFC_PATH, DOC)
            FreeCADGui.exec_loop()
        else:
            xml_str = boundaries.generate_bem_xml_from_file(IFC_PATH)
import FreeCAD
import Draft
import os
import sys

#install comtypes package before importing.
sys.path.append('C:\Python27\Lib\site-packages')
import comtypes.client

#some imputs
AttachToInstance = True
SpecifyPath = False
ModelPath = 'E:\Etabs_Files\Sample Model'

#code
FreeCAD.newDocument("Test")

myEO = comtypes.client.GetActiveObject("CSI.ETABS.API.ETABSObject")
myModel = myEO.SapModel

#till here you got full control over the ETABS.
frames = myModel.FrameObj.GetNameList()
frameNames = frames[1]
framePoints = []

for n in frameNames:
    framePoints.append(myModel.FrameObj.GetPoints(n))

sPoints = [i[0] for i in framePoints]
ePoints = [i[1] for i in framePoints]